diff --git a/.celld-version b/.celld-version new file mode 100644 index 000000000..b61604874 --- /dev/null +++ b/.celld-version @@ -0,0 +1 @@ +0.6.2 diff --git a/.github/workflows/README.md b/.github/workflows/README.md index 3c7c411de..d0d9ca6c1 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -10,10 +10,14 @@ existing unbounded-tech quality provider plus the integration/* jobs below — | Workflow | `workflow_call` | Audience | |----------|-----------------|----------| | [`quality.yaml`](./quality.yaml) | yes | **Consumers:** fmt → clippy → build → test + coverage (sticky PR comment) | -| [`test-all-features.yaml`](./test-all-features.yaml) | yes | **This repo:** workspace `--all-features` | -| [`integration-*.yaml`](./) | yes | **This repo:** broker / DB / CLI / observability / GraphQL identity+OIDC | +| [`test-all-features.yaml`](./test-all-features.yaml) | yes | **This repo:** `cargo hack --each-feature` compile check | +| [`integration-services.yaml`](./integration-services.yaml) | yes | **This repo:** whole workspace, all features, against `compose.yaml` services via `make test-local`; a test that cannot reach its service fails (`DISTRIBUTED_REQUIRE_SERVICES`) | +| [`integration-gateway.yaml`](./integration-gateway.yaml) | yes | **This repo:** application gateway contracts, native and Worker adapters | +| [`integration-game-demos.yaml`](./integration-game-demos.yaml) | yes | **This repo:** `examples/game` smoke | +| [`integration-*.yaml`](./) | yes | **This repo:** CLI / observability / GraphQL identity+OIDC | | [`integration-e2e-ui.yaml`](./integration-e2e-ui.yaml) | yes | **This repo:** `tests/e2e-ui` offline suite, compose Playwright e2e, and kind local-GitOps Playwright e2e | -| [`integration-celld.yaml`](./integration-celld.yaml) | yes | **This repo:** `tests/e2e-celld` workspace tests + live Azurite+celld+NATS | +| [`integration-celld.yaml`](./integration-celld.yaml) | yes | **This repo:** `tests/e2e-celld` workspace tests, celld storage and cell-alarm proofs (`celld dev`), live celld+NATS | +| [`integration-wasm32-domains.yaml`](./integration-wasm32-domains.yaml) | yes | **This repo:** every domain crate builds for `wasm32-unknown-unknown` (`scripts/check-wasm32-domains.sh`), and a native-only fixture must fail | | [`integration-js.yaml`](./integration-js.yaml) | yes | **This repo:** install, typecheck, test, build, and packed-consumer smoke test for `js/` | | [`on-pr-quality.yaml`](./on-pr-quality.yaml) | entry | **This repo** PR gate (not the consumer quality contract) | | [`on-push-main-version-and-tag.yaml`](./on-push-main-version-and-tag.yaml) | entry | **This repo** main → **vnext** tag | @@ -126,6 +130,36 @@ npm releases authenticate through GitHub Actions OIDC. The workflow intentionally has job-scoped `id-token: write`, uses npm 11.5.1 or newer, and does **not** require or accept a long-lived `NPM_TOKEN` repository secret. +## Speed rules for this repo's pipeline + +The organization is on GitHub's free plan: 20 hosted jobs run at once, across +every pull request. A run that starts more jobs than that waits on itself, so +the pipeline is shaped by runner slots and by compile time. + +- **Caches are written by the base branch and read by pull requests.** A cache + saved on a pull request's merge ref is readable by that pull request alone, + and the repository holds 10 GB in total. Every `Swatinem/rust-cache` step + therefore sets `save-if: ${{ github.event_name != 'pull_request' }}` (or + `false` when a sibling job with the same `shared-key` builds the superset and + writes it). `on-pr-quality` also runs on push to `v5`; that run writes the + caches. A pull request that changes `Cargo.lock` compiles its changed + dependencies once per run until it merges. +- **Jobs that build the same thing share a `shared-key`**, with the same + `workspaces` list. One job per key writes it. +- **A new Rust job needs a `rust-cache` step and a `timeout-minutes`.** The + timeout is the job's budget: set it from the job's measured p95 on a cold + cache, and lower it when the job gets faster. Do not raise one to get a run + green. +- **No `needs:` between test jobs.** A job that waits on another job also + waits on that job's queue time. +- **Small checks share a runner** (`integration-observability`, the gateway + `fixtures` job). Each check step carries `if: ${{ !cancelled() }}` so one + run lists every failure. +- **Tools come prebuilt** (`taiki-e/install-action`) or from the cache + (`cargo install` is a no-op when `~/.cargo/bin` was restored). +- `CARGO_PROFILE_DEV_DEBUG=line-tables-only` in every reusable workflow: + backtraces keep file and line; link time and cache size drop. + ## Why this monorepo doesn’t call `quality.yaml` The framework workspace needs a different gate: default-features tests via diff --git a/.github/workflows/integration-celld.yaml b/.github/workflows/integration-celld.yaml index 40caaef19..260c82cff 100644 --- a/.github/workflows/integration-celld.yaml +++ b/.github/workflows/integration-celld.yaml @@ -7,8 +7,7 @@ name: celld (live + e2e-celld) # make -C tests/e2e-celld test # make -C tests/e2e-ui up && make -C tests/e2e-ui up-celld-nats # WATCH=0 WATCH_WORKER=0 make -C tests/e2e-celld run -# E2E_UI_ORIGIN=http://localhost:5180 npx --prefix tests/e2e-ui playwright test \ -# todos.user.spec.ts chat.user.spec.ts --project chromium-user +# make -C tests/e2e-celld test-browser # the full Playwright suite # # Default `cargo test` (quality) still runs fixture-only celld checks and # skips live HTTP unless CELLD_URL is set. This job sets CELLD_URL / NATS_URL. @@ -17,17 +16,103 @@ on: env: CARGO_TERM_COLOR: always + # File and line in backtraces, without the full debug info that makes up + # most of a dev build's link time and cache size. + CARGO_PROFILE_DEV_DEBUG: line-tables-only + CARGO_INCREMENTAL: "0" # Zitadel owns :18080 in the browser topology. CELLD_HTTP_PORT: "18880" CELLD_URL: http://127.0.0.1:18880 NATS_PORT: "14222" NATS_URL: nats://127.0.0.1:14222 + # A live test that loses its service fails instead of skipping. + DISTRIBUTED_REQUIRE_SERVICES: CELLD_URL,NATS_URL DISTRIBUTED_INTERNAL_SECRET: test-only-internal-secret-change-me-2026 jobs: + storage: + name: celld SQL transactions and crash recovery + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 + with: + toolchain: stable + targets: wasm32-unknown-unknown + - uses: Swatinem/rust-cache@v2 + with: + workspaces: | + tests/celld/worker -> tests/celld/worker/target + tests/celld/alarm-worker -> tests/celld/alarm-worker/target + tests/celld/fact-worker -> tests/celld/fact-worker/target + tests/celld/zone-worker -> tests/celld/zone-worker/target + shared-key: celld-storage + save-if: ${{ github.event_name != 'pull_request' }} + - uses: actions/setup-node@v4 + with: + node-version: "22" + - name: Install test runtimes + run: | + sudo apt-get update && sudo apt-get install -y sqlite3 + npm install -g esbuild + cargo install worker-build --version 0.8.7 --locked + # The pinned celld (/.celld-version) is the one the zone-state R2 + # path, fact routing and every profile below are proven on. + scripts/celld.sh install + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + - name: Build isolated fault-probe Worker + working-directory: tests/celld/worker + run: worker-build --release --features storage-conformance + - name: Prove SQL atomicity, fencing, autonomous recovery and growth + run: node tests/celld/storage-conformance.mjs + - name: Build the cell-alarm Ticker Worker + working-directory: tests/celld/alarm-worker + run: worker-build --release + - name: Prove re-armable cell alarms (atomic arm, cadence, watchdog, restart) + run: node tests/celld/alarms.mjs + - name: Build the zone-fact cells Worker + working-directory: tests/celld/fact-worker + run: worker-build --release + - name: Route zone facts to celld cells (CelldFactSink, outage and restart) + env: + CELLD_FACTS_REQUIRED: "1" + run: cargo test -p distributed_game --features celld,runtime --test celld_facts + - name: Zone leases in celld cells (CellZoneOwnership, alarm expiry, GameServer) + env: + CELLD_FACTS_REQUIRED: "1" + run: cargo test -p distributed_game --features celld,runtime,net --test celld_zone_lease + - name: Zone hibernation state in celld cells (inline + R2 snapshots, crash, GameServer) + env: + CELLD_FACTS_REQUIRED: "1" + run: | + cargo test -p distributed_game --features celld,runtime --test celld_zone_state + cargo test -p distributed_game --features celld,net,lease --test world + - name: Build the celld zone host test Worker + working-directory: tests/celld/zone-worker + run: worker-build --release + - name: Zones as celld objects (celld dev; 3-node fleet on RustFS, crash, facts exactly once) + env: + CELLD_ZONE_REQUIRED: "1" + run: cargo test -p distributed_game --features celld,net --test celld_zone + - name: Retain storage proof results and logs + if: always() + uses: actions/upload-artifact@v4 + with: + name: celld-storage-proof + path: | + /tmp/distributed-cell-storage-*/results.json + /tmp/distributed-cell-storage-*/celld-*.log + /tmp/distributed-cell-alarms-*/results.json + /tmp/distributed-cell-alarms-*/celld-*.log + if-no-files-found: ignore + e2e-celld: name: e2e-celld workspace tests runs-on: ubuntu-latest + timeout-minutes: 10 defaults: run: working-directory: tests/e2e-celld @@ -40,13 +125,18 @@ jobs: toolchain: stable - uses: Swatinem/rust-cache@v2 with: - workspaces: tests/e2e-celld -> target - shared-key: e2e-celld-workspace + # Same list as the live job below, which writes the cache. + workspaces: | + . -> target + tests/e2e-celld -> target + tests/celld/worker -> tests/celld/worker/target + shared-key: celld-live + save-if: false - name: Run e2e-celld workspace tests run: cargo test --workspace --verbose live: - name: celld 0.4 live (local store + Queue + NATS) + name: celld live (local store + Queue + NATS) runs-on: ubuntu-latest timeout-minutes: 60 steps: @@ -66,6 +156,7 @@ jobs: tests/e2e-celld -> target tests/celld/worker -> tests/celld/worker/target shared-key: celld-live + save-if: ${{ github.event_name != 'pull_request' }} - uses: actions/setup-node@v7 with: @@ -83,11 +174,11 @@ jobs: run: npm install -g esbuild - name: Install worker-build - run: cargo install worker-build --locked || cargo install worker-build + run: cargo install worker-build --version 0.8.7 --locked || cargo install worker-build --version 0.8.7 - - name: Install celld CLI + - name: Install celld CLI (pinned in /.celld-version) run: | - curl -fsSL https://celld.dev/install.sh | sh + scripts/celld.sh install echo "$HOME/.local/bin" >> "$GITHUB_PATH" - name: Bring up Postgres + Zitadel and bootstrap OIDC @@ -102,9 +193,8 @@ jobs: cargo build -p distributed_cli --bin distributed target/debug/distributed build tests/e2e-ui --output json target/debug/distributed build tests/e2e-celld --output json - cargo test --test celld --no-run - cargo test --test e2e_ui_celld_nats_profile \ - --features graphql,http,sqlite --no-run + cargo test --test services --no-run + cargo test --test services --features graphql,http,sqlite --no-run npm install --prefix tests/e2e-ui # celld dev watches its project for rebuilds. Complete browser/toolchain @@ -114,7 +204,7 @@ jobs: working-directory: tests/e2e-ui run: npx playwright install chromium --with-deps - - name: Bring up celld 0.4 + Queue relay + NATS + - name: Bring up celld + Queue relay + NATS run: | command -v celld command -v worker-build @@ -133,12 +223,13 @@ jobs: export BIND=127.0.0.1:8791 export CELLD_URL=http://127.0.0.1:18880 export NATS_URL=nats://127.0.0.1:14222 - export AUTH_URL=http://localhost:5180 + export PUBLIC_ORIGIN=http://localhost:8791 + export AUTH_URL="$PUBLIC_ORIGIN" export AUTH_USE_SECURE_COOKIES=false export AUTH_TRUST_HOST=true export PUBLIC_E2E_PROFILE=celld-nats export UI_BIND=localhost - export UI_URL=http://localhost:5180 + export UI_URL=http://localhost:8791 target/debug/distributed dev tests/e2e-celld \ > tests/e2e-celld/.ci-distributed-dev.log 2>&1 & @@ -165,13 +256,13 @@ jobs: fi grep -F 'lifecycle dev: process api ready http://127.0.0.1:8791' \ tests/e2e-celld/.ci-distributed-dev.log - grep -F 'lifecycle dev: process ui ready http://localhost:5180' \ + grep -F 'lifecycle dev: process ui ready http://localhost:8791' \ tests/e2e-celld/.ci-distributed-dev.log ok=0 for i in $(seq 1 60); do code=$(curl -s -o /dev/null -w '%{http_code}' \ - "http://localhost:5180/" 2>/dev/null || echo 000) + "http://localhost:8791/" 2>/dev/null || echo 000) if [ "$code" = "200" ] || [ "$code" = "302" ] || [ "$code" = "303" ]; then ok=1 break @@ -224,13 +315,11 @@ jobs: -H "x-distributed-internal-secret: $DISTRIBUTED_INTERNAL_SECRET" \ -d '{"ids":["forged"]}' - - name: Todo + Chat browser lifecycle through celld + - name: Full Playwright suite through celld (user, admin, anon) working-directory: tests/e2e-ui - run: >- - npx playwright test todos.user.spec.ts chat.user.spec.ts - --project chromium-user + run: npx playwright test env: - E2E_UI_ORIGIN: http://localhost:5180 + E2E_UI_ORIGIN: http://localhost:8791 E2E_API_ORIGIN: http://127.0.0.1:8791 CI: true diff --git a/.github/workflows/integration-distributed-cli.yaml b/.github/workflows/integration-distributed-cli.yaml index e5495dea8..49e088ac9 100644 --- a/.github/workflows/integration-distributed-cli.yaml +++ b/.github/workflows/integration-distributed-cli.yaml @@ -6,12 +6,18 @@ name: distributed_cli Integration Tests on: workflow_call: +env: + CARGO_TERM_COLOR: always + # File and line in backtraces, without the full debug info that makes up + # most of a dev build's link time and cache size. + CARGO_PROFILE_DEV_DEBUG: line-tables-only + CARGO_INCREMENTAL: "0" + jobs: distributed-cli: name: distributed_cli Integration Tests runs-on: ubuntu-latest - env: - CARGO_TERM_COLOR: always + timeout-minutes: 15 steps: - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 with: @@ -19,6 +25,12 @@ jobs: - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 with: toolchain: stable + # game-wasm tests compile prediction steps to WebAssembly. + targets: wasm32-unknown-unknown + - uses: Swatinem/rust-cache@v2 + with: + shared-key: cli + save-if: ${{ github.event_name != 'pull_request' }} - uses: actions/setup-node@v7 with: node-version: "24" diff --git a/.github/workflows/integration-e2e-ui.yaml b/.github/workflows/integration-e2e-ui.yaml index 7def14dde..30ac3576b 100644 --- a/.github/workflows/integration-e2e-ui.yaml +++ b/.github/workflows/integration-e2e-ui.yaml @@ -11,6 +11,10 @@ on: env: CARGO_TERM_COLOR: always + # File and line in backtraces, without the full debug info that makes up + # most of a dev build's link time and cache size. + CARGO_PROFILE_DEV_DEBUG: line-tables-only + CARGO_INCREMENTAL: "0" # Playwright / Auth.js over HTTP on localhost CI: true @@ -18,6 +22,7 @@ jobs: offline: name: e2e-ui offline (domain + suite + UI unit) runs-on: ubuntu-latest + timeout-minutes: 12 defaults: run: working-directory: tests/e2e-ui @@ -36,7 +41,8 @@ jobs: workspaces: | . -> target tests/e2e-ui -> target - shared-key: e2e-ui-offline + shared-key: e2e-ui + save-if: false - uses: actions/setup-node@v7 with: @@ -75,7 +81,8 @@ jobs: workspaces: | . -> target tests/e2e-ui -> target - shared-key: e2e-ui-browser + shared-key: e2e-ui + save-if: ${{ github.event_name != 'pull_request' }} - uses: actions/setup-node@v7 with: @@ -106,7 +113,8 @@ jobs: - name: Start application with Distributed dev run: | set -euo pipefail - export AUTH_URL="${E2E_UI_ORIGIN:-http://localhost:5180}" + export PUBLIC_ORIGIN="${E2E_UI_ORIGIN:-http://localhost:8791}" + export AUTH_URL="$PUBLIC_ORIGIN" export AUTH_USE_SECURE_COOKIES=false export AUTH_TRUST_HOST=true @@ -114,7 +122,8 @@ jobs: echo $! > .distributed-dev.pid ok=0 - for i in $(seq 1 240); do + # Match the CLI's bounded cold-runtime + UI readiness budget. + for i in $(seq 1 720); do if grep -Fq 'lifecycle dev: ready generation=' .distributed-dev.log; then ok=1 break @@ -122,6 +131,7 @@ jobs: if ! kill -0 "$(cat .distributed-dev.pid)" 2>/dev/null; then echo "distributed dev exited before readiness" tail -200 .distributed-dev.log + ps -eo pid,ppid,etime,stat,comm exit 1 fi sleep 0.5 @@ -129,11 +139,14 @@ jobs: if [ "$ok" != "1" ]; then echo "distributed dev failed to become ready" tail -200 .distributed-dev.log + # Executable names identify quiet build children without exposing + # credentials from process arguments or environment variables. + ps -eo pid,ppid,etime,stat,comm exit 1 fi grep -F 'lifecycle dev: process api ready http://127.0.0.1:8791' .distributed-dev.log - grep -F 'lifecycle dev: process ui ready http://localhost:5180' .distributed-dev.log + grep -F 'lifecycle dev: process ui ready http://localhost:8791' .distributed-dev.log tail -40 .distributed-dev.log - name: Install Playwright + Chromium @@ -141,12 +154,15 @@ jobs: npm install npx playwright install chromium --with-deps + - name: Verify candidate-key SSR and live delivery end to end + run: 'cargo test --manifest-path ../../Cargo.toml --features graphql,sqlite --test graphql graphql_unique_key_live::projected_candidate_keys_reach_chromium_over_http_and_websocket -- --ignored --exact --nocapture' + - name: Run browser e2e run: | npm run test:browser npm run test:lifecycle-reload env: - E2E_UI_ORIGIN: http://localhost:5180 + E2E_UI_ORIGIN: http://localhost:8791 E2E_API_ORIGIN: http://127.0.0.1:8791 CI: true @@ -155,9 +171,12 @@ jobs: uses: actions/upload-artifact@v7 with: name: e2e-ui-playwright-report + # Only the explicit paths below; never include e2e/.auth or env files. + include-hidden-files: true path: | tests/e2e-ui/playwright-report tests/e2e-ui/test-results + tests/e2e-ui/.distributed-dev.log if-no-files-found: ignore retention-days: 7 @@ -216,7 +235,8 @@ jobs: workspaces: | . -> target tests/e2e-ui -> target - shared-key: e2e-ui-local-gitops + shared-key: e2e-ui + save-if: false - uses: actions/setup-node@v7 with: diff --git a/.github/workflows/integration-game-demos.yaml b/.github/workflows/integration-game-demos.yaml new file mode 100644 index 000000000..253b328d8 --- /dev/null +++ b/.github/workflows/integration-game-demos.yaml @@ -0,0 +1,92 @@ +name: Game demos smoke + +# Reusable workflow: referenced via `uses: ./.github/workflows/integration-game-demos.yaml`. +# `examples/game` is outside the root workspace, so nothing else runs its tests: +# game clients generated from the Rust surfaces (build outputs, never +# checked in; `gen --check` verifies determinism), demo server fmt/clippy/tests +# (incl. the mobpit_service projection test), client type-check, build and +# headless tests, and the SvelteKit demo end to end: `distributed build +# examples/game/server` (GraphQL client, svelte-check, vite build), then +# Playwright against the production build, a real Mob Pit server and the real +# mobpit-service read model. Mob Pit's rooms and durable cells run on celld: +# the tests start their own `celld dev` (CELLD_BIN, pinned in +# /.celld-version) serving examples/game/cells, built with worker-build; the +# SvelteKit Playwright test runs the rooms on a 3-node fleet (RustFS via +# docker compose and the aws CLI, both on the runner; required here). +on: + workflow_call: + +env: + CARGO_TERM_COLOR: always + # File and line in backtraces, without the full debug info that makes up + # most of a dev build's link time and cache size. + CARGO_PROFILE_DEV_DEBUG: line-tables-only + CARGO_INCREMENTAL: "0" + +jobs: + game-demos: + name: Game demos smoke (examples/game) + runs-on: ubuntu-latest + timeout-minutes: 35 + # The shared ticket rate limiter's Lua script and the leaderboard store + # (conformance suite, projector, GraphQL boards) run against a real Redis. + services: + redis: + image: redis:7-alpine + ports: + - 6379:6379 + options: >- + --health-cmd "redis-cli ping" --health-interval 2s --health-timeout 2s --health-retries 15 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 + with: + toolchain: stable + components: clippy, rustfmt + # Predicted steps and pure functions compile to WebAssembly. + targets: wasm32-unknown-unknown + - uses: actions/setup-node@v4 + with: + node-version: "24" + cache: npm + cache-dependency-path: | + js/package-lock.json + examples/game/client/package-lock.json + examples/game/sveltekit/package-lock.json + - uses: Swatinem/rust-cache@v2 + with: + workspaces: | + examples/game/server -> target + examples/game/cells -> target + shared-key: game-demos + save-if: ${{ github.event_name != 'pull_request' }} + - name: Install celld (pinned) and worker-build + run: | + scripts/celld.sh install + echo "CELLD_BIN=$HOME/.local/bin/celld" >> "$GITHUB_ENV" + cargo install worker-build --version 0.8.7 --locked + - name: Install SvelteKit demo dependencies and Chromium + working-directory: examples/game/sveltekit + run: npm ci --no-audit --no-fund && npx playwright install --with-deps chromium + - name: Run examples/game smoke + env: + # The SvelteKit leaderboard is the Redis board (GraphQL board roots). + REDIS_URL: redis://127.0.0.1:6379 + MOBPIT_FLEET_REQUIRED: "1" + run: examples/game/run.sh smoke + - name: Leaderboard conformance and GraphQL boards against real Redis + env: + REDIS_URL: redis://127.0.0.1:6379 + run: cargo test -p distributed_leaderboard --features redis,graphql --test redis -- --nocapture + - name: Redis Streams publisher against real Redis + env: + REDIS_URL: redis://127.0.0.1:6379 + run: 'cargo test --features redis-streams --test transports redis_streams:: -- --nocapture' + - name: Ticket rate limiter against real Redis + working-directory: js + env: + DISTRIBUTED_REDIS_E2E: "1" + REDIS_URL: redis://127.0.0.1:6379 + run: node --test tests/sveltekit-game-rate-limit.test.mjs diff --git a/.github/workflows/integration-gateway.yaml b/.github/workflows/integration-gateway.yaml new file mode 100644 index 000000000..2225bac21 --- /dev/null +++ b/.github/workflows/integration-gateway.yaml @@ -0,0 +1,248 @@ +name: Application gateway + +# Reusable workflow: wired from on-pr-quality and on-push-main, so it gates +# every PR, main and the release tag. +on: + workflow_call: + workflow_dispatch: + +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + # File and line in backtraces, without the full debug info that makes up + # most of a dev build's link time and cache size. + CARGO_PROFILE_DEV_DEBUG: line-tables-only + CARGO_INCREMENTAL: "0" + +jobs: + # The portable and native fixture crates on one runner (they were the + # `contracts` and `native` jobs, about two minutes each). Every check runs + # even when an earlier one fails, so one run lists every failure. + fixtures: + name: fixtures (portable contracts, native adapter) + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 + with: + toolchain: stable + targets: wasm32-unknown-unknown + components: rustfmt, clippy + - uses: Swatinem/rust-cache@v2 + with: + workspaces: | + tests/gateway-portable -> target + tests/gateway-native -> target + shared-key: gateway-fixtures + save-if: ${{ github.event_name != 'pull_request' }} + - name: Format contract and fixture sources + if: ${{ !cancelled() }} + run: rustfmt --edition 2021 --check src/gateway/mod.rs tests/gateway/gateway_routing.rs tests/gateway/gateway_extensions.rs tests/gateway-portable/src/lib.rs + - name: Test portable routing and adapter contracts + if: ${{ !cancelled() }} + run: cargo test --manifest-path tests/gateway-portable/Cargo.toml --locked + - name: Check fixture lints + if: ${{ !cancelled() }} + run: cargo clippy --manifest-path tests/gateway-portable/Cargo.toml --locked --all-targets -- -D warnings + - name: Compile the UI/auth consumer to Wasm + if: ${{ !cancelled() }} + run: cargo check --manifest-path tests/gateway-portable/Cargo.toml --locked --target wasm32-unknown-unknown + - name: Verify native and Wasm dependency isolation + if: ${{ !cancelled() }} + run: python3 tests/gateway-portable/check_dependencies.py + - name: Test real native HTTP streams and upgrades + if: ${{ !cancelled() }} + run: cargo test --manifest-path tests/gateway-native/Cargo.toml --locked + - name: Check native fixture lints + if: ${{ !cancelled() }} + run: cargo clippy --manifest-path tests/gateway-native/Cargo.toml --locked --all-targets -- -D warnings + - name: Verify UI/auth executor dependency isolation + if: ${{ !cancelled() }} + run: python3 tests/gateway-native/check_dependencies.py + + auth: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: '24' + - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 + with: + toolchain: stable + - uses: Swatinem/rust-cache@v2 + with: + # Same test target as the GraphQL identity job; that job writes the cache. + shared-key: graphql + save-if: false + - name: Verify gateway and backend identity + run: 'cargo test -p distributed --no-default-features --features gateway,graphql,sqlite --test graphql graphql_identity::' + - name: Install pinned auth fixture dependencies + working-directory: tests/gateway-auth + run: npm ci + - name: Install Chromium + working-directory: tests/gateway-auth + run: npx playwright install --with-deps chromium + - name: Run production Auth.js lifecycle and browser security cases + working-directory: tests/gateway-auth + run: npm test + + graphql: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 + with: + toolchain: stable + - uses: Swatinem/rust-cache@v2 + with: + workspaces: | + . -> target + tests/gateway-worker -> target + shared-key: gateway-graphql + save-if: false + - name: Verify embedded and remote GraphQL protocols + run: 'cargo test -p distributed --no-default-features --features gateway-graphql-native,sqlite --test gateway --test graphql --test repositories -- gateway_graphql:: gateway_graphql_operation:: graphql_causal_transport:: graphql_query_protocol:: graphql_identity:: graphql_sqlite:: sqlite_repository::' + + - name: Verify the portable delivery state machines and WS codec + run: 'cargo test -p distributed --no-default-features --features gateway --lib gateway::' + - name: Verify native query cancellation, expiry and deadlines + run: cargo test -p distributed --no-default-features --features gateway-graphql-native,sqlite --lib gateway::native::flight::tests + - name: Verify native live driver teardown and reset delivery + run: cargo test -p distributed --no-default-features --features gateway-graphql-native,sqlite --lib gateway::native::live::tests + - name: Verify transactional cache coverage and Atomic rollback + run: | + cargo test -p distributed --no-default-features --features gateway-graphql-native,sqlite --lib graphql::delivery::versions::tests + cargo test -p distributed --no-default-features --features gateway-graphql-native,sqlite --lib sqlite_direct_projection_and_ledger_replay_commit_atomically + + freshness: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 + with: + toolchain: stable + - uses: Swatinem/rust-cache@v2 + with: + # The distributed_cli job writes this cache. + shared-key: cli + save-if: false + - uses: actions/setup-node@v4 + with: + node-version: '24' + - name: Prove primary routing with paused physical standby + run: python3 tests/gateway-postgres/run.py + - name: Verify client freshness and command protocol + run: | + npm ci --prefix js + npm --prefix js run build + node --test js/tests/replica-command-runtime.test.mjs js/tests/replica-protocol.test.mjs js/tests/replica-revalidation.test.mjs js/tests/replica-graphql-transport.test.mjs + - name: Verify generated delivery metadata + run: cargo test -p distributed_cli client_compiler + + worker: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: '24' + - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 + with: + toolchain: stable + targets: wasm32-unknown-unknown + components: clippy + - uses: Swatinem/rust-cache@v2 + with: + workspaces: | + . -> target + tests/gateway-worker -> target + shared-key: gateway-graphql + save-if: ${{ github.event_name != 'pull_request' }} + - name: Install pinned local Worker and auth fixtures + run: | + cargo install worker-build --version 0.8.5 --locked + npm ci --prefix tests/gateway-worker + npm ci --prefix tests/gateway-auth + cd tests/gateway-auth + npx playwright install --with-deps chromium + - name: Check Wasm build and dependency boundary + run: | + cargo check --manifest-path tests/gateway-worker/Cargo.toml --locked --target wasm32-unknown-unknown + cargo clippy --manifest-path tests/gateway-worker/Cargo.toml --locked --target wasm32-unknown-unknown -- -D warnings + python3 tests/gateway-worker/check_dependencies.py + - name: Exercise actual workerd HTTP, WebSockets and Auth.js lifecycle + run: | + node tests/gateway-worker/proxy-runtime.mjs + node tests/gateway-worker/run.mjs + - name: Measure actual native and workerd origin/client savings + run: 'cargo test --no-default-features --features gateway-graphql-native,sqlite --test graphql graphql_query_protocol::load::separate_origin_and_client_savings -- --ignored --nocapture' + - uses: actions/upload-artifact@v4 + if: always() + with: + name: gateway-delivery-load + path: tests/gateway-worker/artifacts/load-report.json + - name: Prove actual DO coordination, SQL reduction, restart and cancellation + run: 'cargo test --no-default-features --features gateway-graphql-native,sqlite --test graphql graphql_query_protocol::worker_ -- --ignored --nocapture --test-threads=1' + + application: + runs-on: ubuntu-latest + timeout-minutes: 35 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: '24' + - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 + with: + toolchain: stable + targets: wasm32-unknown-unknown + - uses: Swatinem/rust-cache@v2 + with: + workspaces: | + . -> target + tests/e2e-ui -> target + # Same workspaces as the e2e-ui jobs, whose browser job writes the cache. + shared-key: e2e-ui + save-if: false + - uses: taiki-e/install-action@v2 + with: + tool: wasm-pack + - name: Install isolated browser fixture + run: | + npm ci --prefix tests/gateway-auth + npm ci --prefix tests/e2e-ui + cd tests/gateway-auth + npx playwright install --with-deps chromium + - name: Verify application composition + run: 'cargo test --no-default-features --features graphql,sqlite,gateway --test core application_composition::' + - name: Build coherent application and run public-origin browser flows + run: node tests/e2e-ui/gateway/run.mjs + - name: Verify dev lifecycle and browser flows through the gateway + run: GATEWAY_SKIP_BUILD=1 GATEWAY_DEV=1 node tests/e2e-ui/gateway/run.mjs + - name: Verify controlled reloads across gateway and application restarts + run: GATEWAY_SKIP_BUILD=1 GATEWAY_DEV=1 GATEWAY_LIFECYCLE=1 node tests/e2e-ui/gateway/run.mjs + - uses: actions/upload-artifact@v4 + if: always() + with: + name: gateway-application + path: tests/e2e-ui/gateway/artifacts/ diff --git a/.github/workflows/integration-graphql.yaml b/.github/workflows/integration-graphql.yaml index 09da3dd88..0eb978cd5 100644 --- a/.github/workflows/integration-graphql.yaml +++ b/.github/workflows/integration-graphql.yaml @@ -10,16 +10,23 @@ name: GraphQL Identity / OIDC Integration Tests # Local parity: # ./scripts/oidc-{zitadel,keycloak,authentik}-up.sh # set -a && source graphql-oidc[-keycloak|-authentik].env && set +a -# cargo test --test graphql_oidc_ --features graphql,sqlite,metrics +# cargo test --test graphql --features graphql,sqlite,metrics graphql_oidc_:: on: workflow_call: +env: + CARGO_TERM_COLOR: always + # File and line in backtraces, without the full debug info that makes up + # most of a dev build's link time and cache size. + CARGO_PROFILE_DEV_DEBUG: line-tables-only + CARGO_INCREMENTAL: "0" + jobs: identity-always-on: name: GraphQL Identity runs-on: ubuntu-latest + timeout-minutes: 10 env: - CARGO_TERM_COLOR: always # Explicitly clear live gates so matrix cannot accidentally run live paths ZITADEL_E2E: "" KEYCLOAK_E2E: "" @@ -33,16 +40,17 @@ jobs: toolchain: stable - uses: Swatinem/rust-cache@v2 with: - shared-key: graphql-identity + shared-key: graphql + save-if: ${{ github.event_name != 'pull_request' }} - name: Always-on identity suite (no IdP) run: | - cargo test --test graphql_identity --features graphql,sqlite,metrics --verbose + cargo test --test graphql --features graphql,sqlite,metrics --verbose graphql_identity:: oidc-zitadel-e2e: name: GraphQL OIDC Zitadel e2e (live) runs-on: ubuntu-latest + timeout-minutes: 10 env: - CARGO_TERM_COLOR: always ZITADEL_HOST: http://localhost:8080 steps: - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 @@ -53,7 +61,8 @@ jobs: toolchain: stable - uses: Swatinem/rust-cache@v2 with: - shared-key: graphql-oidc-zitadel + shared-key: graphql + save-if: false - name: Install bootstrap tools run: sudo apt-get update && sudo apt-get install -y jq openssl curl - name: Start Zitadel + bootstrap (docker compose) @@ -70,22 +79,21 @@ jobs: test -n "${OIDC_ISSUER:-}" test -n "${GRAPHQL_E2E_CUSTOMER_KEY:-}" echo "ZITADEL_E2E=$ZITADEL_E2E OIDC_ISSUER=$OIDC_ISSUER" - cargo test --test graphql_oidc_zitadel --features graphql,sqlite,metrics --verbose -- --nocapture + cargo test --test graphql --features graphql,sqlite,metrics --verbose graphql_oidc_zitadel:: -- --nocapture - name: Dump Zitadel logs on failure if: failure() run: | - docker compose -f tests/graphql_oidc_zitadel/docker-compose.yml ps -a || true - docker compose -f tests/graphql_oidc_zitadel/docker-compose.yml logs --tail=200 || true - ls -la tests/graphql_oidc_zitadel/machinekey || true + docker compose -f tests/graphql/graphql_oidc_zitadel/docker-compose.yml ps -a || true + docker compose -f tests/graphql/graphql_oidc_zitadel/docker-compose.yml logs --tail=200 || true + ls -la tests/graphql/graphql_oidc_zitadel/machinekey || true - name: Tear down if: always() - run: docker compose -f tests/graphql_oidc_zitadel/docker-compose.yml down -v || true + run: docker compose -f tests/graphql/graphql_oidc_zitadel/docker-compose.yml down -v || true oidc-keycloak-e2e: name: GraphQL OIDC Keycloak e2e (live) runs-on: ubuntu-latest - env: - CARGO_TERM_COLOR: always + timeout-minutes: 10 steps: - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 with: @@ -95,7 +103,8 @@ jobs: toolchain: stable - uses: Swatinem/rust-cache@v2 with: - shared-key: graphql-oidc-keycloak + shared-key: graphql + save-if: false - name: Install tools run: sudo apt-get update && sudo apt-get install -y curl python3 - name: Start Keycloak + bootstrap @@ -111,21 +120,20 @@ jobs: test -n "${KEYCLOAK_E2E:-}" test -n "${OIDC_ISSUER:-}" echo "KEYCLOAK_E2E=$KEYCLOAK_E2E OIDC_ISSUER=$OIDC_ISSUER OIDC_AUDIENCE=$OIDC_AUDIENCE" - cargo test --test graphql_oidc_keycloak --features graphql,sqlite,metrics --verbose -- --nocapture + cargo test --test graphql --features graphql,sqlite,metrics --verbose graphql_oidc_keycloak:: -- --nocapture - name: Dump Keycloak logs on failure if: failure() run: | - docker compose -f tests/graphql_oidc_keycloak/docker-compose.yml ps -a || true - docker compose -f tests/graphql_oidc_keycloak/docker-compose.yml logs --tail=200 || true + docker compose -f tests/graphql/graphql_oidc_keycloak/docker-compose.yml ps -a || true + docker compose -f tests/graphql/graphql_oidc_keycloak/docker-compose.yml logs --tail=200 || true - name: Tear down if: always() - run: docker compose -f tests/graphql_oidc_keycloak/docker-compose.yml down -v || true + run: docker compose -f tests/graphql/graphql_oidc_keycloak/docker-compose.yml down -v || true oidc-authentik-e2e: name: GraphQL OIDC Authentik e2e (live) runs-on: ubuntu-latest - env: - CARGO_TERM_COLOR: always + timeout-minutes: 12 steps: - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 with: @@ -135,7 +143,8 @@ jobs: toolchain: stable - uses: Swatinem/rust-cache@v2 with: - shared-key: graphql-oidc-authentik + shared-key: graphql + save-if: false - name: Install tools run: sudo apt-get update && sudo apt-get install -y curl python3 - name: Start Authentik + bootstrap @@ -152,12 +161,12 @@ jobs: test -n "${OIDC_ISSUER:-}" test -n "${OIDC_JWKS_URI:-}" echo "AUTHENTIK_E2E=$AUTHENTIK_E2E OIDC_ISSUER=$OIDC_ISSUER" - cargo test --test graphql_oidc_authentik --features graphql,sqlite,metrics --verbose -- --nocapture + cargo test --test graphql --features graphql,sqlite,metrics --verbose graphql_oidc_authentik:: -- --nocapture - name: Dump Authentik logs on failure if: failure() run: | - docker compose -f tests/graphql_oidc_authentik/docker-compose.yml ps -a || true - docker compose -f tests/graphql_oidc_authentik/docker-compose.yml logs --tail=200 || true + docker compose -f tests/graphql/graphql_oidc_authentik/docker-compose.yml ps -a || true + docker compose -f tests/graphql/graphql_oidc_authentik/docker-compose.yml logs --tail=200 || true - name: Tear down if: always() - run: docker compose -f tests/graphql_oidc_authentik/docker-compose.yml down -v || true + run: docker compose -f tests/graphql/graphql_oidc_authentik/docker-compose.yml down -v || true diff --git a/.github/workflows/integration-js.yaml b/.github/workflows/integration-js.yaml index 06a6d76f8..f3707de43 100644 --- a/.github/workflows/integration-js.yaml +++ b/.github/workflows/integration-js.yaml @@ -12,6 +12,7 @@ jobs: quality: name: Distributed JS client quality (Node ${{ matrix.node-version }}) runs-on: ubuntu-latest + timeout-minutes: 5 strategy: fail-fast: false matrix: diff --git a/.github/workflows/integration-kafka.yaml b/.github/workflows/integration-kafka.yaml deleted file mode 100644 index 5b9d3e33b..000000000 --- a/.github/workflows/integration-kafka.yaml +++ /dev/null @@ -1,52 +0,0 @@ -name: Kafka Integration Tests - -# Reusable workflow: referenced via `uses: ./.github/workflows/integration-kafka.yaml` -# from both the PR-quality and push-to-main pipelines. -on: - workflow_call: - -jobs: - kafka: - name: Kafka Integration Tests - runs-on: ubuntu-latest - services: - kafka: - image: apache/kafka:4.3.1 - ports: - - 9092:9092 - env: - KAFKA_NODE_ID: 1 - KAFKA_PROCESS_ROLES: broker,controller - KAFKA_LISTENERS: PLAINTEXT://:9092,CONTROLLER://:9093 - KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092 - KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER - KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT - KAFKA_CONTROLLER_QUORUM_VOTERS: 1@localhost:9093 - KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 - KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1 - KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1 - KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0 - options: >- - --health-cmd "/opt/kafka/bin/kafka-broker-api-versions.sh --bootstrap-server localhost:9092" - --health-interval 10s - --health-timeout 10s - --health-retries 20 - --health-start-period 20s - env: - CARGO_TERM_COLOR: always - KAFKA_BROKERS: localhost:9092 - steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 - with: - persist-credentials: false - - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 - with: - toolchain: stable - # ubuntu-latest ships cmake + gcc, which rdkafka's cmake-build needs. It - # also has libcurl's runtime but not its headers; librdkafka's bundled - # build enables curl (OAUTHBEARER OIDC) when it finds the lib and then - # needs curl/curl.h, so install the dev package. - - name: Install librdkafka build dependencies - run: sudo apt-get update && sudo apt-get install -y libcurl4-openssl-dev - - name: Run Kafka transport integration tests - run: cargo test --test kafka_transport --features kafka --verbose diff --git a/.github/workflows/integration-nats.yaml b/.github/workflows/integration-nats.yaml deleted file mode 100644 index 7385a4b92..000000000 --- a/.github/workflows/integration-nats.yaml +++ /dev/null @@ -1,32 +0,0 @@ -name: NATS JetStream Integration Tests - -# Reusable workflow: referenced via `uses: ./.github/workflows/integration-nats.yaml` -# from both the PR-quality and push-to-main pipelines. -on: - workflow_call: - -jobs: - nats: - name: NATS JetStream Integration Tests - runs-on: ubuntu-latest - env: - CARGO_TERM_COLOR: always - NATS_URL: nats://localhost:4222 - steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 - with: - persist-credentials: false - - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 - with: - toolchain: stable - # NATS service containers can't override the entrypoint to enable - # JetStream, so start it as a step instead. - - name: Start NATS (JetStream) - run: | - docker run -d --name nats -p 4222:4222 nats:2.10-alpine -js - for i in $(seq 1 30); do - if nc -z localhost 4222; then echo "nats up"; break; fi - sleep 1 - done - - name: Run NATS transport integration tests - run: cargo test --test nats_transport --features nats --verbose diff --git a/.github/workflows/integration-observability.yaml b/.github/workflows/integration-observability.yaml index ce25e124e..00c9a0781 100644 --- a/.github/workflows/integration-observability.yaml +++ b/.github/workflows/integration-observability.yaml @@ -12,13 +12,21 @@ name: Observability Integration Tests on: workflow_call: +env: + CARGO_TERM_COLOR: always + # File and line in backtraces, without the full debug info that makes up + # most of a dev build's link time and cache size. + CARGO_PROFILE_DEV_DEBUG: line-tables-only + CARGO_INCREMENTAL: "0" + jobs: - metrics-exposition: - name: Metrics Exposition (promtool) + # One runner instead of three: each check is under 90 seconds, and the + # runner slots are what a pull request waits for. Every check runs even + # when an earlier one fails, so one run lists every failure. + observability: + name: Observability (promtool, OTLP collector, kubeconform) runs-on: ubuntu-latest - env: - CARGO_TERM_COLOR: always - PROMTOOL: /usr/local/bin/promtool + timeout-minutes: 10 steps: - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 with: @@ -26,6 +34,11 @@ jobs: - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 with: toolchain: stable + - uses: Swatinem/rust-cache@v2 + with: + # The distributed_cli job writes this cache. + shared-key: cli + save-if: false - name: Install promtool run: | VERSION=3.4.1 @@ -33,23 +46,13 @@ jobs: | tar -xz -C /tmp "prometheus-${VERSION}.linux-amd64/promtool" sudo mv "/tmp/prometheus-${VERSION}.linux-amd64/promtool" /usr/local/bin/promtool promtool --version - - name: Run metrics exposition tests - run: cargo test --test metrics_exposition --features http,metrics --verbose - - otel-export: - name: OTLP Export (collector) - runs-on: ubuntu-latest - env: - CARGO_TERM_COLOR: always - OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: http://localhost:4318/v1/traces - OTEL_COLLECTOR_TRACES_FILE: ${{ github.workspace }}/target/otel-out/traces.json - steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 - with: - persist-credentials: false - - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 - with: - toolchain: stable + - name: Install kubeconform + run: | + VERSION=0.7.0 + curl -sSfL "https://github.com/yannh/kubeconform/releases/download/v${VERSION}/kubeconform-linux-amd64.tar.gz" \ + | tar -xz -C /tmp kubeconform + sudo mv /tmp/kubeconform /usr/local/bin/kubeconform + kubeconform -v # The collector needs a config file mount, which `services:` containers # can't express, so start it as a step. `--user 0` lets its file exporter # write to the bind-mounted output dir regardless of host uid mapping. @@ -57,7 +60,7 @@ jobs: run: | mkdir -p target/otel-out && chmod 777 target/otel-out docker run -d --user 0 --name otelcol -p 4318:4318 -p 4317:4317 \ - -v "$PWD/tests/otel_export/collector-config.yaml:/etc/otelcol/config.yaml:ro" \ + -v "$PWD/tests/observability/otel_export/collector-config.yaml:/etc/otelcol/config.yaml:ro" \ -v "$PWD/target/otel-out:/out" \ otel/opentelemetry-collector:0.116.1 --config /etc/otelcol/config.yaml for i in $(seq 1 30); do @@ -65,29 +68,24 @@ jobs: sleep 1 done echo "collector never became ready"; docker logs otelcol; exit 1 - - name: Run OTLP export tests - run: cargo test --test otel_export --features http,otel --verbose - scaffold-manifests: - name: Scaffolded Manifests (kubeconform) - runs-on: ubuntu-latest - env: - CARGO_TERM_COLOR: always - steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 - with: - persist-credentials: false - - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 - with: - toolchain: stable - - name: Install kubeconform - run: | - VERSION=0.7.0 - curl -sSfL "https://github.com/yannh/kubeconform/releases/download/v${VERSION}/kubeconform-linux-amd64.tar.gz" \ - | tar -xz -C /tmp kubeconform - sudo mv /tmp/kubeconform /usr/local/bin/kubeconform - kubeconform -v + # Each check names only its own services, as its own job did: a check + # never sees another check's endpoints. + - name: Run metrics exposition tests + if: ${{ !cancelled() }} + env: + PROMTOOL: /usr/local/bin/promtool + DISTRIBUTED_REQUIRE_SERVICES: PROMTOOL + run: 'cargo test --test observability --features http,metrics --verbose metrics_exposition::' + - name: Run OTLP export tests + if: ${{ !cancelled() }} + env: + OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: http://localhost:4318/v1/traces + OTEL_COLLECTOR_TRACES_FILE: ${{ github.workspace }}/target/otel-out/traces.json + DISTRIBUTED_REQUIRE_SERVICES: OTEL_EXPORTER_OTLP_TRACES_ENDPOINT,OTEL_COLLECTOR_TRACES_FILE + run: 'cargo test --test observability --features http,otel --verbose otel_export::' - name: Scaffold service with metrics and tracing + if: ${{ !cancelled() }} run: | cargo run -p distributed_cli --bin distributed -- scaffold observability-orders \ --path target/tmp/scaffold-observability \ @@ -95,6 +93,7 @@ jobs: --metrics prometheus --tracing --gitops \ --force --distributed-path . - name: Render chart and validate against CRD schemas + if: ${{ !cancelled() }} run: | helm template obs target/tmp/scaffold-observability/.gitops/deploy \ --set image.tag=ci-test \ diff --git a/.github/workflows/integration-postgres.yaml b/.github/workflows/integration-postgres.yaml deleted file mode 100644 index 0dac77468..000000000 --- a/.github/workflows/integration-postgres.yaml +++ /dev/null @@ -1,46 +0,0 @@ -name: Postgres Integration Tests - -# Reusable workflow: referenced via `uses: ./.github/workflows/integration-postgres.yaml` -# from both the PR-quality and push-to-main pipelines. -on: - workflow_call: - -jobs: - postgres: - name: Postgres Integration Tests - runs-on: ubuntu-latest - services: - postgres: - image: postgres:18-alpine - env: - POSTGRES_USER: postgres - POSTGRES_PASSWORD: postgres - POSTGRES_DB: distributed_test - ports: - - 5432:5432 - options: >- - --health-cmd "pg_isready -U postgres -d distributed_test" - --health-interval 5s - --health-timeout 5s - --health-retries 10 - env: - CARGO_TERM_COLOR: always - DATABASE_URL: postgres://postgres:postgres@localhost:5432/distributed_test - steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 - with: - persist-credentials: false - - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 - with: - toolchain: stable - - uses: Swatinem/rust-cache@v2 - with: - shared-key: postgres-integration - - name: Run Postgres integration tests - run: | - cargo test --lib --no-default-features --features postgres postgres_command_ledger_adapter_conformance_when_database_available --verbose - cargo test --test postgres_repository --no-default-features --features postgres --verbose - cargo test --test postgres_repository_conformance --no-default-features --features postgres --verbose - cargo test --test postgres_transport --no-default-features --features postgres --verbose - cargo test --test distributed_read_model --no-default-features --features postgres --verbose - cargo test --test sql_lock_manager --no-default-features --features postgres --verbose diff --git a/.github/workflows/integration-rabbitmq.yaml b/.github/workflows/integration-rabbitmq.yaml deleted file mode 100644 index 6c8f5251a..000000000 --- a/.github/workflows/integration-rabbitmq.yaml +++ /dev/null @@ -1,33 +0,0 @@ -name: RabbitMQ Integration Tests - -# Reusable workflow: referenced via `uses: ./.github/workflows/integration-rabbitmq.yaml` -# from both the PR-quality and push-to-main pipelines. -on: - workflow_call: - -jobs: - rabbitmq: - name: RabbitMQ Integration Tests - runs-on: ubuntu-latest - services: - rabbitmq: - image: rabbitmq:4.3-management-alpine - ports: - - 5672:5672 - options: >- - --health-cmd "rabbitmq-diagnostics -q ping" - --health-interval 5s - --health-timeout 5s - --health-retries 20 - env: - CARGO_TERM_COLOR: always - AMQP_URL: amqp://guest:guest@localhost:5672/%2f - steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 - with: - persist-credentials: false - - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 - with: - toolchain: stable - - name: Run RabbitMQ transport integration tests - run: cargo test --test rabbitmq_transport --features rabbitmq --verbose diff --git a/.github/workflows/integration-services.yaml b/.github/workflows/integration-services.yaml new file mode 100644 index 000000000..2760b4485 --- /dev/null +++ b/.github/workflows/integration-services.yaml @@ -0,0 +1,45 @@ +name: Workspace Tests Against Real Services + +# Reusable workflow: referenced from the PR-quality and push-to-main pipelines. +# +# Runs the whole workspace with all features against the services in +# compose.yaml (Postgres, RabbitMQ, Kafka, NATS, Redis) through +# `make test-local`, the same command a developer runs. +# +# `make test-local` sets DISTRIBUTED_REQUIRE_SERVICES, so a test that cannot +# reach its service fails here instead of returning early and reporting a +# pass (tests/common/src/env.rs). There is no list of test targets to maintain: +# a new service-backed test runs here as soon as it exists. +on: + workflow_call: + +env: + CARGO_TERM_COLOR: always + # File and line in backtraces, without the full debug info that makes up + # most of a dev build's link time and cache size. + CARGO_PROFILE_DEV_DEBUG: line-tables-only + CARGO_INCREMENTAL: "0" + +jobs: + services: + name: Workspace Tests (all features, real services) + runs-on: ubuntu-latest + timeout-minutes: 90 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 + with: + toolchain: stable + components: rust-src + - uses: Swatinem/rust-cache@v2 + with: + shared-key: workspace-services + save-if: ${{ github.event_name != 'pull_request' }} + # --all-features compiles rdkafka; librdkafka's bundled cmake build needs + # curl/curl.h (the runner has libcurl's runtime but not its headers). + - name: Install librdkafka build dependencies + run: sudo apt-get update && sudo apt-get install -y libcurl4-openssl-dev + - name: Run the workspace against compose services + run: make test-local CARGO_TEST_ARGS="--workspace --all-features --verbose" diff --git a/.github/workflows/integration-wasm32-domains.yaml b/.github/workflows/integration-wasm32-domains.yaml new file mode 100644 index 000000000..06b6f6e1c --- /dev/null +++ b/.github/workflows/integration-wasm32-domains.yaml @@ -0,0 +1,39 @@ +name: wasm32 domain crates + +# Reusable workflow: referenced via `uses: ./.github/workflows/integration-wasm32-domains.yaml`. +# Domain crates run inside celld cells (wasm32 Durable Objects), so each must +# build for wasm32-unknown-unknown without Tokio sockets, native SQLite or +# other native-only dependencies (game-services decision D4). The script also +# proves the check bites: tests/fixtures/wasm32-native-domain must fail. +# +# Local parity: scripts/check-wasm32-domains.sh +on: + workflow_call: + +env: + CARGO_TERM_COLOR: always + # File and line in backtraces, without the full debug info that makes up + # most of a dev build's link time and cache size. + CARGO_PROFILE_DEV_DEBUG: line-tables-only + CARGO_INCREMENTAL: "0" + +jobs: + wasm32-domains: + name: Domain crates build for wasm32-unknown-unknown + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 + with: + toolchain: stable + targets: wasm32-unknown-unknown + - uses: Swatinem/rust-cache@v2 + with: + shared-key: wasm32-domains + cache-directories: target/wasm32-domains + save-if: ${{ github.event_name != 'pull_request' }} + - name: Build every domain crate for wasm32 (and reject the native fixture) + run: scripts/check-wasm32-domains.sh diff --git a/.github/workflows/on-pr-quality.yaml b/.github/workflows/on-pr-quality.yaml index ae07ccf80..e26d2c259 100644 --- a/.github/workflows/on-pr-quality.yaml +++ b/.github/workflows/on-pr-quality.yaml @@ -1,22 +1,54 @@ name: Rust Quality Pipeline for PRs +# Runs the whole pipeline three ways: +# +# - pull_request: the gate a pull request waits for. It only reads the Rust +# dependency caches (`save-if` in each reusable workflow). +# - push to an integration branch (v5): the same pipeline on the merged +# result. This run writes the caches every pull request into that branch +# then restores; a pull-request run cannot do that, because a cache written +# on a pull request's merge ref is readable by that pull request alone. +# - merge_group: the same pipeline on a merge-queue candidate, so the queue +# can be required on a branch without another workflow. +# +# workflow_dispatch runs it on any branch (and writes that branch's caches). on: pull_request: + merge_group: + workflow_dispatch: + push: + branches: + - v5 concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true jobs: + # Each job below carries the same `if`: a pull request whose head is the + # integration branch itself (`main <- v5`) has the commit the push run above + # is already testing, with the same jobs, and those results show on that + # pull request. Running it twice would take every hosted runner slot the + # organization has (20) for the length of a run. Fork heads still run. contracts: name: Run fail-fast contract lifecycle check + if: ${{ !(github.event_name == 'pull_request' && github.head_ref == 'v5' && !github.event.pull_request.head.repo.fork) }} runs-on: ubuntu-latest + timeout-minutes: 10 + # The same CARGO_* values as integration-distributed-cli.yaml: rust-cache + # hashes them into the key, and this job restores that job's cache. + env: + CARGO_TERM_COLOR: always + CARGO_PROFILE_DEV_DEBUG: line-tables-only + CARGO_INCREMENTAL: "0" steps: - uses: actions/checkout@v7 with: fetch-depth: 0 - name: Resolve PR merge-base id: base + # Only a pull request has a base ref. + if: github.event_name == 'pull_request' run: | git fetch origin "${{ github.base_ref }}" --depth=1 base=$(git merge-base HEAD "origin/${{ github.base_ref }}" || true) @@ -24,18 +56,19 @@ jobs: echo "merge-base=${base}" - name: Install Rust toolchain uses: dtolnay/rust-toolchain@stable + # Restores what the distributed_cli job writes on the base branch. + - uses: Swatinem/rust-cache@v2 + with: + shared-key: cli + save-if: false - name: Run contracts check - run: | - if [ -f contracts/catalog.json ]; then - cargo run -p distributed_cli --quiet -- contracts check --root . --catalog contracts/catalog.json --output json - else - echo "No contracts/catalog.json yet; gate is present and ready for producers." - fi + run: cargo run -p distributed_cli --quiet -- contracts check --root . --catalog distributed.contracts.json --output json # Framework monorepo keeps its existing quality provider. The reusable # quality.yaml in this directory is the contract for *consumers* (domain # crates / Distributed libraries), not for this workspace's entry pipeline. quality: + if: ${{ !(github.event_name == 'pull_request' && github.head_ref == 'v5' && !github.event.pull_request.head.repo.fork) }} uses: unbounded-tech/workflows-rust/.github/workflows/quality.yaml@feat/cargo-publish with: cargo_build_args: "--verbose" @@ -43,38 +76,45 @@ jobs: cargo_incremental: true all-features: + if: ${{ !(github.event_name == 'pull_request' && github.head_ref == 'v5' && !github.event.pull_request.head.repo.fork) }} uses: ./.github/workflows/test-all-features.yaml - postgres: - uses: ./.github/workflows/integration-postgres.yaml - - nats: - uses: ./.github/workflows/integration-nats.yaml + services: + if: ${{ !(github.event_name == 'pull_request' && github.head_ref == 'v5' && !github.event.pull_request.head.repo.fork) }} + uses: ./.github/workflows/integration-services.yaml - rabbitmq: - uses: ./.github/workflows/integration-rabbitmq.yaml - - kafka: - uses: ./.github/workflows/integration-kafka.yaml + gateway: + if: ${{ !(github.event_name == 'pull_request' && github.head_ref == 'v5' && !github.event.pull_request.head.repo.fork) }} + uses: ./.github/workflows/integration-gateway.yaml distributed-cli: - needs: [contracts] + if: ${{ !(github.event_name == 'pull_request' && github.head_ref == 'v5' && !github.event.pull_request.head.repo.fork) }} uses: ./.github/workflows/integration-distributed-cli.yaml observability: + if: ${{ !(github.event_name == 'pull_request' && github.head_ref == 'v5' && !github.event.pull_request.head.repo.fork) }} uses: ./.github/workflows/integration-observability.yaml graphql: - needs: [contracts] + if: ${{ !(github.event_name == 'pull_request' && github.head_ref == 'v5' && !github.event.pull_request.head.repo.fork) }} uses: ./.github/workflows/integration-graphql.yaml e2e-ui: - needs: [contracts] + if: ${{ !(github.event_name == 'pull_request' && github.head_ref == 'v5' && !github.event.pull_request.head.repo.fork) }} uses: ./.github/workflows/integration-e2e-ui.yaml js-client: - needs: [contracts] + if: ${{ !(github.event_name == 'pull_request' && github.head_ref == 'v5' && !github.event.pull_request.head.repo.fork) }} uses: ./.github/workflows/integration-js.yaml + game-demos: + if: ${{ !(github.event_name == 'pull_request' && github.head_ref == 'v5' && !github.event.pull_request.head.repo.fork) }} + uses: ./.github/workflows/integration-game-demos.yaml + celld: + if: ${{ !(github.event_name == 'pull_request' && github.head_ref == 'v5' && !github.event.pull_request.head.repo.fork) }} uses: ./.github/workflows/integration-celld.yaml + + wasm32-domains: + if: ${{ !(github.event_name == 'pull_request' && github.head_ref == 'v5' && !github.event.pull_request.head.repo.fork) }} + uses: ./.github/workflows/integration-wasm32-domains.yaml diff --git a/.github/workflows/on-push-main-version-and-tag.yaml b/.github/workflows/on-push-main-version-and-tag.yaml index fac4ae48f..39c22fb4d 100644 --- a/.github/workflows/on-push-main-version-and-tag.yaml +++ b/.github/workflows/on-push-main-version-and-tag.yaml @@ -22,17 +22,11 @@ jobs: all-features: uses: ./.github/workflows/test-all-features.yaml - postgres: - uses: ./.github/workflows/integration-postgres.yaml + services: + uses: ./.github/workflows/integration-services.yaml - nats: - uses: ./.github/workflows/integration-nats.yaml - - rabbitmq: - uses: ./.github/workflows/integration-rabbitmq.yaml - - kafka: - uses: ./.github/workflows/integration-kafka.yaml + gateway: + uses: ./.github/workflows/integration-gateway.yaml distributed-cli: uses: ./.github/workflows/integration-distributed-cli.yaml @@ -49,14 +43,20 @@ jobs: js-client: uses: ./.github/workflows/integration-js.yaml + game-demos: + uses: ./.github/workflows/integration-game-demos.yaml + celld: uses: ./.github/workflows/integration-celld.yaml + wasm32-domains: + uses: ./.github/workflows/integration-wasm32-domains.yaml + # This uses commit logs and tags from git to determine the next version number and create a tag for the release. # Some commits such as chore: will not trigger a version bump and tag; this is by design. version-and-tag: name: Version and Tag - needs: [quality, all-features, postgres, nats, rabbitmq, kafka, distributed-cli, observability, graphql, e2e-ui, js-client, celld] + needs: [quality, all-features, services, gateway, distributed-cli, observability, graphql, e2e-ui, js-client, game-demos, celld, wasm32-domains] uses: unbounded-tech/workflow-vnext-tag/.github/workflows/workflow.yaml@v1.22.3 secrets: DEPLOY_KEY: ${{ secrets.DEPLOY_KEY }} diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index bc649fdf8..3592cbd5e 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -17,6 +17,10 @@ jobs: - uses: dtolnay/rust-toolchain@stable with: components: llvm-tools-preview + - uses: Swatinem/rust-cache@v2 + with: + shared-key: coverage + save-if: ${{ github.event_name != 'pull_request' }} - uses: taiki-e/install-action@cargo-llvm-cov # --all-features compiles rdkafka; librdkafka's bundled cmake build needs # curl/curl.h (the runner has libcurl's runtime but not its headers). diff --git a/.github/workflows/test-all-features.yaml b/.github/workflows/test-all-features.yaml index 1d248d1a4..4a8bbfe3e 100644 --- a/.github/workflows/test-all-features.yaml +++ b/.github/workflows/test-all-features.yaml @@ -1,43 +1,25 @@ -name: All-Features Tests +name: Each-Feature Check # Reusable workflow: referenced via `uses: ./.github/workflows/test-all-features.yaml` # from both the PR-quality and push-to-main pipelines. # -# The shared quality job runs `cargo test` with default features (= none), so -# every `#![cfg(feature = ...)]` test target compiles to empty there. This job -# closes that gap: it compiles and runs the whole workspace with all features -# (sqlite, emitter, http, grpc, ...). Broker/database tests self-skip when -# their service env vars (DATABASE_URL, NATS_URL, ...) are unset, so no -# service containers are needed here — the integration-* workflows cover those. +# The all-features test run lives in integration-services.yaml, where the +# services its tests need are running. on: workflow_call: -jobs: - all-features: - name: All-Features Tests - runs-on: ubuntu-latest - env: - CARGO_TERM_COLOR: always - steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 - with: - persist-credentials: false - - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 - with: - toolchain: stable - components: rust-src - # --all-features compiles rdkafka; librdkafka's bundled cmake build needs - # curl/curl.h (the runner has libcurl's runtime but not its headers). - - name: Install librdkafka build dependencies - run: sudo apt-get update && sudo apt-get install -y libcurl4-openssl-dev - - name: Run workspace tests with all features - run: cargo test --workspace --all-features --all-targets --verbose +env: + CARGO_TERM_COLOR: always + # File and line in backtraces, without the full debug info that makes up + # most of a dev build's link time and cache size. + CARGO_PROFILE_DEV_DEBUG: line-tables-only + CARGO_INCREMENTAL: "0" +jobs: each-feature: name: Each-Feature Check runs-on: ubuntu-latest - env: - CARGO_TERM_COLOR: always + timeout-minutes: 20 steps: - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 with: @@ -45,6 +27,10 @@ jobs: - uses: dtolnay/rust-toolchain@29eef336d9b2848a0b548edc03f92a220660cdb8 with: toolchain: stable + - uses: Swatinem/rust-cache@v2 + with: + shared-key: each-feature + save-if: ${{ github.event_name != 'pull_request' }} - uses: taiki-e/install-action@cargo-hack # The kafka feature alone compiles rdkafka; see above. - name: Install librdkafka build dependencies diff --git a/.gitignore b/.gitignore index 05bdbb792..686521539 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,11 @@ # Generated by Cargo /target/ -# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries -# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +# The workspace lockfile is tracked: the workspace ships a CLI binary, and CI +# should build what was reviewed rather than whatever resolved that day. +# Nested crates opt in with their own `!Cargo.lock`. Cargo.lock +!/Cargo.lock # These are backup files generated by rustfmt **/*.rs.bk @@ -44,8 +46,8 @@ graphql-oidc.env graphql-oidc.env graphql-oidc-keycloak.env graphql-oidc-authentik.env -tests/graphql_oidc_zitadel/machinekey/** -!tests/graphql_oidc_zitadel/machinekey/.gitignore +tests/graphql/graphql_oidc_zitadel/machinekey/** +!tests/graphql/graphql_oidc_zitadel/machinekey/.gitignore tests/workshop-service/ui/node_modules/ tests/workshop-service/ui/build/ tests/workshop-service/ui/.svelte-kit/ @@ -59,3 +61,12 @@ tests/celld/worker/build/ tests/celld/worker/.celld/ tests/celld/relay-worker/target/ tests/celld/relay-worker/build/ +tests/celld/alarm-worker/target/ +tests/celld/alarm-worker/build/ +tests/celld/alarm-worker/.celld/ +tests/celld/fact-worker/target/ +tests/celld/fact-worker/build/ +tests/celld/fact-worker/.celld/ + +# Build output of CLI test fixture crates +/distributed_cli/tests/fixtures/*/target/ diff --git a/.gitops/local/cluster.yaml b/.gitops/local/cluster.yaml new file mode 100644 index 000000000..56da61ae7 --- /dev/null +++ b/.gitops/local/cluster.yaml @@ -0,0 +1,17 @@ +# The machine's one Hops Cluster (OrbStack k3s). Mob Pit never provisions a +# cluster; identity (name, mountRoot, localDomain) is machine-owned and must +# match ~/.gitops/local/cluster.yaml. `cluster/` holds the packages Mob Pit +# needs on it (overlaid by `hops local up`). +apiVersion: hops.local/v1alpha1 +kind: Cluster +metadata: + name: hops +spec: + clusterProvider: orbstack + dockerProvider: orbstack + mountRoot: $HOME + browserIngress: + namespaces: + - auth + manifests: + path: .gitops/local/cluster diff --git a/.gitops/local/cluster/README.md b/.gitops/local/cluster/README.md new file mode 100644 index 000000000..81d9da585 --- /dev/null +++ b/.gitops/local/cluster/README.md @@ -0,0 +1,12 @@ +# Mob Pit cluster overlay + +Packages the Mob Pit Environments need on the machine Cluster: + +- `configurations/celld-stack.yaml`: `CelldStack` (celld fleet + RustFS), + used by `mobpit-system`. Dependencies (provider-helm, provider-kubernetes, + function-auto-ready) are already part of the machine Cluster, so + dependency resolution is skipped (the AWS S3 provider is only needed for + `spec.aws`). + +`hops local up` from this checkout layers this directory over the machine +tree; the running Cluster controller then installs it. diff --git a/.gitops/local/cluster/configurations/celld-stack.yaml b/.gitops/local/cluster/configurations/celld-stack.yaml new file mode 100644 index 000000000..3047191ee --- /dev/null +++ b/.gitops/local/cluster/configurations/celld-stack.yaml @@ -0,0 +1,8 @@ +# First celld-stack release with RustFS (hops-ops/celld-stack#15). Its +# render function and provider-aws-s3 come in through dependency resolution. +apiVersion: pkg.crossplane.io/v1 +kind: Configuration +metadata: + name: hops-ops-celld-stack +spec: + package: ghcr.io/hops-ops/celld-stack:v0.11.0 diff --git a/.gitops/local/mobpit-system.yaml b/.gitops/local/mobpit-system.yaml new file mode 100644 index 000000000..6c668af36 --- /dev/null +++ b/.gitops/local/mobpit-system.yaml @@ -0,0 +1,19 @@ +apiVersion: hops.local/v1alpha1 +kind: Environment +metadata: + name: mobpit-system +spec: + # Shared by the Mob Pit Environments on the machine Cluster: the celld + # fleet (CelldStack with RustFS, namespace mobpit-celld) and the CA the + # fleet trusts for its HTTPS outbox relay. Off until + # `hops local env enable mobpit-system`. + scope: cluster + clusterRef: + name: hops + namespace: mobpit-system + root: examples/game + setup: + - path: examples/game/scripts/hops/mobpit-system-setup.sh + deploys: + - path: .gitops/mobpit-system + type: k8s diff --git a/.gitops/local/mobpit.yaml b/.gitops/local/mobpit.yaml new file mode 100644 index 000000000..5593c00c0 --- /dev/null +++ b/.gitops/local/mobpit.yaml @@ -0,0 +1,18 @@ +apiVersion: hops.local/v1alpha1 +kind: Environment +metadata: + # Template name; the runtime name and namespace come from the checkout + # (e.g. distributed-mobpit-world). The browser host is the chart's `host` + # value (https://mobpit.localhost). + name: mobpit +spec: + clusterRef: + name: hops + root: examples/game + # Builds from this checkout on the host (JS SDK, WebAssembly, cells + # worker) and this Environment's secrets. Needs mobpit-system. + setup: + - path: examples/game/scripts/hops/mobpit-setup.sh + deploys: + - path: .gitops/local + type: helm diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 000000000..7c6b98241 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,5662 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "Inflector" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3" + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "amq-protocol" +version = "10.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba56915f72aa721b4bca471fa71ff8ec10aecc0d5e2d99497edb44358ccedd7b" +dependencies = [ + "amq-protocol-tcp", + "amq-protocol-types", + "amq-protocol-uri", + "cookie-factory", + "nom 8.0.0", + "serde", +] + +[[package]] +name = "amq-protocol-tcp" +version = "10.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84153f37233d155953ccbacb21257b4cb82edb68e57066495ff86495d8783a32" +dependencies = [ + "amq-protocol-uri", + "async-rs", + "cfg-if", + "tcp-stream", + "tracing", +] + +[[package]] +name = "amq-protocol-types" +version = "10.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aca84dae6981386bc016fc44434ff9cb6b1f99c25fd0e890ddb048c91261db1" +dependencies = [ + "cookie-factory", + "nom 8.0.0", + "serde", + "serde_json", +] + +[[package]] +name = "amq-protocol-uri" +version = "10.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b58add0b63b221e87956f3ec47d6b8f1a0a6f69cc970b668590000c3aa701af" +dependencies = [ + "amq-protocol-types", + "percent-encoding", + "url", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "ar_archive_writer" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" +dependencies = [ + "object", +] + +[[package]] +name = "arc-swap" +version = "1.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84a22b5d51209f6de83d37a0b33d320acb8da88823e42a94c075140708f032a5" +dependencies = [ + "rustversion", +] + +[[package]] +name = "arcstr" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03918c3dbd7701a85c6b9887732e2921175f26c350b4563841d0958c21d57e6d" + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "ascii_utils" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71938f30533e4d95a6d17aa530939da3842c2ab6f4f84b9dae68447e4129f74a" + +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom 7.1.3", + "num-traits", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure 0.13.2", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-compat" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3293517e7da05b02ea72ba703bf2acc2906a53b2addf2c08fb65de7a90530891" +dependencies = [ + "futures-core", + "futures-io", + "once_cell", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "async-executor" +version = "1.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-global-executor" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13f937e26114b93193065fd44f507aa2e9169ad0cdabbb996920b1fe1ddea7ba" +dependencies = [ + "async-channel", + "async-executor", + "async-lock", + "blocking", + "futures-lite", + "tokio", +] + +[[package]] +name = "async-graphql" +version = "7.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1057a9f7ccf2404d94571dec3451ade1cb524790df6f1ada0d19c2a49f6b0f40" +dependencies = [ + "async-graphql-derive", + "async-graphql-parser", + "async-graphql-value", + "async-io", + "async-trait", + "asynk-strim", + "base64 0.22.1", + "bytes", + "fast_chemail", + "fnv", + "futures-util", + "handlebars", + "http", + "indexmap", + "mime", + "multer", + "num-traits", + "pin-project-lite", + "regex", + "serde", + "serde_json", + "serde_urlencoded", + "static_assertions_next", + "tempfile", + "thiserror", +] + +[[package]] +name = "async-graphql-axum" +version = "7.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1e37c5532e4b686acf45e7162bc93da91fc2c702fb0d465efc2c20c8f973795" +dependencies = [ + "async-graphql", + "axum", + "bytes", + "futures-util", + "serde_json", + "tokio", + "tokio-stream", + "tokio-util", + "tower-service", +] + +[[package]] +name = "async-graphql-derive" +version = "7.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e6cbeadc8515e66450fba0985ce722192e28443697799988265d86304d7cc68" +dependencies = [ + "Inflector", + "async-graphql-parser", + "darling 0.23.0", + "proc-macro-crate", + "proc-macro2", + "quote", + "strum 0.27.2", + "syn 2.0.119", + "thiserror", +] + +[[package]] +name = "async-graphql-parser" +version = "7.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e64ef70f77a1c689111e52076da1cd18f91834bcb847de0a9171f83624b07fbf" +dependencies = [ + "async-graphql-value", + "pest", + "serde", + "serde_json", +] + +[[package]] +name = "async-graphql-value" +version = "7.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e3ef112905abea9dea592fc868a6873b10ebd3f983e83308f995d6284e9ba41" +dependencies = [ + "bytes", + "indexmap", + "serde", + "serde_json", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-nats" +version = "0.50.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83a251fa1a4c9d0fe6e816b7acd60549e473e08d14f27a1d992c2675abff05f" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-util", + "memchr", + "nkeys", + "nuid", + "pin-project", + "portable-atomic", + "rand 0.10.4", + "regex", + "ring", + "rustls-native-certs", + "rustls-pki-types", + "rustls-webpki", + "serde", + "serde_json", + "serde_nanos", + "serde_repr", + "thiserror", + "time", + "tokio", + "tokio-rustls", + "tokio-stream", + "tokio-util", + "tokio-websockets", + "tracing", + "tryhard", + "url", +] + +[[package]] +name = "async-rs" +version = "0.8.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "407bdac3815af195d2d63fa50595610ea8ba4d47b7fc5a37895b05d3b571c241" +dependencies = [ + "async-compat", + "async-global-executor", + "async-trait", + "futures-core", + "futures-io", + "hickory-resolver", + "tokio", + "tokio-stream", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "asynk-strim" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52697735bdaac441a29391a9e97102c74c6ef0f9b60a40cf109b1b404e29d2f6" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "atoi" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" +dependencies = [ + "num-traits", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "aws-lc-rs" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "base64 0.22.1", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit 0.8.4", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sha1 0.10.7", + "sync_wrapper", + "tokio", + "tokio-tungstenite 0.29.0", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "backon" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cffb0e931875b666fc4fcb20fee52e9bbd1ef836fd9e9e04ec21555f9f85f7ef" +dependencies = [ + "fastrand", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bit-set" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0" +dependencies = [ + "borsh", + "serde", +] + +[[package]] +name = "bitcode" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a6ed1b54d8dc333e7be604d00fa9262f4635485ffea923647b6521a5fff045d" +dependencies = [ + "arrayvec", + "bitcode_derive", + "bytemuck", + "glam", + "serde", +] + +[[package]] +name = "bitcode_derive" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "238b90427dfad9da4a9abd60f3ec1cdee6b80454bde49ed37f1781dd8e9dc7f9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "serde_core", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "block-padding" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2", +] + +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" +dependencies = [ + "serde", +] + +[[package]] +name = "cbc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +dependencies = [ + "cipher", +] + +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "js-sys", + "num-traits", + "wasm-bindgen", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common 0.1.7", + "inout", +] + +[[package]] +name = "clap" +version = "4.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac230478587d0269d8d6998b82ae69ea51509d55df66d9e92edd1f986904cd4a" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "895c9d8d2ac2dd8b8a29f3724a14e72aaaa6debcf8c38c82f97305c6a172767a" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "cms" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b77c319abfd5219629c45c34c89ba945ed3c5e49fcde9d16b6c3885f118a730" +dependencies = [ + "const-oid 0.9.6", + "der", + "spki", + "x509-cert", +] + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "futures-core", + "memchr", + "pin-project-lite", + "tokio", + "tokio-util", +] + +[[package]] +name = "common" +version = "0.0.0" +dependencies = [ + "async-graphql", + "axum", + "base64 0.23.1", + "bitcode", + "distributed", + "jsonwebtoken", + "rand 0.8.8", + "reqwest", + "rsa", + "serde", + "serde_json", + "sqlx", + "tokio", + "tower", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "cookie-factory" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9885fa71e26b8ab7855e2ec7cae6e9b380edff76cd052e07c683a0319d51b3a2" + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" + +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctrlc" +version = "3.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11247e6c4f83c2b15748f4873805483deaa2bbc855e773817c07a9f987f55c62" +dependencies = [ + "dispatch2", + "nix", + "windows-sys 0.61.2", +] + +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "digest 0.10.7", + "fiat-crypto", + "rustc_version", + "subtle", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "darling" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" +dependencies = [ + "darling_core 0.20.11", + "darling_macro 0.20.11", +] + +[[package]] +name = "darling" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d" +dependencies = [ + "darling_core 0.23.0", + "darling_macro 0.23.0", +] + +[[package]] +name = "darling_core" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.119", +] + +[[package]] +name = "darling_core" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.119", +] + +[[package]] +name = "darling_macro" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" +dependencies = [ + "darling_core 0.20.11", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "darling_macro" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d" +dependencies = [ + "darling_core 0.23.0", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "der_derive", + "flagset", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom 7.1.3", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "der_derive" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +dependencies = [ + "serde_core", +] + +[[package]] +name = "derive_builder" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947" +dependencies = [ + "derive_builder_macro", +] + +[[package]] +name = "derive_builder_core" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" +dependencies = [ + "darling 0.20.11", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "derive_builder_macro" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" +dependencies = [ + "derive_builder_core", + "syn 2.0.119", +] + +[[package]] +name = "des" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffdd80ce8ce993de27e9f063a444a4d53ce8e8db4c1f00cc03af5ad5a9867a1e" +dependencies = [ + "cipher", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "const-oid 0.9.6", + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid 0.10.3", + "crypto-common 0.2.2", + "ctutils", +] + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags", + "block2", + "libc", + "objc2", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "distributed" +version = "0.1.0" +dependencies = [ + "async-graphql", + "async-graphql-axum", + "async-graphql-parser", + "async-nats", + "async-trait", + "axum", + "base64 0.23.1", + "bitcode", + "common", + "distributed_cli", + "distributed_macros", + "futures", + "futures-channel", + "futures-util", + "hmac 0.12.1", + "http-body-util", + "hyper", + "hyper-util", + "js-sys", + "jsonwebtoken", + "lapin", + "log", + "opentelemetry", + "opentelemetry-otlp", + "opentelemetry_sdk", + "proptest", + "prost", + "rand 0.8.8", + "rdkafka", + "redis", + "reqwest", + "rsa", + "serde", + "serde_json", + "sha2 0.10.9", + "sqlx", + "subtle", + "tokio", + "tokio-stream", + "tokio-tungstenite 0.30.0", + "tonic", + "tonic-build", + "tonic-prost", + "tower", + "tracing", + "tracing-opentelemetry", + "tracing-subscriber", + "url", + "uuid", + "worker", +] + +[[package]] +name = "distributed_cli" +version = "0.1.0" +dependencies = [ + "async-graphql-parser", + "async-graphql-value", + "base64 0.23.1", + "clap", + "ctrlc", + "distributed", + "distributed_game", + "distributed_leaderboard", + "dotenvy", + "fs2", + "glob", + "libc", + "serde", + "serde_json", + "sha2 0.10.9", + "tempfile", +] + +[[package]] +name = "distributed_game" +version = "0.1.0" +dependencies = [ + "axum", + "base64 0.23.1", + "distributed", + "distributed_game_macros", + "futures-util", + "hmac 0.12.1", + "js-sys", + "reqwest", + "serde", + "serde_json", + "sha2 0.10.9", + "sqlx", + "tokio", + "tokio-tungstenite 0.30.0", + "trybuild", + "uuid", + "wasm-bindgen", + "wasm-bindgen-futures", + "worker", +] + +[[package]] +name = "distributed_game_macros" +version = "0.1.0" +dependencies = [ + "distributed_game", + "proc-macro-crate", + "proc-macro2", + "quote", + "serde", + "serde_json", + "syn 2.0.119", + "trybuild", +] + +[[package]] +name = "distributed_leaderboard" +version = "0.1.0" +dependencies = [ + "async-graphql", + "async-trait", + "common", + "distributed", + "distributed_cli", + "futures-util", + "redis", + "serde", + "serde_json", + "sqlx", + "tokio", + "tracing", + "uuid", +] + +[[package]] +name = "distributed_macros" +version = "0.1.0" +dependencies = [ + "distributed", + "proc-macro-crate", + "proc-macro2", + "quote", + "serde", + "serde_json", + "sha2 0.10.9", + "syn 2.0.119", + "trybuild", +] + +[[package]] +name = "dotenvy" +version = "0.15.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "sha2 0.10.9", + "signature", + "subtle", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" +dependencies = [ + "serde", +] + +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "etcetera" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de48cc4d1c1d97a20fd819def54b890cadde72ed3ad0c614822a0a433361be96" +dependencies = [ + "cfg-if", + "windows-sys 0.61.2", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "fast_chemail" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "495a39d30d624c2caabe6312bfead73e7717692b44e0b32df168c275a2e8e9e4" +dependencies = [ + "ascii_utils", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flagset" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe" + +[[package]] +name = "flume" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be" +dependencies = [ + "futures-core", + "futures-sink", + "spin", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "fs2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-intrusive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" +dependencies = [ + "futures-core", + "lock_api", + "parking_lot", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-rustls" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8f2f12607f92c69b12ed746fabf9ca4f5c482cba46679c1a75b874ed7c26adb" +dependencies = [ + "futures-io", + "rustls", + "rustls-pki-types", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "glam" +version = "0.34.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "627003914c6057c9c8f0832ee4f870b5a4f599d0cfa83f4072675114860cd0ff" + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "handlebars" +version = "6.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75c54236f9045c8004a77942bebc52145b4844639db934a5c70fe08617fbe61a" +dependencies = [ + "derive_builder", + "log", + "num-order", + "pest", + "pest_derive", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hashlink" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824e001ac4f3012dd16a264bec811403a67ca9deb6c102fc5049b32c4574b35f" +dependencies = [ + "hashbrown 0.16.1", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hickory-net" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c480823ed7c2c5d0f09c41020cb6b7c28029ce60ec42dc942158dcf22f8e0a4d" +dependencies = [ + "async-trait", + "cfg-if", + "data-encoding", + "futures-channel", + "futures-io", + "futures-util", + "hickory-proto", + "idna", + "ipnet", + "jni", + "rand 0.10.4", + "thiserror", + "tinyvec", + "tokio", + "tracing", + "url", +] + +[[package]] +name = "hickory-proto" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12b92608f679a6fa515dd1d15c1ff89443026e391200a2c840c7afcba482893d" +dependencies = [ + "data-encoding", + "idna", + "ipnet", + "jni", + "once_cell", + "prefix-trie", + "rand 0.10.4", + "ring", + "thiserror", + "tinyvec", + "tracing", + "url", +] + +[[package]] +name = "hickory-resolver" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f3da5255c95d5a716857d54b5b8f4e8d67c3484d3beaaaae2ce25063b3ba981" +dependencies = [ + "cfg-if", + "futures-util", + "hickory-net", + "hickory-proto", + "ipconfig", + "ipnet", + "jni", + "moka", + "ndk-context", + "once_cell", + "parking_lot", + "rand 0.10.4", + "resolv-conf", + "smallvec", + "system-configuration", + "thiserror", + "tokio", + "tracing", +] + +[[package]] +name = "hkdf" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" +dependencies = [ + "hmac 0.13.0", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-timeout" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0" +dependencies = [ + "hyper", + "hyper-util", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "system-configuration", + "tokio", + "tower-service", + "tracing", + "windows-registry", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "block-padding", + "generic-array", +] + +[[package]] +name = "ipconfig" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d40460c0ce33d6ce4b0630ad68ff63d6661961c48b6dba35e5a4d81cfb48222" +dependencies = [ + "socket2", + "widestring", + "windows-registry", + "windows-result", + "windows-sys 0.61.2", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +dependencies = [ + "serde", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "jsonwebtoken" +version = "9.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde" +dependencies = [ + "base64 0.22.1", + "js-sys", + "pem", + "ring", + "serde", + "serde_json", + "simple_asn1", +] + +[[package]] +name = "lapin" +version = "4.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3212643cc0031d982f81a62360998106268587237d81d6e8501a0a323e13b656" +dependencies = [ + "amq-protocol", + "async-rs", + "async-trait", + "backon", + "cfg-if", + "event-listener", + "flume", + "futures-core", + "futures-io", + "tracing", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "libc", +] + +[[package]] +name = "libsqlite3-sys" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b06e69070b7e12262b0cd90832f0a7396f142a2b330181255562decf9f0c6215" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "libz-sys" +version = "1.1.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fee3f59f4321dab0c78d828942e7aa09d0bd8ad6e78a501977e6bf3d02938045" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "matchit" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "md-5" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" +dependencies = [ + "cfg-if", + "digest 0.11.3", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "moka" +version = "0.12.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4293f18e7567a1caf3c584855554377025c65e0aa445344d04171f5ad63d19b9" +dependencies = [ + "crossbeam-channel", + "crossbeam-epoch", + "crossbeam-utils", + "equivalent", + "parking_lot", + "portable-atomic", + "smallvec", + "tagptr", + "uuid", +] + +[[package]] +name = "multer" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" +dependencies = [ + "bytes", + "encoding_rs", + "futures-util", + "http", + "httparse", + "memchr", + "mime", + "spin", + "version_check", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "nix" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77730ed34f01f4990cb2ea67fec715ecebc6fab9a6396cf83c5529b13f581bdc" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "nkeys" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879011babc47a1c7fdf5a935ae3cfe94f34645ca0cac1c7f6424b36fc743d1bf" +dependencies = [ + "data-encoding", + "ed25519", + "ed25519-dalek", + "getrandom 0.2.17", + "log", + "rand 0.8.8", + "signatory", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "nuid" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc895af95856f929163a0aa20c26a78d26bfdc839f51b9d5aa7a5b79e52b7e83" +dependencies = [ + "rand 0.8.8", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand 0.8.8", + "smallvec", + "zeroize", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-modular" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd8e500409e6cd603b03e477c26a6caecdc27ac58979a53e881c75eafc079f44" + +[[package]] +name = "num-order" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "537b596b97c40fcf8056d153049eb22f481c17ebce72a513ec9286e4986d1bb6" +dependencies = [ + "num-modular", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-system-configuration" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7216bd11cbda54ccabcab84d523dc93b858ec75ecfb3a7d89513fa22464da396" +dependencies = [ + "objc2-core-foundation", +] + +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +dependencies = [ + "critical-section", + "portable-atomic", +] + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "opentelemetry" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0142c63252a9e054e68a4c61a5778f7b14f576274d593f8ce883d191a099682" +dependencies = [ + "futures-core", + "futures-sink", + "js-sys", + "pin-project-lite", + "thiserror", +] + +[[package]] +name = "opentelemetry-http" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5683015d09e2df236ef005b17f6f196f0d5f6313c4fa43a7b6a53b52776e4331" +dependencies = [ + "async-trait", + "bytes", + "http", + "opentelemetry", + "reqwest", +] + +[[package]] +name = "opentelemetry-otlp" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9966929966d17620d7c316c643ba62631826e10021409357772d5eea84f62c35" +dependencies = [ + "http", + "opentelemetry", + "opentelemetry-http", + "opentelemetry-proto", + "opentelemetry_sdk", + "prost", + "reqwest", + "thiserror", +] + +[[package]] +name = "opentelemetry-proto" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56d658ba1faf63f7b9c492cfbe6e0ec365440a16132d3270c1065f7b33f1b638" +dependencies = [ + "opentelemetry", + "opentelemetry_sdk", + "prost", +] + +[[package]] +name = "opentelemetry_sdk" +version = "0.32.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b59f80e1ac4d5ff7a2db8fb6c80badb7f0f3f858211fba08dd9aaec750894f9" +dependencies = [ + "futures-channel", + "futures-executor", + "futures-util", + "opentelemetry", + "percent-encoding", + "portable-atomic", + "rand 0.9.5", + "thiserror", +] + +[[package]] +name = "p12-keystore" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffb9bf5222606eb712d3bb30e01bc9420545b00859970897e70c682353a034f2" +dependencies = [ + "base64 0.22.1", + "cbc", + "cms", + "der", + "des", + "hex", + "hmac 0.12.1", + "pkcs12", + "pkcs5", + "rand 0.10.4", + "rc2", + "sha1 0.10.7", + "sha2 0.10.9", + "thiserror", + "x509-parser", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pbkdf2" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" +dependencies = [ + "digest 0.10.7", + "hmac 0.12.1", +] + +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64 0.22.1", + "serde_core", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pest" +version = "2.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ec53fd1d256900a9a771bf2720d42cef6f8bc91b4e25065fbd291e3e7222576" +dependencies = [ + "memchr", + "pest_stack_guard", + "ucd-trie", +] + +[[package]] +name = "pest_derive" +version = "2.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adcf794fd301ddc20818a6b4de85ed507f4b45300245cec948982e69e12e3bd7" +dependencies = [ + "pest", + "pest_generator", +] + +[[package]] +name = "pest_generator" +version = "2.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3073afae5db334c25dea9fc3e230a4f191e920c1df080cb9c0b37c9ce1dbb41" +dependencies = [ + "pest", + "pest_meta", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "pest_meta" +version = "2.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bc7f614b3742541642af1685faaa910bf6333e3cd3729c2cccd118146a57327" +dependencies = [ + "pest", +] + +[[package]] +name = "pest_stack_guard" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ac6154fd4418b8f0b82532c59c26f303f9ca59a64c883e8ce3971fd82733439" +dependencies = [ + "psm", + "stacker", +] + +[[package]] +name = "pin-project" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6c2123f4708bbd422630a6dae7c03f678b1ce1f1c99e4c4b3beac69c8174cc9" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "358938fd6df944c1e44bb328b60fb275f13c804aac47ba26a1165d45a3f87756" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs12" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "695b3df3d3cc1015f12d70235e35b6b79befc5fa7a9b95b951eab1dd07c9efc2" +dependencies = [ + "cms", + "const-oid 0.9.6", + "der", + "digest 0.10.7", + "spki", + "x509-cert", + "zeroize", +] + +[[package]] +name = "pkcs5" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e847e2c91a18bfa887dd028ec33f2fe6f25db77db3619024764914affe8b69a6" +dependencies = [ + "aes", + "cbc", + "der", + "pbkdf2", + "scrypt", + "sha2 0.10.9", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "prefix-trie" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cf6e3177f0684016a5c209b00882e15f8bdd3f3bb48f0491df10cd102d0c6e7" +dependencies = [ + "either", + "ipnet", + "num-traits", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proptest" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" +dependencies = [ + "bit-set", + "bit-vec", + "bitflags", + "chacha20", + "core_detect", + "num-traits", + "rand 0.10.4", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", + "unarray", +] + +[[package]] +name = "prost" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ef0b569d1d907ab3a28596aee62cf1f61dacb0529a4bedcd8e7460e2d5228b4" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-derive" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad9c5423459fa2f729b8d9235fab810aa29628b171467744fc86d21460ad70d" +dependencies = [ + "anyhow", + "itertools", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.4", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb95882a1e14462c69aea9984bb261293ccfe6022ef8de0eda18bd5afb0052df" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "rand_xorshift" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "rc2" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62c64daa8e9438b84aaae55010a93f396f8e60e3911590fcba770d04643fc1dd" +dependencies = [ + "cipher", +] + +[[package]] +name = "rdkafka" +version = "0.39.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7956f9ac12b5712e50372d9749a3102f4810a8d42481c5eae3748d36d585bcf" +dependencies = [ + "futures-channel", + "futures-util", + "libc", + "log", + "rdkafka-sys", + "serde", + "serde_derive", + "serde_json", + "slab", + "tokio", +] + +[[package]] +name = "rdkafka-sys" +version = "4.10.0+2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e234cf318915c1059d4921ef7f75616b5219b10b46e9f3a511a15eb4b56a3f77" +dependencies = [ + "cmake", + "libc", + "libz-sys", + "num_enum", + "pkg-config", +] + +[[package]] +name = "redis" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bef8fa589dd53a8a379a7856de1365d0a1be50c6b8aebb5c01c1ec441a2c509" +dependencies = [ + "arc-swap", + "arcstr", + "async-lock", + "backon", + "bytes", + "cfg-if", + "combine", + "futures-channel", + "futures-util", + "itoa", + "percent-encoding", + "pin-project-lite", + "ryu", + "sha1_smol", + "socket2", + "tokio", + "tokio-util", + "url", + "xxhash-rust", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "renamed-dependency" +version = "0.1.0" +dependencies = [ + "distributed", + "serde", +] + +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "encoding_rs", + "futures-channel", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "mime", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_json", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams 0.5.0", + "web-sys", +] + +[[package]] +name = "resolv-conf" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid 0.9.6", + "digest 0.10.7", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core 0.6.4", + "signature", + "spki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom 7.1.3", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "aws-lc-rs", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-connector" +version = "0.23.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f799ef81c26fda57609b9456ae1e6750e2ca3dafc2dc5478232c0705f1458fbf" +dependencies = [ + "futures-io", + "futures-rustls", + "log", + "rustls", + "rustls-platform-verifier", + "rustls-webpki", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation 0.10.1", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "aws-lc-rs", + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "rusty-fork" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" +dependencies = [ + "fnv", + "quick-error", + "tempfile", + "wait-timeout", +] + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "salsa20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213" +dependencies = [ + "cipher", +] + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "scrypt" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f" +dependencies = [ + "pbkdf2", + "salsa20", + "sha2 0.10.9", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde-wasm-bindgen" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8302e169f0eddcc139c70f139d19d6467353af16f9fce27e8c30158036a1e16b" +dependencies = [ + "js-sys", + "serde", + "wasm-bindgen", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_nanos" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a93142f0367a4cc53ae0fead1bcda39e85beccfad3dcd717656cacab94b12985" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "sha1_smol" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "signatory" +version = "0.27.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1e303f8205714074f6068773f0e29527e0453937fe837c9717d066635b65f31" +dependencies = [ + "pkcs8", + "rand_core 0.6.4", + "signature", + "zeroize", +] + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest 0.10.7", + "rand_core 0.6.4", +] + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "simple_asn1" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" +dependencies = [ + "num-bigint", + "num-traits", + "thiserror", + "time", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" +dependencies = [ + "serde", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +dependencies = [ + "lock_api", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "sqlx" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edb1dddfbdfe5fb99dba0541a87b2edb8adbd59e45815db22d32d4fbbb8813dd" +dependencies = [ + "sqlx-core", + "sqlx-macros", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", +] + +[[package]] +name = "sqlx-core" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08f9787cc5aff062567dea2205f8ae37a617b04342633ab4f74944858ea6072" +dependencies = [ + "base64 0.22.1", + "bytes", + "cfg-if", + "crc", + "crossbeam-queue", + "either", + "event-listener", + "futures-core", + "futures-intrusive", + "futures-io", + "futures-util", + "hashbrown 0.16.1", + "hashlink", + "indexmap", + "log", + "memchr", + "percent-encoding", + "serde", + "serde_json", + "sha2 0.11.1", + "smallvec", + "thiserror", + "tokio", + "tokio-stream", + "tracing", + "url", +] + +[[package]] +name = "sqlx-macros" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf62c58a1e7fd6031ee684eee21d07572f5aebe71c273a01ae4f04eeeba47c47" +dependencies = [ + "proc-macro2", + "quote", + "sqlx-core", + "sqlx-macros-core", + "syn 2.0.119", +] + +[[package]] +name = "sqlx-macros-core" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1ff75c9d609ac84aa8a3e0d92b5c0c54bf541a7f70db492fb40c9a4bea792c8" +dependencies = [ + "cfg-if", + "dotenvy", + "either", + "heck", + "hex", + "proc-macro2", + "quote", + "serde", + "serde_json", + "sha2 0.11.1", + "sqlx-core", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", + "syn 2.0.119", + "tokio", + "url", +] + +[[package]] +name = "sqlx-mysql" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19eeb93b96eb10a3a59dfb436f3daf87d2fc41168ed9e9dc153ec8257dd6a761" +dependencies = [ + "bitflags", + "byteorder", + "bytes", + "crc", + "digest 0.11.3", + "dotenvy", + "either", + "futures-core", + "futures-util", + "generic-array", + "log", + "percent-encoding", + "serde", + "sha1 0.11.0", + "sha2 0.11.1", + "sqlx-core", + "thiserror", + "tracing", +] + +[[package]] +name = "sqlx-postgres" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0e9e02f764a1fe640eeefc8eb33eeddd274204654ec9f2db8ff851a1dee2364" +dependencies = [ + "atoi", + "base64 0.22.1", + "bitflags", + "byteorder", + "crc", + "dotenvy", + "etcetera", + "futures-channel", + "futures-core", + "futures-util", + "hex", + "hkdf", + "hmac 0.13.0", + "itoa", + "log", + "md-5", + "memchr", + "rand 0.10.4", + "serde", + "serde_json", + "sha2 0.11.1", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "tracing", + "whoami", +] + +[[package]] +name = "sqlx-sqlite" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b6b78a34ddcb1db4046d462db8f79cee811019d7297b99fca8fac5de26672e" +dependencies = [ + "atoi", + "flume", + "form_urlencoded", + "futures-channel", + "futures-core", + "futures-executor", + "futures-intrusive", + "futures-util", + "libsqlite3-sys", + "log", + "percent-encoding", + "serde", + "sqlx-core", + "thiserror", + "tracing", + "url", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + +[[package]] +name = "static_assertions_next" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7beae5182595e9a8b683fa98c4317f956c9a2dec3b9716990d20023cc60c766" + +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" +dependencies = [ + "strum_macros 0.27.2", +] + +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros 0.28.0", +] + +[[package]] +name = "strum_macros" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "tagptr" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" + +[[package]] +name = "target-tuple" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "876fef147edbcbddc8ac5cbbba92c7b86519e314e86638596c09673b2ed01e7f" + +[[package]] +name = "tcp-stream" +version = "0.34.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2afa87967dbc0fa02957531aab16e5d5fe8a8aa71d8efd9d4173c1f14c59e381" +dependencies = [ + "async-rs", + "cfg-if", + "futures-io", + "p12-keystore", + "rustix", + "rustls-connector", + "rustls-pki-types", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite 0.29.0", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17a073bfed563fa236697a068031408a93cd9522e08abf9933ead3e73411bd71" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite 0.30.0", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-io", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-websockets" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f591660438b3038dd04d16c938271c79e7e06260ad2ea2885a4861bfb238605d" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "futures-sink", + "http", + "httparse", + "rand 0.8.8", + "ring", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tokio-util", + "webpki-roots 0.26.11", +] + +[[package]] +name = "toml" +version = "1.2.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.19+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "tonic" +version = "0.14.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2cdfc673aabd30fe8fee92e65837b644c37c5d47f0f97ae6d5e0f1237d15e1b" +dependencies = [ + "async-trait", + "axum", + "base64 0.22.1", + "bytes", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-timeout", + "hyper-util", + "percent-encoding", + "pin-project", + "socket2", + "sync_wrapper", + "tokio", + "tokio-stream", + "tokio-util", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tonic-build" +version = "0.14.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac6d916d206ed7bdda1778ddff9bda43303789c258877e7bc22fb44ee5c984b4" +dependencies = [ + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tonic-prost" +version = "0.14.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eba464054e2226f182a34489b8b079bf4c6e3e7ab5fd7fc30e024f24aa92a484" +dependencies = [ + "bytes", + "prost", + "tonic", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "indexmap", + "pin-project-lite", + "slab", + "sync_wrapper", + "tokio", + "tokio-util", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-opentelemetry" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adbc64cba7137545b8044cb1fe9814f7aacf3c6b5f9b45be8bb5db538befdb26" +dependencies = [ + "js-sys", + "opentelemetry", + "tracing", + "tracing-core", + "tracing-subscriber", + "web-time", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "sharded-slab", + "thread_local", + "tracing-core", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "trybuild" +version = "1.0.121" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0cabaa10be1917331a313866bd94526343e03c77bcf69144b62b072ad35d47c" +dependencies = [ + "glob", + "serde", + "serde_derive", + "serde_json", + "target-tuple", + "termcolor", + "toml", +] + +[[package]] +name = "tryhard" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fe58ebd5edd976e0fe0f8a14d2a04b7c81ef153ea9a54eebc42e67c2c23b4e5" +dependencies = [ + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1 0.10.7", + "thiserror", +] + +[[package]] +name = "tungstenite" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e48ac77174b19c110a50ab2128b24215ac9cb40e0e12e093fb602d175c569d22" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.10.4", + "sha1 0.11.0", + "thiserror", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "ucd-trie" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f20bdbfc9915686faa18fb5bbe8b4552778505defbf9f12289beefbc44092a6" + +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "uuid" +version = "1.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "wasm-streams" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "434504846030952e6c0d1e0abf6cb4be16f56e129a9af54a4452d5a2a40f84b1" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.12", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "whoami" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c" +dependencies = [ + "libc", + "libredox", + "objc2-system-configuration", + "web-sys", +] + +[[package]] +name = "widestring" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "worker" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4057bce8ec66c80b7e270d884c312e2a4ff60eb997fd02936656106c06a964e5" +dependencies = [ + "async-trait", + "bytes", + "chrono", + "futures-channel", + "futures-util", + "http", + "http-body", + "js-sys", + "matchit 0.7.3", + "pin-project", + "serde", + "serde-wasm-bindgen", + "serde_json", + "serde_urlencoded", + "strum 0.28.0", + "tokio", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams 0.7.1", + "web-sys", + "worker-macros", + "worker-sys", +] + +[[package]] +name = "worker-macros" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3d7389670b55aab89760be149007aeff773cdad7b650d807f7fb556d04bb304" +dependencies = [ + "async-trait", + "proc-macro2", + "quote", + "strum 0.28.0", + "syn 3.0.10", + "wasm-bindgen", + "wasm-bindgen-macro-support", + "worker-sys", +] + +[[package]] +name = "worker-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a440092e7ae7c5feb5507fbdc6aee0cc241d132757c83e1729766a24cddff82" +dependencies = [ + "cfg-if", + "js-sys", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "x509-cert" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" +dependencies = [ + "const-oid 0.9.6", + "der", + "spki", +] + +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom 7.1.3", + "oid-registry", + "rusticata-macros", + "thiserror", + "time", +] + +[[package]] +name = "xxhash-rust" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40de123dbb523ebcc00d61ec01840ad192578afc378d859f3429caa38308fad5" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure 0.14.0", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure 0.14.0", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml index d187188c7..fd6415920 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] -members = ["distributed_macros", "distributed_cli"] -exclude = ["tests/e2e-ui", "tests/celld/worker", "tests/celld/relay-worker"] +members = ["tests/common", "distributed_macros", "distributed_cli", "distributed_game", "distributed_leaderboard", "distributed_game_macros", "tests/fixtures/renamed-dependency"] +exclude = ["tests/e2e-ui", "tests/celld/worker", "tests/celld/relay-worker", "tests/celld/alarm-worker", "tests/celld/fact-worker", "tests/celld/zone-worker", "tests/fixtures/wasm32-native-domain", "examples/game/server"] resolver = "2" [workspace.package] @@ -34,37 +34,62 @@ required-features = ["graphql", "sqlite"] [features] default = [] -application-runtime = [] -runtime = ["application-runtime"] -emitter = ["dep:event-emitter-rs"] +# Internal: a Tokio runtime is linked. Every Tokio-using feature implies it and +# the crate gates its Tokio-only code (outbox and consumer workers) on this one +# name. Not a public switch: enable the transport or store you need instead. +runtime-tokio = ["dep:tokio"] +# Portable gateway declarations, dispatch, whole-operation GraphQL selection +# and the delivery identity/freshness contracts; runtime adapters are separate. +gateway = ["dep:url", "dep:async-graphql-parser"] +# Native HTTP adapter remains independent of GraphQL and SQL. +gateway-native = ["gateway", "http", "reqwest/stream", "dep:hyper", "dep:hyper-util", "dep:tower", "tokio/io-util"] +# workers-rs ingress and delivery contracts, without native executors. +gateway-worker = ["gateway", "dep:worker", "dep:futures-channel"] +# Native GraphQL execution behind the gateway, including native delivery +# (snapshots, coalescing, live sharing; each still opt-in at runtime). +gateway-graphql-native = ["gateway-native", "graphql", "dep:tokio-tungstenite"] metrics = [] -http = ["dep:axum", "dep:reqwest", "dep:tokio"] -grpc = ["dep:tonic", "dep:tonic-prost", "dep:prost", "dep:tokio"] -postgres = ["dep:sqlx", "dep:tokio", "sqlx/postgres", "sqlx/migrate", "sqlx/runtime-tokio", "sqlx/json"] -sqlite = ["dep:sqlx", "dep:tokio", "sqlx/migrate", "sqlx/runtime-tokio", "sqlx/sqlite", "sqlx/json"] -nats = ["dep:async-nats", "dep:futures", "dep:tokio"] -rabbitmq = ["dep:lapin", "dep:futures", "dep:tokio"] -kafka = ["dep:rdkafka", "dep:tokio"] -workers-rs = ["dep:worker"] -otel = ["dep:opentelemetry", "dep:opentelemetry_sdk", "dep:tracing", "dep:tracing-opentelemetry"] -graphql = ["dep:async-graphql", "dep:async-graphql-axum", "dep:hmac", "dep:jsonwebtoken", "http", "axum?/ws"] +http = ["dep:axum", "dep:reqwest", "runtime-tokio"] +# Knative: `bus::KnativeBus`, `bus::knative_triggers` and the CloudEvents +# ingress `microsvc::cloud_events_router`. +knative = ["http"] +grpc = ["dep:tonic", "dep:tonic-prost", "dep:prost", "runtime-tokio"] +postgres = ["dep:sqlx", "runtime-tokio", "sqlx/postgres", "sqlx/migrate", "sqlx/runtime-tokio", "sqlx/json", "common/postgres"] +sqlite = ["dep:sqlx", "runtime-tokio", "sqlx/migrate", "sqlx/runtime-tokio", "sqlx/sqlite", "sqlx/json", "common/sqlite"] +nats = ["dep:async-nats", "dep:futures", "runtime-tokio"] +rabbitmq = ["dep:lapin", "dep:futures", "runtime-tokio"] +kafka = ["dep:rdkafka", "runtime-tokio"] +# `bus::RedisStreamPublisher`: the Redis Streams `MessagePublisher`. +redis-streams = ["dep:redis", "runtime-tokio"] +# Code that runs inside a celld Worker (wasm32 Durable Objects): the cell +# host's Durable Object storage and outbox, and the celld Queue publisher. +cloudflare-workers = ["dep:worker"] +otel = ["dep:opentelemetry", "dep:opentelemetry_sdk", "dep:tracing-opentelemetry"] +graphql = ["common/graphql", "dep:async-graphql", "dep:async-graphql-axum", "dep:futures-channel", "dep:hmac", "dep:jsonwebtoken", "dep:subtle", "futures-util/sink", "http", "axum?/ws"] [dependencies] async-nats = { version = "0.50", optional = true } async-trait = "0.1" async-graphql = { version = "7", optional = true } +async-graphql-parser = { version = "7", optional = true } +tokio-tungstenite = { version = "0.30", optional = true } async-graphql-axum = { version = "7", optional = true } axum = { version = "0.8", optional = true } +hyper = { version = "1", features = ["http1", "server"], optional = true } +hyper-util = { version = "0.1", features = ["tokio"], optional = true } +tower = { version = "0.5", features = ["util"], optional = true } base64 = "0.23.0" futures = { version = "0.3", optional = true } lapin = { version = "4", optional = true } rdkafka = { version = "0.39", features = ["cmake-build", "tokio"], optional = true } +redis = { version = "1.7.1", default-features = false, features = ["script", "streams", "tokio-comp", "connection-manager"], optional = true } reqwest = { version = "0.13", default-features = false, features = ["json", "rustls"], optional = true } jsonwebtoken = { version = "9", optional = true } bitcode = { version = "0.6.9", features = ["serde"] } -event-emitter-rs = { version = "0.1.4", optional = true } +futures-channel = { version = "0.3", features = ["sink"], optional = true } futures-util = { version = "0.3", default-features = false, features = ["alloc"] } hmac = { version = "0.12", optional = true } +subtle = { version = "2", optional = true } opentelemetry = { version = "0.32", default-features = false, features = ["trace"], optional = true } opentelemetry_sdk = { version = "0.32", default-features = false, features = ["trace"], optional = true } serde = { version = "1.0.210", features = ["derive"] } @@ -76,9 +101,10 @@ tonic = { version = "0.14", default-features = false, features = ["router", "tra tonic-prost = { version = "0.14", optional = true } prost = { version = "0.14", optional = true } tokio = { version = "1", features = ["rt-multi-thread", "net", "macros", "time", "sync"], optional = true } -tracing = { version = "0.1", optional = true } +tracing = "0.1" tracing-opentelemetry = { version = "0.33", default-features = false, optional = true } uuid = { version = "1", features = ["v7"] } +url = { version = "2", optional = true } worker = { version = "0.8", features = ["queue"], optional = true } [target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies] @@ -92,11 +118,16 @@ sha2 = "0.10" tonic-build = { version = "0.14", default-features = false, features = ["transport"] } [dev-dependencies] -axum = "0.8" +# Shared integration-test fixtures and conformance suites; `sqlite`, +# `postgres` and `graphql` forward to it. +common = { path = "tests/common" } +axum = { version = "0.8", features = ["ws"] } distributed_cli = { path = "distributed_cli" } tower = { version = "0.5", features = ["util"] } http-body-util = "0.1" -# OTLP export e2e (tests/otel_export): a real SDK pipeline pointed at a +# Names the level SQLx logs statements at (src/sqlx_repo/statement_count_tests.rs). +log = "0.4" +# OTLP export e2e (tests/observability/otel_export): a real SDK pipeline pointed at a # collector container, exercising the `otel` feature the way a service binary # would. Keep versions in lockstep with the optional `otel` feature deps. opentelemetry-otlp = { version = "0.32", default-features = false, features = ["trace", "http-proto", "reqwest-blocking-client"] } diff --git a/Makefile b/Makefile index 947bd294d..bc7a831fe 100644 --- a/Makefile +++ b/Makefile @@ -17,10 +17,23 @@ AMQP_URL ?= amqp://guest:guest@localhost:5672/%2f KAFKA_BROKERS ?= 127.0.0.1:9092 NATS_URL ?= nats://localhost:4222 +REDIS_URL ?= redis://localhost:6379 + +# Lib tests that write unscoped tables each get a database of their own, +# recreated on every run so the suite is re-runnable. +POSTGRES_ADMIN_URL ?= postgres://sourced:sourced@localhost:5432 +TEST_DATABASES = distributed_projection_protocol distributed_snapshots distributed_rebuild distributed_unique_key_test + +# Every service variable `test-local` provides. Naming them in +# DISTRIBUTED_REQUIRE_SERVICES makes a test that cannot reach its service +# fail instead of returning early (see tests/common/src/env.rs). +REQUIRED_SERVICES = DATABASE_URL,AMQP_URL,KAFKA_BROKERS,NATS_URL,REDIS_URL,DISTRIBUTED_TEST_POSTGRES_URL,DISTRIBUTED_SNAPSHOT_TEST_POSTGRES_URL,DISTRIBUTED_REBUILD_TEST_POSTGRES_URL,DISTRIBUTED_UNIQUE_KEY_TEST_POSTGRES_URL,DISTRIBUTED_ARCHIVE_TEST_NATS_URL + test: test-local .PHONY: test test-local test-cargo test-cli-lifecycle compose-up compose-down +## The whole workspace against real services. This is what CI runs. test-local: set -eu; \ if [ "$(KEEP_COMPOSE)" != "1" ]; then \ @@ -30,10 +43,21 @@ test-local: trap cleanup EXIT HUP INT TERM; \ fi; \ $(DOCKER_COMPOSE) up $(COMPOSE_UP_FLAGS); \ + for database in $(TEST_DATABASES); do \ + $(DOCKER_COMPOSE) exec -T postgres dropdb -U sourced --if-exists --force "$$database"; \ + $(DOCKER_COMPOSE) exec -T postgres createdb -U sourced "$$database"; \ + done; \ export DATABASE_URL="$(DATABASE_URL)"; \ export AMQP_URL="$(AMQP_URL)"; \ export KAFKA_BROKERS="$(KAFKA_BROKERS)"; \ export NATS_URL="$(NATS_URL)"; \ + export REDIS_URL="$(REDIS_URL)"; \ + export DISTRIBUTED_ARCHIVE_TEST_NATS_URL="$(NATS_URL)"; \ + export DISTRIBUTED_TEST_POSTGRES_URL="$(POSTGRES_ADMIN_URL)/distributed_projection_protocol"; \ + export DISTRIBUTED_SNAPSHOT_TEST_POSTGRES_URL="$(POSTGRES_ADMIN_URL)/distributed_snapshots"; \ + export DISTRIBUTED_REBUILD_TEST_POSTGRES_URL="$(POSTGRES_ADMIN_URL)/distributed_rebuild"; \ + export DISTRIBUTED_UNIQUE_KEY_TEST_POSTGRES_URL="$(POSTGRES_ADMIN_URL)/distributed_unique_key_test"; \ + export DISTRIBUTED_REQUIRE_SERVICES="$(REQUIRED_SERVICES)"; \ $(CARGO) test $(CARGO_TEST_ARGS) --all-targets; \ $(CARGO) test $(CARGO_TEST_ARGS) --doc @@ -55,4 +79,4 @@ compose-down: ## Read-only aggregate contract lifecycle check (never writes tracked files). contracts-check: - $(CARGO) run -p distributed_cli --quiet -- contracts check --root . --catalog contracts/catalog.json --output human + $(CARGO) run -p distributed_cli --quiet -- contracts check --root . --catalog distributed.contracts.json --output human diff --git a/README.md b/README.md index 1054981f6..25d353cff 100644 --- a/README.md +++ b/README.md @@ -199,12 +199,130 @@ mutation SaveTodo { } ``` -Handlers stay thin: most Todo commands are `portable_command!` — shard, -invoke one domain method, commit Eventual. `todo.create` keeps a `handle:` -escape hatch when the body needs extra checks. +#### Full-state projections and out-of-order events + +Broker delivery order is not necessarily aggregate commit order. For a read +model whose rows are complete snapshots owned by one aggregate stream, opt in +to source-version fencing: + +```rust,ignore +distributed::projection! { + pub const TODOS: ProjectionDescriptor = { + name: "project_todos", + version: 2, + epoch: "todos-source-snapshots-v1", + model: Todos, + source: aggregate_snapshot, + on { + events: [TodoCreatedDomainEvent, TodoCompletedDomainEvent], + mutation: SaveTodo, + input: { todo: body }, + }, + on { + events: [TodoPurgedDomainEvent], + mutation: DeleteTodo, + input: { todo_id: aggregate_id }, + }, + }; +} +``` + +The framework compares canonical `(aggregate_sequence, publication_ordinal)` +within the owning `(aggregate_type, aggregate_id)` stream. A late snapshot +cannot overwrite a newer row or resurrect a deleted one. Even deletion before +creation leaves a durable tombstone. A newer snapshot can recreate the row. +Source fences, physical rows, row revisions, broker checkpoints and causal +observations commit atomically in the memory, SQLite and PostgreSQL adapters. +A stale input confirms the current row revision without generating a fake row +update; a concurrent change makes that confirmation retry through the normal +projection conflict path. + +Use this only for complete replacement snapshots with stable row keys. Every +affected key must be owned by one aggregate stream; joins, counters, partial +patches and relationship side effects need their own ordering/fold semantics. +This mode rejects delta operations, expression partitions and direct placement. +Different aggregate streams cannot take over an existing fenced key. Matching +source versions with conflicting occurrence content fail closed. + +Migration `0005_projection_source_snapshots` persists the fence alongside each +record, including tombstones; compaction does not remove it. Enabling this on +an existing unversioned projection requires an explicit read-model rebuild +from retained canonical events. Merely changing the projection version or epoch +does not infer a source version for existing rows. The normal ordered-delivery +contract and transport identity checks still apply; this is not a replacement +for reliable broker delivery or an incremental-event reorder buffer. + +Custom program factories can use `ProjectionProgram::with_source_snapshots()`; +the policy is part of the canonical program identity. Browser optimism continues +to use the same mutation program, and authoritative confirmation uses committed +row revisions rather than comparing browser timestamps. + +#### Rebuilding existing snapshot projections + +Use explicit maintenance, not a startup fallback or republishing loop: + +```rust,ignore +// Stop producers, drain outboxes, stop consumers, and back up the read model. +// Reuse the same generated SurfaceProjector mounted by the application. +let rebuild = projector.begin_snapshot_rebuild(&repository).await?; +// Read history AFTER capturing the target inventory. Another authoritative +// archive can supply these canonical occurrences; rebuilding is bus-neutral. +let events = nats_bus.retained_domain_events().await?; +let plan = rebuild.from_complete_history(&events)?; +println!("{} records to rebuild", plan.record_count()); +plan.apply(&repository).await?; +``` + +Memory, SQLite and PostgreSQL commit complete rows/tombstones, source fences, +new record revisions and live-query changes atomically. A concurrent update, +insertion or deletion invalidates the captured inventory. Failure rolls back the +whole projection. Broker checkpoints, inbox receipts, command ledgers and prior +causal observations are preserved; maintenance does not claim a domain command +occurred. No domain handlers, external effects or queue sends run. + +The archive must cover every existing record and retain its stored source +occurrence, where present. Conflicting duplicate occurrences, missing aggregate +sequence prefixes and stale source heads fail closed. The caller must establish +history completeness: even a broker stream starting at sequence one may have +been created after its aggregates. The NATS reader verifies a stable, gap-free +retained stream without creating consumers or acknowledging messages, but cannot +prove that unpublished events or earlier deleted streams never existed. + +This first API is bounded offline maintenance for one active local, +unit-partition snapshot binding: at most 10,000 records and 100,000 occurrences / +64 MiB of canonical history. It intentionally rejects delta folds and histories +whose publication sequences have gaps. It does not migrate schemas/topologies, +perform online shadow swaps, or make several independent projections one +transaction. Keep services stopped if a multi-projection maintenance run fails; +capture fresh inventories and rerun before resuming them. + +Handlers stay thin. The shortest form is the command on the aggregate +method itself: `#[command]` inside the `#[sourced]` impl generates the +handler and the portable mount (see [Command contracts](#command-contracts)): ```rust,ignore -portable_command! { +#[command( + "todo.complete", + shard = todo_id, + load = required, + input = TodoCompleteInput, + outcome = Eventual, + payload = TodoStatusPayload::from_todo, + roles = ["user", "admin"], + field = "todos_complete", +)] +pub fn complete(&mut self, #[principal] owner_id: &str) -> Result<(), TodoError> { .. } +``` + +The Todo playground spells the same registration out with +`command!` — shard, invoke one domain method, commit Eventual. `load:` +is `required`, `or_create` or `create` (an id that already has a stream +is rejected); `guard:` adds a check on top of the roles; the payload +closure also receives the session principal. `handle:` remains the +escape hatch for a body that does more than one domain call. + +```rust,ignore +command! { name: "todo.complete", transition: domain_commands::Complete, aggregate: Todo, @@ -215,7 +333,7 @@ portable_command! { roles: ["user", "admin"], field: "todos_complete", invoke: |todo, _input, principal| todo.complete(principal), - payload: |todo| TodoStatusPayload::from_todo(&**todo), + payload: |todo, _principal| TodoStatusPayload::from_todo(&**todo), } ``` @@ -228,7 +346,7 @@ A module mounts one bounded context — commands, guards, projectors. A playground is one `Service`, one host, one runner that only reads env and calls `run`. You do not set a runtime role flag. -Todo commands are `portable_command!` declarations in `todo-domain`. This +Todo commands are `command!` declarations in `todo-domain`. This playground mounts them on a local Service. The sibling example [`tests/e2e-celld`](tests/e2e-celld) mounts the same declarations and wait-dispatches create, complete, and `chat.post` to a **cell** (one private @@ -260,8 +378,10 @@ Service::new() ``` HTTP `POST /{command}` is **off by default**. Browser writes use the -GraphQL command proxy. Call `.with_http_command_routes()` only for an -intentional non-GraphQL ingress. +GraphQL command proxy. For an intentional non-GraphQL ingress (a provider +webhook), expose that one command with `.with_http_command(command, edge)`: +its edge authenticates the request and returns what to dispatch. Call +`.with_http_command_routes()` only behind a trusted proxy. ### 08 · Browser replica @@ -370,6 +490,18 @@ that scope the client replica. --- +## Multiplayer games + +`distributed_game` adds a server-authoritative realtime engine on top of +this framework: zones that tick at a fixed rate, binary delta replication +with interest management, client prediction (`@hops-ops/distributed/game`), +outcomes saved as idempotent commands on cells without ever pausing the +game, and zones spread across servers with handoff, hibernation and live +content updates. Start with **[`distributed_game/README.md`](distributed_game/README.md)**; +eight runnable demos are in [`examples/game`](examples/game/README.md). + +--- + ## See it run ### e2e-ui playground (`tests/e2e-ui`) @@ -419,7 +551,7 @@ Start here in the code: | [`ui/src/lib/components/blob/SelectedBlobGame.graphql`](tests/e2e-ui/ui/src/lib/components/blob/SelectedBlobGame.graphql) | Reusable component island promoted to the nearest static route boundary; one route-param binding drives SSR and component reads. | | [`ui/src/routes/blob/[[gameId]]/+page.svelte`](tests/e2e-ui/ui/src/routes/blob/[[gameId]]/+page.svelte) | Arrow keys → `commands.blob.move`; board from `BlobGames.use()`. | | [`crates/service/src/modules/compose.rs`](tests/e2e-ui/crates/service/src/modules/compose.rs) | One `Service` lists modules. No `Runtime::role`. | -| [`crates/service/src/handlers/commands/blob_move.rs`](tests/e2e-ui/crates/service/src/handlers/commands/blob_move.rs) | `PreparedCommand>` — map/score written with the event. | +| [`crates/blob-domain/src/commands/move_dir.rs`](tests/e2e-ui/crates/blob-domain/src/commands/move_dir.rs) | `command!` returning `Atomic`: the map/score row commits with the event, and a WASM pure previews the move. | | [`crates/todo-domain/src/models/todo.rs`](tests/e2e-ui/crates/todo-domain/src/models/todo.rs) | Plain aggregate — no GraphQL in the domain. | | [`ui/src/auth.ts`](tests/e2e-ui/ui/src/auth.ts) | Auth.js + Zitadel scopes/groups → engine roles. | @@ -437,13 +569,13 @@ claim → role/session). Live against three local IdPs — not mocks only: | Provider | Compose + bootstrap | Live test | Gate | |---|---|---|---| -| **[Zitadel](tests/graphql_oidc_zitadel/)** (reference) | `./scripts/oidc-zitadel-up.sh` | `cargo test --test graphql_oidc_zitadel --features graphql,sqlite` | `ZITADEL_E2E=1` | -| **[Keycloak](tests/graphql_oidc_keycloak/)** | `./scripts/oidc-keycloak-up.sh` | `cargo test --test graphql_oidc_keycloak --features graphql,sqlite` | `KEYCLOAK_E2E=1` | -| **[Authentik](tests/graphql_oidc_authentik/)** | `./scripts/oidc-authentik-up.sh` | `cargo test --test graphql_oidc_authentik --features graphql,sqlite` | `AUTHENTIK_E2E=1` | +| **[Zitadel](tests/graphql/graphql_oidc_zitadel/)** (reference) | `./scripts/oidc-zitadel-up.sh` | `cargo test --test graphql --features graphql,sqlite graphql_oidc_zitadel::` | `ZITADEL_E2E=1` | +| **[Keycloak](tests/graphql/graphql_oidc_keycloak/)** | `./scripts/oidc-keycloak-up.sh` | `cargo test --test graphql --features graphql,sqlite graphql_oidc_keycloak::` | `KEYCLOAK_E2E=1` | +| **[Authentik](tests/graphql/graphql_oidc_authentik/)** | `./scripts/oidc-authentik-up.sh` | `cargo test --test graphql --features graphql,sqlite graphql_oidc_authentik::` | `AUTHENTIK_E2E=1` | -Shared **E1–E8** in [`tests/graphql_oidc_common/`](tests/graphql_oidc_common/). +Shared **E1–E8** in [`tests/common/src/oidc.rs`](tests/common/src/oidc.rs). Gated binaries skip cleanly when unset. Offline: -`cargo test --test graphql_identity --features graphql,sqlite`. +`cargo test --test graphql --features graphql,sqlite graphql_identity::`. e2e-ui boots **Zitadel** for the browser path; the three stacks prove the same `OidcBearer` edge is not vendor-locked. @@ -503,7 +635,7 @@ inherit it from member crates. Keep the root dependency feature-light, then enable service-specific features only in the service crates. Most application crates should depend on `distributed` only. The proc -macros (`#[sourced]`, `#[digest]`, `#[derive(ReadModel)]`, +macros (`#[sourced]`, `command!`, `#[derive(ReadModel)]`, `#[derive(Snapshot)]`) are re-exported from `distributed`; do not add `distributed_macros` directly unless you are working on the macro crate itself. The `distributed_cli` crate installs the `distributed` tooling @@ -521,8 +653,8 @@ network servers. | Feature | Default | Adds | |---|---:|---| -| `emitter` | No | In-process event emission and `#[enqueue]`. | -| `http` | No | Axum HTTP transport for `microsvc` + the Knative/CloudEvents ingress router. | +| `http` | No | Axum HTTP transport for `microsvc`. | +| `knative` | No | Knative: `bus::KnativeBus`, `bus::knative_triggers` and the CloudEvents ingress `microsvc::cloud_events_router` (implies `http`). | | `grpc` | No | Tonic gRPC transport for `microsvc`. | | `graphql` | No | GraphQL query service over read models (pulls in `http` + WebSocket). Pair with `sqlite` and/or `postgres` for a dialect. | | `postgres` | No | `PostgresRepository` and the Postgres outbox/transport (`PostgresBus`). | @@ -530,6 +662,19 @@ network servers. | `nats` | No | `NatsBus` (NATS JetStream source/publisher). | | `rabbitmq` | No | `RabbitBus` (RabbitMQ source/publisher). | | `kafka` | No | `KafkaBus` (Kafka source/publisher). | +| `redis-streams` | No | `bus::RedisStreamPublisher` (Redis Streams `XADD`, id dedupe). Sorted-set leaderboards live in the `distributed_leaderboard` crate (its own `redis` feature). | +| `metrics` | No | `distributed::metrics`: framework counters and gauges with Prometheus text exposition (no SDK dependency); with `http`, a scrape handler. Bus receive loops record into it. | +| `otel` | No | OpenTelemetry tracing spans for bus receive loops and `microsvc` dispatch/handlers (`opentelemetry`, `tracing-opentelemetry`). | +| `cloudflare-workers` | No | Code that runs inside a celld Worker (`wasm32` Durable Objects, Cloudflare `worker` crate): the cell host's Durable Object storage and outbox, and the celld Queue publisher/relay (`bus::CelldQueue*`). | +| `gateway` | No | `distributed::gateway`: portable gateway declarations (bindings, routes, dispatch), whole-operation GraphQL selection (parser only) and the delivery identity/freshness contracts (snapshots, coalescing, live sharing). Starts no listeners. | +| `gateway-native` | No | Native HTTP gateway adapter (hyper/tower), independent of GraphQL and SQL. | +| `gateway-graphql-native` | No | Native GraphQL execution behind the gateway, including WebSocket `@live` and native delivery (snapshots, coalescing, live sharing; each opt-in at runtime). Implies `gateway-native`, `graphql`. | +| `gateway-worker` | No | workers-rs gateway ingress and delivery contracts, without native executors. | + +`runtime-tokio` is internal: every Tokio-using feature above (`http`, `grpc`, +`postgres`, `sqlite`, `nats`, `rabbitmq`, `kafka`, `redis-streams`) implies it, and the crate gates its Tokio-only code +(the outbox drain and consumer workers) on it. Enable the transport or store you +need rather than `runtime-tokio` itself. > The `InMemoryBus`, `PostgresBus`, and `SqliteBus` need no separate broker > feature. SQL-backed bus support comes from the matching `postgres` or `sqlite` @@ -551,16 +696,51 @@ network servers. - **ReadModel**: Query-optimized relational projection state for UI/API reads. Read models may be updated atomically with a command or eventually from published messages. - **GraphqlEngine**: Deny-by-default GraphQL surface over registered read-model tables: role-scoped columns/row filters, optional command mutations, live subscriptions via `ChangeHub`, and identity modes (`OidcBearer`, `TrustedProxy`, `Hybrid`, `DevHeaders`). - **Bus / BusConsumer**: The service bus facade — `send`/`publish` (produce) and `listen`/`subscribe` (consume), implemented by a per-transport `*Bus` type. -- **microsvc::Service**: Convention-based async command/event handler framework with pluggable transports (HTTP, gRPC, bus, GraphQL mutations, direct dispatch). +- **microsvc::Service**: Convention-based async command/event handler framework with pluggable transports (HTTP, gRPC, bus, GraphQL mutations, in-process dispatch). ## Terminology And CQRS Boundaries -Event sourcing is the model-level persistence strategy: aggregates record replayable `EventRecord`s when command methods such as `#[event]` (within `#[sourced]`) or `#[digest]` methods succeed. Those records are the write-side history used to hydrate the aggregate. +Event sourcing is the model-level persistence strategy: aggregates record replayable `EventRecord`s when command methods such as `#[event]` (within `#[sourced]`) succeed. Those records are the write-side history used to hydrate the aggregate. CQRS is the architectural split between write-side aggregates and query-side read models. Repositories load aggregate event streams by ID for command handling; production business queries should read from `ReadModel` projections shaped for that query. Published messages are a separate boundary. An aggregate event record is not automatically a domain event. When other services, projections, or transports need a fact or command, create an `OutboxMessage` and commit it with the aggregate. The outbox payload can represent a domain event, integration event, command, or any other transport message. +The outbox stores delivery work, not publication history. Successful delivery +deletes the row under its active lease. Failed or ambiguous sends retain the row +for retry or inspection. A crash after transport acceptance but before deletion +can deliver the same event ID again; consumers must remain idempotent. Event +history belongs in the event store, and command retry results belong in command +receipts. Neither depends on retaining delivered outbox rows. + +Commands dispatched to another aggregate cell use the same command ledger, but +with an explicit external dispatch binding. The binding records the logical +route kind and shard alongside the command identity; it is immutable for that +reservation and survives lease reclaim and terminal replay. External completion +updates only the ledger after the returned attempt fence and binding match. It +does not append local events, write the outbox, or treat the cell's commit as +proof that an asynchronous read-model projection has completed. A local causal +commit cannot complete an externally bound reservation, and an external +completion cannot complete a local reservation. Retained cell-only receipts +without a gateway binding remain explicit unknowns until a matching gateway +reservation and trusted completion protocol can be established; they are never +retrofitted into a different route or silently replayed. + +The celld command host reserves that gateway intent before making the cell +request. The reservation's causation ID and logical route binding must be +echoed by the trusted cell receipt; a changed command ID, input, causation, or +route is rejected before it can complete the gateway row. A terminal cell +receipt is durably recorded in the gateway ledger before the response is +returned. Status checks current authorization and re-evaluates the durable +receipt's projection evidence, so an in-memory completed-status cache is never +the source of truth. An ambiguous transport result remains retryable against +the same reservation and cell; it does not invoke the local domain handler or +re-publish the cell's events and outbox. + +In v5, `OutboxStore::complete` and `complete_many` remove delivered rows instead +of retaining `Published` records. Repeating settlement of a removed row returns +`NotFound`; stale claims on existing rows still return `InvalidState`. + The existing names and serialized fields such as `EventRecord::event_name` remain part of the compatibility contract. Terminology cleanup should clarify usage without renaming stored event records unless a migration path is explicitly designed. ## Pluggable by Default @@ -574,13 +754,13 @@ Every infrastructure concern in `distributed` follows the same pattern: a **trai | Read model rows | `ReadModelWritePlanStore` + `RelationalReadModelQueryStore` | `InMemoryReadModelStore` | Postgres, SQLite | | Snapshot store | `SnapshotStore` | `InMemorySnapshotStore` | Postgres, SQLite, … | | Outbox publishing | `OutboxStore` + async `MessagePublisher` | `InMemoryRepository` outbox store (dev/test) | Any `MessagePublisher` (e.g. `BusPublisher` over a real `Bus`) | -| Locking | `Lock` + `LockManager` | `InMemoryLockManager` | `PostgresLockManager`, `SqliteLockManager` (durable leases), Redis, … | +| Locking | `Lock` + `LockManager` | `InMemoryLockManager` | `PostgresLockManager`, `SqliteLockManager` (durable leases); implement the traits for anything else | All in-memory defaults are `Clone` and `Send + Sync`, so they work in single-task tests and multi-task servers alike. When you're ready for production, implement the trait for your infrastructure and plug it in — handler code does not change. ## The `#[sourced]` Macro -The `#[sourced]` attribute macro is the recommended way to define event-sourced aggregates. Place it on an impl block and annotate command methods with lowercase, past-tense aggregate event names such as `#[event("initialized")]`. It replaces both `#[digest]` and `aggregate!()`, and auto-generates a typed event enum plus the `Aggregate` impl. +The `#[sourced]` attribute macro is the recommended way to define event-sourced aggregates. Place it on an impl block and annotate command methods with lowercase, past-tense aggregate event names such as `#[event("initialized")]`. It generates a typed event enum plus the `Aggregate` impl. Event methods are rewritten to return `SourcedResult`, even when the source method omits an explicit return type. Call them with `?` in application code so serialization and event-recording failures are propagated. @@ -634,6 +814,96 @@ impl TryFrom<&EventRecord> for TodoEvent { /* ... */ } impl Aggregate for Todo { /* ... */ } ``` +### Flat events and optimistic updates + +With `domain = event`, recorder parameters are the flat outward event body: + +```rust,ignore +#[sourced(entity, aggregate_type = "review")] +impl Review { + pub fn approve(&mut self, id: String) -> distributed::SourcedResult { + // Validate the decision here, before recording it. + self.record_status(id, "approved".into())?; + Ok(()) + } + + #[event("review.status_recorded", version = 1, domain = event)] + fn record_status(&mut self, id: String, status: String) { + self.entity.set_id(id); + self.status = status; + } +} +``` + +Optimistic projections need to know what a command will leave behind before +the event exists. That is declared, never read out of a method body. A state +recorder (`domain`) lists the values it always sets, in the field grammar of +`state_preview!`: + +```rust,ignore +#[event("todo.completed", version = 1, domain, known(status: "completed"))] +fn completed(&mut self) { self.status = TodoStatus::Completed; } +``` + +A flat event (`domain = event`) declares the body fields it always carries +the same way. When each outcome is its own event, the constant belongs to the +event, and every command that records it gets the preview: + +```rust,ignore +#[event("review.archived", version = 1, domain = event, known(status: "archived"))] +fn record_archived(&mut self, id: String, status: String) { /* .. */ } +``` + +A flat event shared by several outcomes carries no single constant; its +commands declare their preview on the registration instead, with +`.applies(event_preview! { ReviewStatusRecorded => ReviewStatusRecorded { +id: input.id, status: "approved", ..unknown } })`. All of these are checked +against the body's fields when the command is registered. Neither predicts authorization +or guarantees that the event will occur. + +Public transitions can delegate to shared decision helpers in the same +`#[sourced]` impl. For example, `leave` and an owner-authorized `remove_member` +can both call a private `self.remove_member_decision(...)`. Each gets its own +`domain_commands::Leave` / `domain_commands::RemoveMember` witness containing +the outward events reachable through those helpers. Discovery follows static +`self.method(...)` calls, deduplicates events, and terminates on recursive helper +graphs. It does not follow foreign receivers or helpers outside the impl, and +does not propagate argument values through helpers. Custom +`domain = with(Body, adapter)` events use the declared body contract, including +qualified or relative type paths. + +For an event whose body contains the authenticated principal, bind that one +field using the existing command API: + +```rust,ignore +command_transition::>("group.leave") + .authenticated_user_field::( + "user_id", + ) +``` + +The second type is the exact serialized body. Use the flat event itself for +`domain = event` or `#[derive(DomainEvent)]`; state-capture events continue to +use their `DomainState` type. The equivalent `command!` entry is: + +```rust,ignore +authenticated_user_field: ( + GroupMemberRemovedDomainEvent, + GroupMemberRemovedDomainEvent, + "user_id" +), +``` + +This gives a membership-delete projection the trusted `x-user-id` key without +adding a caller-controlled user ID to the command input. The framework checks +the exact event/body descriptor and serialized string field, including Serde +renames. The handler must still obtain the principal from its authenticated +session and enforce membership rules; this declaration only supplies the +generated preview's provenance. + +See [the executable contract tests](tests/core/sourced/flat_preview.rs), including +the generated delete-projection client, helper replay and conflicting/dynamic-value cases. + ### Durable Stream Identity `Aggregate::aggregate_type()` provides the type component of a persistence stream's identity (the pair `(aggregate_type, aggregate_id)`). The default uses Rust's type name for development convenience, but **production persistence should set an explicit, stable durable name**: @@ -713,107 +983,15 @@ impl MyAggregate { } ``` -### With `enqueue` for Choreography +### Replay and event versions -Add `enqueue` to `#[sourced]` to automatically queue events for in-process emission alongside digest. Every `#[event]` method both records to the entity stream and enqueues for emission: - -```rust,ignore -use distributed::{sourced, Entity}; -use distributed::emitter::EntityEmitter; - -#[derive(Default)] -struct Order { - entity: Entity, - emitter: EntityEmitter, - status: String, -} - -#[sourced(entity, enqueue)] -impl Order { - #[event("initialized")] - fn create(&mut self, order_id: String, customer: String) { - self.entity.set_id(&order_id); - self.status = "created".into(); - } - - #[event("shipped", when = self.status == "created")] - fn ship(&mut self) { - self.status = "shipped".into(); - } -} -``` - -**Custom emitter field** — when your emitter field isn't named `emitter`: - -```rust,ignore -#[sourced(entity, enqueue(my_emitter))] -impl Notifier { - #[event("sent")] - fn send(&mut self, id: String, message: String) { - self.entity.set_id(&id); - self.message = message; - } -} -``` - -## The `#[digest]` Macro and `aggregate!()` Macro - -The `#[digest]` and `aggregate!()` macros are the lower-level building blocks that `#[sourced]` replaces. They're still fully supported and useful when you want more granular control. Like `#[event]` methods, `#[digest]` methods become fallible and should be called with `?`. - -### The `#[digest]` Macro - -```rust,ignore -// Basic — captures function parameters -#[digest("initialized")] -fn initialize(&mut self, id: String, user_id: String, task: String) { - self.entity.set_id(&id); - self.user_id = user_id; - self.task = task; -} - -// Guard conditions — only emit when the condition is true -#[digest("completed", when = !self.completed)] -fn complete(&mut self) { - self.completed = true; -} - -// Versioned events -#[digest("initialized", version = 2)] -fn initialize(&mut self, id: String, task: String, priority: u8) { /* ... */ } - -// Custom entity field -#[digest(my_entity, "initialized")] -fn create(&mut self, name: String) { /* uses self.my_entity */ } -``` - -### The `aggregate!` Macro - -Generates the `Aggregate` trait implementation with replay logic: - -```rust,ignore -aggregate!(Todo, entity, aggregate_type = "todo" { - "initialized"(id, user_id, task) => initialize, - "completed"() => complete(), -}); -``` - -With [upcasters](#event-upcasting--versioning) for event schema evolution: - -```rust,ignore -type InitV1 = (String, String); -type InitV2 = (String, String, u8); - -fn upcast_initialized_v1_v2((id, task): InitV1) -> InitV2 { - (id, task, 0) -} - -aggregate!(Todo, entity { - "initialized"(id, task, priority) => initialize, - "completed"() => complete(), -} upcasters [ - ("initialized", 1 => 2, InitV1 => InitV2, upcast_initialized_v1_v2), -]); -``` +Replay requires each event's schema version to match its registered handler +after upcasting. `#[sourced]` reads this version from +`#[event(..., version = N)]`. Omitted versions default to 1. +Older events need an explicit upcaster chain to the registered version; future +versions are rejected. Matching payload layouts do not bypass this check. +The check runs before payload decoding or handler invocation, including when +loading only the event tail after a snapshot in a native repository or cell. ## Event Metadata @@ -821,7 +999,7 @@ Metadata lets you attach cross-cutting context — correlation IDs, causation ID ### Setting Metadata on an Entity -Set metadata on the entity before calling command methods. Every event produced by `#[event]` or `#[digest]` automatically inherits it: +Set metadata on the entity before calling command methods. Every event produced by `#[event]` automatically inherits it: ```rust,ignore let mut todo = Todo::default(); @@ -856,7 +1034,7 @@ The metadata flows through the full chain: ```text Entity.set_correlation_id("req-123") - → #[event] / #[digest] → EventRecord.metadata + → #[event] → EventRecord.metadata → encode_for_entity → OutboxMessage.metadata → OutboxDispatcher → transport Message.metadata → subscriber receives the message with correlation_id() == "req-123" @@ -877,77 +1055,9 @@ message.correlation_id() message.meta("trace_id") ``` -## In-Process Event Choreography (requires `emitter` feature) - -The `emitter` feature adds in-process event-driven choreography — queue local events during commands and emit them after commit for reactive workflows within a single process. - -### With `#[sourced(entity, enqueue)]` - -Every `#[event]` method automatically records to the entity stream (for replay) and enqueues for in-process emission: - -```rust,ignore -use serde::{Deserialize, Serialize}; -use distributed::{sourced, Entity}; -use distributed::emitter::EntityEmitter; - -#[derive(Default, Serialize, Deserialize)] -struct OrderSaga { - entity: Entity, - #[serde(skip, default)] - emitter: EntityEmitter, - order_id: String, - status: String, -} - -#[sourced(entity, enqueue)] -impl OrderSaga { - #[event("started")] - fn start(&mut self, order_id: String) { - self.entity.set_id(&order_id); - self.order_id = order_id; - self.status = "started".into(); - } - - #[event("completed", when = self.status == "started")] - fn complete_step(&mut self) { - self.status = "completed".into(); - } -} -``` - -### Emitting After Commit - -Queued events are held until you explicitly emit them after a successful commit: - -```rust,ignore -let mut saga = OrderSaga::default(); -saga.start("order-1".into())?; - -// Commit the aggregate... -repo.commit(&mut saga).await?; - -// Then emit queued events to registered listeners -saga.emitter.emit_queued(); -``` - -### Registering Listeners - -```rust,ignore -let shared_state = Arc::new(Mutex::new(Vec::new())); -let state = Arc::clone(&shared_state); - -saga.emitter.on("started", move |payload: String| { - if let Ok(mut events) = state.lock() { - events.push(payload); - } -}); -``` - -This pattern is useful for reactive workflows within the same process. For cross-service messaging, use the [Outbox Pattern](#outbox-pattern) and [Service Bus](#service-bus). - ## Queued Repository -Per-entity async locking for serialized workflows. `get` acquires the lock, `commit` releases it: +Per-entity async locking for serialized workflows. `get` waits for the lock and returns an aggregate that owns it. `commit` releases it, and so does dropping the aggregate, so an early return cannot leak a lock: ```rust,ignore use distributed::{AggregateBuilder, InMemoryRepository, Queueable, RepositoryError}; @@ -961,7 +1071,7 @@ let Some(mut todo) = repo.get("todo-1").await? else { repo.commit(&mut todo).await?; // unlocks // Or release without changes: -repo.abort(&todo).await?; +drop(todo); // Read without locking: let _ = repo.peek("todo-1").await?; @@ -1020,7 +1130,7 @@ the durable transport (`PostgresBus`). Streams are keyed by full **stream identity** `(aggregate_type, aggregate_id)`, not bare IDs. Prefer an explicit durable `aggregate_type` in production -(`impl_aggregate!(..., aggregate_type = "...")` or the sourced/aggregate macros). +(`#[sourced(entity, aggregate_type = "...")]`). | Trait | Role | | --- | --- | @@ -1065,18 +1175,68 @@ let message = OutboxMessage::encode_for_entity( )?; ``` +### Facts derived by event handlers + +An event handler may verify an external result without making another aggregate +decision—for example, extracting document metadata after an upload. Derive a +typed fact from the incoming canonical occurrence: + +```rust,ignore +#[derive(serde::Serialize, distributed::DomainEvent)] +#[domain_event(name = "document.indexed", version = 1)] +struct DocumentIndexed { + document_id: String, + word_count: u64, +} + +let indexed = source.derive( + "document-indexer", + "metadata-v1", + &DocumentIndexed { document_id, word_count }, +)?; +``` + +The same source, producer, output key and body produce identical canonical bytes +and an identical event ID. Different outputs or changed bodies have different +IDs. `indexed.derivation()` identifies the immediate source and producer; the +aggregate fields retain the original transition's provenance, not an invented +commit. Timestamp, causation, correlation and trace metadata come from the source. +Ordinary typed projections can consume the derived fact. Aggregate-snapshot +projections reject it because it does not establish a new aggregate version. + +Publish the canonical bytes using the existing bus API and `indexed.id()` as +the message ID. Propagate its causal metadata. Acknowledge the incoming delivery +only after every output publish succeeds; a failure retries the source and may +republish an accepted prefix with the same IDs. This is at-least-once delivery, +not an atomic external effect plus publish. Aggregate decisions still use a +transactional outbox. Bound external reads and make effects idempotent before +using this pattern. + +### Scheduled messages, sagas and fenced leases + +`OutboxMessage::deliver_at(at)` turns an outbox row into a durable timer that +no claim path delivers before `at`. Cross-cell workflows use the event-sourced +`Saga` process manager (`distributed::saga`). Single-owner work uses TTL +leases with monotonic fencing tokens (`distributed::lease`). See +[coordination primitives](docs/coordination-primitives.md). + ### Publishing the Outbox How a committed row reaches the bus depends on whether a bus is attached to the service: -- **Bus attached (`service.with_bus(bus)`)** — `repo.outbox(msg).commit(agg)` - claims the row in the commit transaction (born `InFlight` under a short lease) - and publishes it **immediately** after commit. A crash before the publish, or a - publish failure, leaves the row claimed under that lease; when the lease expires - the polling worker takes it. +- **Bus attached (`service.with_bus(bus)`)** — the row is committed `pending` + and its id is handed to a bounded background worker, which claims it, + publishes it and deletes it. The commit does not wait for the broker. A crash + or a full mailbox leaves the row pending for the polling worker. - **No bus** — the row is committed `pending` and a worker publishes it. +A publish that fails is retried with a growing delay (250 ms doubling to one +minute). A retryable failure, such as the broker being down, never marks a row +`failed`; only a permanent failure does, once the row has been attempted +`max_attempts` times. `OutboxStore::requeue_failed(id)` puts a failed row back +in the queue. + The polling worker is the durable backstop in both cases. It is the same `OutboxDispatcher` primitive composed with your runtime's timer — run it in the service process or as a separate worker, against the same outbox store: @@ -1127,8 +1287,8 @@ let service = Arc::new(build_service().named("order-api")); let bus = InMemoryBus::new(); bus.send("place.bet", payload).await?; // point-to-point command (1:1) bus.publish("seat.reserved", payload).await?; // fan-out event (1:N) -bus.listen(service.clone(), RunOptions::idempotent()).await?; // competing -bus.subscribe(service.clone(), RunOptions::idempotent()).await?; // fan-out +bus.listen(service.clone(), RunOptions::default()).await?; // competing +bus.subscribe(service.clone(), RunOptions::default()).await?; // fan-out // Production: swap the one constructor line — send/listen/publish/subscribe // and the handlers are unchanged. A named Service supplies the consumer group. @@ -1169,7 +1329,7 @@ are rejected before broker topology is created. | `NatsBus` | `nats` | shared durable `{group}_cmd` on the stream | durable `{group}_evt` per group | | `RabbitBus` | `rabbitmq` | default exchange → durable queue `{ns}.cmd.{name}` | topic exchange → queue `{ns}.evt.{group}` per group | | `KafkaBus` | `kafka` | shared consumer group `{ns}.{group}.cmd` | consumer group per service `{ns}.{group}.evt` | -| `KnativeBus` | `http` | POST CloudEvent → `{target}-commands` broker ingress | POST → `{source}-events` broker; consume via generated Triggers | +| `KnativeBus` | `knative` | POST CloudEvent → `{target}-commands` broker ingress | POST → `{source}-events` broker; consume via generated Triggers | `SqliteBus` uses the same single-database pattern scaled down to SQLite: `bus_queue` is claimed with a conditional `UPDATE ... RETURNING` lease because @@ -1180,25 +1340,59 @@ single-node deployments, not as a high-throughput broker replacement. `KnativeBus` implements only `Bus` (produce → broker-ingress POST). It has no in-process consume loop: `KnativeBus::manifests(&plan, &subscriptions)` renders the role-based `Broker` + per-name `Trigger` YAML, and the service mounts -`cloud_events_router` so those Triggers reach `dispatch_message`. +`cloud_events_router` so those Triggers reach `dispatch_message`. A command a +Trigger delivers runs as the transport identity, so its declaration lists +`TRANSPORT_ROLE`, and the CloudEvent id is the id its ledger deduplicates on. -### Idempotency and Failure Policy +### Running, retries and dead letters -`RunOptions::idempotent()` enables idempotent dispatch by default. `RunOptions` also -carries a `FailurePolicy` controlling what happens to a **permanent** handler -failure — `Retry`, `DeadLetter`, `Park`, `LogAndAck`, or `Stop`: +`RunOptions` decides how a consumer run behaves. The same options mean the +same thing on every transport, because the runner applies them above the +adapter. ```rust,ignore -use distributed::bus::{FailurePolicy, RunOptions}; +use distributed::bus::{FailurePolicy, RunOptions, Shutdown}; +let shutdown = Shutdown::new(); bus.listen( service.clone(), - RunOptions::idempotent().with_failure_policy(FailurePolicy::Stop), + RunOptions::until_shutdown(shutdown.clone()) + .with_max_attempts(8) + .with_failure_policy(FailurePolicy::DeadLetter), ).await?; -``` - -Retryable failures (e.g. transient `NotFound`) are nacked for redelivery; the runner -never silently acks a handler error. +// elsewhere: shutdown.trigger(); +``` + +- **When a run ends.** `RunOptions::default()` and `until_shutdown(signal)` + keep consuming while the source is quiet. The run returns `Ok(())` only when + the signal is triggered, after settling the delivery in hand. + `RunOptions::until_idle()` returns as soon as nothing is available; it is for + tests and one-shot drains. +- **Retries.** A retryable failure (for example a transient `NotFound`) is + redelivered after a backoff that doubles with each delivery (50 ms up to 5 s + by default; `with_backoff`). `with_max_attempts(n)` dead-letters a message + that still fails on its `n`th delivery. Without it retries are unlimited. +- **Permanent failures** follow the `FailurePolicy`: `DeadLetter` (default), + `Retry`, `LogAndAck`, or `Stop`. A deterministic, durably recorded rejection + is a permanent error, not a retryable one. +- **Dead letters.** The runner stores `{message, reason, consumer, attempts}` + and only then acknowledges the delivery. A bus stores dead letters by + publishing a `distributed.dead_letter` event to itself; `with_dead_letters` + names another `DeadLetterSink`. If the dead letter cannot be stored the + delivery is handed back and the run ends with an error. + +RabbitMQ reports only whether a delivery is a redelivery, so `max_attempts` +above 2 never triggers there. Positional sources (Kafka, the SQL log) cannot +deliver a later message first: they hold their position for the backoff. + +The [bus contract](docs/bus-contract.md) lists what every transport promises +and where they differ. One conformance suite runs it against every bus. + +A service can place independent route bundles in named delivery lanes +(`Service::lane(name, routes)`). Each lane keeps broker order and runs +concurrently with the others, and a delivery is settled only after every lane +finished it. See [consumer delivery lanes](docs/consumer-delivery-lanes.md) for +the contract and when a route may leave the default lane. ### Transport boundaries (producer vs consumer) @@ -1209,15 +1403,15 @@ in `bus` (no concrete broker dependency). | Type | Purpose | | --- | --- | | `TransportError` / `TransportErrorKind` | Retryable vs permanent — drives redelivery vs failure policy | -| `FailurePolicy` / `FailureAction` | Permanent failure: `Retry`, `DeadLetter`, `Park`, `LogAndAck`, `Stop` | -| `RunOptions` / `ConsumerDeliveryMode` | Idempotent dispatch by default; optional inbox hook | -| `TransportCapabilities` | Per-transport durability, confirms, retry ownership, ack kind | +| `FailurePolicy` / `FailureAction` | Permanent failure: `Retry`, `DeadLetter`, `LogAndAck`, `Stop` | +| `RunOptions` | When a run ends, retry backoff, max attempts, dead-letter sink | +| `DeadLetterSink` | Where a given-up message is stored before it is acknowledged | | `MessageSource` + `run_source` | Pull loop: dispatch then settle only after the handler finishes | | `MessagePublisher` + `OutboxDispatcher` | Publish threshold for outbox completion; claim → publish → complete | **Two confirmation thresholds** (do not collapse them): -1. **Producer publish** — when an outbox row may be marked published (SQL commit, +1. **Producer publish** — when an outbox row may be deleted (SQL commit, broker confirm/ack, Knative 2xx, in-memory accept). Unknown outcomes stay retryable. 2. **Consumer ack** — only after the handler (and optional inbox receipt) committed. Never silently ack a handler error. @@ -1225,126 +1419,238 @@ in `bus` (no concrete broker dependency). ```rust,ignore use distributed::bus::{run_source, RunOptions}; -// Low-level receive loop (facade buses wrap this) -run_source(service, source, RunOptions::idempotent()).await?; +// Low-level receive loop (facade buses wrap this). A bare source has no +// dead-letter sink; name one or choose another failure policy. +run_source(service, source, RunOptions::default().with_dead_letters(sink)).await?; ``` +## Command contracts + +**Commands on the aggregate.** Most commands are one aggregate method: +take the actor from the session, load (or create) the aggregate, call the +method, reject on its error, commit with a payload. Write the method and +mark it `#[command]` inside the `#[sourced]` impl; the macro generates the +handler and the portable mount (`pub struct RecordKill`, mounted with +`routes.mount(RecordKill)` or `AggregateCell::mount(RecordKill)`): + +```rust,ignore +#[sourced(entity, aggregate_type = "Crawler", events = "CrawlerEvent", domain_state = CrawlerState)] +impl Crawler { + #[command("crawler.record_kill", shard = principal, load = or_create, outcome = succeeded)] + pub fn record_kill( + &mut self, + #[principal] principal: &str, + input: RecordKillInput, + ) -> Result { + let xp = xp_for_tier(input.tier).ok_or("unknown tier")?; + self.mob_killed(principal.into(), input.name, input.mob, input.tier, xp) + .map_err(|e| e.to_string())?; + // Receipt helper: the recorded event's stream position and time. + let recorded = self.entity.last_recorded().ok_or("nothing recorded")?; + Ok(KillReceipt { sequence: recorded.sequence, at_ms: recorded.unix_ms(), .. }) + } + + #[event("crawler.mob_killed", version = 1, domain)] + fn mob_killed(&mut self, id: String, name: String, mob: String, tier: u8, xp: u32) { .. } +} +``` + +- **Principal.** Exactly one parameter is `#[principal]` (`&str` or + `String`); the generated handler fills it from the verified session + (`x-user-id`, else `Unauthorized`), never from the input. It is + mandatory, and an input whose field (Rust or serialized name) is named + like it does not compile. +- **Input.** The other parameter is the `CommandInput` type; or, with + `input = Type`, the other parameters are that input's fields by name + (`&str` parameters borrow), so a domain method keeps plain arguments. +- **`shard`** is an input field (also exposed as `RecordKill::shard`) or + the principal parameter; **`load`** is `required` (`NotFound` when + missing), `or_create` or `create`. +- **`outcome`** is `succeeded` / `eventual` (the method's `Ok` value is + the payload) or `Succeeded

` / `Eventual

` with `payload = f` + (`fn(&Aggregate) -> P`). The method's error (`Display`) becomes + `Rejected`. Captured domain events are always published with the commit. +- Optional: `roles = ["player"]`, `guard = f`, `field = "graphql_field"`, + `transition = path` (the emitted-event witness; by default the + `domain_commands::*` type `#[sourced]` derives for the method), + `mount = Name` (the struct name, default from the command name's last + segment). + +The generated registration is exactly the hand-written one +(`command_transition::(name)` + `field_name`, +`roles`, `guarded`/`handle`): the command specs, GraphQL SDL and client +manifest are identical (`tests/core/aggregate_command`). For unusual bodies write +the handler and register it with `command! { .., handle: f }` or +the builder below. + +**Contracts.** Command semantics live in `distributed::command`, independently of the query +transport. Use `CommandInput` and `CommandOutput` to describe Serde input/output +shapes, and `command::{typed_command, Succeeded, Eventual, Atomic, PreparedCommand}` +to declare and prepare commands. The GraphQL adapter derives its surface from +those contracts; GraphQL naming restrictions are checked when exposing them. + +```rust +# use distributed::command; +use distributed::{CommandInput, CommandOutput}; +use distributed::command::{typed_command, Succeeded}; +use serde::{Deserialize, Serialize}; + +#[derive(Deserialize, CommandInput)] +struct RenameInput { id: String, title: String } + +#[derive(Serialize, CommandOutput)] +struct RenameOutput { id: String } + +# fn main() { +let declaration = typed_command::>("todo.rename"); +# } +``` + +This is a breaking Rust API change. Replace `GraphqlInput`/`GraphqlOutput` +with `CommandInput`/`CommandOutput` throughout the DTO's nested types and +move command imports from `distributed::graphql` to `distributed::command`. +Manual metadata implementations now use `CommandInputType`/`CommandOutputType`, +`command_type()`, and `CommandTypeDef`/`CommandTypeField`. The old GraphQL +command re-exports, metadata types, and derives have been removed. + +GraphQL remains the application's UI gateway: it exposes the command contract +alongside queries and subscriptions. Command handlers describe their data and +consistency through the core API, independently of where that gateway runs. + +`Atomic` continues to obtain its response shape from the relational read +model and requires the existing transaction proof. Moving command ownership +does not change Eventual projection confirmation or Atomic response sealing. + ## Microservice Framework (`microsvc`) -The `microsvc` module provides a convention-based async command/event handler framework. Register handlers on typed `Routes` bundles, collect them into a non-generic `Service`, then expose that service over HTTP, gRPC, the bus, or direct dispatch. +The `microsvc` module provides a convention-based async command/event handler framework. Register typed commands and event handlers on `Routes` bundles, collect them into a non-generic `Service`, then expose that service over HTTP, gRPC, the bus, or in-process dispatch. Every command, from every ingress, is typed, authorized by its declared roles, and recorded in the command ledger under its command ID. ### Defining a Service -A `Routes` bundle is generic over a dependency type `D` that handlers read via `ctx`. Build one fluently from `Routes::new()`: add `.with_repo(repo)` for aggregate command handlers, `.with_read_model_store(store)` for projection handlers (chain both when a handler needs both), or `.with_dependencies(deps)` for custom dependencies. Add one or more route bundles to `Service::new()` with `.routes(routes)`, then use `.with_bus(bus)` to consume from / publish to a transport. +A `Routes` bundle is generic over a dependency type `D`. Build one fluently from `Routes::new()`: add `.with_repo(repo)` for aggregate command handlers, `.with_read_model_store(store)` for projection handlers (chain both when a handler needs both), or `.with_dependencies(deps)` for event handlers with custom dependencies. Add one or more route bundles to `Service::new().named(..)` with `.routes(routes)`, then use `.with_bus(bus)` to consume from / publish to a transport. A service that runs commands must be named: the name scopes its command ledger. -Handlers are registered with a fluent builder. `.command(name)` / `.event(name)` start a registration; `.handle(closure)` adds an unguarded handler and `.guarded(guard, closure)` adds a guarded one. The handler closure receives `&Context` and returns a future: +Commands are registered with a fluent builder. `.typed_command(declaration)` starts a registration; `.handle(handler)` adds an unguarded handler and `.guarded(guard, handler)` adds a guarded one. The handler receives `&CausalCommandContext` and the decoded input, and returns the prepared commit: ```rust,ignore use std::sync::Arc; -use distributed::microsvc::{Context, HandlerError, Routes, Service, Session}; +use distributed::command::{typed_command, PreparedCommand, Succeeded}; +use distributed::command_dispatch::VerifiedPrincipal; +use distributed::microsvc::{CausalCommandContext, HandlerError, Routes, Service, Session}; use distributed::{AggregateBuilder, InMemoryRepository, Queueable}; use serde_json::json; +async fn initialize( + ctx: &CausalCommandContext<'_, Counter>, + input: CreateCounter, +) -> Result>, HandlerError> { + let mut counter = ctx.repo().create(); + counter.create(input.id)?; + let value = counter.value; + ctx.repo().commit(counter)?.succeeded(CounterValue { value }) +} + +async fn increment( + ctx: &CausalCommandContext<'_, Counter>, + input: IncrementCounter, +) -> Result>, HandlerError> { + let mut counter = ctx.repo().get(&input.id).await? + .ok_or_else(|| HandlerError::NotFound(input.id.clone()))?; + counter.increment(input.amount)?; + let value = counter.value; + ctx.repo().commit(counter)?.succeeded(CounterValue { value }) +} + let routes = Routes::new() .with_repo(InMemoryRepository::new().queued().aggregate::()) - .command("counter.initialize") - .handle(|ctx: &Context| { - let input = ctx.input::(); - async move { - let input = input?; - let mut counter = Counter::default(); - counter.create(input.id.clone())?; - ctx.repo().commit(&mut counter).await?; - Ok(json!({ "id": input.id })) - } - }) - .command("counter.increment") - .handle(|ctx: &Context| { - let input = ctx.input::(); - async move { - let input = input?; - let mut counter = ctx.repo().get(&input.id).await? - .ok_or_else(|| HandlerError::NotFound(input.id.clone()))?; - counter.increment(input.amount)?; - ctx.repo().commit(&mut counter).await?; - Ok(json!({ "value": counter.value })) - } - }); -let service = Arc::new(Service::new().routes(routes)); + .typed_command(typed_command::>("counter.initialize")) + .handle(initialize) + .typed_command(typed_command::>("counter.increment")) + .handle(increment); +let service = Arc::new(Service::new().named("counters").routes(routes)); -// Direct dispatch +// In-process dispatch: a UUIDv7 command ID and the principal the caller verified let _result = service - .dispatch("counter.initialize", json!({ "id": "c1" }), Session::new()) + .dispatch_causal( + "counter.initialize", + "0190a000-0000-7000-8000-000000000001", + json!({ "id": "c1" }), + Session::new(), + VerifiedPrincipal::internal("counters-job")?, + ) .await?; ``` -### Guards +`CreateCounter` and `IncrementCounter` derive `Deserialize` and `distributed::CommandInput`; `CounterValue` derives `Serialize` and `distributed::CommandOutput`. The handler stages its commit and returns; the framework writes it with the ledger receipt in one transaction, so dispatching the same command ID again replays the receipt instead of running the handler. + +### Roles and Guards -`.guarded(guard, handler)` runs the guard before the handler — if it returns `false`, the command is rejected: +A command declares the roles that may run it with `.roles([..])`; a session without one of them is refused before the handler or guard runs. A command with no declared roles admits any caller. `.guarded(guard, handler)` then runs the guard before the handler — if it returns `false`, the command is rejected: ```rust,ignore let routes = routes - .command("admin.reset") + .typed_command(typed_command::>("admin.reset").roles(["admin"])) .guarded( - |ctx: &Context| ctx.role() == Some("admin"), - |_ctx: &Context| async { Ok(json!({ "reset": true })) }, + |ctx: &CausalCommandContext<'_, Counter>| ctx.claim("x-region") == Some("eu"), + reset, ); ``` ### Handler File Convention -For larger services, organize handlers into separate files. Each handler module exports a `COMMAND` (or `EVENT` / `EVENTS`) name, a `guard`, and an async `handle`: +For larger services, organize handlers into separate files. Each command module exports a `COMMAND` name, a `command()` declaration, and an async `handle`: ```rust,ignore // src/handlers/counter_create.rs -use serde::Deserialize; -use serde_json::{json, Value}; -use distributed::microsvc::{Context, HandlerError}; -use super::Repo; +use serde::{Deserialize, Serialize}; +use distributed::command::{typed_command, PreparedCommand, Succeeded, TypedCommand}; +use distributed::microsvc::{CausalCommandContext, HandlerError}; use crate::models::counter::Counter; pub const COMMAND: &str = "counter.initialize"; -#[derive(Deserialize)] -struct Input { id: String } +#[derive(Debug, Deserialize, distributed::CommandInput)] +pub struct Input { pub id: String } -pub fn guard(ctx: &Context) -> bool { - ctx.has_fields(&["id"]) -} +#[derive(Debug, Serialize, distributed::CommandOutput)] +pub struct Output { pub id: String } -pub async fn handle(ctx: &Context<'_, Repo>) -> Result { - let input = ctx.input::()?; +pub fn command() -> TypedCommand> { + typed_command::>(COMMAND).roles(["user"]) +} +pub async fn handle( + ctx: &CausalCommandContext<'_, Counter>, + input: Input, +) -> Result>, HandlerError> { if ctx.repo().get(&input.id).await?.is_some() { return Err(HandlerError::Rejected(format!("counter {} already exists", input.id))); } - let mut counter = Counter::default(); + let mut counter = ctx.repo().create(); counter.create(input.id.clone())?; // `counter.initialized` is domain-marked on the aggregate. - ctx.repo().publish_events().commit(&mut counter).await?; - - Ok(json!({ "id": input.id })) + ctx.repo().publish_events().commit(counter)?.succeeded(Output { id: input.id }) } ``` -Register them with the `routes!` macro: +Register them on the route bundle: ```rust,ignore -let routes = distributed::routes!( - Routes::new().with_repo(InMemoryRepository::new().queued().aggregate::()), - command handlers::counter_create, - command handlers::counter_increment, -); -let service = Service::new().routes(routes); +let routes = Routes::new() + .with_repo(InMemoryRepository::new().queued().aggregate::()) + .typed_command(handlers::counter_create::command()) + .handle(handlers::counter_create::handle) + .typed_command(handlers::counter_increment::command()) + .handle(handlers::counter_increment::handle); +let service = Service::new().named("counters").routes(routes); ``` -Event projection handlers use `EVENT` / `EVENTS` and `event handlers::...` in the same way; inside the handler, `ctx.message()` gives the raw transport `Message` and `ctx.input::()` decodes its payload. +Event projection handlers export `EVENT` / `EVENTS`, a `guard(ctx) -> bool` and an async `handle(ctx) -> Result`, and register with the `routes!` macro: `distributed::routes!(routes, event handlers::counter_rebuilt, events handlers::counter_projection)`. Inside an event handler, `ctx.message()` gives the raw transport `Message` and `ctx.input::()` decodes its payload. ### HTTP Transport (requires `http` feature) -The `http` feature adds an axum-based HTTP transport. Every registered command becomes a `POST /:command` endpoint. Request headers flow into the `Session` verbatim — including identity claims, which the framework does **not** authenticate. Deploy behind a trusted proxy that strips client-supplied identity headers and injects authenticated ones (see [Security / Trust Boundary](#security--trust-boundary)). +The `http` feature adds an axum-based HTTP transport. With `Service::with_http_command_routes()`, every registered command becomes a `POST /:command` endpoint whose body is `{ "commandId", "input" }`. Request headers flow into the `Session` verbatim — including identity claims, which the framework does **not** authenticate. Deploy behind a trusted proxy that strips client-supplied identity headers and injects authenticated ones (see [Security / Trust Boundary](#security--trust-boundary)). ```rust,ignore use std::sync::Arc; @@ -1361,23 +1667,90 @@ Routes: | Method | Path | Description | |---|---|---| -| `POST` | `/:command` | Dispatch a command. Body = JSON input, headers = session variables. | +| `POST` | `/:command` | Dispatch a command. Body = `{ "commandId", "input" }`, headers = session variables. A body without a `commandId` is a 400. | | `GET` | `/health` | Health check: `{ "ok": true, "commands": ["counter.initialize", ...] }` | ```bash curl -X POST http://localhost:3000/counter.initialize \ -H 'Content-Type: application/json' \ -H 'x-user-id: user-42' \ - -d '{"id": "c1"}' + -H 'x-roles: user' \ + -d '{"commandId": "0190a000-0000-7000-8000-000000000001", "input": {"id": "c1"}}' +# => {"payload": {"id": "c1"}, "receipt": {"commandId": "...", "causationId": "...", "state": "succeeded"}} curl http://localhost:3000/health ``` +To expose one command without trusting any header, give it an edge with `Service::with_http_command`. The edge sees the request headers and JSON body (`null` when empty) and returns an `HttpCommandDispatch { command_id, input, session, principal }`, or a `CausalDispatchError` (a 401 for a bad secret). The command runs through the ledger like any other dispatch, with only the session the edge built, and answers `{ payload, receipt }`. No other command path is mounted. Behind a gateway, `Service::command_gateway_routes(binding)` (feature `gateway`) gives every command path to the service binding, so an unexposed one is the service's 404 rather than a UI page: + +```rust,ignore +fn webhook_edge( + headers: &HeaderMap, + body: Value, +) -> Result { + verify_shared_secret(headers)?; + Ok(HttpCommandDispatch { + command_id: delivery_command_id(&body), + input: body, + session: webhook_session(), + principal: VerifiedPrincipal::internal("system:webhook").expect("a subject"), + }) +} + +let service = Service::new() + .named("identity") + .routes(routes) + .with_http_command("webhook.receive", webhook_edge); +gateway_routes.extend(service.command_gateway_routes("service")); +``` + +`microsvc::command_router(service)` is the command paths alone, to compose under your own router and middleware. + +The command ID is a client-created UUIDv7: retrying a request with the same ID +replays the committed receipt. A command needs an authenticated user +(`x-user-id`), and a role its declaration grants. + `x-user-id` / `x-roles` are convenience keys for `Session::user_id()` / `Session::roles()` only — not a required protocol. Your gateway can inject any claim names; handlers read them with `session.get("…")` or map claims to the convenience keys at the edge. +### Authenticated cell wait-path metadata + +An internal command host can carry a small, explicit set of already-authenticated +facts across the private cell HTTP boundary. Do not put producer or operation +claims in `Session`: ordinary cell calls forward only the authenticated user and +role keys. `CellRequestContext` requires an internal HTTP secret and reserves +framework identity and transport-control headers from application metadata. + +```rust,ignore +use distributed::command_dispatch::{ + CellRequestContext, HttpCommandHost, TrustedRequestMetadata, +}; + +let metadata = TrustedRequestMetadata::try_from_pairs([ + ("x-source-kind", "canonical-fact"), +])?; +let context = CellRequestContext::new("writer-service", "principal-partition") + .with_causation_id("0190a000-0000-7000-8000-000000000001") + .with_trusted_metadata(metadata); +let host = HttpCommandHost::new_internal("http://cell.internal", secret)?; +let (_status, body) = host + .post_cell_wait_path_with_context( + "order.submit", + "0190a000-0000-7000-8000-000000000002", + serde_json::json!({ "order_id": "order-1" }), + &session, + &context, + ) + .await?; +``` + +Metadata names must be canonical lowercase and values are bounded visible HTTP +text. Public callers cannot authenticate this path by supplying the reserved +headers themselves; the cell must validate the shared internal secret before +constructing its typed command identity. + ### gRPC Transport (requires `grpc` feature) The `grpc` feature adds a tonic-based gRPC transport using standard protobuf wire format (no `.proto` file needed): @@ -1392,7 +1765,7 @@ microsvc::serve_grpc(service, "[::1]:50051").await?; | RPC | Input | Output | Description | |---|---|---|---| -| `Dispatch` | `GrpcRequest` | `GrpcResponse` | Dispatch a command. `input` = JSON string, `session_variables` = metadata map. | +| `Dispatch` | `GrpcRequest` | `GrpcResponse` | Dispatch a command. `input` = the JSON string `{ "commandId", "input" }`, `session_variables` = metadata map. | | `Health` | `HealthRequest` | `HealthResponse` | Health check. | Session handling mirrors HTTP — gRPC metadata headers are merged with payload `session_variables`. **Transport metadata (trusted, proxy-injected) takes precedence over the client-controlled payload**, so a client cannot spoof identity via the request body. See [Security / Trust Boundary](#security--trust-boundary) below. Errors are returned inside `GrpcResponse.status` (HTTP-style status codes) with internal (5xx) error detail masked to a generic message, keeping client behavior identical across transports. @@ -1403,27 +1776,30 @@ Attach a bus with `service.with_bus(bus)` and drive it with `run(opts)`: it derives `listen` (point-to-point commands) and `subscribe` (fan-out events) from the registered handlers, and makes `repo.outbox(msg).commit(agg)` publish on commit. The same `Service` can handle commands from multiple transports -simultaneously — HTTP, gRPC, bus, and direct dispatch all share the same handlers -and repository. For finer-grained control, call the `listen` / `subscribe` facade +simultaneously — HTTP, gRPC, bus, and in-process dispatch all share the same handlers, +repository and command ledger. A bus delivers a command as the transport +identity: the command must declare `TRANSPORT_ROLE` in its roles and the +message must carry an id, which the ledger deduplicates redeliveries on. For finer-grained control, call the `listen` / `subscribe` facade methods directly. See [Service Bus](#service-bus) above. ### Error Handling -`HandlerError` maps to HTTP-style status codes: +A command that does not commit returns a `CausalDispatchError`; the HTTP and +gRPC transports answer with its status and a `{ "code", "error" }` body. A +handler's `HandlerError` becomes the recorded rejection of that command ID: -| Variant | Status Code | -|---|---| -| `UnknownCommand` | 404 | -| `DecodeFailed` | 400 | -| `GuardRejected` | 400 | -| `Rejected` | 422 | -| `NotFound` | 404 | -| `Unauthorized` | 401 | -| `Repository` | 500 | -| `Other` | 500 | +| Cause | Status | `code` | +|---|---|---| +| Unknown command, bad envelope, input that does not decode | 400 | `BAD_REQUEST` | +| No authenticated user (or handler `Unauthorized`) | 401 | `UNAUTHORIZED` | +| Session lacks a declared role | 403 | `FORBIDDEN` | +| Handler `NotFound` | 404 | `NOT_FOUND` | +| Command ID reused for different input, or still in progress | 409 | `COMMAND_ID_REUSE` / `COMMAND_IN_PROGRESS` | +| Handler `Rejected`, guard returned `false` | 422 | `REJECTED` | +| Repository or other host failure | 500 | `INTERNAL` | Internal (5xx) errors are **masked** before being returned to clients — the -response body carries a generic `"Internal server error"` so SQL text, driver +response body carries a generic `"internal error"` so SQL text, driver detail, or internal paths never leak. The original error is logged server-side. Client-fault (4xx) errors keep their descriptive message. This applies identically to the HTTP and gRPC transports. @@ -1546,6 +1922,22 @@ let loaded = repo PK (same-named columns, or `foreign_key` / `target_foreign_key` in PK order). A one-column `foreign_key` on a composite PK is an error, not a silent `.first()`. +- **Unique-key joins:** direct relationships can set + `references = "namespace,revision"` alongside + `foreign_key = "object_namespace,object_revision"`. The referenced columns + must be a complete declared unique key, such as + `#[unique(columns = ["namespace", "revision"])]`, on the target of + `belongs_to` or the source of `has_many`. Foreign-key columns pair in the + declared reference order. This lets a model retain a surrogate primary key + for row identity while relating by a domain key. Missing/null foreign keys + produce no match; nested target permissions still apply. Omitting `references` + selects the primary key. `references` is not supported on `many_to_many`. +- **Cyclic singular relationships:** use `Option>` for a `belongs_to` + field when two models refer to each other. For example, + `#[readmodel(belongs_to = "Profile", foreign_key = "id")]` + `profile: Option>`. The box only gives Rust a finite-sized type; + GraphQL still exposes one nullable `Profile`, not a list or embedded JSON + column. Ordinary `Option` remains the same singular relationship. - **Writes:** `ReadModelWritePlan` / workspace `upsert` + `commit` (same transaction as events when staged on `CommitBatch`). - **Internal loads:** PK-anchored includes — @@ -1606,6 +1998,54 @@ distributed = { version = "0.1", features = ["graphql", "postgres"] } `distributed::graphql::{naming,sdl}` compile without the feature so `distributed schema --format graphql` works in tooling crates. +### Literal text search + +Use `_icontains` for a case-insensitive substring search on a String column: + +```graphql +query SearchTodos($q: String! = "") @load @live { + todos(where: { title: { _icontains: $q } }, limit: 20) { + todo_id + title + } +} +``` + +A colocated binding can pass `q: searchParam('q', 'String')` directly. Callers do not +construct `%patterns%`: `%`, `_`, backslash, quotes and the escape character +are literal text. The query engine binds an escaped pattern on both PostgreSQL +and SQLite. An empty string matches every non-null string; use a bounded query +and show results only after a submitted search when building a search form. + +The pattern operators mean the same thing on PostgreSQL and SQLite: + +| Operator | Wildcards | Case | +|---|---|---| +| `_like` | `%` any run, `_` one character, `\` escapes the next character | exact | +| `_ilike` | same | ASCII letters fold; every other character is exact | +| `_icontains` | none: the operand is literal text | same as `_ilike` | + +Folding is ASCII-only on both backends, so `é` does not match `É` under +`_ilike` or `_icontains`; PostgreSQL's collation-dependent `ILIKE` folding is +not used. A pattern that ends in a lone `\` is a `BAD_REQUEST`. The browser +replica does not evaluate these operators locally and relies on the authorized +server result. `_contains` remains the PostgreSQL JSON containment operator. + +Text comparison is by UTF-8 bytes on both backends, for `_eq`, `_neq`, `_in`, +`_nin`, `_gt`/`_gte`/`_lt`/`_lte` and `order_by` alike: `"Open"` is not +`"open"`, and `"Zeta"` sorts before `"alpha"`. The browser replica compares +the same way, so a list filtered by a text column is maintained locally. +On PostgreSQL the range operators and `order_by` pin `COLLATE "C"`; an index +that should serve them must be declared with that collation. Equality uses +the column's own collation, which must be deterministic (the default is), so +`citext` and nondeterministic collations are not supported. + +A comparison with `null` is neither true nor false, as in SQL, and a row is +returned or authorized only when its filter is true. A `where`, a row policy, +the command-delta path and the browser replica all follow that rule, and +`tests/fixtures/client-query-plan-corpus.json` holds PostgreSQL, SQLite, +`FilterExpr::evaluate` and the replica to the same answers. + ### Scope | In | Out | @@ -1621,9 +2061,8 @@ distributed = { version = "0.1", features = ["graphql", "postgres"] } ### Mount on a service ```rust,ignore -use distributed::graphql::{ - claim, col, read, typed_command, Eventual, GraphqlEngine, -}; +use distributed::command::{typed_command, Eventual}; +use distributed::graphql::{claim, col, read, GraphqlEngine}; use distributed::microsvc::{Routes, Service}; let routes = Routes::new() @@ -1694,34 +2133,54 @@ ModelPermissions::new() Row predicates can bind session claims (`claim("x-user-id")`, …) so multi-tenant RLS lives in the engine, not ad-hoc handler SQL. +With the causal protocol enabled, required session presets must be present and +valid for their declared codecs before execution. Missing or malformed values +return `BAD_REQUEST` for both ordinary and streaming requests, without running +resolvers or issuing a partial protocol envelope. The error does not disclose +claim names or values; configure the identity mapping to supply those inputs. + ### Identity (first-class OIDC) Auth is a **built-in GraphQL concern**, not a separate product you wire after the fact. The engine validates tokens, maps claims into a `microsvc::Session`, and -feeds the same claim map into RLS (`claim("x-user-id")`, roles, …). Modes live -under [`src/graphql/identity/`](src/graphql/identity/): +feeds the same claim map into RLS (`claim("x-user-id")`, roles, …). There are +three modes and **no default**: `GraphqlEngine::build()` fails until +`.identity(..)` names one. They live under +[`src/graphql/identity/`](src/graphql/identity/): | Mode | When to use | |---|---| | **`OidcBearer`** | **Default for public edges:** JWT access tokens (`Authorization: Bearer …`), JWKS (incl. discovery), iss/aud/exp/nbf, alg allowlist (no `alg=none`), claim → engine roles. Configure with `OIDC_ISSUER` / `OIDC_AUDIENCE` (and related). | -| **`TrustedProxy`** | Mesh/gateway already authenticated; inject trusted headers, strip client spoofing. | -| **`Hybrid`** | Bearer when present, else trusted proxy headers. | +| **`Gateway`** | A gateway in front already authenticated the caller. `IdentityConfig::gateway(header, secret)`: a request is trusted only when it carries the shared secret (compared in constant time); its `x-user-id` / `x-roles` then become the session. Without the secret: 401. | | **`DevHeaders`** | Local only: ambient `x-user-id` / `x-roles`. **Never** on a public edge. | +Credentials never enter the `Session` handed to command handlers: +`authorization`, `cookie` and the gateway secret header are dropped in every +mode. If the issuer's JWKS endpoint fails, requests keep validating against the +keys already cached, and the issuer is retried after +`OidcConfig::jwks_refresh_failure_backoff` (30s by default). + Scaffolds prefer **`OidcBearer`** whenever OIDC env is set — not DevHeaders. **Provider-portable by design.** Live compose + bootstrap + e2e binaries ship for: -- **Zitadel** — `tests/graphql_oidc_zitadel` + `scripts/oidc-zitadel-up.sh` (JWT-bearer mint; also powers e2e-ui login) -- **Keycloak** — `tests/graphql_oidc_keycloak` + `scripts/oidc-keycloak-up.sh` (client_credentials + realm roles) -- **Authentik** — `tests/graphql_oidc_authentik` + `scripts/oidc-authentik-up.sh` (client_credentials + groups) +- **Zitadel** — `tests/graphql/graphql_oidc_zitadel` + `scripts/oidc-zitadel-up.sh` (JWT-bearer mint; also powers e2e-ui login) +- **Keycloak** — `tests/graphql/graphql_oidc_keycloak` + `scripts/oidc-keycloak-up.sh` (client_credentials + realm roles) +- **Authentik** — `tests/graphql/graphql_oidc_authentik` + `scripts/oidc-authentik-up.sh` (client_credentials + groups) Shared assertions (E1–E8): discovery/JWKS, happy path, role isolation, multi-audience / `azp`, expired and forged tokens, etc. Generic OIDC also works for SaaS IdPs (e.g. Okta) without a dedicated compose stack. **WebSocket subscriptions:** browsers cannot set `Authorization` on the upgrade. Clients send the access token in `connection_init` (`authorization` / -`accessToken` / nested headers). Do not put long-lived tokens in query strings -for production. e2e-ui chat demonstrates the OIDC path. +`accessToken` / nested headers). Identity is never read from the URL query +string. Under `Gateway` the secret must be on the upgrade request and the +`connection_init` payload is ignored. e2e-ui chat demonstrates the OIDC path. + +Each origin WebSocket is bounded by `WebsocketLimits` (set with +`.websocket_limits(..)`): it closes when the token that opened it expires +(close code `4401`) or after `max_lifetime` (12h), whichever is first; the +server pings and drops a peer silent for `idle_timeout` (60s); and one +connection holds at most `max_live_queries` (100) subscriptions. > **Note:** Raw microsvc HTTP/gRPC routes still treat `Session` as opaque unless > you terminate auth at a proxy **or** put the public API on GraphQL @@ -1785,6 +2244,13 @@ Application code does not invoke the client compiler directly or commit its outputs. `distributed client-manifest` and `distributed client` are internal compiler primitives used by the lifecycle, not parallel application workflows. +`distributed dev` tells each supervised process whether it belongs to the +active generation. A process honours that by composing its services with +`.with_lifecycle(LifecycleGate::from_env())` (resolved once, cloned into every +`Service`): outside the active generation, writes fail with +`ApplicationReloading`. Without the call a service is always open. See +[`docs/reloading-event-delivery.md`](docs/reloading-event-delivery.md). + See [`js/README.md`](js/README.md) for the package API and [`tests/e2e-ui/README.md`](tests/e2e-ui/README.md) for the complete integration flow. @@ -1844,22 +2310,22 @@ See [`js/README.md`](js/README.md) for package API and packaging. | Suite | Focus | |---|---| -| `tests/graphql_*` | Engine, HTTP, SDL, dialects, harden (authz/DoS/inject), causal transport | -| `tests/graphql_identity` | Always-on OIDC/JWT matrix (mock JWKS; no Docker) | -| `tests/graphql_oidc_{zitadel,keycloak,authentik}` | **Live** multi-IdP e2e (compose + real JWKS; gated) | -| `tests/typed_commands` | Eventual / Atomic / Succeeded command registration | +| `tests/graphql/` | Engine, HTTP, SDL, dialects, harden (authz/DoS/inject), causal transport | +| `tests/graphql/graphql_identity` | Always-on OIDC/JWT matrix (mock JWKS; no Docker) | +| `tests/graphql/graphql_oidc_{zitadel,keycloak,authentik}` | **Live** multi-IdP e2e (compose + real JWKS; gated) | +| `tests/core/typed_commands` | Eventual / Atomic / Succeeded command registration | | `tests/e2e-ui` | Multi-crate product template + SvelteKit + Zitadel UI login + Playwright | | `js/tests` | Replica, command runtime, adapters | | `examples/graphiql.rs` | Seeded local playground | ```bash -cargo test --test graphql_engine --features "graphql,sqlite" -cargo test --test graphql_identity --features "graphql,sqlite" -cargo test --test graphql_harden --features "graphql,sqlite" +cargo test --test graphql --features "graphql,sqlite" graphql_engine:: +cargo test --test graphql --features "graphql,sqlite" graphql_identity:: +cargo test --test graphql --features "graphql,sqlite" graphql_harden:: cd js && npm run quality # Live IdPs (optional): # ./scripts/oidc-zitadel-up.sh && set -a && source graphql-oidc.env && set +a -# cargo test --test graphql_oidc_zitadel --features graphql,sqlite +# cargo test --test graphql --features graphql,sqlite graphql_oidc_zitadel:: # Full UI matrix: cd tests/e2e-ui && make test ``` @@ -1883,7 +2349,7 @@ struct Todo { } ``` -Fields with `#[serde(skip)]` (like `emitter: EntityEmitter`) are automatically excluded. +Fields with `#[serde(skip)]` are automatically excluded. **Custom ID key** — when the entity ID maps to a domain field like `sku`: @@ -2024,6 +2490,40 @@ a smaller target: model fields, event methods, handler bodies, and projection shapes. Boilerplate service setup, manifest discovery, schema output, and GitOps artifacts stay deterministic. +For an existing typed `Service`, derive the logical application from its command +inventory and the same full GraphQL `Surface` used by the runtime: + +```rust,ignore +let surface = distributed::SurfaceSpec::from_surface("catalog", &full_surface)?; +let application = service.application("catalog", surface)?; +let manifest = application.manifest(); +``` + +Command namespaces such as `orders.submit` supply module names; there is no +second module list to maintain. Assembly rejects commands missing from the +Surface or exposed by the Surface without a Service owner. Role-selected client +exports remain authorization views of that full contract. Complete application +manifests are bounded at 16 MiB; each opaque JSON contract remains bounded at +1 MiB. A generated Surface contract uses the complete-manifest budget rather +than the opaque-value cap; its typed contents and the existing collection, +string and nesting limits are still validated. The complete artifact, including +all surfaces and module inventories, must fit within 16 MiB, matching the CLI +manifest ingress budget. Older tooling capped at 4 MiB must be rebuilt before +consuming larger artifacts; encoding versions and existing fingerprints do not +change. + +An event-driven policy that emits through another aggregate can explicitly carry +the incoming command's causal identity before recording its events: + +```rust,ignore +ctx.inherit_causation(&mut downstream)?; +downstream.record(observation)?; +``` + +This requires an incoming causation ID and does not manufacture one for external +events. NATS preserves the message's payload content type and keeps reserved +transport headers out of user metadata across delivery. + ```bash cargo install distributed_cli # installs `distributed` @@ -2044,6 +2544,17 @@ distributed describe # print the ApplicationManifest as JSON distributed schema --dialect postgres # render migration SQL from read models ``` +Application manifest wire version 2 stores module declarations and selected +Surface contracts without repeating top-level `commands`, `events`, `models`, +or `projections`. The Rust `ApplicationManifest` decoder reconstructs those +inventories and validates their ownership; its convenience fields are unchanged. +Portable application artifacts remain bounded to 16 MiB. Version 1 artifacts must be +regenerated with the matching CLI; they are not accepted as version 2. + +Modeled projection contracts [share repeated operations and selector schemas](docs/compact-projection-contracts.md) +when smaller, preserving every current and retained event selector within the +same manifest budget. Runtime program identities and execution are unchanged. + For a full application, run `distributed build` or `distributed dev` from its Cargo workspace root. The CLI discovers the typed application, runtime binary, conventional `ui/` SvelteKit app, and `@hops-ops/distributed` dependency. A @@ -2165,37 +2676,64 @@ reference: [`distributed_cli/README.md`](distributed_cli/README.md). ```text src/ - aggregate/ # Aggregate trait, hydration, async aggregate repository helpers - bus/ # Bus facade + adapters (in-memory, sqlite, postgres, nats, rabbitmq, kafka, knative) - commit_builder/ # Transactional batches for aggregates, outbox, and read models - emitter/ # In-process event emitter helpers (feature = "emitter") - entity/ # Entity, event records, metadata, upcasting codecs - graphql/ # Query service: engine, permissions, identity, SDL, HTTP/WS (feature = "graphql") - in_memory_repo/ # In-memory repository (implements every async trait) - lock/ # Lock + lock manager traits, in-memory locks - microsvc/ # Command/event handler framework: service, context, session - outbox/ # Durable outbox message + commit extension - outbox_worker/ # Outbox claiming, publishing, workers - postgres_repo/ # Postgres async SQL repository (feature = "postgres") - queued_repo/ # Queue-based locking repository wrapper - read_model/ # Read model store traits, in-memory store, schema metadata - snapshot/ # Snapshot store traits, in-memory store, snapshot repository - sqlite_repo/ # SQLite async SQL repository (feature = "sqlite") - table/ # Neutral table/row primitives shared by read models and ops tables - lib.rs # Public exports -distributed_macros/ - src/ # Proc macros: sourced, digest, aggregate, enqueue, ReadModel, Snapshot -js/ # @hops-ops/distributed JS/TS client, command runtime, and SvelteKit adapter -tests/e2e-ui/ # Full-stack CQRS + GraphQL + SvelteKit template (nested workspace) -migrations/ # Explicit SQLite and Postgres migrations -compose.yaml # Local postgres / rabbitmq / kafka / nats for integration tests + aggregate/ # Aggregate trait, hydration, async aggregate repository helpers + application/ # Placement-independent application composition (modules, mounts, plans) + bus/ # Bus facade + adapters (in-memory, sqlite, postgres, nats, rabbitmq, + # kafka, knative, redis streams, celld Queue relay) + clock.rs # Injectable wall clock for coordination primitives + command/ # Typed commands: Eventual/Atomic/Succeeded, prepared completions, client effects + command_dispatch/ # CommandHost: local, HTTP and remote dispatch boundary + command_ledger/ # Durable command identity and fenced commit primitives (crate-private) + commit_builder/ # Transactional batches for aggregates, outbox, and read models + domain_event/ # Typed outward domain events, separate from replay bytes + entity/ # Entity, event records, metadata, upcasting codecs + gateway/ # Portable application gateway contracts (feature = "gateway*") + graphql/ # Query service: engine, permissions, identity, SDL, HTTP/WS (feature = "graphql") + in_memory_repo/ # In-memory repository (implements every async trait) + lease/ # TTL leases with monotonic fencing tokens + lock/ # Lock + lock manager traits, in-memory locks + metrics/ # Prometheus-compatible framework metrics (feature = "metrics") + microsvc/ # Command/event handler framework: service, context, session, cell_host (celld) + mutation/ # Event-independent read-model mutation IR and interpreters + outbox/ # Durable outbox message + commit extension + outbox_worker/ # Outbox claiming, publishing, workers + postgres_repo/ # Postgres async SQL repository (feature = "postgres") + projection/ # Deterministic domain-event projection programs and runtime + projection_protocol/ # Projection identities, ordering vocabulary, codecs (+ projection_protocol.rs) + queued_repo/ # Queue-based locking repository wrapper + read_model/ # Read model store traits, in-memory store, schema metadata, keyset scans + repository/ # Repository traits (GetStream, TransactionalCommit, …) + saga/ # Event-sourced process managers for cross-cell workflows (incl. fan-out) + schedule.rs # Portable aggregate schedules, host clock, backend capabilities + snapshot/ # Snapshot store traits, in-memory store, snapshot repository + sqlite_repo/ # SQLite async SQL repository (feature = "sqlite") + sqlx_repo/ # SQL code shared by the Postgres and SQLite repositories + table/ # Neutral table/row primitives shared by read models and ops tables + telemetry.rs # Telemetry vocabulary shared by metrics and tracing + time.rs # Wall clock that also works on wasm32 + trace_context.rs # W3C trace-context metadata helpers + lib.rs # Public exports +distributed_macros/ # Proc macros: sourced, command!, mutation!, ReadModel, Snapshot, DomainState, + # DomainEvent, CommandInput, CommandOutput (projection! is in src/lib.rs) +distributed_cli/ # The `distributed` CLI (build/dev lifecycle, client codegen, contracts + # check/accept, game-manifest/game-client/game-wasm); also a library +distributed_game/ # Authoritative multiplayer zone runtime: fixed tick, facts, replication, + # WebSocket net, celld cells (zone lease/state, fact sink) +distributed_game_macros/ # Derives for distributed_game: Replicated, GameInput, GameEvent, … +distributed_leaderboard/ # Sorted-set leaderboards as a rebuildable projection target (memory, + # Redis), served through GraphQL as an external read source +js/ # @hops-ops/distributed JS/TS client, command runtime, SvelteKit adapter, game SDK +examples/ # graphiql.rs, and examples/game (game demos + SvelteKit Mob Pit; own workspace) +tests/e2e-ui/ # Full-stack CQRS + GraphQL + SvelteKit template (nested workspace) +tests/e2e-celld/ # The same UI with commands on celld cells and NATS (nested workspace) +migrations/ # Explicit SQLite and Postgres migrations +compose.yaml # Local postgres / rabbitmq / kafka / nats / redis for integration tests ``` ## Running Tests ```bash cargo test # default feature set -cargo test --features emitter cargo test --features http cargo test --features grpc make test # starts compose and runs full local coverage @@ -2212,14 +2750,14 @@ unset**; SQLite uses a temporary database file and needs no Docker service. docker compose up -d # postgres, rabbitmq, kafka, nats (see compose.yaml) DATABASE_URL=postgres://sourced:sourced@localhost:5432/distributed \ - cargo test --test postgres_transport --features postgres -cargo test --test sqlite_transport --features sqlite + cargo test --test transports --features postgres postgres_transport:: +cargo test --test transports --features sqlite sqlite_transport:: NATS_URL=nats://localhost:4222 \ - cargo test --test nats_transport --features nats + cargo test --test transports --features nats nats_transport:: AMQP_URL=amqp://guest:guest@localhost:5672/%2f \ - cargo test --test rabbitmq_transport --features rabbitmq + cargo test --test transports --features rabbitmq rabbitmq_transport:: KAFKA_BROKERS=127.0.0.1:9092 \ - cargo test --test kafka_transport --features kafka + cargo test --test transports --features kafka kafka_transport:: ``` Each external broker has a matching reusable GitHub Actions job @@ -2250,13 +2788,13 @@ e2e-celld (`tests/e2e-celld`), Blob game, live chat, GraphiQL. | [`tests/e2e-celld/`](tests/e2e-celld/) | Same UI; Todo + `chat.post` wait-dispatch to celld; `@live` stays on GraphQL | | [`js/`](js/) | `@hops-ops/distributed` — transport, causal replica, SvelteKit/React | | [`examples/graphiql.rs`](examples/graphiql.rs) | Seeded GraphQL playground (`--features "graphql,sqlite"`) | -| `tests/graphql_*` | Engine, HTTP/WS, harden, identity, multi-IdP OIDC | -| `tests/typed_commands/` | Eventual / `Atomic` / `Succeeded` command registration | -| `tests/microsvc/` | Handlers on HTTP, gRPC, bus, session | -| `tests/read_models/`, `tests/distributed_read_model/` | Atomic vs eventual projections | -| `tests/sourced*` / `tests/snapshots/` / `tests/upcasting/` | Macros, snapshots, event versioning | -| `tests/sagas/` | Orchestration + choreography with the outbox | -| `tests/*_transport/`, `tests/knative_cloudevents/` | Broker adapters + conformance | +| `tests/graphql/` | Engine, HTTP/WS, harden, identity, multi-IdP OIDC | +| `tests/core/typed_commands/` | Eventual / `Atomic` / `Succeeded` command registration | +| `tests/services/microsvc/` | Handlers on HTTP, gRPC, bus, session | +| `tests/read_models/` | Read models: commit bridge, keyset scans, relationships, sessions, Atomic vs eventual projections | +| `tests/core/sourced*` / `tests/core/snapshots/` / `tests/core/upcasting/` | Macros, snapshots, event versioning | +| `tests/services/sagas/` | Orchestration + choreography with the outbox | +| `tests/transports/` | Broker adapters + conformance | ## License diff --git a/build.rs b/build.rs index a0f3b91bb..c0d969e5f 100644 --- a/build.rs +++ b/build.rs @@ -161,9 +161,10 @@ fn emit_migration_inventory() { } fn emit_dialect(generated: &mut String, name: &str, dialect: Dialect, inventory: &Inventory) { - generated.push_str("#[cfg(feature = \""); - generated.push_str(dialect.name()); - generated.push_str("\")]\n"); + match dialect { + Dialect::Sqlite => generated.push_str("#[cfg(any(feature = \"sqlite\", all(feature = \"cloudflare-workers\", target_arch = \"wasm32\")))]\n"), + Dialect::Postgres => generated.push_str("#[cfg(feature = \"postgres\")]\n"), + } generated.push_str("pub(crate) const "); generated.push_str(name); generated.push_str(": &[EmbeddedMigration] = &[\n"); diff --git a/compose.yaml b/compose.yaml index ca82d22b6..5760aa090 100644 --- a/compose.yaml +++ b/compose.yaml @@ -7,13 +7,15 @@ # (each integration test skips when its env var is unset): # # DATABASE_URL=postgres://sourced:sourced@localhost:5432/distributed \ -# cargo test --test postgres_transport --features postgres +# cargo test --test transports --features postgres postgres_transport:: # AMQP_URL=amqp://guest:guest@localhost:5672/%2f \ -# cargo test --test rabbitmq_transport --features rabbitmq +# cargo test --test transports --features rabbitmq rabbitmq_transport:: # KAFKA_BROKERS=127.0.0.1:9092 \ -# cargo test --test kafka_transport --features kafka +# cargo test --test transports --features kafka kafka_transport:: # NATS_URL=nats://localhost:4222 \ -# cargo test --test nats_transport --features nats +# cargo test --test transports --features nats nats_transport:: +# REDIS_URL=redis://127.0.0.1:6379 \ +# cargo test -p distributed_leaderboard --features redis,graphql --test redis services: postgres: image: postgres:18 @@ -73,3 +75,13 @@ services: interval: 5s timeout: 5s retries: 20 + + redis: + image: redis:8.2-alpine + ports: + - "6379:6379" + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 2s + timeout: 5s + retries: 20 diff --git a/distributed_cli/Cargo.toml b/distributed_cli/Cargo.toml index 841d24c05..39d7e30c4 100644 --- a/distributed_cli/Cargo.toml +++ b/distributed_cli/Cargo.toml @@ -19,7 +19,12 @@ async-graphql-parser = "7" async-graphql-value = "7" base64 = "0.23.0" clap = { version = "4", features = ["derive"] } -ctrlc = "3" +# `termination` adds SIGTERM and SIGHUP to the SIGINT handler. +ctrlc = { version = "3", features = ["termination"] } +distributed = { path = "..", default-features = false } +distributed_game = { path = "../distributed_game" } +# The client manifest's `leaderboards` section (`leaderboards.ts`). +distributed_leaderboard = { path = "../distributed_leaderboard" } dotenvy = "0.15" fs2 = "0.4" glob = "0.3" diff --git a/distributed_cli/README.md b/distributed_cli/README.md index e444c85ca..21e983663 100644 --- a/distributed_cli/README.md +++ b/distributed_cli/README.md @@ -11,8 +11,8 @@ cargo install distributed_cli # installs the `distributed` binary It is also a library, so another CLI can mount its commands instead of reimplementing them. `hops`, for example, exposes the same surface under -`hops service` by depending on this crate and dispatching with -`distributed_cli::run`. **Everything below documented as `distributed ` is also +`hops service` by depending on this crate, mounting `DistributedArgs` and +dispatching with `distributed_cli::run(&args, &["service"])`. **Everything below documented as `distributed ` is also available as `hops service `.** ## `distributed build` — one coherent application generation @@ -59,12 +59,24 @@ document, boundary binding, or UI build therefore leaves the prior generation active. Lifecycle receipts, the application manifest, and generated client trees are tool-owned state under `.distributed/lifecycle/`. +During `distributed dev`, each process launch has a supervisor-owned identity. +Client-only generations can retain an unchanged API process: the active cohort +explicitly admits that instance, and its GraphQL responses advertise the current +generation. Preparing, replaced and retired instances cannot dispatch mutations. +Rollback launches receive new identities; schema compatibility alone never +authorizes an old process. Upgrade the CLI and runtime together and restart dev +after an upgrade so every member receives the matching lifecycle contract. Rust binaries remain in Cargo's target directory and SvelteKit output remains in its adapter-selected output directory. -Use `--output json` for a machine-readable lifecycle report. The compatibility -flags `--root`, `--catalog`, and `--config` exist for older low-level lifecycle -fixtures; normal application builds do not use them. +The discovered lifecycle also carries the absolute executable that initiated the +CLI through its trusted compiler and UI child processes. Generated client +commands therefore use that exact binary even when another `distributed` +executable appears earlier on `PATH`, regardless of a project-local command +override. Standalone Vite integrations retain their documented command setting +and fallback behavior. + +Use `--output json` for a machine-readable lifecycle report. ## `distributed dev` — coherent local supervision @@ -74,9 +86,9 @@ distributed dev ``` `distributed dev` first generates and activates the typed application manifest -and every declared client, then starts the Cargo runtime and `npm run dev` for -`ui/`, waits for both readiness probes, and prints the usable API and browser -URLs. No generated client tree or generation preflight exists in application +and every declared client, then starts the Cargo runtime and the UI dev server +(`npm run dev` in `ui/` unless the project says otherwise, below), waits for +both readiness probes, and prints the usable API and browser URLs. No generated client tree or generation preflight exists in application source. Vite owns Svelte/CSS HMR; GraphQL or binding-only changes rebuild the client node without restarting Rust, while Rust contract changes rebuild the application and its downstream clients together. The browser switches @@ -86,15 +98,48 @@ groups and their descendants. Shell environment variables win. The CLI then loads `.env` and `.env` when present, without displaying their values. `BIND` selects the API -address; `UI_HOST` and `UI_PORT` select the Vite URL. Infrastructure setup is +address; `UI_HOST` and `UI_PORT` select the UI URL. Infrastructure setup is still project-specific—for example, the e2e UI's `make up` creates its local Zitadel/Postgres environment—but starting the application no longer needs a lifecycle shell script. +### The UI and the addresses, in workspace metadata + +A SvelteKit project in `ui/` that uses npm needs no configuration. Anything +else about the UI, and the addresses `dev` uses, is declared in the Cargo +workspace's metadata; there is no other configuration file. Every key is +optional, and an unknown key is an error: + +```toml +[workspace.metadata.distributed.runtime] +bind = "127.0.0.1:8791" # API address; `BIND` overrides it + +[workspace.metadata.distributed.ui] +path = "ui" # the UI directory, relative to the workspace +package_manager = "npm" # the program every command below is given to +install = ["ci"] # default: `ci` beside package-lock.json, else `install` +check = ["run", "check", "--if-present"] # `distributed build`; [] skips the step +build = ["run", "build"] +dev = ["run", "dev", "--", "--host", "{host}", "--port", "{port}"] +host = "localhost" # `UI_HOST` overrides it +port = 5180 # `UI_PORT` overrides it + +# Environment of the UI dev server, beyond what the CLI itself provides +# (`DISTRIBUTED_API_ORIGIN`). `{api_url}` and `{ui_url}` are this session's +# URLs. A value without a placeholder is the project's development default: +# the shell or an `.env` file overrides it. +[workspace.metadata.distributed.ui.env] +AUTH_URL = "{ui_url}" +``` + +The CLI names no application variable and holds no secret: a project that needs +a local-only secret for its dev server declares it here, as `tests/e2e-ui` does. + The lifecycle CLI contract has black-box Bats coverage. It builds and starts a -generated Rust application plus conventional SvelteKit project with no lifecycle JSON, -as well as lower-level coverage for atomic activation, rollback, selective -restarts, readiness, cancellation, and descendant cleanup: +generated Rust application plus conventional SvelteKit project with no lifecycle +configuration, and drives a small Cargo project +(`tests/fixtures/lifecycle-project`) through atomic activation, drift checks, +selective restarts, readiness, cancellation, and descendant cleanup: ```bash # Requires Bats; CI installs the pinned version used by the project. @@ -237,7 +282,9 @@ from that selected surface. The runtime applies GraphQL singleton-list coercion, canonical scalar encoding, unknown-field rejection, and deterministic deep freezing before variables can identify a cache entry or reach the network. Manifest v7 and variable codec v2 carry the selected service's exact -`max_depth`, `max_bool_width`, and `max_in_list` contract. Static literal and +`max_depth`, `max_bool_width`, and `max_in_list` contract, and its `max_rows` +budget ([query cost](../docs/graphql-query-cost.md)): an operation whose +literal or default page sizes already exceed it fails to compile. Static literal and mixed-variable filters are rejected during generation when their known shape exceeds those limits; runtime variables carry per-use `filterBaseDepth` and `maxItems` constraints. Reused variables receive the most restrictive @@ -253,6 +300,95 @@ prove ownership. Unsupported or unprovable selections fail at build time with their source location; the compiler does not emit a partial normalization plan or an adapter-specific route registry. +## `distributed game-manifest` / `game-client` / `game-wasm` — typed game clients + +For [`distributed_game`](../distributed_game/README.md#generated-clients) +zones. The zone's authoring derives (`#[derive(Replicated)]`, +`#[derive(GameInput)]`, `#[derive(GameEvent)]`, `#[predict]`, +`#[game_pure]`) describe a versioned `GameSurface` (schema v3): kinds with +fields, wire types, priorities and client correction defaults, the input +layout with its sanitize rules, events and the records they mention, the +zone's client-predicted step, pure functions compiled to WebAssembly, +constants and standalone record codecs. It is deliberately separate from +the GraphQL client manifest above. + +```bash +# Build and run the crate's surface export through the manifest harness +# (default entrypoint `::game_surface`). +distributed game-manifest --manifest-path game/Cargo.toml \ + --entrypoint my_game::arena::game_surface --out target/arena.surface.json + +# Generate TypeScript (imports only `@hops-ops/distributed/game`). +distributed game-client --manifest target/arena.surface.json --out web/src/generated/arena + +# CI: compare without writing (also catches surface drift via surface.json) +distributed game-client --manifest target/arena.surface.json --out web/src/generated/arena --check + +# Compile the zone's `#[predict]` step and `#[game_pure]` functions to +# web/src/generated/arena/wasm/arena.wasm +# (skipped when the stamp says the sources are unchanged; --check verifies only). +distributed game-wasm --manifest target/arena.surface.json --manifest-path game/Cargo.toml \ + --out web/src/generated/arena +``` + +`game-manifest` accepts the same `--path` / `--manifest-path` / +`--package` / `--features` / `--no-default-features` options as `describe` +and validates the JSON it prints (or writes with `--out`). `game-client` +owns its `--out` directory: it writes `schema.ts` (kind ids, typed field +interfaces and accessors, wire types, correction defaults), `input.ts` +(input interface, bit maps, encoder/decoder/sanitize), `events.ts` (record +and event types, codecs, `onEvent`), `client.ts` (`createClient`, a +`GameClient` with the encoder and corrections wired in and typed `on`), +`index.ts` and `surface.json`, removes stale files it generated earlier, +and refuses to delete files it did not. Output is deterministic. +`--import-extension ts|js|none` picks the specifier style between the +generated files (default `ts`, for Vite and Node type stripping). A surface +with a predicted step also gets `predict.ts` (state and context layouts, +`PREDICT_WASM_URL`, `createPrediction`), and `createClient` +predicts with the compiled step by default. Pure functions add `pures.ts` +(`createPures`, one typed synchronous wrapper per function over the +same module), constants add `constants.ts` (typed literals; floats are the +exact binary32 values, and each value is validated against its type), and +record codecs add `encode` / `decode` to `events.ts`. + +`game-wasm` builds the Cargo package the surface names as the declarer of +its step and pure functions (one package per surface; `cargo rustc +--release --target wasm32-unknown-unknown --crate-type cdylib`; install the +target with `rustup target add wasm32-unknown-unknown`), checks the module +is self-contained (no imports) and exports the ABI (`memory`, +`dg_predict_abi`, `dg_predict_buffer`, `dg_predict_`, every +`dg_pure_`), and writes `/wasm/.wasm` plus a stamp (the +source fingerprint of the package and its local dependencies — the same +one browser WASM pures use — the `rustc` identity, the required exports +and the module hash). A surface with neither a step nor pure functions is +an error. The module is a build output: +keep `wasm/` out of version control and run `game-wasm` before bundling. +Unlike browser WASM pures it needs no wasm-pack, wasm-bindgen glue or JSON +bridge; the SDK instantiates the module directly over a binary ABI. + +## `distributed contracts check` / `accept` — the contract catalog + +```bash +distributed contracts check # read-only; never writes tracked files +distributed contracts check --output json +distributed contracts accept --scope --staged staged.json +``` + +`check` loads the catalog (default `distributed.contracts.json` under +`--root`, the current directory by default) and verifies that every entry's +recorded identity still matches its sources (for this repository, the +migration inventory). It exits non-zero on drift and +prints what changed. `make contracts-check` and the PR quality workflow run it +on this repository. + +`accept` takes one exact scope (no wildcards: `catalog`, +`migration_inventory`, `surface_client_manifest`, `generated_client_tree`, +`application_manifest`, `deployment_plan`, or `program:`) and a staged JSON object mapping portable relative paths to UTF-8 contents. +It writes those files through a staging directory with an atomic replace and +rolls back on failure. An unchanged payload is a no-op. + +`distributed build` reads the same catalog. + ## `distributed describe` — manifest as JSON ```bash diff --git a/distributed_cli/skills/distributed-game/SKILL.md b/distributed_cli/skills/distributed-game/SKILL.md new file mode 100644 index 000000000..99e71813b --- /dev/null +++ b/distributed_cli/skills/distributed-game/SKILL.md @@ -0,0 +1,219 @@ +--- +name: distributed-game +description: Build authoritative game zones with distributed_game - a plain Rust Zone for the simulation, replicated entities with interest management, durable facts settled into cells, and zones that watch world cells as pushed read models. Use when writing or scaling a game zone, its facts, its replication, or its world cells (native host or celld). +--- + +# Game zones with distributed_game + +A zone is a plain Rust struct that owns one authoritative simulation +(movement, physics, combat ticks). The framework hosts it, replicates it, +settles its outcomes and keeps it informed about the world. Game code holds +no storage, transport, retry or celld code. `distributed_game/README.md` is +the full reference; this skill is the shortest path to the common cases. + +## The three rules + +1. **Ticks are never stored.** Only meaningful outcomes leave the zone, as + *facts* (`ctx.emit`), and the tick never waits for them. +2. **Identity is bound by the host.** A fact's principal comes from the + player's verified ticket. Inputs never carry owner identity, XP amounts + or rewards chosen by a client. +3. **Read models are for display.** Watched world state flavours the zone + (weather, a boss tier, an event); rewards still go through the fact → + command path and are validated by the cell's handler. + +## Facts: outcomes into cells + +```rust +#[derive(Serialize, Deserialize, FactCommand)] +#[fact(command = RECORD_KILL)] // the same constant the cell mounts +pub struct RecordKillInput { pub mob: u32 } + +// in a zone hook: never blocks, returns the key +ctx.emit(player, RecordKillInput { mob: id })?; // principal bound from the ticket +ctx.emit_zone(RoomAwakeInput { .. })?; // zone/system fact, no principal +``` + +Route facts once, where the host is built (celld: `CelldZone::fact_routes`): + +```rust +sink.route(FactRoute::by_principal::("crawler")) // crawler/{principal} + .route(FactRoute::by_input_field::("borough", "borough")) +``` + +You get: +- **Exactly once.** The key (zone + boot epoch + parts) becomes the command + id, and the cell's ledger turns a retry into a replay. +- **Order per principal.** Facts of one player commit in emission order; + different players overlap (`max_concurrent_commits`). +- **Backpressure, not loss.** Past `capacity` unsettled facts, `emit` + returns `Backpressure` and the game decides what to do. +- **Batches by default on celld.** A lane's waiting facts for one cell go + as one `POST …/__batch` (`ZONE_FACT_BATCH`, default 16), and the zone + outbox clears them with one delete. A batch stops at its first retryable + failure and resumes from there, so order and exactly-once hold. A custom + sink opts in with one override, `FactSink::batches` returning + `Some(self)` as a `&dyn FactBatchSink` (its `commit_batch`); a host, + `FactHost::fact_batches` returning a `&dyn FactBatchHost`. Otherwise it + gets one fact at a time. + +Results come back on a later tick in `on_fact_settled`. + +## Replication: what each client sees + +```rust +// one #[replicated] per view struct (Mob Pit: examples/game/server/rooms/src/zone.rs) +#[replicated(kind = "mob", id = 2, of = Mob)] // interest-managed +#[replicated(kind = "pillar", id = 3, global, of = Pillar)] // everyone, always +#[replicated(kind = "hero", id = 4, every_patch, of = Hero)] // never rate-thinned +``` + +- Clients see entities within their view radius, under a per-Delta byte + budget (4 KiB) ranked by priority. Deferred entities gain priority until + they are sent. +- Far entities update less often (`HostConfig::interest.update_rates`): + - within 0.5 of the radius: every patch; + - up to 0.8: every 2nd patch; + - beyond that: every 4th. + + Creates and removes are never held. `UpdateRates::every_patch()` turns + the rates off. +- Interest across borders: place each zone in the world and give its + players' view radius, once: + + ```rust + fn origin(&self) -> Option { // world = origin + zone-local + let (x, y) = self.room.room; + Some(Origin::new(f64::from(x) * 48.0, f64::from(y) * 48.0)) + } + fn view_radius(&self) -> Option { Some(VIEW_RADIUS) } + ``` + + The client then reports the player once per frame or tick + (`client.setPosition(p.x, p.y, me.zoneId)`). The SDK focuses every + watched neighbour on the player in that neighbour's coordinates. The + default `Zone::on_observer_focus` gives that watcher the same view + radius there. No coordinate math in the game. Zones without an origin: + `watchZones(...).setFocus(at)`. +- Each changed entity is encoded once per patch and shared by every client + that was up to date. A dense room costs selection plus copying, not one + encode per client. +- The wire format and the JS SDK's prediction are unchanged by these + knobs. + +## The world around: watched cells (CQRS) + +World cells (hood, borough, city, content rollout, dev settings) are the +write model. Each zone keeps a pushed read model of the cells it declares, +and each view decodes into a plain struct that becomes a normal zone +message: + +```rust +impl CelldZone for MobPit { + fn watch(zone: &str) -> Watches { + Watches::new() + .cell(HOOD_KIND, &hood_of(zone), |read: HoodRead| read.state.map(PitMessage::hood)) + .cell(CITY_KIND, CITY_SHARD, |read: CityRead| read.state.map(PitMessage::city)) + } +} +``` + +A cell opts in with one field and two calls: + +```rust +pub struct HoodCell { cell: AggregateCell, env: Env, watchers: CellWatchers } +// fetch: self.watchers.serve(&self.env, &self.cell, req, read_hood, sessions).await +// alarm: self.watchers.alarm(&self.env, &self.cell, read_hood).await +``` + +How it behaves: +- **Reads.** A zone reads each watched cell on wake. The read leaves an + in-memory lease on the cell; nothing is written. +- **Pushes.** The cell pushes `{topic, version, view}` after a commit or + alarm that changes the view. A heartbeat that only bumps the version + pushes nothing. +- **Ordering.** The zone applies only newer versions. +- **Repair.** The zone re-reads every 45 ± 15 s, which renews its lease + and repairs a lost push. +- **Sleeping zones.** A sleeping zone is never woken by a push. +- **Scale.** Cost grows with view changes × watchers, not with zones × + seconds. +- **Other reads.** `refresh`/`refresh_every` remain for async reads that + are not cell views. + +## Hits and walls: one raycast + +Declare level geometry once in `on_create`, then ask one question per +shot. The answer is the closest entity or wall, so walls block shots +without game-side geometry code: + +```rust +ctx.set_colliders(pillars.iter() + .map(|p| Collider::cylinder([p.x, p.y], p.r, PILLAR_HEIGHT)) + .fold(Colliders::new(), Colliders::with)); + +let ray = Ray::new(origin, dir, RANGE).ignoring(shooter); +let hit = ctx.raycast_where(time, &ray, |id| alive(id)); // or raycast_shot(timing, ..) +let at = hit.map_or_else(|| ray.at(ray.max_dist), |h| h.point); +``` + +- `RayHit` holds `target` (`Entity(id)` or `Static(index)`), `distance`, + `point` and `normal`; use the point and normal to place the impact. +- A ray's layer `mask` and `ignoring(id)` skip the shooter and + transparent things. Use an `accept` filter for game state the layers + don't hold. +- `ctx.colliders().push_out(at, radius, mask)` keeps server-moved bodies + out of walls. +- Client prediction is not affected: `sim` does its own movement. +- Ramps (`Collider::ramp`), terrain (`Colliders::with_terrain`, a + `Heightfield`) and `ground_at(at, mask)` + `walkable(normal)` give a + step what it needs to climb, slide and fall; the step itself is yours. +- `bounce(ray, n, cast)` reflects a ray off static surfaces; + `trace.stop_at(colliders, layers)` cuts it at walls it must not pass; + `trace.exit_box(origin, half)` says where it leaves the zone's square. + +## Zone to zone: messages and leases + +A running zone can tell another one something with its own message type: +`ctx.send_zone(to, &msg)`, or `ctx.send_zone_for(player, to, &msg)` to +bind that player's verified principal (the target gets it as +`ZoneSender::principal` and may `ctx.emit_fact_as(principal, fact)`). +Handle them in `Zone::on_zone_message`. + +- Delivery is best effort and never wakes a sleeping zone; repeats of one + envelope are dropped. Don't trust a sender's coordinates: check that the + sender is a neighbour and the values are finite and in range. +- To move an entity into the zone next door without losing or doubling + it, lease it (`distributed_game::lease`): + `const LEASE: LeaseTimings = LeaseTimings::new(beat, lease, grace)` + (rejects anything but `beat < lease < grace`). Home: `LEASE.lend(..)`, + `lent.heard(tick)` on each beat (reply renew, or recall if not lent), + bring it back when `lent.overdue(tick)`. Holder: `LEASE.hold(..)`, + `held.renew(tick)` on a renewal, and each tick `held.poll(tick)`: + `Beat` (send one), `Lapsed` (drop it) or `Held`. +- Keep the lent entity's zone and transfer in the home zone's snapshot + and lend it again on restore; ids come from `TransferIds::next(boot_epoch)`. +- Example: `examples/game/server/rooms/src/zone/cross.rs` (lasers and + chasing mobs crossing Mob Pit rooms). + +## Checking your work + +- `cargo test -p distributed_game --all-features` runs the native host, the + facts, replication and interest management with in-memory sinks. +- `mobpit-load` (in `examples/game/server/examples`) measures: + - `--steps 32,64` for one room; + - `--steps 64x1,128x1` for many rooms; + - `--no-attack` for movement only; + - `--var KEY=VALUE` for a worker var on every run. +- Compare work, not wall clock. Each step prints a `work` line from the + rooms' `WorkCounters` (`GET /zones/{zone}/info` → `work`) and the + watched cells' `__watchers` counts: records encoded and sent per patch, + updates held by rates, bytes per frame, fact commands, cell requests and + outbox deletes per room-second, world reads and pushes per room-minute. + Counts do not depend on machine load; timings do. +- A/B one switch with interleaved runs of the same build: + `--ab VAR=VAL --pairs 3` runs A,B then B,A … (fresh celld each) and + prints the median of each side and of the per-pair change. Switches: + `ZONE_FACT_BATCH=1` (fact batches off), `ZONE_UPDATE_RATES=0` (update + rates off), `ZONE_WORLD_PUSH=0` (watched cells polled every second + instead of pushed). Read timings only as these interleaved medians. diff --git a/distributed_cli/skills/distributed-graphql/SKILL.md b/distributed_cli/skills/distributed-graphql/SKILL.md index a4d5f05d9..9b31455a0 100644 --- a/distributed_cli/skills/distributed-graphql/SKILL.md +++ b/distributed_cli/skills/distributed-graphql/SKILL.md @@ -43,7 +43,7 @@ pub fn permissions() -> ModelPermissions { } ``` -3. Register it in `src/query/mod.rs` via `graphql_models!(builder, order_view)` or +3. Register it in `src/query/mod.rs` with `.model::(order_view::permissions())`. ### Roles @@ -66,9 +66,12 @@ let service = service.try_with_graphql(engine)?; // GET /graphql — GraphiQL IDE when `.graphiql(true)` ``` -`POST /{command}` stays off unless you call `with_http_command_routes()`. -Call that only for an intentional, independently authenticated ingress. -GraphQL mutations do not need it. +`POST /{command}` stays off. For an intentional, independently authenticated +ingress, expose that one command with `with_http_command(command, edge)`: the +edge checks the request and returns the dispatch (command ID, input, session, +principal). `with_http_command_routes()` opens every command to trusted-proxy +headers. Behind a gateway, `command_gateway_routes(binding)` keeps every +command path on the service. GraphQL mutations need none of these. Build the executable `Service` first and pass that exact instance to `GraphqlEngineBuilder::service`. For `Atomic`, pass the repository handle @@ -100,10 +103,11 @@ ambient `DevHeaders` on the public scaffold path. | Mode | Use | |---|---| | `OidcBearer` | Public API — validate `Authorization: Bearer` JWT (access token) | -| `Hybrid` | Bearer preferred; else gateway-injected headers | -| `TrustedProxy` | Mesh — strip client identity denylist at process | +| `Gateway` | Behind an authenticating gateway — `IdentityConfig::gateway(header, secret)`; headers are trusted only with the shared secret | | `DevHeaders` | Local GraphiQL / unit tests only (explicit opt-in) | +There is no default mode: `build()` fails without `.identity(..)`. + Wire via `.identity(distributed::graphql::public_oidc_identity_from_env())`. Never trust raw client `x-user-id` / `x-roles` on a public edge. diff --git a/distributed_cli/skills/distributed-usage/SKILL.md b/distributed_cli/skills/distributed-usage/SKILL.md index 28abd0413..ce5693cfa 100644 --- a/distributed_cli/skills/distributed-usage/SKILL.md +++ b/distributed_cli/skills/distributed-usage/SKILL.md @@ -28,8 +28,7 @@ plane — not open-coded per dialect in `main`. **Always reach for the highest-level API first.** The macros and one-call conveniences are the recommended surface, not sugar: -- `#[sourced]` — not `#[digest]` + `aggregate!()` (its lower-level building - blocks, still supported but only for granular control you actually need) +- `#[sourced]` — not a hand-written `Aggregate` impl and replay match - `#[derive(Snapshot)]` / `#[derive(ReadModel)]` — not hand-written snapshot payloads or table plumbing - `routes!` + `Service::routes(..)` — not manual handler registration @@ -149,8 +148,10 @@ Rules that prevent real bugs: - **Always set an explicit `aggregate_type`** — the default is the Rust type name, which silently changes the durable stream identity if the type is renamed. -- **Event methods become fallible.** `#[event]`/`#[digest]` methods return - `SourcedResult` even without a declared return type — call them with `?`. +- **Event methods become fallible.** An `#[event]` method declares no return + type and may not use `?` or `return`; the macro makes it return + `SourcedResult`, so call it with `?`. Validate in the public method that + calls it. - Event names are lowercase past-tense facts (`"initialized"`, `"completed"`). Use `when = ` for intentional idempotent/no-op transitions so they record nothing; use explicit validation when the API promises a rejection. @@ -160,60 +161,73 @@ Rules that prevent real bugs: ## Command handlers -For a browser-facing GraphQL service, use the typed causal command path instead -of exposing a raw `Context`/`serde_json::Value` handler as the mutation contract: +Every command is typed, authorized by its declared roles, and recorded in the +command ledger under its command ID, whichever ingress delivers it: - declare `.typed_command(typed_command:: | Eventual | Atomic>(...))` on the executable route; - implement the handler with `CausalCommandContext` and return a `PreparedCommand<_>` so the framework owns commit, ledger, outbox, and projection atomicity; -- bind that exact `Service` through `GraphqlEngineBuilder::service`, configure - public OIDC. HTTP command routes stay off; browser writes use - only the GraphQL command proxy. Call `.with_http_command_routes()` only for - an intentional non-GraphQL ingress; +- for a browser-facing GraphQL service, bind that exact `Service` through + `GraphqlEngineBuilder::service` and configure public OIDC. HTTP command + routes stay off; browser writes use only the GraphQL command proxy. Expose + one command for an intentional non-GraphQL ingress with + `.with_http_command(command, edge)` (the edge authenticates the request); + call `.with_http_command_routes()` only behind a trusted proxy; - generate the strictly typed client with `distributed client`. Use the `distributed-graphql` skill for the complete route, consistency, -authorization, and client-generation contract. The raw handler form below -remains valid for intentional non-GraphQL transports. +authorization, and client-generation contract. -One module per handler, exporting `COMMAND` (or `EVENT`/`EVENTS`), a `guard`, -and an async `handle`: +One module per command, exporting `COMMAND`, a `command()` declaration, and an +async `handle`: ```rust pub const COMMAND: &str = "todo.initialize"; -pub fn guard(ctx: &Context) -> bool { - ctx.has_fields(&["id", "task"]) +pub fn command() -> TypedCommand> { + typed_command::>(COMMAND).roles(["user"]) } -pub async fn handle(ctx: &Context<'_, Repo>) -> Result { - let input = ctx.input::()?; - let mut todo = Todo::default(); +pub async fn handle( + ctx: &CausalCommandContext<'_, Todo>, + input: CreateTodo, +) -> Result>, HandlerError> { + let mut todo = ctx.repo().create(); todo.initialize(input.id.clone(), input.task)?; - ctx.repo().publish_events().commit(&mut todo).await?; - Ok(json!({ "id": input.id })) + ctx.repo() + .publish_events() + .commit(todo)? + .succeeded(TodoCreated { id: input.id }) } ``` -Register with `routes!` and serve — the same handlers work over direct -dispatch, HTTP (`microsvc::serve`, feature `http`), gRPC (feature `grpc`), and -the bus: +`CreateTodo` derives `Deserialize` + `distributed::CommandInput`; `TodoCreated` +derives `Serialize` + `distributed::CommandOutput`. Register on the route +bundle and serve — the same handlers work over in-process dispatch +(`Service::dispatch_causal`), HTTP (`microsvc::serve`, feature `http`; body +`{ "commandId", "input" }`), gRPC (feature `grpc`), and the bus (the command +declares `TRANSPORT_ROLE` and the message carries an id): ```rust -let routes = distributed::routes!( - Routes::new().with_repo(repo.queued().aggregate::()), - command handlers::todo_create, - command handlers::todo_complete, -); +let routes = Routes::new() + .with_repo(repo.queued().aggregate::()) + .typed_command(handlers::todo_create::command()) + .handle(handlers::todo_create::handle) + .typed_command(handlers::todo_complete::command()) + .handle(handlers::todo_complete::handle); let service = Service::new() .named("todo-api") .with_http_command_routes() // required for POST /{command}; GraphQL stays off by default .routes(routes); -service.with_bus(bus).run(RunOptions::idempotent()).await?; +service.with_bus(bus).run(RunOptions::default()).await?; // until the process ends ``` +Event handlers export `EVENT`/`EVENTS`, a `guard`, and an async +`handle(ctx: &Context<'_, D>) -> Result`, and register +with `distributed::routes!(routes, event handlers::todo_projection)`. + ## Publication is explicit (outbox) An `EventRecord` is write-side replay history, **not** automatically a domain diff --git a/distributed_cli/src/cli.rs b/distributed_cli/src/cli.rs index a8f46d0cc..dcfeaa71c 100644 --- a/distributed_cli/src/cli.rs +++ b/distributed_cli/src/cli.rs @@ -1,14 +1,14 @@ -//! The `distributed` command surface: clap types plus the [`run_distributed`] -//! dispatcher. Generation lives in the crate's `generate`/`atlas` modules and -//! the `describe`/`schema` harness in `manifest_harness`; this module maps -//! flags onto those types and owns filesystem / process side effects. +//! The `distributed` command surface: clap types plus the [`run`] dispatcher. +//! Generation lives in the crate's `generate`/`atlas` modules and the +//! `describe`/`schema` harness in `manifest_harness`; this module maps flags +//! onto those types and owns filesystem / process side effects. //! -//! Host CLIs (for example `hops`) may mount [`ServiceArgs`] under a nested -//! service command and dispatch with [`run`], re-exporting rather than -//! reimplementing service-related commands. +//! A host CLI (for example `hops`) mounts the same [`DistributedArgs`] under +//! its own command and dispatches with [`run`], naming that command so `build` +//! and `dev` can call back into the host executable. use clap::{ArgGroup, Args, Subcommand, ValueEnum}; -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeMap; use std::error::Error; use std::ffi::OsString; use std::fs; @@ -19,8 +19,8 @@ use std::sync::Arc; use std::time::Duration; use crate::client_compiler::{ - compile_client, ClientCompileInput, ClientDocument, ClientSurfaceSelector, - GeneratedClientFile, GeneratedClientProject, + check_client_project, compile_client, write_client_project, ClientCompileInput, ClientDocument, + ClientSurfaceIdentity, }; use crate::contracts::{ contracts_accept, contracts_check, unknown_scope_diagnostic, ContractAcceptScope, @@ -28,10 +28,9 @@ use crate::contracts::{ }; use crate::js_framework::watch_local_javascript; use crate::lifecycle::{ - activate_lifecycle_project_generation, discover_lifecycle_project, run_lifecycle_build, - run_lifecycle_dev, run_lifecycle_project_build, run_lifecycle_project_dev, - DiscoveredLifecycleProject, LifecycleActivation, LifecycleBuildOptions, LifecycleBuildRequest, - LifecycleCheckBaseline, LifecycleDevOptions, LifecycleProjectDevOptions, + activate_lifecycle_project_generation, discover_lifecycle_project, run_lifecycle_project_build, + run_lifecycle_project_dev, DiscoveredLifecycleProject, LifecycleActivation, + LifecycleBuildRequest, LifecycleProjectDevOptions, UiAdapter, }; use crate::manifest_harness::{ resolve_target_manifest_path, run_manifest_harness, HarnessMode, HarnessOptions, @@ -44,10 +43,10 @@ use crate::{ MetricsTarget, PostCreateAction, ServiceScaffoldSpec, ServiceTransport, StoreTarget, }; -const DISTRIBUTED_MANIFEST_SCHEMA_VERSION: u64 = 1; -const DISTRIBUTED_CLIENT_MANIFEST_VERSION: u64 = 2; +const DISTRIBUTED_MANIFEST_SCHEMA_VERSION: u64 = 3; -/// Top-level standalone CLI arguments for the `distributed` binary. +/// The command tree, for the `distributed` binary and for a host CLI that +/// mounts it under one of its own commands. #[derive(Args, Debug)] pub struct DistributedArgs { #[command(subcommand)] @@ -71,11 +70,17 @@ pub enum DistributedCommands { Client(ClientArgs), /// Compile the service's authorized client Surface manifest as JSON ClientManifest(ClientManifestArgs), + /// Print a distributed_game zone's GameSurface (kinds, input, events) as JSON + GameManifest(GameManifestArgs), + /// Generate typed TypeScript for a distributed_game zone from its GameSurface + GameClient(GameClientArgs), + /// Compile a distributed_game zone's `#[predict]` step and `#[game_pure]` functions to WebAssembly for its generated client + GameWasm(GameWasmArgs), /// Render schema artifacts (SQL or an Atlas Operator resource) from a read-model catalog Schema(SchemaArgs), /// Extract the embedded Distributed agent skills into a project Skills(SkillsArgs), - /// Internal bounded readiness probe used by `distributed dev`. + /// Internal bounded readiness probe used by `dev`. #[command(name = "__probe", hide = true)] Probe(ProbeArgs), /// Internal local Distributed JavaScript source watcher. @@ -100,54 +105,11 @@ pub struct JavascriptWatchArgs { pub project_root: PathBuf, } -/// Library adapter for embedding service-related commands under another CLI. -#[derive(Args, Debug)] -pub struct ServiceArgs { - #[command(subcommand)] - pub command: ServiceCommands, -} - -#[derive(Subcommand, Debug)] -pub enum ServiceCommands { - /// Build one coherent application generation - Build(BuildArgs), - /// Run one coherent local application supervisor - Dev(DevArgs), - /// Scaffold a new Distributed microservice crate - #[command(alias = "create")] - Scaffold(ScaffoldArgs), - /// Print a service's explicit ApplicationManifest as JSON - Describe(DescribeArgs), - /// Compile role/application-scoped GraphQL operations into client artifacts - Client(ClientArgs), - /// Compile the service's authorized client Surface manifest as JSON - ClientManifest(ClientManifestArgs), - /// Render schema artifacts (SQL or an Atlas Operator resource) from a read-model catalog - Schema(SchemaArgs), - /// Extract the embedded Distributed agent skills into a project - Skills(SkillsArgs), - /// Internal bounded readiness probe used by `hops service dev`. - #[command(name = "__probe", hide = true)] - Probe(ProbeArgs), - /// Internal local Distributed JavaScript source watcher. - #[command(name = "__js-watch", hide = true)] - JavascriptWatch(JavascriptWatchArgs), -} - #[derive(Args, Debug)] pub struct BuildArgs { /// Project to build; defaults to the current directory #[arg(value_name = "PROJECT")] pub project: Option, - /// Deprecated alias for the project directory - #[arg(long, hide = true, conflicts_with = "project")] - pub root: Option, - /// Advanced contract-catalog override, relative to the project - #[arg(long, hide = true)] - pub catalog: Option, - /// Advanced lifecycle-config override, relative to the project - #[arg(long, hide = true)] - pub config: Option, /// Advanced generation-store override, relative to the project #[arg(long)] pub out: Option, @@ -173,15 +135,6 @@ pub struct DevArgs { /// Project to run; defaults to the current directory #[arg(value_name = "PROJECT")] pub project: Option, - /// Deprecated alias for the project directory - #[arg(long, hide = true, conflicts_with = "project")] - pub root: Option, - /// Advanced contract-catalog override, relative to the project - #[arg(long, hide = true)] - pub catalog: Option, - /// Advanced lifecycle-config override, relative to the project - #[arg(long, hide = true)] - pub config: Option, /// Advanced generation-store override, relative to the project #[arg(long)] pub out: Option, @@ -210,7 +163,7 @@ pub struct ContractsCheckArgs { #[arg(long, default_value = ".")] pub root: PathBuf, /// Path to the contract catalog JSON (relative to root or absolute) - #[arg(long, default_value = "contracts/catalog.json")] + #[arg(long, default_value = "distributed.contracts.json")] pub catalog: PathBuf, /// Output format #[arg(long, value_enum, default_value = "human")] @@ -397,7 +350,7 @@ pub struct DescribeArgs { /// Path to the local Distributed crate. #[arg(long)] pub distributed_path: Option, - /// Exact wasm-pack JavaScript launcher owned by the resolved framework package. + /// Exact wasm-pack JavaScript launcher installed beside the resolved framework package. #[arg(long, hide = true)] pub wasm_pack_launcher: Option, } @@ -428,6 +381,77 @@ pub struct ClientManifestArgs { pub distributed_path: Option, } +#[derive(Args, Debug)] +pub struct GameManifestArgs { + /// Game crate directory. Defaults to the current directory. + #[arg(long, default_value = ".")] + pub path: PathBuf, + /// Cargo.toml of the game crate. Overrides --path. + #[arg(long)] + pub manifest_path: Option, + /// Cargo package to inspect when the manifest belongs to a workspace. + #[arg(long)] + pub package: Option, + /// Comma-delimited feature list for the game crate. + #[arg(long, value_delimiter = ',')] + pub features: Vec, + /// Disable default features on the game crate dependency. + #[arg(long)] + pub no_default_features: bool, + /// Surface export function returning `distributed_game::GameSurface`. + /// Defaults to `::game_surface`; e.g. `game_demos::arena::game_surface`. + #[arg(long)] + pub entrypoint: Option, + /// Write the JSON here instead of stdout. + #[arg(long)] + pub out: Option, +} + +#[derive(Clone, Copy, Debug, ValueEnum)] +pub enum GameImportExtension { + /// `./schema.ts` (Vite, Node type stripping, `allowImportingTsExtensions`) + Ts, + /// `./schema.js` (tsc NodeNext emit) + Js, + /// `./schema` (bundler resolution) + None, +} + +#[derive(Args, Debug)] +pub struct GameClientArgs { + /// GameSurface JSON (from `distributed game-manifest`). + #[arg(long)] + pub manifest: PathBuf, + /// Generated TypeScript directory (owned by the generator). + #[arg(long)] + pub out: PathBuf, + /// Verify the generated files are current without writing anything. + #[arg(long)] + pub check: bool, + /// Import specifier extension between generated files. + #[arg(long, value_enum, default_value = "ts")] + pub import_extension: GameImportExtension, +} + +#[derive(Args, Debug)] +pub struct GameWasmArgs { + /// GameSurface JSON (from `distributed game-manifest`) with a predicted step or pure functions. + #[arg(long)] + pub manifest: PathBuf, + /// Generated client directory; the module is written to `/wasm/.wasm`. + #[arg(long)] + pub out: PathBuf, + /// Cargo project containing the package that declares the step. + #[arg(long, default_value = ".")] + pub path: PathBuf, + /// Cargo.toml of that project. Overrides --path. + #[arg(long)] + pub manifest_path: Option, + /// Verify the module is current without compiling. + #[arg(long)] + pub check: bool, +} + #[derive(Args, Debug)] #[command(group( ArgGroup::new("client_surface") @@ -623,16 +647,24 @@ impl From for GitopsPromoteTarget { } } -/// Dispatch the standalone `distributed` binary command tree. -pub fn run_distributed(args: &DistributedArgs) -> Result<(), Box> { +/// Dispatch a parsed command. +/// +/// `command_prefix` is how this command tree is reached from the running +/// executable: empty for the `distributed` binary, `["service"]` for a host +/// that mounts it as `hops service`. `build` and `dev` start the executable +/// again with that prefix for their internal commands. +pub fn run(args: &DistributedArgs, command_prefix: &[&str]) -> Result<(), Box> { match &args.command { - DistributedCommands::Build(build) => run_build(build, &[]), - DistributedCommands::Dev(dev) => run_dev(dev, &[]), + DistributedCommands::Build(build) => run_build(build, command_prefix), + DistributedCommands::Dev(dev) => run_dev(dev, command_prefix), DistributedCommands::Contracts(contracts) => run_contracts(contracts), DistributedCommands::Scaffold(scaffold) => run_scaffold(scaffold), DistributedCommands::Describe(describe) => run_describe(describe), DistributedCommands::Client(client) => run_client(client), DistributedCommands::ClientManifest(client) => run_client_manifest(client), + DistributedCommands::GameManifest(game) => run_game_manifest(game), + DistributedCommands::GameClient(game) => run_game_client(game), + DistributedCommands::GameWasm(game) => run_game_wasm(game), DistributedCommands::Schema(schema) => run_schema(schema), DistributedCommands::Skills(skills) => match &skills.command { SkillsCommands::Init(init) => run_skills_init(init), @@ -670,50 +702,15 @@ fn run_probe(args: &ProbeArgs) -> Result<(), Box> { .into()) } -/// Dispatch a parsed service command. Host CLIs (for example `hops service`) -/// call this without mounting the aggregate contracts surface. -pub fn run(args: &ServiceArgs) -> Result<(), Box> { - match &args.command { - ServiceCommands::Build(build) => run_build(build, &["service"]), - ServiceCommands::Dev(dev) => run_dev(dev, &["service"]), - ServiceCommands::Scaffold(scaffold) => run_scaffold(scaffold), - ServiceCommands::Describe(describe) => run_describe(describe), - ServiceCommands::Client(client) => run_client(client), - ServiceCommands::ClientManifest(client) => run_client_manifest(client), - ServiceCommands::Schema(schema) => run_schema(schema), - ServiceCommands::Skills(skills) => match &skills.command { - SkillsCommands::Init(init) => run_skills_init(init), - SkillsCommands::List => run_skills_list(), - }, - ServiceCommands::Probe(probe) => run_probe(probe), - ServiceCommands::JavascriptWatch(watch) => run_javascript_watch(watch), - } -} - -#[derive(Debug)] -enum ResolvedLifecycleProject { - Discovered(Box), - Files { - project: PathBuf, - workspace: PathBuf, - catalog: PathBuf, - config: PathBuf, - out: PathBuf, - }, -} - +/// The project a `build` or `dev` invocation names, discovered from its Cargo +/// workspace. The project's `.env` files are loaded first: discovery reads the +/// addresses they may set. fn resolve_lifecycle_project( project: Option<&Path>, - legacy_root: Option<&Path>, - catalog: Option<&Path>, - config: Option<&Path>, out: Option<&Path>, command_prefix: &[&str], -) -> Result> { - if project.is_some() && legacy_root.is_some() { - return Err("pass a project path or --root, not both".into()); - } - let requested = project.or(legacy_root).unwrap_or_else(|| Path::new(".")); +) -> Result> { + let requested = project.unwrap_or_else(|| Path::new(".")); let project = requested.canonicalize().map_err(|error| { format!( "failed to resolve lifecycle project `{}`: {error}", @@ -727,85 +724,14 @@ fn resolve_lifecycle_project( ) .into()); } - - let uses_file_adapter = legacy_root.is_some() || catalog.is_some() || config.is_some(); - if !uses_file_adapter { - load_project_environment(&project)?; - let executable = std::env::current_exe()?; - return discover_lifecycle_project(&project, executable, command_prefix, out) - .map(Box::new) - .map(ResolvedLifecycleProject::Discovered) - .map_err(Into::into); - } - if catalog.is_some() != config.is_some() && legacy_root.is_none() { - return Err("advanced lifecycle overrides require both --catalog and --config".into()); - } - - let resolve_input = |provided: Option<&Path>, default: &str, label: &str| { - let requested = provided.unwrap_or_else(|| Path::new(default)); - let candidate = if requested.is_absolute() { - requested.to_path_buf() - } else { - project.join(requested) - }; - candidate.canonicalize().map_err(|error| { - let guidance = if provided.is_none() { - format!( - "; expected this project to contain `{default}` (run from the project directory or pass the project path)" - ) - } else { - String::new() - }; - format!( - "failed to resolve lifecycle {label} `{}`: {error}{guidance}", - candidate.display() - ) - }) - }; - let catalog = resolve_input(catalog, "distributed.contracts.json", "contract catalog")?; - let config = resolve_input(config, "distributed.lifecycle.json", "config")?; - let requested_out = out.unwrap_or_else(|| Path::new("dist/distributed")); - let out = if requested_out.is_absolute() { - requested_out.to_path_buf() - } else { - project.join(requested_out) - }; - - let mut failures = Vec::new(); - let mut workspace = None; - for candidate in project.ancestors() { - if !catalog.starts_with(candidate) - || !config.starts_with(candidate) - || !out.starts_with(candidate) - { - continue; - } - match ContractCatalog::from_path_at_root(&catalog, candidate) { - Ok(_) => { - workspace = Some(candidate.to_path_buf()); - break; - } - Err(error) => failures.push(format!("{}: {error}", candidate.display())), - } - } - let workspace = workspace.ok_or_else(|| { - let detail = failures - .last() - .map(|failure| format!(" Last attempted root: {failure}")) - .unwrap_or_default(); - format!( - "unable to discover the workspace for lifecycle project `{}`; no project ancestor resolves every catalog source.{detail}", - project.display() - ) - })?; - - Ok(ResolvedLifecycleProject::Files { - project, - workspace, - catalog, - config, + load_project_environment(&project)?; + let executable = std::env::current_exe()?; + Ok(discover_lifecycle_project( + &project, + executable, + command_prefix, out, - }) + )?) } fn load_project_environment(project: &Path) -> Result<(), Box> { @@ -829,104 +755,85 @@ fn load_project_environment(project: &Path) -> Result<(), Box> { Ok(()) } +/// The flag a `build` or `dev` session polls to stop. +/// +/// SIGINT, SIGTERM and SIGHUP all set it (on Windows: Ctrl-C, Ctrl-Break and +/// the console closing), so the session ends the same way for each: it stops +/// its process groups and returns. The session's children do not share its +/// process group, so this handler is the only thing that stops them. +fn stop_on_signals() -> Result, Box> { + let stop = Arc::new(AtomicBool::new(false)); + let signaled = Arc::clone(&stop); + ctrlc::set_handler(move || signaled.store(true, Ordering::SeqCst))?; + Ok(stop) +} + fn run_build(args: &BuildArgs, command_prefix: &[&str]) -> Result<(), Box> { - let resolved = resolve_lifecycle_project( - args.project.as_deref(), - args.root.as_deref(), - args.catalog.as_deref(), - args.config.as_deref(), - args.out.as_deref(), - command_prefix, - )?; - let (report, detail) = match &resolved { - ResolvedLifecycleProject::Discovered(project) => { - if args.check { - prepare_project_javascript(project, true)?; - } else { - build_project_runtime(project)?; - prepare_project_javascript(project, false)?; - if let Some(ui) = &project.ui { - prepare_ui_dependencies(project, ui)?; - } - prepare_project_wasm_pures(project).map_err(|error| { - contextualize_project_generation_error( - project, - ProjectGenerationPhase::ApplicationPreflight, - error, - ) - })?; - } - eprintln!( - "distributed build: introspecting typed application {} (the first run may compile its harness)", - project.application_package - ); - let report = run_lifecycle_project_build( - &project.plan, - &LifecycleBuildRequest { - check: args.check, - check_baseline: LifecycleCheckBaseline::ActiveGeneration, - lock_timeout: Duration::from_millis(args.lock_timeout_ms), - nodes: None, - activation_inputs: None, - cancel: None, - activation: LifecycleActivation::Deferred, - }, + let project = + resolve_lifecycle_project(args.project.as_deref(), args.out.as_deref(), command_prefix)?; + let project = &project; + let stop = stop_on_signals()?; + if args.check { + prepare_project_javascript(project, true, &stop)?; + } else { + build_project_runtime(project, &stop)?; + prepare_project_javascript(project, false, &stop)?; + if let Some(ui) = &project.ui { + prepare_ui_dependencies(project, ui, &stop)?; + } + prepare_project_wasm_pures(project, &stop).map_err(|error| { + contextualize_project_generation_error( + project, + ProjectGenerationPhase::ApplicationPreflight, + error, ) - .map_err(|error| { - contextualize_project_generation_error( - project, - ProjectGenerationPhase::LifecycleBuild, - error, - ) - })?; - if !args.check { - build_project_ui(project, &report)?; - activate_lifecycle_project_generation( - &project.plan, - &report, - Duration::from_millis(args.lock_timeout_ms), - )?; - } - (report, Some(project)) - } - ResolvedLifecycleProject::Files { - workspace, - catalog, - config, - out, - .. - } => ( - run_lifecycle_build(&LifecycleBuildOptions { - root: workspace.clone(), - catalog: catalog.clone(), - config: config.clone(), - out: out.clone(), - check: args.check, - lock_timeout: Duration::from_millis(args.lock_timeout_ms), - nodes: None, - activation_inputs: None, - cancel: None, - })?, - None, - ), - }; + })?; + } + eprintln!( + "distributed build: introspecting typed application {} (the first run may compile its harness)", + project.application_package + ); + let report = run_lifecycle_project_build( + &project.plan, + &LifecycleBuildRequest { + check: args.check, + lock_timeout: Duration::from_millis(args.lock_timeout_ms), + nodes: None, + activation_inputs: None, + cancel: Some(Arc::clone(&stop)), + activation: LifecycleActivation::Deferred, + }, + ) + .map_err(|error| { + contextualize_project_generation_error( + project, + ProjectGenerationPhase::LifecycleBuild, + error, + ) + })?; + if !args.check { + build_project_ui(project, &report, &stop)?; + activate_lifecycle_project_generation( + &project.plan, + &report, + Duration::from_millis(args.lock_timeout_ms), + )?; + } match args.output { LifecycleOutput::Json => println!("{}", serde_json::to_string(&report)?), LifecycleOutput::Human => { let mode = if report.check { "check" } else { "build" }; - if let Some(project) = detail { - println!( - "distributed {mode}: project={} application={} runtime={}{}", - project.name, - project.application_package, - project.runtime_binary, - project - .ui - .as_ref() - .map(|ui| format!(" ui={}", ui.display())) - .unwrap_or_default() - ); - } + println!( + "distributed {mode}: project={} application={} runtime={}{}", + project.name, + project.application_package, + project.runtime_binary, + project + .ui + .as_ref() + .map(|ui| format!(" ui={}", ui.root.display())) + .unwrap_or_default() + ); println!( "lifecycle graph: {} generation={} release={} nodes={}", if report.ok { "ok" } else { "drift" }, @@ -951,7 +858,10 @@ fn run_build(args: &BuildArgs, command_prefix: &[&str]) -> Result<(), Box Result<(), Box> { +fn build_project_runtime( + project: &DiscoveredLifecycleProject, + stop: &AtomicBool, +) -> Result<(), Box> { eprintln!( "distributed build: compiling Rust runtime {} ({})", project.runtime_binary, project.runtime_package @@ -967,6 +877,7 @@ fn build_project_runtime(project: &DiscoveredLifecycleProject) -> Result<(), Box OsString::from(&project.runtime_binary), ], "Rust runtime build", + stop, ) } @@ -1005,7 +916,10 @@ fn is_application_introspection_failure(phase: ProjectGenerationPhase, error: &s } } -fn prepare_project_wasm_pures(project: &DiscoveredLifecycleProject) -> Result<(), Box> { +fn prepare_project_wasm_pures( + project: &DiscoveredLifecycleProject, + stop: &AtomicBool, +) -> Result<(), Box> { if project.ui.is_none() { return Ok(()); } @@ -1020,6 +934,7 @@ fn prepare_project_wasm_pures(project: &DiscoveredLifecycleProject) -> Result<() distributed_path: Some(project.distributed_root.clone()), }, HarnessMode::DescribeJson, + Some(stop), )?; let manifest: serde_json::Value = serde_json::from_str(&json)?; validate_manifest_json(&manifest)?; @@ -1027,11 +942,12 @@ fn prepare_project_wasm_pures(project: &DiscoveredLifecycleProject) -> Result<() .javascript .as_ref() .zip(project.ui.as_ref()) - .map(|(javascript, ui)| javascript.wasm_pack_launcher(ui)); + .map(|(javascript, ui)| javascript.wasm_pack_launcher(&ui.root)); build_declared_wasm_pures( &manifest, &project.cargo_root.join("Cargo.toml"), wasm_pack_launcher.as_deref(), + Some(stop), )?; Ok(()) } @@ -1039,43 +955,38 @@ fn prepare_project_wasm_pures(project: &DiscoveredLifecycleProject) -> Result<() fn build_project_ui( project: &DiscoveredLifecycleProject, generation: &crate::lifecycle::LifecycleBuildReport, + stop: &AtomicBool, ) -> Result<(), Box> { if let Some(ui) = &project.ui { - let ui_root = ui; - prepare_ui_dependencies(project, &ui_root)?; - eprintln!( - "distributed build: checking SvelteKit UI {}", - ui_root.display() - ); - run_project_ui_script(project, generation, ui_root, "check", true)?; - eprintln!( - "distributed build: compiling SvelteKit UI {}", - ui_root.display() - ); - run_project_ui_script(project, generation, ui_root, "build", false)?; + prepare_ui_dependencies(project, ui, stop)?; + for (step, args) in [("check", &ui.check), ("build", &ui.build)] { + if args.is_empty() { + continue; + } + eprintln!("distributed build: UI {step} in {}", ui.root.display()); + run_project_ui_command(project, generation, ui, step, args, stop)?; + } } Ok(()) } -fn run_project_ui_script( +fn run_project_ui_command( project: &DiscoveredLifecycleProject, generation: &crate::lifecycle::LifecycleBuildReport, - ui_root: &Path, - script: &str, - if_present: bool, + ui: &UiAdapter, + step: &str, + args: &[String], + stop: &AtomicBool, ) -> Result<(), Box> { let lifecycle_dir = if project.plan.out.is_absolute() { project.plan.out.clone() } else { project.plan.root.join(&project.plan.out) }; - let mut command = Command::new("npm"); - command.args(["run", script]); - if if_present { - command.arg("--if-present"); - } - let status = command - .current_dir(ui_root) + let mut command = Command::new(&ui.package_manager); + command + .args(args) + .current_dir(&ui.root) .env("DISTRIBUTED_LIFECYCLE_OWNS_CLIENT_COMPILE", "1") .env("DISTRIBUTED_LIFECYCLE_PROJECT_ROOT", &project.plan.root) .env("DISTRIBUTED_LIFECYCLE_DIR", lifecycle_dir) @@ -1083,25 +994,31 @@ fn run_project_ui_script( "DISTRIBUTED_LIFECYCLE_GENERATION_ID", &generation.generation_id, ) - .status()?; - if !status.success() { - return Err(format!("SvelteKit UI `{script}` failed with {status}").into()); - } - Ok(()) + .env( + crate::lifecycle::LIFECYCLE_CLI_EXECUTABLE_ENV, + &project.plan.cli_executable, + ); + finish_project_command( + crate::process::run(&mut command, Some(stop))?, + &format!("UI {step}"), + ) } fn prepare_ui_dependencies( project: &DiscoveredLifecycleProject, - ui_root: &Path, + ui: &UiAdapter, + stop: &AtomicBool, ) -> Result<(), Box> { - ensure_ui_dependencies(ui_root)?; + if !ui.root.join("node_modules").is_dir() { + install_ui_dependencies(ui, stop)?; + } let Some(javascript) = &project.javascript else { return Ok(()); }; - if let Err(error) = javascript.verify_installed(ui_root) { - eprintln!("distributed: refreshing SvelteKit dependencies because {error}"); - install_ui_dependencies(ui_root)?; - javascript.verify_installed(ui_root)?; + if let Err(error) = javascript.verify_installed(&ui.root) { + eprintln!("distributed: refreshing UI dependencies because {error}"); + install_ui_dependencies(ui, stop)?; + javascript.verify_installed(&ui.root)?; } Ok(()) } @@ -1109,129 +1026,96 @@ fn prepare_ui_dependencies( fn prepare_project_javascript( project: &DiscoveredLifecycleProject, check: bool, + stop: &AtomicBool, ) -> Result<(), Box> { if let Some(javascript) = &project.javascript { - javascript.prepare(&project.cargo_root, check)?; + javascript.prepare(&project.cargo_root, check, Some(stop))?; if check { let ui = project .ui .as_ref() .ok_or("Distributed JavaScript package resolved without a UI root")?; - javascript.verify_installed(ui)?; + javascript.verify_installed(&ui.root)?; } } Ok(()) } -fn ensure_ui_dependencies(ui_root: &Path) -> Result<(), Box> { - if ui_root.join("node_modules").is_dir() { - return Ok(()); - } - install_ui_dependencies(ui_root) -} - -fn install_ui_dependencies(ui_root: &Path) -> Result<(), Box> { - let install = if ui_root.join("package-lock.json").is_file() { - "ci" - } else { - "install" - }; +fn install_ui_dependencies(ui: &UiAdapter, stop: &AtomicBool) -> Result<(), Box> { + let install = ui.install.clone().unwrap_or_else(|| { + let locked = ui.root.join("package-lock.json").is_file(); + vec![if locked { "ci" } else { "install" }.to_string()] + }); eprintln!( - "distributed: installing SvelteKit dependencies with `npm {install}` in {}", - ui_root.display() + "distributed: installing UI dependencies with `{} {}` in {}", + ui.package_manager, + install.join(" "), + ui.root.display() ); - run_project_command( - ui_root, - "npm", - &[OsString::from(install)], - "SvelteKit dependency install", + let mut command = Command::new(&ui.package_manager); + command.args(install).current_dir(&ui.root); + finish_project_command( + crate::process::run(&mut command, Some(stop))?, + "UI dependency install", ) } +/// Run a build step of the session: in its own process group, until it exits +/// or the session is stopped. fn run_project_command( cwd: &Path, program: &str, args: &[OsString], label: &str, + stop: &AtomicBool, ) -> Result<(), Box> { - let status = Command::new(program).args(args).current_dir(cwd).status()?; - if !status.success() { - return Err(format!("{label} failed with {status}").into()); + let mut command = Command::new(program); + command.args(args).current_dir(cwd); + finish_project_command(crate::process::run(&mut command, Some(stop))?, label) +} + +fn finish_project_command( + status: Option, + label: &str, +) -> Result<(), Box> { + match status { + Some(status) if status.success() => Ok(()), + Some(status) => Err(format!("{label} failed with {status}").into()), + None => Err(format!("{label} was stopped").into()), } - Ok(()) } fn run_dev(args: &DevArgs, command_prefix: &[&str]) -> Result<(), Box> { - let resolved = resolve_lifecycle_project( - args.project.as_deref(), - args.root.as_deref(), - args.catalog.as_deref(), - args.config.as_deref(), - args.out.as_deref(), - command_prefix, - )?; - let stop = Arc::new(AtomicBool::new(false)); - let signal_stop = Arc::clone(&stop); - ctrlc::set_handler(move || signal_stop.store(true, Ordering::SeqCst))?; - let report = match resolved { - ResolvedLifecycleProject::Discovered(project) => { - prepare_project_javascript(&project, false)?; - if let Some(ui) = &project.ui { - prepare_ui_dependencies(&project, ui)?; - } - eprintln!( - "distributed dev: project={} api={} ui={} (Ctrl-C to stop)", - project.name, - project.runtime_binary, - project - .ui - .as_ref() - .map(|ui| ui.display().to_string()) - .unwrap_or_else(|| "none".to_string()) - ); - run_lifecycle_project_dev(&LifecycleProjectDevOptions { - project: project.plan, - build: LifecycleBuildRequest { - check: false, - check_baseline: LifecycleCheckBaseline::Workspace, - lock_timeout: Duration::from_millis(args.lock_timeout_ms), - nodes: None, - activation_inputs: None, - cancel: Some(Arc::clone(&stop)), - activation: LifecycleActivation::Immediate, - }, - stop: Arc::clone(&stop), - progress: true, - })? - } - ResolvedLifecycleProject::Files { - project, - workspace, - catalog, - config, - out, - } => { - eprintln!( - "lifecycle dev: starting project={} and waiting for the initial generation (Ctrl-C to stop)", - project.display() - ); - run_lifecycle_dev(&LifecycleDevOptions { - build: LifecycleBuildOptions { - root: workspace, - catalog, - config, - out, - check: false, - lock_timeout: Duration::from_millis(args.lock_timeout_ms), - nodes: None, - activation_inputs: None, - cancel: Some(Arc::clone(&stop)), - }, - stop: Arc::clone(&stop), - progress: true, - })? - } - }; + let project = + resolve_lifecycle_project(args.project.as_deref(), args.out.as_deref(), command_prefix)?; + let stop = stop_on_signals()?; + prepare_project_javascript(&project, false, &stop)?; + if let Some(ui) = &project.ui { + prepare_ui_dependencies(&project, ui, &stop)?; + } + eprintln!( + "distributed dev: project={} api={} ui={} (Ctrl-C to stop)", + project.name, + project.runtime_binary, + project + .ui + .as_ref() + .map(|ui| ui.root.display().to_string()) + .unwrap_or_else(|| "none".to_string()) + ); + let report = run_lifecycle_project_dev(&LifecycleProjectDevOptions { + project: project.plan, + build: LifecycleBuildRequest { + check: false, + lock_timeout: Duration::from_millis(args.lock_timeout_ms), + nodes: None, + activation_inputs: None, + cancel: Some(Arc::clone(&stop)), + activation: LifecycleActivation::Immediate, + }, + stop: Arc::clone(&stop), + progress: true, + })?; println!( "lifecycle dev: stopped initial={} final={} rebuilds={}", report.initial_generation, report.final_generation, report.rebuilds @@ -1649,6 +1533,7 @@ fn run_describe(args: &DescribeArgs) -> Result<(), Box> { distributed_path: args.distributed_path.clone(), }, HarnessMode::DescribeJson, + None, )?; let envelope: serde_json::Value = serde_json::from_str(&json)?; validate_manifest_json(&envelope)?; @@ -1662,6 +1547,7 @@ fn run_describe(args: &DescribeArgs) -> Result<(), Box> { &envelope, &cargo_manifest, args.wasm_pack_launcher.as_deref(), + None, )?; } println!("{}", serde_json::to_string_pretty(&envelope)?); @@ -1672,8 +1558,6 @@ fn run_describe(args: &DescribeArgs) -> Result<(), Box> { const MAX_CLIENT_MANIFEST_BYTES: usize = 16 * 1024 * 1024; const MAX_CLIENT_DOCUMENT_BYTES: usize = 1024 * 1024; -const MAX_GENERATED_CLIENT_ARTIFACT_BYTES: usize = 8 * 1024 * 1024; -const MAX_GENERATED_CLIENT_FILES: usize = 8_192; fn run_client(args: &ClientArgs) -> Result<(), Box> { let manifest_source = @@ -1683,7 +1567,7 @@ fn run_client(args: &ClientArgs) -> Result<(), Box> { format!("parse client manifest {}: {error}", args.manifest.display()).into() })?; let selector = match (&args.role, &args.surface) { - (Some(role), None) => ClientSurfaceSelector::role(role.clone()), + (Some(role), None) => ClientSurfaceIdentity::role(role.clone()), (None, Some(surface)) => { // Prefer explicit CLI roles when both lists are provided; otherwise // take eligible/schema roles from the application surface in the @@ -1700,14 +1584,16 @@ fn run_client(args: &ClientArgs) -> Result<(), Box> { } else { application_roles_from_manifest(&manifest, surface)? }; - ClientSurfaceSelector::application(surface.clone(), eligible_roles, schema_roles) + ClientSurfaceIdentity::application(surface.clone(), eligible_roles, schema_roles) } _ => { return Err("pass exactly one of --role or --surface ".into()); } }; let documents = collect_client_documents(&args.documents)?; - let project = compile_client(ClientCompileInput::new(manifest, selector, documents))?; + let project = compile_client(ClientCompileInput::from_manifest_json( + manifest, selector, documents, + )?)?; if args.check { check_client_project(&args.out, &project)?; @@ -1873,421 +1759,104 @@ fn portable_relative_path(path: &Path) -> Result> { Ok(parts.join("/")) } -fn generated_client_path( - root: &Path, - file: &GeneratedClientFile, -) -> Result> { - let relative = Path::new(&file.path); - if relative.is_absolute() - || relative - .components() - .any(|component| !matches!(component, Component::Normal(_))) - { - return Err(format!("compiler produced unsafe generated path `{}`", file.path).into()); - } - Ok(root.join(relative)) -} - -fn write_client_project( - root: &Path, - project: &GeneratedClientProject, -) -> Result<(), Box> { - validate_generated_client_files(&project.files)?; - validate_client_write_targets(root, &project.files)?; - let stale_files = stale_generated_client_files(root, project)?; - validate_client_output_convergence(root, project, &stale_files)?; - fs::create_dir_all(root)?; - - for path in stale_files { - fs::remove_file(&path).map_err(|error| { - format!( - "remove stale generated client artifact {}: {error}", - path.display() - ) - })?; - } - - // Provenance is written last so an interrupted run never advertises a new - // complete generation before its operation modules exist. - let mut files = project.files.iter().collect::>(); - files.sort_by_key(|file| (file.path == "manifest.json", file.path.as_str())); - for file in files { - let path = generated_client_path(root, file)?; - if let Some(parent) = path.parent() { - fs::create_dir_all(parent)?; - } - fs::write(&path, &file.contents) - .map_err(|error| format!("write generated artifact {}: {error}", path.display()))?; - } - Ok(()) -} - -fn validate_client_output_convergence( - root: &Path, - project: &GeneratedClientProject, - stale_files: &[PathBuf], -) -> Result<(), Box> { - let expected = project - .files - .iter() - .map(|file| file.path.clone()) - .collect::>(); - let stale = stale_files - .iter() - .map(|path| { - path.strip_prefix(root) - .map_err(|_| { - format!( - "stale generated client path {} escaped output {}", - path.display(), - root.display() - ) - }) - .and_then(|relative| { - portable_relative_path(relative).map_err(|error| error.to_string()) - }) - }) - .collect::, _>>()?; - let unexpected = collect_generated_client_paths(root)? - .into_iter() - .filter(|path| !expected.contains(path) && !stale.contains(path)) - .collect::>(); - if unexpected.is_empty() { - return Ok(()); - } - Err(format!( - "generated output contains files without current or previous compiler ownership:\n {}; refusing to write until they are moved or removed", - unexpected.join("\n ") - ) - .into()) -} - -fn validate_client_write_targets( - root: &Path, - files: &[GeneratedClientFile], -) -> Result<(), Box> { - match fs::symlink_metadata(root) { - Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_dir() => { - return Err(format!( - "generated output {} must be a real directory, not a symlink or other entry", - root.display() - ) - .into()) - } - Ok(_) => {} - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), - Err(error) => { - return Err(format!("inspect generated output {}: {error}", root.display()).into()) - } - } - - for file in files { - let relative = Path::new(&file.path); - let mut current = root.to_path_buf(); - let component_count = relative.components().count(); - for (index, component) in relative.components().enumerate() { - let Component::Normal(component) = component else { - unreachable!("generated paths were validated before write-target inspection") - }; - current.push(component); - let metadata = match fs::symlink_metadata(¤t) { - Ok(metadata) => metadata, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => break, - Err(error) => { - return Err(format!( - "inspect generated client path {}: {error}", - current.display() - ) - .into()) - } - }; - let is_target = index + 1 == component_count; - let valid = if is_target { - metadata.is_file() && !metadata.file_type().is_symlink() - } else { - metadata.is_dir() && !metadata.file_type().is_symlink() - }; - if !valid { - return Err(format!( - "generated client path {} contains a symlink or incompatible entry", - current.display() - ) - .into()); - } - } - } +fn run_client_manifest(args: &ClientManifestArgs) -> Result<(), Box> { + let json = run_manifest_harness( + &HarnessOptions { + path: args.path.clone(), + manifest_path: args.manifest_path.clone(), + package: args.package.clone(), + features: args.features.clone(), + no_default_features: args.no_default_features, + entrypoint: args.entrypoint.clone(), + distributed_path: args.distributed_path.clone(), + }, + HarnessMode::ClientManifest, + None, + )?; + let manifest: serde_json::Value = serde_json::from_str(&json)?; + validate_client_manifest_json(&manifest)?; + println!("{}", serde_json::to_string_pretty(&manifest)?); Ok(()) } -fn stale_generated_client_files( - root: &Path, - project: &GeneratedClientProject, -) -> Result, Box> { - let provenance_path = root.join("manifest.json"); - let metadata = match fs::symlink_metadata(&provenance_path) { - Ok(metadata) => metadata, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), - Err(error) => { - return Err(format!( - "inspect previous generated client manifest {}: {error}", - provenance_path.display() - ) - .into()) - } - }; - if metadata.file_type().is_symlink() || !metadata.is_file() { - return Err(format!( - "previous generated client manifest {} must be a regular file", - provenance_path.display() - ) - .into()); - } - - let source = read_utf8_bounded( - &provenance_path, - MAX_CLIENT_MANIFEST_BYTES, - "previous generated client manifest", +fn run_game_manifest(args: &GameManifestArgs) -> Result<(), Box> { + let json = run_manifest_harness( + &HarnessOptions { + path: args.path.clone(), + manifest_path: args.manifest_path.clone(), + package: args.package.clone(), + features: args.features.clone(), + no_default_features: args.no_default_features, + entrypoint: args.entrypoint.clone(), + distributed_path: None, + }, + HarnessMode::GameManifest, + None, )?; - let provenance: serde_json::Value = serde_json::from_str(&source).map_err(|error| { - format!( - "parse previous generated client manifest {}: {error}; refusing to guess stale-file ownership", - provenance_path.display() - ) - })?; - let compiler_manifest_version = provenance - .get("compiler_manifest_version") - .and_then(serde_json::Value::as_u64); - if !matches!(compiler_manifest_version, Some(1 | 2)) { - return Err(format!( - "previous generated client manifest {} has an unsupported compiler_manifest_version; refusing to guess stale-file ownership", - provenance_path.display() - ) - .into()); - } - let operations = provenance - .get("operations") - .and_then(serde_json::Value::as_array) - .ok_or_else(|| { - format!( - "previous generated client manifest {} is missing operations; refusing to guess stale-file ownership", - provenance_path.display() - ) - })?; - let expected = project - .files - .iter() - .map(|file| file.path.as_str()) - .collect::>(); - let mut stale = BTreeSet::new(); - for (index, operation) in operations.iter().enumerate() { - let module_path = operation - .get("module_path") - .and_then(serde_json::Value::as_str) - .ok_or_else(|| { - format!( - "previous generated client manifest {} operations[{index}] is missing module_path; refusing to guess stale-file ownership", - provenance_path.display() - ) - })?; - validate_previous_client_module_path(module_path)?; - if !expected.contains(module_path) { - stale.insert(module_path.to_string()); - } - } - - if compiler_manifest_version == Some(1) && !expected.contains("routes.ts") { - stale.insert("routes.ts".to_string()); - } - - let mut paths = Vec::with_capacity(stale.len()); - for relative in stale { - let path = root.join(&relative); - let metadata = match fs::symlink_metadata(&path) { - Ok(metadata) => metadata, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue, - Err(error) => { - return Err(format!( - "inspect stale generated client artifact {}: {error}", - path.display() - ) - .into()) + crate::game_client::validate_game_surface(&json)?; + let value: serde_json::Value = serde_json::from_str(&json)?; + let pretty = serde_json::to_string_pretty(&value)? + "\n"; + match &args.out { + Some(path) => { + if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { + fs::create_dir_all(parent)?; } - }; - if metadata.file_type().is_symlink() || !metadata.is_file() { - return Err(format!( - "stale generated client artifact {} must be a regular file", - path.display() - ) - .into()); + fs::write(path, pretty) + .map_err(|error| format!("write game surface {}: {error}", path.display()))?; } - let contents = read_utf8_bounded( - &path, - MAX_GENERATED_CLIENT_ARTIFACT_BYTES, - "stale generated client artifact", - )?; - let has_compatible_marker = contents - .starts_with("/** GENERATED by distributed client. Do not edit. */") - || (compiler_manifest_version == Some(1) - && relative == "routes.ts" - && contents.starts_with( - "/** GENERATED framework-neutral `@load` ownership plan. */", - )); - if !has_compatible_marker { - return Err(format!( - "refusing to remove {} because its compiler ownership marker is missing", - path.display() - ) - .into()); - } - paths.push(path); - } - Ok(paths) -} - -fn validate_previous_client_module_path(path: &str) -> Result<(), Box> { - let mut components = Path::new(path).components(); - let valid = matches!(components.next(), Some(Component::Normal(value)) if value == "operations") - && matches!(components.next(), Some(Component::Normal(value)) if Path::new(value).extension().is_some_and(|extension| extension == "ts")) - && components.next().is_none(); - if !valid { - return Err(format!( - "previous compiler provenance contains unsafe operation module path `{path}`; refusing to remove it" - ) - .into()); + None => print!("{pretty}"), } Ok(()) } -fn check_client_project( - root: &Path, - project: &GeneratedClientProject, -) -> Result<(), Box> { - validate_generated_client_files(&project.files)?; - let expected = project - .files - .iter() - .map(|file| (file.path.clone(), file.contents.as_str())) - .collect::>(); - let actual_paths = collect_generated_client_paths(root)?; - let mut drift = Vec::new(); - - for (path, contents) in &expected { - let full_path = root.join(path); - match fs::read_to_string(&full_path) { - Ok(actual) if actual == *contents => {} - Ok(_) => drift.push(format!("changed {path}")), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - drift.push(format!("missing {path}")); - } - Err(error) => { - return Err( - format!("read generated artifact {}: {error}", full_path.display()).into(), - ) - } - } - } - for path in actual_paths { - if !expected.contains_key(&path) { - drift.push(format!("unexpected {path}")); - } - } - if drift.is_empty() { - return Ok(()); - } - drift.sort(); - Err(format!( - "generated Distributed client artifacts are stale:\n {}\nrun `distributed client` without --check to regenerate", - drift.join("\n ") - ) - .into()) -} - -fn validate_generated_client_files(files: &[GeneratedClientFile]) -> Result<(), Box> { - if files.is_empty() || files.len() > MAX_GENERATED_CLIENT_FILES { - return Err(format!( - "compiler produced {} files; expected 1..={MAX_GENERATED_CLIENT_FILES}", +fn run_game_client(args: &GameClientArgs) -> Result<(), Box> { + let source = read_utf8_bounded(&args.manifest, MAX_CLIENT_MANIFEST_BYTES, "game surface")?; + let ext = match args.import_extension { + GameImportExtension::Ts => crate::game_client::ImportExtension::Ts, + GameImportExtension::Js => crate::game_client::ImportExtension::Js, + GameImportExtension::None => crate::game_client::ImportExtension::None, + }; + let files = crate::game_client::generate_game_client(&source, ext) + .map_err(|error| format!("{}: {error}", args.manifest.display()))?; + if args.check { + crate::game_client::check_game_client(&args.out, &files)?; + println!( + "Game client for {} is current ({} files)", + args.manifest.display(), files.len() - ) - .into()); - } - let mut paths = BTreeSet::new(); - for file in files { - let _ = generated_client_path(Path::new("."), file)?; - if !paths.insert(file.path.as_str()) { - return Err(format!("compiler produced duplicate path `{}`", file.path).into()); - } + ); + } else { + crate::game_client::write_game_client(&args.out, &files)?; + println!( + "Generated {} game client files at {}", + files.len(), + args.out.display() + ); } Ok(()) } -fn collect_generated_client_paths(root: &Path) -> Result, Box> { - let mut files = BTreeSet::new(); - match fs::symlink_metadata(root) { - Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_dir() => { - return Err(format!( - "generated output {} must be a real directory, not a symlink or other entry", - root.display() - ) - .into()) - } - Ok(_) => {} - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(files), - Err(error) => { - return Err(format!("inspect generated output {}: {error}", root.display()).into()) +fn run_game_wasm(args: &GameWasmArgs) -> Result<(), Box> { + let source = read_utf8_bounded(&args.manifest, MAX_CLIENT_MANIFEST_BYTES, "game surface")?; + let cargo_manifest = args + .manifest_path + .clone() + .unwrap_or_else(|| args.path.join("Cargo.toml")); + let outcome = crate::game_wasm::run_game_wasm(&crate::game_wasm::GameWasmOptions { + surface: &source, + cargo_manifest: &cargo_manifest, + out: &args.out, + check: args.check, + }) + .map_err(|error| format!("{}: {error}", args.manifest.display()))?; + match outcome { + crate::game_wasm::GameWasmOutcome::Current(path) => { + println!("Compiled game module {} is current", path.display()) } - } - let mut pending = vec![(root.to_path_buf(), PathBuf::new())]; - while let Some((directory, relative)) = pending.pop() { - for entry in fs::read_dir(&directory)? { - let entry = entry?; - let file_type = entry.file_type()?; - let next_relative = relative.join(entry.file_name()); - if file_type.is_symlink() { - return Err(format!( - "generated output contains unsupported symlink {}", - entry.path().display() - ) - .into()); - } - if file_type.is_dir() { - pending.push((entry.path(), next_relative)); - } else if file_type.is_file() { - files.insert(portable_relative_path(&next_relative)?); - if files.len() > MAX_GENERATED_CLIENT_FILES { - return Err(format!( - "generated output {} exceeds {MAX_GENERATED_CLIENT_FILES} files", - root.display() - ) - .into()); - } - } else { - return Err(format!( - "generated output contains unsupported entry {}", - entry.path().display() - ) - .into()); - } + crate::game_wasm::GameWasmOutcome::Built(path) => { + println!("Compiled game module to {}", path.display()) } } - Ok(files) -} - -fn run_client_manifest(args: &ClientManifestArgs) -> Result<(), Box> { - let json = run_manifest_harness( - &HarnessOptions { - path: args.path.clone(), - manifest_path: args.manifest_path.clone(), - package: args.package.clone(), - features: args.features.clone(), - no_default_features: args.no_default_features, - entrypoint: args.entrypoint.clone(), - distributed_path: args.distributed_path.clone(), - }, - HarnessMode::ClientManifest, - )?; - let manifest: serde_json::Value = serde_json::from_str(&json)?; - validate_client_manifest_json(&manifest)?; - println!("{}", serde_json::to_string_pretty(&manifest)?); Ok(()) } @@ -2307,6 +1876,7 @@ fn run_schema(args: &SchemaArgs) -> Result<(), Box> { distributed_path: args.distributed_path.clone(), }, mode, + None, ).map_err(|err| -> Box { let msg = err.to_string(); if msg.contains("graphql_sdl") || msg.contains("no method named `graphql_sdl`") { @@ -2516,36 +2086,22 @@ fn github_repo_create_args(slug: &str) -> Vec<&str> { } fn validate_manifest_json(envelope: &serde_json::Value) -> Result<(), Box> { - let Some(schema_version) = envelope + let schema_version = envelope .get("schema_version") .and_then(serde_json::Value::as_u64) - else { - return Err("manifest JSON is missing numeric schema_version".into()); - }; + .ok_or("manifest JSON is missing numeric schema_version")?; if schema_version != DISTRIBUTED_MANIFEST_SCHEMA_VERSION { - return Err(format!( - "unsupported Distributed manifest schema version {schema_version}; expected {DISTRIBUTED_MANIFEST_SCHEMA_VERSION}" - ) - .into()); + return Err(format!("unsupported Distributed manifest schema version {schema_version}; expected {DISTRIBUTED_MANIFEST_SCHEMA_VERSION}").into()); } - // `describe` emits ApplicationManifest JSON (logical composition artifact), - // not the retired DistributedManifestEnvelope { project: ... } shape. if envelope .get("name") .and_then(serde_json::Value::as_str) - .map(str::is_empty) - .unwrap_or(true) + .filter(|name| !name.is_empty()) + .is_none() { return Err("application manifest JSON is missing non-empty string name".into()); } - for field in [ - "modules", - "commands", - "events", - "projections", - "models", - "surfaces", - ] { + for field in ["modules", "surfaces"] { if envelope .get(field) .and_then(serde_json::Value::as_array) @@ -2554,6 +2110,13 @@ fn validate_manifest_json(envelope: &serde_json::Value) -> Result<(), Box Result<(), Box Result<(), Box> { - let Some(version) = manifest - .get("manifest_version") - .and_then(serde_json::Value::as_u64) - else { - return Err("client manifest JSON is missing numeric manifest_version".into()); - }; - if version != DISTRIBUTED_CLIENT_MANIFEST_VERSION { - return Err(format!( - "unsupported Distributed client manifest version {version}; expected {DISTRIBUTED_CLIENT_MANIFEST_VERSION}" - ) - .into()); - } - if manifest - .get("protocol_version") - .and_then(serde_json::Value::as_u64) - .is_none() - { - return Err("client manifest JSON is missing numeric protocol_version".into()); - } - for field in ["service_id", "schema_fingerprint", "protocol_fingerprint"] { - if manifest - .get(field) - .and_then(serde_json::Value::as_str) - .is_none() - { - return Err(format!("client manifest JSON is missing string {field}").into()); - } - } - for field in ["surface", "capabilities"] { - if manifest - .get(field) - .and_then(serde_json::Value::as_object) - .is_none() - { - return Err(format!("client manifest JSON is missing object {field}").into()); - } - } - for field in ["scalar_codecs", "models", "roots", "commands", "projectors"] { - if manifest - .get(field) - .and_then(serde_json::Value::as_array) - .is_none() - { - return Err(format!("client manifest JSON is missing array {field}").into()); - } - } - Ok(()) + serde_json::from_value::(manifest.clone()) + .map(drop) + .map_err(|error| format!("invalid Distributed client manifest: {error}").into()) } pub(crate) fn resolve_distributed_path( @@ -2836,32 +2356,13 @@ mod tests { } #[test] - fn client_manifest_validator_accepts_only_current_version() { - let manifest = serde_json::json!({ - "manifest_version": DISTRIBUTED_CLIENT_MANIFEST_VERSION, - "protocol_version": 1, - "service_id": "orders", - "schema_fingerprint": "sha256:schema", - "protocol_fingerprint": "sha256:protocol", - "surface": {}, - "capabilities": {}, - "scalar_codecs": [], - "models": [], - "roots": [], - "commands": [], - "projectors": [], - "projection_programs": [], - "projection_bindings": [] - }); - validate_client_manifest_json(&manifest).expect("current manifest version"); - - let mut stale = manifest; - stale["manifest_version"] = serde_json::json!(3); - let error = validate_client_manifest_json(&stale) + fn client_manifest_validator_rejects_other_versions() { + let error = validate_client_manifest_json(&serde_json::json!({"manifest_version": 3})) .expect_err("pre-release v3 manifests must be rejected"); - assert!(error.to_string().contains(&format!( - "version 3; expected {DISTRIBUTED_CLIENT_MANIFEST_VERSION}" - ))); + assert!( + error.to_string().contains("version 3; expected 2"), + "{error}" + ); } #[test] @@ -2881,42 +2382,6 @@ mod tests { )); } - #[test] - fn client_generation_removes_owned_version_one_routes_artifact() { - let fixture = tempfile::tempdir().expect("create generated client fixture"); - let root = fixture.path(); - fs::write( - root.join("manifest.json"), - r#"{"compiler_manifest_version":1,"operations":[]}"#, - ) - .expect("write legacy manifest"); - fs::write( - root.join("routes.ts"), - "/** GENERATED framework-neutral `@load` ownership plan. */\nexport const DISTRIBUTED_ROUTES = [];\n", - ) - .expect("write legacy routes"); - let current_manifest = - "{\"compiler_manifest_version\":2,\"operations\":[]}\n".to_string(); - let project = GeneratedClientProject { - files: vec![GeneratedClientFile { - path: "manifest.json".to_string(), - contents: current_manifest.clone(), - }], - operations: Vec::new(), - islands: Vec::new(), - schema_fingerprint: "sha256:schema".to_string(), - protocol_fingerprint: "sha256:protocol".to_string(), - }; - - write_client_project(root, &project).expect("upgrade legacy generated client"); - - assert!(!root.join("routes.ts").exists()); - assert_eq!( - fs::read_to_string(root.join("manifest.json")).expect("read current manifest"), - current_manifest - ); - } - #[test] fn optional_github_repo_reports_the_flag_on_error() { let err = parse_optional_github_repo(Some("missing-repo"), "--github") diff --git a/distributed_cli/src/client_compiler/command_manifest/confirmations.rs b/distributed_cli/src/client_compiler/command_manifest/confirmations.rs deleted file mode 100644 index 4ec19f294..000000000 --- a/distributed_cli/src/client_compiler/command_manifest/confirmations.rs +++ /dev/null @@ -1,181 +0,0 @@ -use std::collections::{BTreeMap, BTreeSet}; - -use crate::client_compiler::manifest::{ - ManifestCommand, ManifestConfirmationKind, ManifestConsistencyKind, ManifestField, - ManifestModel, ManifestProjector, -}; -use crate::client_compiler::ClientCompileError; - -use super::effects::{require_model, validate_expression, validate_key}; -use super::support::{command_error, invalid, nonempty}; -use super::CommandManifestValidation; - -// Mirrors `projection_protocol::MAX_PROJECTION_EVIDENCE_BATCH_ITEMS`, which is -// not exported across the `distributed`/`distributed_cli` package boundary. -const MAX_CONFIRMATIONS: usize = 128; - -pub(super) fn validate_confirmations( - command: &ManifestCommand, - models: &BTreeMap, - projectors: &BTreeMap<&str, &ManifestProjector>, - report: &mut CommandManifestValidation, -) -> Result<(), ClientCompileError> { - let confirmations = command.extensions.confirmations.as_ref(); - match (command.extensions.consistency.kind, confirmations) { - (ManifestConsistencyKind::Eventual, None) => { - return Err(command_error( - command, - "client.manifest.command_confirmations", - "eventual consistency requires confirmations", - )); - } - (ManifestConsistencyKind::Atomic, Some(_)) => { - return Err(command_error( - command, - "client.manifest.command_confirmations", - "atomic consistency cannot declare asynchronous confirmations", - )); - } - _ => {} - } - let Some(confirmations) = confirmations else { - if command.extensions.consistency.kind == ManifestConsistencyKind::Succeeded { - report - .commands_requiring_revalidation - .insert(command.name.clone()); - } - return Ok(()); - }; - if confirmations.version != 1 { - return Err(command_error( - command, - "client.manifest.command_confirmations", - "confirmations.version must be 1", - )); - } - if confirmations.expected.len() > MAX_CONFIRMATIONS { - return Err(command_error( - command, - "client.manifest.command_confirmations", - format!( - "declares {} projector confirmations; maximum is {MAX_CONFIRMATIONS}", - confirmations.expected.len() - ), - )); - } - match confirmations.kind { - ManifestConfirmationKind::Unavailable => { - if !confirmations.expected.is_empty() { - return Err(command_error( - command, - "client.manifest.command_confirmations", - "unavailable confirmations must have an empty expected inventory", - )); - } - report - .commands_requiring_revalidation - .insert(command.name.clone()); - return Ok(()); - } - ManifestConfirmationKind::Finite if confirmations.expected.is_empty() => { - return Err(command_error( - command, - "client.manifest.command_confirmations", - "finite confirmations must contain at least one expected target", - )); - } - ManifestConfirmationKind::Finite => {} - } - - let mut seen = BTreeSet::new(); - for confirmation in &confirmations.expected { - let projector = projectors - .get(confirmation.projector.as_str()) - .copied() - .ok_or_else(|| { - command_error( - command, - "client.manifest.confirmation_projector", - format!( - "confirmation references unknown projector `{}`", - confirmation.projector - ), - ) - })?; - if !projector.causal_confirmation - || !projector - .models - .iter() - .any(|model| model == &confirmation.model) - { - return Err(command_error( - command, - "client.manifest.confirmation_projector", - format!( - "projector `{}` is not an authorized causal owner of model `{}`", - projector.name, confirmation.model - ), - )); - } - let model = require_model(command, &confirmation.model, models)?; - validate_key(command, model, &confirmation.key, true, report)?; - if let Some(partition) = &confirmation.partition { - let expected = ManifestField { - name: "projector partition".into(), - scalar: "String".into(), - codec: "string".into(), - nullable: false, - }; - validate_expression(command, partition, &expected)?; - } - let identity = serde_json::to_string(confirmation).map_err(|error| { - command_error( - command, - "client.manifest.command_confirmations", - format!("could not canonicalize confirmation: {error}"), - ) - })?; - if !seen.insert(identity) { - return Err(command_error( - command, - "client.manifest.command_confirmations", - "repeats an expected projector confirmation", - )); - } - } - Ok(()) -} - -pub(super) fn validate_projector_inventory<'a>( - projectors: &'a [ManifestProjector], - models: &BTreeMap, -) -> Result, ClientCompileError> { - let mut result = BTreeMap::new(); - for projector in projectors { - if projector.version != 1 { - return Err(invalid( - "client.manifest.projector_version", - format!("projector `{}` must use version 1", projector.name), - )); - } - nonempty(&projector.name, "projector name")?; - for model in &projector.models { - if !models.contains_key(model) { - return Err(invalid( - "client.manifest.projector_model", - format!( - "projector `{}` references unknown model `{model}`", - projector.name - ), - )); - } - } - if result.insert(projector.name.as_str(), projector).is_some() { - return Err(invalid( - "client.manifest.duplicate_projector", - format!("duplicate projector `{}`", projector.name), - )); - } - } - Ok(result) -} diff --git a/distributed_cli/src/client_compiler/command_manifest/effects.rs b/distributed_cli/src/client_compiler/command_manifest/effects.rs index 9a295c070..5af8e3957 100644 --- a/distributed_cli/src/client_compiler/command_manifest/effects.rs +++ b/distributed_cli/src/client_compiler/command_manifest/effects.rs @@ -1,62 +1,22 @@ -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeSet; use crate::client_compiler::manifest::{ - ManifestCommand, ManifestCommandShape, ManifestEffect, ManifestEffectExpression, - ManifestEffectField, ManifestEffectKey, ManifestEffectRelationship, ManifestField, - ManifestInputDefault, ManifestModel, ManifestNormalization, ManifestProjectionPreviewSource, - ManifestTypeField, + ClientCommand, ClientCommandShape, ClientProjectionPreviewSource, CommandInputDefault, + EffectExpression, }; use crate::client_compiler::ClientCompileError; -use super::support::{command_error, constant_matches}; -use super::CommandManifestValidation; +use super::support::command_error; pub(super) fn validate_trusted_preset_inventory( - command: &ManifestCommand, + command: &ClientCommand, ) -> Result<(), ClientCompileError> { - fn expression_names<'a>(expression: &'a ManifestEffectExpression, out: &mut BTreeSet<&'a str>) { - if let ManifestEffectExpression::TrustedPreset { name } = expression { + fn expression_names<'a>(expression: &'a EffectExpression, out: &mut BTreeSet<&'a str>) { + if let EffectExpression::TrustedPreset { name } = expression { out.insert(name); } } - fn key_names<'a>(key: &'a ManifestEffectKey, out: &mut BTreeSet<&'a str>) { - for field in &key.fields { - expression_names(&field.value, out); - } - } - let mut referenced = BTreeSet::new(); - if let Some(effects) = &command.extensions.effects { - for effect in &effects.operations { - match effect { - ManifestEffect::Upsert { key, fields, .. } - | ManifestEffect::Patch { key, fields, .. } => { - key_names(key, &mut referenced); - for field in fields { - expression_names(&field.value, &mut referenced); - } - } - ManifestEffect::Delete { key, .. } => key_names(key, &mut referenced), - ManifestEffect::Link { source, target, .. } - | ManifestEffect::Unlink { source, target, .. } => { - key_names(source, &mut referenced); - key_names(target, &mut referenced); - } - ManifestEffect::InvalidateRelationship { source, .. } => { - key_names(source, &mut referenced); - } - ManifestEffect::InvalidateModel { .. } => {} - } - } - } - if let Some(confirmations) = &command.extensions.confirmations { - for confirmation in &confirmations.expected { - key_names(&confirmation.key, &mut referenced); - if let Some(partition) = &confirmation.partition { - expression_names(partition, &mut referenced); - } - } - } if let Some(direct) = &command.extensions.direct_projection { if let Some(partition) = &direct.partition { expression_names(partition, &mut referenced); @@ -65,7 +25,7 @@ pub(super) fn validate_trusted_preset_inventory( if let Some(projection) = &command.extensions.projection { for occurrence in &projection.preview_occurrences { for value in &occurrence.values { - if let ManifestProjectionPreviewSource::TrustedPreset { name, .. } = &value.source { + if let ClientProjectionPreviewSource::TrustedPreset { name, .. } = &value.source { referenced.insert(name); } } @@ -89,9 +49,9 @@ pub(super) fn validate_trusted_preset_inventory( } pub(super) fn validate_defaults( - command: &ManifestCommand, + command: &ClientCommand, version: u32, - defaults: &[ManifestInputDefault], + defaults: &[CommandInputDefault], ) -> Result<(), ClientCompileError> { if version != 1 || defaults.is_empty() { return Err(command_error( @@ -100,7 +60,7 @@ pub(super) fn validate_defaults( "input_defaults must be version 1 with at least one entry", )); } - let ManifestCommandShape::Object { definition } = &command.input else { + let ClientCommandShape::Object { definition } = &command.input else { return Err(command_error( command, "client.manifest.input_default_path", @@ -150,398 +110,3 @@ pub(super) fn validate_defaults( } Ok(()) } - -pub(super) fn validate_effect( - command: &ManifestCommand, - effect: &ManifestEffect, - models: &BTreeMap, - report: &mut CommandManifestValidation, -) -> Result<(), ClientCompileError> { - match effect { - ManifestEffect::Upsert { model, key, fields } - | ManifestEffect::Patch { model, key, fields } => { - let model = addressable_model(command, model, models)?; - validate_key(command, model, key, false, report)?; - validate_effect_fields(command, model, fields) - } - ManifestEffect::Delete { model, key } => { - let model = addressable_model(command, model, models)?; - validate_key(command, model, key, false, report) - } - ManifestEffect::Link { - relationship, - source, - target, - } - | ManifestEffect::Unlink { - relationship, - source, - target, - } => { - let (source_model, target_model) = - validate_relationship(command, relationship, models)?; - require_addressable(command, source_model)?; - require_addressable(command, target_model)?; - validate_key(command, source_model, source, false, report)?; - validate_key(command, target_model, target, false, report) - } - ManifestEffect::InvalidateModel { model } => { - require_model(command, model, models).map(|_| ()) - } - ManifestEffect::InvalidateRelationship { - relationship, - source, - } => { - let (source_model, _) = validate_relationship(command, relationship, models)?; - require_addressable(command, source_model)?; - validate_key(command, source_model, source, false, report) - } - } -} - -fn validate_effect_fields( - command: &ManifestCommand, - model: &ManifestModel, - fields: &[ManifestEffectField], -) -> Result<(), ClientCompileError> { - let identity = model - .identity() - .expect("effect model addressability checked before field validation"); - let mut names = BTreeSet::new(); - for assignment in fields { - if !names.insert(assignment.field.as_str()) { - return Err(command_error( - command, - "client.manifest.effect_field", - format!("effect repeats `{}.{}`", model.id, assignment.field), - )); - } - let field = model.field(&assignment.field).ok_or_else(|| { - command_error( - command, - "client.manifest.effect_field", - format!( - "effect references unknown field `{}.{}`", - model.id, assignment.field - ), - ) - })?; - if identity.iter().any(|key| key.name == assignment.field) { - return Err(command_error( - command, - "client.manifest.effect_field", - format!( - "effect cannot assign identity field `{}.{}`", - model.id, field.name - ), - )); - } - validate_expression(command, &assignment.value, field)?; - } - Ok(()) -} - -fn validate_relationship<'a>( - command: &ManifestCommand, - relationship: &ManifestEffectRelationship, - models: &'a BTreeMap, -) -> Result<(&'a ManifestModel, &'a ManifestModel), ClientCompileError> { - let source = require_model(command, &relationship.source_model, models)?; - let declared = source.relationship(&relationship.field).ok_or_else(|| { - command_error( - command, - "client.manifest.effect_relationship", - format!( - "effect references unknown relationship `{}.{}`", - relationship.source_model, relationship.field - ), - ) - })?; - if declared.target_model != relationship.target_model { - return Err(command_error( - command, - "client.manifest.effect_relationship", - format!( - "relationship `{}.{}` targets `{}`, not `{}`", - relationship.source_model, - relationship.field, - declared.target_model, - relationship.target_model - ), - )); - } - let target = require_model(command, &relationship.target_model, models)?; - Ok((source, target)) -} - -pub(super) fn validate_key( - command: &ManifestCommand, - model: &ManifestModel, - key: &ManifestEffectKey, - allow_embedded: bool, - report: &mut CommandManifestValidation, -) -> Result<(), ClientCompileError> { - match &model.normalization { - ManifestNormalization::Normalized { fields, .. } => { - let actual = key - .fields - .iter() - .map(|field| field.field.as_str()) - .collect::>(); - let expected = fields - .iter() - .map(|field| field.name.as_str()) - .collect::>(); - if actual != expected { - return Err(command_error( - command, - "client.manifest.effect_key", - format!( - "key for `{}` must exactly match ordered identity ({})", - model.id, - expected.join(", ") - ), - )); - } - } - ManifestNormalization::Embedded if allow_embedded => { - report - .commands_requiring_revalidation - .insert(command.name.clone()); - if key.fields.is_empty() { - return Err(command_error( - command, - "client.manifest.confirmation_key", - format!( - "embedded confirmation key for `{}` must not be empty", - model.id - ), - )); - } - let mut names = BTreeSet::new(); - if key - .fields - .iter() - .any(|field| !names.insert(field.field.as_str())) - { - return Err(command_error( - command, - "client.manifest.confirmation_key", - format!( - "embedded confirmation key for `{}` repeats a field", - model.id - ), - )); - } - } - ManifestNormalization::Embedded => { - return Err(command_error( - command, - "client.manifest.effect_identity", - format!( - "key-addressed effect cannot target embedded model `{}`", - model.id - ), - )); - } - } - for key_field in &key.fields { - let field = model.field(&key_field.field).ok_or_else(|| { - command_error( - command, - "client.manifest.effect_key", - format!( - "key for `{}` references unknown field `{}`", - model.id, key_field.field - ), - ) - })?; - validate_expression(command, &key_field.value, field)?; - } - Ok(()) -} - -pub(super) fn validate_expression( - command: &ManifestCommand, - expression: &ManifestEffectExpression, - expected: &ManifestField, -) -> Result<(), ClientCompileError> { - match expression { - ManifestEffectExpression::Input { path } => { - let (field, inherited_nullable) = input_field(command, path)?; - let json_container = - expected.scalar == "JSON" && (field.list || field.nested.is_some()); - if !json_container - && (field.list || field.nested.is_some() || field.type_name != expected.scalar) - { - return Err(command_error( - command, - "client.manifest.effect_input_type", - format!( - "input `{}` cannot populate `{}:{}`", - path.join("."), - expected.name, - expected.scalar - ), - )); - } - if (inherited_nullable || field.nullable) && !expected.nullable { - return Err(command_error( - command, - "client.manifest.effect_input_nullability", - format!( - "nullable input `{}` cannot populate non-null field `{}`", - path.join("."), - expected.name - ), - )); - } - Ok(()) - } - ManifestEffectExpression::TrustedPreset { name } => { - let descriptor = command - .extensions - .trusted_presets - .iter() - .find(|descriptor| descriptor.name == *name) - .ok_or_else(|| { - command_error( - command, - "client.manifest.effect_trusted_preset", - format!("uses undeclared trusted preset `{name}`"), - ) - })?; - if descriptor.codec != expected.codec { - return Err(command_error( - command, - "client.manifest.effect_trusted_preset", - format!( - "trusted preset `{name}` codec `{}` cannot populate `{}:{}` with codec `{}`", - descriptor.codec, - expected.name, - expected.scalar, - expected.codec - ), - )); - } - Ok(()) - } - ManifestEffectExpression::Constant { value } if constant_matches(value, expected) => Ok(()), - ManifestEffectExpression::Constant { .. } => Err(command_error( - command, - "client.manifest.effect_constant", - format!( - "constant is incompatible with field `{}` (`{}`)", - expected.name, expected.scalar - ), - )), - ManifestEffectExpression::Null if expected.nullable => Ok(()), - ManifestEffectExpression::Null => Err(command_error( - command, - "client.manifest.effect_null", - format!("null cannot populate non-null field `{}`", expected.name), - )), - } -} - -fn input_field<'a>( - command: &'a ManifestCommand, - path: &[String], -) -> Result<(&'a ManifestTypeField, bool), ClientCompileError> { - if path.is_empty() { - return Err(command_error( - command, - "client.manifest.effect_input_path", - "effect input path must not be empty", - )); - } - let ManifestCommandShape::Object { definition } = &command.input else { - return Err(command_error( - command, - "client.manifest.effect_input_path", - "effect input references require a typed object input", - )); - }; - let mut current = definition; - let mut inherited_nullable = false; - for (index, segment) in path.iter().enumerate() { - let field = current - .fields - .iter() - .find(|field| field.name == *segment) - .ok_or_else(|| { - command_error( - command, - "client.manifest.effect_input_path", - format!("effect references unknown input path `{}`", path.join(".")), - ) - })?; - if index + 1 == path.len() { - return Ok((field, inherited_nullable)); - } - if field.list { - return Err(command_error( - command, - "client.manifest.effect_input_path", - format!( - "effect input path `{}` descends through a list", - path.join(".") - ), - )); - } - inherited_nullable |= field.nullable; - current = field.nested.as_deref().ok_or_else(|| { - command_error( - command, - "client.manifest.effect_input_path", - format!( - "effect input path `{}` descends through a scalar", - path.join(".") - ), - ) - })?; - } - unreachable!("a non-empty path either resolves or returns an error") -} - -fn addressable_model<'a>( - command: &ManifestCommand, - name: &str, - models: &'a BTreeMap, -) -> Result<&'a ManifestModel, ClientCompileError> { - let model = require_model(command, name, models)?; - require_addressable(command, model)?; - Ok(model) -} - -fn require_addressable( - command: &ManifestCommand, - model: &ManifestModel, -) -> Result<(), ClientCompileError> { - if model.identity().is_some_and(|fields| !fields.is_empty()) { - Ok(()) - } else { - Err(command_error( - command, - "client.manifest.effect_identity", - format!( - "key-addressed effect cannot target embedded model `{}`", - model.id - ), - )) - } -} - -pub(super) fn require_model<'a>( - command: &ManifestCommand, - name: &str, - models: &'a BTreeMap, -) -> Result<&'a ManifestModel, ClientCompileError> { - models.get(name).ok_or_else(|| { - command_error( - command, - "client.manifest.effect_model", - format!("references unknown model `{name}`"), - ) - }) -} diff --git a/distributed_cli/src/client_compiler/command_manifest/mod.rs b/distributed_cli/src/client_compiler/command_manifest/mod.rs index 4df644050..3b5429c98 100644 --- a/distributed_cli/src/client_compiler/command_manifest/mod.rs +++ b/distributed_cli/src/client_compiler/command_manifest/mod.rs @@ -1,7 +1,7 @@ use std::collections::BTreeSet; -mod confirmations; mod effects; +mod projectors; mod protocol; mod shape; mod support; diff --git a/distributed_cli/src/client_compiler/command_manifest/projectors.rs b/distributed_cli/src/client_compiler/command_manifest/projectors.rs new file mode 100644 index 000000000..3c9ca4e56 --- /dev/null +++ b/distributed_cli/src/client_compiler/command_manifest/projectors.rs @@ -0,0 +1,40 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use crate::client_compiler::manifest::{ClientModel, ClientProjector}; +use crate::client_compiler::ClientCompileError; + +use super::support::{invalid, nonempty}; + +pub(super) fn validate_projector_inventory( + projectors: &[ClientProjector], + models: &BTreeMap, +) -> Result<(), ClientCompileError> { + let mut names = BTreeSet::new(); + for projector in projectors { + if projector.version != 1 { + return Err(invalid( + "client.manifest.projector_version", + format!("projector `{}` must use version 1", projector.name), + )); + } + nonempty(&projector.name, "projector name")?; + for model in &projector.models { + if !models.contains_key(model) { + return Err(invalid( + "client.manifest.projector_model", + format!( + "projector `{}` references unknown model `{model}`", + projector.name + ), + )); + } + } + if !names.insert(projector.name.as_str()) { + return Err(invalid( + "client.manifest.duplicate_projector", + format!("duplicate projector `{}`", projector.name), + )); + } + } + Ok(()) +} diff --git a/distributed_cli/src/client_compiler/command_manifest/protocol.rs b/distributed_cli/src/client_compiler/command_manifest/protocol.rs index 33c6ff475..28e7527ab 100644 --- a/distributed_cli/src/client_compiler/command_manifest/protocol.rs +++ b/distributed_cli/src/client_compiler/command_manifest/protocol.rs @@ -1,13 +1,12 @@ -use crate::client_compiler::manifest::{validate_exact_operation_hash, ManifestProtocolOperations}; +use crate::client_compiler::manifest::{ + command_status_operation, validate_exact_operation_hash, ClientProtocolOperations, +}; use crate::client_compiler::ClientCompileError; use super::support::invalid; -const COMMAND_STATUS_OPERATION: &str = - "query Distributed_CommandStatus($commandId: ID!) { commandStatus(commandId: $commandId) { state } }"; - pub(super) fn validate_protocol_operations( - operations: &ManifestProtocolOperations, + operations: &ClientProtocolOperations, commands_present: bool, ) -> Result<(), ClientCompileError> { if operations.version != 1 { @@ -28,7 +27,7 @@ pub(super) fn validate_protocol_operations( (None, false) => Ok(()), (Some(status), true) => { if status.name != "Distributed_CommandStatus" - || status.operation != COMMAND_STATUS_OPERATION + || status.operation != command_status_operation() { return Err(invalid( "client.manifest.command_status", diff --git a/distributed_cli/src/client_compiler/command_manifest/shape.rs b/distributed_cli/src/client_compiler/command_manifest/shape.rs index 09eba1a78..d846f4f1a 100644 --- a/distributed_cli/src/client_compiler/command_manifest/shape.rs +++ b/distributed_cli/src/client_compiler/command_manifest/shape.rs @@ -1,8 +1,8 @@ use std::collections::{BTreeMap, BTreeSet}; use crate::client_compiler::manifest::{ - ManifestCommand, ManifestCommandShape, ManifestConsistencyKind, ManifestModel, ManifestRoot, - ManifestTypeDef, RootOperation, + ClientCommand, ClientCommandShape, ClientModel, ClientRoot, ClientRootOperation, ClientTypeDef, + CommandConsistency, }; use crate::client_compiler::ClientCompileError; @@ -15,8 +15,8 @@ pub(super) enum CommandTypeKind { } pub(super) fn projected_output_typename<'a>( - command: &ManifestCommand, - models: &'a BTreeMap, + command: &ClientCommand, + models: &'a BTreeMap, ) -> Option<&'a str> { if let Some(target) = command.extensions.direct_projection.as_ref() { if let Some(model) = models.get(&target.model) { @@ -24,10 +24,10 @@ pub(super) fn projected_output_typename<'a>( } } let consistency = &command.extensions.consistency; - if consistency.kind != ManifestConsistencyKind::Atomic { + if consistency.kind != CommandConsistency::Atomic { return None; } - let ManifestCommandShape::Object { definition } = &command.output else { + let ClientCommandShape::Object { definition } = &command.output else { return None; }; models @@ -37,8 +37,8 @@ pub(super) fn projected_output_typename<'a>( } pub(super) fn occupied_surface_types( - models: &BTreeMap, - roots: &BTreeMap<(RootOperation, String), ManifestRoot>, + models: &BTreeMap, + roots: &BTreeMap<(ClientRootOperation, String), ClientRoot>, scalar_codecs: &BTreeMap, ) -> BTreeSet { let mut occupied = ["Query", "Mutation", "Subscription", "order_by"] @@ -83,17 +83,17 @@ pub(super) fn occupied_surface_types( } pub(super) fn validate_shape( - shape: &ManifestCommandShape, + shape: &ClientCommandShape, kind: CommandTypeKind, scalar_codecs: &BTreeMap, label: &str, occupied_types: &BTreeSet, allowed_occupied_type: Option<&str>, - definitions: &mut BTreeMap, + definitions: &mut BTreeMap, ) -> Result<(), ClientCompileError> { match shape { - ManifestCommandShape::None => Ok(()), - ManifestCommandShape::Object { definition } => validate_type_def( + ClientCommandShape::None => Ok(()), + ClientCommandShape::Object { definition } => validate_type_def( definition, kind, scalar_codecs, @@ -106,13 +106,13 @@ pub(super) fn validate_shape( } fn validate_type_def( - definition: &ManifestTypeDef, + definition: &ClientTypeDef, kind: CommandTypeKind, scalar_codecs: &BTreeMap, label: &str, occupied_types: &BTreeSet, allowed_occupied_type: Option<&str>, - definitions: &mut BTreeMap, + definitions: &mut BTreeMap, ) -> Result<(), ClientCompileError> { graphql_name(&definition.name, &format!("{label} type"))?; if occupied_types.contains(&definition.name) @@ -219,6 +219,12 @@ fn validate_codec( ) -> Result<(), ClientCompileError> { match scalar_codecs.get(scalar) { Some(expected) if expected == codec => Ok(()), + Some(_) + if scalar == "BigInt" + && matches!(codec, "uint8" | "uint16" | "uint32" | "uint64_safe_integer") => + { + Ok(()) + } Some(expected) => Err(invalid( "client.manifest.command_type_codec", format!("{label} codec `{codec}` does not match `{scalar}` codec `{expected}`"), @@ -229,36 +235,3 @@ fn validate_codec( )), } } - -pub(super) fn canonical_command_operation(command: &ManifestCommand) -> String { - let operation_name = format!("Client_{}", command.mutation_field); - let (variables, arguments) = match &command.input { - ManifestCommandShape::None => ("($commandId: ID!)".to_string(), "(commandId: $commandId)"), - ManifestCommandShape::Object { definition } => ( - format!("($commandId: ID!, $input: {}!)", definition.name), - "(commandId: $commandId, input: $input)", - ), - }; - let selection = match &command.output { - ManifestCommandShape::Object { definition } => { - format!(" {{ {} }}", command_selection(definition)) - } - ManifestCommandShape::None => String::new(), - }; - format!( - "mutation {operation_name}{variables} {{ {}{arguments}{selection} }}", - command.mutation_field - ) -} - -fn command_selection(definition: &ManifestTypeDef) -> String { - definition - .fields - .iter() - .map(|field| match &field.nested { - Some(nested) => format!("{} {{ {} }}", field.name, command_selection(nested)), - None => field.name.clone(), - }) - .collect::>() - .join(" ") -} diff --git a/distributed_cli/src/client_compiler/command_manifest/support.rs b/distributed_cli/src/client_compiler/command_manifest/support.rs index 96a88a5cb..64c019ca9 100644 --- a/distributed_cli/src/client_compiler/command_manifest/support.rs +++ b/distributed_cli/src/client_compiler/command_manifest/support.rs @@ -1,100 +1,8 @@ use std::collections::BTreeSet; -use base64::Engine as _; -use serde_json::Value as JsonValue; - -use crate::client_compiler::manifest::{ManifestCommand, ManifestField}; +use crate::client_compiler::manifest::ClientCommand; use crate::client_compiler::ClientCompileError; -pub(super) fn constant_matches(value: &JsonValue, expected: &ManifestField) -> bool { - if expected.scalar == "JSON" { - return true; - } - match (expected.scalar.as_str(), value) { - ("Boolean", JsonValue::Bool(_)) => true, - ("BigInt", JsonValue::Number(number)) => number.is_i64() || number.is_u64(), - ("Int", JsonValue::Number(number)) => { - number - .as_i64() - .is_some_and(|value| i32::try_from(value).is_ok()) - || number - .as_u64() - .is_some_and(|value| i32::try_from(value).is_ok()) - } - ("Float", JsonValue::Number(_)) => true, - ("String" | "ID", JsonValue::String(_)) => true, - ("Timestamptz", JsonValue::String(value)) => is_rfc3339(value), - ("Bytea", JsonValue::String(value)) => base64::engine::general_purpose::STANDARD - .decode(value) - .is_ok(), - _ => false, - } -} - -fn is_rfc3339(value: &str) -> bool { - let bytes = value.as_bytes(); - if bytes.len() < 20 - || bytes.get(4) != Some(&b'-') - || bytes.get(7) != Some(&b'-') - || !matches!(bytes.get(10), Some(b'T' | b't')) - || bytes.get(13) != Some(&b':') - || bytes.get(16) != Some(&b':') - { - return false; - } - let number = |range: std::ops::Range| { - std::str::from_utf8(bytes.get(range)?) - .ok()? - .parse::() - .ok() - }; - let (Some(year), Some(month), Some(day), Some(hour), Some(minute), Some(second)) = ( - number(0..4), - number(5..7), - number(8..10), - number(11..13), - number(14..16), - number(17..19), - ) else { - return false; - }; - let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); - let max_day = match month { - 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, - 4 | 6 | 9 | 11 => 30, - 2 if leap => 29, - 2 => 28, - _ => return false, - }; - if day == 0 || day > max_day || hour > 23 || minute > 59 || second > 60 { - return false; - } - let mut cursor = 19; - if bytes.get(cursor) == Some(&b'.') { - cursor += 1; - let start = cursor; - while bytes.get(cursor).is_some_and(u8::is_ascii_digit) { - cursor += 1; - } - if cursor == start { - return false; - } - } - match bytes.get(cursor) { - Some(b'Z' | b'z') => cursor + 1 == bytes.len(), - Some(b'+' | b'-') if cursor + 6 == bytes.len() && bytes.get(cursor + 3) == Some(&b':') => { - matches!( - ( - number(cursor + 1..cursor + 3), - number(cursor + 4..cursor + 6) - ), - (Some(0..=23), Some(0..=59)) - ) - } - _ => false, - } -} - pub(super) fn graphql_name(value: &str, label: &str) -> Result<(), ClientCompileError> { if !crate::client_compiler::is_graphql_name(value) || value.starts_with("__") { Err(invalid( @@ -132,7 +40,7 @@ pub(super) fn nonempty(value: &str, label: &str) -> Result<(), ClientCompileErro } pub(super) fn command_error( - command: &ManifestCommand, + command: &ClientCommand, code: &'static str, message: impl std::fmt::Display, ) -> ClientCompileError { diff --git a/distributed_cli/src/client_compiler/command_manifest/validation.rs b/distributed_cli/src/client_compiler/command_manifest/validation.rs index a4c9f2478..d2a30257f 100644 --- a/distributed_cli/src/client_compiler/command_manifest/validation.rs +++ b/distributed_cli/src/client_compiler/command_manifest/validation.rs @@ -1,29 +1,29 @@ use std::collections::{BTreeMap, BTreeSet}; use crate::client_compiler::manifest::{ - validate_exact_operation_hash, ManifestCommand, ManifestCommandShape, ManifestModel, - ManifestProjector, ManifestProtocolOperations, ManifestRoot, ManifestTypeDef, RootOperation, + command_operation, validate_exact_operation_hash, ClientCommand, ClientCommandShape, + ClientModel, ClientProjector, ClientProtocolOperations, ClientRoot, ClientRootOperation, + ClientTypeDef, }; use crate::client_compiler::ClientCompileError; -use super::confirmations::{validate_confirmations, validate_projector_inventory}; -use super::effects::{validate_defaults, validate_effect, validate_trusted_preset_inventory}; +use super::effects::{validate_defaults, validate_trusted_preset_inventory}; +use super::projectors::validate_projector_inventory; use super::protocol::validate_protocol_operations; use super::shape::{ - canonical_command_operation, occupied_surface_types, projected_output_typename, validate_shape, - CommandTypeKind, + occupied_surface_types, projected_output_typename, validate_shape, CommandTypeKind, }; use super::support::{command_error, graphql_name, invalid, nonempty, unique_nonempty}; use super::CommandManifestValidation; pub(crate) fn validate_command_manifest( - commands: &[ManifestCommand], - models: &BTreeMap, - roots: &BTreeMap<(RootOperation, String), ManifestRoot>, + commands: &[ClientCommand], + models: &BTreeMap, + roots: &BTreeMap<(ClientRootOperation, String), ClientRoot>, scalar_codecs: &BTreeMap, - projectors: &[ManifestProjector], + projectors: &[ClientProjector], causal_receipts: bool, - protocol_operations: &ManifestProtocolOperations, + protocol_operations: &ClientProtocolOperations, ) -> Result { if causal_receipts != !commands.is_empty() { return Err(invalid( @@ -32,22 +32,19 @@ pub(crate) fn validate_command_manifest( )); } validate_protocol_operations(protocol_operations, !commands.is_empty())?; - let projectors = validate_projector_inventory(projectors, models)?; + validate_projector_inventory(projectors, models)?; let occupied_types = occupied_surface_types(models, roots, scalar_codecs); let mut command_names = BTreeSet::new(); let mut mutation_fields = BTreeSet::new(); let mut type_definitions = BTreeMap::new(); - let mut report = CommandManifestValidation::default(); for command in commands { validate_command( command, models, scalar_codecs, - &projectors, &occupied_types, &mut type_definitions, - &mut report, )?; if !command_names.insert(command.name.as_str()) { return Err(invalid( @@ -65,17 +62,15 @@ pub(crate) fn validate_command_manifest( )); } } - Ok(report) + Ok(CommandManifestValidation::default()) } fn validate_command( - command: &ManifestCommand, - models: &BTreeMap, + command: &ClientCommand, + models: &BTreeMap, scalar_codecs: &BTreeMap, - projectors: &BTreeMap<&str, &ManifestProjector>, occupied_types: &BTreeSet, - type_definitions: &mut BTreeMap, - report: &mut CommandManifestValidation, + type_definitions: &mut BTreeMap, ) -> Result<(), ClientCompileError> { if command.version != 1 { return Err(command_error( @@ -100,7 +95,7 @@ fn validate_command( None, type_definitions, )?; - if matches!(command.output, ManifestCommandShape::None) { + if matches!(command.output, ClientCommandShape::None) { return Err(command_error( command, "client.manifest.command_output", @@ -117,7 +112,7 @@ fn validate_command( type_definitions, )?; - let canonical = canonical_command_operation(command); + let canonical = command_operation(&command.mutation_field, &command.input, &command.output); if command.operation != canonical { return Err(command_error( command, @@ -146,35 +141,5 @@ fn validate_command( if let Some(defaults) = &extensions.input_defaults { validate_defaults(command, defaults.version, &defaults.defaults)?; } - if extensions.version == 1 { - if let Some(effects) = &extensions.effects { - if effects.version != 1 { - return Err(command_error( - command, - "client.manifest.command_effects", - "effects.version must be 1", - )); - } - if effects.operations.is_empty() { - report - .commands_requiring_revalidation - .insert(command.name.clone()); - } - for effect in &effects.operations { - validate_effect(command, effect, models, report)?; - } - } else { - report - .commands_requiring_revalidation - .insert(command.name.clone()); - } - validate_confirmations(command, models, projectors, report)?; - } else if extensions.effects.is_some() || extensions.confirmations.is_some() { - return Err(command_error( - command, - "client.manifest.legacy_command_authority", - "manifest v2 cannot carry legacy effects or confirmations", - )); - } validate_trusted_preset_inventory(command) } diff --git a/distributed_cli/src/client_compiler/command_manifest_tests.rs b/distributed_cli/src/client_compiler/command_manifest_tests.rs index c697778db..76dadf5ae 100644 --- a/distributed_cli/src/client_compiler/command_manifest_tests.rs +++ b/distributed_cli/src/client_compiler/command_manifest_tests.rs @@ -1,23 +1,24 @@ use std::collections::BTreeMap; use super::command_manifest::validate_command_manifest; +use distributed::command::InputDefaultGenerator; + use super::manifest::{ - hash_bytes, ManifestCommand, ManifestCommandConsistency, ManifestCommandExtensions, - ManifestCommandShape, ManifestConfirmationKind, ManifestConfirmations, ManifestConsistencyKind, - ManifestEffects, ManifestField, ManifestFilterField, ManifestFilterInput, ManifestInputDefault, - ManifestInputDefaultGenerator, ManifestInputDefaults, ManifestKeyField, ManifestModel, - ManifestNormalization, ManifestProjector, ManifestProtocolOperation, - ManifestProtocolOperations, ManifestRevalidationFallback, ManifestRowPolicy, - ManifestTrustedPresetDescriptor, ManifestTypeDef, ManifestTypeField, + hash_bytes, ClientCommand, ClientCommandExtensionSlots, ClientCommandShape, ClientField, + ClientFilterField, ClientFilterInput, ClientKeyField, ClientModel, ClientProjector, + ClientProtocolOperation, ClientProtocolOperations, ClientRowPolicy, + ClientTrustedPresetDescriptor, ClientTypeDef, ClientTypeField, CommandConsistency, + CommandConsistencyExtension, CommandInputDefault, CommandInputDefaultsExtension, + ModelNormalization, }; fn field( name: &str, type_name: &str, codec: Option<&str>, - nested: Option, -) -> ManifestTypeField { - ManifestTypeField { + nested: Option, +) -> ClientTypeField { + ClientTypeField { name: name.into(), type_name: type_name.into(), nullable: false, @@ -28,33 +29,33 @@ fn field( } } -fn model() -> ManifestModel { - ManifestModel { +fn model() -> ClientModel { + ClientModel { id: "Todo".into(), typename: "Todo".into(), source_table: "todos".into(), dependencies: vec!["todos".into()], - normalization: ManifestNormalization::Normalized { - fields: vec![ManifestKeyField { + normalization: ModelNormalization::Normalized { + fields: vec![ClientKeyField { name: "id".into(), codec: "string".into(), }], encoding: "length_prefixed_v1".into(), }, fields: vec![ - ManifestField { + ClientField { name: "id".into(), scalar: "ID".into(), codec: "string".into(), nullable: false, }, - ManifestField { + ClientField { name: "payload".into(), scalar: "Bytea".into(), codec: "base64".into(), nullable: false, }, - ManifestField { + ClientField { name: "title".into(), scalar: "String".into(), codec: "string".into(), @@ -62,18 +63,18 @@ fn model() -> ManifestModel { }, ], relationships: Vec::new(), - filter_input: ManifestFilterInput { + filter_input: ClientFilterInput { type_name: "todos_bool_exp".into(), fields: ["id", "payload", "title"] .into_iter() - .map(|name| ManifestFilterField { + .map(|name| ClientFilterField { name: name.into(), operators: vec!["_eq".into()], }) .collect(), relationships: Vec::new(), }, - row_policy: ManifestRowPolicy::Unrestricted, + row_policy: ClientRowPolicy::Unrestricted, record_revisions: true, tombstones: true, } @@ -90,8 +91,8 @@ fn codecs() -> BTreeMap { .collect() } -fn input() -> ManifestTypeDef { - ManifestTypeDef { +fn input() -> ClientTypeDef { + ClientTypeDef { name: "CreateTodoInput".into(), fields: vec![ field("id", "ID", Some("string"), None), @@ -99,7 +100,7 @@ fn input() -> ManifestTypeDef { "metadata", "TodoMetadataInput", None, - Some(ManifestTypeDef { + Some(ClientTypeDef { name: "TodoMetadataInput".into(), fields: vec![field("title", "String", Some("string"), None)], }), @@ -108,8 +109,8 @@ fn input() -> ManifestTypeDef { } } -fn output() -> ManifestTypeDef { - ManifestTypeDef { +fn output() -> ClientTypeDef { + ClientTypeDef { name: "CreateTodoPayload".into(), fields: vec![ field("id", "ID", Some("string"), None), @@ -117,7 +118,7 @@ fn output() -> ManifestTypeDef { "todo", "TodoResult", None, - Some(ManifestTypeDef { + Some(ClientTypeDef { name: "TodoResult".into(), fields: vec![ field("id", "ID", Some("string"), None), @@ -129,59 +130,56 @@ fn output() -> ManifestTypeDef { } } -fn command() -> ManifestCommand { +fn command() -> ClientCommand { let operation = "mutation Client_createTodo($commandId: ID!, $input: CreateTodoInput!) { createTodo(commandId: $commandId, input: $input) { id todo { id title } } }"; - ManifestCommand { + ClientCommand { version: 1, name: "CreateTodo".into(), mutation_field: "createTodo".into(), grants: vec!["user".into()], - input: ManifestCommandShape::Object { + input: ClientCommandShape::Object { definition: input(), }, - output: ManifestCommandShape::Object { + output: ClientCommandShape::Object { definition: output(), }, operation: operation.into(), operation_hash: hash_bytes(operation.as_bytes()), - extensions: ManifestCommandExtensions { + extensions: ClientCommandExtensionSlots { version: 2, - consistency: ManifestCommandConsistency { + consistency: CommandConsistencyExtension { version: 1, - kind: ManifestConsistencyKind::Eventual, + kind: CommandConsistency::Eventual, }, direct_projection: None, - input_defaults: Some(ManifestInputDefaults { + input_defaults: Some(CommandInputDefaultsExtension { version: 1, - defaults: vec![ManifestInputDefault { + defaults: vec![CommandInputDefault { path: vec!["id".into()], - generator: ManifestInputDefaultGenerator::UuidV7, + generator: InputDefaultGenerator::UuidV7, }], }), - effects: None, - confirmations: None, projection: None, trusted_presets: Vec::new(), }, } } -fn projector() -> ManifestProjector { - ManifestProjector { +fn projector() -> ClientProjector { + ClientProjector { version: 1, name: "todos".into(), facts: vec!["TodoCreated".into()], models: vec!["Todo".into()], dependencies: vec!["todos".into()], - causal_confirmation: true, } } -fn protocol() -> ManifestProtocolOperations { +fn protocol() -> ClientProtocolOperations { let operation = "query Distributed_CommandStatus($commandId: ID!) { commandStatus(commandId: $commandId) { state } }"; - ManifestProtocolOperations { + ClientProtocolOperations { version: 1, - command_status: Some(ManifestProtocolOperation { + command_status: Some(ClientProtocolOperation { name: "Distributed_CommandStatus".into(), operation: operation.into(), operation_hash: hash_bytes(operation.as_bytes()), @@ -190,13 +188,13 @@ fn protocol() -> ManifestProtocolOperations { } fn validate( - command: &ManifestCommand, + command: &ClientCommand, ) -> Result { validate_commands(std::slice::from_ref(command)) } fn validate_commands( - commands: &[ManifestCommand], + commands: &[ClientCommand], ) -> Result { validate_command_manifest( commands, @@ -209,7 +207,7 @@ fn validate_commands( ) } -fn command_with_identity(name: &str, mutation_field: &str) -> ManifestCommand { +fn command_with_identity(name: &str, mutation_field: &str) -> ClientCommand { let mut command = command(); command.name = name.into(); command.mutation_field = mutation_field.into(); @@ -235,7 +233,7 @@ fn requires_byte_exact_canonical_operation_and_recursive_codecs() { assert_eq!(error.code, "client.manifest.command_operation"); let mut wrong_codec = command(); - let ManifestCommandShape::Object { definition } = &mut wrong_codec.input else { + let ClientCommandShape::Object { definition } = &mut wrong_codec.input else { unreachable!() }; definition.fields[1].nested.as_mut().expect("nested").fields[0].codec = Some("json".into()); @@ -249,7 +247,7 @@ fn unreferenced_trusted_preset_descriptors_fail_closed() { trusted .extensions .trusted_presets - .push(ManifestTrustedPresetDescriptor { + .push(ClientTrustedPresetDescriptor { name: "subject".into(), codec: "string".into(), }); @@ -258,41 +256,22 @@ fn unreferenced_trusted_preset_descriptors_fail_closed() { } #[test] -fn legacy_command_authority_has_no_v2_decoder() { +fn command_extensions_v1_has_no_decoder() { let mut old_version = command(); old_version.extensions.version = 1; let error = validate(&old_version).expect_err("extensions v1 must fail closed"); assert_eq!(error.code, "client.manifest.command_extensions"); - - let mut effects = command(); - effects.extensions.effects = Some(ManifestEffects { - version: 1, - operations: Vec::new(), - fallback: ManifestRevalidationFallback::Revalidate, - }); - let error = validate(&effects).expect_err("legacy effects must fail closed"); - assert_eq!(error.code, "client.manifest.legacy_command_authority"); - - let mut confirmations = command(); - confirmations.extensions.confirmations = Some(ManifestConfirmations { - version: 1, - kind: ManifestConfirmationKind::Unavailable, - expected: Vec::new(), - fallback: ManifestRevalidationFallback::Revalidate, - }); - let error = validate(&confirmations).expect_err("legacy confirmations must fail closed"); - assert_eq!(error.code, "client.manifest.legacy_command_authority"); } #[test] fn rejects_empty_outputs_and_ambiguous_command_type_namespaces() { let mut empty = command(); - empty.output = ManifestCommandShape::None; + empty.output = ClientCommandShape::None; let error = validate(&empty).expect_err("GraphQL mutation output cannot be empty"); assert_eq!(error.code, "client.manifest.command_output"); let mut overlaps_input = command(); - overlaps_input.output = ManifestCommandShape::Object { + overlaps_input.output = ClientCommandShape::Object { definition: input(), }; let error = validate(&overlaps_input).expect_err("input/output type IDs cannot overlap"); @@ -304,7 +283,7 @@ fn rejects_empty_outputs_and_ambiguous_command_type_namespaces() { .expect("identical output definitions may be shared across commands"); let mut conflicting = second; - let ManifestCommandShape::Object { definition } = &mut conflicting.output else { + let ClientCommandShape::Object { definition } = &mut conflicting.output else { unreachable!() }; definition.fields[0].nullable = true; @@ -313,7 +292,7 @@ fn rejects_empty_outputs_and_ambiguous_command_type_namespaces() { assert_eq!(error.code, "client.manifest.command_type_reference"); let mut model_collision = command(); - let ManifestCommandShape::Object { definition } = &mut model_collision.input else { + let ClientCommandShape::Object { definition } = &mut model_collision.input else { unreachable!() }; definition.name = "Todo".into(); @@ -322,7 +301,7 @@ fn rejects_empty_outputs_and_ambiguous_command_type_namespaces() { assert_eq!(error.code, "client.manifest.command_type_namespace"); let mut scalar_collision = command(); - let ManifestCommandShape::Object { definition } = &mut scalar_collision.input else { + let ClientCommandShape::Object { definition } = &mut scalar_collision.input else { unreachable!() }; definition.name = "String".into(); @@ -331,7 +310,7 @@ fn rejects_empty_outputs_and_ambiguous_command_type_namespaces() { assert_eq!(error.code, "client.manifest.command_type_namespace"); let mut non_projected_model_output = command(); - let ManifestCommandShape::Object { definition } = &mut non_projected_model_output.output else { + let ClientCommandShape::Object { definition } = &mut non_projected_model_output.output else { unreachable!() }; definition.name = "Todo".into(); @@ -343,19 +322,19 @@ fn rejects_empty_outputs_and_ambiguous_command_type_namespaces() { #[test] fn accepts_shapes_beyond_removed_compiler_only_size_limits() { let mut deep = command(); - let mut nested = ManifestTypeDef { + let mut nested = ClientTypeDef { name: "Deep40".into(), fields: vec![field("value", "String", Some("string"), None)], }; for depth in (0..40).rev() { let type_name = format!("Deep{depth}"); let child_name = nested.name.clone(); - nested = ManifestTypeDef { + nested = ClientTypeDef { name: type_name, fields: vec![field("child", &child_name, None, Some(nested))], }; } - let ManifestCommandShape::Object { definition } = &mut deep.input else { + let ClientCommandShape::Object { definition } = &mut deep.input else { unreachable!() }; let nested_name = nested.name.clone(); @@ -365,7 +344,7 @@ fn accepts_shapes_beyond_removed_compiler_only_size_limits() { validate(&deep).expect("Surface has no 32-level command type limit"); let mut wide = command(); - let ManifestCommandShape::Object { definition } = &mut wide.input else { + let ClientCommandShape::Object { definition } = &mut wide.input else { unreachable!() }; let mut fields = (0..4_097) @@ -385,7 +364,7 @@ fn query_only_protocol_has_no_command_status_or_causal_capability() { &codecs(), &[], false, - &ManifestProtocolOperations { + &ClientProtocolOperations { version: 1, command_status: None, }, diff --git a/distributed_cli/src/client_compiler/graphql/arguments.rs b/distributed_cli/src/client_compiler/graphql/arguments.rs index 9daab786f..9a9fdd1c3 100644 --- a/distributed_cli/src/client_compiler/graphql/arguments.rs +++ b/distributed_cli/src/client_compiler/graphql/arguments.rs @@ -23,8 +23,8 @@ pub(super) fn single_root_field<'a>( pub(super) fn compile_arguments( field: &Field, owner: &str, - allowed_arguments: &[ManifestArgument], - model: &ManifestModel, + allowed_arguments: &[ClientArgument], + model: &ClientModel, manifest: &ClientManifest, variables: &[CompiledVariable], used_variables: &mut BTreeSet, @@ -243,11 +243,11 @@ pub(super) fn contains_variable(value: &Value) -> bool { pub(super) fn canonicalize_argument_literal( value: &Value, - argument: &ManifestArgument, - model: &ManifestModel, + argument: &ClientArgument, + model: &ClientModel, manifest: &ClientManifest, ) -> Value { - let value = if argument.kind == ManifestArgumentKind::Filter { + let value = if argument.kind == ClientArgumentKind::Filter { canonicalize_filter_literal(value, model, &model.filter_input, manifest) } else { value.clone() @@ -275,8 +275,8 @@ pub(super) fn canonicalize_argument_literal( pub(super) fn canonicalize_filter_literal( value: &Value, - model: &ManifestModel, - input: &ManifestFilterInput, + model: &ClientModel, + input: &ClientFilterInput, manifest: &ClientManifest, ) -> Value { let Value::Object(fields) = value else { @@ -314,8 +314,8 @@ pub(super) fn canonicalize_filter_literal( pub(super) fn canonicalize_filter_literal_list( value: &Value, - model: &ManifestModel, - input: &ManifestFilterInput, + model: &ClientModel, + input: &ClientFilterInput, manifest: &ClientManifest, ) -> Value { match value { @@ -332,10 +332,7 @@ pub(super) fn canonicalize_filter_literal_list( } } -pub(super) fn canonicalize_filter_comparison_literal( - value: &Value, - field: &ManifestField, -) -> Value { +pub(super) fn canonicalize_filter_comparison_literal(value: &Value, field: &ClientField) -> Value { let Value::Object(operators) = value else { return value.clone(); }; @@ -442,7 +439,7 @@ pub(super) fn canonicalize_float_number(number: &serde_json::Number) -> Option Result<(), ClientCompileError> { diff --git a/distributed_cli/src/client_compiler/graphql/mod.rs b/distributed_cli/src/client_compiler/graphql/mod.rs index 5d7664167..986db3b64 100644 --- a/distributed_cli/src/client_compiler/graphql/mod.rs +++ b/distributed_cli/src/client_compiler/graphql/mod.rs @@ -11,12 +11,12 @@ use serde::Serialize; use serde_json::{Map as JsonMap, Value as JsonValue}; use super::manifest::{ - hash_bytes, ClientManifest, ManifestAggregateSemantics, ManifestArgument, ManifestArgumentKind, - ManifestComplexityWeights, ManifestExecutionLimits, ManifestField, ManifestFilterExpr, - ManifestFilterField, ManifestFilterInput, ManifestFilterSemantics, ManifestModel, - ManifestOrderSemantics, ManifestPagination, ManifestRelationship, - ManifestRelationshipKeyMapping, ManifestRelationshipKind, ManifestRelationshipMaintenance, - ManifestRoot, ManifestRowPolicy, RootKind, RootOperation, + hash_bytes, row_cost, ClientAggregateSemantics, ClientArgument, ClientArgumentKind, + ClientExecutionLimits, ClientField, ClientFilterField, ClientFilterInput, + ClientFilterSemantics, ClientManifest, ClientModel, ClientOrderSemantics, + ClientPaginationSemantics, ClientRelationship, ClientRelationshipKind, + ClientRelationshipMaintenance, ClientRoot, ClientRootKind, ClientRootOperation, + ClientRowPolicy, FilterExpr, RelationshipKeyMapping, }; use super::{ClientCompileError, ClientDocument}; diff --git a/distributed_cli/src/client_compiler/graphql/objects.rs b/distributed_cli/src/client_compiler/graphql/objects.rs index 1401d9869..c223380c9 100644 --- a/distributed_cli/src/client_compiler/graphql/objects.rs +++ b/distributed_cli/src/client_compiler/graphql/objects.rs @@ -22,7 +22,7 @@ impl<'a> ModelCompileContext<'a> { pub(super) fn compile_model_object<'ast>( field: &MergedField<'ast>, - model: &ManifestModel, + model: &ClientModel, context: &ModelCompileContext<'_>, used_variables: &mut BTreeSet, expander: &mut FragmentExpander<'ast, '_>, @@ -308,7 +308,7 @@ pub(super) fn compile_model_object<'ast>( Ok(object) } -pub(super) fn compiled_storage(model: &ManifestModel) -> CompiledStorage { +pub(super) fn compiled_storage(model: &ClientModel) -> CompiledStorage { match model.identity() { Some(identity) => CompiledStorage::Normalized { model_id: model.id.clone(), @@ -319,13 +319,15 @@ pub(super) fn compiled_storage(model: &ManifestModel) -> CompiledStorage { } pub(super) fn compiled_relationship_plan( - relationship: &ManifestRelationship, + relationship: &ClientRelationship, ) -> CompiledRelationshipPlan { let maintenance = match &relationship.key_mapping { - ManifestRelationshipKeyMapping::Direct { .. } - | ManifestRelationshipKeyMapping::Through { .. } => relationship.maintenance, - ManifestRelationshipKeyMapping::ThroughOpaque { .. } - | ManifestRelationshipKeyMapping::Embedded => ManifestRelationshipMaintenance::Revalidate, + RelationshipKeyMapping::Direct { .. } | RelationshipKeyMapping::Through { .. } => { + relationship.maintenance + } + RelationshipKeyMapping::ThroughOpaque { .. } | RelationshipKeyMapping::Embedded => { + ClientRelationshipMaintenance::Revalidate + } }; CompiledRelationshipPlan { field: relationship.name.clone(), @@ -337,26 +339,24 @@ pub(super) fn compiled_relationship_plan( } } -pub(super) fn relationship_key_fields( - mapping: &ManifestRelationshipKeyMapping, -) -> (&[String], &[String]) { +pub(super) fn relationship_key_fields(mapping: &RelationshipKeyMapping) -> (&[String], &[String]) { match mapping { - ManifestRelationshipKeyMapping::Direct { local, remote } - | ManifestRelationshipKeyMapping::Through { local, remote, .. } - | ManifestRelationshipKeyMapping::ThroughOpaque { local, remote, .. } => (local, remote), - ManifestRelationshipKeyMapping::Embedded => (&[], &[]), + RelationshipKeyMapping::Direct { local, remote } + | RelationshipKeyMapping::Through { local, remote, .. } + | RelationshipKeyMapping::ThroughOpaque { local, remote, .. } => (local, remote), + RelationshipKeyMapping::Embedded => (&[], &[]), } } #[allow(clippy::too_many_arguments)] pub(super) fn compile_aggregate_object<'ast>( field: &MergedField<'ast>, - model: &ManifestModel, - semantics: &ManifestAggregateSemantics, - arguments: &[ManifestArgument], + model: &ClientModel, + semantics: &ClientAggregateSemantics, + arguments: &[ClientArgument], compiled_arguments: &BTreeMap, - filter_semantics: Option<&ManifestFilterSemantics>, - order_semantics: Option<&ManifestOrderSemantics>, + filter_semantics: Option<&ClientFilterSemantics>, + order_semantics: Option<&ClientOrderSemantics>, dependencies: &[String], manifest: &ClientManifest, variables: &[CompiledVariable], @@ -543,7 +543,7 @@ pub(super) fn compile_aggregate_object<'ast>( pub(super) fn compile_aggregate_fields_object<'ast>( field: &MergedField<'ast>, - semantics: &ManifestAggregateSemantics, + semantics: &ClientAggregateSemantics, document: &ClientDocument, expander: &mut FragmentExpander<'ast, '_>, depth: usize, @@ -621,7 +621,7 @@ pub(super) fn compile_aggregate_fields_object<'ast>( pub(super) fn compiled_scalar( response_key: &str, - field: &ManifestField, + field: &ClientField, expose: bool, ) -> CompiledScalar { CompiledScalar { diff --git a/distributed_cli/src/client_compiler/graphql/operation.rs b/distributed_cli/src/client_compiler/graphql/operation.rs index 4a4005bfa..8f3ca285e 100644 --- a/distributed_cli/src/client_compiler/graphql/operation.rs +++ b/distributed_cli/src/client_compiler/graphql/operation.rs @@ -68,7 +68,7 @@ pub(crate) fn compile_document( let root_name = root_field.first.node.name.node.as_str(); let root_manifest = manifest - .root(RootOperation::Query, root_name) + .root(ClientRootOperation::Query, root_name) .ok_or_else(|| { source_error( "client.root.denied_or_unknown", @@ -99,7 +99,7 @@ pub(crate) fn compile_document( document, )?; let mut selection = match root_manifest.kind { - RootKind::List | RootKind::ByPk => compile_model_object( + ClientRootKind::List | ClientRootKind::ByPk => compile_model_object( &root_field, model, &ModelCompileContext::new(manifest, &variables, document), @@ -107,7 +107,7 @@ pub(crate) fn compile_document( &mut expander, 2, )?, - RootKind::Aggregate => { + ClientRootKind::Aggregate => { let semantics = root_manifest.aggregate.as_ref().ok_or_else(|| { ClientCompileError::manifest( "client.manifest.aggregate_semantics", @@ -132,7 +132,7 @@ pub(crate) fn compile_document( )? } }; - if root_manifest.kind == RootKind::List { + if root_manifest.kind == ClientRootKind::List { let dependencies = query_plan_field_dependencies( model, root_manifest.filter.as_ref(), @@ -152,13 +152,13 @@ pub(crate) fn compile_document( expander.reject_unused_fragments()?; let cardinality = match root_manifest.kind { - RootKind::List => Cardinality::Many, - RootKind::ByPk => Cardinality::One, - RootKind::Aggregate => Cardinality::One, + ClientRootKind::List => Cardinality::Many, + ClientRootKind::ByPk => Cardinality::One, + ClientRootKind::Aggregate => Cardinality::One, }; let coverage = match root_manifest.kind { - RootKind::Aggregate => Some(complete_coverage()), - RootKind::List | RootKind::ByPk => compile_coverage( + ClientRootKind::Aggregate => Some(complete_coverage()), + ClientRootKind::List | ClientRootKind::ByPk => compile_coverage( root_manifest.pagination.as_ref(), &root_manifest.arguments, &root_manifest.name, @@ -178,13 +178,16 @@ pub(crate) fn compile_document( &root_field.first.node, coverage.as_ref(), 0, - root_manifest.kind == RootKind::List, + root_manifest.kind == ClientRootKind::List, )?; let root = CompiledRoot { response_key: root_field.first.node.response_key().node.to_string(), field: root_name.to_string(), cardinality, - nullable: matches!(root_manifest.kind, RootKind::ByPk | RootKind::Aggregate), + nullable: matches!( + root_manifest.kind, + ClientRootKind::ByPk | ClientRootKind::Aggregate + ), arguments: compiled_arguments, dependencies: root_manifest.dependencies.clone(), coverage, @@ -296,7 +299,7 @@ pub(super) fn compile_live( query_name: &str, variables: &[CompiledVariable], root: &CompiledRoot, - query_manifest: &ManifestRoot, + query_manifest: &ClientRoot, manifest: &ClientManifest, document: &ClientDocument, position: Pos, @@ -313,7 +316,7 @@ pub(super) fn compile_live( )); } let subscription = manifest - .root(RootOperation::Subscription, &query_manifest.name) + .root(ClientRootOperation::Subscription, &query_manifest.name) .ok_or_else(|| { source_error( "client.live.root_missing", @@ -350,8 +353,8 @@ pub(super) fn compile_live( }) } -pub(super) fn arguments_compatible(left: &[ManifestArgument], right: &[ManifestArgument]) -> bool { - let canonical = |arguments: &[ManifestArgument]| { +pub(super) fn arguments_compatible(left: &[ClientArgument], right: &[ClientArgument]) -> bool { + let canonical = |arguments: &[ClientArgument]| { arguments .iter() .map(|argument| { diff --git a/distributed_cli/src/client_compiler/graphql/query_plan.rs b/distributed_cli/src/client_compiler/graphql/query_plan.rs index 12e4ec379..9a545b250 100644 --- a/distributed_cli/src/client_compiler/graphql/query_plan.rs +++ b/distributed_cli/src/client_compiler/graphql/query_plan.rs @@ -2,7 +2,7 @@ use super::*; pub(super) fn inject_wire_fields( members: &mut Vec, - model: &ManifestModel, + model: &ClientModel, document: &ClientDocument, position: Pos, ) -> Result<(), ClientCompileError> { @@ -58,21 +58,21 @@ pub(super) fn inject_wire_fields( } pub(super) fn query_plan_field_dependencies( - model: &ManifestModel, - filter: Option<&ManifestFilterSemantics>, - order: Option<&ManifestOrderSemantics>, - declared_arguments: &[ManifestArgument], + model: &ClientModel, + filter: Option<&ClientFilterSemantics>, + order: Option<&ClientOrderSemantics>, + declared_arguments: &[ClientArgument], compiled_arguments: &BTreeMap, ) -> BTreeSet { let mut fields = BTreeSet::new(); let mut relationships = BTreeSet::new(); if let Some(filter) = filter { - if let ManifestRowPolicy::Predicate { expression } = &filter.row_policy { + if let ClientRowPolicy::Predicate { expression } = &filter.row_policy { collect_policy_fields(expression, &mut fields, &mut relationships); } if let Some(argument) = declared_arguments .iter() - .find(|argument| argument.kind == ManifestArgumentKind::Filter) + .find(|argument| argument.kind == ClientArgumentKind::Filter) .and_then(|argument| compiled_arguments.get(&argument.name)) { collect_filter_source_fields(argument, filter, &mut fields, &mut relationships); @@ -81,7 +81,7 @@ pub(super) fn query_plan_field_dependencies( if let Some(order) = order { if let Some(argument) = declared_arguments .iter() - .find(|argument| argument.kind == ManifestArgumentKind::Order) + .find(|argument| argument.kind == ClientArgumentKind::Order) .and_then(|argument| compiled_arguments.get(&argument.name)) { collect_order_source_fields(argument, order, &mut fields); @@ -98,7 +98,7 @@ pub(super) fn query_plan_field_dependencies( pub(super) fn collect_filter_source_fields( source: &CompiledArgument, - semantics: &ManifestFilterSemantics, + semantics: &ClientFilterSemantics, fields: &mut BTreeSet, relationships: &mut BTreeSet, ) { @@ -146,7 +146,7 @@ pub(super) fn collect_filter_source_fields( pub(super) fn collect_order_source_fields( source: &CompiledArgument, - semantics: &ManifestOrderSemantics, + semantics: &ClientOrderSemantics, fields: &mut BTreeSet, ) { match source { @@ -170,25 +170,23 @@ pub(super) fn collect_order_source_fields( } pub(super) fn collect_policy_fields( - expression: &ManifestFilterExpr, + expression: &FilterExpr, fields: &mut BTreeSet, relationships: &mut BTreeSet, ) { match expression { - ManifestFilterExpr::And(expressions) | ManifestFilterExpr::Or(expressions) => { + FilterExpr::And(expressions) | FilterExpr::Or(expressions) => { for expression in expressions { collect_policy_fields(expression, fields, relationships); } } - ManifestFilterExpr::Not(expression) => { - collect_policy_fields(expression, fields, relationships) - } - ManifestFilterExpr::Cmp { column, .. } - | ManifestFilterExpr::In { column, .. } - | ManifestFilterExpr::IsNull { column, .. } => { + FilterExpr::Not(expression) => collect_policy_fields(expression, fields, relationships), + FilterExpr::Cmp { column, .. } + | FilterExpr::In { column, .. } + | FilterExpr::IsNull { column, .. } => { fields.insert(column.clone()); } - ManifestFilterExpr::Rel { field, .. } => { + FilterExpr::Rel { field, .. } => { relationships.insert(field.clone()); } } @@ -196,7 +194,7 @@ pub(super) fn collect_policy_fields( pub(super) fn collect_client_filter_fields( value: &JsonValue, - semantics: &ManifestFilterSemantics, + semantics: &ClientFilterSemantics, fields: &mut BTreeSet, relationships: &mut BTreeSet, ) { @@ -236,7 +234,7 @@ pub(super) fn collect_client_filter_fields( pub(super) fn inject_dependency_fields( selection: &mut CompiledObject, - model: &ManifestModel, + model: &ClientModel, dependencies: &BTreeSet, document: &ClientDocument, position: Pos, @@ -294,8 +292,8 @@ pub(super) fn allocate_wire_alias(field: &str, used: &mut BTreeSet) -> S } pub(super) fn compile_coverage( - pagination: Option<&ManifestPagination>, - arguments: &[ManifestArgument], + pagination: Option<&ClientPaginationSemantics>, + arguments: &[ClientArgument], owner: &str, document: &ClientDocument, position: Pos, @@ -318,11 +316,11 @@ pub(super) fn compile_coverage( kind: "offset".into(), offset_argument: arguments .iter() - .find(|argument| argument.kind == ManifestArgumentKind::Offset) + .find(|argument| argument.kind == ClientArgumentKind::Offset) .map(|argument| argument.name.clone()), limit_argument: arguments .iter() - .find(|argument| argument.kind == ManifestArgumentKind::Limit) + .find(|argument| argument.kind == ClientArgumentKind::Limit) .map(|argument| argument.name.clone()), default_limit: Some(pagination.default_limit), max_limit: Some(pagination.max_limit), @@ -370,10 +368,10 @@ pub(super) fn compiled_pagination_plan(coverage: &CompiledCoverage) -> CompiledP #[allow(clippy::too_many_arguments)] pub(super) fn compile_query_plans( - model: &ManifestModel, - filter: Option<&ManifestFilterSemantics>, - order: Option<&ManifestOrderSemantics>, - declared_arguments: &[ManifestArgument], + model: &ClientModel, + filter: Option<&ClientFilterSemantics>, + order: Option<&ClientOrderSemantics>, + declared_arguments: &[ClientArgument], compiled_arguments: &BTreeMap, variables: &[CompiledVariable], manifest: &ClientManifest, @@ -385,10 +383,10 @@ pub(super) fn compile_query_plans( ) -> Result { let filter_argument = declared_arguments .iter() - .find(|argument| argument.kind == ManifestArgumentKind::Filter); + .find(|argument| argument.kind == ClientArgumentKind::Filter); let order_argument = declared_arguments .iter() - .find(|argument| argument.kind == ManifestArgumentKind::Order); + .find(|argument| argument.kind == ClientArgumentKind::Order); let filter_plan = match filter { Some(semantics) => { @@ -398,7 +396,7 @@ pub(super) fn compile_query_plans( .cloned(); if let Some(input) = &input { let input_type = filter_argument - .map(ManifestArgument::graphql_type) + .map(ClientArgument::graphql_type) .ok_or_else(|| { ClientCompileError::manifest( "client.manifest.filter_argument", @@ -528,7 +526,7 @@ pub(super) fn compile_query_plans( } pub(super) fn compiled_order_field( - model: &ManifestModel, + model: &ClientModel, name: &str, ) -> Result { let field = model.field(name).ok_or_else(|| { diff --git a/distributed_cli/src/client_compiler/graphql/types.rs b/distributed_cli/src/client_compiler/graphql/types.rs index 809147ac1..6d4d97723 100644 --- a/distributed_cli/src/client_compiler/graphql/types.rs +++ b/distributed_cli/src/client_compiler/graphql/types.rs @@ -249,7 +249,7 @@ pub(crate) struct CompiledFilterPlan { pub(crate) input: Option, pub(crate) fields: Vec, pub(crate) relationships: Vec, - pub(crate) row_policy: ManifestRowPolicy, + pub(crate) row_policy: ClientRowPolicy, pub(super) variable_constraints: BTreeMap, } @@ -306,9 +306,9 @@ pub(crate) struct CompiledFilterField { pub(crate) struct CompiledRelationshipPlan { pub(crate) field: String, pub(crate) target_model: String, - pub(crate) kind: ManifestRelationshipKind, - pub(crate) key_mapping: ManifestRelationshipKeyMapping, - pub(crate) maintenance: ManifestRelationshipMaintenance, + pub(crate) kind: ClientRelationshipKind, + pub(crate) key_mapping: RelationshipKeyMapping, + pub(crate) maintenance: ClientRelationshipMaintenance, pub(crate) dependencies: Vec, } diff --git a/distributed_cli/src/client_compiler/graphql/validation.rs b/distributed_cli/src/client_compiler/graphql/validation.rs index abe7080bc..7fe398120 100644 --- a/distributed_cli/src/client_compiler/graphql/validation.rs +++ b/distributed_cli/src/client_compiler/graphql/validation.rs @@ -2,8 +2,8 @@ use super::*; pub(super) fn validate_execution_limits( root: &CompiledRoot, - kind: RootKind, - execution: &ManifestExecutionLimits, + kind: ClientRootKind, + execution: &ClientExecutionLimits, document: &ClientDocument, position: Pos, ) -> Result<(), ClientCompileError> { @@ -20,21 +20,13 @@ pub(super) fn validate_execution_limits( )); } - let weights = &execution.complexity; - let child = compiled_object_complexity(&root.selection, weights); - let complexity = match kind { - RootKind::List => weights - .list_root - .saturating_add(weights.list_fanout.saturating_mul(child)), - RootKind::ByPk => weights.by_pk.saturating_add(child), - RootKind::Aggregate => weights.aggregate.saturating_add(child), - }; - if complexity > execution.max_complexity { + let rows = compiled_root_rows(root, kind); + if rows > execution.max_rows { return Err(source_error( - "client.operation.complexity_limit", + "client.operation.row_limit", format!( - "compiled operation complexity {complexity} exceeds the selected service max_complexity {}", - execution.max_complexity + "compiled operation may return {rows} rows, exceeding the selected service max_rows {}", + execution.max_rows ), document, position, @@ -60,45 +52,74 @@ pub(super) fn compiled_object_depth(selection: &CompiledObject, parent_depth: u6 .unwrap_or(parent_depth) } -pub(super) fn compiled_object_complexity( - selection: &CompiledObject, - weights: &ManifestComplexityWeights, -) -> u64 { - selection.members.iter().fold(0, |total, member| { - let cost = match member { - CompiledMember::Scalar(_) => weights.scalar, - CompiledMember::Branch(branch) => match branch.semantic { - CompiledBranchSemantic::Relationship => { - let child = compiled_object_complexity(&branch.selection, weights); - match branch - .relationship - .as_ref() - .expect("relationship branches retain their compiled descriptor") - .kind - { - ManifestRelationshipKind::BelongsTo => { - weights.belongs_to.saturating_add(child) +/// The service's row cost ([`row_cost`]) of a compiled root: every list +/// counts its page size, so nested lists cost about the product of their +/// limits. +/// +/// A literal `limit` counts as given (capped by the field's `max_limit`); an +/// absent one, or a variable whose value is unknown until run time, counts as +/// the field's `default_limit`. The service checks the actual values again +/// for every request, so this build-time check refuses only what the defaults +/// already put over budget. +pub(super) fn compiled_root_rows(root: &CompiledRoot, kind: ClientRootKind) -> u64 { + let limit = page_limit(&root.arguments, root.coverage.as_ref()); + match kind { + ClientRootKind::List => row_cost::page(limit, compiled_object_rows(&root.selection, limit)), + ClientRootKind::ByPk => row_cost::one(compiled_object_rows(&root.selection, limit)), + ClientRootKind::Aggregate => compiled_object_rows(&root.selection, limit), + } +} + +/// Rows nested under one object. `nodes_limit` is the page size of an +/// aggregate's `nodes`, which take their arguments from the aggregate field. +fn compiled_object_rows(selection: &CompiledObject, nodes_limit: u64) -> u64 { + selection + .members + .iter() + .map(|member| match member { + CompiledMember::Scalar(_) => 0, + CompiledMember::Branch(branch) => { + let limit = page_limit(&branch.arguments, branch.coverage.as_ref()); + match branch.semantic { + CompiledBranchSemantic::Relationship => { + let nested = compiled_object_rows(&branch.selection, limit); + match branch.cardinality { + Cardinality::Many => row_cost::page(limit, nested), + Cardinality::One => row_cost::one(nested), } - ManifestRelationshipKind::HasMany => weights - .has_many - .saturating_add(weights.list_fanout.saturating_mul(child)), - ManifestRelationshipKind::ManyToMany => weights - .m2m - .saturating_add(weights.list_fanout.saturating_mul(child)), } + CompiledBranchSemantic::Aggregate => { + compiled_object_rows(&branch.selection, limit) + } + CompiledBranchSemantic::AggregateFields => 0, + CompiledBranchSemantic::AggregateNodes => row_cost::page( + nodes_limit, + compiled_object_rows(&branch.selection, nodes_limit), + ), } - CompiledBranchSemantic::Aggregate => weights - .aggregate - .saturating_add(compiled_object_complexity(&branch.selection, weights)), - CompiledBranchSemantic::AggregateFields => weights.scalar, - CompiledBranchSemantic::AggregateNodes => weights - .list_fanout - .saturating_mul(compiled_object_complexity(&branch.selection, weights)) - .max(weights.scalar), - }, - }; - total.saturating_add(cost) - }) + } + }) + .fold(0, u64::saturating_add) +} + +fn page_limit( + arguments: &BTreeMap, + coverage: Option<&CompiledCoverage>, +) -> u64 { + let Some(coverage) = coverage else { + return 1; + }; + let default = coverage.default_limit.unwrap_or(1); + let literal = coverage + .limit_argument + .as_ref() + .and_then(|name| arguments.get(name)) + .and_then(|argument| match argument { + CompiledArgument::Literal { value, .. } => value.as_u64(), + _ => None, + }); + let limit = literal.unwrap_or(default); + coverage.max_limit.map_or(limit, |max| limit.min(max)) } pub(super) fn filter_depth_from_selection(selection_depth: usize, root_offset: usize) -> u64 { @@ -109,12 +130,12 @@ pub(super) fn filter_depth_from_selection(selection_depth: usize, root_offset: u #[allow(clippy::too_many_arguments)] pub(super) fn validate_filter_source( source: &CompiledArgument, - model: &ManifestModel, - input: &ManifestFilterInput, + model: &ClientModel, + input: &ClientFilterInput, expected_type: &str, variables: &[CompiledVariable], manifest: &ClientManifest, - execution: &ManifestExecutionLimits, + execution: &ClientExecutionLimits, document: &ClientDocument, position: Pos, depth: u64, @@ -310,8 +331,8 @@ pub(super) fn validate_filter_source( } pub(super) fn validate_filter_depth( - model: &ManifestModel, - execution: &ManifestExecutionLimits, + model: &ClientModel, + execution: &ClientExecutionLimits, depth: u64, document: &ClientDocument, position: Pos, @@ -376,11 +397,11 @@ pub(super) fn constrain_variable( #[allow(clippy::too_many_arguments)] pub(super) fn validate_filter_comparison_source( source: &CompiledArgument, - model: &ManifestModel, - field: &ManifestField, - semantics: &ManifestFilterField, + model: &ClientModel, + field: &ClientField, + semantics: &ClientFilterField, variables: &[CompiledVariable], - execution: &ManifestExecutionLimits, + execution: &ClientExecutionLimits, document: &ClientDocument, position: Pos, constraints: &mut BTreeMap, @@ -583,8 +604,8 @@ pub(super) fn validate_filter_comparison_source( pub(super) fn validate_compiled_filter_literal( source: &CompiledArgument, - model: &ManifestModel, - field: &ManifestField, + model: &ClientModel, + field: &ClientField, nullable: bool, document: &ClientDocument, position: Pos, @@ -604,8 +625,8 @@ pub(super) fn validate_compiled_filter_literal( #[allow(clippy::too_many_arguments)] pub(super) fn validate_compiled_filter_typed_literal( source: &CompiledArgument, - model: &ManifestModel, - field: &ManifestField, + model: &ClientModel, + field: &ClientField, scalar: &str, codec: &str, nullable: bool, @@ -647,8 +668,8 @@ pub(super) fn compiled_literal_json(source: &CompiledArgument) -> Option JsonValue { #[allow(clippy::too_many_arguments)] pub(super) fn validate_filter_literal( value: &JsonValue, - model: &ManifestModel, - input: &ManifestFilterInput, + model: &ClientModel, + input: &ClientFilterInput, manifest: &ClientManifest, - execution: &ManifestExecutionLimits, + execution: &ClientExecutionLimits, document: &ClientDocument, position: Pos, depth: u64, @@ -1018,7 +1039,7 @@ pub(super) fn validate_filter_literal( pub(super) fn validate_order_literal( value: &JsonValue, - semantics: &ManifestOrderSemantics, + semantics: &ClientOrderSemantics, document: &ClientDocument, position: Pos, ) -> Result<(), ClientCompileError> { @@ -1081,8 +1102,8 @@ pub(super) fn validate_order_literal( pub(super) fn validate_order_source( source: &CompiledArgument, - semantics: &ManifestOrderSemantics, - argument: Option<&ManifestArgument>, + semantics: &ClientOrderSemantics, + argument: Option<&ClientArgument>, variables: &[CompiledVariable], document: &ClientDocument, position: Pos, @@ -1092,14 +1113,12 @@ pub(super) fn validate_order_source( validate_order_literal(value, semantics, document, position) } CompiledArgument::Variable(name) => { - let expected = argument - .map(ManifestArgument::graphql_type) - .ok_or_else(|| { - ClientCompileError::manifest( - "client.manifest.order_argument", - "order semantics exist without an order argument", - ) - })?; + let expected = argument.map(ClientArgument::graphql_type).ok_or_else(|| { + ClientCompileError::manifest( + "client.manifest.order_argument", + "order semantics exist without an order argument", + ) + })?; validate_nested_variable(name, &expected, variables, document, position) } CompiledArgument::List(entries) => { @@ -1156,7 +1175,7 @@ pub(super) fn validate_order_source( pub(super) fn validate_order_entry_source( fields: &BTreeMap, - semantics: &ManifestOrderSemantics, + semantics: &ClientOrderSemantics, variables: &[CompiledVariable], document: &ClientDocument, position: Pos, @@ -1212,3 +1231,110 @@ pub(super) fn validate_order_entry_source( )), } } + +#[cfg(test)] +mod tests { + use super::*; + + fn object(members: Vec) -> CompiledObject { + CompiledObject { + typename: "todo".into(), + storage: CompiledStorage::Embedded, + members, + } + } + + fn branch( + semantic: CompiledBranchSemantic, + cardinality: Cardinality, + limit: Option, + selection: CompiledObject, + ) -> CompiledMember { + let mut arguments = BTreeMap::new(); + if let Some(limit) = limit { + arguments.insert( + "limit".to_owned(), + CompiledArgument::Literal { + value: JsonValue::from(limit), + wire: limit.to_string(), + }, + ); + } + CompiledMember::Branch(Box::new(CompiledBranch { + semantic, + response_key: "items".into(), + field: "items".into(), + cardinality, + nullable: false, + arguments, + dependencies: Vec::new(), + coverage: Some(CompiledCoverage { + kind: "offset".into(), + offset_argument: None, + limit_argument: Some("limit".into()), + default_limit: Some(100), + max_limit: Some(1000), + }), + filter: None, + order: None, + pagination: None, + relationship: None, + selection, + })) + } + + /// The compiler's arithmetic is the service's: nested lists multiply, + /// one-to-one relationships add one row, aggregates count their nodes. + #[test] + fn row_cost_matches_the_service() { + let many = |limit, selection| { + branch( + CompiledBranchSemantic::Relationship, + Cardinality::Many, + limit, + selection, + ) + }; + // orders(limit: 1000) { items(limit: 1000) { id } } + let nested = object(vec![many(Some(1000), object(Vec::new()))]); + assert_eq!(compiled_object_rows(&nested, 1), 1000); + assert_eq!( + row_cost::page(1000, compiled_object_rows(&nested, 1)), + 1_001_000 + ); + // An absent limit is the default page. + assert_eq!( + compiled_object_rows(&object(vec![many(None, object(Vec::new()))]), 1), + 100 + ); + // A belongs-to costs one row plus what it carries. + let one = branch( + CompiledBranchSemantic::Relationship, + Cardinality::One, + None, + object(Vec::new()), + ); + assert_eq!(compiled_object_rows(&object(vec![one]), 1), 1); + // items_aggregate(limit: 7) { aggregate { count } nodes { id } } + let aggregate = branch( + CompiledBranchSemantic::Aggregate, + Cardinality::One, + Some(7), + object(vec![ + branch( + CompiledBranchSemantic::AggregateFields, + Cardinality::One, + None, + object(Vec::new()), + ), + branch( + CompiledBranchSemantic::AggregateNodes, + Cardinality::Many, + None, + object(Vec::new()), + ), + ]), + ); + assert_eq!(compiled_object_rows(&object(vec![aggregate]), 1), 7); + } +} diff --git a/distributed_cli/src/client_compiler/graphql/variables.rs b/distributed_cli/src/client_compiler/graphql/variables.rs index e1ca7cbb9..fb5c1eee9 100644 --- a/distributed_cli/src/client_compiler/graphql/variables.rs +++ b/distributed_cli/src/client_compiler/graphql/variables.rs @@ -49,14 +49,14 @@ pub(super) fn compile_variables( #[derive(Clone, Copy)] pub(super) struct FilterInputCandidate<'a> { - model: &'a ManifestModel, - semantics: &'a ManifestFilterInput, + model: &'a ClientModel, + semantics: &'a ClientFilterInput, } #[derive(Clone, Copy)] pub(super) struct OrderInputCandidate<'a> { - model: &'a ManifestModel, - semantics: &'a ManifestOrderSemantics, + model: &'a ClientModel, + semantics: &'a ClientOrderSemantics, } pub(super) fn compile_variable_codec( @@ -220,15 +220,15 @@ pub(super) fn merge_filter_constraints( } pub(super) fn register_order_input_candidate<'a>( - arguments: &[ManifestArgument], - order: Option<&'a ManifestOrderSemantics>, - model: &'a ManifestModel, + arguments: &[ClientArgument], + order: Option<&'a ClientOrderSemantics>, + model: &'a ClientModel, orders: &mut BTreeMap>, ) -> Result<(), ClientCompileError> { if let Some(semantics) = order { if let Some(argument) = arguments .iter() - .find(|argument| argument.kind == ManifestArgumentKind::Order) + .find(|argument| argument.kind == ClientArgumentKind::Order) { register_order_input(&argument.type_name, model, semantics, orders)?; } @@ -238,8 +238,8 @@ pub(super) fn register_order_input_candidate<'a>( pub(super) fn register_filter_input<'a>( name: &str, - model: &'a ManifestModel, - semantics: &'a ManifestFilterInput, + model: &'a ClientModel, + semantics: &'a ClientFilterInput, candidates: &mut BTreeMap>, ) -> Result<(), ClientCompileError> { if let Some(existing) = candidates.get(name) { @@ -257,8 +257,8 @@ pub(super) fn register_filter_input<'a>( pub(super) fn register_order_input<'a>( name: &str, - model: &'a ManifestModel, - semantics: &'a ManifestOrderSemantics, + model: &'a ClientModel, + semantics: &'a ClientOrderSemantics, candidates: &mut BTreeMap>, ) -> Result<(), ClientCompileError> { if let Some(existing) = candidates.get(name) { diff --git a/distributed_cli/src/client_compiler/islands.rs b/distributed_cli/src/client_compiler/islands.rs index 1f5f5200e..7afa5b253 100644 --- a/distributed_cli/src/client_compiler/islands.rs +++ b/distributed_cli/src/client_compiler/islands.rs @@ -1,7 +1,7 @@ use serde::Serialize; use super::graphql::{Cardinality, CompiledOperation}; -use super::manifest::{hash_bytes, ClientManifest, ManifestSurface}; +use super::manifest::{hash_bytes, ClientManifest, ClientSurfaceIdentity}; use super::{ GeneratedIslandDirectives, GeneratedIslandLiveCoverage, GeneratedIslandPlan, GeneratedIslandSource, GeneratedIslandVariable, GeneratedIslandVariableSchema, @@ -15,7 +15,7 @@ pub(crate) struct GeneratedIslandInventory<'a> { pub(crate) version: u32, pub(crate) schema_fingerprint: &'a str, pub(crate) protocol_fingerprint: &'a str, - pub(crate) surface: &'a ManifestSurface, + pub(crate) surface: &'a ClientSurfaceIdentity, pub(crate) islands: &'a [GeneratedIslandPlan], } diff --git a/distributed_cli/src/client_compiler/manifest/commands.rs b/distributed_cli/src/client_compiler/manifest/commands.rs index 582163ddd..df6e46e99 100644 --- a/distributed_cli/src/client_compiler/manifest/commands.rs +++ b/distributed_cli/src/client_compiler/manifest/commands.rs @@ -1,7 +1,7 @@ use super::*; pub(crate) fn canonicalize_commands( - commands: &mut [ManifestCommand], + commands: &mut [ClientCommand], ) -> Result<(), ClientCompileError> { for command in commands.iter_mut() { canonicalize_string_set( @@ -46,7 +46,9 @@ pub(crate) fn canonicalize_commands( &format!("command `{}` input default path", command.name), )?; } - defaults.defaults.sort(); + defaults + .defaults + .sort_by(|left, right| left.path.cmp(&right.path)); if defaults .defaults .windows(2) @@ -66,54 +68,13 @@ pub(crate) fn canonicalize_commands( canonicalize_effect_expression(partition); } } - if let Some(effects) = &mut command.extensions.effects { - for effect in &mut effects.operations { - canonicalize_effect(effect); - } - } - if let Some(confirmations) = &mut command.extensions.confirmations { - for confirmation in &mut confirmations.expected { - canonicalize_effect_key(&mut confirmation.key); - if let Some(partition) = &mut confirmation.partition { - canonicalize_effect_expression(partition); - } - } - } } commands.sort_by(|left, right| left.name.cmp(&right.name)); Ok(()) } -pub(crate) fn canonicalize_effect(effect: &mut ManifestEffect) { - match effect { - ManifestEffect::Upsert { key, fields, .. } | ManifestEffect::Patch { key, fields, .. } => { - canonicalize_effect_key(key); - for field in fields.iter_mut() { - canonicalize_effect_expression(&mut field.value); - } - fields.sort_by(|left, right| left.field.cmp(&right.field)); - } - ManifestEffect::Delete { key, .. } => canonicalize_effect_key(key), - ManifestEffect::Link { source, target, .. } - | ManifestEffect::Unlink { source, target, .. } => { - canonicalize_effect_key(source); - canonicalize_effect_key(target); - } - ManifestEffect::InvalidateRelationship { source, .. } => { - canonicalize_effect_key(source); - } - ManifestEffect::InvalidateModel { .. } => {} - } -} - -pub(crate) fn canonicalize_effect_key(key: &mut ManifestEffectKey) { - for field in &mut key.fields { - canonicalize_effect_expression(&mut field.value); - } -} - -pub(crate) fn canonicalize_effect_expression(expression: &mut ManifestEffectExpression) { - if let ManifestEffectExpression::Constant { value } = expression { +pub(crate) fn canonicalize_effect_expression(expression: &mut EffectExpression) { + if let EffectExpression::Constant { value } = expression { *value = canonical_json_value(std::mem::take(value)); } } diff --git a/distributed_cli/src/client_compiler/manifest/leaderboards.rs b/distributed_cli/src/client_compiler/manifest/leaderboards.rs new file mode 100644 index 000000000..0e844122b --- /dev/null +++ b/distributed_cli/src/client_compiler/manifest/leaderboards.rs @@ -0,0 +1,138 @@ +//! Leaderboard section of the client manifest: server-ranked board queries +//! (`top`, `around_me`, `my_rank`, `rank`) generated into `leaderboards.ts`. +//! They are not read-model roots and never enter the replica cache. + +use std::collections::BTreeSet; + +use super::*; + +/// The only row type the framework emits for leaderboards. +pub(crate) const LEADERBOARD_ENTRY_TYPENAME: &str = "LeaderboardEntry"; + +fn invalid(message: impl Into) -> ClientCompileError { + ClientCompileError::manifest("client.manifest.leaderboard", message) +} + +/// The typed `leaderboards` section of the manifest's external read sources. +/// Any other section is refused: this compiler cannot generate a client for +/// it. +pub(crate) fn external_leaderboards( + external: &std::collections::BTreeMap>, +) -> Result, ClientCompileError> { + let mut leaderboards = Vec::new(); + for (section, values) in external { + if section != LEADERBOARDS_SECTION { + return Err(ClientCompileError::manifest( + "client.manifest.external", + format!("unknown external read source section `{section}`"), + )); + } + for value in values { + leaderboards.push( + serde_json::from_value(value.clone()) + .map_err(|error| invalid(format!("malformed leaderboard: {error}")))?, + ); + } + } + Ok(leaderboards) +} + +/// Validate the leaderboard section against itself and the read-model roots. +pub(crate) fn validate_leaderboards( + leaderboards: &[ClientLeaderboard], + roots: &std::collections::BTreeMap<(ClientRootOperation, String), ClientRoot>, + typenames: &BTreeSet, +) -> Result<(), ClientCompileError> { + if !leaderboards.is_empty() && typenames.contains(LEADERBOARD_ENTRY_TYPENAME) { + return Err(invalid(format!( + "model typename `{LEADERBOARD_ENTRY_TYPENAME}` collides with the leaderboard entry type" + ))); + } + let mut names = BTreeSet::new(); + let mut root_names = roots + .keys() + .map(|(_, name)| name.clone()) + .collect::>(); + for leaderboard in leaderboards { + if !is_graphql_name(&leaderboard.name) || !names.insert(leaderboard.name.clone()) { + return Err(invalid(format!( + "invalid or duplicate leaderboard `{}`", + leaderboard.name + ))); + } + if leaderboard.entry_typename != LEADERBOARD_ENTRY_TYPENAME { + return Err(invalid(format!( + "leaderboard `{}` entry type must be `{LEADERBOARD_ENTRY_TYPENAME}`", + leaderboard.name + ))); + } + if !matches!(leaderboard.order.as_str(), "high_first" | "low_first") + || !matches!(leaderboard.boards.as_str(), "single" | "family") + { + return Err(invalid(format!( + "leaderboard `{}` has an unknown order or board kind", + leaderboard.name + ))); + } + if leaderboard.default_first == 0 + || leaderboard.default_first > leaderboard.max_first + || leaderboard.max_radius == 0 + { + return Err(invalid(format!( + "leaderboard `{}` has inconsistent limits", + leaderboard.name + ))); + } + if leaderboard.roots.is_empty() { + return Err(invalid(format!( + "leaderboard `{}` exposes no roots", + leaderboard.name + ))); + } + let family = leaderboard.boards == "family"; + for root in &leaderboard.roots { + if !is_graphql_name(&root.name) || !root_names.insert(root.name.clone()) { + return Err(invalid(format!( + "leaderboard root `{}` is invalid or collides with another root", + root.name + ))); + } + let (list, live, extra): (bool, bool, Option<(&str, &str, bool)>) = + match root.operation.as_str() { + "top" => (true, root.live, Some(("first", "Int", true))), + "around_me" => (true, root.live, Some(("radius", "Int", true))), + "my_rank" => (false, root.live, None), + "rank" => (false, false, Some(("member", "String", false))), + other => { + return Err(invalid(format!( + "leaderboard root `{}` has unknown operation `{other}`", + root.name + ))) + } + }; + let mut expected = Vec::new(); + if family { + expected.push(("board", "String", false)); + } + expected.extend(extra); + let actual = root + .arguments + .iter() + .map(|argument| { + ( + argument.name.as_str(), + argument.type_name.as_str(), + argument.nullable, + ) + }) + .collect::>(); + if root.list != list || root.live != live || actual != expected { + return Err(invalid(format!( + "leaderboard root `{}` does not match its `{}` contract", + root.name, root.operation + ))); + } + } + } + Ok(()) +} diff --git a/distributed_cli/src/client_compiler/manifest/mod.rs b/distributed_cli/src/client_compiler/manifest/mod.rs index 92e747912..8d63c0269 100644 --- a/distributed_cli/src/client_compiler/manifest/mod.rs +++ b/distributed_cli/src/client_compiler/manifest/mod.rs @@ -1,33 +1,35 @@ mod commands; +mod leaderboards; mod model_validation; mod parse; mod projections; mod projectors; mod roots; -mod types; mod util; -pub(crate) use super::{is_graphql_name, ClientCompileError, ClientSurfaceSelector}; +pub(crate) use super::{is_graphql_name, ClientCompileError}; pub(crate) use commands::*; +pub(crate) use leaderboards::*; pub(crate) use model_validation::*; +pub(crate) use parse::ClientManifest; pub(crate) use projections::*; pub(crate) use projectors::*; pub(crate) use roots::*; pub(crate) use util::{validate_hash, validate_nonempty}; -const MANIFEST_VERSION: u64 = 2; -const PROTOCOL_VERSION: u64 = 1; -const PROTOCOL_FINGERPRINT: &str = - "sha256:00fb342f3acb4dc1c1716a43cc3001c748d5f6c500ff831690d820e9e43e2782"; +// The manifest contract is the runtime's: one definition of every type, +// version and fingerprint. +pub(crate) use distributed::command::{CommandConsistency, CommandInputDefault, EffectExpression}; +pub(crate) use distributed::graphql::*; +pub(crate) use distributed::projection::placement::{ + ProjectionBindingState, ProjectionExecutionClass, ProjectionPlacement, +}; +pub(crate) use distributed::projection::{ + ProjectionRelationshipEffectKind, ProjectionScalarTransform, ProjectionValueType, + PROJECTION_OPERATION_SEMANTICS_VERSION, PROJECTION_PROGRAM_IR_VERSION, +}; +pub(crate) use distributed_leaderboard::{ + ClientLeaderboard, ClientLeaderboardRoot, LEADERBOARDS_SECTION, +}; -pub(crate) const CLIENT_PROJECTION_PROGRAM_VERSION: u32 = 2; -pub(crate) const CLIENT_PROJECTION_BINDING_VERSION: u32 = 1; -pub(crate) const COMMAND_PROJECTION_EXTENSION_VERSION: u32 = 2; -pub(crate) const PROJECTION_PROGRAM_IR_VERSION: u16 = 1; -pub(crate) const PROJECTION_OPERATION_SEMANTICS_VERSION: u16 = 1; - -pub(crate) use types::*; pub(crate) use util::{canonical_json_value, hash_bytes, validate_exact_operation_hash}; - -#[cfg(test)] -pub(crate) use parse::refresh_schema_fingerprint; diff --git a/distributed_cli/src/client_compiler/manifest/model_validation.rs b/distributed_cli/src/client_compiler/manifest/model_validation.rs index dcf9db697..079295d9f 100644 --- a/distributed_cli/src/client_compiler/manifest/model_validation.rs +++ b/distributed_cli/src/client_compiler/manifest/model_validation.rs @@ -4,48 +4,14 @@ use serde_json::Value as JsonValue; use super::*; -pub(crate) fn validate_input_default_generators_in_json( - value: &JsonValue, -) -> Result<(), ClientCompileError> { - let Some(commands) = value.get("commands").and_then(JsonValue::as_array) else { - return Ok(()); - }; - for (command_index, command) in commands.iter().enumerate() { - let command_name = command - .get("name") - .and_then(JsonValue::as_str) - .unwrap_or(""); - let Some(defaults) = command - .pointer("/extensions/input_defaults/defaults") - .and_then(JsonValue::as_array) - else { - continue; - }; - for (default_index, default) in defaults.iter().enumerate() { - if !matches!( - default.get("generator").and_then(JsonValue::as_str), - Some("uuid_v7" | "ulid") - ) { - return Err(ClientCompileError::manifest( - "client.manifest.input_default_generator", - format!( - "manifest command `{command_name}` input default {default_index} must use uuid_v7 or ulid (commands[{command_index}])" - ), - )); - } - } - } - Ok(()) -} - pub(crate) fn canonicalize_surface( - surface: &mut ManifestSurface, + surface: &mut ClientSurfaceIdentity, ) -> Result<(), ClientCompileError> { match surface { - ManifestSurface::Role { name } => { + ClientSurfaceIdentity::Role { name } => { validate_nonempty(name, "manifest.surface.name")?; } - ManifestSurface::Application { + ClientSurfaceIdentity::Application { name, eligible_roles, schema_roles, @@ -137,21 +103,21 @@ pub(crate) fn validate_graphql_name(value: &str, label: &str) -> Result<(), Clie } pub(crate) fn validate_surface( - actual: &ManifestSurface, - expected: &ClientSurfaceSelector, + actual: &ClientSurfaceIdentity, + expected: &ClientSurfaceIdentity, ) -> Result<(), ClientCompileError> { let matches = match (actual, expected) { ( - ManifestSurface::Role { name: actual }, - ClientSurfaceSelector::Role { name: expected }, + ClientSurfaceIdentity::Role { name: actual }, + ClientSurfaceIdentity::Role { name: expected }, ) => !expected.trim().is_empty() && actual == expected, ( - ManifestSurface::Application { + ClientSurfaceIdentity::Application { name: actual, eligible_roles, schema_roles, }, - ClientSurfaceSelector::Application { + ClientSurfaceIdentity::Application { name: expected, eligible_roles: expected_eligible_roles, schema_roles: expected_schema_roles, @@ -175,12 +141,12 @@ pub(crate) fn validate_surface( return Ok(()); } let actual_label = match actual { - ManifestSurface::Role { name } => format!("role `{name}`"), - ManifestSurface::Application { name, .. } => format!("application `{name}`"), + ClientSurfaceIdentity::Role { name } => format!("role `{name}`"), + ClientSurfaceIdentity::Application { name, .. } => format!("application `{name}`"), }; let expected_label = match expected { - ClientSurfaceSelector::Role { name } => format!("role `{name}`"), - ClientSurfaceSelector::Application { + ClientSurfaceIdentity::Role { name } => format!("role `{name}`"), + ClientSurfaceIdentity::Application { name, eligible_roles, schema_roles, @@ -199,7 +165,7 @@ pub(crate) fn validate_surface( } pub(crate) fn validate_capabilities( - capabilities: &ManifestCapabilities, + capabilities: &ClientCapabilities, ) -> Result<(), ClientCompileError> { if capabilities.query_fallback != "revalidate" { return Err(ClientCompileError::manifest( @@ -226,11 +192,13 @@ pub(crate) fn validate_capabilities( } pub(crate) fn validate_execution_limits( - execution: &ManifestExecutionLimits, + execution: &ClientExecutionLimits, ) -> Result<(), ClientCompileError> { const JS_MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991; for (name, value) in [ ("max_depth", execution.max_depth), + ("max_fields", execution.max_fields), + ("max_rows", execution.max_rows), ("max_bool_width", execution.max_bool_width), ("max_in_list", execution.max_in_list), ] { @@ -241,42 +209,19 @@ pub(crate) fn validate_execution_limits( )); } } - if execution.complexity.version != 1 { - return Err(ClientCompileError::manifest( - "client.manifest.complexity_version", - format!( - "unsupported query complexity contract version {}; distributed requires version 1", - execution.complexity.version - ), - )); - } - let weights = [ - ("scalar", execution.complexity.scalar), - ("belongs_to", execution.complexity.belongs_to), - ("has_many", execution.complexity.has_many), - ("m2m", execution.complexity.m2m), - ("aggregate", execution.complexity.aggregate), - ("list_root", execution.complexity.list_root), - ("by_pk", execution.complexity.by_pk), - ("list_fanout", execution.complexity.list_fanout), - ]; - if let Some((name, _)) = weights.into_iter().find(|(_, value)| *value == 0) { - return Err(ClientCompileError::manifest( - "client.manifest.complexity_weight", - format!("query complexity weight `{name}` must be greater than zero"), - )); - } Ok(()) } pub(crate) fn validate_derived_capabilities( - capabilities: &ManifestCapabilities, - roots: &BTreeMap<(RootOperation, String), ManifestRoot>, - commands: &[ManifestCommand], + capabilities: &ClientCapabilities, + roots: &BTreeMap<(ClientRootOperation, String), ClientRoot>, + commands: &[ClientCommand], + live_leaderboards: bool, ) -> Result<(), ClientCompileError> { - let has_live_roots = roots - .keys() - .any(|(operation, _)| *operation == RootOperation::Subscription); + let has_live_roots = live_leaderboards + || roots + .keys() + .any(|(operation, _)| *operation == ClientRootOperation::Subscription); if capabilities.live_queries != has_live_roots { return Err(ClientCompileError::manifest( "client.manifest.live_capability", @@ -300,7 +245,7 @@ pub(crate) fn validate_derived_capabilities( } pub(crate) fn validate_scalar_codecs( - codecs: Vec, + codecs: Vec, ) -> Result, ClientCompileError> { if codecs.is_empty() { return Err(ClientCompileError::manifest( @@ -364,7 +309,7 @@ pub(crate) fn validate_scalar_codecs( Ok(result) } -pub(crate) fn canonicalize_model(model: &mut ManifestModel) -> Result<(), ClientCompileError> { +pub(crate) fn canonicalize_model(model: &mut ClientModel) -> Result<(), ClientCompileError> { canonicalize_string_set( &mut model.dependencies, &format!("model `{}` dependency", model.id), @@ -419,41 +364,41 @@ pub(crate) fn canonicalize_model(model: &mut ManifestModel) -> Result<(), Client Ok(()) } -pub(crate) fn canonicalize_row_policy(policy: &mut ManifestRowPolicy) { - if let ManifestRowPolicy::Predicate { expression } = policy { +pub(crate) fn canonicalize_row_policy(policy: &mut ClientRowPolicy) { + if let ClientRowPolicy::Predicate { expression } = policy { canonicalize_filter_expression(expression); } } -pub(crate) fn canonicalize_filter_expression(expression: &mut ManifestFilterExpr) { +pub(crate) fn canonicalize_filter_expression(expression: &mut FilterExpr) { match expression { - ManifestFilterExpr::And(expressions) | ManifestFilterExpr::Or(expressions) => { + FilterExpr::And(expressions) | FilterExpr::Or(expressions) => { for expression in expressions { canonicalize_filter_expression(expression); } } - ManifestFilterExpr::Not(expression) => canonicalize_filter_expression(expression), - ManifestFilterExpr::Cmp { rhs, .. } => canonicalize_operand(rhs), - ManifestFilterExpr::In { values, .. } => { + FilterExpr::Not(expression) => canonicalize_filter_expression(expression), + FilterExpr::Cmp { rhs, .. } => canonicalize_operand(rhs), + FilterExpr::In { values, .. } => { for operand in values { canonicalize_operand(operand); } } - ManifestFilterExpr::Rel { predicate, .. } => { + FilterExpr::Rel { predicate, .. } => { canonicalize_filter_expression(predicate); } - ManifestFilterExpr::IsNull { .. } => {} + FilterExpr::IsNull { .. } => {} } } -pub(crate) fn canonicalize_operand(operand: &mut ManifestOperand) { - if let ManifestOperand::Lit(ManifestLitValue::Json(value)) = operand { +pub(crate) fn canonicalize_operand(operand: &mut Operand) { + if let Operand::Lit(LitValue::Json(value)) = operand { *value = canonical_json_value(std::mem::take(value)); } } pub(crate) fn canonicalize_filter_semantics( - semantics: &mut ManifestFilterSemantics, + semantics: &mut ClientFilterSemantics, ) -> Result<(), ClientCompileError> { canonicalize_filter_fields(&mut semantics.fields)?; canonicalize_string_set(&mut semantics.relationships, "filter relationship")?; @@ -462,7 +407,7 @@ pub(crate) fn canonicalize_filter_semantics( } pub(crate) fn canonicalize_filter_input( - input: &mut ManifestFilterInput, + input: &mut ClientFilterInput, ) -> Result<(), ClientCompileError> { canonicalize_filter_fields(&mut input.fields)?; input @@ -472,7 +417,7 @@ pub(crate) fn canonicalize_filter_input( } pub(crate) fn canonicalize_filter_fields( - fields: &mut [ManifestFilterField], + fields: &mut [ClientFilterField], ) -> Result<(), ClientCompileError> { fields.sort_by(|left, right| left.name.cmp(&right.name)); for field in fields { @@ -485,14 +430,14 @@ pub(crate) fn canonicalize_filter_fields( } pub(crate) fn canonicalize_order_semantics( - semantics: &mut ManifestOrderSemantics, + semantics: &mut ClientOrderSemantics, ) -> Result<(), ClientCompileError> { canonicalize_string_set(&mut semantics.fields, "order field")?; canonicalize_string_set(&mut semantics.values, "order value") } pub(crate) fn canonicalize_aggregate_semantics( - semantics: &mut ManifestAggregateSemantics, + semantics: &mut ClientAggregateSemantics, ) -> Result<(), ClientCompileError> { canonicalize_string_set(&mut semantics.sum, "aggregate sum field")?; canonicalize_string_set(&mut semantics.avg, "aggregate avg field")?; @@ -501,7 +446,7 @@ pub(crate) fn canonicalize_aggregate_semantics( } pub(crate) fn canonicalize_arguments( - arguments: &mut [ManifestArgument], + arguments: &mut [ClientArgument], _label: &str, ) -> Result<(), ClientCompileError> { arguments.sort_by(|left, right| left.name.cmp(&right.name)); @@ -509,7 +454,7 @@ pub(crate) fn canonicalize_arguments( } pub(crate) fn validate_model( - model: &ManifestModel, + model: &ClientModel, scalar_codecs: &BTreeMap, ) -> Result<(), ClientCompileError> { validate_graphql_name(&model.id, "manifest model id")?; @@ -611,8 +556,8 @@ pub(crate) fn validate_model( )?; } match &model.normalization { - ManifestNormalization::Embedded => {} - ManifestNormalization::Normalized { fields, encoding } => { + ModelNormalization::Embedded => {} + ModelNormalization::Normalized { fields, encoding } => { if encoding != "canonical_json_tuple_v1" { return Err(ClientCompileError::manifest( "client.manifest.identity_encoding", @@ -666,7 +611,7 @@ pub(crate) fn validate_model( } pub(crate) fn validate_model_graph( - models: &BTreeMap, + models: &BTreeMap, scalar_codecs: &BTreeMap, ) -> Result<(), ClientCompileError> { for model in models.values() { @@ -705,8 +650,7 @@ pub(crate) fn validate_model_graph( &target.source_table, &format!("relationship {}.{}", model.id, relationship.name), )?; - if let ManifestRelationshipKeyMapping::Through { table, .. } = &relationship.key_mapping - { + if let RelationshipKeyMapping::Through { table, .. } = &relationship.key_mapping { require_dependency( &relationship.dependencies, table, @@ -714,7 +658,7 @@ pub(crate) fn validate_model_graph( )?; } match relationship.kind { - ManifestRelationshipKind::BelongsTo if relationship.list => { + ClientRelationshipKind::BelongsTo if relationship.list => { return Err(ClientCompileError::manifest( "client.manifest.relationship_cardinality", format!( @@ -723,7 +667,7 @@ pub(crate) fn validate_model_graph( ), )); } - ManifestRelationshipKind::HasMany | ManifestRelationshipKind::ManyToMany + ClientRelationshipKind::HasMany | ClientRelationshipKind::ManyToMany if !relationship.list => { return Err(ClientCompileError::manifest( @@ -753,9 +697,9 @@ pub(crate) fn validate_model_graph( } pub(crate) fn validate_key_mapping( - source: &ManifestModel, - target: &ManifestModel, - relationship: &ManifestRelationship, + source: &ClientModel, + target: &ClientModel, + relationship: &ClientRelationship, ) -> Result<(), ClientCompileError> { let validate_fields = |local: &[String], remote: &[String]| { if local.is_empty() || local.len() != remote.len() { @@ -813,13 +757,12 @@ pub(crate) fn validate_key_mapping( }; let local_maintenance = matches!( relationship.key_mapping, - ManifestRelationshipKeyMapping::Direct { .. } - | ManifestRelationshipKeyMapping::Through { .. } + RelationshipKeyMapping::Direct { .. } | RelationshipKeyMapping::Through { .. } ); if local_maintenance != matches!( relationship.maintenance, - ManifestRelationshipMaintenance::Local + ClientRelationshipMaintenance::Local ) { return Err(ClientCompileError::manifest( @@ -831,8 +774,8 @@ pub(crate) fn validate_key_mapping( )); } match &relationship.key_mapping { - ManifestRelationshipKeyMapping::Direct { local, remote } => validate_fields(local, remote), - ManifestRelationshipKeyMapping::Through { + RelationshipKeyMapping::Direct { local, remote } => validate_fields(local, remote), + RelationshipKeyMapping::Through { local, remote, table, @@ -862,7 +805,7 @@ pub(crate) fn validate_key_mapping( "relationship through target foreign key", ) } - ManifestRelationshipKeyMapping::ThroughOpaque { + RelationshipKeyMapping::ThroughOpaque { local, remote, dependency, @@ -884,15 +827,15 @@ pub(crate) fn validate_key_mapping( } Ok(()) } - ManifestRelationshipKeyMapping::Embedded => Ok(()), + RelationshipKeyMapping::Embedded => Ok(()), } } pub(crate) fn validate_relationship_semantics( - source: &ManifestModel, - target: &ManifestModel, - relationship: &ManifestRelationship, - models: &BTreeMap, + source: &ClientModel, + target: &ClientModel, + relationship: &ClientRelationship, + models: &BTreeMap, scalar_codecs: &BTreeMap, ) -> Result<(), ClientCompileError> { validate_filter_argument_type( @@ -903,19 +846,19 @@ pub(crate) fn validate_relationship_semantics( let has_filter_argument = relationship .arguments .iter() - .any(|argument| argument.kind == ManifestArgumentKind::Filter); + .any(|argument| argument.kind == ClientArgumentKind::Filter); let has_order_argument = relationship .arguments .iter() - .any(|argument| argument.kind == ManifestArgumentKind::Order); + .any(|argument| argument.kind == ClientArgumentKind::Order); let has_limit_argument = relationship .arguments .iter() - .any(|argument| argument.kind == ManifestArgumentKind::Limit); + .any(|argument| argument.kind == ClientArgumentKind::Limit); let has_offset_argument = relationship .arguments .iter() - .any(|argument| argument.kind == ManifestArgumentKind::Offset); + .any(|argument| argument.kind == ClientArgumentKind::Offset); if relationship.filter.is_some() != has_filter_argument || relationship.order.is_some() != has_order_argument || relationship.pagination.is_some() != (has_limit_argument && has_offset_argument) @@ -1020,9 +963,9 @@ pub(crate) fn validate_relationship_semantics( } pub(crate) fn validate_filter_input( - input: &ManifestFilterInput, - model: &ManifestModel, - models: &BTreeMap, + input: &ClientFilterInput, + model: &ClientModel, + models: &BTreeMap, ) -> Result<(), ClientCompileError> { validate_filter_fields(&input.fields, model)?; let expected_relationships = model @@ -1085,8 +1028,8 @@ pub(crate) fn validate_filter_input( } pub(crate) fn validate_filter_fields( - fields: &[ManifestFilterField], - model: &ManifestModel, + fields: &[ClientFilterField], + model: &ClientModel, ) -> Result<(), ClientCompileError> { let expected_fields = model .fields @@ -1134,6 +1077,7 @@ pub(crate) fn validate_filter_fields( | "_is_null" | "_like" | "_ilike" + | "_icontains" | "_contains" | "_contained_in" | "_has_key" @@ -1152,9 +1096,9 @@ pub(crate) fn validate_filter_fields( } pub(crate) fn validate_filter_semantics( - semantics: &ManifestFilterSemantics, - model: &ManifestModel, - models: &BTreeMap, + semantics: &ClientFilterSemantics, + model: &ClientModel, + models: &BTreeMap, ) -> Result<(), ClientCompileError> { if semantics.fields != model.filter_input.fields { return Err(ClientCompileError::manifest( @@ -1198,13 +1142,13 @@ pub(crate) fn validate_filter_semantics( } pub(crate) fn validate_filter_argument_type( - arguments: &[ManifestArgument], - model: &ManifestModel, + arguments: &[ClientArgument], + model: &ClientModel, owner: &str, ) -> Result<(), ClientCompileError> { let Some(argument) = arguments .iter() - .find(|argument| argument.kind == ManifestArgumentKind::Filter) + .find(|argument| argument.kind == ClientArgumentKind::Filter) else { return Ok(()); }; @@ -1221,8 +1165,8 @@ pub(crate) fn validate_filter_argument_type( } pub(crate) fn validate_order_semantics( - semantics: &ManifestOrderSemantics, - model: &ManifestModel, + semantics: &ClientOrderSemantics, + model: &ClientModel, ) -> Result<(), ClientCompileError> { let expected_fields = model .fields @@ -1271,7 +1215,7 @@ pub(crate) fn validate_order_semantics( } pub(crate) fn validate_pagination( - pagination: &ManifestPagination, + pagination: &ClientPaginationSemantics, owner: &str, ) -> Result<(), ClientCompileError> { if pagination.kind != "offset" || pagination.coverage != "window" { @@ -1290,8 +1234,8 @@ pub(crate) fn validate_pagination( } pub(crate) fn validate_aggregate_semantics( - aggregate: &ManifestAggregateSemantics, - model: &ManifestModel, + aggregate: &ClientAggregateSemantics, + model: &ClientModel, ) -> Result<(), ClientCompileError> { validate_graphql_name(&aggregate.wrapper_typename, "aggregate wrapper typename")?; validate_graphql_name(&aggregate.fields_typename, "aggregate fields typename")?; @@ -1330,159 +1274,18 @@ pub(crate) fn validate_aggregate_semantics( } pub(crate) fn validate_row_policy( - policy: &ManifestRowPolicy, - model: &ManifestModel, - models: &BTreeMap, + policy: &ClientRowPolicy, + model: &ClientModel, + models: &BTreeMap, ) -> Result<(), ClientCompileError> { match policy { - ManifestRowPolicy::Unrestricted | ManifestRowPolicy::ServerOnly => Ok(()), - ManifestRowPolicy::Predicate { expression } => { + ClientRowPolicy::Unrestricted | ClientRowPolicy::ServerOnly => Ok(()), + ClientRowPolicy::Predicate { expression } => { validate_filter_expression(expression, model, models) } } } -pub(crate) fn derive_trusted_preset_descriptors( - models: &BTreeMap, - commands: &[ManifestCommand], -) -> Result, ClientCompileError> { - let mut descriptors = BTreeMap::::new(); - for command in commands { - for descriptor in &command.extensions.trusted_presets { - insert_trusted_preset_descriptor( - &mut descriptors, - descriptor, - &format!("command `{}`", command.name), - )?; - } - } - for model in models.values() { - if let ManifestRowPolicy::Predicate { expression } = &model.row_policy { - collect_row_policy_trusted_presets(expression, model, models, &mut descriptors)?; - } - } - Ok(descriptors - .into_iter() - .map(|(name, codec)| ManifestTrustedPresetDescriptor { name, codec }) - .collect()) -} - -pub(crate) fn collect_row_policy_trusted_presets( - expression: &ManifestFilterExpr, - model: &ManifestModel, - models: &BTreeMap, - descriptors: &mut BTreeMap, -) -> Result<(), ClientCompileError> { - match expression { - ManifestFilterExpr::And(expressions) | ManifestFilterExpr::Or(expressions) => { - for expression in expressions { - collect_row_policy_trusted_presets(expression, model, models, descriptors)?; - } - } - ManifestFilterExpr::Not(expression) => { - collect_row_policy_trusted_presets(expression, model, models, descriptors)?; - } - ManifestFilterExpr::Cmp { - column, - rhs: ManifestOperand::Claim(claim), - .. - } => { - insert_row_policy_trusted_preset(model, column, &claim.header, descriptors)?; - } - ManifestFilterExpr::In { column, values, .. } => { - for value in values { - if let ManifestOperand::Claim(claim) = value { - insert_row_policy_trusted_preset(model, column, &claim.header, descriptors)?; - } - } - } - ManifestFilterExpr::Rel { field, predicate } => { - let relationship = model.relationship(field).ok_or_else(|| { - ClientCompileError::manifest( - "client.manifest.row_policy_relationship", - format!( - "model `{}` row policy references absent relationship `{field}`", - model.id - ), - ) - })?; - let target = models.get(&relationship.target_model).ok_or_else(|| { - ClientCompileError::manifest( - "client.manifest.row_policy_relationship", - format!( - "model `{}` row policy relationship `{field}` targets absent model `{}`", - model.id, relationship.target_model - ), - ) - })?; - collect_row_policy_trusted_presets(predicate, target, models, descriptors)?; - } - ManifestFilterExpr::Cmp { .. } | ManifestFilterExpr::IsNull { .. } => {} - } - Ok(()) -} - -pub(crate) fn insert_row_policy_trusted_preset( - model: &ManifestModel, - column: &str, - name: &str, - descriptors: &mut BTreeMap, -) -> Result<(), ClientCompileError> { - let field = model.field(column).ok_or_else(|| { - ClientCompileError::manifest( - "client.manifest.row_policy_column", - format!( - "model `{}` row policy references absent field `{column}`", - model.id - ), - ) - })?; - if matches!(field.codec.as_str(), "base64" | "json") { - return Err(ClientCompileError::manifest( - "client.manifest.row_policy_portability", - format!( - "model `{}` row-policy claim `{name}` targets `{column}` with non-local codec `{}`", - model.id, field.codec - ), - )); - } - insert_trusted_preset_descriptor( - descriptors, - &ManifestTrustedPresetDescriptor { - name: name.into(), - codec: field.codec.clone(), - }, - &format!("model `{}` row policy field `{column}`", model.id), - ) -} - -pub(crate) fn insert_trusted_preset_descriptor( - descriptors: &mut BTreeMap, - descriptor: &ManifestTrustedPresetDescriptor, - owner: &str, -) -> Result<(), ClientCompileError> { - validate_trusted_preset_name(&descriptor.name, "trusted preset name")?; - match descriptors.entry(descriptor.name.clone()) { - std::collections::btree_map::Entry::Vacant(entry) => { - entry.insert(descriptor.codec.clone()); - } - std::collections::btree_map::Entry::Occupied(entry) if entry.get() == &descriptor.codec => { - } - std::collections::btree_map::Entry::Occupied(entry) => { - return Err(ClientCompileError::manifest( - "client.manifest.trusted_preset_inventory", - format!( - "trusted preset `{}` uses incompatible codecs `{}` and `{}` across the selected client surface ({owner})", - descriptor.name, - entry.get(), - descriptor.codec - ), - )); - } - } - Ok(()) -} - pub(crate) fn validate_trusted_preset_name( value: &str, description: &str, @@ -1498,33 +1301,31 @@ pub(crate) fn validate_trusted_preset_name( } pub(crate) fn validate_filter_expression( - expression: &ManifestFilterExpr, - model: &ManifestModel, - models: &BTreeMap, + expression: &FilterExpr, + model: &ClientModel, + models: &BTreeMap, ) -> Result<(), ClientCompileError> { match expression { - ManifestFilterExpr::And(expressions) | ManifestFilterExpr::Or(expressions) => { + FilterExpr::And(expressions) | FilterExpr::Or(expressions) => { for expression in expressions { validate_filter_expression(expression, model, models)?; } Ok(()) } - ManifestFilterExpr::Not(expression) => { - validate_filter_expression(expression, model, models) - } - ManifestFilterExpr::Cmp { column, rhs, .. } => { + FilterExpr::Not(expression) => validate_filter_expression(expression, model, models), + FilterExpr::Cmp { column, rhs, .. } => { validate_policy_column(model, column)?; validate_operand(rhs) } - ManifestFilterExpr::In { column, values, .. } => { + FilterExpr::In { column, values, .. } => { validate_policy_column(model, column)?; for operand in values { validate_operand(operand)?; } Ok(()) } - ManifestFilterExpr::IsNull { column, .. } => validate_policy_column(model, column), - ManifestFilterExpr::Rel { field, predicate } => { + FilterExpr::IsNull { column, .. } => validate_policy_column(model, column), + FilterExpr::Rel { field, predicate } => { let relationship = model.relationship(field).ok_or_else(|| { ClientCompileError::manifest( "client.manifest.row_policy_relationship", @@ -1549,7 +1350,7 @@ pub(crate) fn validate_filter_expression( } pub(crate) fn validate_policy_column( - model: &ManifestModel, + model: &ClientModel, column: &str, ) -> Result<(), ClientCompileError> { if model.field(column).is_none() { @@ -1564,7 +1365,7 @@ pub(crate) fn validate_policy_column( Ok(()) } -pub(crate) fn validate_operand(operand: &ManifestOperand) -> Result<(), ClientCompileError> { +pub(crate) fn validate_operand(operand: &Operand) -> Result<(), ClientCompileError> { const JS_MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991; fn json_is_portable(value: &JsonValue) -> bool { @@ -1584,17 +1385,15 @@ pub(crate) fn validate_operand(operand: &ManifestOperand) -> Result<(), ClientCo } } - if let ManifestOperand::Claim(claim) = operand { + if let Operand::Claim(claim) = operand { validate_trusted_preset_name(&claim.header, "row policy claim header")?; return Ok(()); } let portable = match operand { - ManifestOperand::Claim(_) => unreachable!("claim returned above"), - ManifestOperand::Lit(ManifestLitValue::I64(value)) => { - value.unsigned_abs() <= JS_MAX_SAFE_INTEGER - } - ManifestOperand::Lit(ManifestLitValue::Json(value)) => json_is_portable(value), - ManifestOperand::Lit(_) => true, + Operand::Claim(_) => unreachable!("claim returned above"), + Operand::Lit(LitValue::I64(value)) => value.unsigned_abs() <= JS_MAX_SAFE_INTEGER, + Operand::Lit(LitValue::Json(value)) => json_is_portable(value), + Operand::Lit(_) => true, }; if !portable { return Err(ClientCompileError::manifest( diff --git a/distributed_cli/src/client_compiler/manifest/parse.rs b/distributed_cli/src/client_compiler/manifest/parse.rs index c9651b271..3eefdc702 100644 --- a/distributed_cli/src/client_compiler/manifest/parse.rs +++ b/distributed_cli/src/client_compiler/manifest/parse.rs @@ -1,79 +1,59 @@ use std::collections::{BTreeMap, BTreeSet}; -use serde::{Deserialize, Serialize}; -use serde_json::Value as JsonValue; - use super::*; -// The compiler treats one manifest version as an exact executable contract. -// Same-version extensions must bump the pre-release version instead of being -// silently ignored by an older client compiler. -#[derive(Deserialize)] -#[serde(deny_unknown_fields)] -struct ManifestWire { - manifest_version: u64, - protocol_version: u64, - service_id: String, - surface: ManifestSurface, - schema_fingerprint: String, - protocol_fingerprint: String, - execution: ManifestExecutionLimits, - capabilities: ManifestCapabilities, - scalar_codecs: Vec, - models: Vec, - roots: Vec, - commands: Vec, - protocol_operations: ManifestProtocolOperations, - projectors: Vec, - projection_programs: Vec, - projection_bindings: Vec, -} - -#[derive(Serialize)] -struct ManifestSchemaMaterial<'a> { - manifest_version: u64, - protocol_version: u64, - service_id: &'a str, - surface: &'a ManifestSurface, - execution: &'a ManifestExecutionLimits, - capabilities: &'a ManifestCapabilities, - scalar_codecs: &'a [ManifestScalarCodec], - models: &'a [ManifestModel], - roots: &'a [ManifestRoot], - commands: &'a [ManifestCommand], - protocol_operations: &'a ManifestProtocolOperations, - projectors: &'a [ManifestProjector], - projection_programs: &'a [ManifestProjectionProgram], - projection_bindings: &'a [ManifestProjectionBinding], +/// The validated, indexed form of one [`DistributedClientManifest`]. +#[derive(Clone, Debug)] +pub(crate) struct ClientManifest { + pub(crate) service_id: String, + pub(crate) surface: ClientSurfaceIdentity, + pub(crate) schema_fingerprint: String, + pub(crate) protocol_fingerprint: String, + pub(crate) execution: ClientExecutionLimits, + pub(crate) capabilities: ClientCapabilities, + pub(crate) scalar_codecs: BTreeMap, + pub(crate) models: BTreeMap, + pub(crate) roots: BTreeMap<(ClientRootOperation, String), ClientRoot>, + pub(crate) commands: Vec, + /// Exact scope-wide descriptor inventory derived from command-local + /// presets plus every client-visible row-policy claim/column codec. + pub(crate) trusted_presets: Vec, + pub(crate) commands_requiring_revalidation: BTreeSet, + pub(crate) protocol_operations: ClientProtocolOperations, + pub(crate) projectors: Vec, + pub(crate) projection_programs: Vec, + pub(crate) projection_bindings: Vec, + pub(crate) leaderboards: Vec, } impl ClientManifest { + /// Validate one manifest as an exact executable contract: the versions + /// and protocol family this compiler was built with, the surface the + /// caller selected, and content matching its declared fingerprint. pub(crate) fn parse( - value: JsonValue, - selector: &ClientSurfaceSelector, + mut wire: DistributedClientManifest, + selector: &ClientSurfaceIdentity, ) -> Result { - validate_input_default_generators_in_json(&value)?; - let mut wire: ManifestWire = serde_json::from_value(value).map_err(|error| { + let computed_schema_fingerprint = wire.computed_schema_fingerprint().map_err(|error| { ClientCompileError::manifest( - "client.manifest.invalid", - format!("invalid Distributed client manifest: {error}"), + "client.manifest.schema_fingerprint", + format!("could not recompute manifest schema fingerprint: {error}"), ) })?; - let computed_schema_fingerprint = schema_fingerprint(&wire)?; - if wire.manifest_version != MANIFEST_VERSION { + if wire.manifest_version != DISTRIBUTED_CLIENT_MANIFEST_VERSION { return Err(ClientCompileError::manifest( "client.manifest.version", format!( - "client compiler requires manifest_version {MANIFEST_VERSION}, received {}", + "client compiler requires manifest_version {DISTRIBUTED_CLIENT_MANIFEST_VERSION}, received {}", wire.manifest_version ), )); } - if wire.protocol_version != PROTOCOL_VERSION { + if wire.protocol_version != DISTRIBUTED_CLIENT_PROTOCOL_VERSION { return Err(ClientCompileError::manifest( "client.manifest.protocol_version", format!( - "client compiler requires protocol_version {PROTOCOL_VERSION}, received {}", + "client compiler requires protocol_version {DISTRIBUTED_CLIENT_PROTOCOL_VERSION}, received {}", wire.protocol_version ), )); @@ -82,11 +62,14 @@ impl ClientManifest { validate_hash(&wire.schema_fingerprint, "manifest.schema_fingerprint")?; validate_hash(&wire.protocol_fingerprint, "manifest.protocol_fingerprint")?; validate_execution_limits(&wire.execution)?; - if wire.protocol_fingerprint != PROTOCOL_FINGERPRINT { + let protocol_fingerprint = client_protocol_fingerprint().map_err(|error| { + ClientCompileError::manifest("client.manifest.protocol_fingerprint", error.to_string()) + })?; + if wire.protocol_fingerprint != protocol_fingerprint { return Err(ClientCompileError::manifest( "client.manifest.protocol_fingerprint", format!( - "client compiler protocol contract is `{PROTOCOL_FINGERPRINT}`, received `{}`; regenerate the manifest and use a matching distributed version", + "client compiler protocol contract is `{protocol_fingerprint}`, received `{}`; regenerate the manifest and use a matching distributed version", wire.protocol_fingerprint ), )); @@ -204,8 +187,19 @@ impl ClientManifest { &models, &projectors, )?); - let trusted_presets = derive_trusted_preset_descriptors(&models, &commands)?; - validate_derived_capabilities(&wire.capabilities, &roots, &commands)?; + let trusted_presets = + trusted_preset_descriptors(models.values(), &commands).map_err(|error| { + ClientCompileError::manifest( + "client.manifest.trusted_preset_inventory", + error.to_string(), + ) + })?; + let leaderboards = external_leaderboards(&wire.external)?; + validate_leaderboards(&leaderboards, &roots, &typenames)?; + let live_leaderboards = leaderboards + .iter() + .any(|leaderboard| leaderboard.roots.iter().any(|root| root.live)); + validate_derived_capabilities(&wire.capabilities, &roots, &commands, live_leaderboards)?; if wire.schema_fingerprint != computed_schema_fingerprint { return Err(ClientCompileError::manifest( "client.manifest.schema_fingerprint", @@ -233,45 +227,11 @@ impl ClientManifest { projectors, projection_programs, projection_bindings, + leaderboards, }) } - pub(crate) fn root(&self, operation: RootOperation, name: &str) -> Option<&ManifestRoot> { + pub(crate) fn root(&self, operation: ClientRootOperation, name: &str) -> Option<&ClientRoot> { self.roots.get(&(operation, name.to_string())) } } - -fn schema_fingerprint(wire: &ManifestWire) -> Result { - let material = ManifestSchemaMaterial { - manifest_version: wire.manifest_version, - protocol_version: wire.protocol_version, - service_id: &wire.service_id, - surface: &wire.surface, - execution: &wire.execution, - capabilities: &wire.capabilities, - scalar_codecs: &wire.scalar_codecs, - models: &wire.models, - roots: &wire.roots, - commands: &wire.commands, - protocol_operations: &wire.protocol_operations, - projectors: &wire.projectors, - projection_programs: &wire.projection_programs, - projection_bindings: &wire.projection_bindings, - }; - serde_json::to_vec(&material) - .map(|bytes| hash_bytes(&bytes)) - .map_err(|error| { - ClientCompileError::manifest( - "client.manifest.schema_fingerprint", - format!("could not recompute manifest schema fingerprint: {error}"), - ) - }) -} - -#[cfg(test)] -pub(crate) fn refresh_schema_fingerprint(value: &mut JsonValue) { - let wire: ManifestWire = - serde_json::from_value(value.clone()).expect("test manifest must match the v2 wire shape"); - value["schema_fingerprint"] = - JsonValue::String(schema_fingerprint(&wire).expect("test manifest must be serializable")); -} diff --git a/distributed_cli/src/client_compiler/manifest/projections.rs b/distributed_cli/src/client_compiler/manifest/projections.rs index 8f57977c9..e98c22fdb 100644 --- a/distributed_cli/src/client_compiler/manifest/projections.rs +++ b/distributed_cli/src/client_compiler/manifest/projections.rs @@ -3,22 +3,19 @@ use std::collections::{BTreeMap, BTreeSet}; use super::*; const MAX_PROJECTION_ITEMS: usize = 128; +// Retained event versions grow the catalog without expanding a command's +// selected capabilities or an occurrence's executable operation budget. +const MAX_PROJECTION_PROGRAM_ARMS: usize = 256; // Frozen with `distributed::MAX_PROJECTION_EXPRESSION_DEPTH`. The CLI crate is // intentionally dependency-free from the runtime crate, so keep a boundary // test below to prevent this executable-contract limit from drifting. const MAX_EXPRESSION_DEPTH: usize = 64; pub(crate) fn validate_projection_manifest( - mut programs: Vec, - mut bindings: Vec, - models: &BTreeMap, -) -> Result< - ( - Vec, - Vec, - ), - ClientCompileError, -> { + mut programs: Vec, + mut bindings: Vec, + models: &BTreeMap, +) -> Result<(Vec, Vec), ClientCompileError> { if programs.len() > MAX_PROJECTION_ITEMS || bindings.len() > MAX_PROJECTION_ITEMS { return Err(projection_error( "client.manifest.projection_inventory", @@ -82,7 +79,7 @@ pub(crate) fn validate_projection_manifest( format!("duplicate projection binding `{}`", binding.binding_id), )); } - if binding.state == ManifestProjectionBindingState::Active + if binding.state == ProjectionBindingState::Active && !active_programs.insert(binding.program_id.as_str()) { return Err(projection_error( @@ -93,7 +90,7 @@ pub(crate) fn validate_projection_manifest( ), )); } - if binding.placement == ManifestProjectionPlacement::Eventual + if binding.placement == ProjectionPlacement::Eventual && !program_ids.contains(binding.program_id.as_str()) { return Err(projection_error( @@ -107,9 +104,9 @@ pub(crate) fn validate_projection_manifest( // Direct may export the same portable program for `.applies` previews. // Server apply site is still the command handler (Atomic response); // client never runs this as an async eventual obligation. - if binding.placement == ManifestProjectionPlacement::Direct + if binding.placement == ProjectionPlacement::Direct && program_ids.contains(binding.program_id.as_str()) - && binding.execution_class != ManifestProjectionExecutionClass::Causal + && binding.execution_class != ProjectionExecutionClass::Causal { return Err(projection_error( "client.manifest.projection_placement", @@ -127,20 +124,20 @@ pub(crate) fn validate_projection_manifest( /// /// Eventual: async projector path + local `.applies` previews. /// Direct: same mutation IR; handler-owned Atomic apply; previews optional. -fn is_preview_eligible_binding(binding: &ManifestProjectionBinding) -> bool { - binding.state == ManifestProjectionBindingState::Active - && binding.execution_class == ManifestProjectionExecutionClass::Causal +fn is_preview_eligible_binding(binding: &ClientProjectionBinding) -> bool { + binding.state == ProjectionBindingState::Active + && binding.execution_class == ProjectionExecutionClass::Causal && matches!( binding.placement, - ManifestProjectionPlacement::Eventual | ManifestProjectionPlacement::Direct + ProjectionPlacement::Eventual | ProjectionPlacement::Direct ) } pub(crate) fn validate_command_projections( - commands: &[ManifestCommand], - programs: &[ManifestProjectionProgram], - bindings: &[ManifestProjectionBinding], - models: &BTreeMap, + commands: &[ClientCommand], + programs: &[ClientProjectionProgram], + bindings: &[ClientProjectionBinding], + models: &BTreeMap, ) -> Result, ClientCompileError> { let programs = programs .iter() @@ -215,10 +212,8 @@ pub(crate) fn validate_command_projections( )); } - let mut selected_slots = BTreeMap::< - ManifestProjectionEventRef, - BTreeMap, - >::new(); + let mut selected_slots = + BTreeMap::>::new(); let mut selected_programs = BTreeSet::new(); for selected in &projection.program_arms { validate_event_ref(&selected.event)?; @@ -330,8 +325,8 @@ pub(crate) fn validate_command_projections( } fn validate_program( - program: &ManifestProjectionProgram, - models: &BTreeMap, + program: &ClientProjectionProgram, + models: &BTreeMap, ) -> Result<(), ClientCompileError> { if program.version != CLIENT_PROJECTION_PROGRAM_VERSION || program.ir_version != PROJECTION_PROGRAM_IR_VERSION @@ -348,11 +343,11 @@ fn validate_program( } validate_program_id(&program.program_id)?; validate_nonempty(&program.name, "projection program name")?; - if program.arms.is_empty() || program.arms.len() > MAX_PROJECTION_ITEMS { + if program.arms.is_empty() || program.arms.len() > MAX_PROJECTION_PROGRAM_ARMS { return Err(projection_error( "client.manifest.projection_program_arms", format!( - "projection program `{}` must contain 1..={MAX_PROJECTION_ITEMS} arms", + "projection program `{}` must contain 1..={MAX_PROJECTION_PROGRAM_ARMS} arms", program.program_id ), )); @@ -418,7 +413,7 @@ fn validate_program( Ok(()) } -fn validate_binding(binding: &ManifestProjectionBinding) -> Result<(), ClientCompileError> { +fn validate_binding(binding: &ClientProjectionBinding) -> Result<(), ClientCompileError> { if binding.version != CLIENT_PROJECTION_BINDING_VERSION { return Err(projection_error( "client.manifest.projection_binding_version", @@ -434,10 +429,10 @@ fn validate_binding(binding: &ManifestProjectionBinding) -> Result<(), ClientCom } fn validate_operation( - program: &ManifestProjectionProgram, - arm: &ManifestProjectionArm, - operation: &ManifestProjectionOperation, - models: &BTreeMap, + program: &ClientProjectionProgram, + arm: &ClientProjectionArm, + operation: &ClientProjectionOperation, + models: &BTreeMap, ) -> Result<(), ClientCompileError> { validate_nonempty(&operation.operation, "projection operation id")?; let model = models.get(&operation.model).ok_or_else(|| { @@ -450,7 +445,7 @@ fn validate_operation( ) })?; let Some(identity) = model.identity() else { - if operation.kind != ManifestProjectionMutationKind::InvalidateModel { + if operation.kind != ClientProjectionMutationKind::InvalidateModel { return Err(projection_error( "client.manifest.projection_model", format!( @@ -475,7 +470,7 @@ fn validate_operation( validate_invalidations(operation, models)?; if !matches!( operation.invalidations.as_slice(), - [ManifestProjectionInvalidation::Model { model }] if model == &operation.model + [ClientProjectionInvalidation::Model { model }] if model == &operation.model ) { return Err(projection_error( "client.manifest.projection_invalidation", @@ -492,12 +487,20 @@ fn validate_operation( validate_projection_fields(operation, model)?; match operation.kind { - ManifestProjectionMutationKind::Insert - | ManifestProjectionMutationKind::Upsert - | ManifestProjectionMutationKind::Recreate - | ManifestProjectionMutationKind::InsertRelated - | ManifestProjectionMutationKind::UpsertRelated => { - if operation.fields.is_empty() { + ClientProjectionMutationKind::Insert + | ClientProjectionMutationKind::Upsert + | ClientProjectionMutationKind::Recreate + | ClientProjectionMutationKind::InsertRelated + | ClientProjectionMutationKind::UpsertRelated => { + // Identity assignments live in `key`, so a key-only normalized + // model has a complete row even with an empty non-key field mask. + if operation.fields.is_empty() + && model.fields.iter().any(|field| { + !identity + .iter() + .any(|key_field| key_field.name == field.name) + }) + { return Err(projection_error( "client.manifest.projection_field_mask", format!( @@ -507,7 +510,7 @@ fn validate_operation( )); } } - ManifestProjectionMutationKind::Patch | ManifestProjectionMutationKind::UpsertPatch => { + ClientProjectionMutationKind::Patch | ClientProjectionMutationKind::UpsertPatch => { if operation.fields.is_empty() { return Err(projection_error( "client.manifest.projection_field_mask", @@ -518,7 +521,7 @@ fn validate_operation( )); } } - ManifestProjectionMutationKind::Delete => { + ClientProjectionMutationKind::Delete => { if !operation.fields.is_empty() { return Err(projection_error( "client.manifest.projection_field_mask", @@ -526,8 +529,8 @@ fn validate_operation( )); } } - ManifestProjectionMutationKind::InvalidateModel => {} - ManifestProjectionMutationKind::InvalidateRelationship => { + ClientProjectionMutationKind::InvalidateModel => {} + ClientProjectionMutationKind::InvalidateRelationship => { return Err(projection_error( "client.manifest.projection_invalidation", "top-level relationship invalidation has no source-key provenance; use an \ @@ -540,8 +543,8 @@ fn validate_operation( } fn validate_projection_fields( - operation: &ManifestProjectionOperation, - model: &ManifestModel, + operation: &ClientProjectionOperation, + model: &ClientModel, ) -> Result<(), ClientCompileError> { let identity = model .identity() @@ -573,7 +576,7 @@ fn validate_projection_fields( ), )); } - if let ManifestProjectionAssignment::Set { expression } = &field.assignment { + if let ClientProjectionAssignment::Set { expression } = &field.assignment { validate_expression(expression, 1)?; } } @@ -581,8 +584,8 @@ fn validate_projection_fields( } fn validate_relationships( - operation: &ManifestProjectionOperation, - models: &BTreeMap, + operation: &ClientProjectionOperation, + models: &BTreeMap, ) -> Result<(), ClientCompileError> { let mut identities = BTreeSet::new(); for (index, effect) in operation.relationships.iter().enumerate() { @@ -658,13 +661,13 @@ fn validate_relationships( } fn validate_invalidations( - operation: &ManifestProjectionOperation, - models: &BTreeMap, + operation: &ClientProjectionOperation, + models: &BTreeMap, ) -> Result<(), ClientCompileError> { let mut identities = BTreeSet::new(); for invalidation in &operation.invalidations { let identity = match invalidation { - ManifestProjectionInvalidation::Model { model } => { + ClientProjectionInvalidation::Model { model } => { if !models.contains_key(model) { return Err(projection_error( "client.manifest.projection_invalidation", @@ -673,7 +676,7 @@ fn validate_invalidations( } format!("model:{model}") } - ManifestProjectionInvalidation::Relationship { + ClientProjectionInvalidation::Relationship { source_model, relationship, target_model, @@ -707,8 +710,8 @@ fn validate_invalidations( } fn validate_key( - key: &[ManifestProjectionKeyField], - identity: &[ManifestKeyField], + key: &[ClientProjectionKeyField], + identity: &[ClientKeyField], label: &str, ) -> Result<(), ClientCompileError> { if key.len() != identity.len() { @@ -729,15 +732,15 @@ fn validate_key( Ok(()) } -fn validate_partition(partition: &ManifestProjectionPartition) -> Result<(), ClientCompileError> { - if let ManifestProjectionPartition::Expression { expression } = partition { +fn validate_partition(partition: &ClientProjectionPartition) -> Result<(), ClientCompileError> { + if let ClientProjectionPartition::Expression { expression } = partition { validate_expression(expression, 1)?; } Ok(()) } fn validate_expression( - expression: &ManifestProjectionExpression, + expression: &ClientProjectionExpression, depth: usize, ) -> Result<(), ClientCompileError> { if depth > MAX_EXPRESSION_DEPTH { @@ -747,23 +750,23 @@ fn validate_expression( )); } match expression { - ManifestProjectionExpression::Slot { + ClientProjectionExpression::Slot { slot, value_type: _, } => validate_nonempty(slot, "projection expression slot"), - ManifestProjectionExpression::Envelope { field: _ } => Ok(()), - ManifestProjectionExpression::Constant { value } => validate_value(value, depth), - ManifestProjectionExpression::Enum { enum_type, variant } => { + ClientProjectionExpression::Envelope { field: _ } => Ok(()), + ClientProjectionExpression::Constant { value } => validate_value(value, depth), + ClientProjectionExpression::Enum { enum_type, variant } => { validate_nonempty(enum_type, "projection enum type")?; validate_nonempty(variant, "projection enum variant") } - ManifestProjectionExpression::List { values } => { + ClientProjectionExpression::List { values } => { for value in values { validate_expression(value, depth + 1)?; } Ok(()) } - ManifestProjectionExpression::Object { fields } => { + ClientProjectionExpression::Object { fields } => { if fields.windows(2).any(|pair| pair[0].name >= pair[1].name) { return Err(projection_error( "client.manifest.projection_expression_object", @@ -776,7 +779,7 @@ fn validate_expression( } Ok(()) } - ManifestProjectionExpression::Transform { + ClientProjectionExpression::Transform { transform: _, arguments, } => { @@ -794,7 +797,7 @@ fn validate_expression( } } -fn validate_value(value: &ManifestProjectionValue, depth: usize) -> Result<(), ClientCompileError> { +fn validate_value(value: &ClientProjectionValue, depth: usize) -> Result<(), ClientCompileError> { if depth > MAX_EXPRESSION_DEPTH { return Err(projection_error( "client.manifest.projection_value_depth", @@ -802,11 +805,11 @@ fn validate_value(value: &ManifestProjectionValue, depth: usize) -> Result<(), C )); } match value { - ManifestProjectionValue::Null | ManifestProjectionValue::Boolean(_) => Ok(()), - ManifestProjectionValue::I64(value) => validate_canonical_i64(value), - ManifestProjectionValue::U64(value) => validate_canonical_u64(value), - ManifestProjectionValue::F64(value) => validate_canonical_f64(value), - ManifestProjectionValue::String(value) => { + ClientProjectionValue::Null | ClientProjectionValue::Boolean(_) => Ok(()), + ClientProjectionValue::I64(value) => validate_canonical_i64(value), + ClientProjectionValue::U64(value) => validate_canonical_u64(value), + ClientProjectionValue::F64(value) => validate_canonical_f64(value), + ClientProjectionValue::String(value) => { if value.chars().any(char::is_control) { return Err(projection_error( "client.manifest.projection_value", @@ -815,17 +818,17 @@ fn validate_value(value: &ManifestProjectionValue, depth: usize) -> Result<(), C } Ok(()) } - ManifestProjectionValue::Enum { enum_type, variant } => { + ClientProjectionValue::Enum { enum_type, variant } => { validate_nonempty(enum_type, "projection enum type")?; validate_nonempty(variant, "projection enum variant") } - ManifestProjectionValue::List(values) => { + ClientProjectionValue::List(values) => { for value in values { validate_value(value, depth + 1)?; } Ok(()) } - ManifestProjectionValue::Object(fields) => { + ClientProjectionValue::Object(fields) => { if fields.windows(2).any(|pair| pair[0].name >= pair[1].name) { return Err(projection_error( "client.manifest.projection_value_object", @@ -841,16 +844,16 @@ fn validate_value(value: &ManifestProjectionValue, depth: usize) -> Result<(), C } fn validate_preview_source( - command: &ManifestCommand, - source: &ManifestProjectionPreviewSource, - expected: &ManifestProjectionValueType, + command: &ClientCommand, + source: &ClientProjectionPreviewSource, + expected: &ProjectionValueType, ) -> Result<(), ClientCompileError> { match source { - ManifestProjectionPreviewSource::Input { path } => { + ClientProjectionPreviewSource::Input { path } => { let field = validate_shape_path(&command.input, path, "input")?; validate_input_source_type(command, field, expected, "input") } - ManifestProjectionPreviewSource::GeneratedDefault { path } => { + ClientProjectionPreviewSource::GeneratedDefault { path } => { let field = validate_shape_path(&command.input, path, "generated default")?; let declared = command .extensions @@ -871,7 +874,7 @@ fn validate_preview_source( } validate_input_source_type(command, field, expected, "generated default") } - ManifestProjectionPreviewSource::TrustedPreset { name, codec } => { + ClientProjectionPreviewSource::TrustedPreset { name, codec } => { let declared = command .extensions .trusted_presets @@ -893,7 +896,7 @@ fn validate_preview_source( } Ok(()) } - ManifestProjectionPreviewSource::Constant { value } => { + ClientProjectionPreviewSource::Constant { value } => { validate_value(value, 1)?; if !constant_compatible(value, expected) { return Err(command_projection_error( @@ -904,18 +907,18 @@ fn validate_preview_source( } Ok(()) } - ManifestProjectionPreviewSource::Null - | ManifestProjectionPreviewSource::Absent - | ManifestProjectionPreviewSource::Unknown => Ok(()), + ClientProjectionPreviewSource::Null + | ClientProjectionPreviewSource::Absent + | ClientProjectionPreviewSource::Unknown => Ok(()), } } fn validate_shape_path<'a>( - shape: &'a ManifestCommandShape, + shape: &'a ClientCommandShape, path: &[String], label: &str, -) -> Result<&'a ManifestTypeField, ClientCompileError> { - let ManifestCommandShape::Object { definition } = shape else { +) -> Result<&'a ClientTypeField, ClientCompileError> { + let ClientCommandShape::Object { definition } = shape else { return Err(projection_error( "client.manifest.command_projection_path", format!("{label} path cannot target a command without input"), @@ -953,9 +956,9 @@ fn validate_shape_path<'a>( } fn validate_input_source_type( - command: &ManifestCommand, - field: &ManifestTypeField, - expected: &ManifestProjectionValueType, + command: &ClientCommand, + field: &ClientTypeField, + expected: &ProjectionValueType, label: &str, ) -> Result<(), ClientCompileError> { let compatible = !field.list @@ -974,69 +977,61 @@ fn validate_input_source_type( Ok(()) } -fn input_codec_compatible( - type_name: &str, - codec: &str, - expected: &ManifestProjectionValueType, -) -> bool { +fn input_codec_compatible(type_name: &str, codec: &str, expected: &ProjectionValueType) -> bool { match expected { - ManifestProjectionValueType::Boolean => type_name == "Boolean" && codec == "boolean", - ManifestProjectionValueType::I64 => matches!( + ProjectionValueType::Boolean => type_name == "Boolean" && codec == "boolean", + ProjectionValueType::I64 => matches!( (type_name, codec), ("Int", "int32") | ("BigInt", "json_number_precision_limited") ), - // Both numeric command codecs admit negative values. Without a - // non-negative refinement in the frozen manifest, neither proves U64. - ManifestProjectionValueType::U64 => false, - ManifestProjectionValueType::F64 => type_name == "Float" && codec == "float64", - ManifestProjectionValueType::String => matches!( + ProjectionValueType::U64 => type_name == "BigInt" && unsigned_codec(codec), + ProjectionValueType::F64 => type_name == "Float" && codec == "float64", + ProjectionValueType::String => matches!( (type_name, codec), ("ID" | "String", "string") | ("Timestamptz", "string_unvalidated_timestamp") ), - ManifestProjectionValueType::Enum(enum_type) => type_name == enum_type && codec == "string", - ManifestProjectionValueType::Json => type_name == "JSON" && codec == "json", + ProjectionValueType::Enum(enum_type) => type_name == enum_type && codec == "string", + ProjectionValueType::Json => type_name == "JSON" && codec == "json", } } -fn codec_compatible(codec: &str, expected: &ManifestProjectionValueType) -> bool { +fn codec_compatible(codec: &str, expected: &ProjectionValueType) -> bool { match expected { - ManifestProjectionValueType::Boolean => codec == "boolean", - ManifestProjectionValueType::I64 => { + ProjectionValueType::Boolean => codec == "boolean", + ProjectionValueType::I64 => { matches!(codec, "int32" | "json_number_precision_limited") } - ManifestProjectionValueType::U64 => false, - ManifestProjectionValueType::F64 => codec == "float64", - ManifestProjectionValueType::String | ManifestProjectionValueType::Enum(_) => { - codec == "string" - } - ManifestProjectionValueType::Json => codec == "json", + ProjectionValueType::U64 => unsigned_codec(codec), + ProjectionValueType::F64 => codec == "float64", + ProjectionValueType::String | ProjectionValueType::Enum(_) => codec == "string", + ProjectionValueType::Json => codec == "json", } } -fn constant_compatible( - value: &ManifestProjectionValue, - expected: &ManifestProjectionValueType, -) -> bool { +fn unsigned_codec(codec: &str) -> bool { + matches!(codec, "uint8" | "uint16" | "uint32" | "uint64_safe_integer") +} + +fn constant_compatible(value: &ClientProjectionValue, expected: &ProjectionValueType) -> bool { match (value, expected) { - (ManifestProjectionValue::Boolean(_), ManifestProjectionValueType::Boolean) - | (ManifestProjectionValue::I64(_), ManifestProjectionValueType::I64) - | (ManifestProjectionValue::U64(_), ManifestProjectionValueType::U64) - | (ManifestProjectionValue::F64(_), ManifestProjectionValueType::F64) - | (ManifestProjectionValue::String(_), ManifestProjectionValueType::String) => true, - ( - ManifestProjectionValue::Enum { enum_type, .. }, - ManifestProjectionValueType::Enum(expected), - ) => enum_type == expected, - (_, ManifestProjectionValueType::Json) => true, + (ClientProjectionValue::Boolean(_), ProjectionValueType::Boolean) + | (ClientProjectionValue::I64(_), ProjectionValueType::I64) + | (ClientProjectionValue::U64(_), ProjectionValueType::U64) + | (ClientProjectionValue::F64(_), ProjectionValueType::F64) + | (ClientProjectionValue::String(_), ProjectionValueType::String) => true, + (ClientProjectionValue::Enum { enum_type, .. }, ProjectionValueType::Enum(expected)) => { + enum_type == expected + } + (_, ProjectionValueType::Json) => true, _ => false, } } fn collect_arm_slots( - arm: &ManifestProjectionArm, - slots: &mut BTreeMap, + arm: &ClientProjectionArm, + slots: &mut BTreeMap, ) -> Result<(), ClientCompileError> { - if let ManifestProjectionPartition::Expression { expression } = &arm.partition { + if let ClientProjectionPartition::Expression { expression } = &arm.partition { collect_expression_slots(expression, slots)?; } for operation in &arm.operations { @@ -1044,7 +1039,7 @@ fn collect_arm_slots( collect_expression_slots(&field.expression, slots)?; } for field in &operation.fields { - if let ManifestProjectionAssignment::Set { expression } = &field.assignment { + if let ClientProjectionAssignment::Set { expression } = &field.assignment { collect_expression_slots(expression, slots)?; } } @@ -1062,11 +1057,11 @@ fn collect_arm_slots( } fn collect_expression_slots( - expression: &ManifestProjectionExpression, - slots: &mut BTreeMap, + expression: &ClientProjectionExpression, + slots: &mut BTreeMap, ) -> Result<(), ClientCompileError> { match expression { - ManifestProjectionExpression::Slot { slot, value_type } => { + ClientProjectionExpression::Slot { slot, value_type } => { if slots .insert(slot.clone(), value_type.clone()) .is_some_and(|existing| existing != *value_type) @@ -1077,29 +1072,29 @@ fn collect_expression_slots( )); } } - ManifestProjectionExpression::List { values } => { + ClientProjectionExpression::List { values } => { for value in values { collect_expression_slots(value, slots)?; } } - ManifestProjectionExpression::Object { fields } => { + ClientProjectionExpression::Object { fields } => { for field in fields { collect_expression_slots(&field.value, slots)?; } } - ManifestProjectionExpression::Transform { arguments, .. } => { + ClientProjectionExpression::Transform { arguments, .. } => { for argument in arguments { collect_expression_slots(argument, slots)?; } } - ManifestProjectionExpression::Envelope { .. } - | ManifestProjectionExpression::Constant { .. } - | ManifestProjectionExpression::Enum { .. } => {} + ClientProjectionExpression::Envelope { .. } + | ClientProjectionExpression::Constant { .. } + | ClientProjectionExpression::Enum { .. } => {} } Ok(()) } -fn validate_event_ref(event: &ManifestProjectionEventRef) -> Result<(), ClientCompileError> { +fn validate_event_ref(event: &ClientProjectionEventRef) -> Result<(), ClientCompileError> { validate_nonempty(&event.id, "projection event id")?; validate_nonempty(&event.name, "projection event name")?; if event.version == 0 { @@ -1185,7 +1180,7 @@ fn projection_error(code: &'static str, message: impl Into) -> ClientCom } fn command_projection_error( - command: &ManifestCommand, + command: &ClientCommand, code: &'static str, message: impl Into, ) -> ClientCompileError { @@ -1199,12 +1194,12 @@ fn command_projection_error( mod tests { use super::*; - fn nested_expression(depth: usize) -> ManifestProjectionExpression { - let mut expression = ManifestProjectionExpression::Constant { - value: ManifestProjectionValue::Null, + fn nested_expression(depth: usize) -> ClientProjectionExpression { + let mut expression = ClientProjectionExpression::Constant { + value: ClientProjectionValue::Null, }; for _ in 1..depth { - expression = ManifestProjectionExpression::List { + expression = ClientProjectionExpression::List { values: vec![expression], }; } diff --git a/distributed_cli/src/client_compiler/manifest/projectors.rs b/distributed_cli/src/client_compiler/manifest/projectors.rs index 2d63753a6..bc74e03f8 100644 --- a/distributed_cli/src/client_compiler/manifest/projectors.rs +++ b/distributed_cli/src/client_compiler/manifest/projectors.rs @@ -3,7 +3,7 @@ use std::collections::{BTreeMap, BTreeSet}; use super::*; pub(crate) fn canonicalize_projectors( - projectors: &mut [ManifestProjector], + projectors: &mut [ClientProjector], ) -> Result<(), ClientCompileError> { for projector in projectors.iter_mut() { canonicalize_string_set( @@ -24,8 +24,8 @@ pub(crate) fn canonicalize_projectors( } pub(crate) fn validate_projectors( - projectors: &[ManifestProjector], - models: &BTreeMap, + projectors: &[ClientProjector], + models: &BTreeMap, ) -> Result<(), ClientCompileError> { let mut names = BTreeSet::new(); for projector in projectors { @@ -51,15 +51,6 @@ pub(crate) fn validate_projectors( ), )); } - if projector.facts.is_empty() && projector.causal_confirmation { - return Err(ClientCompileError::manifest( - "client.manifest.projector_inventory", - format!( - "direct-only projection owner `{}` cannot provide asynchronous confirmation", - projector.name - ), - )); - } let mut expected_dependencies = BTreeSet::new(); for model in &projector.models { let Some(model_contract) = models.get(model) else { @@ -92,16 +83,16 @@ pub(crate) fn validate_projectors( } pub(crate) fn validate_direct_projections( - commands: &[ManifestCommand], - models: &BTreeMap, - projectors: &[ManifestProjector], + commands: &[ClientCommand], + models: &BTreeMap, + projectors: &[ClientProjector], ) -> Result, ClientCompileError> { let mut requiring_revalidation = BTreeSet::new(); for command in commands { let consistency = command.extensions.consistency.kind; let direct = command.extensions.direct_projection.as_ref(); match (consistency, direct) { - (ManifestConsistencyKind::Atomic, None) => { + (CommandConsistency::Atomic, None) => { return Err(ClientCompileError::manifest( "client.manifest.direct_projection_required", format!( @@ -110,7 +101,7 @@ pub(crate) fn validate_direct_projections( ), )); } - (ManifestConsistencyKind::Atomic, Some(direct)) => { + (CommandConsistency::Atomic, Some(direct)) => { if validate_direct_projection(command, direct, models, projectors)? { requiring_revalidation.insert(command.name.clone()); } @@ -131,10 +122,10 @@ pub(crate) fn validate_direct_projections( } pub(crate) fn validate_direct_projection( - command: &ManifestCommand, - direct: &ManifestDirectProjection, - models: &BTreeMap, - projectors: &[ManifestProjector], + command: &ClientCommand, + direct: &CommandDirectProjectionExtension, + models: &BTreeMap, + projectors: &[ClientProjector], ) -> Result { if direct.topology.version != 1 { return Err(ClientCompileError::manifest( @@ -182,10 +173,7 @@ pub(crate) fn validate_direct_projection( ), ) })?; - if !matches!( - &model.normalization, - ManifestNormalization::Normalized { .. } - ) { + if !matches!(&model.normalization, ModelNormalization::Normalized { .. }) { return Err(ClientCompileError::manifest( "client.manifest.direct_projection_model", format!( @@ -194,7 +182,7 @@ pub(crate) fn validate_direct_projection( ), )); } - let ManifestCommandShape::Object { definition } = &command.output else { + let ClientCommandShape::Object { definition } = &command.output else { return Err(ClientCompileError::manifest( "client.manifest.direct_projection_output", format!( @@ -320,11 +308,11 @@ pub(crate) fn validate_projection_epoch( } pub(crate) fn validate_direct_projection_partition( - command: &ManifestCommand, - partition: &ManifestEffectExpression, + command: &ClientCommand, + partition: &EffectExpression, ) -> Result { match partition { - ManifestEffectExpression::Input { path } => { + EffectExpression::Input { path } => { if path.is_empty() { return Err(ClientCompileError::manifest( "client.manifest.direct_projection_partition", @@ -341,7 +329,7 @@ pub(crate) fn validate_direct_projection_partition( command.name ), )?; - let ManifestCommandShape::Object { definition } = &command.input else { + let ClientCommandShape::Object { definition } = &command.input else { return Err(ClientCompileError::manifest( "client.manifest.direct_projection_partition", format!( @@ -402,7 +390,7 @@ pub(crate) fn validate_direct_projection_partition( } unreachable!("non-empty direct projection path resolves or returns an error") } - ManifestEffectExpression::TrustedPreset { name } => { + EffectExpression::TrustedPreset { name } => { let declared = command .extensions .trusted_presets @@ -419,6 +407,6 @@ pub(crate) fn validate_direct_projection_partition( } Ok(false) } - ManifestEffectExpression::Constant { .. } | ManifestEffectExpression::Null => Ok(false), + EffectExpression::Constant { .. } | EffectExpression::Null => Ok(false), } } diff --git a/distributed_cli/src/client_compiler/manifest/roots.rs b/distributed_cli/src/client_compiler/manifest/roots.rs index 23f4b825a..fdd3840fb 100644 --- a/distributed_cli/src/client_compiler/manifest/roots.rs +++ b/distributed_cli/src/client_compiler/manifest/roots.rs @@ -2,7 +2,7 @@ use std::collections::{BTreeMap, BTreeSet}; use super::*; -pub(crate) fn canonicalize_root(root: &mut ManifestRoot) -> Result<(), ClientCompileError> { +pub(crate) fn canonicalize_root(root: &mut ClientRoot) -> Result<(), ClientCompileError> { canonicalize_arguments( &mut root.arguments, &format!("manifest root `{}` argument", root.name), @@ -24,14 +24,14 @@ pub(crate) fn canonicalize_root(root: &mut ManifestRoot) -> Result<(), ClientCom } pub(crate) fn validate_root_contract( - root: &ManifestRoot, - models: &BTreeMap, + root: &ClientRoot, + models: &BTreeMap, ) -> Result<(), ClientCompileError> { let expected_id = format!( "{}:{}", match root.operation { - RootOperation::Query => "query", - RootOperation::Subscription => "subscription", + ClientRootOperation::Query => "query", + ClientRootOperation::Subscription => "subscription", }, root.name ); @@ -68,7 +68,7 @@ pub(crate) fn validate_root_contract( &model.source_table, &format!("manifest root {}", root.name), )?; - if root.operation == RootOperation::Subscription && root.kind != RootKind::List { + if root.operation == ClientRootOperation::Subscription && root.kind != ClientRootKind::List { return Err(ClientCompileError::manifest( "client.manifest.subscription_kind", format!( @@ -77,7 +77,7 @@ pub(crate) fn validate_root_contract( ), )); } - if root.operation == RootOperation::Subscription && !root.live { + if root.operation == ClientRootOperation::Subscription && !root.live { return Err(ClientCompileError::manifest( "client.manifest.subscription_live", format!("subscription root `{}` must be marked live", root.name), @@ -87,19 +87,19 @@ pub(crate) fn validate_root_contract( let has_filter_argument = root .arguments .iter() - .any(|argument| argument.kind == ManifestArgumentKind::Filter); + .any(|argument| argument.kind == ClientArgumentKind::Filter); let has_order_argument = root .arguments .iter() - .any(|argument| argument.kind == ManifestArgumentKind::Order); + .any(|argument| argument.kind == ClientArgumentKind::Order); let has_limit_argument = root .arguments .iter() - .any(|argument| argument.kind == ManifestArgumentKind::Limit); + .any(|argument| argument.kind == ClientArgumentKind::Limit); let has_offset_argument = root .arguments .iter() - .any(|argument| argument.kind == ManifestArgumentKind::Offset); + .any(|argument| argument.kind == ClientArgumentKind::Offset); if root.filter.is_some() != has_filter_argument || root.order.is_some() != has_order_argument || root.pagination.is_some() != (has_limit_argument && has_offset_argument) @@ -119,7 +119,7 @@ pub(crate) fn validate_root_contract( validate_order_semantics(order, model)?; } match root.kind { - RootKind::List => { + ClientRootKind::List => { root.filter.as_ref().ok_or_else(|| { ClientCompileError::manifest( "client.manifest.root_filter", @@ -151,7 +151,7 @@ pub(crate) fn validate_root_contract( )); } } - RootKind::ByPk => { + ClientRootKind::ByPk => { if root.pagination.is_some() || root.aggregate.is_some() || root.filter.is_some() @@ -166,7 +166,7 @@ pub(crate) fn validate_root_contract( )); } if root.arguments.iter().any(|argument| { - argument.kind != ManifestArgumentKind::PrimaryKey + argument.kind != ClientArgumentKind::PrimaryKey || argument.nullable || argument.list }) { @@ -179,7 +179,7 @@ pub(crate) fn validate_root_contract( )); } } - RootKind::Aggregate => { + ClientRootKind::Aggregate => { if root.pagination.is_some() || root.order.is_some() { return Err(ClientCompileError::manifest( "client.manifest.aggregate_root_semantics", @@ -207,7 +207,7 @@ pub(crate) fn validate_root_contract( } pub(crate) fn validate_unique_arguments( - root: &ManifestRoot, + root: &ClientRoot, scalar_codecs: &BTreeMap, ) -> Result<(), ClientCompileError> { validate_unique_arguments_for( @@ -218,7 +218,7 @@ pub(crate) fn validate_unique_arguments( } pub(crate) fn validate_unique_arguments_for( - arguments: &[ManifestArgument], + arguments: &[ClientArgument], scalar_codecs: &BTreeMap, owner: &str, ) -> Result<(), ClientCompileError> { @@ -233,7 +233,7 @@ pub(crate) fn validate_unique_arguments_for( format!("{owner} repeats argument `{}`", argument.name), )); } - if argument.kind != ManifestArgumentKind::PrimaryKey && !kinds.insert(argument.kind) { + if argument.kind != ClientArgumentKind::PrimaryKey && !kinds.insert(argument.kind) { return Err(ClientCompileError::manifest( "client.manifest.duplicate_argument_kind", format!("{owner} repeats {:?} argument semantics", argument.kind), @@ -241,7 +241,7 @@ pub(crate) fn validate_unique_arguments_for( } if matches!( argument.kind, - ManifestArgumentKind::Limit | ManifestArgumentKind::Offset + ClientArgumentKind::Limit | ClientArgumentKind::Offset ) && (argument.list || argument.type_name != "Int") { return Err(ClientCompileError::manifest( diff --git a/distributed_cli/src/client_compiler/manifest/types.rs b/distributed_cli/src/client_compiler/manifest/types.rs deleted file mode 100644 index a8c9b64b3..000000000 --- a/distributed_cli/src/client_compiler/manifest/types.rs +++ /dev/null @@ -1,1148 +0,0 @@ -use std::collections::{BTreeMap, BTreeSet}; - -use serde::{Deserialize, Serialize}; -use serde_json::Value as JsonValue; - -use super::canonical_json_value; - -#[derive(Clone, Debug)] -pub(crate) struct ClientManifest { - pub(crate) service_id: String, - pub(crate) surface: ManifestSurface, - pub(crate) schema_fingerprint: String, - pub(crate) protocol_fingerprint: String, - pub(crate) execution: ManifestExecutionLimits, - pub(crate) capabilities: ManifestCapabilities, - pub(crate) scalar_codecs: BTreeMap, - pub(crate) models: BTreeMap, - pub(crate) roots: BTreeMap<(RootOperation, String), ManifestRoot>, - pub(crate) commands: Vec, - /// Exact scope-wide descriptor inventory derived from command-local - /// presets plus every client-visible row-policy claim/column codec. - pub(crate) trusted_presets: Vec, - pub(crate) commands_requiring_revalidation: BTreeSet, - pub(crate) protocol_operations: ManifestProtocolOperations, - pub(crate) projectors: Vec, - pub(crate) projection_programs: Vec, - pub(crate) projection_bindings: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestExecutionLimits { - pub(crate) max_depth: u64, - pub(crate) max_complexity: u64, - pub(crate) max_bool_width: u64, - pub(crate) max_in_list: u64, - pub(crate) complexity: ManifestComplexityWeights, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestComplexityWeights { - pub(crate) version: u32, - pub(crate) scalar: u64, - pub(crate) belongs_to: u64, - pub(crate) has_many: u64, - pub(crate) m2m: u64, - pub(crate) aggregate: u64, - pub(crate) list_root: u64, - pub(crate) by_pk: u64, - pub(crate) list_fanout: u64, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub(crate) enum ManifestSurface { - Role { - name: String, - }, - Application { - name: String, - eligible_roles: Vec, - schema_roles: Vec, - }, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestCapabilities { - pub(crate) live_queries: bool, - pub(crate) record_revisions: bool, - pub(crate) tombstones: bool, - pub(crate) causal_receipts: bool, - pub(crate) live_resume: bool, - pub(crate) query_fallback: String, - pub(crate) cache_scope: bool, - pub(crate) confirmed_persistence: bool, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestScalarCodec { - pub(crate) scalar: String, - pub(crate) codec: String, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestModel { - pub(crate) id: String, - pub(crate) typename: String, - pub(crate) source_table: String, - pub(crate) dependencies: Vec, - pub(crate) normalization: ManifestNormalization, - pub(crate) fields: Vec, - pub(crate) relationships: Vec, - pub(crate) filter_input: ManifestFilterInput, - pub(crate) row_policy: ManifestRowPolicy, - pub(crate) record_revisions: bool, - pub(crate) tombstones: bool, -} - -impl ManifestModel { - pub(crate) fn field(&self, name: &str) -> Option<&ManifestField> { - self.fields.iter().find(|field| field.name == name) - } - - pub(crate) fn relationship(&self, name: &str) -> Option<&ManifestRelationship> { - self.relationships - .iter() - .find(|relationship| relationship.name == name) - } - - pub(crate) fn identity(&self) -> Option<&[ManifestKeyField]> { - match &self.normalization { - ManifestNormalization::Normalized { fields, .. } => Some(fields), - ManifestNormalization::Embedded => None, - } - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub(crate) enum ManifestNormalization { - Normalized { - fields: Vec, - encoding: String, - }, - Embedded, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestKeyField { - pub(crate) name: String, - pub(crate) codec: String, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestField { - pub(crate) name: String, - pub(crate) scalar: String, - pub(crate) codec: String, - pub(crate) nullable: bool, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestFilterInput { - pub(crate) type_name: String, - pub(crate) fields: Vec, - pub(crate) relationships: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestFilterInputRelationship { - pub(crate) field: String, - pub(crate) target_type: String, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub(crate) enum ManifestRowPolicy { - Unrestricted, - Predicate { expression: ManifestFilterExpr }, - ServerOnly, -} - -#[derive(Clone, Debug, PartialEq, Deserialize)] -#[serde(tag = "kind", content = "value", rename_all = "snake_case")] -pub(crate) enum ManifestFilterExpr { - And(Vec), - Or(Vec), - Not(Box), - Cmp { - column: String, - op: ManifestCmpOp, - rhs: ManifestOperand, - }, - In { - column: String, - values: Vec, - negated: bool, - }, - IsNull { - column: String, - is_null: bool, - }, - Rel { - field: String, - predicate: Box, - }, -} - -impl Serialize for ManifestFilterExpr { - fn serialize(&self, serializer: S) -> Result - where - S: serde::Serializer, - { - use serde_json::json; - - fn wire_value(expression: &ManifestFilterExpr) -> JsonValue { - match expression { - ManifestFilterExpr::And(items) => json!({ - "kind": "and", - "value": items.iter().map(wire_value).collect::>() - }), - ManifestFilterExpr::Or(items) => json!({ - "kind": "or", - "value": items.iter().map(wire_value).collect::>() - }), - ManifestFilterExpr::Not(item) => { - json!({"kind": "not", "value": wire_value(item)}) - } - ManifestFilterExpr::Cmp { column, op, rhs } => json!({ - "kind": "cmp", - "value": {"column": column, "op": op, "rhs": rhs} - }), - ManifestFilterExpr::In { - column, - values, - negated, - } => json!({ - "kind": "in", - "value": { - "column": column, - "values": values, - "negated": negated - } - }), - ManifestFilterExpr::IsNull { column, is_null } => json!({ - "kind": "is_null", - "value": {"column": column, "is_null": is_null} - }), - ManifestFilterExpr::Rel { field, predicate } => json!({ - "kind": "rel", - "value": {"field": field, "predicate": wire_value(predicate)} - }), - } - } - - canonical_json_value(wire_value(self)).serialize(serializer) - } -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(tag = "kind", content = "value", rename_all = "snake_case")] -pub(crate) enum ManifestOperand { - Lit(ManifestLitValue), - Claim(ManifestClaimRef), -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(tag = "kind", content = "value", rename_all = "snake_case")] -pub(crate) enum ManifestLitValue { - String(String), - I64(i64), - F64(f64), - Bool(bool), - Json(JsonValue), - Null, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestClaimRef { - pub(crate) header: String, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ManifestCmpOp { - Eq, - Neq, - Gt, - Gte, - Lt, - Lte, - Like, - Ilike, - Contains, - ContainedIn, - HasKey, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestRelationship { - pub(crate) name: String, - pub(crate) target_model: String, - pub(crate) target_typename: String, - pub(crate) kind: ManifestRelationshipKind, - pub(crate) list: bool, - pub(crate) nullable: bool, - pub(crate) arguments: Vec, - pub(crate) key_mapping: ManifestRelationshipKeyMapping, - pub(crate) maintenance: ManifestRelationshipMaintenance, - pub(crate) dependencies: Vec, - pub(crate) filter: Option, - pub(crate) order: Option, - pub(crate) pagination: Option, - pub(crate) aggregate: Option, - pub(crate) live: bool, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ManifestRelationshipKind { - HasMany, - BelongsTo, - ManyToMany, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub(crate) enum ManifestRelationshipKeyMapping { - Direct { - local: Vec, - remote: Vec, - }, - Through { - local: Vec, - remote: Vec, - table: String, - source_foreign_key: Vec, - target_foreign_key: Vec, - }, - ThroughOpaque { - local: Vec, - remote: Vec, - dependency: String, - }, - Embedded, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ManifestRelationshipMaintenance { - Local, - Revalidate, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestRelationshipAggregate { - pub(crate) name: String, - pub(crate) arguments: Vec, - pub(crate) semantics: ManifestAggregateSemantics, - pub(crate) dependencies: Vec, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum RootOperation { - Query, - Subscription, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum RootKind { - List, - ByPk, - Aggregate, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestRoot { - pub(crate) id: String, - pub(crate) operation: RootOperation, - pub(crate) name: String, - pub(crate) kind: RootKind, - pub(crate) model: String, - pub(crate) arguments: Vec, - pub(crate) filter: Option, - pub(crate) order: Option, - pub(crate) pagination: Option, - pub(crate) aggregate: Option, - pub(crate) dependencies: Vec, - pub(crate) live: bool, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestArgument { - pub(crate) name: String, - pub(crate) kind: ManifestArgumentKind, - pub(crate) type_name: String, - pub(crate) nullable: bool, - pub(crate) list: bool, - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) codec: Option, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ManifestArgumentKind { - Filter, - Order, - Limit, - Offset, - PrimaryKey, -} - -impl ManifestArgument { - pub(crate) fn graphql_type(&self) -> String { - let base = if self.list { - format!("[{}!]", self.type_name) - } else { - self.type_name.clone() - }; - if self.nullable { - base - } else { - format!("{base}!") - } - } -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestFilterSemantics { - pub(crate) fields: Vec, - pub(crate) relationships: Vec, - pub(crate) row_policy: ManifestRowPolicy, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestFilterField { - pub(crate) name: String, - pub(crate) operators: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestOrderSemantics { - pub(crate) fields: Vec, - pub(crate) values: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestPagination { - pub(crate) kind: String, - pub(crate) default_limit: u64, - pub(crate) max_limit: u64, - pub(crate) coverage: String, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestAggregateSemantics { - pub(crate) wrapper_typename: String, - pub(crate) fields_typename: String, - pub(crate) nodes_pagination: ManifestPagination, - pub(crate) count: bool, - pub(crate) nodes: bool, - pub(crate) sum: Vec, - pub(crate) avg: Vec, - pub(crate) min: Vec, - pub(crate) max: Vec, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestCommand { - pub(crate) version: u32, - pub(crate) name: String, - pub(crate) mutation_field: String, - pub(crate) grants: Vec, - pub(crate) input: ManifestCommandShape, - pub(crate) output: ManifestCommandShape, - pub(crate) operation: String, - pub(crate) operation_hash: String, - pub(crate) extensions: ManifestCommandExtensions, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub(crate) enum ManifestCommandShape { - None, - Object { definition: ManifestTypeDef }, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestTypeDef { - pub(crate) name: String, - pub(crate) fields: Vec, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestTypeField { - pub(crate) name: String, - pub(crate) type_name: String, - pub(crate) nullable: bool, - pub(crate) list: bool, - pub(crate) item_nullable: bool, - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) codec: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) nested: Option>, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestCommandExtensions { - pub(crate) version: u32, - pub(crate) consistency: ManifestCommandConsistency, - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) direct_projection: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) input_defaults: Option, - #[serde( - default, - skip_serializing, - deserialize_with = "reject_legacy_command_authority" - )] - pub(crate) effects: Option, - #[serde( - default, - skip_serializing, - deserialize_with = "reject_legacy_command_authority" - )] - pub(crate) confirmations: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) projection: Option, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub(crate) trusted_presets: Vec, -} - -fn reject_legacy_command_authority<'de, D, T>(deserializer: D) -> Result, D::Error> -where - D: serde::Deserializer<'de>, -{ - let _ = serde::de::IgnoredAny::deserialize(deserializer)?; - Err(serde::de::Error::custom( - "client manifest v2 rejects legacy command effects/confirmations authority", - )) -} - -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestTrustedPresetDescriptor { - pub(crate) name: String, - pub(crate) codec: String, -} -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestCommandConsistency { - pub(crate) version: u32, - pub(crate) kind: ManifestConsistencyKind, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestDirectProjection { - pub(crate) topology: ManifestProjectionTopologyIdentity, - pub(crate) model: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) partition: Option, - pub(crate) change_epoch: String, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestProjectionTopologyIdentity { - pub(crate) version: u32, - pub(crate) name: String, - pub(crate) digest: String, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ManifestConsistencyKind { - Succeeded, - Eventual, - Atomic, -} - -#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestInputDefaults { - pub(crate) version: u32, - pub(crate) defaults: Vec, -} - -impl Serialize for ManifestInputDefaults { - fn serialize(&self, serializer: S) -> Result - where - S: serde::Serializer, - { - #[derive(Serialize)] - struct Wire<'a> { - version: u32, - defaults: &'a [JsonValue], - } - - let defaults = self - .defaults - .iter() - .map(serde_json::to_value) - .collect::, _>>() - .map_err(serde::ser::Error::custom)?; - Wire { - version: self.version, - defaults: &defaults, - } - .serialize(serializer) - } -} - -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestInputDefault { - pub(crate) path: Vec, - pub(crate) generator: ManifestInputDefaultGenerator, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ManifestInputDefaultGenerator { - UuidV7, - Ulid, -} - -#[derive(Clone, Debug, PartialEq, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestEffects { - pub(crate) version: u32, - pub(crate) operations: Vec, - pub(crate) fallback: ManifestRevalidationFallback, -} - -impl Serialize for ManifestEffects { - fn serialize(&self, serializer: S) -> Result - where - S: serde::Serializer, - { - #[derive(Serialize)] - struct Wire<'a> { - version: u32, - operations: &'a [JsonValue], - fallback: ManifestRevalidationFallback, - } - - let operations = self - .operations - .iter() - .map(serde_json::to_value) - .collect::, _>>() - .map_err(serde::ser::Error::custom)?; - Wire { - version: self.version, - operations: &operations, - fallback: self.fallback, - } - .serialize(serializer) - } -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub(crate) enum ManifestEffect { - Upsert { - model: String, - key: ManifestEffectKey, - fields: Vec, - }, - Patch { - model: String, - key: ManifestEffectKey, - fields: Vec, - }, - Delete { - model: String, - key: ManifestEffectKey, - }, - Link { - relationship: ManifestEffectRelationship, - source: ManifestEffectKey, - target: ManifestEffectKey, - }, - Unlink { - relationship: ManifestEffectRelationship, - source: ManifestEffectKey, - target: ManifestEffectKey, - }, - InvalidateModel { - model: String, - }, - InvalidateRelationship { - relationship: ManifestEffectRelationship, - source: ManifestEffectKey, - }, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestEffectRelationship { - pub(crate) source_model: String, - pub(crate) field: String, - pub(crate) target_model: String, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestEffectKey { - pub(crate) fields: Vec, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestEffectField { - pub(crate) field: String, - pub(crate) value: ManifestEffectExpression, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub(crate) enum ManifestEffectExpression { - Input { path: Vec }, - TrustedPreset { name: String }, - Constant { value: JsonValue }, - Null, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ManifestRevalidationFallback { - Revalidate, -} - -#[derive(Clone, Debug, PartialEq, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestConfirmations { - pub(crate) version: u32, - pub(crate) kind: ManifestConfirmationKind, - pub(crate) expected: Vec, - pub(crate) fallback: ManifestRevalidationFallback, -} - -impl Serialize for ManifestConfirmations { - fn serialize(&self, serializer: S) -> Result - where - S: serde::Serializer, - { - #[derive(Serialize)] - struct Wire<'a> { - version: u32, - kind: ManifestConfirmationKind, - expected: &'a [JsonValue], - fallback: ManifestRevalidationFallback, - } - - let expected = self - .expected - .iter() - .map(serde_json::to_value) - .collect::, _>>() - .map_err(serde::ser::Error::custom)?; - Wire { - version: self.version, - kind: self.kind, - expected: &expected, - fallback: self.fallback, - } - .serialize(serializer) - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ManifestConfirmationKind { - Finite, - Unavailable, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestConfirmation { - pub(crate) projector: String, - pub(crate) model: String, - pub(crate) key: ManifestEffectKey, - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) partition: Option, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestProtocolOperations { - pub(crate) version: u32, - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) command_status: Option, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestProtocolOperation { - pub(crate) name: String, - pub(crate) operation: String, - pub(crate) operation_hash: String, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestProjector { - pub(crate) version: u32, - pub(crate) name: String, - pub(crate) facts: Vec, - pub(crate) models: Vec, - pub(crate) dependencies: Vec, - pub(crate) causal_confirmation: bool, -} - -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestProjectionEventRef { - pub(crate) id: String, - pub(crate) name: String, - pub(crate) version: u64, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestProjectionBinding { - pub(crate) version: u32, - pub(crate) binding_id: String, - pub(crate) program_id: String, - pub(crate) epoch: String, - pub(crate) state: ManifestProjectionBindingState, - pub(crate) placement: ManifestProjectionPlacement, - pub(crate) execution_class: ManifestProjectionExecutionClass, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ManifestProjectionBindingState { - Active, - Draining, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ManifestProjectionPlacement { - Eventual, - Direct, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ManifestProjectionExecutionClass { - Causal, - Background, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestProjectionProgram { - pub(crate) version: u32, - pub(crate) program_id: String, - pub(crate) name: String, - pub(crate) program_version: u64, - pub(crate) ir_version: u16, - pub(crate) operation_semantics_version: u16, - pub(crate) arms: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestProjectionArm { - pub(crate) arm: String, - pub(crate) event: ManifestProjectionEventRef, - pub(crate) partition: ManifestProjectionPartition, - pub(crate) operations: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub(crate) enum ManifestProjectionPartition { - Unit, - Expression { - expression: ManifestProjectionExpression, - }, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestProjectionOperation { - pub(crate) operation: String, - pub(crate) ordinal: u32, - pub(crate) kind: ManifestProjectionMutationKind, - pub(crate) model: String, - pub(crate) key: Vec, - pub(crate) fields: Vec, - pub(crate) relationships: Vec, - pub(crate) invalidations: Vec, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ManifestProjectionMutationKind { - Insert, - Upsert, - Patch, - UpsertPatch, - Delete, - Recreate, - InsertRelated, - UpsertRelated, - InvalidateModel, - InvalidateRelationship, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestProjectionKeyField { - pub(crate) ordinal: u32, - pub(crate) name: String, - pub(crate) expression: ManifestProjectionExpression, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestProjectionField { - pub(crate) ordinal: u32, - pub(crate) name: String, - pub(crate) assignment: ManifestProjectionAssignment, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub(crate) enum ManifestProjectionAssignment { - Set { - expression: ManifestProjectionExpression, - }, - Unset, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub(crate) enum ManifestProjectionExpression { - Slot { - slot: String, - value_type: ManifestProjectionValueType, - }, - Envelope { - field: ManifestProjectionEnvelopeField, - }, - Constant { - value: ManifestProjectionValue, - }, - Enum { - enum_type: String, - variant: String, - }, - List { - values: Vec, - }, - Object { - fields: Vec, - }, - Transform { - transform: ManifestProjectionScalarTransform, - arguments: Vec, - }, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestProjectionObjectField { - pub(crate) name: String, - pub(crate) value: ManifestProjectionExpression, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde( - tag = "type", - content = "name", - rename_all = "snake_case", - deny_unknown_fields -)] -pub(crate) enum ManifestProjectionValueType { - Boolean, - I64, - U64, - F64, - String, - Enum(String), - Json, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ManifestProjectionScalarTransform { - StringConcat, - FirstPresent, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ManifestProjectionEnvelopeField { - OccurrenceVersion, - EventName, - EventVersion, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde( - tag = "type", - content = "value", - rename_all = "snake_case", - deny_unknown_fields -)] -pub(crate) enum ManifestProjectionValue { - Null, - Boolean(bool), - I64(String), - U64(String), - F64(String), - String(String), - Enum { enum_type: String, variant: String }, - List(Vec), - Object(Vec), -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestProjectionValueField { - pub(crate) name: String, - pub(crate) value: ManifestProjectionValue, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestProjectionRelationshipEffect { - pub(crate) ordinal: u32, - pub(crate) kind: ManifestProjectionRelationshipEffectKind, - pub(crate) source_model: String, - pub(crate) relationship: String, - pub(crate) target_model: String, - pub(crate) source_key: Vec, - pub(crate) target_key: Vec, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ManifestProjectionRelationshipEffectKind { - Link, - Unlink, - Invalidate, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub(crate) enum ManifestProjectionInvalidation { - Model { - model: String, - }, - Relationship { - source_model: String, - relationship: String, - target_model: String, - }, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestCommandProjection { - pub(crate) version: u32, - pub(crate) event_set: Vec, - pub(crate) program_arms: Vec, - pub(crate) preview_occurrences: Vec, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub(crate) pure_reduces: Vec, - pub(crate) fallback: ManifestProjectionFallback, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestCommandPureReduce { - pub(crate) fn_name: String, - #[serde(default, skip_serializing_if = "String::is_empty")] - pub(crate) client_module: String, - #[serde(default, skip_serializing_if = "String::is_empty")] - pub(crate) client_export: String, - #[serde(default, skip_serializing_if = "String::is_empty")] - pub(crate) wasm_package: String, - #[serde(default, skip_serializing_if = "String::is_empty")] - pub(crate) wasm_export: String, - pub(crate) model: String, - pub(crate) key: Vec, - pub(crate) args: Vec, - pub(crate) assign: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestCommandPureArg { - pub(crate) name: String, - pub(crate) source: ManifestProjectionPreviewSource, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum ManifestProjectionFallback { - Revalidate, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestCommandProjectionArmRef { - pub(crate) event: ManifestProjectionEventRef, - pub(crate) program_id: String, - pub(crate) arm: String, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestCommandProjectionPreviewOccurrence { - pub(crate) ordinal: u32, - pub(crate) event: ManifestProjectionEventRef, - pub(crate) values: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ManifestCommandProjectionPreviewValue { - pub(crate) slot: String, - pub(crate) source: ManifestProjectionPreviewSource, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub(crate) enum ManifestProjectionPreviewSource { - Input { path: Vec }, - GeneratedDefault { path: Vec }, - TrustedPreset { name: String, codec: String }, - Constant { value: ManifestProjectionValue }, - Null, - Absent, - Unknown, -} diff --git a/distributed_cli/src/client_compiler/manifest/util.rs b/distributed_cli/src/client_compiler/manifest/util.rs index feda806b5..f507b6ebd 100644 --- a/distributed_cli/src/client_compiler/manifest/util.rs +++ b/distributed_cli/src/client_compiler/manifest/util.rs @@ -69,18 +69,18 @@ pub(crate) fn canonical_json_value(value: JsonValue) -> JsonValue { #[cfg(test)] mod canonical_wire_tests { - use super::super::{ManifestFilterExpr, ManifestLitValue, ManifestOperand}; + use super::super::{FilterExpr, LitValue, Operand}; #[test] fn filter_expr_serialization_is_canonical_across_map_backends() { let mut value = serde_json::Map::new(); value.insert("z".into(), serde_json::json!(2)); value.insert("a".into(), serde_json::json!(1)); - let expression = ManifestFilterExpr::In { + let expression = FilterExpr::In { column: "metadata".into(), - values: vec![ManifestOperand::Lit(ManifestLitValue::Json( - serde_json::Value::Object(value), - ))], + values: vec![Operand::Lit(LitValue::Json(serde_json::Value::Object( + value, + )))], negated: false, }; diff --git a/distributed_cli/src/client_compiler/mod.rs b/distributed_cli/src/client_compiler/mod.rs index 278cbb7a3..f491ec12a 100644 --- a/distributed_cli/src/client_compiler/mod.rs +++ b/distributed_cli/src/client_compiler/mod.rs @@ -1,13 +1,14 @@ //! Pure, framework-neutral compiler for Distributed client artifacts. //! -//! This module deliberately owns no filesystem or glob behavior. Callers load -//! one role/application-selected manifest and the colocated GraphQL documents, -//! then decide how to write or check the returned files. +//! The compiler deliberately owns no filesystem or glob behavior. Callers load +//! one role/application-selected manifest and the colocated GraphQL documents; +//! `output` writes or checks the returned files in a directory. mod command_manifest; mod graphql; mod islands; mod manifest; +mod output; mod projection_delta; mod render; @@ -17,28 +18,31 @@ mod command_manifest_tests; use std::collections::BTreeMap; use std::fmt; -use serde::{Deserialize, Serialize}; +pub use distributed::graphql::{ClientSurfaceIdentity, DistributedClientManifest}; +use serde::Serialize; use serde_json::Value as JsonValue; use graphql::compile_document; use manifest::ClientManifest; +pub(crate) use output::{check_client_project, write_client_project}; use render::render_project; /// Complete input to one deterministic client compilation. #[derive(Clone, Debug)] pub struct ClientCompileInput { /// The role/application-selected Distributed client manifest. - pub manifest: JsonValue, - /// Exact authorization surface expected by the caller. - pub selector: ClientSurfaceSelector, + pub manifest: DistributedClientManifest, + /// Exact authorization surface expected by the caller. This value only + /// verifies manifest provenance; it can never relabel a broader manifest. + pub selector: ClientSurfaceIdentity, /// GraphQL sources. Filesystem traversal and glob expansion stay in the CLI. pub documents: Vec, } impl ClientCompileInput { pub fn new( - manifest: JsonValue, - selector: ClientSurfaceSelector, + manifest: DistributedClientManifest, + selector: ClientSurfaceIdentity, documents: Vec, ) -> Self { Self { @@ -47,42 +51,26 @@ impl ClientCompileInput { documents, } } -} - -/// Explicit client authorization surface. This value only verifies manifest -/// provenance; it can never relabel a broader manifest. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case")] -pub enum ClientSurfaceSelector { - Role { name: String }, - Application { - name: String, - eligible_roles: Vec, - schema_roles: Vec, - }, -} - -impl ClientSurfaceSelector { - pub fn role(name: impl Into) -> Self { - Self::Role { name: name.into() } - } - pub fn application( - name: impl Into, - eligible_roles: impl IntoIterator>, - schema_roles: impl IntoIterator>, - ) -> Self { - let mut eligible_roles = eligible_roles.into_iter().map(Into::into).collect::>(); - let mut schema_roles = schema_roles.into_iter().map(Into::into).collect::>(); - eligible_roles.sort(); - eligible_roles.dedup(); - schema_roles.sort(); - schema_roles.dedup(); - Self::Application { - name: name.into(), - eligible_roles, - schema_roles, - } + /// The same input from manifest JSON, as `distributed client-manifest` + /// writes it. + /// + /// # Errors + /// + /// `client.manifest.invalid` when the JSON is not exactly the manifest + /// shape and versions this compiler was built with. + pub fn from_manifest_json( + manifest: JsonValue, + selector: ClientSurfaceIdentity, + documents: Vec, + ) -> Result { + let manifest = serde_json::from_value(manifest).map_err(|error| { + ClientCompileError::manifest( + "client.manifest.invalid", + format!("invalid Distributed client manifest: {error}"), + ) + })?; + Ok(Self::new(manifest, selector, documents)) } } diff --git a/distributed_cli/src/client_compiler/output.rs b/distributed_cli/src/client_compiler/output.rs new file mode 100644 index 000000000..3aef2e14e --- /dev/null +++ b/distributed_cli/src/client_compiler/output.rs @@ -0,0 +1,124 @@ +//! Writing and checking a compiled client project on disk. +//! +//! The compiler itself stays pure; this is the only part of the module that +//! touches the filesystem, and it does so through [`GeneratedDir`]. + +use std::collections::BTreeSet; +use std::error::Error; +use std::fs; +use std::path::{Component, Path}; + +use super::GeneratedClientProject; +use crate::generated_dir::GeneratedDir; + +const MAX_PROVENANCE_BYTES: u64 = 16 * 1024 * 1024; +const OWNERSHIP_MARKER: &str = "/** GENERATED by distributed client. Do not edit. */"; + +/// Make `root` hold exactly the compiled project. +/// +/// An operation module the previous run recorded in `manifest.json`, and that +/// still carries the compiler's marker, is removed when its operation is gone. +/// Any other file the project does not contain makes the write fail before +/// anything changes: a missing or unreadable record never authorizes a +/// deletion. +pub(crate) fn write_client_project( + root: &Path, + project: &GeneratedClientProject, +) -> Result<(), Box> { + let previous = previous_operation_modules(root)?; + // Provenance is written last so an interrupted run never advertises a new + // complete generation before its operation modules exist. + let mut files = project.files.clone(); + files.sort_by(|left, right| { + (left.path == "manifest.json", &left.path) + .cmp(&(right.path == "manifest.json", &right.path)) + }); + client_dir(root).write(&files, |path, contents| { + if !previous.contains(path) { + return Ok(false); + } + if !contents.starts_with(OWNERSHIP_MARKER) { + return Err(format!( + "refusing to remove {} because its compiler ownership marker is missing", + root.join(path).display() + ) + .into()); + } + Ok(true) + }) +} + +/// Fail unless `root` holds exactly the compiled project. Reads only. +pub(crate) fn check_client_project( + root: &Path, + project: &GeneratedClientProject, +) -> Result<(), Box> { + let drift = client_dir(root).drift(&project.files)?; + if drift.is_empty() { + return Ok(()); + } + Err(format!( + "generated Distributed client artifacts are stale:\n {}\nrun `distributed client` without --check to regenerate", + drift.join("\n ") + ) + .into()) +} + +fn client_dir(root: &Path) -> GeneratedDir<'_> { + GeneratedDir { root, nested: true } +} + +/// The operation modules the previous run recorded in `/manifest.json`. +/// Empty when there was no previous run. +fn previous_operation_modules(root: &Path) -> Result, Box> { + let path = root.join("manifest.json"); + let refuse = |problem: &str| -> Box { + format!( + "previous generated client manifest {} {problem}; refusing to guess stale-file ownership", + path.display() + ) + .into() + }; + let metadata = match fs::symlink_metadata(&path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeSet::new()), + Err(error) => return Err(refuse(&format!("cannot be inspected: {error}"))), + }; + if !metadata.is_file() || metadata.len() > MAX_PROVENANCE_BYTES { + return Err(refuse("must be a regular file of at most 16 MiB")); + } + let provenance: serde_json::Value = serde_json::from_slice( + &fs::read(&path).map_err(|error| refuse(&format!("cannot be read: {error}")))?, + ) + .map_err(|error| refuse(&format!("cannot be parsed: {error}")))?; + if provenance + .get("compiler_manifest_version") + .and_then(serde_json::Value::as_u64) + != Some(2) + { + return Err(refuse("has an unsupported compiler_manifest_version")); + } + let operations = provenance + .get("operations") + .and_then(serde_json::Value::as_array) + .ok_or_else(|| refuse("is missing operations"))?; + let mut modules = BTreeSet::new(); + for (index, operation) in operations.iter().enumerate() { + let module = operation + .get("module_path") + .and_then(serde_json::Value::as_str) + .ok_or_else(|| refuse(&format!("operations[{index}] is missing module_path")))?; + let mut components = Path::new(module).components(); + let is_operation_module = matches!(components.next(), Some(Component::Normal(directory)) if directory == "operations") + && matches!(components.next(), Some(Component::Normal(file)) if Path::new(file).extension().is_some_and(|extension| extension == "ts")) + && components.next().is_none(); + if !is_operation_module { + return Err(format!( + "previous compiler provenance contains unsafe operation module path `{module}`; refusing to remove it" + ) + .into()); + } + modules.insert(module.to_string()); + } + Ok(modules) +} diff --git a/distributed_cli/src/client_compiler/projection_delta/mod.rs b/distributed_cli/src/client_compiler/projection_delta/mod.rs index 1daf48f79..a79c38cb6 100644 --- a/distributed_cli/src/client_compiler/projection_delta/mod.rs +++ b/distributed_cli/src/client_compiler/projection_delta/mod.rs @@ -1,11 +1,7 @@ -//! Compiler-owned projection-delta contracts. -//! -//! `wire` mirrors the frozen Rust response protocol exactly. `preview` is a -//! separate executable artifact IR whose values remain scoped input/preset -//! expressions until the JavaScript command runtime prepares a command. +//! Compiler-owned command preview: an executable artifact IR whose values +//! remain scoped input/preset expressions until the JavaScript command +//! runtime prepares a command. mod preview; -mod wire; pub(crate) use preview::{compile_command_preview, CompiledCommandProjection}; -pub(crate) use wire::PROJECTION_DELTA_WIRE_VERSION; diff --git a/distributed_cli/src/client_compiler/projection_delta/preview.rs b/distributed_cli/src/client_compiler/projection_delta/preview.rs index 0245253eb..1631d3902 100644 --- a/distributed_cli/src/client_compiler/projection_delta/preview.rs +++ b/distributed_cli/src/client_compiler/projection_delta/preview.rs @@ -4,7 +4,7 @@ use serde::Serialize; use super::super::manifest::*; use super::super::ClientCompileError; -use super::PROJECTION_DELTA_WIRE_VERSION; +use distributed::graphql::projection_delta::PROJECTION_DELTA_WIRE_VERSION; const PREVIEW_PLAN_VERSION: u16 = 1; const MAX_PREVIEW_ITEMS: usize = 128; @@ -47,7 +47,7 @@ pub(crate) enum PreviewExpression { codec: String, }, Constant { - value: ManifestProjectionValue, + value: ClientProjectionValue, }, Null, List { @@ -57,7 +57,7 @@ pub(crate) enum PreviewExpression { fields: Vec, }, Transform { - transform: ManifestProjectionScalarTransform, + transform: ProjectionScalarTransform, arguments: Vec, }, } @@ -76,12 +76,12 @@ pub(crate) struct CompiledCommandProjection { projection_program_version: u32, operation_semantics_version: u16, projections: Vec, - event_set: Vec, + event_set: Vec, capabilities: ProjectionCapabilities, preview: PreviewPlan, #[serde(default, skip_serializing_if = "Vec::is_empty")] pure_reduces: Vec, - fallback: ManifestProjectionFallback, + fallback: ClientProjectionFallback, #[serde(skip)] selected_models: BTreeSet, } @@ -116,6 +116,16 @@ struct CompiledPureArg { } impl CompiledCommandProjection { + /// Only emitted mutations consume command presets. Authored occurrences + /// can lower to recovery without retaining any of their input expressions. + pub(crate) fn trusted_preset_names(&self) -> BTreeSet { + let mut names = BTreeSet::new(); + for operation in &self.preview.operations { + operation.mutation.collect_trusted_presets(&mut names); + } + names + } + pub(crate) fn affected_models(&self) -> BTreeSet { let mut models = BTreeSet::new(); for operation in &self.preview.operations { @@ -194,7 +204,7 @@ struct ProjectionCapabilities { #[derive(Clone, Debug, PartialEq, Eq, Serialize)] struct ProjectionCapabilityArm { - event: ManifestProjectionEventRef, + event: ClientProjectionEventRef, projection_ref: u32, arm: String, partition: ProjectionCapabilityPartition, @@ -245,7 +255,7 @@ struct PreviewPlan { #[derive(Clone, Debug, PartialEq, Eq, Serialize)] struct PreviewOccurrence { ordinal: u32, - event: ManifestProjectionEventRef, + event: ClientProjectionEventRef, } #[derive(Clone, Debug, PartialEq, Eq, Serialize)] @@ -333,6 +343,31 @@ enum PreviewMutation { } impl PreviewMutation { + fn collect_trusted_presets(&self, names: &mut BTreeSet) { + match self { + Self::Upsert { scope, fields, .. } + | Self::Patch { + scope, set: fields, .. + } => { + scope.collect_trusted_presets(names); + for field in fields { + field.value.collect_trusted_presets(names); + } + } + Self::Delete { scope } => scope.collect_trusted_presets(names), + Self::Link { source, target, .. } | Self::Unlink { source, target, .. } => { + source.collect_trusted_presets(names); + target.collect_trusted_presets(names); + } + Self::InvalidateRelationship { source, .. } => source.collect_trusted_presets(names), + Self::InvalidateModel { partition, .. } => { + if let Some(partition) = partition { + partition.collect_trusted_presets(names); + } + } + } + } + fn canonical_scope(&self) -> Result { let scope_json = |scope: &PreviewScope| { serde_json::to_string(scope).map_err(|error| { @@ -430,6 +465,50 @@ impl PreviewMutation { } } +impl PreviewScope { + fn collect_trusted_presets(&self, names: &mut BTreeSet) { + self.partition.collect_trusted_presets(names); + for field in &self.key { + field.value.collect_trusted_presets(names); + } + } +} + +impl PreviewPartition { + fn collect_trusted_presets(&self, names: &mut BTreeSet) { + if let Self::Expression { expression, .. } = self { + expression.collect_trusted_presets(names); + } + } +} + +impl PreviewExpression { + fn collect_trusted_presets(&self, names: &mut BTreeSet) { + match self { + Self::TrustedPreset { name, .. } => { + names.insert(name.clone()); + } + Self::List { values } + | Self::Transform { + arguments: values, .. + } => { + for value in values { + value.collect_trusted_presets(names); + } + } + Self::Object { fields } => { + for field in fields { + field.value.collect_trusted_presets(names); + } + } + Self::Input { .. } + | Self::GeneratedDefault { .. } + | Self::Constant { .. } + | Self::Null => {} + } + } +} + /// The variant declaration order is the canonical operation-kind order shared /// with the authoritative ProjectionDelta wire. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] @@ -545,7 +624,7 @@ enum PreviewRecoveryTargetKey { } pub(crate) fn compile_command_preview( - command: &ManifestCommand, + command: &ClientCommand, manifest: &ClientManifest, ) -> Result, ClientCompileError> { let Some(extension) = &command.extensions.projection else { @@ -571,11 +650,11 @@ pub(crate) fn compile_command_preview( .iter() .find(|binding| { binding.program_id == program_id - && binding.state == ManifestProjectionBindingState::Active - && binding.execution_class == ManifestProjectionExecutionClass::Causal + && binding.state == ProjectionBindingState::Active + && binding.execution_class == ProjectionExecutionClass::Causal && matches!( binding.placement, - ManifestProjectionPlacement::Eventual | ManifestProjectionPlacement::Direct + ProjectionPlacement::Eventual | ProjectionPlacement::Direct ) }) .expect("manifest validation proved one eligible binding"); @@ -700,14 +779,14 @@ pub(crate) fn compile_command_preview( } fn compile_capability_arm( - event: ManifestProjectionEventRef, + event: ClientProjectionEventRef, projection_ref: u32, - arm: &ManifestProjectionArm, + arm: &ClientProjectionArm, manifest: &ClientManifest, ) -> Result { let partition = match &arm.partition { - ManifestProjectionPartition::Unit => ProjectionCapabilityPartition::Unit, - ManifestProjectionPartition::Expression { expression } => { + ClientProjectionPartition::Unit => ProjectionCapabilityPartition::Unit, + ClientProjectionPartition::Expression { expression } => { let encoded = serde_json::to_vec(expression).map_err(|error| { ClientCompileError::manifest( "client.projection_capability.partition", @@ -727,8 +806,8 @@ fn compile_capability_arm( .expect("manifest validation proved operation model"); if !matches!( operation.kind, - ManifestProjectionMutationKind::InvalidateModel - | ManifestProjectionMutationKind::InvalidateRelationship + ClientProjectionMutationKind::InvalidateModel + | ClientProjectionMutationKind::InvalidateRelationship ) { let identity = model .identity() @@ -755,11 +834,11 @@ fn compile_capability_arm( fields.dedup(); let complete = matches!( operation.kind, - ManifestProjectionMutationKind::Insert - | ManifestProjectionMutationKind::Upsert - | ManifestProjectionMutationKind::Recreate - | ManifestProjectionMutationKind::InsertRelated - | ManifestProjectionMutationKind::UpsertRelated + ClientProjectionMutationKind::Insert + | ClientProjectionMutationKind::Upsert + | ClientProjectionMutationKind::Recreate + | ClientProjectionMutationKind::InsertRelated + | ClientProjectionMutationKind::UpsertRelated ); mutations.push(ProjectionCapabilityMutation::Record { model: operation.model.clone(), @@ -772,13 +851,13 @@ fn compile_capability_arm( replace: replace.clone(), upsert: complete, patch: !fields.is_empty(), - delete: operation.kind == ManifestProjectionMutationKind::Delete, + delete: operation.kind == ClientProjectionMutationKind::Delete, }); mutations.push(ProjectionCapabilityMutation::Model { model: operation.model.clone(), }); } - if operation.kind == ManifestProjectionMutationKind::InvalidateModel { + if operation.kind == ClientProjectionMutationKind::InvalidateModel { mutations.push(ProjectionCapabilityMutation::Model { model: operation.model.clone(), }); @@ -798,8 +877,8 @@ fn compile_capability_arm( .iter() .map(|field| field.name.clone()) .collect(), - link: effect.kind == ManifestProjectionRelationshipEffectKind::Link, - unlink: effect.kind == ManifestProjectionRelationshipEffectKind::Unlink, + link: effect.kind == ProjectionRelationshipEffectKind::Link, + unlink: effect.kind == ProjectionRelationshipEffectKind::Unlink, }); mutations.push(ProjectionCapabilityMutation::Model { model: effect.source_model.clone(), @@ -807,18 +886,18 @@ fn compile_capability_arm( } for invalidation in &operation.invalidations { match invalidation { - ManifestProjectionInvalidation::Model { model } => { + ClientProjectionInvalidation::Model { model } => { mutations.push(ProjectionCapabilityMutation::Model { model: model.clone(), }); } - ManifestProjectionInvalidation::Relationship { + ClientProjectionInvalidation::Relationship { source_model, relationship, target_model, } => { let keyed = operation.relationships.iter().any(|effect| { - effect.kind == ManifestProjectionRelationshipEffectKind::Invalidate + effect.kind == ProjectionRelationshipEffectKind::Invalidate && effect.source_model == *source_model && effect.relationship == *relationship && effect.target_model == *target_model @@ -847,10 +926,10 @@ fn compile_capability_arm( fn lower_arm( occurrence_ordinal: u32, projection_ref: u32, - event: &ManifestProjectionEventRef, - arm: &ManifestProjectionArm, + event: &ClientProjectionEventRef, + arm: &ClientProjectionArm, slots: &BTreeMap<&str, Knowledge>, - command: &ManifestCommand, + command: &ClientCommand, manifest: &ClientManifest, operations: &mut Vec, recoveries: &mut Vec, @@ -929,7 +1008,7 @@ fn push_preview_item(items: &mut Vec, item: T) -> Result<(), ClientCompile Ok(()) } -fn collect_selected_models(arm: &ManifestProjectionArm, models: &mut BTreeSet) { +fn collect_selected_models(arm: &ClientProjectionArm, models: &mut BTreeSet) { for operation in &arm.operations { models.insert(operation.model.clone()); for relationship in &operation.relationships { @@ -938,10 +1017,10 @@ fn collect_selected_models(arm: &ManifestProjectionArm, models: &mut BTreeSet { + ClientProjectionInvalidation::Model { model } => { models.insert(model.clone()); } - ManifestProjectionInvalidation::Relationship { + ClientProjectionInvalidation::Relationship { source_model, target_model, .. @@ -958,19 +1037,19 @@ fn collect_selected_models(arm: &ManifestProjectionArm, models: &mut BTreeSet, slots: &BTreeMap<&str, Knowledge>, - command: &ManifestCommand, - model: &ManifestModel, + command: &ClientCommand, + model: &ClientModel, operations: &mut Vec, recoveries: &mut Vec, ) -> Result<(), ClientCompileError> { if matches!( operation.kind, - ManifestProjectionMutationKind::InvalidateModel - | ManifestProjectionMutationKind::InvalidateRelationship + ClientProjectionMutationKind::InvalidateModel + | ClientProjectionMutationKind::InvalidateRelationship ) { return Ok(()); } @@ -1008,11 +1087,11 @@ fn lower_record( .collect::>(); let (set, unset, uncertain) = evaluate_fields(&operation.fields, slots, event); match operation.kind { - ManifestProjectionMutationKind::Insert - | ManifestProjectionMutationKind::Upsert - | ManifestProjectionMutationKind::Recreate - | ManifestProjectionMutationKind::InsertRelated - | ManifestProjectionMutationKind::UpsertRelated => { + ClientProjectionMutationKind::Insert + | ClientProjectionMutationKind::Upsert + | ClientProjectionMutationKind::Recreate + | ClientProjectionMutationKind::InsertRelated + | ClientProjectionMutationKind::UpsertRelated => { let mapped = set .iter() .map(|field| field.field.as_str()) @@ -1072,7 +1151,7 @@ fn lower_record( )?; } } - ManifestProjectionMutationKind::Patch | ManifestProjectionMutationKind::UpsertPatch => { + ClientProjectionMutationKind::Patch | ClientProjectionMutationKind::UpsertPatch => { if !set.is_empty() || !unset.is_empty() { push_preview_item( operations, @@ -1108,7 +1187,7 @@ fn lower_record( )?; } } - ManifestProjectionMutationKind::Delete => push_preview_item( + ClientProjectionMutationKind::Delete => push_preview_item( operations, PreviewOperation { occurrence_ordinal, @@ -1116,8 +1195,8 @@ fn lower_record( mutation: PreviewMutation::Delete { scope }, }, )?, - ManifestProjectionMutationKind::InvalidateModel - | ManifestProjectionMutationKind::InvalidateRelationship => unreachable!(), + ClientProjectionMutationKind::InvalidateModel + | ClientProjectionMutationKind::InvalidateRelationship => unreachable!(), } Ok(()) } @@ -1126,11 +1205,11 @@ fn lower_record( fn lower_relationships( occurrence_ordinal: u32, projection_ref: u32, - event: &ManifestProjectionEventRef, - operation: &ManifestProjectionOperation, + event: &ClientProjectionEventRef, + operation: &ClientProjectionOperation, partition: &Option, slots: &BTreeMap<&str, Knowledge>, - command: &ManifestCommand, + command: &ClientCommand, operations: &mut Vec, recoveries: &mut Vec, ) -> Result<(), ClientCompileError> { @@ -1153,7 +1232,7 @@ fn lower_relationships( key, }); match (effect.kind, source, target) { - (ManifestProjectionRelationshipEffectKind::Link, Some(source), Some(target)) => { + (ProjectionRelationshipEffectKind::Link, Some(source), Some(target)) => { push_preview_item( operations, PreviewOperation { @@ -1167,7 +1246,7 @@ fn lower_relationships( }, )?; } - (ManifestProjectionRelationshipEffectKind::Unlink, Some(source), Some(target)) => { + (ProjectionRelationshipEffectKind::Unlink, Some(source), Some(target)) => { push_preview_item( operations, PreviewOperation { @@ -1221,13 +1300,13 @@ fn lower_relationships( fn lower_invalidations( occurrence_ordinal: u32, projection_ref: u32, - operation: &ManifestProjectionOperation, + operation: &ClientProjectionOperation, partition: &Option, operations: &mut Vec, recoveries: &mut Vec, ) -> Result<(), ClientCompileError> { let partition = partition.clone(); - if operation.kind == ManifestProjectionMutationKind::InvalidateModel { + if operation.kind == ClientProjectionMutationKind::InvalidateModel { push_preview_item( operations, PreviewOperation { @@ -1251,7 +1330,7 @@ fn lower_invalidations( } for invalidation in &operation.invalidations { match invalidation { - ManifestProjectionInvalidation::Model { model } => { + ClientProjectionInvalidation::Model { model } => { push_preview_item( operations, PreviewOperation { @@ -1273,13 +1352,13 @@ fn lower_invalidations( ), )?; } - ManifestProjectionInvalidation::Relationship { + ClientProjectionInvalidation::Relationship { source_model, relationship, target_model, } => { let has_keyed_effect = operation.relationships.iter().any(|effect| { - effect.kind == ManifestProjectionRelationshipEffectKind::Invalidate + effect.kind == ProjectionRelationshipEffectKind::Invalidate && effect.source_model == *source_model && effect.relationship == *relationship && effect.target_model == *target_model @@ -1317,13 +1396,13 @@ fn lower_invalidations( } fn evaluate_partition( - partition: &ManifestProjectionPartition, + partition: &ClientProjectionPartition, slots: &BTreeMap<&str, Knowledge>, - event: &ManifestProjectionEventRef, + event: &ClientProjectionEventRef, ) -> Option { match partition { - ManifestProjectionPartition::Unit => Some(PreviewPartition::Unit), - ManifestProjectionPartition::Expression { expression } => { + ClientProjectionPartition::Unit => Some(PreviewPartition::Unit), + ClientProjectionPartition::Expression { expression } => { match evaluate_expression(expression, slots, event) { // This is an executable logical expression, never a server // projection-partition token. The runtime must prove it maps @@ -1344,10 +1423,10 @@ fn evaluate_partition( } fn evaluate_key( - key: &[ManifestProjectionKeyField], + key: &[ClientProjectionKeyField], slots: &BTreeMap<&str, Knowledge>, - event: &ManifestProjectionEventRef, - command: &ManifestCommand, + event: &ClientProjectionEventRef, + command: &ClientCommand, ) -> Option> { let mut result = Vec::with_capacity(key.len()); for field in key { @@ -1368,7 +1447,7 @@ fn evaluate_key( fn preview_key_value_is_provably_non_null_scalar( value: &PreviewExpression, - command: &ManifestCommand, + command: &ClientCommand, ) -> bool { match value { PreviewExpression::Input { path } => { @@ -1392,12 +1471,12 @@ fn preview_key_value_is_provably_non_null_scalar( PreviewExpression::TrustedPreset { codec, .. } => codec != "json", PreviewExpression::Constant { value } => matches!( value, - ManifestProjectionValue::Boolean(_) - | ManifestProjectionValue::I64(_) - | ManifestProjectionValue::U64(_) - | ManifestProjectionValue::F64(_) - | ManifestProjectionValue::String(_) - | ManifestProjectionValue::Enum { .. } + ClientProjectionValue::Boolean(_) + | ClientProjectionValue::I64(_) + | ClientProjectionValue::U64(_) + | ClientProjectionValue::F64(_) + | ClientProjectionValue::String(_) + | ClientProjectionValue::Enum { .. } ), PreviewExpression::Null | PreviewExpression::List { .. } @@ -1406,23 +1485,21 @@ fn preview_key_value_is_provably_non_null_scalar( transform, arguments, } => match transform { - ManifestProjectionScalarTransform::StringConcat => arguments + ProjectionScalarTransform::StringConcat => arguments .iter() .all(|argument| preview_key_value_is_provably_non_null_scalar(argument, command)), - ManifestProjectionScalarTransform::FirstPresent => { - arguments.first().is_some_and(|argument| { - preview_key_value_is_provably_non_null_scalar(argument, command) - }) - } + ProjectionScalarTransform::FirstPresent => arguments.first().is_some_and(|argument| { + preview_key_value_is_provably_non_null_scalar(argument, command) + }), }, } } fn command_input_field<'a>( - shape: &'a ManifestCommandShape, + shape: &'a ClientCommandShape, path: &[String], -) -> Option<&'a ManifestTypeField> { - let ManifestCommandShape::Object { definition } = shape else { +) -> Option<&'a ClientTypeField> { + let ClientCommandShape::Object { definition } = shape else { return None; }; let mut current = definition; @@ -1440,17 +1517,17 @@ fn command_input_field<'a>( } fn evaluate_fields( - fields: &[ManifestProjectionField], + fields: &[ClientProjectionField], slots: &BTreeMap<&str, Knowledge>, - event: &ManifestProjectionEventRef, + event: &ClientProjectionEventRef, ) -> (Vec, Vec, bool) { let mut set = Vec::new(); let mut unset = Vec::new(); let mut uncertain = false; for field in fields { match &field.assignment { - ManifestProjectionAssignment::Unset => unset.push(field.name.clone()), - ManifestProjectionAssignment::Set { expression } => { + ClientProjectionAssignment::Unset => unset.push(field.name.clone()), + ClientProjectionAssignment::Set { expression } => { match evaluate_expression(expression, slots, event) { Knowledge::Known(value) => set.push(PreviewField { field: field.name.clone(), @@ -1470,33 +1547,33 @@ fn evaluate_fields( (set, unset, uncertain) } -fn source_knowledge(source: &ManifestProjectionPreviewSource) -> Knowledge { +fn source_knowledge(source: &ClientProjectionPreviewSource) -> Knowledge { match source { - ManifestProjectionPreviewSource::Input { path } => { + ClientProjectionPreviewSource::Input { path } => { Knowledge::Known(PreviewExpression::Input { path: path.clone() }) } - ManifestProjectionPreviewSource::GeneratedDefault { path } => { + ClientProjectionPreviewSource::GeneratedDefault { path } => { Knowledge::Known(PreviewExpression::GeneratedDefault { path: path.clone() }) } - ManifestProjectionPreviewSource::TrustedPreset { name, codec } => { + ClientProjectionPreviewSource::TrustedPreset { name, codec } => { Knowledge::Known(PreviewExpression::TrustedPreset { name: name.clone(), codec: codec.clone(), }) } - ManifestProjectionPreviewSource::Constant { value } => { + ClientProjectionPreviewSource::Constant { value } => { Knowledge::Known(PreviewExpression::Constant { value: value.clone(), }) } - ManifestProjectionPreviewSource::Null => Knowledge::Known(PreviewExpression::Null), - ManifestProjectionPreviewSource::Absent => Knowledge::Absent, - ManifestProjectionPreviewSource::Unknown => Knowledge::Unknown, + ClientProjectionPreviewSource::Null => Knowledge::Known(PreviewExpression::Null), + ClientProjectionPreviewSource::Absent => Knowledge::Absent, + ClientProjectionPreviewSource::Unknown => Knowledge::Unknown, } } fn compile_pure_reduces( - extension: &super::super::manifest::ManifestCommandProjection, + extension: &super::super::manifest::CommandProjectionExtension, projection_refs: &BTreeMap<&str, u32>, occurrences: &[PreviewOccurrence], ) -> Result, ClientCompileError> { @@ -1552,7 +1629,7 @@ fn compile_pure_reduces( } fn compile_one_pure_reduce( - reduce: &super::super::manifest::ManifestCommandPureReduce, + reduce: &super::super::manifest::ClientCommandPureReduce, occurrence_ordinal: u32, projection_refs: Vec, ) -> Result { @@ -1606,43 +1683,43 @@ fn compile_one_pure_reduce( } fn evaluate_expression( - expression: &ManifestProjectionExpression, + expression: &ClientProjectionExpression, slots: &BTreeMap<&str, Knowledge>, - event: &ManifestProjectionEventRef, + event: &ClientProjectionEventRef, ) -> Knowledge { match expression { - ManifestProjectionExpression::Slot { slot, .. } => slots + ClientProjectionExpression::Slot { slot, .. } => slots .get(slot.as_str()) .cloned() .unwrap_or(Knowledge::Denied), - ManifestProjectionExpression::Envelope { field } => { + ClientProjectionExpression::Envelope { field } => { let value = match field { - ManifestProjectionEnvelopeField::OccurrenceVersion => { - ManifestProjectionValue::U64("1".into()) + ClientProjectionEnvelopeField::OccurrenceVersion => { + ClientProjectionValue::U64("1".into()) } - ManifestProjectionEnvelopeField::EventName => { - ManifestProjectionValue::String(event.name.clone()) + ClientProjectionEnvelopeField::EventName => { + ClientProjectionValue::String(event.name.clone()) } - ManifestProjectionEnvelopeField::EventVersion => { - ManifestProjectionValue::U64(event.version.to_string()) + ClientProjectionEnvelopeField::EventVersion => { + ClientProjectionValue::U64(event.version.to_string()) } }; Knowledge::Known(PreviewExpression::Constant { value }) } - ManifestProjectionExpression::Constant { value } => { + ClientProjectionExpression::Constant { value } => { Knowledge::Known(PreviewExpression::Constant { value: value.clone(), }) } - ManifestProjectionExpression::Enum { enum_type, variant } => { + ClientProjectionExpression::Enum { enum_type, variant } => { Knowledge::Known(PreviewExpression::Constant { - value: ManifestProjectionValue::Enum { + value: ClientProjectionValue::Enum { enum_type: enum_type.clone(), variant: variant.clone(), }, }) } - ManifestProjectionExpression::List { values } => { + ClientProjectionExpression::List { values } => { let mut resolved = Vec::with_capacity(values.len()); for value in values { match evaluate_expression(value, slots, event) { @@ -1652,7 +1729,7 @@ fn evaluate_expression( } Knowledge::Known(PreviewExpression::List { values: resolved }) } - ManifestProjectionExpression::Object { fields } => { + ClientProjectionExpression::Object { fields } => { let mut resolved = Vec::with_capacity(fields.len()); for field in fields { match evaluate_expression(&field.value, slots, event) { @@ -1669,7 +1746,7 @@ fn evaluate_expression( } Knowledge::Known(PreviewExpression::Object { fields: resolved }) } - ManifestProjectionExpression::Transform { + ClientProjectionExpression::Transform { transform, arguments, } => { @@ -1677,11 +1754,8 @@ fn evaluate_expression( for argument in arguments { match evaluate_expression(argument, slots, event) { Knowledge::Known(value) => resolved.push(value), - Knowledge::Absent - if *transform == ManifestProjectionScalarTransform::FirstPresent => {} - Knowledge::Unset - if *transform == ManifestProjectionScalarTransform::FirstPresent => - { + Knowledge::Absent if *transform == ProjectionScalarTransform::FirstPresent => {} + Knowledge::Unset if *transform == ProjectionScalarTransform::FirstPresent => { return Knowledge::Unknown; } other => return other, @@ -1957,33 +2031,87 @@ fn model_recovery( mod tests { use super::*; - fn event() -> ManifestProjectionEventRef { - ManifestProjectionEventRef { + #[test] + fn emitted_mutation_presets_include_nested_values_keys_and_partitions_only() { + let preset = |name: &str| PreviewExpression::TrustedPreset { + name: name.into(), + codec: "string".into(), + }; + let scope = PreviewScope { + model: "Todo".into(), + partition: PreviewPartition::Expression { + expression: preset("tenant"), + requires: PreviewPartitionRequirement::CurrentCachePartition, + }, + key: vec![PreviewKeyField { + ordinal: 0, + field: "id".into(), + value: preset("actor"), + }], + }; + let mutation = PreviewMutation::Upsert { + scope: scope.clone(), + fields: vec![PreviewField { + field: "title".into(), + value: PreviewExpression::Object { + fields: vec![PreviewObjectField { + name: "nested".into(), + value: PreviewExpression::List { + values: vec![ + preset("label"), + preset("actor"), + PreviewExpression::Constant { + value: ClientProjectionValue::String("trusted_preset".into()), + }, + ], + }, + }], + }, + }], + replace: vec![], + }; + let mut names = BTreeSet::new(); + mutation.collect_trusted_presets(&mut names); + assert_eq!(names, ["actor", "label", "tenant"].map(String::from).into()); + names.clear(); + PreviewMutation::Delete { scope }.collect_trusted_presets(&mut names); + assert_eq!(names, ["actor", "tenant"].map(String::from).into()); + names.clear(); + PreviewMutation::InvalidateModel { + model: "Todo".into(), + partition: Some(PreviewPartition::Unit), + } + .collect_trusted_presets(&mut names); + assert!(names.is_empty()); + } + + fn event() -> ClientProjectionEventRef { + ClientProjectionEventRef { id: "event:test:v1".into(), name: "test.changed".into(), version: 1, } } - fn slot() -> ManifestProjectionExpression { - ManifestProjectionExpression::Slot { + fn slot() -> ClientProjectionExpression { + ClientProjectionExpression::Slot { slot: "value".into(), - value_type: ManifestProjectionValueType::String, + value_type: ProjectionValueType::String, } } - fn key_command() -> ManifestCommand { - ManifestCommand { + fn key_command() -> ClientCommand { + ClientCommand { version: 1, name: "test".into(), mutation_field: "test".into(), grants: vec!["user".into()], - input: ManifestCommandShape::Object { - definition: ManifestTypeDef { + input: ClientCommandShape::Object { + definition: ClientTypeDef { name: "TestInput".into(), fields: ["source", "target"] .into_iter() - .map(|name| ManifestTypeField { + .map(|name| ClientTypeField { name: name.into(), type_name: "ID".into(), nullable: false, @@ -1995,47 +2123,45 @@ mod tests { .collect(), }, }, - output: ManifestCommandShape::None, + output: ClientCommandShape::None, operation: "mutation Test { test }".into(), operation_hash: "sha256:0000000000000000000000000000000000000000000000000000000000000000".into(), - extensions: ManifestCommandExtensions { + extensions: ClientCommandExtensionSlots { version: 2, - consistency: ManifestCommandConsistency { + consistency: CommandConsistencyExtension { version: 1, - kind: ManifestConsistencyKind::Eventual, + kind: CommandConsistency::Eventual, }, direct_projection: None, input_defaults: None, - effects: None, - confirmations: None, projection: None, trusted_presets: Vec::new(), }, } } - fn projection_model() -> ManifestModel { - ManifestModel { + fn projection_model() -> ClientModel { + ClientModel { id: "Todo".into(), typename: "Todo".into(), source_table: "todos".into(), dependencies: vec!["todos".into()], - normalization: ManifestNormalization::Normalized { - fields: vec![ManifestKeyField { + normalization: ModelNormalization::Normalized { + fields: vec![ClientKeyField { name: "id".into(), codec: "string".into(), }], encoding: "tuple_v1".into(), }, fields: vec![ - ManifestField { + ClientField { name: "id".into(), scalar: "ID".into(), codec: "string".into(), nullable: false, }, - ManifestField { + ClientField { name: "metadata".into(), scalar: "JSON".into(), codec: "json".into(), @@ -2043,12 +2169,12 @@ mod tests { }, ], relationships: Vec::new(), - filter_input: ManifestFilterInput { + filter_input: ClientFilterInput { type_name: "TodoBoolExp".into(), fields: Vec::new(), relationships: Vec::new(), }, - row_policy: ManifestRowPolicy::Unrestricted, + row_policy: ClientRowPolicy::Unrestricted, record_revisions: false, tombstones: false, } @@ -2085,27 +2211,27 @@ mod tests { } } - fn relationship_operation() -> ManifestProjectionOperation { + fn relationship_operation() -> ClientProjectionOperation { let key = |slot: &str| { - vec![ManifestProjectionKeyField { + vec![ClientProjectionKeyField { ordinal: 0, name: "id".into(), - expression: ManifestProjectionExpression::Slot { + expression: ClientProjectionExpression::Slot { slot: slot.into(), - value_type: ManifestProjectionValueType::String, + value_type: ProjectionValueType::String, }, }] }; - ManifestProjectionOperation { + ClientProjectionOperation { operation: "link-owner".into(), ordinal: 0, - kind: ManifestProjectionMutationKind::Patch, + kind: ClientProjectionMutationKind::Patch, model: "Todo".into(), key: key("source"), fields: Vec::new(), - relationships: vec![ManifestProjectionRelationshipEffect { + relationships: vec![ClientProjectionRelationshipEffect { ordinal: 0, - kind: ManifestProjectionRelationshipEffectKind::Link, + kind: ProjectionRelationshipEffectKind::Link, source_model: "Todo".into(), relationship: "owner".into(), target_model: "User".into(), @@ -2135,8 +2261,8 @@ mod tests { #[test] fn denied_or_cache_unowned_nested_dependencies_never_become_values() { - let expression = ManifestProjectionExpression::Object { - fields: vec![ManifestProjectionObjectField { + let expression = ClientProjectionExpression::Object { + fields: vec![ClientProjectionObjectField { name: "secret".into(), value: slot(), }], @@ -2149,7 +2275,7 @@ mod tests { #[test] fn known_partition_expression_requires_current_cache_proof() { - let expression = ManifestProjectionPartition::Expression { expression: slot() }; + let expression = ClientProjectionPartition::Expression { expression: slot() }; let known = BTreeMap::from([( "value", Knowledge::Known(PreviewExpression::Input { @@ -2169,7 +2295,7 @@ mod tests { #[test] fn uncertain_or_unowned_partition_never_addresses_a_row() { - let expression = ManifestProjectionPartition::Expression { expression: slot() }; + let expression = ClientProjectionPartition::Expression { expression: slot() }; for knowledge in [ Knowledge::Unknown, Knowledge::Absent, @@ -2193,17 +2319,17 @@ mod tests { }), ), ]); - let slot = |name: &str| ManifestProjectionExpression::Slot { + let slot = |name: &str| ClientProjectionExpression::Slot { slot: name.into(), - value_type: ManifestProjectionValueType::String, + value_type: ProjectionValueType::String, }; - let object = ManifestProjectionExpression::Object { + let object = ClientProjectionExpression::Object { fields: vec![ - ManifestProjectionObjectField { + ClientProjectionObjectField { name: "missing".into(), value: slot("absent"), }, - ManifestProjectionObjectField { + ClientProjectionObjectField { name: "present".into(), value: slot("known"), }, @@ -2226,12 +2352,12 @@ mod tests { }), ), ]); - let slot = |name: &str| ManifestProjectionExpression::Slot { + let slot = |name: &str| ClientProjectionExpression::Slot { slot: name.into(), - value_type: ManifestProjectionValueType::String, + value_type: ProjectionValueType::String, }; - let first_present = ManifestProjectionExpression::Transform { - transform: ManifestProjectionScalarTransform::FirstPresent, + let first_present = ClientProjectionExpression::Transform { + transform: ProjectionScalarTransform::FirstPresent, arguments: vec![slot("absent"), slot("known")], }; assert!(matches!( @@ -2239,8 +2365,8 @@ mod tests { Knowledge::Known(PreviewExpression::Transform { arguments, .. }) if arguments.len() == 1 )); - let all_absent = ManifestProjectionExpression::Transform { - transform: ManifestProjectionScalarTransform::FirstPresent, + let all_absent = ClientProjectionExpression::Transform { + transform: ProjectionScalarTransform::FirstPresent, arguments: vec![slot("absent")], }; assert_eq!( @@ -2251,16 +2377,16 @@ mod tests { #[test] fn first_present_fails_closed_instead_of_skipping_an_unset_argument() { - let expression = ManifestProjectionExpression::Transform { - transform: ManifestProjectionScalarTransform::FirstPresent, + let expression = ClientProjectionExpression::Transform { + transform: ProjectionScalarTransform::FirstPresent, arguments: vec![ - ManifestProjectionExpression::Slot { + ClientProjectionExpression::Slot { slot: "unset".into(), - value_type: ManifestProjectionValueType::String, + value_type: ProjectionValueType::String, }, - ManifestProjectionExpression::Slot { + ClientProjectionExpression::Slot { slot: "known".into(), - value_type: ManifestProjectionValueType::String, + value_type: ProjectionValueType::String, }, ], }; @@ -2281,26 +2407,26 @@ mod tests { #[test] fn first_present_unset_lowers_to_record_recovery_without_a_write_or_clear() { - let slot = |name: &str| ManifestProjectionExpression::Slot { + let slot = |name: &str| ClientProjectionExpression::Slot { slot: name.into(), - value_type: ManifestProjectionValueType::String, + value_type: ProjectionValueType::String, }; - let operation = ManifestProjectionOperation { + let operation = ClientProjectionOperation { operation: "upsert-todo".into(), ordinal: 0, - kind: ManifestProjectionMutationKind::Upsert, + kind: ClientProjectionMutationKind::Upsert, model: "Todo".into(), - key: vec![ManifestProjectionKeyField { + key: vec![ClientProjectionKeyField { ordinal: 0, name: "id".into(), expression: slot("source"), }], - fields: vec![ManifestProjectionField { + fields: vec![ClientProjectionField { ordinal: 0, name: "metadata".into(), - assignment: ManifestProjectionAssignment::Set { - expression: ManifestProjectionExpression::Transform { - transform: ManifestProjectionScalarTransform::FirstPresent, + assignment: ClientProjectionAssignment::Set { + expression: ClientProjectionExpression::Transform { + transform: ProjectionScalarTransform::FirstPresent, arguments: vec![slot("unset"), slot("known")], }, }, @@ -2358,28 +2484,28 @@ mod tests { #[test] fn json_input_slots_compile_into_their_exact_optimistic_patch_fields() { - let slot = |name: &str, value_type| ManifestProjectionExpression::Slot { + let slot = |name: &str, value_type| ClientProjectionExpression::Slot { slot: name.into(), value_type, }; - let operation = ManifestProjectionOperation { + let operation = ClientProjectionOperation { operation: "patch-json".into(), ordinal: 0, - kind: ManifestProjectionMutationKind::Patch, + kind: ClientProjectionMutationKind::Patch, model: "Todo".into(), - key: vec![ManifestProjectionKeyField { + key: vec![ClientProjectionKeyField { ordinal: 0, name: "id".into(), - expression: slot("source", ManifestProjectionValueType::String), + expression: slot("source", ProjectionValueType::String), }], fields: ["details", "tags"] .into_iter() .enumerate() - .map(|(ordinal, name)| ManifestProjectionField { + .map(|(ordinal, name)| ClientProjectionField { ordinal: ordinal as u32, name: name.into(), - assignment: ManifestProjectionAssignment::Set { - expression: slot(name, ManifestProjectionValueType::Json), + assignment: ClientProjectionAssignment::Set { + expression: slot(name, ProjectionValueType::Json), }, }) .collect(), @@ -2409,7 +2535,7 @@ mod tests { let mut model = projection_model(); model .fields - .extend(["details", "tags"].into_iter().map(|name| ManifestField { + .extend(["details", "tags"].into_iter().map(|name| ClientField { name: name.into(), scalar: "JSON".into(), codec: "json".into(), @@ -2455,8 +2581,8 @@ mod tests { #[test] fn object_expression_fails_closed_when_a_member_is_unset() { - let expression = ManifestProjectionExpression::Object { - fields: vec![ManifestProjectionObjectField { + let expression = ClientProjectionExpression::Object { + fields: vec![ClientProjectionObjectField { name: "cleared".into(), value: slot(), }], @@ -2470,17 +2596,17 @@ mod tests { #[test] fn unset_object_member_lowers_to_uncertainty_without_a_write_or_clear() { - let expression = ManifestProjectionExpression::Object { - fields: vec![ManifestProjectionObjectField { + let expression = ClientProjectionExpression::Object { + fields: vec![ClientProjectionObjectField { name: "cleared".into(), value: slot(), }], }; let slots = BTreeMap::from([("value", Knowledge::Unset)]); - let fields = vec![ManifestProjectionField { + let fields = vec![ClientProjectionField { ordinal: 0, name: "metadata".into(), - assignment: ManifestProjectionAssignment::Set { expression }, + assignment: ClientProjectionAssignment::Set { expression }, }]; assert_eq!( evaluate_fields(&fields, &slots, &event()), @@ -2492,12 +2618,12 @@ mod tests { fn projection_keys_require_provable_non_null_scalars() { let command = key_command(); for value in [ - ManifestProjectionValue::Boolean(true), - ManifestProjectionValue::I64("-1".into()), - ManifestProjectionValue::U64("1".into()), - ManifestProjectionValue::F64("1.5".into()), - ManifestProjectionValue::String("id".into()), - ManifestProjectionValue::Enum { + ClientProjectionValue::Boolean(true), + ClientProjectionValue::I64("-1".into()), + ClientProjectionValue::U64("1".into()), + ClientProjectionValue::F64("1.5".into()), + ClientProjectionValue::String("id".into()), + ClientProjectionValue::Enum { enum_type: "Status".into(), variant: "OPEN".into(), }, @@ -2508,11 +2634,11 @@ mod tests { )); } for value in [ - ManifestProjectionValue::Null, - ManifestProjectionValue::List(vec![ManifestProjectionValue::String("id".into())]), - ManifestProjectionValue::Object(vec![ManifestProjectionValueField { + ClientProjectionValue::Null, + ClientProjectionValue::List(vec![ClientProjectionValue::String("id".into())]), + ClientProjectionValue::Object(vec![ClientProjectionValueField { name: "id".into(), - value: ManifestProjectionValue::String("id".into()), + value: ClientProjectionValue::String("id".into()), }]), ] { assert!(!preview_key_value_is_provably_non_null_scalar( @@ -2528,7 +2654,7 @@ mod tests { &command, )); let mut nullable = command; - let ManifestCommandShape::Object { definition } = &mut nullable.input else { + let ClientCommandShape::Object { definition } = &mut nullable.input else { unreachable!(); }; definition.fields[0].nullable = true; @@ -2785,8 +2911,8 @@ mod tests { let partition = Some(PreviewPartition::Unit); let slots = BTreeMap::from([("source", known("source")), ("target", known("target"))]); let mut operation = relationship_operation(); - operation.relationships[0].kind = ManifestProjectionRelationshipEffectKind::Invalidate; - operation.invalidations = vec![ManifestProjectionInvalidation::Relationship { + operation.relationships[0].kind = ProjectionRelationshipEffectKind::Invalidate; + operation.invalidations = vec![ClientProjectionInvalidation::Relationship { source_model: "Todo".into(), relationship: "owner".into(), target_model: "User".into(), @@ -2852,9 +2978,9 @@ mod tests { #[test] fn model_invalidation_and_recovery_compile_without_a_record_key() { let mut operation = relationship_operation(); - operation.kind = ManifestProjectionMutationKind::InvalidateModel; + operation.kind = ClientProjectionMutationKind::InvalidateModel; operation.relationships.clear(); - operation.invalidations = vec![ManifestProjectionInvalidation::Model { + operation.invalidations = vec![ClientProjectionInvalidation::Model { model: "Todo".into(), }]; let mut operations = Vec::new(); diff --git a/distributed_cli/src/client_compiler/projection_delta/wire.rs b/distributed_cli/src/client_compiler/projection_delta/wire.rs deleted file mode 100644 index 63830091e..000000000 --- a/distributed_cli/src/client_compiler/projection_delta/wire.rs +++ /dev/null @@ -1,1013 +0,0 @@ -#![cfg_attr( - not(test), - allow( - dead_code, - reason = "compiler-owned mirror of the frozen wire contract; runtime consumption lands in Task 16" - ) -)] - -use std::collections::BTreeSet; - -use base64::engine::general_purpose::URL_SAFE_NO_PAD; -use base64::Engine as _; -use serde::{Deserialize, Serialize}; - -use super::super::manifest::{hash_bytes, validate_projection_epoch}; -use super::super::ClientCompileError; - -pub(crate) const PROJECTION_DELTA_WIRE_VERSION: u16 = 1; -const MAX_ITEMS: usize = 128; -const MAX_VALUE_DEPTH: usize = 64; -const MAX_BODY_BYTES: usize = 1024 * 1024; -const MAX_PARTITION_BYTES: usize = 4 * 1024; -const MAX_RECORD_KEY_BYTES: usize = 4 * 1024; - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ProjectionDeltaWire { - pub(crate) wire_version: u16, - pub(crate) identity: ProjectionDeltaIdentity, - pub(crate) projections: Vec, - pub(crate) occurrences: Vec, - pub(crate) operations: Vec, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub(crate) recoveries: Vec, -} - -impl ProjectionDeltaWire { - pub(crate) fn from_canonical_bytes(bytes: &[u8]) -> Result { - if bytes.len() > MAX_BODY_BYTES { - return Err(invalid(format!( - "ProjectionDelta body exceeds {MAX_BODY_BYTES} bytes" - ))); - } - let decoded: Self = serde_json::from_slice(bytes).map_err(|error| { - invalid(format!("invalid ProjectionDelta wire-v1 payload: {error}")) - })?; - decoded.validate()?; - let canonical = decoded.canonical_bytes()?; - if canonical != bytes { - return Err(invalid( - "ProjectionDelta wire-v1 payload is not canonical JSON", - )); - } - Ok(decoded) - } - - pub(crate) fn canonical_bytes(&self) -> Result, ClientCompileError> { - self.validate()?; - let bytes = serde_json::to_vec(self).map_err(|error| { - invalid(format!("cannot serialize ProjectionDelta wire-v1: {error}")) - })?; - if bytes.len() > MAX_BODY_BYTES { - return Err(invalid(format!( - "ProjectionDelta body exceeds {MAX_BODY_BYTES} bytes" - ))); - } - Ok(bytes) - } - - pub(crate) fn fingerprint(&self) -> Result { - Ok(hash_bytes(&self.canonical_bytes()?)) - } - - fn validate(&self) -> Result<(), ClientCompileError> { - if self.wire_version != PROJECTION_DELTA_WIRE_VERSION { - return Err(invalid("unsupported ProjectionDelta wire version")); - } - self.identity.validate()?; - for (label, len) in [ - ("projections", self.projections.len()), - ("occurrences", self.occurrences.len()), - ("operations", self.operations.len()), - ("recoveries", self.recoveries.len()), - ] { - if len > MAX_ITEMS { - return Err(invalid(format!( - "ProjectionDelta {label} exceeds {MAX_ITEMS} entries" - ))); - } - } - if self.projections.windows(2).any(|pair| pair[0] >= pair[1]) { - return Err(invalid( - "ProjectionDelta projections must be sorted and unique", - )); - } - for projection in &self.projections { - projection.validate()?; - } - let mut occurrence_ids = BTreeSet::new(); - for (index, occurrence) in self.occurrences.iter().enumerate() { - if occurrence.ordinal as usize != index - || occurrence.causation_id != self.identity.command_causation_id - { - return Err(invalid( - "ProjectionDelta occurrences must be dense and causation-bound", - )); - } - nonempty(&occurrence.occurrence_id, "occurrence id")?; - if !occurrence_ids.insert(&occurrence.occurrence_id) { - return Err(invalid("ProjectionDelta occurrence IDs must be unique")); - } - } - if self.projections.is_empty() - && (!self.occurrences.is_empty() - || !self.operations.is_empty() - || !self.recoveries.is_empty()) - { - return Err(invalid( - "empty projection inventory requires an empty authoritative delta", - )); - } - let mut operation_scopes = BTreeSet::new(); - let mut previous_operation = None; - for operation in &self.operations { - operation.validate(self.projections.len(), self.occurrences.len())?; - let scope = operation.scope_key(); - let order = (scope.clone(), operation.occurrence_ordinal); - if previous_operation - .as_ref() - .is_some_and(|previous| previous >= &order) - || !operation_scopes.insert(scope) - { - return Err(invalid( - "ProjectionDelta operations must use canonical unique scope order", - )); - } - previous_operation = Some(order); - } - let mut recovery_targets = BTreeSet::new(); - let mut previous_recovery = None; - for recovery in &self.recoveries { - recovery.validate(self.projections.len(), self.occurrences.len())?; - let target = recovery.target.clone(); - let order = (target.clone(), recovery.occurrence_ordinal); - if previous_recovery - .as_ref() - .is_some_and(|previous| previous >= &order) - || !recovery_targets.insert(target) - { - return Err(invalid( - "ProjectionDelta recoveries must use canonical unique target order", - )); - } - if recovery.condition == RecoveryCondition::IfRecordMissing { - let RecoveryTarget::Record { scope } = &recovery.target else { - return Err(invalid( - "if_record_missing recovery requires a record target", - )); - }; - if !self.operations.iter().any(|operation| { - matches!( - &operation.mutation, - ProjectionMutation::Patch { - scope: patch_scope, - if_present: true, - .. - } if patch_scope == scope - ) - }) { - return Err(invalid( - "if_record_missing recovery requires a same-scope conditional patch", - )); - } - } - previous_recovery = Some(order); - } - Ok(()) - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ProjectionDeltaIdentity { - pub(crate) manifest_version: u32, - pub(crate) client_protocol_version: u32, - pub(crate) surface: ProjectionSurfaceIdentity, - pub(crate) schema_fingerprint: String, - pub(crate) protocol_fingerprint: String, - pub(crate) authorization_generation: String, - pub(crate) cache_scope_token: String, - pub(crate) command_causation_id: String, -} - -impl ProjectionDeltaIdentity { - fn validate(&self) -> Result<(), ClientCompileError> { - if self.manifest_version != 2 || self.client_protocol_version != 1 { - return Err(invalid( - "ProjectionDelta identity requires manifest v2 and client protocol v1", - )); - } - self.surface.validate()?; - nonempty(&self.schema_fingerprint, "schema fingerprint")?; - nonempty(&self.protocol_fingerprint, "protocol fingerprint")?; - nonempty(&self.authorization_generation, "authorization generation")?; - validate_token(&self.cache_scope_token, "cache-scope")?; - nonempty(&self.command_causation_id, "command causation id") - } -} - -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub(crate) enum ProjectionSurfaceIdentity { - Role { name: String }, - Application { - name: String, - eligible_roles: Vec, - schema_roles: Vec, - }, -} - -impl ProjectionSurfaceIdentity { - fn validate(&self) -> Result<(), ClientCompileError> { - match self { - Self::Role { name } => nonempty(name, "role surface"), - Self::Application { - name, - eligible_roles, - schema_roles, - } => { - nonempty(name, "application surface")?; - if eligible_roles.is_empty() { - return Err(invalid( - "ProjectionDelta application eligible roles must be sorted, unique, and non-empty", - )); - } - validate_names(eligible_roles, "application eligible roles")?; - if schema_roles.is_empty() - || !schema_roles - .iter() - .all(|role| eligible_roles.iter().any(|eligible| eligible == role)) - { - return Err(invalid( - "ProjectionDelta application schema roles must be a sorted, unique, non-empty subset of eligible roles", - )); - } - validate_names(schema_roles, "application schema roles") - } - } - } -} - -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ProjectionIdentity { - pub(crate) program_id: String, - pub(crate) binding_id: String, - pub(crate) epoch: String, - pub(crate) program_ir_version: u16, - pub(crate) operation_semantics_version: u16, -} - -impl ProjectionIdentity { - fn validate(&self) -> Result<(), ClientCompileError> { - validate_prefixed_hash(&self.program_id, "pp1:")?; - validate_prefixed_hash(&self.binding_id, "pb1:")?; - validate_projection_epoch(&self.epoch, "ProjectionDelta projection epoch")?; - if self.program_ir_version != 1 || self.operation_semantics_version != 1 { - return Err(invalid( - "ProjectionDelta executable identities require IR/semantics v1", - )); - } - Ok(()) - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ProjectionOccurrence { - pub(crate) causation_id: String, - pub(crate) ordinal: u32, - pub(crate) occurrence_id: String, -} - -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ProjectionScope { - pub(crate) partition: ProjectionPartition, - pub(crate) model: String, - pub(crate) key: Vec, -} - -impl ProjectionScope { - fn validate(&self) -> Result<(), ClientCompileError> { - self.partition.validate()?; - nonempty(&self.model, "projection model")?; - if self.key.is_empty() { - return Err(invalid("ProjectionDelta record key must not be empty")); - } - let mut names = BTreeSet::new(); - for (index, field) in self.key.iter().enumerate() { - if field.ordinal as usize != index || !names.insert(&field.field) { - return Err(invalid( - "ProjectionDelta key ordinals/names must be dense and unique", - )); - } - nonempty(&field.field, "projection key field")?; - field.value.validate(1)?; - if matches!( - field.value, - DeltaValue::Null | DeltaValue::List(_) | DeltaValue::Object(_) - ) { - return Err(invalid( - "ProjectionDelta record key values must be non-null scalars", - )); - } - } - let key_bytes = serde_json::to_vec(&self.key) - .map_err(|error| invalid(format!("cannot serialize ProjectionDelta key: {error}")))?; - if key_bytes.len() > MAX_RECORD_KEY_BYTES { - return Err(invalid(format!( - "ProjectionDelta record key exceeds {MAX_RECORD_KEY_BYTES} bytes" - ))); - } - Ok(()) - } -} - -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub(crate) enum ProjectionPartition { - Unit, - Opaque { token: String }, -} - -impl ProjectionPartition { - fn validate(&self) -> Result<(), ClientCompileError> { - let encoded = serde_json::to_vec(self).map_err(|error| { - invalid(format!( - "cannot serialize ProjectionDelta partition: {error}" - )) - })?; - if encoded.len() > MAX_PARTITION_BYTES { - return Err(invalid(format!( - "ProjectionDelta partition exceeds {MAX_PARTITION_BYTES} bytes" - ))); - } - if let Self::Opaque { token } = self { - nonempty(token, "opaque partition")?; - validate_token(token, "projection-partition")?; - } - Ok(()) - } -} - -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct DeltaKeyField { - pub(crate) ordinal: u32, - pub(crate) field: String, - pub(crate) value: DeltaValue, -} - -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct DeltaField { - pub(crate) field: String, - pub(crate) value: DeltaValue, -} - -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde( - tag = "type", - content = "value", - rename_all = "snake_case", - deny_unknown_fields -)] -pub(crate) enum DeltaValue { - Null, - Boolean(bool), - I64(String), - U64(String), - F64(String), - String(String), - Enum { enum_type: String, variant: String }, - List(Vec), - Object(Vec), -} - -impl DeltaValue { - fn validate(&self, depth: usize) -> Result<(), ClientCompileError> { - if depth > MAX_VALUE_DEPTH { - return Err(invalid("ProjectionDelta value exceeds depth 64")); - } - match self { - Self::Null | Self::Boolean(_) => Ok(()), - Self::I64(value) => canonical_number::(value, "i64"), - Self::U64(value) => canonical_number::(value, "u64"), - Self::F64(value) => { - let parsed = value - .parse::() - .ok() - .filter(|value| value.is_finite()) - .ok_or_else(|| invalid("invalid ProjectionDelta f64"))?; - let canonical = - serde_json::Number::from_f64(if parsed == 0.0 { 0.0 } else { parsed }) - .expect("finite float") - .to_string(); - if canonical != *value { - return Err(invalid("noncanonical ProjectionDelta f64")); - } - Ok(()) - } - Self::String(value) => { - if value.len() > MAX_BODY_BYTES { - return Err(invalid(format!( - "ProjectionDelta string exceeds {MAX_BODY_BYTES} bytes" - ))); - } - Ok(()) - } - Self::Enum { enum_type, variant } => { - nonempty(enum_type, "enum type")?; - nonempty(variant, "enum variant") - } - Self::List(values) => { - for value in values { - value.validate(depth + 1)?; - } - Ok(()) - } - Self::Object(fields) => { - validate_fields(fields)?; - for field in fields { - field.value.validate(depth + 1)?; - } - Ok(()) - } - } - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ProjectionOperation { - pub(crate) occurrence_ordinal: u32, - pub(crate) projection_refs: Vec, - pub(crate) mutation: ProjectionMutation, -} - -impl ProjectionOperation { - fn validate( - &self, - projection_count: usize, - occurrence_count: usize, - ) -> Result<(), ClientCompileError> { - validate_refs(&self.projection_refs, projection_count)?; - if self.occurrence_ordinal as usize >= occurrence_count { - return Err(invalid( - "ProjectionDelta operation references an absent occurrence", - )); - } - self.mutation.validate() - } - - fn scope_key(&self) -> OperationScope { - self.mutation.scope() - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)] -pub(crate) enum ProjectionMutation { - Upsert { - scope: ProjectionScope, - fields: Vec, - replace: Vec, - }, - Patch { - scope: ProjectionScope, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - set: Vec, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - unset: Vec, - if_present: bool, - }, - Delete { - scope: ProjectionScope, - }, - Link { - relationship: String, - source: ProjectionScope, - target: ProjectionScope, - }, - Unlink { - relationship: String, - source: ProjectionScope, - target: ProjectionScope, - }, - InvalidateModel { - #[serde(default, skip_serializing_if = "Option::is_none")] - partition: Option, - model: String, - }, - InvalidateRelationship { - relationship: String, - source: ProjectionScope, - }, -} - -impl ProjectionMutation { - fn validate(&self) -> Result<(), ClientCompileError> { - match self { - Self::Upsert { - scope, - fields, - replace, - } => { - scope.validate()?; - validate_fields(fields)?; - validate_names(replace, "upsert replacement mask")?; - if fields.iter().any(|field| !replace.contains(&field.field)) { - return Err(invalid( - "ProjectionDelta upsert field is outside its replacement mask", - )); - } - } - Self::Patch { - scope, - set, - unset, - if_present, - } => { - scope.validate()?; - validate_fields(set)?; - validate_names(unset, "patch unset fields")?; - if !if_present || (set.is_empty() && unset.is_empty()) { - return Err(invalid( - "ProjectionDelta patch must be conditional and non-empty", - )); - } - if set.iter().any(|field| unset.contains(&field.field)) { - return Err(invalid( - "ProjectionDelta patch cannot set and unset one field", - )); - } - } - Self::Delete { scope } => scope.validate()?, - Self::Link { - relationship, - source, - target, - } - | Self::Unlink { - relationship, - source, - target, - } => { - nonempty(relationship, "relationship")?; - source.validate()?; - target.validate()?; - } - Self::InvalidateModel { partition, model } => { - if let Some(partition) = partition { - partition.validate()?; - } - nonempty(model, "model")?; - } - Self::InvalidateRelationship { - relationship, - source, - } => { - nonempty(relationship, "relationship")?; - source.validate()?; - } - } - Ok(()) - } - - fn scope(&self) -> OperationScope { - match self { - Self::Upsert { scope, .. } | Self::Patch { scope, .. } | Self::Delete { scope } => { - OperationScope::Record(scope.clone()) - } - Self::Link { - relationship, - source, - target, - } - | Self::Unlink { - relationship, - source, - target, - } => OperationScope::Edge { - relationship: relationship.clone(), - source: source.clone(), - target: target.clone(), - }, - Self::InvalidateModel { partition, model } => OperationScope::Model { - partition: partition.clone(), - model: model.clone(), - }, - Self::InvalidateRelationship { - relationship, - source, - } => OperationScope::Relationship { - relationship: relationship.clone(), - source: source.clone(), - }, - } - } -} - -/// Mirrors the declaration order of the authoritative Rust wire type. Derived -/// `Ord` is part of the frozen canonical contract; JSON tag spelling is not. -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] -enum OperationScope { - Record(ProjectionScope), - Edge { - relationship: String, - source: ProjectionScope, - target: ProjectionScope, - }, - Model { - partition: Option, - model: String, - }, - Relationship { - relationship: String, - source: ProjectionScope, - }, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub(crate) struct ProjectionRecovery { - pub(crate) occurrence_ordinal: u32, - pub(crate) projection_refs: Vec, - pub(crate) condition: RecoveryCondition, - pub(crate) target: RecoveryTarget, -} - -impl ProjectionRecovery { - fn validate( - &self, - projection_count: usize, - occurrence_count: usize, - ) -> Result<(), ClientCompileError> { - validate_refs(&self.projection_refs, projection_count)?; - if self.occurrence_ordinal as usize >= occurrence_count { - return Err(invalid( - "ProjectionDelta recovery references an absent occurrence", - )); - } - self.target.validate() - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub(crate) enum RecoveryCondition { - Always, - IfRecordMissing, -} - -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] -pub(crate) enum RecoveryTarget { - Record { - scope: ProjectionScope, - }, - Relationship { - relationship: String, - source: ProjectionScope, - }, - Model { - #[serde(default, skip_serializing_if = "Option::is_none")] - partition: Option, - model: String, - }, -} - -impl RecoveryTarget { - fn validate(&self) -> Result<(), ClientCompileError> { - match self { - Self::Record { scope } => scope.validate(), - Self::Relationship { - relationship, - source, - } => { - nonempty(relationship, "relationship")?; - source.validate() - } - Self::Model { partition, model } => { - if let Some(partition) = partition { - partition.validate()?; - } - nonempty(model, "model") - } - } - } -} - -fn validate_refs(refs: &[u32], count: usize) -> Result<(), ClientCompileError> { - if refs.is_empty() - || refs.windows(2).any(|pair| pair[0] >= pair[1]) - || refs.iter().any(|value| *value as usize >= count) - { - return Err(invalid( - "ProjectionDelta projection refs must be sorted, unique, and in range", - )); - } - Ok(()) -} - -fn validate_fields(fields: &[DeltaField]) -> Result<(), ClientCompileError> { - if fields.windows(2).any(|pair| pair[0].field >= pair[1].field) { - return Err(invalid("ProjectionDelta fields must be sorted and unique")); - } - for field in fields { - nonempty(&field.field, "delta field")?; - field.value.validate(1)?; - } - Ok(()) -} - -fn validate_names(names: &[String], label: &str) -> Result<(), ClientCompileError> { - if names.windows(2).any(|pair| pair[0] >= pair[1]) { - return Err(invalid(format!( - "ProjectionDelta {label} must be sorted and unique" - ))); - } - for name in names { - nonempty(name, label)?; - } - Ok(()) -} - -fn validate_prefixed_hash(value: &str, prefix: &str) -> Result<(), ClientCompileError> { - let Some(hash) = value.strip_prefix(prefix) else { - return Err(invalid("invalid ProjectionDelta opaque identity")); - }; - if hash.len() != 71 - || !hash.starts_with("sha256:") - || !hash[7..] - .bytes() - .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) - { - return Err(invalid("invalid ProjectionDelta opaque identity")); - } - Ok(()) -} - -fn validate_token(value: &str, purpose: &str) -> Result<(), ClientCompileError> { - let mut parts = value.split('.'); - if parts.next() != Some("v1") || parts.next() != Some(purpose) || parts.clone().count() != 1 { - return Err(invalid("invalid ProjectionDelta protocol token")); - } - let encoded = parts - .next() - .ok_or_else(|| invalid("invalid ProjectionDelta protocol token"))?; - let decoded = URL_SAFE_NO_PAD - .decode(encoded) - .map_err(|_| invalid("invalid ProjectionDelta protocol token"))?; - if decoded.len() != 32 || URL_SAFE_NO_PAD.encode(decoded) != encoded { - return Err(invalid("invalid ProjectionDelta protocol token")); - } - Ok(()) -} - -fn canonical_number(value: &str, label: &str) -> Result<(), ClientCompileError> -where - T: std::str::FromStr + ToString, -{ - value - .parse::() - .ok() - .filter(|parsed| parsed.to_string() == value) - .map(|_| ()) - .ok_or_else(|| invalid(format!("invalid or noncanonical ProjectionDelta {label}"))) -} - -fn nonempty(value: &str, label: &str) -> Result<(), ClientCompileError> { - if value.is_empty() || value.len() > 4 * 1024 || value.trim() != value { - return Err(invalid(format!("invalid ProjectionDelta {label}"))); - } - Ok(()) -} - -fn invalid(message: impl Into) -> ClientCompileError { - ClientCompileError::manifest("client.projection_delta.invalid", message) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn vector() -> ProjectionDeltaWire { - serde_json::from_slice( - include_bytes!("../../../../tests/fixtures/projection-delta-v1.json") - .strip_suffix(b"\n") - .unwrap(), - ) - .unwrap() - } - - fn first_record_scope_mut(delta: &mut ProjectionDeltaWire) -> &mut ProjectionScope { - delta - .operations - .iter_mut() - .find_map(|operation| match &mut operation.mutation { - ProjectionMutation::Upsert { scope, .. } - | ProjectionMutation::Patch { scope, .. } - | ProjectionMutation::Delete { scope } => Some(scope), - _ => None, - }) - .unwrap() - } - - #[test] - fn task13_projection_delta_vector_is_byte_exact() { - let file = include_bytes!("../../../../tests/fixtures/projection-delta-v1.json"); - let canonical = file - .strip_suffix(b"\n") - .expect("checked fixture ends in one newline"); - let decoded = ProjectionDeltaWire::from_canonical_bytes(canonical) - .expect("task13 vector must satisfy compiler wire-v1"); - assert_eq!(decoded.canonical_bytes().unwrap(), canonical); - assert_eq!( - decoded.fingerprint().unwrap(), - "sha256:7bdc06e1d3accc4c62132f967df1310d31f2f3b856fa7e97a7c5d0907a4ae17b" - ); - assert_eq!( - hash_bytes(file), - "sha256:6d406bade34c766ed12554222bd2696a532448b46f8dd48bba2e286b82de94d1" - ); - } - - #[test] - fn projection_delta_f64_notation_matches_serde_json_ryu() { - let canonical = |value: f64| { - serde_json::Number::from_f64(value) - .expect("test values are finite") - .to_string() - }; - assert_eq!(canonical(1.0), "1.0"); - assert_eq!(canonical(1.5), "1.5"); - assert_eq!(canonical(1e20), "1e+20"); - assert_eq!(canonical(1e-6), "1e-6"); - assert_eq!(canonical(1e-5), "0.00001"); - assert_eq!(canonical(1e15), "1000000000000000.0"); - assert_eq!(canonical(1e16), "1e+16"); - } - - #[test] - fn projection_delta_wire_rejects_unknown_fields_and_versions() { - let file = include_bytes!("../../../../tests/fixtures/projection-delta-v1.json"); - let canonical = file.strip_suffix(b"\n").unwrap(); - let mut value: serde_json::Value = serde_json::from_slice(canonical).unwrap(); - value["wire_version"] = serde_json::json!(2); - assert!( - ProjectionDeltaWire::from_canonical_bytes(&serde_json::to_vec(&value).unwrap()) - .is_err() - ); - value["wire_version"] = serde_json::json!(1); - value["unexpected"] = serde_json::json!(true); - assert!( - ProjectionDeltaWire::from_canonical_bytes(&serde_json::to_vec(&value).unwrap()) - .is_err() - ); - } - - #[test] - fn application_surface_roles_match_server_identity_validation() { - for roles in [ - Vec::::new(), - vec!["".into()], - vec![" user".into()], - vec!["user".into(), "user".into()], - vec!["user".into(), "admin".into()], - vec!["x".repeat(4 * 1024 + 1)], - ] { - let mut delta = vector(); - delta.identity.surface = ProjectionSurfaceIdentity::Application { - name: "web".into(), - eligible_roles: roles, - schema_roles: Vec::new(), - }; - assert!( - delta.canonical_bytes().is_err(), - "invalid application role inventory must fail closed" - ); - } - - let mut delta = vector(); - delta.identity.surface = ProjectionSurfaceIdentity::Application { - name: "web".into(), - eligible_roles: vec!["admin".into(), "user".into()], - schema_roles: vec!["admin".into(), "user".into()], - }; - assert!(delta.canonical_bytes().is_ok()); - } - - #[test] - fn mixed_operation_and_recovery_kinds_use_frozen_enum_order() { - let canonical = vector(); - assert!(matches!( - canonical.operations[0].mutation, - ProjectionMutation::Upsert { .. } - )); - assert!(matches!( - canonical.operations[3].mutation, - ProjectionMutation::Link { .. } - )); - assert!(matches!( - canonical.operations[6].mutation, - ProjectionMutation::InvalidateModel { .. } - )); - assert!(matches!( - canonical.operations[7].mutation, - ProjectionMutation::InvalidateRelationship { .. } - )); - assert!(matches!( - canonical.recoveries[0].target, - RecoveryTarget::Record { .. } - )); - assert!(matches!( - canonical.recoveries[1].target, - RecoveryTarget::Relationship { .. } - )); - assert!(matches!( - canonical.recoveries[2].target, - RecoveryTarget::Model { .. } - )); - - let mut operation_permutation = canonical.clone(); - operation_permutation.operations.swap(2, 3); - assert!(operation_permutation.validate().is_err()); - - let mut recovery_permutation = canonical; - recovery_permutation.recoveries.swap(0, 1); - assert!(recovery_permutation.validate().is_err()); - } - - #[test] - fn wire_validation_rejects_empty_authority_duplicate_occurrences_and_oversized_body() { - let mut empty_authority = vector(); - empty_authority.projections.clear(); - assert!(empty_authority.validate().is_err()); - - let mut duplicate_occurrence = vector(); - duplicate_occurrence.occurrences[1].occurrence_id = - duplicate_occurrence.occurrences[0].occurrence_id.clone(); - assert!(duplicate_occurrence.validate().is_err()); - - assert!( - ProjectionDeltaWire::from_canonical_bytes(&vec![b' '; MAX_BODY_BYTES + 1]).is_err() - ); - } - - #[test] - fn wire_key_validation_matches_scalar_unique_and_size_rules() { - let mut duplicate_name = vector(); - let scope = first_record_scope_mut(&mut duplicate_name); - scope.key[1].field = scope.key[0].field.clone(); - assert!(duplicate_name.validate().is_err()); - - let mut null_key = vector(); - first_record_scope_mut(&mut null_key).key[0].value = DeltaValue::Null; - assert!(null_key.validate().is_err()); - - let mut composite_key = vector(); - first_record_scope_mut(&mut composite_key).key[0].value = - DeltaValue::String("x".repeat(MAX_RECORD_KEY_BYTES)); - assert!(composite_key.validate().is_err()); - } - - #[test] - fn patch_and_conditional_recovery_are_fail_closed() { - let mut overlap = vector(); - let ProjectionMutation::Patch { set, unset, .. } = &mut overlap.operations[1].mutation - else { - panic!("fixture operation 1 is the conditional patch"); - }; - unset.push(set[0].field.clone()); - unset.sort(); - assert!(overlap.validate().is_err()); - - let mut unpaired = vector(); - unpaired.operations.remove(1); - assert!(unpaired.validate().is_err()); - } - - #[test] - fn empty_masks_are_valid_but_payload_strings_and_epochs_are_bounded() { - let mut delta = vector(); - let ProjectionMutation::Upsert { - fields, replace, .. - } = &mut delta.operations[0].mutation - else { - panic!("fixture operation 0 is an upsert"); - }; - fields.clear(); - replace.clear(); - delta.operations[0].mutation.validate().unwrap(); - - assert!(DeltaValue::String("x".repeat(MAX_BODY_BYTES + 1)) - .validate(1) - .is_err()); - let mut identity = delta.projections[0].clone(); - identity.epoch = "x".repeat(129); - assert!(identity.validate().is_err()); - } -} diff --git a/distributed_cli/src/client_compiler/render/artifact.rs b/distributed_cli/src/client_compiler/render/artifact.rs index a2f56f84b..96f0a5321 100644 --- a/distributed_cli/src/client_compiler/render/artifact.rs +++ b/distributed_cli/src/client_compiler/render/artifact.rs @@ -10,8 +10,8 @@ use super::super::graphql::{ CompiledVariableCodec, }; use super::super::manifest::{ - ClientManifest, ManifestRelationshipKeyMapping, ManifestRelationshipKind, - ManifestRelationshipMaintenance, ManifestRowPolicy, ManifestTrustedPresetDescriptor, + ClientManifest, ClientRelationshipKind, ClientRelationshipMaintenance, ClientRowPolicy, + ClientTrustedPresetDescriptor, RelationshipKeyMapping, }; use super::super::ClientCompileError; @@ -41,10 +41,12 @@ struct ArtifactProtocol<'a> { version: u32, #[serde(rename = "schemaHash")] schema_hash: &'a str, - surface: &'a super::super::manifest::ManifestSurface, + #[serde(rename = "protocolHash")] + protocol_hash: &'a str, + surface: &'a super::super::manifest::ClientSurfaceIdentity, operation: &'a str, #[serde(rename = "trustedPresets")] - trusted_presets: &'a [ManifestTrustedPresetDescriptor], + trusted_presets: &'a [ClientTrustedPresetDescriptor], } #[derive(Serialize)] @@ -111,7 +113,7 @@ struct ArtifactFilter<'a> { fields: Vec>, relationships: Vec>, #[serde(rename = "rowPolicy")] - row_policy: &'a ManifestRowPolicy, + row_policy: &'a ClientRowPolicy, } #[derive(Serialize)] @@ -128,10 +130,10 @@ struct ArtifactRelationship<'a> { field: &'a str, #[serde(rename = "targetModel")] target_model: &'a str, - kind: ManifestRelationshipKind, + kind: ClientRelationshipKind, #[serde(rename = "keyMapping")] key_mapping: ArtifactRelationshipKeyMapping<'a>, - maintenance: ManifestRelationshipMaintenance, + maintenance: ClientRelationshipMaintenance, dependencies: &'a [String], } @@ -256,6 +258,7 @@ pub(super) fn render_operation_artifact_json( protocol: ArtifactProtocol { version: 1, schema_hash: &manifest.schema_fingerprint, + protocol_hash: &manifest.protocol_fingerprint, surface: &manifest.surface, operation: &operation.query_hash, trusted_presets: &manifest.trusted_presets, @@ -368,10 +371,10 @@ fn artifact_relationship(relationship: &CompiledRelationshipPlan) -> ArtifactRel target_model: &relationship.target_model, kind: relationship.kind, key_mapping: match &relationship.key_mapping { - ManifestRelationshipKeyMapping::Direct { local, remote } => { + RelationshipKeyMapping::Direct { local, remote } => { ArtifactRelationshipKeyMapping::Direct { local, remote } } - ManifestRelationshipKeyMapping::Through { + RelationshipKeyMapping::Through { local, remote, table, @@ -384,7 +387,7 @@ fn artifact_relationship(relationship: &CompiledRelationshipPlan) -> ArtifactRel source_foreign_key, target_foreign_key, }, - ManifestRelationshipKeyMapping::ThroughOpaque { + RelationshipKeyMapping::ThroughOpaque { local, remote, dependency, @@ -393,7 +396,7 @@ fn artifact_relationship(relationship: &CompiledRelationshipPlan) -> ArtifactRel remote, dependency, }, - ManifestRelationshipKeyMapping::Embedded => ArtifactRelationshipKeyMapping::Embedded, + RelationshipKeyMapping::Embedded => ArtifactRelationshipKeyMapping::Embedded, }, maintenance: relationship.maintenance, dependencies: &relationship.dependencies, diff --git a/distributed_cli/src/client_compiler/render/commands.rs b/distributed_cli/src/client_compiler/render/commands.rs index 1998b390c..0553613b1 100644 --- a/distributed_cli/src/client_compiler/render/commands.rs +++ b/distributed_cli/src/client_compiler/render/commands.rs @@ -3,9 +3,8 @@ use std::collections::BTreeSet; use serde_json::Value as JsonValue; use super::super::manifest::{ - canonical_json_value, ClientManifest, ManifestCommand, ManifestCommandShape, - ManifestConsistencyKind, ManifestDirectProjection, ManifestEffectExpression, ManifestTypeDef, - ManifestTypeField, + canonical_json_value, ClientCommand, ClientCommandShape, ClientManifest, ClientTypeDef, + ClientTypeField, CommandConsistency, CommandDirectProjectionExtension, EffectExpression, }; use super::super::projection_delta::{compile_command_preview, CompiledCommandProjection}; use super::super::ClientCompileError; @@ -13,6 +12,54 @@ use super::common::quoted_property; const COMMAND_ARTIFACT_VERSION: u32 = 2; +pub(super) fn render_lazy_commands( + manifest: &ClientManifest, +) -> Result { + let catalog = manifest + .commands + .iter() + .map(|command| { + ( + command.name.clone(), + serde_json::json!({ + "operationHash": command.operation_hash, + "hasInput": !matches!(command.input, ClientCommandShape::None), + }), + ) + }) + .collect::>(); + let catalog = serde_json::to_string_pretty(&catalog).map_err(|error| { + ClientCompileError::manifest("client.render.lazy_commands", error.to_string()) + })?; + let pures = if pure_function_inventory(manifest)?.is_empty() { + "import('./commands.js').then(({ COMMANDS }) => ({ entries: COMMANDS }))" + } else { + "Promise.all([import('./commands.js'), import('./pures.js')]).then(([{ COMMANDS }, { PURE_FUNCTIONS }]) => ({ entries: COMMANDS, pureFunctions: PURE_FUNCTIONS }))" + }; + Ok(format!( + r#"/** GENERATED by distributed client. Do not edit. */ + +import {{ createLazyReplicaCommandRuntime }} from '@hops-ops/distributed/replica/lazy'; +import type {{ DistributedReplica, ReplicaCommandTransport, ReplicaLazyCommandRuntime }} from '@hops-ops/distributed/replica'; +import type {{ COMMANDS, GeneratedCommandRuntimeOptions }} from './commands.js'; +import {{ COMMAND_STATUS }} from './protocol.js'; + +const COMMAND_CATALOG = {catalog} as const; + +/** Register authority now; import one shared runtime on preload or first command. */ +export function createLazyCommands( + replica: DistributedReplica, + transport: ReplicaCommandTransport, + options?: GeneratedCommandRuntimeOptions +): ReplicaLazyCommandRuntime {{ + return createLazyReplicaCommandRuntime(replica, transport, + {{ commands: COMMAND_CATALOG, status: COMMAND_STATUS }}, + () => {pures}, options); +}} +"# + )) +} + pub(super) fn render_commands(manifest: &ClientManifest) -> Result { validate_command_namespaces(&manifest.commands)?; let projectors = serde_json::to_string_pretty(&manifest.projectors).map_err(|error| { @@ -155,7 +202,9 @@ fn pure_function_inventory( } /// Generate `pures.ts` mapping pure fn ids to hosts / hand imports. -pub(super) fn render_pures(manifest: &ClientManifest) -> Result, ClientCompileError> { +pub(super) fn render_pures( + manifest: &ClientManifest, +) -> Result, ClientCompileError> { let inventory = pure_function_inventory(manifest)?; if inventory.is_empty() { return Ok(None); @@ -168,9 +217,7 @@ pub(super) fn render_pures(manifest: &ClientManifest) -> Result, .iter() .any(|(_, d)| matches!(d, PureDelivery::WasmPackage { .. })); if needs_wasm { - sections.push( - "import { createWasmJsonPure } from '@hops-ops/distributed/replica';".into(), - ); + sections.push("import { createWasmJsonPure } from '@hops-ops/distributed/replica';".into()); } let mut entries = Vec::new(); let mut ready_calls = Vec::new(); @@ -209,7 +256,7 @@ pub(super) fn render_pures(manifest: &ClientManifest) -> Result, Ok(Some(format!("{}\n", sections.join("\n\n")))) } -fn validate_command_namespaces(commands: &[ManifestCommand]) -> Result<(), ClientCompileError> { +fn validate_command_namespaces(commands: &[ClientCommand]) -> Result<(), ClientCompileError> { const RESERVED_SEGMENTS: [&str; 3] = ["__proto__", "constructor", "prototype"]; let mut paths = Vec::with_capacity(commands.len()); @@ -265,7 +312,7 @@ fn validate_command_namespaces(commands: &[ManifestCommand]) -> Result<(), Clien } fn render_command( - command: &ManifestCommand, + command: &ClientCommand, manifest: &ClientManifest, ) -> Result { // Domain command names deliberately permit dots and other non-GraphQL @@ -302,7 +349,7 @@ fn render_command( ) })?; let prepare = match command.input { - ManifestCommandShape::None => format!( + ClientCommandShape::None => format!( "export function prepareCommand_{}(\n options?: PrepareReplicaCommandOptions\n): ReplicaPreparedCommand<{}, {}> {{\n return prepareReplicaCommand(Command_{}, undefined, options);\n}}", identifier, input_name, output_name, identifier ), @@ -322,20 +369,20 @@ fn render_command( } fn render_command_shape_type( - shape: &ManifestCommandShape, + shape: &ClientCommandShape, input: bool, defaults: &BTreeSet>, ) -> Result { match shape { - ManifestCommandShape::None => Ok("void".into()), - ManifestCommandShape::Object { definition } => { + ClientCommandShape::None => Ok("void".into()), + ClientCommandShape::Object { definition } => { render_command_type_definition(definition, input, defaults, &[], 0) } } } fn render_command_type_definition( - definition: &ManifestTypeDef, + definition: &ClientTypeDef, input: bool, defaults: &BTreeSet>, prefix: &[String], @@ -369,7 +416,7 @@ fn render_command_type_definition( } fn render_command_field_type( - field: &ManifestTypeField, + field: &ClientTypeField, input: bool, defaults: &BTreeSet>, path: &[String], @@ -380,7 +427,15 @@ fn render_command_field_type( } match field.codec.as_deref() { Some("boolean") => Ok("boolean".into()), - Some("float64" | "int32" | "json_number_precision_limited") => Ok("number".into()), + Some( + "float64" + | "int32" + | "json_number_precision_limited" + | "uint8" + | "uint16" + | "uint32" + | "uint64_safe_integer", + ) => Ok("number".into()), Some("string" | "base64" | "string_unvalidated_timestamp") => Ok("string".into()), Some("json") => Ok("ReplicaValue".into()), Some(codec) => Err(ClientCompileError::manifest( @@ -401,7 +456,7 @@ fn render_command_field_type( } fn command_artifact_json( - command: &ManifestCommand, + command: &ClientCommand, manifest: &ClientManifest, ) -> Result { let consistency = &command.extensions.consistency; @@ -470,11 +525,26 @@ fn command_artifact_json( direct_projection_json(direct, manifest)?, ); } - if !command.extensions.trusted_presets.is_empty() { - artifact.insert( - "trustedPresets".into(), - serde_json::json!(command.extensions.trusted_presets), - ); + let mut referenced_presets = projection + .as_ref() + .map(CompiledCommandProjection::trusted_preset_names) + .unwrap_or_default(); + if let Some(EffectExpression::TrustedPreset { name }) = command + .extensions + .direct_projection + .as_ref() + .and_then(|direct| direct.partition.as_ref()) + { + referenced_presets.insert(name.clone()); + } + let trusted_presets = command + .extensions + .trusted_presets + .iter() + .filter(|descriptor| referenced_presets.contains(&descriptor.name)) + .collect::>(); + if !trusted_presets.is_empty() { + artifact.insert("trustedPresets".into(), serde_json::json!(trusted_presets)); } artifact.insert( "revalidation".into(), @@ -483,24 +553,24 @@ fn command_artifact_json( Ok(JsonValue::Object(artifact)) } -fn command_shape_json(shape: &ManifestCommandShape) -> JsonValue { +fn command_shape_json(shape: &ClientCommandShape) -> JsonValue { match shape { - ManifestCommandShape::None => serde_json::json!({"kind": "none"}), - ManifestCommandShape::Object { definition } => serde_json::json!({ + ClientCommandShape::None => serde_json::json!({"kind": "none"}), + ClientCommandShape::Object { definition } => serde_json::json!({ "kind": "object", "definition": command_type_definition_json(definition), }), } } -fn command_type_definition_json(definition: &ManifestTypeDef) -> JsonValue { +fn command_type_definition_json(definition: &ClientTypeDef) -> JsonValue { serde_json::json!({ "name": definition.name, "fields": definition.fields.iter().map(command_type_field_json).collect::>(), }) } -fn command_type_field_json(field: &ManifestTypeField) -> JsonValue { +fn command_type_field_json(field: &ClientTypeField) -> JsonValue { let mut result = serde_json::Map::new(); result.insert("name".into(), serde_json::json!(field.name)); result.insert("typeName".into(), serde_json::json!(field.type_name)); @@ -519,31 +589,31 @@ fn command_type_field_json(field: &ManifestTypeField) -> JsonValue { JsonValue::Object(result) } -fn consistency_label(kind: ManifestConsistencyKind) -> &'static str { +fn consistency_label(kind: CommandConsistency) -> &'static str { match kind { - ManifestConsistencyKind::Succeeded => "succeeded", - ManifestConsistencyKind::Eventual => "eventual", - ManifestConsistencyKind::Atomic => "atomic", + CommandConsistency::Succeeded => "succeeded", + CommandConsistency::Eventual => "eventual", + CommandConsistency::Atomic => "atomic", } } -fn effect_expression_json(expression: &ManifestEffectExpression) -> JsonValue { +fn effect_expression_json(expression: &EffectExpression) -> JsonValue { match expression { - ManifestEffectExpression::Input { path } => { + EffectExpression::Input { path } => { serde_json::json!({"kind": "input", "path": path}) } - ManifestEffectExpression::TrustedPreset { name } => { + EffectExpression::TrustedPreset { name } => { serde_json::json!({"kind": "trusted_preset", "name": name}) } - ManifestEffectExpression::Constant { value } => { + EffectExpression::Constant { value } => { serde_json::json!({"kind": "constant", "value": value}) } - ManifestEffectExpression::Null => serde_json::json!({"kind": "null"}), + EffectExpression::Null => serde_json::json!({"kind": "null"}), } } fn direct_projection_json( - direct: &ManifestDirectProjection, + direct: &CommandDirectProjectionExtension, manifest: &ClientManifest, ) -> Result { let identity = manifest @@ -585,7 +655,7 @@ fn direct_projection_json( } fn command_revalidation_json( - command: &ManifestCommand, + command: &ClientCommand, manifest: &ClientManifest, projection: Option<&CompiledCommandProjection>, ) -> JsonValue { diff --git a/distributed_cli/src/client_compiler/render/leaderboards.rs b/distributed_cli/src/client_compiler/render/leaderboards.rs new file mode 100644 index 000000000..991bc9195 --- /dev/null +++ b/distributed_cli/src/client_compiler/render/leaderboards.rs @@ -0,0 +1,147 @@ +//! `leaderboards.ts`: typed documents for the manifest's leaderboard roots. +//! +//! Leaderboard results are ranked by the server (Redis sorted sets) and are +//! not normalized read-model rows, so they are plain GraphQL operations with +//! exact documents, variable and data types, and an `@live` subscription +//! document where the surface has one. They never enter the replica cache. + +use super::common::json_string; +use crate::client_compiler::manifest::{ + ClientLeaderboard, ClientLeaderboardRoot, ClientManifest, LEADERBOARD_ENTRY_TYPENAME, +}; +use crate::client_compiler::ClientCompileError; + +/// `None` when the manifest has no leaderboards. +pub(super) fn render_leaderboards( + manifest: &ClientManifest, +) -> Result, ClientCompileError> { + if manifest.leaderboards.is_empty() { + return Ok(None); + } + let mut out = vec![ + "/** GENERATED by distributed client. Server-ranked leaderboard queries; not replica-cached. */".to_string(), + format!( + "export interface {LEADERBOARD_ENTRY_TYPENAME} {{\n\ + \t/** Zero-based rank in the board's order. */\n\ + \treadonly rank: number;\n\ + \treadonly member: string;\n\ + \treadonly score: number;\n\ + }}" + ), + ]; + let mut index = Vec::new(); + for leaderboard in &manifest.leaderboards { + for root in &leaderboard.roots { + let (block, export) = render_root(manifest, leaderboard, root)?; + out.push(block); + index.push(format!("\t{}: {export},", json_string(&root.name)?)); + } + } + out.push(format!( + "export const LEADERBOARD_OPERATIONS = {{\n{}\n}} as const;", + index.join("\n") + )); + Ok(Some(format!("{}\n", out.join("\n\n")))) +} + +fn pascal(name: &str) -> String { + let mut chars = name.chars(); + match chars.next() { + Some(first) => first.to_ascii_uppercase().to_string() + chars.as_str(), + None => String::new(), + } +} + +fn render_root( + manifest: &ClientManifest, + leaderboard: &ClientLeaderboard, + root: &ClientLeaderboardRoot, +) -> Result<(String, String), ClientCompileError> { + let operation = pascal(&root.name); + let variables = root + .arguments + .iter() + .map(|argument| { + let ty = if argument.type_name == "Int" { + "number" + } else { + "string" + }; + if argument.nullable { + format!("readonly {}?: {ty} | null;", argument.name) + } else { + format!("readonly {}: {ty};", argument.name) + } + }) + .collect::>(); + let definitions = root + .arguments + .iter() + .map(|argument| { + format!( + "${}: {}{}", + argument.name, + argument.type_name, + if argument.nullable { "" } else { "!" } + ) + }) + .collect::>(); + let (definitions, call) = if root.arguments.is_empty() { + (String::new(), String::new()) + } else { + ( + format!("({})", definitions.join(", ")), + format!( + "({})", + root.arguments + .iter() + .map(|argument| format!("{0}: ${0}", argument.name)) + .collect::>() + .join(", ") + ), + ) + }; + let selection = format!("{}{call} {{ rank member score }}", root.name); + let document = format!("query {operation}{definitions} {{ {selection} }}"); + let live = root + .live + .then(|| format!("subscription {operation}_Live{definitions} {{ {selection} }}")); + let data_type = if root.list { + format!("readonly {LEADERBOARD_ENTRY_TYPENAME}[]") + } else { + format!("{LEADERBOARD_ENTRY_TYPENAME} | null") + }; + let export = format!("{operation}Leaderboard"); + let block = format!( + "export type {operation}Variables = {{{}}};\n\ + export type {operation}Data = {{ readonly {}: {data_type} }};\n\ + export const {export} = {{\n\ + \tleaderboard: {},\n\ + \toperation: {},\n\ + \torder: {},\n\ + \tlimits: {{ defaultFirst: {}, maxFirst: {}, maxRadius: {} }},\n\ + \tdocument: {},\n\ + \tliveDocument: {},\n\ + \tschemaHash: {},\n\ + }} as const;", + if variables.is_empty() { + String::new() + } else { + format!(" {} ", variables.join(" ")) + }, + root.name, + json_string(&leaderboard.name)?, + json_string(&root.operation)?, + json_string(&leaderboard.order)?, + leaderboard.default_first, + leaderboard.max_first, + leaderboard.max_radius, + json_string(&document)?, + match &live { + Some(live) => json_string(live)?, + None => "null".to_string(), + }, + json_string(&manifest.schema_fingerprint)?, + ); + Ok((block, export)) +} diff --git a/distributed_cli/src/client_compiler/render/mod.rs b/distributed_cli/src/client_compiler/render/mod.rs index 598f61b70..bacfa4e9b 100644 --- a/distributed_cli/src/client_compiler/render/mod.rs +++ b/distributed_cli/src/client_compiler/render/mod.rs @@ -1,6 +1,7 @@ mod artifact; mod commands; mod common; +mod leaderboards; mod operation; mod project; mod typescript; diff --git a/distributed_cli/src/client_compiler/render/project.rs b/distributed_cli/src/client_compiler/render/project.rs index 581bb009c..959803097 100644 --- a/distributed_cli/src/client_compiler/render/project.rs +++ b/distributed_cli/src/client_compiler/render/project.rs @@ -4,11 +4,11 @@ use serde::Serialize; use super::super::graphql::CompiledOperation; use super::super::islands::{island_plan, GeneratedIslandInventory, ISLAND_PLAN_VERSION}; -use super::super::manifest::{canonical_json_value, ClientManifest, ManifestSurface}; +use super::super::manifest::{canonical_json_value, ClientManifest, ClientSurfaceIdentity}; use super::super::{ ClientCompileError, GeneratedClientFile, GeneratedClientProject, GeneratedOperationSummary, }; -use super::commands::render_commands; +use super::commands::{render_commands, render_lazy_commands}; use super::common::json_string; use super::operation::render_operation_module; @@ -40,6 +40,12 @@ pub(crate) fn render_project( path: "commands.ts".into(), contents: render_commands(manifest)?, }); + if !manifest.commands.is_empty() { + files.push(GeneratedClientFile { + path: "lazy-commands.ts".into(), + contents: render_lazy_commands(manifest)?, + }); + } let pures = super::commands::render_pures(manifest)?; let has_pures = pures.is_some(); if let Some(pures) = pures { @@ -48,6 +54,14 @@ pub(crate) fn render_project( contents: pures, }); } + let leaderboards = super::leaderboards::render_leaderboards(manifest)?; + let has_leaderboards = leaderboards.is_some(); + if let Some(leaderboards) = leaderboards { + files.push(GeneratedClientFile { + path: "leaderboards.ts".into(), + contents: leaderboards, + }); + } files.push(GeneratedClientFile { path: "protocol.ts".into(), contents: render_protocol(manifest)?, @@ -66,7 +80,7 @@ pub(crate) fn render_project( }); files.push(GeneratedClientFile { path: "index.ts".into(), - contents: render_index(&operations, has_pures), + contents: render_index(&operations, has_pures, has_leaderboards), }); files.push(GeneratedClientFile { path: "manifest.json".into(), @@ -161,7 +175,7 @@ struct CompilerManifest<'a> { distributed_manifest_version: u32, protocol_version: u32, service_id: &'a str, - surface: &'a super::super::manifest::ManifestSurface, + surface: &'a super::super::manifest::ClientSurfaceIdentity, schema_fingerprint: &'a str, protocol_fingerprint: &'a str, scalar_codecs: &'a BTreeMap, @@ -279,7 +293,11 @@ fn render_islands( )) } -fn render_index(operations: &[CompiledOperation], has_pures: bool) -> String { +fn render_index( + operations: &[CompiledOperation], + has_pures: bool, + has_leaderboards: bool, +) -> String { let mut lines = vec![ "/** GENERATED public entrypoint. */".to_string(), "export * from './commands.js';".into(), @@ -289,6 +307,9 @@ fn render_index(operations: &[CompiledOperation], has_pures: bool) -> String { if has_pures { lines.push("export * from './pures.js';".into()); } + if has_leaderboards { + lines.push("export * from './leaderboards.js';".into()); + } for operation in operations { let module = operation .module_path @@ -308,8 +329,8 @@ fn render_sveltekit( // schema fingerprints, and protocol hashes belong to compatibility, not // identity. let (kind, name) = match &manifest.surface { - ManifestSurface::Role { name } => ("role", name), - ManifestSurface::Application { name, .. } => ("application", name), + ClientSurfaceIdentity::Role { name } => ("role", name), + ClientSurfaceIdentity::Application { name, .. } => ("application", name), }; let reload_key = serde_json::to_string(&format!("surface:{kind}:{name}")).map_err(|error| { ClientCompileError::manifest( @@ -345,6 +366,8 @@ fn render_sveltekit( ]); if !manifest.commands.is_empty() { value_exports.insert("createCommands".into()); + value_exports.insert("createLazyCommands".into()); + value_exports.insert("provideDistributedLazy".into()); } for command in &manifest.commands { value_exports.insert(format!("Command_{}", command.mutation_field)); @@ -405,6 +428,8 @@ fn render_sveltekit( "} from './commands.js';", "", "export type { GeneratedCommands } from './commands.js';", + "import { createLazyCommands } from './lazy-commands.js';", + "export { createLazyCommands } from './lazy-commands.js';", ] .join("\n"), ); @@ -483,6 +508,18 @@ fn render_sveltekit( .map(str::to_string), ); sections.push(bindings.join("\n")); + if !manifest.commands.is_empty() { + sections.push(format!(r#"/** Opt-in deferred commands; query, SSR and boundary loading stay unchanged. */ +export function provideDistributedLazy( + options: Omit, 'createCommands' | 'reload'> & {{ reload?: Omit }} +): DistributedSvelteKitClient {{ + return provideDistributedSvelteKitClient(createDistributedSvelteKit({{ + ...options, + createCommands: createLazyCommands, + reload: {{ ...options.reload, key: {reload_key} }} + }})); +}}"#)); + } Ok(format!("{}\n", sections.join("\n\n"))) } diff --git a/distributed_cli/src/client_compiler/runtime_bridge_tests.rs b/distributed_cli/src/client_compiler/runtime_bridge_tests.rs index d6055ec48..c723e579d 100644 --- a/distributed_cli/src/client_compiler/runtime_bridge_tests.rs +++ b/distributed_cli/src/client_compiler/runtime_bridge_tests.rs @@ -1,8 +1,58 @@ use super::graphql::{compile_document, CompiledOperation}; use super::manifest::ClientManifest; use super::render::{render_operation_artifact_json, render_operation_module}; -use super::tests::manifest; -use super::{ClientDocument, ClientSurfaceSelector}; +use super::tests::{manifest, parse_manifest, refresh_schema_fingerprint}; +use super::{ClientDocument, ClientSurfaceIdentity}; +use crate::golden::assert_golden; + +#[test] +fn unique_key_runtime_bridge_artifact_is_byte_exact() { + let mut value = manifest(); + value["models"][0]["fields"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ + "name": "ownerTitle", "scalar": "String", "codec": "string", "nullable": true + })); + value["models"][0]["filter_input"]["fields"] + .as_array_mut() + .unwrap() + .push(serde_json::json!({ + "name": "ownerTitle", "operators": ["_eq"] + })); + for root in value["roots"].as_array_mut().unwrap() { + if let Some(fields) = root + .get_mut("filter") + .and_then(|filter| filter.get_mut("fields")) + .and_then(|fields| fields.as_array_mut()) + { + fields.push(serde_json::json!({"name": "ownerTitle", "operators": ["_eq"]})); + } + if let Some(fields) = root + .get_mut("order") + .and_then(|order| order.get_mut("fields")) + .and_then(|fields| fields.as_array_mut()) + { + fields.push(serde_json::json!("ownerTitle")); + } + } + value["models"][0]["relationships"][0]["key_mapping"] = serde_json::json!({ + "kind": "direct", "local": ["tenantId", "ownerTitle"], "remote": ["tenantId", "title"] + }); + value["models"][0]["relationships"][0]["maintenance"] = serde_json::json!("local"); + refresh_schema_fingerprint(&mut value); + let manifest = parse_manifest(value, &ClientSurfaceIdentity::role("user")).unwrap(); + let document = ClientDocument::new( + "src/routes/unique-key/+page.graphql", + "query UniqueKeyBridge @load @live { todos(limit: 25) { id title owner { id title } } }", + ); + let operation = compile_document(&document, &manifest).unwrap(); + let artifact = format!( + "{}\n", + render_operation_artifact_json(&operation, &manifest).unwrap() + ); + assert_golden("unique-key-bridge-operation.json", &artifact); +} const RUNTIME_BRIDGE_QUERY: &str = r#" query RustRuntimeBridge($id: ID!, $tenantId: ID!) { @@ -14,7 +64,7 @@ const RUNTIME_BRIDGE_QUERY: &str = r#" "#; fn compile_runtime_bridge_operation() -> (ClientManifest, CompiledOperation) { - let manifest = ClientManifest::parse(manifest(), &ClientSurfaceSelector::role("user")) + let manifest = parse_manifest(manifest(), &ClientSurfaceIdentity::role("user")) .expect("runtime bridge manifest"); let document = ClientDocument::new( "src/routes/runtime-bridge/+page.graphql", @@ -34,10 +84,10 @@ fn rust_runtime_bridge_artifact() -> String { #[test] fn rust_emitted_runtime_bridge_artifact_is_byte_exact() { - assert_eq!( - rust_runtime_bridge_artifact(), - include_str!("../../tests/fixtures/runtime-bridge-operation.json"), - "the JavaScript runtime bridge fixture must remain exact Rust compiler output" + // The JavaScript runtime bridge reads this fixture. + assert_golden( + "runtime-bridge-operation.json", + &rust_runtime_bridge_artifact(), ); } @@ -46,11 +96,8 @@ fn scalar_only_operation_module_is_byte_exact_and_needs_no_replica_value_import( let (manifest, operation) = compile_runtime_bridge_operation(); let module = render_operation_module(&operation, &manifest) .expect("render scalar-only operation module"); - assert_eq!( - module, - include_str!("../../tests/fixtures/generated-scalar-operation.ts"), - "the strict TypeScript scalar-only fixture must remain exact Rust compiler output" - ); + // The strict TypeScript consumer check compiles this fixture. + assert_golden("generated-scalar-operation.ts", &module); assert!( module.contains( "import type { ReplicaOperationArtifact } from '@hops-ops/distributed/replica';" diff --git a/distributed_cli/src/client_compiler/tests.rs b/distributed_cli/src/client_compiler/tests.rs index 90d1f0ae0..2feb03cb5 100644 --- a/distributed_cli/src/client_compiler/tests.rs +++ b/distributed_cli/src/client_compiler/tests.rs @@ -1,10 +1,40 @@ use serde_json::{json, Value as JsonValue}; use sha2::{Digest, Sha256}; -use super::manifest::{refresh_schema_fingerprint, ClientManifest}; +use super::manifest::ClientManifest; use super::{ - compile_client, ClientCompileInput, ClientDocument, ClientSurfaceSelector, + compile_client, ClientCompileError, ClientCompileInput, ClientDocument, ClientSurfaceIdentity, + DistributedClientManifest, GeneratedClientProject, }; +use crate::golden::assert_golden; + +/// Compile a test input built from manifest JSON; a manifest that does not +/// decode is the same `client.manifest.invalid` the CLI reports. +fn compile( + input: Result, +) -> Result { + input.and_then(compile_client) +} + +pub(super) fn parse_manifest( + value: JsonValue, + selector: &ClientSurfaceIdentity, +) -> Result { + let input = ClientCompileInput::from_manifest_json(value, selector.clone(), Vec::new())?; + ClientManifest::parse(input.manifest, &input.selector) +} + +/// Re-stamp an edited manifest with the fingerprint of its content. A value +/// that no longer decodes has none, and is left for the compiler to reject. +pub(super) fn refresh_schema_fingerprint(value: &mut JsonValue) { + if let Ok(manifest) = serde_json::from_value::(value.clone()) { + value["schema_fingerprint"] = JsonValue::String( + manifest + .computed_schema_fingerprint() + .expect("test manifest must be serializable"), + ); + } +} fn fingerprint(label: &str) -> String { let digest = Sha256::digest(label.as_bytes()); @@ -268,23 +298,13 @@ pub(super) fn manifest() -> JsonValue { "service_id": "todos-service", "surface": {"kind": "role", "name": "user"}, "schema_fingerprint": fingerprint("schema"), - "protocol_fingerprint": "sha256:00fb342f3acb4dc1c1716a43cc3001c748d5f6c500ff831690d820e9e43e2782", + "protocol_fingerprint": "sha256:0dfa8a3f49e17d8d99c5c095c1ed14f528cae3e55fbc2f2b852975a50936ec5b", "execution": { "max_depth": 8, - "max_complexity": 500, + "max_fields": 500, + "max_rows": 200000, "max_bool_width": 256, - "max_in_list": 1000, - "complexity": { - "version": 1, - "scalar": 1, - "belongs_to": 2, - "has_many": 10, - "m2m": 12, - "aggregate": 8, - "list_root": 3, - "by_pk": 1, - "list_fanout": 5 - } + "max_in_list": 1000 }, "capabilities": { "live_queries": true, @@ -611,8 +631,7 @@ fn projected_manifest() -> JsonValue { "name": "todos", "facts": [], "models": ["Todo"], - "dependencies": ["todo_rows"], - "causal_confirmation": false + "dependencies": ["todo_rows"] }]); value["protocol_operations"] = json!({ "version": 1, @@ -760,6 +779,279 @@ fn generated_command_types_manifest() -> JsonValue { value } +fn retained_projection_catalog(arm_count: usize) -> JsonValue { + let mut value = generated_command_types_manifest(); + let arms = value["projection_programs"][0]["arms"] + .as_array_mut() + .unwrap(); + let template = arms[0].clone(); + for index in 1..arm_count { + let mut arm = template.clone(); + arm["arm"] = json!(format!("retained-{index:03}")); + arm["event"] = json!({ + "id": format!("event:todo.retained:v{index:03}"), + "name": "todo.retained", + "version": index + }); + arm["operations"][0]["operation"] = json!(format!("retained-upsert-{index:03}")); + arms.push(arm); + } + refresh_schema_fingerprint(&mut value); + value +} + +#[test] +fn retained_projection_catalog_compiles_134_and_256_arms_with_one_selected_capability() { + let selected_preview = |manifest: &ClientManifest| { + let command = manifest + .commands + .iter() + .find(|command| command.extensions.projection.is_some()) + .unwrap(); + serde_json::to_value( + super::projection_delta::compile_command_preview(command, manifest) + .unwrap() + .unwrap(), + ) + .unwrap() + }; + let baseline = parse_manifest( + generated_command_types_manifest(), + &ClientSurfaceIdentity::role("user"), + ) + .unwrap(); + let expected = selected_preview(&baseline); + assert_eq!( + expected["capabilities"]["arms"].as_array().unwrap().len(), + 1 + ); + for count in [128, 134, 256] { + let value = retained_projection_catalog(count); + let manifest = parse_manifest(value.clone(), &ClientSurfaceIdentity::role("user")) + .unwrap_or_else(|error| panic!("{count} retained arms: {error}")); + assert_eq!(manifest.projection_programs[0].arms.len(), count); + assert_eq!(selected_preview(&manifest), expected); + compile(ClientCompileInput::from_manifest_json( + value, + ClientSurfaceIdentity::role("user"), + vec![ClientDocument::new( + "src/routes/todos/+page.graphql", + "query Todo { todo(id: \"1\", tenantId: \"tenant\") { id tenantId } }", + )], + )) + .unwrap_or_else(|error| panic!("compile {count} retained arms: {error}")); + } +} + +#[test] +fn retained_projection_catalog_rejects_257_arms_and_preserves_nested_limits() { + let error = parse_manifest( + retained_projection_catalog(257), + &ClientSurfaceIdentity::role("user"), + ) + .unwrap_err(); + assert_eq!(error.code, "client.manifest.projection_program_arms"); + for (mutation, expected) in [ + (0, "client.manifest.projection_arm_id"), + (1, "client.manifest.projection_arm_order"), + (2, "client.manifest.projection_operation_id"), + (3, "client.manifest.projection_operations"), + // Repeated program arms never decode into a projection extension. + (4, "client.manifest.invalid"), + ] { + let mut value = retained_projection_catalog(134); + let arms = value["projection_programs"][0]["arms"] + .as_array_mut() + .unwrap(); + match mutation { + 0 => arms[1]["arm"] = arms[0]["arm"].clone(), + 1 => arms.swap(0, 1), + 2 => { + arms[1]["operations"][0]["operation"] = + arms[0]["operations"][0]["operation"].clone() + } + 3 => arms[1]["operations"] = json!(vec![arms[1]["operations"][0].clone(); 129]), + 4 => { + let projection = &mut value["commands"][0]["extensions"]["projection"]; + projection["program_arms"] = + json!(vec![projection["program_arms"][0].clone(); 129]); + } + _ => unreachable!(), + } + refresh_schema_fingerprint(&mut value); + let error = parse_manifest(value, &ClientSurfaceIdentity::role("user")).unwrap_err(); + assert_eq!(error.code, expected, "mutation {mutation}"); + } +} + +fn key_only_projection_manifest(composite: bool) -> JsonValue { + let mut value = generated_command_types_manifest(); + value["capabilities"]["live_queries"] = json!(false); + value["capabilities"]["live_resume"] = json!(false); + value["commands"][0]["extensions"]["consistency"]["kind"] = json!("eventual"); + value["commands"][0]["extensions"] + .as_object_mut() + .unwrap() + .remove("direct_projection"); + value["commands"][0]["output"]["definition"]["name"] = json!("ProjectTodoPayload"); + let key_names = if composite { + vec!["tenantId", "id"] + } else { + vec!["id"] + }; + value["models"][0]["fields"] + .as_array_mut() + .unwrap() + .retain(|field| key_names.contains(&field["name"].as_str().unwrap())); + value["models"][0]["normalization"]["fields"] + .as_array_mut() + .unwrap() + .retain(|field| key_names.contains(&field["name"].as_str().unwrap())); + value["models"][0]["filter_input"]["fields"] + .as_array_mut() + .unwrap() + .retain(|field| key_names.contains(&field["name"].as_str().unwrap())); + value["roots"] = json!([by_pk_root()]); + value["roots"][0]["arguments"] + .as_array_mut() + .unwrap() + .retain(|field| key_names.contains(&field["name"].as_str().unwrap())); + let arm = &mut value["projection_programs"][0]["arms"][0]; + arm["partition"] = json!({"kind": "unit"}); + arm["operations"][0]["fields"] = json!([]); + let key = arm["operations"][0]["key"].as_array_mut().unwrap(); + key.retain(|field| key_names.contains(&field["name"].as_str().unwrap())); + for (ordinal, field) in key.iter_mut().enumerate() { + field["ordinal"] = json!(ordinal); + } + value["commands"][0]["extensions"]["projection"]["preview_occurrences"][0]["values"] + .as_array_mut() + .unwrap() + .retain(|slot| { + key_names + .iter() + .any(|name| slot["slot"] == format!("state.{name}")) + }); + refresh_schema_fingerprint(&mut value); + value +} + +#[test] +fn key_only_complete_projections_compile_identity_only_upserts() { + for composite in [false, true] { + for kind in [ + "insert", + "upsert", + "recreate", + "insert_related", + "upsert_related", + ] { + let mut value = key_only_projection_manifest(composite); + value["projection_programs"][0]["arms"][0]["operations"][0]["kind"] = json!(kind); + refresh_schema_fingerprint(&mut value); + let manifest = parse_manifest(value.clone(), &ClientSurfaceIdentity::role("user")) + .unwrap_or_else(|error| panic!("{kind}, composite={composite}: {error}")); + let command = manifest + .commands + .iter() + .find(|command| command.extensions.projection.is_some()) + .expect("modeled command"); + let preview = super::projection_delta::compile_command_preview(command, &manifest) + .expect("compile identity-only preview") + .expect("projection preview"); + let preview = serde_json::to_value(preview).unwrap(); + assert_eq!( + preview["preview"]["operations"].as_array().unwrap().len(), + 1 + ); + let mutation = &preview["preview"]["operations"][0]["mutation"]; + assert_eq!(mutation["op"], "upsert"); + assert_eq!(mutation["fields"], json!([])); + assert_eq!(mutation["replace"], json!([])); + assert_eq!( + mutation["scope"]["key"].as_array().unwrap().len(), + if composite { 2 } else { 1 } + ); + assert_eq!(preview["preview"]["recoveries"], json!([])); + let query = if composite { + "query Todo { todo(id: \"1\", tenantId: \"tenant\") { id tenantId } }" + } else { + "query Todo { todo(id: \"1\") { id } }" + }; + let project = compile(ClientCompileInput::from_manifest_json( + value, + ClientSurfaceIdentity::role("user"), + vec![ClientDocument::new("src/routes/todos/+page.graphql", query)], + )) + .expect("generate identity-only client"); + let commands = file(&project, "commands.ts"); + assert!(commands.contains("\"op\": \"upsert\"")); + assert!(commands.contains("\"fields\": []")); + assert!(commands.contains("\"replace\": []")); + } + } +} + +#[test] +fn key_only_projection_exception_preserves_field_mask_validation() { + for kind in [ + "insert", + "upsert", + "recreate", + "insert_related", + "upsert_related", + "patch", + "upsert_patch", + ] { + let mut value = generated_command_types_manifest(); + let operation = &mut value["projection_programs"][0]["arms"][0]["operations"][0]; + operation["kind"] = json!(kind); + operation["fields"] = json!([]); + refresh_schema_fingerprint(&mut value); + let error = parse_manifest(value, &ClientSurfaceIdentity::role("user")) + .expect_err("non-key fields still require a field mask"); + assert_eq!( + error.code, "client.manifest.projection_field_mask", + "{kind}" + ); + } + for kind in ["patch", "upsert_patch"] { + let mut value = key_only_projection_manifest(true); + value["projection_programs"][0]["arms"][0]["operations"][0]["kind"] = json!(kind); + refresh_schema_fingerprint(&mut value); + let error = parse_manifest(value, &ClientSurfaceIdentity::role("user")) + .expect_err("key-only models do not allow empty patches"); + assert_eq!(error.code, "client.manifest.projection_field_mask"); + } + let mut value = key_only_projection_manifest(true); + value["projection_programs"][0]["arms"][0]["operations"][0]["fields"] = json!([{ + "ordinal": 0, "name": "id", "assignment": {"kind": "set", "expression": { + "kind": "slot", "slot": "state.id", "value_type": {"type": "string"} + }} + }]); + refresh_schema_fingerprint(&mut value); + let error = parse_manifest(value, &ClientSurfaceIdentity::role("user")) + .expect_err("identity must remain outside the field mask"); + assert_eq!(error.code, "client.manifest.projection_field_mask"); +} + +#[test] +fn key_only_projection_still_requires_the_exact_identity() { + for key in [ + json!([]), + json!([{"ordinal": 0, "name": "id", "expression": { + "kind": "slot", "slot": "state.id", "value_type": {"type": "string"} + }}]), + ] { + let mut value = key_only_projection_manifest(true); + value["projection_programs"][0]["arms"][0]["operations"][0]["key"] = key; + refresh_schema_fingerprint(&mut value); + let error = parse_manifest(value, &ClientSurfaceIdentity::role("user")) + .expect_err("missing composite identity fields must reject"); + assert_eq!(error.code, "client.manifest.projection_key"); + } +} + fn embedded_model_invalidation_manifest() -> JsonValue { let mut value = generated_command_types_manifest(); let command = &mut value["commands"][0]; @@ -787,7 +1079,7 @@ fn embedded_model_invalidation_manifest() -> JsonValue { #[test] fn embedded_model_invalidation_parses_compiles_and_generates_unkeyed_recovery() { let value = embedded_model_invalidation_manifest(); - let manifest = ClientManifest::parse(value.clone(), &ClientSurfaceSelector::role("user")) + let manifest = parse_manifest(value.clone(), &ClientSurfaceIdentity::role("user")) .expect("embedded model invalidation must be valid client authority"); let command = manifest .commands @@ -813,9 +1105,9 @@ fn embedded_model_invalidation_parses_compiles_and_generates_unkeyed_recovery() json!([{"kind": "model", "model": "Todo"}]) ); - let project = compile_client(ClientCompileInput::new( + let project = compile(ClientCompileInput::from_manifest_json( value, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -851,7 +1143,7 @@ fn embedded_model_rejects_every_identity_dependent_projection_mutation() { operation["key"] = key.clone(); refresh_schema_fingerprint(&mut value); - let error = ClientManifest::parse(value, &ClientSurfaceSelector::role("user")) + let error = parse_manifest(value, &ClientSurfaceIdentity::role("user")) .expect_err("identity-dependent operations must reject embedded models"); assert_eq!(error.code, "client.manifest.projection_model", "{kind}"); } @@ -866,7 +1158,7 @@ fn embedded_model_invalidation_rejects_record_and_relationship_authority() { template["projection_programs"][0]["arms"][0]["operations"][0][member].clone(); refresh_schema_fingerprint(&mut value); - let error = ClientManifest::parse(value, &ClientSurfaceSelector::role("user")) + let error = parse_manifest(value, &ClientSurfaceIdentity::role("user")) .expect_err("embedded model invalidation must remain unkeyed and fieldless"); assert_eq!( error.code, "client.manifest.projection_invalidation", @@ -885,7 +1177,7 @@ fn embedded_model_invalidation_rejects_record_and_relationship_authority() { "target_key": [] }]); refresh_schema_fingerprint(&mut value); - let error = ClientManifest::parse(value, &ClientSurfaceSelector::role("user")) + let error = parse_manifest(value, &ClientSurfaceIdentity::role("user")) .expect_err("embedded model invalidation cannot carry relationship effects"); assert_eq!(error.code, "client.manifest.projection_invalidation"); } @@ -896,7 +1188,7 @@ fn embedded_model_invalidation_requires_canonical_same_model_scope() { value["projection_programs"][0]["arms"][0]["operations"][0]["invalidations"] = json!([]); refresh_schema_fingerprint(&mut value); - let error = ClientManifest::parse(value, &ClientSurfaceSelector::role("user")) + let error = parse_manifest(value, &ClientSurfaceIdentity::role("user")) .expect_err("embedded model invalidation must retain its canonical model scope"); assert_eq!(error.code, "client.manifest.projection_invalidation"); } @@ -912,7 +1204,7 @@ fn embedded_model_invalidation_rejects_relationship_invalidation_scope() { }]); refresh_schema_fingerprint(&mut value); - let error = ClientManifest::parse(value, &ClientSurfaceSelector::role("user")) + let error = parse_manifest(value, &ClientSurfaceIdentity::role("user")) .expect_err("embedded model invalidation cannot authorize relationship invalidation"); assert_eq!(error.code, "client.manifest.projection_invalidation"); } @@ -928,7 +1220,7 @@ fn embedded_model_invalidation_rejects_foreign_existing_model_scope() { json!([{"kind": "model", "model": "Other"}]); refresh_schema_fingerprint(&mut value); - let error = ClientManifest::parse(value, &ClientSurfaceSelector::role("user")) + let error = parse_manifest(value, &ClientSurfaceIdentity::role("user")) .expect_err("embedded model invalidation cannot authorize a foreign model"); assert_eq!(error.code, "client.manifest.projection_invalidation"); } @@ -942,7 +1234,7 @@ fn embedded_model_invalidation_preserves_duplicate_scope_rejection() { json!([invalidation.clone(), invalidation]); refresh_schema_fingerprint(&mut value); - let error = ClientManifest::parse(value, &ClientSurfaceSelector::role("user")) + let error = parse_manifest(value, &ClientSurfaceIdentity::role("user")) .expect_err("duplicate embedded model invalidation scope must remain invalid"); assert_eq!(error.code, "client.manifest.projection_invalidation"); assert!( @@ -957,17 +1249,17 @@ fn rejects_legacy_top_level_json_command_shapes() { let mut value = projected_manifest(); value["commands"][0][slot] = json!({"kind": "json", "codec": "json"}); - let error = ClientManifest::parse(value, &ClientSurfaceSelector::role("user")) + let error = parse_manifest(value, &ClientSurfaceIdentity::role("user")) .expect_err("top-level JSON command shapes were removed in manifest v7"); assert_eq!(error.code, "client.manifest.invalid"); assert!(error.message.contains("unknown variant `json`")); } } -fn input(source: &str) -> ClientCompileInput { - ClientCompileInput::new( +fn input(source: &str) -> Result { + ClientCompileInput::from_manifest_json( manifest(), - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", source, @@ -975,10 +1267,13 @@ fn input(source: &str) -> ClientCompileInput { ) } -fn input_with_manifest(manifest: JsonValue, source: &str) -> ClientCompileInput { - ClientCompileInput::new( +fn input_with_manifest( + manifest: JsonValue, + source: &str, +) -> Result { + ClientCompileInput::from_manifest_json( manifest, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", source, @@ -1015,7 +1310,7 @@ const CUSTOM_SCALAR_QUERY: &str = r#" "#; fn custom_scalar_project() -> super::GeneratedClientProject { - compile_client(input_with_manifest( + compile(input_with_manifest( custom_scalar_manifest(), CUSTOM_SCALAR_QUERY, )) @@ -1084,7 +1379,7 @@ fn selected_relationship_artifact(relationship: JsonValue) -> JsonValue { let mut value = manifest(); value["models"][0]["relationships"][0] = relationship; refresh_schema_fingerprint(&mut value); - let project = compile_client(input_with_manifest( + let project = compile(input_with_manifest( value, "query RelationshipPlan { todos { owner { id } } }", )) @@ -1094,7 +1389,7 @@ fn selected_relationship_artifact(relationship: JsonValue) -> JsonValue { #[test] fn compiles_aliases_composite_wire_identity_live_and_load() { - let project = compile_client(input( + let project = compile(input( r#" query Todos($limit: Int!) @load @live { rows: todos(limit: $limit) { @@ -1127,7 +1422,7 @@ fn compiles_aliases_composite_wire_identity_live_and_load() { #[test] fn operation_artifact_carries_normalized_source_provenance() { - let project = compile_client(input("query SourceLocated { todos { id } }")) + let project = compile(input("query SourceLocated { todos { id } }")) .expect("compile source-located operation"); let artifact = operation_artifact(&project); @@ -1143,9 +1438,9 @@ fn operation_artifact_carries_normalized_source_provenance() { #[test] fn component_load_compiles_to_a_framework_neutral_island_inventory() { - let project = compile_client(ClientCompileInput::new( + let project = compile(ClientCompileInput::from_manifest_json( manifest(), - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/lib/todos/TodoSummary.graphql", "query TodoSummary($limit: Int!) @load @live { todos(limit: $limit) { id } }", @@ -1183,22 +1478,20 @@ fn component_load_compiles_to_a_framework_neutral_island_inventory() { #[test] fn multiple_load_islands_may_share_one_future_boundary() { - let project = compile_client( - ClientCompileInput::new( - manifest(), - ClientSurfaceSelector::role("user"), - vec![ - ClientDocument::new( - "src/lib/todos/TodoCount.graphql", - "query TodoCount @load { todos { id } }", - ), - ClientDocument::new( - "src/lib/todos/TodoTitles.graphql", - "query TodoTitles @load { todos { title } }", - ), - ], - ), - ) + let project = compile(ClientCompileInput::from_manifest_json( + manifest(), + ClientSurfaceIdentity::role("user"), + vec![ + ClientDocument::new( + "src/lib/todos/TodoCount.graphql", + "query TodoCount @load { todos { id } }", + ), + ClientDocument::new( + "src/lib/todos/TodoTitles.graphql", + "query TodoTitles @load { todos { title } }", + ), + ], + )) .expect("route ownership is no longer one-operation-per-route"); assert_eq!(project.islands.len(), 2); @@ -1206,18 +1499,18 @@ fn multiple_load_islands_may_share_one_future_boundary() { } #[test] -fn enforces_the_selected_services_exact_depth_and_complexity_limits() { +fn enforces_the_selected_services_exact_depth_and_row_limits() { let shallow_source = "query ExactDepth { todos { id } }"; let mut exact_depth_manifest = manifest(); exact_depth_manifest["execution"]["max_depth"] = json!(2); refresh_schema_fingerprint(&mut exact_depth_manifest); - compile_client(input_with_manifest(exact_depth_manifest, shallow_source)) + compile(input_with_manifest(exact_depth_manifest, shallow_source)) .expect("root and leaf fields exactly at max_depth must compile"); let mut shallow_rejected_manifest = manifest(); shallow_rejected_manifest["execution"]["max_depth"] = json!(1); refresh_schema_fingerprint(&mut shallow_rejected_manifest); - let error = compile_client(input_with_manifest( + let error = compile(input_with_manifest( shallow_rejected_manifest, shallow_source, )) @@ -1228,7 +1521,7 @@ fn enforces_the_selected_services_exact_depth_and_complexity_limits() { let mut depth_manifest = manifest(); depth_manifest["execution"]["max_depth"] = json!(3); refresh_schema_fingerprint(&mut depth_manifest); - let error = compile_client(input_with_manifest( + let error = compile(input_with_manifest( depth_manifest, "query TooDeep { todos { owner { owner { id } } } }", )) @@ -1239,34 +1532,53 @@ fn enforces_the_selected_services_exact_depth_and_complexity_limits() { let mut exact_deep_manifest = manifest(); exact_deep_manifest["execution"]["max_depth"] = json!(4); refresh_schema_fingerprint(&mut exact_deep_manifest); - compile_client(input_with_manifest( + compile(input_with_manifest( exact_deep_manifest, "query ExactDeep { todos { owner { owner { id } } } }", )) .expect("the exact recursive service depth boundary must compile"); - let source = "query ExactCost { todos { id } }"; + // A literal limit counts as given; nested lists multiply. + let source = "query ExactRows { todos(limit: 40) { id } }"; let mut accepted_manifest = manifest(); - accepted_manifest["execution"]["max_complexity"] = json!(18); + accepted_manifest["execution"]["max_rows"] = json!(40); refresh_schema_fingerprint(&mut accepted_manifest); - compile_client(input_with_manifest(accepted_manifest, source)) - .expect("the exact service complexity boundary must compile"); + compile(input_with_manifest(accepted_manifest, source)) + .expect("the exact service row boundary must compile"); let mut rejected_manifest = manifest(); - rejected_manifest["execution"]["max_complexity"] = json!(17); + rejected_manifest["execution"]["max_rows"] = json!(39); refresh_schema_fingerprint(&mut rejected_manifest); - let error = compile_client(input_with_manifest(rejected_manifest, source)) - .expect_err("complexity must fail at build time"); - assert_eq!(error.code, "client.operation.complexity_limit"); - assert!( - error.message.contains("operation complexity 18"), - "{error:?}" - ); + let error = compile(input_with_manifest(rejected_manifest, source)) + .expect_err("rows over budget must fail at build time"); + assert_eq!(error.code, "client.operation.row_limit"); + assert!(error.message.contains("may return 40 rows"), "{error:?}"); + + // An absent limit counts as the field's default (25); a literal above + // `max_limit` (100) counts as the cap. + let mut default_manifest = manifest(); + default_manifest["execution"]["max_rows"] = json!(24); + refresh_schema_fingerprint(&mut default_manifest); + let error = compile(input_with_manifest( + default_manifest, + "query DefaultRows { todos { id } }", + )) + .expect_err("the default page counts"); + assert!(error.message.contains("may return 25 rows"), "{error:?}"); + + let mut capped_manifest = manifest(); + capped_manifest["execution"]["max_rows"] = json!(100); + refresh_schema_fingerprint(&mut capped_manifest); + compile(input_with_manifest( + capped_manifest, + "query CappedRows { todos(limit: 5000) { id } }", + )) + .expect("a limit above max_limit costs max_limit"); } #[test] fn compiles_recursive_normalized_relationships_and_nested_fragments() { - let project = compile_client(input( + let project = compile(input( r#" query NestedOwner { todos { @@ -1466,7 +1778,7 @@ fn relationship_filter_catalog_injects_its_referenced_source_keys() { }); value["models"][0]["relationships"][0] = relationship; refresh_schema_fingerprint(&mut value); - let project = compile_client(input_with_manifest( + let project = compile(input_with_manifest( value, r#"query RelationshipFilter { todos(where: {owner: {title: {_eq: "owned"}}}) { id } @@ -1492,9 +1804,9 @@ fn compiles_nested_list_arguments_coverage_and_variable_usage() { let mut value = manifest(); value["models"][0]["relationships"][0] = normalized_list_relationship(); refresh_schema_fingerprint(&mut value); - let project = compile_client(ClientCompileInput::new( + let project = compile(ClientCompileInput::from_manifest_json( value, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query NestedList($take: Int!) { todos { copies: owner(limit: $take, offset: 0) { headline: title } } }", @@ -1569,9 +1881,9 @@ fn compiles_embedded_objects_without_inventing_wire_identity() { value["roots"][3]["filter"]["relationships"] = json!(["details", "owner"]); refresh_schema_fingerprint(&mut value); - let project = compile_client(ClientCompileInput::new( + let project = compile(ClientCompileInput::from_manifest_json( value, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Embedded { todos { details { note } } }", @@ -1590,7 +1902,7 @@ fn compiles_embedded_objects_without_inventing_wire_identity() { #[test] fn compiles_aggregate_count_and_nodes_with_exact_typenames_and_window() { - let project = compile_client(input( + let project = compile(input( r#" query AggregateTodos($where: todo_bool_exp) { stats: todos_aggregate(where: $where) { ...AggregateParts } @@ -1629,7 +1941,7 @@ fn compiles_aggregate_count_and_nodes_with_exact_typenames_and_window() { #[test] fn compiles_count_only_without_inventing_nodes_or_record_identity() { - let project = compile_client(input( + let project = compile(input( "query CountOnly { summary: todos_aggregate { stats: aggregate { total: count } } }", )) .expect("compile count-only aggregate"); @@ -1673,9 +1985,9 @@ fn compiles_nullable_relationship_aggregate_from_declared_typenames() { }); value["models"][0]["relationships"][0] = relationship; refresh_schema_fingerprint(&mut value); - let project = compile_client(ClientCompileInput::new( + let project = compile(ClientCompileInput::from_manifest_json( value, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query RelationshipStats { todos { metrics: owner_aggregate { stats: aggregate { total: count } items: nodes { headline: title } } } }", @@ -1697,7 +2009,7 @@ fn compiles_nullable_relationship_aggregate_from_declared_typenames() { #[test] fn preserves_enum_wire_syntax_and_json_runtime_value() { - let project = compile_client(input( + let project = compile(input( r#" query Ordered { todos(order_by: [{priority: asc}]) { id } @@ -1713,7 +2025,7 @@ fn preserves_enum_wire_syntax_and_json_runtime_value() { #[test] fn emits_executable_filter_order_and_pagination_plans_with_hidden_dependencies() { - let project = compile_client(input( + let project = compile(input( r#" query Planned($where: todo_bool_exp, $order: [todo_order_by!]) { todos(where: $where, order_by: $order, limit: 10) { id } @@ -1778,11 +2090,7 @@ fn generated_variable_codec_types_recursive_inputs_and_custom_scalars() { let project = custom_scalar_project(); let generated = file(&project, &project.operations[0].module_path); - assert_eq!( - generated, - include_str!("../../tests/fixtures/generated-operation.ts"), - "the checked-in TypeScript consumer fixture must remain byte-exact" - ); + assert_golden("generated-operation.ts", generated); assert!(generated.contains("readonly \"id\": string | number;")); assert!(generated.contains("readonly \"big\": number;")); assert!(generated.contains("readonly \"bytes\"?: string | null;")); @@ -1843,7 +2151,7 @@ fn generated_variable_codec_types_recursive_inputs_and_custom_scalars() { #[test] fn generated_query_carries_row_policy_claim_contract_without_a_command_runtime() { - let project = compile_client(input_with_manifest( + let project = compile(input_with_manifest( row_policy_claim_manifest(), "query Todos { todos { id tenantId } }", )) @@ -1887,7 +2195,7 @@ fn model_filter_contract_resolves_belongs_to_and_has_many_cycles() { } } refresh_schema_fingerprint(&mut recursive); - let project = compile_client(input_with_manifest( + let project = compile(input_with_manifest( recursive, "query RecursiveWhere($where: todo_bool_exp) { todos(where: $where) { id } }", )) @@ -1920,7 +2228,7 @@ fn model_filter_contract_resolves_belongs_to_and_has_many_cycles() { #[test] fn literal_index_plans_inject_only_referenced_fields_and_validate_shape() { - let project = compile_client(input( + let project = compile(input( "query LiteralPlan { todos(where: {priority: {_eq: 3}}, order_by: [{priority: desc}]) { id } }", )) .expect("compile literal index plan"); @@ -1932,31 +2240,31 @@ fn literal_index_plans_inject_only_referenced_fields_and_validate_shape() { assert!(generated.contains("\"priority\": {")); assert!(generated.contains("\"_eq\": 3")); - let error = compile_client(input( + let error = compile(input( "query BadFilterField { todos(where: {missing: {_eq: 3}}) { id } }", )) .expect_err("unknown filter field must fail at build time"); assert_eq!(error.code, "client.filter.field_denied_or_unknown"); - let error = compile_client(input( + let error = compile(input( "query BadFilterOperator { todos(where: {priority: {_gt: 3}}) { id } }", )) .expect_err("unselected filter operator must fail at build time"); assert_eq!(error.code, "client.filter.operator_denied_or_unknown"); - let error = compile_client(input( + let error = compile(input( "query BadFilterLiteral { todos(where: {priority: {_eq: \"bad\"}}) { id } }", )) .expect_err("filter literals must match the selected scalar codec"); assert_eq!(error.code, "client.filter.literal_type"); - let error = compile_client(input( + let error = compile(input( "query BadFilterList { todos(where: {priority: {_in: [1, \"bad\"]}}) { id } }", )) .expect_err("every filter list item must match the selected scalar codec"); assert_eq!(error.code, "client.filter.literal_type"); - let error = compile_client(input( + let error = compile(input( "query AmbiguousOrder { todos(order_by: [{priority: asc, id: desc}]) { id } }", )) .expect_err("ambiguous order priority must fail at build time"); @@ -1965,7 +2273,7 @@ fn literal_index_plans_inject_only_referenced_fields_and_validate_shape() { #[test] fn scalar_literals_use_the_same_canonical_domains_as_variables() { - let project = compile_client(input_with_manifest( + let project = compile(input_with_manifest( literal_scalar_manifest(), r#" query LiteralScalarCodecs { @@ -1999,7 +2307,7 @@ fn scalar_literals_use_the_same_canonical_domains_as_variables() { assert!(document.contains("decimal: 0.1")); assert!(!document.contains("0.100000000000000005")); - let rounded_float = compile_client(input_with_manifest( + let rounded_float = compile(input_with_manifest( literal_scalar_manifest(), "query RoundedFloat { todos(where: {ratio: {_eq: 9007199254740993}}) { id } }", )) @@ -2014,7 +2322,7 @@ fn scalar_literals_use_the_same_canonical_domains_as_variables() { .expect("rounded document"); assert!(!rounded_document.contains("9007199254740993")); - let mixed_json = compile_client(input_with_manifest( + let mixed_json = compile(input_with_manifest( custom_scalar_manifest(), "query MixedJson($id: ID!) { todos(where: {id: {_eq: $id}, payload: {_eq: {a: 1}}}) { id } }", )) @@ -2025,7 +2333,7 @@ fn scalar_literals_use_the_same_canonical_domains_as_variables() { 1 ); - let by_pk = compile_client(input( + let by_pk = compile(input( "query LiteralIds { todo(id: -0, tenantId: 1) { id } }", )) .expect("GraphQL integer ID literals coerce to canonical strings"); @@ -2063,21 +2371,21 @@ fn scalar_literals_use_the_same_canonical_domains_as_variables() { "JSON integer whose JavaScript decimal serialization changes", ), ] { - let error = match compile_client(input_with_manifest(literal_scalar_manifest(), source)) { + let error = match compile(input_with_manifest(literal_scalar_manifest(), source)) { Ok(_) => panic!("{label} must fail"), Err(error) => error, }; assert_eq!(error.code, "client.filter.literal_type", "{label}"); } - let error = compile_client(input("query WideLimit { todos(limit: 2147483648) { id } }")) + let error = compile(input("query WideLimit { todos(limit: 2147483648) { id } }")) .expect_err("root Int literals use the same signed 32-bit domain as variables"); assert_eq!(error.code, "client.argument.literal_type"); } #[test] fn canonicalizes_graphql_singletons_at_every_filter_and_order_list_position() { - let project = compile_client(input( + let project = compile(input( r#" query SingletonLists { todos( @@ -2120,7 +2428,7 @@ fn enforces_filter_depth_and_width_limits_after_graphql_singleton_coercion() { let mut depth_manifest = manifest(); depth_manifest["execution"]["max_depth"] = json!(2); refresh_schema_fingerprint(&mut depth_manifest); - compile_client(input_with_manifest( + compile(input_with_manifest( depth_manifest.clone(), r#" query ExactFilterDepth { @@ -2142,7 +2450,7 @@ fn enforces_filter_depth_and_width_limits_after_graphql_singleton_coercion() { "query TooDeepNot { todos(where: {_not: {_not: {_not: null}}}) { id } }", "query TooDeepRelationship { todos(where: {owner: {owner: {owner: null}}}) { id } }", ] { - let error = compile_client(input_with_manifest(depth_manifest.clone(), source)) + let error = compile(input_with_manifest(depth_manifest.clone(), source)) .expect_err("null still enters _not and relationship filter children"); assert_eq!(error.code, "client.filter.depth_limit", "{source}"); } @@ -2151,7 +2459,7 @@ fn enforces_filter_depth_and_width_limits_after_graphql_singleton_coercion() { width_manifest["execution"]["max_bool_width"] = json!(1); width_manifest["execution"]["max_in_list"] = json!(1); refresh_schema_fingerprint(&mut width_manifest); - compile_client(input_with_manifest( + compile(input_with_manifest( width_manifest.clone(), r#" query ExactFilterWidths { @@ -2179,7 +2487,7 @@ fn enforces_filter_depth_and_width_limits_after_graphql_singleton_coercion() { "mixed IN list", ), ] { - let error = compile_client(input_with_manifest(width_manifest.clone(), source)) + let error = compile(input_with_manifest(width_manifest.clone(), source)) .expect_err("filter width above the exact service boundary must fail"); assert_eq!(error.code, "client.filter.width_limit", "{label}"); } @@ -2191,7 +2499,7 @@ fn variable_codec_intersects_filter_depth_and_list_constraints() { value["execution"]["max_bool_width"] = json!(7); value["execution"]["max_in_list"] = json!(11); refresh_schema_fingerprint(&mut value); - let project = compile_client(input_with_manifest( + let project = compile(input_with_manifest( value, r#" query VariableConstraints( @@ -2246,7 +2554,7 @@ fn relationship_selection_and_aggregate_filters_inherit_model_edge_depth() { }); value["models"][0]["relationships"][0] = relationship; refresh_schema_fingerprint(&mut value); - let project = compile_client(input_with_manifest( + let project = compile(input_with_manifest( value, r#" query EdgeFilterDepth( @@ -2274,18 +2582,18 @@ fn relationship_selection_and_aggregate_filters_inherit_model_edge_depth() { #[test] fn variable_nullability_is_compatible_but_never_weaker() { - compile_client(input( + compile(input( "query Strict($limit: Int!) { todos(limit: $limit) { id } }", )) .expect("non-null variable may satisfy nullable argument"); - let error = compile_client(input( + let error = compile(input( "query Weak($tenantId: ID, $id: ID!) { todo(tenantId: $tenantId, id: $id) { title } }", )) .expect_err("nullable variable may not satisfy non-null argument"); assert_eq!(error.code, "client.variable.type_mismatch"); - let error = compile_client(input( + let error = compile(input( "query WeakItem($order: [todo_order_by]) { todos(order_by: $order) { id } }", )) .expect_err("nullable list item may not satisfy non-null item"); @@ -2294,7 +2602,7 @@ fn variable_nullability_is_compatible_but_never_weaker() { #[test] fn compiles_nested_filter_and_order_variables_with_recursive_value_sources() { - let project = compile_client(input( + let project = compile(input( r#" query Nested($priority: Int!, $direction: order_by!) { todos( @@ -2320,19 +2628,19 @@ fn compiles_nested_filter_and_order_variables_with_recursive_value_sources() { assert!(generated.contains("\"kind\": \"enum\"")); assert!(!generated.contains("Readonly>")); - let error = compile_client(input( + let error = compile(input( "query WrongNested($priority: String!) { todos(where: {priority: {_eq: $priority}}) { id } }", )) .expect_err("nested variable type must match its scalar position"); assert_eq!(error.code, "client.variable.type_mismatch"); - let error = compile_client(input( + let error = compile(input( "query MissingNested { todos(where: {priority: {_eq: $missing}}) { id } }", )) .expect_err("nested variable must be defined"); assert_eq!(error.code, "client.variable.undefined"); - let error = compile_client(input( + let error = compile(input( "query WrongListItem($priority: String!) { todos(where: {priority: {_in: [$priority]}}) { id } }", )) .expect_err("nested list-item variables must match the non-null scalar item type"); @@ -2341,7 +2649,7 @@ fn compiles_nested_filter_and_order_variables_with_recursive_value_sources() { #[test] fn compiles_variable_defaults_into_query_types_identity_and_island_plan() { - let project = compile_client(input( + let project = compile(input( "query Defaulted($limit: Int! = 10) @load { todos(limit: $limit) { id } }", )) .expect("defaults are compiler-owned inputs"); @@ -2380,9 +2688,9 @@ fn application_surfaces_are_explicit_and_fingerprint_separate_chunks() { .as_str() .expect("common fingerprint") .to_string(); - let common_project = compile_client(ClientCompileInput::new( + let common_project = compile(ClientCompileInput::from_manifest_json( common.clone(), - ClientSurfaceSelector::application("web-common", ["user"], ["user"]), + ClientSurfaceIdentity::application("web-common", ["user"], ["user"]), vec![document.clone()], )) .expect("compile exact application surface"); @@ -2394,9 +2702,9 @@ fn application_surfaces_are_explicit_and_fingerprint_separate_chunks() { let mut changed_contract = common.clone(); changed_contract["surface"]["eligible_roles"] = json!(["admin", "user"]); refresh_schema_fingerprint(&mut changed_contract); - let changed_project = compile_client(ClientCompileInput::new( + let changed_project = compile(ClientCompileInput::from_manifest_json( changed_contract, - ClientSurfaceSelector::application("web-common", ["admin", "user"], ["user"]), + ClientSurfaceIdentity::application("web-common", ["admin", "user"], ["user"]), vec![document.clone()], )) .expect("compile changed contract for the same application surface"); @@ -2404,9 +2712,9 @@ fn application_surfaces_are_explicit_and_fingerprint_separate_chunks() { file(&changed_project, "sveltekit.ts").contains("key: \"surface:application:web-common\"") ); - let mismatch = compile_client(ClientCompileInput::new( + let mismatch = compile(ClientCompileInput::from_manifest_json( common, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![document.clone()], )) .expect_err("a role selector cannot relabel an application surface"); @@ -2420,9 +2728,9 @@ fn application_surfaces_are_explicit_and_fingerprint_separate_chunks() { "schema_roles": ["admin"], }); refresh_schema_fingerprint(&mut elevated); - let elevated_project = compile_client(ClientCompileInput::new( + let elevated_project = compile(ClientCompileInput::from_manifest_json( elevated, - ClientSurfaceSelector::application("web-admin", ["admin"], ["admin"]), + ClientSurfaceIdentity::application("web-admin", ["admin"], ["admin"]), vec![document], )) .expect("compile separate elevated application surface"); @@ -2434,15 +2742,15 @@ fn application_surfaces_are_explicit_and_fingerprint_separate_chunks() { #[test] fn sveltekit_wrapper_exposes_framework_neutral_islands_without_routes() { - let input = ClientCompileInput::new( + let input = ClientCompileInput::from_manifest_json( manifest(), - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/features/todos.graphql", "query Todos @load { todos { id } }", )], ); - let project = compile_client(input).expect("adapter-owned island placement"); + let project = compile(input).expect("adapter-owned island placement"); assert!(project.islands[0].directives.load); assert!(project.files.iter().all(|file| file.path != "routes.ts")); let sveltekit = file(&project, "sveltekit.ts"); @@ -2466,7 +2774,7 @@ fn sveltekit_wrapper_exposes_framework_neutral_islands_without_routes() { #[test] fn sveltekit_wrapper_names_cannot_shadow_generated_runtime_exports() { - let error = compile_client(input( + let error = compile(input( r#" query useCommands { todos { id } @@ -2481,7 +2789,7 @@ fn sveltekit_wrapper_names_cannot_shadow_generated_runtime_exports() { #[test] fn sveltekit_wrapper_names_fail_closed_on_typescript_keywords() { for name in ["default", "await"] { - let error = compile_client(input(&format!("query {name} {{ todos {{ id }} }}"))) + let error = compile(input(&format!("query {name} {{ todos {{ id }} }}"))) .expect_err("TypeScript keyword must not become a generated value binding"); assert_eq!(error.code, "client.operation.sveltekit_identifier"); assert!(error.message.contains(name), "{error}"); @@ -2490,14 +2798,14 @@ fn sveltekit_wrapper_names_fail_closed_on_typescript_keywords() { assert_eq!(source.line, 1); } - let project = compile_client(input("query awaited { todos { id } }")) + let project = compile(input("query awaited { todos { id } }")) .expect("near-keyword operation remains valid"); assert!(file(&project, "sveltekit.ts").contains("export const awaited =")); } #[test] fn expands_root_named_and_inline_fragments_into_canonical_full_text() { - let project = compile_client(input( + let project = compile(input( r#" query Fragmented { ...Root @@ -2522,7 +2830,7 @@ fn expands_root_named_and_inline_fragments_into_canonical_full_text() { #[test] fn merges_identical_root_objects_and_preserves_first_encounter_order() { - let project = compile_client(input( + let project = compile(input( r#" query Merged { ...First @@ -2572,13 +2880,13 @@ fn rejects_fragment_graph_errors_deterministically() { ), ]; for (source, code, message) in cases { - let error = compile_client(input(source)).expect_err(source); + let error = compile(input(source)).expect_err(source); assert_eq!(error.code, code, "{source}: {error}"); assert!(error.message.contains(message), "{source}: {error}"); assert!(error.source.is_some()); } - let error = compile_client(input( + let error = compile(input( r#" query Unused { todos { id } } fragment ZedFirst on todo { id } @@ -2592,7 +2900,7 @@ fn rejects_fragment_graph_errors_deterministically() { #[test] fn prevalidates_fragment_graph_through_nested_fields_before_lowering() { - let error = compile_client(input( + let error = compile(input( r#" query NestedCycle { todos { ...Recursive } @@ -2607,7 +2915,7 @@ fn prevalidates_fragment_graph_through_nested_fields_before_lowering() { assert!(error.message.contains("Recursive -> Recursive")); assert_eq!(error.source.as_ref().map(|source| source.line), Some(6)); - let error = compile_client(input( + let error = compile(input( "query NestedMissing { todos { owner { ...Missing } } }", )) .expect_err("undefined nested fragments precede unsupported relationship lowering"); @@ -2618,11 +2926,11 @@ fn prevalidates_fragment_graph_through_nested_fields_before_lowering() { #[test] fn fragment_definition_order_does_not_change_generated_output() { let operation = "query Stable { todos { ...First ...Second } }\n"; - let left = compile_client(input(&format!( + let left = compile(input(&format!( "{operation}fragment First on todo {{ id }}\nfragment Second on todo {{ title }}\n" ))) .expect("first definition order"); - let right = compile_client(input(&format!( + let right = compile(input(&format!( "{operation}fragment Second on todo {{ title }}\nfragment First on todo {{ id }}\n" ))) .expect("second definition order"); @@ -2647,7 +2955,7 @@ fn rejects_directives_on_every_fragment_surface() { ), ]; for (source, code) in cases { - let error = compile_client(input(source)).expect_err(source); + let error = compile(input(source)).expect_err(source); assert_eq!(error.code, code, "{source}: {error}"); } } @@ -2662,7 +2970,7 @@ fn rejects_response_key_conflicts_at_the_later_selection() { } } "#; - let error = compile_client(input(source)).expect_err("field-name conflict"); + let error = compile(input(source)).expect_err("field-name conflict"); assert_eq!(error.code, "client.selection.conflict"); assert_eq!(error.source.as_ref().map(|source| source.line), Some(5)); assert!(error.message.contains("first selection at 4:")); @@ -2671,7 +2979,7 @@ fn rejects_response_key_conflicts_at_the_later_selection() { "query ShapeConflict { todos { same: id same: id { value } } }", "query ArgumentConflict { rows: todos(limit: 1) { id } rows: todos(limit: 2) { id } }", ] { - let error = compile_client(input(source)).expect_err(source); + let error = compile(input(source)).expect_err(source); assert_eq!(error.code, "client.selection.conflict", "{source}: {error}"); } } @@ -2686,13 +2994,13 @@ fn fragment_expansion_is_bounded_by_depth_and_total_work() { )); } deep.push_str("fragment F65 on todo { id }\n"); - let error = compile_client(input(&deep)).expect_err("depth bound"); + let error = compile(input(&deep)).expect_err("depth bound"); assert_eq!(error.code, "client.selection.depth"); let spreads = "...Fields ".repeat(5_000); let expanded = format!("query Expanded {{ todos {{ {spreads} }} }} fragment Fields on todo {{ id }}"); - let error = compile_client(input(&expanded)).expect_err("expansion work bound"); + let error = compile(input(&expanded)).expect_err("expansion work bound"); assert_eq!(error.code, "client.selection.expansion_bound"); } @@ -2709,7 +3017,7 @@ fn rejects_conditional_and_multi_root() { ), ]; for (source, code) in cases { - let error = compile_client(input(source)).expect_err(source); + let error = compile(input(source)).expect_err(source); assert_eq!(error.code, code, "{source}: {error}"); assert!(error.source.is_some()); } @@ -2740,7 +3048,7 @@ fn recursive_selection_shapes_fail_closed() { ), ]; for (source, code) in cases { - let error = compile_client(input(source)).expect_err(source); + let error = compile(input(source)).expect_err(source); assert_eq!(error.code, code, "{source}: {error}"); assert!(error.source.is_some()); } @@ -2753,9 +3061,9 @@ fn rejects_unknown_scalar_and_codec_instead_of_emitting_unknown() { .as_array_mut() .expect("array") .push(json!({"scalar": "Money", "codec": "money"})); - let error = compile_client(ClientCompileInput::new( + let error = compile(ClientCompileInput::from_manifest_json( invalid, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -2769,9 +3077,9 @@ fn rejects_unknown_scalar_and_codec_instead_of_emitting_unknown() { fn rejects_well_formed_but_incompatible_protocol_fingerprint() { let mut invalid = manifest(); invalid["protocol_fingerprint"] = json!(fingerprint("different protocol")); - let error = compile_client(ClientCompileInput::new( + let error = compile(ClientCompileInput::from_manifest_json( invalid, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -2793,9 +3101,9 @@ fn live_companion_fails_closed_on_dependency_or_pagination_drift() { .expect("subscription"); subscription["pagination"]["default_limit"] = json!(24); refresh_schema_fingerprint(&mut invalid); - let error = compile_client(ClientCompileInput::new( + let error = compile(ClientCompileInput::from_manifest_json( invalid, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos @live { todos { id } }", @@ -2935,8 +3243,7 @@ fn command_protocol_and_extensions_are_preserved_exactly() { "name": "todos", "facts": ["TodoCreated"], "models": ["Todo"], - "dependencies": ["todo_rows"], - "causal_confirmation": true + "dependencies": ["todo_rows"] }]); value["protocol_operations"] = json!({ "version": 1, @@ -3110,10 +3417,118 @@ fn command_protocol_and_extensions_are_preserved_exactly() { ["values"][2]["source"] = json!({"kind": "trusted_preset", "name": "priority", "codec": "int32"}); refresh_schema_fingerprint(&mut preset_i64_value); + // An unknown record identity drops the mutation, including its preset + // expression. The generated inventory must follow the compiled result, + // while the surface retains the complete trusted context contract. + let mut recovery_preset = preset_i64_value.clone(); + recovery_preset["commands"][0]["extensions"]["projection"]["preview_occurrences"][0] + ["values"][1]["source"] = json!({"kind": "unknown"}); + refresh_schema_fingerprint(&mut recovery_preset); + for (fixture, retained) in [(preset_i64_value.clone(), true), (recovery_preset, false)] { + let compiled = compile(input_with_manifest(fixture, "query Todos { todos { id } }")) + .expect("compile preset inventory after preview lowering"); + let source = file(&compiled, "commands.ts"); + let declaration = source + .split("export const Command_createTodo:") + .nth(1) + .unwrap(); + let body = declaration + .split_once(" = ") + .unwrap() + .1 + .split_once("\n};") + .unwrap() + .0; + let artifact: JsonValue = serde_json::from_str(&format!("{body}\n}}")).unwrap(); + assert_eq!( + artifact["protocol"]["trustedPresets"], + json!([{"name": "priority", "codec": "int32"}]) + ); + if retained { + assert_eq!( + artifact["trustedPresets"], + json!([{"name": "priority", "codec": "int32"}]) + ); + assert!(!artifact["projection"]["preview"]["operations"] + .as_array() + .unwrap() + .is_empty()); + } else { + let fixture: JsonValue = serde_json::from_str(include_str!( + "../../tests/fixtures/generated-recovery-preset-command.json" + )) + .unwrap(); + assert_eq!( + artifact, fixture, + "JS bridge fixture must match compiler output" + ); + assert!(artifact.get("trustedPresets").is_none()); + assert!(artifact["projection"]["preview"]["operations"] + .as_array() + .unwrap() + .is_empty()); + assert!(!artifact["projection"]["preview"]["recoveries"] + .as_array() + .unwrap() + .is_empty()); + } + } let mut invalid_u64_source = input_i64_value.clone(); invalid_u64_source["projection_programs"][0]["arms"][0]["operations"][0]["fields"][1] ["assignment"]["expression"]["value_type"] = json!({"type": "u64"}); refresh_schema_fingerprint(&mut invalid_u64_source); + for codec in ["uint8", "uint16", "uint32", "uint64_safe_integer"] { + let mut unsigned = invalid_u64_source.clone(); + unsigned["commands"][0]["input"]["definition"]["fields"][1]["type_name"] = json!("BigInt"); + unsigned["commands"][0]["input"]["definition"]["fields"][1]["codec"] = json!(codec); + unsigned["models"][0]["fields"][2]["scalar"] = json!("BigInt"); + unsigned["models"][0]["fields"][2]["codec"] = json!("json_number_precision_limited"); + refresh_schema_fingerprint(&mut unsigned); + let compiled = compile(input_with_manifest( + unsigned.clone(), + "query Todos { todos { id priority } }", + )) + .expect("unsigned refined inputs prove U64 slots"); + let source = file(&compiled, "commands.ts"); + assert!(source.contains("readonly \"priority\": number;")); + let body = source + .split("export const Command_createTodo:") + .nth(1) + .unwrap() + .split_once(" = ") + .unwrap() + .1 + .split_once("\n};") + .unwrap() + .0; + let artifact: JsonValue = serde_json::from_str(&format!("{body}\n}}")).unwrap(); + assert_eq!(artifact["input"]["definition"]["fields"][1]["codec"], codec); + assert_eq!( + artifact["projection"]["preview"]["operations"][0]["mutation"]["fields"][1]["value"] + ["kind"], + "input" + ); + if codec == "uint64_safe_integer" { + let fixture: JsonValue = serde_json::from_str(include_str!( + "../../tests/fixtures/generated-unsigned-command.json" + )) + .unwrap(); + assert_eq!( + artifact, fixture, + "unsigned JS bridge must match generated output" + ); + } + unsigned["commands"][0]["extensions"]["trusted_presets"] = + json!([{"name": "priority", "codec": codec}]); + unsigned["commands"][0]["extensions"]["projection"]["preview_occurrences"][0]["values"] + [2]["source"] = json!({"kind": "trusted_preset", "name": "priority", "codec": codec}); + refresh_schema_fingerprint(&mut unsigned); + compile(input_with_manifest( + unsigned, + "query Todos { todos { id priority } }", + )) + .expect("unsigned trusted preset codec proves U64 slot"); + } let mut invalid_constant_source = value.clone(); invalid_constant_source["commands"][0]["extensions"]["projection"]["preview_occurrences"][0] ["values"][2]["source"] = @@ -3225,9 +3640,9 @@ fn command_protocol_and_extensions_are_preserved_exactly() { } })); refresh_schema_fingerprint(&mut too_many_values); - let project = compile_client(ClientCompileInput::new( + let project = compile(ClientCompileInput::from_manifest_json( value, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -3287,9 +3702,9 @@ fn command_protocol_and_extensions_are_preserved_exactly() { assert!(sveltekit.contains("createCommands: createGeneratedCommands")); assert!(!sveltekit.contains("Readonly>")); - let partial = compile_client(ClientCompileInput::new( + let partial = compile(ClientCompileInput::from_manifest_json( partial_value, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -3303,9 +3718,9 @@ fn command_protocol_and_extensions_are_preserved_exactly() { assert!(partial_commands.contains("\"kind\": \"record\"")); assert!(partial_commands.contains("\"required\": false")); - let absent = compile_client(ClientCompileInput::new( + let absent = compile(ClientCompileInput::from_manifest_json( absent_value, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -3320,9 +3735,9 @@ fn command_protocol_and_extensions_are_preserved_exactly() { assert!(absent_commands.contains("\"condition\": \"if_record_missing\"")); assert!(!absent_commands.contains("\"op\": \"upsert\"")); - let absent_object = compile_client(ClientCompileInput::new( + let absent_object = compile(ClientCompileInput::from_manifest_json( absent_object_value, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -3335,9 +3750,9 @@ fn command_protocol_and_extensions_are_preserved_exactly() { assert!(!absent_object_commands.contains("\"name\": \"missing\"")); assert!(!absent_object_commands.contains("\"op\": \"upsert\"")); - let null = compile_client(ClientCompileInput::new( + let null = compile(ClientCompileInput::from_manifest_json( null_value, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -3357,9 +3772,9 @@ fn command_protocol_and_extensions_are_preserved_exactly() { json_object_key_value, unknown_partition_value, ] { - let project = compile_client(ClientCompileInput::new( + let project = compile(ClientCompileInput::from_manifest_json( fallback, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -3374,9 +3789,9 @@ fn command_protocol_and_extensions_are_preserved_exactly() { assert!(fallback_commands.contains("\"required\": true")); } - let delete = compile_client(ClientCompileInput::new( + let delete = compile(ClientCompileInput::from_manifest_json( delete_value, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -3388,9 +3803,9 @@ fn command_protocol_and_extensions_are_preserved_exactly() { assert!(!delete_commands.contains("\"op\": \"upsert\"")); assert!(!delete_commands.contains("\"op\": \"patch\"")); - let multi_model = compile_client(ClientCompileInput::new( + let multi_model = compile(ClientCompileInput::from_manifest_json( multi_model_value, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -3406,9 +3821,9 @@ fn command_protocol_and_extensions_are_preserved_exactly() { assert!(multi_model_commands.contains("\"model\": \"User\"")); for (operation_count, boundary) in capability_boundaries { - let compiled = compile_client(ClientCompileInput::new( + let compiled = compile(ClientCompileInput::from_manifest_json( boundary, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -3427,9 +3842,9 @@ fn command_protocol_and_extensions_are_preserved_exactly() { } for valid_i64 in [input_i64_value, preset_i64_value] { - compile_client(ClientCompileInput::new( + compile(ClientCompileInput::from_manifest_json( valid_i64, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -3445,9 +3860,9 @@ fn command_protocol_and_extensions_are_preserved_exactly() { invalid_list_source, invalid_preset_source, ] { - let error = compile_client(ClientCompileInput::new( + let error = compile(ClientCompileInput::from_manifest_json( invalid_source, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -3457,9 +3872,9 @@ fn command_protocol_and_extensions_are_preserved_exactly() { assert_eq!(error.code, "client.manifest.command_projection_source_type"); } - let error = compile_client(ClientCompileInput::new( + let error = compile(ClientCompileInput::from_manifest_json( conflicting_slot_type, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -3468,9 +3883,9 @@ fn command_protocol_and_extensions_are_preserved_exactly() { .expect_err("one opaque slot cannot claim conflicting value types"); assert_eq!(error.code, "client.manifest.command_projection_slot_type"); - let error = compile_client(ClientCompileInput::new( + let error = compile(ClientCompileInput::from_manifest_json( top_level_relationship_invalidation, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -3479,9 +3894,9 @@ fn command_protocol_and_extensions_are_preserved_exactly() { .expect_err("top-level relationship invalidation lacks source-key provenance"); assert_eq!(error.code, "client.manifest.projection_invalidation"); - let no_preview = compile_client(ClientCompileInput::new( + let no_preview = compile(ClientCompileInput::from_manifest_json( no_preview_value, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -3494,9 +3909,9 @@ fn command_protocol_and_extensions_are_preserved_exactly() { assert!(!no_preview_commands.contains("\"user_rows\"")); for boundary in [occurrence_boundary, value_boundary] { - compile_client(ClientCompileInput::new( + compile(ClientCompileInput::from_manifest_json( boundary, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -3505,9 +3920,9 @@ fn command_protocol_and_extensions_are_preserved_exactly() { .expect("projection preview accepts the frozen 128-entry boundary"); } for overflow in [too_many_occurrences, too_many_values] { - let error = compile_client(ClientCompileInput::new( + let error = compile(ClientCompileInput::from_manifest_json( overflow, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -3595,17 +4010,15 @@ fn manifest_v2_parses_exact_projection_program_binding_and_preview_contract() { install_create_projection(&mut value); refresh_schema_fingerprint(&mut value); - let parsed = ClientManifest::parse(value, &ClientSurfaceSelector::role("user")) + let parsed = parse_manifest(value, &ClientSurfaceIdentity::role("user")) .expect("manifest-v2 projection contract"); assert_eq!(parsed.projection_programs.len(), 1); assert_eq!(parsed.projection_programs[0].version, 2); assert!(matches!( parsed.projection_programs[0].arms[0].partition, - super::manifest::ManifestProjectionPartition::Expression { .. } + super::manifest::ClientProjectionPartition::Expression { .. } )); assert_eq!(parsed.projection_bindings.len(), 1); - assert!(parsed.commands[0].extensions.effects.is_none()); - assert!(parsed.commands[0].extensions.confirmations.is_none()); assert_eq!( parsed.commands[0] .extensions @@ -3623,30 +4036,31 @@ fn manifest_v2_has_no_legacy_projection_or_command_authority_decoder() { let mut stale_manifest = manifest(); stale_manifest["manifest_version"] = json!(1); refresh_schema_fingerprint(&mut stale_manifest); - let error = ClientManifest::parse(stale_manifest, &ClientSurfaceSelector::role("user")) + let error = parse_manifest(stale_manifest, &ClientSurfaceIdentity::role("user")) .expect_err("manifest v1 must fail closed"); - assert_eq!(error.code, "client.manifest.version"); + assert_eq!(error.code, "client.manifest.invalid"); + assert!(error.message.contains("version 1; expected 2"), "{error}"); let mut stale_command = projected_manifest(); stale_command["commands"][0]["extensions"]["version"] = json!(1); refresh_schema_fingerprint(&mut stale_command); - let error = ClientManifest::parse(stale_command, &ClientSurfaceSelector::role("user")) + let error = parse_manifest(stale_command, &ClientSurfaceIdentity::role("user")) .expect_err("command extensions v1 must fail closed"); - assert_eq!(error.code, "client.manifest.command_extensions"); + assert_eq!(error.code, "client.manifest.invalid"); - let mut legacy_effects = projected_manifest(); - legacy_effects["commands"][0]["extensions"]["effects"] = + let mut unknown_extension = projected_manifest(); + unknown_extension["commands"][0]["extensions"]["effects"] = json!({"version": 1, "operations": [], "fallback": "revalidate"}); - let error = ClientManifest::parse(legacy_effects, &ClientSurfaceSelector::role("user")) - .expect_err("legacy effects must not deserialize"); + let error = parse_manifest(unknown_extension, &ClientSurfaceIdentity::role("user")) + .expect_err("unknown command extension slots must not deserialize"); assert_eq!(error.code, "client.manifest.invalid"); let mut unknown_projection_field = manifest(); install_create_projection(&mut unknown_projection_field); unknown_projection_field["projection_programs"][0]["unexpected"] = json!(true); - let error = ClientManifest::parse( + let error = parse_manifest( unknown_projection_field, - &ClientSurfaceSelector::role("user"), + &ClientSurfaceIdentity::role("user"), ) .expect_err("unknown projection fields must fail closed"); assert_eq!(error.code, "client.manifest.invalid"); @@ -3655,9 +4069,9 @@ fn manifest_v2_has_no_legacy_projection_or_command_authority_decoder() { install_create_projection(&mut unsupported_program); unsupported_program["projection_programs"][0]["version"] = json!(3); refresh_schema_fingerprint(&mut unsupported_program); - let error = ClientManifest::parse(unsupported_program, &ClientSurfaceSelector::role("user")) + let error = parse_manifest(unsupported_program, &ClientSurfaceIdentity::role("user")) .expect_err("unknown projection program versions must fail closed"); - assert_eq!(error.code, "client.manifest.projection_program_version"); + assert_eq!(error.code, "client.manifest.invalid"); let mut duplicate_operation = manifest(); install_create_projection(&mut duplicate_operation); @@ -3669,16 +4083,16 @@ fn manifest_v2_has_no_legacy_projection_or_command_authority_decoder() { .unwrap() .push(duplicate); refresh_schema_fingerprint(&mut duplicate_operation); - let error = ClientManifest::parse(duplicate_operation, &ClientSurfaceSelector::role("user")) + let error = parse_manifest(duplicate_operation, &ClientSurfaceIdentity::role("user")) .expect_err("projection operation IDs must be unique within a program"); assert_eq!(error.code, "client.manifest.projection_operation_id"); } #[test] fn generated_command_typescript_covers_typed_json_fields_and_no_input_wrappers() { - let project = compile_client(ClientCompileInput::new( + let project = compile(ClientCompileInput::from_manifest_json( generated_command_types_manifest(), - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -3686,10 +4100,7 @@ fn generated_command_typescript_covers_typed_json_fields_and_no_input_wrappers() )) .expect("compile generated command type fixture"); let commands = file(&project, "commands.ts"); - assert_eq!( - commands, - include_str!("../../tests/fixtures/generated-commands.ts") - ); + assert_golden("generated-commands.ts", commands); } #[test] @@ -3699,9 +4110,9 @@ fn generated_command_namespaces_reject_prefix_collisions() { value["commands"][1]["name"] = json!("todo.complete"); refresh_schema_fingerprint(&mut value); - let error = compile_client(ClientCompileInput::new( + let error = compile(ClientCompileInput::from_manifest_json( value, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -3717,10 +4128,9 @@ fn generated_command_namespaces_reject_prefix_collisions() { #[test] fn projected_command_requires_exact_role_safe_direct_projection() { let value = projected_manifest(); - let parsed = ClientManifest::parse(value, &ClientSurfaceSelector::role("user")) + let parsed = parse_manifest(value, &ClientSurfaceIdentity::role("user")) .expect("valid projected direct target"); assert!(parsed.projectors[0].facts.is_empty()); - assert!(!parsed.projectors[0].causal_confirmation); let direct = parsed.commands[0] .extensions .direct_projection @@ -3732,11 +4142,11 @@ fn projected_command_requires_exact_role_safe_direct_projection() { assert_eq!(direct.change_epoch, "todos-v1"); assert!(matches!( direct.partition, - Some(super::manifest::ManifestEffectExpression::Input { ref path }) + Some(super::manifest::EffectExpression::Input { ref path }) if path.as_slice() == ["tenantId"] )); - let project = compile_client(input_with_manifest( + let project = compile(input_with_manifest( projected_manifest(), "query Todos { todos { id } }", )) @@ -3751,31 +4161,21 @@ fn projected_command_requires_exact_role_safe_direct_projection() { .expect("extensions") .remove("direct_projection"); refresh_schema_fingerprint(&mut absent); - let error = ClientManifest::parse(absent, &ClientSurfaceSelector::role("user")) + let error = parse_manifest(absent, &ClientSurfaceIdentity::role("user")) .expect_err("projected direct target is mandatory"); assert_eq!(error.code, "client.manifest.direct_projection_required"); let mut non_projected = projected_manifest(); non_projected["commands"][0]["extensions"]["consistency"]["kind"] = json!("succeeded"); refresh_schema_fingerprint(&mut non_projected); - let error = ClientManifest::parse(non_projected, &ClientSurfaceSelector::role("user")) + let error = parse_manifest(non_projected, &ClientSurfaceIdentity::role("user")) .expect_err("succeeded commands cannot carry direct projection metadata"); assert_eq!(error.code, "client.manifest.direct_projection_unexpected"); - let mut impossible_confirmation = projected_manifest(); - impossible_confirmation["projectors"][0]["causal_confirmation"] = json!(true); - refresh_schema_fingerprint(&mut impossible_confirmation); - let error = ClientManifest::parse( - impossible_confirmation, - &ClientSurfaceSelector::role("user"), - ) - .expect_err("a direct-only owner cannot confirm asynchronous work"); - assert_eq!(error.code, "client.manifest.projector_inventory"); - let mut embedded = projected_manifest(); embedded["models"][0]["normalization"] = json!({"kind": "embedded"}); refresh_schema_fingerprint(&mut embedded); - let error = ClientManifest::parse(embedded, &ClientSurfaceSelector::role("user")) + let error = parse_manifest(embedded, &ClientSurfaceIdentity::role("user")) .expect_err("direct projection requires a complete normalized identity"); assert_eq!(error.code, "client.manifest.direct_projection_model"); } @@ -3786,7 +4186,7 @@ fn projected_command_rejects_tampered_topology_and_wrong_owner() { tampered["commands"][0]["extensions"]["direct_projection"]["topology"]["digest"] = json!(format!("sha256:{}", "AB".repeat(32))); refresh_schema_fingerprint(&mut tampered); - let error = ClientManifest::parse(tampered, &ClientSurfaceSelector::role("user")) + let error = parse_manifest(tampered, &ClientSurfaceIdentity::role("user")) .expect_err("topology digest must be canonical lowercase SHA-256"); assert_eq!(error.code, "client.manifest.hash"); @@ -3794,7 +4194,7 @@ fn projected_command_rejects_tampered_topology_and_wrong_owner() { wrong_owner["commands"][0]["extensions"]["direct_projection"]["topology"]["name"] = json!("other_projector"); refresh_schema_fingerprint(&mut wrong_owner); - let error = ClientManifest::parse(wrong_owner, &ClientSurfaceSelector::role("user")) + let error = parse_manifest(wrong_owner, &ClientSurfaceIdentity::role("user")) .expect_err("direct target must use the visible model owner"); assert_eq!(error.code, "client.manifest.direct_projection_owner"); @@ -3804,9 +4204,9 @@ fn projected_command_rejects_tampered_topology_and_wrong_owner() { trusted_preset["commands"][0]["extensions"]["trusted_presets"] = json!([{"name": "current_tenant", "codec": "string"}]); refresh_schema_fingerprint(&mut trusted_preset); - ClientManifest::parse(trusted_preset.clone(), &ClientSurfaceSelector::role("user")) + parse_manifest(trusted_preset.clone(), &ClientSurfaceIdentity::role("user")) .expect("scope-bound trusted preset may define a direct target"); - let project = compile_client(input_with_manifest( + let project = compile(input_with_manifest( trusted_preset, "query Todos { todos { id } }", )) @@ -3881,9 +4281,9 @@ fn rejects_commands_without_causal_identity_or_normative_input_defaults() { "operation_hash": fingerprint(status) } }); - compile_client(ClientCompileInput::new( + compile(ClientCompileInput::from_manifest_json( value, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -3903,7 +4303,7 @@ fn rejects_commands_without_causal_identity_or_normative_input_defaults() { compile(command(valid, "uuid_v4")) .expect_err("unsupported generator") .code, - "client.manifest.input_default_generator" + "client.manifest.invalid" ); } @@ -3933,23 +4333,23 @@ fn output_is_identical_for_shuffled_documents() { "query Todo { todo(tenantId: \"t\", id: \"1\") { title } }", ), ]; - let left = compile_client(ClientCompileInput::new( + let left = compile(ClientCompileInput::from_manifest_json( left_manifest, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), docs.clone(), )) .expect("left"); - let right = compile_client(ClientCompileInput::new( + let right = compile(ClientCompileInput::from_manifest_json( right_manifest, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), docs.into_iter().rev().collect(), )) .expect("right"); assert_eq!(left, right); - let error = compile_client(ClientCompileInput::new( + let error = compile(ClientCompileInput::from_manifest_json( tampered_manifest, - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/routes/todos/+page.graphql", "query Todos { todos { id } }", @@ -3977,7 +4377,7 @@ fn manifest_parser_accepts_embedded_by_pk_and_zero_sized_windows() { } refresh_schema_fingerprint(&mut value); - ClientManifest::parse(value, &ClientSurfaceSelector::role("user")) + parse_manifest(value, &ClientSurfaceIdentity::role("user")) .expect("embedded models and zero-sized authorized windows are valid v6 contracts"); } @@ -3987,7 +4387,7 @@ fn manifest_parser_rejects_execution_limits_outside_javascript_integer_range() { let mut value = manifest(); value["execution"][name] = json!(9_007_199_254_740_992_u64); refresh_schema_fingerprint(&mut value); - let error = ClientManifest::parse(value, &ClientSurfaceSelector::role("user")) + let error = parse_manifest(value, &ClientSurfaceIdentity::role("user")) .expect_err("runtime codec limits must remain exact JavaScript integers"); assert_eq!(error.code, "client.manifest.execution_js_integer", "{name}"); } @@ -4023,7 +4423,7 @@ fn manifest_parser_rejects_list_roots_without_executable_query_plan_semantics() }); refresh_schema_fingerprint(&mut value); - let error = ClientManifest::parse(value, &ClientSurfaceSelector::role("user")) + let error = parse_manifest(value, &ClientSurfaceIdentity::role("user")) .expect_err("list roots require the complete executable query-plan contract"); assert_eq!(error.code, expected_code, "missing {semantic}"); } @@ -4035,14 +4435,14 @@ fn manifest_parser_rejects_filter_input_target_and_argument_drift() { wrong_target["models"][0]["filter_input"]["relationships"][0]["target_type"] = json!("other_bool_exp"); refresh_schema_fingerprint(&mut wrong_target); - let error = ClientManifest::parse(wrong_target, &ClientSurfaceSelector::role("user")) + let error = parse_manifest(wrong_target, &ClientSurfaceIdentity::role("user")) .expect_err("relationship filter targets must resolve to the target model contract"); assert_eq!(error.code, "client.manifest.filter_input_target_type"); let mut wrong_argument = manifest(); wrong_argument["roots"][0]["arguments"][0]["type_name"] = json!("other_bool_exp"); refresh_schema_fingerprint(&mut wrong_argument); - let error = ClientManifest::parse(wrong_argument, &ClientSurfaceSelector::role("user")) + let error = parse_manifest(wrong_argument, &ClientSurfaceIdentity::role("user")) .expect_err("root filter arguments must name the model filter contract"); assert_eq!(error.code, "client.manifest.filter_argument_type"); } @@ -4061,15 +4461,15 @@ fn manifest_parser_accepts_mixed_per_model_revision_evidence() { value["capabilities"]["tombstones"] = json!(false); refresh_schema_fingerprint(&mut value); - ClientManifest::parse(value, &ClientSurfaceSelector::role("user")) + parse_manifest(value, &ClientSurfaceIdentity::role("user")) .expect("global record evidence describes the selected query footprint, not any model"); } #[test] fn source_paths_fail_closed_before_they_can_inject_generated_typescript() { - let error = compile_client(ClientCompileInput::new( + let error = compile(ClientCompileInput::from_manifest_json( manifest(), - ClientSurfaceSelector::role("user"), + ClientSurfaceIdentity::role("user"), vec![ClientDocument::new( "src/injected*/\nexport const compromised = true;\n/**.graphql", "query Safe { todos { id } }", @@ -4079,3 +4479,183 @@ fn source_paths_fail_closed_before_they_can_inject_generated_typescript() { assert_eq!(error.code, "client.documents.invalid_path"); assert!(!error.message.contains("export const compromised")); } + +#[test] +fn generated_lazy_commands_defer_definitions_and_preserve_command_signatures() { + let project = compile(ClientCompileInput::from_manifest_json( + generated_command_types_manifest(), + ClientSurfaceIdentity::role("user"), + vec![ClientDocument::new( + "todos.graphql", + "query Todos { todos { id } }", + )], + )) + .expect("compile lazy commands"); + let lazy = file(&project, "lazy-commands.ts"); + assert!(lazy.contains("import type { COMMANDS, GeneratedCommandRuntimeOptions }")); + assert!(lazy.contains("import('./commands.js')")); + assert!(lazy.contains("\"hasInput\": false")); + assert!(lazy.contains("\"hasInput\": true")); + let wrapper = file(&project, "sveltekit.ts"); + assert!(wrapper.contains("export function provideDistributedLazy(")); + assert!(wrapper.contains("createCommands: createLazyCommands")); + assert!(wrapper.contains("createCommands: createGeneratedCommands")); + assert_golden( + "generated-lazy-commands.ts", + &lazy.replace("'./commands.js'", "'./generated-commands.js'"), + ); +} + +fn leaderboard_manifest() -> JsonValue { + let mut value = manifest(); + value["external"]["leaderboards"] = json!([ + { + "name": "xp", + "entry_typename": "LeaderboardEntry", + "order": "high_first", + "boards": "single", + "default_first": 3, + "max_first": 5, + "max_radius": 2, + "roots": [ + {"name": "xpLeaderboard", "operation": "top", "list": true, "live": true, + "arguments": [{"name": "first", "type_name": "Int", "nullable": true}]}, + {"name": "xpMyRank", "operation": "my_rank", "list": false, "live": true, + "arguments": []} + ] + }, + { + "name": "season", + "entry_typename": "LeaderboardEntry", + "order": "low_first", + "boards": "family", + "default_first": 10, + "max_first": 100, + "max_radius": 25, + "roots": [ + {"name": "seasonRank", "operation": "rank", "list": false, "live": false, + "arguments": [ + {"name": "board", "type_name": "String", "nullable": false}, + {"name": "member", "type_name": "String", "nullable": false} + ]} + ] + } + ]); + refresh_schema_fingerprint(&mut value); + value +} + +const LEADERBOARD_PAGE: &str = r#" + query Todos($limit: Int!) { + todos(limit: $limit) { title } + } +"#; + +#[test] +fn leaderboard_roots_generate_typed_documents() { + let project = compile(input_with_manifest( + leaderboard_manifest(), + LEADERBOARD_PAGE, + )) + .unwrap(); + let generated = file(&project, "leaderboards.ts"); + assert!(generated.contains("export interface LeaderboardEntry {")); + assert!(generated + .contains("export type XpLeaderboardVariables = { readonly first?: number | null; };")); + assert!(generated.contains( + "export type XpLeaderboardData = { readonly xpLeaderboard: readonly LeaderboardEntry[] };" + )); + assert!(generated.contains( + r#"document: "query XpLeaderboard($first: Int) { xpLeaderboard(first: $first) { rank member score } }","# + )); + assert!(generated.contains( + r#"liveDocument: "subscription XpLeaderboard_Live($first: Int) { xpLeaderboard(first: $first) { rank member score } }","# + )); + // The viewer's rank takes no member argument: the server binds it from + // the verified session. + assert!(generated.contains("export type XpMyRankVariables = {};")); + assert!(generated.contains(r#"document: "query XpMyRank { xpMyRank { rank member score } }","#)); + assert!(generated.contains( + "export type SeasonRankVariables = { readonly board: string; readonly member: string; };" + )); + assert!(generated.contains("liveDocument: null,")); + assert!(generated.contains("\"xpLeaderboard\": XpLeaderboardLeaderboard,")); + assert!(file(&project, "index.ts").contains("export * from './leaderboards.js';")); + assert_golden("generated-leaderboards.ts", generated); +} + +#[test] +fn manifests_without_leaderboards_generate_no_module() { + let project = compile(input(LEADERBOARD_PAGE)).unwrap(); + assert!(project + .files + .iter() + .all(|file| file.path != "leaderboards.ts")); + assert!(!file(&project, "index.ts").contains("leaderboards")); +} + +type ManifestMutation = Box; + +#[test] +fn malformed_leaderboard_sections_are_refused() { + let cases: Vec<(&str, ManifestMutation)> = vec![ + ( + "a member argument on my_rank", + Box::new(|value: &mut JsonValue| { + value["external"]["leaderboards"][0]["roots"][1]["arguments"] = + json!([{"name": "member", "type_name": "String", "nullable": false}]); + }), + ), + ( + "a live rank root", + Box::new(|value: &mut JsonValue| { + value["external"]["leaderboards"][1]["roots"][0]["live"] = json!(true); + }), + ), + ( + "an unknown operation", + Box::new(|value: &mut JsonValue| { + value["external"]["leaderboards"][0]["roots"][0]["operation"] = json!("everyone"); + }), + ), + ( + "a root colliding with a read-model root", + Box::new(|value: &mut JsonValue| { + value["external"]["leaderboards"][0]["roots"][0]["name"] = json!("todos"); + }), + ), + ( + "an unknown field", + Box::new(|value: &mut JsonValue| { + value["external"]["leaderboards"][0]["extra"] = json!(true); + }), + ), + ( + "a family root without board", + Box::new(|value: &mut JsonValue| { + value["external"]["leaderboards"][1]["roots"][0]["arguments"] = + json!([{"name": "member", "type_name": "String", "nullable": false}]); + }), + ), + ]; + for (case, mutate) in cases { + let mut value = leaderboard_manifest(); + mutate(&mut value); + refresh_schema_fingerprint(&mut value); + let error = compile(input_with_manifest(value, LEADERBOARD_PAGE)).expect_err(case); + assert_eq!(error.code, "client.manifest.leaderboard", "{case}: {error}"); + } + + // A section this compiler does not know is refused. + let mut unknown = leaderboard_manifest(); + unknown["external"]["search"] = json!([{"name": "docs"}]); + refresh_schema_fingerprint(&mut unknown); + let error = compile(input_with_manifest(unknown, LEADERBOARD_PAGE)).unwrap_err(); + assert_eq!(error.code, "client.manifest.external", "{error}"); + + // A stale fingerprint is still caught. + let mut tampered = leaderboard_manifest(); + tampered["external"]["leaderboards"][0]["max_first"] = json!(50); + let error = compile(input_with_manifest(tampered, LEADERBOARD_PAGE)).unwrap_err(); + assert_eq!(error.code, "client.manifest.schema_fingerprint"); +} diff --git a/distributed_cli/src/contracts/classification.rs b/distributed_cli/src/contracts/classification.rs index a07661381..6ef321512 100644 --- a/distributed_cli/src/contracts/classification.rs +++ b/distributed_cli/src/contracts/classification.rs @@ -111,10 +111,11 @@ pub fn decisions_are_distinct(changes: &[ClassifiedChange]) -> bool { // Distinctness is only meaningful when both families appear. let has_wire = seen.contains(&LifecycleDecision::AcceptManifestWire); let has_protocol = seen.contains(&LifecycleDecision::AcceptProtocolSemantic); - !(has_wire && has_protocol && changes.iter().any(|c| { - c.decision == LifecycleDecision::AcceptManifestWire - && c.path.contains("protocol") - })) + !(has_wire + && has_protocol + && changes.iter().any(|c| { + c.decision == LifecycleDecision::AcceptManifestWire && c.path.contains("protocol") + })) } #[cfg(test)] diff --git a/distributed_cli/src/contracts/closeout.rs b/distributed_cli/src/contracts/closeout.rs index 22cf7ed1d..1297983de 100644 --- a/distributed_cli/src/contracts/closeout.rs +++ b/distributed_cli/src/contracts/closeout.rs @@ -70,10 +70,7 @@ mod tests { #[test] fn local_chain_closeout_accepts_matching_predecessors() { - let app = ArtifactIdentity::new( - ContractArtifactKind::ApplicationManifest, - "sha256:app", - ); + let app = ArtifactIdentity::new(ContractArtifactKind::ApplicationManifest, "sha256:app"); let plan = ArtifactIdentity::new(ContractArtifactKind::DeploymentPlan, "sha256:plan"); let result = close_local_contract_chain(&app, &plan, true, None); assert!(result.diagnostics.is_empty()); @@ -90,10 +87,7 @@ mod tests { )); fs::create_dir_all(&root).unwrap(); fs::write(root.join("a.js"), b"1").unwrap(); - let app = ArtifactIdentity::new( - ContractArtifactKind::ApplicationManifest, - "sha256:app", - ); + let app = ArtifactIdentity::new(ContractArtifactKind::ApplicationManifest, "sha256:app"); let plan = ArtifactIdentity::new(ContractArtifactKind::DeploymentPlan, "sha256:plan"); let program = ClientProgramDescriptor::builder("e2e-ui") .surface(ClientProgramSurface { diff --git a/distributed_cli/src/contracts/mod.rs b/distributed_cli/src/contracts/mod.rs index 68f3fe2c3..201165ff7 100644 --- a/distributed_cli/src/contracts/mod.rs +++ b/distributed_cli/src/contracts/mod.rs @@ -8,8 +8,8 @@ mod artifact; mod catalog; mod chain; -mod closeout; mod classification; +mod closeout; mod diagnostic; mod migrations; mod program; @@ -31,10 +31,10 @@ pub use catalog::{ MAX_CATALOG_GLOB_MATCHES, MAX_CATALOG_JSON_DEPTH, }; pub use chain::{check_predecessor_chain, ObservedPredecessor}; -pub use closeout::{classify_release_programs, close_local_contract_chain}; pub use classification::{ classify_snapshot_diff, decisions_are_distinct, ClassifiedChange, LifecycleDecision, }; +pub use closeout::{classify_release_programs, close_local_contract_chain}; pub use diagnostic::{ ContractCheckResult, ContractDiagnostic, ContractDiagnosticCode, SafeDiagnosticValue, }; diff --git a/distributed_cli/src/contracts/program.rs b/distributed_cli/src/contracts/program.rs index 0b9da7d20..bfd13da6b 100644 --- a/distributed_cli/src/contracts/program.rs +++ b/distributed_cli/src/contracts/program.rs @@ -118,7 +118,9 @@ impl ClientProgramDescriptor { return Err("program must declare at least one surface".into()); } if self.assets.len() > MAX_PROGRAM_ASSETS { - return Err(format!("program exceeds max asset count {MAX_PROGRAM_ASSETS}")); + return Err(format!( + "program exceeds max asset count {MAX_PROGRAM_ASSETS}" + )); } let mut paths = BTreeSet::new(); for asset in &self.assets { @@ -291,7 +293,10 @@ fn contract_set_id( ); } for artifact in artifacts { - material.insert(format!("artifact:{}", artifact.path), artifact.digest.clone()); + material.insert( + format!("artifact:{}", artifact.path), + artifact.digest.clone(), + ); } let bytes = serde_json::to_vec(&material).unwrap_or_default(); identity_digest("distributed.client-program.contract-set.v1", &bytes) @@ -319,7 +324,10 @@ fn program_id( fn collect_assets(root: &Path) -> Result, String> { if !root.is_dir() { - return Err(format!("asset root `{}` is not a directory", root.display())); + return Err(format!( + "asset root `{}` is not a directory", + root.display() + )); } let root = root.canonicalize().map_err(|e| e.to_string())?; let mut assets = Vec::new(); @@ -398,14 +406,15 @@ fn identity_digest(domain: &str, bytes: &[u8]) -> String { mod tests { use super::*; use std::path::PathBuf; - use std::time::{SystemTime, UNIX_EPOCH}; fn temp_dir() -> PathBuf { - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos(); - let path = std::env::temp_dir().join(format!("client-program-{nanos}")); + // Unique per call: tests run in parallel and the clock alone repeats. + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let path = std::env::temp_dir().join(format!( + "client-program-{}-{}", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + )); fs::create_dir_all(&path).unwrap(); path } @@ -439,7 +448,10 @@ mod tests { fs::write(root.join("app.js"), b"console.log(1)").unwrap(); let first = base_builder(&root).build().unwrap(); let second = base_builder(&root).build().unwrap(); - assert_eq!(first.canonical_bytes().unwrap(), second.canonical_bytes().unwrap()); + assert_eq!( + first.canonical_bytes().unwrap(), + second.canonical_bytes().unwrap() + ); assert_eq!( first.classify_against(&second).unwrap(), ProgramCompatibility::Current diff --git a/distributed_cli/src/contracts/snapshots.rs b/distributed_cli/src/contracts/snapshots.rs index 6c387e620..94a6a1d1e 100644 --- a/distributed_cli/src/contracts/snapshots.rs +++ b/distributed_cli/src/contracts/snapshots.rs @@ -161,10 +161,7 @@ fn flatten_value( Value::String(text) if text.len() > MAX_SNAPSHOT_VALUE_BYTES => { out.insert( prefix.to_string(), - Value::String(format!( - "", - text.len() - )), + Value::String(format!("", text.len())), ); } other => { @@ -243,10 +240,7 @@ mod tests { .unwrap(); let changes = diff_snapshots(&left, &drifted).changes; assert_eq!(changes.len(), 1); - assert_eq!( - changes[0].path, - "models.TodoView.fields.title.nullable" - ); + assert_eq!(changes[0].path, "models.TodoView.fields.title.nullable"); assert_eq!(changes[0].before, Some(json!(false))); assert_eq!(changes[0].after, Some(json!(true))); } diff --git a/distributed_cli/src/contracts/tests.rs b/distributed_cli/src/contracts/tests.rs index 9c2bb4538..cdfc55745 100644 --- a/distributed_cli/src/contracts/tests.rs +++ b/distributed_cli/src/contracts/tests.rs @@ -703,10 +703,6 @@ fn human_and_json_diagnostics_preserve_same_facts_and_redact_values() { .to_json() .expect("diagnostic JSON") .contains("postgres://")); - assert_eq!( - result.canonical_bytes().expect("canonical result"), - result.canonical_bytes().expect("second canonical result") - ); let decoded: ContractDiagnostic = serde_json::from_value(serde_json::json!({ "code": "CTL-SCHEMA-DRIFT", @@ -1251,7 +1247,7 @@ fn write_json_value(path: &Path, value: &Value) { } #[test] -fn migration_inventory_is_deterministic_and_preserves_runtime_order() { +fn migration_inventory_preserves_runtime_order() { let inventory = MigrationInventory::from_repository_root(repository_root()) .expect("repository migration inventory"); let versions = inventory @@ -1259,12 +1255,9 @@ fn migration_inventory_is_deterministic_and_preserves_runtime_order() { .iter() .map(|migration| migration.version) .collect::>(); - assert_eq!(versions, vec![1, 2, 3, 4]); assert_eq!( - inventory.canonical_bytes().expect("canonical inventory"), - inventory - .canonical_bytes() - .expect("second canonical inventory") + versions, + vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] ); } diff --git a/distributed_cli/src/contracts/transaction.rs b/distributed_cli/src/contracts/transaction.rs index cdd6b6643..fa9e63d87 100644 --- a/distributed_cli/src/contracts/transaction.rs +++ b/distributed_cli/src/contracts/transaction.rs @@ -5,9 +5,7 @@ use super::catalog::ContractCatalog; use super::chain::{check_predecessor_chain, ObservedPredecessor}; -use super::diagnostic::{ - ContractCheckResult, ContractDiagnostic, ContractDiagnosticCode, -}; +use super::diagnostic::{ContractCheckResult, ContractDiagnostic, ContractDiagnosticCode}; use super::ContractArtifactKind; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; @@ -25,7 +23,9 @@ pub enum ContractAcceptScope { ApplicationManifest, DeploymentPlan, /// Exact client-program scope: `program:`. - Program { id: String }, + Program { + id: String, + }, } impl ContractAcceptScope { @@ -190,10 +190,7 @@ pub fn contracts_accept( }) } -fn rollback( - root: &Path, - prior: &BTreeMap>>, -) -> Result<(), String> { +fn rollback(root: &Path, prior: &BTreeMap>>) -> Result<(), String> { for (relative, contents) in prior { let path = resolve_under_root(root, relative)?; match contents { @@ -224,9 +221,7 @@ fn resolve_under_root(root: &Path, relative: &str) -> Result { "accept path `{relative}` escapes or is not a portable relative path" )); } - let root = root - .canonicalize() - .unwrap_or_else(|_| root.to_path_buf()); + let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); let candidate = root.join(relative); if let Ok(canonical) = candidate.canonicalize() { if !canonical.starts_with(&root) { @@ -272,14 +267,15 @@ pub fn unknown_scope_diagnostic(scope: &str) -> ContractDiagnostic { #[cfg(test)] mod tests { use super::*; - use std::time::{SystemTime, UNIX_EPOCH}; fn temp_root() -> PathBuf { - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos(); - let root = std::env::temp_dir().join(format!("distributed-contracts-accept-{nanos}")); + // Unique per call: tests run in parallel and the clock alone repeats. + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let root = std::env::temp_dir().join(format!( + "distributed-contracts-accept-{}-{}", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + )); fs::create_dir_all(&root).unwrap(); root } @@ -304,15 +300,4 @@ mod tests { assert!(contracts_accept(&root, ContractAcceptScope::Catalog, &bad).is_err()); let _ = fs::remove_dir_all(root); } - - #[test] - fn check_report_is_no_write() { - // Empty catalog check shape only — catalog construction is covered elsewhere. - let report = ContractsCheckReport { - ok: true, - result: ContractCheckResult::default(), - human: String::new(), - }; - assert!(report.ok); - } } diff --git a/distributed_cli/src/game_client.rs b/distributed_cli/src/game_client.rs new file mode 100644 index 000000000..d4a402fe6 --- /dev/null +++ b/distributed_cli/src/game_client.rs @@ -0,0 +1,1756 @@ +//! `distributed game-client`: typed TypeScript for one `distributed_game` +//! zone surface (`GameSurface` JSON, schema v3, from `distributed +//! game-manifest`). +//! +//! The generated files import only `@hops-ops/distributed/game` and are +//! deterministic (same surface → same bytes): +//! +//! | file | contents | +//! |---|---| +//! | `schema.ts` | `KIND` ids, per-kind field interfaces + accessors over rendered entities, field wire types, `CORRECTIONS` defaults | +//! | `input.ts` | the input interface, `BUTTON` bits, `encodeInput` / `decodeInput` / `sanitizeInput` | +//! | `events.ts` | record + event payload interfaces, `EVENT` ids, `EVENTS` codecs, `decodeEvent`, `onEvent`; `encode` / `decode` for the surface's standalone codecs; with zone inbox messages, `Message` interfaces, `MESSAGE` ids, `MESSAGES` codecs and `encodeMessage` (for services posting to `/admin/zone-message`) | +//! | `client.ts` | `createClient`: a `GameClient` with the input encoder and correction defaults wired in, plus typed `on`; with a predicted step, prediction defaults to the compiled WebAssembly step | +//! | `predict.ts` | only with a `#[predict]` step: its state/context layouts, the module URL (`wasm/.wasm`, built by `distributed game-wasm`) and `createPrediction` | +//! | `pures.ts` | only with `#[game_pure]` functions: `createPures`, one typed wrapper per function over the same module | +//! | `constants.ts` | only with constants: each value as a typed TypeScript literal (exact binary32 floats) | +//! | `index.ts` | re-exports | +//! | `surface.json` | the surface it was generated from (so `--check` also catches manifest drift) | +//! +//! This is intentionally not the GraphQL client manifest: that contract is +//! strict (`deny_unknown_fields`, fingerprints) and describes a different +//! protocol. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt::Write as _; + +use distributed_game::codec::WireType; +use distributed_game::prediction::ABI_VERSION as PREDICT_ABI_VERSION; +use distributed_game::schema::Correction; +use distributed_game::surface::{ + EventPayload, EventSurface, GameSurface, PayloadField, RecordSurface, + GAME_SURFACE_SCHEMA_VERSION, +}; + +use crate::client_compiler::GeneratedClientFile; + +const SDK: &str = "@hops-ops/distributed/game"; + +/// Import specifier style for imports between generated files. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ImportExtension { + /// `./schema.ts` (Node type stripping, Vite, `allowImportingTsExtensions`). + Ts, + /// `./schema.js` (tsc `NodeNext` emit). + Js, + /// `./schema` (bundler resolution). + None, +} + +impl ImportExtension { + fn suffix(self) -> &'static str { + match self { + Self::Ts => ".ts", + Self::Js => ".js", + Self::None => "", + } + } +} + +/// What `distributed game-wasm` compiles for a surface: one module from one +/// Cargo package exporting the predicted step and the pure functions. +#[derive(Debug)] +pub(crate) struct ModulePlan { + /// The declaring Cargo package. + pub(crate) package: String, + /// Required function exports (`dg_predict_`, `dg_pure_`). + pub(crate) exports: Vec, + /// ABI version. + pub(crate) abi: u32, +} + +// ---- naming --------------------------------------------------------------- + +fn words(name: &str) -> Vec { + let mut out = Vec::new(); + let mut current = String::new(); + let mut prev_lower = false; + for c in name.chars() { + if c == '_' || c == '-' || c == ' ' { + if !current.is_empty() { + out.push(std::mem::take(&mut current)); + } + prev_lower = false; + continue; + } + if c.is_uppercase() && prev_lower && !current.is_empty() { + out.push(std::mem::take(&mut current)); + } + prev_lower = c.is_lowercase() || c.is_ascii_digit(); + current.push(c); + } + if !current.is_empty() { + out.push(current); + } + out +} + +fn capitalize(word: &str) -> String { + let mut chars = word.chars(); + match chars.next() { + Some(first) => first + .to_uppercase() + .chain(chars.flat_map(char::to_lowercase)) + .collect(), + None => String::new(), + } +} + +/// `view_radius` → `viewRadius`. +fn camel(name: &str) -> String { + let words = words(name); + let mut out = String::new(); + for (i, word) in words.iter().enumerate() { + if i == 0 { + out.push_str(&word.to_lowercase()); + } else { + out.push_str(&capitalize(word)); + } + } + out +} + +/// `board_snapshot` → `BoardSnapshot`. +fn pascal(name: &str) -> String { + words(name).iter().map(|w| capitalize(w)).collect() +} + +/// `slow_ms` → `SLOW_MS`. +fn constant(name: &str) -> String { + words(name) + .iter() + .map(|w| w.to_uppercase()) + .collect::>() + .join("_") +} + +/// Property names must stay distinct and non-empty in camelCase. +fn check_field_names(fields: &[PayloadField], owner: &str) -> GenResult<()> { + let mut props = BTreeSet::new(); + for field in fields { + if !props.insert(camel(&field.name)) || camel(&field.name).is_empty() { + return Err(format!( + "{owner}: field `{}` is empty or collides with another as `{}`", + field.name, + camel(&field.name) + )); + } + } + Ok(()) +} + +fn is_identifier(name: &str) -> bool { + let mut chars = name.chars(); + matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$') + && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$') +} + +fn key(name: &str) -> String { + if is_identifier(name) { + name.to_string() + } else { + format!("'{}'", name.replace('\\', "\\\\").replace('\'', "\\'")) + } +} + +/// Single-quoted TypeScript string literal. +fn string(value: &str) -> String { + let mut out = String::from("'"); + for c in value.chars() { + match c { + '\\' => out.push_str("\\\\"), + '\'' => out.push_str("\\'"), + '\n' => out.push_str("\\n"), + c if c.is_control() => { + let _ = write!(out, "\\u{{{:x}}}", c as u32); + } + c => out.push(c), + } + } + out.push('\''); + out +} + +fn f32_literal(v: f32) -> String { + if v.is_finite() { + format!("{v}") + } else { + "Number.NaN".into() + } +} + +/// The exact binary32 value as a JS number (`Math.fround` of it is itself). +fn f32_exact(v: f32) -> String { + if v.is_finite() { + format!("{}", f64::from(v)) + } else { + "Number.NaN".into() + } +} + +fn f64_literal(v: f64) -> String { + format!("{v}") +} + +// ---- generation ----------------------------------------------------------- + +struct Gen<'a> { + surface: &'a GameSurface, + records: BTreeMap<&'a str, &'a RecordSurface>, + ext: ImportExtension, +} + +type GenResult = Result; + +/// Generate the client files for a surface manifest (JSON text). +pub fn generate_game_client( + manifest_json: &str, + ext: ImportExtension, +) -> GenResult> { + let value: serde_json::Value = + serde_json::from_str(manifest_json).map_err(|e| format!("parse game surface: {e}"))?; + let version = value + .get("schemaVersion") + .and_then(serde_json::Value::as_u64); + if version != Some(u64::from(GAME_SURFACE_SCHEMA_VERSION)) { + return Err(format!( + "unsupported game surface schemaVersion {version:?}; this CLI generates schema version {GAME_SURFACE_SCHEMA_VERSION}" + )); + } + let surface: GameSurface = + serde_json::from_value(value.clone()).map_err(|e| format!("invalid game surface: {e}"))?; + let gen = Gen::new(&surface, ext)?; + let mut files = vec![ + file("schema.ts", gen.schema_ts()?), + file("input.ts", gen.input_ts()?), + file("events.ts", gen.events_ts()?), + file("client.ts", gen.client_ts()), + file("index.ts", gen.index_ts()), + file( + "surface.json", + serde_json::to_string_pretty(&value).expect("surface serializes") + "\n", + ), + ]; + if let Some(predict) = gen.predict_ts()? { + files.push(file("predict.ts", predict)); + } + if let Some(pures) = gen.pures_ts()? { + files.push(file("pures.ts", pures)); + } + if let Some(constants) = gen.constants_ts()? { + files.push(file("constants.ts", constants)); + } + files.sort_by(|a, b| a.path.cmp(&b.path)); + Ok(files) +} + +/// What `distributed game-wasm` builds for a surface: its name and the +/// validated module plan (`None` when the zone compiles nothing: no +/// predicted step and no pure functions). +pub(crate) fn surface_module(manifest_json: &str) -> GenResult<(String, Option)> { + validate_game_surface(manifest_json)?; + let surface: GameSurface = + serde_json::from_str(manifest_json).map_err(|e| format!("invalid game surface: {e}"))?; + let package = surface + .predict + .as_ref() + .map(|p| p.package.clone()) + .or_else(|| surface.pures.first().map(|p| p.package.clone())); + let plan = package.map(|package| { + let mut exports: Vec = surface + .predict + .iter() + .map(|p| format!("dg_predict_{}", p.export)) + .collect(); + exports.extend( + surface + .pures + .iter() + .map(|p| format!("dg_pure_{}", p.export)), + ); + ModulePlan { + package, + exports, + abi: PREDICT_ABI_VERSION, + } + }); + Ok((surface.name, plan)) +} + +/// Module path of a surface's compiled step, relative to the generated +/// client directory. +pub(crate) fn predict_wasm_path(surface: &str) -> String { + format!("wasm/{surface}.wasm") +} + +/// Validate a manifest (as `game-manifest` prints it). +pub fn validate_game_surface(manifest_json: &str) -> GenResult<()> { + generate_game_client(manifest_json, ImportExtension::Ts).map(|_| ()) +} + +/// The directory `distributed game-client` writes. It owns the files directly +/// in it; a subdirectory (`wasm/`, from `distributed game-wasm`) is not its +/// own. +fn game_client_dir(root: &std::path::Path) -> crate::generated_dir::GeneratedDir<'_> { + crate::generated_dir::GeneratedDir { + root, + nested: false, + } +} + +/// Make `root` hold exactly the generated files. A file that is not one of +/// them is removed if it starts with the generator's header, and otherwise +/// makes the write fail before anything changes. +pub(crate) fn write_game_client( + root: &std::path::Path, + files: &[GeneratedClientFile], +) -> Result<(), Box> { + game_client_dir(root).write(files, |_, contents| { + Ok(contents.starts_with("// @generated by `distributed game-client`")) + }) +} + +/// Fail unless `root` holds exactly the generated files. Reads only. +pub(crate) fn check_game_client( + root: &std::path::Path, + files: &[GeneratedClientFile], +) -> Result<(), Box> { + let drift = game_client_dir(root).drift(files)?; + if drift.is_empty() { + return Ok(()); + } + Err(format!( + "generated game client at {} is stale:\n {}\nrun `distributed game-client` without --check to regenerate", + root.display(), + drift.join("\n ") + ) + .into()) +} + +fn file(path: &str, contents: String) -> GeneratedClientFile { + GeneratedClientFile { + path: path.to_string(), + contents, + } +} + +impl<'a> Gen<'a> { + fn new(surface: &'a GameSurface, ext: ImportExtension) -> GenResult { + surface.validate()?; + let gen = Self { + surface, + records: surface + .records + .iter() + .map(|record| (record.name.as_str(), record)) + .collect(), + ext, + }; + gen.check_names()?; + Ok(gen) + } + + /// TypeScript naming on top of [`GameSurface::validate`]: names that + /// are distinct in Rust must stay distinct (and usable) after case + /// conversion, and constants must have a literal of their type. + fn check_names(&self) -> GenResult<()> { + for record in &self.surface.records { + if !is_identifier(&record.name) { + return Err(format!( + "record name {:?} is not an identifier", + record.name + )); + } + check_field_names(&record.fields, &record.name)?; + } + let mut kind_names = BTreeSet::new(); + for kind in &self.surface.kinds { + if pascal(&kind.name).is_empty() || !kind_names.insert(pascal(&kind.name)) { + return Err(format!("duplicate or empty kind name {:?}", kind.name)); + } + let mut props = BTreeSet::new(); + for field in &kind.fields { + if !props.insert(camel(&field.name)) { + return Err(format!( + "kind {} fields collide as `{}`", + kind.name, + camel(&field.name) + )); + } + } + } + let mut event_names = BTreeSet::new(); + for event in &self.surface.events { + if !event_names.insert(camel(&event.name)) { + return Err(format!("duplicate event {} / {}", event.id, event.name)); + } + if let EventPayload::Fields { fields } = &event.payload { + check_field_names(fields, &event.name)?; + } + } + if let Some(input) = &self.surface.input { + check_field_names(&input.fields, &input.name)?; + let mut buttons = BTreeSet::new(); + for b in input.fields.iter().flat_map(|field| &field.buttons) { + if !buttons.insert(camel(b)) { + return Err(format!("duplicate input button {b}")); + } + } + } + let mut wrappers = BTreeSet::new(); + for pure in &self.surface.pures { + if !wrappers.insert(camel(&pure.export)) { + return Err(format!("duplicate pure function {}", pure.export)); + } + if matches!(camel(&pure.export).as_str(), "ready" | "loaded" | "module") { + return Err(format!( + "pure function name {} is reserved by the generated handle", + pure.export + )); + } + } + for constant in &self.surface.constants { + self.literal(&constant.ty, &constant.value, 0) + .map_err(|e| format!("constant {}: {e}", constant.name))?; + } + self.check_exports() + } + + /// Every name the generated modules export, so `index.ts` re-exports + /// cannot collide. + fn check_exports(&self) -> GenResult<()> { + let prefix = pascal(&self.surface.name); + let mut names: Vec = [ + "KIND", + "KindName", + "FIELD_TYPES", + "CORRECTIONS", + "Input", + "EVENT", + "Events", + "EVENTS", + "AnyEvent", + "decodeEvent", + "onEvent", + ] + .iter() + .map(|s| s.to_string()) + .collect(); + names.push(format!("create{prefix}Client")); + names.push(format!("{prefix}Client")); + names.push(format!("{prefix}ClientOptions")); + names.push(format!("{prefix}PredictionOptions")); + for kind in &self.surface.kinds { + names.push(format!("{}Fields", pascal(&kind.name))); + names.push(format!("is{}", pascal(&kind.name))); + names.push(format!("{}Fields", camel(&kind.name))); + } + if let Some(input) = &self.surface.input { + names.extend( + [ + "BUTTON", + "INPUT_LAYOUT", + "encodeInput", + "decodeInput", + "sanitizeInput", + ] + .map(String::from), + ); + names.push(input.name.clone()); + } + for record in &self.surface.records { + names.push(record.name.clone()); + } + for event in &self.surface.events { + names.push(format!("{}Event", pascal(&event.name))); + } + if !self.surface.pures.is_empty() { + names.extend(["PURES", "PURES_WASM_URL"].map(String::from)); + names.push(format!("create{prefix}Pures")); + names.push(format!("{prefix}Pures")); + names.push(format!("{prefix}PureFns")); + } + for c in &self.surface.constants { + names.push(constant(&c.name)); + } + for codec in &self.surface.codecs { + names.push(format!("encode{codec}")); + names.push(format!("decode{codec}")); + } + if self.surface.predict.is_some() { + names.extend( + [ + "PREDICT", + "PREDICT_STATE", + "PREDICT_CONTEXT", + "PREDICT_WASM_URL", + "PredictContext", + ] + .map(String::from), + ); + names.push(format!("create{prefix}Prediction")); + names.push(format!("{prefix}Prediction")); + } + let mut seen = BTreeSet::new(); + for name in names { + if !seen.insert(name.clone()) { + return Err(format!( + "generated export `{name}` would be declared twice; rename the record, input, kind or event" + )); + } + } + Ok(()) + } + + fn header(&self, what: &str) -> String { + format!( + "// @generated by `distributed game-client` from game surface `{}` (schema v{}, protocol v{}).\n// {what}\n// Do not edit: change the Rust definitions and regenerate.\n", + self.surface.name, + self.surface.schema_version, + self.surface.protocol_version + ) + } + + fn local(&self, module: &str) -> String { + format!("./{module}{}", self.ext.suffix()) + } + + fn ts_type(&self, ty: &WireType) -> String { + match ty { + WireType::Bool => "boolean".into(), + WireType::ShortStr | WireType::Str => "string".into(), + WireType::Bytes => "Uint8Array".into(), + WireType::List { item } => { + let inner = self.ts_type(item); + if inner.contains(' ') { + format!("readonly ({inner})[]") + } else { + format!("readonly {inner}[]") + } + } + WireType::Optional { item } => format!("{} | undefined", self.ts_type(item)), + WireType::Record { name } => name.clone(), + _ => "number".into(), + } + } + + /// A `WireType` literal; records refer to their `*_TYPE` constants. + fn wire_literal(&self, ty: &WireType) -> String { + match ty { + WireType::Quant { min, max, bits } => format!( + "{{ type: 'quant', min: {}, max: {}, bits: {bits} }}", + f32_exact(*min), + f32_exact(*max) + ), + WireType::Angle { bits } => format!("{{ type: 'angle', bits: {bits} }}"), + WireType::List { item } => { + format!("{{ type: 'list', item: {} }}", self.wire_literal(item)) + } + WireType::Optional { item } => { + format!("{{ type: 'optional', item: {} }}", self.wire_literal(item)) + } + WireType::Record { name } => format!("{}_TYPE", constant(name)), + other => format!("{{ type: '{}' }}", simple_tag(other)), + } + } + + fn layout(&self, fields: &[PayloadField]) -> String { + if fields.is_empty() { + return "[]".into(); + } + let mut out = String::from("[\n"); + for field in fields { + let _ = writeln!( + out, + "\t[{}, {}],", + string(&camel(&field.name)), + self.wire_literal(&field.ty) + ); + } + out.push(']'); + out + } + + fn interface(&self, name: &str, doc: &str, fields: &[PayloadField]) -> String { + let mut out = format!("/** {doc} */\nexport interface {name} {{\n"); + for field in fields { + let _ = writeln!( + out, + "\treadonly {}: {};", + key(&camel(&field.name)), + self.ts_type(&field.ty) + ); + } + out.push_str("}\n"); + out + } + + fn schema_ts(&self) -> GenResult { + let kinds = &self.surface.kinds; + let mut readers = BTreeSet::new(); + for kind in kinds { + for field in &kind.fields { + readers.insert(reader(&field.ty)); + } + } + let mut imports: Vec = readers.into_iter().map(str::to_string).collect(); + imports.push("type CorrectionPolicies".into()); + imports.push("type EntityFields".into()); + imports.push("type WireType".into()); + let mut out = + self.header("Replicated kinds: ids, typed fields, wire types, correction defaults."); + let _ = writeln!(out, "import {{ {} }} from '{SDK}';\n", imports.join(", ")); + + out.push_str("/** Replicated kind ids by name. */\nexport const KIND = {\n"); + for kind in kinds { + let _ = writeln!(out, "\t{}: {},", key(&camel(&kind.name)), kind.id); + } + out.push_str("} as const;\n\nexport type KindName = keyof typeof KIND;\n"); + + for kind in kinds { + let pascal_name = pascal(&kind.name); + let camel_name = camel(&kind.name); + let _ = write!( + out, + "\n/** `{}` (kind {}, priority {}). */\nexport interface {pascal_name}Fields {{\n", + kind.name, + kind.id, + f32_literal(kind.priority) + ); + for field in &kind.fields { + let doc = field_doc(&field.ty, field.priority); + let _ = writeln!( + out, + "\t/** {doc} */\n\treadonly {}: {};", + key(&camel(&field.name)), + self.ts_type(&field.ty) + ); + } + out.push_str("}\n\n"); + let _ = writeln!( + out, + "/** True for a `{}` entity. */\nexport function is{pascal_name}(entity: {{ readonly kind: number }}): boolean {{\n\treturn entity.kind === {};\n}}\n", + kind.name, kind.id + ); + let _ = writeln!( + out, + "/** Typed fields of a `{}` entity (rendered or replica). */\nexport function {camel_name}Fields(entity: {{ readonly fields: EntityFields }}): {pascal_name}Fields {{\n\tconst f = entity.fields;\n\treturn {{", + kind.name + ); + for field in &kind.fields { + let _ = writeln!( + out, + "\t\t{}: {}(f, {}),", + key(&camel(&field.name)), + reader(&field.ty), + string(&field.name) + ); + } + out.push_str("\t};\n}\n"); + } + + out.push_str("\n/** Wire type of every replicated field, by kind and wire field name. */\nexport const FIELD_TYPES = {\n"); + for kind in kinds { + let _ = writeln!(out, "\t{}: {{", key(&camel(&kind.name))); + for field in &kind.fields { + let _ = writeln!( + out, + "\t\t{}: {},", + key(&field.name), + self.wire_literal(&field.ty) + ); + } + out.push_str("\t},\n"); + } + out.push_str("} as const satisfies Record>;\n"); + + out.push_str("\n/** Client correction defaults (`#[correct(..)]`), by kind and wire field name. */\nexport const CORRECTIONS: CorrectionPolicies = {\n"); + for kind in kinds { + let corrected: Vec<_> = kind + .fields + .iter() + .filter_map(|f| f.correction.as_ref().map(|c| (f, c))) + .collect(); + if corrected.is_empty() { + continue; + } + let _ = writeln!(out, "\t{}: {{", key(&kind.name)); + for (field, correction) in corrected { + let policy = match correction { + Correction::Ease { + duration_ms, + snap_above: None, + } => format!("{{ mode: 'ease', durationMs: {duration_ms} }}"), + Correction::Ease { + duration_ms, + snap_above: Some(above), + } => format!( + "{{ mode: 'ease', durationMs: {duration_ms}, snapAbove: {} }}", + f32_literal(*above) + ), + Correction::Snap => "{ mode: 'snap' }".into(), + Correction::Replace => "{ mode: 'replace' }".into(), + }; + let _ = writeln!(out, "\t\t{}: {policy},", key(&field.name)); + } + out.push_str("\t},\n"); + } + out.push_str("};\n"); + Ok(out) + } + + fn input_ts(&self) -> GenResult { + let mut out = + self.header("Input frame: interface, button bits, encoder, decoder, sanitize."); + let Some(input) = &self.surface.input else { + out.push_str("\n/** This zone takes no typed input. */\nexport type Input = never;\n"); + return Ok(out); + }; + let can_reject = input + .fields + .iter() + .any(|f| matches!(f.ty, WireType::F32 | WireType::F64)); + let _ = writeln!( + out, + "import {{ decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout }} from '{SDK}';\n" + ); + out.push_str(&self.interface( + &input.name, + &format!("One `{}` input frame (`#[derive(GameInput)]`).", input.name), + &input.fields, + )); + let _ = writeln!(out, "\nexport type Input = {};", input.name); + let flag_fields: Vec<&PayloadField> = input + .fields + .iter() + .filter(|f| !f.buttons.is_empty()) + .collect(); + if !flag_fields.is_empty() { + out.push_str("\n/** Bits of each bit-flag field (`#[buttons(..)]`), by field. */\nexport const BITS = {\n"); + for field in &flag_fields { + let _ = writeln!(out, "\t{}: {{", key(&camel(&field.name))); + for (bit, name) in field.buttons.iter().enumerate() { + let _ = writeln!(out, "\t\t{}: {},", key(&camel(name)), 1u32 << bit); + } + out.push_str("\t},\n"); + } + out.push_str("} as const;\n"); + if let [only] = flag_fields.as_slice() { + let _ = writeln!( + out, + "\n/** Bits of `{}`, the only bit-flag field. */\nexport const BUTTON = BITS.{};", + camel(&only.name), + camel(&only.name) + ); + } + } + let _ = writeln!( + out, + "\n/** Wire layout, in field order. */\nexport const INPUT_LAYOUT: PayloadLayout = {};\n", + self.layout(&input.fields) + ); + out.push_str("const INPUT_RULES: readonly InputRule[] = [\n"); + for field in &input.fields { + let rule = if !field.buttons.is_empty() { + let mask: u64 = (1u64 << field.buttons.len()) - 1; + format!("{{ buttons: {mask} }}") + } else if let Some([min, max]) = field.range { + let (min, max) = if matches!( + field.ty, + WireType::U8 + | WireType::I8 + | WireType::U16 + | WireType::I16 + | WireType::U32 + | WireType::I32 + | WireType::U64 + ) { + (min.trunc(), max.trunc()) + } else { + (min, max) + }; + format!("{{ range: [{}, {}] }}", f64_literal(min), f64_literal(max)) + } else { + "undefined".into() + }; + let _ = writeln!(out, "\t{rule},"); + } + out.push_str("];\n\n"); + let name = &input.name; + let _ = writeln!( + out, + "/** Payload bytes of one input frame. */\nexport function encodeInput(input: {name}): Uint8Array {{\n\treturn encodePayload(INPUT_LAYOUT, input);\n}}\n" + ); + let _ = writeln!( + out, + "/** Decode one input frame (no sanitizing). */\nexport function decodeInput(payload: Uint8Array): {name} {{\n\treturn decodePayload(INPUT_LAYOUT, payload) as unknown as {name};\n}}\n" + ); + if can_reject { + let _ = writeln!( + out, + "/**\n * What the zone simulates for `input` (`#[range]` clamps, `#[buttons]` masks,\n * wire precision); `undefined` when the server would drop it (non-finite float).\n */\nexport function sanitizeInput(input: {name}): {name} | undefined {{\n\treturn sanitizePayload(INPUT_LAYOUT, INPUT_RULES, input);\n}}" + ); + } else { + let _ = writeln!( + out, + "/** What the zone simulates for `input` (`#[range]` clamps, `#[buttons]` masks, wire precision). */\nexport function sanitizeInput(input: {name}): {name} {{\n\treturn sanitizePayload(INPUT_LAYOUT, INPUT_RULES, input)!;\n}}" + ); + } + Ok(out) + } + + fn events_ts(&self) -> GenResult { + let mut out = self + .header("Events and records: payload interfaces, ids, codecs, typed subscriptions."); + let events = &self.surface.events; + let records = self.surface.records_in_dependency_order()?; + let mut sdk = vec![ + "decodeGameEvent", + "onGameEvent", + "type DecodedGameEvent", + "type GameEventCodecs", + "type GameEventSource", + ]; + let messages = &self.surface.messages; + let uses_fields = events + .iter() + .chain(messages) + .any(|e| matches!(e.payload, EventPayload::Fields { .. })); + let uses_value = events + .iter() + .chain(messages) + .any(|e| matches!(e.payload, EventPayload::Value { .. })); + if uses_fields { + sdk.extend(["decodePayload", "encodePayload", "type PayloadLayout"]); + } + let has_codecs = !self.surface.codecs.is_empty(); + if uses_value || has_codecs { + sdk.extend(["decodeValue", "encodeValue"]); + } + if uses_value + || has_codecs + || records + .iter() + .any(|r| self.encoded_records().contains(r.name.as_str())) + { + sdk.push("type WireType"); + } + sdk.sort_by_key(|s| (s.starts_with("type "), s.to_string())); + let _ = writeln!(out, "import {{ {} }} from '{SDK}';", sdk.join(", ")); + + let encoded = self.encoded_records(); + for record in &records { + out.push('\n'); + out.push_str(&self.interface( + &record.name, + &format!("Record `{}` (`#[derive(GameRecord)]`).", record.name), + &record.fields, + )); + // Records only the predicted step uses (its state and context) + // are encoded by `predict.ts` layouts, not by an event codec. + if encoded.contains(record.name.as_str()) { + let _ = writeln!( + out, + "\nconst {}_TYPE: WireType = {{\n\ttype: 'record',\n\tfields: {}\n}};", + constant(&record.name), + indent(&self.layout(&record.fields)) + ); + } + } + + for codec in &self.surface.codecs { + let c = constant(codec); + let _ = writeln!( + out, + "\n/** Encode a `{codec}` record (standalone codec, e.g. served over HTTP). */\nexport function encode{codec}(value: {codec}): Uint8Array {{\n\treturn encodeValue({c}_TYPE, value);\n}}\n\n/** Decode a whole `{codec}` record (throws on trailing or missing bytes). */\nexport function decode{codec}(bytes: Uint8Array): {codec} {{\n\treturn decodeValue({c}_TYPE, bytes) as {codec};\n}}" + ); + } + + self.payload_types(&mut out, events, "Event", ""); + if !messages.is_empty() { + self.payload_types(&mut out, messages, "Message", "MESSAGE_"); + } + + out.push_str("\n/** Event type ids by name. */\nexport const EVENT = {\n"); + for event in events { + let _ = writeln!(out, "\t{}: {},", key(&camel(&event.name)), event.id); + } + out.push_str( + "} as const;\n\n/** Event payload types by name. */\nexport interface Events {\n", + ); + for event in events { + let _ = writeln!( + out, + "\t{}: {}Event;", + key(&camel(&event.name)), + pascal(&event.name) + ); + } + out.push_str("}\n\n/** Codecs of every event. */\nexport const EVENTS: GameEventCodecs = {\n"); + for event in events { + let type_name = format!("{}Event", pascal(&event.name)); + let c = constant(&event.name); + let (encode, decode) = match &event.payload { + EventPayload::Fields { .. } => ( + format!("(value) => encodePayload({c}_LAYOUT, value)"), + format!( + "(payload) => decodePayload({c}_LAYOUT, payload) as unknown as {type_name}" + ), + ), + EventPayload::Value { .. } => ( + format!("(value) => encodeValue({c}_PAYLOAD, value)"), + format!("(payload) => decodeValue({c}_PAYLOAD, payload) as {type_name}"), + ), + }; + let _ = writeln!( + out, + "\t{}: {{\n\t\tid: {},\n\t\tname: {},\n\t\tencode: {encode},\n\t\tdecode: {decode}\n\t}},", + key(&camel(&event.name)), + event.id, + string(&event.name) + ); + } + out.push_str("};\n\n"); + out.push_str("/** A decoded event, discriminated by `name`. */\nexport type AnyEvent = DecodedGameEvent;\n\n"); + out.push_str("/** Decode an Event message (`undefined` for ids this surface does not declare). */\nexport function decodeEvent(event: { readonly typeId: number; readonly payload: Uint8Array }): AnyEvent | undefined {\n\treturn decodeGameEvent(EVENTS, event);\n}\n\n"); + out.push_str("/** Subscribe to one typed event on every zone of `client`; returns the unsubscribe. */\nexport function onEvent(\n\tclient: GameEventSource,\n\tname: K,\n\thandler: (value: Events[K], zoneId: string) => void\n): () => void {\n\treturn onGameEvent(client, EVENTS, name, handler);\n}\n"); + if !messages.is_empty() { + self.messages_ts(&mut out, messages); + } + Ok(out) + } + + /// Zone inbox message ids, codecs and `encodeMessage` (the body of a + /// `/admin/zone-message` `message`). + fn messages_ts(&self, out: &mut String, messages: &[EventSurface]) { + out.push_str("\n/** Zone inbox message type ids by name. */\nexport const MESSAGE = {\n"); + for m in messages { + let _ = writeln!(out, "\t{}: {},", key(&camel(&m.name)), m.id); + } + out.push_str("} as const;\n\n/** Zone inbox message payload types by name. */\nexport interface Messages {\n"); + for m in messages { + let _ = writeln!( + out, + "\t{}: {}Message;", + key(&camel(&m.name)), + pascal(&m.name) + ); + } + out.push_str("}\n\n/** Codecs of every zone inbox message. */\nexport const MESSAGES: GameEventCodecs = {\n"); + for m in messages { + let type_name = format!("{}Message", pascal(&m.name)); + let c = format!("MESSAGE_{}", constant(&m.name)); + let (encode, decode) = match &m.payload { + EventPayload::Fields { .. } => ( + format!("(value) => encodePayload({c}_LAYOUT, value)"), + format!( + "(payload) => decodePayload({c}_LAYOUT, payload) as unknown as {type_name}" + ), + ), + EventPayload::Value { .. } => ( + format!("(value) => encodeValue({c}_PAYLOAD, value)"), + format!("(payload) => decodeValue({c}_PAYLOAD, payload) as {type_name}"), + ), + }; + let _ = writeln!( + out, + "\t{}: {{\n\t\tid: {},\n\t\tname: {},\n\t\tencode: {encode},\n\t\tdecode: {decode}\n\t}},", + key(&camel(&m.name)), + m.id, + string(&m.name) + ); + } + out.push_str("};\n\n/** Encode a zone inbox message: `typeId` and `payload` of a `/admin/zone-message` body (base64url the payload). */\nexport function encodeMessage(\n\tname: K,\n\tvalue: Messages[K]\n): { readonly typeId: number; readonly payload: Uint8Array } {\n\tconst codec = MESSAGES[name];\n\treturn { typeId: codec.id, payload: codec.encode(value) };\n}\n"); + } + + /// Payload interfaces and layouts of events (`suffix` `Event`) or zone + /// inbox messages (`Message`, constants prefixed `MESSAGE_`). + fn payload_types(&self, out: &mut String, items: &[EventSurface], suffix: &str, prefix: &str) { + for event in items { + let type_name = format!("{}{suffix}", pascal(&event.name)); + out.push('\n'); + match &event.payload { + EventPayload::Fields { fields } if fields.is_empty() => { + let _ = writeln!( + out, + "/** {suffix} `{}` (id {}): no payload. */\nexport type {type_name} = Readonly>;", + event.name, event.id + ); + let _ = writeln!( + out, + "\nconst {prefix}{}_LAYOUT: PayloadLayout = [];", + constant(&event.name) + ); + } + EventPayload::Fields { fields } => { + out.push_str(&self.interface( + &type_name, + &format!("{suffix} `{}` (id {}).", event.name, event.id), + fields, + )); + let _ = writeln!( + out, + "\nconst {prefix}{}_LAYOUT: PayloadLayout = {};", + constant(&event.name), + self.layout(fields) + ); + } + EventPayload::Value { ty } => { + let _ = writeln!( + out, + "/** {suffix} `{}` (id {}). */\nexport type {type_name} = {};", + event.name, + event.id, + self.ts_type(ty) + ); + let _ = writeln!( + out, + "\nconst {prefix}{}_PAYLOAD: WireType = {};", + constant(&event.name), + self.wire_literal(ty) + ); + } + } + } + } + + /// Records an event payload (or the input) encodes, directly or nested. + fn encoded_records(&self) -> BTreeSet<&'a str> { + fn walk<'r>(ty: &'r WireType, out: &mut Vec<&'r str>) { + match ty { + WireType::List { item } | WireType::Optional { item } => walk(item, out), + WireType::Record { name } => out.push(name), + _ => {} + } + } + let mut pending = Vec::new(); + for event in self.surface.events.iter().chain(&self.surface.messages) { + match &event.payload { + EventPayload::Fields { fields } => { + fields.iter().for_each(|f| walk(&f.ty, &mut pending)) + } + EventPayload::Value { ty } => walk(ty, &mut pending), + } + } + if let Some(input) = &self.surface.input { + input.fields.iter().for_each(|f| walk(&f.ty, &mut pending)); + } + pending.extend(self.surface.codecs.iter().map(String::as_str)); + let mut seen = BTreeSet::new(); + while let Some(name) = pending.pop() { + if seen.insert(name) { + if let Some(record) = self.records.get(name) { + record.fields.iter().for_each(|f| walk(&f.ty, &mut pending)); + } + } + } + seen + } + + fn client_ts(&self) -> String { + let prefix = pascal(&self.surface.name); + let mut out = self.header("Typed client factory."); + let input = self.surface.input.as_ref().map(|i| i.name.as_str()); + match input { + Some(name) if self.surface.predict.is_some() => { + out.push_str(&self.predicted_client_ts(name)); + } + Some(name) => { + let _ = writeln!( + out, + "import {{ GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions }} from '{SDK}';\n\nimport {{ EVENTS, type Events }} from '{}';\nimport {{ encodeInput, type {name} }} from '{}';\nimport {{ CORRECTIONS }} from '{}';\n", + self.local("events"), + self.local("input"), + self.local("schema") + ); + let _ = writeln!( + out, + "/** Prediction options; `encodeInput` and the correction defaults are filled in. */\nexport type {prefix}PredictionOptions = Omit, 'encodeInput'> &\n\tPartial, 'encodeInput'>>;\n\nexport type {prefix}ClientOptions = Omit, 'prediction'> &\n\tReadonly<{{ prediction?: {prefix}PredictionOptions }}>;\n" + ); + let _ = writeln!( + out, + "export type {prefix}Client = Readonly<{{\n\tclient: GameClient<{name}>;\n\t/** Typed event subscription (every zone); returns the unsubscribe. */\n\ton(name: K, handler: (value: Events[K], zoneId: string) => void): () => void;\n\t/** Send one input: predicted when prediction is configured, raw otherwise. */\n\tsend(input: {name}): number | undefined;\n}}>;\n" + ); + let _ = writeln!( + out, + "/** A `GameClient` for the `{surface}` surface with its input encoder and correction defaults. */\nexport function create{prefix}Client(options: {prefix}ClientOptions): {prefix}Client {{\n\tconst prediction = options.prediction;\n\tconst client = new GameClient<{name}>({{\n\t\t...options,\n\t\tprediction:\n\t\t\tprediction === undefined\n\t\t\t\t? undefined\n\t\t\t\t: {{\n\t\t\t\t\t\t...prediction,\n\t\t\t\t\t\tencodeInput: prediction.encodeInput ?? ((input) => encodeInput(input)),\n\t\t\t\t\t\tcorrections: mergeCorrections(CORRECTIONS, prediction.corrections)\n\t\t\t\t\t}}\n\t}});\n\treturn {{\n\t\tclient,\n\t\ton: (name, handler) =>\n\t\t\tclient.on('event', (zoneId, event) => {{\n\t\t\t\tconst codec = EVENTS[name];\n\t\t\t\tif (event.typeId === codec.id) handler(codec.decode(event.payload), zoneId);\n\t\t\t}}),\n\t\tsend: (input) =>\n\t\t\tprediction === undefined ? client.sendRawInput(encodeInput(input)) : client.sendInput(input)\n\t}};\n}}", + surface = self.surface.name + ); + } + None => { + let _ = writeln!( + out, + "import {{ GameClient, type GameClientOptions }} from '{SDK}';\n\nimport {{ EVENTS, type Events }} from '{}';\n", + self.local("events") + ); + let _ = writeln!( + out, + "export type {prefix}ClientOptions = Omit, 'prediction'>;\n\nexport type {prefix}Client = Readonly<{{\n\tclient: GameClient;\n\t/** Typed event subscription (every zone); returns the unsubscribe. */\n\ton(name: K, handler: (value: Events[K], zoneId: string) => void): () => void;\n}}>;\n" + ); + let _ = writeln!( + out, + "/** A `GameClient` for the `{surface}` surface (no typed input). */\nexport function create{prefix}Client(options: {prefix}ClientOptions): {prefix}Client {{\n\tconst client = new GameClient(options);\n\treturn {{\n\t\tclient,\n\t\ton: (name, handler) =>\n\t\t\tclient.on('event', (zoneId, event) => {{\n\t\t\t\tconst codec = EVENTS[name];\n\t\t\t\tif (event.typeId === codec.id) handler(codec.decode(event.payload), zoneId);\n\t\t\t}})\n\t}};\n}}", + surface = self.surface.name + ); + } + } + out + } + + /// `client.ts` of a surface with a `#[predict]` step: prediction defaults + /// to the compiled WebAssembly step. + fn predicted_client_ts(&self, name: &str) -> String { + let prefix = pascal(&self.surface.name); + let mut out = String::new(); + let _ = writeln!( + out, + "import {{ GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions, type WasmSource }} from '{SDK}';\n\nimport {{ EVENTS, type Events }} from '{}';\nimport {{ encodeInput, type {name} }} from '{}';\nimport {{ create{prefix}Prediction, type {prefix}Prediction }} from '{}';\nimport {{ CORRECTIONS }} from '{}';\n", + self.local("events"), + self.local("input"), + self.local("predict"), + self.local("schema") + ); + let _ = writeln!( + out, + "/**\n * Prediction tuning; `encodeInput`, the correction defaults and `predict` (the\n * compiled `#[predict]` step) are filled in. A `predict` given here replaces\n * the WebAssembly step.\n */\nexport type {prefix}PredictionOptions = Omit, 'encodeInput' | 'predict'> &\n\tPartial, 'encodeInput' | 'predict'>>;\n\nexport type {prefix}ClientOptions = Omit, 'prediction'> &\n\tReadonly<{{\n\t\t/** Prediction tuning, or `false` for none. Default: the compiled step. */\n\t\tprediction?: {prefix}PredictionOptions | false;\n\t\t/** Where to load the compiled step from (default `PREDICT_WASM_URL`). */\n\t\twasm?: WasmSource;\n\t}}>;\n" + ); + let _ = writeln!( + out, + "export type {prefix}Client = Readonly<{{\n\tclient: GameClient<{name}>;\n\t/** The compiled step (`ready`, `setContext`); undefined when prediction is off or custom. */\n\tprediction: {prefix}Prediction | undefined;\n\t/** Typed event subscription (every zone); returns the unsubscribe. */\n\ton(name: K, handler: (value: Events[K], zoneId: string) => void): () => void;\n\t/** Send one input: predicted when prediction is on, raw otherwise. */\n\tsend(input: {name}): number | undefined;\n}}>;\n" + ); + let _ = write!( + out, + "/**\n * A `GameClient` for the `{surface}` surface with its input encoder, correction\n * defaults and the compiled predicted step wired in.\n */\nexport function create{prefix}Client(options: {prefix}ClientOptions): {prefix}Client {{\n\tconst {{ prediction: tuning, wasm, ...rest }} = options;\n\tconst prediction =\n\t\ttuning === false || tuning?.predict !== undefined ? undefined : create{prefix}Prediction(wasm);\n\tconst client = new GameClient<{name}>({{\n\t\t...rest,\n\t\tprediction:\n\t\t\ttuning === false\n\t\t\t\t? undefined\n\t\t\t\t: {{\n\t\t\t\t\t\t...tuning,\n\t\t\t\t\t\tpredict: tuning?.predict ?? prediction!.predict,\n\t\t\t\t\t\tencodeInput: tuning?.encodeInput ?? ((input) => encodeInput(input)),\n\t\t\t\t\t\tcorrections: mergeCorrections(CORRECTIONS, tuning?.corrections)\n\t\t\t\t\t}}\n\t}});\n\treturn {{\n\t\tclient,\n\t\tprediction,\n\t\ton: (name, handler) =>\n\t\t\tclient.on('event', (zoneId, event) => {{\n\t\t\t\tconst codec = EVENTS[name];\n\t\t\t\tif (event.typeId === codec.id) handler(codec.decode(event.payload), zoneId);\n\t\t\t}}),\n\t\tsend: (input) =>\n\t\t\ttuning === false ? client.sendRawInput(encodeInput(input)) : client.sendInput(input)\n\t}};\n}}\n", + surface = self.surface.name + ); + out + } + + fn index_ts(&self) -> String { + let mut out = self.header("Everything generated for this surface."); + let mut modules = vec!["client"]; + if !self.surface.constants.is_empty() { + modules.push("constants"); + } + modules.extend(["events", "input"]); + if self.surface.predict.is_some() { + modules.push("predict"); + } + if !self.surface.pures.is_empty() { + modules.push("pures"); + } + modules.push("schema"); + for module in modules { + let _ = writeln!(out, "export * from '{}';", self.local(module)); + } + out + } + + fn predict_ts(&self) -> GenResult> { + let Some(predict) = &self.surface.predict else { + return Ok(None); + }; + let input = self + .surface + .input + .as_ref() + .ok_or("a predicted step needs the zone's input type")?; + let state = self.records[predict.state.as_str()]; + let prefix = pascal(&self.surface.name); + let mut out = self.header( + "Client-predicted step: the Rust `#[predict]` fn compiled to WebAssembly (binary ABI).", + ); + let mut sdk = vec![ + "createWasmPrediction", + "type PredictStateLayout", + "type WasmPrediction", + "type WasmSource", + ]; + if predict.context.is_some() { + sdk.push("type PayloadLayout"); + } + let _ = writeln!(out, "import {{ {} }} from '{SDK}';\n", sdk.join(", ")); + if let Some(context) = &predict.context { + let _ = writeln!( + out, + "import type {{ {context} }} from '{}';", + self.local("events") + ); + } + let _ = writeln!( + out, + "import {{ encodeInput, type {} }} from '{}';\n", + input.name, + self.local("input") + ); + let _ = writeln!( + out, + "/** The predicted step: `#[predict]` fn `{}` of Cargo package `{}`, predicting kind `{}`. */\nexport const PREDICT = {{\n\tkind: {},\n\texport: {},\n\tpackage: {},\n\tstate: {},\n\tabi: {},\n}} as const;\n", + predict.export, + predict.package, + predict.kind, + string(&predict.kind), + string(&predict.export), + string(&predict.package), + string(&predict.state), + predict.abi + ); + let _ = writeln!( + out, + "/** Predicted `{}` fields (record `{}`): wire field name and codec type, in record order. */\nexport const PREDICT_STATE: PredictStateLayout = [", + predict.kind, state.name + ); + for field in &state.fields { + let _ = writeln!( + out, + "\t[{}, {}],", + string(&field.name), + self.wire_literal(&field.ty) + ); + } + out.push_str("];\n\n"); + match &predict.context { + Some(context) => { + let record = self.records[context.as_str()]; + let _ = writeln!( + out, + "/** What the step reads besides state and input (`prediction.setContext`). */\nexport type PredictContext = {context};\n\n/** Layout of the context record `{context}`. */\nexport const PREDICT_CONTEXT: PayloadLayout | undefined = {};\n", + self.layout(&record.fields) + ); + } + None => { + out.push_str("/** The step takes no context. */\nexport type PredictContext = undefined;\n\n/** The step takes no context. */\nexport const PREDICT_CONTEXT = undefined;\n\n"); + } + } + let _ = writeln!( + out, + "/** The compiled step (`distributed game-wasm`); bundlers emit it as an asset. */\nexport const PREDICT_WASM_URL: URL = new URL({}, import.meta.url);\n", + string(&format!("./{}", predict_wasm_path(&self.surface.name))) + ); + let _ = writeln!( + out, + "/** The `{surface}` step as `GameClient` prediction (see `createWasmPrediction`). */\nexport type {prefix}Prediction = WasmPrediction<{input}, PredictContext>;\n", + surface = self.surface.name, + input = input.name + ); + let _ = writeln!( + out, + "/**\n * Load the compiled step (default `PREDICT_WASM_URL`) as prediction: `predict`\n * leaves the state unchanged until `ready` resolves{}.\n */\nexport function create{prefix}Prediction(source: WasmSource = PREDICT_WASM_URL): {prefix}Prediction {{\n\treturn createWasmPrediction<{input}, PredictContext>({{\n\t\tsource,\n\t\texportName: PREDICT.export,\n\t\tstate: PREDICT_STATE,\n\t\tcontext: PREDICT_CONTEXT,\n\t\tencodeInput\n\t}});\n}}", + if predict.context.is_some() { + " and a context is set" + } else { + "" + }, + input = input.name + ); + Ok(Some(out)) + } +} + +impl Gen<'_> { + /// Records reachable from `roots` (nested ones included). + fn reachable<'t>(&self, roots: impl IntoIterator) -> BTreeSet<&str> { + let mut pending = Vec::new(); + for root in roots { + top_records(root, &mut pending); + } + let mut seen = BTreeSet::new(); + while let Some(name) = pending.pop() { + if let Some((name, record)) = self.records.get_key_value(name.as_str()) { + if seen.insert(*name) { + for field in &record.fields { + top_records(&field.ty, &mut pending); + } + } + } + } + seen + } + + /// `const _TYPE: WireType` for `names`, dependencies first. + fn type_consts(&self, names: &BTreeSet<&str>) -> GenResult { + let mut out = String::new(); + for record in self.surface.records_in_dependency_order()? { + if names.contains(record.name.as_str()) { + let _ = writeln!( + out, + "const {}_TYPE: WireType = {{\n\ttype: 'record',\n\tfields: {}\n}};\n", + constant(&record.name), + indent(&self.layout(&record.fields)) + ); + } + } + Ok(out) + } + + /// `import type { A, B } from './events'` for the records `types` + /// mention directly. + fn import_records<'t>(&self, types: impl IntoIterator) -> String { + let mut names = Vec::new(); + for ty in types { + top_records(ty, &mut names); + } + let names: BTreeSet = names.into_iter().collect(); + if names.is_empty() { + return String::new(); + } + format!( + "import type {{ {} }} from '{}';\n", + names.into_iter().collect::>().join(", "), + self.local("events") + ) + } + + fn pures_ts(&self) -> GenResult> { + let pures = &self.surface.pures; + let Some(first) = pures.first() else { + return Ok(None); + }; + let prefix = pascal(&self.surface.name); + let mut out = self.header( + "Pure functions: the Rust `#[game_pure]` fns compiled to WebAssembly (binary ABI).", + ); + let types: Vec<&WireType> = pures + .iter() + .flat_map(|p| p.arg.iter().chain([&p.output])) + .collect(); + let records = self.reachable(types.iter().copied()); + let _ = writeln!( + out, + "import {{ createWasmPures, type WasmPures, type WasmSource{} }} from '{SDK}';\n", + if records.is_empty() && !types.iter().any(|t| !matches!(t, WireType::Record { .. })) { + "" + } else { + ", type WireType" + } + ); + let imports = self.import_records(types.iter().copied()); + if !imports.is_empty() { + out.push_str(&imports); + out.push('\n'); + } + out.push_str(&self.type_consts(&records)?); + let _ = writeln!( + out, + "/** The pure functions (`#[game_pure]`) of Cargo package `{}`: wrapper name → module export. */\nexport const PURES = {{", + first.package + ); + for pure in pures { + let _ = writeln!( + out, + "\t{}: {{ export: {}, abi: {} }},", + key(&camel(&pure.export)), + string(&pure.export), + pure.abi + ); + } + out.push_str("} as const;\n\n"); + let _ = writeln!( + out, + "/** The compiled module (`distributed game-wasm`; shared with the predicted step); bundlers emit it as an asset. */\nexport const PURES_WASM_URL: URL = new URL({}, import.meta.url);\n", + string(&format!("./{}", predict_wasm_path(&self.surface.name))) + ); + let _ = writeln!( + out, + "/** Typed calls of the compiled functions (synchronous; they throw until `ready` resolves). */\nexport interface {prefix}PureFns {{" + ); + for pure in pures { + let signature = match &pure.arg { + Some(arg) => format!("arg: {}", self.ts_type(arg)), + None => String::new(), + }; + let _ = writeln!( + out, + "\t/** `{}` (`dg_pure_{}`). */\n\t{}({signature}): {};", + pure.export, + pure.export, + camel(&pure.export), + self.ts_type(&pure.output) + ); + } + out.push_str("}\n\n"); + let _ = writeln!( + out, + "/** The `{surface}` pure functions plus `ready` / `loaded()` / `module()`. */\nexport type {prefix}Pures = WasmPures<{prefix}PureFns>;\n", + surface = self.surface.name + ); + let _ = writeln!( + out, + "/**\n * Load the compiled pure functions (default `PURES_WASM_URL`; a URL loaded by\n * the predicted step too is instantiated once).\n */\nexport function create{prefix}Pures(source: WasmSource = PURES_WASM_URL): {prefix}Pures {{\n\treturn createWasmPures<{prefix}PureFns>(source, {{" + ); + for pure in pures { + let arg = match &pure.arg { + Some(arg) => format!(", arg: {}", self.wire_literal(arg)), + None => String::new(), + }; + let _ = writeln!( + out, + "\t\t{}: {{ exportName: {}{arg}, output: {} }},", + key(&camel(&pure.export)), + string(&pure.export), + self.wire_literal(&pure.output) + ); + } + out.push_str("\t});\n}\n"); + Ok(Some(out)) + } + + fn constants_ts(&self) -> GenResult> { + let constants = &self.surface.constants; + if constants.is_empty() { + return Ok(None); + } + let mut out = + self.header("Constants: static data defined once in Rust (`GameSurface::constant`)."); + let imports = self.import_records(constants.iter().map(|c| &c.ty)); + if !imports.is_empty() { + out.push_str(&imports); + } + for c in constants { + let _ = writeln!( + out, + "\n/** `{}`, as the client decodes it. */\nexport const {}: {} = {};", + c.name, + constant(&c.name), + self.ts_type(&c.ty), + self.literal(&c.ty, &c.value, 0) + .map_err(|e| format!("constant {}: {e}", c.name))? + ); + } + Ok(Some(out)) + } + + /// A TypeScript literal of `value` (JSON as `GameSurface::constant` + /// stores it) of type `ty`: records keyed by camelCase field name, floats + /// as exact binary32 values, `null` as `undefined`. + fn literal(&self, ty: &WireType, value: &serde_json::Value, depth: usize) -> GenResult { + use serde_json::Value; + let pad = "\t".repeat(depth + 1); + let close = "\t".repeat(depth); + let mismatch = || format!("value {value} does not match {}", self.ts_type(ty)); + let int = |min: i128, max: i128| -> GenResult { + let v = value + .as_i64() + .map(i128::from) + .or(value.as_u64().map(i128::from)) + .ok_or_else(mismatch)?; + if v < min || v > max { + return Err(format!("{v} is out of range")); + } + Ok(v.to_string()) + }; + Ok(match ty { + WireType::Bool => value.as_bool().ok_or_else(mismatch)?.to_string(), + WireType::U8 => int(0, 255)?, + WireType::I8 => int(-128, 127)?, + WireType::U16 => int(0, 65_535)?, + WireType::I16 => int(-32_768, 32_767)?, + WireType::U32 => int(0, u32::MAX.into())?, + WireType::I32 => int(i32::MIN.into(), i32::MAX.into())?, + WireType::U64 => int(0, (1 << 53) - 1)?, + WireType::F32 | WireType::Quant { .. } | WireType::Angle { .. } => { + let v = value.as_f64().ok_or_else(mismatch)?; + if f64::from(v as f32) != v { + return Err(format!("{v} is not a binary32 value")); + } + f32_exact(v as f32) + } + WireType::F64 => f64_literal(value.as_f64().ok_or_else(mismatch)?), + WireType::ShortStr | WireType::Str => string(value.as_str().ok_or_else(mismatch)?), + WireType::Bytes => { + let bytes = value.as_array().ok_or_else(mismatch)?; + let mut items = Vec::new(); + for b in bytes { + items.push(self.literal(&WireType::U8, b, depth)?); + } + format!("new Uint8Array([{}])", items.join(", ")) + } + WireType::Optional { item } => match value { + Value::Null => "undefined".into(), + other => self.literal(item, other, depth)?, + }, + WireType::List { item } => { + let items = value.as_array().ok_or_else(mismatch)?; + if items.is_empty() { + return Ok("[]".into()); + } + let parts = items + .iter() + .map(|v| self.literal(item, v, depth + 1)) + .collect::>>()?; + let inline = format!("[{}]", parts.join(", ")); + if is_scalar(item) && inline.len() <= 100 { + inline + } else { + format!("[\n{pad}{}\n{close}]", parts.join(&format!(",\n{pad}"))) + } + } + WireType::Record { name } => { + let record = self.records[name.as_str()]; + let object = value.as_object().ok_or_else(mismatch)?; + if object.len() != record.fields.len() { + return Err(format!( + "record {name} value has fields {:?}", + object.keys().collect::>() + )); + } + let mut parts = Vec::new(); + let mut simple = true; + for field in &record.fields { + let v = object + .get(&field.name) + .ok_or_else(|| format!("record {name} value lacks field {}", field.name))?; + simple &= is_scalar(&field.ty); + parts.push(format!( + "{}: {}", + key(&camel(&field.name)), + self.literal(&field.ty, v, depth + 1)? + )); + } + let inline = format!("{{ {} }}", parts.join(", ")); + if simple && inline.len() <= 100 { + inline + } else { + format!("{{\n{pad}{}\n{close}}}", parts.join(&format!(",\n{pad}"))) + } + } + }) + } +} + +/// Records a type names directly (through lists and options, not through +/// other records). +fn top_records(ty: &WireType, out: &mut Vec) { + match ty { + WireType::List { item } | WireType::Optional { item } => top_records(item, out), + WireType::Record { name } => out.push(name.clone()), + _ => {} + } +} + +fn is_scalar(ty: &WireType) -> bool { + match ty { + WireType::List { .. } | WireType::Record { .. } | WireType::Bytes => false, + WireType::Optional { item } => is_scalar(item), + _ => true, + } +} + +fn simple_tag(ty: &WireType) -> &'static str { + match ty { + WireType::Bool => "bool", + WireType::U8 => "u8", + WireType::I8 => "i8", + WireType::U16 => "u16", + WireType::I16 => "i16", + WireType::U32 => "u32", + WireType::I32 => "i32", + WireType::U64 => "u64", + WireType::F32 => "f32", + WireType::F64 => "f64", + WireType::ShortStr => "short_str", + WireType::Str => "str", + WireType::Bytes => "bytes", + _ => unreachable!("composite types have their own literal"), + } +} + +fn reader(ty: &WireType) -> &'static str { + match ty { + WireType::Bool => "fieldBool", + WireType::ShortStr => "fieldString", + WireType::Bytes => "fieldBytes", + _ => "fieldNumber", + } +} + +fn field_doc(ty: &WireType, priority: f32) -> String { + let wire = match ty { + WireType::Quant { min, max, bits } => format!( + "quant [{}, {}] / {bits} bits", + f32_literal(*min), + f32_literal(*max) + ), + WireType::Angle { bits } => format!("angle / {bits} bits"), + other => simple_tag(other).to_string(), + }; + if priority == 1.0 { + format!("`{wire}`") + } else { + format!("`{wire}`, priority {}", f32_literal(priority)) + } +} + +fn indent(block: &str) -> String { + block.replace("\n\t", "\n\t\t").replace("\n]", "\n\t]") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_convert() { + assert_eq!(camel("view_radius"), "viewRadius"); + assert_eq!(camel("slowMs"), "slowMs"); + assert_eq!(camel("hp"), "hp"); + assert_eq!(pascal("board_snapshot"), "BoardSnapshot"); + assert_eq!(pascal("player"), "Player"); + assert_eq!(constant("BoardRow"), "BOARD_ROW"); + assert_eq!(constant("slow_ms"), "SLOW_MS"); + assert_eq!(key("type"), "type"); + assert_eq!(key("a-b"), "'a-b'"); + } + + #[test] + fn rejects_other_schema_versions_and_unknown_fields() { + let err = generate_game_client(r#"{"schemaVersion": 1}"#, ImportExtension::Ts).unwrap_err(); + assert!(err.contains("schemaVersion"), "{err}"); + let err = generate_game_client( + r#"{"schemaVersion":3,"name":"x","protocolVersion":1,"kinds":[],"input":null,"events":[],"records":[],"extra":1}"#, + ImportExtension::Ts, + ) + .unwrap_err(); + assert!(err.contains("unknown field"), "{err}"); + } + + fn sample() -> serde_json::Value { + let fixture: serde_json::Value = serde_json::from_str(include_str!( + "../../distributed_game/tests/fixtures/authoring.json" + )) + .unwrap(); + fixture["surface"].clone() + } + + fn generate(surface: &serde_json::Value) -> GenResult> { + generate_game_client(&surface.to_string(), ImportExtension::Ts) + } + + #[test] + fn validates_the_predicted_step() { + let ok = sample(); + let files = generate(&ok).unwrap(); + let predict = files.iter().find(|f| f.path == "predict.ts").unwrap(); + assert!(predict + .contents + .contains("new URL('./wasm/sample.wasm', import.meta.url)")); + assert!(predict.contents.contains("['dead', { type: 'bool' }]")); + + type Mutate = fn(&mut serde_json::Value); + let cases: [(&str, Mutate); 6] = [ + ("ABI v9", |s| s["predict"]["abi"] = 9.into()), + ("not replicated", |s| s["predict"]["kind"] = "ghost".into()), + ("state record Nope is missing", |s| { + s["predict"]["state"] = "Nope".into() + }), + ("context record Nope is missing", |s| { + s["predict"]["context"] = "Nope".into() + }), + ("invalid predicted step export", |s| { + s["predict"]["export"] = "a-b".into() + }), + ("does not match the type", |s| { + let records = s["records"].as_array_mut().unwrap(); + let state = records + .iter_mut() + .find(|r| r["name"] == "SampleState") + .unwrap(); + state["fields"][2]["type"] = serde_json::json!({"type": "u16"}); + }), + ]; + for (expected, mutate) in cases { + let mut surface = ok.clone(); + mutate(&mut surface); + let err = generate(&surface).unwrap_err(); + assert!(err.contains(expected), "{expected}: {err}"); + } + + let mut none = ok.clone(); + none.as_object_mut().unwrap().remove("predict"); + let files = generate(&none).unwrap(); + assert!(files.iter().all(|f| f.path != "predict.ts")); + let client = files.iter().find(|f| f.path == "client.ts").unwrap(); + assert!(!client.contents.contains("Prediction(")); + } + + #[test] + fn validates_pures_constants_and_codecs() { + type Mutate = fn(&mut serde_json::Value); + let cases: [(&str, Mutate); 9] = [ + ("ABI v2", |s| s["pures"][0]["abi"] = 2.into()), + ("module is built from distributed_game", |s| { + s["pures"][1]["package"] = "other".into() + }), + ("reserved", |s| s["pures"][0]["export"] = "ready".into()), + ("duplicate pure function", |s| { + s["pures"][1]["export"] = "sample_mirror".into() + }), + ("unknown record Nope", |s| { + s["pures"][0]["output"] = serde_json::json!({"type": "record", "name": "Nope"}) + }), + ("not a binary32 value", |s| { + s["constants"][1]["value"][0] = 0.1.into() + }), + ("out of range", |s| { + s["constants"][0]["value"]["version"] = (-1).into() + }), + ("lacks field label", |s| { + let spot = s["constants"][2]["value"].as_object_mut().unwrap(); + spot.remove("label"); + spot.insert("other".into(), "x".into()); + }), + ("codec record Nope is missing", |s| { + s["codecs"][0] = "Nope".into() + }), + ]; + for (expected, mutate) in cases { + let mut surface = sample(); + mutate(&mut surface); + let err = generate(&surface).unwrap_err(); + assert!(err.contains(expected), "{expected}: {err}"); + } + // Without pures, constants or codecs: no extra files or functions. + let mut plain = sample(); + for key in ["pures", "constants", "codecs"] { + plain.as_object_mut().unwrap().remove(key); + } + let files = generate(&plain).unwrap(); + assert!(files + .iter() + .all(|f| f.path != "pures.ts" && f.path != "constants.ts")); + let events = files.iter().find(|f| f.path == "events.ts").unwrap(); + assert!(!events.contents.contains("decodeSampleWind")); + // The module plan lists the step and every pure function. + let (name, plan) = surface_module(&sample().to_string()).unwrap(); + let plan = plan.unwrap(); + assert_eq!(name, "sample"); + assert_eq!( + plan.exports, + [ + "dg_predict_sample_step", + "dg_pure_sample_mirror", + "dg_pure_sample_rows" + ] + ); + plain.as_object_mut().unwrap().remove("predict"); + assert!(surface_module(&plain.to_string()).unwrap().1.is_none()); + } + + #[test] + fn rejects_recursive_records() { + let json = r#"{"schemaVersion":3,"name":"x","protocolVersion":1,"kinds":[],"input":null,"events":[], + "records":[{"name":"Node","fields":[{"name":"next","type":{"type":"optional","item":{"type":"record","name":"Node"}}}]}]}"#; + let err = generate_game_client(json, ImportExtension::Ts).unwrap_err(); + assert!(err.contains("recursive"), "{err}"); + } +} diff --git a/distributed_cli/src/game_wasm.rs b/distributed_cli/src/game_wasm.rs new file mode 100644 index 000000000..5bd7a8daf --- /dev/null +++ b/distributed_cli/src/game_wasm.rs @@ -0,0 +1,401 @@ +//! `distributed game-wasm`: compile a zone's client-predicted step +//! (`#[predict]`) and pure functions (`#[game_pure]`), recorded in its +//! `GameSurface`, to one WebAssembly module next to the generated client. +//! +//! The surface names the Cargo package that declares them. The command +//! builds that package's library as a `cdylib` for `wasm32-unknown-unknown` +//! (`cargo rustc --release`), checks the module speaks the ABI (no imports; +//! exports `memory`, `dg_predict_buffer`, `dg_predict_abi`, the step's +//! `dg_predict_` and every `dg_pure_`) and writes it to +//! `/wasm/.wasm`, which the generated `predict.ts` and +//! `pures.ts` load. No wasm-bindgen glue, no JSON: the SDK instantiates the +//! module directly. +//! +//! A stamp next to the module (`.stamp.json`) records the source +//! fingerprint of the package and its local dependencies (the same one the +//! browser WASM pures use), the compiler and the module's hash, so an +//! unchanged step is not rebuilt and `--check` can verify a build is current +//! without compiling. + +use std::error::Error; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use crate::game_client::{predict_wasm_path, surface_module}; +use crate::wasm_pures::{cargo_metadata, ensure_real_directory_path, package_source_identity}; + +const TARGET: &str = "wasm32-unknown-unknown"; +const STAMP_VERSION: u32 = 2; +const MAX_MODULE_BYTES: u64 = 64 * 1024 * 1024; + +/// What to build. +pub(crate) struct GameWasmOptions<'a> { + /// Surface JSON text. + pub(crate) surface: &'a str, + /// Cargo.toml of the project containing the declaring package. + pub(crate) cargo_manifest: &'a Path, + /// Generated client directory. + pub(crate) out: &'a Path, + /// Verify only. + pub(crate) check: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Stamp { + version: u32, + package: String, + exports: Vec, + abi: u32, + source_identity: String, + compiler_identity: String, + module_sha256: String, +} + +/// Outcome of a run. +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum GameWasmOutcome { + /// The module on disk matches the sources. + Current(PathBuf), + /// The module was (re)built. + Built(PathBuf), +} + +pub(crate) fn run_game_wasm( + options: &GameWasmOptions<'_>, +) -> Result> { + let (surface, plan) = surface_module(options.surface)?; + let plan = plan.ok_or_else(|| { + format!( + "game surface `{surface}` declares nothing to compile; add `.predict::()` (a `#[predict]` fn) or `.pure::()` (a `#[game_pure]` fn) to its GameSurface" + ) + })?; + let metadata = cargo_metadata(options.cargo_manifest)?; + let mut candidates = metadata + .packages + .iter() + .filter(|p| p.name == plan.package && p.source.is_none()); + let package = candidates.next().ok_or_else(|| { + format!( + "the WebAssembly functions of game surface `{surface}` are declared by Cargo package `{}`, which is not a local package of {}", + plan.package, + options.cargo_manifest.display() + ) + })?; + if candidates.next().is_some() { + return Err(format!( + "more than one local Cargo package is named `{}`", + plan.package + ) + .into()); + } + let lib = package + .targets + .iter() + .find(|t| { + t.kind + .iter() + .any(|k| matches!(k.as_str(), "lib" | "rlib" | "cdylib")) + }) + .ok_or_else(|| format!("Cargo package `{}` has no library target", package.name))?; + let lib_name = lib.name.replace('-', "_"); + + let module_rel = predict_wasm_path(&surface); + let module_path = options.out.join(&module_rel); + let stamp_path = module_path.with_extension("stamp.json"); + let mut expected = Stamp { + version: STAMP_VERSION, + package: plan.package.clone(), + exports: plan.exports.clone(), + abi: plan.abi, + source_identity: package_source_identity(&metadata, &package.id)?, + compiler_identity: compiler_identity()?, + module_sha256: String::new(), + }; + if stamp_is_current(&stamp_path, &module_path, &expected)? { + return Ok(GameWasmOutcome::Current(module_path)); + } + if options.check { + return Err(format!( + "compiled module {} is missing or stale; run `distributed game-wasm` without --check", + module_path.display() + ) + .into()); + } + + eprintln!( + "distributed: compiling {} (Cargo package {}) to WebAssembly", + plan.exports.join(", "), + plan.package + ); + let status = Command::new(std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into())) + .arg("rustc") + .arg("--manifest-path") + .arg(options.cargo_manifest) + .args([ + "-p", + &plan.package, + "--lib", + "--release", + "--target", + TARGET, + ]) + .args(["--crate-type", "cdylib"]) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::inherit()) + .status() + .map_err(|error| format!("failed to run cargo for the WebAssembly module: {error}"))?; + if !status.success() { + return Err(format!( + "compiling Cargo package `{}` for {TARGET} failed ({status}); is the target installed (`rustup target add {TARGET}`)?", + plan.package + ) + .into()); + } + let artifact = metadata + .target_directory + .join(TARGET) + .join("release") + .join(format!("{lib_name}.wasm")); + let size = fs::metadata(&artifact) + .map_err(|error| format!("cargo produced no {}: {error}", artifact.display()))? + .len(); + if size > MAX_MODULE_BYTES { + return Err(format!( + "{} is larger than {MAX_MODULE_BYTES} bytes", + artifact.display() + ) + .into()); + } + let module = fs::read(&artifact)?; + check_module(&module, &plan.exports) + .map_err(|error| format!("{}: {error}", artifact.display()))?; + expected.module_sha256 = format!("{:x}", Sha256::digest(&module)); + + let wasm_dir = module_path.parent().expect("module path has a directory"); + fs::create_dir_all(options.out)?; + let out_root = options.out.canonicalize()?; + ensure_real_directory_path(&out_root, &out_root.join("wasm"))?; + let staged = wasm_dir.join(format!(".{surface}.wasm.tmp")); + fs::write(&staged, &module)?; + fs::rename(&staged, &module_path)?; + fs::write(&stamp_path, serde_json::to_string_pretty(&expected)? + "\n")?; + Ok(GameWasmOutcome::Built(module_path)) +} + +fn stamp_is_current( + stamp_path: &Path, + module_path: &Path, + expected: &Stamp, +) -> Result> { + let Ok(text) = fs::read_to_string(stamp_path) else { + return Ok(false); + }; + let Ok(stamp) = serde_json::from_str::(&text) else { + return Ok(false); + }; + let Ok(module) = fs::read(module_path) else { + return Ok(false); + }; + let actual = format!("{:x}", Sha256::digest(&module)); + Ok(stamp.module_sha256 == actual + && Stamp { + module_sha256: actual, + ..expected.clone() + } == stamp) +} + +/// `rustc -vV` (the toolchain cargo will use, including rustup overrides). +fn compiler_identity() -> Result> { + let rustc = std::env::var_os("RUSTC").unwrap_or_else(|| "rustc".into()); + let output = Command::new(rustc) + .arg("-vV") + .output() + .map_err(|error| format!("failed to run `rustc -vV`: {error}"))?; + if !output.status.success() { + return Err("`rustc -vV` failed".into()); + } + Ok(format!("sha256:{:x}", Sha256::digest(&output.stdout))) +} + +/// The module imports nothing and exports the ABI plus every function in +/// `functions` (`dg_predict_`, `dg_pure_`). +pub(crate) fn check_module(module: &[u8], functions: &[String]) -> Result<(), String> { + let sections = wasm_sections(module)?; + let mut exports = Vec::new(); + for (id, body) in sections { + match id { + 2 => { + let mut r = WasmReader::new(body); + if r.u32()? != 0 { + return Err("the module imports functions or memory; compiled game functions must be self-contained (no wasm-bindgen, no host calls)".into()); + } + } + 7 => { + let mut r = WasmReader::new(body); + for _ in 0..r.u32()? { + let name = r.name()?; + let kind = r.byte()?; + let _index = r.u32()?; + exports.push((name, kind)); + } + } + _ => {} + } + } + let required = [ + ("memory", 2u8), + ("dg_predict_buffer", 0), + ("dg_predict_abi", 0), + ] + .into_iter() + .chain(functions.iter().map(|f| (f.as_str(), 0))); + for (name, kind) in required { + if !exports.iter().any(|(n, k)| n == name && *k == kind) { + return Err(format!( + "the module does not export `{name}` (is it declared with `#[predict]` / `#[game_pure]` in this package?)" + )); + } + } + Ok(()) +} + +fn wasm_sections(module: &[u8]) -> Result, String> { + if module.len() < 8 || &module[..4] != b"\0asm" || module[4..8] != [1, 0, 0, 0] { + return Err("not a WebAssembly v1 module".into()); + } + let mut r = WasmReader::new(&module[8..]); + let mut sections = Vec::new(); + while !r.done() { + let id = r.byte()?; + let len = r.u32()? as usize; + sections.push((id, r.take(len)?)); + } + Ok(sections) +} + +struct WasmReader<'a> { + bytes: &'a [u8], + at: usize, +} + +impl<'a> WasmReader<'a> { + fn new(bytes: &'a [u8]) -> Self { + Self { bytes, at: 0 } + } + + fn done(&self) -> bool { + self.at >= self.bytes.len() + } + + fn byte(&mut self) -> Result { + let b = *self.bytes.get(self.at).ok_or("truncated module")?; + self.at += 1; + Ok(b) + } + + fn u32(&mut self) -> Result { + let mut value = 0u32; + for shift in (0..35).step_by(7) { + let b = self.byte()?; + value |= u32::from(b & 0x7f) << shift; + if b & 0x80 == 0 { + return Ok(value); + } + } + Err("malformed LEB128".into()) + } + + fn take(&mut self, len: usize) -> Result<&'a [u8], String> { + let end = self.at.checked_add(len).filter(|e| *e <= self.bytes.len()); + let end = end.ok_or("truncated section")?; + let out = &self.bytes[self.at..end]; + self.at = end; + Ok(out) + } + + fn name(&mut self) -> Result { + let len = self.u32()? as usize; + String::from_utf8(self.take(len)?.to_vec()).map_err(|_| "export name is not UTF-8".into()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn leb(mut v: u32, out: &mut Vec) { + loop { + let b = (v & 0x7f) as u8; + v >>= 7; + if v == 0 { + out.push(b); + return; + } + out.push(b | 0x80); + } + } + + fn module(imports: u32, exports: &[(&str, u8)]) -> Vec { + let mut out = b"\0asm\x01\0\0\0".to_vec(); + let mut body = Vec::new(); + leb(imports, &mut body); + out.push(2); + leb(body.len() as u32, &mut out); + out.extend(&body); + let mut body = Vec::new(); + leb(exports.len() as u32, &mut body); + for (name, kind) in exports { + leb(name.len() as u32, &mut body); + body.extend(name.as_bytes()); + body.push(*kind); + leb(0, &mut body); + } + out.push(7); + leb(body.len() as u32, &mut out); + out.extend(&body); + out + } + + const ABI: [(&str, u8); 4] = [ + ("memory", 2), + ("dg_predict_buffer", 0), + ("dg_predict_abi", 0), + ("dg_predict_arena_step", 0), + ]; + + fn names(names: &[&str]) -> Vec { + names.iter().map(|n| n.to_string()).collect() + } + + #[test] + fn accepts_a_self_contained_module_with_the_abi() { + check_module(&module(0, &ABI), &names(&["dg_predict_arena_step"])).unwrap(); + let mut with_pure = ABI.to_vec(); + with_pure.push(("dg_pure_grid_cell", 0)); + check_module( + &module(0, &with_pure), + &names(&["dg_predict_arena_step", "dg_pure_grid_cell"]), + ) + .unwrap(); + } + + #[test] + fn rejects_imports_missing_exports_and_garbage() { + let step = names(&["dg_predict_arena_step"]); + let error = check_module(&module(1, &ABI), &step).unwrap_err(); + assert!(error.contains("imports"), "{error}"); + let error = check_module(&module(0, &ABI), &names(&["dg_predict_grid_step"])).unwrap_err(); + assert!(error.contains("dg_predict_grid_step"), "{error}"); + let error = check_module(&module(0, &ABI), &names(&["dg_pure_grid_cell"])).unwrap_err(); + assert!(error.contains("dg_pure_grid_cell"), "{error}"); + assert!(check_module(b"nope", &step).is_err()); + let mut truncated = module(0, &ABI); + truncated.truncate(truncated.len() - 3); + assert!(check_module(&truncated, &step).is_err()); + } +} diff --git a/distributed_cli/src/generate/mod.rs b/distributed_cli/src/generate/mod.rs index 7938491bf..65eec044a 100644 --- a/distributed_cli/src/generate/mod.rs +++ b/distributed_cli/src/generate/mod.rs @@ -126,7 +126,7 @@ impl Scaffold { files.push(file("src/main.rs", self.main_rs())); files.push(file("src/manifest.rs", self.manifest_rs())); files.push(file("src/service.rs", self.service_rs())); - if !self.models.is_empty() || (self.query_api && !self.commands.is_empty()) { + if !self.models.is_empty() || !self.commands.is_empty() { files.push(file("src/models/mod.rs", self.models_mod_rs())); for model in &self.models { files.push(file( @@ -254,12 +254,15 @@ mod tests { let project = generate_service_scaffold(spec("orders")).unwrap(); let service = contents(&project, "src/service.rs"); assert!( - service.contains("distributed::routes!("), - "service.rs should register handlers with routes!:\n{service}" + service.contains(".typed_command(handlers::") + && service.contains( + "AggregateRepository::<_, crate::models::CommandAggregate>::new(repo.clone())" + ), + "service.rs should register typed commands on a route bundle:\n{service}" ); assert!( - service.contains("Routes::new().with_dependencies(repo)"), - "service.rs should build a typed route bundle:\n{service}" + !service.contains("command handlers::"), + "commands are not registered through routes!:\n{service}" ); assert!( service.contains(".with_http_command_routes()"), @@ -270,6 +273,41 @@ mod tests { assert!(!service.contains("register_handlers!")); } + #[test] + fn knative_commands_declare_the_transport_role_and_events_use_routes() { + let mut s = spec("orders"); + s.transport = ServiceTransport::Knative; + s.commands = vec!["orders.create".to_string()]; + s.events = vec!["orders.shipped".to_string()]; + let project = generate_service_scaffold(s).unwrap(); + let service = contents(&project, "src/service.rs"); + assert!( + service.contains("distributed::routes!(") + && service.contains("Routes::new().with_dependencies(repo.clone())") + && service.contains("event handlers::"), + "event handlers register through routes!:\n{service}" + ); + assert!( + !service.contains(".with_http_command_routes()"), + "a Knative service takes its commands from triggers:\n{service}" + ); + let command = project + .files + .iter() + .find(|file| { + file.contents + .contains("pub const COMMAND: &str = \"orders.create\";") + }) + .expect("the command handler is generated"); + assert!( + command + .contents + .contains(r#".roles(["user", TRANSPORT_ROLE])"#), + "a trigger-delivered command must declare the transport role:\n{}", + command.contents + ); + } + #[test] fn cargo_features_track_transport_and_store() { let mut s = spec("orders"); diff --git a/distributed_cli/src/generate/service_crate.rs b/distributed_cli/src/generate/service_crate.rs index 77521fe5b..1e5f2efbd 100644 --- a/distributed_cli/src/generate/service_crate.rs +++ b/distributed_cli/src/generate/service_crate.rs @@ -62,7 +62,7 @@ tokio = {{ version = "1", features = ["macros", "net", "rt-multi-thread"] }} let mut features = Vec::new(); match self.transport { ServiceTransport::Http => features.push("http"), - ServiceTransport::Knative => features.push("http"), + ServiceTransport::Knative => features.push("knative"), } match self.store { StoreTarget::Postgres => features.push("postgres"), @@ -82,7 +82,7 @@ tokio = {{ version = "1", features = ["macros", "net", "rt-multi-thread"] }} } pub(super) fn lib_rs(&self) -> String { - let models = if !self.models.is_empty() || (self.query_api && !self.commands.is_empty()) { + let models = if !self.models.is_empty() || !self.commands.is_empty() { "pub mod models;\n" } else { "" @@ -213,7 +213,7 @@ async fn main() -> Result<(), {error_type}> {{ .map(|model| format!(" .read_model::<{}>()\n", model.view_ident)) .collect::(); format!( -r#"use distributed::{{ + r#"use distributed::{{ Application, ApplicationManifest, ReadModelCatalog, SurfaceSpec, }}; @@ -256,7 +256,11 @@ pub fn service_descriptor() -> distributed::microsvc::ServiceDescriptor {{ "InMemoryRepository" }; let mut manifest_imports = vec![ - "microsvc::{Routes, Service}", + if self.commands.is_empty() && self.events.is_empty() { + "microsvc::Service" + } else { + "microsvc::{Routes, Service}" + }, repo_import, "ServiceDescriptor", ]; @@ -266,20 +270,10 @@ pub fn service_descriptor() -> distributed::microsvc::ServiceDescriptor {{ if self.tracing { manifest_imports.push("TracingDescriptor"); } - if self.query_api && !self.commands.is_empty() { + if !self.commands.is_empty() { manifest_imports.push("AggregateRepository"); } let manifest_imports = manifest_imports.join(", "); - let registrations = self - .commands - .iter() - .map(|handler| format!(" command handlers::{},\n", handler.module_ident)) - .chain( - self.events - .iter() - .map(|handler| format!(" event handlers::{},\n", handler.module_ident)), - ) - .collect::(); let event_registrations = self .events .iter() @@ -415,8 +409,10 @@ pub fn build(repo: ServiceRepo) -> Arc {{ }} fn build_service(repo: ServiceRepo) -> Service {{ + // Under `distributed dev`, only the active generation may write. let service = Service::new() - .named({service_name}); + .named({service_name}) + .with_lifecycle(distributed::microsvc::LifecycleGate::from_env()); {typed_route_attachments}{event_route_attachment} service }} @@ -458,10 +454,11 @@ pub fn in_memory() -> Arc {{ }} pub fn build(repo: ServiceRepo) -> Arc {{ - let routes = distributed::routes!( - Routes::new().with_dependencies(repo), -{registrations} ); - Arc::new(Service::new().named({service_name}){http_command_opt_in}.routes(routes)) + // Under `distributed dev`, only the active generation may write. + let service = Service::new() + .named({service_name}) + .with_lifecycle(distributed::microsvc::LifecycleGate::from_env()){http_command_opt_in}; +{typed_route_attachments}{event_route_attachment} Arc::new(service) }} pub fn descriptor() -> ServiceDescriptor {{ @@ -472,7 +469,7 @@ pub fn descriptor() -> ServiceDescriptor {{ service_name = rust_string(&self.names.package_name), transport = rust_string(transport), http_command_opt_in = match self.transport { - ServiceTransport::Http => ".with_http_command_routes()", + ServiceTransport::Http => "\n .with_http_command_routes()", ServiceTransport::Knative => "", }, ) @@ -492,9 +489,8 @@ pub fn descriptor() -> ServiceDescriptor {{ .collect::>() .join(""); - let fallback_aggregate = - if self.query_api && self.models.is_empty() && !self.commands.is_empty() { - r#" + let fallback_aggregate = if self.models.is_empty() && !self.commands.is_empty() { + r#" use distributed::{sourced, Entity, Snapshot}; #[derive(Default, Snapshot)] @@ -514,34 +510,24 @@ impl CommandAggregate { } } "# - } else { - "" - }; + } else { + "" + }; - let command_types = if self.query_api { - r#"#[derive(Clone, Debug, Deserialize, distributed::GraphqlInput)] + let command_types = r#"#[derive(Clone, Debug, Deserialize, distributed::CommandInput)] pub struct CommandInput { pub id: String, pub name: Option, } -#[derive(Clone, Debug, Serialize, distributed::GraphqlOutput)] +#[derive(Clone, Debug, Serialize, distributed::CommandOutput)] pub struct CommandOutput { pub command: String, pub id: String, pub model: String, pub name: Option, } -"# - } else { - r#"#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct CommandInput { - pub id: String, - #[serde(default)] - pub name: Option, -} -"# - }; +"#; format!( r#"{modules} @@ -591,14 +577,22 @@ impl {model_struct} {{ } pub(super) fn command_handler_rs(&self, handler: &MessageHandler) -> String { - if self.query_api { - let (model_type, model_name) = self - .command_model(handler) - .map(|model| (model.type_ident.as_str(), model.name.as_str())) - .unwrap_or(("CommandAggregate", "CommandAggregate")); - return format!( - r#"use distributed::graphql::{{typed_command, Succeeded, PreparedCommand, TypedCommand}}; -use distributed::microsvc::{{CausalCommandContext, HandlerError}}; + let (model_type, model_name) = self + .command_model(handler) + .map(|model| (model.type_ident.as_str(), model.name.as_str())) + .unwrap_or(("CommandAggregate", "CommandAggregate")); + // A Knative trigger delivers the command as the transport identity, + // which runs only commands that declare its role. + let (microsvc_imports, roles) = match self.transport { + ServiceTransport::Http => ("CausalCommandContext, HandlerError", r#"["user"]"#), + ServiceTransport::Knative => ( + "CausalCommandContext, HandlerError, TRANSPORT_ROLE", + r#"["user", TRANSPORT_ROLE]"#, + ), + }; + format!( + r#"use distributed::command::{{typed_command, Succeeded, PreparedCommand, TypedCommand}}; +use distributed::microsvc::{{{microsvc_imports}}}; use crate::models::{{CommandInput, CommandOutput, {model_type}}}; @@ -606,7 +600,7 @@ pub const COMMAND: &str = {message_name}; pub const MODEL: &str = {model_name}; pub fn command() -> TypedCommand> {{ - typed_command::>(COMMAND).roles(["user"]) + typed_command::>(COMMAND).roles({roles}) }} pub async fn handle( @@ -626,64 +620,9 @@ pub async fn handle( }}) }} "#, - message_name = rust_string(&handler.message_name), - model_name = rust_string(model_name), - ); - } - - if let Some(model) = self.command_model(handler) { - format!( - r#"use distributed::{{ - microsvc::{{Context, HandlerError}}, Aggregate, CommitBatch, StreamIdentity, StreamWrite, - TransactionalCommit, -}}; -use serde_json::{{json, Value}}; - -use crate::models::{{CommandInput, {model_type}}}; -use crate::service::ServiceRepo; - -pub const COMMAND: &str = {message_name}; -pub const MODEL: &str = {model_name}; - -pub fn guard(ctx: &Context) -> bool {{ - ctx.has_fields(&["id"]) -}} - -pub async fn handle(ctx: &Context<'_, ServiceRepo>) -> Result {{ - let input = ctx.input::()?; - let mut aggregate = {model_type}::default(); - aggregate.record_command(COMMAND.to_string(), input.id.clone(), input.name.clone())?; - let identity = StreamIdentity::new({model_type}::aggregate_type(), aggregate.entity().id())?; - let stream = StreamWrite::new(identity, aggregate.entity_mut()); - ctx.repo().commit_batch(CommitBatch::new(vec![stream])).await?; - Ok(json!({{ "command": COMMAND, "id": input.id, "model": MODEL, "name": input.name }})) -}} -"#, - model_type = model.type_ident, - message_name = rust_string(&handler.message_name), - model_name = rust_string(&model.name), - ) - } else { - format!( - r#"use distributed::microsvc::{{Context, HandlerError}}; -use serde_json::{{json, Value}}; - -use crate::service::ServiceRepo; - -pub const COMMAND: &str = {message_name}; - -pub fn guard(_ctx: &Context) -> bool {{ - true -}} - -pub async fn handle(ctx: &Context<'_, ServiceRepo>) -> Result {{ - let input = ctx.input::()?; - Ok(json!({{ "command": COMMAND, "input": input }})) -}} -"#, - message_name = rust_string(&handler.message_name), - ) - } + message_name = rust_string(&handler.message_name), + model_name = rust_string(model_name), + ) } pub(super) fn event_handler_rs(&self, handler: &MessageHandler) -> String { @@ -766,7 +705,7 @@ use serde::{{Deserialize, Serialize}}; .collect::>() .join(", "); format!( - "// Tighten grants by replacing grant_all with:\n// distributed::graphql_models!(builder, {names})\n// after filling permissions() in each model module.\n" + "// Tighten grants by replacing grant_all with one\n// .model::(module::permissions())\n// per model ({names}) after filling permissions() in each model module.\n" ) }; let protocol_key_parameter = if self.commands.is_empty() { @@ -804,7 +743,7 @@ pub fn build_engine( // Public GraphQL identity (D6/D7): always OidcBearer + require_auth=true. // Set OIDC_ISSUER + OIDC_AUDIENCE (or OIDC_CLIENT_ID). Unset → placeholder // issuer (still OidcBearer; ambient headers never trusted). For local - // GraphiQL ambient headers only, pass IdentityMode::DevHeaders explicitly. + // GraphiQL ambient headers only, pass `IdentityConfig::DevHeaders` explicitly. let identity = distributed::graphql::public_oidc_identity_from_env(); GraphqlEngine::from_schema_catalog(&crate::read_model_catalog(), source)? .service(service){protocol_key_builder} diff --git a/distributed_cli/src/generated_dir.rs b/distributed_cli/src/generated_dir.rs new file mode 100644 index 000000000..c953db4a9 --- /dev/null +++ b/distributed_cli/src/generated_dir.rs @@ -0,0 +1,519 @@ +//! The one writer for a directory a generator owns. +//! +//! Both client generators (`distributed client`, `distributed game-client`) +//! write and check their output through [`GeneratedDir`], so both get the same +//! guarantees: +//! +//! - nothing is written through a symlink; +//! - an unchanged file is left untouched, so a watching dev server does not +//! reload for nothing; +//! - a file the generator produced before and no longer produces is removed; +//! - a file the generator cannot prove it produced is never removed or +//! overwritten around: the write is refused before anything changes. + +use std::collections::{BTreeMap, BTreeSet}; +use std::error::Error; +use std::fs; +use std::path::{Component, Path, PathBuf}; + +use crate::client_compiler::GeneratedClientFile; + +const MAX_FILES: usize = 8_192; +/// Largest existing file read to decide whether the generator owns it. +const MAX_OWNED_FILE_BYTES: u64 = 8 * 1024 * 1024; + +pub(crate) struct GeneratedDir<'a> { + pub(crate) root: &'a Path, + /// Whether the generator owns the files in subdirectories too. One that + /// owns only the top level leaves every subdirectory to its own writer. + pub(crate) nested: bool, +} + +impl GeneratedDir<'_> { + /// Make the directory hold exactly `files`, writing them in the order + /// given. + /// + /// `owned(path, contents)` says whether an existing file that is not in + /// `files` was produced by this generator. Owned files are removed; any + /// other makes the write fail before anything is changed. + pub(crate) fn write( + &self, + files: &[GeneratedClientFile], + owned: impl Fn(&str, &str) -> Result>, + ) -> Result<(), Box> { + let expected = expected(files)?; + self.refuse_symlinks(files)?; + let mut stale = Vec::new(); + let mut foreign = Vec::new(); + for path in self.existing()? { + if expected.contains_key(path.as_str()) { + continue; + } + let full_path = self.root.join(&path); + // A file too large or not UTF-8 to inspect is nobody's proof. + let contents = fs::metadata(&full_path) + .is_ok_and(|metadata| metadata.len() <= MAX_OWNED_FILE_BYTES) + .then(|| fs::read_to_string(&full_path).ok()) + .flatten(); + let owned = match contents { + Some(contents) => owned(&path, &contents)?, + None => false, + }; + if owned { + stale.push(full_path); + } else { + foreign.push(path); + } + } + if !foreign.is_empty() { + return Err(format!( + "generated output contains files without current or previous compiler ownership:\n {}; refusing to write until they are moved or removed", + foreign.join("\n ") + ) + .into()); + } + + fs::create_dir_all(self.root)?; + for path in stale { + fs::remove_file(&path).map_err(|error| { + format!("remove stale generated file {}: {error}", path.display()) + })?; + } + for file in files { + let path = self.root.join(&file.path); + if fs::read(&path).is_ok_and(|current| current == file.contents.as_bytes()) { + continue; + } + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } + fs::write(&path, &file.contents) + .map_err(|error| format!("write generated file {}: {error}", path.display()))?; + } + Ok(()) + } + + /// How the directory differs from `files`: `changed`, `missing` and + /// `unexpected` paths, sorted. Empty when it holds exactly `files`. + /// Reads only. + pub(crate) fn drift( + &self, + files: &[GeneratedClientFile], + ) -> Result, Box> { + let expected = expected(files)?; + let mut drift = Vec::new(); + for (path, contents) in &expected { + let full_path = self.root.join(path); + match fs::read(&full_path) { + Ok(actual) if actual == contents.as_bytes() => {} + Ok(_) => drift.push(format!("changed {path}")), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + drift.push(format!("missing {path}")); + } + Err(error) => { + return Err( + format!("read generated file {}: {error}", full_path.display()).into(), + ) + } + } + } + for path in self.existing()? { + if !expected.contains_key(path.as_str()) { + drift.push(format!("unexpected {path}")); + } + } + drift.sort(); + Ok(drift) + } + + /// The files in the generator's part of the directory, as portable + /// relative paths. Empty when the directory does not exist. + fn existing(&self) -> Result, Box> { + let mut files = BTreeSet::new(); + if !self.root_exists()? { + return Ok(files); + } + let mut pending = vec![(self.root.to_path_buf(), String::new())]; + while let Some((directory, prefix)) = pending.pop() { + for entry in fs::read_dir(&directory)? { + let entry = entry?; + let file_type = entry.file_type()?; + let name = entry.file_name(); + let name = name.to_str().ok_or_else(|| { + format!( + "generated output contains a non-UTF-8 name {}", + entry.path().display() + ) + })?; + let relative = format!("{prefix}{name}"); + if file_type.is_file() { + files.insert(relative); + if files.len() > MAX_FILES { + return Err(format!( + "generated output {} exceeds {MAX_FILES} files", + self.root.display() + ) + .into()); + } + } else if !self.nested { + // Not this generator's entry. + } else if file_type.is_dir() { + pending.push((entry.path(), format!("{relative}/"))); + } else { + return Err(format!( + "generated output contains unsupported {} {}", + if file_type.is_symlink() { + "symlink" + } else { + "entry" + }, + entry.path().display() + ) + .into()); + } + } + } + Ok(files) + } + + /// Whether the root exists. One that is not a real directory is an error. + fn root_exists(&self) -> Result> { + match fs::symlink_metadata(self.root) { + Ok(metadata) if metadata.is_dir() => Ok(true), + Ok(_) => Err(format!( + "generated output {} must be a real directory, not a symlink or other entry", + self.root.display() + ) + .into()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(error) => { + Err(format!("inspect generated output {}: {error}", self.root.display()).into()) + } + } + } + + /// Refuse a root, a parent directory or a target file that is a symlink + /// (or anything else than the directory or regular file it must be). + fn refuse_symlinks(&self, files: &[GeneratedClientFile]) -> Result<(), Box> { + if !self.root_exists()? { + return Ok(()); + } + for file in files { + let mut current = self.root.to_path_buf(); + let mut components = Path::new(&file.path).components().peekable(); + while let Some(component) = components.next() { + current.push(component); + let metadata = match fs::symlink_metadata(¤t) { + Ok(metadata) => metadata, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => break, + Err(error) => { + return Err(format!( + "inspect generated path {}: {error}", + current.display() + ) + .into()) + } + }; + // `symlink_metadata` does not follow links, so a link is + // neither a file nor a directory here. + let valid = if components.peek().is_none() { + metadata.is_file() + } else { + metadata.is_dir() + }; + if !valid { + return Err(format!( + "generated path {} contains a symlink or incompatible entry", + current.display() + ) + .into()); + } + } + } + Ok(()) + } +} + +/// `files` by path, after checking every path stays inside the directory and +/// names one file. +fn expected(files: &[GeneratedClientFile]) -> Result, Box> { + if files.is_empty() || files.len() > MAX_FILES { + return Err(format!( + "generator produced {} files; expected 1..={MAX_FILES}", + files.len() + ) + .into()); + } + let mut expected = BTreeMap::new(); + for file in files { + let portable = !file.path.is_empty() + && !file.path.contains('\\') + && PathBuf::from(&file.path) + .components() + .all(|component| matches!(component, Component::Normal(_))) + && !file.path.split('/').any(str::is_empty); + if !portable { + return Err(format!("generator produced unsafe path `{}`", file.path).into()); + } + if expected + .insert(file.path.as_str(), file.contents.as_str()) + .is_some() + { + return Err(format!("generator produced duplicate path `{}`", file.path).into()); + } + } + Ok(expected) +} + +#[cfg(test)] +mod tests { + use super::*; + + const MARKER: &str = "// generated"; + + fn file(path: &str, contents: &str) -> GeneratedClientFile { + GeneratedClientFile { + path: path.to_string(), + contents: contents.to_string(), + } + } + + fn marked(_: &str, contents: &str) -> Result> { + Ok(contents.starts_with(MARKER)) + } + + fn tree(root: &Path) -> BTreeMap { + let mut files = BTreeMap::new(); + let mut pending = vec![root.to_path_buf()]; + while let Some(directory) = pending.pop() { + for entry in fs::read_dir(directory).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + pending.push(path); + } else { + files.insert( + path.strip_prefix(root) + .unwrap() + .to_str() + .unwrap() + .to_string(), + fs::read_to_string(&path).unwrap(), + ); + } + } + } + files + } + + #[test] + fn write_converges_and_leaves_unchanged_files_untouched() { + let fixture = tempfile::tempdir().unwrap(); + let root = fixture.path().join("out"); + let dir = GeneratedDir { + root: &root, + nested: true, + }; + let first = [ + file("index.ts", "// generated\nindex 1\n"), + file("operations/a.ts", "// generated\na\n"), + file("operations/b.ts", "// generated\nb\n"), + ]; + assert_eq!( + dir.drift(&first).unwrap(), + [ + "missing index.ts", + "missing operations/a.ts", + "missing operations/b.ts" + ] + ); + dir.write(&first, marked).unwrap(); + assert!(dir.drift(&first).unwrap().is_empty()); + + // An unchanged file keeps its inode contents and its modification + // time; a changed one is rewritten; a dropped one is removed. + let old = std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000); + let unchanged = fs::File::options() + .write(true) + .open(root.join("operations/a.ts")) + .unwrap(); + unchanged.set_modified(old).unwrap(); + let second = [ + file("index.ts", "// generated\nindex 2\n"), + file("operations/a.ts", "// generated\na\n"), + ]; + assert_eq!( + dir.drift(&second).unwrap(), + ["changed index.ts", "unexpected operations/b.ts"] + ); + dir.write(&second, marked).unwrap(); + assert_eq!( + fs::metadata(root.join("operations/a.ts")) + .unwrap() + .modified() + .unwrap(), + old + ); + assert_eq!( + tree(&root), + BTreeMap::from([ + ( + "index.ts".to_string(), + "// generated\nindex 2\n".to_string() + ), + ( + "operations/a.ts".to_string(), + "// generated\na\n".to_string() + ), + ]) + ); + } + + #[test] + fn write_refuses_a_file_it_does_not_own_before_changing_anything() { + let fixture = tempfile::tempdir().unwrap(); + let root = fixture.path().join("out"); + let dir = GeneratedDir { + root: &root, + nested: true, + }; + dir.write( + &[ + file("a.ts", "// generated\na\n"), + file("b.ts", "// generated\nb\n"), + ], + marked, + ) + .unwrap(); + fs::write(root.join("mine.ts"), "export const mine = 1;\n").unwrap(); + let before = tree(&root); + + let error = dir + .write(&[file("a.ts", "// generated\nchanged\n")], marked) + .unwrap_err() + .to_string(); + assert!(error.contains("mine.ts"), "{error}"); + assert!(!error.contains("b.ts"), "{error}"); + assert_eq!(tree(&root), before); + + // The generator's own reason for refusing a file is reported as is. + let error = dir + .write(&[file("a.ts", "// generated\nchanged\n")], |path, _| { + Err(format!("{path} was edited").into()) + }) + .unwrap_err() + .to_string(); + assert!(error.ends_with("was edited"), "{error}"); + assert_eq!(tree(&root), before); + } + + #[test] + fn a_top_level_generator_leaves_subdirectories_alone() { + let fixture = tempfile::tempdir().unwrap(); + let root = fixture.path().join("out"); + fs::create_dir_all(root.join("wasm")).unwrap(); + fs::write(root.join("wasm/module.wasm"), "binary").unwrap(); + let dir = GeneratedDir { + root: &root, + nested: false, + }; + let files = [file("schema.ts", "// generated\n")]; + dir.write(&files, marked).unwrap(); + assert!(dir.drift(&files).unwrap().is_empty()); + assert_eq!( + fs::read_to_string(root.join("wasm/module.wasm")).unwrap(), + "binary" + ); + + let nested = GeneratedDir { + root: &root, + nested: true, + }; + assert_eq!( + nested.drift(&files).unwrap(), + ["unexpected wasm/module.wasm"] + ); + } + + #[test] + fn unsafe_and_duplicate_paths_are_rejected() { + let fixture = tempfile::tempdir().unwrap(); + let dir = GeneratedDir { + root: &fixture.path().join("out"), + nested: true, + }; + for path in [ + "../escape.ts", + "/absolute.ts", + "a//b.ts", + "./a.ts", + "a\\b.ts", + "", + ] { + let error = dir + .write(&[file(path, "x")], marked) + .unwrap_err() + .to_string(); + assert!(error.contains("unsafe path"), "{path}: {error}"); + } + let error = dir + .write(&[file("a.ts", "x"), file("a.ts", "y")], marked) + .unwrap_err() + .to_string(); + assert!(error.contains("duplicate path"), "{error}"); + assert!(dir.write(&[], marked).is_err()); + assert!(!fixture.path().join("out").exists()); + } + + #[cfg(unix)] + #[test] + fn nothing_is_written_through_a_symlink() { + use std::os::unix::fs::symlink; + + let fixture = tempfile::tempdir().unwrap(); + let outside = fixture.path().join("outside"); + fs::create_dir_all(&outside).unwrap(); + fs::write(outside.join("victim.ts"), "untouched").unwrap(); + let files = [file("victim.ts", "// generated\n")]; + + // The root is a link. + let linked_root = fixture.path().join("linked-root"); + symlink(&outside, &linked_root).unwrap(); + for nested in [false, true] { + let dir = GeneratedDir { + root: &linked_root, + nested, + }; + assert!(dir.write(&files, marked).is_err()); + assert!(dir.drift(&files).is_err()); + } + + // The target file is a link, in a generator that owns only the top level. + let root = fixture.path().join("out"); + fs::create_dir_all(&root).unwrap(); + symlink(outside.join("victim.ts"), root.join("victim.ts")).unwrap(); + let dir = GeneratedDir { + root: &root, + nested: false, + }; + let error = dir.write(&files, marked).unwrap_err().to_string(); + assert!(error.contains("contains a symlink"), "{error}"); + + // A parent directory is a link. + fs::remove_file(root.join("victim.ts")).unwrap(); + symlink(&outside, root.join("operations")).unwrap(); + let dir = GeneratedDir { + root: &root, + nested: true, + }; + let error = dir + .write(&[file("operations/victim.ts", "// generated\n")], marked) + .unwrap_err() + .to_string(); + assert!(error.contains("contains a symlink"), "{error}"); + + assert_eq!( + fs::read_to_string(outside.join("victim.ts")).unwrap(), + "untouched" + ); + } +} diff --git a/distributed_cli/src/js_framework.rs b/distributed_cli/src/js_framework.rs index 117602a96..c8d83feba 100644 --- a/distributed_cli/src/js_framework.rs +++ b/distributed_cli/src/js_framework.rs @@ -13,6 +13,7 @@ use std::fs; use std::io::Write; use std::path::{Path, PathBuf}; use std::process::Command; +use std::sync::atomic::AtomicBool; use std::time::Duration; use crate::lifecycle::{digest_bytes, LifecycleError}; @@ -168,11 +169,19 @@ impl JavascriptFrameworkPackage { } } - pub(crate) fn prepare(&self, project_root: &Path, check: bool) -> Result<(), LifecycleError> { + /// Build a local checkout of the package when it is stale. `stop` is the + /// session's stop flag, or `None` outside a session (see + /// [`crate::process`]). + pub(crate) fn prepare( + &self, + project_root: &Path, + check: bool, + stop: Option<&AtomicBool>, + ) -> Result<(), LifecycleError> { let Some(root) = self.local_root() else { return Ok(()); }; - prepare_local_package(root, project_root, check) + prepare_local_package(root, project_root, check, stop) } pub(crate) fn lifecycle_receipt(&self, project_root: &Path) -> Option { @@ -182,9 +191,7 @@ impl JavascriptFrameworkPackage { pub(crate) fn wasm_pack_launcher(&self, ui_root: &Path) -> PathBuf { match &self.source { - JavascriptPackageSource::Local { root } => { - root.join("node_modules/wasm-pack/run.js") - } + JavascriptPackageSource::Local { root } => root.join("node_modules/wasm-pack/run.js"), JavascriptPackageSource::Registry => ui_root.join("node_modules/wasm-pack/run.js"), } } @@ -251,7 +258,7 @@ pub(crate) fn watch_local_javascript( "failed to resolve local JavaScript watch package: {error}" )) })?)?; - package.prepare(project_root, false)?; + package.prepare(project_root, false, None)?; let mut observed_source = source_identity(package_root)?; loop { std::thread::sleep(Duration::from_millis(500)); @@ -265,7 +272,7 @@ pub(crate) fn watch_local_javascript( if next_source == observed_source { continue; } - match package.prepare(project_root, false) { + match package.prepare(project_root, false, None) { Ok(()) => observed_source = next_source, Err(error) => { eprintln!("distributed: local JavaScript rebuild failed: {error}"); @@ -278,6 +285,7 @@ fn prepare_local_package( root: &Path, project_root: &Path, check: bool, + stop: Option<&AtomicBool>, ) -> Result<(), LifecycleError> { let package = read_package_json(&root.join("package.json"))?; let version = package.version.clone().ok_or_else(|| { @@ -302,7 +310,7 @@ fn prepare_local_package( }); if current { if !check { - prepare_local_wasm_pack(root)?; + prepare_local_wasm_pack(root, stop)?; } return Ok(()); } @@ -329,14 +337,15 @@ fn prepare_local_package( root, &[install, "--ignore-scripts"], "JavaScript framework dependency install", + stop, )?; } - prepare_local_wasm_pack(root)?; + prepare_local_wasm_pack(root, stop)?; eprintln!( "distributed: compiling local {DISTRIBUTED_JS_PACKAGE} from {}", root.display() ); - build_local_package_staged(root, &package)?; + build_local_package_staged(root, &package, stop)?; let output_identity = output_identity(root, &package)?; let receipt = JavascriptReceipt { schema_version: RECEIPT_SCHEMA_VERSION, @@ -379,7 +388,7 @@ fn prepare_local_package( Ok(()) } -fn prepare_local_wasm_pack(root: &Path) -> Result<(), LifecycleError> { +fn prepare_local_wasm_pack(root: &Path, stop: Option<&AtomicBool>) -> Result<(), LifecycleError> { let package = root.join("node_modules/wasm-pack/package.json"); if !package.is_file() { return Ok(()); @@ -401,10 +410,15 @@ fn prepare_local_wasm_pack(root: &Path) -> Result<(), LifecycleError> { root, &["rebuild", "wasm-pack"], "JavaScript framework wasm-pack install", + stop, ) } -fn build_local_package_staged(root: &Path, package: &PackageJson) -> Result<(), LifecycleError> { +fn build_local_package_staged( + root: &Path, + package: &PackageJson, + stop: Option<&AtomicBool>, +) -> Result<(), LifecycleError> { let parent = root .parent() .ok_or_else(|| LifecycleError::new("local JavaScript package has no parent directory"))?; @@ -438,6 +452,7 @@ fn build_local_package_staged(root: &Path, package: &PackageJson) -> Result<(), stage.path(), &["run", "build"], "JavaScript framework build", + stop, )?; output_identity(stage.path(), package)?; publish_dist(&stage.path().join("dist"), &root.join("dist")) @@ -550,14 +565,17 @@ fn publish_dist(staged: &Path, destination: &Path) -> Result<(), LifecycleError> Ok(()) } -fn run_npm(root: &Path, args: &[&str], label: &str) -> Result<(), LifecycleError> { - let status = Command::new("npm") - .args(args) - .current_dir(root) - .status() - .map_err(|error| { - LifecycleError::new(format!("failed to start npm for {label}: {error}")) - })?; +fn run_npm( + root: &Path, + args: &[&str], + label: &str, + stop: Option<&AtomicBool>, +) -> Result<(), LifecycleError> { + let mut npm = Command::new("npm"); + npm.args(args).current_dir(root); + let status = crate::process::run(&mut npm, stop) + .map_err(|error| LifecycleError::new(format!("failed to start npm for {label}: {error}")))? + .ok_or_else(|| LifecycleError::new(format!("{label} was stopped")))?; if !status.success() { return Err(LifecycleError::new(format!("{label} failed with {status}"))); } diff --git a/distributed_cli/src/lib.rs b/distributed_cli/src/lib.rs index 32c899050..ea54f68cd 100644 --- a/distributed_cli/src/lib.rs +++ b/distributed_cli/src/lib.rs @@ -2,63 +2,75 @@ //! //! It bundles pure generation (`generate` / `atlas`), the contract lifecycle //! surface (`contracts`), and the clap command surface (`cli`). The standalone -//! binary parses [`DistributedArgs`] and dispatches with [`run_distributed`]. -//! Host CLIs such as `hops` may mount [`ServiceArgs`] and dispatch with [`run`]. +//! binary parses [`DistributedArgs`] and dispatches with [`run`]. A host CLI +//! such as `hops` mounts the same arguments under one of its commands and +//! passes that command to [`run`]. mod atlas; mod cli; mod client_compiler; pub mod contracts; +mod game_client; +mod game_wasm; mod generate; +mod generated_dir; +#[cfg(test)] +#[path = "../tests/support/golden.rs"] +mod golden; mod js_framework; pub mod lifecycle; mod manifest_harness; +mod process; mod skills; mod wasm_pures; pub use atlas::{render_atlas_schema, AtlasDatabaseUrl, AtlasSchemaSpec}; pub use cli::{ - run, run_distributed, AgentHarness, BuildArgs, Bus, ClientArgs, ClientManifestArgs, - ContractsAcceptArgs, ContractsArgs, ContractsCheckArgs, ContractsCommands, ContractsOutput, - DescribeArgs, DevArgs, DistributedArgs, DistributedCommands, Framework, GitopsPromote, - JavascriptWatchArgs, LifecycleOutput, ManifestFormat, Metrics, ProbeArgs, ScaffoldArgs, - SchemaArgs, SchemaDialect, SchemaFormat, ServiceArgs, ServiceCommands, SkillsArgs, - SkillsCommands, SkillsInitArgs, Store, Transport, + run, AgentHarness, BuildArgs, Bus, ClientArgs, ClientManifestArgs, ContractsAcceptArgs, + ContractsArgs, ContractsCheckArgs, ContractsCommands, ContractsOutput, DescribeArgs, DevArgs, + DistributedArgs, DistributedCommands, Framework, GameClientArgs, GameManifestArgs, + GameWasmArgs, GitopsPromote, JavascriptWatchArgs, LifecycleOutput, ManifestFormat, Metrics, + ProbeArgs, ScaffoldArgs, SchemaArgs, SchemaDialect, SchemaFormat, SkillsArgs, SkillsCommands, + SkillsInitArgs, Store, Transport, }; pub use client_compiler::{ compile_client, ClientCompileError, ClientCompileInput, ClientDocument, ClientSourceLocation, - ClientSurfaceSelector, GeneratedClientFile, GeneratedClientProject, GeneratedIslandDirectives, - GeneratedIslandLiveCoverage, GeneratedIslandPlan, GeneratedIslandSource, - GeneratedIslandVariable, GeneratedIslandVariableSchema, GeneratedOperationSummary, + ClientSurfaceIdentity, DistributedClientManifest, GeneratedClientFile, GeneratedClientProject, + GeneratedIslandDirectives, GeneratedIslandLiveCoverage, GeneratedIslandPlan, + GeneratedIslandSource, GeneratedIslandVariable, GeneratedIslandVariableSchema, + GeneratedOperationSummary, }; pub use contracts::{ check_migration_history, check_migration_inventory, check_predecessor_chain, - classify_release_programs, classify_snapshot_diff, close_local_contract_chain, contracts_accept, - contracts_check, diff_snapshots, snapshot_from_json, ArtifactIdentity, ArtifactPredecessor, - ArtifactProvenance, BaselineAvailability, ClassifiedChange, ClientDeclaration, ClientInventory, - ClientProgramArtifact, ClientProgramAsset, ClientProgramDescriptor, ClientProgramSurface, - ContractAcceptScope, ContractArtifactKind, ContractCatalog, ContractCheckResult, - ContractDiagnostic, ContractDiagnosticCode, ContractEntry, ContractError, ContractScope, - ContractsAcceptReport, ContractsCheckReport, EnvironmentPolicyReference, LifecycleDecision, - MigrationDialect, MigrationEntry, MigrationFile, MigrationHistoryCheck, MigrationInventory, - ObservedPredecessor, ProgramCompatibility, SafeDiagnosticValue, - SemanticSnapshot, SnapshotChange, SnapshotDiff, SnapshotEntry, MAX_CATALOG_BYTES, - MAX_CATALOG_DIRECTORIES, MAX_CATALOG_DIRECTORY_DEPTH, MAX_CATALOG_DIRECTORY_ENTRIES, - MAX_CATALOG_ENTRIES, MAX_CATALOG_FILES, MAX_CATALOG_GLOB_MATCHES, MAX_CATALOG_JSON_DEPTH, - MAX_MIGRATIONS, MAX_MIGRATION_INVENTORY_BYTES, MAX_MIGRATION_SQL_BYTES, MAX_SNAPSHOT_DEPTH, - MAX_SNAPSHOT_PATHS, MAX_SNAPSHOT_VALUE_BYTES, MIGRATION_INVENTORY_PATH, - MIGRATION_INVENTORY_SCHEMA_VERSION, MIGRATION_OWNER, MIGRATION_SCOPE, + classify_release_programs, classify_snapshot_diff, close_local_contract_chain, + contracts_accept, contracts_check, diff_snapshots, snapshot_from_json, ArtifactIdentity, + ArtifactPredecessor, ArtifactProvenance, BaselineAvailability, ClassifiedChange, + ClientDeclaration, ClientInventory, ClientProgramArtifact, ClientProgramAsset, + ClientProgramDescriptor, ClientProgramSurface, ContractAcceptScope, ContractArtifactKind, + ContractCatalog, ContractCheckResult, ContractDiagnostic, ContractDiagnosticCode, + ContractEntry, ContractError, ContractScope, ContractsAcceptReport, ContractsCheckReport, + EnvironmentPolicyReference, LifecycleDecision, MigrationDialect, MigrationEntry, MigrationFile, + MigrationHistoryCheck, MigrationInventory, ObservedPredecessor, ProgramCompatibility, + SafeDiagnosticValue, SemanticSnapshot, SnapshotChange, SnapshotDiff, SnapshotEntry, + MAX_CATALOG_BYTES, MAX_CATALOG_DIRECTORIES, MAX_CATALOG_DIRECTORY_DEPTH, + MAX_CATALOG_DIRECTORY_ENTRIES, MAX_CATALOG_ENTRIES, MAX_CATALOG_FILES, + MAX_CATALOG_GLOB_MATCHES, MAX_CATALOG_JSON_DEPTH, MAX_MIGRATIONS, + MAX_MIGRATION_INVENTORY_BYTES, MAX_MIGRATION_SQL_BYTES, MAX_SNAPSHOT_DEPTH, MAX_SNAPSHOT_PATHS, + MAX_SNAPSHOT_VALUE_BYTES, MIGRATION_INVENTORY_PATH, MIGRATION_INVENTORY_SCHEMA_VERSION, + MIGRATION_OWNER, MIGRATION_SCOPE, }; +pub use game_client::{generate_game_client, validate_game_surface, ImportExtension}; pub use generate::{generate_service_scaffold, package_name}; pub use lifecycle::{ - run_lifecycle_build, run_lifecycle_dev, ArtifactNodeReceipt, BuildDrift, DistributedSourceIdentity, - GenerationManifest, LifecycleBuildConfig, LifecycleBuildOptions, LifecycleBuildReport, - LifecycleConfig, LifecycleDevConfig, LifecycleDevOptions, LifecycleDevProbe, - LifecycleDevProcess, LifecycleDevReport, LifecycleError, LifecycleExecutor, LifecycleGraph, LifecycleNode, - ReleaseManifest, ReleaseMember, GENERATION_MANIFEST_SCHEMA_VERSION, + activate_lifecycle_project_generation, discover_lifecycle_project, run_lifecycle_project_build, + run_lifecycle_project_dev, ArtifactNodeReceipt, BuildDrift, DiscoveredLifecycleProject, + DistributedSourceIdentity, GenerationManifest, LifecycleActivation, LifecycleBuildConfig, + LifecycleBuildReport, LifecycleBuildRequest, LifecycleConfig, LifecycleDevConfig, + LifecycleDevProbe, LifecycleDevProcess, LifecycleDevReport, LifecycleError, LifecycleExecutor, + LifecycleGraph, LifecycleNode, LifecycleProjectDevOptions, LifecycleProjectPlan, + ReleaseManifest, ReleaseMember, UiAdapter, GENERATION_MANIFEST_SCHEMA_VERSION, LIFECYCLE_BUILD_CONFIG_SCHEMA_VERSION, LIFECYCLE_CONFIG_SCHEMA_VERSION, - LIFECYCLE_GRAPH_SCHEMA_VERSION, NODE_RECEIPT_SCHEMA_VERSION, - RELEASE_MANIFEST_SCHEMA_VERSION, + LIFECYCLE_GRAPH_SCHEMA_VERSION, NODE_RECEIPT_SCHEMA_VERSION, RELEASE_MANIFEST_SCHEMA_VERSION, }; pub use skills::{embedded_skills, generate_skills, EmbeddedFile, EmbeddedSkill, SkillsInitSpec}; diff --git a/distributed_cli/src/lifecycle/build.rs b/distributed_cli/src/lifecycle/build.rs index c8dcdb66f..025345ac4 100644 --- a/distributed_cli/src/lifecycle/build.rs +++ b/distributed_cli/src/lifecycle/build.rs @@ -11,13 +11,14 @@ use std::sync::Arc; use std::time::{Duration, Instant}; use crate::contracts::ContractCatalog; +use crate::process::ProcessGroup; use super::graph::source_uses_output; use super::{ digest_bytes, validate_content_identity, validate_portable_path, validate_stable_value, ArtifactNodeReceipt, DistributedSourceIdentity, GenerationManifest, LifecycleConfig, LifecycleDevConfig, LifecycleError, LifecycleGraph, ReleaseManifest, - LIFECYCLE_CONFIG_SCHEMA_VERSION, + GENERATED_DIRECTORY_MARKER, LIFECYCLE_CLI_EXECUTABLE_ENV, LIFECYCLE_CONFIG_SCHEMA_VERSION, }; pub const LIFECYCLE_BUILD_CONFIG_SCHEMA_VERSION: u32 = 1; @@ -85,37 +86,6 @@ pub struct LifecycleBuildConfig { } impl LifecycleBuildConfig { - pub fn from_path(path: impl AsRef) -> Result { - let metadata = fs::symlink_metadata(path.as_ref()).map_err(|error| { - LifecycleError::new(format!( - "failed to inspect lifecycle config `{}`: {error}", - path.as_ref().display() - )) - })?; - if metadata.file_type().is_symlink() || !metadata.is_file() { - return Err(LifecycleError::new( - "lifecycle config must be a regular non-symlink file", - )); - } - if metadata.len() > 1024 * 1024 { - return Err(LifecycleError::new("lifecycle config exceeds 1 MiB")); - } - let bytes = fs::read(path.as_ref()).map_err(|error| { - LifecycleError::new(format!( - "failed to read lifecycle config `{}`: {error}", - path.as_ref().display() - )) - })?; - let config: Self = serde_json::from_slice(&bytes).map_err(|error| { - LifecycleError::new(format!( - "failed to parse lifecycle config `{}`: {error}", - path.as_ref().display() - )) - })?; - config.validate()?; - Ok(config) - } - pub fn lifecycle(&self) -> LifecycleConfig { LifecycleConfig { schema_version: LIFECYCLE_CONFIG_SCHEMA_VERSION, @@ -148,24 +118,7 @@ impl LifecycleBuildConfig { } } -#[derive(Clone, Debug)] -pub struct LifecycleBuildOptions { - pub root: PathBuf, - pub catalog: PathBuf, - pub config: PathBuf, - pub out: PathBuf, - pub check: bool, - pub lock_timeout: Duration, - /// Optional downstream-closed node subset; other receipts are verified and reused. - pub nodes: Option>, - /// Optional content snapshot that must still match immediately before activation. - pub activation_inputs: Option>, - /// Optional cooperative cancellation shared with a supervising watcher. - pub cancel: Option>, -} - -/// A lifecycle graph resolved from project metadata rather than user-authored -/// lifecycle files. +/// The lifecycle graph of one project: what `build` and `dev` run. #[derive(Clone, Debug)] pub struct LifecycleProjectPlan { /// Canonical lifecycle root shared by every owned application component. @@ -176,6 +129,9 @@ pub struct LifecycleProjectPlan { pub config: LifecycleBuildConfig, /// Project-relative or absolute content-addressed lifecycle state directory. pub out: PathBuf, + /// Canonical `distributed` executable that initiated the lifecycle work. + /// Executors and UI commands receive it so they call back into the same CLI. + pub cli_executable: PathBuf, } /// Per-invocation behavior for an already resolved lifecycle project. @@ -183,8 +139,6 @@ pub struct LifecycleProjectPlan { pub struct LifecycleBuildRequest { /// Build in an isolated stage and report drift without activation. pub check: bool, - /// Existing output set against which check-mode outputs are compared. - pub check_baseline: LifecycleCheckBaseline, /// Maximum time to wait for a concurrent lifecycle build. pub lock_timeout: Duration, /// Optional downstream-closed node subset for incremental rebuilds. @@ -207,29 +161,6 @@ pub enum LifecycleActivation { Deferred, } -/// Output set used as the baseline for a read-only lifecycle check. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum LifecycleCheckBaseline { - /// Compare staged outputs with catalog-owned files in the source workspace. - Workspace, - /// Compare staged outputs with the currently active immutable generation. - ActiveGeneration, -} - -impl From<&LifecycleBuildOptions> for LifecycleBuildRequest { - fn from(options: &LifecycleBuildOptions) -> Self { - Self { - check: options.check, - check_baseline: LifecycleCheckBaseline::Workspace, - lock_timeout: options.lock_timeout, - nodes: options.nodes.clone(), - activation_inputs: options.activation_inputs.clone(), - cancel: options.cancel.clone(), - activation: LifecycleActivation::Immediate, - } - } -} - #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(deny_unknown_fields)] pub struct BuildDrift { @@ -255,34 +186,6 @@ pub struct LifecycleBuildReport { pub active_generation: Option, } -pub fn run_lifecycle_build( - options: &LifecycleBuildOptions, -) -> Result { - let root = options.root.canonicalize().map_err(|error| { - LifecycleError::new(format!( - "failed to resolve lifecycle root `{}`: {error}", - options.root.display() - )) - })?; - if !root.is_dir() { - return Err(LifecycleError::new("lifecycle root must be a directory")); - } - let catalog_path = resolve_under_root(&root, &options.catalog, "contract catalog")?; - let config_path = resolve_under_root(&root, &options.config, "lifecycle config")?; - let config = LifecycleBuildConfig::from_path(config_path)?; - let catalog = ContractCatalog::from_path_at_root(&catalog_path, &root) - .map_err(|error| LifecycleError::new(error.to_string()))?; - run_lifecycle_project_build( - &LifecycleProjectPlan { - root, - catalog, - config, - out: options.out.clone(), - }, - &LifecycleBuildRequest::from(options), - ) -} - /// Build a lifecycle project whose catalog and execution plan were derived by /// the CLI from Cargo metadata and project conventions. pub fn run_lifecycle_project_build( @@ -394,6 +297,7 @@ pub fn run_lifecycle_project_build( &node.outputs, executor, request.check, + &project.cli_executable, request.cancel.as_deref(), )?; let output_identities = collect_node_outputs(stage.path(), node_id, &graph)?; @@ -422,12 +326,7 @@ pub fn run_lifecycle_project_build( let compatibility_id = digest_bytes(&compatibility_bytes); let drift = if request.check { - match request.check_baseline { - LifecycleCheckBaseline::Workspace => compare_workspace_outputs(&root, &generation)?, - LifecycleCheckBaseline::ActiveGeneration => { - compare_active_outputs(&out, &generation)? - } - } + compare_active_outputs(&out, &generation)? } else { if request .cancel @@ -462,6 +361,7 @@ pub fn run_lifecycle_project_build( install_generation(stage, &out, &generation.generation_id)?; if request.activation == LifecycleActivation::Immediate { write_active_generation(&out, &generation.generation_id, &release.release_id)?; + prune_generations(&out, &generation.generation_id); Some(generation.generation_id.clone()) } else { read_active_generation(&out)? @@ -487,7 +387,9 @@ fn compare_active_outputs( generation: &GenerationManifest, ) -> Result, LifecycleError> { let active = read_active_generation(out)?; - let active_root = active.as_ref().map(|identity| out.join("generations").join(identity)); + let active_root = active + .as_ref() + .map(|identity| out.join("generations").join(identity)); let mut drift = Vec::new(); for receipt in generation.receipts.values() { for (output, built_identity) in &receipt.output_identities { @@ -641,6 +543,7 @@ fn execute_node( declared_outputs: &BTreeSet, executor: &LifecycleExecutor, check: bool, + cli_executable: &Path, cancel: Option<&AtomicBool>, ) -> Result<(), LifecycleError> { let root_value = root.to_string_lossy(); @@ -675,47 +578,40 @@ fn execute_node( .env("DISTRIBUTED_LIFECYCLE_ROOT", root) .env("DISTRIBUTED_LIFECYCLE_STAGE", stage) .env("DISTRIBUTED_LIFECYCLE_NODE", node_id) - .env( - "DISTRIBUTED_LIFECYCLE_CHECK", - if check { "1" } else { "0" }, - ) + .env("DISTRIBUTED_LIFECYCLE_CHECK", if check { "1" } else { "0" }) + .env(LIFECYCLE_CLI_EXECUTABLE_ENV, cli_executable) + .stdin(Stdio::null()) .stdout(stdout) .stderr(Stdio::piped()); - let mut child = command.spawn().map_err(|error| { + // The executor leads its own process group: `describe` blocks in `cargo + // run`, so cancelling the leader alone would leave the compiler running. + let mut executor_group = ProcessGroup::spawn(&mut command).map_err(|error| { LifecycleError::new(format!( "lifecycle node `{node_id}` failed to start executor `{}`: {error}", executor.program )) })?; - let stderr = child + let stderr = executor_group + .leader() .stderr .take() .ok_or_else(|| LifecycleError::new("lifecycle executor stderr pipe is unavailable"))?; - let stderr_reader = match std::thread::Builder::new() + let stderr_reader = std::thread::Builder::new() .name(format!("lifecycle-stderr-{node_id}")) .spawn(move || forward_executor_stderr(stderr)) - { - Ok(reader) => reader, - Err(error) => { - let _ = child.kill(); - let _ = child.wait(); - return Err(io_error("start lifecycle executor stderr reader")(error)); - } - }; + .map_err(io_error("start lifecycle executor stderr reader"))?; let status = loop { if cancel.is_some_and(|cancel| cancel.load(Ordering::SeqCst)) { - child + executor_group .kill() .map_err(io_error("cancel lifecycle executor"))?; - child - .wait() - .map_err(io_error("wait for canceled lifecycle executor"))?; let _ = finish_executor_stderr(stderr_reader); return Err(LifecycleError::canceled(format!( "lifecycle build was canceled while node `{node_id}` was running" ))); } - if let Some(status) = child + if let Some(status) = executor_group + .leader() .try_wait() .map_err(io_error("inspect lifecycle executor"))? { @@ -723,6 +619,10 @@ fn execute_node( } std::thread::sleep(Duration::from_millis(10)); }; + // Nothing the executor left running may hold its stderr pipe open. + executor_group + .kill() + .map_err(io_error("stop lifecycle executor descendants"))?; let stderr_tail = finish_executor_stderr(stderr_reader)?; if !status.success() { let detail = String::from_utf8_lossy(&stderr_tail); @@ -931,6 +831,9 @@ fn collect_regular_files( path.display() ))); } + if path.join(GENERATED_DIRECTORY_MARKER).is_file() { + return Ok(()); + } let mut entries = fs::read_dir(path) .map_err(io_error("read lifecycle directory"))? .collect::, _>>() @@ -978,31 +881,6 @@ fn collect_regular_files( Ok(()) } -fn compare_workspace_outputs( - root: &Path, - generation: &GenerationManifest, -) -> Result, LifecycleError> { - let mut drift = Vec::new(); - for (node_id, receipt) in &generation.receipts { - for (output, built_identity) in &receipt.output_identities { - let workspace_identity = match fs::symlink_metadata(root.join(output)) { - Ok(_) => Some(hash_path(&root.join(output), root)?), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, - Err(error) => return Err(io_error("inspect workspace output")(error)), - }; - if workspace_identity.as_ref() != Some(built_identity) { - drift.push(BuildDrift { - node_id: node_id.clone(), - output: output.clone(), - built_identity: built_identity.clone(), - workspace_identity, - }); - } - } - } - Ok(drift) -} - fn reject_unowned_stage_files(stage: &Path, graph: &LifecycleGraph) -> Result<(), LifecycleError> { let outputs = graph .nodes @@ -1140,7 +1018,45 @@ pub fn activate_lifecycle_project_generation( report.active_generation.as_deref(), &report.generation_id, )?; - write_active_generation(&out, &report.generation_id, &report.release_id) + write_active_generation(&out, &report.generation_id, &report.release_id)?; + prune_generations(&out, &report.generation_id); + Ok(()) +} + +/// Remove the installed generations nothing can read any more. +/// +/// Kept: the generation that was just activated, and every generation a +/// running `dev` session names in its state file: the one it serves, the one +/// it is switching to, and the one each of its processes was started with (a +/// UI server that is not restarted keeps resolving the generation it started +/// on). Every other generation is unreachable: nothing serves it, and +/// activation refuses a generation built before the pointer last moved. +/// +/// The caller holds the build lock and has moved the pointer. A generation +/// that cannot be removed is reported and left for the next activation. +fn prune_generations(out: &Path, active: &str) { + let Some(mut keep) = super::dev::generations_in_use(out) else { + return; + }; + keep.insert(active.to_string()); + let Ok(entries) = fs::read_dir(out.join("generations")) else { + return; + }; + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(generation) = name.to_str() else { + continue; + }; + if keep.contains(generation) + || validate_content_identity(generation, "generation").is_err() + || !entry.file_type().is_ok_and(|kind| kind.is_dir()) + { + continue; + } + if let Err(error) = fs::remove_dir_all(entry.path()) { + eprintln!("lifecycle: could not remove unused generation `{generation}`: {error}"); + } + } } fn ensure_activation_predecessor( @@ -1251,27 +1167,6 @@ impl Drop for BuildLock { } } -fn resolve_under_root(root: &Path, path: &Path, label: &str) -> Result { - let candidate = if path.is_absolute() { - path.to_path_buf() - } else { - root.join(path) - }; - reject_symlink_components(root, &candidate, label)?; - let resolved = candidate.canonicalize().map_err(|error| { - LifecycleError::new(format!( - "failed to resolve {label} `{}`: {error}", - candidate.display() - )) - })?; - if !resolved.starts_with(root) { - return Err(LifecycleError::new(format!( - "{label} escapes lifecycle root" - ))); - } - Ok(resolved) -} - pub(super) fn resolve_output(root: &Path, path: &Path) -> Result { if path .components() @@ -1376,6 +1271,126 @@ mod tests { use super::*; use crate::lifecycle::graph::LifecycleErrorReason; + #[cfg(unix)] + #[test] + fn lifecycle_executor_receives_exact_cli_path_including_spaces() { + let fixture = tempfile::tempdir().expect("create executor fixture"); + let stage = fixture.path().join("stage"); + fs::create_dir_all(&stage).expect("create executor stage"); + let script = fixture.path().join("print-cli.sh"); + fs::write( + &script, + "#!/bin/sh\nprintf '%s' \"$DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE\"\n", + ) + .expect("write executor script"); + let cli = fixture.path().join("cli with spaces").join("distributed"); + let mut outputs = BTreeSet::new(); + outputs.insert("cli-path.txt".to_string()); + + execute_node( + fixture.path(), + &stage, + "clients", + &outputs, + &LifecycleExecutor { + identity: "sha256:executor".to_string(), + // Run the script through `sh` instead of exec-ing it: a + // freshly written executable can fail with ETXTBSY while a + // concurrently forked test child still holds its write fd. + program: "/bin/sh".to_string(), + args: vec![script.to_string_lossy().into_owned()], + stdout: Some("cli-path.txt".to_string()), + }, + false, + &cli, + None, + ) + .expect("executor should receive the initiating CLI identity"); + assert_eq!( + fs::read_to_string(stage.join("cli-path.txt")).unwrap(), + cli.to_string_lossy() + ); + } + + #[test] + fn a_generated_directory_is_not_a_lifecycle_input() { + let fixture = tempfile::tempdir().expect("create source fixture"); + let lib = fixture.path().join("lib"); + fs::create_dir_all(lib.join("pkg")).unwrap(); + fs::write(lib.join("app.ts"), "export {};\n").unwrap(); + fs::write(lib.join("pkg/module.wasm"), "first").unwrap(); + let identity = || hash_path(&lib, fixture.path()).unwrap(); + + let unmarked = identity(); + fs::write(lib.join("pkg/module.wasm"), "second").unwrap(); + assert_ne!(identity(), unmarked, "an ordinary directory is an input"); + + fs::write(lib.join("pkg").join(GENERATED_DIRECTORY_MARKER), "").unwrap(); + let marked = identity(); + fs::write(lib.join("pkg/module.wasm"), "third").unwrap(); + fs::remove_file(lib.join("pkg/module.wasm")).unwrap(); + assert_eq!(identity(), marked, "a generated directory is not"); + + fs::write(lib.join("app.ts"), "export const changed = true;\n").unwrap(); + assert_ne!(identity(), marked, "its siblings still are"); + } + + #[test] + fn activation_removes_the_generations_nothing_reads() { + let generation = |digit: &str| format!("sha256:{}", digit.repeat(64)); + let installed = |out: &Path| { + fs::read_dir(out.join("generations")) + .unwrap() + .map(|entry| entry.unwrap().file_name().into_string().unwrap()) + .collect::>() + }; + let fixture = |state: Option<&str>| { + let fixture = tempfile::tempdir().expect("create generation store"); + for name in ["1", "2", "3", "4"].map(generation) { + fs::create_dir_all(fixture.path().join("generations").join(name)).unwrap(); + } + fs::create_dir_all(fixture.path().join("generations/not-a-generation")).unwrap(); + if let Some(state) = state { + fs::write(fixture.path().join("dev.json"), state).unwrap(); + } + fixture + }; + + // No session: only the active generation is read. + let store = fixture(None); + prune_generations(store.path(), &generation("4")); + assert_eq!( + installed(store.path()), + BTreeSet::from([generation("4"), "not-a-generation".to_string()]) + ); + + // A session switching from 2 to 4 whose `ui` process started on 1. + let state = serde_json::json!({ + "schemaVersion": 1, + "phase": "preparing", + "active": { "generationId": generation("2") }, + "pending": { "generationId": generation("4") }, + "members": { "ui": { "instanceId": "member-x", "generationId": generation("1") } }, + }) + .to_string(); + let store = fixture(Some(&state)); + prune_generations(store.path(), &generation("4")); + assert_eq!( + installed(store.path()), + BTreeSet::from([ + generation("1"), + generation("2"), + generation("4"), + "not-a-generation".to_string() + ]) + ); + + // A session whose state cannot be read: nothing is known to be unused. + let store = fixture(Some("{")); + prune_generations(store.path(), &generation("4")); + assert_eq!(installed(store.path()).len(), 5); + } + #[test] fn activation_rejects_an_advanced_generation() { let fixture = tempfile::tempdir().expect("create activation fixture"); diff --git a/distributed_cli/src/lifecycle/dev.rs b/distributed_cli/src/lifecycle/dev.rs index 25ecedaed..f5c337514 100644 --- a/distributed_cli/src/lifecycle/dev.rs +++ b/distributed_cli/src/lifecycle/dev.rs @@ -1,23 +1,21 @@ use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; use std::fs; -#[cfg(unix)] -use std::os::unix::process::CommandExt; use std::path::{Path, PathBuf}; -use std::process::{Child, Command, Stdio}; +use std::process::{Command, Stdio}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use crate::contracts::ContractCatalog; +use crate::process::ProcessGroup; use super::build::{lifecycle_input_snapshot, resolve_output}; use super::graph::LifecycleErrorReason; use super::{ activate_lifecycle_project_generation, run_lifecycle_project_build, validate_portable_path, - validate_stable_value, LifecycleActivation, LifecycleBuildConfig, LifecycleBuildOptions, - LifecycleBuildReport, LifecycleBuildRequest, LifecycleError, LifecycleGraph, - LifecycleProjectPlan, + validate_stable_value, LifecycleActivation, LifecycleBuildReport, LifecycleBuildRequest, + LifecycleError, LifecycleGraph, LifecycleProjectPlan, }; const MAX_DEV_PROCESSES: usize = 64; @@ -54,8 +52,8 @@ pub struct LifecycleDevProcess { /// Working directory relative to the lifecycle root. #[serde(default, skip_serializing_if = "Option::is_none")] pub cwd: Option, - /// Permit an absolute working directory selected by trusted project - /// discovery. Ordinary lifecycle files remain root-confined by default. + /// Permit an absolute working directory. Project discovery sets it for a + /// UI outside the lifecycle root; it cannot be deserialized. #[serde(skip)] pub external_cwd: bool, /// Process-specific environment. Values may use lifecycle placeholders. @@ -200,14 +198,6 @@ fn readiness_budget_ms(process: &LifecycleDevProcess) -> u64 { .map_or(process.ready_after_ms, |probe| probe.timeout_ms) } -#[derive(Clone, Debug)] -pub struct LifecycleDevOptions { - pub build: LifecycleBuildOptions, - pub stop: Arc, - /// Emit operator-facing readiness and rebuild progress to stderr. - pub progress: bool, -} - #[derive(Clone, Debug)] pub struct LifecycleProjectDevOptions { /// In-memory lifecycle plan derived from the project. @@ -229,39 +219,6 @@ pub struct LifecycleDevReport { pub restarts: BTreeMap, } -pub fn run_lifecycle_dev( - options: &LifecycleDevOptions, -) -> Result { - if options.build.check { - return Err(LifecycleError::new( - "lifecycle dev requires an activating build configuration", - )); - } - let root = options.build.root.canonicalize().map_err(|error| { - LifecycleError::new(format!("failed to resolve lifecycle dev root: {error}")) - })?; - let config_path = resolve_file(&root, &options.build.config)?; - let catalog_path = resolve_file(&root, &options.build.catalog)?; - let config = LifecycleBuildConfig::from_path(config_path)?; - let dev = config.dev.clone().ok_or_else(|| { - LifecycleError::new("lifecycle config has no `dev` process configuration") - })?; - dev.validate()?; - let catalog = ContractCatalog::from_path_at_root(&catalog_path, &root) - .map_err(|error| LifecycleError::new(error.to_string()))?; - run_lifecycle_project_dev(&LifecycleProjectDevOptions { - project: LifecycleProjectPlan { - root, - catalog, - config, - out: options.build.out.clone(), - }, - build: LifecycleBuildRequest::from(&options.build), - stop: Arc::clone(&options.stop), - progress: options.progress, - }) -} - /// Run development processes for a project resolved from Cargo metadata and /// filesystem conventions. pub fn run_lifecycle_project_dev( @@ -285,13 +242,16 @@ pub fn run_lifecycle_project_dev( validate_restart_nodes(&dev, &graph)?; // Initial coherent generation is an absolute serving barrier. + // Observe before building/starting children: edits during startup must not + // become a new baseline without ever being built. + let mut snapshot = lifecycle_input_snapshot(&root, catalog, &graph)?; let mut initial_options = options.build.clone(); initial_options.nodes = None; initial_options.activation_inputs = None; initial_options.cancel = Some(Arc::clone(&options.stop)); let initial = run_lifecycle_project_build(&options.project, &initial_options)?; let state = DevStateStore::new(&root, &options.project.out)?; - state.write_active(&initial)?; + state.write_active(&initial, &BTreeMap::new())?; for process in dev.processes.values_mut() { process.env.insert( "DISTRIBUTED_LIFECYCLE_DIR".to_string(), @@ -299,6 +259,10 @@ pub fn run_lifecycle_project_dev( ); } let mut children = ChildSet::start(&root, &dev, &initial, &options.stop)?; + if let Err(error) = state.write_active(&initial, &children.members) { + let _ = children.shutdown(Duration::from_millis(dev.shutdown_ms)); + return Err(error); + } if options.progress { for (name, process) in &dev.processes { if let Some(url) = &process.url { @@ -311,7 +275,6 @@ pub fn run_lifecycle_project_dev( dev.processes.keys().cloned().collect::>().join(",") ); } - let mut snapshot = lifecycle_input_snapshot(&root, catalog, &graph)?; let mut final_generation = initial.generation_id.clone(); let mut active = initial.clone(); let mut rebuilds = 0; @@ -321,11 +284,20 @@ pub fn run_lifecycle_project_dev( .map(|name| (name.clone(), 0)) .collect::>(); + let mut watch = InputWatch { + root: &root, + catalog, + graph: &graph, + progress: options.progress, + failure: None, + }; let result = (|| { while !options.stop.load(Ordering::SeqCst) { children.ensure_running()?; std::thread::sleep(Duration::from_millis(dev.poll_ms)); - let next = lifecycle_input_snapshot(&root, catalog, &graph)?; + let Some(next) = watch.observe() else { + continue; + }; let mut changed = changed_paths(&snapshot, &next); if changed.is_empty() { continue; @@ -339,7 +311,10 @@ pub fn run_lifecycle_project_dev( return Ok(()); } std::thread::sleep(Duration::from_millis(dev.poll_ms.min(dev.debounce_ms))); - let observed = lifecycle_input_snapshot(&root, catalog, &graph)?; + let Some(observed) = watch.observe() else { + quiet_since = Instant::now(); + continue; + }; let delta = changed_paths(&latest, &observed); if !delta.is_empty() { changed.extend(delta); @@ -371,16 +346,7 @@ pub fn run_lifecycle_project_dev( return Err(error); } std::thread::sleep(Duration::from_millis(dev.poll_ms)); - let observed = match lifecycle_input_snapshot(&root, catalog, &graph) { - Ok(observed) => observed, - Err(error) => { - cancel.store(true, Ordering::SeqCst); - let _ = build.join(); - return Err(error); - } - }; - if !changed_paths(&latest, &observed).is_empty() { - latest = observed; + if watch.observe().is_some_and(|observed| observed != latest) { superseded = true; cancel.store(true, Ordering::SeqCst); } @@ -396,16 +362,11 @@ pub fn run_lifecycle_project_dev( { return Ok(()) } - Err(error) - if superseded - && matches!( - error.reason(), - LifecycleErrorReason::Canceled | LifecycleErrorReason::Superseded - ) => - { - continue - } Err(error) if error.reason() == LifecycleErrorReason::Superseded => continue, + // A build says nothing about inputs that changed, or could not + // be read, while it ran. The baseline is unchanged, so the + // next poll builds what is there now. + Err(_) if superseded || watch.observe().as_ref() != Some(&latest) => continue, Err(error) => return Err(error), }; rebuilds += 1; @@ -416,13 +377,18 @@ pub fn run_lifecycle_project_dev( // acknowledgements to this attempt so a persisted response from a // rejected/superseded attempt can never authorize the next one. let transition = state.begin_transition()?; - state.write_preparing(&active, &generation, transition.id(), dev.prepare_ms)?; + state.write_preparing( + &active, + &generation, + transition.id(), + dev.prepare_ms, + &children.members, + )?; if let Err(error) = state.wait_for_prepare( transition.id(), Duration::from_millis(dev.prepare_ms), &options.stop, ) { - state.write_active(&active)?; if options.stop.load(Ordering::SeqCst) && error.reason() == LifecycleErrorReason::Canceled { @@ -433,6 +399,7 @@ pub fn run_lifecycle_project_dev( "pending generation preparation failed: {error}; prior generation is no longer serving: {serving}" )) })?; + state.write_active(&active, &children.members)?; if options.progress { eprintln!( "lifecycle dev: rejected generation={} during preparation; prior generation remains active: {}", @@ -460,15 +427,14 @@ pub fn run_lifecycle_project_dev( if options.stop.load(Ordering::SeqCst) && error.reason() == LifecycleErrorReason::Canceled { - state.write_active(&active)?; return Ok(()); } - state.write_active(&active)?; children.ensure_running().map_err(|serving| { LifecycleError::new(format!( "pending generation readiness failed: {error}; prior generation rollback is not serving: {serving}" )) - })?; + })?; + state.write_active(&active, &children.members)?; if options.progress { eprintln!( "lifecycle dev: rejected generation={} during readiness; prior generation remains active: {}", @@ -493,7 +459,8 @@ pub fn run_lifecycle_project_dev( ); return match rollback { Ok(()) => { - state.write_active(&active)?; + children.ensure_running()?; + state.write_active(&active, &children.members)?; if options.progress { eprintln!( "lifecycle dev: rejected generation={} during activation; prior generation remains active: {}", @@ -510,7 +477,8 @@ pub fn run_lifecycle_project_dev( } final_generation = generation.generation_id.clone(); active = generation.clone(); - state.write_active(&active)?; + children.ensure_running()?; + state.write_active(&active, &children.members)?; if options.progress { eprintln!( "lifecycle dev: activated generation={} invalidated={} restarted={}", @@ -528,8 +496,10 @@ pub fn run_lifecycle_project_dev( Ok(()) })(); + let retired = state.write_active(&active, &BTreeMap::new()); let shutdown = children.shutdown(Duration::from_millis(dev.shutdown_ms)); result?; + retired?; shutdown?; Ok(LifecycleDevReport { initial_generation: initial.generation_id, @@ -554,6 +524,7 @@ struct DevLifecycleState<'a> { schema_version: u32, phase: &'static str, active: DevGenerationState<'a>, + members: &'a BTreeMap, #[serde(skip_serializing_if = "Option::is_none")] pending: Option>, #[serde(skip_serializing_if = "Option::is_none")] @@ -580,11 +551,16 @@ impl DevStateStore { }) } - fn write_active(&self, active: &LifecycleBuildReport) -> Result<(), LifecycleError> { + fn write_active( + &self, + active: &LifecycleBuildReport, + members: &BTreeMap, + ) -> Result<(), LifecycleError> { self.write(&DevLifecycleState { schema_version: 1, phase: "active", active: generation_state(active), + members, pending: None, transition_id: None, deadline_unix_ms: None, @@ -617,12 +593,14 @@ impl DevStateStore { pending: &LifecycleBuildReport, transition_id: &str, prepare_ms: u64, + members: &BTreeMap, ) -> Result<(), LifecycleError> { let deadline = unix_ms()?.saturating_add(prepare_ms); self.write(&DevLifecycleState { schema_version: 1, phase: "preparing", active: generation_state(active), + members, pending: Some(generation_state(pending)), transition_id: Some(transition_id), deadline_unix_ms: Some(deadline), @@ -784,6 +762,38 @@ impl DevStateStore { } } +/// The generations a `dev` session over the lifecycle directory `out` still +/// reads, from its state file: the active one, a pending one, and the one each +/// process was started with. Empty when no session is running. `None` when +/// the state file cannot be understood, and so nothing is known to be unused. +pub(super) fn generations_in_use(out: &Path) -> Option> { + fn collect(value: &serde_json::Value, found: &mut BTreeSet) { + match value { + serde_json::Value::Object(object) => { + for (key, value) in object { + match value.as_str() { + Some(generation) if key == "generationId" => { + found.insert(generation.to_string()); + } + _ => collect(value, found), + } + } + } + serde_json::Value::Array(values) => { + values.iter().for_each(|value| collect(value, found)) + } + _ => {} + } + } + let mut found = BTreeSet::new(); + match fs::read(out.join("dev.json")) { + Ok(bytes) => collect(&serde_json::from_slice(&bytes).ok()?, &mut found), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => return None, + } + Some(found) +} + struct DevTransition { id: String, // TempDir removes this attempt's acknowledgement directory after the @@ -853,6 +863,45 @@ fn validate_restart_nodes( Ok(()) } +/// The watched inputs as the supervisor polls them. +/// +/// A file can vanish or be half replaced while it is read (an editor's atomic +/// rename, a checkout), so a failed read is not an observation: the caller +/// keeps what it last saw and the next poll reads again. A failure that +/// persists is reported once, and so is the recovery. +struct InputWatch<'a> { + root: &'a Path, + catalog: &'a ContractCatalog, + graph: &'a LifecycleGraph, + progress: bool, + failure: Option, +} + +impl InputWatch<'_> { + fn observe(&mut self) -> Option> { + match lifecycle_input_snapshot(self.root, self.catalog, self.graph) { + Ok(snapshot) => { + if self.failure.take().is_some() && self.progress { + eprintln!("lifecycle dev: watched inputs are readable again"); + } + Some(snapshot) + } + Err(error) => { + let failure = error.to_string(); + if self.failure.as_ref() != Some(&failure) { + if self.progress { + eprintln!( + "lifecycle dev: cannot read watched inputs, will keep trying: {failure}" + ); + } + self.failure = Some(failure); + } + None + } + } + } +} + fn changed_paths( before: &BTreeMap, after: &BTreeMap, @@ -865,8 +914,36 @@ fn changed_paths( .collect() } +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct DevMemberState { + instance_id: String, + generation_id: String, +} + +impl DevMemberState { + fn new(generation: &LifecycleBuildReport) -> Result { + let identity = tempfile::Builder::new() + .prefix("member-") + .rand_bytes(16) + .tempfile() + .map_err(dev_io("allocate lifecycle process identity"))?; + let instance_id = identity + .path() + .file_name() + .and_then(|name| name.to_str()) + .ok_or_else(|| LifecycleError::new("invalid lifecycle process identity"))? + .to_owned(); + Ok(Self { + instance_id, + generation_id: generation.generation_id.clone(), + }) + } +} + struct ChildSet { - children: BTreeMap, + children: BTreeMap, + members: BTreeMap, } impl ChildSet { @@ -878,11 +955,17 @@ impl ChildSet { ) -> Result { let mut set = Self { children: BTreeMap::new(), + members: BTreeMap::new(), }; for (name, process) in &config.processes { - match spawn_process(root, name, process, generation) { - Ok(child) => { + let spawned = DevMemberState::new(generation).and_then(|member| { + spawn_process(root, name, process, generation, &member.instance_id) + .map(|child| (child, member)) + }); + match spawned { + Ok((child, member)) => { set.children.insert(name.clone(), child); + set.members.insert(name.clone(), member); } Err(error) => { let _ = set.shutdown(Duration::from_millis(config.shutdown_ms)); @@ -907,8 +990,14 @@ impl ChildSet { } fn ensure_running(&mut self) -> Result<(), LifecycleError> { + if self.children.len() != self.members.len() || self.children.keys().ne(self.members.keys()) + { + return Err(LifecycleError::new( + "lifecycle process cohort is incomplete", + )); + } for (name, child) in &mut self.children { - if let Some(status) = child.try_wait().map_err(|error| { + if let Some(status) = child.leader().try_wait().map_err(|error| { LifecycleError::new(format!("failed to inspect dev process `{name}`: {error}")) })? { return Err(LifecycleError::new(format!( @@ -946,20 +1035,27 @@ impl ChildSet { self.children.insert(name.clone(), previous_child); return Err(error); } - let replacement = - spawn_process(root, name, process, generation).and_then(|mut child| { - if let Err(error) = - wait_ready(root, name, process, generation, &mut child, stop) - { - let _ = - stop_child(name, &mut child, Duration::from_millis(config.shutdown_ms)); - return Err(error); - } - Ok(child) - }); + let replacement = DevMemberState::new(generation).and_then(|member| { + spawn_process(root, name, process, generation, &member.instance_id).and_then( + |mut child| { + if let Err(error) = + wait_ready(root, name, process, generation, &mut child, stop) + { + let _ = stop_child( + name, + &mut child, + Duration::from_millis(config.shutdown_ms), + ); + return Err(error); + } + Ok((child, member)) + }, + ) + }); match replacement { - Ok(child) => { + Ok((child, member)) => { self.children.insert(name.clone(), child); + self.members.insert(name.clone(), member); replaced.insert(name.clone()); } Err(error) => { @@ -1008,49 +1104,41 @@ impl ChildSet { for name in names { let process = &config.processes[name]; if let Some(mut child) = self.children.remove(name) { - if let Err(error) = stop_child( - name, - &mut child, - Duration::from_millis(config.shutdown_ms), - ) { + if let Err(error) = + stop_child(name, &mut child, Duration::from_millis(config.shutdown_ms)) + { self.children.insert(name.clone(), child); return Err(error); } } - let mut child = spawn_process(root, name, process, replacement)?; + let member = DevMemberState::new(replacement)?; + let mut child = spawn_process(root, name, process, replacement, &member.instance_id)?; if let Err(error) = wait_ready(root, name, process, replacement, &mut child, stop) { let _ = stop_child(name, &mut child, Duration::from_millis(config.shutdown_ms)); return Err(error); } self.children.insert(name.clone(), child); + self.members.insert(name.clone(), member); } Ok(()) } + /// Stop every process: all are asked at once, and share one grace period. fn shutdown(&mut self, timeout: Duration) -> Result<(), LifecycleError> { for (name, child) in &mut self.children { - terminate_process_group(name, child)?; + child.terminate().map_err(group_error(name, "stop"))?; } - let started = Instant::now(); - loop { - let mut running = Vec::new(); - for (name, child) in &mut self.children { - if process_group_is_running(child)? { - running.push(name.clone()); - } - } - if running.is_empty() { - return Ok(()); - } - if started.elapsed() >= timeout { - for name in &running { - let child = self.children.get_mut(name).unwrap(); - kill_process_group(name, child)?; - } - return wait_for_stopped_groups(&mut self.children, Duration::from_secs(1)); + let deadline = Instant::now() + timeout; + for (name, child) in &mut self.children { + let remaining = deadline.saturating_duration_since(Instant::now()); + if !child + .wait_gone(remaining) + .map_err(group_error(name, "inspect"))? + { + child.kill().map_err(group_error(name, "kill"))?; } - std::thread::sleep(Duration::from_millis(10)); } + Ok(()) } } @@ -1059,7 +1147,7 @@ fn wait_ready( name: &str, process: &LifecycleDevProcess, generation: &LifecycleBuildReport, - child: &mut Child, + child: &mut ProcessGroup, stop: &AtomicBool, ) -> Result<(), LifecycleError> { let started = Instant::now(); @@ -1073,7 +1161,7 @@ fn wait_ready( "readiness for lifecycle dev process `{name}` was canceled" ))); } - if let Some(status) = child.try_wait().map_err(|error| { + if let Some(status) = child.leader().try_wait().map_err(|error| { LifecycleError::new(format!("failed to inspect dev process `{name}`: {error}")) })? { return Err(LifecycleError::new(format!( @@ -1108,15 +1196,13 @@ fn wait_ready( .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()); - #[cfg(unix)] - command.process_group(0); - let mut probe_child = command.spawn().map_err(|error| { + let mut probe_child = ProcessGroup::spawn(&mut command).map_err(|error| { LifecycleError::new(format!( "failed to run readiness probe for lifecycle dev process `{name}` with `{program}`: {error}" )) })?; let status = loop { - match probe_child.try_wait() { + match probe_child.leader().try_wait() { Ok(Some(status)) => { if started.elapsed() >= timeout.unwrap() { return Err(readiness_timeout(name, probe.timeout_ms)); @@ -1125,20 +1211,23 @@ fn wait_ready( } Ok(None) => {} Err(error) => { - let _ = force_stop_child(name, &mut probe_child); return Err(LifecycleError::new(format!( "failed to inspect readiness probe for lifecycle dev process `{name}`: {error}" ))); } } if stop.load(Ordering::SeqCst) { - force_stop_child(name, &mut probe_child)?; + probe_child + .kill() + .map_err(group_error(name, "kill the readiness probe of"))?; return Err(LifecycleError::canceled(format!( "readiness for lifecycle dev process `{name}` was canceled" ))); } if started.elapsed() >= timeout.unwrap() { - force_stop_child(name, &mut probe_child)?; + probe_child + .kill() + .map_err(group_error(name, "kill the readiness probe of"))?; return Err(readiness_timeout(name, probe.timeout_ms)); } std::thread::sleep( @@ -1187,7 +1276,8 @@ fn spawn_process( name: &str, process: &LifecycleDevProcess, generation: &LifecycleBuildReport, -) -> Result { + instance_id: &str, +) -> Result { let cwd = resolve_working_dir(root, process.cwd.as_deref(), process.external_cwd)?; let args = process .args @@ -1205,28 +1295,31 @@ fn spawn_process( .env("DISTRIBUTED_TOPOLOGY_ID", &generation.graph_id) .env("DISTRIBUTED_COMPATIBILITY_ID", &generation.compatibility_id) .env("DISTRIBUTED_MEMBER_ID", name) + .env("DISTRIBUTED_PROCESS_INSTANCE_ID", instance_id) .stdin(Stdio::null()); - #[cfg(unix)] - command.process_group(0); - command.spawn().map_err(|error| { + ProcessGroup::spawn(&mut command).map_err(|error| { LifecycleError::new(format!( "failed to start lifecycle dev process `{name}` with `{program}`: {error}" )) }) } -fn stop_child(name: &str, child: &mut Child, timeout: Duration) -> Result<(), LifecycleError> { - terminate_process_group(name, child)?; - if wait_for_stopped_child(child, timeout)? { - return Ok(()); - } - kill_process_group(name, child)?; - if wait_for_stopped_child(child, Duration::from_secs(1))? { - Ok(()) - } else { - Err(LifecycleError::new(format!( - "lifecycle dev process group `{name}` remained alive after SIGKILL" - ))) +fn stop_child( + name: &str, + child: &mut ProcessGroup, + timeout: Duration, +) -> Result<(), LifecycleError> { + child.stop(timeout).map_err(group_error(name, "stop")) +} + +fn group_error<'a>( + name: &'a str, + action: &'a str, +) -> impl FnOnce(std::io::Error) -> LifecycleError + 'a { + move |error| { + LifecycleError::new(format!( + "failed to {action} lifecycle dev process group `{name}`: {error}" + )) } } @@ -1320,159 +1413,6 @@ fn validate_process_env( Ok(()) } -#[cfg(unix)] -fn signal_process_group(child: &Child, signal: libc::c_int) -> std::io::Result<()> { - let result = unsafe { libc::kill(-(child.id() as libc::pid_t), signal) }; - if result == 0 { - return Ok(()); - } - let error = std::io::Error::last_os_error(); - if error.raw_os_error() == Some(libc::ESRCH) { - Ok(()) - } else { - Err(error) - } -} - -fn process_group_is_running(child: &mut Child) -> Result { - let leader_running = child.try_wait().map_err(io_error)?.is_none(); - #[cfg(unix)] - { - let result = unsafe { libc::kill(-(child.id() as libc::pid_t), 0) }; - if result == 0 { - return Ok(true); - } - let error = std::io::Error::last_os_error(); - match error.raw_os_error() { - Some(libc::ESRCH) => Ok(leader_running), - Some(libc::EPERM) => Ok(true), - _ => Err(LifecycleError::new(format!( - "failed to inspect lifecycle dev process group: {error}" - ))), - } - } - #[cfg(not(unix))] - { - Ok(leader_running) - } -} - -fn wait_for_stopped_child(child: &mut Child, timeout: Duration) -> Result { - let started = Instant::now(); - loop { - if !process_group_is_running(child)? { - return Ok(true); - } - if started.elapsed() >= timeout { - return Ok(false); - } - std::thread::sleep(Duration::from_millis(10)); - } -} - -fn wait_for_stopped_groups( - children: &mut BTreeMap, - timeout: Duration, -) -> Result<(), LifecycleError> { - let started = Instant::now(); - loop { - let mut running = Vec::new(); - for (name, child) in children.iter_mut() { - if process_group_is_running(child)? { - running.push(name.clone()); - } - } - if running.is_empty() { - return Ok(()); - } - if started.elapsed() >= timeout { - return Err(LifecycleError::new(format!( - "lifecycle dev process groups remained alive after SIGKILL: {}", - running.join(", ") - ))); - } - std::thread::sleep(Duration::from_millis(10)); - } -} - -fn force_stop_child(name: &str, child: &mut Child) -> Result<(), LifecycleError> { - kill_process_group(name, child)?; - if wait_for_stopped_child(child, Duration::from_secs(1))? { - Ok(()) - } else { - Err(LifecycleError::new(format!( - "readiness probe for lifecycle dev process `{name}` remained alive after SIGKILL" - ))) - } -} - -fn terminate_process_group(name: &str, child: &mut Child) -> Result<(), LifecycleError> { - #[cfg(unix)] - { - signal_process_group(child, libc::SIGTERM).map_err(|error| { - LifecycleError::new(format!( - "failed to stop lifecycle dev process group `{name}`: {error}" - )) - }) - } - #[cfg(not(unix))] - { - if child.try_wait().map_err(io_error)?.is_none() { - child.kill().map_err(|error| { - LifecycleError::new(format!( - "failed to stop lifecycle dev process `{name}`: {error}" - )) - })?; - } - Ok(()) - } -} - -fn kill_process_group(name: &str, child: &mut Child) -> Result<(), LifecycleError> { - #[cfg(unix)] - { - signal_process_group(child, libc::SIGKILL).map_err(|error| { - LifecycleError::new(format!( - "failed to kill lifecycle dev process group `{name}`: {error}" - )) - }) - } - #[cfg(not(unix))] - { - if child.try_wait().map_err(io_error)?.is_none() { - child.kill().map_err(|error| { - LifecycleError::new(format!( - "failed to kill lifecycle dev process `{name}`: {error}" - )) - })?; - } - Ok(()) - } -} - -fn resolve_file(root: &Path, path: &PathBuf) -> Result { - let path = if path.is_absolute() { - path.clone() - } else { - root.join(path) - }; - let resolved = path.canonicalize().map_err(|error| { - LifecycleError::new(format!("failed to resolve `{}`: {error}", path.display())) - })?; - if !resolved.starts_with(root) - || !fs::metadata(&resolved).is_ok_and(|metadata| metadata.is_file()) - { - return Err(LifecycleError::new( - "lifecycle dev input must be a file under the root", - )); - } - Ok(resolved) -} - -fn io_error(error: std::io::Error) -> LifecycleError { - LifecycleError::new(error.to_string()) -} - #[cfg(test)] mod tests { use super::*; diff --git a/distributed_cli/src/lifecycle/mod.rs b/distributed_cli/src/lifecycle/mod.rs index 887edab69..1af906836 100644 --- a/distributed_cli/src/lifecycle/mod.rs +++ b/distributed_cli/src/lifecycle/mod.rs @@ -10,22 +10,31 @@ mod project; mod receipt; mod release; +/// Internal process contract carrying the canonical CLI that initiated a +/// discovered lifecycle. It is deliberately not part of user-authored +/// lifecycle configuration. +pub(crate) const LIFECYCLE_CLI_EXECUTABLE_ENV: &str = "DISTRIBUTED_LIFECYCLE_CLI_EXECUTABLE"; + +/// A file the CLI puts in a directory it generates inside the application +/// source tree. Such a directory is a build product, never a lifecycle input: +/// hashing and watching skip it, so writing it does not start another build. +pub(crate) const GENERATED_DIRECTORY_MARKER: &str = ".distributed-generated"; + pub use build::{ - activate_lifecycle_project_generation, run_lifecycle_build, run_lifecycle_project_build, - BuildDrift, LifecycleActivation, LifecycleBuildConfig, LifecycleBuildOptions, - LifecycleBuildReport, LifecycleBuildRequest, LifecycleCheckBaseline, LifecycleExecutor, - LifecycleProjectPlan, LIFECYCLE_BUILD_CONFIG_SCHEMA_VERSION, + activate_lifecycle_project_generation, run_lifecycle_project_build, BuildDrift, + LifecycleActivation, LifecycleBuildConfig, LifecycleBuildReport, LifecycleBuildRequest, + LifecycleExecutor, LifecycleProjectPlan, LIFECYCLE_BUILD_CONFIG_SCHEMA_VERSION, }; pub use dev::{ - run_lifecycle_dev, run_lifecycle_project_dev, LifecycleDevConfig, LifecycleDevOptions, - LifecycleDevProbe, LifecycleDevProcess, LifecycleDevReport, LifecycleProjectDevOptions, + run_lifecycle_project_dev, LifecycleDevConfig, LifecycleDevProbe, LifecycleDevProcess, + LifecycleDevReport, LifecycleProjectDevOptions, }; pub use graph::{ DistributedSourceIdentity, LifecycleConfig, LifecycleError, LifecycleGraph, LifecycleNode, LIFECYCLE_CONFIG_SCHEMA_VERSION, LIFECYCLE_GRAPH_SCHEMA_VERSION, MAX_LIFECYCLE_NODES, }; pub(crate) use project::discover_ui; -pub use project::{discover_lifecycle_project, DiscoveredLifecycleProject}; +pub use project::{discover_lifecycle_project, DiscoveredLifecycleProject, UiAdapter}; pub use receipt::{ ArtifactNodeReceipt, GenerationManifest, GENERATION_MANIFEST_SCHEMA_VERSION, NODE_RECEIPT_SCHEMA_VERSION, diff --git a/distributed_cli/src/lifecycle/project.rs b/distributed_cli/src/lifecycle/project.rs index 705e8cc75..d24c9ff5c 100644 --- a/distributed_cli/src/lifecycle/project.rs +++ b/distributed_cli/src/lifecycle/project.rs @@ -20,7 +20,7 @@ use crate::js_framework::{ use super::{ digest_bytes, DistributedSourceIdentity, LifecycleBuildConfig, LifecycleDevConfig, LifecycleDevProbe, LifecycleDevProcess, LifecycleError, LifecycleExecutor, - LifecycleProjectPlan, LIFECYCLE_BUILD_CONFIG_SCHEMA_VERSION, + LifecycleProjectPlan, LIFECYCLE_BUILD_CONFIG_SCHEMA_VERSION, LIFECYCLE_CLI_EXECUTABLE_ENV, }; const APPLICATION_NODE: &str = "application"; @@ -47,15 +47,74 @@ pub struct DiscoveredLifecycleProject { /// Canonical Cargo workspace root. This can be narrower than the lifecycle /// root when the application owns a repository-local sibling UI. pub(crate) cargo_root: PathBuf, - /// Canonical SvelteKit root, discovered conventionally or from Cargo - /// workspace metadata. - pub ui: Option, + /// The project's UI, discovered conventionally or from Cargo workspace + /// metadata. + pub ui: Option, /// Resolved Distributed browser runtime, when the UI consumes it. pub(crate) javascript: Option, /// Internal lifecycle graph synthesized from the discovered project. pub plan: LifecycleProjectPlan, } +/// A project's UI: where it is and how `build` and `dev` run it. +/// +/// The defaults are a SvelteKit application under npm. A project replaces any +/// of them in `[workspace.metadata.distributed.ui]` of its `Cargo.toml`, which +/// is also where it names the environment its own dev server needs. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq)] +#[serde(default, deny_unknown_fields)] +pub struct UiAdapter { + /// UI directory, relative to the Cargo workspace root. + pub path: String, + /// Canonical UI directory resolved from `path`. + #[serde(skip)] + pub root: PathBuf, + /// Program that runs `install`, `check`, `build` and `dev`. + pub package_manager: String, + /// Arguments that install dependencies. When unset: `ci` beside a + /// `package-lock.json`, otherwise `install`. + pub install: Option>, + /// Arguments that check the UI during `build`. Empty skips the step. + pub check: Vec, + /// Arguments that compile the UI during `build`. Empty skips the step. + pub build: Vec, + /// Arguments that start the dev server. `{host}` and `{port}` are the + /// address it must bind. + pub dev: Vec, + /// Host of the dev server. `UI_HOST` overrides it; `UI_BIND` overrides + /// the bind address alone. + pub host: String, + /// Port of the dev server. `UI_PORT` overrides it. + pub port: u16, + /// Environment of the dev server. `{api_url}` and `{ui_url}` are the + /// addresses of the running session; a value that uses one is always set. + /// Any other value is a development default: a variable that the shell or + /// the project's `.env` file already sets keeps that value. + pub env: BTreeMap, +} + +impl Default for UiAdapter { + fn default() -> Self { + let args = |args: &[&str]| args.iter().map(|arg| (*arg).to_string()).collect(); + Self { + path: "ui".to_string(), + root: PathBuf::new(), + package_manager: "npm".to_string(), + install: None, + check: args(&["run", "check", "--if-present"]), + build: args(&["run", "build"]), + dev: args(&["run", "dev", "--", "--host", "{host}", "--port", "{port}"]), + host: "localhost".to_string(), + port: 5180, + env: BTreeMap::new(), + } + } +} + +/// Address the runtime binds unless `BIND` or +/// `[workspace.metadata.distributed.runtime] bind` says otherwise. +const DEFAULT_API_BIND: &str = "127.0.0.1:8791"; + #[derive(Debug, Deserialize)] struct CargoMetadata { workspace_root: PathBuf, @@ -178,14 +237,14 @@ pub fn discover_lifecycle_project( .unwrap_or(&application.package) .to_string(); let ui = discover_ui(&metadata.metadata, &root)?; - let lifecycle_root = lifecycle_root(&root, ui.as_deref())?; - let javascript = ui - .as_ref() - .map(|ui| discover_javascript_framework(ui)) + let ui_root = ui.as_ref().map(|ui| ui.root.as_path()); + let lifecycle_root = lifecycle_root(&root, ui_root)?; + let javascript = ui_root + .map(discover_javascript_framework) .transpose()? .flatten(); let mut sources = workspace_sources(&lifecycle_root, &root, &workspace_packages)?; - let mut client_lifecycle = discover_client_lifecycle(&lifecycle_root, ui.as_deref())?; + let mut client_lifecycle = discover_client_lifecycle(&lifecycle_root, ui_root)?; if let Some(receipt) = javascript .as_ref() .and_then(|package| package.lifecycle_receipt(&root)) @@ -291,11 +350,18 @@ pub fn discover_lifecycle_project( entries, }; + let api_bind = match metadata.metadata.pointer("/distributed/runtime/bind") { + None => DEFAULT_API_BIND, + Some(bind) => bind.as_str().ok_or_else(|| { + LifecycleError::new("workspace Distributed runtime `bind` must be a string") + })?, + }; let dev = lifecycle_dev( &lifecycle_root, &root, &runtime, - ui.as_deref(), + api_bind, + ui.as_ref(), javascript.as_ref(), client_lifecycle.is_some(), &executable, @@ -326,7 +392,7 @@ pub fn discover_lifecycle_project( .collect::>(); if let Some(wasm_pack_launcher) = javascript .as_ref() - .zip(ui.as_ref()) + .zip(ui_root) .map(|(javascript, ui)| javascript.wasm_pack_launcher(ui)) { describe_args.extend([ @@ -349,8 +415,7 @@ pub fn discover_lifecycle_project( "distributed.clients.json requires @hops-ops/distributed in the UI package", ) })?; - let compiler = ui - .as_ref() + let compiler = ui_root .expect("client lifecycle has a UI") .join("node_modules/@hops-ops/distributed/dist/sveltekit/lifecycle-compiler.js"); let identity = digest_bytes( @@ -409,6 +474,7 @@ pub fn discover_lifecycle_project( catalog, config, out: root.join(out.unwrap_or_else(|| Path::new(".distributed/lifecycle"))), + cli_executable: executable.clone(), }, }) } @@ -434,34 +500,39 @@ fn cargo_metadata(manifest: &Path) -> Result { pub(crate) fn discover_ui( workspace_metadata: &Value, root: &Path, -) -> Result, LifecycleError> { - let declared = match workspace_metadata.pointer("/distributed/ui") { - None => None, - Some(ui) => Some(ui.get("path").and_then(Value::as_str).ok_or_else(|| { - LifecycleError::new("workspace Distributed UI metadata requires a string `path`") - })?), - }; - let candidate = match declared { - Some(path) => { - if path.is_empty() - || path.trim() != path - || Path::new(path).is_absolute() - || path.contains('\0') - { - return Err(LifecycleError::new( - "workspace Distributed UI path must be a non-empty relative path", - )); - } - root.join(path) - } +) -> Result, LifecycleError> { + let mut adapter = match workspace_metadata.pointer("/distributed/ui") { None => { - let conventional = root.join("ui"); - if !conventional.join("package.json").is_file() { + let conventional = UiAdapter::default(); + if !root.join(&conventional.path).join("package.json").is_file() { return Ok(None); } conventional } + Some(declared) => { + serde_json::from_value::(declared.clone()).map_err(|error| { + LifecycleError::new(format!( + "invalid `[workspace.metadata.distributed.ui]`: {error}" + )) + })? + } }; + let path = adapter.path.as_str(); + if path.is_empty() + || path.trim() != path + || Path::new(path).is_absolute() + || path.contains('\0') + { + return Err(LifecycleError::new( + "workspace Distributed UI path must be a non-empty relative path", + )); + } + if adapter.package_manager.is_empty() || adapter.dev.is_empty() { + return Err(LifecycleError::new( + "workspace Distributed UI requires a `package_manager` and a `dev` command", + )); + } + let candidate = root.join(path); let ui = candidate.canonicalize().map_err(|error| { LifecycleError::new(format!( "failed to resolve Distributed UI `{}`: {error}", @@ -491,7 +562,8 @@ pub(crate) fn discover_ui( ))); } } - Ok(Some(ui)) + adapter.root = ui; + Ok(Some(adapter)) } fn discover_application( @@ -997,21 +1069,16 @@ fn lifecycle_dev( root: &Path, cargo_root: &Path, runtime: &RuntimeTarget, - ui: Option<&Path>, + api_bind: &str, + ui: Option<&UiAdapter>, javascript: Option<&JavascriptFrameworkPackage>, lifecycle_owns_client_compile: bool, executable: &Path, command_prefix: &[&str], ) -> LifecycleDevConfig { - let bind = std::env::var("BIND").unwrap_or_else(|_| "127.0.0.1:8791".to_string()); + let bind = std::env::var("BIND").unwrap_or_else(|_| api_bind.to_string()); let api_address = loopback_address(&bind); let api_url = format!("http://{api_address}"); - let ui_host = std::env::var("UI_HOST").unwrap_or_else(|_| "localhost".to_string()); - let ui_bind = std::env::var("UI_BIND").unwrap_or_else(|_| ui_host.clone()); - let ui_port = std::env::var("UI_PORT").unwrap_or_else(|_| "5180".to_string()); - let ui_url = std::env::var("UI_URL") - .or_else(|_| std::env::var("AUTH_URL")) - .unwrap_or_else(|_| format!("http://{ui_host}:{ui_port}")); let cargo_cwd = cargo_root .strip_prefix(root) .ok() @@ -1050,24 +1117,39 @@ fn lifecycle_dev( }, )]); if let Some(ui) = ui { - let (cwd, external_cwd) = match ui.strip_prefix(root) { + let (cwd, external_cwd) = match ui.root.strip_prefix(root) { Ok(relative) if relative.as_os_str().is_empty() => (None, false), Ok(relative) => ( Some(portable_path(relative).expect("validated UI path")), false, ), - Err(_) => (Some(ui.to_string_lossy().into_owned()), true), + Err(_) => (Some(ui.root.to_string_lossy().into_owned()), true), }; - let mut ui_env = BTreeMap::from([ + let ui_host = std::env::var("UI_HOST").unwrap_or_else(|_| ui.host.clone()); + let ui_bind = std::env::var("UI_BIND").unwrap_or_else(|_| ui_host.clone()); + let ui_port = std::env::var("UI_PORT").unwrap_or_else(|_| ui.port.to_string()); + let ui_url = std::env::var("PUBLIC_ORIGIN") + .or_else(|_| std::env::var("UI_URL")) + .unwrap_or_else(|_| format!("http://{ui_host}:{ui_port}")); + let session = |value: &str| { + value + .replace("{api_url}", &api_url) + .replace("{ui_url}", &ui_url) + }; + let mut ui_env = BTreeMap::new(); + for (name, declared) in &ui.env { + let value = session(declared); + // A literal is the application's development default. + if value != *declared || std::env::var_os(name).is_none() { + ui_env.insert(name.clone(), value); + } + } + ui_env.extend([ ("DISTRIBUTED_API_ORIGIN".to_string(), api_url.clone()), - ("E2E_API_ORIGIN".to_string(), api_url.clone()), ( - "AUTH_SECRET".to_string(), - std::env::var("AUTH_SECRET") - .unwrap_or_else(|_| "distributed-local-development-only-secret".to_string()), + LIFECYCLE_CLI_EXECUTABLE_ENV.to_string(), + executable.to_string_lossy().into_owned(), ), - ("AUTH_URL".to_string(), ui_url.clone()), - ("AUTH_USE_SECURE_COOKIES".to_string(), "false".to_string()), ]); if lifecycle_owns_client_compile { ui_env.insert( @@ -1082,16 +1164,12 @@ fn lifecycle_dev( processes.insert( "ui".to_string(), LifecycleDevProcess { - program: "npm".to_string(), - args: vec![ - "run".to_string(), - "dev".to_string(), - "--".to_string(), - "--host".to_string(), - ui_bind.clone(), - "--port".to_string(), - ui_port.clone(), - ], + program: ui.package_manager.clone(), + args: ui + .dev + .iter() + .map(|arg| arg.replace("{host}", &ui_bind).replace("{port}", &ui_port)) + .collect(), cwd, external_cwd, env: ui_env, @@ -1133,7 +1211,10 @@ fn lifecycle_dev( args, cwd: None, external_cwd: false, - env: BTreeMap::new(), + env: BTreeMap::from([( + LIFECYCLE_CLI_EXECUTABLE_ENV.to_string(), + executable.to_string_lossy().into_owned(), + )]), url: None, restart_on: BTreeSet::new(), ready_after_ms: 100, @@ -1280,7 +1361,141 @@ mod tests { .unwrap() .unwrap(); - assert_eq!(discovered, ui.canonicalize().unwrap()); + assert_eq!(discovered.root, ui.canonicalize().unwrap()); + assert_eq!( + UiAdapter { + root: PathBuf::new(), + ..discovered + }, + UiAdapter { + path: "../../clients/web".to_string(), + ..UiAdapter::default() + }, + "an undeclared key keeps its default" + ); + } + + #[test] + fn a_conventional_ui_needs_no_metadata_and_a_misspelled_key_is_refused() { + let project = tempfile::tempdir().unwrap(); + let root = project.path().canonicalize().unwrap(); + assert_eq!(discover_ui(&Value::Null, &root).unwrap(), None); + fs::create_dir_all(root.join("ui")).unwrap(); + fs::write(root.join("ui/package.json"), "{}").unwrap(); + + let conventional = discover_ui(&Value::Null, &root).unwrap().unwrap(); + assert_eq!( + conventional, + UiAdapter { + root: root.join("ui"), + ..UiAdapter::default() + } + ); + // Declaring only what the application needs keeps the conventional path. + let declared = discover_ui( + &serde_json::json!({ "distributed": { "ui": { "env": { "API": "{api_url}" } } } }), + &root, + ) + .unwrap() + .unwrap(); + assert_eq!(declared.root, root.join("ui")); + + let error = discover_ui( + &serde_json::json!({ "distributed": { "ui": { "pakage_manager": "pnpm" } } }), + &root, + ) + .unwrap_err() + .to_string(); + assert!( + error.contains("[workspace.metadata.distributed.ui]") + && error.contains("pakage_manager"), + "{error}" + ); + } + + #[test] + fn the_ui_adapter_owns_the_dev_command_and_its_environment() { + let project = tempfile::tempdir().unwrap(); + let ui = project.path().join("ui"); + fs::create_dir_all(&ui).unwrap(); + let adapter = UiAdapter { + root: ui, + package_manager: "pnpm".to_string(), + dev: vec!["dev".into(), "{host}:{port}".into()], + env: BTreeMap::from([ + ("FIXTURE_API".to_string(), "{api_url}/graphql".to_string()), + ("FIXTURE_ORIGIN".to_string(), "{ui_url}".to_string()), + // No test process has this variable; every one has `PATH`. + ( + "DISTRIBUTED_FIXTURE_DEFAULT".to_string(), + "development".to_string(), + ), + ("PATH".to_string(), "never".to_string()), + ]), + ..UiAdapter::default() + }; + let executable = std::env::current_exe().unwrap(); + let config = lifecycle_dev( + project.path(), + project.path(), + &RuntimeTarget { + package: "fixture-runner".into(), + binary: "fixture".into(), + }, + "127.0.0.1:9000", + Some(&adapter), + None, + false, + &executable, + &[], + ); + + config.validate().unwrap(); + let api_url = config.processes["api"].url.clone().unwrap(); + let process = &config.processes["ui"]; + let ui_url = process.url.clone().unwrap(); + assert_eq!(process.program, "pnpm"); + assert_eq!(process.args[0], "dev"); + assert!(!process.args[1].contains('{'), "{:?}", process.args); + assert_eq!(process.env["FIXTURE_API"], format!("{api_url}/graphql")); + assert_eq!(process.env["FIXTURE_ORIGIN"], ui_url); + assert_eq!(process.env["DISTRIBUTED_FIXTURE_DEFAULT"], "development"); + assert!( + !process.env.contains_key("PATH"), + "a variable the shell sets keeps its value" + ); + assert_eq!(process.env["DISTRIBUTED_API_ORIGIN"], api_url); + // Nothing application-specific is passed unless the application asks. + let conventional = lifecycle_dev( + project.path(), + project.path(), + &RuntimeTarget { + package: "fixture-runner".into(), + binary: "fixture".into(), + }, + DEFAULT_API_BIND, + Some(&UiAdapter { + root: adapter.root.clone(), + ..UiAdapter::default() + }), + None, + false, + &executable, + &[], + ); + assert_eq!( + conventional.processes["ui"] + .env + .keys() + .map(String::as_str) + .collect::>(), + ["DISTRIBUTED_API_ORIGIN", LIFECYCLE_CLI_EXECUTABLE_ENV] + ); + assert_eq!(conventional.processes["ui"].program, "npm"); + assert_eq!( + conventional.processes["ui"].args[..5], + ["run", "dev", "--", "--host", "localhost"][..], + ); } #[test] @@ -1330,7 +1545,11 @@ mod tests { package: "fixture-runner".into(), binary: "fixture".into(), }, - Some(&ui), + DEFAULT_API_BIND, + Some(&UiAdapter { + root: ui.clone(), + ..UiAdapter::default() + }), Some(&javascript), true, &executable, @@ -1359,6 +1578,13 @@ mod tests { .find(|args| args[0] == "--project-root") .map(|args| args[1].as_str()); assert_eq!(project_root, application.to_str()); + assert_eq!( + framework + .env + .get(LIFECYCLE_CLI_EXECUTABLE_ENV) + .map(String::as_str), + executable.to_str() + ); } #[test] @@ -1448,7 +1674,11 @@ mod tests { package: "fixture-runner".into(), binary: "fixture".into(), }, - Some(&ui), + DEFAULT_API_BIND, + Some(&UiAdapter { + root: ui.clone(), + ..UiAdapter::default() + }), None, true, &executable, @@ -1471,6 +1701,13 @@ mod tests { .map(String::as_str), project.path().to_str() ); + assert_eq!( + process + .env + .get(LIFECYCLE_CLI_EXECUTABLE_ENV) + .map(String::as_str), + executable.to_str() + ); assert!(process.restart_on.is_empty()); } diff --git a/distributed_cli/src/main.rs b/distributed_cli/src/main.rs index 72c3bb810..b112431c5 100644 --- a/distributed_cli/src/main.rs +++ b/distributed_cli/src/main.rs @@ -12,7 +12,7 @@ struct Cli { fn main() { let cli = Cli::parse(); - if let Err(err) = distributed_cli::run_distributed(&cli.args) { + if let Err(err) = distributed_cli::run(&cli.args, &[]) { if matches!( &cli.args.command, DistributedCommands::Build(args) if matches!(args.output, LifecycleOutput::Json) diff --git a/distributed_cli/src/manifest_harness.rs b/distributed_cli/src/manifest_harness.rs index 391e779df..447cbfb29 100644 --- a/distributed_cli/src/manifest_harness.rs +++ b/distributed_cli/src/manifest_harness.rs @@ -9,6 +9,7 @@ use std::error::Error; use std::fs; use std::path::{Path, PathBuf}; use std::process::Command; +use std::sync::atomic::AtomicBool; use crate::cli::{path_for_toml, resolve_distributed_path}; use crate::SchemaDialect; @@ -32,6 +33,7 @@ pub(crate) enum HarnessMode { SchemaSql(SchemaDialect), SchemaGraphql, ClientManifest, + GameManifest, } impl HarnessMode { @@ -42,12 +44,14 @@ impl HarnessMode { HarnessMode::SchemaSql(SchemaDialect::Sqlite) => "schema-sqlite", HarnessMode::SchemaGraphql => "schema-graphql", HarnessMode::ClientManifest => "client-manifest", + HarnessMode::GameManifest => "game-manifest", } } fn default_entrypoint(self) -> &'static str { match self { HarnessMode::ClientManifest => "distributed_client_surface", + HarnessMode::GameManifest => "game_surface", HarnessMode::DescribeJson => "application_manifest", HarnessMode::SchemaSql(_) | HarnessMode::SchemaGraphql => "read_model_catalog", } @@ -58,9 +62,15 @@ impl HarnessMode { } } +/// Compile and run the harness for `options`, returning what it prints. +/// +/// `stop` is the session's stop flag when a `build` or `dev` session calls +/// this itself, and `None` in a helper or a one-off command (see +/// [`crate::process`]). pub(crate) fn run_manifest_harness( options: &HarnessOptions, mode: HarnessMode, + stop: Option<&AtomicBool>, ) -> Result> { let manifest_path = resolve_target_manifest_path(&options.path, options.manifest_path.as_deref())?; @@ -87,6 +97,12 @@ pub(crate) fn run_manifest_harness( .join(&package.name); let harness_dir = harness_root.join(mode.cache_key()); fs::create_dir_all(harness_dir.join("src"))?; + // One harness directory serves every entrypoint of this package and mode: + // hold it from writing `main.rs` until its output is read, or a concurrent + // run (a dev-server watcher next to a manual regenerate) swaps entrypoints + // under us and both print the last writer's export. + let lock = fs::File::create(harness_root.join(format!("{}.lock", mode.cache_key())))?; + fs2::FileExt::lock_exclusive(&lock)?; fs::write( harness_dir.join("Cargo.toml"), harness_cargo_toml( @@ -105,15 +121,21 @@ pub(crate) fn run_manifest_harness( )?; let manifest_path = harness_dir.join("Cargo.toml"); - let output = Command::new("cargo") + let mut command = Command::new("cargo"); + command .args([ "run", "--quiet", "--manifest-path", manifest_path.to_string_lossy().as_ref(), ]) - .env("CARGO_TARGET_DIR", harness_root.join("target")) - .output()?; + .env("CARGO_TARGET_DIR", harness_root.join("target")); + let output = crate::process::output(&mut command, stop)?.ok_or_else(|| { + format!( + "manifest harness for package `{}` was stopped", + package.name + ) + })?; if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); @@ -226,6 +248,13 @@ fn harness_main_rs(entrypoint: &str, mode: HarnessMode) -> String { .expect("read-model GraphQL SDL should render"); print!("{{}}", sdl); }} +"# + ), + HarnessMode::GameManifest => format!( + r#"fn main() {{ + let surface = {entrypoint}(); + println!("{{}}", serde_json::to_string_pretty(&surface).expect("game surface should serialize")); +}} "# ), HarnessMode::ClientManifest => format!( @@ -423,6 +452,18 @@ mod tests { assert!(!main_rs.contains("build_surface")); } + #[test] + fn game_harness_prints_the_surface_export() { + assert_eq!( + HarnessMode::GameManifest.default_entrypoint(), + "game_surface" + ); + assert!(!HarnessMode::GameManifest.requires_distributed_dependency()); + let main_rs = harness_main_rs("game_demos::arena::game_surface", HarnessMode::GameManifest); + assert!(main_rs.contains("let surface = game_demos::arena::game_surface();")); + assert!(main_rs.contains("serde_json::to_string_pretty(&surface)")); + } + #[test] fn client_harness_does_not_add_a_second_framework_dependency() { assert!(!HarnessMode::ClientManifest.requires_distributed_dependency()); diff --git a/distributed_cli/src/process.rs b/distributed_cli/src/process.rs new file mode 100644 index 000000000..2bc96397f --- /dev/null +++ b/distributed_cli/src/process.rs @@ -0,0 +1,435 @@ +//! Child processes owned by a `build` or `dev` session. +//! +//! A session starts each child as the leader of its own process group and owns +//! it through a [`ProcessGroup`]. Dropping the owner kills the whole group, so +//! a session that ends for any reason (a signal, a cancelled build, an error +//! return, a panic) leaves no descendant behind. +//! +//! Only the session's own process creates groups. A helper it runs (`describe`, +//! `__js-watch`) starts its children in the group it was given: a nested group +//! would escape the session's kill. So [`run`] and [`output`] take the session's +//! stop flag when the session calls them and `None` everywhere else. +//! +//! A group is signalled by its leader's process ID. Once the leader has been +//! reaped and the last member has exited, that ID is free again, so nothing +//! here signals a group it has already seen empty. +//! +//! Windows has no process groups. There the owner controls the direct child +//! only, and a grandchild can outlive the session. + +use std::io::{self, Read}; +use std::process::{Child, Command, ExitStatus, Output, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +const POLL: Duration = Duration::from_millis(10); +/// How long a foreground command gets to exit after SIGTERM. +const GRACE: Duration = Duration::from_secs(5); + +#[derive(Debug)] +pub(crate) struct ProcessGroup { + leader: Child, + /// The leader was reaped and no member was left. + gone: bool, +} + +impl ProcessGroup { + /// Start `command` as the leader of a new process group. + pub(crate) fn spawn(command: &mut Command) -> io::Result { + #[cfg(unix)] + std::os::unix::process::CommandExt::process_group(command, 0); + Ok(Self { + leader: command.spawn()?, + gone: false, + }) + } + + /// The direct child: its pipes, and its exit status once it has one. + pub(crate) fn leader(&mut self) -> &mut Child { + &mut self.leader + } + + /// Whether the leader or any other member of its group is still alive. + pub(crate) fn is_running(&mut self) -> io::Result { + if self.gone { + return Ok(false); + } + let mut running = self.leader.try_wait()?.is_none(); + #[cfg(unix)] + if !running { + running = match self.signal(0) { + Ok(delivered) => delivered, + // A member this user may not signal is still a member. + Err(error) if error.raw_os_error() == Some(libc::EPERM) => true, + Err(error) => return Err(error), + }; + } + self.gone = !running; + Ok(running) + } + + /// Ask every member to exit (SIGTERM). + pub(crate) fn terminate(&mut self) -> io::Result<()> { + if !self.is_running()? { + return Ok(()); + } + #[cfg(unix)] + { + self.signal(libc::SIGTERM).map(drop) + } + #[cfg(not(unix))] + { + self.leader.kill() + } + } + + /// Kill every member (SIGKILL) and reap the leader. + /// + /// SIGKILL cannot be caught and reaches every member in one call, so none + /// survives it. This does not wait for the kernel to finish removing + /// them: how long that takes depends on the machine's load, not on them. + pub(crate) fn kill(&mut self) -> io::Result<()> { + if self.gone { + return Ok(()); + } + #[cfg(unix)] + match self.signal(libc::SIGKILL) { + Ok(_) => {} + // macOS answers EPERM for a group whose members are all exiting. + Err(error) if error.raw_os_error() == Some(libc::EPERM) => {} + Err(error) => return Err(error), + } + // A leader that left its own group is not reached by the group signal. + // `Child::kill` does nothing once the leader has been reaped. + self.leader.kill()?; + self.leader.wait()?; + self.gone = true; + Ok(()) + } + + /// Wait up to `timeout` for the whole group to exit. + pub(crate) fn wait_gone(&mut self, timeout: Duration) -> io::Result { + let started = Instant::now(); + loop { + if !self.is_running()? { + return Ok(true); + } + if started.elapsed() >= timeout { + return Ok(false); + } + std::thread::sleep(POLL); + } + } + + /// Ask the group to exit, then kill whatever is left after `grace`. + pub(crate) fn stop(&mut self, grace: Duration) -> io::Result<()> { + self.terminate()?; + if self.wait_gone(grace)? { + return Ok(()); + } + self.kill() + } + + /// Send `signal` to the group. `Ok(false)` means the group has no member. + #[cfg(unix)] + fn signal(&self, signal: libc::c_int) -> io::Result { + // SAFETY: `kill` takes plain integers and touches no memory. + if unsafe { libc::kill(-(self.leader.id() as libc::pid_t), signal) } == 0 { + return Ok(true); + } + let error = io::Error::last_os_error(); + if error.raw_os_error() == Some(libc::ESRCH) { + Ok(false) + } else { + Err(error) + } + } +} + +impl Drop for ProcessGroup { + fn drop(&mut self) { + let _ = self.kill(); + } +} + +/// Run `command` until it exits or the session stops. +/// +/// `stop` is the session's stop flag: the command then leads its own process +/// group, and `None` is returned when it was stopped, its group gone. It gets +/// no standard input, because a background process group that reads the +/// terminal is suspended. +/// +/// Without `stop` this process is not a session (it is a helper inside a +/// session's group, or a one-off command) and the command is its ordinary +/// child. +pub(crate) fn run( + command: &mut Command, + stop: Option<&AtomicBool>, +) -> io::Result> { + let Some(stop) = stop else { + return command.status().map(Some); + }; + if stop.load(Ordering::SeqCst) { + return Ok(None); + } + let mut group = ProcessGroup::spawn(command.stdin(Stdio::null()))?; + wait(&mut group, stop) +} + +/// [`run`], collecting what the command writes to its output and error streams. +pub(crate) fn output( + command: &mut Command, + stop: Option<&AtomicBool>, +) -> io::Result> { + let Some(stop) = stop else { + return command.output().map(Some); + }; + if stop.load(Ordering::SeqCst) { + return Ok(None); + } + command + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let mut group = ProcessGroup::spawn(command)?; + let stdout = drain(group.leader().stdout.take()); + let stderr = drain(group.leader().stderr.take()); + let status = wait(&mut group, stop)?; + // A member that outlived the leader still holds the pipes open. + drop(group); + let (stdout, stderr) = (stdout.join(), stderr.join()); + let collected = |stream: std::thread::Result>>| { + stream.unwrap_or_else(|_| Err(io::Error::other("output reader panicked"))) + }; + let (stdout, stderr) = (collected(stdout)?, collected(stderr)?); + Ok(status.map(|status| Output { + status, + stdout, + stderr, + })) +} + +/// Wait for the leader to exit; stop the whole group when `stop` is set first. +fn wait(group: &mut ProcessGroup, stop: &AtomicBool) -> io::Result> { + loop { + if let Some(status) = group.leader().try_wait()? { + return Ok(Some(status)); + } + if stop.load(Ordering::SeqCst) { + group.stop(GRACE)?; + return Ok(None); + } + std::thread::sleep(POLL); + } +} + +/// Read a pipe to its end on another thread, so a full pipe never blocks the +/// command. +fn drain(pipe: Option) -> std::thread::JoinHandle>> { + std::thread::spawn(move || { + let mut bytes = Vec::new(); + if let Some(mut pipe) = pipe { + pipe.read_to_end(&mut bytes)?; + } + Ok(bytes) + }) +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use std::io::{BufRead, BufReader}; + + /// A leader that ignores SIGTERM and starts a grandchild that does too, + /// then prints both process IDs. + fn stubborn_family() -> (ProcessGroup, [libc::pid_t; 2]) { + let mut command = Command::new("/bin/sh"); + command + .args([ + "-c", + r#"trap "" TERM +/bin/sh -c 'trap "" TERM; while :; do sleep 1; done' & +echo "$$ $!" +wait"#, + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()); + let mut group = ProcessGroup::spawn(&mut command).expect("spawn process group"); + let mut line = String::new(); + BufReader::new(group.leader().stdout.take().expect("leader stdout")) + .read_line(&mut line) + .expect("read family process IDs"); + let mut pids = line + .split_whitespace() + .map(|pid| pid.parse().expect("process ID")); + let family = [pids.next().unwrap(), pids.next().unwrap()]; + assert_eq!(family[0], group.leader().id() as libc::pid_t); + (group, family) + } + + /// A process is gone once it cannot be signalled. The grandchild is not + /// this test's child, so nothing here can leave it a zombie. + fn assert_gone(family: [libc::pid_t; 2]) { + let started = Instant::now(); + loop { + let alive = family + .into_iter() + .filter(|pid| unsafe { libc::kill(*pid, 0) } == 0) + .collect::>(); + if alive.is_empty() { + return; + } + if started.elapsed() > Duration::from_secs(10) { + for pid in &alive { + unsafe { libc::kill(*pid, libc::SIGKILL) }; + } + panic!("processes outlived their group owner: {alive:?}"); + } + std::thread::sleep(POLL); + } + } + + #[test] + fn dropping_the_owner_kills_the_whole_group() { + let (group, family) = stubborn_family(); + drop(group); + assert_gone(family); + } + + #[test] + fn a_panicking_owner_kills_the_whole_group() { + let (group, family) = stubborn_family(); + let owner = std::thread::spawn(move || { + let _group = group; + panic!("the session failed"); + }); + assert!(owner.join().is_err()); + assert_gone(family); + } + + #[test] + fn stop_kills_members_that_ignore_the_request() { + let (mut group, family) = stubborn_family(); + group.stop(Duration::from_millis(50)).expect("stop group"); + assert!(!group.is_running().unwrap()); + assert_gone(family); + } + + #[test] + fn a_group_outlives_its_leader_until_killed() { + let mut command = Command::new("/bin/sh"); + command + .args(["-c", "sleep 60 & echo $!"]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()); + let mut group = ProcessGroup::spawn(&mut command).expect("spawn process group"); + let mut line = String::new(); + BufReader::new(group.leader().stdout.take().expect("leader stdout")) + .read_line(&mut line) + .expect("read descendant process ID"); + let descendant: libc::pid_t = line.trim().parse().expect("process ID"); + let leader = group.leader().id() as libc::pid_t; + assert!(group.leader().wait().expect("wait for leader").success()); + assert!(group.is_running().unwrap(), "the descendant is a member"); + group.kill().expect("kill group"); + assert_gone([leader, descendant]); + } + + #[test] + fn a_stopped_command_takes_its_descendants_with_it() { + let directory = tempfile::tempdir().unwrap(); + let pids = directory.path().join("pids"); + let stop = std::sync::Arc::new(AtomicBool::new(false)); + let runner = { + let (stop, pids) = (std::sync::Arc::clone(&stop), pids.clone()); + std::thread::spawn(move || { + let mut command = Command::new("/bin/sh"); + command.args([ + "-c", + r#"sleep 60 & echo "$$ $!" > "$0.tmp" && mv "$0.tmp" "$0"; wait"#, + pids.to_str().unwrap(), + ]); + run(&mut command, Some(&stop)) + }) + }; + let started = Instant::now(); + let family = loop { + if let Ok(line) = std::fs::read_to_string(&pids) { + let mut pids = line.split_whitespace().map(|pid| pid.parse().unwrap()); + break [pids.next().unwrap(), pids.next().unwrap()]; + } + assert!(started.elapsed() < Duration::from_secs(10)); + std::thread::sleep(POLL); + }; + stop.store(true, Ordering::SeqCst); + assert!(runner.join().unwrap().unwrap().is_none()); + assert_gone(family); + + let mut ignored = Command::new("/bin/sh"); + ignored.args(["-c", "exit 0"]); + assert!(run(&mut ignored, Some(&stop)).unwrap().is_none()); + stop.store(false, Ordering::SeqCst); + assert!(run(&mut ignored, Some(&stop)).unwrap().unwrap().success()); + } + + #[test] + fn output_is_collected_and_a_stopped_command_takes_its_descendants_with_it() { + let stop = std::sync::Arc::new(AtomicBool::new(false)); + // More than a pipe holds, on both streams, and a descendant that keeps + // them open after the leader exits. + let mut noisy = Command::new("/bin/sh"); + noisy.args([ + "-c", + "head -c 200000 /dev/zero; head -c 200000 /dev/zero >&2; sleep 60 & exit 3", + ]); + let output = output(&mut noisy, Some(&stop)).unwrap().unwrap(); + assert_eq!(output.status.code(), Some(3)); + assert_eq!( + (output.stdout.len(), output.stderr.len()), + (200_000, 200_000) + ); + + let directory = tempfile::tempdir().unwrap(); + let pids = directory.path().join("pids"); + let runner = { + let (stop, pids) = (std::sync::Arc::clone(&stop), pids.clone()); + std::thread::spawn(move || { + let mut command = Command::new("/bin/sh"); + command.args([ + "-c", + r#"sleep 60 & echo "$$ $!" > "$0.tmp" && mv "$0.tmp" "$0"; wait"#, + pids.to_str().unwrap(), + ]); + super::output(&mut command, Some(&stop)) + }) + }; + let started = Instant::now(); + let family = loop { + if let Ok(line) = std::fs::read_to_string(&pids) { + let mut pids = line.split_whitespace().map(|pid| pid.parse().unwrap()); + break [pids.next().unwrap(), pids.next().unwrap()]; + } + assert!(started.elapsed() < Duration::from_secs(10)); + std::thread::sleep(POLL); + }; + stop.store(true, Ordering::SeqCst); + assert!(runner.join().unwrap().unwrap().is_none()); + assert_gone(family); + } + + #[test] + fn outside_a_session_a_command_is_an_ordinary_child() { + let mut command = Command::new("/bin/sh"); + command.args(["-c", "echo out; echo err >&2; exit 4"]); + let output = output(&mut command, None).unwrap().unwrap(); + assert_eq!(output.status.code(), Some(4)); + assert_eq!( + (output.stdout, output.stderr), + (b"out\n".to_vec(), b"err\n".to_vec()) + ); + let mut command = Command::new("/bin/sh"); + // Its own process group would have its own ID. + command.args(["-c", r#"test "$(ps -o pgid= -p $$ | tr -d " ")" != "$$""#]); + assert!(run(&mut command, None).unwrap().unwrap().success()); + } +} diff --git a/distributed_cli/src/skills.rs b/distributed_cli/src/skills.rs index 5930c5d9d..3ea07cd22 100644 --- a/distributed_cli/src/skills.rs +++ b/distributed_cli/src/skills.rs @@ -40,7 +40,7 @@ pub struct EmbeddedSkill { pub files: &'static [EmbeddedFile], } -static SKILLS: [EmbeddedSkill; 4] = [ +static SKILLS: [EmbeddedSkill; 5] = [ EmbeddedSkill { name: "distributed-usage", description: "Build Distributed CQRS/event-sourced Rust services where you mostly write models and handlers while the framework and distributed generate persistence, transports, manifests, and deploy wiring. Use model-first TDD to specify plain aggregate behavior with fast unit tests before implementing models and thin handlers. Use when designing, testing, writing, or modifying a Distributed service or domain model.", @@ -72,6 +72,13 @@ static SKILLS: [EmbeddedSkill; 4] = [ relative_path: "SKILL.md", contents: include_str!("../skills/distributed-graphql/SKILL.md"), }], + }, EmbeddedSkill { + name: "distributed-game", + description: "Build authoritative game zones with distributed_game - a plain Rust Zone for the simulation, replicated entities with interest management, durable facts settled into cells, and zones that watch world cells as pushed read models. Use when writing or scaling a game zone, its facts, its replication, or its world cells (native host or celld).", + files: &[EmbeddedFile { + relative_path: "SKILL.md", + contents: include_str!("../skills/distributed-game/SKILL.md"), + }], }, ]; diff --git a/distributed_cli/src/wasm_pures.rs b/distributed_cli/src/wasm_pures.rs index 305286a1f..4b60a2367 100644 --- a/distributed_cli/src/wasm_pures.rs +++ b/distributed_cli/src/wasm_pures.rs @@ -11,6 +11,7 @@ use std::error::Error; use std::fs; use std::path::{Component, Path, PathBuf}; use std::process::Command; +use std::sync::atomic::AtomicBool; const MAX_SOURCE_FILES: usize = 20_000; const MAX_SOURCE_BYTES: u64 = 128 * 1024 * 1024; @@ -23,9 +24,11 @@ struct WasmPure { } #[derive(Debug, Deserialize)] -struct CargoMetadata { - workspace_root: PathBuf, - packages: Vec, +pub(crate) struct CargoMetadata { + pub(crate) workspace_root: PathBuf, + #[serde(default)] + pub(crate) target_directory: PathBuf, + pub(crate) packages: Vec, resolve: Option, #[serde(default)] metadata: Value, @@ -44,22 +47,24 @@ struct CargoResolveNode { } #[derive(Debug, Deserialize)] -struct CargoPackage { - id: String, - name: String, - manifest_path: PathBuf, - source: Option, +pub(crate) struct CargoPackage { + pub(crate) id: String, + pub(crate) name: String, + pub(crate) manifest_path: PathBuf, + pub(crate) source: Option, #[serde(default)] features: BTreeMap>, #[serde(default)] - targets: Vec, + pub(crate) targets: Vec, } #[derive(Debug, Deserialize)] -struct CargoTarget { +pub(crate) struct CargoTarget { + #[serde(default)] + pub(crate) name: String, src_path: PathBuf, #[serde(default)] - kind: Vec, + pub(crate) kind: Vec, } #[derive(Debug, Deserialize, Serialize)] @@ -71,10 +76,13 @@ struct WasmStamp { import: String, } +/// Compile the browser WASM the manifest declares. `stop` is the session's +/// stop flag, or `None` outside a session (see [`crate::process`]). pub(crate) fn build_declared_wasm_pures( manifest: &Value, cargo_manifest: &Path, wasm_pack_launcher: Option<&Path>, + stop: Option<&AtomicBool>, ) -> Result> { let pures = collect_wasm_pures(manifest)?; if pures.is_empty() { @@ -82,13 +90,13 @@ pub(crate) fn build_declared_wasm_pures( } let metadata = cargo_metadata(cargo_manifest)?; let project_root = &metadata.workspace_root; - let Some(ui_root) = crate::lifecycle::discover_ui(&metadata.metadata, project_root)? else { + let Some(ui) = crate::lifecycle::discover_ui(&metadata.metadata, project_root)? else { return Ok(0); }; + let ui_root = ui.root; let ui_lib = ui_root.join("src/lib"); - let wasm_pack_launcher = wasm_pack_launcher.ok_or( - "browser WASM pures require @hops-ops/distributed in the application UI", - )?; + let wasm_pack_launcher = wasm_pack_launcher + .ok_or("browser WASM pures require @hops-ops/distributed in the application UI")?; let compiler_identity = compiler_identity(wasm_pack_launcher)?; let mut outputs = BTreeMap::::new(); for pure in &pures { @@ -151,6 +159,7 @@ pub(crate) fn build_declared_wasm_pures( &destination, &stamp_path, &stamp, + stop, )?; } Ok(pures.len()) @@ -198,7 +207,7 @@ fn collect_wasm_pures(manifest: &Value) -> Result, Box Result> { Ok(path.to_path_buf()) } -fn cargo_metadata(manifest: &Path) -> Result> { +pub(crate) fn cargo_metadata(manifest: &Path) -> Result> { let output = Command::new("cargo") .args(["metadata", "--format-version", "1", "--manifest-path"]) .arg(manifest) @@ -270,7 +279,7 @@ fn cargo_metadata(manifest: &Path) -> Result> { Ok(serde_json::from_slice(&output.stdout)?) } -fn package_source_identity( +pub(crate) fn package_source_identity( metadata: &CargoMetadata, root_package_id: &str, ) -> Result> { @@ -410,7 +419,9 @@ fn collect_source_files( fn compiler_identity(launcher: &Path) -> Result> { let launcher = launcher.canonicalize().map_err(|error| { format!( - "failed to resolve browser WASM compiler `{}`: {error}", + "failed to resolve browser WASM compiler `{}`: {error}; browser WASM pures need the \ + `wasm-pack` npm package installed there (an optional peer of \ + @hops-ops/distributed: add it to the application UI's devDependencies)", launcher.display() ) })?; @@ -437,7 +448,11 @@ fn compiler_identity(launcher: &Path) -> Result> { ) .into()); } - hash.update(file.strip_prefix(package_root)?.to_string_lossy().as_bytes()); + hash.update( + file.strip_prefix(package_root)? + .to_string_lossy() + .as_bytes(), + ); hash.update([0]); hash.update(&content); hash.update([0]); @@ -496,6 +511,9 @@ fn stamp_matches( && observed.compiler_identity == expected.compiler_identity && observed.rust_package == expected.rust_package && observed.import == expected.import + && destination + .join(crate::lifecycle::GENERATED_DIRECTORY_MARKER) + .is_file() && destination .join(format!( "{}_bg.wasm", @@ -525,6 +543,7 @@ fn build_wasm_pure( destination: &Path, stamp_path: &Path, stamp: &WasmStamp, + stop: Option<&AtomicBool>, ) -> Result<(), Box> { let parent = destination .parent() @@ -548,22 +567,31 @@ fn build_wasm_pure( "distributed: compiling required browser WASM {} from Cargo package {}", stamp.import, stamp.rust_package ); - let output = Command::new("node") + let mut compiler = Command::new("node"); + compiler .arg(wasm_pack_launcher) .arg("build") .arg(package_dir) .args(["--target", "web", "--out-dir"]) .arg(stage.path()) - .args(["--out-name", output_name, "--", "--no-default-features", "--features", "wasm"]) + .args([ + "--out-name", + output_name, + "--", + "--no-default-features", + "--features", + "wasm", + ]) .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::inherit()) - .status() + .stderr(std::process::Stdio::inherit()); + let output = crate::process::run(&mut compiler, stop) .map_err(|error| { format!( "failed to start the @hops-ops/distributed WASM compiler `{}` for pure `{}`; run `distributed build` from `{}`: {error}", wasm_pack_launcher.display(), stamp.import, project_root.display() ) - })?; + })? + .ok_or_else(|| format!("WASM compiler for pure `{}` was stopped", stamp.import))?; if !output.success() { return Err(format!( "required WASM pure `{}` failed to compile with {output}", @@ -584,6 +612,14 @@ fn build_wasm_pure( .into()); } } + // The package lands under the UI's `src/lib`, which the lifecycle watches. + // The marker keeps it out of the watched inputs. + fs::write( + stage + .path() + .join(crate::lifecycle::GENERATED_DIRECTORY_MARKER), + "Generated by `distributed` from a Rust package. Not a lifecycle input.\n", + )?; let staged_path = stage.keep(); let backup = tempfile::Builder::new() .prefix(".distributed-wasm-backup-") @@ -615,7 +651,10 @@ fn build_wasm_pure( Ok(()) } -fn ensure_real_directory_path(root: &Path, directory: &Path) -> Result<(), Box> { +pub(crate) fn ensure_real_directory_path( + root: &Path, + directory: &Path, +) -> Result<(), Box> { let relative = directory.strip_prefix(root).map_err(|_| { format!( "generated directory `{}` escapes project `{}`", @@ -718,12 +757,14 @@ mod tests { source: None, features: BTreeMap::new(), targets: vec![CargoTarget { + name: String::new(), src_path: directory.join("src/lib.rs"), kind: vec!["lib".to_string()], }], } }; let metadata = CargoMetadata { + target_directory: PathBuf::new(), workspace_root: root.to_path_buf(), packages: vec![ package("pure", "pure"), @@ -766,6 +807,7 @@ mod tests { fs::write(package_dir.join("lib.rs"), "mod sibling;\n").unwrap(); fs::write(package_dir.join("sibling.rs"), "pub const VALUE: u8 = 1;\n").unwrap(); let metadata = CargoMetadata { + target_directory: PathBuf::new(), workspace_root: workspace.to_path_buf(), packages: vec![CargoPackage { id: "pure".to_string(), @@ -774,6 +816,7 @@ mod tests { source: None, features: BTreeMap::new(), targets: vec![CargoTarget { + name: String::new(), src_path: package_dir.join("lib.rs"), kind: vec!["lib".to_string()], }], @@ -813,12 +856,14 @@ mod tests { source: None, features: BTreeMap::new(), targets: vec![CargoTarget { + name: String::new(), src_path: directory.join("src/lib.rs"), kind: vec![kind.to_string()], }], } }; let metadata = CargoMetadata { + target_directory: PathBuf::new(), workspace_root: root.to_path_buf(), packages: vec![ package("pure", "cdylib"), @@ -863,6 +908,7 @@ mod tests { targets: Vec::new(), }; let metadata = CargoMetadata { + target_directory: PathBuf::new(), workspace_root: PathBuf::from("/repo/application"), packages: vec![package], resolve: None, @@ -882,6 +928,7 @@ mod tests { import: "domain/pkg/domain_wasm".to_string(), }; let metadata = CargoMetadata { + target_directory: PathBuf::new(), workspace_root: PathBuf::from("/repo/application"), packages: vec![CargoPackage { id: "registry+https://example.invalid#domain@0.1.0".to_string(), @@ -916,6 +963,7 @@ mod tests { targets: Vec::new(), }; let metadata = CargoMetadata { + target_directory: PathBuf::new(), workspace_root: PathBuf::from("/repo/application"), packages: vec![package("domain-one"), package("domain-two")], resolve: None, @@ -927,5 +975,4 @@ mod tests { .to_string() .contains("more than one local Cargo package")); } - } diff --git a/distributed_cli/tests/bats/lifecycle.bats b/distributed_cli/tests/bats/lifecycle.bats index 383e70b53..2087faeee 100644 --- a/distributed_cli/tests/bats/lifecycle.bats +++ b/distributed_cli/tests/bats/lifecycle.bats @@ -12,7 +12,7 @@ setup() { ROOT="$(cd "$ROOT" && pwd -P)" DEV_LOG="$ROOT/dev.log" SUPERVISOR_PID="" - write_fixture + PROJECT="" } teardown() { @@ -21,11 +21,14 @@ teardown() { wait_for_exit "$SUPERVISOR_PID" 100 || kill -TERM "$SUPERVISOR_PID" 2>/dev/null || true wait "$SUPERVISOR_PID" 2>/dev/null || true fi - if [ -f "$ROOT/dev-descendants.log" ]; then - while IFS= read -r pid; do - kill -TERM "$pid" 2>/dev/null || true - done < "$ROOT/dev-descendants.log" - fi + # The test project's processes start descendants that ignore SIGTERM. + for log in "$PROJECT/dev-family.log" "$PROJECT/build-family.log"; do + if [ -n "$PROJECT" ] && [ -f "$log" ]; then + for pid in $(cat "$log"); do + kill -KILL "$pid" 2>/dev/null || true + done + fi + done } @test "project build and dev are zero-config and invalid typed exports fail before UI" { @@ -121,7 +124,7 @@ SCRIPT printf 'unexpected invalid-export diagnostic:\n%s\n' "$output" >&2 false fi - [[ "$output" != *'compiling SvelteKit UI'* ]] + [[ "$output" != *'distributed build: UI '* ]] [ "$(cat "$ROOT/npm.log")" = 'npm-must-not-run' ] [ "$(cat "$PROJECT/.distributed/lifecycle/active.json")" = "$active_before" ] } @@ -162,49 +165,53 @@ SCRIPT } @test "build activates atomically and check reports drift without replacing active" { - run "$DISTRIBUTED_BIN" build --root "$ROOT" --output json + write_project + ACTIVE="$PROJECT/.distributed/lifecycle/active.json" + + run project build --output json [ "$status" -eq 0 ] [[ "$output" == *'"ok":true'* ]] - [[ "$output" == *'"executed":["application","plan"]'* ]] - [ -f "$ROOT/dist/distributed/active.json" ] - active_before="$(cat "$ROOT/dist/distributed/active.json")" + [[ "$output" == *'"executed":["application"]'* ]] + [ -f "$ACTIVE" ] + active_before="$(cat "$ACTIVE")" - run "$DISTRIBUTED_BIN" build --root "$ROOT" --check --output json + run project build --check --output json [ "$status" -eq 0 ] [[ "$output" == *'"drift":[]'* ]] - [ "$(cat "$ROOT/dist/distributed/active.json")" = "$active_before" ] + [ "$(cat "$ACTIVE")" = "$active_before" ] - printf 'second\n' > "$ROOT/src/input.txt" - run "$DISTRIBUTED_BIN" build --root "$ROOT" --check --output json + printf 'renamed\n' > "$PROJECT/service/src/name.txt" + run project build --check --output json [ "$status" -eq 1 ] [[ "$output" == *'"ok":false'* ]] [[ "$output" == *'"node_id":"application"'* ]] - [ "$(cat "$ROOT/dist/distributed/active.json")" = "$active_before" ] + [ "$(cat "$ACTIVE")" = "$active_before" ] - : > "$ROOT/fail-plan" - run "$DISTRIBUTED_BIN" build --root "$ROOT" --output json + : > "$PROJECT/fail-manifest" + run project build --output json [ "$status" -ne 0 ] - [[ "$output" == *'injected plan failure'* ]] - [ "$(cat "$ROOT/dist/distributed/active.json")" = "$active_before" ] + [[ "$output" == *'injected manifest failure'* ]] + [ "$(cat "$ACTIVE")" = "$active_before" ] } @test "dev reports process readiness, rebuilds selectively, and cleans descendants" { - "$DISTRIBUTED_BIN" dev --root "$ROOT" > "$DEV_LOG" 2>&1 & + write_project + project dev > "$DEV_LOG" 2>&1 & SUPERVISOR_PID=$! - wait_for_log 'lifecycle dev: ready generation=' 300 - grep -F 'lifecycle dev: process api ready http://127.0.0.1:18081/health' "$DEV_LOG" - grep -F 'lifecycle dev: process ui ready http://127.0.0.1:15181' "$DEV_LOG" - grep -F "api:api:$ROOT/src" "$ROOT/dev-environment.log" - grep -F "ui:ui:$ROOT/src" "$ROOT/dev-environment.log" + wait_for_log 'lifecycle dev: ready generation=' 6000 + grep -F "lifecycle dev: process api ready http://127.0.0.1:$API_PORT" "$DEV_LOG" + grep -F "lifecycle dev: process ui ready http://127.0.0.1:$UI_PORT_VALUE" "$DEV_LOG" + grep -Fx "api:$PROJECT" "$PROJECT/dev-environment.log" + grep -Fx "ui:$PROJECT/ui" "$PROJECT/dev-environment.log" - printf 'second\n' > "$ROOT/src/input.txt" - wait_for_log 'invalidated=application,plan restarted=api' 300 - [ "$(grep -c '^api:' "$ROOT/dev-process.log")" -eq 2 ] - [ "$(grep -c '^ui:' "$ROOT/dev-process.log")" -eq 1 ] + printf 'renamed\n' > "$PROJECT/service/src/name.txt" + wait_for_log 'invalidated=application restarted=api' 6000 + [ "$(grep -c '^api:' "$PROJECT/dev-process.log")" -eq 2 ] + [ "$(grep -c '^ui:' "$PROJECT/dev-process.log")" -eq 1 ] kill -INT "$SUPERVISOR_PID" - wait_for_exit "$SUPERVISOR_PID" 200 + wait_for_exit "$SUPERVISOR_PID" 600 wait "$SUPERVISOR_PID" dev_status=$? SUPERVISOR_PID="" @@ -212,26 +219,34 @@ SCRIPT grep -F 'process=api restarts=1' "$DEV_LOG" grep -F 'process=ui restarts=0' "$DEV_LOG" - while IFS= read -r pid; do + # Three processes ran, each with a descendant. + [ "$(wc -w < "$PROJECT/dev-family.log" | tr -d ' ')" -eq 6 ] + for pid in $(cat "$PROJECT/dev-family.log"); do ! kill -0 "$pid" 2>/dev/null - done < "$ROOT/dev-descendants.log" + done } @test "Ctrl-C cancels the initial build before any process starts" { - : > "$ROOT/slow-plan" - "$DISTRIBUTED_BIN" dev --root "$ROOT" > "$DEV_LOG" 2>&1 & + write_project + : > "$PROJECT/slow-manifest" + project dev > "$DEV_LOG" 2>&1 & SUPERVISOR_PID=$! - wait_for_file "$ROOT/build-plan-starts.log" 300 + wait_for_file "$PROJECT/build-family.log" 6000 + # The file exists before the harness has written its record. + while [ ! -s "$PROJECT/build-family.log" ]; do sleep 0.05; done kill -INT "$SUPERVISOR_PID" - wait_for_exit "$SUPERVISOR_PID" 200 + wait_for_exit "$SUPERVISOR_PID" 600 wait "$SUPERVISOR_PID" || dev_status=$? dev_status="${dev_status:-0}" SUPERVISOR_PID="" [ "$dev_status" -ne 0 ] grep -F 'lifecycle build was canceled' "$DEV_LOG" - [ ! -e "$ROOT/dev-process.log" ] + [ ! -e "$PROJECT/dev-process.log" ] + for pid in $(cat "$PROJECT/build-family.log"); do + ! kill -0 "$pid" 2>/dev/null + done } free_port() { @@ -291,142 +306,35 @@ wait_for_exit() { return 1 } -write_fixture() { - mkdir -p "$ROOT/src" "$ROOT/plan" "$ROOT/generated" - printf 'first\n' > "$ROOT/src/input.txt" - printf 'local\n' > "$ROOT/plan/input.txt" - printf 'application:first\n' > "$ROOT/generated/application.json" - printf 'plan:local:application:first\n' > "$ROOT/generated/plan.json" - - cat > "$ROOT/build-app.sh" <<'SCRIPT' -#!/bin/sh -set -eu -root=$1 -sed 's/^/application:/' "$root/src/input.txt" -SCRIPT - - cat > "$ROOT/build-plan.sh" <<'SCRIPT' -#!/bin/sh -set -eu -root=$1 -stage=$2 -if [ -f "$root/fail-plan" ]; then - printf 'injected plan failure\n' >&2 - exit 17 -fi -if [ -f "$root/slow-plan" ]; then - printf 'started\n' >> "$root/build-plan-starts.log" - while [ -f "$root/slow-plan" ]; do sleep 0.05; done -fi -printf 'plan:' > "$stage/generated/plan.json" -tr -d '\n' < "$root/plan/input.txt" >> "$stage/generated/plan.json" -printf ':' >> "$stage/generated/plan.json" -cat "$stage/generated/application.json" >> "$stage/generated/plan.json" -SCRIPT - - cat > "$ROOT/dev-child.sh" <<'SCRIPT' -#!/bin/sh -set -eu -root=$1 -name=$2 -printf '%s:%s:%s\n' "$name" "$DISTRIBUTED_GENERATION_ID" "$DISTRIBUTED_RELEASE_ID" >> "$root/dev-process.log" -printf '%s:%s:%s\n' "$name" "$DEV_FIXTURE_NAME" "$PWD" >> "$root/dev-environment.log" -trap 'exit 0' TERM -/bin/sh -c 'trap "" TERM; while :; do sleep 1; done' & -descendant=$! -printf '%s\n' "$descendant" >> "$root/dev-descendants.log" -wait "$descendant" -SCRIPT - chmod +x "$ROOT/build-app.sh" "$ROOT/build-plan.sh" "$ROOT/dev-child.sh" - - cat > "$ROOT/distributed.contracts.json" <<'JSON' -{ - "schema_version": 1, - "entries": { - "application": { - "id": "application", - "kind": "application_manifest", - "scope": { "id": "application/bats" }, - "owner": "application/bats", - "identity": { "kind": "application_manifest", "value": "ref:application" }, - "provenance": { "sources": ["src/input.txt"], "generator": "bats.application" }, - "outputs": { "manifest": "generated/application.json" }, - "lifecycle": ["build", "check", "dev"] - }, - "plan": { - "id": "plan", - "kind": "deployment_plan", - "scope": { "id": "deployment/bats" }, - "owner": "deployment/bats", - "identity": { "kind": "deployment_plan", "value": "ref:plan" }, - "provenance": { - "sources": ["generated/application.json", "plan/input.txt"], - "generator": "bats.plan" - }, - "predecessor": { - "entry_id": "application", - "identity": { "kind": "application_manifest", "value": "ref:application" } - }, - "outputs": { "plan": "generated/plan.json" }, - "lifecycle": ["build", "check", "dev"] - } - } -} -JSON - - cat > "$ROOT/distributed.lifecycle.json" <<'JSON' -{ - "schema_version": 1, - "application": "bats", - "source": { - "rust": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "cli": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "javascript": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - }, - "roots": ["plan"], - "executors": { - "bats.application": { - "identity": "sha256:1111111111111111111111111111111111111111111111111111111111111111", - "program": "/bin/sh", - "args": ["{root}/build-app.sh", "{root}"], - "stdout": "generated/application.json" - }, - "bats.plan": { - "identity": "sha256:2222222222222222222222222222222222222222222222222222222222222222", - "program": "/bin/sh", - "args": ["{root}/build-plan.sh", "{root}", "{stage}"] - } - }, - "dev": { - "poll_ms": 20, - "debounce_ms": 30, - "shutdown_ms": 100, - "processes": { - "api": { - "program": "/bin/sh", - "args": ["{root}/dev-child.sh", "{root}", "{process}"], - "cwd": "src", - "env": { "DEV_FIXTURE_NAME": "{process}" }, - "url": "http://127.0.0.1:18081/health", - "restart_on": ["application"], - "ready": { - "program": "/bin/test", - "args": ["-f", "{root}/dist/distributed/active.json"], - "interval_ms": 10, - "timeout_ms": 2000 - } - }, - "ui": { - "program": "/bin/sh", - "args": ["{root}/dev-child.sh", "{root}", "{process}"], - "cwd": "src", - "env": { "DEV_FIXTURE_NAME": "{process}" }, - "url": "http://127.0.0.1:15181", - "restart_on": [], - "ready_after_ms": 20 - } - } - } +# The lifecycle test project (tests/fixtures/lifecycle-project) as $PROJECT: +# a Cargo workspace whose API and UI listen on ports of their own. +write_project() { + PROJECT="$ROOT/project" + API_PORT="$(free_port)" + UI_PORT_VALUE="$(free_port)" + while [ "$UI_PORT_VALUE" = "$API_PORT" ]; do + UI_PORT_VALUE="$(free_port)" + done + cp -R "$DISTRIBUTED_ROOT/distributed_cli/tests/fixtures/lifecycle-project" "$PROJECT" + for manifest in "$PROJECT/Cargo.toml" "$PROJECT/service/Cargo.toml"; do + sed -e "s|@DISTRIBUTED@|$DISTRIBUTED_ROOT|" \ + -e "s|@API_PORT@|$API_PORT|" \ + -e "s|@UI_PORT@|$UI_PORT_VALUE|" \ + "$manifest" > "$manifest.next" + mv "$manifest.next" "$manifest" + done + # The framework's lock file resolves the project without the network. + cp "$DISTRIBUTED_ROOT/Cargo.lock" "$PROJECT/Cargo.lock" } -JSON + +# `distributed $PROJECT ...`, replacing the subshell that `run` or +# `&` started, so that `$!` is the CLI itself. The test projects of this file +# share one Cargo target directory, and their own metadata decides where they +# listen. +project() { + command=$1 + shift + exec env -u BIND -u UI_HOST -u UI_BIND -u UI_PORT -u UI_URL -u PUBLIC_ORIGIN \ + CARGO_TARGET_DIR="$BATS_FILE_TMPDIR/lifecycle-project-target" \ + "$DISTRIBUTED_BIN" "$command" "$PROJECT" "$@" } diff --git a/distributed_cli/tests/cli_client.rs b/distributed_cli/tests/cli_client.rs index 3b0f73dd4..b7baa0533 100644 --- a/distributed_cli/tests/cli_client.rs +++ b/distributed_cli/tests/cli_client.rs @@ -16,24 +16,14 @@ const ROLE_MANIFEST: &str = r#"{ "kind": "role", "name": "user" }, - "schema_fingerprint": "sha256:758a97e4f7e1e538e8be86d24abd3d50a8da2d5813d29abd7a04bfa092d05189", - "protocol_fingerprint": "sha256:00fb342f3acb4dc1c1716a43cc3001c748d5f6c500ff831690d820e9e43e2782", + "schema_fingerprint": "sha256:eb28c89f691ba3b5500f63a610f427dfa6a2a2a46e8874330411a98199e21d15", + "protocol_fingerprint": "sha256:0dfa8a3f49e17d8d99c5c095c1ed14f528cae3e55fbc2f2b852975a50936ec5b", "execution": { "max_depth": 8, - "max_complexity": 500, + "max_fields": 500, + "max_rows": 200000, "max_bool_width": 256, - "max_in_list": 1000, - "complexity": { - "version": 1, - "scalar": 1, - "belongs_to": 2, - "has_many": 10, - "m2m": 12, - "aggregate": 8, - "list_root": 3, - "by_pk": 1, - "list_fanout": 5 - } + "max_in_list": 1000 }, "capabilities": { "live_queries": false, @@ -382,6 +372,53 @@ fn snapshot_tree(root: &Path) -> BTreeMap> { snapshot } +#[test] +fn literal_text_search_generates_a_typed_load_island() { + let project = project_dir("client-literal-text"); + fs::write( + project.join("client-manifest.json"), + ROLE_MANIFEST + .replace("\"_ilike\"", "\"_ilike\", \"_icontains\"") + // Adding a filter changes the selected schema contract. + .replace( + "sha256:eb28c89f691ba3b5500f63a610f427dfa6a2a2a46e8874330411a98199e21d15", + "sha256:ef5eca766105f3447552a5662d8553ef6b4c9a0a9ae20b70257152208aca88ca", + ), + ) + .unwrap(); + write_document( + &project, + "queries/search.graphql", + r#" + query SearchTodos($q: String! = "") @load { + todos(where: {title: {_icontains: $q}}, limit: 20) { id title } + } + "#, + ); + assert_success( + &generate(&project, "queries/*.graphql", &[]), + "literal search generation", + ); + assert_success( + &generate(&project, "queries/*.graphql", &["--check"]), + "literal search drift check", + ); + let inventory = fs::read_to_string(project.join("generated/islands.json")).unwrap(); + assert!(inventory.contains("SearchTodos")); + assert!(inventory.contains("\"load\": true")); + assert!(inventory.contains("String!")); + write_document( + &project, + "queries/search.graphql", + r#" + query SearchTodos { todos(where: {title: {_icontains: 1}}) { id } } + "#, + ); + assert!(!generate(&project, "queries/*.graphql", &[]) + .status + .success()); +} + #[test] fn generate_then_check_accepts_the_exact_artifact_tree() { let project = project_dir("client-generate-check"); @@ -584,7 +621,7 @@ fn unmatched_document_glob_fails_before_creating_output() { #[test] fn component_load_intent_remains_framework_neutral_outside_route_conventions() { - let project = project_dir("client-component-load"); + let project = project_dir("client-component-load"); write_document(&project, "queries/todos.graphql", LOAD_TODOS_QUERY); let unplaced = generate(&project, "queries/*.graphql", &[]); @@ -596,10 +633,10 @@ fn component_load_intent_remains_framework_neutral_outside_route_conventions() { "unplaced component island must retain its load intent for the adapter" ); - assert!( - !project.join("generated/routes.ts").exists(), - "the framework-neutral compiler must not invent adapter route ownership" - ); + assert!( + !project.join("generated/routes.ts").exists(), + "the framework-neutral compiler must not invent adapter route ownership" + ); } #[test] diff --git a/distributed_cli/tests/cli_game_client.rs b/distributed_cli/tests/cli_game_client.rs new file mode 100644 index 000000000..c3a79c52c --- /dev/null +++ b/distributed_cli/tests/cli_game_client.rs @@ -0,0 +1,326 @@ +//! `distributed game-client` / `game-manifest`. +//! +//! The golden surface is the one `distributed_game`'s authoring test writes +//! (`distributed_game/tests/fixtures/authoring.json`); its generated +//! TypeScript is pinned in `tests/fixtures/game-client/sample/`, type-checked +//! by `js` (`npm run check:generated`) and round-tripped against the Rust +//! samples by `js/tests/game-generated.test.mjs`. Regenerate with +//! `UPDATE_GOLDEN=1 cargo test -p distributed_cli --test cli_game_client`. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use distributed_cli::{generate_game_client, ImportExtension}; + +#[path = "support/golden.rs"] +mod golden; +use golden::assert_golden; + +fn root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).to_path_buf() +} + +fn sample_surface() -> String { + let path = root().join("../distributed_game/tests/fixtures/authoring.json"); + let fixture: serde_json::Value = + serde_json::from_str(&fs::read_to_string(path).expect("authoring fixture")).unwrap(); + serde_json::to_string_pretty(&fixture["surface"]).unwrap() +} + +fn distributed(args: &[&str]) -> std::process::Output { + Command::new(env!("CARGO_BIN_EXE_distributed")) + .args(args) + .output() + .expect("distributed should run") +} + +#[test] +fn generated_typescript_matches_the_golden_files() { + let files = generate_game_client(&sample_surface(), ImportExtension::Ts).unwrap(); + let names: Vec<_> = files.iter().map(|f| f.path.as_str()).collect(); + assert_eq!( + names, + [ + "client.ts", + "constants.ts", + "events.ts", + "index.ts", + "input.ts", + "predict.ts", + "pures.ts", + "schema.ts", + "surface.json" + ] + ); + for file in &files { + assert_golden(&format!("game-client/sample/{}", file.path), &file.contents); + } + // Deterministic: a second run is byte-identical. + assert_eq!( + generate_game_client(&sample_surface(), ImportExtension::Ts).unwrap(), + files + ); + // Only the SDK is imported from outside the directory. + for file in files.iter().filter(|f| f.path.ends_with(".ts")) { + for line in file + .contents + .lines() + .filter(|l| l.starts_with("import ") || l.starts_with("export * from")) + { + assert!( + line.contains("'@hops-ops/distributed/game'") || line.contains("'./"), + "{}: unexpected import {line}", + file.path + ); + } + } +} + +#[test] +fn import_extension_is_configurable() { + let js = generate_game_client(&sample_surface(), ImportExtension::Js).unwrap(); + let index = js.iter().find(|f| f.path == "index.ts").unwrap(); + assert!(index.contents.contains("export * from './schema.js';")); + let none = generate_game_client(&sample_surface(), ImportExtension::None).unwrap(); + let index = none.iter().find(|f| f.path == "index.ts").unwrap(); + assert!(index.contents.contains("export * from './schema';")); +} + +#[test] +fn check_mode_detects_drift_and_write_keeps_foreign_files() { + let tmp = tempfile::tempdir().unwrap(); + let manifest = tmp.path().join("surface.json"); + fs::write(&manifest, sample_surface()).unwrap(); + let out = tmp.path().join("gen"); + let (m, o) = (manifest.to_str().unwrap(), out.to_str().unwrap()); + + let check = distributed(&["game-client", "--manifest", m, "--out", o, "--check"]); + assert!(!check.status.success()); + assert!(String::from_utf8_lossy(&check.stderr).contains("missing schema.ts")); + + assert!(distributed(&["game-client", "--manifest", m, "--out", o]) + .status + .success()); + assert!( + distributed(&["game-client", "--manifest", m, "--out", o, "--check"]) + .status + .success() + ); + + // Regenerating identical output does not rewrite (or touch) any file. + let modified = |name: &str| fs::metadata(out.join(name)).unwrap().modified().unwrap(); + let before = modified("schema.ts"); + std::thread::sleep(std::time::Duration::from_millis(20)); + assert!(distributed(&["game-client", "--manifest", m, "--out", o]) + .status + .success()); + assert_eq!(modified("schema.ts"), before); + + fs::write(out.join("events.ts"), "// edited").unwrap(); + fs::write( + out.join("stale.ts"), + "// @generated by `distributed game-client` (old)", + ) + .unwrap(); + let check = distributed(&["game-client", "--manifest", m, "--out", o, "--check"]); + let stderr = String::from_utf8_lossy(&check.stderr); + assert!(!check.status.success()); + assert!(stderr.contains("changed events.ts"), "{stderr}"); + assert!(stderr.contains("unexpected stale.ts"), "{stderr}"); + + // Regenerating removes stale generated files... + assert!(distributed(&["game-client", "--manifest", m, "--out", o]) + .status + .success()); + assert!(!out.join("stale.ts").exists()); + // ...but refuses to delete files it did not generate. + fs::write(out.join("mine.ts"), "export const x = 1;").unwrap(); + let write = distributed(&["game-client", "--manifest", m, "--out", o]); + assert!(!write.status.success()); + assert!(out.join("mine.ts").exists()); +} + +#[test] +fn invalid_surfaces_are_rejected() { + let tmp = tempfile::tempdir().unwrap(); + let manifest = tmp.path().join("surface.json"); + fs::write(&manifest, r#"{"schemaVersion": 9}"#).unwrap(); + let out = tmp.path().join("gen"); + let run = distributed(&[ + "game-client", + "--manifest", + manifest.to_str().unwrap(), + "--out", + out.to_str().unwrap(), + ]); + assert!(!run.status.success()); + assert!(String::from_utf8_lossy(&run.stderr).contains("schemaVersion")); +} + +#[test] +#[ignore = "compiles the fixture via the manifest harness; run in the integration job"] +fn game_manifest_runs_the_surface_export() { + let manifest = root().join("tests/fixtures/game-surface/Cargo.toml"); + let tmp = tempfile::tempdir().unwrap(); + let out = tmp.path().join("orbs.json"); + let run = distributed(&[ + "game-manifest", + "--manifest-path", + manifest.to_str().unwrap(), + "--out", + out.to_str().unwrap(), + ]); + assert!( + run.status.success(), + "{}", + String::from_utf8_lossy(&run.stderr) + ); + let surface: serde_json::Value = + serde_json::from_str(&fs::read_to_string(&out).unwrap()).unwrap(); + assert_eq!(surface["schemaVersion"], 3); + assert_eq!(surface["name"], "orbs"); + assert_eq!(surface["predict"]["export"], "orb_step"); + assert_eq!(surface["predict"]["package"], "game-surface-fixture"); + assert_eq!(surface["pures"][0]["export"], "orb_radius"); + assert_eq!(surface["constants"][0]["value"]["limit"], 32.0); + assert_eq!( + surface["kinds"][0]["fields"][0]["correction"]["durationMs"], + 80 + ); + assert_eq!(surface["input"]["fields"][1]["buttons"][0], "boost"); + assert_eq!(surface["events"][0]["name"], "hello"); + let gen = tmp.path().join("gen"); + let run = distributed(&[ + "game-client", + "--manifest", + out.to_str().unwrap(), + "--out", + gen.to_str().unwrap(), + ]); + assert!( + run.status.success(), + "{}", + String::from_utf8_lossy(&run.stderr) + ); + assert!(fs::read_to_string(gen.join("client.ts")) + .unwrap() + .contains("createOrbsClient")); + + // The predicted step and the pure function compile to one + // self-contained module next to the client (game-wasm checks both + // exports); a second run is a stamp hit, and --check verifies it. + let wasm = |extra: &[&str]| { + let mut args = vec![ + "game-wasm", + "--manifest", + out.to_str().unwrap(), + "--manifest-path", + manifest.to_str().unwrap(), + "--out", + gen.to_str().unwrap(), + ]; + args.extend(extra); + distributed(&args) + }; + let check = wasm(&["--check"]); + assert!(!check.status.success(), "nothing built yet"); + let build = wasm(&[]); + assert!( + build.status.success(), + "{}", + String::from_utf8_lossy(&build.stderr) + ); + let module = fs::read(gen.join("wasm/orbs.wasm")).unwrap(); + assert_eq!(&module[..4], b"\0asm"); + let again = wasm(&[]); + assert!(String::from_utf8_lossy(&again.stdout).contains("is current")); + assert!(wasm(&["--check"]).status.success()); + fs::write(gen.join("wasm/orbs.wasm"), b"tampered").unwrap(); + assert!( + !wasm(&["--check"]).status.success(), + "a changed module is stale" + ); +} + +#[test] +fn game_wasm_needs_something_to_compile() { + let tmp = tempfile::tempdir().unwrap(); + let mut surface: serde_json::Value = serde_json::from_str(&sample_surface()).unwrap(); + surface.as_object_mut().unwrap().remove("predict"); + surface.as_object_mut().unwrap().remove("pures"); + let manifest = tmp.path().join("surface.json"); + fs::write(&manifest, surface.to_string()).unwrap(); + let run = distributed(&[ + "game-wasm", + "--manifest", + manifest.to_str().unwrap(), + "--out", + tmp.path().join("gen").to_str().unwrap(), + ]); + assert!(!run.status.success()); + assert!( + String::from_utf8_lossy(&run.stderr).contains("declares nothing to compile"), + "{}", + String::from_utf8_lossy(&run.stderr) + ); +} + +#[test] +#[ignore = "compiles the fixture via the manifest harness; run in the integration job"] +fn concurrent_game_manifests_export_their_own_entrypoints() { + // Every entrypoint of a package shares one harness directory; without + // the harness lock, concurrent runs overwrote each other's `main.rs` and + // exported the last writer's surface. + let manifest = root().join("tests/fixtures/game-surface/Cargo.toml"); + let tmp = tempfile::tempdir().unwrap(); + // Warm the harness build so the concurrent runs race on `main.rs`, not + // on the first compile. + let warm = distributed(&[ + "game-manifest", + "--manifest-path", + manifest.to_str().unwrap(), + "--out", + tmp.path().join("warm.json").to_str().unwrap(), + ]); + assert!( + warm.status.success(), + "{}", + String::from_utf8_lossy(&warm.stderr) + ); + for round in 0..4 { + let runs: Vec<_> = [("game_surface", "orbs"), ("bare_surface", "bare")] + .into_iter() + .flat_map(|pair| [pair, pair]) + .enumerate() + .map(|(i, (entrypoint, name))| { + let out = tmp.path().join(format!("{round}-{i}.json")); + let child = Command::new(env!("CARGO_BIN_EXE_distributed")) + .args([ + "game-manifest", + "--manifest-path", + manifest.to_str().unwrap(), + "--entrypoint", + entrypoint, + "--out", + out.to_str().unwrap(), + ]) + .stderr(std::process::Stdio::piped()) + .spawn() + .expect("distributed should run"); + (child, out, name) + }) + .collect(); + for (child, out, name) in runs { + let output = child.wait_with_output().unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let surface: serde_json::Value = + serde_json::from_str(&fs::read_to_string(&out).unwrap()).unwrap(); + assert_eq!(surface["name"], name, "round {round}: {}", out.display()); + } + } +} diff --git a/distributed_cli/tests/cli_lifecycle.rs b/distributed_cli/tests/cli_lifecycle.rs index 9ec12e873..2850c9d2e 100644 --- a/distributed_cli/tests/cli_lifecycle.rs +++ b/distributed_cli/tests/cli_lifecycle.rs @@ -1,46 +1,96 @@ -//! Process-level coherent lifecycle build checks. +//! Lifecycle `build` and `dev` behaviour. +//! +//! Most tests drive the lifecycle engine on a project whose two artifact nodes +//! are built by shell scripts, so every step is deterministic and fast. The +//! tests at the end run the `distributed` binary on a real Cargo project. use distributed_cli::{ - run_lifecycle_build, run_lifecycle_dev, LifecycleBuildOptions, LifecycleDevOptions, - LifecycleDevReport, LifecycleError, + run_lifecycle_project_build, run_lifecycle_project_dev, ContractCatalog, LifecycleActivation, + LifecycleBuildReport, LifecycleBuildRequest, LifecycleDevReport, LifecycleError, + LifecycleProjectDevOptions, LifecycleProjectPlan, }; use serde_json::Value; use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; -use std::process::{Command, Output, Stdio}; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::process::{Command, Stdio}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Arc; use std::thread; use std::thread::JoinHandle; use std::time::Duration; use tempfile::TempDir; -fn distributed(root: &Path, extra: &[&str]) -> Output { - let mut args = vec![ - "build", - "--root", - root.to_str().expect("UTF-8 fixture root"), - "--output", - "json", - ]; - args.extend_from_slice(extra); - Command::new(env!("CARGO_BIN_EXE_distributed")) - .args(args) - .output() - .expect("distributed build should run") -} - -fn temporary_root(label: &str) -> TempDir { - let root = tempfile::Builder::new() - .prefix(&format!("distributed-lifecycle-{label}-")) +/// A directory of this test's own. The process ID keeps concurrent test +/// binaries apart and the counter keeps the tests of this one apart. +fn temporary_directory(label: &str) -> TempDir { + static CREATED: AtomicUsize = AtomicUsize::new(0); + tempfile::Builder::new() + .prefix(&format!( + "distributed-lifecycle-{label}-{}-{}-", + std::process::id(), + CREATED.fetch_add(1, Ordering::Relaxed) + )) .tempdir() - .expect("create exclusive lifecycle fixture root"); - fs::create_dir_all(root.path().join("src")).expect("create lifecycle fixture source"); - root + .expect("create exclusive lifecycle fixture root") } -fn write_fixture(root: &Path) { +/// A lifecycle project: its workspace on disk, and the catalog and +/// configuration that project discovery would otherwise derive. +struct Fixture { + _directory: TempDir, + root: PathBuf, + catalog: Value, + config: Value, +} + +impl Fixture { + fn new(label: &str) -> Self { + let directory = temporary_directory(label); + let root = directory + .path() + .canonicalize() + .expect("resolve lifecycle fixture root"); + fs::create_dir_all(root.join("src")).expect("create lifecycle fixture source"); + let (catalog, config) = write_fixture(&root); + Self { + _directory: directory, + root, + catalog, + config, + } + } + + fn plan(&self) -> LifecycleProjectPlan { + LifecycleProjectPlan { + root: self.root.clone(), + catalog: ContractCatalog::from_json_str(&self.catalog.to_string()) + .expect("parse lifecycle catalog"), + config: serde_json::from_value(self.config.clone()).expect("parse lifecycle config"), + out: "dist/distributed".into(), + cli_executable: env!("CARGO_BIN_EXE_distributed").into(), + } + } + + /// What `distributed build [--check]` does with the plan. + fn build(&self, check: bool) -> Result { + run_lifecycle_project_build(&self.plan(), &build_request(check)) + } +} + +fn build_request(check: bool) -> LifecycleBuildRequest { + LifecycleBuildRequest { + check, + lock_timeout: Duration::from_secs(1), + nodes: None, + activation_inputs: None, + cancel: None, + activation: LifecycleActivation::Immediate, + } +} + +/// Writes the workspace and returns its catalog and lifecycle configuration. +fn write_fixture(root: &Path) -> (Value, Value) { fs::write(root.join("src/input.txt"), "first\n").expect("write lifecycle input"); fs::create_dir_all(root.join("plan")).expect("create plan input directory"); fs::write(root.join("plan/input.txt"), "local\n").expect("write plan input"); @@ -68,6 +118,8 @@ if test -f "$root/fail-plan"; then exit 17 fi if test -f "$root/slow-plan"; then + /bin/sh -c 'trap "" TERM; while :; do sleep 1; done' & + printf '%s %s\n' "$$" "$!" >> "$root/build-plan-family.log" printf 'started\n' >> "$root/build-plan-starts.log" while test -f "$root/slow-plan"; do :; done fi @@ -125,11 +177,6 @@ cat "$stage/generated/application.json" >> "$stage/generated/plan.json" } } }); - fs::write( - root.join("distributed.contracts.json"), - serde_json::to_vec_pretty(&catalog).expect("serialize lifecycle catalog"), - ) - .expect("write lifecycle catalog"); let identity = format!("sha256:{}", "1".repeat(64)); let source_identity = format!("sha256:{}", "a".repeat(64)); let config = serde_json::json!({ @@ -155,24 +202,16 @@ cat "$stage/generated/application.json" >> "$stage/generated/plan.json" } } }); - fs::write( - root.join("distributed.lifecycle.json"), - serde_json::to_vec_pretty(&config).expect("serialize lifecycle config"), - ) - .expect("write lifecycle config"); + (catalog, config) } -fn report(output: &Output) -> Value { - serde_json::from_slice(&output.stdout).unwrap_or_else(|error| { - panic!( - "parse lifecycle report: {error}; stdout={}; stderr={}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - ) - }) +/// The report as `distributed build --output json` prints it. +fn report(report: &LifecycleBuildReport) -> Value { + serde_json::to_value(report).expect("serialize lifecycle report") } -fn enable_dev(root: &Path) { +fn enable_dev(fixture: &mut Fixture) { + let root = &fixture.root; fs::write( root.join("dev-child.sh"), r#"#!/bin/sh @@ -186,17 +225,17 @@ else fi printf '%s:%s:%s\n' "$name" "$barrier" "$DISTRIBUTED_GENERATION_ID" >> "$root/dev-process.log" printf '%s:%s:%s\n' "$name" "$DEV_FIXTURE_NAME" "$PWD" >> "$root/dev-environment.log" +printf '%s:%s\n' "$name" "$DISTRIBUTED_PROCESS_INSTANCE_ID" >> "$root/dev-instances.log" trap 'exit 0' TERM /bin/sh -c 'trap "" TERM; while :; do sleep 1; done' & descendant=$! +printf '%s %s\n' "$$" "$descendant" >> "$root/dev-family.log" printf '%s\n' "$descendant" >> "$root/dev-descendants.log" wait "$descendant" "#, ) .expect("write dev child fixture"); - let path = root.join("distributed.lifecycle.json"); - let mut config: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap(); - config["dev"] = serde_json::json!({ + fixture.config["dev"] = serde_json::json!({ "poll_ms": 20, "debounce_ms": 30, "shutdown_ms": 100, @@ -226,10 +265,10 @@ wait "$descendant" } } }); - fs::write(path, serde_json::to_vec_pretty(&config).unwrap()).unwrap(); } -fn configure_blocking_readiness_probe(root: &Path, timeout_ms: u64) { +fn configure_blocking_readiness_probe(fixture: &mut Fixture, timeout_ms: u64) { + let root = &fixture.root; fs::write( root.join("readiness-probe.sh"), r#"#!/bin/sh @@ -244,18 +283,16 @@ exit 1 "#, ) .expect("write blocking readiness probe"); - let path = root.join("distributed.lifecycle.json"); - let mut config: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap(); - config["dev"]["processes"]["api"]["ready"] = serde_json::json!({ + fixture.config["dev"]["processes"]["api"]["ready"] = serde_json::json!({ "program": "/bin/sh", "args": ["{root}/readiness-probe.sh", "{root}"], "interval_ms": 10, "timeout_ms": timeout_ms }); - fs::write(path, serde_json::to_vec_pretty(&config).unwrap()).unwrap(); } -fn configure_generation_rejecting_probe(root: &Path) { +fn configure_generation_rejecting_probe(fixture: &mut Fixture) { + let root = &fixture.root; fs::write( root.join("generation-probe.sh"), r#"#!/bin/sh @@ -273,18 +310,22 @@ exit 1 "#, ) .expect("write generation readiness probe"); - let path = root.join("distributed.lifecycle.json"); - let mut config: Value = serde_json::from_slice(&fs::read(&path).unwrap()).unwrap(); + let config = &mut fixture.config; config["dev"]["prepare_ms"] = serde_json::json!(100); + // The probe rejects a replacement by never passing, so this budget is + // also how long a rejection takes. It must still leave headroom for the + // initial generation's probe (a `/bin/sh` spawn) under a loaded + // `cargo test --workspace`: at 100 ms that probe timed out and the + // supervisor failed before the test's first assertion. config["dev"]["processes"]["api"]["ready"] = serde_json::json!({ "program": "/bin/sh", "args": ["{root}/generation-probe.sh", "{root}"], "interval_ms": 10, - "timeout_ms": 100 + "timeout_ms": 1500 }); - fs::write(path, serde_json::to_vec_pretty(&config).unwrap()).unwrap(); } +#[track_caller] fn wait_until(timeout: Duration, predicate: impl Fn() -> bool) { let started = std::time::Instant::now(); while !predicate() { @@ -302,22 +343,14 @@ struct DevSupervisor { } impl DevSupervisor { - fn start(root: PathBuf) -> Self { + fn start(fixture: &Fixture) -> Self { let stop = Arc::new(AtomicBool::new(false)); let supervisor_stop = Arc::clone(&stop); + let project = fixture.plan(); let handle = thread::spawn(move || { - run_lifecycle_dev(&LifecycleDevOptions { - build: LifecycleBuildOptions { - root, - catalog: "distributed.contracts.json".into(), - config: "distributed.lifecycle.json".into(), - out: "dist/distributed".into(), - check: false, - lock_timeout: Duration::from_secs(1), - nodes: None, - activation_inputs: None, - cancel: None, - }, + run_lifecycle_project_dev(&LifecycleProjectDevOptions { + project, + build: build_request(false), stop: supervisor_stop, progress: false, }) @@ -407,17 +440,10 @@ fn file_snapshot(root: &Path) -> BTreeMap> { #[test] fn build_is_deterministic_and_check_is_read_only_and_content_based() { - let fixture = temporary_root("deterministic"); - let root = fixture.path().to_path_buf(); - write_fixture(&root); + let fixture = Fixture::new("deterministic"); + let root = fixture.root.clone(); - let first = distributed(&root, &[]); - assert!( - first.status.success(), - "{}", - String::from_utf8_lossy(&first.stderr) - ); - let first = report(&first); + let first = report(&fixture.build(false).expect("first build")); let active_before = fs::read(root.join("dist/distributed/active.json")) .expect("read active generation pointer"); let generation = first["generation_id"].as_str().expect("generation ID"); @@ -433,19 +459,13 @@ fn build_is_deterministic_and_check_is_read_only_and_content_based() { .is_file()); fs::write(root.join("src/input.txt"), "first\n").expect("rewrite identical content"); - let second = distributed(&root, &[]); - assert!(second.status.success()); - let second = report(&second); + let second = report(&fixture.build(false).expect("second build")); assert_eq!(first["generation_id"], second["generation_id"]); assert_eq!(first["release_id"], second["release_id"]); let snapshot_before_check = file_snapshot(&root); - let check = distributed(&root, &["--check"]); - assert!( - check.status.success(), - "{}", - String::from_utf8_lossy(&check.stderr) - ); + let check = fixture.build(true).expect("check"); + assert!(check.ok, "`distributed build --check` exits 0"); assert!(report(&check)["drift"].as_array().unwrap().is_empty()); assert_eq!( active_before, @@ -456,21 +476,10 @@ fn build_is_deterministic_and_check_is_read_only_and_content_based() { #[test] fn partial_build_reuses_verified_upstream_receipts() { - let fixture = temporary_root("partial"); - let root = fixture.path().to_path_buf(); - write_fixture(&root); - let options = LifecycleBuildOptions { - root: root.clone(), - catalog: "distributed.contracts.json".into(), - config: "distributed.lifecycle.json".into(), - out: "dist/distributed".into(), - check: false, - lock_timeout: Duration::from_secs(1), - nodes: None, - activation_inputs: None, - cancel: None, - }; - let first = run_lifecycle_build(&options).unwrap(); + let fixture = Fixture::new("partial"); + let root = fixture.root.clone(); + let project = fixture.plan(); + let first = run_lifecycle_project_build(&project, &build_request(false)).unwrap(); let first_manifest: Value = serde_json::from_slice( &fs::read( root.join("dist/distributed/generations") @@ -497,10 +506,10 @@ fn partial_build_reuses_verified_upstream_receipts() { ), ]); fs::write(root.join("plan/input.txt"), "split\n").unwrap(); - let mut partial = options.clone(); + let mut partial = build_request(false); partial.nodes = Some(["plan".to_string()].into_iter().collect()); partial.activation_inputs = Some(old_inputs); - let superseded = run_lifecycle_build(&partial).unwrap_err(); + let superseded = run_lifecycle_project_build(&project, &partial).unwrap_err(); assert!(superseded.message().contains("superseded")); assert!( fs::read_to_string(root.join("dist/distributed/active.json")) @@ -508,62 +517,61 @@ fn partial_build_reuses_verified_upstream_receipts() { .contains(&first.generation_id) ); partial.activation_inputs = None; - let second = run_lifecycle_build(&partial).unwrap(); + let second = run_lifecycle_project_build(&project, &partial).unwrap(); assert_eq!(second.executed, ["plan"]); assert_ne!(first.generation_id, second.generation_id); - let manifest = |generation: &str| -> Value { - serde_json::from_slice( - &fs::read( - root.join("dist/distributed/generations") - .join(generation) - .join("generation.json"), - ) - .unwrap(), + // Activating the second generation removed the first; its manifest was + // read while it was active. + let second_manifest: Value = serde_json::from_slice( + &fs::read( + root.join("dist/distributed/generations") + .join(&second.generation_id) + .join("generation.json"), ) - .unwrap() - }; + .unwrap(), + ) + .unwrap(); assert_eq!( - manifest(&first.generation_id)["receipts"]["application"], - manifest(&second.generation_id)["receipts"]["application"] + first_manifest["receipts"]["application"], + second_manifest["receipts"]["application"] ); + assert!(!root + .join("dist/distributed/generations") + .join(&first.generation_id) + .exists()); } #[test] fn mixed_source_and_unowned_outputs_fail_before_activation() { - let mixed_fixture = temporary_root("mixed-source"); - let mixed_root = mixed_fixture.path().to_path_buf(); - write_fixture(&mixed_root); - let config_path = mixed_root.join("distributed.lifecycle.json"); - let mut config: Value = serde_json::from_slice(&fs::read(&config_path).unwrap()).unwrap(); - config["source"]["javascript"] = Value::String(format!("sha256:{}", "b".repeat(64))); - fs::write(&config_path, serde_json::to_vec_pretty(&config).unwrap()).unwrap(); - let mixed = distributed(&mixed_root, &[]); - assert!(!mixed.status.success()); - let diagnostic = String::from_utf8_lossy(&mixed.stderr); + let mut mixed = Fixture::new("mixed-source"); + mixed.config["source"]["javascript"] = Value::String(format!("sha256:{}", "b".repeat(64))); + let mixed_root = mixed.root.clone(); + let diagnostic = mixed + .build(false) + .expect_err("mixed framework sources are refused") + .to_string(); assert!(diagnostic.contains(&format!("sha256:{}", "a".repeat(64)))); assert!(diagnostic.contains(&format!("sha256:{}", "b".repeat(64)))); assert!(!mixed_root.join("dist/distributed/active.json").exists()); - let unowned_fixture = temporary_root("unowned-output"); - let unowned_root = unowned_fixture.path().to_path_buf(); - write_fixture(&unowned_root); + let unowned = Fixture::new("unowned-output"); + let unowned_root = unowned.root.clone(); fs::write(unowned_root.join("produce-unowned"), "yes\n").unwrap(); - let unowned = distributed(&unowned_root, &[]); - assert!(!unowned.status.success()); - assert!( - String::from_utf8_lossy(&unowned.stderr).contains("unowned staged output `unowned.txt`") - ); + let diagnostic = unowned + .build(false) + .expect_err("an unowned output is refused") + .to_string(); + assert!(diagnostic.contains("unowned staged output `unowned.txt`")); assert!(!unowned_root.join("dist/distributed/active.json").exists()); } #[test] fn dev_waits_for_initial_generation_and_restarts_only_invalidated_processes() { - let fixture = temporary_root("dev-supervisor"); - let root = fixture.path().to_path_buf(); - write_fixture(&root); - enable_dev(&root); - let supervisor = DevSupervisor::start(root.clone()); + let mut fixture = Fixture::new("dev-supervisor"); + enable_dev(&mut fixture); + let root = fixture.root.clone(); + let supervisor = DevSupervisor::start(&fixture); wait_until(Duration::from_secs(5), || { fs::read_to_string(root.join("dev-process.log")).is_ok_and(|log| log.lines().count() == 2) @@ -586,12 +594,77 @@ fn dev_waits_for_initial_generation_and_restarts_only_invalidated_processes() { &root.join("dist/distributed/active.json"), Duration::from_secs(5), ); + wait_until(Duration::from_secs(5), || { + dev_state(&root)["members"]["api"].is_object() + }); + let initial_state = dev_state(&root); + let instances = fs::read_to_string(root.join("dev-instances.log")).unwrap(); + for name in ["api", "ui"] { + assert!(instances.lines().any(|line| line + == format!( + "{name}:{}", + initial_state["members"][name]["instanceId"] + .as_str() + .unwrap() + ))); + } + let mut previous_generation = initial_state["active"]["generationId"].clone(); + // Changes outside either process's restart inventory retain both instances + // while their authorized application generation advances repeatedly. + for input in ["client-one", "client-two"] { + fs::write(root.join("plan/input.txt"), input).unwrap(); + wait_until(Duration::from_secs(5), || { + let state = dev_state(&root); + state["phase"] == "active" && state["active"]["generationId"] != previous_generation + }); + let state = dev_state(&root); + assert_eq!(state["members"], initial_state["members"]); + previous_generation = state["active"]["generationId"].clone(); + } fs::write(root.join("src/input.txt"), "second\n").unwrap(); wait_until(Duration::from_secs(5), || { fs::read_to_string(root.join("dev-process.log")).is_ok_and(|log| log.lines().count() == 3) }); + wait_until(Duration::from_secs(5), || { + let state = dev_state(&root); + state["phase"] == "active" && state["active"]["generationId"] != previous_generation + }); + let replaced = dev_state(&root); + assert_ne!( + replaced["members"]["api"]["instanceId"], + initial_state["members"]["api"]["instanceId"] + ); + assert_eq!( + replaced["members"]["api"]["generationId"], + replaced["active"]["generationId"] + ); + assert_eq!(replaced["members"]["ui"], initial_state["members"]["ui"]); + // Four generations were activated. The one in between is unused and gone: + // what stays is the active one, the one it replaced, and the first, which + // the `ui` process was started with and still resolves. + let installed = fs::read_dir(root.join("dist/distributed/generations")) + .unwrap() + .map(|entry| entry.unwrap().file_name().into_string().unwrap()) + .collect::>(); + let generation = |state: &Value| { + state["active"]["generationId"] + .as_str() + .unwrap() + .to_string() + }; + assert_eq!( + installed, + [ + generation(&initial_state), + previous_generation.as_str().unwrap().to_string(), + generation(&replaced), + ] + .into_iter() + .collect() + ); let report = supervisor.stop_and_join(); - assert_eq!(report.rebuilds, 1); + assert_eq!(report.rebuilds, 3); + assert!(!root.join("dist/distributed/dev.json").exists()); assert_eq!(report.restarts["api"], 1); assert_eq!(report.restarts["ui"], 0); let log = fs::read_to_string(root.join("dev-process.log")).unwrap(); @@ -617,14 +690,20 @@ fn dev_waits_for_initial_generation_and_restarts_only_invalidated_processes() { } } +fn dev_state(root: &Path) -> Value { + fs::read(root.join("dist/distributed/dev.json")) + .ok() + .and_then(|bytes| serde_json::from_slice(&bytes).ok()) + .unwrap_or(Value::Null) +} + #[test] fn dev_readiness_failure_restores_processes_and_preserves_active_pointer() { - let fixture = temporary_root("dev-rollback"); - let root = fixture.path().to_path_buf(); - write_fixture(&root); - enable_dev(&root); - configure_generation_rejecting_probe(&root); - let supervisor = DevSupervisor::start(root.clone()); + let mut fixture = Fixture::new("dev-rollback"); + enable_dev(&mut fixture); + let root = fixture.root.clone(); + configure_generation_rejecting_probe(&mut fixture); + let supervisor = DevSupervisor::start(&fixture); wait_until(Duration::from_secs(5), || { fs::read_to_string(root.join("dev-process.log")).is_ok_and(|log| log.lines().count() == 2) }); @@ -632,6 +711,10 @@ fn dev_readiness_failure_restores_processes_and_preserves_active_pointer() { &root.join("dist/distributed/active.json"), Duration::from_secs(5), ); + wait_until(Duration::from_secs(5), || { + dev_state(&root)["members"]["api"].is_object() + }); + let initial_members = dev_state(&root)["members"].clone(); fs::write(root.join("src/input.txt"), "replacement\n").unwrap(); wait_until(Duration::from_secs(5), || { @@ -642,6 +725,17 @@ fn dev_readiness_failure_restores_processes_and_preserves_active_pointer() { fs::read_to_string(root.join("accepted-readiness.log")) .is_ok_and(|log| log.lines().count() == 2) }); + wait_until(Duration::from_secs(5), || { + let state = dev_state(&root); + state["phase"] == "active" + && state["members"]["api"]["instanceId"] != initial_members["api"]["instanceId"] + }); + let rollback = dev_state(&root); + assert_eq!( + rollback["members"]["api"]["generationId"], + initial_members["api"]["generationId"] + ); + assert_eq!(rollback["members"]["ui"], initial_members["ui"]); let report = supervisor.stop_and_join(); assert_eq!(report.initial_generation, report.final_generation); assert_eq!( @@ -662,15 +756,11 @@ fn dev_readiness_failure_restores_processes_and_preserves_active_pointer() { #[test] fn dev_browser_prepare_timeout_preserves_active_pointer_and_processes() { - let fixture = temporary_root("dev-prepare-timeout"); - let root = fixture.path().to_path_buf(); - write_fixture(&root); - enable_dev(&root); - let config_path = root.join("distributed.lifecycle.json"); - let mut config: Value = serde_json::from_slice(&fs::read(&config_path).unwrap()).unwrap(); - config["dev"]["prepare_ms"] = serde_json::json!(100); - fs::write(&config_path, serde_json::to_vec_pretty(&config).unwrap()).unwrap(); - let supervisor = DevSupervisor::start(root.clone()); + let mut fixture = Fixture::new("dev-prepare-timeout"); + enable_dev(&mut fixture); + let root = fixture.root.clone(); + fixture.config["dev"]["prepare_ms"] = serde_json::json!(100); + let supervisor = DevSupervisor::start(&fixture); wait_until(Duration::from_secs(5), || { fs::read_to_string(root.join("dev-process.log")).is_ok_and(|log| log.lines().count() == 2) }); @@ -709,13 +799,55 @@ fn dev_browser_prepare_timeout_preserves_active_pointer_and_processes() { ); } +#[test] +fn dev_rebuilds_source_edited_while_initial_process_readiness_is_held() { + let mut fixture = Fixture::new("dev-startup-edit"); + enable_dev(&mut fixture); + let root = fixture.root.clone(); + fixture.config["dev"]["processes"]["api"]["ready"] = serde_json::json!({ + "program": "/bin/test", + "args": ["-f", "{root}/release-readiness"], + "interval_ms": 10, + "timeout_ms": 5000 + }); + let supervisor = DevSupervisor::start(&fixture); + wait_until(Duration::from_secs(5), || { + root.join("dev-process.log").exists() + }); + let before = wait_for_stable_file( + &root.join("dist/distributed/active.json"), + Duration::from_secs(5), + ); + // The initial build is complete but the supervisor cannot finish startup. + fs::write(root.join("src/input.txt"), "edited-during-startup\n").unwrap(); + fs::write(root.join("release-readiness"), "release\n").unwrap(); + wait_until(Duration::from_secs(5), || { + fs::read(root.join("dist/distributed/active.json")).is_ok_and(|active| active != before) + }); + let report = supervisor.stop_and_join(); + assert_ne!(report.initial_generation, report.final_generation); + assert_eq!(report.rebuilds, 1); + assert_eq!(report.restarts["api"], 1); + assert_eq!(report.restarts["ui"], 0); + let active: Value = + serde_json::from_slice(&fs::read(root.join("dist/distributed/active.json")).unwrap()) + .unwrap(); + let artifact = root + .join("dist/distributed") + .join(active["path"].as_str().unwrap()) + .join("generated/application.json"); + assert_eq!( + fs::read_to_string(artifact).unwrap(), + "application:edited-during-startup\n" + ); +} + #[test] fn dev_cancels_a_superseded_executor_before_activation() { - let fixture = temporary_root("dev-cancel"); - let root = fixture.path().to_path_buf(); - write_fixture(&root); - enable_dev(&root); - let supervisor = DevSupervisor::start(root.clone()); + let mut fixture = Fixture::new("dev-cancel"); + enable_dev(&mut fixture); + let root = fixture.root.clone(); + let supervisor = DevSupervisor::start(&fixture); wait_until(Duration::from_secs(5), || { fs::read_to_string(root.join("dev-process.log")).is_ok_and(|log| log.lines().count() == 2) }); @@ -729,11 +861,14 @@ fn dev_cancels_a_superseded_executor_before_activation() { wait_until(Duration::from_secs(5), || { root.join("build-plan-starts.log").exists() }); + let canceled = recorded_pids(&root.join("build-plan-family.log")); + assert_eq!(canceled.len(), 2, "the executor and its descendant"); fs::write(root.join("plan/input.txt"), "latest\n").unwrap(); wait_until(Duration::from_secs(5), || { fs::read_to_string(root.join("build-plan-starts.log")) .is_ok_and(|log| log.lines().count() >= 2) }); + assert_no_survivors(&canceled); assert_eq!( initial_active, fs::read(root.join("dist/distributed/active.json")).unwrap() @@ -747,6 +882,9 @@ fn dev_cancels_a_superseded_executor_before_activation() { assert_eq!(report.rebuilds, 1); assert_eq!(report.restarts["api"], 0); assert_eq!(report.restarts["ui"], 0); + // The executor that completed left a descendant behind; it is gone too. + assert_no_survivors(&recorded_pids(&root.join("build-plan-family.log"))); + assert_no_survivors(&recorded_pids(&root.join("dev-family.log"))); let active: Value = serde_json::from_slice(&fs::read(root.join("dist/distributed/active.json")).unwrap()) .unwrap(); @@ -761,12 +899,11 @@ fn dev_cancels_a_superseded_executor_before_activation() { #[test] fn dev_stop_cancels_the_initial_build_before_process_startup() { - let fixture = temporary_root("dev-initial-cancel"); - let root = fixture.path().to_path_buf(); - write_fixture(&root); - enable_dev(&root); + let mut fixture = Fixture::new("dev-initial-cancel"); + enable_dev(&mut fixture); + let root = fixture.root.clone(); fs::write(root.join("slow-plan"), "yes\n").unwrap(); - let supervisor = DevSupervisor::start(root.clone()); + let supervisor = DevSupervisor::start(&fixture); wait_until(Duration::from_secs(5), || { root.join("build-plan-starts.log").exists() }); @@ -775,21 +912,21 @@ fn dev_stop_cancels_the_initial_build_before_process_startup() { let error = supervisor .stop_and_join_result() .expect_err("initial build should report cancellation"); - assert!(started.elapsed() < Duration::from_secs(1)); + // The plan never finishes by itself; the bound only has to be finite. + assert!(started.elapsed() < Duration::from_secs(10)); assert!(error.message().contains("was canceled")); assert!(!root.join("dev-process.log").exists()); } #[test] fn dev_enforces_timeout_while_readiness_probe_is_running() { - let fixture = temporary_root("dev-readiness-timeout"); - let root = fixture.path().to_path_buf(); - write_fixture(&root); - enable_dev(&root); - configure_blocking_readiness_probe(&root, 100); + let mut fixture = Fixture::new("dev-readiness-timeout"); + enable_dev(&mut fixture); + let root = fixture.root.clone(); + configure_blocking_readiness_probe(&mut fixture, 100); let started = std::time::Instant::now(); - let error = DevSupervisor::start(root.clone()) + let error = DevSupervisor::start(&fixture) .join_result() .expect_err("blocked readiness probe should time out"); assert!(started.elapsed() < Duration::from_secs(3)); @@ -799,13 +936,12 @@ fn dev_enforces_timeout_while_readiness_probe_is_running() { #[test] fn dev_stop_cancels_a_running_readiness_probe() { - let fixture = temporary_root("dev-readiness-cancel"); - let root = fixture.path().to_path_buf(); - write_fixture(&root); - enable_dev(&root); - configure_blocking_readiness_probe(&root, 2_000); - let supervisor = DevSupervisor::start(root.clone()); - wait_until(Duration::from_secs(1), || { + let mut fixture = Fixture::new("dev-readiness-cancel"); + enable_dev(&mut fixture); + let root = fixture.root.clone(); + configure_blocking_readiness_probe(&mut fixture, 2_000); + let supervisor = DevSupervisor::start(&fixture); + wait_until(Duration::from_secs(5), || { root.join("readiness-probe-descendant.pid").exists() }); @@ -844,17 +980,17 @@ fn assert_fixture_processes_gone(_root: &Path, _prefix: &str) {} #[test] fn stale_check_names_owner_and_failed_downstream_build_preserves_active_generation() { - let fixture = temporary_root("failure"); - let root = fixture.path().to_path_buf(); - write_fixture(&root); - let baseline = distributed(&root, &[]); - assert!(baseline.status.success()); + let fixture = Fixture::new("failure"); + let root = fixture.root.clone(); + fixture.build(false).expect("baseline build"); let active_before = fs::read(root.join("dist/distributed/active.json")).unwrap(); - fs::write(root.join("generated/plan.json"), "stale\n").expect("make tracked output stale"); - let check = distributed(&root, &["--check"]); - assert_eq!(check.status.code(), Some(1)); + // The plan no longer builds what the active generation holds. + fs::write(root.join("plan/input.txt"), "stale\n").expect("change the plan input"); + let check = fixture.build(true).expect("check"); + assert!(!check.ok, "`distributed build --check` exits 1"); let check = report(&check); + assert_eq!(check["drift"].as_array().unwrap().len(), 1); assert_eq!(check["drift"][0]["node_id"], "plan"); assert_eq!(check["drift"][0]["output"], "generated/plan.json"); assert!(check["drift"][0]["built_identity"] @@ -868,9 +1004,10 @@ fn stale_check_names_owner_and_failed_downstream_build_preserves_active_generati fs::write(root.join("src/input.txt"), "second\n").expect("change lifecycle source"); fs::write(root.join("fail-plan"), "fail\n").expect("inject downstream failure"); - let failed = distributed(&root, &[]); - assert!(!failed.status.success()); - let failed_diagnostic = String::from_utf8_lossy(&failed.stderr); + let failed_diagnostic = fixture + .build(false) + .expect_err("the plan executor fails") + .to_string(); assert!(failed_diagnostic.contains("lifecycle node `plan`")); assert!(failed_diagnostic.contains("injected downstream failure")); assert_eq!( @@ -878,3 +1015,367 @@ fn stale_check_names_owner_and_failed_downstream_build_preserves_active_generati fs::read(root.join("dist/distributed/active.json")).unwrap() ); } + +/// Every process ID a fixture script appended to `path`. +#[cfg(unix)] +fn recorded_pids(path: &Path) -> Vec { + fs::read_to_string(path) + .unwrap_or_default() + .split_whitespace() + .map(|pid| pid.parse().expect("fixture process ID")) + .collect() +} + +/// Polls until none of `pids` can be signalled. None of them is a child of +/// this test process once its owner has reaped or exited, so a process that +/// still answers is alive, not a zombie waiting for this test. +#[cfg(unix)] +fn assert_no_survivors(pids: &[libc::pid_t]) { + let started = std::time::Instant::now(); + loop { + let alive = pids + .iter() + .copied() + .filter(|pid| unsafe { libc::kill(*pid, 0) } == 0) + .collect::>(); + if alive.is_empty() { + return; + } + if started.elapsed() > Duration::from_secs(10) { + for pid in &alive { + unsafe { libc::kill(*pid, libc::SIGKILL) }; + } + panic!("processes outlived their session: {alive:?}"); + } + thread::sleep(Duration::from_millis(10)); + } +} + +/// The lifecycle test project (`tests/fixtures/lifecycle-project`) in a +/// directory of its own: a Cargo workspace that `distributed dev ` +/// discovers as any project. Its API and UI listen on ports of their own. +#[cfg(unix)] +struct Project { + _directory: TempDir, + root: PathBuf, + /// Projects share one Cargo target directory, so they run one at a time. + _turn: std::sync::MutexGuard<'static, ()>, +} + +#[cfg(unix)] +impl Project { + fn new(label: &str) -> Self { + static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(()); + let turn = TURN.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let directory = temporary_directory(label); + let root = directory + .path() + .canonicalize() + .expect("resolve lifecycle project root"); + let listeners = [(); 2] + .map(|()| std::net::TcpListener::bind("127.0.0.1:0").expect("reserve a loopback port")); + let [api_port, ui_port] = + listeners.map(|listener| listener.local_addr().expect("reserved port").port()); + let framework = Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .expect("the CLI is a member of the framework workspace"); + let fixture = + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/lifecycle-project"); + for file in [ + "Cargo.toml", + "service/Cargo.toml", + "service/src/lib.rs", + "service/src/name.txt", + "runner/Cargo.toml", + "runner/src/main.rs", + "ui/Cargo.toml", + "ui/src/main.rs", + "ui/package.json", + ] { + let text = fs::read_to_string(fixture.join(file)) + .expect("read lifecycle project file") + .replace("@DISTRIBUTED@", framework.to_str().expect("UTF-8 path")) + .replace("@API_PORT@", &api_port.to_string()) + .replace("@UI_PORT@", &ui_port.to_string()); + let target = root.join(file); + fs::create_dir_all(target.parent().unwrap()).expect("create lifecycle project"); + fs::write(target, text).expect("write lifecycle project file"); + } + // The framework's lock file resolves the project without the network. + fs::copy(framework.join("Cargo.lock"), root.join("Cargo.lock")) + .expect("copy the framework lock file"); + Self { + _directory: directory, + root, + _turn: turn, + } + } + + /// `distributed dev `, with its output in `dev.log`. + fn dev(&self) -> DevProcess { + let log = self.root.join("dev.log"); + let output = fs::File::create(&log).expect("create dev log"); + let mut command = Command::new(env!("CARGO_BIN_EXE_distributed")); + command + .arg("dev") + .arg(&self.root) + .env( + "CARGO_TARGET_DIR", + Path::new(env!("CARGO_TARGET_TMPDIR")).join("lifecycle-project"), + ) + .stdin(Stdio::null()) + .stdout(output.try_clone().expect("share dev log")) + .stderr(output); + // The project's own metadata decides where its processes listen. + for name in [ + "BIND", + "UI_HOST", + "UI_BIND", + "UI_PORT", + "UI_URL", + "PUBLIC_ORIGIN", + ] { + command.env_remove(name); + } + DevProcess { + child: command.spawn().expect("start distributed dev"), + log, + } + } +} + +/// How long a step that may compile the project gets. +#[cfg(unix)] +const COMPILES: Duration = Duration::from_secs(300); + +#[cfg(unix)] +struct DevProcess { + child: std::process::Child, + log: PathBuf, +} + +#[cfg(unix)] +impl DevProcess { + fn log(&self) -> String { + fs::read_to_string(&self.log).unwrap_or_default() + } + + /// Polls until the session has printed `text`; fails once it has exited. + #[track_caller] + fn wait_for(&mut self, text: &str) { + let started = std::time::Instant::now(); + while !self.log().contains(text) { + let exited = self.child.try_wait().expect("inspect distributed dev"); + assert!( + exited.is_none() && started.elapsed() < COMPILES, + "distributed dev never printed `{text}` (exit: {exited:?}):\n{}", + self.log() + ); + thread::sleep(Duration::from_millis(20)); + } + } + + fn signal(&self, signal: libc::c_int) { + assert_eq!( + unsafe { libc::kill(self.child.id() as libc::pid_t, signal) }, + 0 + ); + } + + fn wait(&mut self) -> std::process::ExitStatus { + let started = std::time::Instant::now(); + loop { + if let Some(status) = self.child.try_wait().expect("inspect distributed dev") { + return status; + } + assert!( + started.elapsed() < Duration::from_secs(60), + "distributed dev did not exit:\n{}", + self.log() + ); + thread::sleep(Duration::from_millis(10)); + } + } +} + +#[cfg(unix)] +impl Drop for DevProcess { + /// A failed test still stops its session: killing `distributed dev` + /// outright would orphan what it started. + fn drop(&mut self) { + if self.child.try_wait().is_ok_and(|status| status.is_none()) { + self.signal(libc::SIGTERM); + let started = std::time::Instant::now(); + while self.child.try_wait().is_ok_and(|status| status.is_none()) + && started.elapsed() < Duration::from_secs(30) + { + thread::sleep(Duration::from_millis(10)); + } + } + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +/// A session with two processes that each started a descendant ignoring +/// SIGTERM, and a build executor (with its own descendant) in flight. +#[cfg(unix)] +fn signaled_dev_session_leaves_no_descendant(label: &str, signal: libc::c_int) { + let project = Project::new(label); + let root = &project.root; + let mut dev = project.dev(); + dev.wait_for("lifecycle dev: ready"); + fs::write(root.join("slow-manifest"), "yes\n").unwrap(); + fs::write(root.join("service/src/name.txt"), "changed\n").unwrap(); + wait_until(COMPILES, || { + !recorded_pids(&root.join("build-family.log")).is_empty() + }); + let mut session = recorded_pids(&root.join("dev-family.log")); + session.extend(recorded_pids(&root.join("build-family.log"))); + assert_eq!( + session.len(), + 6, + "two processes, one executor, a descendant each" + ); + for pid in &session { + assert_eq!( + unsafe { libc::kill(*pid, 0) }, + 0, + "{pid} runs before the signal" + ); + } + + dev.signal(signal); + let status = dev.wait(); + assert!(status.success(), "{status}:\n{}", dev.log()); + assert!( + dev.log().contains("lifecycle dev: stopped"), + "{}", + dev.log() + ); + assert_no_survivors(&session); +} + +#[cfg(unix)] +#[test] +#[ignore = "compiles the lifecycle test project; run in the integration job"] +fn dev_interrupted_leaves_no_descendant() { + signaled_dev_session_leaves_no_descendant("dev-sigint", libc::SIGINT); +} + +#[cfg(unix)] +#[test] +#[ignore = "compiles the lifecycle test project; run in the integration job"] +fn dev_terminated_leaves_no_descendant() { + signaled_dev_session_leaves_no_descendant("dev-sigterm", libc::SIGTERM); +} + +#[cfg(unix)] +#[test] +#[ignore = "compiles the lifecycle test project; run in the integration job"] +fn dev_hung_up_leaves_no_descendant() { + signaled_dev_session_leaves_no_descendant("dev-sighup", libc::SIGHUP); +} + +/// `distributed build` runs the manifest harness itself, before the lifecycle +/// graph. A lone SIGTERM stops that child and what it started. +#[cfg(unix)] +#[test] +#[ignore = "compiles the lifecycle test project; run in the integration job"] +fn build_terminated_leaves_no_descendant() { + let project = Project::new("build-sigterm"); + let root = &project.root; + fs::write(root.join("slow-manifest"), "yes\n").unwrap(); + let mut build = Command::new(env!("CARGO_BIN_EXE_distributed")) + .arg("build") + .arg(root) + .env( + "CARGO_TARGET_DIR", + Path::new(env!("CARGO_TARGET_TMPDIR")).join("lifecycle-project"), + ) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("start distributed build"); + let started = std::time::Instant::now(); + while recorded_pids(&root.join("build-family.log")).is_empty() { + let exited = build.try_wait().expect("inspect distributed build"); + if exited.is_some() || started.elapsed() > COMPILES { + let _ = build.kill(); + panic!("the manifest harness never ran (exit: {exited:?})"); + } + thread::sleep(Duration::from_millis(20)); + } + let harness = recorded_pids(&root.join("build-family.log")); + assert_eq!(harness.len(), 2, "the harness and its descendant"); + + assert_eq!( + unsafe { libc::kill(build.id() as libc::pid_t, libc::SIGTERM) }, + 0 + ); + let status = build.wait().expect("wait for distributed build"); + assert!(!status.success(), "a stopped build fails: {status}"); + assert_no_survivors(&harness); + assert!(!root.join(".distributed/lifecycle/active.json").exists()); +} + +#[cfg(unix)] +#[test] +fn dev_that_fails_leaves_no_descendant() { + let mut fixture = Fixture::new("dev-failed"); + enable_dev(&mut fixture); + let root = fixture.root.clone(); + let supervisor = DevSupervisor::start(&fixture); + // Both processes are ready: a process that dies while its readiness is + // awaited is a different failure. + wait_until(Duration::from_secs(5), || { + dev_state(&root)["members"]["ui"].is_object() + && recorded_pids(&root.join("dev-family.log")).len() == 4 + }); + let session = recorded_pids(&root.join("dev-family.log")); + + // One process dies under the supervisor; the session ends with an error. + assert_eq!(unsafe { libc::kill(session[0], libc::SIGKILL) }, 0); + let error = supervisor + .join_result() + .expect_err("a dead process ends the session"); + assert!(error.message().contains("exited with"), "{error}"); + assert_no_survivors(&session); +} + +#[cfg(unix)] +#[test] +#[ignore = "compiles the lifecycle test project; run in the integration job"] +fn dev_keeps_running_while_a_watched_input_is_missing_and_says_so_once() { + let project = Project::new("dev-missing-input"); + let root = &project.root; + let mut dev = project.dev(); + dev.wait_for("lifecycle dev: ready"); + + // An editor or a checkout removes the file before writing its replacement. + let manifest = root.join("service/Cargo.toml"); + let replacement = fs::read_to_string(&manifest).unwrap() + "\n# replaced\n"; + fs::remove_file(&manifest).unwrap(); + dev.wait_for("cannot read watched inputs"); + // Several polls (500ms each) see the same failure. + thread::sleep(Duration::from_secs(2)); + fs::write(&manifest, replacement).unwrap(); + dev.wait_for("lifecycle dev: activated generation"); + + dev.signal(libc::SIGINT); + let status = dev.wait(); + let log = dev.log(); + assert!(status.success(), "{status}:\n{log}"); + assert_eq!( + log.matches("cannot read watched inputs").count(), + 1, + "{log}" + ); + assert_eq!( + log.matches("watched inputs are readable again").count(), + 1, + "{log}" + ); + assert!(log.contains("rebuilds=1"), "{log}"); +} diff --git a/distributed_cli/tests/cli_manifest.rs b/distributed_cli/tests/cli_manifest.rs index a98df5f89..f0caa3317 100644 --- a/distributed_cli/tests/cli_manifest.rs +++ b/distributed_cli/tests/cli_manifest.rs @@ -41,6 +41,15 @@ fn distributed(args: &[&str]) -> String { fn describe_emits_manifest_json() { let json = distributed(&["describe"]); let manifest: serde_json::Value = serde_json::from_str(&json).unwrap(); + assert_eq!(manifest["schema_version"], 3); + for inventory in ["commands", "events", "models", "projections"] { + assert!(manifest.get(inventory).is_none(), "redundant {inventory}"); + } + // This read-model-only fixture owns models through its Surface, not modules. + assert!(!manifest["surfaces"][0]["contract"]["models"] + .as_array() + .unwrap() + .is_empty()); assert!(json.contains("\"schema_version\""), "json: {json}"); assert!(json.contains("\"orders\""), "json: {json}"); let framework = manifest["extensions"] @@ -63,13 +72,17 @@ fn client_manifest_uses_service_surface_export() { assert_eq!(manifest["service_id"], "orders"); assert_eq!(manifest["surface"]["kind"], "role"); assert_eq!(manifest["surface"]["name"], "user"); + // The fingerprint commits to the exported schema contract: it is the one + // a client recomputes from the manifest itself. + let decoded: distributed::graphql::DistributedClientManifest = + serde_json::from_value(manifest.clone()).unwrap(); assert_eq!( manifest["schema_fingerprint"], - "sha256:8f91d3fc7b6d916241b959f6bacd6228eeb06586e9681739ba3e986b4092e134" + decoded.computed_schema_fingerprint().unwrap() ); assert_eq!( manifest["protocol_fingerprint"], - "sha256:00fb342f3acb4dc1c1716a43cc3001c748d5f6c500ff831690d820e9e43e2782" + "sha256:0dfa8a3f49e17d8d99c5c095c1ed14f528cae3e55fbc2f2b852975a50936ec5b" ); assert_eq!(manifest["models"][0]["id"], "OrderView"); assert_eq!(manifest["models"][0]["record_revisions"], true); @@ -92,7 +105,7 @@ fn client_manifest_uses_service_surface_export() { ); assert_eq!( manifest["commands"][0]["extensions"]["direct_projection"]["topology"]["digest"], - "sha256:32e51a5f5c3b7a83d27366f8dc889b87045e65f027f7b598421a6db765efe8a4" + "sha256:e1a6b71d390f627c5b446daa9b035499f87c03ef24b15df275a807658084b31d" ); assert_eq!( manifest["commands"][0]["extensions"]["direct_projection"]["model"], @@ -115,14 +128,15 @@ fn client_manifest_uses_service_surface_export() { fn emitted_client_manifest_is_accepted_by_client_compiler() { let json = distributed(&["client-manifest"]); let manifest: serde_json::Value = serde_json::from_str(&json).unwrap(); - let project = distributed_cli::compile_client(distributed_cli::ClientCompileInput::new( + let project = distributed_cli::ClientCompileInput::from_manifest_json( manifest, - distributed_cli::ClientSurfaceSelector::role("user"), + distributed_cli::ClientSurfaceIdentity::role("user"), vec![distributed_cli::ClientDocument::new( "src/routes/orders/+page.graphql", "query Orders { orders { order_id status } }", )], - )) + ) + .and_then(distributed_cli::compile_client) .expect("the compiler must consume the exact manifest emitted by the server crate"); assert_eq!(project.operations.len(), 1); diff --git a/distributed_cli/tests/cli_scaffold.rs b/distributed_cli/tests/cli_scaffold.rs index 6710a2e17..bb216bd9d 100644 --- a/distributed_cli/tests/cli_scaffold.rs +++ b/distributed_cli/tests/cli_scaffold.rs @@ -84,7 +84,8 @@ fn scaffold_generates_a_service_tree() { assert!(deploy_values.starts_with("local: false\npreview: false\n")); assert!(deploy_values.contains("tag: \"\"")); assert!(!read(&out_dir, ".gitops/local/templates/deployment.yaml").contains(".Values.local")); - assert!(read(&out_dir, ".gitops/deploy/templates/deployment.yaml").contains("image.tag must be an immutable build tag")); + assert!(read(&out_dir, ".gitops/deploy/templates/deployment.yaml") + .contains("image.tag must be an immutable build tag")); let cargo = read(&out_dir, "Cargo.toml"); assert!(cargo.contains("\"postgres\""), "Cargo.toml: {cargo}"); @@ -167,6 +168,7 @@ fn knative_transport_serves_the_cloudevents_router() { // The scaffolded axum must match the major the `distributed` crate exposes // its `Router` from, or `axum::serve(listener, app)` cannot type-check. assert!(cargo.contains("axum = \"0.8\""), "{cargo}"); + assert!(cargo.contains("\"knative\""), "{cargo}"); let service = read(&out_dir, "src/service.rs"); assert!(service.contains(".transport(\"knative\")"), "{service}"); } diff --git a/distributed_cli/tests/cli_scaffold_compile.rs b/distributed_cli/tests/cli_scaffold_compile.rs index 9811ed7a7..5afbb10dd 100644 --- a/distributed_cli/tests/cli_scaffold_compile.rs +++ b/distributed_cli/tests/cli_scaffold_compile.rs @@ -100,7 +100,15 @@ fn scaffolded_http_tracing_service_compiles() { fn scaffolded_query_api_service_compiles() { let out_dir = scaffold( "compile-query-api-sqlite", - &["--query-api", "--store", "sqlite", "--model", "order"], + &[ + "--query-api", + "--store", + "sqlite", + "--model", + "order", + "--command", + "orders.place", + ], ); cargo_check(&out_dir); } diff --git a/distributed_cli/tests/cli_skills_init.rs b/distributed_cli/tests/cli_skills_init.rs index 86c7d305e..3b8b8efb5 100644 --- a/distributed_cli/tests/cli_skills_init.rs +++ b/distributed_cli/tests/cli_skills_init.rs @@ -78,7 +78,7 @@ fn init_bootstraps_a_fresh_project_and_reruns_are_noops() { let agents_md = read(&dir, "AGENTS.md"); assert!(agents_md.contains(BEGIN) && agents_md.contains(END)); assert!(stdout.contains("created .distributed/skills/distributed-ci/SKILL.md")); - assert!(stdout.contains("Initialized 4 skills at .distributed/skills (wired: claude, agents)")); + assert!(stdout.contains("Initialized 5 skills at .distributed/skills (wired: claude, agents)")); // No strays at the harness skill roots (only skill folders). for root in [".agents/skills", ".claude/skills"] { diff --git a/distributed_cli/tests/fixtures/game-client/sample/client.ts b/distributed_cli/tests/fixtures/game-client/sample/client.ts new file mode 100644 index 000000000..7d2651912 --- /dev/null +++ b/distributed_cli/tests/fixtures/game-client/sample/client.ts @@ -0,0 +1,68 @@ +// @generated by `distributed game-client` from game surface `sample` (schema v3, protocol v1). +// Typed client factory. +// Do not edit: change the Rust definitions and regenerate. +import { GameClient, mergeCorrections, type GameClientOptions, type GamePredictionOptions, type WasmSource } from '@hops-ops/distributed/game'; + +import { EVENTS, type Events } from './events.ts'; +import { encodeInput, type SampleInput } from './input.ts'; +import { createSamplePrediction, type SamplePrediction } from './predict.ts'; +import { CORRECTIONS } from './schema.ts'; + +/** + * Prediction tuning; `encodeInput`, the correction defaults and `predict` (the + * compiled `#[predict]` step) are filled in. A `predict` given here replaces + * the WebAssembly step. + */ +export type SamplePredictionOptions = Omit, 'encodeInput' | 'predict'> & + Partial, 'encodeInput' | 'predict'>>; + +export type SampleClientOptions = Omit, 'prediction'> & + Readonly<{ + /** Prediction tuning, or `false` for none. Default: the compiled step. */ + prediction?: SamplePredictionOptions | false; + /** Where to load the compiled step from (default `PREDICT_WASM_URL`). */ + wasm?: WasmSource; + }>; + +export type SampleClient = Readonly<{ + client: GameClient; + /** The compiled step (`ready`, `setContext`); undefined when prediction is off or custom. */ + prediction: SamplePrediction | undefined; + /** Typed event subscription (every zone); returns the unsubscribe. */ + on(name: K, handler: (value: Events[K], zoneId: string) => void): () => void; + /** Send one input: predicted when prediction is on, raw otherwise. */ + send(input: SampleInput): number | undefined; +}>; + +/** + * A `GameClient` for the `sample` surface with its input encoder, correction + * defaults and the compiled predicted step wired in. + */ +export function createSampleClient(options: SampleClientOptions): SampleClient { + const { prediction: tuning, wasm, ...rest } = options; + const prediction = + tuning === false || tuning?.predict !== undefined ? undefined : createSamplePrediction(wasm); + const client = new GameClient({ + ...rest, + prediction: + tuning === false + ? undefined + : { + ...tuning, + predict: tuning?.predict ?? prediction!.predict, + encodeInput: tuning?.encodeInput ?? ((input) => encodeInput(input)), + corrections: mergeCorrections(CORRECTIONS, tuning?.corrections) + } + }); + return { + client, + prediction, + on: (name, handler) => + client.on('event', (zoneId, event) => { + const codec = EVENTS[name]; + if (event.typeId === codec.id) handler(codec.decode(event.payload), zoneId); + }), + send: (input) => + tuning === false ? client.sendRawInput(encodeInput(input)) : client.sendInput(input) + }; +} diff --git a/distributed_cli/tests/fixtures/game-client/sample/constants.ts b/distributed_cli/tests/fixtures/game-client/sample/constants.ts new file mode 100644 index 000000000..1d0bbf15a --- /dev/null +++ b/distributed_cli/tests/fixtures/game-client/sample/constants.ts @@ -0,0 +1,21 @@ +// @generated by `distributed game-client` from game surface `sample` (schema v3, protocol v1). +// Constants: static data defined once in Rust (`GameSurface::constant`). +// Do not edit: change the Rust definitions and regenerate. +import type { Board, Spot } from './events.ts'; + +/** `sample_board`, as the client decodes it. */ +export const SAMPLE_BOARD: Board = { + version: 7, + kills: [ + { rank: 1, name: 'Ada', score: 9007199254740991 }, + { rank: 2, name: 'Bob ✓', score: 3 } + ], + note: undefined, + motd: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' +}; + +/** `sample_gusts`, as the client decodes it. */ +export const SAMPLE_GUSTS: readonly number[] = [0.10000000149011612, -2.5]; + +/** `sample_spot`, as the client decodes it. */ +export const SAMPLE_SPOT: Spot = { at: 1.313783049583435, label: 'dock' }; diff --git a/distributed_cli/tests/fixtures/game-client/sample/events.ts b/distributed_cli/tests/fixtures/game-client/sample/events.ts new file mode 100644 index 000000000..3febc862a --- /dev/null +++ b/distributed_cli/tests/fixtures/game-client/sample/events.ts @@ -0,0 +1,253 @@ +// @generated by `distributed game-client` from game surface `sample` (schema v3, protocol v1). +// Events and records: payload interfaces, ids, codecs, typed subscriptions. +// Do not edit: change the Rust definitions and regenerate. +import { decodeGameEvent, decodePayload, decodeValue, encodePayload, encodeValue, onGameEvent, type DecodedGameEvent, type GameEventCodecs, type GameEventSource, type PayloadLayout, type WireType } from '@hops-ops/distributed/game'; + +/** Record `Row` (`#[derive(GameRecord)]`). */ +export interface Row { + readonly rank: number; + readonly name: string; + readonly score: number; +} + +const ROW_TYPE: WireType = { + type: 'record', + fields: [ + ['rank', { type: 'u16' }], + ['name', { type: 'short_str' }], + ['score', { type: 'u64' }], + ] +}; + +/** Record `Board` (`#[derive(GameRecord)]`). */ +export interface Board { + readonly version: number; + readonly kills: readonly Row[]; + readonly note: string | undefined; + readonly motd: string; +} + +const BOARD_TYPE: WireType = { + type: 'record', + fields: [ + ['version', { type: 'u32' }], + ['kills', { type: 'list', item: ROW_TYPE }], + ['note', { type: 'optional', item: { type: 'short_str' } }], + ['motd', { type: 'str' }], + ] +}; + +/** Record `SampleState` (`#[derive(GameRecord)]`). */ +export interface SampleState { + readonly x: number; + readonly vx: number; + readonly hp: number; + readonly dead: boolean; +} + +/** Record `SampleWind` (`#[derive(GameRecord)]`). */ +export interface SampleWind { + readonly speed: number; + readonly gusts: number; +} + +const SAMPLE_WIND_TYPE: WireType = { + type: 'record', + fields: [ + ['speed', { type: 'f32' }], + ['gusts', { type: 'u16' }], + ] +}; + +/** Record `Spot` (`#[derive(GameRecord)]`). */ +export interface Spot { + readonly at: number; + readonly label: string; +} + +/** Encode a `SampleWind` record (standalone codec, e.g. served over HTTP). */ +export function encodeSampleWind(value: SampleWind): Uint8Array { + return encodeValue(SAMPLE_WIND_TYPE, value); +} + +/** Decode a whole `SampleWind` record (throws on trailing or missing bytes). */ +export function decodeSampleWind(bytes: Uint8Array): SampleWind { + return decodeValue(SAMPLE_WIND_TYPE, bytes) as SampleWind; +} + +/** Event `hello` (id 1). */ +export interface HelloEvent { + readonly entity: number; + readonly viewRadius: number; + readonly half: number; +} + +const HELLO_LAYOUT: PayloadLayout = [ + ['entity', { type: 'u32' }], + ['viewRadius', { type: 'f32' }], + ['half', { type: 'quant', min: 0, max: 64, bits: 10 }], +]; + +/** Event `board` (id 2). */ +export type BoardEvent = Board; + +const BOARD_PAYLOAD: WireType = BOARD_TYPE; + +/** Event `respawned` (id 3): no payload. */ +export type RespawnedEvent = Readonly>; + +const RESPAWNED_LAYOUT: PayloadLayout = []; + +/** Event `shot` (id 4). */ +export interface ShotEvent { + readonly hit: boolean; + readonly target: number | undefined; + readonly offset: number; + readonly small: number; + readonly atMs: number; + readonly tags: readonly string[]; + readonly bytes: Uint8Array; + readonly total: number; +} + +const SHOT_LAYOUT: PayloadLayout = [ + ['hit', { type: 'bool' }], + ['target', { type: 'optional', item: { type: 'u32' } }], + ['offset', { type: 'i16' }], + ['small', { type: 'i8' }], + ['atMs', { type: 'f64' }], + ['tags', { type: 'list', item: { type: 'short_str' } }], + ['bytes', { type: 'bytes' }], + ['total', { type: 'u64' }], +]; + +/** Event `ping` (id 9). */ +export interface PingEvent { + readonly seq: number; +} + +const PING_LAYOUT: PayloadLayout = [ + ['seq', { type: 'u32' }], +]; + +/** Message `announce` (id 1). */ +export interface AnnounceMessage { + readonly text: string; + readonly urgent: boolean; +} + +const MESSAGE_ANNOUNCE_LAYOUT: PayloadLayout = [ + ['text', { type: 'str' }], + ['urgent', { type: 'bool' }], +]; + +/** Message `set_wind` (id 2). */ +export type SetWindMessage = SampleWind; + +const MESSAGE_SET_WIND_PAYLOAD: WireType = SAMPLE_WIND_TYPE; + +/** Event type ids by name. */ +export const EVENT = { + hello: 1, + board: 2, + respawned: 3, + shot: 4, + ping: 9, +} as const; + +/** Event payload types by name. */ +export interface Events { + hello: HelloEvent; + board: BoardEvent; + respawned: RespawnedEvent; + shot: ShotEvent; + ping: PingEvent; +} + +/** Codecs of every event. */ +export const EVENTS: GameEventCodecs = { + hello: { + id: 1, + name: 'hello', + encode: (value) => encodePayload(HELLO_LAYOUT, value), + decode: (payload) => decodePayload(HELLO_LAYOUT, payload) as unknown as HelloEvent + }, + board: { + id: 2, + name: 'board', + encode: (value) => encodeValue(BOARD_PAYLOAD, value), + decode: (payload) => decodeValue(BOARD_PAYLOAD, payload) as BoardEvent + }, + respawned: { + id: 3, + name: 'respawned', + encode: (value) => encodePayload(RESPAWNED_LAYOUT, value), + decode: (payload) => decodePayload(RESPAWNED_LAYOUT, payload) as unknown as RespawnedEvent + }, + shot: { + id: 4, + name: 'shot', + encode: (value) => encodePayload(SHOT_LAYOUT, value), + decode: (payload) => decodePayload(SHOT_LAYOUT, payload) as unknown as ShotEvent + }, + ping: { + id: 9, + name: 'ping', + encode: (value) => encodePayload(PING_LAYOUT, value), + decode: (payload) => decodePayload(PING_LAYOUT, payload) as unknown as PingEvent + }, +}; + +/** A decoded event, discriminated by `name`. */ +export type AnyEvent = DecodedGameEvent; + +/** Decode an Event message (`undefined` for ids this surface does not declare). */ +export function decodeEvent(event: { readonly typeId: number; readonly payload: Uint8Array }): AnyEvent | undefined { + return decodeGameEvent(EVENTS, event); +} + +/** Subscribe to one typed event on every zone of `client`; returns the unsubscribe. */ +export function onEvent( + client: GameEventSource, + name: K, + handler: (value: Events[K], zoneId: string) => void +): () => void { + return onGameEvent(client, EVENTS, name, handler); +} + +/** Zone inbox message type ids by name. */ +export const MESSAGE = { + announce: 1, + setWind: 2, +} as const; + +/** Zone inbox message payload types by name. */ +export interface Messages { + announce: AnnounceMessage; + setWind: SetWindMessage; +} + +/** Codecs of every zone inbox message. */ +export const MESSAGES: GameEventCodecs = { + announce: { + id: 1, + name: 'announce', + encode: (value) => encodePayload(MESSAGE_ANNOUNCE_LAYOUT, value), + decode: (payload) => decodePayload(MESSAGE_ANNOUNCE_LAYOUT, payload) as unknown as AnnounceMessage + }, + setWind: { + id: 2, + name: 'set_wind', + encode: (value) => encodeValue(MESSAGE_SET_WIND_PAYLOAD, value), + decode: (payload) => decodeValue(MESSAGE_SET_WIND_PAYLOAD, payload) as SetWindMessage + }, +}; + +/** Encode a zone inbox message: `typeId` and `payload` of a `/admin/zone-message` body (base64url the payload). */ +export function encodeMessage( + name: K, + value: Messages[K] +): { readonly typeId: number; readonly payload: Uint8Array } { + const codec = MESSAGES[name]; + return { typeId: codec.id, payload: codec.encode(value) }; +} diff --git a/distributed_cli/tests/fixtures/game-client/sample/index.ts b/distributed_cli/tests/fixtures/game-client/sample/index.ts new file mode 100644 index 000000000..aa01a9bfc --- /dev/null +++ b/distributed_cli/tests/fixtures/game-client/sample/index.ts @@ -0,0 +1,10 @@ +// @generated by `distributed game-client` from game surface `sample` (schema v3, protocol v1). +// Everything generated for this surface. +// Do not edit: change the Rust definitions and regenerate. +export * from './client.ts'; +export * from './constants.ts'; +export * from './events.ts'; +export * from './input.ts'; +export * from './predict.ts'; +export * from './pures.ts'; +export * from './schema.ts'; diff --git a/distributed_cli/tests/fixtures/game-client/sample/input.ts b/distributed_cli/tests/fixtures/game-client/sample/input.ts new file mode 100644 index 000000000..c30fd7a07 --- /dev/null +++ b/distributed_cli/tests/fixtures/game-client/sample/input.ts @@ -0,0 +1,64 @@ +// @generated by `distributed game-client` from game surface `sample` (schema v3, protocol v1). +// Input frame: interface, button bits, encoder, decoder, sanitize. +// Do not edit: change the Rust definitions and regenerate. +import { decodePayload, encodePayload, sanitizePayload, type InputRule, type PayloadLayout } from '@hops-ops/distributed/game'; + +/** One `SampleInput` input frame (`#[derive(GameInput)]`). */ +export interface SampleInput { + readonly mx: number; + readonly my: number; + readonly buttons: number; + readonly aim: number; + readonly power: number; + readonly viewTick: number; +} + +export type Input = SampleInput; + +/** Bits of each bit-flag field (`#[buttons(..)]`), by field. */ +export const BITS = { + buttons: { + dash: 1, + attack: 2, + }, +} as const; + +/** Bits of `buttons`, the only bit-flag field. */ +export const BUTTON = BITS.buttons; + +/** Wire layout, in field order. */ +export const INPUT_LAYOUT: PayloadLayout = [ + ['mx', { type: 'i8' }], + ['my', { type: 'i8' }], + ['buttons', { type: 'u8' }], + ['aim', { type: 'angle', bits: 10 }], + ['power', { type: 'f32' }], + ['viewTick', { type: 'u32' }], +]; + +const INPUT_RULES: readonly InputRule[] = [ + { range: [-127, 127] }, + { range: [-127, 127] }, + { buttons: 3 }, + undefined, + { range: [0, 1] }, + undefined, +]; + +/** Payload bytes of one input frame. */ +export function encodeInput(input: SampleInput): Uint8Array { + return encodePayload(INPUT_LAYOUT, input); +} + +/** Decode one input frame (no sanitizing). */ +export function decodeInput(payload: Uint8Array): SampleInput { + return decodePayload(INPUT_LAYOUT, payload) as unknown as SampleInput; +} + +/** + * What the zone simulates for `input` (`#[range]` clamps, `#[buttons]` masks, + * wire precision); `undefined` when the server would drop it (non-finite float). + */ +export function sanitizeInput(input: SampleInput): SampleInput | undefined { + return sanitizePayload(INPUT_LAYOUT, INPUT_RULES, input); +} diff --git a/distributed_cli/tests/fixtures/game-client/sample/predict.ts b/distributed_cli/tests/fixtures/game-client/sample/predict.ts new file mode 100644 index 000000000..a90c23756 --- /dev/null +++ b/distributed_cli/tests/fixtures/game-client/sample/predict.ts @@ -0,0 +1,53 @@ +// @generated by `distributed game-client` from game surface `sample` (schema v3, protocol v1). +// Client-predicted step: the Rust `#[predict]` fn compiled to WebAssembly (binary ABI). +// Do not edit: change the Rust definitions and regenerate. +import { createWasmPrediction, type PredictStateLayout, type WasmPrediction, type WasmSource, type PayloadLayout } from '@hops-ops/distributed/game'; + +import type { SampleWind } from './events.ts'; +import { encodeInput, type SampleInput } from './input.ts'; + +/** The predicted step: `#[predict]` fn `sample_step` of Cargo package `distributed_game`, predicting kind `player`. */ +export const PREDICT = { + kind: 'player', + export: 'sample_step', + package: 'distributed_game', + state: 'SampleState', + abi: 1, +} as const; + +/** Predicted `player` fields (record `SampleState`): wire field name and codec type, in record order. */ +export const PREDICT_STATE: PredictStateLayout = [ + ['x', { type: 'f32' }], + ['vx', { type: 'f32' }], + ['hp', { type: 'u8' }], + ['dead', { type: 'bool' }], +]; + +/** What the step reads besides state and input (`prediction.setContext`). */ +export type PredictContext = SampleWind; + +/** Layout of the context record `SampleWind`. */ +export const PREDICT_CONTEXT: PayloadLayout | undefined = [ + ['speed', { type: 'f32' }], + ['gusts', { type: 'u16' }], +]; + +/** The compiled step (`distributed game-wasm`); bundlers emit it as an asset. */ +export const PREDICT_WASM_URL: URL = new URL('./wasm/sample.wasm', import.meta.url); + +/** The `sample` step as `GameClient` prediction (see `createWasmPrediction`). */ +export type SamplePrediction = WasmPrediction; + +/** + * Load the compiled step (default `PREDICT_WASM_URL`) as prediction: `predict` + * leaves the state unchanged until `ready` resolves and a context is set. + */ +export function createSamplePrediction(source: WasmSource = PREDICT_WASM_URL): SamplePrediction { + return createWasmPrediction({ + source, + exportName: PREDICT.export, + state: PREDICT_STATE, + context: PREDICT_CONTEXT, + encodeInput + }); +} diff --git a/distributed_cli/tests/fixtures/game-client/sample/pures.ts b/distributed_cli/tests/fixtures/game-client/sample/pures.ts new file mode 100644 index 000000000..c56081ff6 --- /dev/null +++ b/distributed_cli/tests/fixtures/game-client/sample/pures.ts @@ -0,0 +1,54 @@ +// @generated by `distributed game-client` from game surface `sample` (schema v3, protocol v1). +// Pure functions: the Rust `#[game_pure]` fns compiled to WebAssembly (binary ABI). +// Do not edit: change the Rust definitions and regenerate. +import { createWasmPures, type WasmPures, type WasmSource, type WireType } from '@hops-ops/distributed/game'; + +import type { Row, SampleWind } from './events.ts'; + +const ROW_TYPE: WireType = { + type: 'record', + fields: [ + ['rank', { type: 'u16' }], + ['name', { type: 'short_str' }], + ['score', { type: 'u64' }], + ] +}; + +const SAMPLE_WIND_TYPE: WireType = { + type: 'record', + fields: [ + ['speed', { type: 'f32' }], + ['gusts', { type: 'u16' }], + ] +}; + +/** The pure functions (`#[game_pure]`) of Cargo package `distributed_game`: wrapper name → module export. */ +export const PURES = { + sampleMirror: { export: 'sample_mirror', abi: 1 }, + sampleRows: { export: 'sample_rows', abi: 1 }, +} as const; + +/** The compiled module (`distributed game-wasm`; shared with the predicted step); bundlers emit it as an asset. */ +export const PURES_WASM_URL: URL = new URL('./wasm/sample.wasm', import.meta.url); + +/** Typed calls of the compiled functions (synchronous; they throw until `ready` resolves). */ +export interface SamplePureFns { + /** `sample_mirror` (`dg_pure_sample_mirror`). */ + sampleMirror(arg: SampleWind): SampleWind; + /** `sample_rows` (`dg_pure_sample_rows`). */ + sampleRows(): readonly Row[]; +} + +/** The `sample` pure functions plus `ready` / `loaded()` / `module()`. */ +export type SamplePures = WasmPures; + +/** + * Load the compiled pure functions (default `PURES_WASM_URL`; a URL loaded by + * the predicted step too is instantiated once). + */ +export function createSamplePures(source: WasmSource = PURES_WASM_URL): SamplePures { + return createWasmPures(source, { + sampleMirror: { exportName: 'sample_mirror', arg: SAMPLE_WIND_TYPE, output: SAMPLE_WIND_TYPE }, + sampleRows: { exportName: 'sample_rows', output: { type: 'list', item: ROW_TYPE } }, + }); +} diff --git a/distributed_cli/tests/fixtures/game-client/sample/schema.ts b/distributed_cli/tests/fixtures/game-client/sample/schema.ts new file mode 100644 index 000000000..9cdb565f3 --- /dev/null +++ b/distributed_cli/tests/fixtures/game-client/sample/schema.ts @@ -0,0 +1,150 @@ +// @generated by `distributed game-client` from game surface `sample` (schema v3, protocol v1). +// Replicated kinds: ids, typed fields, wire types, correction defaults. +// Do not edit: change the Rust definitions and regenerate. +import { fieldBool, fieldBytes, fieldNumber, fieldString, type CorrectionPolicies, type EntityFields, type WireType } from '@hops-ops/distributed/game'; + +/** Replicated kind ids by name. */ +export const KIND = { + player: 1, + marker: 2, + stats: 4, +} as const; + +export type KindName = keyof typeof KIND; + +/** `player` (kind 1, priority 2). */ +export interface PlayerFields { + /** `quant [-20, 19.999847] / 18 bits` */ + readonly x: number; + /** `quant [-20, 19.999847] / 18 bits` */ + readonly y: number; + /** `quant [-16, 16] / 12 bits` */ + readonly vx: number; + /** `angle / 8 bits` */ + readonly face: number; + /** `short_str`, priority 0.2 */ + readonly name: string; + /** `u8` */ + readonly hp: number; + /** `u16` */ + readonly level: number; + /** `bool` */ + readonly dead: boolean; + /** `i32` */ + readonly score: number; + /** `f32` */ + readonly raw: number; + /** `bytes` */ + readonly blob: Uint8Array; + /** `u32` */ + readonly kills: number; +} + +/** True for a `player` entity. */ +export function isPlayer(entity: { readonly kind: number }): boolean { + return entity.kind === 1; +} + +/** Typed fields of a `player` entity (rendered or replica). */ +export function playerFields(entity: { readonly fields: EntityFields }): PlayerFields { + const f = entity.fields; + return { + x: fieldNumber(f, 'x'), + y: fieldNumber(f, 'y'), + vx: fieldNumber(f, 'vx'), + face: fieldNumber(f, 'face'), + name: fieldString(f, 'name'), + hp: fieldNumber(f, 'hp'), + level: fieldNumber(f, 'level'), + dead: fieldBool(f, 'dead'), + score: fieldNumber(f, 'score'), + raw: fieldNumber(f, 'raw'), + blob: fieldBytes(f, 'blob'), + kills: fieldNumber(f, 'kills'), + }; +} + +/** `marker` (kind 2, priority 1). */ +export interface MarkerFields { + /** `quant [-64, 63.998047] / 16 bits` */ + readonly px: number; + /** `quant [-64, 63.998047] / 16 bits` */ + readonly py: number; + /** `short_str` */ + readonly label: string; +} + +/** True for a `marker` entity. */ +export function isMarker(entity: { readonly kind: number }): boolean { + return entity.kind === 2; +} + +/** Typed fields of a `marker` entity (rendered or replica). */ +export function markerFields(entity: { readonly fields: EntityFields }): MarkerFields { + const f = entity.fields; + return { + px: fieldNumber(f, 'px'), + py: fieldNumber(f, 'py'), + label: fieldString(f, 'label'), + }; +} + +/** `stats` (kind 4, priority 1). */ +export interface StatsFields { + /** `u16` */ + readonly slowMs: number; + /** `f32` */ + readonly tickMs: number; +} + +/** True for a `stats` entity. */ +export function isStats(entity: { readonly kind: number }): boolean { + return entity.kind === 4; +} + +/** Typed fields of a `stats` entity (rendered or replica). */ +export function statsFields(entity: { readonly fields: EntityFields }): StatsFields { + const f = entity.fields; + return { + slowMs: fieldNumber(f, 'slow_ms'), + tickMs: fieldNumber(f, 'tick_ms'), + }; +} + +/** Wire type of every replicated field, by kind and wire field name. */ +export const FIELD_TYPES = { + player: { + x: { type: 'quant', min: -20, max: 19.999847412109375, bits: 18 }, + y: { type: 'quant', min: -20, max: 19.999847412109375, bits: 18 }, + vx: { type: 'quant', min: -16, max: 16, bits: 12 }, + face: { type: 'angle', bits: 8 }, + name: { type: 'short_str' }, + hp: { type: 'u8' }, + level: { type: 'u16' }, + dead: { type: 'bool' }, + score: { type: 'i32' }, + raw: { type: 'f32' }, + blob: { type: 'bytes' }, + kills: { type: 'u32' }, + }, + marker: { + px: { type: 'quant', min: -64, max: 63.998046875, bits: 16 }, + py: { type: 'quant', min: -64, max: 63.998046875, bits: 16 }, + label: { type: 'short_str' }, + }, + stats: { + slow_ms: { type: 'u16' }, + tick_ms: { type: 'f32' }, + }, +} as const satisfies Record>; + +/** Client correction defaults (`#[correct(..)]`), by kind and wire field name. */ +export const CORRECTIONS: CorrectionPolicies = { + player: { + x: { mode: 'ease', durationMs: 150 }, + y: { mode: 'ease', durationMs: 150, snapAbove: 2.5 }, + vx: { mode: 'snap' }, + face: { mode: 'replace' }, + name: { mode: 'replace' }, + }, +}; diff --git a/distributed_cli/tests/fixtures/game-client/sample/surface.json b/distributed_cli/tests/fixtures/game-client/sample/surface.json new file mode 100644 index 000000000..d3d7c3a39 --- /dev/null +++ b/distributed_cli/tests/fixtures/game-client/sample/surface.json @@ -0,0 +1,629 @@ +{ + "codecs": [ + "SampleWind" + ], + "constants": [ + { + "name": "sample_board", + "type": { + "name": "Board", + "type": "record" + }, + "value": { + "kills": [ + { + "name": "Ada", + "rank": 1, + "score": 9007199254740991 + }, + { + "name": "Bob ✓", + "rank": 2, + "score": 3 + } + ], + "motd": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "note": null, + "version": 7 + } + }, + { + "name": "sample_gusts", + "type": { + "item": { + "type": "f32" + }, + "type": "list" + }, + "value": [ + 0.10000000149011612, + -2.5 + ] + }, + { + "name": "sample_spot", + "type": { + "name": "Spot", + "type": "record" + }, + "value": { + "at": 1.313783049583435, + "label": "dock" + } + } + ], + "events": [ + { + "id": 1, + "name": "hello", + "payload": { + "fields": [ + { + "name": "entity", + "type": { + "type": "u32" + } + }, + { + "name": "view_radius", + "type": { + "type": "f32" + } + }, + { + "name": "half", + "type": { + "bits": 10, + "max": 64.0, + "min": 0.0, + "type": "quant" + } + } + ], + "kind": "fields" + } + }, + { + "id": 2, + "name": "board", + "payload": { + "kind": "value", + "type": { + "name": "Board", + "type": "record" + } + } + }, + { + "id": 3, + "name": "respawned", + "payload": { + "fields": [], + "kind": "fields" + } + }, + { + "id": 4, + "name": "shot", + "payload": { + "fields": [ + { + "name": "hit", + "type": { + "type": "bool" + } + }, + { + "name": "target", + "type": { + "item": { + "type": "u32" + }, + "type": "optional" + } + }, + { + "name": "offset", + "type": { + "type": "i16" + } + }, + { + "name": "small", + "type": { + "type": "i8" + } + }, + { + "name": "at_ms", + "type": { + "type": "f64" + } + }, + { + "name": "tags", + "type": { + "item": { + "type": "short_str" + }, + "type": "list" + } + }, + { + "name": "bytes", + "type": { + "type": "bytes" + } + }, + { + "name": "total", + "type": { + "type": "u64" + } + } + ], + "kind": "fields" + } + }, + { + "id": 9, + "name": "ping", + "payload": { + "fields": [ + { + "name": "seq", + "type": { + "type": "u32" + } + } + ], + "kind": "fields" + } + } + ], + "input": { + "fields": [ + { + "name": "mx", + "range": [ + -127.0, + 127.0 + ], + "type": { + "type": "i8" + } + }, + { + "name": "my", + "range": [ + -127.0, + 127.0 + ], + "type": { + "type": "i8" + } + }, + { + "buttons": [ + "dash", + "attack" + ], + "name": "buttons", + "type": { + "type": "u8" + } + }, + { + "name": "aim", + "type": { + "bits": 10, + "type": "angle" + } + }, + { + "name": "power", + "range": [ + 0.0, + 1.0 + ], + "type": { + "type": "f32" + } + }, + { + "name": "view_tick", + "type": { + "type": "u32" + } + } + ], + "name": "SampleInput" + }, + "kinds": [ + { + "fields": [ + { + "correction": { + "durationMs": 150, + "mode": "ease" + }, + "name": "x", + "priority": 1.0, + "type": { + "bits": 18, + "max": 19.999847, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": { + "durationMs": 150, + "mode": "ease", + "snapAbove": 2.5 + }, + "name": "y", + "priority": 1.0, + "type": { + "bits": 18, + "max": 19.999847, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "vx", + "priority": 1.0, + "type": { + "bits": 12, + "max": 16.0, + "min": -16.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "face", + "priority": 1.0, + "type": { + "bits": 8, + "type": "angle" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "name", + "priority": 0.2, + "type": { + "type": "short_str" + } + }, + { + "correction": null, + "name": "hp", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": null, + "name": "level", + "priority": 1.0, + "type": { + "type": "u16" + } + }, + { + "correction": null, + "name": "dead", + "priority": 1.0, + "type": { + "type": "bool" + } + }, + { + "correction": null, + "name": "score", + "priority": 1.0, + "type": { + "type": "i32" + } + }, + { + "correction": null, + "name": "raw", + "priority": 1.0, + "type": { + "type": "f32" + } + }, + { + "correction": null, + "name": "blob", + "priority": 1.0, + "type": { + "type": "bytes" + } + }, + { + "correction": null, + "name": "kills", + "priority": 1.0, + "type": { + "type": "u32" + } + } + ], + "id": 1, + "name": "player", + "priority": 2.0 + }, + { + "fields": [ + { + "correction": null, + "name": "px", + "priority": 1.0, + "type": { + "bits": 16, + "max": 63.998047, + "min": -64.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "py", + "priority": 1.0, + "type": { + "bits": 16, + "max": 63.998047, + "min": -64.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "label", + "priority": 1.0, + "type": { + "type": "short_str" + } + } + ], + "id": 2, + "name": "marker", + "priority": 1.0 + }, + { + "fields": [ + { + "correction": null, + "name": "slow_ms", + "priority": 1.0, + "type": { + "type": "u16" + } + }, + { + "correction": null, + "name": "tick_ms", + "priority": 1.0, + "type": { + "type": "f32" + } + } + ], + "id": 4, + "name": "stats", + "priority": 1.0 + } + ], + "messages": [ + { + "id": 1, + "name": "announce", + "payload": { + "fields": [ + { + "name": "text", + "type": { + "type": "str" + } + }, + { + "name": "urgent", + "type": { + "type": "bool" + } + } + ], + "kind": "fields" + } + }, + { + "id": 2, + "name": "set_wind", + "payload": { + "kind": "value", + "type": { + "name": "SampleWind", + "type": "record" + } + } + } + ], + "name": "sample", + "predict": { + "abi": 1, + "context": "SampleWind", + "export": "sample_step", + "kind": "player", + "package": "distributed_game", + "state": "SampleState" + }, + "protocolVersion": 1, + "pures": [ + { + "abi": 1, + "arg": { + "name": "SampleWind", + "type": "record" + }, + "export": "sample_mirror", + "output": { + "name": "SampleWind", + "type": "record" + }, + "package": "distributed_game" + }, + { + "abi": 1, + "export": "sample_rows", + "output": { + "item": { + "name": "Row", + "type": "record" + }, + "type": "list" + }, + "package": "distributed_game" + } + ], + "records": [ + { + "fields": [ + { + "name": "version", + "type": { + "type": "u32" + } + }, + { + "name": "kills", + "type": { + "item": { + "name": "Row", + "type": "record" + }, + "type": "list" + } + }, + { + "name": "note", + "type": { + "item": { + "type": "short_str" + }, + "type": "optional" + } + }, + { + "name": "motd", + "type": { + "type": "str" + } + } + ], + "name": "Board" + }, + { + "fields": [ + { + "name": "rank", + "type": { + "type": "u16" + } + }, + { + "name": "name", + "type": { + "type": "short_str" + } + }, + { + "name": "score", + "type": { + "type": "u64" + } + } + ], + "name": "Row" + }, + { + "fields": [ + { + "name": "x", + "type": { + "type": "f32" + } + }, + { + "name": "vx", + "type": { + "type": "f32" + } + }, + { + "name": "hp", + "type": { + "type": "u8" + } + }, + { + "name": "dead", + "type": { + "type": "bool" + } + } + ], + "name": "SampleState" + }, + { + "fields": [ + { + "name": "speed", + "type": { + "type": "f32" + } + }, + { + "name": "gusts", + "type": { + "type": "u16" + } + } + ], + "name": "SampleWind" + }, + { + "fields": [ + { + "name": "at", + "type": { + "bits": 10, + "max": 64.0, + "min": 0.0, + "type": "quant" + } + }, + { + "name": "label", + "type": { + "type": "short_str" + } + } + ], + "name": "Spot" + } + ], + "schemaVersion": 3 +} diff --git a/distributed_cli/tests/fixtures/game-surface/Cargo.toml b/distributed_cli/tests/fixtures/game-surface/Cargo.toml new file mode 100644 index 000000000..330aa0e08 --- /dev/null +++ b/distributed_cli/tests/fixtures/game-surface/Cargo.toml @@ -0,0 +1,15 @@ +# Standalone fixture compiled by `distributed game-manifest` in integration tests. +# Its own `[workspace]` decouples it from the repo workspace. +[package] +name = "game-surface-fixture" +version = "0.0.0" +edition = "2021" +publish = false + +[workspace] + +[lib] +path = "src/lib.rs" + +[dependencies] +distributed_game = { path = "../../../../distributed_game" } diff --git a/distributed_cli/tests/fixtures/game-surface/src/lib.rs b/distributed_cli/tests/fixtures/game-surface/src/lib.rs new file mode 100644 index 000000000..75cdfdb42 --- /dev/null +++ b/distributed_cli/tests/fixtures/game-surface/src/lib.rs @@ -0,0 +1,99 @@ +//! A minimal zone surface for `distributed game-manifest` tests. + +use distributed_game::{ + game_pure, predict, schema, Ctx, EntitySchema, GameEvent, GameInput, GameRecord, GameSurface, PlayerId, + Replicated, WorldView, Zone, +}; + +#[derive(Replicated)] +#[replicated(kind = "orb", id = 1)] +pub struct OrbView { + #[quant(centered = 32.0, bits = 14)] + #[correct(ease = 80)] + pub x: f32, + #[quant(centered = 32.0, bits = 14)] + #[correct(ease = 80)] + pub y: f32, +} + +#[derive(Clone, Copy, GameInput)] +pub struct Steer { + #[range(min = -127, max = 127)] + pub turn: i8, + #[buttons(boost)] + pub buttons: u8, +} + +#[derive(GameEvent)] +pub enum OrbEvent { + #[game_event(id = 1)] + Hello { entity: u32 }, +} + +/// The predicted part of an orb. +#[derive(Clone, Copy, GameRecord)] +pub struct OrbState { + pub x: f32, +} + +/// The client-predicted step (compiled to WASM by `distributed game-wasm`). +#[predict(OrbStep, kind = "orb")] +pub fn orb_step(state: &OrbState, input: &Steer, _context: &(), dt: f32) -> OrbState { + OrbState { + x: state.x + f32::from(input.turn) * dt, + } +} + +/// A pure function compiled into the same module (`dg_pure_orb_radius`). +#[game_pure(OrbRadiusFn)] +pub fn orb_radius(state: &OrbState) -> f32 { + (state.x * state.x).sqrt() +} + +/// Static data the client gets as a generated constant. +#[derive(Clone, Copy, GameRecord)] +pub struct OrbLimits { + pub limit: f32, +} + +pub struct Orbs; + +impl Zone for Orbs { + type Config = (); + type Input = Steer; + type Timer = (); + type Message = distributed_game::NoMessages; + + fn schema() -> EntitySchema { + schema![OrbView] + } + + fn on_create(_ctx: &mut Ctx<'_, Self>, _config: ()) -> Self { + Orbs + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { + Steer::from_payload(payload) + } + + fn on_tick(&mut self, _ctx: &mut Ctx<'_, Self>) {} + + fn replicate(&self, out: &mut WorldView) { + out.add(1, &OrbView { x: 0.0, y: 0.0 }); + } +} + +/// The export `distributed game-manifest` runs by default. +pub fn game_surface() -> GameSurface { + GameSurface::for_zone::("orbs") + .events::() + .predict::() + .pure::() + .constant("orb_limits", &OrbLimits { limit: 32.0 }) +} + +/// A second export of the same package (concurrent harness runs must each +/// print their own entrypoint's surface). +pub fn bare_surface() -> GameSurface { + GameSurface::for_zone::("bare") +} diff --git a/distributed_cli/tests/fixtures/generated-commands.ts b/distributed_cli/tests/fixtures/generated-commands.ts index 6994f8724..5a27aaa43 100644 --- a/distributed_cli/tests/fixtures/generated-commands.ts +++ b/distributed_cli/tests/fixtures/generated-commands.ts @@ -67,8 +67,8 @@ export const Command_importTodos: ReplicaCommandArtifact { + return createLazyReplicaCommandRuntime(replica, transport, + { commands: COMMAND_CATALOG, status: COMMAND_STATUS }, + () => import('./generated-commands.js').then(({ COMMANDS }) => ({ entries: COMMANDS })), options); +} diff --git a/distributed_cli/tests/fixtures/generated-leaderboards.ts b/distributed_cli/tests/fixtures/generated-leaderboards.ts new file mode 100644 index 000000000..79ca4841f --- /dev/null +++ b/distributed_cli/tests/fixtures/generated-leaderboards.ts @@ -0,0 +1,50 @@ +/** GENERATED by distributed client. Server-ranked leaderboard queries; not replica-cached. */ + +export interface LeaderboardEntry { + /** Zero-based rank in the board's order. */ + readonly rank: number; + readonly member: string; + readonly score: number; +} + +export type XpLeaderboardVariables = { readonly first?: number | null; }; +export type XpLeaderboardData = { readonly xpLeaderboard: readonly LeaderboardEntry[] }; +export const XpLeaderboardLeaderboard = { + leaderboard: "xp", + operation: "top", + order: "high_first", + limits: { defaultFirst: 3, maxFirst: 5, maxRadius: 2 }, + document: "query XpLeaderboard($first: Int) { xpLeaderboard(first: $first) { rank member score } }", + liveDocument: "subscription XpLeaderboard_Live($first: Int) { xpLeaderboard(first: $first) { rank member score } }", + schemaHash: "sha256:1e530895b54f8e80d0d2162cfdf5e2b5eb67a8956735bdc82b6c8f10df870743", +} as const; + +export type XpMyRankVariables = {}; +export type XpMyRankData = { readonly xpMyRank: LeaderboardEntry | null }; +export const XpMyRankLeaderboard = { + leaderboard: "xp", + operation: "my_rank", + order: "high_first", + limits: { defaultFirst: 3, maxFirst: 5, maxRadius: 2 }, + document: "query XpMyRank { xpMyRank { rank member score } }", + liveDocument: "subscription XpMyRank_Live { xpMyRank { rank member score } }", + schemaHash: "sha256:1e530895b54f8e80d0d2162cfdf5e2b5eb67a8956735bdc82b6c8f10df870743", +} as const; + +export type SeasonRankVariables = { readonly board: string; readonly member: string; }; +export type SeasonRankData = { readonly seasonRank: LeaderboardEntry | null }; +export const SeasonRankLeaderboard = { + leaderboard: "season", + operation: "rank", + order: "low_first", + limits: { defaultFirst: 10, maxFirst: 100, maxRadius: 25 }, + document: "query SeasonRank($board: String!, $member: String!) { seasonRank(board: $board, member: $member) { rank member score } }", + liveDocument: null, + schemaHash: "sha256:1e530895b54f8e80d0d2162cfdf5e2b5eb67a8956735bdc82b6c8f10df870743", +} as const; + +export const LEADERBOARD_OPERATIONS = { + "xpLeaderboard": XpLeaderboardLeaderboard, + "xpMyRank": XpMyRankLeaderboard, + "seasonRank": SeasonRankLeaderboard, +} as const; diff --git a/distributed_cli/tests/fixtures/generated-operation.ts b/distributed_cli/tests/fixtures/generated-operation.ts index 46a11817f..b4a174856 100644 --- a/distributed_cli/tests/fixtures/generated-operation.ts +++ b/distributed_cli/tests/fixtures/generated-operation.ts @@ -827,7 +827,8 @@ export const Operation_ScalarInputs: ReplicaOperationArtifact ("ui", address), + None => ("api", std::env::var("BIND").expect("the API is given BIND")), + }; + let descendant = Command::new("/bin/sh") + .args(["-c", r#"trap "" TERM; while :; do sleep 1; done"#]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("start descendant"); + let record = |file: &str, line: String| { + let mut log = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(root.join(file)) + .expect("open dev process log"); + // One write, so a reader never sees half of the record. + log.write_all(format!("{line}\n").as_bytes()) + .expect("record dev process"); + }; + let generation = std::env::var("DISTRIBUTED_GENERATION_ID").unwrap_or_default(); + let directory = std::env::current_dir().expect("working directory"); + record( + "dev-environment.log", + format!("{name}:{}", directory.display()), + ); + record( + "dev-family.log", + format!("{} {}", std::process::id(), descendant.id()), + ); + record("dev-process.log", format!("{name}:{generation}")); + // Readiness is a connection, so whoever sees it also sees the records. + let listener = TcpListener::bind(&address).expect("bind the dev process address"); + for connection in listener.incoming() { + drop(connection); + } +} diff --git a/distributed_cli/tests/fixtures/lifecycle-project/service/Cargo.toml b/distributed_cli/tests/fixtures/lifecycle-project/service/Cargo.toml new file mode 100644 index 000000000..c30e2fb20 --- /dev/null +++ b/distributed_cli/tests/fixtures/lifecycle-project/service/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "fixture-service" +version = "0.1.0" +edition = "2021" + +[dependencies] +distributed = { path = "@DISTRIBUTED@" } diff --git a/distributed_cli/tests/fixtures/lifecycle-project/service/src/lib.rs b/distributed_cli/tests/fixtures/lifecycle-project/service/src/lib.rs new file mode 100644 index 000000000..496251447 --- /dev/null +++ b/distributed_cli/tests/fixtures/lifecycle-project/service/src/lib.rs @@ -0,0 +1,42 @@ +//! The typed application of the lifecycle test project. +//! +//! `distributed describe` compiles and runs `application_manifest`. A test +//! steers that run with marker files in the project root, and changes the +//! manifest by editing `name.txt`. + +use std::io::Write; +use std::path::Path; +use std::process::{Command, Stdio}; +use std::time::Duration; + +pub fn application_manifest() -> distributed::ApplicationManifest { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .expect("the service is a member of the project"); + if root.join("fail-manifest").exists() { + eprintln!("injected manifest failure"); + std::process::exit(17); + } + if root.join("slow-manifest").exists() { + // A descendant that ignores SIGTERM, with none of this process's pipes. + let descendant = Command::new("/bin/sh") + .args(["-c", r#"trap "" TERM; while :; do sleep 1; done"#]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("start descendant"); + let mut log = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(root.join("build-family.log")) + .expect("open build-family.log"); + // One write, so a reader never sees half of the record. + log.write_all(format!("{} {}\n", std::process::id(), descendant.id()).as_bytes()) + .expect("record processes"); + while root.join("slow-manifest").exists() { + std::thread::sleep(Duration::from_millis(20)); + } + } + distributed::ApplicationManifest::new(include_str!("name.txt").trim()) +} diff --git a/distributed_cli/tests/fixtures/lifecycle-project/service/src/name.txt b/distributed_cli/tests/fixtures/lifecycle-project/service/src/name.txt new file mode 100644 index 000000000..ee8c1ee49 --- /dev/null +++ b/distributed_cli/tests/fixtures/lifecycle-project/service/src/name.txt @@ -0,0 +1 @@ +fixture diff --git a/distributed_cli/tests/fixtures/lifecycle-project/ui/Cargo.toml b/distributed_cli/tests/fixtures/lifecycle-project/ui/Cargo.toml new file mode 100644 index 000000000..de1ed6c77 --- /dev/null +++ b/distributed_cli/tests/fixtures/lifecycle-project/ui/Cargo.toml @@ -0,0 +1,4 @@ +[package] +name = "fixture-ui" +version = "0.1.0" +edition = "2021" diff --git a/distributed_cli/tests/fixtures/lifecycle-project/ui/package.json b/distributed_cli/tests/fixtures/lifecycle-project/ui/package.json new file mode 100644 index 000000000..8af2b5f3a --- /dev/null +++ b/distributed_cli/tests/fixtures/lifecycle-project/ui/package.json @@ -0,0 +1 @@ +{ "name": "fixture-ui", "private": true } diff --git a/distributed_cli/tests/fixtures/lifecycle-project/ui/src/main.rs b/distributed_cli/tests/fixtures/lifecycle-project/ui/src/main.rs new file mode 100644 index 000000000..3fad0171f --- /dev/null +++ b/distributed_cli/tests/fixtures/lifecycle-project/ui/src/main.rs @@ -0,0 +1,3 @@ +// The UI is the runner under a name of its own: two `cargo run`s of one +// binary replace it under each other. +include!("../../runner/src/main.rs"); diff --git a/distributed_cli/tests/fixtures/orders-service/src/lib.rs b/distributed_cli/tests/fixtures/orders-service/src/lib.rs index 8e81ee8e9..4b4768d24 100644 --- a/distributed_cli/tests/fixtures/orders-service/src/lib.rs +++ b/distributed_cli/tests/fixtures/orders-service/src/lib.rs @@ -3,10 +3,13 @@ use std::any::TypeId; +use distributed::command::{ + typed_command, Atomic, CommandInputType, CommandOutputType, CommandTypeDef, CommandTypeField, + PreparedCommand, +}; use distributed::graphql::{ - build_surface, surface_for_role, typed_command, DistributedClientSurfaceExport, - Atomic, GraphqlInputType, GraphqlOutputType, GraphqlTypeDef, GraphqlTypeField, PreparedCommand, - RoleGrant, SurfaceOptions, SurfaceProjector, + build_surface, read, surface_for_role, DistributedClientSurfaceExport, + SurfaceOptions, SurfaceProjector, }; use distributed::microsvc::{CausalCommandContext, HandlerError, Routes, Service}; use distributed::{ @@ -23,12 +26,13 @@ pub struct OrderView { pub status: String, } -impl GraphqlOutputType for OrderView { - fn graphql_type() -> GraphqlTypeDef { - GraphqlTypeDef::new( +impl CommandOutputType for OrderView { + fn command_type() -> CommandTypeDef { + CommandTypeDef::new( "OrderView", vec![ - GraphqlTypeField { + CommandTypeField { + unsigned_integer: None, name: "order_id".into(), type_name: "String".into(), nullable: false, @@ -36,7 +40,8 @@ impl GraphqlOutputType for OrderView { item_nullable: false, nested: None, }, - GraphqlTypeField { + CommandTypeField { + unsigned_integer: None, name: "status".into(), type_name: "String".into(), nullable: false, @@ -55,11 +60,12 @@ struct ProjectOrderInput { order_id: String, } -impl GraphqlInputType for ProjectOrderInput { - fn graphql_type() -> GraphqlTypeDef { - GraphqlTypeDef::new( +impl CommandInputType for ProjectOrderInput { + fn command_type() -> CommandTypeDef { + CommandTypeDef::new( "ProjectOrderInput", - vec![GraphqlTypeField { + vec![CommandTypeField { + unsigned_integer: None, name: "order_id".into(), type_name: "String".into(), nullable: false, @@ -153,7 +159,7 @@ pub fn distributed_client_surface() -> DistributedClientSurfaceExport { .expect("fixture projector should bind"); let grants = std::collections::BTreeMap::from([( "OrderView".to_string(), - RoleGrant::all_columns().with_aggregations(), + read().all_columns().aggregations(), )]); let user = surface_for_role(&full, "user", &grants).expect("fixture role policy should be valid"); diff --git a/distributed_cli/tests/fixtures/runtime-bridge-operation.json b/distributed_cli/tests/fixtures/runtime-bridge-operation.json index 9fde60eca..82db9ff2e 100644 --- a/distributed_cli/tests/fixtures/runtime-bridge-operation.json +++ b/distributed_cli/tests/fixtures/runtime-bridge-operation.json @@ -99,7 +99,8 @@ ], "protocol": { "version": 1, - "schemaHash": "sha256:787216f76fd2c62f867b9d9553710c888f325c6cc5598c4681fb34c1a655e3be", + "schemaHash": "sha256:c412ca635b39dcdfe58946594c9b718af976cbe150912a932b24c3b6c2bb2f2f", + "protocolHash": "sha256:0dfa8a3f49e17d8d99c5c095c1ed14f528cae3e55fbc2f2b852975a50936ec5b", "surface": { "kind": "role", "name": "user" diff --git a/distributed_cli/tests/fixtures/unique-key-bridge-operation.json b/distributed_cli/tests/fixtures/unique-key-bridge-operation.json new file mode 100644 index 000000000..9df0b4a1e --- /dev/null +++ b/distributed_cli/tests/fixtures/unique-key-bridge-operation.json @@ -0,0 +1,333 @@ +{ + "id": "sha256:64d793257325afec58385b9e2e5e3d55fa778bc4d01753a123bd6fab2b67b010", + "document": "query UniqueKeyBridge {\n todos(limit: 25) {\n id\n title\n owner {\n id\n title\n _distributed_tenantId: tenantId\n _distributed_typename: __typename\n }\n _distributed_tenantId: tenantId\n _distributed_typename: __typename\n _distributed_ownerTitle: ownerTitle\n }\n}\n", + "source": { + "path": "src/routes/unique-key/+page.graphql", + "line": 1, + "column": 1 + }, + "variableCodec": { + "version": 2, + "limits": { + "maxDepth": 8, + "maxBoolWidth": 256, + "maxInList": 1000 + }, + "variables": {}, + "defaults": {}, + "inputs": {} + }, + "roots": [ + { + "responseKey": "todos", + "field": "todos", + "cardinality": "many", + "nullable": false, + "arguments": { + "limit": { + "kind": "literal", + "value": 25 + } + }, + "dependencies": [ + "todo_rows" + ], + "coverage": { + "kind": "offset", + "offsetArgument": "offset", + "limitArgument": "limit", + "defaultLimit": 25, + "maxLimit": 100 + }, + "filter": { + "fields": [ + { + "field": "completed", + "scalar": "Boolean", + "codec": "boolean", + "nullable": false, + "operators": [ + "_eq" + ] + }, + { + "field": "id", + "scalar": "ID", + "codec": "string", + "nullable": false, + "operators": [ + "_eq" + ] + }, + { + "field": "ownerTitle", + "scalar": "String", + "codec": "string", + "nullable": true, + "operators": [ + "_eq" + ] + }, + { + "field": "priority", + "scalar": "Int", + "codec": "int32", + "nullable": false, + "operators": [ + "_eq", + "_in", + "_nin" + ] + }, + { + "field": "tenantId", + "scalar": "ID", + "codec": "string", + "nullable": false, + "operators": [ + "_eq" + ] + }, + { + "field": "title", + "scalar": "String", + "codec": "string", + "nullable": true, + "operators": [ + "_eq" + ] + } + ], + "relationships": [ + { + "field": "owner", + "targetModel": "Todo", + "kind": "belongs_to", + "keyMapping": { + "kind": "direct", + "local": [ + "tenantId", + "ownerTitle" + ], + "remote": [ + "tenantId", + "title" + ] + }, + "maintenance": "local", + "dependencies": [ + "todo_rows" + ] + } + ], + "rowPolicy": { + "kind": "unrestricted" + } + }, + "order": { + "fields": [ + { + "field": "completed", + "scalar": "Boolean", + "codec": "boolean", + "nullable": false + }, + { + "field": "id", + "scalar": "ID", + "codec": "string", + "nullable": false + }, + { + "field": "ownerTitle", + "scalar": "String", + "codec": "string", + "nullable": true + }, + { + "field": "priority", + "scalar": "Int", + "codec": "int32", + "nullable": false + }, + { + "field": "tenantId", + "scalar": "ID", + "codec": "string", + "nullable": false + }, + { + "field": "title", + "scalar": "String", + "codec": "string", + "nullable": true + } + ], + "tieBreakers": [ + { + "field": "tenantId", + "scalar": "ID", + "codec": "string", + "nullable": false + }, + { + "field": "id", + "scalar": "ID", + "codec": "string", + "nullable": false + } + ] + }, + "pagination": { + "kind": "offset", + "insert": "local", + "delete": "local", + "reorder": "local", + "stableUpdate": "local" + }, + "selection": { + "typename": "todo", + "storage": { + "kind": "normalized", + "model": "Todo", + "identityFields": [ + "tenantId", + "id" + ] + }, + "members": [ + { + "kind": "scalar", + "responseKey": "id", + "field": "id", + "codec": "string", + "nullable": false + }, + { + "kind": "scalar", + "responseKey": "title", + "field": "title", + "codec": "string", + "nullable": true + }, + { + "kind": "branch", + "semantic": "relationship", + "responseKey": "owner", + "field": "owner", + "cardinality": "one", + "nullable": true, + "dependencies": [ + "todo_rows" + ], + "coverage": { + "kind": "complete" + }, + "relationship": { + "field": "owner", + "targetModel": "Todo", + "kind": "belongs_to", + "keyMapping": { + "kind": "direct", + "local": [ + "tenantId", + "ownerTitle" + ], + "remote": [ + "tenantId", + "title" + ] + }, + "maintenance": "local", + "dependencies": [ + "todo_rows" + ] + }, + "selection": { + "typename": "todo", + "storage": { + "kind": "normalized", + "model": "Todo", + "identityFields": [ + "tenantId", + "id" + ] + }, + "members": [ + { + "kind": "scalar", + "responseKey": "id", + "field": "id", + "codec": "string", + "nullable": false + }, + { + "kind": "scalar", + "responseKey": "title", + "field": "title", + "codec": "string", + "nullable": true + }, + { + "kind": "scalar", + "responseKey": "_distributed_tenantId", + "field": "tenantId", + "codec": "string", + "nullable": false, + "expose": false + }, + { + "kind": "scalar", + "responseKey": "_distributed_typename", + "field": "__typename", + "codec": "string", + "nullable": false, + "expose": false + } + ] + } + }, + { + "kind": "scalar", + "responseKey": "_distributed_tenantId", + "field": "tenantId", + "codec": "string", + "nullable": false, + "expose": false + }, + { + "kind": "scalar", + "responseKey": "_distributed_typename", + "field": "__typename", + "codec": "string", + "nullable": false, + "expose": false + }, + { + "kind": "scalar", + "responseKey": "_distributed_ownerTitle", + "field": "ownerTitle", + "codec": "string", + "nullable": true, + "expose": false + } + ] + } + } + ], + "protocol": { + "version": 1, + "schemaHash": "sha256:e54b9612f0c48fffb597337e3246b43203cb33e6487319986d47920b772d4c1b", + "protocolHash": "sha256:0dfa8a3f49e17d8d99c5c095c1ed14f528cae3e55fbc2f2b852975a50936ec5b", + "surface": { + "kind": "role", + "name": "user" + }, + "operation": "sha256:64d793257325afec58385b9e2e5e3d55fa778bc4d01753a123bd6fab2b67b010", + "trustedPresets": [] + }, + "live": { + "id": "sha256:5f1d6c2a80bd0417bfd53ba757436a319fc6d9801af10247cd91cd32a6ac48e9", + "document": "subscription UniqueKeyBridge_Live {\n todos(limit: 25) {\n id\n title\n owner {\n id\n title\n _distributed_tenantId: tenantId\n _distributed_typename: __typename\n }\n _distributed_tenantId: tenantId\n _distributed_typename: __typename\n _distributed_ownerTitle: ownerTitle\n }\n}\n" + } +} diff --git a/distributed_cli/tests/support/golden.rs b/distributed_cli/tests/support/golden.rs new file mode 100644 index 000000000..dafd20663 --- /dev/null +++ b/distributed_cli/tests/support/golden.rs @@ -0,0 +1,24 @@ +//! The one byte-exact comparison for checked-in generated output, shared by +//! the crate's unit tests and its integration tests. + +use std::fs; +use std::path::Path; + +/// Assert `actual` is byte-identical to `tests/fixtures/`. +/// `UPDATE_GOLDEN=1` rewrites the fixture with `actual` instead; review the +/// diff, since downstream TypeScript and JavaScript tests read the same files. +pub(crate) fn assert_golden(fixture: &str, actual: &str) { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures") + .join(fixture); + if std::env::var_os("UPDATE_GOLDEN").is_some() { + fs::create_dir_all(path.parent().expect("fixture has a directory")).unwrap(); + fs::write(&path, actual).unwrap(); + return; + } + let golden = fs::read_to_string(&path).unwrap_or_default(); + assert_eq!( + golden, actual, + "{fixture} drifted; regenerate with UPDATE_GOLDEN=1" + ); +} diff --git a/distributed_game/Cargo.toml b/distributed_game/Cargo.toml new file mode 100644 index 000000000..6e19ecba4 --- /dev/null +++ b/distributed_game/Cargo.toml @@ -0,0 +1,167 @@ +[package] +name = "distributed_game" +description = "Authoritative multiplayer zone runtime for `distributed`: fixed-timestep zones, sequenced inputs, non-blocking durable facts, interest-managed binary replication and an optional WebSocket transport." +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +readme = "README.md" + +[lib] +path = "src/lib.rs" + +[features] +default = [] +# Tokio-driven fact worker (`spawn_fact_worker`). Core stays runtime-agnostic. +runtime = ["dep:tokio"] +# Adapter that commits facts into a `distributed` AggregateCell. +cell = ["dep:distributed", "dep:sha2", "dep:base64"] +# `command_sink::CommandFactSink` over `CelldCommandHost` / +# `LocalCommandHost` (a local service over any repository, or celld cells +# over HTTP). The sink itself is portable (`cell`). +command-host = ["cell", "distributed/graphql"] +# celld clients: `CelldFactSink` (the command sink over a remote-only +# `CelldCommandHost`), `CellZoneOwnership`, `CellZoneStateStore`. +celld = ["cell", "command-host", "dep:reqwest", "dep:uuid"] +# celld worker glue (wasm32 Durable Objects): `world::zone_state::celld_worker`, +# the zone-state HTTP surface over a cell and an R2 bucket binding. +cloudflare-workers = ["cell", "dep:worker", "distributed/cloudflare-workers"] +# Zones as celld Durable Objects (wasm32): `celld_zone::ZoneObject`, +# `CelldObjectHost` (facts object to object), `celld_zone_object!`. +celld-zone = ["cell", "ticket", "cloudflare-workers", "dep:js-sys", "dep:wasm-bindgen", "dep:wasm-bindgen-futures", "dep:futures-util"] +# Per-zone Prometheus metrics (dependency-free text exposition). +metrics = [] +# Load-test bots (library + `game-bots` binary). +bots = ["net", "dep:tokio-tungstenite", "dep:futures-util", "tokio/rt-multi-thread"] +# axum WebSocket zone server with signed-ticket admission (+ /metrics). +# HMAC-signed admission tickets (`ticket`) without the axum server (the +# celld zone host admits players with it). +ticket = ["dep:hmac", "dep:sha2", "dep:base64"] +net = ["runtime", "metrics", "ticket", "dep:distributed", "dep:reqwest", "dep:axum", "dep:hmac", "dep:sha2", "dep:base64", "tokio/net", "tokio/macros", "tokio/io-util"] +# `world::FencedLeaseOwnership`: zone ownership over `distributed::lease`. +lease = ["dep:distributed"] + +[dependencies] +distributed_game_macros = { version = "0.1.0", path = "../distributed_game_macros" } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +tokio = { version = "1", default-features = false, features = ["rt", "sync", "time"], optional = true } +distributed = { path = "..", default-features = false, optional = true } +axum = { version = "0.8", default-features = false, features = ["ws", "tokio", "http1"], optional = true } +hmac = { version = "0.12", optional = true } +sha2 = { version = "0.10", optional = true } +base64 = { version = "0.23", optional = true } +tokio-tungstenite = { version = "0.30", optional = true } +futures-util = { version = "0.3", default-features = false, features = ["sink", "std"], optional = true } +reqwest = { version = "0.13", default-features = false, features = ["json", "rustls"], optional = true } +uuid = { version = "1", features = ["v7"], optional = true } +worker = { version = "0.8", optional = true } +js-sys = { version = "0.3", optional = true } +wasm-bindgen = { version = "0.2", optional = true } +wasm-bindgen-futures = { version = "0.4", optional = true } + +[dev-dependencies] +base64 = "0.23" +# `tests/zone_status`: the read model projected by a consumer service over +# a SQLite bus and read-model store. +distributed = { path = "..", default-features = false, features = ["sqlite", "graphql"] } +sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", "sqlite"] } +trybuild = "=1.0.121" +tokio = { version = "1", features = ["full", "test-util"] } +tokio-tungstenite = "0.30" +futures-util = { version = "0.3", default-features = false, features = ["sink", "std"] } +serde = { version = "1", features = ["derive"] } + +[[bin]] +name = "game-bots" +path = "src/bin/game-bots.rs" +required-features = ["bots"] + +[[test]] +name = "netcode" +path = "tests/netcode/main.rs" +required-features = ["runtime"] + +[[test]] +name = "bots" +path = "tests/bots/main.rs" +required-features = ["bots"] + +[[test]] +name = "net_e2e" +path = "tests/net_e2e/main.rs" +required-features = ["net"] + +[[test]] +name = "zone_lease" +path = "tests/zone_lease/main.rs" +required-features = ["cell"] + +[[test]] +name = "content_rollout" +path = "tests/content_rollout/main.rs" +required-features = ["cell"] + +[[test]] +name = "zone_state" +path = "tests/zone_state/main.rs" +required-features = ["cell"] + +[[test]] +name = "command_facts" +path = "tests/command_facts/main.rs" +required-features = ["command-host"] + +[[test]] +name = "zone_status" +path = "tests/zone_status/main.rs" +required-features = ["cell"] + +[[test]] +name = "celld_zone_lease" +path = "tests/celld_zone_lease/main.rs" +required-features = ["celld", "runtime", "net"] + +[[test]] +name = "celld_zone_state" +path = "tests/celld_zone_state/main.rs" +required-features = ["celld", "runtime"] + +[[test]] +name = "celld_facts" +path = "tests/celld_facts/main.rs" +required-features = ["celld", "runtime"] + +[[test]] +name = "celld_zone" +path = "tests/celld_zone/main.rs" +required-features = ["celld", "net"] + +[[test]] +name = "inbox" +path = "tests/inbox/main.rs" +required-features = ["net"] + +[[test]] +name = "zone_message" +path = "tests/zone_message/main.rs" + +[[test]] +name = "lifecycle" +path = "tests/lifecycle/main.rs" +required-features = ["runtime"] + +[[test]] +name = "cell_facts" +path = "tests/cell_facts/main.rs" +required-features = ["cell", "runtime"] + +[[test]] +name = "world" +path = "tests/world/main.rs" +required-features = ["net", "lease", "celld"] + +[[example]] +name = "echo_arena" +path = "examples/echo_arena.rs" +required-features = ["net"] diff --git a/distributed_game/PROTOCOL.md b/distributed_game/PROTOCOL.md new file mode 100644 index 000000000..a1e84430b --- /dev/null +++ b/distributed_game/PROTOCOL.md @@ -0,0 +1,704 @@ +# distributed_game wire protocol — version 2 + +Normative specification of the binary protocol spoken between a +`distributed_game` zone server and its clients. The Rust implementation +lives in `src/protocol/` and `src/schema.rs`; the reference client-side +state machine is `protocol::ClientMirror`. Golden byte fixtures for +independent implementations live in `tests/fixtures/*.json` (§9). + +Key words MUST / MUST NOT / SHOULD / MAY are used as in RFC 2119. + +One version is specified: 2. A server speaks exactly that version and +refuses any other in the handshake (§6.0). + +--- + +## 1. Transport and framing + +### 1.1 WebSocket (normative transport) + +- Endpoint: `GET /zones/{zone_id}` upgraded to a WebSocket. The path + selects the zone; the zone in the admission ticket MUST equal it + (transfer tickets: §8.1). +- A host that does not own the zone answers the Hello with + `Redirect(zone_id, url)` and closes; the client MUST reconnect to `url` + and send the **same** Hello (the ticket was not consumed). Clients + SHOULD follow at most 3 redirects in a row. +- Every protocol message is exactly **one binary WebSocket message**. + There is no additional length prefix inside a WebSocket message. +- Text messages are a protocol violation: the server replies + `Error(BAD_MESSAGE)` and closes. +- The transport is reliable and ordered. Deltas are encoded against the + last state the server *sent* to that connection (§7.2), so a client MUST + apply every server message in order and MUST NOT skip any. +- Byte 0 of every message is the **message type** (§6). Client→server + types are `0x01..0x7f`; server→client types are `0x80..0xff`. +- Servers reject inbound messages larger than 64 KiB by default. + +### 1.2 Stream framing (non-message transports) + +For byte-stream transports (raw TCP, pipes, test harnesses) each message +is prefixed with its byte length as a `varuint` (§2): `varuint(len) ‖ message`. +WebSocket transports MUST NOT use this prefix. + +## 2. Primitive encodings + +All multi-byte fixed-width numbers are **little-endian**. + +| Name | Encoding | +|---|---| +| `u8` | 1 byte. | +| `bool` | `u8`, `0x00` = false, `0x01` = true. Any other value is a decode error. | +| `varuint` | Unsigned LEB128 of a 32-bit value: 7 bits per byte, least-significant group first; bit 7 (`0x80`) set means another byte follows. At most 5 bytes; in the 5th byte only the low 4 bits may be set (`<= 0x0f`), otherwise decode error (overflow). Encoders MUST emit the minimal form. | +| `varint` | Signed 32-bit, zigzag-mapped then `varuint`: `z = (v << 1) ^ (v >> 31)` (arithmetic shift); decode `v = (z >>> 1) ^ -(z & 1)`. | +| `f32` | IEEE-754 binary32, 4 bytes LE. | +| `f64` | IEEE-754 binary64, 8 bytes LE. | +| `string` | `varuint` byte length, then that many bytes of UTF-8. Length MUST be <= 1 MiB. Invalid UTF-8 is a decode error. | +| `bytes` | `varuint` length, then raw bytes (<= 1 MiB). | +| `short_string` | `u8` byte length (0..255), then UTF-8. Encoders truncate at a char boundary to fit 255 bytes. | + +Examples (from `fixtures/primitives.json`): + +| Value | Kind | Bytes | +|---|---|---| +| 0 | varuint | `00` | +| 127 | varuint | `7f` | +| 128 | varuint | `80 01` | +| 300 | varuint | `ac 02` | +| 4294967295 | varuint | `ff ff ff ff 0f` | +| -1 | varint | `01` | +| 1 | varint | `02` | +| -64 | varint | `7f` | +| 64 | varint | `80 01` | +| 1.5 | f32 | `00 00 c0 3f` | +| 1234.5 | f64 | `00 00 00 00 00 4a 93 40` | +| "hi" | string | `02 68 69` | +| "héros" | string | `06 68 c3 a9 72 6f 73` | + +JavaScript note: `varuint` values up to `2^32-1` exceed the int32 range; +decode with multiplication (`value += (b & 0x7f) * 2 ** shift`) or `>>> 0`, +never with signed `<<` on the 5th byte. + +## 3. Ids, ticks and times + +- **Sequence numbers** (`seq`) are `varuint`, start at **1** per connection + and strictly increase. `ack_seq = 0` means "nothing processed yet". +- **Ticks** are `varuint` holding the low 32 bits of the server's tick + counter. +- **Times** (`server_time`, `client_time`) are `f64` milliseconds on the + sender's own monotonic clock (origin arbitrary). Clients estimate + offset/RTT from Ping/Pong: + `rtt = now - pong.client_time`; `offset = pong.server_time + rtt/2 - now`. +- **Entity ids** are `varuint`, assigned by the game, unique within a zone. + An id MAY be reused after its remove has been sent. +- **Kind ids** are `varuint` values `<= 65535`. + +## 4. Field types and quantization + +Each component field has a wire type. Type tags appear in the schema (§5). + +| Tag | Type | Params (in schema) | Value encoding | Decoded value | +|---|---|---|---|---| +| 0 | `bool` | — | `bool` | boolean | +| 1 | `u8` | — | 1 raw byte | unsigned int | +| 2 | `u16` | — | `varuint` (MUST be <= 65535) | unsigned int | +| 3 | `u32` | — | `varuint` | unsigned int | +| 4 | `i32` | — | `varint` (zigzag) | signed int | +| 5 | `f32` | — | `f32` | float | +| 6 | `quant_f32` | `f32 min`, `f32 max`, `u8 bits` (1..32) | `varuint q` | float | +| 7 | `angle` | `u8 bits` (1..32) | `varuint q` | float (radians, `[0, 2π)`) | +| 8 | `short_str` | — | `short_string` | string | +| 9 | `bytes` | — | `bytes` | byte array | + +Unknown tags are a decode error. + +All quantization math below is performed in **IEEE-754 binary64** +(JavaScript `number`) in exactly the order written; conversions to f32 +are round-to-nearest-even (`Math.fround`). `floor` is mathematical floor. +Server and client MUST use identical formulas so client-side prediction +can reproduce exactly what the server will send. + +### 4.1 `quant_f32 {min, max, bits}` + +``` +maxq = 2^bits - 1 (as f64) +lo = f64(min); hi = f64(max) +encode(v): v is an f32 widened to f64 + if hi <= lo: q = 0 + else: + x = isNaN(v) ? lo : v + x = clamp(x, lo, hi) + t = (x - lo) / (hi - lo) + q = min(floor(t * maxq + 0.5), maxq) (round half up) +decode(q): + q MUST be <= maxq, otherwise decode error + v = fround(lo + (q / maxq) * (hi - lo)) +``` + +Worked example (`min=-100, max=100, bits=16`, from `fixtures/quantization.json`): +`v = 0.0` → `t = 0.5` → `q = floor(0.5 * 65535 + 0.5) = 32768` → bytes +`80 80 02`; decodes to `fround(-100 + (32768/65535) * 200) = 0.0015259022` +(bits `3ac800c8`). `v = 250` clamps to `q = 65535` (`ff ff 03`) → `100.0`. + +*Informative:* a symmetric range (`min = -max`) has `2^bits - 1` intervals, +so `0` is not on the grid (the example above decodes `0.0` as +`0.0015259022`). Signed quantities that must rest at exactly zero use +`max = -min · (1 - 2^-(bits-1))` (Rust: `FieldType::quant_centered`), which +puts `0` at `q = 2^(bits-1)`. + +### 4.2 `angle {bits}` + +``` +TAU = 6.283185307179586 (2π as f64) +steps = 2^bits (as f64) +encode(v): + if !isFinite(v): q = 0 + else: + a = v % TAU (truncated remainder, JS `%`, C fmod) + if a < 0: a = a + TAU + q = floor((a / TAU) * steps + 0.5) % steps +decode(q): + q MUST be < steps, otherwise decode error + v = fround((q * TAU) / steps) +``` + +Example (`bits=8`): `π` → `q = 128`; `-π/2` → `a = 3π/2` → `q = 192`; +`-0.000001` → `a ≈ TAU` → `q = 256 % 256 = 0`. + +### 4.3 Coercion (server side) + +The server coerces game-supplied values to the field type (numeric +saturation, `bool` = non-zero). Clients only ever see canonical values. + +## 5. Entity schema encoding + +Sent inside Welcome. A generic client decodes Deltas with it, no codegen. + +``` +schema := varuint kind_count, kind* +kind := varuint kind_id, string name, varuint field_count (<= 32), field* +field := string name, u8 type_tag, params +params := (tag 6) f32 min, f32 max, u8 bits + | (tag 7) u8 bits + | (other tags) nothing +``` + +Field order is wire order: field `i` is bit `i` of update masks. A kind +has at most 32 fields. Duplicate kind ids are a decode error. Server-side +replication priorities are not transmitted. + +## 6. Messages + +### 6.0 Version check + +- A client sends `protocol_version` 2 in Hello. +- A server MUST answer any other version with `Error(VERSION_MISMATCH)` + whose message starts with `protocol` (e.g. `protocol 1 unsupported`) + and close, **before** verifying the ticket or reconnect token, so + neither is consumed. (Content mismatches use the same code with a + message starting `content version`.) There is no fallback: a client + treats it as a terminal refusal (the JS SDK rejects the join). +- A client MUST NOT send a message gated by a runtime feature (`Focus`) + unless the Welcome announced it. + +### 6.1 Type bytes + +| Byte | Direction | Message | +|---|---|---| +| `0x01` | C→S | Hello | +| `0x02` | C→S | Input | +| `0x03` | C→S | Ping | +| `0x04` | C→S | Leave | +| `0x05` | C→S | Content | +| `0x06` | C→S | Near | +| `0x07` | C→S | Focus | +| `0x80` | S→C | Welcome | +| `0x81` | S→C | Delta | +| `0x82` | S→C | Event | +| `0x83` | S→C | Pong | +| `0x84` | S→C | Freeze | +| `0x85` | S→C | Resume | +| `0x86` | S→C | Handoff | +| `0x87` | S→C | Kick | +| `0x88` | S→C | Error | +| `0x89` | S→C | Redirect | + +Unknown type bytes and trailing bytes after a complete message are +decode errors. + +### 6.2 Client → server + +``` +Hello := 0x01, varuint protocol_version, string content_version, + varuint capabilities, string ticket, string reconnect_token, + bool near +Input := 0x02, varuint seq, varuint client_tick, bytes payload +Ping := 0x03, f64 client_time +Leave := 0x04 +Content := 0x05, string content_version +Near := 0x06, bool near +Focus := 0x07, f32 x, f32 y +``` + +- **Hello** MUST be the first message, sent within the server's hello + timeout (default 5 s); a silent connection is closed then, and any other + first message gets `Error(BAD_MESSAGE)` and close (no Pong before + Hello). Nothing is activated or woken before the Hello's ticket (or + reconnect token) is verified. `protocol_version` is `2` (§6.0). + `content_version` MUST equal the server's when the server pins one. + `capabilities` are game-defined bits, opaque to the runtime. For a fresh + join `ticket` is a signed admission ticket (§8) and `reconnect_token` is + empty; for a reconnect `ticket` MAY be empty and `reconnect_token` is the + token from the last Welcome. A second Hello gets `Error(BAD_MESSAGE)`. + `near` is for observers (ignored for players): see **Near**. +- **Input**: `payload` is game-defined. Duplicate or already-processed + `seq` values are ignored. Observers' inputs are ignored. + Every client message after the Welcome but Leave (inputs, pings, + focus, near, content, undecodable frames) is rate limited per + connection (default 120/s, burst 240): excess messages are dropped and + the server sends `Error(RATE_LIMITED)` at most once per second; more + than a burst dropped within a second gets `Kick(RATE_LIMITED)`. + `client_tick` SHOULD be the latest `server_tick` the client has applied + (the tick its interpolated view is based on). Servers that do lag + compensation evaluate shots at `time(client_tick) - interp_delay`, where + `interp_delay` is game-defined and carried **inside `payload`**; the + server clamps the rewind to its configured maximum, so the value is + advisory and never trusted beyond that bound. +- **Ping**: the server answers with Pong immediately. +- **Leave**: graceful exit; the player is removed at once (no reconnect + grace). +- **Content**: the client patched its content live (typically after a + `Resume` carrying a new version) and now runs `content_version`. The + server records it for the connection's player only when it equals the + zone's current content version (a client can catch up, never get + ahead) and ignores it otherwise; observers' are ignored. Without it a + live-patched client counts as stale until its next Hello. +- **Near** (and Hello `near`): an observer says it is near the zone (e.g. + its player is close to this room) or no longer is. On zones hosted as + celld objects a near observer whose ticket grants `wake` (§8) counts as + occupancy: its Hello wakes a sleeping zone (instead of `ASLEEP`) and the + zone keeps ticking while it stays near; `near = false` (or closing the + connection) lets the zone go dormant and hibernate as usual. Without the + grant the observer stays a passive watcher and is sent + `Error(WAKE_DENIED)` (the connection stays open). + Servers that keep observed zones running anyway (the native `net` + server) ignore it; players' are ignored. +- **Focus** (feature `FOCUS`; only to servers whose Welcome announces + it): where an observer is looking, in the zone's local coordinates + (e.g. its player next door, seen from this zone: world position minus + the zone's Welcome `origin`). The zone decides what it means; by + default the observer's view centre moves there, with the zone's player + view radius when it declares one (else the observer's radius). It only + steers what that observer is sent. Clients SHOULD throttle it (the JS + SDK: at most every 200 ms, after a move of 0.25 or more) and send it + again after each Welcome. Players' are ignored; non-finite values are + ignored. + +Worked example — Hello (`hello`: version 2, content "c1", caps 5, +ticket "t.k.n"): + +``` +01 type Hello +02 protocol_version 2 +02 63 31 content_version "c1" +05 capabilities 5 +05 74 2e 6b 2e 6e ticket "t.k.n" +00 reconnect_token "" +00 near false +``` + +Input (`seq 300, client_tick 1000, payload 01 ff`): `02 ac02 e807 02 01ff`. +Ping (`1234.5`): `03 0000000000004a9340`. Leave: `04`. + +### 6.3 Server → client + +``` +Welcome := 0x80, string session_id, string zone_id, u8 role, + varuint tick_rate, varuint patch_rate, varuint server_tick, + f64 server_time, string reconnect_token, string content_version, + schema, varuint features, bool placed, + [placed: f64 origin_x, f64 origin_y] +Delta := 0x81, see §7 +Event := 0x82, varuint type_id, bytes payload +Pong := 0x83, f64 client_time, f64 server_time +Freeze := 0x84, string reason, string version, string notes +Resume := 0x85, string reason, string version, string notes +Handoff := 0x86, string target_zone, string transfer_ticket +Kick := 0x87, varuint code, string message +Error := 0x88, varuint code, string message +Redirect := 0x89, string zone_id, string url +``` + +- **Welcome**: `role` `0` = player, `1` = observer. `session_id` is stable + across reconnects of the same player. `reconnect_token` is single-use and + rotated on every Welcome (empty for observers). A client MUST discard all + mirrored entities on Welcome; the server resends creates afterwards. + `tick_rate`/`patch_rate` are Hz. + `features` are runtime feature bits (defined by the runtime, + unlike Hello's game-defined `capabilities`): bit 0 `FOCUS` = the server + handles `Focus`; unknown bits MUST be ignored. `origin` (when `placed`) + is where the zone sits in the world: world = origin + zone-local, for + zones whose positions are local to one place in a continuous world + (`Zone::origin`). A client that knows its player's world position + focuses each placed zone it observes on `world - origin` by itself. +- **Event**: reliable, ordered, game-defined (`type_id`, `payload`). Events + are queued when emitted and may arrive before the Delta of the tick that + produced them. +- **Pong**: echoes `client_time`; `server_time` is the server clock. +- **Freeze**: the zone stops simulating; inputs are dropped (and counted) + until **Resume**. For a content rollout `reason` is `content_update` and + `version` is the **target** content version. Clients SHOULD stop + sending inputs and show `notes`. +- **Resume**: simulation continues. `version` is the content version the + zone now runs: the new one after a committed rollout + (`reason = content_update`), the old one after an aborted rollout + (`reason = content_update_aborted`). Events and facts after Resume are + produced by `version`. A client whose own content differs MAY keep + playing until told to reload (§8.2). +- **Handoff**: the player has been removed from this zone; connect to + `/zones/{target_zone}` (on the current host; follow any Redirect) and + present `transfer_ticket` as the Hello `ticket` (empty + `reconnect_token`). The server closes the socket. See §8.1. +- **Kick**: the session is over; the server closes the socket. + Codes: `1` BY_ZONE, `2` REPLACED (same principal connected again), + `3` SHUTDOWN, `4` RATE_LIMITED, `5` ZONE_DISPOSED, `6` SLOW_CONSUMER, + `7` RELOAD. **RELOAD** is the exception to "session over": the player + is kept for the reconnect grace window; the client MUST reload its + content to the zone's current version (`Resume.version` / Welcome + `content_version`) and reconnect with the token from its last Welcome + and the new `content_version` in Hello. +- **Redirect**: this host does not own `zone_id`; reconnect to `url` (a + full `ws://` / `wss://` URL including `/zones/{zone_id}`) with the same + Hello. The server closes the socket. +- **Error**: codes `1` BAD_MESSAGE, `2` UNAUTHORIZED, `3` REJECTED, + `4` ZONE_FULL, `5` VERSION_MISMATCH, `6` RATE_LIMITED, `7` NOT_FOUND, + `8` RECONNECT_FAILED, `9` ZONE_UNAVAILABLE (the zone could not be created + right now; retry later), `10` ASLEEP (an observer is not admitted to a + sleeping zone it would otherwise wake; zones hosted as celld objects treat + observers as passive watchers unless near with a `wake` grant; retry + later), `11` WAKE_DENIED (an observer said it is near but its ticket + does not grant `wake`; it stays a passive watcher — a fresh ticket may + grant it). Errors during the handshake are followed by close; + `BAD_MESSAGE`, `RATE_LIMITED` and `WAKE_DENIED` after joining are not. + +Worked example — Welcome (`welcome`: session "s1", zone "z1", player, 30 Hz ticks, +20 Hz patches, tick 42, time 1000.25 ms, token "rt", content "c1", +schema of `fixtures/messages.json`): + +``` +80 Welcome +02 73 31 session_id "s1" +02 7a 31 zone_id "z1" +00 role player +1e tick_rate 30 +14 patch_rate 20 +2a server_tick 42 +00 00 00 00 00 42 8f 40 server_time 1000.25 +02 72 74 reconnect_token "rt" +02 63 31 content_version "c1" +02 2 kinds + 01 04 68 65 72 6f 0a kind 1 "hero", 10 fields + 05 616c697665 00 "alive" bool + 05 6c6576656c 01 "level" u8 + 02 6870 02 "hp" u16 + 04 676f6c64 03 "gold" u32 + 02 647a 04 "dz" i32 + 05 7370656564 05 "speed" f32 + 01 78 06 0000c8c2 0000c842 10 "x" quant_f32 min -100 max 100 bits 16 + 03 796177 07 0a "yaw" angle bits 10 + 04 6e616d65 08 "name" short_str + 03 746167 09 "tag" bytes + 02 03 6f 72 62 01 kind 2 "orb", 1 field + 01 78 06 00000000 00008042 0c "x" quant_f32 min 0 max 64 bits 12 +``` + +ending with the tail `01 00`: features `FOCUS`, not placed. + +`welcome_origin` is the same fields with role observer and the zone +placed: + +``` +01 features FOCUS +01 placed +00 00 00 00 00 00 48 c0 origin_x -48 +00 00 00 00 81 84 2e 41 origin_y 1000000.5 +``` + +Redirect (`fixtures/messages.json` → `redirect`): +`89 0a 7265616c6d2e77657374 23 77733a2f2f31302e302e302e323a323536372f7a6f6e65732f7265616c6d2e77657374` += zone `"realm.west"`, url `"ws://10.0.0.2:2567/zones/realm.west"`. +Kick RELOAD (`kick_reload`): `87 07 13 "content c2 required"`. + +## 7. Delta + +### 7.1 Encoding + +``` +Delta := 0x81, varuint server_tick, varuint ack_seq, + varuint remove_count, varuint id * remove_count, + varuint create_count, create * create_count, + varuint update_count, update * update_count +create := varuint id, varuint kind_id, value(field_0) … value(field_{n-1}) +update := varuint id, varuint mask, value(field_i) for each set bit i, ascending +``` + +- `ack_seq` is the highest input `seq` of this connection's player that + the simulation has consumed (or discarded under a "latest" policy). + Prediction: drop pending inputs with `seq <= ack_seq`, reset to the + authoritative state, replay the rest. +- A **create** carries every field of the kind in schema order. +- An **update** carries a 32-bit field bitmask as a `varuint` (bit `i` set = + field `i` present) followed by only those fields in ascending `i`. A + mask bit `>= field_count` is a decode error. An update's kind is the + kind of the entity as known by the client (from its create, possibly + earlier in the same Delta). +- The server always sends a Delta every patch to every connection, even + when empty (it carries `server_tick` and `ack_seq`). + +### 7.2 Applying (normative, see `ClientMirror::apply`) + +1. Remove every id in `removes`. +2. Insert every create (replacing any existing entry with the same id). +3. For each update, overwrite the present fields of the known entity. An + update for an unknown id is a protocol error. +4. Set `server_tick` and `ack_seq`. + +### 7.3 Server semantics (informative) + +- Deltas are computed per connection against what was last **sent** to it. +- Interest: each connection has a view (center, radius) on the zone's 2D + interest plane. An entity is created when within `radius` and removed + when beyond `radius × (1 + leave_margin)` (default margin 0.1) or gone. + Global entities are visible everywhere. +- Change detection compares encoded field bytes, so changes smaller than + the quantization step are never sent. +- Per-connection byte budget (default 4096 B of create+update data per + Delta): candidates gain `kind priority × entity priority × max(changed + field priority) × 1/(1 + distance/radius)` per patch into an + accumulator; the highest accumulators are sent first and reset; + deferred entities keep accumulating, so none starve. At least one + candidate is sent per Delta. Removes are never budgeted. +- Update rates (default): a changed, already-known, non-global entity + beyond half the radius is a candidate only every 2nd patch, beyond 0.8 + of it every 4th. Clients see this only as less frequent updates. + +### 7.4 Worked example + +`fixtures/messages.json` → `delta`, with the client already knowing +entity 5 (kind 1 "hero") and 6 (kind 2 "orb"): + +``` +81 Delta +c8 01 server_tick 200 +11 ack_seq 17 +02 09 82 01 removes [9, 130] +02 2 creates + ac 02 01 id 300, kind 1 + 01 alive true + 07 level 7 + ac 02 hp 300 + f0 a2 04 gold 70000 + 03 dz -2 (zigzag 3) + 00 00 c0 3f speed 1.5 + 00 x -100.0 (q 0) + 00 yaw 0 (q 0) + 03 41 6e 61 name "Ana" + 02 de ad tag de ad + ad 02 02 id 301, kind 2 + 80 10 x 32.0 → q 2048 (12 bits over 0..64) +03 3 updates + 05 44 id 5, mask 0b0100_0100 (fields 2 and 6) + ab 02 hp 299 + 80 80 02 x q 32768 → 0.0015259022 + 06 01 id 6, mask 0b1 + ff 1f x q 4095 → 64.0 + ad 02 01 id 301 (created above), mask 0b1 + 00 x q 0 → 0.0 +``` + +Full hex: `81c801110209820102ac02010107ac02f0a204030000c03f000003416e6102deadad02028010030544ab028080020601ff1fad020100`. + +An empty Delta at tick 43: `81 2b 00 00 00 00`. + +## 8. Admission tickets + +A ticket is a compact JWT signed with **HS256** (HMAC-SHA256 over the +ASCII `base64url(header) "." base64url(claims)` with a shared secret; +unpadded base64url). Any HS256 JWT library can mint one. + +- Header: `{"alg":"HS256","typ":"JWT"}`; any other `alg` is rejected. +- Claims: + - `sub` (string, required) — the **principal**. The server takes + identity only from this verified claim; nothing in Hello, Input or any + payload can set or change it. + - `zone` (string, required) — MUST equal the route's zone id. + - `exp` (integer Unix seconds, required) — rejected when `exp <= now`. + - `nonce` (string, required) — single use; reuse before `exp` is + rejected. + - `role` (string, optional) — `"player"` (default) or `"observer"`. + Observers receive Deltas and Events but own no player and cannot send + inputs. + - `name` (string, optional) — display name vouched for by the issuer + (never identity). Carried into transfer tickets. + - `wake` (bool, optional, default false) — observers only: the issuer + lets this watcher wake the zone and keep it awake while it is near + (Hello `near` / `Near`, celld zones). The issuer decides who may (for + example only rooms next to the principal's own); the zone never + trusts the client for it. +- Failures produce `Error(UNAUTHORIZED)` and close. + +**Custom ticket formats.** A server MAY admit join tickets in another +format through a pluggable verifier (`AdmissionConfig::verifier`, e.g. +a web backend's own JWTs with `iss`/`aud`/`jti` and no `zone`/`nonce`). +The verifier maps the token to the same claims (principal, zone = route +zone, expiry, replay key, role, name); the server still rejects a zone +other than the route's, `exp <= now` and a reused replay key. Transfer +tickets (§8.1) always use the format above. + +### 8.1 Transfer tickets and handoff + +A zone hands a player to another zone (possibly on another host) with a +**transfer ticket**: the same HS256 JWT format, minted by the source host, +with extra claims — `kind: "transfer"`, `src` (source zone), `iss` +(issuing host id), `gen` (source zone ownership token), `carry` +(base64url carried game state, <= 16 KiB). Clients treat it as opaque. + +Procedure (client side): + +1. Receive `Handoff(target_zone, transfer_ticket)`; the socket closes. + The player is already removed from the source zone. +2. Connect to `/zones/{target_zone}`; follow `Redirect` if any; send + Hello with `ticket = transfer_ticket`. +3. Welcome → in the target zone (the zone received the carried state). +4. If the target refuses (any `Error` before Welcome, or no Welcome + within ~10 s): connect to `/zones/{source_zone}` (the zone the client + just left) and send the **same** Hello; the source re-admits the player + with its carried state. If that also fails, fall back to the lobby for + a fresh admission ticket. + +Server guarantees: a transfer ticket is single use across hosts — the +target reserves it with the issuing host before admitting, confirms on +success and releases on refusal; the source accepts it back only while it +is neither reserved nor used. In doubt (an unconfirmed reservation that +lapsed) the ticket counts as used: a player is never in two zones. +Tickets expire after 30 s by default. + +### 8.2 Content versions (barrier and safe rooms) + +A world runs one content version. A rollout freezes every zone +(`Freeze{version: target}`), applies the new content, then resumes every +zone (`Resume{version: target}`); if any zone fails to freeze in time +all zones resume on the old version (`Resume{reason: +content_update_aborted}`). Servers pin a version per policy: + +- **Strict** (default): Hello `content_version` MUST equal the server's + for joins and reconnects; otherwise `Error(VERSION_MISMATCH)`. +- **SafeRoom** ("keep playing until a safe room"): after a *rolling* + rollout, clients on the old version keep playing in the zone they are + in (reconnects allowed). They may only be handed off into *gate* zones + (safe rooms) unless the server allows roaming; on entering a gate they + get Welcome and then `Kick(RELOAD)`. A fresh join with an old version + gets `Error(VERSION_MISMATCH)` (message ends with `reload`). +- A *hard* rollout sends `Kick(RELOAD)` to every stale client right after + Resume. + +### 8.3 Reconnect + +Reconnect: after an abrupt disconnect the player stays in the zone for +the reconnect grace window (default 15 s). A Hello with the last Welcome's +`reconnect_token` rebinds the same player (same `session_id`, new token, +fresh creates). After the window the player is removed and the token +fails with `Error(RECONNECT_FAILED)`. A fresh join of the same principal +replaces any existing connection (`Kick(REPLACED)` to the old one). + +## 9. Golden fixtures + +`tests/fixtures/` (regenerate with `UPDATE_GOLDEN=1 cargo test -p +distributed_game --test golden`; a drift fails the test): + +- `primitives.json` — `{cases: [{kind, value, hex}]}` for varuint, varint, + f32, f64, string, short_string. +- `quantization.json` — `{cases: [{field, input_bits, q, hex, decoded}]}`; + `input_bits` is the input f32 bit pattern (hex, big-endian digits), + `q` the quantized integer, `hex` its varuint bytes. +- `messages.json` — `{messages: [{name, direction, hex, decoded, + known_entities?, schema?}]}`. Delta entries include the schema and the + `known_entities` (`[{id, kind}]`) needed to decode updates. Welcome + entries carry `features` and `origin` (`{x, y}` or `null`). +- `authoring.json` (`--test authoring`) — a sample game surface and + input / event payloads encoded with the typed payload codec (§11), with + their expected TypeScript values; generated clients are round-tripped + against it (`js/tests/game-generated.test.mjs`). + +JSON conventions in `decoded`: + +- byte arrays are lowercase hex strings; +- floats are `{"f32": number, "bits": "xxxxxxxx"}` (`bits` is the exact + binary32 pattern; compare bits, not decimal text); +- field values are tagged: `{"bool"}`, `{"u"}`, `{"i"}`, `{"f32","bits"}`, + `{"str"}`, `{"bytes"}`; +- schema fields are `{"name", "type", ...params}` with `type` one of + `bool u8 u16 u32 i32 f32 quant_f32 angle short_str bytes`. + +## 10. Versioning + +`protocol_version` changes on any incompatible wire change; a server +speaks one version (§6.0), so clients and servers of different versions +do not interoperate and are deployed together. Message +type bytes `0x08..0x7f` and `0x8a..0xff`, and field type tags `10..255`, +are reserved for future versions. + +Version 2 (version 1 is no longer spoken): + +- Welcome carries `features` and the optional `origin` (§6.3). +- `0x07 Focus` is gated on the `FOCUS` feature. +- Payload encodings (fields, inputs, events, §11) are unchanged, so a + game surface keeps `protocolVersion: 1`. + +Additive changes made within version 1 (kept in 2; clients SHOULD ignore unknown kick and +error codes and treat them as "session over" / "request failed"): + +- `0x89 Redirect` (server → client). +- Kick code `7` RELOAD. +- Error code `9` ZONE_UNAVAILABLE. +- Error code `10` ASLEEP. +- Error code `11` WAKE_DENIED. +- `0x06 Near` (client → server) and the ticket claim `wake`. +- `0x07 Focus` (client → server), gated since version 2 (above). + +Not additive (made before the first release, so the version stays 1): +Hello's trailing `bool near` — clients built before it send one byte +less and are refused with `BAD_MESSAGE`; rebuild them. +- Transfer tickets (§8.1) and content-version policies (§8.2); `Handoff` + and `Freeze`/`Resume` encodings are unchanged. + +## 11. Typed payload codec (informative) + +`Input.payload` and `Event.payload` stay game-defined; this section is not +part of the frame format and changes nothing above. It specifies the +encoding the authoring derives (`#[derive(GameInput)]`, +`#[derive(GameEvent)]`, `#[derive(GameRecord)]`, `distributed_game::codec`) +and generated clients use, so both sides of a game can agree on it from a +game surface (`GameSurface` JSON, schema v1). + +A payload is its fields concatenated in declaration order, no tags or +lengths between fields. A whole payload must be consumed (trailing bytes +are an error). Field encodings: + +| Wire type | Encoding | +|---|---| +| `bool`, `u8`, `u16`, `u32`, `i32`, `f32`, `quant`, `angle`, `short_str`, `bytes` | exactly as the §4 field type of the same name (`quant` = `quant_f32`) | +| `i8` | one byte, two's complement | +| `i16` | zigzag `varint`, rejected outside `-32768..=32767` | +| `u64` | unsigned LEB128 like `varuint`, up to 8 bytes, value ≤ `2^53 − 1` (encoders saturate; JavaScript decodes it exactly) | +| `f64` | binary64 LE | +| `str` | `string` (§2: `varuint` length + UTF-8) | +| `list` | `varuint` count, then the items | +| `optional` | `u8` 0 (absent) or 1 followed by the value; other tags are invalid | +| `record` | the record's fields in order | + +An input decoded by `GameInput::from_payload` is then sanitized: fields +with a `range [min, max]` are clamped (integers truncated after the +clamp), bit-flag fields keep only their named bits, and a non-finite +`f32` rejects the whole input. + diff --git a/distributed_game/README.md b/distributed_game/README.md new file mode 100644 index 000000000..88f56c9d4 --- /dev/null +++ b/distributed_game/README.md @@ -0,0 +1,1596 @@ +# distributed_game + +A server-authoritative multiplayer game engine for the `distributed` +framework. You write the rules of a piece of your world (a **zone**) as a +plain Rust struct. The engine runs it at a fixed tick rate, takes player +input, sends each player only the changes they can see, saves important +outcomes without ever pausing the game, and spreads zones across as many +server processes as you need. A TypeScript client SDK +(`@hops-ops/distributed/game`) connects browsers to it, with prediction and +smoothing built in. + +It replaces the role a room server like Colyseus plays, but in Rust and on +the same event-sourced storage the rest of `distributed` uses. + +**It is:** the authoritative simulation loop, networking, replication, +persistence of outcomes, and world layout across servers. + +**It is not:** a renderer, a physics engine or a content pipeline. Bring +your own physics and step it inside `on_tick`. The demos use Babylon.js in +the browser, but the client SDK has no rendering dependency. + +## Contents + +- [The big picture](#the-big-picture) +- [Try it](#try-it) +- [Build a zone](#build-a-zone) +- [Guides](#guides): game loop · input · what clients see · the client SDK · + generated clients · SvelteKit apps · client prediction (Rust → WebAssembly) · shared + logic and data (no TypeScript twins) · saving progress · scaling out + (zones as celld objects, the native multi-host server) · + live updates · lag compensation · testing and operations · security +- [Design decisions](#design-decisions) +- [Status and limits](#status-and-limits) +- [Reference](#reference) + +## The big picture + +```mermaid +flowchart LR + subgraph Browser + C[GameClient
prediction + interpolation] + end + subgraph "Game server process (GameServer)" + H1[ZoneHost: town] --- Z1[your Zone code] + H2[ZoneHost: dungeon-1] --- Z2[your Zone code] + W[fact worker] + end + subgraph Storage + CELL[(player cells
SQLite / Workers)] + SNAP[(hibernation
snapshots)] + end + C -- "binary WebSocket: inputs" --> H1 + H1 -- "deltas, events" --> C + Z1 -- "facts (never awaited)" --> W + W -- "idempotent commands" --> CELL + H2 -. "sleep when empty" .-> SNAP +``` + +The words used throughout: + +| Term | Meaning | +|---|---| +| **Zone** | One piece of the world with its own rules and state: a room, an arena, a dungeon floor, a 32 m map cell. Your code implements the `Zone` trait. Zones are the unit of simulation, ownership and scaling. | +| **ZoneHost** | Runs one zone: the fixed-timestep loop, connected clients, input queues, timers, replication. Has no networking of its own, so it is easy to test with a `ManualClock`. | +| **GameServer** | (`net` feature) A WebSocket server hosting many zones, creating them on demand, routing players, and serving `/metrics` and admin routes. | +| **Tick** | One fixed simulation step (30 Hz by default). Separate from the **patch** rate (20 Hz by default), how often clients get updates. | +| **Player / Observer** | A *player* controls something and sends inputs. An *observer* only watches: a spectator, a leaderboard page, or a client looking into the zone next door. | +| **Entity** | A thing inside a zone with its own `EntityId`: a player, a mob, a pillar. It holds server state, some of which no client may see. | +| **View** | What clients see of an entity: a `#[derive(Replicated)]` struct *projected* from it each patch (converted, derived, or left out). The engine works out what changed for each client. | +| **Schema** | The kinds of entity and their fields (with quantization), usually from `#[derive(Replicated)]` views. Sent to clients on connect, so a generic client needs no generated code; a generated one adds types. | +| **Fact** | An outcome worth keeping ("Alice killed the elite"). The zone emits it (typically the cell command's own input) and moves on; a background worker commits it to storage, where the command decides the reward, and reports back later. | +| **Cell** | Durable, event-sourced state in `distributed`, for example one player's profile. Facts usually end up as commands on a cell. | +| **Ticket** | A signed, single-use admission token naming the player (principal), the zone and a role. Identity always comes from the ticket, never from game input. | + +### The life of a tick + +1. Inputs arrive over the socket. Each is numbered; the host drops + duplicates and stale ones, decodes them with `Zone::decode_input`, and + checks them with `Zone::sanitize_input`. +2. The host calls `Zone::on_tick`. Your code reads inputs with + `ctx.take_inputs`, moves things, resolves combat, and may emit facts, + events, timers or a handoff. +3. On patch ticks the host calls `Zone::replicate`. For each client it + compares what you described with what that client last received, keeps + only what the client can see (interest), fits it into the client's byte + budget (most important first), and sends one binary **Delta** with the + number of the last input it processed. +4. The browser applies the Delta. Other entities are drawn slightly in the + past (interpolated) so they move smoothly. The player's own character is + predicted from their inputs and quietly corrected when the server + disagrees. +5. Meanwhile, emitted facts are committed by the fact worker. When one + settles, `Zone::on_fact_settled` runs on a later tick (to show + "saved ✓", for example). The tick never waits for storage. + +## Try it + +The runnable demos live in [`examples/game`](../examples/game/README.md). +They are being folded into one game, Mob Pit (the others are deleted as +their mechanic moves in): + +| Demo | Run | Shows | +|---|---|---| +| Mob Pit | `examples/game/run.sh mobpit` (`--fleet` for several celld nodes) | rooms as celld objects joined by doorways, sleeping when empty and restored on return; combat whose rewards are saved exactly once without stalling; a network panel (simulated latency / jitter / loss on every room, prediction on/off with a server ghost, the interest ring); the rooms next door seen through passive watchers (the doorway rooms in reach woken by near watchers); hoods › boroughs › city as tier cells (boss kills ripple up through a saga, weather lifts as bosses fall); world events scheduled by boroughs; jumping; a bow with lag-compensated hits and first person | +| Leaderboard | `run.sh leaderboard` | a live ranking fed from saved kills, rebuilt from history | +| The Freeze | `run.sh freeze` | pausing every zone on two servers, updating content, resuming; safe-room reloads | + +Then open `http://localhost:5173//`. Each page explains what to try. + +## Build a zone + +A zone is a struct plus a few trait methods. You describe **what clients +see**, **what they send** and **what you tell them** as plain Rust structs +with derives, and the rule clients **predict** as a plain Rust function; +the engine encodes them, `distributed game-client` generates the matching +TypeScript and `distributed game-wasm` compiles the predicted step to +WebAssembly, so field order, ids, quantization and movement rules are +written down exactly once. This zone is a dot that players push left and +right: + +```rust +use std::sync::Arc; +use std::time::Duration; +use distributed_game::*; + +/// What clients see: one replicated kind. Field order is the wire order; +/// the KindDef and the encoding both come from this struct. +#[derive(Replicated)] +#[replicated(kind = "dot", id = 1, global)] +struct DotView { + #[quant(min = -50.0, max = 50.0, bits = 12)] // 12-bit wire precision + #[correct(ease = 100)] // client correction default + x: f32, +} + +/// What a player sends, once per tick. `from_payload` decodes it and +/// clamps `#[range]` fields, so cheating inputs never reach `on_tick`. +#[derive(Clone, Copy, GameInput)] +struct Push { + #[range(min = -1, max = 1)] + dx: i8, +} + +/// One-off messages, with stable ids and typed payloads. +#[derive(GameEvent)] +enum RoomEvent { + #[game_event(id = 1)] + Hello { entity: u32 }, +} + +/// The predicted fields of a `dot` (named after the kind's fields). +#[derive(Clone, Copy, GameRecord)] +struct DotState { + x: f32, +} + +/// The movement rule: run by `on_tick` on the server and, compiled to +/// WebAssembly, by the browser to predict its own dot. One input is one +/// fixed 30 Hz frame. +#[predict(PushStep, kind = "dot")] +fn push_step(state: &DotState, input: &Push, _context: &(), _dt: f32) -> DotState { + DotState { x: state.x + f32::from(input.dx) * 5.0 / 30.0 } +} + +struct Room { x: f32 } + +impl Zone for Room { + type Config = (); + type Input = Push; + type Timer = (); + type Message = NoMessages; // or a #[derive(GameEvent)] type (zone inbox) + + fn schema() -> EntitySchema { schema![DotView] } + + fn on_create(_ctx: &mut Ctx<'_, Self>, _: ()) -> Self { Room { x: 0.0 } } + + fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + ctx.send(player, &RoomEvent::Hello { entity: 1 }); + } + + // Bytes from the client → your input type (decoded and sanitized). + fn decode_input(&self, _p: PlayerId, bytes: &[u8]) -> Option { + Push::from_payload(bytes) + } + + // The game rules, once per tick. + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + let players: Vec<_> = ctx.players().map(|p| p.id).collect(); + for p in players { + for input in ctx.take_inputs(p, ConsumePolicy::Drain) { + self.x = push_step(&DotState { x: self.x }, &input.input, &(), ctx.dt_secs()).x; + } + } + } + + // Describe the world; the engine diffs it per client. (Zones with + // entity collections register them in `entities()` instead and + // project views from them: see "What each client sees".) + fn replicate(&self, out: &mut WorldView) { + out.add(1, &DotView { x: self.x }); + } +} + +/// Everything a browser needs to know about this zone, for the generator. +pub fn game_surface() -> GameSurface { + GameSurface::for_zone::("room") + .events::() + .predict::() +} + +// Drive it directly (tests, tools) with a manual clock: +let clock = ManualClock::new(); +let mut host = ZoneHost::::new("room-1", HostConfig::default(), Arc::new(clock.clone()), ()); +let claims = TicketClaims::new("alice", "room-1", u64::MAX, "n", Role::Player); +let joined = host.join(&claims, 0, "").unwrap(); +host.push_input(joined.client, 1, 0, &Push { dx: 1 }.to_payload()); +clock.advance(Duration::from_millis(100)); +host.advance(); +for out in host.drain_outbound() { /* Outbound::Frame bytes go to the client */ } +assert_eq!(game_surface().kinds[0].name, "dot"); +``` + +Serve it over WebSockets (`net` feature). The zone factory decides which +zone ids this server hosts and with what config: + +```rust,ignore +let server = GameServer::::new( + ServerConfig::new(TicketKey::new(secret)), + ZoneFactory::sync(|activation| activation.zone_id.starts_with("room-").then_some(())), +); +server.serve(tokio::net::TcpListener::bind("0.0.0.0:2567").await?, shutdown_signal).await?; +``` + +Generate the browser client from `game_surface` (see +[Generated clients](#generated-clients)): + +```sh +distributed game-manifest --entrypoint my_game::game_surface --out room.surface.json +distributed game-client --manifest room.surface.json --out web/src/generated/room +distributed game-wasm --manifest room.surface.json --out web/src/generated/room # push_step → wasm/room.wasm +``` + +Connect a browser with it. The input encoder, the correction defaults, the +event decoders and prediction (`push_step`, compiled) are generated; you +write only drawing: + +```ts +import { InputPacer } from '@hops-ops/distributed/game'; +import { createRoomClient, dotFields, isDot } from './generated/room/index.ts'; + +const room = createRoomClient({ + url: (zone) => `wss://game.example/zones/${zone}`, + ticket: ({ zoneId, role }) => api.mintZoneTicket(zoneId, role) // your backend signs these +}); // predicts with wasm/room.wasm; `room.prediction.ready` once loaded +room.on('hello', (hello) => room.client.setControlledEntity(hello.entity)); // typed payload +await room.client.connect('room-1'); +const pacer = new InputPacer({ tickRate: () => room.client.authority?.connection.welcome?.tickRate }); +requestAnimationFrame(function frame(now) { + pacer.update(now, (dtMs) => room.client.sendInput({ dx: readKeys() }, dtMs)); // one input per tick + for (const e of room.client.render()) if (isDot(e)) draw(dotFields(e).x); // typed fields + requestAnimationFrame(frame); +}); +``` + +The rest of `Zone` is optional hooks: `on_auth`, `on_join`, `on_leave`, +`on_rejoin`, `on_connection_lost` (grace started), `on_reconnected`, +`on_observe`, `on_timer`, `on_fact_settled`, +`on_tier_changed`, `on_dispose`, `hibernate` / `on_restore`, +`on_handoff_join`, `on_child_event`, `is_gate`, `freeze_ready`, +`on_content_version_changed`, `record_rewind`, `state_hash`. Each is +explained in the guide that uses it. Hand-written schemas +(`EntitySchema::new().kind(KindDef::new(..).field(..))`), `EntityState`s, +byte inputs and `ctx.send_event(viewer, type_id, bytes)` still work; the +derives are a layer over them. + +## Guides + +### The game loop + +`ZoneHost::advance()` runs as many fixed steps as real time requires, +capped at `HostConfig::max_catch_up` (5) so a stalled process skips ahead +instead of fast-forwarding. `ctx.dt_secs()` is always the fixed step. + +A zone is in one of three **tiers**: + +- **Hot**: someone is connected; full `tick_rate` (30 Hz). +- **Idle**: empty; ticks at `idle_tick_rate` (1 Hz) so timers and + respawns keep going. Return `true` from `Zone::wants_background` to stay + Idle forever (a city clock, say) or from `has_pending_work` to stay Hot. +- **Dormant**: idle for `dormant_after` (30 s); no ticks. With + hibernation on, a Dormant zone is saved and unloaded (see + [Scaling out](#scaling-out-zones-as-celld-objects)). + +`on_tier_changed` tells you about transitions. Timers +(`ctx.set_timeout(after, value)`, `ctx.set_interval(every, value)`, +`ctx.cancel_timer(id)`) fire `on_timer` on the tick they are due; +`ctx.rng()` is a seeded RNG derived from the world seed and zone id, so a +recorded session replays identically. + +### Input + +Clients number every input. The host keeps a bounded queue per player, +rejects duplicates and inputs older than the last processed one, and +reports the last processed number back in every Delta. The client uses +that to drop inputs the server has already applied when it reconciles. + +- `#[derive(GameInput)]` generates a compact codec for an input struct + (`i8`/`u8`/`i16`/`u16`/`i32`/`u32`/`bool`/`f32`, `#[quant]` / `#[angle]` + floats) and its sanitize: `#[range(min, max)]` **clamps**, a + `#[buttons(dash, attack)]` bit field clears unknown bits (and gets + `Input::DASH`, `Input::ATTACK` constants), any non-finite `f32` rejects + the input, and a frame of the wrong length is dropped. `decode_input` + is then one line: `MyInput::from_payload(bytes)`. Hand-written + `decode_input` / `sanitize_input` (rejecting or clamping anything a + cheater could send) keep working. +- `ctx.take_inputs(player, ConsumePolicy::…)` reads them in `on_tick`. + `InputCredits` allows one input per tick per player (with a small bank + for network jitter), so flooding inputs cannot make anyone move faster. +- Every new connection (a fresh ticket, a reconnect token, or a reconnect + after a content reload) starts its numbering again from 1, and so does + the host. +- A player who reconnects with a fresh ticket while still in the zone + gets `on_rejoin`, by default `on_leave(Rejoined)` then `on_join`, so the + zone re-sends whatever a new client needs. +- While the world is frozen for an update, inputs are dropped and counted. + +### What each client sees + +**Zones, entities, views and facts.** The same split as on the business +side of `distributed`: + +| game runtime | business side | here | +|---|---|---| +| zone | aggregate root | one consistency boundary, changed only on its own tick | +| zone entity (`Entity`, `EntityId`) | entity inside the aggregate | `Mob { id, home, target, hp, .. }`, server-only state included | +| view (`Replicated` + `Project`) | read model / projection | `MobView { x, y, hp% , tele }`, recomputed each patch | +| fact | domain event | `crawler.record_kill`, committed by a cell | + +Views are projections, not copies: a view converts (`hp` as a percent), +derives (a telegraph ring from a windup timer), flattens (a nested move +state), clamps, or returns `None` to leave the entity out (a dead mob), +and server-only fields (`target`, `home`, `principal`) simply have no +view field. Declare the entity type with `of` and mark straight copies +`#[from]` (same name) or `#[from(path.to.field)]`; the derive generates +`MobView::project(&mob, MobViewRest { .. })` with only the hand-filled +fields left in `MobViewRest` (a missing or mistyped `#[from]` field is a +compile error at the attribute), and when every field is `#[from]` it +also implements `Project` for you: + +```rust,ignore +#[derive(Replicated)] +#[replicated(kind = "mob", id = 2, of = Mob)] +pub struct MobView { + #[quant(min = -40.0, max = 40.0, bits = 14)] #[from(body.x)] pub x: f32, + #[quant(min = -40.0, max = 40.0, bits = 14)] #[from(body.y)] pub y: f32, + pub hp: u8, // percent: filled by hand +} + +impl Entity for Mob { + fn entity_id(&self) -> EntityId { self.id } +} + +impl Project for Mob { + fn view(&self) -> Option { + (self.hp > 0).then(|| MobView::project(self, MobViewRest { + hp: (self.hp * 100 / self.max_hp) as u8, + })) + } +} +``` + +The zone registers its collections once (`Zone::entities`, like +`schema()`); each patch the host projects every entity in registration +order (`Vec`, slices, `VecDeque`, `BTreeMap` values, `Option`, or one +entity such as the zone itself for a HUD view) and then calls +`Zone::replicate` for anything else: + +```rust,ignore +fn entities() -> Entities { + Entities::new() + .each(|z: &Self| &z.players) + .each(|z: &Self| &z.mobs) + .one(|z: &Self| z) // impl Project for the zone +} +``` + +`replicate` now defaults to nothing and stays for unusual zones: there, +`out.project::(&mob)` pushes one entity's view, and +`out.add(id, &view)` any `#[derive(Replicated)]` view (with or without +`of`; or push a hand-built `EntityState`). `ZoneHost::world_view()` +returns the patch's projected world (tests, tooling). Mob Pit +(`examples/game/server/src/mobpit/zone.rs`) has no `replicate` at all, +and a golden test there checks the projected world and the Delta bytes +against its former hand-written loop. + +**Kinds.** The view's struct is the kind: `#[replicated(kind = "mob", id = 2, priority = +2.0, global)]`, one field per replicated field in wire order (`bool`, `u8`, +`u16`, `u32`, `i32`, `f32`, `String` as a short string, `Vec` as +bytes), `#[quant(min, max, bits)]` / `#[quant(centered = R, bits)]` (zero +exact) / `#[angle(bits)]` / `#[field_type(EXPR)]` for floats, +`#[priority(p)]`, and `#[correct(ease = ms | snap | replace)]` client +defaults (`ease = ms, snap_above = m`: an error larger than `m` cuts the whole +entity — a respawn or another server-side teleport is a cut, not a slide). The interest position is the `x` / `y` fields (or +`#[replicated(x = .., y = ..)]`); a kind without one must be `global`. +`out.add(..)` returns a handle for `.global()`, `.local()`, `.priority(p)`. +For each client the engine then sends only the difference from what that +client already has: + +- **Schema and quantization.** Fields are typed (`QuantF32`, integers, + booleans, strings, …). Floats are quantized to the precision you choose, + and a change too small to show up after quantization costs nothing. +- **Interest.** Each viewer has a `View` (centre and radius, set with + `ctx.set_view`). Entities outside it are not sent and are removed from + the client when they leave it. A spatial grid makes this cheap. Mark + entities that everyone must always see (players in a small room, a boss, + pillars) with `.global()`. +- **Across borders.** A zone says where it sits in the world once + (`fn origin(&self) -> Option`, e.g. from the room in its zone + id) and how far its players see (`fn view_radius(&self) -> Option`). + The origin travels in Welcome; the game tells the JS client where the + player is with one call (`client.setPosition(x, y, zoneId)`, local to + the player's zone, or world coordinates without `zoneId`), and the SDK + focuses every zone it watches next door on the player in that zone's + coordinates (`Focus`, throttled). The default + `Zone::on_observer_focus` gives that observer the zone's player view + radius around the player, so interest and update rates carry on past + the wall instead of the neighbour sending all it has. Zones without an + origin are focused by hand (`watchZones(...).setFocus(at)`). +- **Bandwidth budget.** Each client has `byte_budget` bytes per Delta + (4 KiB). Creates and updates compete by priority (kind × entity × + field × nearness). Anything deferred builds up priority, so it is always + sent eventually. +- **Update rates.** Far entities are updated less often: within half the + view radius every patch, up to 0.8 of it every 2nd patch, beyond that + every 4th (`HostConfig::interest.update_rates`, staggered by entity id, + so a far entity's latest state is at most 3 patches late). Creates, + removes and global entities are never held, nor are kinds marked + `#[replicated(.., every_patch)]`; keep your own entity near the view + centre (it is when the view follows the player) or mark its kind. + `UpdateRates::every_patch()` turns the rates off. +- **Encoded once.** Each changed entity's update is encoded once per patch + and copied into every Delta of a client that was current; clients + further behind (budget or update rates) share one encoding per + baseline. The bytes are exactly those of a per-client encoding (a + randomized test checks it), so a dense room's cost per client is + selection and copying: 128 mutually visible players build a patch + about 5× faster than encoding per client. +- **Events** carry one-off messages such as "kill", "saved" or "weather + changed" next to the Deltas. Declare them as a `#[derive(GameEvent)]` + enum (each variant `#[game_event(id = N)]`: unit, named fields, or one + value such as a `#[derive(GameRecord)]` struct) or struct, and send them + with `ctx.send(viewer, &event)` / `ctx.broadcast(&event)`. Payloads use + the same value codec as entity fields plus `i8`/`i16`/`u64`/`f64`, + `#[long]` strings, `Vec`, `Option` and nested records. + `E::decode_event(type_id, bytes)` decodes them (bots, tests). The raw + `ctx.send_event(viewer, type_id, bytes)` remains for custom payloads. + +Wire details are in [`PROTOCOL.md`](PROTOCOL.md). + +### The client SDK + +`GameClient` (`@hops-ops/distributed/game`) handles the connection, +reconnection and clock sync, and gives you `render()`: a list of entities +ready to draw. A [generated client](#generated-clients) wraps it with your +zone's typed fields, input encoder, events and correction defaults. + +- **Interpolation.** Other entities are drawn a little in the past, + between two received states, so movement is smooth whatever the network + does. The delay adapts to measured latency and jitter (`AdaptiveDelay`). +- **Prediction.** The player's own entity moves the moment they press a + key, using a `predict` function — with a generated client, the zone's + `#[predict]` step compiled to WebAssembly (see + [Client prediction](#client-prediction-rust--webassembly)). Each + Delta, the client replays not-yet-acknowledged inputs on top of the + server's state; any difference is resolved per field (`ease`, `snap` or + `replace`). `setPredictionEnabled(false)` turns it off, to feel the raw + latency. +- **Neighbouring zones.** `observe(zone)` opens a watch-only connection, + so a player sees across a border before crossing it. +- **Crossing zones.** When the server hands the player to another zone + (possibly on another server), the client follows automatically. The + predicted character is held in place until the new zone takes over, and + if the new zone refuses, the client goes back. +- **Content reloads.** `reloadContent` is called when the server requires + a newer content version, and the client rejoins afterwards with the same + player. + +### Generated clients + +The derives also describe the zone for the browser. A **game surface** +(`GameSurface`, versioned JSON, schema v3) lists the zone's kinds with +their fields, wire types, priorities and correction defaults, its input +layout and sanitize rules, its events and the records they mention, its +predicted step, and what else the client shares with Rust: pure functions +compiled to WebAssembly, constants and standalone record codecs. Export +one function per zone type, conventionally `game_surface`: + +```rust,ignore +pub fn game_surface() -> GameSurface { + GameSurface::for_zone::("arena") + .events::() + .predict::() + .constant("arena_floor", &arena_floor()) +} +``` + +`distributed game-manifest` builds and runs it (through the same harness +as `distributed describe`), and `distributed game-client --manifest + --out

[--check]` writes framework-neutral TypeScript that +imports only `@hops-ops/distributed/game`: + +| File | Contents | +|---|---| +| `schema.ts` | `KIND` ids, `PlayerFields` interfaces with `isPlayer(e)` / `playerFields(e)` over rendered or replica entities (camelCase properties), `FIELD_TYPES`, `CORRECTIONS` | +| `input.ts` | the input interface, `BITS` / `BUTTON`, `encodeInput`, `decodeInput`, `sanitizeInput` (what the server will simulate) | +| `events.ts` | record and event interfaces, `EVENT` ids, `EVENTS` codecs, `decodeEvent`, `onEvent` | +| `client.ts` | `createClient(options)`: a `GameClient` with the encoder and correction defaults wired in (and, with a predicted step, prediction by the compiled step), a typed `on(name, handler)` and `send(input)` | +| `predict.ts` | with a `#[predict]` step: `PREDICT`, the state/context layouts, `PREDICT_WASM_URL` (`./wasm/.wasm`) and `createPrediction` | +| `pures.ts` | with `#[game_pure]` functions: `PURES`, `PURES_WASM_URL` (the same module) and `createPures()`, one typed wrapper per function | +| `constants.ts` | with `.constant(..)`s: each value as a typed literal (`ARENA_FLOOR: ArenaFloor`) | +| `index.ts`, `surface.json` | re-exports; the surface it came from | + +`events.ts` also gets `encode` / `decode` for every +`.record::()` (see [Shared logic and data](#shared-logic-and-data-no-typescript-twins)). + +The output is deterministic, so check it in and run `--check` in CI: a +changed Rust definition then fails the build until the client is +regenerated. The binary protocol is unchanged; the generated code only +removes the hand-written glue around it. The compiled module +(`distributed game-wasm`, `wasm/.wasm`: the predicted step and the +pure functions) is a build output: ignore `wasm/` in version control and +build it before bundling. + +### SvelteKit apps + +`@hops-ops/distributed` integrates zones with SvelteKit where it removes +boilerplate — admission, code generation and the HUD around the game — and +leaves the canvas and render loop to you (game state is never +server-rendered). Full API: [js README](../js/README.md#game-zones-in-sveltekit); +runnable: [`examples/game/sveltekit`](../examples/game/sveltekit) +(`examples/game/run.sh sveltekit`). + +1. **Tickets from the session.** `createGameTicketHandler` (server-only, + `@hops-ops/distributed/sveltekit/game/server`) is a `POST` route that + signs this crate's ticket format (§8, HS256 with the zone servers' + `TicketKey` secret) for the app's **verified session** principal and the + zone **your server code** chooses. The browser may only hint `{ zone, + role }`; any other body field is refused, so identity, ownership and + rewards never come from the request. Same-origin, a per-principal rate + limit and `cache-control: no-store` are built in; the zone server still + enforces signature, zone, expiry and single use. Extension claims (match + id, team…) come only from the server-side `claims(context)` callback and + are signed under `ext`. `js/tests` reproduce + `tests/fixtures/sveltekit_tickets.json` byte for byte and `net_e2e` + admits those tickets on a real `GameServer` (and refuses tampered, + expired, wrong-zone and replayed ones). +2. **Clients generated by Vite.** `distributedSvelteKit({ games: [...] })` + runs `game-manifest` → `game-client` → `game-wasm` on dev start, on Rust + changes and on build; `checkDistributedGames` is the CI check. +3. **Runes state.** `useGame(() => createClient({ url, ticket: + gameTicketSource() }), { zone, events: EVENTS })` gives reactive + `status`, `zone`, `rttMs`, `predictionReady`, `error` and typed + `latest(event)` / `events(event)`; it connects on mount and closes on + destroy or navigation. +4. **Settled progress through the business side.** Game state stays in the + zone; what a player keeps belongs to a Distributed service. Mark the cell + command's event as a domain event (`#[event(.., domain)]` + + `repo.publish_events()`), drain the cell outbox onto a bus + (`AggregateCell::drain_outbox_with(BusPublisher::new(bus), ..)`), project + it with a modeled projector into a SQL read model and read that with + generated `@load @live` GraphQL (`clients` in the same Vite plugin, + session-bound variables via `sessionClaim`). The example does this with + `mobpit_service` and a SQLite bus. + +```ts +// src/routes/api/game/ticket/+server.ts +export const POST = createGameTicketHandler({ + secret: () => env.GAME_TICKET_SECRET, + getSession: (event) => event.locals.auth(), + zone: ({ principal }) => zoneFor(principal) +}); +``` + +### Client prediction (Rust → WebAssembly) + +Prediction is an optimistic update at tick rate: the client applies each +input to its own entity at once and, on every Delta, replays the inputs the +server has not acknowledged yet on top of the authoritative state. That is +only invisible if the client's step is *exactly* the server's. So the step +is declared **once**, in Rust, and the browser runs it compiled to +WebAssembly — there is no TypeScript twin to keep in sync. + +```rust,ignore +/// Predicted fields of the `player` kind (same names, plain scalar types: +/// `f32` for quantized floats, u8/u16/u32/i32/bool otherwise). +#[derive(Clone, Copy, GameRecord)] +pub struct MoveState { pub x: f32, pub y: f32, pub vx: f32, pub vy: f32, pub dash: u8, pub cd: u8 } + +/// Read-only data the client supplies (optional; `&()` for none). +#[derive(Clone, Copy, GameRecord)] +pub struct GridContext { pub seed: u32, pub cx: i32, pub cy: i32 } + +#[predict(GridStep, kind = "walker")] +pub fn grid_step(state: &WalkerState, input: &MoveInput, context: &GridContext, _dt: f32) -> WalkerState { + let props = cell_props(context.seed, (context.cx, context.cy)); + let (x, y) = step(state.x, state.y, *input, &props); + WalkerState { x, y } +} +``` + +- **Declare.** `#[predict(StepType, kind = "…")]` on a + `fn(&State, &Input, &Context, dt: f32) -> State` keeps the function and + adds `StepType: PredictStep`. `Input` is the zone's `GameInput`; the + WASM side decodes it with `from_payload`, so it steps exactly what the + server simulates (ranges clamped, unknown buttons cleared). Call the + function from `on_tick` (or the code it wraps) so there is one rule. +- **Record.** `GameSurface::…​.predict::()` checks that the kind + is replicated, that the step takes the zone's input, and that every state + field is a field of the kind with a matching type (it panics at export + time otherwise), then records the step, its state/context records and + the declaring Cargo package in the surface. +- **Build.** `distributed game-wasm --manifest + --manifest-path --out ` compiles that package + for `wasm32-unknown-unknown` (`cargo rustc --release --crate-type + cdylib`) and writes `wasm/.wasm`, stamped with the sources' + fingerprint. Put the step and everything it reads in a crate without + server-only dependencies (the demos use `game_sim`); `distributed_game` + itself compiles to `wasm32` with default features. +- **Run.** The generated `createClient` loads the module and predicts + with it; `client.prediction.setContext(…)` provides the context. + `prediction: false` turns prediction off; a `predict` in `prediction` + replaces it. + +**Binary ABI (v1).** The module imports nothing and exports `memory`, +`dg_predict_abi() -> 1`, `dg_predict_buffer()` (a 64 KiB scratch area) and +`dg_predict_(state_len, input_len, context_len, dt) -> i32`. The client +writes `state ‖ input ‖ context` into the scratch area — state and context +with the payload codec (binary32 floats, never rounded through JSON or +`f64`), the input as its wire payload — calls the step, and reads the next +state from the start of the buffer (a negative result is an error code). +`prediction::step_bytes::` runs the same path natively. + +**Determinism.** Native and WASM results are bit-identical when the step +uses only operations that are correctly rounded on both targets: `+ - * /`, +`sqrt`, `abs`, `min`/`max`, `floor`/`ceil`/`trunc`/`round`, comparisons and +integer arithmetic (Rust never fuses `a * b + c` into an FMA on its own). +Transcendentals are **not** portable: `sin`, `cos`, `atan2`, `exp`, `ln`, +`powf` use the platform libm natively and another implementation on +`wasm32`. If a step needs them, use one deterministic implementation on +both sides (the `libm` crate, or a polynomial in plain arithmetic). Never +produce NaN (payloads may differ). Prefer fixed command frames (one input += one tick, `dt` ignored) and snap replicated floats to their wire +quantization after each step, so the server holds exactly what clients +decode. The demos prove all of this per step function: `game-demos +predict-trace` prints native traces over recorded input streams +(scripted, random, every sanitize edge) and +`examples/game/client/tests/prediction-wasm.test.mjs` requires every state +from the compiled module to be byte-identical (16 788 frames across the +four steps — 20 744 comparisons over the five surfaces' modules — +including the grid's prop collisions). + +**Cost.** Measured on Apple silicon: ~0.2 µs per raw ABI call, ~0.8 µs per +`predict` (fields → bytes → step → fields) in Node 24 and ~1.2 µs in Chrome +156; a reconciliation that replays 10 pending inputs takes ~8–12 µs. +At 30 Hz input and 20 Hz Deltas that is ≈ 0.2 ms of prediction per +second — far below one 33 ms frame. The module is ~90 KB (the demos' four +steps plus the grid's world generation). + +**Security.** Prediction is cosmetic. The server never runs client code +and never trusts a predicted value: it simulates the inputs itself, and +every Delta replaces the prediction with the authoritative state. + +### Shared logic and data (no TypeScript twins) + +Prediction is not the only client code that must agree with the server. +Procedural content, drawing constants and served data have the same +problem: a TypeScript copy drifts. The surface gives each kind of shared +thing one home in Rust and one generated way into the client: + +| What | Rust | Surface | Client | +|---|---|---|---| +| **Logic** (pure functions: world generation, previews) | `#[game_pure(FnType)] fn f(arg: &A) -> R` (or `fn f() -> R`) | `.pure::()` | `createPures().f(arg)`: the same code, compiled into the surface's WebAssembly module | +| **Static data** (sizes, layouts, names) | any `Wire` value (`#[derive(GameRecord)]` struct, list, …) | `.constant("name", &value)` | `NAME` in `constants.ts`, a typed literal | +| **Served data** (fetched at run time, e.g. a content pack) | a `#[derive(GameRecord)]` struct | `.record::()` | `decodeT(bytes)` / `encodeT(value)` over the payload codec | + +Choose by what the thing *is*: computation the client repeats with +arguments it only knows at run time belongs in a pure function (the +Endless Grid generates terrain and props for any cell); data fixed at +build time is a constant (no module to wait for, readable in diffs); +data that changes after the client was built is served and decoded (The +Freeze's content packs, which a client must be able to receive without a +rebuild). + +```rust,ignore +/// What the page draws for one cell (terrain lattice + props). +#[game_pure(GridCellFn)] +pub fn grid_cell(cell: &GridContext) -> GridCellContent { + /* the server's own generation */ +} + +pub fn game_surface() -> GameSurface { + GameSurface::for_zone::("grid") + .predict::() + .pure::() + .constant("grid_world", &grid_world()) +} +``` + +```ts +const pures = createGridPures(); // same module (and instance) as the predicted step +await pures.ready; +const content = pures.gridCell({ seed, cx: 3, cy: -2 }); // GridCellContent, exact binary32 floats +``` + +- **Pure functions** share the predicted step's module, package and ABI + v1: each is an export `dg_pure_(arg_len) -> i32`; the argument's + codec encoding goes into the scratch buffer, the result's comes back + (≤ 64 KiB; negative results are errors, `-6` = argument does not + decode). Every function and the step of one surface must be declared in + one Cargo package; `distributed game-wasm` builds the module when a + surface has either and checks every export. The wrappers are + synchronous and throw until `ready` resolves. `pure::call_bytes::` + runs the export's path natively, so native ↔ WASM tests compare bytes. + The [determinism rules](#client-prediction-rust--webassembly) apply. +- **Constants** are stored in the surface as the client decodes them + (`codec::to_json_value`: encoded, then decoded against the wire type — + floats are exact binary32 values, quantized fields quantized), so the + generated literal equals what `decodeValue` would return for the Rust + encoding. +- **Record codecs** are the event payload codec for one record; serve the + bytes (`codec::to_bytes`) from any transport. + +The demos have no TypeScript twins left for these: the Endless Grid's +terrain, biomes and props (`grid_cell`, `grid_sample`), the Arena floor, +The Freeze's world layout and content packs, Mob Pit's tier radii and +Boss Ripple's zone hierarchy all come from Rust. `game-demos +predict-trace` also prints native traces of every pure function, and +`prediction-wasm.test.mjs` requires the module's results to be +byte-identical (1 440 `grid_sample` points and 64 `grid_cell` cells, +coordinate limits included). Generating one grid cell (17 × 17 heights, +moisture and biomes plus props) costs ~6 µs in the module and ~13 µs +including decoding the result into JS objects in Node 24 (native Rust +~5.6 µs; the removed TypeScript twin took ~77 µs); a point sample ~0.5 µs. + +### Saving progress without pausing the game + +The rule: **the tick never waits for storage.** A slow disk or a busy +database must not freeze the world. Zones emit **facts** and continue. +A fact is the cell command's own input type, bound to the command name +with `#[derive(FactCommand)]` (pointing at the same constant the cell +mounts the command under): + +```rust,ignore +#[derive(Serialize, CommandInput, FactCommand)] +#[fact(command = RECORD_KILL)] // typed_command::(RECORD_KILL) +pub struct RecordKillInput { pub mob: String, pub tier: u8 } + +// in on_tick: key "crawler.record_kill:{zone}:{boot_epoch}:m{mob}:{generation}" +ctx.emit_keyed(killer, RecordKillInput { mob, tier }, &[&format_args!("m{id}"), &generation])?; +``` + +- The host attaches the killer's **verified identity** from their ticket. + The zone cannot claim to be someone else, and the payload names no + reward amount; the command handler decides the XP from what it trusts. + The derive refuses identity-, reward- and economy-looking fields + (`principal`, `user_id`, `owner`, `xp`, `reward`, `amount`, `coins`, + `gold`, `currency`, `price`, `cost`, `balance`, `grant`, `payout`, + `credit`, `debit`; `_`/`-`/case ignored, serde renames and aliases + included) at compile time, one error per field. +- Keys are restart-safe automatically: `ctx.emit(player, input)` uses the + input's `#[fact(key(field, ..))]` parts, or the tick and emission order; + `ctx.emit_keyed` takes explicit parts; `ctx.emit_zone` emits a zone + fact with no principal; `ctx.fact(&input)` builds the `Fact` for a retry + backlog. `Fact::new(key, command, json)` still works. +- A background worker commits facts with retries. + `command_sink::CommandFactSink` dispatches each one as a + command through a command host — `celld::CelldFactSink` to its celld cell + (that player's cell, a match cell, ...) over the internal path, or a + `LocalCommandHost` to a service over any repository — with a command id + derived from the fact key. A retry or a duplicate is + therefore a harmless replay, never a double reward. +- `on_fact_settled` reports the outcome on a later tick. +- Keys must be unique across restarts; `ctx.fact_key` includes the + activation's boot epoch for you (see [Durable facts](#durable-facts)). +- If the process crashes, each in-flight fact is either fully saved or + not saved at all. A zone hosted on celld (`celld_zone`) also keeps its + emitted facts in an outbox in object storage, so they are resent after + a crash: exactly once (Mob Pit's rooms). +- **Player lifecycle facts.** With `HostConfig::lifecycle_facts = true` + the host itself emits `lifecycle::PlayerJoined` (ticket, rejoin or + handoff), `ConnectionLost` (grace started; dropped or told to reload), + `PlayerReconnected`, `PlayerDisconnected` (grace expired) and + `PlayerLeft { reason }` as facts bound to the verified principal, so + presence, match admission and abandon need no hand-written facts. Keys + are `{command}:{zone}:{boot_epoch}:p{slot}:{n}` (stable across retries, + new after a restart); they share the principal's commit lane (order kept + with `max_concurrent_commits > 1`) and wait in a host backlog rather + than being dropped when the queue is full. `lifecycle::Lifecycle::of(&fact)` + decodes them in a sink. Mob Pit routes them to per-player celld presence + cells (`CommandFactSink::lifecycle_route`), ordered by stamp. +- Every fact carries a `FactStamp`: zone, activation (boot epoch), tick, + host wall time `emitted_at_ms` (`Clock::unix_ms`; `ManualClock` in + tests), content version, config version (`HostConfig::config_version`, + `ctx.set_config_version`) and `seq`, the host's per-activation emission + sequence (every stamped fact gets the next number). The cell sink passes it to handlers as + trusted `x-game-*` session variables (`cell::session_stamp`), and + `stamp_metadata` / `FactStamp::from_metadata` copy it onto events. +- **Commit order is not emission order.** Order facts with + `FactStamp::emission_order` (same zone: activation, then `seq`, so two + facts of one tick and millisecond still order strictly; across + zones: wall time). After a handoff the target's stamps start after the + source's departure time, which the transfer ticket carries, so "joined + B" sorts after "left A" even when it commits first or the two hosts' + clocks disagree. + +### Scaling out: zones as celld objects + +On celld every zone is a Durable Object (feature `celld-zone`, +[`celld_zone`](src/celld_zone/mod.rs)): one object per zone id, so a room +*is* a cell. Game code implements `CelldZone` for its `Zone` and declares +the class; nothing in the game or its API names a server. + +```rust,ignore +impl CelldZone for MobPit { + fn object_config(zone: &str, env: &ObjectEnv) -> Result { /* … */ } + fn fact_routes(sink: ObjectFactSink) -> ObjectFactSink { + sink.route(FactRoute::by_principal::("crawler")) + } +} +distributed_game::celld_zone_object!(PitRoom, MobPit); + +// worker entry: /zones/{zone} → the zone's object (WebSocket or …/info) +if let Some(response) = forward_to_zone(req, &env, "PIT_ROOM", "/zones/").await? { … } +``` + +**What celld handles:** where a zone runs (first touch; overflow to the +least-loaded node with `CELLD_MAX_RESIDENT_CELLS`), forwarding a WebSocket +from any node to the owner, one live instance per zone (fenced by its own +epochs), evicting idle objects, moving idle ones to balance load, draining +a stopping node and recovering a crashed node's objects elsewhere. + +**What the framework handles:** the WebSocket join (signed ticket, transfer +ticket of a doorway handoff — single use across activations — or reconnect +token), a self-correcting tick loop that runs only while someone is +connected (and `ZONE_DORMANT_AFTER_MS`, default 10 s, after it empties, +so a room whose last player or near watcher comes and goes does not report +and snapshot every swing), the zone's snapshot in object storage (every +`ZONE_PERSIST_MS`, default 60 s, while occupied, when a player leaves and +when it goes dormant: each snapshot is a durable write celld keeps, so a short +interval grows the store and slows every later write), dormancy and +hibernation (`ZONE_HIBERNATE_AFTER_MS` later, by object alarm, so it also +happens after an eviction), restore on the next join, facts to the cells +of the same worker object to object (`CelldObjectHost` under the usual +`CommandFactSink` routes; a durable outbox in the object's storage makes +them exactly once across crashes; a lane's waiting facts for one cell go +as one `POST …/__batch` and leave the outbox in one delete, see +[Durable facts](#durable-facts)), and the zone's lifecycle reports +(`active` / `dormant` / `hibernated`) into its +[`zone_activity`](src/world/zone_activity.rs) cell, which the +`zone_status` read model projects for minimaps. + +**The world around: watched cells (CQRS).** World cells (a hood, a +borough, the content rollout, the dev settings) are the write model; each +zone keeps a small read model of the ones it cares about. The zone +declares them; each cell's view decodes into a plain struct and becomes a +normal zone message: + +```rust,ignore +impl CelldZone for MobPit { + fn watch(zone: &str) -> Watches { + Watches::new() + .cell(HOOD_KIND, &hood_of(zone), |read: HoodRead| read.state.map(PitMessage::hood)) + .cell(CITY_KIND, CITY_SHARD, |read: CityRead| read.state.map(PitMessage::city)) + } +} + +// the cell: one field and two calls (reads leave a lease, commits push) +self.watchers.serve(&self.env, &self.cell, req, read_hood, sessions).await +self.watchers.alarm(&self.env, &self.cell, read_hood).await +``` + +The zone reads each cell on wake (`GET …?watch=PIT_ROOM/pit.0.0`, which +leaves a lease in the cell's memory — no write); after every commit or +alarm that moves the aggregate's version the cell pushes `{topic, +version, view}` to the live watchers ([`CellWatchers`](src/celld_zone/cells.rs)); +the zone applies only newer versions and re-reads every 45 ± 15 s, renewing +its lease and repairing a lost push. A command that moves the aggregate but +not its view (a heartbeat such as Mob Pit's `room_awake`) pushes nothing, +so N rooms waking do not cost N² pushes. A push never wakes a sleeping zone +(it hydrates on wake). Load is O(view changes × watchers + zones / 45 s), +not every zone reading every cell every second: on one laptop node the +refusals of saturated world cells (celld's 64-in-flight cap) fell from 85 +to 25 with 128 one-player Mob Pit rooms and from 12 to 3 with 64 fighting +ones (numbers in the `mobpit-zone-load-test` task). Read models are for +display and world flavour; rewards stay on the fact → command path. +`CelldZone::refresh` remains for other async reads. + +**Limits.** A live zone never moves (only idle objects are rebalanced), so +load spreads by first touch and node caps. Objects of one class share V8 +isolates: a slow zone delays its neighbours. A node crash takes about the +node lease TTL (`CELLD_TTL_MS`, 10 s) to recover and loses at most the +snapshot interval of zone state; facts survive in the outbox. A socket +that outlives its activation closes with 1012 and the SDK rejoins with a +fresh ticket. celld does not tell code which node it runs on: the node +shown in debug views comes from an opt-in operator lookup +(`CELLD_ZONE_NODES`), never used for routing. + +Measured on celld 0.6.2 (gr-p42 spike, a loaded 18-core laptop): about 150 +one-player rooms or 4–5 fifty-player rooms per core at 30 Hz; forwarding +through another node adds under a millisecond; a hibernated room wakes in +35–130 ms (p50). + +### Zone-to-zone messages + +A running zone can tell another running zone something: a shot that +carries on through a doorway, a mob that follows a player across. It +sends its own `Zone::Message` type; the target handles it in +`on_zone_message`: + +```rust,ignore +// Sender: bind the shooter's verified principal into the message. +ctx.send_zone_for(player, "pit.1.0", &PitMessage::LaserLeg { .. }); + +// Target: +fn on_zone_message(&mut self, ctx: &mut Ctx, from: &ZoneSender, msg: PitMessage) { + if let Some(who) = &from.principal { + ctx.emit_fact_as(who, kill_fact); // reward the remote shooter + } +} +``` + +Each [`ZoneEnvelope`](src/zone_message.rs) has an id unique to the +sending activation (`zone/boot_epoch/seq`); `deliver_zone` drops a repeat. +The receiver sees the sender's principal only as a `VerifiedPrincipal`, +which game code cannot make: it came from a verified ticket in the sending +zone, and facts on behalf of it go through `emit_fact_as`. Drivers move +envelopes with `ZoneHost::take_zone_messages` and `deliver_zone`; on celld +the object posts them to `POST /{zone}/__zone` on its own class with the +internal secret (never a public route); the native `net` server queues +them for a zone on the same server or posts them to the owning peer's +`POST /admin/zone-envelope` (internal secret). A message for a sleeping +zone is refused (409 on celld, 404 native): messages never wake zones. +Delivery is best effort and unordered (dropped, never retried), so a +transfer that must not lose or duplicate state needs a protocol on top. + +**Lending an entity** ([`lease`](src/lease.rs)). To move an entity into +the zone next door (a mob chasing a player through a doorway), the home +zone keeps it `Lent` (hidden, slot reserved) and the other zone keeps it +`Held`. The holder beats; the home answers with a renewal, or a recall +when it no longer lends that transfer. `LeaseTimings::new(beat, lease, +grace)` only accepts `beat < lease < grace`, so the holder always lets go +before the home takes the entity back: the entity is never live in two +zones, and a lost message or a stopped zone only brings it home. The +module keeps the state and the clock; the messages are the game's own: + +```rust,ignore +const LEASE: LeaseTimings = LeaseTimings::new(20, 60, 120); // ticks: lease ≥ 3 beats + +// Home: lend it, answer beats, take it back when overdue. +let transfer = self.transfers.next(ctx.boot_epoch()); +mob.away = Some(LEASE.lend(to, transfer, ctx.tick())); +ctx.send_zone(to, &Msg::Arrive { transfer, hp, x, y }); +// on Msg::Beat: lent.heard(tick) and reply Msg::Renew, or Msg::Recall +if lent.overdue(tick) { bring_back(mob) } + +// Holder: hold it, renew it, beat or drop it each tick. +visitor.lease = LEASE.hold(&from.zone, transfer, tick); +match visitor.lease.poll(tick) { + Hold::Beat => ctx.send_zone(visitor.lease.from(), &Msg::Beat { transfer }), + Hold::Lapsed => drop_visitor(), + Hold::Held => {} +} +``` + +Mob Pit's crossings (`examples/game/server/rooms/src/zone/cross.rs`) are the +full protocol: arrive, beat, renew, recall, home and fell. + +### Scaling out: the native multi-host server + +The `net` server can also spread zones over several processes itself +(Endless Grid and Boss Ripple use it): placement, ownership and +hibernation are then the framework's job. + +- **Placement.** A `ZoneDirectory` (`HashRing`) maps each zone id to a + host. A client that connects to the wrong host is told where to go + (`Redirect`) and follows automatically. +- **One owner at a time.** Each activation of a zone holds a fenced claim + (`ZoneOwnership`, with leases in production). Two servers never run the + same zone, and a server that loses its claim stops without saving. +- **On demand and asleep.** Zones start on first use. With + `hibernate_after`, an empty zone is saved (`Zone::hibernate`) and + unloaded, and restored (`on_restore`) the next time someone arrives. + On celld the snapshot is the zone's own `ZoneState` cell: a sleeping + zone is a sleeping Durable Object. +- **Handoff.** `ctx.handoff(player, "next-zone", carried_bytes)` moves a + player to another zone, on any server, with a signed transfer ticket. + The target receives `on_handoff_join` with the carried state. When the + player's durable records must move too, emit a fact and let a + `distributed::saga` do it off the tick. +- **Hierarchy.** Zone ids like `realm.city.borough` form a tree + (`DottedTopology`). `ctx.emit_upward(…)` sends an event to the parent + zones, wherever they run, and each level can tick at its own rate + (`GameServer::with_host_config`). + +### Live content updates + +`WorldCoordinator::rollout` updates content across every server: + +1. **Freeze**: every zone pauses, shows the update notice, and drops + inputs. A zone can delay with `freeze_ready` (for example, mid-ritual). +2. **Apply**: your function switches the content version (it may be + async, a download for example). +3. **Resume**: everyone continues on the new version. Facts are stamped + with the version they happened under. + +If any zone does not acknowledge in time, the rollout is **aborted** and +everyone resumes on the old version. In `Hard` mode every client reloads +at once. In `Rolling` mode with `StalePolicy::SafeRoom`, clients that +cannot patch live keep playing until they walk into a gate zone +(`is_gate`), where they reload. + +### Lag compensation + +For hit-scan weapons, the server judges a shot against where targets were +**on the shooter's screen** when they fired, not where they are when the +shot arrives. `record_rewind` stores hit volumes each tick, and +`ctx.rewind().hit_test_shot(timing, ray, filter)` tests against that +moment, capped at `max_rewind` (500 ms by default) so lag cannot buy +unlimited rewind. + +### Walls and raycasts + +A zone declares its level geometry once in `on_create`: vertical +cylinders and axis-aligned boxes, each extruded up from the floor. One +query then finds the closest hit among entities and walls, so a shot +stops at a pillar instead of passing through it: + +```rust,ignore +ctx.set_colliders(Colliders::new() + .with(Collider::cylinder([4.0, 2.0], 0.8, 2.4)) + .with(Collider::aabb([-20.0, 19.5], [20.0, 20.0], 3.0))); + +let ray = Ray::new(muzzle, aim, 100.0).ignoring(shooter); +if let Some(hit) = ctx.raycast_shot(timing, &ray) { // lag-compensated + impact(hit.point, hit.normal); + if let Target::Entity(id) = hit.target { damage(id); } +} +``` + +Each hit carries its distance, point and surface normal. Entities and +colliders sit on layer bits (`on_layers`), and a ray meets only the +layers in its `mask`. `colliders().push_out(at, radius, mask)` keeps a +moving body out of the walls. Queries are a linear scan, which suits +rooms with tens of shapes; there is no spatial index yet. + +**Slopes, ground and bounces.** `Collider::ramp(a, b, height, uphill)` is +a wedge rising along one axis, and `Colliders::with_terrain` adds a +`Heightfield` (rolling ground; a `HOLE` sample is no ground at all). +`ground_at(at, mask)` gives the top surface under a point, with its +height and normal, and `walkable(normal)` says whether that is floor +(about 45° or flatter). That is enough for a game's own step to climb +ramps, slide off steep ones and fall into holes; the movement itself +stays the game's, as physics does. `bounce(ray, max_bounces, cast)` +follows a ray, reflecting it off each static surface it meets and +stopping at the first entity: + +```rust,ignore +let mut trace = bounce(ray.mask(LASER_MASK), 4, |r| ctx.raycast_shot(timing, r)); +trace.stop_at(ctx.colliders(), LAYER_BARRIER); // walls it never bounces past +if let Some(exit) = trace.exit_box(muzzle, HALF) { + // It left the room by `exit.side` at `exit.point`: hand the rest of the + // path (`range - exit.travelled`) to the zone next door. +} +``` + +`exit_box` does not count a leg that only reaches a side (a shot that +stopped at a wall on the room's edge) as leaving. + +### Testing and operations + +- **Deterministic tests**: drive `ZoneHost` with `ManualClock`; the RNG + is seeded. +- **Record and replay**: `HostConfig::record` keeps every stimulus a host + is applied, on any driver; `replay` re-runs it and pinpoints the first + tick that differs. +- **Metrics**: `GET /metrics` (Prometheus): tick time, players, entities, + inputs by outcome, bytes per Delta, facts pending and settled. +- **Load bots**: `game-bots` connects N WebSocket clients and reports + round-trip time and bandwidth. +- **Work counters**: `WorkCounters` counts what a zone did (records + encoded, updates sent and held back, Delta bytes, fact commands and + cell requests, outbox deletes, world reads and pushes). Counts do not + move with machine load, so they compare runs exactly where timings + cannot. +- **Network simulation**: `NetSim` adds latency, jitter and loss in + development, and can be changed at runtime. + +### Security + +- Players are admitted only with a signed, single-use, expiring ticket. + Your web backend mints it (in SvelteKit, `createGameTicketHandler` binds + it to the verified session — see [SvelteKit apps](#sveltekit-apps)); plug + in your own verifier with `AdmissionConfig::with_ticket_verifier`. +- The ticket's principal is the only identity the zone sees, and the only + one attached to facts. Inputs are game data, never identity, owner or + reward amounts. +- Admin routes (transfers, tier events, rollout) need a separate shared + secret. + +## Design decisions + +- **Server-authoritative, not lockstep or peer-to-peer.** The server owns + the truth and clients predict. That tolerates cheaters and mixed + latencies, and needs only one simulation per zone. +- **Zones, not one global world loop.** A zone is the unit that ticks, + sleeps, moves between servers and is owned by exactly one process. + Actors live inside their zone. Only things that outlive a zone (a + player's profile, a match) get their own durable cell. +- **Facts, not per-tick persistence.** Movement and combat ticks are never + stored, only meaningful outcomes. The tick enqueues and moves on, so + storage speed never shows up as lag. +- **Idempotency through keys; the outbox is a log consumed in batches.** + A fact key plus the cell's command ledger make retries safe. A native + zone keeps facts in its bounded queue only (the zone state lost in a + crash is lost either way). A celld zone also journals them in object + storage, written with the tick's other writes and settled in batches + (one cell request and one delete per batch), so the outbox costs one + batched write per tick, not two writes and a request per outcome. +- **Static world from a seed.** Terrain and props are a pure function of + seed and content version, generated identically on server and client. + Only things that change are replicated. +- **Prediction compiled from the server's Rust, over a binary ABI.** A + TypeScript twin of the movement code drifts the first time someone + changes one side; running the same Rust as WebAssembly cannot. JSON + bridges (as browser WASM pures use) round-trip `f32` through `f64` and + allocate per call; a fixed scratch buffer with codec-encoded state keeps + every float bit and costs about a microsecond per step. +- **Binary protocol with the schema sent on connect.** Small, + diff-friendly frames, and any client can decode them without generated + code. One protocol version, checked in the handshake (`PROTOCOL.md` + §6.0): a server refuses any other, so servers and clients deploy + together (pre-release; no negotiation to maintain). +- **Reliable, ordered WebSockets.** Deltas are computed against what each + client last received, which only works because nothing is lost or + reordered. Loss shows up as delay, which the adaptive interpolation + absorbs. +- **Shared encodings, per-client baselines.** Deltas stay per client + (each knows only what it was sent), but each distinct entity state and + each update between two states is encoded once and shared, so dense + rooms pay for copying, not encoding. Lowering far update rates on top + is a server choice: the wire and the client are unchanged. + +## Status and limits + +- Pre-release, on the unreleased v5 line. +- Covered by unit, integration and golden-wire tests, plus the demos' + smoke tests (bots and headless browsers). +- **Not yet verified here:** `FencedLeaseOwnership` on Postgres (Docker + was unavailable) and the Redis leaderboard against a real Redis (only a + fake). +- No production deployment or load testing beyond local bots. +- WebSocket only (no UDP or WebTransport). No built-in physics. Exact + input replay needs the predicted step to be what `on_tick` runs: declare + it once with `#[predict]` and call it from the zone. Steps must stay + within portable float operations (see + [Client prediction](#client-prediction-rust--webassembly)). + +--- + +# Reference + +## Authoring derives + +Re-exported from `distributed_game_macros`; each has spanned compile +errors for unsupported types and attributes. + +| Derive | On | Container attribute | Field attributes | Implements | +|---|---|---|---|---| +| `Replicated` | struct | `#[replicated(kind = "name", id = N, priority = P, global, x = f, y = f, of = Entity)]` | `quant`, `angle`, `field_type`, `priority`, `correct`, `from` / `from(a.b)` (with `of`) | `Replicated` (`kind_def`, `field_values`, `position`); with `of`: `View::project` + `ViewRest` (or, all `#[from]`, `impl Project for Entity`) | +| `GameInput` | struct | – | `range`, `buttons`, `quant`, `angle`, `field_type` | `GameInput` (`from_payload`, `to_payload`, `sanitize`) + button consts | +| `GameEvent` | enum / struct | `#[game_event(id = N, name = "..")]` per variant / on the struct | `quant`, `angle`, `field_type`, `long` | `GameEvent` (`decode_event`, `to_payload`) + id consts | +| `GameRecord` | struct | – | `quant`, `angle`, `field_type`, `long` | `Wire` (nested payload record) | +| `FactCommand` | struct (`Serialize`) | `#[fact(command = CONST_OR_LITERAL, key(field, ..))]` | – | `FactCommand` (`COMMAND`, `dedupe_parts`) | +| `#[predict]` (attribute) | `fn(&State, &Input, &Context, f32) -> State` | `#[predict(StepType, kind = "name")]` | – | `struct StepType: PredictStep` + the `wasm32` export `dg_predict_` | +| `#[game_pure]` (attribute) | `fn(&A) -> R` or `fn() -> R` (`Wire` types) | `#[game_pure(FnType)]` | – | `struct FnType: GamePure` + the `wasm32` export `dg_pure_` | + +`schema![A, B]` builds an `EntitySchema`; `GameSurface::for_zone::(name)` +(kinds from `Z::schema()`, input from `Z::Input`) `.events::()` +`.predict::()` `.pure::()` `.constant(name, &v)` `.record::()` +builds the surface; `codec` holds the shared value codec (`Wire`, +`WireType`, `to_json_value`); `prediction` the predicted-step trait, its +ABI (`run_abi`, `step_bytes`) and the float rules; `pure` the pure-function +trait and its ABI (`run_abi`, `call_bytes`). + +## Features + +| Feature | Adds | Deps | +|---|---|---| +| *(default)* | Zone/host runtime, facts queue, protocol, schema, replication, authoring derives, game surface, predicted steps (compiles to `wasm32-unknown-unknown`, where `#[predict]` exports its steps) | `serde`, `serde_json`, `distributed_game_macros` | +| `runtime` | `spawn_fact_worker` on Tokio | `tokio` (rt, time, sync) | +| `cell` | `cell::command_id_for` / `trusted_session` / `run_fact_batch`; `cell::fact_session_from_headers` / `session_stamp` for cells (also wasm32); `stamp_event_record`; the `world::zone_lease` and `world::zone_state` cell aggregates | `distributed`, `sha2`, `base64` | +| `cell` (also) | `command_sink::CommandFactSink`: facts → commands through any fact host, routed by command (`FactRoute`); `world::zone_activity` | | +| `command-host` | `FactHost` for `CelldCommandHost` / `LocalCommandHost` (`CelldFactSink`) | `cell` + `distributed/graphql` | +| `celld-zone` | `celld_zone`: any `Zone` as a celld Durable Object (`ZoneObject`, `celld_zone_object!`, `forward_to_zone`), facts object to object (`CelldObjectHost`), `serve_cell` / `ZoneActivityCell` for the worker's cells (wasm32) | `cell`, `ticket`, `cloudflare-workers` + `js-sys`, `wasm-bindgen(-futures)` | +| `ticket` | `ticket`: HS256 admission and transfer tickets without the axum server | `hmac`, `sha2`, `base64` | +| `celld` | `celld::CelldFactSink` (the command sink over a remote-only `CelldCommandHost`): facts → celld cells over the internal HTTP path; `celld::CellZoneOwnership`: zone leases in celld `ZoneLease` cells; `celld::CellZoneStateStore`: hibernation snapshots in celld `ZoneState` cells | `command-host` + `reqwest`, `uuid` | +| `cloudflare-workers` | `world::zone_state::celld_worker`: the `zone-state/{zone}` route of a celld worker (cell + R2 bucket binding for large snapshots) | `cell` + `worker` | +| `metrics` | `metrics::GameMetrics` per-zone Prometheus text | – | +| `net` | `net::GameServer` (axum WebSocket), HMAC tickets, `GET /metrics` (implies `metrics`), handoff, admin peer routes, `WorldCoordinator` | `axum`, `hmac`, `sha2`, `base64`, `tokio` | +| `bots` | `bots` load-test client library + `game-bots` binary | `net` + `tokio-tungstenite` | +| `lease` | `world::FencedLeaseOwnership` over `distributed::lease` | `distributed` | + +## Durable facts + +Zones never await storage. Emit a fact during a tick — typed (the cell +command's input with `#[derive(FactCommand)]`, key derived for you) or by +hand: + +```rust,ignore +ctx.emit_keyed(player, SlayInput { enemy: enemy_id }, &[&enemy_id, &enemy_generation])?; +// "hero.slay:{zone}:{boot_epoch}:{enemy}:{generation}"; or by hand: +let key = ctx.fact_key("slay", &[&enemy_id, &enemy_generation]); // "slay:{zone}:{boot_epoch}:…" +ctx.emit_fact_for(player, Fact::new(key, "hero.slay", json!({"enemy": enemy_id})))?; +``` + +Settlements: `settlement.is::()`, and +`receipt.payload_as::()` for the command's typed output. + +`ctx.emit*` answers `EmitError::Backpressure` when the zone's fact queue +is full. `ctx.emit_queued(player, input)` (and `queue_fact_for` / +`queue_fact_as` for a fact built by hand) never does: the fact is stamped +now and waits in the host's backlog — the one the lifecycle facts use — +in order, and goes out as settlements free capacity. It counts as in +flight, so the zone does not go Dormant with it waiting. + +**Durability differs by driver, and is named here on purpose:** + +| Driver | Guarantee | Why | +|---|---|---| +| native (`GameServer`, `ZoneHost` + `spawn_fact_worker`) | **at most once** across a crash; exactly once (idempotent key) while the process lives | the queue and the backlog are process memory: a crash, a kill, a disposal that outlives `settle_timeout`, or lost ownership (`abandon_facts`) drops what is unsettled | +| celld zone object | **at least once** to the cell, exactly once in effect | each call's emitted facts are spooled to the object's storage (its outbox) and deleted on settlement; the next activation (or the outbox alarm) resends what is left, and the cell's command ledger turns a resend into a replay | + +A native game that cannot lose a fact keeps its own durable record (or +emits from a cell, not a zone). + +> **Warning — restart-safe keys.** Ticks, entity ids and generations all +> restart from zero when a process restarts (or a zone is re-activated from +> a snapshot). A key derived only from them — `format!("kill:{zone}:{tick}")` +> — **collides with an earlier run's key**, and an idempotent sink then +> treats the new outcome as a replay of the old one: the XP is silently +> never credited. Always include `ctx.boot_epoch()` (unique per activation, +> increasing across restarts; the `net` server uses the activation's fencing +> token, a bare `ZoneHost` Unix microseconds, or `HostConfig::boot_epoch`) +> — `ctx.fact_key(prefix, parts)` / `fact_key(prefix, zone, epoch, parts)` +> do it for you. + +The host binds the principal from the player's **verified ticket** and +stamps zone, activation, tick, wall time, content and config version and emission sequence. A `FactSink` commits facts on a worker +with bounded retries/backoff; `Zone::on_fact_settled` receives the outcome +on a later tick. `command_sink::CommandFactSink` dispatches each fact as a +command with a deterministic command id per fact key, so retries replay +instead of double-crediting. A custom sink needs only crate-root imports: +`impl FactSink for MySink { fn commit<'a>(&'a self, fact: &'a Fact) -> BoxFuture<'a, Result> { Box::pin(async move { … }) } }` +(`BoxFuture` is also re-exported from `world` and `net` for +`ZoneOwnership` / `BarrierParticipant` impls). + +**Facts as commands.** A zone server sends its facts to the durable +aggregates as commands through a `CommandHost`, with one +`command_sink::CommandFactSink` (feature `command-host`), routing each fact +by its command to an aggregate kind and shard (`FactRoute`: by principal, +by input field, by zone, or a function of the input and trusted session). +The same routes serve every host: `celld::CelldFactSink` (feature `celld`) +addresses celld cells by kind and shard; over a `LocalCommandHost` a +service routes by command and its handler picks the stream +(`tests/command_facts` runs the celld test's routes against an in-memory +repository): + +```rust,ignore +let sink = CelldFactSink::celld(celld_url, InternalHttpSecret::new(secret)?, "zone-server", "zone:pit-1")? + .route(FactRoute::by_principal::("crawler")) // Crawler:{principal} + .route(FactRoute::by_input_field::("match", "match_id")) + .lifecycle_route("presence"); // zone.* → Presence:{account} +// or: CommandFactSink::new(LocalCommandHost::new(service), "zone-server", "zone:pit-1")?.route(..) +let (queue, feed) = fact_channel(capacity, RetryPolicy::until_settled(base, max)); +spawn_fact_worker(feed.with_max_concurrent_commits(n), sink); +``` + +Over celld each fact is `POST {CELLD_URL}/{kind}/{shard}/{command}` with +`{commandId, input}` (the remote-only `CelldCommandHost`); the command id is +`cell::command_id_for(service, key)`, so a retry after a timeout replays the +cell's ledger receipt (`replayed`) instead of committing twice. Cells answer +the standard wait-path body (`CausalDispatchResult::wait_path_wire`). The +principal travels as `x-user-id` and the command-ledger principal partition, +the stamp as `x-game-*` headers (`CelldCommandHost::forward_session_prefix`), +and every request carries +`DISTRIBUTED_INTERNAL_SECRET`; the cell rebuilds the trusted session with +`cell::fact_session_from_headers` after checking the secret. Player +lifecycle facts route to presence, never to gameplay cells. celld slow, +unreachable or answering 5xx/`COMMAND_IN_PROGRESS` is `Retryable`: with +`RetryPolicy::until_settled` the fact stays in the queue (no local durable +fallback), the zone keeps ticking, a full queue answers `Backpressure`, +and after celld returns the backlog drains in per-principal order. An +unrouted command, a rejected command or a bad shard is `Permanent`. +`tests/celld_facts` proves this on `celld dev` against +`tests/celld/fact-worker`, including a crash and restart of celld. + +**Throughput.** One worker per zone commits facts in emission order, one at +a time (a slow commit delays every later fact). Set +`ServerConfig::max_concurrent_commits` (or +`FactFeed::with_max_concurrent_commits`) above 1 to overlap commits in +**per-principal lanes**: a principal's facts (and, separately, zone facts +without a principal) stay sequential in emission order; different +principals commit concurrently; settlements arrive in completion order. + +**Batches.** A sink that settles many facts in one round trip opts in +with one override that also supplies the batch commit: +`fn batches(&self) -> Option<&dyn FactBatchSink> { Some(self) }` plus +`impl FactBatchSink for MySink { fn commit_batch(…) }` (a host: +`FactHost::fact_batches` → `FactBatchHost::dispatch_fact_batch`; the +celld object host does). The feed then hands it up to +`FactFeed::with_max_batch` (default 16; celld zones: `ZONE_FACT_BATCH`) +waiting facts of a lane at once. Other sinks (`batches` is `None` by +default) get one fact at a time and each settlement as soon as it +commits. Game code is unchanged (`ctx.emit`, `#[derive(FactCommand)]`, +`#[command]` handlers). `CommandFactSink` groups consecutive facts for +the same aggregate and hands them to the host's batch dispatch, which the +celld object host sends as one `POST {kind}/{shard}/__batch` (each entry +with its own command id, principal and stamp; `serve_cell` runs them in +order through the same idempotent wait path and drains the cell outbox +once). A batch stops at its first retryable failure and is retried from +there; attempts count per fact, so order, exactly-once and +`RetryPolicy` mean what they mean for single facts. A cell without the +batch route, or one refusing the batch request as a whole (a 4xx other +than 408/429), gets the facts one by one. Serve fact cells with +`serve_cell` (or `CellWatchers::serve`), whose `__batch` runs the batch +under one command guard and one alarm reschedule +(`AggregateCell::dispatch_idempotent_batch`); each entry is still its own +ledger reservation and commit. + +## Netcode and operations + +- **Admission tickets** (`net`): by default join tickets are HS256 JWTs + signed with the admission key (`ServerConfig::admission.key`, PROTOCOL.md + §8). Both drivers (the `net` server and celld zone objects) admit through + the same `admission::admit`. To admit tickets your web backend already + mints, plug in a verifier — + `config.admission = config.admission.with_ticket_verifier(|token: &str, zone: &str, now: u64| { … })` + (celld: the `CelldZone::admission` hook) + (or implement `net::TicketVerifier`) — that checks your issuer, audience + and lifetime (`net::decode_hs256` verifies an HS256 signature and + returns the claims) and returns `TicketClaims` with `zone` = the route + zone and `nonce` = your replay key (e.g. `jti`). The server still + enforces route zone, expiry and single use; `TicketClaims::name` becomes + `PlayerInfo::name` / `ObserverInfo::name` and travels with handoffs. + Transfer tickets always use the admission key. +- **Extension claims**: game-declared claims the issuer vouches for (match + id, team, party) travel in the ticket's `ext` object. Declare them once — + `#[derive(Serialize, Deserialize, TicketExtension)] struct MatchClaims { + match_id: String, team: u8 }` — and admit them with + `AdmissionConfig::with_ticket_extensions::()` (`net`: + `config.admission`; celld: the `CelldZone::admission` hook). The derive + refuses identity-, reward- and economy-looking names (the `FactCommand` + deny list, shared with the JS handler through + `tests/fixtures/trusted_field_denylist.json`); the server refuses tickets + whose `ext` has undeclared names or wrong types, and any `ext` when no + schema is declared (join tickets from any verifier and transfer tickets + alike). Zones read them typed in `on_auth` + (`req.claims.extensions.typed::()`) and afterwards from + `PlayerInfo::extensions`; a rejoin replaces them with the fresh ticket's + and handoffs carry them to the next zone. +- **Input pacing**: `InputCredits::new(max)` gives each player one input + credit per tick (banking up to `max` for jitter bursts); + `credits.take(ctx, player)` consumes queued inputs while credits last, so + a client can never simulate faster than real time by flooding inputs. + Pair it with the JS SDK's `InputPacer` (one input per server tick from a + render loop). +- **Observers**: `Ctx::observer(id)` / `observers()` / `observers_of(principal)` + expose each observer's verified principal and name (also during + `on_unobserve`); `ctx.send_event(observer_id, …)` addresses one observer. + +- **Lag compensation** (`rewind`): implement `Zone::record_rewind` to push + hit volumes (sphere / vertical capsule + numeric fields) each tick; the + host keeps a ring buffer sized by `HostConfig::rewind.max_rewind` + (default 500 ms). In a hook, + `ctx.rewind().hit_test_shot(ShotTiming { client_tick, interp_delay }, &HitQuery::ray(o, d, range), |id| id != me)` + evaluates at the shooter's view time, clamped to `max_rewind` and the + stored history. The interpolation delay travels in the game's input + payload (no wire change). +- **Static colliders** (`collide`): `ctx.set_colliders(Colliders)` in + `on_create` (cylinders and boxes extruded from `z = 0`, each on layer + bits). `ctx.raycast(&Ray)`, `raycast_at(time, ..)`, `raycast_where(time, + .., accept)` and `raycast_shot(timing, ..)` return the closest + `RayHit { target: Entity(id) | Static(index), distance, point, normal }` + among the recorded rewind entities and the colliders. A `Ray` has + `max_dist`, a layer `mask` and an `ignoring(id)`; it is not a + client-side query, and the predicted movement in `sim` does not use it. +- **Record/replay** (`replay`): everything outside a zone reaches it as + one `Stimulus` through `ZoneHost::apply` (the typed methods `join`, + `push_input`, `advance`, … are shorthand for it), with the clock read + once per stimulus. A host created with `HostConfig::record` keeps each + stimulus with that clock reading and what it observed — on the native + server, a celld zone object or a test alike (`ZoneHost::recording`; + `GameServer::inspect` reads it from a live zone). Save the compact + `Recording` (`DGR4`), and `replay::(&recording, config)` re-runs it + on the recorded clock readings, checking join and input outcomes and a + per-tick state hash (`Zone::state_hash`, or the replicated `WorldView`). + A mismatch returns a `Divergence` naming the tick and the stimuli + applied since the last matching tick. Fact settlements are replayed on + the tick they were delivered, and `ReplaySummary::facts` returns the + facts the replay emitted (same keys and stamps as the live run's). + Zone-issued handoffs replay against a stub issuer that always signs. +- **Metrics** (`metrics`, served by `GameServer` at `GET /metrics`): + tick duration histogram, ticks/dropped ticks, tier, players, observers, + entities, inputs by outcome (incl. `rate_limited` and `frozen` barrier drops), + Delta bytes per frame, facts pending/settled. + Only the first `ServerConfig::metrics_zone_labels` (default 64) live + zones get a `zone` label; the rest aggregate into `zone="_other"`. + `AdvanceReport` carries the raw numbers for custom drivers. +- **Work counters** (`work::WorkCounters`, always on, plain integers): + `record_advance(&report)` adds a patch's records encoded + (`AdvanceReport::encodes`, shared by every client), frames, Delta bytes, + creates, updates, updates held back by update rates + (`DeltaStats::held`) and budget deferrals. A celld zone object keeps one + per object and adds its fact commands, cell requests and `__batch` + requests, outbox deletes, watched-cell reads and pushes received; `GET + /zones/{zone}/info` reports it as `work`, with the A/B switches in effect + (`switches`). A watched cell answers `GET /{kind}/{shard}/__watchers` + (internal secret) with its live watchers and `WatcherStats` (watching + reads, views published, views skipped as unchanged, pushes sent). + Switches (worker vars, default on): `ZONE_FACT_BATCH=1` (one fact per + request), `ZONE_UPDATE_RATES=0` (every visible change every patch), + `ZONE_WORLD_PUSH=0` (zones poll watched cells every second instead of + taking pushes). Mob Pit's `mobpit-load` prints the counters per step, + normalised per room patch, room-second or room-minute, and runs + interleaved A/B (`--ab ZONE_UPDATE_RATES=0 --pairs 3`: A,B then B,A …, + medians per side and of the per-pair change). +- **Bots** (`bots`): `run_bots(BotConfig, |i| behaviour)` connects N + WebSocket clients with signed tickets, sends inputs (random walk, + circle, or your own `Behaviour`), measures RTT and Delta bytes/s: + `cargo run -p distributed_game --features bots --bin game-bots -- --url ws://127.0.0.1:2567 --zone room-1 --bots 50`. +- **Network simulation** (`NetSim`, dev only): one-way latency + uniform + jitter + loss, per direction. WebSockets are reliable and ordered, so + loss is simulated as a TCP retransmission delay (`retransmit`, default + 200 ms, up to 3×) with head-of-line blocking, never as a dropped or + reordered message. `config.net_sim = NetSim::from_env()` reads + `DG_NET_LATENCY_MS`, `DG_NET_JITTER_MS`, `DG_NET_LOSS`, + `DG_NET_RETRANSMIT_MS`. `GameServer::set_net_sim(Some(sim) | None)` + changes it at runtime for every connection (order is preserved). + `distributed_game::netsim` is portable: zones hosted as celld objects + (`celld-zone`) apply the same simulation to each socket when the worker + sets `ZONE_DEV_SETTINGS=1`; the setting lives in the worker's dev + settings object (`celld_zone::ZoneDevSettings`, `PUT /zone-dev/netsim` + `{latencyMs, jitterMs, loss}` with the internal secret), pushed to every + zone object watching it (`world::watch`). + +## World structure + +`world` (no feature needed for the traits and in-memory impls): + +| Piece | Purpose | +|---|---| +| `ZoneDirectory` (`StaticDirectory`, `HashRing`) | zone → owning `HostAddr`. `HashRing` uses virtual nodes; adding/removing one of N hosts moves ~1/N of the zones. A Hello for a zone owned elsewhere gets `Redirect(zone, url)`; `url` is the owner's `HostAddr::ws_url` (advertise a proxied public URL with `HostAddr::with_ws_url`) or `ServerConfig::with_redirect_url(\|host, zone\| …)`. | +| `ZoneOwnership` (`LocalOwnership`, `FencedLeaseOwnership`, `celld::CellZoneOwnership`) | every activation acquires a fenced claim (`host#activation`) and renews it; a failed renewal disposes the zone **without** saving. Two hosts never run the same zone. `CellZoneOwnership` keeps each claim in a celld `ZoneLease:{zone}` cell (`world::zone_lease`, mount with `mount_zone_lease`): acquire and release publish `zone.activated` / `zone.released`, renewals are internal (no outward events), and the lease's expiry schedule (`ctx.schedule`; the routes require `Capability::Scheduling` and `Clock`) publishes `zone.lease_expired` when a holder stops renewing, so services see a crashed zone server; each event carries the lease's `ZoneLeaseStatus { zone_id, holder, token, status }`. `world::ownership_conformance` is the behaviour every implementation passes. | +| `ZoneStateStore` (`celld::CellZoneStateStore`; `MemoryZoneStateStore` for unit tests) | hibernation snapshots (async `load` / `save` / `delete`), written under the claim's fencing token (stale writers get `StateError::Stale`, counted in `distributed_game_hibernation_saves_total{outcome="stale"}` and logged to stderr, never silently dropped). On celld each zone's snapshot is its own `ZoneState:{zone}` cell (`world::zone_state`): inline up to 64 KiB, larger ones in the worker's R2 bucket with the digest in the cell; saves and deletes publish `zone_state.saved` / `zone_state.deleted` with a `ZoneSnapshotStatus { zone_id, token, stored, content_version, bytes }` (no bytes). `LocalOwnership` seeds its tokens from the Unix time (µs) at creation, so a restarted host still outranks the snapshots its previous run saved. | +| `world::zone_status` (feature `cell`) | the read model of those events: `zone_leases` and `zone_snapshots` rows (`projection!` upserts of the state bodies), `projectors()` to mount on any consumer service and read-model store, and `ZoneStatus::of` → `Active { holder }` / `Hibernated { bytes }` / `Cold`. For views (world maps, minimaps): it answers "which zones are active or asleep?" without opening a cell per zone (on celld a read of a never-used cell creates it). Eventually consistent; ownership and restore always go to the cells. | +| `world::watch` (`Watches`, `Watchers`, `TopicVersions`) | watched world views: a zone's typed list of the cells it watches; a cell's in-memory watcher leases; the zone's per-topic version guard (a late push or read never rolls back). On celld: `CelldZone::watch` + `celld_zone::CellWatchers`. | +| `ZoneTopology` (`DottedTopology` default: `eldoria.port.docks` → `eldoria.port` → `eldoria`) | parent links for tier-up events. | + +**Per-zone host settings.** `GameServer::with_host_config(|zone_id, host| +…)` adjusts the `HostConfig` of each activation (e.g. a province ticking at +2 Hz while its neighborhoods run at 30 Hz); the world content version is +applied afterwards. + +**Zone inbox.** Services talk to a running zone through typed messages: +`type Message = MyMessage` on the zone (a `#[derive(GameEvent)]` struct or +enum, so it has stable ids and the event payload codec; `NoMessages` for +none) and `Zone::on_message(ctx, message)`, which runs on the zone's task +between ticks, never during one. Deliver with `GameServer::send(zone, +ZoneInbound::Message(m))` locally, `POST /admin/zone-message` (admin +secret; `{zone, message: {type_id, payload}}` or `{zone, kick: +{principal, reason}}`) from peers, or `net::ZoneInboxClient` from a +service: it finds the owner through the `ZoneDirectory` and follows `421 +wrong_owner` answers. The built-in `ZoneInbound::Kick { principal, reason +}` removes every connection of the principal (`LeaveReason::Kicked`, and a +`PlayerLeft` lifecycle fact). A message for a zone that is not running is +refused (`404 inactive` / `InboxError::Inactive`) and never activates it. +Messages appear in the game surface under `messages`; the generated +TypeScript has `MESSAGE`, `MESSAGES` and `encodeMessage` for TS services. +Recorded and replayed like every other stimulus. + +**Zone factory and allocation.** `ZoneFactory::new(|activation| async move +{ … })` may await storage: it runs on the activation task after the +ownership claim and snapshot load, before the zone exists. It receives a +`ZoneActivation { zone_id, activation, allocation }` — `activation` is the +fencing token (= `boot_epoch` = the facts' stamp activation), `allocation` +the `ZoneAllocation` record (roster, mode, config version) that the service +which allocated the zone wrote into the store passed to +`GameServer::with_allocation_store` (`MemoryZoneAllocationStore`, or your +own `ZoneAllocationStore`). Return `Ok(Some(config))` to create the zone +(`on_create` gets it), `Ok(None)` for "no such zone" (`Error(NOT_FOUND)`), +`Err(ZoneCreateError)` when something it needs failed +(`Error(ZONE_UNAVAILABLE)`). Store failures and a factory that outlives +`ServerConfig::activation_timeout` also answer `ZONE_UNAVAILABLE`, never a +hang. Joins that arrive during creation wait and are admitted afterwards; +the tick never awaits. `ZoneFactory::sync(|activation| …)` covers factories +without I/O. `GameServer::activate(zone).await` waits for a zone to run; +`begin_activation(zone)` only starts it. + +**Activate on demand / hibernate.** `GameServer` creates a zone on first +join (or tier-up event). With `ServerConfig::hibernate_after = Some(d)` a +zone that stays Dormant for `d` (no clients, no in-flight facts, not +frozen) is hibernated: unregistered atomically (later joins start a new +activation, which waits for this one's claim), `Zone::hibernate()` is +stored, `on_dispose` runs, the claim is released. The next activation +calls `Zone::on_restore`. + +*Facts on dispose:* a zone only becomes Dormant with zero unsettled +facts, so hibernation never strands a settlement. Facts emitted during +disposal (e.g. in `on_dispose`) are still committed: the fact worker +drains its queue after the zone drops it, and the zone task waits up to +`settle_timeout` for it; what is still unsettled after that is dropped. +Native facts are at most once across a crash (see +[Durable facts](#durable-facts)): "settle, then dispose" keeps them in +memory only; the celld zone object spools them instead. + +**Handoff.** In a hook: `ctx.handoff(player, "realm.west", &carried)?`, +`carried` any `Wire` value (a `#[derive(GameRecord)]` struct); the target +decodes it in `on_handoff_join` with `codec::from_bytes`. +The host signs a transfer ticket (principal, source, target, issuer host, +ownership generation, carried state, nonce, 30 s expiry), removes the +player (`LeaveReason::Handoff`) and sends `Handoff(target, ticket)`. The +target reserves the ticket with the issuing host (locally or via +`/admin/transfer`), admits it with `Zone::on_handoff_join(player, from, +carried)` and confirms; a refused transfer is released and the client may +present the same ticket back to the source (PROTOCOL.md §8.1). The +realtime path never waits on storage. **Custody:** the carried state then +lives only in the ticket the client holds, so it is delivered at most +once: a dropped or discarded ticket, an expired one, or an issuer restart +before the target reserves it loses it (the player is in neither zone +until it joins again; it is never in both). When the player's **durable** +record must move too (home zone, inventory cell), emit a fact from the +handoff hook and let a `distributed::saga` drive it, off the tick: + +```rust,ignore +// zone hook: non-blocking +ctx.emit_fact_for(player, Fact::new(format!("move:{nonce}"), "player.relocate", + json!({"from": from, "to": to})))?; +// fact sink → SagaRunner::<_, Relocate>::start(nonce, data): +// step "detach" → source cell (compensate: "reattach") +// step "attach" → target cell (compensate: "detach_again") +// timeouts compensate; the game keeps playing on carried state meanwhile. +``` + +**Tier-up events.** `ctx.emit_upward("boss_defeated", payload, +ChildEvent::TO_ROOT)`; the server routes it to the parent (activating it, +on its owning host via `/admin/child-event`), whose host delivers +`Zone::on_child_event` on a later tick and forwards it further up while +`levels` remain. + +**Content barrier.** `net::WorldCoordinator::rollout(version, notes, mode, +apply)` over `GameServer`s and `RemoteHost`s (admin HTTP, shared secret): +freeze all zones (`Freeze{version}`; `Zone::freeze_ready` may delay), +wait for every ack within the timeout, `apply(version)`, then commit +(`Resume{version, notes}`; facts/`ctx.stamp()` carry the new version). +`rollout_async(…, |version| async { … })` awaits an async `apply` while +every zone stays frozen (a visible "applying update" pause, no extra +barrier participant needed). A missing ack or failed `apply` aborts: +everyone resumes on the old version with `AbortNotes` +(`WorldCoordinator::with_abort_notes`; `{error}` expands to the apply +error). Inputs while frozen are dropped and counted +(`ZoneHost::inputs_dropped_frozen`). `HostConfig::stale_policy = +StalePolicy::SafeRoom { roam }` lets old clients keep playing after a +`BarrierMode::Rolling` commit until they reach a gate zone +(`Zone::is_gate`), where they get `Kick(RELOAD)` and reconnect with their +token after reloading — stale clients already inside a gate when the +rolling commit lands are reloaded there at once; `BarrierMode::Hard` +reloads every stale client at once. + +Admin routes (enabled by `ServerConfig::admin_secret`, an +`InternalHttpSecret`; header `x-distributed-internal-secret`, the internal +secret convention): `POST /admin/transfer`, `/admin/child-event`, +`/admin/barrier/{prepare,commit,abort}` — see `net::world`. + +## Protocol + +See [`PROTOCOL.md`](PROTOCOL.md) — binary, little-endian, varints, one +message per WebSocket frame, schema shipped in Welcome so generic clients +need no codegen. Golden fixtures for other implementations are in +`tests/fixtures/`. + +## Tests + +```sh +cargo test -p distributed_game --all-features +UPDATE_GOLDEN=1 cargo test -p distributed_game --test golden # accept wire changes +``` diff --git a/distributed_game/examples/echo_arena.rs b/distributed_game/examples/echo_arena.rs new file mode 100644 index 000000000..7b417f64b --- /dev/null +++ b/distributed_game/examples/echo_arena.rs @@ -0,0 +1,129 @@ +//! Tiny WebSocket zone server for client end-to-end tests (feature `net`). +//! +//! Every player owns one avatar moved by 2-byte inputs `[dx, dy]` (i8, +//! clamped to -1..=1) at 10 units/s. On join the player receives Event type +//! 1 carrying its avatar entity id (u32 LE) so a client can bind prediction. +//! Zones `arena-*` are created on demand; tickets are HS256 with the secret +//! from `DISTRIBUTED_GAME_SECRET` (default `dev-secret`). +//! +//! Prints `LISTENING ws://127.0.0.1:` once bound, then serves until +//! stdin closes (so a parent test process can stop it by exiting). +//! +//! ```sh +//! cargo run -p distributed_game --features net --example echo_arena +//! ``` + +use std::collections::BTreeMap; +use std::io::{BufRead, Write}; + +use distributed_game::net::{GameServer, ServerConfig, TicketKey, ZoneFactory}; +use distributed_game::{ + ConsumePolicy, Ctx, EntitySchema, EntityState, FieldType, FieldValue, KindDef, LeaveReason, + PlayerId, View, WorldView, Zone, +}; + +const AVATAR: u16 = 1; +const SPEED: f32 = 10.0; + +struct EchoArena { + avatars: BTreeMap, +} + +impl Zone for EchoArena { + type Config = (); + type Input = (i8, i8); + type Timer = (); + type Message = distributed_game::NoMessages; + + fn schema() -> EntitySchema { + let pos = FieldType::QuantF32 { + min: -500.0, + max: 500.0, + bits: 20, + }; + EntitySchema::new().kind( + KindDef::new(AVATAR, "avatar") + .field("x", pos) + .field("y", pos) + .field("seq_hint", FieldType::U32), + ) + } + + fn on_create(_ctx: &mut Ctx<'_, Self>, _config: ()) -> Self { + Self { + avatars: BTreeMap::new(), + } + } + + fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + let entity = 100 + player.0; + self.avatars.insert(player, (entity, 0.0, 0.0)); + ctx.set_view(player, View::new(0.0, 0.0, 1000.0)); + ctx.send_event(player, 1, entity.to_le_bytes().to_vec()); + } + + fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, player: PlayerId, _reason: LeaveReason) { + self.avatars.remove(&player); + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option<(i8, i8)> { + match payload { + [dx, dy] => Some(((*dx as i8).clamp(-1, 1), (*dy as i8).clamp(-1, 1))), + _ => None, + } + } + + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + let dt = ctx.dt_secs(); + let players: Vec = self.avatars.keys().copied().collect(); + for player in players { + let inputs = ctx.take_inputs(player, ConsumePolicy::Drain); + if let Some(avatar) = self.avatars.get_mut(&player) { + for input in inputs { + avatar.1 += f32::from(input.input.0) * SPEED * dt; + avatar.2 += f32::from(input.input.1) * SPEED * dt; + } + } + } + } + + fn replicate(&self, out: &mut WorldView) { + for (entity, x, y) in self.avatars.values() { + out.push(EntityState::new( + *entity, + AVATAR, + *x, + *y, + vec![FieldValue::F(*x), FieldValue::F(*y), FieldValue::U(0)], + )); + } + } +} + +#[tokio::main] +async fn main() -> std::io::Result<()> { + let secret = std::env::var("DISTRIBUTED_GAME_SECRET").unwrap_or_else(|_| "dev-secret".into()); + let mut config = ServerConfig::new(TicketKey::new(secret)); + config.host.tick_rate = 30; + config.host.patch_rate = 20; + let server = GameServer::::new( + config, + ZoneFactory::sync(|a| a.zone_id.starts_with("arena-").then_some(())), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let addr = listener.local_addr()?; + println!("LISTENING ws://{addr}"); + std::io::stdout().flush()?; + let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>(); + std::thread::spawn(move || { + // Stop when the parent closes our stdin (or sends a line). + let mut line = String::new(); + let _ = std::io::stdin().lock().read_line(&mut line); + let _ = stop_tx.send(()); + }); + server + .serve(listener, async move { + let _ = stop_rx.await; + }) + .await +} diff --git a/distributed_game/src/admission.rs b/distributed_game/src/admission.rs new file mode 100644 index 000000000..cb262bad4 --- /dev/null +++ b/distributed_game/src/admission.rs @@ -0,0 +1,480 @@ +//! Admission, shared by every driver (the `net` server and celld zone +//! objects): what a Hello must prove before a connection may touch a zone, +//! and the per-connection gate every later client message passes. +//! +//! A driver reads the first frame within [`AdmissionConfig::hello_timeout`] +//! and calls [`admit`]: protocol version, then a reconnect token (checked +//! by the zone itself) or a ticket (signature or custom +//! [`TicketVerifier`](crate::ticket::TicketVerifier), expiry, a non-empty +//! principal and replay key, declared extension claims, the route zone). +//! The ticket's single use is recorded with [`Admitted::consume`] once the +//! driver's own checks passed (a transfer's reservation with its issuer, +//! for instance). Only an admitted Hello may activate or wake a zone. +//! +//! After the Welcome every client message but `Leave` goes through the +//! connection's [`InputGate`] (a token bucket): excess messages are +//! dropped (one `Error(RATE_LIMITED)` per second) and more than a burst +//! of drops within a second is kicked. Undecodable frames count too. +//! +//! Transport framing (WebSocket frames, Durable Object socket attachments), +//! transfer custody and zone placement stay with the drivers. + +use std::time::Duration; + +use crate::claims::{validate_extensions, ExtensionSchema}; +use crate::handoff::Transfer; +use crate::protocol::{error, Hello, PROTOCOL_VERSION}; +use crate::ticket::{ + NonceCache, SharedTicketVerifier, TicketError, TicketKey, TicketVerifier, VerifiedTicket, +}; +use crate::zone::TicketClaims; + +/// Admission settings of a driver. +#[derive(Debug, Clone)] +pub struct AdmissionConfig { + /// HMAC key of transfer tickets and, unless `verifier` is set, of join + /// tickets. + pub key: TicketKey, + /// Custom verifier for **join** tickets (e.g. the game's web-BFF JWTs); + /// `None` = HS256 tickets signed with `key`. Expiry, route zone and + /// single use are enforced either way. + pub verifier: Option, + /// Extension claims tickets may carry + /// ([`ExtensionSchema::of::()`](crate::ExtensionSchema::of) for a + /// `#[derive(TicketExtension)]` type). `None` = a ticket with any `ext` + /// claims is refused. Applies to join (any verifier) and transfer + /// tickets. + pub extensions: Option, + /// Deadline for the first (Hello) frame. + pub hello_timeout: Duration, + /// Sustained client messages per second per connection. + pub input_rate: f64, + /// Client message burst size. + pub input_burst: f64, +} + +impl AdmissionConfig { + /// Defaults with the given ticket key: 5 s Hello deadline, 120 + /// messages per second, bursts of 240. + pub fn new(key: TicketKey) -> Self { + Self { + key, + verifier: None, + extensions: None, + hello_timeout: Duration::from_secs(5), + input_rate: 120.0, + input_burst: 240.0, + } + } + + /// Admit join tickets with `verifier` instead of `key`. + pub fn with_ticket_verifier(mut self, verifier: impl TicketVerifier) -> Self { + self.verifier = Some(SharedTicketVerifier::new(verifier)); + self + } + + /// Admit ticket extension claims of type `E`. + pub fn with_ticket_extensions(mut self) -> Self { + self.extensions = Some(ExtensionSchema::of::()); + self + } +} + +/// An admitted Hello. +#[derive(Debug, Clone, PartialEq)] +pub enum Admitted { + /// A join ticket for this zone. + Join(TicketClaims), + /// A handoff transfer ticket arriving at its target zone. + Arrival(Transfer), + /// A refused handoff returning to its source zone: the ticket's zone + /// and source are swapped, so `claims.zone` is this zone. + Return(Transfer), + /// A reconnect token (the zone checks it). + Reconnect(String), +} + +impl Admitted { + /// The verified claims (`None` for a reconnect). + pub fn claims(&self) -> Option<&TicketClaims> { + match self { + Admitted::Join(claims) => Some(claims), + Admitted::Arrival(transfer) | Admitted::Return(transfer) => Some(&transfer.claims), + Admitted::Reconnect(_) => None, + } + } + + /// Record the ticket's single use in `nonces` (a return to the source + /// has its own replay key: the target may have recorded the nonce on + /// the same host). A reconnect has nothing to record. + pub fn consume(&self, nonces: &mut NonceCache, now_unix: u64) -> Result<(), Refusal> { + let Some(claims) = self.claims() else { + return Ok(()); + }; + let key = match self { + Admitted::Return(_) => format!("return:{}", claims.replay_key()), + _ => claims.replay_key().to_string(), + }; + nonces + .check_and_insert(&key, claims.expires_at, now_unix) + .map_err(Refusal::ticket) + } +} + +/// Why a Hello was refused: the `Error` frame to answer with. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Refusal { + /// [`error`] code. + pub code: u32, + /// Message. + pub message: String, +} + +impl Refusal { + /// A refusal with `code`. + pub fn new(code: u32, message: impl Into) -> Self { + Self { + code, + message: message.into(), + } + } + + /// `UNAUTHORIZED` for a ticket error. + pub fn ticket(error: TicketError) -> Self { + let code = match error { + TicketError::NonceCacheFull => error::ZONE_UNAVAILABLE, + _ => error::UNAUTHORIZED, + }; + Self::new(code, format!("{error:?}")) + } +} + +/// Check a Hello for `zone_id` at `now_unix` (seconds). Pure: nothing is +/// recorded (see [`Admitted::consume`]). +pub fn admit( + config: &AdmissionConfig, + hello: &Hello, + zone_id: &str, + now_unix: u64, +) -> Result { + // Refuse other versions before the ticket is touched (§6.0). + if hello.protocol_version != PROTOCOL_VERSION { + return Err(Refusal::new( + error::VERSION_MISMATCH, + format!( + "protocol {} unsupported (this server speaks {PROTOCOL_VERSION})", + hello.protocol_version + ), + )); + } + if !hello.reconnect_token.is_empty() { + return Ok(Admitted::Reconnect(hello.reconnect_token.clone())); + } + let other_zone = || Refusal::new(error::UNAUTHORIZED, "ticket is for another zone"); + match verify(config, &hello.ticket, zone_id, now_unix).map_err(Refusal::ticket)? { + VerifiedTicket::Join(claims) if claims.zone == zone_id => Ok(Admitted::Join(claims)), + VerifiedTicket::Join(_) => Err(other_zone()), + VerifiedTicket::Transfer(transfer) if transfer.claims.zone == zone_id => { + Ok(Admitted::Arrival(transfer)) + } + VerifiedTicket::Transfer(mut transfer) if transfer.source_zone == zone_id => { + let never_reached = std::mem::replace(&mut transfer.claims.zone, zone_id.to_string()); + transfer.source_zone = never_reached; + Ok(Admitted::Return(transfer)) + } + VerifiedTicket::Transfer(_) => Err(other_zone()), + } +} + +/// Transfer tickets always use `config.key`; join tickets go through the +/// configured verifier and are then checked for a principal, a replay key, +/// expiry and declared extensions. +fn verify( + config: &AdmissionConfig, + ticket: &str, + zone_id: &str, + now_unix: u64, +) -> Result { + let verified = match &config.verifier { + None => config.key.verify_ticket(ticket, now_unix)?, + Some(custom) => match config.key.verify_ticket(ticket, now_unix) { + Ok(VerifiedTicket::Transfer(transfer)) => VerifiedTicket::Transfer(transfer), + _ => VerifiedTicket::Join(custom.0.verify(ticket, zone_id, now_unix)?), + }, + }; + let claims = match &verified { + VerifiedTicket::Join(claims) => claims, + VerifiedTicket::Transfer(transfer) => &transfer.claims, + }; + if claims.principal.is_empty() { + return Err(TicketError::MissingClaim("sub")); + } + if claims.replay_key().is_empty() { + return Err(TicketError::MissingClaim("nonce")); + } + if claims.expires_at <= now_unix { + return Err(TicketError::Expired); + } + validate_extensions(config.extensions.as_ref(), &claims.extensions) + .map_err(|e| TicketError::Invalid(e.to_string()))?; + Ok(verified) +} + +/// What the gate does with one client message. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Gate { + /// Handle it. + Pass, + /// Drop it; `warn`: answer `Error(RATE_LIMITED)` (at most once per + /// second). + Drop { + /// Tell the client. + warn: bool, + }, + /// A flood (more than a burst dropped within a second): kick the + /// connection (`Kick(RATE_LIMITED)`). + Kick, +} + +/// Per-connection token bucket over every post-Hello client message. +/// Times are any monotonic clock (`Duration` since an origin of the +/// driver's choosing). +#[derive(Debug, Clone)] +pub struct InputGate { + tokens: f64, + rate: f64, + burst: f64, + last: Duration, + /// Start of the second the drops are counted in (and warned about + /// once); `None` before the first drop. + drop_window: Option, + dropped: u32, +} + +impl InputGate { + /// A full bucket at `now`. + pub fn new(config: &AdmissionConfig, now: Duration) -> Self { + Self { + tokens: config.input_burst, + rate: config.input_rate, + burst: config.input_burst, + last: now, + drop_window: None, + dropped: 0, + } + } + + /// Admit one message at `now`. More than a burst of drops within one + /// second is a kick, however the drops interleave with refills (a + /// flood is kicked at any delivery speed). + pub fn take(&mut self, now: Duration) -> Gate { + let elapsed = now.saturating_sub(self.last).as_secs_f64(); + self.tokens = (self.tokens + elapsed * self.rate).min(self.burst); + self.last = self.last.max(now); + if self.tokens >= 1.0 { + self.tokens -= 1.0; + return Gate::Pass; + } + let warn = self + .drop_window + .is_none_or(|start| now.saturating_sub(start) >= Duration::from_secs(1)); + if warn { + self.drop_window = Some(now); + self.dropped = 0; + } + self.dropped += 1; + if f64::from(self.dropped) > self.burst { + return Gate::Kick; + } + Gate::Drop { warn } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::protocol::Role; + + const ZONE: &str = "z1"; + + fn config() -> AdmissionConfig { + AdmissionConfig::new(TicketKey::new("admission-test-secret")) + } + + fn claims(zone: &str, nonce: &str) -> TicketClaims { + TicketClaims { + principal: "ana".into(), + zone: zone.into(), + expires_at: 2_000, + nonce: nonce.into(), + role: Role::Player, + name: None, + extensions: Default::default(), + wake: false, + } + } + + fn hello(ticket: String) -> Hello { + Hello { + protocol_version: PROTOCOL_VERSION, + ticket, + ..Hello::default() + } + } + + fn transfer(target: &str, source: &str) -> String { + config().key.sign_transfer(&Transfer { + claims: claims(target, "t1"), + source_zone: source.into(), + issuer: "host".into(), + generation: 1, + carried: vec![1], + departed_at_ms: 0, + }) + } + + #[test] + fn admits_join_arrival_return_and_reconnect() { + let c = config(); + let join = hello(c.key.sign(&claims(ZONE, "n1"))); + assert_eq!( + admit(&c, &join, ZONE, 1_000), + Ok(Admitted::Join(claims(ZONE, "n1"))) + ); + let arrival = admit(&c, &hello(transfer(ZONE, "z0")), ZONE, 1_000).unwrap(); + assert!(matches!(arrival, Admitted::Arrival(t) if t.source_zone == "z0")); + let back = admit(&c, &hello(transfer("z2", ZONE)), ZONE, 1_000).unwrap(); + assert!( + matches!(&back, Admitted::Return(t) if t.claims.zone == ZONE && t.source_zone == "z2") + ); + let token = Hello { + reconnect_token: "tok".into(), + ..hello(String::new()) + }; + assert_eq!( + admit(&c, &token, ZONE, 1_000), + Ok(Admitted::Reconnect("tok".into())) + ); + } + + #[test] + fn refuses_bad_tickets_before_anything_is_recorded() { + let c = config(); + let refused = |hello: Hello| admit(&c, &hello, ZONE, 1_000).unwrap_err().code; + assert_eq!(refused(hello("garbage".into())), error::UNAUTHORIZED); + let forged = TicketKey::new("another-key").sign(&claims(ZONE, "n1")); + assert_eq!(refused(hello(forged)), error::UNAUTHORIZED); + let expired = c.key.sign(&TicketClaims { + expires_at: 1_000, + ..claims(ZONE, "n1") + }); + assert_eq!(refused(hello(expired)), error::UNAUTHORIZED); + let elsewhere = c.key.sign(&claims("z9", "n1")); + assert_eq!(refused(hello(elsewhere)), error::UNAUTHORIZED); + assert_eq!( + refused(hello(transfer("z8", "z9"))), + error::UNAUTHORIZED, + "a transfer for neither end" + ); + for version in [PROTOCOL_VERSION - 1, PROTOCOL_VERSION + 1] { + let other = Hello { + protocol_version: version, + ..hello(c.key.sign(&claims(ZONE, "n1"))) + }; + assert_eq!(refused(other), error::VERSION_MISMATCH, "version {version}"); + } + let ext = c.key.sign(&TicketClaims { + extensions: crate::TicketExtensions::from_json(serde_json::json!({"team": 1})).unwrap(), + ..claims(ZONE, "n1") + }); + assert_eq!(refused(hello(ext)), error::UNAUTHORIZED, "undeclared ext"); + } + + #[test] + fn custom_verifiers_still_need_principal_nonce_and_expiry() { + let c = config().with_ticket_verifier(|_: &str, zone: &str, _: u64| { + Ok(TicketClaims { + nonce: String::new(), + ..claims(zone, "") + }) + }); + let refusal = admit(&c, &hello("anything".into()), ZONE, 1_000).unwrap_err(); + assert_eq!(refusal.code, error::UNAUTHORIZED); + assert!(refusal.message.contains("nonce"), "{refusal:?}"); + } + + #[test] + fn tickets_are_single_use_and_returns_have_their_own_key() { + let c = config(); + let mut nonces = NonceCache::default(); + let join = admit(&c, &hello(c.key.sign(&claims(ZONE, "t1"))), ZONE, 1_000).unwrap(); + join.consume(&mut nonces, 1_000).unwrap(); + assert_eq!( + join.consume(&mut nonces, 1_000).unwrap_err().code, + error::UNAUTHORIZED + ); + let back = admit(&c, &hello(transfer("z2", ZONE)), ZONE, 1_000).unwrap(); + back.consume(&mut nonces, 1_000).unwrap(); + assert!(back.consume(&mut nonces, 1_000).is_err()); + Admitted::Reconnect("x".into()) + .consume(&mut nonces, 1_000) + .unwrap(); + } + + #[test] + fn the_gate_drops_warns_once_a_second_and_kicks_a_flood() { + let c = AdmissionConfig { + input_rate: 10.0, + input_burst: 3.0, + ..config() + }; + let t = Duration::from_secs(100); + let mut gate = InputGate::new(&c, t); + for _ in 0..3 { + assert_eq!(gate.take(t), Gate::Pass); + } + assert_eq!(gate.take(t), Gate::Drop { warn: true }); + assert_eq!(gate.take(t), Gate::Drop { warn: false }); + // A token every 100 ms. + assert_eq!(gate.take(t + Duration::from_millis(100)), Gate::Pass); + assert_eq!( + gate.take(t + Duration::from_millis(100)), + Gate::Drop { warn: false } + ); + assert_eq!( + gate.take(t + Duration::from_millis(1_100)), + Gate::Pass, + "refilled" + ); + let later = t + Duration::from_millis(1_100); + for _ in 0..2 { + assert_eq!(gate.take(later), Gate::Pass); + } + assert_eq!(gate.take(later), Gate::Drop { warn: true }); + for _ in 0..2 { + assert_eq!(gate.take(later), Gate::Drop { warn: false }); + } + assert_eq!(gate.take(later), Gate::Kick, "more than a burst dropped"); + } + + #[test] + fn a_flood_interleaved_with_refills_is_kicked() { + let c = AdmissionConfig { + input_rate: 10.0, + input_burst: 3.0, + ..config() + }; + let t = Duration::from_secs(100); + let mut gate = InputGate::new(&c, t); + // A message every 20 ms: a token every 5th, which passes. + let kicked_at = + (0..50u64).position(|i| gate.take(t + Duration::from_millis(20 * i)) == Gate::Kick); + assert_eq!(kicked_at, Some(7), "3 burst, drops 1-2, a pass, drops 3-4"); + // Just over the rate for long stretches is dropped, never kicked. + let mut gate = InputGate::new(&c, t); + for i in 0..1_000u64 { + let got = gate.take(t + Duration::from_millis(90 * i)); + assert_ne!(got, Gate::Kick, "message {i}"); + } + } +} diff --git a/distributed_game/src/authoring.rs b/distributed_game/src/authoring.rs new file mode 100644 index 000000000..26bb51197 --- /dev/null +++ b/distributed_game/src/authoring.rs @@ -0,0 +1,186 @@ +//! Traits implemented by the authoring derives (`distributed_game_macros`, +//! re-exported from this crate): [`Replicated`] views, [`GameInput`] frames +//! and [`GameEvent`] messages. Implement them by hand only when a derive does +//! not fit; the derives keep the schema, the encoding and the surface in one +//! declaration so they cannot drift. + +use crate::codec::Wire; +use crate::protocol::wire::{DecodeError, Reader, Writer}; +use crate::replication::{EntityState, WorldView}; +use crate::schema::{FieldValue, KindDef}; +use crate::surface::{EventSurface, InputSurface, RecordSurface}; + +/// A struct describing one replicated entity kind (`#[derive(Replicated)]`). +/// +/// The derive generates the [`KindDef`] and the field values from the same +/// field list, so the schema order and the encoding order cannot drift. +pub trait Replicated { + /// Kind id. + const KIND_ID: u16; + /// Kind name. + const KIND_NAME: &'static str; + /// Every entity of this kind is visible to every client by default. + const GLOBAL: bool; + + /// The kind definition (field names, wire types, priorities, client + /// correction defaults). + fn kind_def() -> KindDef; + + /// Interest-plane position (the `x` / `y` fields unless overridden). + fn position(&self) -> (f32, f32); + + /// Append the field values in schema order to `out`. + fn write_fields(&self, out: &mut Vec); + + /// Field values in schema order. + fn field_values(&self) -> Vec { + let mut values = Vec::new(); + self.write_fields(&mut values); + values + } + + /// The entity for a [`WorldView`]. + fn entity(&self, id: u32) -> EntityState { + entity_with(self, id, self.field_values()) + } +} + +/// `view`'s entity `id` with `fields` (its field values). +fn entity_with(view: &R, id: u32, fields: Vec) -> EntityState { + let (x, y) = view.position(); + let mut entity = EntityState::new(id, R::KIND_ID, x, y, fields); + entity.global = R::GLOBAL; + entity +} + +/// Builds an [`EntitySchema`](crate::EntitySchema) from `Replicated` view +/// types, in order: `schema![PlayerView, DroneView]`. +#[macro_export] +macro_rules! schema { + ($($kind:ty),* $(,)?) => { + $crate::EntitySchema::new() + $(.kind(<$kind as $crate::Replicated>::kind_def()))* + }; +} + +/// Handle to an entity just pushed with [`WorldView::add`]. +#[derive(Debug)] +pub struct Pushed<'a>(&'a mut EntityState); + +impl Pushed<'_> { + /// Visible to every client regardless of view. + pub fn global(self) -> Self { + self.0.global = true; + self + } + + /// Only within views (overrides a `global` kind). + pub fn local(self) -> Self { + self.0.global = false; + self + } + + /// Priority multiplier for this entity. + pub fn priority(self, p: f32) -> Self { + self.0.priority = p; + self + } + + /// Interest-plane position override. + pub fn at(self, x: f32, y: f32) -> Self { + self.0.x = x; + self.0.y = y; + self + } +} + +impl WorldView { + /// Push entity `id` described by a `Replicated` view. Its field values + /// go into a vector the view kept from its last patch (the host reuses + /// one view), so numeric fields cost no allocation. + pub fn add(&mut self, id: impl Into, view: &R) -> Pushed<'_> { + let mut fields = self.spare_fields(); + view.write_fields(&mut fields); + self.push(entity_with(view, id.into().get(), fields)); + Pushed(self.last_mut().expect("just pushed")) + } +} + +/// A compact binary input frame (`#[derive(GameInput)]`). +/// +/// [`from_payload`](Self::from_payload) decodes **and sanitizes**, so a +/// zone's `decode_input` is a one-liner: +/// +/// ```ignore +/// fn decode_input(&self, _: PlayerId, payload: &[u8]) -> Option { +/// MoveInput::from_payload(payload) +/// } +/// ``` +pub trait GameInput: Sized { + /// Field layout (pushes any records it mentions). + fn input_surface(records: &mut Vec) -> InputSurface; + /// Append the raw encoding (no sanitizing). + fn encode_input(&self, w: &mut Writer); + /// Decode without sanitizing. + fn decode_input(r: &mut Reader<'_>) -> Result; + /// Clamp `#[range]` fields, clear unknown `#[buttons]` bits, reject + /// non-finite floats (`None` drops the input). + fn sanitize(self) -> Option; + + /// Encoded payload bytes. + fn to_payload(&self) -> Vec { + let mut w = Writer::new(); + self.encode_input(&mut w); + w.into_bytes() + } + + /// Decode exactly one frame (trailing bytes reject) and sanitize it. + fn from_payload(payload: &[u8]) -> Option { + let mut r = Reader::new(payload); + let input = Self::decode_input(&mut r).ok()?; + r.finish().ok()?; + input.sanitize() + } +} + +/// A reliable zone event with a stable type id (`#[derive(GameEvent)]` on a +/// struct, or on an enum whose variants are the zone's events). +/// +/// Send with [`Ctx::send`](crate::Ctx::send) / +/// [`Ctx::broadcast`](crate::Ctx::broadcast). +pub trait GameEvent: Sized { + /// Type id of this value. + fn event_id(&self) -> u32; + /// Append the payload encoding. + fn encode_payload(&self, w: &mut Writer); + /// Decode an Event message: `Ok(None)` when `type_id` is not one of + /// this type's events. + fn decode_event(type_id: u32, payload: &[u8]) -> Result, DecodeError>; + /// Every event this type declares (pushes any records they mention). + fn event_surfaces(records: &mut Vec) -> Vec; + + /// Encoded payload bytes. + fn to_payload(&self) -> Vec { + let mut w = Writer::new(); + self.encode_payload(&mut w); + w.into_bytes() + } +} + +/// Decode a whole event payload as `T` (generated code). +#[doc(hidden)] +pub fn decode_whole( + payload: &[u8], + decode: impl FnOnce(&mut Reader<'_>) -> Result, +) -> Result { + let mut r = Reader::new(payload); + let value = decode(&mut r)?; + r.finish()?; + Ok(value) +} + +/// Push `T`'s records (generated code). +#[doc(hidden)] +pub fn records_of(out: &mut Vec) { + T::records(out); +} diff --git a/distributed_game/src/bin/game-bots.rs b/distributed_game/src/bin/game-bots.rs new file mode 100644 index 000000000..a088753e7 --- /dev/null +++ b/distributed_game/src/bin/game-bots.rs @@ -0,0 +1,87 @@ +//! Load-test bots against a running `distributed_game` server. +//! +//! ```sh +//! cargo run -p distributed_game --features bots --bin game-bots -- \ +//! --url ws://127.0.0.1:2567 --zone room-1 --bots 50 --rate 20 --secs 10 \ +//! --secret dev-secret --behaviour circle +//! ``` +//! +//! Flags fall back to `DG_BOTS_URL`, `DG_BOTS_ZONE`, `DG_BOTS_COUNT`, +//! `DG_BOTS_RATE`, `DG_BOTS_SECS`, `DG_TICKET_SECRET`, `DG_BOTS_BEHAVIOUR`. +//! Inputs are encoded as an `(i8, i8)` direction pair. + +use std::time::Duration; + +use distributed_game::bots::{run_bots, BehaviourKind, BotConfig}; +use distributed_game::net::TicketKey; + +const USAGE: &str = "usage: game-bots [--url ws://host:port] [--zone id] [--bots n] [--rate hz] \ +[--secs s] [--ramp-ms ms] [--secret s] [--behaviour random|circle] [--prefix p]"; + +fn main() { + let mut args = std::env::args().skip(1); + let env = |k: &str, d: &str| std::env::var(k).unwrap_or_else(|_| d.to_string()); + let mut url = env("DG_BOTS_URL", "ws://127.0.0.1:2567"); + let mut zone = env("DG_BOTS_ZONE", "room-1"); + let mut bots = env("DG_BOTS_COUNT", "10"); + let mut rate = env("DG_BOTS_RATE", "20"); + let mut secs = env("DG_BOTS_SECS", "10"); + let mut ramp = String::from("0"); + let mut secret = env("DG_TICKET_SECRET", "dev-secret"); + let mut behaviour = env("DG_BOTS_BEHAVIOUR", "random"); + let mut prefix = String::from("bot"); + while let Some(flag) = args.next() { + let slot = match flag.as_str() { + "--url" => &mut url, + "--zone" => &mut zone, + "--bots" => &mut bots, + "--rate" => &mut rate, + "--secs" => &mut secs, + "--ramp-ms" => &mut ramp, + "--secret" => &mut secret, + "--behaviour" => &mut behaviour, + "--prefix" => &mut prefix, + _ => { + eprintln!("{USAGE}"); + std::process::exit(if flag == "--help" || flag == "-h" { + 0 + } else { + 2 + }); + } + }; + *slot = args.next().unwrap_or_else(|| { + eprintln!("{flag} needs a value\n{USAGE}"); + std::process::exit(2) + }); + } + let parse = |name: &str, v: &str| -> f64 { + v.parse().unwrap_or_else(|_| { + eprintln!("bad {name}: {v}"); + std::process::exit(2) + }) + }; + let kind = match behaviour.as_str() { + "random" => BehaviourKind::RandomWalk, + "circle" => BehaviourKind::Circle, + other => { + eprintln!("unknown behaviour {other}\n{USAGE}"); + std::process::exit(2) + } + }; + let mut config = BotConfig::new(url, zone, TicketKey::new(secret)); + config.bots = parse("bots", &bots) as usize; + config.input_rate = parse("rate", &rate); + config.duration = Duration::from_secs_f64(parse("secs", &secs)); + config.ramp_up = Duration::from_millis(parse("ramp-ms", &ramp) as u64); + config.principal_prefix = prefix; + let runtime = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .expect("tokio runtime"); + let summary = runtime.block_on(run_bots(config, move |i| kind.build(i))); + println!("{summary}"); + if summary.failed() > 0 { + std::process::exit(1); + } +} diff --git a/distributed_game/src/bots.rs b/distributed_game/src/bots.rs new file mode 100644 index 000000000..04f4ebe3a --- /dev/null +++ b/distributed_game/src/bots.rs @@ -0,0 +1,492 @@ +//! Load-test bots (`bots` feature). +//! +//! Each bot is a real WebSocket client speaking the binary protocol through +//! the reference [`ClientMirror`]: it mints a signed ticket with the +//! server's [`TicketKey`] (dev/test only — production tickets come from the +//! auth service), joins a zone, sends inputs at a fixed rate from a pluggable +//! [`Behaviour`], pings for RTT and counts Deltas/bytes. [`run_bots`] runs N +//! of them concurrently and returns a [`Summary`]. +//! +//! Inputs are game-defined bytes: a [`Behaviour`] yields a 2D direction and +//! an [`Encoder`] turns it into the zone's input payload +//! ([`encode_i8_pair`] matches a `(dx, dy): (i8, i8)` input). +//! +//! The `game-bots` binary wraps this for demos: +//! `cargo run -p distributed_game --features bots --bin game-bots -- --help`. + +use std::fmt; +use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use futures_util::{SinkExt, StreamExt}; +use tokio::time::Instant; +use tokio_tungstenite::tungstenite::Message; + +use crate::net::TicketKey; +use crate::protocol::{ClientMessage, ClientMirror, Hello, Role, ServerMessage, PROTOCOL_VERSION}; +use crate::rng::ZoneRng; +use crate::zone::TicketClaims; + +/// Produces a movement direction each input tick. +pub trait Behaviour: Send { + /// Direction for the input sent at `elapsed` since the bot joined. + fn direction(&mut self, elapsed: Duration, rng: &mut ZoneRng) -> [f32; 2]; +} + +/// Keeps a heading and occasionally picks a new random one. +#[derive(Debug, Clone)] +pub struct RandomWalk { + /// Probability per input of turning. + pub turn_chance: f32, + heading: [f32; 2], +} + +impl RandomWalk { + /// Walker turning with probability `turn_chance` per input. + pub fn new(turn_chance: f32) -> Self { + Self { + turn_chance, + heading: [0.0, 0.0], + } + } +} + +impl Behaviour for RandomWalk { + fn direction(&mut self, _elapsed: Duration, rng: &mut ZoneRng) -> [f32; 2] { + if self.heading == [0.0, 0.0] || rng.chance(self.turn_chance) { + let a = rng.next_f32() * std::f32::consts::TAU; + self.heading = [a.cos(), a.sin()]; + } + self.heading + } +} + +/// Walks in a circle with a fixed period. +#[derive(Debug, Clone, Copy)] +pub struct Circle { + /// Time for one full turn. + pub period: Duration, + /// Starting angle (radians). + pub phase: f32, +} + +impl Behaviour for Circle { + fn direction(&mut self, elapsed: Duration, _rng: &mut ZoneRng) -> [f32; 2] { + let turns = elapsed.as_secs_f32() / self.period.as_secs_f32().max(1e-3); + let a = self.phase + turns * std::f32::consts::TAU; + [-a.sin(), a.cos()] + } +} + +/// Built-in behaviour selector (binary, quick tests). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BehaviourKind { + /// [`RandomWalk`] turning 10% of inputs. + RandomWalk, + /// [`Circle`] with a 4 s period, phase spread by bot index. + Circle, +} + +impl BehaviourKind { + /// Behaviour for bot `index`. + pub fn build(self, index: usize) -> Box { + match self { + Self::RandomWalk => Box::new(RandomWalk::new(0.1)), + Self::Circle => Box::new(Circle { + period: Duration::from_secs(4), + phase: index as f32 * 0.7, + }), + } + } +} + +/// Direction → input payload. +pub type Encoder = Arc Vec + Send + Sync>; + +/// Encode as two `i8` in `[-1, 1]` (rounded). +pub fn encode_i8_pair(dir: [f32; 2]) -> Vec { + dir.iter() + .map(|v| v.round().clamp(-1.0, 1.0) as i8 as u8) + .collect() +} + +/// Bot run settings. +#[derive(Clone)] +pub struct BotConfig { + /// Server base URL, e.g. `ws://127.0.0.1:2567` (`{path}/{zone}` is + /// appended). + pub url: String, + /// Path the zone id is appended to: `/zones` on the `net` server and + /// whatever the worker routes to its zone objects on celld (Mob Pit: + /// `/zones` too). + pub path: String, + /// Zone to join. + pub zone: String, + /// Number of bots. + pub bots: usize, + /// Inputs per second per bot. + pub input_rate: f64, + /// Ping cadence (RTT samples). + pub ping_interval: Duration, + /// How long each bot stays after joining. + pub duration: Duration, + /// Spread connects uniformly over this window. + pub ramp_up: Duration, + /// Signs tickets (must match the server's key). + pub ticket_key: TicketKey, + /// Principal prefix (`{prefix}-{index}`). + pub principal_prefix: String, + /// Hello content version. + pub content_version: String, + /// Seed for behaviours. + pub seed: u64, + /// Payload encoder. + pub encoder: Encoder, +} + +impl BotConfig { + /// Defaults: 20 inputs/s, ping every 500 ms, 10 s, random-walk friendly + /// `i8` pair encoding. + pub fn new(url: impl Into, zone: impl Into, ticket_key: TicketKey) -> Self { + Self { + url: url.into(), + path: "/zones".into(), + zone: zone.into(), + bots: 10, + input_rate: 20.0, + ping_interval: Duration::from_millis(500), + duration: Duration::from_secs(10), + ramp_up: Duration::ZERO, + ticket_key, + principal_prefix: "bot".into(), + content_version: String::new(), + seed: 1, + encoder: Arc::new(encode_i8_pair), + } + } +} + +/// One bot's results. +#[derive(Debug, Clone, Default)] +pub struct BotStats { + /// Bot index. + pub index: usize, + /// Welcome received. + pub joined: bool, + /// Time from the start of the connect to the Welcome. + pub joined_after: Option, + /// Why it stopped early. + pub error: Option, + /// Deltas applied. + pub deltas: u64, + /// Delta bytes received. + pub delta_bytes: u64, + /// Inputs sent. + pub inputs_sent: u64, + /// Highest `ack_seq` seen. + pub last_ack: u32, + /// RTT samples. + pub rtts: Vec, + /// Entities in the mirror at the end. + pub entities: usize, + /// Time from Welcome to the end. + pub session: Duration, +} + +/// Aggregate of a run. +#[derive(Debug, Clone, Default)] +pub struct Summary { + /// Per-bot stats. + pub bots: Vec, + /// Wall time of the run. + pub elapsed: Duration, +} + +impl Summary { + /// Bots that received Welcome. + pub fn joined(&self) -> usize { + self.bots.iter().filter(|b| b.joined).count() + } + + /// Bots that stopped with an error. + pub fn failed(&self) -> usize { + self.bots.iter().filter(|b| b.error.is_some()).count() + } + + /// Fewest Deltas any bot received. + pub fn min_deltas(&self) -> u64 { + self.bots.iter().map(|b| b.deltas).min().unwrap_or(0) + } + + /// Total Deltas. + pub fn deltas(&self) -> u64 { + self.bots.iter().map(|b| b.deltas).sum() + } + + /// Total Delta bytes. + pub fn delta_bytes(&self) -> u64 { + self.bots.iter().map(|b| b.delta_bytes).sum() + } + + /// Delta bytes per second per bot (mean over bot sessions). + pub fn delta_bytes_per_sec_per_bot(&self) -> f64 { + let rates: Vec = self + .bots + .iter() + .filter(|b| !b.session.is_zero()) + .map(|b| b.delta_bytes as f64 / b.session.as_secs_f64()) + .collect(); + if rates.is_empty() { + 0.0 + } else { + rates.iter().sum::() / rates.len() as f64 + } + } + + /// RTT quantile `q` in `[0, 1]` over all samples. + pub fn rtt_quantile(&self, q: f64) -> Option { + let mut all: Vec = self.bots.iter().flat_map(|b| b.rtts.clone()).collect(); + if all.is_empty() { + return None; + } + all.sort(); + let i = ((all.len() - 1) as f64 * q.clamp(0.0, 1.0)).round() as usize; + Some(all[i]) + } + + /// Inputs sent. + pub fn inputs_sent(&self) -> u64 { + self.bots.iter().map(|b| b.inputs_sent).sum() + } +} + +impl fmt::Display for Summary { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let ms = |d: Option| { + d.map_or("-".into(), |d| format!("{:.1}ms", d.as_secs_f64() * 1e3)) + }; + writeln!( + f, + "bots: {} joined, {} failed, {} total in {:.1}s", + self.joined(), + self.failed(), + self.bots.len(), + self.elapsed.as_secs_f64() + )?; + writeln!( + f, + "deltas: {} total, min/bot {}, {:.0} B/s/bot, {} bytes", + self.deltas(), + self.min_deltas(), + self.delta_bytes_per_sec_per_bot(), + self.delta_bytes() + )?; + writeln!(f, "inputs sent: {}", self.inputs_sent())?; + write!( + f, + "rtt: p50 {} p95 {} max {}", + ms(self.rtt_quantile(0.5)), + ms(self.rtt_quantile(0.95)), + ms(self.rtt_quantile(1.0)) + )?; + for b in self.bots.iter().filter(|b| b.error.is_some()).take(5) { + write!( + f, + "\n bot {}: {}", + b.index, + b.error.as_deref().unwrap_or("") + )?; + } + Ok(()) + } +} + +/// Run `config.bots` bots concurrently; `behaviour(index)` builds each one. +pub async fn run_bots( + config: BotConfig, + behaviour: impl Fn(usize) -> Box, +) -> Summary { + let started = Instant::now(); + let n = config.bots; + let config = Arc::new(config); + let mut tasks = Vec::with_capacity(n); + for index in 0..n { + let delay = if n > 1 { + config.ramp_up.mul_f64(index as f64 / (n - 1) as f64) + } else { + Duration::ZERO + }; + let behaviour = behaviour(index); + let config = config.clone(); + tasks.push(tokio::spawn(async move { + tokio::time::sleep(delay).await; + run_bot(&config, index, behaviour).await + })); + } + let mut bots = Vec::with_capacity(n); + for (index, task) in tasks.into_iter().enumerate() { + bots.push(task.await.unwrap_or_else(|e| BotStats { + index, + error: Some(format!("task: {e}")), + ..BotStats::default() + })); + } + Summary { + bots, + elapsed: started.elapsed(), + } +} + +/// Run one bot to completion. +pub async fn run_bot( + config: &BotConfig, + index: usize, + mut behaviour: Box, +) -> BotStats { + let mut stats = BotStats { + index, + ..BotStats::default() + }; + if let Err(e) = drive(config, index, behaviour.as_mut(), &mut stats).await { + stats.error = Some(e); + } + stats +} + +async fn drive( + config: &BotConfig, + index: usize, + behaviour: &mut dyn Behaviour, + stats: &mut BotStats, +) -> Result<(), String> { + let unix = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()); + let principal = format!("{}-{index}", config.principal_prefix); + let ticket = config.ticket_key.sign(&TicketClaims { + principal: principal.clone(), + zone: config.zone.clone(), + expires_at: unix + 3600, + nonce: format!("{principal}-{}-{}", config.seed, unix), + role: Role::Player, + name: None, + extensions: Default::default(), + wake: false, + }); + let started = Instant::now(); + let url = format!( + "{}/{}/{}", + config.url.trim_end_matches('/'), + config.path.trim_matches('/'), + config.zone + ); + let (mut ws, _) = tokio_tungstenite::connect_async(url.as_str()) + .await + .map_err(|e| format!("connect: {e}"))?; + let hello = ClientMessage::Hello(Hello { + protocol_version: PROTOCOL_VERSION, + content_version: config.content_version.clone(), + capabilities: 0, + ticket, + reconnect_token: String::new(), + near: false, + }); + ws.send(Message::Binary(hello.encode().into())) + .await + .map_err(|e| format!("hello: {e}"))?; + + let mut mirror = ClientMirror::new(); + let mut rng = ZoneRng::for_zone(config.seed ^ index as u64, &config.zone); + let origin = Instant::now(); + let mut joined_at: Option = None; + let mut seq = 0u32; + let input_every = Duration::from_secs_f64(1.0 / config.input_rate.max(0.01)); + let mut next_input = Instant::now(); + let mut next_ping = Instant::now(); + let end_of = |joined: Instant| joined + config.duration; + let connect_deadline = origin + Duration::from_secs(10); + + loop { + let now = Instant::now(); + let deadline = joined_at.map_or(connect_deadline, end_of); + if now >= deadline { + if joined_at.is_none() { + return Err("no Welcome".into()); + } + break; + } + let wake = if joined_at.is_some() { + next_input.min(next_ping).min(deadline) + } else { + deadline + }; + tokio::select! { + msg = ws.next() => { + let bytes = match msg { + Some(Ok(Message::Binary(b))) => b, + Some(Ok(Message::Close(Some(frame)))) => { + return Err(format!("closed by server ({} {})", u16::from(frame.code), frame.reason)) + } + Some(Ok(Message::Close(None))) | None => return Err("closed by server".into()), + Some(Ok(_)) => continue, + Some(Err(e)) => return Err(format!("recv: {e}")), + }; + match mirror.apply(&bytes).map_err(|e| format!("decode: {e}"))? { + ServerMessage::Welcome(_) => { + stats.joined = true; + let now = Instant::now(); + stats.joined_after = Some(now - started); + joined_at = Some(now); + next_input = now; + next_ping = now; + } + ServerMessage::Delta(d) => { + stats.deltas += 1; + stats.delta_bytes += bytes.len() as u64; + stats.last_ack = stats.last_ack.max(d.ack_seq); + } + ServerMessage::Pong { client_time, .. } => { + let now_ms = origin.elapsed().as_secs_f64() * 1e3; + stats.rtts.push(Duration::from_secs_f64(((now_ms - client_time) / 1e3).max(0.0))); + } + ServerMessage::Kick { code, message } => return Err(format!("kicked {code}: {message}")), + ServerMessage::Error { code, message } if !stats.joined => { + return Err(format!("refused {code}: {message}")); + } + _ => {} + } + } + _ = tokio::time::sleep_until(wake) => { + let Some(joined) = joined_at else { continue }; + let now = Instant::now(); + if now >= next_input { + seq += 1; + let dir = behaviour.direction(now - joined, &mut rng); + let input = ClientMessage::Input { + seq, + client_tick: mirror.server_tick, + payload: (config.encoder)(dir), + }; + ws.send(Message::Binary(input.encode().into())).await.map_err(|e| format!("send: {e}"))?; + stats.inputs_sent += 1; + next_input += input_every; + if next_input < now { + next_input = now + input_every; + } + } + if now >= next_ping { + let ping = ClientMessage::Ping { client_time: origin.elapsed().as_secs_f64() * 1e3 }; + ws.send(Message::Binary(ping.encode().into())).await.map_err(|e| format!("ping: {e}"))?; + next_ping = now + config.ping_interval; + } + } + } + } + stats.session = joined_at.map_or(Duration::ZERO, |j| j.elapsed()); + stats.entities = mirror.entities.len(); + let _ = ws + .send(Message::Binary(ClientMessage::Leave.encode().into())) + .await; + let _ = ws.close(None).await; + Ok(()) +} diff --git a/distributed_game/src/cell.rs b/distributed_game/src/cell.rs new file mode 100644 index 000000000..3a105e4f9 --- /dev/null +++ b/distributed_game/src/cell.rs @@ -0,0 +1,188 @@ +//! Helpers for committing facts as idempotent commands into a +//! `distributed` [`AggregateCell`](distributed::cell_host::AggregateCell) +//! (the sinks themselves are `CommandFactSink` and `CelldFactSink`): +//! +//! - the principal comes **only** from [`Fact::principal`] — bound by the +//! host from the player's verified ticket — or a system principal for +//! zone facts; client payloads never supply identity; +//! - [`trusted_session`] builds the server-side [`Session`] (`x-user-id` = +//! principal, plus the [`FactStamp`](crate::FactStamp) as `x-game-*` +//! variables so handlers can [`stamp_metadata`](crate::stamp_metadata) +//! their events); +//! - [`command_id_for`] derives a deterministic UUIDv7-shaped command id +//! from `sha256(service_id ‖ 0x00 ‖ fact key)`, so retries and +//! re-emissions of the same key replay through the cell's command ledger +//! instead of committing twice; +//! - [`run_fact_batch`] answers a celld object host's fact batch. + +use distributed::cell_host::{ + AggregateCell, CausalDispatchError, CellBatchCommand, CellCommandIdentity, CellWaitPathRequest, +}; +use distributed::microsvc::Session; +use distributed::Aggregate; +use distributed::USER_ID_KEY; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; + +use crate::facts::Fact; + +/// Deterministic UUIDv7-shaped command id for a fact key. +pub fn command_id_for(service_id: &str, key: &str) -> String { + let mut hasher = Sha256::new(); + hasher.update(service_id.as_bytes()); + hasher.update([0u8]); + hasher.update(key.as_bytes()); + let digest = hasher.finalize(); + let mut b = [0u8; 16]; + b.copy_from_slice(&digest[..16]); + b[6] = (b[6] & 0x0f) | 0x70; + b[8] = (b[8] & 0x3f) | 0x80; + let hex: String = b.iter().map(|x| format!("{x:02x}")).collect(); + format!( + "{}-{}-{}-{}-{}", + &hex[0..8], + &hex[8..12], + &hex[12..16], + &hex[16..20], + &hex[20..32] + ) +} + +/// Trusted session for a fact: principal + stamp. +pub fn trusted_session(principal: &str, fact: &Fact) -> Session { + let mut session = Session::new(); + session.set(USER_ID_KEY, principal); + for (key, value) in fact.stamp().session_vars() { + session.set(key, value); + } + session +} + +/// The trusted session of a fact received by a celld cell over the internal +/// path ([`crate::celld::CelldFactSink`]): `x-user-id` plus the `x-game-*` +/// stamp headers. `header` reads one request header. Call it only after the +/// request authenticated with `DISTRIBUTED_INTERNAL_SECRET`; returns `None` +/// when the principal or a stamp field is missing (not a fact request). +pub fn fact_session_from_headers(header: impl Fn(&str) -> Option) -> Option { + let principal = header(USER_ID_KEY).filter(|value| !value.is_empty())?; + let mut vars = std::collections::HashMap::new(); + for (name, _) in crate::FactStamp::default().session_vars() { + vars.insert(name.clone(), header(&name)?); + } + let stamp = crate::FactStamp::from_session_vars(&vars)?; + let mut session = Session::new(); + session.set(USER_ID_KEY, principal); + for (key, value) in stamp.session_vars() { + session.set(key, value); + } + Some(session) +} + +/// The [`FactStamp`](crate::FactStamp) a [`trusted_session`] carries +/// (None for a session that did not come from a fact). Handlers use it to +/// order facts ([`FactStamp::emission_order`](crate::FactStamp::emission_order)) +/// and to [`stamp_metadata`](crate::stamp_metadata) their events. +pub fn session_stamp(session: &Session) -> Option { + crate::FactStamp::from_session_vars(session.variables()) +} + +/// Run a fact batch (`POST /{kind}/{shard}/__batch`, the celld object +/// host's batch request) against `cell`: `{ entries: [{ command, +/// commandId, input, partition, session }] }` → `{ results: [{ status, +/// body }] }`, each body as the entry's own wait-path response. Every entry +/// gets its own ledger id (`service` + `partition` + `commandId`) and its +/// session from its `session` variables through `sessions`, and runs in +/// order ([`AggregateCell::dispatch_idempotent_batch`]); the results end at +/// the first retryable one. Call it only after the request authenticated +/// with `DISTRIBUTED_INTERNAL_SECRET`. +pub async fn run_fact_batch( + cell: &AggregateCell, + service: &str, + body: &Value, + sessions: impl Fn(&dyn Fn(&str) -> Option) -> Option, +) -> Result +where + A: Aggregate + Send + Sync + 'static, +{ + let entries = body + .get("entries") + .and_then(Value::as_array) + .ok_or_else(|| CausalDispatchError::BadRequest("`entries` is required".into()))?; + // An entry that does not parse never reaches the cell; it is answered + // in its place. + let mut refused = Vec::with_capacity(entries.len()); + let mut commands = Vec::with_capacity(entries.len()); + for entry in entries { + match batch_command(service, entry, &sessions) { + Ok(command) => { + commands.push(command); + refused.push(None); + } + Err(error) => refused.push(Some(error)), + } + } + let mut dispatched = cell.dispatch_idempotent_batch(commands).await.into_iter(); + let mut results = Vec::with_capacity(entries.len()); + for refused in refused { + let result = match refused { + Some(error) => Err(error), + None => match dispatched.next() { + Some(result) => result.map(|dispatch| dispatch.wait_path_wire()), + // Not attempted: an earlier entry ended the batch. + None => break, + }, + }; + let (status, body) = match result { + Ok(body) => (200, body), + Err(error) => ( + error.status_code(), + json!({ "error": error.client_message(), "code": error.code() }), + ), + }; + let retryable = status >= 500 + || matches!(status, 408 | 429) + || body.get("code").and_then(Value::as_str) == Some("COMMAND_IN_PROGRESS"); + results.push(json!({ "status": status, "body": body })); + if retryable { + break; + } + } + Ok(json!({ "results": results })) +} + +/// One `__batch` entry as its own wait-path command. +fn batch_command( + service: &str, + entry: &Value, + sessions: &impl Fn(&dyn Fn(&str) -> Option) -> Option, +) -> Result { + let field = |name: &str| entry.get(name).and_then(Value::as_str); + let (Some(command), Some(partition)) = (field("command"), field("partition")) else { + return Err(CausalDispatchError::BadRequest( + "`command` and `partition` are required".into(), + )); + }; + let parsed = CellWaitPathRequest::parse(json!({ + "commandId": entry.get("commandId"), + "input": entry.get("input"), + })) + .map_err(CausalDispatchError::BadRequest)?; + let identity = CellCommandIdentity::new( + service.to_string(), + partition.to_string(), + &parsed.command_id, + )?; + let vars = entry.get("session").and_then(Value::as_object); + let header = |name: &str| { + vars.and_then(|vars| vars.get(name)) + .and_then(Value::as_str) + .map(str::to_string) + }; + let session = sessions(&header).ok_or(CausalDispatchError::Forbidden)?; + Ok(CellBatchCommand { + command: command.to_string(), + identity, + input: parsed.input, + session, + }) +} diff --git a/distributed_game/src/celld.rs b/distributed_game/src/celld.rs new file mode 100644 index 000000000..7d51654b6 --- /dev/null +++ b/distributed_game/src/celld.rs @@ -0,0 +1,453 @@ +//! A zone server's celld clients: [`CelldFactSink`] (facts as commands to +//! the durable aggregates in celld cells, game-services decision D3: the +//! [`CommandFactSink`](crate::command_sink::CommandFactSink) over a +//! remote-only `CelldCommandHost`), [`CellZoneOwnership`] (zone leases) and +//! [`CellZoneStateStore`] (hibernation snapshots). + +pub use crate::command_sink::{CelldFactSink, FactRoute, DEFAULT_CELLD_FACT_TIMEOUT}; + +use std::time::Duration; + +use distributed::cell_host::{ + InternalHttpSecret, CELL_INTERNAL_SECRET_HEADER, CELL_PRINCIPAL_PARTITION_HEADER, + CELL_SERVICE_ID_HEADER, +}; +use distributed::USER_ID_KEY; +use serde_json::{json, Value}; + +use crate::facts::BoxFuture; + +/// Path segments are non-empty, short, and printable. +fn valid_segment(segment: &str) -> bool { + !segment.is_empty() + && segment.len() <= 256 + && segment.bytes().all(|byte| (0x21..=0x7e).contains(&byte)) +} + +fn encode_segment(segment: &str) -> String { + let mut encoded = String::with_capacity(segment.len()); + for byte in segment.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~' | b':') { + encoded.push(byte as char); + } else { + encoded.push_str(&format!("%{byte:02X}")); + } + } + encoded +} + +/// [`ZoneOwnership`](crate::world::ZoneOwnership) over celld +/// `ZoneLease:{zone_id}` cells ([`crate::world::zone_lease`]): zone servers +/// acquire, renew and release over the internal path, and the cell's alarm +/// declares expiry (`zone.lease_expired`) when a holder stops renewing, so +/// services see a crashed zone server. +/// +/// Every call uses a fresh command id. A retried `acquire` by the same +/// holder returns its existing claim, so an ambiguous response is safe. +#[derive(Clone)] +pub struct CellZoneOwnership { + client: reqwest::Client, + base: String, + secret: InternalHttpSecret, + service_id: String, + host: String, + kind: String, +} + +/// Cell kind (URL segment) of zone-lease cells. +pub const ZONE_LEASE_KIND: &str = "zone-lease"; + +impl CellZoneOwnership { + /// Ownership for zone server `host` (its internal identity) against + /// `celld_url`, under command-ledger `service_id`. + pub fn new( + celld_url: impl Into, + secret: InternalHttpSecret, + service_id: impl Into, + host: impl Into, + ) -> Result { + let base = celld_url.into().trim_end_matches('/').to_string(); + if !(base.starts_with("http://") || base.starts_with("https://")) { + return Err(format!("celld URL must be http(s): {base}")); + } + let service_id = service_id.into(); + let host = host.into(); + if service_id.trim().is_empty() || host.trim().is_empty() { + return Err("cell zone ownership needs a service id and a host identity".into()); + } + let client = reqwest::Client::builder() + .timeout(DEFAULT_CELLD_FACT_TIMEOUT) + .redirect(reqwest::redirect::Policy::none()) + .build() + .map_err(|error| format!("celld ownership client: {error}"))?; + Ok(Self { + client, + base, + secret, + service_id, + host, + kind: ZONE_LEASE_KIND.to_string(), + }) + } + + async fn call( + &self, + zone_id: &str, + command: &str, + input: Value, + ) -> Result { + use crate::world::zone_lease::ZONE_HOST_ROLE; + use crate::world::OwnershipError; + if !valid_segment(zone_id) { + return Err(OwnershipError::Backend(format!( + "invalid zone id `{zone_id}`" + ))); + } + let url = format!( + "{}/{}/{}/{}", + self.base, + encode_segment(&self.kind), + encode_segment(zone_id), + encode_segment(command) + ); + let response = self + .client + .post(&url) + .header(CELL_INTERNAL_SECRET_HEADER, self.secret.header_value()) + .header(CELL_SERVICE_ID_HEADER, &self.service_id) + .header(CELL_PRINCIPAL_PARTITION_HEADER, &self.host) + .header(USER_ID_KEY, &self.host) + .header(distributed::microsvc::ROLE_KEY, ZONE_HOST_ROLE) + .json(&json!({ + "commandId": uuid::Uuid::now_v7().hyphenated().to_string(), + "input": input, + })) + .send() + .await + .map_err(|error| OwnershipError::Backend(format!("celld unreachable: {error}")))?; + let status = response.status().as_u16(); + let body: Value = response.json().await.unwrap_or(Value::Null); + if (200..300).contains(&status) { + return serde_json::from_value(body.get("payload").cloned().unwrap_or(Value::Null)) + .map_err(|error| OwnershipError::Backend(format!("bad claim payload: {error}"))); + } + let message = body.get("error").and_then(Value::as_str).unwrap_or(""); + Err(match crate::world::zone_lease::ownership_error(message) { + OwnershipError::Backend(message) => { + OwnershipError::Backend(format!("HTTP {status}: {message}")) + } + error => error, + }) + } +} + +fn claim_of(payload: crate::world::zone_lease::ClaimPayload) -> crate::world::ZoneClaim { + crate::world::ZoneClaim { + zone_id: payload.zone_id, + holder: payload.holder, + token: payload.token, + expires_at: std::time::SystemTime::UNIX_EPOCH + + Duration::from_millis(payload.expires_at_ms), + } +} + +fn ttl_ms(ttl: Duration) -> u64 { + u64::try_from(ttl.as_millis()).unwrap_or(u64::MAX).max(1) +} + +impl crate::world::ZoneOwnership for CellZoneOwnership { + fn acquire<'a>( + &'a self, + zone_id: &'a str, + holder: &'a str, + ttl: Duration, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + self.call( + zone_id, + crate::world::zone_lease::ACQUIRE, + json!({ "zone_id": zone_id, "holder": holder, "ttl_ms": ttl_ms(ttl) }), + ) + .await + .map(claim_of) + }) + } + + fn renew<'a>( + &'a self, + claim: &'a crate::world::ZoneClaim, + ttl: Duration, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + self.call( + &claim.zone_id, + crate::world::zone_lease::RENEW, + json!({ + "zone_id": claim.zone_id, + "holder": claim.holder, + "token": claim.token, + "ttl_ms": ttl_ms(ttl), + }), + ) + .await + .map(claim_of) + }) + } + + fn release<'a>(&'a self, claim: &'a crate::world::ZoneClaim) -> BoxFuture<'a, ()> { + Box::pin(async move { + let _ = self + .call( + &claim.zone_id, + crate::world::zone_lease::RELEASE, + json!({ "zone_id": claim.zone_id, "holder": claim.holder, "token": claim.token }), + ) + .await; + }) + } +} + +/// [`ZoneStateStore`](crate::world::ZoneStateStore) over celld +/// `ZoneState:{zone_id}` cells ([`crate::world::zone_state`]): hibernation +/// snapshots of a zone server live in one celld cell per zone (inline below +/// [`ZONE_STATE_INLINE_MAX`](crate::world::zone_state::ZONE_STATE_INLINE_MAX), +/// in celld's object storage above it), fenced by the ownership token. +/// +/// Every write uses a fresh command id: a retried save under the same token +/// is accepted again (equal tokens are allowed), so an ambiguous response is +/// safe. +#[derive(Clone)] +pub struct CellZoneStateStore { + client: reqwest::Client, + base: String, + secret: InternalHttpSecret, + service_id: String, + host: String, +} + +/// Cell kind (URL segment) of zone-state cells. +pub const ZONE_STATE_KIND: &str = "zone-state"; + +impl CellZoneStateStore { + /// Store for zone server `host` against `celld_url`, under + /// command-ledger `service_id`. + pub fn new( + celld_url: impl Into, + secret: InternalHttpSecret, + service_id: impl Into, + host: impl Into, + ) -> Result { + let base = celld_url.into().trim_end_matches('/').to_string(); + if !(base.starts_with("http://") || base.starts_with("https://")) { + return Err(format!("celld URL must be http(s): {base}")); + } + let service_id = service_id.into(); + let host = host.into(); + if service_id.trim().is_empty() || host.trim().is_empty() { + return Err("cell zone state needs a service id and a host identity".into()); + } + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(30)) + .redirect(reqwest::redirect::Policy::none()) + .build() + .map_err(|error| format!("celld zone-state client: {error}"))?; + Ok(Self { + client, + base, + secret, + service_id, + host, + }) + } + + fn url( + &self, + zone_id: &str, + command: Option<&str>, + ) -> Result { + if !valid_segment(zone_id) { + return Err(crate::world::StateError::Backend(format!( + "invalid zone id `{zone_id}`" + ))); + } + let mut url = format!( + "{}/{}/{}", + self.base, + encode_segment(ZONE_STATE_KIND), + encode_segment(zone_id) + ); + if let Some(command) = command { + url.push('/'); + url.push_str(&encode_segment(command)); + } + Ok(url) + } + + async fn command( + &self, + zone_id: &str, + command: &str, + input: Value, + ) -> Result<(), crate::world::StateError> { + use crate::world::zone_lease::ZONE_HOST_ROLE; + use crate::world::StateError; + let url = self.url(zone_id, Some(command))?; + let token = input.get("token").and_then(Value::as_u64).unwrap_or(0); + let response = self + .client + .post(&url) + .header(CELL_INTERNAL_SECRET_HEADER, self.secret.header_value()) + .header(CELL_SERVICE_ID_HEADER, &self.service_id) + .header(CELL_PRINCIPAL_PARTITION_HEADER, &self.host) + .header(USER_ID_KEY, &self.host) + .header(distributed::microsvc::ROLE_KEY, ZONE_HOST_ROLE) + .json(&json!({ + "commandId": uuid::Uuid::now_v7().hyphenated().to_string(), + "input": input, + })) + .send() + .await + .map_err(|error| StateError::Backend(format!("celld unreachable: {error}")))?; + let status = response.status().as_u16(); + let body: Value = response.json().await.unwrap_or(Value::Null); + if (200..300).contains(&status) { + return Ok(()); + } + let message = body.get("error").and_then(Value::as_str).unwrap_or(""); + match crate::world::zone_state::stale_current(message) { + Some(current) => Err(StateError::Stale { + presented: token, + current, + }), + None => Err(StateError::Backend(format!("HTTP {status}: {message}"))), + } + } +} + +impl crate::world::ZoneStateStore for CellZoneStateStore { + fn load<'a>( + &'a self, + zone_id: &'a str, + ) -> BoxFuture<'a, Result, crate::world::StateError>> + { + use crate::world::StateError; + Box::pin(async move { + use base64::Engine as _; + let url = self.url(zone_id, None)?; + let response = self + .client + .get(&url) + .header(CELL_INTERNAL_SECRET_HEADER, self.secret.header_value()) + .send() + .await + .map_err(|error| StateError::Backend(format!("celld unreachable: {error}")))?; + let status = response.status().as_u16(); + let body: Value = response.json().await.unwrap_or(Value::Null); + if !(200..300).contains(&status) { + return Err(StateError::Backend(format!("HTTP {status}: {body}"))); + } + let Some(state) = body.get("state").filter(|state| !state.is_null()) else { + return Ok(None); + }; + let field = |name: &str| { + state + .get(name) + .ok_or_else(|| StateError::Backend(format!("zone state without `{name}`"))) + }; + let bytes = base64::engine::general_purpose::STANDARD + .decode(field("state_b64")?.as_str().unwrap_or_default()) + .map_err(|_| StateError::Backend("zone state is not base64".into()))?; + Ok(Some(crate::world::StoredZoneState { + token: field("token")?.as_u64().unwrap_or(0), + content_version: field("content_version")? + .as_str() + .unwrap_or_default() + .to_string(), + state: bytes, + })) + }) + } + + fn save<'a>( + &'a self, + zone_id: &'a str, + state: &'a crate::world::StoredZoneState, + ) -> BoxFuture<'a, Result<(), crate::world::StateError>> { + Box::pin(async move { + use base64::Engine as _; + self.command( + zone_id, + crate::world::zone_state::SAVE, + json!({ + "zone_id": zone_id, + "token": state.token, + "content_version": state.content_version, + "state_b64": base64::engine::general_purpose::STANDARD.encode(&state.state), + }), + ) + .await + }) + } + + fn delete<'a>( + &'a self, + zone_id: &'a str, + token: u64, + ) -> BoxFuture<'a, Result<(), crate::world::StateError>> { + Box::pin(async move { + self.command( + zone_id, + crate::world::zone_state::DELETE, + json!({ "zone_id": zone_id, "token": token }), + ) + .await + }) + } +} + +#[cfg(test)] +mod tests { + use crate::facts::Fact; + use crate::stamp::FactStamp; + use distributed::USER_ID_KEY; + use serde_json::json; + + #[test] + fn the_cell_rebuilds_the_trusted_fact_session_from_the_headers() { + let stamp = FactStamp { + zone_id: "pit-1".into(), + tick: 42, + content_version: "c1".into(), + emitted_at_ms: 1_700_000_000_000, + activation: 3, + config_version: "cfg-2".into(), + seq: 5, + }; + let fact = Fact::trusted( + "k", + "crawler.record_kill", + json!({}), + Some("alice".into()), + stamp.clone(), + ); + // Exactly the headers `commit` sends (besides the internal ones). + let mut headers = std::collections::HashMap::new(); + headers.insert(USER_ID_KEY.to_string(), "alice".to_string()); + for (name, value) in fact.stamp().session_vars() { + headers.insert(name, value); + } + let session = + crate::cell::fact_session_from_headers(|name| headers.get(name).cloned()).unwrap(); + assert_eq!(session.user_id(), Some("alice")); + assert_eq!(crate::cell::session_stamp(&session), Some(stamp)); + headers.remove("x-game-tick"); + assert!( + crate::cell::fact_session_from_headers(|name| headers.get(name).cloned()).is_none() + ); + headers.insert("x-game-tick".into(), "42".into()); + headers.remove(USER_ID_KEY); + assert!( + crate::cell::fact_session_from_headers(|name| headers.get(name).cloned()).is_none() + ); + } +} diff --git a/distributed_game/src/celld_zone/cells.rs b/distributed_game/src/celld_zone/cells.rs new file mode 100644 index 000000000..dd5287eef --- /dev/null +++ b/distributed_game/src/celld_zone/cells.rs @@ -0,0 +1,651 @@ +//! Serving fact cells next to celld zones (wasm32): the internal wait-path +//! route every fact cell of a game worker needs, watched world cells +//! ([`CellWatchers`]), and the zone-activity cell. + +use std::cell::RefCell; + +use distributed::cell_host::{ + AggregateCell, CausalDispatchError, CellCommandIdentity, CellWaitPathRequest, CelldOutbox, + InternalHttpSecret, CELL_INTERNAL_SECRET_ENV, CELL_INTERNAL_SECRET_HEADER, + CELL_PRINCIPAL_PARTITION_HEADER, CELL_SERVICE_ID_HEADER, +}; +use distributed::microsvc::Session; +use distributed::Aggregate; +use serde_json::{json, Value}; +use worker::{Delay, Env, Headers, Method, Request, RequestInit, Response, Result, State}; + +use crate::cell::{fact_session_from_headers, run_fact_batch}; +use crate::world::content_rollout::{mount_content_rollout, ContentRollout}; +use crate::world::watch::{ + parse_watcher_address, push_retryable, topic, watch_query, WatchUpdate, Watchers, + PUSH_CONCURRENCY, PUSH_RETRY_MS, PUSH_ROUTE, STATS_ROUTE, +}; +use crate::world::zone_activity::{mount_zone_activity, ZoneActivity}; + +/// Builds the handler session from trusted request headers (after the +/// internal secret was checked); `None` refuses the command. +pub type Sessions = fn(&dyn Fn(&str) -> Option) -> Option; + +/// Facts only: the principal and the `x-game-*` stamp +/// ([`fact_session_from_headers`]). +pub fn fact_sessions(header: &dyn Fn(&str) -> Option) -> Option { + fact_session_from_headers(header) +} + +/// Check `x-distributed-internal-secret` against +/// `DISTRIBUTED_INTERNAL_SECRET`. +pub fn authenticate(req: &Request, env: &Env) -> std::result::Result<(), CausalDispatchError> { + let configured = env + .secret(CELL_INTERNAL_SECRET_ENV) + .map(|value| value.to_string()) + .or_else(|_| { + env.var(CELL_INTERNAL_SECRET_ENV) + .map(|value| value.to_string()) + }) + .map_err(|_| CausalDispatchError::Internal("internal secret is required".into()))?; + let secret = InternalHttpSecret::new(configured).map_err(CausalDispatchError::Internal)?; + let candidate = req + .headers() + .get(CELL_INTERNAL_SECRET_HEADER) + .ok() + .flatten() + .ok_or(CausalDispatchError::Unauthorized)?; + if secret.matches(&candidate) { + Ok(()) + } else { + Err(CausalDispatchError::Unauthorized) + } +} + +/// A JSON response with `status`. +pub fn json_status(body: Value, status: u16) -> Result { + Ok(Response::from_json(&body)?.with_status(status)) +} + +/// The wire form of a dispatch error. +pub fn error_response(error: CausalDispatchError) -> Result { + let status = error.status_code(); + json_status(error_body(&error), status) +} + +fn error_body(error: &CausalDispatchError) -> Value { + json!({ "error": error.client_message(), "code": error.code() }) +} + +/// The route of a fact batch: `POST /{kind}/{shard}/__batch` (see +/// [`serve_cell`]). +pub const BATCH_ROUTE: &str = "__batch"; + +/// One cell's internal routes: `GET /{kind}/{shard}` → `read(cell)`, `POST +/// /{kind}/{shard}/{command}` → the idempotent wait-path dispatch (identity +/// from the service-id and principal-partition headers, the session from +/// `sessions`), then a best-effort outbox drain. `POST +/// /{kind}/{shard}/__batch` ([`BATCH_ROUTE`]) runs a zone's consecutive +/// facts for this cell in one request ([`run_fact_batch`]: each entry as +/// its own wait-path command, with its own ledger id and session, in order, +/// stopping after the first retryable result), then one outbox drain. +/// Every request must carry the internal secret. +pub async fn serve_cell( + env: &Env, + cell: &AggregateCell, + mut req: Request, + read: F, + sessions: Sessions, +) -> Result +where + A: Aggregate + Send + Sync + 'static, + F: AsyncFnOnce(&AggregateCell) -> std::result::Result, +{ + if let Err(error) = authenticate(&req, env) { + return error_response(error); + } + let url = req.url()?; + let parts: Vec = url + .path() + .split('/') + .filter(|part| !part.is_empty()) + .map(str::to_string) + .collect(); + match (req.method(), parts.get(2)) { + (Method::Get, None) => match read(cell).await { + Ok(body) => json_status(body, 200), + Err(error) => error_response(CausalDispatchError::Internal(error)), + }, + (Method::Post, Some(route)) if route == BATCH_ROUTE => { + serve_batch(env, cell, req, sessions).await + } + (Method::Post, Some(command)) => { + let command = command.clone(); + let body: Value = match req.json().await { + Ok(body) => body, + Err(_) => { + return error_response(CausalDispatchError::BadRequest("invalid JSON".into())) + } + }; + let parsed = match CellWaitPathRequest::parse(body) { + Ok(parsed) => parsed, + Err(error) => return error_response(CausalDispatchError::BadRequest(error)), + }; + let header = |name: &str| req.headers().get(name).ok().flatten(); + let identity = match ( + header(CELL_SERVICE_ID_HEADER), + header(CELL_PRINCIPAL_PARTITION_HEADER), + ) { + (Some(service), Some(partition)) => { + match CellCommandIdentity::new(service, partition, &parsed.command_id) { + Ok(identity) => identity, + Err(error) => return error_response(error), + } + } + _ => return error_response(CausalDispatchError::Unauthorized), + }; + let Some(session) = sessions(&header) else { + return error_response(CausalDispatchError::Forbidden); + }; + let result = cell + .dispatch_idempotent(&command, &identity, parsed.input, session) + .await; + if let Err(error) = cell.drain_outbox(env).await { + worker::console_error!("post-commit drain deferred: {error}"); + } + match result { + Ok(dispatch) => json_status(dispatch.wait_path_wire(), 200), + Err(error) => error_response(error), + } + } + _ => json_status(json!({ "error": "not found" }), 404), + } +} + +async fn serve_batch( + env: &Env, + cell: &AggregateCell, + mut req: Request, + sessions: Sessions, +) -> Result +where + A: Aggregate + Send + Sync + 'static, +{ + let Some(service) = req.headers().get(CELL_SERVICE_ID_HEADER).ok().flatten() else { + return error_response(CausalDispatchError::Unauthorized); + }; + let body: Value = match req.json().await { + Ok(body) => body, + Err(_) => return error_response(CausalDispatchError::BadRequest("invalid JSON".into())), + }; + let results = run_fact_batch(cell, &service, &body, sessions).await; + if let Err(error) = cell.drain_outbox(env).await { + worker::console_error!("post-commit drain deferred: {error}"); + } + match results { + Ok(results) => json_status(results, 200), + Err(error) => error_response(error), + } +} + +/// A watched world cell's watchers ([`crate::world::watch`]): zones that +/// read the cell with `?watch=` get its view pushed after every commit (and +/// every alarm) that moves its version. Memory only. +/// +/// ```ignore +/// pub struct HoodCell { cell: AggregateCell, env: Env, watchers: CellWatchers } +/// // fetch: self.watchers.serve(&self.env, &self.cell, req, read_hood, sessions).await +/// // alarm: self.watchers.alarm(&self.env, &self.cell, read_hood).await +/// ``` +pub struct CellWatchers { + topic: String, + watchers: RefCell, +} + +impl CellWatchers { + /// The watchers of cell `kind` whose Durable Object is `state` (its + /// name is the shard). + pub fn new(kind: &str, state: &State) -> Self { + Self::of(kind, &state.id().name().unwrap_or_default()) + } + + /// The watchers of cell `kind/shard`. + pub fn of(kind: &str, shard: &str) -> Self { + Self { + topic: topic(kind, shard), + watchers: RefCell::new(Watchers::new()), + } + } + + /// [`serve_cell`], plus: a read with `?watch=` leaves a lease and its + /// body carries the cell's `version`; a command that changed the view + /// is pushed to the live watchers; `GET /{kind}/{shard}/__watchers` + /// ([`STATS_ROUTE`]) answers the live watchers and + /// [`WatcherStats`](crate::world::watch::WatcherStats). + pub async fn serve( + &self, + env: &Env, + cell: &AggregateCell, + req: Request, + read: F, + sessions: Sessions, + ) -> Result + where + A: Aggregate + Send + Sync + 'static, + F: AsyncFn(&AggregateCell) -> std::result::Result, + { + if req.method() == Method::Get { + if let Err(error) = authenticate(&req, env) { + return error_response(error); + } + let url = req.url()?; + if url.path().ends_with(&format!("/{STATS_ROUTE}")) { + return json_status(self.stats(), 200); + } + if let Some((watcher, lease)) = url.query().and_then(watch_query) { + self.watchers.borrow_mut().watch(&watcher, now_ms(), lease); + } + } + let is_command = req.method() == Method::Post; + let response = if req.method() == Method::Get { + match versioned(cell, &read).await { + Ok(body) => json_status(body, 200), + Err(error) => error_response(CausalDispatchError::Internal(error)), + } + } else { + serve_cell(env, cell, req, &read, sessions).await + }; + if is_command { + self.publish(env, cell, &read).await; + } + response + } + + /// The live watchers and what the cell did for them. + fn stats(&self) -> Value { + stats_body(&self.topic, &mut self.watchers.borrow_mut()) + } + + /// [`cell_alarm`], then a push if a schedule moved the version. + pub async fn alarm(&self, env: &Env, cell: &AggregateCell, read: F) -> Result + where + A: Aggregate + Send + Sync + 'static, + F: AsyncFn(&AggregateCell) -> std::result::Result, + { + let response = cell_alarm(env, cell).await; + self.publish(env, cell, &read).await; + response + } + + /// Push the cell's view to its live watchers when it changed (best + /// effort, off the request; a lost push is repaired by the + /// watcher's next reconcile read). + async fn publish(&self, env: &Env, cell: &AggregateCell, read: &F) + where + A: Aggregate + Send + Sync + 'static, + F: AsyncFn(&AggregateCell) -> std::result::Result, + { + let live = self.watchers.borrow_mut().live(now_ms()); + if live.is_empty() { + return; + } + let Ok(view) = versioned(cell, read).await else { + return; + }; + let version = crate::world::watch::view_version(&view); + { + let mut watchers = self.watchers.borrow_mut(); + if !watchers.publish(version, &view) { + return; + } + watchers.pushed(live.len()); + } + let update = WatchUpdate { + topic: self.topic.clone(), + version, + view, + }; + push_all(env.clone(), live, update); + } +} + +/// `{topic, live, ...WatcherStats}`. +fn stats_body(topic: &str, watchers: &mut Watchers) -> Value { + let mut body = serde_json::to_value(watchers.stats()).unwrap_or_else(|_| json!({})); + if let Value::Object(fields) = &mut body { + fields.insert("topic".into(), json!(topic)); + fields.insert("live".into(), json!(watchers.live(now_ms()).len())); + } + body +} + +/// `read(cell)` with the aggregate's version in its `version` field. +async fn versioned(cell: &AggregateCell, read: &F) -> std::result::Result +where + A: Aggregate + Send + Sync + 'static, + F: AsyncFn(&AggregateCell) -> std::result::Result, +{ + let version = cell + .load() + .await + .map_err(|error| error.to_string())? + .map_or(0, |aggregate| aggregate.entity().version()); + let mut body = read(cell).await?; + if let Value::Object(fields) = &mut body { + fields.insert("version".into(), json!(version)); + } + Ok(body) +} + +/// Push `update` to `watchers`, [`PUSH_CONCURRENCY`] at a time, off the +/// caller. +pub(crate) fn push_all(env: Env, watchers: Vec, update: WatchUpdate) { + wasm_bindgen_futures::spawn_local(async move { + let Some(secret) = internal_secret(&env) else { + return; + }; + let Ok(body) = serde_json::to_string(&update) else { + return; + }; + for chunk in watchers.chunks(PUSH_CONCURRENCY) { + let pushes = chunk + .iter() + .map(|watcher| push(&env, watcher, &secret, &body)); + futures_util::future::join_all(pushes).await; + } + }); +} + +/// One push, retried after [`PUSH_RETRY_MS`] while it fails in transport or +/// the zone is too busy to take it ([`push_retryable`]). +async fn push(env: &Env, watcher: &str, secret: &str, body: &str) { + let Some((binding, name)) = parse_watcher_address(watcher) else { + return; + }; + let mut waits = PUSH_RETRY_MS.iter(); + loop { + let error = match push_once(env, binding, name, secret, body).await { + Ok(status) if !push_retryable(status) => return, + Ok(status) => format!("HTTP {status}"), + Err(error) => error.to_string(), + }; + let Some(wait) = waits.next() else { + worker::console_warn!( + "world push to {watcher}: {error}; giving up until its reconcile" + ); + return; + }; + Delay::from(std::time::Duration::from_millis(*wait)).await; + } +} + +async fn push_once(env: &Env, binding: &str, name: &str, secret: &str, body: &str) -> Result { + let stub = env + .durable_object(binding)? + .id_from_name(name)? + .get_stub()?; + let headers = Headers::new(); + headers.set(CELL_INTERNAL_SECRET_HEADER, secret)?; + headers.set(super::ZONE_HEADER, name)?; + headers.set("content-type", "application/json")?; + let mut init = RequestInit::new(); + init.with_method(Method::Post) + .with_headers(headers) + .with_body(Some(body.into())); + let url = format!("https://zone/{name}/{PUSH_ROUTE}"); + let response = stub + .fetch_with_request(Request::new_with_init(&url, &init)?) + .await?; + Ok(response.status_code()) +} + +/// Post a zone message ([`crate::zone_message`]) to the zone object of +/// class `binding` it is addressed to, with the internal secret. Returns +/// the target's status: 204 delivered, 409 asleep or refused. +pub(super) async fn send_zone_message( + env: &Env, + binding: &str, + envelope: &crate::zone_message::ZoneEnvelope, +) -> Result { + let secret = internal_secret(env).ok_or_else(|| { + worker::Error::RustError(format!("{CELL_INTERNAL_SECRET_ENV} is required")) + })?; + let stub = env + .durable_object(binding)? + .id_from_name(&envelope.to)? + .get_stub()?; + let headers = Headers::new(); + headers.set(CELL_INTERNAL_SECRET_HEADER, &secret)?; + headers.set(super::ZONE_HEADER, &envelope.to)?; + headers.set("content-type", "application/json")?; + let body = + serde_json::to_string(envelope).map_err(|e| worker::Error::RustError(e.to_string()))?; + let mut init = RequestInit::new(); + init.with_method(Method::Post) + .with_headers(headers) + .with_body(Some(body.into())); + let url = format!("https://zone/{}/{}", envelope.to, super::ZONE_MESSAGE_ROUTE); + let response = stub + .fetch_with_request(Request::new_with_init(&url, &init)?) + .await?; + Ok(response.status_code()) +} + +fn internal_secret(env: &Env) -> Option { + env.secret(CELL_INTERNAL_SECRET_ENV) + .map(|value| value.to_string()) + .or_else(|_| { + env.var(CELL_INTERNAL_SECRET_ENV) + .map(|value| value.to_string()) + }) + .ok() +} + +fn now_ms() -> u64 { + js_sys::Date::now() as u64 +} + +/// A cell's alarm: due schedules, then the outbox drain. +pub async fn cell_alarm(env: &Env, cell: &AggregateCell) -> Result +where + A: Aggregate + Send + Sync + 'static, +{ + let wake = cell + .alarm(env) + .await + .map_err(|error| worker::Error::RustError(error.to_string()))?; + for error in &wake.drain.deferred { + worker::console_error!("drain deferred: {error}"); + } + Response::ok("ok") +} + +/// The zone-activity cell of a game worker (`ZoneActivity:{zone}`, kind +/// `zone-activity`, binding `ZONE_ACTIVITY`): the zone's own lifecycle +/// facts; its `zone.activity_changed` events leave through `outbox` (the +/// worker's Queue) for the zone status read model. `GET` returns the row. +pub struct ZoneActivityCell { + cell: AggregateCell, + env: Env, +} + +impl ZoneActivityCell { + /// Open the cell of `state`, publishing its events to `outbox` (the + /// worker's Queue producer binding; cells commit only with one). + pub fn new(state: State, env: Env, outbox: CelldOutbox) -> Self { + let cell = mount_zone_activity( + AggregateCell::::from_state_with_snapshots(state, 20) + .expect("zone activity cell identity"), + ) + .with_celld_outbox(outbox); + Self { cell, env } + } + + /// Durable Object `fetch`. + pub async fn fetch(&self, req: Request) -> Result { + serve_cell(&self.env, &self.cell, req, read_activity, fact_sessions).await + } + + /// Durable Object `alarm`. + pub async fn alarm(&self) -> Result { + cell_alarm(&self.env, &self.cell).await + } +} + +async fn read_activity(cell: &AggregateCell) -> std::result::Result { + let activity = cell.load().await.map_err(|error| error.to_string())?; + Ok(json!({ "activity": activity.map(|a| a.row()) })) +} + +/// Dev-only settings shared by every zone object of a worker (kind +/// [`ZONE_DEV_KIND`](super::ZONE_DEV_KIND), binding `ZONE_DEV`), e.g. the +/// network simulation under shard [`NETSIM_SHARD`](super::NETSIM_SHARD). +/// `GET /zone-dev/{shard}` returns the stored JSON (`{}` when unset), `PUT` +/// (or `POST`) replaces it. Every request needs the internal secret. Zone +/// objects watch it only when `ZONE_DEV_SETTINGS=1` (a `GET` with `?watch=`; +/// each write is pushed to the watchers with the next `version`). +pub struct ZoneDevSettings { + state: State, + env: Env, + watchers: RefCell, + topic: String, +} + +impl ZoneDevSettings { + /// The settings object of `state`. + pub fn new(state: State, env: Env) -> Self { + let topic = topic(super::ZONE_DEV_KIND, &state.id().name().unwrap_or_default()); + Self { + state, + env, + watchers: RefCell::new(Watchers::new()), + topic, + } + } + + /// Durable Object `fetch`. + pub async fn fetch(&self, mut req: Request) -> Result { + if let Err(error) = authenticate(&req, &self.env) { + return error_response(error); + } + const KEY: &str = "settings"; + const VERSION: &str = "version"; + match req.method() { + Method::Get => { + let url = req.url()?; + if url.path().ends_with(&format!("/{STATS_ROUTE}")) { + return json_status( + stats_body(&self.topic, &mut self.watchers.borrow_mut()), + 200, + ); + } + if let Some((watcher, lease)) = url.query().and_then(watch_query) { + self.watchers.borrow_mut().watch(&watcher, now_ms(), lease); + } + let stored: Option = self.state.storage().get(KEY).await.ok().flatten(); + let version: u64 = self + .state + .storage() + .get(VERSION) + .await + .ok() + .flatten() + .unwrap_or(0); + let mut body = stored.unwrap_or_else(|| json!({})); + if let Value::Object(fields) = &mut body { + fields.insert(VERSION.into(), json!(version)); + } + json_status(body, 200) + } + Method::Put | Method::Post => { + let body: Value = match req.json().await { + Ok(body @ Value::Object(_)) => body, + _ => { + return error_response(CausalDispatchError::BadRequest( + "a JSON object is required".into(), + )) + } + }; + let version: u64 = self + .state + .storage() + .get(VERSION) + .await + .ok() + .flatten() + .unwrap_or(0) + + 1; + self.state.storage().put(KEY, &body).await?; + self.state.storage().put(VERSION, version).await?; + let live = self.watchers.borrow_mut().live(now_ms()); + let mut view = body.clone(); + if let Value::Object(fields) = &mut view { + fields.insert(VERSION.into(), json!(version)); + } + if !live.is_empty() && self.watchers.borrow_mut().publish(version, &view) { + self.watchers.borrow_mut().pushed(live.len()); + push_all( + self.env.clone(), + live, + WatchUpdate { + topic: self.topic.clone(), + version, + view, + }, + ); + } + json_status(body, 200) + } + _ => json_status(json!({ "error": "not found" }), 404), + } + } +} + +/// The content-rollout cell of a game worker (`ContentRollout:{world}`, +/// kind [`CONTENT_ROLLOUT_KIND`](crate::world::content_rollout::CONTENT_ROLLOUT_KIND), +/// binding `CONTENT_ROLLOUT`): the world's live content version and rollout +/// phase, read by every zone object ([`ObjectOptions::content_rollout`](super::ObjectOptions::content_rollout)). +/// `sessions` decides who may start a rollout: it must give the admin's +/// session the [`CONTENT_ADMIN_ROLE`](crate::world::content_rollout::CONTENT_ADMIN_ROLE) +/// (the cell's own schedules need no session). `GET` returns +/// `{"state": ContentState | null, "version": n}`; zones watch it +/// ([`CellWatchers`]). +pub struct ContentRolloutCell { + cell: AggregateCell, + env: Env, + sessions: Sessions, + watchers: CellWatchers, +} + +impl ContentRolloutCell { + /// Open the cell of `state`, publishing its events to `outbox`. + pub fn new(state: State, env: Env, outbox: CelldOutbox, sessions: Sessions) -> Self { + let watchers = + CellWatchers::new(crate::world::content_rollout::CONTENT_ROLLOUT_KIND, &state); + let cell = mount_content_rollout( + AggregateCell::::from_state_with_snapshots(state, 20) + .expect("content rollout cell identity"), + ) + .with_celld_outbox(outbox); + Self { + cell, + env, + sessions, + watchers, + } + } + + /// Durable Object `fetch` (zones watch it: every phase is pushed). + pub async fn fetch(&self, req: Request) -> Result { + self.watchers + .serve(&self.env, &self.cell, req, read_rollout, self.sessions) + .await + } + + /// Durable Object `alarm` (the rollout's own schedule). + pub async fn alarm(&self) -> Result { + self.watchers + .alarm(&self.env, &self.cell, read_rollout) + .await + } +} + +async fn read_rollout(cell: &AggregateCell) -> std::result::Result { + let rollout = cell.load().await.map_err(|error| error.to_string())?; + Ok(json!({ "state": rollout.map(|r| r.state()) })) +} diff --git a/distributed_game/src/celld_zone/mod.rs b/distributed_game/src/celld_zone/mod.rs new file mode 100644 index 000000000..a2e0e458d --- /dev/null +++ b/distributed_game/src/celld_zone/mod.rs @@ -0,0 +1,151 @@ +//! Zones as celld Durable Objects (feature `celld-zone`): host any [`Zone`] +//! as one object per zone id. celld decides where a zone runs, forwards +//! every connection to it, moves idle zones, evicts sleeping ones and +//! recovers them after a node crash; game code and game APIs never name a +//! server. +//! +//! ```text +//! client ──WebSocket /zones/{zone}──▶ any celld node ──forward──▶ the zone's object +//! │ ZoneHost (this activation) +//! Hello(ticket | transfer ticket | reconnect token) ┤ deadline tick loop while occupied +//! │ snapshot every min + on leave/empty +//! facts (outbox in object storage) ───┼──▶ cell objects (CommandFactSink +//! │ over CelldObjectHost, exactly once) +//! zone_activity.record (active / dormant / hibernated)┘──▶ zone-activity/{zone} cell +//! └ outbox ▶ Queue ▶ zone_status read model +//! ``` +//! +//! What the framework does per object ([`ZoneObject`], wasm32): +//! - **Join.** A WebSocket upgrade is accepted as a hibernatable socket; +//! its attachment holds the client id and the activation id. Hello is +//! verified with the shared HS256 [`TicketKey`](crate::ticket::TicketKey) +//! (env `GAME_TICKET_SECRET`): a join ticket, a transfer ticket from a +//! neighbouring zone's handoff (single use, also across activations) or a +//! reconnect token inside the grace window. +//! - **Ticks.** A self-correcting `setTimeout` loop over absolute deadlines +//! ([`TickSchedule`]; `setInterval` drifts) drives +//! [`ZoneHost::advance`](crate::ZoneHost::advance) while anyone is +//! connected, and stops `ZONE_DORMANT_AFTER_MS` (10 s) after the zone +//! empties. +//! - **State.** The zone's [`Zone::hibernate`] snapshot is written to object +//! storage every `ZONE_PERSIST_MS` (60 s) while occupied, on the tick a +//! player leaves (leave, handoff, grace expired) and when the loop stops +//! (`dormant`); after `ZONE_HIBERNATE_AFTER_MS` empty (an +//! object alarm, so it survives eviction) the zone is dropped from memory +//! (`hibernated`). The next join wakes it and restores the snapshot. +//! - **Restarts.** A socket that outlives its activation (eviction, a move, +//! a crash) is closed with [`CLOSE_RESTARTED`] (1012); the client rejoins +//! with a fresh ticket. +//! - **Facts.** Zone facts go to cells of the same worker object to object +//! ([`CelldObjectHost`] under [`CommandFactSink`](crate::command_sink::CommandFactSink), +//! the same routes and command ids as over HTTP). Each fact is written to +//! the object's outbox before it is sent and deleted when settled; the +//! next activation or the outbox alarm resends what is left, and the +//! cells' command ledger turns a resend into a replay: exactly once. +//! - **The world around.** A zone *watches* the world cells it cares +//! about ([`CelldZone::watch`], [`crate::world::watch`]): each is read +//! on wake, then pushed by its cell ([`CellWatchers`]) after every +//! change, and re-read every ~45 s (renewing the zone's in-memory watch +//! lease, repairing a lost push). Each view decodes into a plain struct +//! that becomes a zone message. The object takes pushes at its class +//! binding (`celld_zone_object!(PitRoom, …)` → `PIT_ROOM`). Custom async +//! reads still go through [`CelldZone::refresh`] / +//! [`CelldZone::refresh_every`]. +//! - **Status.** The zone reports its lifecycle as facts into its +//! [`zone_activity`](crate::world::zone_activity) cell, projected into the +//! [`zone_status`](crate::world::zone_status) read model (minimaps). +//! +//! What celld does: placement (first touch, overflow by +//! `CELLD_MAX_RESIDENT_CELLS`), forwarding from any node, idle eviction, +//! rebalancing of idle objects, graceful drain and crash recovery (fenced +//! by its own epochs; one instance per object name). +//! +//! Limits: a live zone never moves (only idle ones are rebalanced), so +//! spreading load depends on first touch and node caps; objects of one +//! class share V8 isolates (a slow zone delays its neighbours); a crash +//! loses at most the snapshot interval of zone state (facts are kept by +//! the outbox) and takes the node lease TTL (~10 s) to recover. +//! +//! **Observers are passive watchers** on celld: an observer connection +//! (a ticket with role `observer`, e.g. a page watching the rooms next to +//! its own) never counts as occupancy — a zone with only observers stops +//! ticking (they keep its last state), goes dormant and hibernates (their +//! sockets are closed) — and an observer Hello never wakes a sleeping zone: +//! it is refused with [`error::ASLEEP`](crate::protocol::error::ASLEEP). +//! Only a player — or a *near* watcher — wakes a zone. A watcher joining +//! a dormant zone gets its current state at once +//! ([`ZoneHost::patch_now`](crate::ZoneHost::patch_now)). +//! +//! **Near watchers** (proximity wake): an observer whose ticket grants +//! `wake` ([`TicketClaims::wake`](crate::TicketClaims::wake)) and that says +//! it is near (Hello `near`, later +//! [`ClientMessage::Near`](crate::protocol::ClientMessage::Near), no +//! reconnect) counts as occupancy like a player: it wakes a sleeping zone +//! and keeps it ticking. When it says it is no longer near, or closes, the +//! zone goes dormant and hibernates as usual. Without the grant the +//! watcher stays passive and is told +//! [`error::WAKE_DENIED`](crate::protocol::error::WAKE_DENIED) (still +//! connected; a fresh ticket may carry the grant). The ticket issuer bounds who may wake what (e.g. only rooms +//! next to the principal's own); the zone checks only the signed grant. +//! +//! **Live content updates.** With `ZONE_CONTENT_ROLLOUT=` every +//! zone object follows the world's +//! [`content_rollout`](crate::world::content_rollout) cell +//! ([`ContentRolloutCell`], binding `CONTENT_ROLLOUT`): it watches the cell +//! (each phase is pushed) and runs +//! [`zone_step`](crate::world::content_rollout::zone_step) — freeze with +//! the change notes, then switch to the new version and resume (a hard +//! rollout reloads stale clients at once). A zone that slept through a +//! rollout restores its snapshot's version and catches up on wake; a Hello +//! whose content version differs from the zone's waits for that read +//! before admission, so a doorway into a sleeping zone admits on the live +//! version. Stale clients are handled by the host's +//! [`StalePolicy`](crate::world::StalePolicy). +//! +//! Dev only: with `ZONE_DEV_SETTINGS=1` every zone object applies the +//! network simulation ([`NetSim`](crate::netsim::NetSim): latency, jitter, +//! loss per socket and direction) stored in the worker's +//! [`ZoneDevSettings`] object (`zone-dev/netsim`), watched like the content +//! rollout (each write is pushed); a dev route writes it (one setting for +//! every zone, like the native server's `set_net_sim`). +//! +//! **Work counters.** `GET …/info` carries the object's +//! [`WorkCounters`](crate::work::WorkCounters) as `work` (records encoded, +//! updates sent and held, Delta bytes, fact commands and `__batch` +//! requests, outbox deletes, world reads and pushes) and the switches in +//! effect; a watched cell answers `GET /{kind}/{shard}/__watchers` with its +//! [`WatcherStats`](crate::world::watch::WatcherStats). A/B switches (worker +//! vars, default on): `ZONE_FACT_BATCH` (1 = one fact per request), +//! `ZONE_UPDATE_RATES=0` (every change every patch), `ZONE_WORLD_PUSH=0` +//! (poll watched cells every second instead of taking pushes). +//! +//! Debug only: celld does not tell application code which node runs an +//! object. With `CELLD_ZONE_NODES` set (operator listeners) the object asks +//! each node whether it holds it; `CELLD_ZONE_NODE` names a fixed node. +//! Both are off by default; nothing routes by them. + +pub mod plan; + +#[cfg(target_arch = "wasm32")] +mod cells; +#[cfg(target_arch = "wasm32")] +mod object; + +pub use plan::{ + cell_binding, ObjectOptions, RoomState, StoredFact, TickSchedule, CLOSE_RESTARTED, + CONTENT_ROLLOUT_VAR, DEV_SETTINGS_VAR, NETSIM_SHARD, UPDATE_RATES_VAR, WORLD_PUSH_VAR, + ZONE_DEV_KIND, ZONE_HEADER, ZONE_MESSAGE_ROUTE, +}; + +#[cfg(target_arch = "wasm32")] +pub use cells::{ + authenticate, cell_alarm, error_response, fact_sessions, json_status, serve_cell, CellWatchers, + ContentRolloutCell, Sessions, ZoneActivityCell, ZoneDevSettings, +}; +#[cfg(target_arch = "wasm32")] +pub use object::{ + forward_to_zone, CelldObjectHost, CelldZone, LocalFuture, ObjectEnv, ObjectFactSink, ZoneObject, +}; + +#[cfg(doc)] +use crate::Zone; diff --git a/distributed_game/src/celld_zone/object.rs b/distributed_game/src/celld_zone/object.rs new file mode 100644 index 000000000..86138ce75 --- /dev/null +++ b/distributed_game/src/celld_zone/object.rs @@ -0,0 +1,1544 @@ +//! The Durable Object side of the celld zone host (wasm32 only). + +use std::cell::RefCell; +use std::collections::{HashMap, HashSet}; +use std::future::Future; +use std::pin::Pin; +use std::rc::{Rc, Weak}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +use distributed::cell_host::{ + CELL_INTERNAL_SECRET_ENV, CELL_INTERNAL_SECRET_HEADER, CELL_PRINCIPAL_PARTITION_HEADER, + CELL_SERVICE_ID_HEADER, +}; +use distributed::USER_ID_KEY; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use worker::send::{SendFuture, SendWrapper}; +use worker::{ + Delay, Env, Headers, Method, Request, RequestInit, Response, Result, State, Storage, WebSocket, + WebSocketIncomingMessage, WebSocketPair, +}; + +use super::plan::{ + cell_binding, classify_wait_path, zone_from_path, ObjectOptions, RoomState, StoredFact, + TickSchedule, Window, CLOSE_RESTARTED, NETSIM_SHARD, OUTBOX_PREFIX, ZONE_DEV_KIND, ZONE_HEADER, +}; +use crate::admission::{admit, AdmissionConfig, Admitted, Gate, InputGate}; +use crate::command_sink::{CommandFactSink, FactBatchHost, FactCall, FactHost, FactRoute}; +use crate::facts::{ + fact_channel, BoxFuture, Fact, FactBatchSink, FactError, FactQueue, FactReceipt, FactSink, + RetryPolicy, +}; +use crate::handoff::{HandoffRequest, Transfer}; +use crate::inbox::ZoneInbound; +use crate::netsim::{DelayLine, NetSim, NetSimJson}; +use crate::protocol::{error, kick, ClientMessage, Notice, Role, ServerMessage}; +use crate::stamp::FactStamp; +use crate::ticket::{NonceCache, TicketKey}; +use crate::work::WorkCounters; +use crate::world::content_rollout::{zone_step, ContentState, ZoneStep, CONTENT_ROLLOUT_KIND}; +use crate::world::watch::{ + topic, view_version, watch_query_string, watcher_address, WatchUpdate, Watches, WorldSync, + PUSH_ROUTE, WATCH_LEASE_MS, +}; +use crate::world::zone_activity::{ + zone_principal, RecordActivity, ACTIVITY_ACTIVE, ACTIVITY_DORMANT, ACTIVITY_HIBERNATED, + ZONE_ACTIVITY_KIND, +}; + +mod facts; +mod lifecycle; +mod sockets; +mod world_sync; + +use crate::world::FreezeState; +use crate::zone::Viewer; +use crate::{ClientId, Clock, HostConfig, Outbound, TicketClaims, Zone, ZoneHost}; +pub use facts::CelldObjectHost; +use facts::{fact_batch, DurableFacts}; + +/// A future that runs on the object's (single) thread. +pub type LocalFuture = Pin + 'static>>; + +/// The zone's fact sink on celld: commands to cells, object to object. +pub type ObjectFactSink = CommandFactSink; + +const SNAPSHOT_KEY: &str = "zone:snapshot"; +const STATUS_KEY: &str = "zone:status"; +const NONCE_PREFIX: &str = "nonce:"; +/// Transfer tickets (doorways) live this long. +const TRANSFER_TTL_SECS: u64 = 30; +/// Unsettled facts one activation may hold. +const FACT_CAPACITY: usize = 512; +/// Retry stored facts this often while any is unsettled (ms). +const OUTBOX_RETRY_MS: f64 = 10_000.0; +/// Shortest crash watchdog period (each re-arm is a durable alarm write). +const WATCHDOG_MIN_MS: f64 = 60_000.0; + +/// Server → client, through the socket's simulated network. +enum OutItem { + Frame(Vec), + Close, +} + +/// Client → server, through the socket's simulated network. +enum InItem { + Input { + seq: u32, + client_tick: u32, + payload: Vec, + }, + Ping(f64), +} + +/// A game zone the framework can host as a celld Durable Object: one object +/// per zone id (celld places it, forwards to it, hibernates and moves it). +pub trait CelldZone: Zone { + /// The zone's construction parameters for `zone_id` (validate the id + /// here: `Err` refuses the join). + fn object_config(zone_id: &str, env: &ObjectEnv) -> std::result::Result; + + /// Host tuning; the object sets the tick and patch rates, reconnect + /// grace and boot epoch from its options. Default: [`HostConfig`] + /// defaults. + fn host_config(_zone_id: &str, _env: &ObjectEnv) -> HostConfig { + HostConfig::default() + } + + /// Who may join: the object builds the [`AdmissionConfig`] from its + /// ticket secret; add a custom ticket verifier or the zone's ticket + /// extensions here. Default: unchanged. + fn admission(config: AdmissionConfig, _env: &ObjectEnv) -> AdmissionConfig { + config + } + + /// Fact routes of the zone (lifecycle facts too, if the host config + /// emits them). The zone-activity route is added by the framework. + fn fact_routes(sink: ObjectFactSink) -> ObjectFactSink { + sink + } + + /// Async work after a player joined (e.g. read the player's profile + /// from its cell); the message it returns is delivered into the zone + /// ([`Zone::on_message`]). Runs off the tick; the zone must not wait + /// for it. + fn after_join( + _env: &ObjectEnv, + _principal: &str, + ) -> Option>> { + None + } + + /// The world cells the zone watches ([`Watches`]): each is read on + /// wake, pushed by its cell after every change and re-read every ~45 s; + /// its view becomes a message ([`Zone::on_message`]). Eventually + /// consistent: world flavour, never reward settlement. + /// + /// ```ignore + /// fn watch(zone_id: &str) -> Watches { + /// Watches::new().cell(HOOD_KIND, &hood_of(zone_id), |read: HoodRead| read.state.map(PitMessage::Hood)) + /// } + /// ``` + fn watch(_zone_id: &str) -> Watches { + Watches::new() + } + + /// How often [`refresh`](Self::refresh) runs while the zone ticks + /// (`None`: never). It also runs once on every wake. For cell state, + /// prefer [`watch`](Self::watch) (pushed, no polling). + fn refresh_every() -> Option { + None + } + + /// Async work that keeps the zone in step with the world around it — + /// e.g. read the cells of the tiers it belongs to — off the tick; the + /// message it returns is delivered into the zone ([`Zone::on_message`]). + /// `round` counts the calls of this activation (0 on wake), so a zone + /// can read slower tiers less often. + fn refresh( + _env: &ObjectEnv, + _zone_id: &str, + _round: u64, + ) -> Option>> { + None + } +} + +// ------------------------------------------------------------------ env + +/// The object's environment for game hooks: vars and cell reads. +#[derive(Clone)] +pub struct ObjectEnv { + env: Env, +} + +impl ObjectEnv { + /// Wrap a worker env. + pub fn new(env: Env) -> Self { + Self { env } + } + + /// A var or secret. + pub fn var(&self, name: &str) -> Option { + self.env + .var(name) + .map(|v| v.to_string()) + .or_else(|_| self.env.secret(name).map(|v| v.to_string())) + .ok() + } + + /// The worker env. + pub fn env(&self) -> &Env { + &self.env + } + + /// `GET /{kind}/{shard}` on a cell of this worker (its read route), + /// object to object, with the internal secret. + pub async fn read_cell(&self, kind: &str, shard: &str) -> std::result::Result { + self.read_cell_watching(kind, shard, None).await + } + + /// [`read_cell`](Self::read_cell) that also watches the cell for + /// `watcher` ([`crate::world::watch`]): the cell pushes its next + /// versions until the lease ends. + pub async fn read_cell_watching( + &self, + kind: &str, + shard: &str, + watcher: Option<&str>, + ) -> std::result::Result { + let secret = self + .var(CELL_INTERNAL_SECRET_ENV) + .ok_or_else(|| format!("{CELL_INTERNAL_SECRET_ENV} is required"))?; + let headers = Headers::new(); + headers + .set(CELL_INTERNAL_SECRET_HEADER, &secret) + .map_err(|e| e.to_string())?; + let mut init = RequestInit::new(); + init.with_method(Method::Get).with_headers(headers); + let mut url = format!("https://cell/{kind}/{}", encode_segment(shard)); + if let Some(watcher) = watcher { + url.push('?'); + url.push_str(&watch_query_string(watcher, WATCH_LEASE_MS)); + } + let request = Request::new_with_init(&url, &init).map_err(|e| e.to_string())?; + let stub = stub_for(&self.env, kind, shard).map_err(|e| e.to_string())?; + let mut response = stub + .fetch_with_request(request) + .await + .map_err(|e| e.to_string())?; + let status = response.status_code(); + let body: Value = response.json().await.unwrap_or(Value::Null); + if (200..300).contains(&status) { + Ok(body) + } else { + Err(format!("HTTP {status}: {body}")) + } + } +} + +/// The stub of cell `kind/shard` (binding [`cell_binding`]`(kind)`). +fn stub_for(env: &Env, kind: &str, shard: &str) -> Result { + let namespace = env.durable_object(&cell_binding(kind))?; + let id = namespace.id_from_name(shard)?; + id.get_stub() +} + +fn encode_segment(segment: &str) -> String { + let mut encoded = String::with_capacity(segment.len()); + for byte in segment.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~' | b':') { + encoded.push(byte as char); + } else { + encoded.push_str(&format!("%{byte:02X}")); + } + } + encoded +} + +// ------------------------------------------------------------------ time + +fn now_ms() -> f64 { + js_sys::Date::now() +} + +/// Monotonic host clock over `Date.now()` (`Instant` panics on +/// wasm32-unknown-unknown). +struct JsClock { + origin_ms: f64, + last_us: AtomicU64, +} + +impl JsClock { + fn new() -> Self { + Self { + origin_ms: now_ms(), + last_us: AtomicU64::new(0), + } + } +} + +impl Clock for JsClock { + fn now(&self) -> Duration { + let us = ((now_ms() - self.origin_ms).max(0.0) * 1000.0) as u64; + Duration::from_micros(self.last_us.fetch_max(us, Ordering::Relaxed).max(us)) + } + + fn unix_ms(&self) -> u64 { + self.origin_ms as u64 + self.now().as_millis() as u64 + } +} + +/// `n` random bytes as hex, from `crypto.getRandomValues`. +fn random_hex(n: usize) -> String { + let bytes = js_sys::Uint8Array::new_with_length(n as u32); + let crypto = js_sys::Reflect::get(&js_sys::global(), &"crypto".into()).ok(); + let filled = crypto.and_then(|crypto| { + let get = js_sys::Reflect::get(&crypto, &"getRandomValues".into()).ok()?; + let get: js_sys::Function = get.into(); + get.call1(&crypto, &bytes).ok() + }); + if filled.is_none() { + for i in 0..n { + bytes.set_index(i as u32, (js_sys::Math::random() * 256.0) as u8); + } + } + bytes.to_vec().iter().map(|b| format!("{b:02x}")).collect() +} + +async fn yield_now() { + let _ = wasm_bindgen_futures::JsFuture::from(js_sys::Promise::resolve( + &wasm_bindgen::JsValue::NULL, + )) + .await; +} + +thread_local! { + /// One id per V8 isolate (module instance), for the debug info. + static ISOLATE: String = random_hex(4); +} + +// ------------------------------------------------------------------ object + +/// What a socket carries across object hibernation. +#[derive(Serialize, Deserialize)] +enum Attachment { + /// Accepted, no Hello yet: it must arrive before `deadline_ms` + /// (`Date.now()` ms). + Pending { deadline_ms: f64 }, + /// Admitted by `activation` as `client`. + Joined { client: u32, activation: String }, +} + +#[derive(Serialize, Deserialize)] +struct Snapshot { + version: String, + state: String, +} + +/// When this activation woke and where its first join spent its time +/// (`Date.now()` ms; celld advances it at I/O boundaries, so the spans are +/// the awaited storage calls). Debug info for recovery timing. +#[derive(Default, Clone, Copy)] +struct WakeTrace { + /// The object was constructed (celld claimed and opened the cell). + constructed_at: f64, + /// First request of any kind (fetch, socket message, alarm). + first_call_at: Option, + /// What woke it: 1 fetch, 2 socket message, 3 alarm. + first_call: u8, + /// [`ZoneObject::start_facts`] (zone id write + outbox listing). + facts_ms: Option, + /// Facts resent from the outbox on wake. + outbox_resent: usize, + /// Snapshot read. + snapshot_read_ms: Option, + /// Restore (and, before the join writes moved after the Welcome, the + /// wake's status write). + restore_ms: Option, + /// The join's own status write and start of the loop, after the wake. + join_ms: Option, + /// First Welcome handed to celld (the output gate may hold it). + welcome_at: Option, +} + +#[derive(Default)] +struct TickStats { + late: Window, + work: Window, + dropped: u64, + iterations: u64, +} + +struct Inner { + zone_id: String, + activation: String, + activation_epoch: u64, + options: Option, + admission: Option, + host: Option>, + restored: bool, + wakes: u64, + state: RoomState, + sockets: HashMap, + /// Per admitted socket: its message rate limit. + gates: HashMap, + /// Observers whose ticket grants `wake` ([`TicketClaims::wake`]). + may_wake: HashSet, + /// Of those, the ones near right now: they keep the zone awake. + near: HashSet, + ticking: bool, + nonces: NonceCache, + sink: Option, + activity: Option, + activity_seq: u64, + outbox_loaded: bool, + last_status: String, + /// The status last written (`None`: not read yet this activation). + stored_status: Option, + node: String, + stats: TickStats, + last_persist_ms: f64, + /// A snapshot write is in flight (see [`ZoneObject::persist_later`]). + persisting: bool, + /// Players at the last tick; a drop (leave, handoff, grace expired) + /// snapshots on that tick, not at the next interval. + players_seen: usize, + /// When the ticking room last became empty (it goes dormant after + /// `dormant_after` of that). + empty_since_ms: Option, + /// A player left since the last snapshot. + persist_soon: bool, + spooled: u64, + /// Dev network simulation in effect (from the dev settings object). + net_sim: Option, + /// Per socket: server → client and client → server delay lines. + out_lines: HashMap>, + in_lines: HashMap>, + /// When the pending drain task wakes up (one per earliest deadline). + drain_at: Option, + /// Spawns a drain task waking at the given time (set by the object). + drainer: Option>, + /// Watched world cells ([`CelldZone::watch`] plus the dev settings and + /// content rollout), built on the first wake. + watches: Option>>, + /// Highest version applied per watched topic (this activation) and + /// when each is read next. + world: WorldSync, + /// Work done by this object (all its activations). + work: Rc>, + /// [`CelldZone::refresh`] calls of this activation, and the last one. + refresh_round: u64, + last_refresh_ms: f64, + trace: WakeTrace, +} + +impl Inner { + /// Send `item` to `client` through its simulated network. + fn send_out(&mut self, client: u32, item: OutItem) { + let sim = self.net_sim; + let line = self + .out_lines + .entry(client) + .or_insert_with(|| DelayLine::new(u64::from(client) ^ 0x5eed_0u64)); + match line.push(sim, now_ms(), item) { + Some(item) => self.deliver(client, item), + None => { + if let Some(due) = line.next_due() { + self.want_drain(due); + } + } + } + } + + fn deliver(&mut self, client: u32, item: OutItem) { + match item { + OutItem::Frame(frame) => { + if let Some(ws) = self.sockets.get(&client) { + let _ = ws.send_with_bytes(frame); + } + } + OutItem::Close => { + self.forget(client); + if let Some(ws) = self.sockets.remove(&client) { + let _ = ws.close(Some(1000), Some("closed by zone")); + } + } + } + } + + /// Take `item` from `client` through its simulated network. + fn receive(&mut self, client: u32, item: InItem) { + let sim = self.net_sim; + let line = self + .in_lines + .entry(client) + .or_insert_with(|| DelayLine::new(u64::from(client) ^ 0xfeed_0u64)); + match line.push(sim, now_ms(), item) { + Some(item) => self.apply(client, item), + None => { + if let Some(due) = line.next_due() { + self.want_drain(due); + } + } + } + } + + fn apply(&mut self, client: u32, item: InItem) { + match item { + InItem::Input { + seq, + client_tick, + payload, + } => { + if let Some(host) = self.host.as_mut() { + host.push_input(ClientId(client), seq, client_tick, &payload); + } + } + InItem::Ping(client_time) => { + let server_time = self.host.as_ref().map_or(0.0, |h| h.server_time_ms()); + if let Ok(pong) = (ServerMessage::Pong { + client_time, + server_time, + }) + .encode(&()) + { + self.send_out(client, OutItem::Frame(pong)); + } + } + } + } + + /// Deliver and apply everything due at `now`. + fn drain_due(&mut self, now: f64) { + let clients: Vec = self.in_lines.keys().copied().collect(); + for client in clients { + while let Some(item) = self.in_lines.get_mut(&client).and_then(|l| l.pop_due(now)) { + self.apply(client, item); + } + } + let clients: Vec = self.out_lines.keys().copied().collect(); + for client in clients { + while let Some(item) = self.out_lines.get_mut(&client).and_then(|l| l.pop_due(now)) { + self.deliver(client, item); + } + } + } + + fn next_due(&self) -> Option { + self.in_lines + .values() + .filter_map(DelayLine::next_due) + .chain(self.out_lines.values().filter_map(DelayLine::next_due)) + .min_by(f64::total_cmp) + } + + /// Make sure a drain task wakes up by `due`. + fn want_drain(&mut self, due: f64) { + if self.drain_at.is_some_and(|at| at <= due) { + return; + } + self.drain_at = Some(due); + if let Some(drainer) = self.drainer.clone() { + drainer(due); + } + } + + /// Forget a socket's delay lines and nearness. + fn forget(&mut self, client: u32) { + self.out_lines.remove(&client); + self.in_lines.remove(&client); + self.gates.remove(&client); + self.may_wake.remove(&client); + self.near.remove(&client); + } + + /// Players keep a zone awake (also inside their reconnect grace), and + /// so do near observers; other observers are passive watchers. + /// Players here or near, or work the zone says must finish first + /// ([`Zone::has_pending_work`], e.g. a crossing between zones), keep it + /// ticking (as the native host's tiers do). + fn occupied(&self) -> bool { + self.host.as_ref().is_some_and(|h| { + h.player_count() > 0 + || self.near.iter().any(|c| self.sockets.contains_key(c)) + || h.zone().has_pending_work() + }) + } + + /// An observer declares itself near (or not). Only an observer whose + /// ticket grants `wake` can be near (others are told `WAKE_DENIED`); + /// returns whether the zone must start ticking (it was not and is + /// occupied now). + fn set_near(&mut self, client: u32, near: bool) -> bool { + if !self.sockets.contains_key(&client) { + return false; + } + if near && self.may_wake.contains(&client) { + self.near.insert(client); + } else { + self.near.remove(&client); + if near { + if let Ok(frame) = (ServerMessage::Error { + code: error::WAKE_DENIED, + message: "ticket does not grant wake".into(), + }) + .encode(&()) + { + self.send_out(client, OutItem::Frame(frame)); + } + } + } + self.occupied() && !self.ticking + } + + fn flush(&mut self) { + let Some(host) = self.host.as_mut() else { + return; + }; + let outbound = host.drain_outbound(); + for out in outbound { + match out { + Outbound::Frame { client, frame } => { + self.send_out(client.0, OutItem::Frame(frame)); + } + Outbound::Close { client } => self.send_out(client.0, OutItem::Close), + } + } + } + + /// Facts emitted since the last call (zone and activity queues). + fn emitted(&mut self) -> Vec { + let mut facts = self + .host + .as_mut() + .map(ZoneHost::take_emitted_facts) + .unwrap_or_default(); + if let Some(queue) = self.activity.as_mut() { + facts.extend(queue.take_journal()); + } + facts + } + + fn snapshot(&self) -> Option { + let host = self.host.as_ref()?; + let state = host.hibernate_state()?; + use base64::Engine as _; + Some(Snapshot { + version: host.config().content_version.clone(), + state: base64::engine::general_purpose::STANDARD.encode(state), + }) + } + + /// Queue an activity report (a zone fact into its zone-activity cell). + fn report(&mut self, status: &str) { + if let Some(queue) = self.activity.as_mut() { + queue.drain(); + } + let Some(queue) = self.activity.as_mut() else { + return; + }; + self.activity_seq += 1; + let input = RecordActivity { + status: status.to_string(), + activation: self.activation.clone(), + restored: self.restored, + players: self.host.as_ref().map_or(0, |h| h.player_count() as u32), + node: self.node.clone(), + isolate: ISOLATE.with(|i| i.clone()), + }; + let stamp = FactStamp { + zone_id: self.zone_id.clone(), + tick: self.host.as_ref().map_or(0, |h| h.tick()), + emitted_at_ms: now_ms() as u64, + activation: self.activation_epoch, + seq: self.activity_seq, + ..FactStamp::default() + }; + let key = format!( + "zone_activity.record:{}:{}:{}", + self.zone_id, self.activation_epoch, self.activity_seq + ); + match serde_json::to_value(&input) { + Ok(value) => { + let fact = Fact::trusted( + key, + crate::world::zone_activity::RECORD, + value, + Some(zone_principal(&self.zone_id)), + stamp, + ); + if let Err(e) = queue.try_send(fact) { + worker::console_error!("zone {}: activity report dropped: {e:?}", self.zone_id); + } + } + Err(e) => worker::console_error!("zone activity encode: {e}"), + } + self.last_status = status.to_string(); + } +} + +/// Hosts one [`CelldZone`] as a celld Durable Object. The game's +/// `#[durable_object]` delegates to it (see [`crate::celld_zone_object!`]). +/// +/// Routes (on the object, via [`forward_to_zone`]): a WebSocket upgrade +/// joins the zone (the `distributed_game` wire protocol: Hello with a +/// ticket, a transfer ticket or a reconnect token); `GET …/info` returns +/// debug JSON (activation, node, isolate, tick timing) without waking a +/// hibernated zone. +pub struct ZoneObject { + state: Rc, + env: ObjectEnv, + inner: Rc>>, + /// Namespace binding of the object's class (`PIT_ROOM`): where watched + /// cells push. Empty: no pushes, watched cells are polled. + binding: Rc, +} + +impl ZoneObject { + /// The object of Durable Object class `class` (bound, by convention, as + /// [`class_binding`](crate::world::watch::class_binding)`(class)`, e.g. + /// `PitRoom` → `PIT_ROOM`); [`crate::celld_zone_object!`] calls it. + pub fn of_class(state: State, env: Env, class: &str) -> Self { + let mut object = Self::new(state, env); + object.binding = crate::world::watch::class_binding(class).into(); + object + } + + /// The object for `state` (constructor of the Durable Object). Watched + /// cells push to it only if `ZONE_BINDING` names its class binding; + /// prefer [`of_class`](Self::of_class). + pub fn new(state: State, env: Env) -> Self { + let zone_id = state.id().name().unwrap_or_default(); + let env = ObjectEnv::new(env); + let options = ObjectOptions::from_vars(|name| env.var(name)); + if let Err(e) = &options { + worker::console_error!("celld zone: {e}"); + } + let options = options.ok(); + let admission = options.as_ref().map(|o| { + Z::admission( + AdmissionConfig::new(TicketKey::new(o.ticket_secret.clone().into_bytes())), + &env, + ) + }); + let node = options + .as_ref() + .and_then(|o| o.node.clone()) + .unwrap_or_default(); + let inner = Inner { + zone_id, + activation: random_hex(6), + activation_epoch: (now_ms() * 1000.0) as u64, + options, + admission, + host: None, + restored: false, + wakes: 0, + state: RoomState::Cold, + sockets: HashMap::new(), + gates: HashMap::new(), + may_wake: HashSet::new(), + near: HashSet::new(), + ticking: false, + nonces: NonceCache::default(), + sink: None, + activity: None, + activity_seq: 0, + outbox_loaded: false, + last_status: String::new(), + stored_status: None, + node, + stats: TickStats::default(), + last_persist_ms: 0.0, + persisting: false, + players_seen: 0, + empty_since_ms: None, + persist_soon: false, + spooled: 0, + net_sim: None, + out_lines: HashMap::new(), + in_lines: HashMap::new(), + drain_at: None, + drainer: None, + watches: None, + world: WorldSync::new(), + work: Rc::default(), + refresh_round: 0, + last_refresh_ms: 0.0, + trace: WakeTrace { + constructed_at: now_ms(), + ..WakeTrace::default() + }, + }; + let inner = Rc::new(RefCell::new(inner)); + let weak = Rc::downgrade(&inner); + inner.borrow_mut().drainer = Some(Rc::new(move |due: f64| { + wasm_bindgen_futures::spawn_local(drain_task(weak.clone(), due)); + })); + let binding = env.var("ZONE_BINDING").unwrap_or_default().into(); + Self { + state: Rc::new(state), + env, + inner, + binding, + } + } + + /// The game hook environment. + pub fn env(&self) -> &ObjectEnv { + &self.env + } + + /// Durable Object `fetch`. + pub async fn fetch(&self, req: Request) -> Result { + self.first_call(1); + if let Some(zone) = req.headers().get(ZONE_HEADER)? { + let mut inner = self.inner.borrow_mut(); + if inner.zone_id.is_empty() { + inner.zone_id = zone; + } + } + if self.inner.borrow().zone_id.is_empty() { + return Response::error("zone id required", 400); + } + let path = req.url()?.path().to_string(); + if req.method() == Method::Post && path.ends_with(&format!("/{PUSH_ROUTE}")) { + return self.take_push(req).await; + } + if req.method() == Method::Post + && path.ends_with(&format!("/{}", super::ZONE_MESSAGE_ROUTE)) + { + return self.take_zone_message(req).await; + } + if path.ends_with("/info") { + // Debug JSON without secrets; pages on other origins may read it. + let response = Response::from_json(&self.info())?; + response.headers().set("access-control-allow-origin", "*")?; + return Ok(response); + } + if req.headers().get("upgrade")?.as_deref() != Some("websocket") { + return Response::error("expected a WebSocket upgrade", 426); + } + if self.inner.borrow().options.is_none() { + return Response::error("zone host is not configured", 503); + } + // Not woken here: only a player's Hello wakes a sleeping zone. The + // Hello must come in time: a timer closes a silent socket, and a + // late Hello (the timer died with a hibernation) is refused. + let pair = WebSocketPair::new()?; + self.state.accept_web_socket(&pair.server); + let timeout = self + .inner + .borrow() + .admission + .as_ref() + .expect("configured") + .hello_timeout; + pair.server.serialize_attachment(Attachment::Pending { + deadline_ms: now_ms() + timeout.as_secs_f64() * 1000.0, + })?; + let ws = pair.server.clone(); + wasm_bindgen_futures::spawn_local(async move { + sleep(timeout).await; + if let Ok(Some(Attachment::Pending { .. })) = ws.deserialize_attachment() { + reject(&ws, error::BAD_MESSAGE, "no Hello in time"); + } + }); + Response::from_websocket(pair.client) + } + + /// Durable Object `websocket_message`. + pub async fn websocket_message( + &self, + ws: WebSocket, + message: WebSocketIncomingMessage, + ) -> Result<()> { + self.first_call(2); + let WebSocketIncomingMessage::Binary(bytes) = message else { + let _ = ws.close(Some(1003), Some("binary frames only")); + return Ok(()); + }; + let attached: Option = ws.deserialize_attachment().ok().flatten(); + let activation = self.inner.borrow().activation.clone(); + let client = match attached { + Some(Attachment::Joined { + client, + activation: admitted_by, + }) if admitted_by == activation => Some(client), + // The socket outlived the activation that admitted it. + Some(Attachment::Joined { .. }) => { + let _ = ws.close(Some(CLOSE_RESTARTED), Some("zone restarted; rejoin")); + return Ok(()); + } + Some(Attachment::Pending { deadline_ms }) if now_ms() <= deadline_ms => None, + // Too late for a Hello (or a socket from before deadlines). + Some(Attachment::Pending { .. }) | None => { + reject(&ws, error::BAD_MESSAGE, "no Hello in time"); + return Ok(()); + } + }; + let msg = match ClientMessage::decode(&bytes) { + Ok(m) => m, + Err(_) => { + reject(&ws, error::BAD_MESSAGE, "bad message"); + return Ok(()); + } + }; + // Every message of an admitted client but Leave spends a token. + if let Some(client) = client.filter(|_| !matches!(msg, ClientMessage::Leave)) { + let gate = { + let mut inner = self.inner.borrow_mut(); + let now = Duration::from_secs_f64(now_ms().max(0.0) / 1000.0); + let Inner { + gates, admission, .. + } = &mut *inner; + let admission = admission.as_ref().expect("configured"); + gates + .entry(client) + .or_insert_with(|| InputGate::new(admission, now)) + .take(now) + }; + match gate { + Gate::Pass => {} + Gate::Drop { warn } => { + if warn { + if let Ok(frame) = (ServerMessage::Error { + code: error::RATE_LIMITED, + message: "message dropped".into(), + }) + .encode(&()) + { + let _ = ws.send_with_bytes(frame); + } + } + return Ok(()); + } + Gate::Kick => { + if let Ok(frame) = (ServerMessage::Kick { + code: kick::RATE_LIMITED, + message: "message flood".into(), + }) + .encode(&()) + { + let _ = ws.send_with_bytes(frame); + } + self.drop_socket(&ws); + let _ = ws.close(Some(1008), Some("message flood")); + return Ok(()); + } + } + } + match (client, msg) { + (None, ClientMessage::Hello(hello)) => self.hello(&ws, hello).await?, + ( + Some(client), + ClientMessage::Input { + seq, + client_tick, + payload, + }, + ) => { + let mut inner = self.inner.borrow_mut(); + if inner.host.is_some() { + inner.receive( + client, + InItem::Input { + seq, + client_tick, + payload, + }, + ); + } else { + drop(inner); + let _ = ws.close(Some(CLOSE_RESTARTED), Some("zone asleep; rejoin")); + } + } + (Some(client), ClientMessage::Ping { client_time }) => { + self.inner + .borrow_mut() + .receive(client, InItem::Ping(client_time)); + } + (Some(client), ClientMessage::Near { near }) => { + let start = self.inner.borrow_mut().set_near(client, near); + if start { + self.keep_awake().await; + } + } + (Some(client), ClientMessage::Focus { x, y }) => { + let mut inner = self.inner.borrow_mut(); + if let Some(host) = inner.host.as_mut() { + host.observer_focus(ClientId(client), x, y); + } + } + (Some(client), ClientMessage::Content { content_version }) => { + let mut inner = self.inner.borrow_mut(); + if let Some(host) = inner.host.as_mut() { + host.content_patched(ClientId(client), &content_version); + } + } + (Some(client), ClientMessage::Leave) => { + { + let mut inner = self.inner.borrow_mut(); + inner.sockets.remove(&client); + inner.forget(client); + if let Some(host) = inner.host.as_mut() { + host.disconnect(ClientId(client), true); + } + inner.flush(); + } + self.spool().await; + let _ = ws.close(Some(1000), Some("left")); + } + _ => reject(&ws, error::BAD_MESSAGE, "unexpected message"), + } + Ok(()) + } + + /// Durable Object `websocket_close`. + pub async fn websocket_close( + &self, + ws: WebSocket, + _code: usize, + _reason: String, + _was_clean: bool, + ) -> Result<()> { + self.drop_socket(&ws); + Ok(()) + } + + /// Durable Object `websocket_error`. + pub async fn websocket_error(&self, ws: WebSocket, _error: worker::Error) -> Result<()> { + self.drop_socket(&ws); + Ok(()) + } + + /// Durable Object `alarm`: hibernate a room that stayed empty, resend + /// unsettled facts, and after a crash mark the room asleep. + pub async fn alarm(&self) -> Result { + self.first_call(3); + if self.inner.borrow().options.is_none() { + return Response::ok("unconfigured"); + } + self.load_zone_id().await; + self.start_facts().await; + let (cold, due, hibernate_after) = { + let inner = self.inner.borrow(); + let after = inner + .options + .as_ref() + .map_or(Duration::from_secs(10), |o| o.hibernate_after); + ( + inner.host.is_none(), + !inner.occupied() && inner.state.hibernate_due(now_ms(), after), + after, + ) + }; + if due { + self.hibernate().await; + } else if cold { + // A fresh activation woken by its alarm: the last one crashed or + // was evicted while awake. Its snapshot is what it left. + let stored: Option = self.state.storage().get(STATUS_KEY).await.ok().flatten(); + if stored.as_deref().is_some_and(|s| s != ACTIVITY_HIBERNATED) { + self.inner.borrow_mut().report(ACTIVITY_HIBERNATED); + self.store_status().await; + } + } else { + let since = match self.inner.borrow().state { + RoomState::Dormant { since_ms } => Some(since_ms), + _ => None, + }; + if let Some(since) = since { + let wait = since + hibernate_after.as_millis() as f64 - now_ms(); + self.arm(wait.max(10.0)).await; + } else if let Some(watchdog) = self.watchdog_ms() { + // Still ticking: keep the crash watchdog (see `tick_loop`). + self.arm(watchdog).await; + } + } + self.arm_outbox().await; + Response::ok("ok") + } + + // -------------------------------------------------------------- internals + + fn first_call(&self, kind: u8) { + let mut inner = self.inner.borrow_mut(); + if inner.trace.first_call_at.is_none() { + inner.trace.first_call_at = Some(now_ms()); + inner.trace.first_call = kind; + } + } + + /// Sockets accepted before an eviction reach a new instance without a + /// zone id from a request; the id is kept in storage. + async fn load_zone_id(&self) { + if !self.inner.borrow().zone_id.is_empty() { + return; + } + if let Ok(Some(zone)) = self.state.storage().get::("zone:id").await { + let mut inner = self.inner.borrow_mut(); + if inner.zone_id.is_empty() { + inner.zone_id = zone; + } + } + } + + /// Start the fact pipeline once per activation and resend what the + /// previous activation left in the outbox. + async fn start_facts(&self) { + if self.inner.borrow().sink.is_some() { + return; + } + let (zone_id, service, secret) = { + let inner = self.inner.borrow(); + let Some(options) = inner.options.as_ref() else { + return; + }; + ( + inner.zone_id.clone(), + options.fact_service.clone(), + options.internal_secret.clone(), + ) + }; + let Some(secret) = secret else { + worker::console_error!( + "zone {zone_id}: {CELL_INTERNAL_SECRET_ENV} is not set; facts are disabled" + ); + return; + }; + let started = now_ms(); + let work = self.inner.borrow().work.clone(); + let host = + CelldObjectHost::new(self.env.env().clone(), secret, &service).counting(work.clone()); + let sink = match ObjectFactSink::new(host, service, zone_principal(&zone_id)) { + Ok(sink) => { + Z::fact_routes(sink.route(FactRoute::by_zone::(ZONE_ACTIVITY_KIND))) + } + Err(e) => { + worker::console_error!("zone {zone_id}: fact sink: {e}"); + return; + } + }; + let durable = DurableFacts { + sink, + storage: SendWrapper::new(Rc::new(self.state.storage())), + work: SendWrapper::new(work), + }; + let (queue, feed) = fact_channel(FACT_CAPACITY, retry_policy()); + let queue = queue.with_journal(); + let batch = fact_batch(&self.inner.borrow().options); + wasm_bindgen_futures::spawn_local( + feed.with_max_concurrent_commits(4) + .with_max_batch(batch) + .run(durable.clone(), sleep), + ); + { + let mut inner = self.inner.borrow_mut(); + if inner.sink.is_some() { + return; + } + inner.sink = Some(durable); + inner.activity = Some(queue); + } + // Written once per zone, not per activation: a wake after a crash + // writes nothing before its first player is in. + let stored_id: Option = self.state.storage().get("zone:id").await.ok().flatten(); + if stored_id.as_deref() != Some(zone_id.as_str()) { + let _ = self.state.storage().put("zone:id", &zone_id).await; + } + // Resend the previous activations' unsettled facts. + let stored = self + .state + .storage() + .list_with_options(worker::ListOptions::new().prefix(OUTBOX_PREFIX)) + .await; + let mut inner = self.inner.borrow_mut(); + inner.outbox_loaded = true; + inner.trace.facts_ms.get_or_insert(now_ms() - started); + if let Ok(map) = stored { + let mut resent = 0; + let Some(queue) = inner.activity.as_mut() else { + return; + }; + for value in map.values().into_iter().flatten() { + let Some(stored) = value + .as_string() + .and_then(|text| serde_json::from_str::(&text).ok()) + else { + continue; + }; + if let Some(fact) = stored.into_fact() { + let _ = queue.try_send(fact); + resent += 1; + } + } + // Already stored. + queue.take_journal(); + inner.trace.outbox_resent += resent; + } + } + + /// Make sure the zone is in memory (restoring its snapshot); true when + /// it was not. Reads only: the caller stores the zone's status (and the + /// facts of the wake) once its frames are out, so celld's output gate + /// does not hold a joining player's Welcome for writes of the wake. + async fn wake(&self) -> Result { + self.start_facts().await; + if self.inner.borrow().host.is_some() { + return Ok(false); + } + let read_at = now_ms(); + let stored: Option = self.state.storage().get(SNAPSHOT_KEY).await.ok().flatten(); + let restore_at = now_ms(); + let host = { + let inner = self.inner.borrow(); + if inner.host.is_some() { + return Ok(false); + } + let options = inner + .options + .as_ref() + .ok_or_else(|| worker::Error::RustError("zone host is not configured".into()))?; + let zone_id = inner.zone_id.clone(); + let config = Z::object_config(&zone_id, &self.env).map_err(worker::Error::RustError)?; + let mut host_config = Z::host_config(&zone_id, &self.env); + host_config.tick_rate = options.tick_hz; + host_config.patch_rate = options.patch_hz; + // The object stops ticking when empty instead of idling. + host_config.idle_tick_rate = None; + host_config.reconnect_grace = options.reconnect_grace; + host_config.boot_epoch = (now_ms() * 1000.0) as u64; + if !options.update_rates { + host_config.interest.update_rates = crate::UpdateRates::every_patch(); + } + // The content version the zone slept on (a rollout it missed is + // caught up by its first content rollout read). + if let Some(snapshot) = &stored { + host_config.content_version = snapshot.version.clone(); + } + let key = inner + .admission + .as_ref() + .expect("admission with options") + .key + .clone(); + let issuer_zone = zone_id.clone(); + let generation = inner.activation_epoch; + let mut host = + ZoneHost::::new(zone_id, host_config, Arc::new(JsClock::new()), config) + .with_token_source(|| random_hex(24)) + .with_transfer_issuer(move |request: &HandoffRequest| { + let expires_at = (now_ms() / 1000.0) as u64 + TRANSFER_TTL_SECS; + Some(key.sign_transfer(&Transfer { + claims: TicketClaims { + principal: request.principal.clone(), + zone: request.target_zone.clone(), + expires_at, + nonce: random_hex(16), + role: Role::Player, + name: request.name.clone(), + extensions: request.extensions.clone(), + wake: false, + }, + source_zone: request.source_zone.clone(), + issuer: issuer_zone.clone(), + generation, + carried: request.carried.clone(), + departed_at_ms: request.departed_at_ms, + })) + }); + let (queue, feed) = fact_channel(FACT_CAPACITY, retry_policy()); + if let Some(sink) = inner.sink.clone() { + wasm_bindgen_futures::spawn_local( + feed.with_max_concurrent_commits(4) + .with_max_batch(fact_batch(&inner.options)) + .run(sink, sleep), + ); + host = host.with_facts(queue.with_journal()); + } + let restored = match &stored { + Some(snapshot) => { + use base64::Engine as _; + match base64::engine::general_purpose::STANDARD.decode(&snapshot.state) { + Ok(state) => { + host.restore(&state, &snapshot.version); + true + } + Err(_) => false, + } + } + None => false, + }; + (host, restored) + }; + let (host, restored) = host; + { + let mut inner = self.inner.borrow_mut(); + if inner.host.is_some() { + return Ok(false); + } + inner.host = Some(host); + inner.restored = restored; + inner.wakes += 1; + inner.refresh_round = 0; + // Each wake is a new activation: sockets of an earlier one are + // told to rejoin (1012). + if inner.wakes > 1 { + inner.activation = random_hex(6); + } + inner.state = RoomState::Active; + inner.last_persist_ms = now_ms(); + inner.report(ACTIVITY_ACTIVE); + let trace = &mut inner.trace; + trace.snapshot_read_ms.get_or_insert(restore_at - read_at); + trace.restore_ms.get_or_insert(now_ms() - restore_at); + } + self.find_node(); + // Hydrate every watched cell, off the join path: a wake (often a + // doorway into a sleeping zone, with the player's inputs waiting) + // does not wait for them. The snapshot restored the zone's last + // content version; the rollout read catches up with one it slept + // through (a Hello on another version waits for its own read, see + // `hello`). + self.inner.borrow_mut().world.clear(); + self.reconcile_world(true); + self.refresh(); + Ok(true) + } + + /// Debug only, off by default: ask each configured operator listener + /// whether it holds this object. + fn find_node(&self) { + let (nodes, id) = { + let inner = self.inner.borrow(); + let Some(options) = inner.options.as_ref() else { + return; + }; + if options.nodes.is_empty() || options.node.is_some() { + return; + } + (options.nodes.clone(), self.state.id().to_string()) + }; + let inner = self.inner.clone(); + wasm_bindgen_futures::spawn_local(async move { + for (node, addr) in nodes { + let Ok(url) = format!("http://{addr}/state").parse() else { + continue; + }; + let Ok(mut response) = worker::Fetch::Url(url).send().await else { + continue; + }; + let Ok(state) = response.json::().await else { + continue; + }; + let mine = state["deployment"]["cells"] + .as_object() + .is_some_and(|cells| cells.keys().any(|k| k.ends_with(&id))); + if mine { + let mut inner = inner.borrow_mut(); + inner.node = node; + if inner.state == RoomState::Active { + inner.report(ACTIVITY_ACTIVE); + } + return; + } + } + }); + } + + fn info(&self) -> Value { + let inner = self.inner.borrow(); + let host = inner.host.as_ref(); + let stats = &inner.stats; + json!({ + "zone": inner.zone_id, + "status": inner.last_status, + "awake": host.is_some(), + "activation": inner.activation, + "restored": inner.restored, + "wakes": inner.wakes, + "node": inner.node, + "isolate": ISOLATE.with(|i| i.clone()), + "players": host.map_or(0, |h| h.player_count()), + "observers": host.map_or(0, |h| h.observer_count()), + "near": inner.near.len(), + "pendingWork": host.is_some_and(|h| h.zone().has_pending_work()), + "tick": host.map_or(0, |h| h.tick()), + "hz": inner.options.as_ref().map_or(0, |o| o.tick_hz), + "ticking": inner.ticking, + "factsInFlight": host.map_or(0, |h| h.facts_in_flight()) + + inner.activity.as_ref().map_or(0, |q| q.in_flight()), + "spooledFacts": inner.spooled, + "iterations": stats.iterations, + "droppedTicks": stats.dropped, + "lateMs": { "p50": stats.late.percentile(0.5), "p99": stats.late.percentile(0.99) }, + "netsim": NetSim::to_json(inner.net_sim), + "content": host.map(|h| json!({ + "version": h.config().content_version, + "freeze": format!("{:?}", h.freeze_state()).to_lowercase(), + })), + "workMs": { "p50": stats.work.percentile(0.5), "p99": stats.work.percentile(0.99) }, + "wake": { + "constructedAt": inner.trace.constructed_at, + "firstCallAt": inner.trace.first_call_at, + "firstCall": inner.trace.first_call, + "factsMs": inner.trace.facts_ms, + "outboxResent": inner.trace.outbox_resent, + "snapshotReadMs": inner.trace.snapshot_read_ms, + "restoreMs": inner.trace.restore_ms, + "joinMs": inner.trace.join_ms, + "welcomeAt": inner.trace.welcome_at, + }, + "work": *inner.work.borrow(), + "switches": inner.options.as_ref().map(|o| json!({ + "factBatch": o.fact_batch, + "updateRates": o.update_rates, + "worldPush": o.world_push && !self.binding.is_empty(), + })), + }) + } +} + +/// Deliver what the delay lines hold as it falls due, then stop (a newer +/// task with an earlier deadline takes over). +async fn drain_task(inner: Weak>>, mut target: f64) { + loop { + Delay::from(Duration::from_micros( + ((target - now_ms()).max(0.0) * 1000.0) as u64, + )) + .await; + let Some(inner) = inner.upgrade() else { + return; + }; + let mut inner = inner.borrow_mut(); + inner.drain_due(now_ms()); + if inner.drain_at != Some(target) { + return; + } + match inner.next_due() { + Some(next) => { + inner.drain_at = Some(next); + target = next; + } + None => { + inner.drain_at = None; + return; + } + } + } +} + +fn retry_policy() -> RetryPolicy { + RetryPolicy::until_settled(Duration::from_millis(100), Duration::from_secs(5)) +} + +fn sleep(d: Duration) -> Delay { + Delay::from(d) +} + +fn reject(ws: &WebSocket, code: u32, message: &str) { + if let Ok(frame) = (ServerMessage::Error { + code, + message: message.into(), + }) + .encode(&()) + { + let _ = ws.send_with_bytes(frame); + } + let _ = ws.close(Some(1008), Some(message)); +} + +/// Worker entry helper: route `"{prefix}{zone}[/…]"` to the zone's object +/// in Durable Object namespace `binding` (one object per zone id; celld +/// places it). Returns `None` when the path is not under `prefix`. +pub async fn forward_to_zone( + req: Request, + env: &Env, + binding: &str, + prefix: &str, +) -> Result> { + let path = req.url()?.path().to_string(); + let Some((zone, _)) = zone_from_path(prefix, &path) else { + return Ok(None); + }; + let stub = env + .durable_object(binding)? + .id_from_name(&zone)? + .get_stub()?; + let headers = req.headers().clone(); + headers.set(ZONE_HEADER, &zone)?; + let mut init = RequestInit::new(); + init.with_method(req.method()).with_headers(headers); + let forwarded = Request::new_with_init(req.url()?.as_str(), &init)?; + stub.fetch_with_request(forwarded).await.map(Some) +} + +/// Declare the Durable Object class hosting zone type `$zone`: +/// +/// ```ignore +/// distributed_game::celld_zone_object!(PitRoom, MobPit); +/// ``` +/// +/// The crate needs `worker` as a dependency. Bind the class in +/// `wrangler.jsonc` (a SQLite class) and route to it with +/// [`forward_to_zone`]. +#[macro_export] +macro_rules! celld_zone_object { + ($name:ident, $zone:ty) => { + #[::worker::durable_object] + pub struct $name { + zone: $crate::celld_zone::ZoneObject<$zone>, + } + + impl ::worker::DurableObject for $name { + fn new(state: ::worker::State, env: ::worker::Env) -> Self { + Self { + zone: $crate::celld_zone::ZoneObject::of_class( + state, + env, + ::core::stringify!($name), + ), + } + } + + async fn fetch(&self, req: ::worker::Request) -> ::worker::Result<::worker::Response> { + self.zone.fetch(req).await + } + + async fn websocket_message( + &self, + ws: ::worker::WebSocket, + message: ::worker::WebSocketIncomingMessage, + ) -> ::worker::Result<()> { + self.zone.websocket_message(ws, message).await + } + + async fn websocket_close( + &self, + ws: ::worker::WebSocket, + code: usize, + reason: String, + was_clean: bool, + ) -> ::worker::Result<()> { + self.zone.websocket_close(ws, code, reason, was_clean).await + } + + async fn websocket_error( + &self, + ws: ::worker::WebSocket, + error: ::worker::Error, + ) -> ::worker::Result<()> { + self.zone.websocket_error(ws, error).await + } + + async fn alarm(&self) -> ::worker::Result<::worker::Response> { + self.zone.alarm().await + } + } + }; +} diff --git a/distributed_game/src/celld_zone/object/facts.rs b/distributed_game/src/celld_zone/object/facts.rs new file mode 100644 index 000000000..ee9a44ef7 --- /dev/null +++ b/distributed_game/src/celld_zone/object/facts.rs @@ -0,0 +1,305 @@ +//! The zone's fact host on celld: commands to cells, durable outbox. + +use super::*; + +// ------------------------------------------------------------------ fact host + +/// [`FactHost`] over the cells of the same worker: the cell wait-path +/// request (`POST /{kind}/{shard}/{command}`, internal secret, principal, +/// `x-game-*` stamp) sent straight to the cell's Durable Object stub — +/// object to object, no HTTP hop through a node's public listener. The +/// binding of kind `k` is [`cell_binding`]`(k)`. +pub struct CelldObjectHost { + pub(super) env: SendWrapper, + pub(super) secret: String, + pub(super) service_id: String, + pub(super) work: SendWrapper>>, +} + +impl CelldObjectHost { + /// A host for `env`'s cells under command-ledger `service_id`. + pub fn new(env: Env, secret: impl Into, service_id: impl Into) -> Self { + Self { + env: SendWrapper::new(env), + secret: secret.into(), + service_id: service_id.into(), + work: SendWrapper::new(Rc::default()), + } + } + + /// Count the facts and requests it sends into `work`. + pub(super) fn counting(mut self, work: Rc>) -> Self { + self.work = SendWrapper::new(work); + self + } + + pub(super) async fn post( + &self, + call: &FactCall<'_>, + ) -> std::result::Result { + let headers = Headers::new(); + let set = |name: &str, value: &str| { + headers + .set(name, value) + .map_err(|e| FactError::Permanent(format!("header {name}: {e}"))) + }; + set(CELL_INTERNAL_SECRET_HEADER, &self.secret)?; + set(CELL_SERVICE_ID_HEADER, &self.service_id)?; + set(CELL_PRINCIPAL_PARTITION_HEADER, &call.principal)?; + set(USER_ID_KEY, &call.principal)?; + set("content-type", "application/json")?; + for (name, value) in call.session.variables() { + if name.starts_with(crate::stamp::SESSION_PREFIX) { + set(name, value)?; + } + } + let body = json!({ "commandId": call.command_id, "input": call.input }); + { + let mut work = self.work.borrow_mut(); + work.fact_commands += 1; + work.fact_requests += 1; + } + let (status, body) = self + .send(call.kind, &call.shard, call.command, headers, body) + .await?; + classify_wait_path(status, &body) + } + + /// `calls` (one aggregate) in one `POST /{kind}/{shard}/__batch` + /// ([`super::super::cells::serve_cell`]); each entry carries its own command + /// id, principal and stamp. A cell without the route, or one refusing + /// the batch request as a whole (4xx), gets them one by one. + pub(super) async fn post_batch( + &self, + calls: Vec>, + ) -> Vec> { + let Some(first) = calls.first() else { + return Vec::new(); + }; + let (kind, shard) = (first.kind, first.shard.clone()); + let entries: Vec = calls + .iter() + .map(|call| { + let mut session = serde_json::Map::new(); + session.insert(USER_ID_KEY.into(), json!(call.principal)); + for (name, value) in call.session.variables() { + if name.starts_with(crate::stamp::SESSION_PREFIX) { + session.insert(name.clone(), json!(value)); + } + } + json!({ + "command": call.command, + "commandId": call.command_id, + "input": call.input, + "partition": call.principal, + "session": session, + }) + }) + .collect(); + let headers = Headers::new(); + let set = |name: &str, value: &str| headers.set(name, value).is_ok(); + if !(set(CELL_INTERNAL_SECRET_HEADER, &self.secret) + && set(CELL_SERVICE_ID_HEADER, &self.service_id) + && set("content-type", "application/json")) + { + return vec![Err(FactError::Permanent("batch headers".into()))]; + } + { + let mut work = self.work.borrow_mut(); + work.fact_commands += calls.len() as u64; + work.fact_requests += 1; + work.fact_batches += 1; + } + let sent = self + .send( + kind, + &shard, + super::super::cells::BATCH_ROUTE, + headers, + json!({ "entries": entries }), + ) + .await; + match sent { + // No batch route (404; a cell serving only commands answers + // `__batch` 400), or the batch itself refused: each fact gets + // its own answer, never the first fact the batch's. + Ok((status, _)) if (400..500).contains(&status) && !matches!(status, 408 | 429) => { + let mut results = Vec::with_capacity(calls.len()); + for call in &calls { + let result = self.post(call).await; + let stop = matches!(result, Err(FactError::Retryable(_))); + results.push(result); + if stop { + break; + } + } + results + } + Ok((status, body)) if (200..300).contains(&status) => body + .get("results") + .and_then(Value::as_array) + .map(|results| { + results + .iter() + .map(|result| { + let status = result + .get("status") + .and_then(Value::as_u64) + .and_then(|status| u16::try_from(status).ok()) + .unwrap_or(500); + classify_wait_path(status, result.get("body").unwrap_or(&Value::Null)) + }) + .collect() + }) + .unwrap_or_default(), + Ok((status, body)) => vec![classify_wait_path(status, &body)], + Err(error) => vec![Err(error)], + } + } + + /// `POST https://cell/{kind}/{shard}/{route}` to the cell's stub: + /// `(status, JSON body)`. + pub(super) async fn send( + &self, + kind: &str, + shard: &str, + route: &str, + headers: Headers, + body: Value, + ) -> std::result::Result<(u16, Value), FactError> { + let retry = |e: worker::Error| FactError::Retryable(e.to_string()); + let mut init = RequestInit::new(); + init.with_method(Method::Post) + .with_headers(headers) + .with_body(Some(body.to_string().into())); + let url = format!( + "https://cell/{}/{}/{}", + encode_segment(kind), + encode_segment(shard), + encode_segment(route) + ); + let request = Request::new_with_init(&url, &init).map_err(retry)?; + let stub = stub_for(&self.env, kind, shard) + .map_err(|e| FactError::Permanent(format!("cell `{kind}`: {e}")))?; + let mut response = stub.fetch_with_request(request).await.map_err(retry)?; + let status = response.status_code(); + let body: Value = response.json().await.unwrap_or(Value::Null); + Ok((status, body)) + } +} + +impl FactHost for CelldObjectHost { + fn dispatch_fact<'a>( + &'a self, + call: FactCall<'a>, + ) -> BoxFuture<'a, std::result::Result> { + Box::pin(SendFuture::new(async move { self.post(&call).await })) + } + + /// One `__batch` request per cell (the feed's `ZONE_FACT_BATCH` bounds + /// it). + fn fact_batches(&self) -> Option<&dyn FactBatchHost> { + Some(self) + } +} + +impl FactBatchHost for CelldObjectHost { + fn dispatch_fact_batch<'a>( + &'a self, + calls: Vec>, + ) -> BoxFuture<'a, Vec>> { + Box::pin(SendFuture::new(async move { + if calls.len() == 1 { + let call = calls.into_iter().next().expect("one call"); + return vec![self.post(&call).await]; + } + self.post_batch(calls).await + })) + } +} + +/// The durable fact outbox around the sink: every emitted fact is written +/// to object storage right after the call that emitted it (from the fact +/// queues' journals, [`FactQueue::with_journal`]) and deleted here once it +/// settled (committed or permanently refused). The next activation (or the +/// outbox alarm) resends what is left; the cells' command ledger makes a +/// resend a replay. +#[derive(Clone)] +pub(super) struct DurableFacts { + pub(super) sink: ObjectFactSink, + pub(super) storage: SendWrapper>, + pub(super) work: SendWrapper>>, +} + +impl FactSink for DurableFacts { + fn commit<'a>( + &'a self, + fact: &'a Fact, + ) -> BoxFuture<'a, std::result::Result> { + Box::pin(SendFuture::new(async move { + let result = self.sink.commit(fact).await; + match &result { + Err(FactError::Permanent(e)) => { + worker::console_error!("fact {} refused: {e}", fact.key()) + } + Err(FactError::Retryable(e)) => { + worker::console_warn!("fact {} will be retried: {e}", fact.key()) + } + Ok(_) => {} + } + if !matches!(result, Err(FactError::Retryable(_))) { + self.work.borrow_mut().outbox_deletes += 1; + let _ = self + .storage + .delete(&StoredFact::storage_key(fact.key())) + .await; + } + result + })) + } + + /// Batches when the cells take them. + fn batches(&self) -> Option<&dyn FactBatchSink> { + self.sink.batches().map(|_| self as &dyn FactBatchSink) + } +} + +impl FactBatchSink for DurableFacts { + /// One batched delete for the facts the batch settled. + fn commit_batch<'a>( + &'a self, + facts: &'a [Fact], + ) -> BoxFuture<'a, Vec>> { + Box::pin(SendFuture::new(async move { + let results = self.sink.commit_batch(facts).await; + let mut settled = Vec::new(); + for (fact, result) in facts.iter().zip(&results) { + match result { + Err(FactError::Permanent(e)) => { + worker::console_error!("fact {} refused: {e}", fact.key()) + } + Err(FactError::Retryable(e)) => { + worker::console_warn!("fact {} will be retried: {e}", fact.key()); + continue; + } + Ok(_) => {} + } + settled.push(StoredFact::storage_key(fact.key())); + } + if !settled.is_empty() { + self.work.borrow_mut().outbox_deletes += 1; + let _ = self.storage.delete_multiple(settled).await; + } + results + })) + } +} + +/// Facts per cell batch from the zone's options. +pub(super) fn fact_batch(options: &Option) -> usize { + options + .as_ref() + .map_or(crate::facts::DEFAULT_MAX_BATCH, |options| { + options.fact_batch + }) +} diff --git a/distributed_game/src/celld_zone/object/lifecycle.rs b/distributed_game/src/celld_zone/object/lifecycle.rs new file mode 100644 index 000000000..a5377df9f --- /dev/null +++ b/distributed_game/src/celld_zone/object/lifecycle.rs @@ -0,0 +1,292 @@ +//! The tick loop, persistence, dormancy and hibernation, and alarms. + +use super::*; + +impl ZoneObject { + pub(super) async fn tick_loop(&self) { + let (hz, persist_every, dormant_after) = { + let mut inner = self.inner.borrow_mut(); + inner.empty_since_ms = None; + let options = inner.options.as_ref().expect("configured"); + ( + options.tick_hz, + options.persist_every.as_millis() as f64, + options.dormant_after.as_millis() as f64, + ) + }; + let mut schedule = TickSchedule::new(now_ms(), hz); + // Crash watchdog: if this activation dies while awake, the alarm + // wakes a fresh one that reports the room asleep. Armed once here and + // again from `alarm` while ticking — never per snapshot: each + // `set_alarm` leaves a wake entry celld scans when it starts. + if let Some(watchdog) = self.watchdog_ms() { + self.arm_later(watchdog); + } + loop { + Delay::from(Duration::from_micros( + (schedule.wait_ms(now_ms()) * 1000.0) as u64, + )) + .await; + let woke = now_ms(); + let late = schedule.woke(woke); + let (stop, persist, mail) = { + let mut inner = self.inner.borrow_mut(); + let Some(host) = inner.host.as_mut() else { + inner.ticking = false; + return; + }; + let report = host.advance(); + let players = host.player_count(); + inner.work.borrow_mut().record_advance(&report); + if players < inner.players_seen { + inner.persist_soon = true; + } + inner.players_seen = players; + inner.flush(); + let mail = inner + .host + .as_mut() + .map(ZoneHost::take_zone_messages) + .unwrap_or_default(); + let stats = &mut inner.stats; + stats.iterations += 1; + stats.late.push(late); + stats.work.push(now_ms() - woke); + stats.dropped += u64::from(report.dropped_ticks); + if let Some(queue) = inner.activity.as_mut() { + queue.drain(); + } + let stop = if inner.occupied() { + inner.empty_since_ms = None; + false + } else { + woke - *inner.empty_since_ms.get_or_insert(woke) >= dormant_after + }; + let persist = + stop || inner.persist_soon || woke - inner.last_persist_ms >= persist_every; + if stop { + inner.ticking = false; + } + (stop, persist, mail) + }; + self.send_zone_messages(mail); + // Storage stays off the loop: the simulation keeps its pace + // while a write waits on the bucket. + self.spool_later(); + self.reconcile_world(false); + self.refresh_if_due(); + if stop { + self.persist().await; + self.go_dormant().await; + return; + } + if persist { + self.persist_later(); + } + } + } + + /// Write the zone's snapshot (after the fact outbox writes queued by + /// this tick, so a crash never keeps an outcome without its fact). + pub(super) async fn persist(&self) { + yield_now().await; + let snapshot = { + let mut inner = self.inner.borrow_mut(); + inner.last_persist_ms = now_ms(); + inner.persist_soon = false; + inner.snapshot() + }; + if let Some(snapshot) = snapshot { + if let Err(e) = self.state.storage().put(SNAPSHOT_KEY, snapshot).await { + worker::console_error!("zone snapshot write failed: {e}"); + } + } + } + + /// [`persist`](Self::persist) off the tick loop. One snapshot write at + /// a time: while one is in flight a due tick leaves it to a later tick. + /// Spawned after the tick's [`spool_later`](Self::spool_later), so the + /// outbox write is issued before the snapshot that reflects it. + pub(super) fn persist_later(&self) { + { + let mut inner = self.inner.borrow_mut(); + if inner.persisting { + return; + } + inner.persisting = true; + } + let this = self.handle(); + wasm_bindgen_futures::spawn_local(async move { + this.persist().await; + this.inner.borrow_mut().persisting = false; + }); + } + + pub(super) async fn go_dormant(&self) { + let after = { + let mut inner = self.inner.borrow_mut(); + if inner.occupied() { + return; + } + inner.state = RoomState::Dormant { since_ms: now_ms() }; + inner.report(ACTIVITY_DORMANT); + inner + .options + .as_ref() + .map_or(10_000.0, |o| o.hibernate_after.as_millis() as f64) + }; + self.store_status().await; + self.arm(after).await; + } + + pub(super) async fn hibernate(&self) { + self.persist().await; + { + let mut inner = self.inner.borrow_mut(); + if inner.occupied() { + return; + } + inner.report(ACTIVITY_HIBERNATED); + // Watchers of a sleeping zone are let go (they may come back + // and are told it is asleep). + for (_, ws) in inner.sockets.drain() { + let _ = ws.close(Some(1000), Some("zone asleep")); + } + inner.out_lines.clear(); + inner.in_lines.clear(); + inner.may_wake.clear(); + inner.near.clear(); + // Dropped, so the next join restores from storage. + inner.host = None; + inner.state = RoomState::Cold; + inner.ticking = false; + } + self.store_status().await; + } + + /// Write the facts emitted since the last call to the outbox. + pub(super) async fn spool(&self) { + self.spool_with(None).await; + } + + /// [`spool`](Self::spool), with the zone's `status` in the same batch. + pub(super) async fn spool_with(&self, status: Option) { + let facts = self.inner.borrow_mut().emitted(); + if facts.is_empty() && status.is_none() { + return; + } + // One batched write (the storage API takes at most 128 keys). + let mut batches: Vec<(js_sys::Object, usize)> = facts + .chunks(128) + .map(|chunk| { + let batch = js_sys::Object::new(); + for fact in chunk { + let text = serde_json::to_string(&StoredFact::of(fact)).unwrap_or_default(); + let _ = js_sys::Reflect::set( + &batch, + &StoredFact::storage_key(fact.key()).into(), + &text.into(), + ); + } + (batch, chunk.len()) + }) + .collect(); + if let Some(status) = status { + if batches.last().is_none_or(|(_, keys)| *keys >= 128) { + batches.push((js_sys::Object::new(), 0)); + } + if let Some((batch, keys)) = batches.last_mut() { + let _ = js_sys::Reflect::set(batch, &STATUS_KEY.into(), &status.into()); + *keys += 1; + } + } + let storage = self.state.storage(); + for (batch, _) in batches { + if let Err(e) = storage.put_multiple_raw(batch).await { + worker::console_error!("fact outbox write failed: {e}"); + } + } + if !facts.is_empty() { + self.inner.borrow_mut().spooled += facts.len() as u64; + self.arm_outbox().await; + } + } + + /// [`spool`](Self::spool) from a synchronous handler. + pub(super) fn spool_later(&self) { + let this = self.handle(); + wasm_bindgen_futures::spawn_local(async move { this.spool().await }); + } + + /// Spool the pending facts and write the zone's status with them when + /// it changed (one batch; an unchanged status writes nothing). + pub(super) async fn store_status(&self) { + let (status, known) = { + let inner = self.inner.borrow(); + (inner.last_status.clone(), inner.stored_status.clone()) + }; + let stored = match known { + Some(stored) => Some(stored), + None => self + .state + .storage() + .get::(STATUS_KEY) + .await + .ok() + .flatten(), + }; + let changed = !status.is_empty() && stored.as_deref() != Some(status.as_str()); + self.inner.borrow_mut().stored_status = Some(if changed { + status.clone() + } else { + stored.unwrap_or_default() + }); + self.spool_with(changed.then_some(status)).await; + } + + /// Set the object's alarm `in_ms` from now. + pub(super) async fn arm(&self, in_ms: f64) { + if let Err(e) = self + .state + .storage() + .set_alarm(Duration::from_millis(in_ms.max(1.0) as u64)) + .await + { + worker::console_error!("zone alarm: {e}"); + } + } + + /// The crash watchdog's period while ticking (three snapshot + /// intervals, at least a minute), when configured and ticking. + pub(super) fn watchdog_ms(&self) -> Option { + let inner = self.inner.borrow(); + let options = inner.options.as_ref()?; + (inner.ticking && inner.host.is_some()) + .then(|| (options.persist_every.as_millis() as f64 * 3.0).max(WATCHDOG_MIN_MS)) + } + + /// [`arm`](Self::arm) off the caller's path. + pub(super) fn arm_later(&self, in_ms: f64) { + let this = self.handle(); + wasm_bindgen_futures::spawn_local(async move { this.arm(in_ms).await }); + } + + /// Keep an alarm while unsettled facts wait in the outbox. + pub(super) async fn arm_outbox(&self) { + let pending = { + let mut inner = self.inner.borrow_mut(); + // Settlements only leave the queue on `drain`; a hibernated + // room has no tick loop to drain it, and would otherwise re-arm + // this alarm forever on a report that settled long ago. + if let Some(queue) = inner.activity.as_mut() { + queue.drain(); + } + inner.activity.as_ref().map_or(0, |q| q.in_flight()) + + inner.host.as_ref().map_or(0, |h| h.facts_in_flight()) + }; + let alarm = self.state.storage().get_alarm().await.ok().flatten(); + if pending > 0 && alarm.is_none() { + self.arm(OUTBOX_RETRY_MS).await; + } + } +} diff --git a/distributed_game/src/celld_zone/object/sockets.rs b/distributed_game/src/celld_zone/object/sockets.rs new file mode 100644 index 000000000..2b8a04f4f --- /dev/null +++ b/distributed_game/src/celld_zone/object/sockets.rs @@ -0,0 +1,260 @@ +//! Client sockets: admission (Hello), keeping the zone awake, dropping. + +use super::*; + +impl ZoneObject { + pub(super) async fn hello(&self, ws: &WebSocket, hello: crate::protocol::Hello) -> Result<()> { + let now = (now_ms() / 1000.0) as u64; + let admitted = { + let inner = self.inner.borrow(); + let admission = inner.admission.as_ref().expect("configured"); + admit(admission, &hello, &inner.zone_id, now) + }; + let admitted = match admitted { + Ok(admitted) => admitted, + Err(refusal) => { + reject(ws, refusal.code, &refusal.message); + return Ok(()); + } + }; + let cold = self.inner.borrow().host.is_none(); + let mut principal = None; + let mut wake_grant = false; + let mut woke = false; + let joined = match admitted { + Admitted::Reconnect(token) => { + // Sessions die with the activation: rejoin with a ticket + // (which wakes the zone for a player, not for an observer). + let mut inner = self.inner.borrow_mut(); + let Some(host) = inner.host.as_mut() else { + drop(inner); + reject(ws, error::RECONNECT_FAILED, "zone restarted; rejoin"); + return Ok(()); + }; + host.reconnect_with_version(&token, hello.capabilities, &hello.content_version) + } + // A transfer's single use is recorded by the target object + // alone: a return to the source would make it usable twice. + Admitted::Return(_) => { + reject(ws, error::UNAUTHORIZED, "ticket is for another zone"); + return Ok(()); + } + admitted @ (Admitted::Join(_) | Admitted::Arrival(_)) => { + let claims = admitted.claims().expect("a ticket").clone(); + // A passive watcher never wakes a sleeping zone; a near one + // whose ticket grants `wake` does. + let observer = claims.role == Role::Observer; + wake_grant = observer && claims.wake; + if cold && observer && !(hello.near && wake_grant) { + reject(ws, error::ASLEEP, "zone asleep"); + return Ok(()); + } + // Transfer tickets are single use across activations too. + let arrival = matches!(admitted, Admitted::Arrival(_)); + let nonce_key = format!("{NONCE_PREFIX}{}", claims.nonce); + let used_before = arrival + && self + .state + .storage() + .get::(&nonce_key) + .await + .ok() + .flatten() + .is_some(); + let consumed = admitted.consume(&mut self.inner.borrow_mut().nonces, now); + if used_before || consumed.is_err() { + reject(ws, error::UNAUTHORIZED, "ticket already used"); + return Ok(()); + } + if arrival { + let _ = self + .state + .storage() + .put(&nonce_key, claims.expires_at) + .await; + } + woke = match self.wake().await { + Ok(woke) => woke, + Err(e) => { + reject(ws, error::NOT_FOUND, &e.to_string()); + return Ok(()); + } + }; + if claims.role == Role::Player { + principal = Some(claims.principal.clone()); + } + // A client on another content version than the zone: the + // zone may be behind the world (it slept through a + // rollout), so it learns the live version before deciding. + let behind = { + let inner = self.inner.borrow(); + inner + .options + .as_ref() + .is_some_and(|o| o.content_rollout.is_some()) + && inner + .host + .as_ref() + .is_some_and(|h| h.config().content_version != hello.content_version) + }; + if behind { + if let Some(world) = self.content_world() { + self.reconcile(&topic(CONTENT_ROLLOUT_KIND, &world)).await; + } + } + let mut inner = self.inner.borrow_mut(); + let Some(host) = inner.host.as_mut() else { + drop(inner); + reject(ws, error::ZONE_UNAVAILABLE, "zone asleep"); + return Ok(()); + }; + match &admitted { + Admitted::Arrival(transfer) => { + host.join_transfer(transfer, hello.capabilities, &hello.content_version) + } + _ => host.join(&claims, hello.capabilities, &hello.content_version), + } + } + }; + match joined { + Ok(joined) => { + let mut observer = matches!(joined.viewer, Viewer::Observer(_)); + { + let mut inner = self.inner.borrow_mut(); + let activation = inner.activation.clone(); + ws.serialize_attachment(Attachment::Joined { + client: joined.client.0, + activation, + })?; + inner.sockets.insert(joined.client.0, ws.clone()); + if observer && wake_grant { + inner.may_wake.insert(joined.client.0); + } + if observer && hello.near { + // A near watcher (with the grant) keeps the zone + // awake like a player; without it, it is told so + // after its Welcome and stays passive. + inner.flush(); + inner.set_near(joined.client.0, true); + observer = !wake_grant; + } + if observer && !inner.ticking { + // A dormant zone does not tick: greet the watcher + // with its current state (it stays dormant). + if let Some(host) = inner.host.as_mut() { + host.patch_now(); + } + } + inner.flush(); + if !observer && inner.state != RoomState::Active { + inner.state = RoomState::Active; + inner.report(ACTIVITY_ACTIVE); + } + } + if observer { + if woke { + self.store_status().await; + } + return Ok(()); + } + let joined_at = now_ms(); + self.store_status().await; + self.start_loop(); + { + let mut inner = self.inner.borrow_mut(); + let trace = &mut inner.trace; + if trace.welcome_at.is_none() { + trace.welcome_at = Some(joined_at); + trace.join_ms = Some(now_ms() - joined_at); + } + } + if let Some(principal) = principal { + self.after_join(principal); + } + } + Err(e) => { + reject(ws, e.code, &e.message); + if woke { + self.store_status().await; + } + } + } + Ok(()) + } + + /// A near watcher arrived on an awake zone that is not ticking + /// (dormant): it is active again and ticks. + pub(super) async fn keep_awake(&self) { + { + let mut inner = self.inner.borrow_mut(); + if inner.host.is_none() { + return; + } + if inner.state != RoomState::Active { + inner.state = RoomState::Active; + inner.report(ACTIVITY_ACTIVE); + } + } + self.store_status().await; + self.start_loop(); + } + + pub(super) fn after_join(&self, principal: String) { + let Some(work) = Z::after_join(&self.env, &principal) else { + return; + }; + let inner = self.inner.clone(); + wasm_bindgen_futures::spawn_local(async move { + if let Some(message) = work.await { + let mut inner = inner.borrow_mut(); + if let Some(host) = inner.host.as_mut() { + host.deliver(ZoneInbound::Message(message)); + inner.flush(); + } + // Facts the message produced are written on the next tick. + } + }); + } + + pub(super) fn drop_socket(&self, ws: &WebSocket) { + let attached: Option = ws.deserialize_attachment().ok().flatten(); + let mut inner = self.inner.borrow_mut(); + let client = match attached { + Some(Attachment::Joined { client, activation }) if activation == inner.activation => { + Some(client) + } + _ => None, + }; + if let Some(client) = client { + inner.sockets.remove(&client); + inner.forget(client); + if let Some(host) = inner.host.as_mut() { + host.disconnect(ClientId(client), false); + } + inner.flush(); + drop(inner); + self.spool_later(); + } + } + + pub(super) fn start_loop(&self) { + { + let mut inner = self.inner.borrow_mut(); + if inner.ticking || inner.host.is_none() { + return; + } + inner.ticking = true; + } + let this = self.handle(); + wasm_bindgen_futures::spawn_local(async move { this.tick_loop().await }); + } + + pub(super) fn handle(&self) -> Self { + Self { + state: self.state.clone(), + env: self.env.clone(), + inner: self.inner.clone(), + binding: self.binding.clone(), + } + } +} diff --git a/distributed_game/src/celld_zone/object/world_sync.rs b/distributed_game/src/celld_zone/object/world_sync.rs new file mode 100644 index 000000000..b996f9f1a --- /dev/null +++ b/distributed_game/src/celld_zone/object/world_sync.rs @@ -0,0 +1,274 @@ +//! Refresh, world watches and pushes, zone messages and content rollout. + +use super::*; + +impl ZoneObject { + /// Run [`CelldZone::refresh`] off the tick and deliver its message. + pub(super) fn refresh(&self) { + let (zone_id, round) = { + let mut inner = self.inner.borrow_mut(); + inner.last_refresh_ms = now_ms(); + let round = inner.refresh_round; + inner.refresh_round += 1; + (inner.zone_id.clone(), round) + }; + let Some(work) = Z::refresh(&self.env, &zone_id, round) else { + return; + }; + let inner = self.inner.clone(); + wasm_bindgen_futures::spawn_local(async move { + if let Some(message) = work.await { + let mut inner = inner.borrow_mut(); + if let Some(host) = inner.host.as_mut() { + host.deliver(ZoneInbound::Message(message)); + inner.flush(); + } + } + }); + } + + /// [`refresh`](Self::refresh) when [`CelldZone::refresh_every`] is due. + pub(super) fn refresh_if_due(&self) { + let Some(every) = Z::refresh_every() else { + return; + }; + let due = now_ms() - self.inner.borrow().last_refresh_ms >= every.as_millis() as f64; + if due { + self.refresh(); + } + } + + /// The world whose content rollout the zone follows, if any. + pub(super) fn content_world(&self) -> Option { + let inner = self.inner.borrow(); + inner + .options + .as_ref() + .and_then(|o| o.content_rollout.clone()) + } + + /// Every watched topic: the dev settings (`ZONE_DEV_SETTINGS=1`), the + /// content rollout (`ZONE_CONTENT_ROLLOUT`) and the game's + /// [`CelldZone::watch`]. + pub(super) fn world_topics(&self) -> Vec { + let (dev, zone_id) = { + let inner = self.inner.borrow(); + let dev = inner.options.as_ref().is_some_and(|o| o.dev_settings); + (dev, inner.zone_id.clone()) + }; + let watches = self + .inner + .borrow_mut() + .watches + .get_or_insert_with(|| Rc::new(Z::watch(&zone_id))) + .clone(); + let mut topics = Vec::with_capacity(watches.len() + 2); + if dev { + topics.push(topic(ZONE_DEV_KIND, NETSIM_SHARD)); + } + if let Some(world) = self.content_world() { + topics.push(topic(CONTENT_ROLLOUT_KIND, &world)); + } + topics.extend(watches.iter().map(|w| w.topic())); + topics + } + + /// Whether watched cells push to this object: it has a class binding + /// and `ZONE_WORLD_PUSH` is not `0`. + pub(super) fn pushed(&self) -> bool { + !self.binding.is_empty() + && self + .inner + .borrow() + .options + .as_ref() + .is_some_and(|o| o.world_push) + } + + /// Read the watched topics that are due (all of them with `all`, on + /// wake) off the tick ([`WorldSync::due`]). When pushed, each read + /// renews the zone's watch and the next comes ~45 s later (pushes + /// carry the changes); otherwise the cells are polled every second. + pub(super) fn reconcile_world(&self, all: bool) { + let topics = self.world_topics(); + let pushed = self.pushed(); + let due = self.inner.borrow_mut().world.due( + topics, + now_ms() as u64, + all, + pushed, + js_sys::Math::random, + ); + for topic in due { + let this = self.handle(); + wasm_bindgen_futures::spawn_local(async move { this.reconcile(&topic).await }); + } + } + + /// Read watched `topic` (`kind/shard`), watching it when the object + /// can take pushes, and apply its view. + pub(super) async fn reconcile(&self, topic: &str) { + let Some((kind, shard)) = topic.split_once('/') else { + return; + }; + let watcher = self.pushed().then(|| { + let zone_id = self.inner.borrow().zone_id.clone(); + watcher_address(&self.binding, &zone_id) + }); + self.inner.borrow().work.borrow_mut().world_reads += 1; + match self + .env + .read_cell_watching(kind, shard, watcher.as_deref()) + .await + { + Ok(view) => self.apply_view(topic, view), + Err(e) => worker::console_warn!("world view {topic}: {e}"), + } + } + + /// A pushed update (`POST …/__world`, internal secret): applied when + /// the zone is in memory and watches the topic; a sleeping zone + /// hydrates on wake instead (a push never wakes it). + /// A message from another zone object ([`crate::zone_message`]): + /// internal secret only; refused (409) while the zone is not running, + /// so it never wakes one. + pub(super) async fn take_zone_message(&self, mut req: Request) -> Result { + if let Err(error) = super::super::cells::authenticate(&req, self.env.env()) { + return super::super::cells::error_response(error); + } + let Ok(envelope) = req.json::().await else { + return Response::error("a zone message is required", 400); + }; + let mut inner = self.inner.borrow_mut(); + let Some(host) = inner.host.as_mut() else { + return Response::error("zone asleep", 409); + }; + let delivered = host.deliver_zone(envelope); + inner.flush(); + match delivered { + Ok(()) => Response::empty().map(|r| r.with_status(204)), + Err(crate::zone_message::ZoneMessageError::Duplicate) => { + Response::empty().map(|r| r.with_status(204)) + } + Err(e) => Response::error(e.to_string(), 409), + } + } + + /// Post the zone messages the tick sent to their target objects (same + /// class), off the tick. Best effort: a refused or failed one is + /// dropped (protocols that must not lose state carry their own acks). + pub(super) fn send_zone_messages(&self, messages: Vec) { + if messages.is_empty() { + return; + } + if self.binding.is_empty() { + worker::console_error!("zone messages need the object's class binding (of_class)"); + return; + } + for envelope in messages { + let env = self.env.env().clone(); + let binding = self.binding.clone(); + wasm_bindgen_futures::spawn_local(async move { + match super::super::cells::send_zone_message(&env, &binding, &envelope).await { + Ok(204) => {} + Ok(status) => worker::console_log!( + "zone message {} to {} refused: {status}", + envelope.id, + envelope.to + ), + Err(e) => worker::console_error!("zone message to {}: {e}", envelope.to), + } + }); + } + } + + pub(super) async fn take_push(&self, mut req: Request) -> Result { + if let Err(error) = super::super::cells::authenticate(&req, self.env.env()) { + return super::super::cells::error_response(error); + } + let Ok(update) = req.json::().await else { + return Response::error("a world update is required", 400); + }; + let awake = { + let inner = self.inner.borrow(); + inner.work.borrow_mut().world_pushes += 1; + inner.host.is_some() + }; + if awake && self.world_topics().contains(&update.topic) { + self.apply_view(&update.topic, update.view); + } + Response::empty().map(|r| r.with_status(204)) + } + + /// Apply `view` of `topic` if it is newer than what the zone has. + pub(super) fn apply_view(&self, topic: &str, view: Value) { + let version = view_version(&view); + if !self.inner.borrow_mut().world.accept(topic, version) { + return; + } + let (kind, shard) = topic.split_once('/').unwrap_or((topic, "")); + if kind == ZONE_DEV_KIND && shard == NETSIM_SHARD { + let sim = serde_json::from_value::(view) + .unwrap_or_default() + .to_sim(); + self.inner.borrow_mut().net_sim = sim; + return; + } + if kind == CONTENT_ROLLOUT_KIND && self.content_world().as_deref() == Some(shard) { + let state = view + .get("state") + .cloned() + .and_then(|state| serde_json::from_value::(state).ok()); + if let Some(state) = state { + self.apply_content(&state); + } + return; + } + let watches = self.inner.borrow().watches.clone(); + let Some(message) = watches + .as_ref() + .and_then(|w| w.get(topic)) + .and_then(|watch| watch.message(view)) + else { + return; + }; + let mut inner = self.inner.borrow_mut(); + if let Some(host) = inner.host.as_mut() { + host.deliver(ZoneInbound::Message(message)); + inner.flush(); + } + } + + pub(super) fn apply_content(&self, state: &ContentState) { + let mut inner = self.inner.borrow_mut(); + let Some(host) = inner.host.as_mut() else { + return; + }; + let frozen = host.freeze_state() != FreezeState::Running; + let current = host.config().content_version.clone(); + match zone_step(state, ¤t, frozen) { + ZoneStep::Stay => return, + ZoneStep::Freeze => { + host.request_freeze(Notice { + reason: "content_update".into(), + version: state.target.clone(), + notes: state.notes.clone(), + }); + } + ZoneStep::Apply(version) => { + host.set_content_version(version.clone()); + if frozen { + host.resume(Notice { + reason: "content_updated".into(), + version, + notes: state.notes.clone(), + }); + } + if state.hard { + host.reload_stale_players(); + } + } + } + inner.flush(); + } +} diff --git a/distributed_game/src/celld_zone/plan.rs b/distributed_game/src/celld_zone/plan.rs new file mode 100644 index 000000000..69f3cc660 --- /dev/null +++ b/distributed_game/src/celld_zone/plan.rs @@ -0,0 +1,545 @@ +//! The runtime-free parts of the celld zone host: options, the room's +//! lifecycle states, the self-correcting tick schedule, the durable fact +//! outbox encoding and the cell wait-path answer classification. Compiled +//! on every target so they are unit-tested natively; the Durable Object glue +//! ([`super::ZoneObject`], wasm32) drives them. + +use std::collections::HashMap; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::facts::{Fact, FactError, FactReceipt}; +use crate::stamp::FactStamp; + +/// Env var: HS256 secret admission (and transfer) tickets are signed with. +pub const TICKET_SECRET_VAR: &str = "GAME_TICKET_SECRET"; +/// Env var: tick rate (Hz, default 30). +pub const TICK_HZ_VAR: &str = "ZONE_TICK_HZ"; +/// Env var: patch rate (Hz, default 20, at most the tick rate). +pub const PATCH_HZ_VAR: &str = "ZONE_PATCH_HZ"; +/// Env var: snapshot interval while occupied (ms, default 60000). Each +/// snapshot is a durable write celld keeps (an LTX file per write), so a +/// short interval grows the store and the cost of every later write. +pub const PERSIST_MS_VAR: &str = "ZONE_PERSIST_MS"; +/// Env var: how long an emptied room keeps ticking before it goes dormant +/// (ms, default 10000). Going dormant reports the room's activity and writes +/// its snapshot, so a room whose last player or near watcher comes and goes +/// (a player by a doorway wakes and releases the room behind it every few +/// seconds) would otherwise pay those writes on every swing. +pub const DORMANT_AFTER_MS_VAR: &str = "ZONE_DORMANT_AFTER_MS"; +/// Env var: how long an empty room stays dormant before it hibernates (ms, +/// default 10000). +pub const HIBERNATE_AFTER_MS_VAR: &str = "ZONE_HIBERNATE_AFTER_MS"; +/// Env var: reconnect grace (ms, default 5000). +pub const RECONNECT_GRACE_MS_VAR: &str = "ZONE_RECONNECT_GRACE_MS"; +/// Env var: command-ledger service id of the zone's facts (default +/// `celld-zone`). +pub const FACT_SERVICE_VAR: &str = "ZONE_FACT_SERVICE"; +/// Env var: facts of a lane settled in one cell request at most (default +/// [`DEFAULT_MAX_BATCH`](crate::facts::DEFAULT_MAX_BATCH), 1..=256; 1 +/// sends each fact alone). +pub const FACT_BATCH_VAR: &str = "ZONE_FACT_BATCH"; +/// Env var (debug only, off by default): `name=host:port,…` celld operator +/// listeners asked which node holds the room (celld does not tell +/// application code its node id). +pub const NODES_VAR: &str = "CELLD_ZONE_NODES"; +/// Env var (debug only): a fixed node name (e.g. `dev` for `celld dev`). +pub const NODE_VAR: &str = "CELLD_ZONE_NODE"; + +/// Env var (dev only): `1` makes zone objects read the worker's dev +/// settings (the network simulation, [`NETSIM_SHARD`]). +pub const DEV_SETTINGS_VAR: &str = "ZONE_DEV_SETTINGS"; +/// Env var: the world whose content rollout the zones follow (the shard of +/// the worker's `content-rollout` cell, e.g. `world`; unset: no live +/// content updates). +pub const CONTENT_ROLLOUT_VAR: &str = "ZONE_CONTENT_ROLLOUT"; +/// Env var (A/B switch): `0` makes zones poll their watched cells every +/// second instead of taking pushes (default `1`: pushed, reconciled every +/// ~45 s). +pub const WORLD_PUSH_VAR: &str = "ZONE_WORLD_PUSH"; +/// Env var (A/B switch): `0` turns the distance-based update rates off +/// (every visible change every patch, [`UpdateRates::every_patch`](crate::UpdateRates::every_patch)); +/// default `1`: the zone's [`HostConfig`](crate::HostConfig) rates. +pub const UPDATE_RATES_VAR: &str = "ZONE_UPDATE_RATES"; +pub use crate::netsim::{NETSIM_SHARD, ZONE_DEV_KIND}; + +/// Request header naming the zone (set by [`super::forward_to_zone`]; the +/// object's id has no name on some celld paths). +pub const ZONE_HEADER: &str = "x-celld-zone"; + +/// Route of a message from another zone object +/// ([`crate::zone_message`]): `POST /{zone}/__zone`, internal secret only. +pub const ZONE_MESSAGE_ROUTE: &str = "__zone"; + +/// Close code for sockets of an earlier activation (the room restarted or +/// moved): the client rejoins with a fresh ticket. +pub const CLOSE_RESTARTED: u16 = 1012; + +/// Object settings, from the worker's vars and secrets. +#[derive(Debug, Clone, PartialEq)] +pub struct ObjectOptions { + /// Ticket key secret. + pub ticket_secret: String, + /// Internal secret for cell calls (`DISTRIBUTED_INTERNAL_SECRET`). + pub internal_secret: Option, + /// Hot tick rate. + pub tick_hz: u32, + /// Patch rate. + pub patch_hz: u32, + /// Snapshot interval while occupied. + pub persist_every: Duration, + /// Emptied → dormant. + pub dormant_after: Duration, + /// Dormant → hibernated. + pub hibernate_after: Duration, + /// Reconnect grace window. + pub reconnect_grace: Duration, + /// Fact command-ledger service id. + pub fact_service: String, + /// Facts per cell batch at most ([`FACT_BATCH_VAR`]). + pub fact_batch: usize, + /// Debug node lookup: `(name, operator host:port)`. + pub nodes: Vec<(String, String)>, + /// Debug fixed node name. + pub node: Option, + /// Dev only: read the worker's dev settings (network simulation). + pub dev_settings: bool, + /// The world (`content-rollout` shard) whose live content version and + /// rollout the zone follows. + pub content_rollout: Option, + /// Watched cells push to the zone ([`WORLD_PUSH_VAR`]). + pub world_push: bool, + /// Distance-based update rates on ([`UPDATE_RATES_VAR`]). + pub update_rates: bool, +} + +/// A switch var: on unless set to `0`, `false` or `no`. +fn on_unless_off(get: &impl Fn(&str) -> Option, name: &str) -> bool { + get(name).is_none_or(|v| !matches!(v.trim(), "0" | "false" | "no")) +} + +fn parse( + get: &impl Fn(&str) -> Option, + name: &str, + default: T, +) -> Result { + match get(name).filter(|value| !value.trim().is_empty()) { + None => Ok(default), + Some(value) => value + .trim() + .parse() + .map_err(|_| format!("{name}: not a number: {value}")), + } +} + +impl ObjectOptions { + /// Read the options through `get` (vars, then secrets). + pub fn from_vars(get: impl Fn(&str) -> Option) -> Result { + let ticket_secret = get(TICKET_SECRET_VAR) + .filter(|secret| secret.len() >= 16) + .ok_or_else(|| format!("{TICKET_SECRET_VAR} (>= 16 bytes) is required"))?; + let tick_hz: u32 = parse(&get, TICK_HZ_VAR, 30)?; + if !(1..=120).contains(&tick_hz) { + return Err(format!("{TICK_HZ_VAR} must be within 1..=120")); + } + let patch_hz: u32 = parse(&get, PATCH_HZ_VAR, 20)?; + let fact_batch: usize = parse(&get, FACT_BATCH_VAR, crate::facts::DEFAULT_MAX_BATCH)?; + if !(1..=256).contains(&fact_batch) { + return Err(format!("{FACT_BATCH_VAR} must be within 1..=256")); + } + let nodes = get(NODES_VAR) + .unwrap_or_default() + .split(',') + .filter_map(|entry| { + let (name, addr) = entry.trim().split_once('=')?; + (!name.is_empty() && !addr.is_empty()).then(|| (name.into(), addr.into())) + }) + .collect(); + Ok(Self { + ticket_secret, + internal_secret: get(distributed::cell_host::CELL_INTERNAL_SECRET_ENV) + .filter(|secret| !secret.is_empty()), + tick_hz, + patch_hz: patch_hz.clamp(1, tick_hz), + persist_every: Duration::from_millis(parse(&get, PERSIST_MS_VAR, 60_000)?), + dormant_after: Duration::from_millis(parse(&get, DORMANT_AFTER_MS_VAR, 10_000)?), + hibernate_after: Duration::from_millis(parse(&get, HIBERNATE_AFTER_MS_VAR, 10_000)?), + reconnect_grace: Duration::from_millis(parse(&get, RECONNECT_GRACE_MS_VAR, 5_000)?), + fact_service: get(FACT_SERVICE_VAR) + .filter(|service| !service.trim().is_empty()) + .unwrap_or_else(|| "celld-zone".into()), + fact_batch, + nodes, + node: get(NODE_VAR).filter(|node| !node.is_empty()), + dev_settings: get(DEV_SETTINGS_VAR) + .is_some_and(|v| matches!(v.trim(), "1" | "true" | "yes")), + content_rollout: get(CONTENT_ROLLOUT_VAR) + .map(|world| world.trim().to_string()) + .filter(|world| !world.is_empty()), + world_push: on_unless_off(&get, WORLD_PUSH_VAR), + update_rates: on_unless_off(&get, UPDATE_RATES_VAR), + }) + } +} + +/// Where a room is in its life (per object activation). +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum RoomState { + /// No zone in memory (fresh activation, or hibernated and dropped). + Cold, + /// Zone in memory with players (or just woke up). + Active, + /// Empty since `since_ms` (Unix ms); snapshot written. + Dormant { + /// When the last player left. + since_ms: f64, + }, +} + +impl RoomState { + /// True when an empty room should hibernate at `now_ms`. + pub fn hibernate_due(&self, now_ms: f64, after: Duration) -> bool { + match self { + Self::Dormant { since_ms } => now_ms + 1.0 >= since_ms + after.as_millis() as f64, + _ => false, + } + } +} + +/// A self-correcting fixed-rate schedule over absolute deadlines +/// (`setInterval` drifts: 33.3 ms gave 35 ms on celld). Each wake-up aims at +/// `start + k × step`; deadlines already missed are skipped (the fixed +/// timestep catches up inside one `advance`). +#[derive(Debug, Clone)] +pub struct TickSchedule { + start_ms: f64, + step_ms: f64, + k: u64, +} + +impl TickSchedule { + /// A schedule at `hz` from `now_ms`. + pub fn new(now_ms: f64, hz: u32) -> Self { + Self { + start_ms: now_ms, + step_ms: 1000.0 / f64::from(hz.max(1)), + k: 1, + } + } + + /// The next deadline. + pub fn deadline(&self) -> f64 { + self.start_ms + self.k as f64 * self.step_ms + } + + /// How long to wait from `now_ms` (never negative). + pub fn wait_ms(&self, now_ms: f64) -> f64 { + (self.deadline() - now_ms).max(0.0) + } + + /// Record a wake-up at `now_ms`: returns how late it was, and moves to + /// the first deadline after `now_ms`. + pub fn woke(&mut self, now_ms: f64) -> f64 { + let late = (now_ms - self.deadline()).max(0.0); + let next = ((now_ms - self.start_ms) / self.step_ms).floor() as u64 + 1; + self.k = next.max(self.k + 1); + late + } +} + +/// A fact in the object's durable outbox (written before it is sent, +/// deleted once settled, resent by the next activation). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct StoredFact { + /// Idempotency key. + pub key: String, + /// Command. + pub command: String, + /// Input. + pub input: Value, + /// Bound principal. + pub principal: Option, + /// Stamp as its `x-game-*` session variables. + pub stamp: HashMap, +} + +impl StoredFact { + /// Storage key of a fact. + pub fn storage_key(key: &str) -> String { + format!("{OUTBOX_PREFIX}{key}") + } + + /// Encode `fact`. + pub fn of(fact: &Fact) -> Self { + Self { + key: fact.key().to_string(), + command: fact.command().to_string(), + input: fact.input().clone(), + principal: fact.principal().map(str::to_string), + stamp: fact.stamp().session_vars().into_iter().collect(), + } + } + + /// Decode (None for a malformed stamp). + pub fn into_fact(self) -> Option { + let stamp = FactStamp::from_session_vars(&self.stamp)?; + Some(Fact::trusted( + self.key, + self.command, + self.input, + self.principal, + stamp, + )) + } +} + +/// Storage key prefix of the durable fact outbox. +pub const OUTBOX_PREFIX: &str = "fact:"; + +/// Durable Object binding of a cell kind: upper case, `-` → `_` +/// (`zone-activity` → `ZONE_ACTIVITY`, `crawler` → `CRAWLER`). +pub fn cell_binding(kind: &str) -> String { + kind.chars() + .map(|c| { + if c == '-' { + '_' + } else { + c.to_ascii_uppercase() + } + }) + .collect() +} + +/// Classify a cell wait-path answer (`status`, JSON `body`). +pub fn classify_wait_path(status: u16, body: &Value) -> Result { + if (200..300).contains(&status) { + return Ok(FactReceipt { + payload: body.get("payload").cloned().unwrap_or(Value::Null), + replayed: body + .pointer("/receipt/replayed") + .and_then(Value::as_bool) + .unwrap_or(false), + }); + } + let code = body.get("code").and_then(Value::as_str).unwrap_or(""); + let message = body + .get("error") + .and_then(Value::as_str) + .unwrap_or("rejected"); + let detail = format!("HTTP {status} {code}: {message}"); + if status >= 500 || matches!(status, 408 | 429) || code == "COMMAND_IN_PROGRESS" { + Err(FactError::Retryable(detail)) + } else { + Err(FactError::Permanent(detail)) + } +} + +/// `"{prefix}{zone}[/rest]"` → `(zone, rest)` (percent-decoded zone; None +/// when the path does not match or the zone is empty / not printable). +pub fn zone_from_path<'a>(prefix: &str, path: &'a str) -> Option<(String, &'a str)> { + let rest = path.strip_prefix(prefix)?; + let (raw, tail) = rest.split_once('/').unwrap_or((rest, "")); + let zone = percent_decode(raw)?; + (!zone.is_empty() + && zone.len() <= 128 + && zone.bytes().all(|byte| (0x21..=0x7e).contains(&byte))) + .then_some((zone, tail)) +} + +fn percent_decode(segment: &str) -> Option { + let bytes = segment.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' { + out.push(u8::from_str_radix(segment.get(i + 1..i + 3)?, 16).ok()?); + i += 3; + } else { + out.push(bytes[i]); + i += 1; + } + } + String::from_utf8(out).ok() +} + +/// Percentiles of the last values (tick timing in the debug info). +#[derive(Debug, Clone, Default)] +pub struct Window { + values: std::collections::VecDeque, +} + +impl Window { + const MAX: usize = 900; + + /// Add a value. + pub fn push(&mut self, value: f64) { + if self.values.len() == Self::MAX { + self.values.pop_front(); + } + self.values.push_back(value); + } + + /// The `p` percentile (0 when empty). + pub fn percentile(&self, p: f64) -> f64 { + if self.values.is_empty() { + return 0.0; + } + let mut sorted: Vec = self.values.iter().copied().collect(); + sorted.sort_by(f64::total_cmp); + sorted[((sorted.len() - 1) as f64 * p.clamp(0.0, 1.0)).round() as usize] + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn vars(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option { + let map: HashMap = pairs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + move |name| map.get(name).cloned() + } + + #[test] + fn options_need_a_ticket_secret_and_default_the_rest() { + assert!(ObjectOptions::from_vars(vars(&[])).is_err()); + assert!(ObjectOptions::from_vars(vars(&[(TICKET_SECRET_VAR, "short")])).is_err()); + let options = + ObjectOptions::from_vars(vars(&[(TICKET_SECRET_VAR, "0123456789abcdef")])).unwrap(); + assert_eq!((options.tick_hz, options.patch_hz), (30, 20)); + assert_eq!(options.dormant_after, Duration::from_secs(10)); + assert_eq!(options.hibernate_after, Duration::from_secs(10)); + assert!(options.nodes.is_empty(), "node lookup is off by default"); + assert_eq!(options.fact_service, "celld-zone"); + assert!( + options.world_push && options.update_rates, + "switches default on" + ); + let options = ObjectOptions::from_vars(vars(&[ + (TICKET_SECRET_VAR, "0123456789abcdef"), + (TICK_HZ_VAR, "10"), + (PATCH_HZ_VAR, "20"), + (NODES_VAR, "node-a=127.0.0.1:1, bad ,node-b=127.0.0.1:2"), + ("DISTRIBUTED_INTERNAL_SECRET", "s"), + (WORLD_PUSH_VAR, "0"), + (UPDATE_RATES_VAR, "false"), + ])) + .unwrap(); + assert!(!options.world_push && !options.update_rates); + assert_eq!(options.patch_hz, 10, "patches never outpace ticks"); + assert_eq!(options.nodes.len(), 2); + assert_eq!(options.internal_secret.as_deref(), Some("s")); + assert!(ObjectOptions::from_vars(vars(&[ + (TICKET_SECRET_VAR, "0123456789abcdef"), + (TICK_HZ_VAR, "0"), + ])) + .is_err()); + } + + #[test] + fn the_tick_schedule_corrects_itself_and_skips_missed_deadlines() { + let mut schedule = TickSchedule::new(1000.0, 20); + assert_eq!(schedule.deadline(), 1050.0); + assert_eq!(schedule.wait_ms(1010.0), 40.0); + // Woke 3 ms late: the next deadline stays on the grid (no drift). + assert_eq!(schedule.woke(1053.0), 3.0); + assert_eq!(schedule.deadline(), 1100.0); + // A 130 ms stall skips the missed deadlines. + assert_eq!(schedule.woke(1230.0), 130.0); + assert_eq!(schedule.deadline(), 1250.0); + assert_eq!(schedule.wait_ms(1300.0), 0.0); + // Early wake-ups still advance by one step. + let before = schedule.deadline(); + schedule.woke(before - 5.0); + assert_eq!(schedule.deadline(), before + 50.0); + } + + #[test] + fn dormant_rooms_hibernate_after_the_delay() { + let after = Duration::from_millis(500); + assert!(!RoomState::Active.hibernate_due(10_000.0, after)); + assert!(!RoomState::Cold.hibernate_due(10_000.0, after)); + let dormant = RoomState::Dormant { since_ms: 1_000.0 }; + assert!(!dormant.hibernate_due(1_400.0, after)); + assert!(dormant.hibernate_due(1_500.0, after)); + } + + #[test] + fn stored_facts_round_trip() { + let fact = Fact::trusted( + "kill:pit:1:m1:0", + "crawler.record_kill", + json!({ "mob": 1 }), + Some("alice".into()), + FactStamp { + zone_id: "pit.0.0".into(), + tick: 7, + activation: 9, + seq: 2, + emitted_at_ms: 1_700_000_000_000, + ..FactStamp::default() + }, + ); + let stored = StoredFact::of(&fact); + let text = serde_json::to_string(&stored).unwrap(); + let back: StoredFact = serde_json::from_str(&text).unwrap(); + assert_eq!(back.into_fact().unwrap(), fact); + assert_eq!(StoredFact::storage_key("k"), format!("{OUTBOX_PREFIX}k")); + } + + #[test] + fn wait_path_answers_are_classified() { + let ok = classify_wait_path( + 200, + &json!({ "payload": { "xp": 3 }, "receipt": { "replayed": true } }), + ) + .unwrap(); + assert_eq!(ok.payload, json!({ "xp": 3 })); + assert!(ok.replayed); + let retry = |status, code: &str| { + matches!( + classify_wait_path(status, &json!({ "code": code })), + Err(FactError::Retryable(_)) + ) + }; + assert!(retry(503, "INTERNAL")); + assert!(retry(409, "COMMAND_IN_PROGRESS")); + assert!(retry(429, "")); + assert!(!retry(401, "UNAUTHORIZED")); + assert!(!retry(422, "REJECTED")); + } + + #[test] + fn bindings_and_paths() { + assert_eq!(cell_binding("zone-activity"), "ZONE_ACTIVITY"); + assert_eq!(cell_binding("crawler"), "CRAWLER"); + assert_eq!( + zone_from_path("/zones/", "/zones/pit.1.-2/info"), + Some(("pit.1.-2".to_string(), "info")) + ); + assert_eq!( + zone_from_path("/zones/", "/zones/a%20b"), + None, + "zones are printable ASCII without spaces" + ); + assert_eq!(zone_from_path("/zones/", "/zones/"), None); + assert_eq!(zone_from_path("/zones/", "/other/x"), None); + } + + #[test] + fn windows_report_percentiles() { + let mut window = Window::default(); + assert_eq!(window.percentile(0.5), 0.0); + for v in 1..=100 { + window.push(f64::from(v)); + } + assert_eq!(window.percentile(0.0), 1.0); + assert_eq!(window.percentile(1.0), 100.0); + assert!((window.percentile(0.99) - 99.0).abs() <= 1.0); + } +} diff --git a/distributed_game/src/claims.rs b/distributed_game/src/claims.rs new file mode 100644 index 000000000..333868e66 --- /dev/null +++ b/distributed_game/src/claims.rs @@ -0,0 +1,247 @@ +//! Ticket extension claims: game-declared facts the ticket issuer vouches +//! for (match id, team, party, mode), carried next to the fixed +//! [`TicketClaims`](crate::TicketClaims) fields. +//! +//! The issuer (the web backend, a matchmaker) signs them under the ticket's +//! `ext` object; the zone reads them from +//! [`TicketClaims::extensions`](crate::TicketClaims::extensions) in +//! [`Zone::on_auth`](crate::Zone::on_auth) and from +//! [`PlayerInfo::extensions`](crate::PlayerInfo::extensions) afterwards, typed +//! with [`TicketExtensions::typed`]. Handoff transfer tickets carry them to +//! the next zone unchanged. +//! +//! A game declares the schema once with `#[derive(TicketExtension)]`: +//! +//! ```rust,ignore +//! #[derive(Serialize, Deserialize, TicketExtension)] +//! pub struct MatchClaims { pub match_id: String, pub team: u8 } +//! // config.admission = config.admission.with_ticket_extensions::(); +//! ``` +//! +//! The derive refuses identity-, reward- and economy-looking names (the +//! same deny list as `FactCommand`): identity is only ever the verified +//! `sub`, and amounts are decided by command handlers. The `net` server +//! refuses a ticket whose extensions do not match the declared schema +//! (unknown names, wrong types), and any ticket with extensions when no +//! schema is declared. + +use std::collections::BTreeMap; +use std::fmt; + +use serde::de::DeserializeOwned; +use serde::Serialize; +use serde_json::{Map, Value}; + +/// Largest accepted extension object, as compact JSON (bytes). +pub const MAX_EXTENSION_BYTES: usize = 2048; + +/// A game-declared extension claims type (`#[derive(TicketExtension)]`). +pub trait TicketExtension: Serialize + DeserializeOwned { + /// Claim names as serialized (serde renames applied). + const CLAIMS: &'static [&'static str]; +} + +/// Why extension claims were refused. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ExtensionError { + /// `ext` is not a JSON object. + NotAnObject, + /// Larger than [`MAX_EXTENSION_BYTES`]. + TooLarge, + /// A name the declared schema does not know. + Unknown(String), + /// Extensions present but the server declares no schema. + Undeclared, + /// The values do not decode as the declared type. + Invalid(String), +} + +impl fmt::Display for ExtensionError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::NotAnObject => f.write_str("extension claims must be an object"), + Self::TooLarge => write!(f, "extension claims exceed {MAX_EXTENSION_BYTES} bytes"), + Self::Unknown(name) => write!(f, "undeclared extension claim `{name}`"), + Self::Undeclared => f.write_str("this server declares no ticket extension claims"), + Self::Invalid(why) => write!(f, "invalid extension claims: {why}"), + } + } +} + +impl std::error::Error for ExtensionError {} + +/// Verified extension claims (name → JSON value), empty for a ticket +/// without any. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct TicketExtensions(BTreeMap); + +impl TicketExtensions { + /// No extensions. + pub fn new() -> Self { + Self::default() + } + + /// From a typed declaration. + pub fn from_typed(claims: &E) -> Result { + let value = + serde_json::to_value(claims).map_err(|e| ExtensionError::Invalid(e.to_string()))?; + Self::from_json(value) + } + + /// From a JSON object (the ticket's `ext`), size-checked. + pub fn from_json(value: Value) -> Result { + let Value::Object(map) = value else { + return Err(ExtensionError::NotAnObject); + }; + let extensions = Self(map.into_iter().collect()); + if extensions.encoded_len() > MAX_EXTENSION_BYTES { + return Err(ExtensionError::TooLarge); + } + Ok(extensions) + } + + /// As a JSON object (what the ticket signs under `ext`). + pub fn to_json(&self) -> Value { + Value::Object(self.0.clone().into_iter().collect::>()) + } + + fn encoded_len(&self) -> usize { + self.to_json().to_string().len() + } + + /// True when the ticket carried none. + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// One raw claim. + pub fn get(&self, name: &str) -> Option<&Value> { + self.0.get(name) + } + + /// All claims, by name. + pub fn iter(&self) -> impl Iterator { + self.0.iter().map(|(k, v)| (k.as_str(), v)) + } + + /// Decode as the declared type. Names `E` does not declare are refused. + pub fn typed(&self) -> Result { + if let Some(unknown) = self + .0 + .keys() + .find(|name| !E::CLAIMS.contains(&name.as_str())) + { + return Err(ExtensionError::Unknown(unknown.clone())); + } + serde_json::from_value(self.to_json()).map_err(|e| ExtensionError::Invalid(e.to_string())) + } +} + +/// The extension schema a server admits ([`ExtensionSchema::of`]). +#[derive(Clone, Copy)] +pub struct ExtensionSchema { + claims: &'static [&'static str], + check: fn(&TicketExtensions) -> Result<(), ExtensionError>, +} + +impl fmt::Debug for ExtensionSchema { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ExtensionSchema") + .field("claims", &self.claims) + .finish() + } +} + +impl ExtensionSchema { + /// Admit extensions that decode as `E` (missing optional fields are + /// fine; unknown names are not). + pub fn of() -> Self { + Self { + claims: E::CLAIMS, + check: |ext| ext.typed::().map(drop), + } + } + + /// Declared claim names. + pub fn claims(&self) -> &'static [&'static str] { + self.claims + } + + /// Check verified extensions against the schema. + pub fn validate(&self, extensions: &TicketExtensions) -> Result<(), ExtensionError> { + if extensions.is_empty() { + return Ok(()); + } + (self.check)(extensions) + } +} + +/// Check extensions against an optional server schema: none declared means +/// none admitted. +pub fn validate_extensions( + schema: Option<&ExtensionSchema>, + extensions: &TicketExtensions, +) -> Result<(), ExtensionError> { + match schema { + Some(schema) => schema.validate(extensions), + None if extensions.is_empty() => Ok(()), + None => Err(ExtensionError::Undeclared), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde::Deserialize; + use serde_json::json; + + #[derive(Debug, PartialEq, Serialize, Deserialize)] + struct MatchClaims { + match_id: String, + #[serde(default)] + team: Option, + } + + impl TicketExtension for MatchClaims { + const CLAIMS: &'static [&'static str] = &["match_id", "team"]; + } + + #[test] + fn typed_round_trip_and_schema_checks() { + let claims = MatchClaims { + match_id: "m-1".into(), + team: Some(2), + }; + let ext = TicketExtensions::from_typed(&claims).unwrap(); + assert_eq!(ext.get("team"), Some(&json!(2))); + assert_eq!(ext.typed::().unwrap(), claims); + let schema = ExtensionSchema::of::(); + schema.validate(&ext).unwrap(); + schema.validate(&TicketExtensions::new()).unwrap(); + + let unknown = TicketExtensions::from_json(json!({"match_id": "m", "gold": 9})).unwrap(); + assert_eq!( + schema.validate(&unknown), + Err(ExtensionError::Unknown("gold".into())) + ); + let mistyped = TicketExtensions::from_json(json!({"match_id": 7})).unwrap(); + assert!(matches!( + schema.validate(&mistyped), + Err(ExtensionError::Invalid(_)) + )); + assert_eq!( + TicketExtensions::from_json(json!(["x"])), + Err(ExtensionError::NotAnObject) + ); + let big = "x".repeat(MAX_EXTENSION_BYTES); + assert_eq!( + TicketExtensions::from_json(json!({ "match_id": big })), + Err(ExtensionError::TooLarge) + ); + assert_eq!( + validate_extensions(None, &ext), + Err(ExtensionError::Undeclared) + ); + validate_extensions(None, &TicketExtensions::new()).unwrap(); + } +} diff --git a/distributed_game/src/clock.rs b/distributed_game/src/clock.rs new file mode 100644 index 000000000..a1b60758c --- /dev/null +++ b/distributed_game/src/clock.rs @@ -0,0 +1,136 @@ +//! Injectable monotonic clocks. +//! +//! The runtime never reads wall time directly. Every [`ZoneHost`](crate::ZoneHost) +//! is built with an `Arc`; production uses [`SystemClock`] and tests +//! use [`ManualClock`] to drive time explicitly, which (together with the seeded +//! [`ZoneRng`](crate::ZoneRng)) makes simulation runs reproducible. +//! +//! A clock reports elapsed time since its own origin as a [`Duration`]. Only +//! differences matter to the runtime; values are also sent to clients as +//! "server time" in milliseconds for clock synchronization. +//! +//! [`Clock::unix_ms`] is the clock's wall time (Unix milliseconds), used to +//! stamp facts ([`FactStamp::emitted_at_ms`](crate::FactStamp::emitted_at_ms)) +//! so facts from different zones and hosts can be ordered. It advances with +//! [`now`](Clock::now) and never goes backwards either. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +/// Monotonic time source. +pub trait Clock: Send + Sync + 'static { + /// Time elapsed since this clock's origin. Must never go backwards. + fn now(&self) -> Duration; + + /// Wall time in Unix milliseconds. Must never go backwards. + fn unix_ms(&self) -> u64; +} + +/// Real monotonic clock backed by [`Instant`]. Its wall time is the system +/// time read once at creation plus the monotonic elapsed time, so a system +/// clock step (NTP) never moves fact stamps backwards. +#[derive(Debug, Clone)] +pub struct SystemClock { + origin: Instant, + origin_unix: Duration, +} + +impl SystemClock { + /// Clock whose origin is "now". + pub fn new() -> Self { + Self { + origin: Instant::now(), + origin_unix: SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default(), + } + } +} + +impl Default for SystemClock { + fn default() -> Self { + Self::new() + } +} + +impl Clock for SystemClock { + fn now(&self) -> Duration { + self.origin.elapsed() + } + + fn unix_ms(&self) -> u64 { + (self.origin_unix + self.origin.elapsed()).as_millis() as u64 + } +} + +/// Virtual clock advanced explicitly; clones share the same time. Its wall +/// time is a fixed Unix origin (0 unless set with +/// [`with_unix_origin_ms`](Self::with_unix_origin_ms)) plus the virtual time. +#[derive(Debug, Clone, Default)] +pub struct ManualClock { + nanos: Arc, + unix_origin_ms: u64, +} + +impl ManualClock { + /// Clock starting at zero. + pub fn new() -> Self { + Self::default() + } + + /// The same clock reporting wall time `origin_ms + now()` (e.g. two + /// hosts whose wall clocks disagree). Clones made before this call keep + /// their own origin but share the virtual time. + pub fn with_unix_origin_ms(mut self, origin_ms: u64) -> Self { + self.unix_origin_ms = origin_ms; + self + } + + /// Move time forward by `by`. + pub fn advance(&self, by: Duration) { + self.nanos.fetch_add(by.as_nanos() as u64, Ordering::SeqCst); + } + + /// Jump to an absolute time. Ignored if it would move time backwards. + pub fn set(&self, to: Duration) { + self.nanos.fetch_max(to.as_nanos() as u64, Ordering::SeqCst); + } +} + +impl Clock for ManualClock { + fn now(&self) -> Duration { + Duration::from_nanos(self.nanos.load(Ordering::SeqCst)) + } + + fn unix_ms(&self) -> u64 { + self.unix_origin_ms + self.now().as_millis() as u64 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn manual_wall_time_follows_virtual_time() { + let clock = ManualClock::new().with_unix_origin_ms(1_000); + let shared = clock.clone(); + assert_eq!(clock.unix_ms(), 1_000); + shared.advance(Duration::from_millis(250)); + assert_eq!(clock.unix_ms(), 1_250); + let skewed = shared.clone().with_unix_origin_ms(500); + assert_eq!(skewed.unix_ms(), 750); + } + + #[test] + fn system_wall_time_is_close_to_system_time() { + let clock = SystemClock::new(); + let system = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis() as u64; + assert!(clock.unix_ms().abs_diff(system) < 1_000); + assert!(clock.unix_ms() <= clock.unix_ms()); + } +} diff --git a/distributed_game/src/codec.rs b/distributed_game/src/codec.rs new file mode 100644 index 000000000..504deecad --- /dev/null +++ b/distributed_game/src/codec.rs @@ -0,0 +1,617 @@ +//! Typed payload codec behind the authoring derives. +//! +//! Entity fields, inputs and events all use **one** value codec. Its scalar +//! encodings are exactly the entity [`FieldType`] encodings (`PROTOCOL.md` +//! §4), so a value means the same bytes whether it is replicated, sent as an +//! input or carried in an event. Payloads (inputs, events) may additionally +//! use types an entity field cannot: `i8`, `i16`, `u64`, `f64`, long +//! strings, lists, options and nested records. +//! +//! | Rust | [`WireType`] | bytes | +//! |---|---|---| +//! | `bool` | `bool` | `u8` 0/1 | +//! | `u8` / `i8` | `u8` / `i8` | one byte (two's complement for `i8`) | +//! | `u16` / `u32` | `u16` / `u32` | varuint (`u16` checked ≤ 65535) | +//! | `i16` / `i32` | `i16` / `i32` | zigzag varint (`i16` range-checked) | +//! | `u64` | `u64` | varuint up to `2^53 - 1` (saturating; exact in JS) | +//! | `f32` / `f64` | `f32` / `f64` | binary32 / binary64 LE | +//! | `f32` + `#[quant(..)]` | `quant` | varuint (§4.1) | +//! | `f32` + `#[angle(..)]` | `angle` | varuint (§4.2) | +//! | `String` | `short_str` | `u8` length + UTF-8 (truncated to 255 bytes) | +//! | `String` + `#[long]` | `str` | varuint length + UTF-8 | +//! | `Vec` | `bytes` | varuint length + bytes | +//! | `Vec` | `list` | varuint count + items | +//! | `Option` | `optional` | `u8` 0 (none) / 1 + value | +//! | `#[derive(GameRecord)]` struct | `record` | fields in declaration order | +//! +//! The derives in `distributed_game_macros` generate the calls; use this +//! module directly only for hand-written payloads. + +use serde::{Deserialize, Serialize}; + +use crate::protocol::wire::{DecodeError, Reader, Writer}; +use crate::schema::{FieldType, FieldValue}; +use crate::surface::RecordSurface; + +/// Wire type of one payload or entity field, as exported in the +/// [`GameSurface`](crate::surface::GameSurface). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] +pub enum WireType { + /// `u8` 0/1. + Bool, + /// One byte. + U8, + /// One byte, two's complement. + I8, + /// varuint ≤ 65535. + U16, + /// zigzag varint in `i16` range. + I16, + /// varuint. + U32, + /// zigzag varint. + I32, + /// varuint up to `2^53 - 1`. + U64, + /// binary32 LE. + F32, + /// binary64 LE. + F64, + /// Clamped linear quantization (`FieldType::QuantF32`). + Quant { + /// Lower bound. + min: f32, + /// Upper bound. + max: f32, + /// Precision in bits (1..=32). + bits: u8, + }, + /// Wrapped angle quantization (`FieldType::Angle`). + Angle { + /// Precision in bits (1..=32). + bits: u8, + }, + /// `u8` length + UTF-8. + ShortStr, + /// varuint length + UTF-8. + Str, + /// varuint length + bytes. + Bytes, + /// varuint count + items. + List { + /// Item type. + item: Box, + }, + /// `u8` presence + value. + Optional { + /// Value type. + item: Box, + }, + /// A named record (see the surface's `records`). + Record { + /// Record name (the Rust type name). + name: String, + }, +} + +impl WireType { + /// The equivalent entity [`FieldType`], if this type can be replicated. + pub fn field_type(&self) -> Option { + Some(match self { + Self::Bool => FieldType::Bool, + Self::U8 => FieldType::U8, + Self::U16 => FieldType::U16, + Self::U32 => FieldType::U32, + Self::I32 => FieldType::I32, + Self::F32 => FieldType::F32, + Self::Quant { min, max, bits } => FieldType::QuantF32 { + min: *min, + max: *max, + bits: *bits, + }, + Self::Angle { bits } => FieldType::Angle { bits: *bits }, + Self::ShortStr => FieldType::ShortStr, + Self::Bytes => FieldType::Bytes, + _ => return None, + }) + } + + /// The payload type of an entity field type. + pub fn of_field(ty: FieldType) -> Self { + match ty { + FieldType::Bool => Self::Bool, + FieldType::U8 => Self::U8, + FieldType::U16 => Self::U16, + FieldType::U32 => Self::U32, + FieldType::I32 => Self::I32, + FieldType::F32 => Self::F32, + FieldType::QuantF32 { min, max, bits } => Self::Quant { min, max, bits }, + FieldType::Angle { bits } => Self::Angle { bits }, + FieldType::ShortStr => Self::ShortStr, + FieldType::Bytes => Self::Bytes, + } + } +} + +/// A Rust type with a default payload encoding (see the module table). +/// +/// Implemented for the scalar types, `String`, `Vec`, `Option`, and by +/// `#[derive(GameRecord)]` / `#[derive(GameEvent)]` for structs. +#[diagnostic::on_unimplemented( + message = "`{Self}` has no game payload encoding", + label = "unsupported payload field type", + note = "supported: bool, u8, i8, u16, i16, u32, i32, u64, f32, f64, String, Vec, Option and `#[derive(GameRecord)]` structs" +)] +pub trait Wire: Sized { + /// Wire type descriptor. + fn wire_type() -> WireType; + /// Append the encoding. + fn encode(&self, w: &mut Writer); + /// Decode one value. + fn decode(r: &mut Reader<'_>) -> Result; + /// Push the definitions of every record this type mentions (itself + /// included), depth first; duplicates are removed by the surface. + fn records(_out: &mut Vec) {} +} + +macro_rules! wire_scalar { + ($ty:ty, $wire:ident, |$w:ident, $v:ident| $enc:expr, |$r:ident| $dec:expr) => { + impl Wire for $ty { + fn wire_type() -> WireType { + WireType::$wire + } + fn encode(&self, $w: &mut Writer) { + let $v = *self; + $enc; + } + fn decode($r: &mut Reader<'_>) -> Result { + $dec + } + } + }; +} + +wire_scalar!(bool, Bool, |w, v| w.bool(v), |r| r.bool()); +wire_scalar!(u8, U8, |w, v| w.u8(v), |r| r.u8()); +wire_scalar!(i8, I8, |w, v| w.u8(v as u8), |r| Ok(r.u8()? as i8)); +wire_scalar!(u16, U16, |w, v| w.varuint(u32::from(v)), |r| { + u16::try_from(r.varuint()?).map_err(|_| DecodeError::Invalid("u16 out of range")) +}); +wire_scalar!(i16, I16, |w, v| w.varint(i32::from(v)), |r| { + i16::try_from(r.varint()?).map_err(|_| DecodeError::Invalid("i16 out of range")) +}); +wire_scalar!(u32, U32, |w, v| w.varuint(v), |r| r.varuint()); +wire_scalar!(i32, I32, |w, v| w.varint(v), |r| r.varint()); +wire_scalar!(u64, U64, |w, v| w.varuint64(v), |r| r.varuint64()); +wire_scalar!(f32, F32, |w, v| w.f32(v), |r| r.f32()); +wire_scalar!(f64, F64, |w, v| w.f64(v), |r| r.f64()); + +impl Wire for String { + fn wire_type() -> WireType { + WireType::ShortStr + } + fn encode(&self, w: &mut Writer) { + w.short_string(self); + } + fn decode(r: &mut Reader<'_>) -> Result { + r.short_string() + } +} + +impl Wire for Vec { + fn wire_type() -> WireType { + WireType::List { + item: Box::new(T::wire_type()), + } + } + fn encode(&self, w: &mut Writer) { + w.varuint(u32::try_from(self.len()).unwrap_or(u32::MAX)); + for item in self { + item.encode(w); + } + } + fn decode(r: &mut Reader<'_>) -> Result { + let count = r.varuint()? as usize; + // Every item takes at least one byte: bound the allocation. + if count > r.remaining() { + return Err(DecodeError::UnexpectedEof); + } + let mut out = Vec::with_capacity(count); + for _ in 0..count { + out.push(T::decode(r)?); + } + Ok(out) + } + fn records(out: &mut Vec) { + T::records(out); + } +} + +impl Wire for Option { + fn wire_type() -> WireType { + WireType::Optional { + item: Box::new(T::wire_type()), + } + } + fn encode(&self, w: &mut Writer) { + match self { + None => { + w.u8(0); + } + Some(value) => { + w.u8(1); + value.encode(w); + } + } + } + fn decode(r: &mut Reader<'_>) -> Result { + match r.u8()? { + 0 => Ok(None), + 1 => Ok(Some(T::decode(r)?)), + _ => Err(DecodeError::Invalid("option tag must be 0 or 1")), + } + } + fn records(out: &mut Vec) { + T::records(out); + } +} + +/// `#[quant(..)]` / `#[angle(..)]` / `#[long]` field encodings (used by the +/// generated code). +pub mod special { + use super::*; + + /// An `f32` encoded as entity field type `ty` (quantized or angle). + pub fn encode_f32(w: &mut Writer, ty: FieldType, v: f32) { + ty.encode(w, &FieldValue::F(v)); + } + + /// Inverse of [`encode_f32`] (range-checked). + pub fn decode_f32(r: &mut Reader<'_>, ty: FieldType) -> Result { + match ty.decode(r)? { + FieldValue::F(v) => Ok(v), + _ => Err(DecodeError::Invalid("expected a float field type")), + } + } + + /// varuint-length string (`#[long]`). + pub fn encode_long(w: &mut Writer, v: &str) { + w.string(v); + } + + /// Inverse of [`encode_long`]. + pub fn decode_long(r: &mut Reader<'_>) -> Result { + r.string() + } +} + +/// Encode a whole value into a fresh buffer. +pub fn to_bytes(value: &T) -> Vec { + let mut w = Writer::new(); + value.encode(&mut w); + w.into_bytes() +} + +/// Decode a whole value; trailing bytes are an error. +pub fn from_bytes(bytes: &[u8]) -> Result { + let mut r = Reader::new(bytes); + let value = T::decode(&mut r)?; + r.finish()?; + Ok(value) +} + +/// A value as the JSON a client decodes from its encoding: records are +/// objects keyed by Rust field name, lists arrays, `None` `null`, `bytes` +/// arrays of numbers, and every float the exact binary32 / binary64 value +/// the decoder yields (quantized fields after quantization). Built by +/// encoding the value and decoding it against its wire type, so it is the +/// codec's view by construction +/// ([`GameSurface::constant`](crate::GameSurface::constant)). +pub fn to_json_value(value: &T) -> Result { + let mut records = Vec::new(); + T::records(&mut records); + let bytes = to_bytes(value); + let mut r = Reader::new(&bytes); + let json = decode_json(&T::wire_type(), &records, &mut r)?; + r.finish()?; + Ok(json) +} + +/// Decode one value of type `ty` (records looked up in `records`) as JSON; +/// see [`to_json_value`]. Non-finite floats are rejected. +pub fn decode_json( + ty: &WireType, + records: &[RecordSurface], + r: &mut Reader<'_>, +) -> Result { + use serde_json::{json, Map, Value}; + let float = |v: f64| { + serde_json::Number::from_f64(v) + .map(Value::Number) + .ok_or(DecodeError::Invalid("non-finite float")) + }; + Ok(match ty { + WireType::Bool => json!(r.bool()?), + WireType::U8 => json!(r.u8()?), + WireType::I8 => json!(r.u8()? as i8), + WireType::U16 => json!(u16::decode(r)?), + WireType::I16 => json!(i16::decode(r)?), + WireType::U32 => json!(r.varuint()?), + WireType::I32 => json!(r.varint()?), + WireType::U64 => json!(r.varuint64()?), + WireType::F32 => float(f64::from(r.f32()?))?, + WireType::F64 => float(r.f64()?)?, + WireType::Quant { .. } | WireType::Angle { .. } => { + let field = ty.field_type().expect("float field type"); + float(f64::from(special::decode_f32(r, field)?))? + } + WireType::ShortStr => json!(r.short_string()?), + WireType::Str => json!(r.string()?), + WireType::Bytes => json!(r.bytes()?), + WireType::List { item } => { + let count = r.varuint()? as usize; + // As `Vec::decode`: every item takes at least one byte. + if count > r.remaining() { + return Err(DecodeError::UnexpectedEof); + } + let mut out = Vec::with_capacity(count); + for _ in 0..count { + out.push(decode_json(item, records, r)?); + } + Value::Array(out) + } + WireType::Optional { item } => match r.u8()? { + 0 => Value::Null, + 1 => decode_json(item, records, r)?, + _ => return Err(DecodeError::Invalid("option tag must be 0 or 1")), + }, + WireType::Record { name } => { + let record = records + .iter() + .find(|record| &record.name == name) + .ok_or(DecodeError::Invalid("unknown record"))?; + let mut out = Map::new(); + for field in &record.fields { + out.insert(field.name.clone(), decode_json(&field.ty, records, r)?); + } + Value::Object(out) + } + }) +} + +/// A Rust type usable as a replicated entity field (`#[derive(Replicated)]`). +#[diagnostic::on_unimplemented( + message = "`{Self}` cannot be a replicated entity field", + label = "unsupported entity field type", + note = "supported: bool, u8, u16, u32, i32, f32 (optionally #[quant]/#[angle]), String (short_str) and Vec (bytes)" +)] +pub trait EntityField { + /// Default wire type (overridden by `#[quant]` / `#[angle]` on `f32`). + const FIELD_TYPE: FieldType; + /// This value as a [`FieldValue`]. + fn to_field_value(&self) -> FieldValue; +} + +macro_rules! entity_field { + ($ty:ty, $ft:expr, |$v:ident| $value:expr) => { + impl EntityField for $ty { + const FIELD_TYPE: FieldType = $ft; + fn to_field_value(&self) -> FieldValue { + let $v = self; + $value + } + } + }; +} + +entity_field!(bool, FieldType::Bool, |v| FieldValue::Bool(*v)); +entity_field!(u8, FieldType::U8, |v| FieldValue::U(u32::from(*v))); +entity_field!(u16, FieldType::U16, |v| FieldValue::U(u32::from(*v))); +entity_field!(u32, FieldType::U32, |v| FieldValue::U(*v)); +entity_field!(i32, FieldType::I32, |v| FieldValue::I(*v)); +entity_field!(f32, FieldType::F32, |v| FieldValue::F(*v)); +entity_field!(String, FieldType::ShortStr, |v| FieldValue::Str(v.clone())); +entity_field!(Vec, FieldType::Bytes, |v| FieldValue::Bytes(v.clone())); + +/// Marker: a field type that accepts `#[quant(..)]` / `#[angle(..)]`. +#[diagnostic::on_unimplemented( + message = "`#[quant]` / `#[angle]` need an `f32` field, not `{Self}`", + label = "quantize an f32" +)] +pub trait QuantizedF32 { + /// The value. + fn get(&self) -> f32; + /// From a decoded value. + fn from_f32(v: f32) -> Self; +} + +impl QuantizedF32 for f32 { + fn get(&self) -> f32 { + *self + } + fn from_f32(v: f32) -> Self { + v + } +} + +/// Marker: a field type that accepts `#[long]`. +#[diagnostic::on_unimplemented( + message = "`#[long]` needs a `String` field, not `{Self}`", + label = "long strings are Strings" +)] +pub trait LongString { + /// The text. + fn text(&self) -> &str; + /// From decoded text. + fn from_text(v: String) -> Self; +} + +impl LongString for String { + fn text(&self) -> &str { + self + } + fn from_text(v: String) -> Self { + v + } +} + +/// A scalar usable in a `#[derive(GameInput)]` struct, and how its +/// `#[range(..)]` clamps. +#[diagnostic::on_unimplemented( + message = "`{Self}` cannot be a game input field", + label = "unsupported input field type", + note = "inputs are small fixed scalars: bool, u8, i8, u16, i16, u32, i32 or f32 (optionally #[quant]/#[angle])" +)] +pub trait InputField: Wire + Copy { + /// Clamp into `[min, max]` (given as `f64`); `None` rejects the input + /// (non-finite floats). + fn sanitize_range(self, min: f64, max: f64) -> Option; + /// Validity without a range (floats must be finite). + fn sanitize_plain(self) -> Option { + Some(self) + } +} + +macro_rules! input_int { + ($($ty:ty),*) => {$( + impl InputField for $ty { + fn sanitize_range(self, min: f64, max: f64) -> Option { + Some((self as f64).clamp(min, max) as $ty) + } + } + )*}; +} + +input_int!(u8, i8, u16, i16, u32, i32); + +impl InputField for bool { + fn sanitize_range(self, _min: f64, _max: f64) -> Option { + Some(self) + } +} + +impl InputField for f32 { + fn sanitize_range(self, min: f64, max: f64) -> Option { + self.is_finite() + .then(|| f64::from(self).clamp(min, max) as f32) + } + fn sanitize_plain(self) -> Option { + self.is_finite().then_some(self) + } +} + +/// A bit-flag field (`#[buttons(..)]`): unknown bits are cleared. +#[diagnostic::on_unimplemented( + message = "`#[buttons]` needs a u8, u16 or u32 field, not `{Self}`", + label = "button bits live in an unsigned integer" +)] +pub trait ButtonBits: Copy { + /// Keep only the bits of `mask`. + fn mask(self, mask: u32) -> Self; +} + +macro_rules! button_bits { + ($($ty:ty),*) => {$( + impl ButtonBits for $ty { + fn mask(self, mask: u32) -> Self { + (u32::from(self) & mask) as $ty + } + } + )*}; +} + +button_bits!(u8, u16, u32); + +#[cfg(test)] +mod tests { + use super::*; + + fn field_bytes(ty: FieldType, value: &FieldValue) -> Vec { + let mut w = Writer::new(); + ty.encode(&mut w, value); + w.into_bytes() + } + + #[test] + fn scalars_match_entity_field_encodings() { + for (bytes, field) in [ + ( + to_bytes(&true), + field_bytes(FieldType::Bool, &FieldValue::Bool(true)), + ), + ( + to_bytes(&200u8), + field_bytes(FieldType::U8, &FieldValue::U(200)), + ), + ( + to_bytes(&300u16), + field_bytes(FieldType::U16, &FieldValue::U(300)), + ), + ( + to_bytes(&70_000u32), + field_bytes(FieldType::U32, &FieldValue::U(70_000)), + ), + ( + to_bytes(&-5i32), + field_bytes(FieldType::I32, &FieldValue::I(-5)), + ), + ( + to_bytes(&1.5f32), + field_bytes(FieldType::F32, &FieldValue::F(1.5)), + ), + ( + to_bytes(&"hé".to_string()), + field_bytes(FieldType::ShortStr, &FieldValue::Str("hé".into())), + ), + ] { + assert_eq!(bytes, field); + } + } + + #[test] + fn composite_types_round_trip() { + let value: (Vec>, u64) = (vec![Some(-128), None, Some(127)], (1 << 53) - 1); + let mut w = Writer::new(); + value.0.encode(&mut w); + value.1.encode(&mut w); + let bytes = w.into_bytes(); + let mut r = Reader::new(&bytes); + assert_eq!(Vec::>::decode(&mut r).unwrap(), value.0); + assert_eq!(u64::decode(&mut r).unwrap(), value.1); + r.finish().unwrap(); + // u64 saturates at 2^53 - 1 so JavaScript decodes it exactly. + assert_eq!( + from_bytes::(&to_bytes(&u64::MAX)).unwrap(), + (1 << 53) - 1 + ); + assert!(from_bytes::(&to_bytes(&70_000u32)).is_err()); + assert!(from_bytes::>(&[2]).is_err()); + assert!(from_bytes::>(&[200]).is_err()); + } + + #[test] + fn input_ranges_clamp_and_floats_must_be_finite() { + assert_eq!((-128i8).sanitize_range(-127.0, 127.0), Some(-127)); + assert_eq!(9u8.sanitize_range(0.0, 4.0), Some(4)); + assert_eq!(f32::NAN.sanitize_range(-1.0, 1.0), None); + assert_eq!(f32::INFINITY.sanitize_plain(), None); + assert_eq!(2.5f32.sanitize_range(-1.0, 1.0), Some(1.0)); + assert_eq!(0b111u8.mask(0b101), 0b101); + } + + #[test] + fn wire_types_serialize_tagged() { + let ty = Vec::>::wire_type(); + let json = serde_json::to_value(&ty).unwrap(); + assert_eq!( + json, + serde_json::json!({"type": "list", "item": {"type": "optional", "item": {"type": "f32"}}}) + ); + assert_eq!(serde_json::from_value::(json).unwrap(), ty); + assert_eq!( + WireType::of_field(FieldType::quant_centered(16.0, 12)).field_type(), + Some(FieldType::quant_centered(16.0, 12)) + ); + } +} diff --git a/distributed_game/src/collide.rs b/distributed_game/src/collide.rs new file mode 100644 index 000000000..46beb255a --- /dev/null +++ b/distributed_game/src/collide.rs @@ -0,0 +1,1550 @@ +//! Static colliders and the one raycast games use for hits. +//! +//! A zone declares its level geometry once, in [`Zone::on_create`] (which +//! runs on every wake): vertical cylinders (columns, trees) and axis-aligned +//! boxes (walls, crates), each extruded from the floor (`z = 0`) to a +//! height. +//! +//! ```ignore +//! ctx.set_colliders( +//! Colliders::new() +//! .with(Collider::cylinder([4.0, 2.0], 0.8, 2.4)) +//! .with(Collider::aabb([-20.0, 19.5], [20.0, 20.0], 3.0)), +//! ); +//! ``` +//! +//! A [`Ray`] then finds the closest hit among the recorded entities +//! ([`Zone::record_rewind`]) and the colliders, with the point and surface +//! normal for placing the impact: +//! +//! ```ignore +//! let ray = Ray::new(muzzle, aim, 100.0).ignoring(shooter.0); +//! if let Some(hit) = ctx.raycast_shot(timing, &ray) { // lag-compensated +//! spawn_impact(hit.point, hit.normal); +//! if let Target::Entity(id) = hit.target { damage(id); } +//! } +//! ``` +//! +//! **Slopes and bounces.** [`Collider::ramp`] is a wedge rising along one +//! axis. [`Colliders::ground_at`] gives the top surface under a point (its +//! height and normal), and [`walkable`] says whether that normal is floor: +//! up component above [`WALKABLE_MIN_NZ`], about 45°. [`bounce`] follows a +//! ray, reflecting it ([`reflect`]) off each static surface it meets: +//! +//! ```ignore +//! let trace = bounce(Ray::new(muzzle, aim, 100.0), 4, |r| ctx.raycast_shot(timing, r)); +//! for hit in &trace.hits { spark(hit.point, hit.normal); } +//! ``` +//! +//! [`Trace::stop_at`] cuts a trace at the first collider on some layers +//! (walls a shot never bounces past), and [`Trace::exit_box`] finds where +//! it leaves the zone's square, for a shot that carries on next door. +//! +//! **Layers.** Every entity and collider sits on a set of layer bits +//! ([`Historic::on_layers`], [`Collider::on_layers`]; [`layer::DEFAULT`] +//! unless set) and a ray only meets those its [`Ray::mask`] shares; a +//! [`Ray::ignoring`] id is never hit (the shooter). Put an entity on no +//! layer (`0`) to make it transparent (a dead mob). +//! +//! Distances are in world units along the ray; `dir` need not be +//! normalised. A ray starting inside a shape hits it at distance 0 with the +//! normal pointing back along the ray. Queries are a linear scan: fine for +//! rooms of tens of shapes and entities, not for large open worlds. +//! +//! [`Zone::on_create`]: crate::Zone::on_create +//! [`Zone::record_rewind`]: crate::Zone::record_rewind +//! [`Historic::on_layers`]: crate::rewind::Historic::on_layers + +use crate::rewind::{add, norm, scale, sub, Historic, HitQuery, Vec3}; + +/// Layer bits. +pub mod layer { + /// Where entities and colliders sit unless told otherwise. + pub const DEFAULT: u32 = 1; + /// Every layer (a ray's default mask). + pub const ALL: u32 = u32::MAX; + /// No layer: never hit. + pub const NONE: u32 = 0; +} + +/// A ray: `origin + t·dir` for `t` in `0..=max_dist`. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Ray { + /// Start (e.g. the muzzle). + pub origin: Vec3, + /// Unit direction (zero for a degenerate ray, which hits nothing). + pub dir: Vec3, + /// Maximum distance. + pub max_dist: f32, + /// Layers this ray meets. + pub mask: u32, + /// Entity never hit (the shooter). + pub ignore: Option, +} + +impl Ray { + /// Ray from `origin` along `dir` (need not be normalised) up to + /// `max_dist`, meeting every layer. + pub fn new(origin: Vec3, dir: Vec3, max_dist: f32) -> Self { + let n = norm(dir); + Self { + origin, + dir: if n > 0.0 { + scale(dir, 1.0 / n) + } else { + [0.0; 3] + }, + max_dist: if n > 0.0 { max_dist.max(0.0) } else { 0.0 }, + mask: layer::ALL, + ignore: None, + } + } + + /// Only meet entities and colliders on these layers. + pub fn mask(mut self, layers: u32) -> Self { + self.mask = layers; + self + } + + /// Never hit this entity (the shooter). + pub fn ignoring(mut self, id: u32) -> Self { + self.ignore = Some(id); + self + } + + /// The point at distance `t`. + pub fn at(&self, t: f32) -> Vec3 { + add(self.origin, scale(self.dir, t)) + } + + /// The same segment as a [`HitQuery`] (for [`Rewind`](crate::Rewind) + /// queries that take one). + pub fn query(&self) -> HitQuery { + HitQuery::Segment { + from: self.origin, + to: self.at(self.max_dist), + } + } + + fn meets(&self, layers: u32) -> bool { + self.mask & layers != 0 + } +} + +/// What a ray hit. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Target { + /// A recorded entity (its id). + Entity(u32), + /// A static collider (its index in [`Colliders`]). + Static(usize), + /// The terrain ([`Colliders::with_terrain`]). + Terrain, +} + +/// The closest hit of a [`Ray`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct RayHit { + /// Entity or collider. + pub target: Target, + /// Distance from the ray's origin. + pub distance: f32, + /// Where the ray entered. + pub point: Vec3, + /// Unit surface normal there (facing the ray). + pub normal: Vec3, +} + +/// A surface counts as walkable floor when its normal's up component is +/// above this (`cos 45.57°`). +pub const WALKABLE_MIN_NZ: f32 = 0.7; + +/// Whether a surface with this unit normal is floor to walk on. +pub fn walkable(normal: Vec3) -> bool { + normal[2] > WALKABLE_MIN_NZ +} + +/// `v` mirrored about the plane with unit normal `n`: `v − 2(v·n)n`. +pub fn reflect(v: Vec3, n: Vec3) -> Vec3 { + let d = v[0] * n[0] + v[1] * n[1] + v[2] * n[2]; + sub(v, scale(n, 2.0 * d)) +} + +/// One piece of level geometry, from the floor (`z = 0`) up to `height`. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Collider { + /// Footprint. + pub shape: Footprint, + /// Top (`z`); a ramp's high edge. + pub height: f32, + /// A ramp ([`Collider::ramp`]): the way its top climbs from `0` to + /// `height`. `None`: a flat top. + pub uphill: Option, + /// Layer bits ([`layer::DEFAULT`] unless set). + pub layers: u32, +} + +/// The way a ramp climbs (over its rectangle, from one edge to the other). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Uphill { + /// Low at `min.x`, high at `max.x`. + PosX, + /// Low at `max.x`, high at `min.x`. + NegX, + /// Low at `min.y`, high at `max.y`. + PosY, + /// Low at `max.y`, high at `min.y`. + NegY, +} + +impl Uphill { + /// The horizontal unit vector it climbs along. + pub fn dir(self) -> [f32; 2] { + match self { + Uphill::PosX => [1.0, 0.0], + Uphill::NegX => [-1.0, 0.0], + Uphill::PosY => [0.0, 1.0], + Uphill::NegY => [0.0, -1.0], + } + } +} + +/// The top surface under a point ([`Colliders::ground_at`]). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Ground { + /// What it stands on: a collider ([`Target::Static`]) or the terrain. + pub target: Target, + /// Height of the surface there. + pub height: f32, + /// Its unit normal (up for a flat top). + pub normal: Vec3, +} + +/// Where a [`bounce`] went. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Trace { + /// Each surface met, in order; the last is an entity when one was hit. + pub hits: Vec, + /// Where it stopped. + pub end: Vec3, +} + +impl Trace { + /// The entity it stopped at. + pub fn entity(&self) -> Option { + match self.hits.last()?.target { + Target::Entity(id) => Some(id), + Target::Static(_) | Target::Terrain => None, + } + } + + /// Cut it at the first static hit on a collider sharing `layers` (it + /// ends there; anything it met after that never happened). For a ray + /// that bounces off some surfaces but is stopped by others. + pub fn stop_at(&mut self, colliders: &Colliders, layers: u32) { + let stop = self.hits.iter().position(|h| match h.target { + Target::Static(i) => colliders.get(i).is_some_and(|c| c.layers & layers != 0), + Target::Entity(_) | Target::Terrain => false, + }); + if let Some(i) = stop { + self.hits.truncate(i + 1); + self.end = self.hits[i].point; + } + } + + /// Where the path from `origin` through each hit to the end first + /// leaves the square of half-size `half` centred on the floor origin + /// (the zone's bounds, for a shot that carries on next door). A leg + /// that only reaches a side (it stopped at a wall there) does not leave. + pub fn exit_box(&self, origin: Vec3, half: f32) -> Option { + let points: Vec = std::iter::once(origin) + .chain(self.hits.iter().map(|h| h.point)) + .chain(std::iter::once(self.end)) + .collect(); + let mut travelled = 0.0f32; + for (leg, pair) in points.windows(2).enumerate() { + let (from, to) = (pair[0], pair[1]); + let len = norm(sub(to, from)); + if len < 1e-4 { + continue; + } + let dir = scale(sub(to, from), 1.0 / len); + let mut best: Option<(f32, [i32; 2])> = None; + for (axis, sign) in [(0usize, 1.0f32), (0, -1.0), (1, 1.0), (1, -1.0)] { + let v = dir[axis] * sign; + // Going out through this side, from inside. + if v <= 1e-6 || from[axis] * sign > half { + continue; + } + let t = (half - from[axis] * sign) / v; + if t > len - EXIT_EPS { + continue; + } + let other = from[1 - axis] + dir[1 - axis] * t; + if other.abs() > half || best.is_some_and(|b| b.0 <= t) { + continue; + } + let mut side = [0, 0]; + side[axis] = sign as i32; + best = Some((t, side)); + } + if let Some((t, side)) = best { + return Some(Exit { + side, + point: add(from, scale(dir, t)), + dir, + travelled: travelled + t, + leg, + }); + } + travelled += len; + } + None + } +} + +/// How far short of a leg's end a side must be for the leg to leave +/// through it ([`Trace::exit_box`]): a leg ending on the side stopped there. +const EXIT_EPS: f32 = 1e-3; + +/// Where a [`Trace`] leaves a box ([`Trace::exit_box`]). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Exit { + /// The side it leaves by: `[1, 0]` is +x, `[0, -1]` is −y. + pub side: [i32; 2], + /// The point on that side. + pub point: Vec3, + /// Its unit direction there. + pub dir: Vec3, + /// Path length from the origin to `point`. + pub travelled: f32, + /// Which leg leaves (0: before any bounce; also the bounces used). + pub leg: usize, +} + +/// [`Heightfield`] sample with no ground: a hole. +pub const HOLE: f32 = f32::NEG_INFINITY; + +/// Terrain: heights sampled on a regular grid and bilinear between the +/// samples (rolling hills), with [`HOLE`] samples where there is no +/// ground. A cell with a hole corner is open: rays pass and movers fall. +#[derive(Debug, Clone, PartialEq)] +pub struct Heightfield { + min: [f32; 2], + cell: f32, + nx: usize, + ny: usize, + heights: Vec, + top: f32, + /// Lowest sample other than a hole (`INFINITY` if all are holes). + bottom: f32, +} + +impl Heightfield { + /// `nx × ny` samples (each ≥ 2), the first at `min`, `cell` apart, of + /// `height(x, y)`. + pub fn new( + min: [f32; 2], + cell: f32, + nx: usize, + ny: usize, + mut height: impl FnMut(f32, f32) -> f32, + ) -> Self { + let mut heights = Vec::with_capacity(nx * ny); + for j in 0..ny { + for i in 0..nx { + heights.push(height(min[0] + i as f32 * cell, min[1] + j as f32 * cell)); + } + } + Self::from_samples(min, cell, nx, ny, heights) + } + + /// From samples, row by row (`y` outer, `x` inner). + pub fn from_samples(min: [f32; 2], cell: f32, nx: usize, ny: usize, heights: Vec) -> Self { + assert!(nx >= 2 && ny >= 2 && heights.len() == nx * ny && cell > 0.0); + let top = heights.iter().copied().fold(f32::NEG_INFINITY, f32::max); + let bottom = heights + .iter() + .copied() + .filter(|&h| h != HOLE) + .fold(f32::INFINITY, f32::min); + Self { + min, + cell, + nx, + ny, + heights, + top, + bottom, + } + } + + /// The first sample's position. + pub fn min(&self) -> [f32; 2] { + self.min + } + + /// Sample spacing. + pub fn cell(&self) -> f32 { + self.cell + } + + /// Samples along x and y. + pub fn size(&self) -> (usize, usize) { + (self.nx, self.ny) + } + + /// Every sample, row by row. + pub fn samples(&self) -> &[f32] { + &self.heights + } + + /// Highest sample. + pub fn top(&self) -> f32 { + self.top + } + + /// Height and unit normal at `[x, y]`; `None` off the grid or over a + /// hole. + pub fn height_at(&self, at: [f32; 2]) -> Option<(f32, Vec3)> { + let fx = (at[0] - self.min[0]) / self.cell; + let fy = (at[1] - self.min[1]) / self.cell; + let (lx, ly) = ((self.nx - 1) as f32, (self.ny - 1) as f32); + if !(0.0..=lx).contains(&fx) || !(0.0..=ly).contains(&fy) { + return None; + } + let i = (fx.floor() as usize).min(self.nx - 2); + let j = (fy.floor() as usize).min(self.ny - 2); + let (tx, ty) = (fx - i as f32, fy - j as f32); + let h = |a: usize, b: usize| self.heights[b * self.nx + a]; + let (h00, h10, h01, h11) = (h(i, j), h(i + 1, j), h(i, j + 1), h(i + 1, j + 1)); + if [h00, h10, h01, h11].contains(&HOLE) { + return None; + } + let height = + (h00 * (1.0 - tx) + h10 * tx) * (1.0 - ty) + (h01 * (1.0 - tx) + h11 * tx) * ty; + let dx = ((h10 - h00) * (1.0 - ty) + (h11 - h01) * ty) / self.cell; + let dy = ((h01 - h00) * (1.0 - tx) + (h11 - h10) * tx) / self.cell; + let raw = [-dx, -dy, 1.0]; + Some((height, scale(raw, 1.0 / norm(raw)))) + } + + /// Where `ray` first meets the surface (marched half a cell at a time + /// over the part of the ray above the grid and below its top, then + /// bisected); starting under it = 0. Any range (`f32::MAX`, infinite) + /// ends; a NaN range, origin or direction hits nothing. + pub fn raycast(&self, ray: &Ray) -> Option<(f32, Vec3)> { + if ray.max_dist.is_nan() || ray.max_dist <= 0.0 { + return None; + } + let under = |t: f32| { + let p = ray.at(t); + self.height_at([p[0], p[1]]).is_some_and(|(h, _)| p[2] <= h) + }; + if under(0.0) { + return Some((0.0, scale(ray.dir, -1.0))); + } + let (enter, exit) = self.span(ray)?; + let step = self.cell * 0.5; + let (mut lo, mut t) = (enter, (enter + step).min(exit)); + loop { + if under(t) { + let mut hi = t; + for _ in 0..14 { + let mid = 0.5 * (lo + hi); + if under(mid) { + hi = mid; + } else { + lo = mid; + } + } + let p = ray.at(hi); + let normal = self + .height_at([p[0], p[1]]) + .map_or([0.0, 0.0, 1.0], |(_, n)| n); + return Some((hi, normal)); + } + if t >= exit { + return None; + } + lo = t; + t = (t + step).min(exit); + } + } + + /// The part `[enter, exit]` of `ray` (within its range) inside the + /// grid's box: over the grid, between its lowest and highest sample. + /// Always finite: `None` when there is no such part, or for a ray + /// that is degenerate or not finite. The range is not NaN. + fn span(&self, ray: &Ray) -> Option<(f32, f32)> { + let finite = ray.origin.iter().chain(&ray.dir).all(|v| v.is_finite()); + let degenerate = ray.dir == [0.0; 3]; + if !finite || degenerate { + return None; + } + if self.bottom > self.top { + return None; // all holes + } + let (mut enter, mut exit) = (0.0f32, ray.max_dist); + let extent = [self.nx, self.ny].map(|n| (n - 1) as f32 * self.cell); + for axis in 0..3 { + let (lo, hi) = match axis { + 2 => (self.bottom, self.top), + _ => (self.min[axis], self.min[axis] + extent[axis]), + }; + let (o, d) = (ray.origin[axis], ray.dir[axis]); + if d == 0.0 { + if !(lo..=hi).contains(&o) { + return None; + } + continue; + } + let (a, b) = ((lo - o) / d, (hi - o) / d); + enter = enter.max(a.min(b)); + exit = exit.min(a.max(b)); + } + (enter <= exit).then_some((enter, exit)) + } +} + +/// How far off a surface a bounced ray restarts. +const BOUNCE_LIFT: f32 = 1e-3; + +/// Follow `ray` for its whole `max_dist`, reflecting it off each static +/// surface [`cast`] reports (up to `max_bounces` times) and stopping at the +/// first entity. Each leg keeps the ray's mask and ignore. +pub fn bounce(ray: Ray, max_bounces: usize, mut cast: impl FnMut(&Ray) -> Option) -> Trace { + let mut trace = Trace::default(); + let mut leg = ray; + loop { + let Some(hit) = cast(&leg) else { + trace.end = leg.at(leg.max_dist); + return trace; + }; + trace.hits.push(hit); + trace.end = hit.point; + if matches!(hit.target, Target::Entity(_)) || trace.hits.len() > max_bounces { + return trace; + } + let left = leg.max_dist - hit.distance; + if left <= BOUNCE_LIFT { + return trace; + } + leg = Ray { + origin: add(hit.point, scale(hit.normal, BOUNCE_LIFT)), + ..Ray::new(hit.point, reflect(leg.dir, hit.normal), left) + } + .mask(ray.mask); + leg.ignore = ray.ignore; + } +} + +/// A collider's footprint on the floor. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Footprint { + /// Circle: a vertical cylinder. + Circle { + /// Centre `[x, y]`. + center: [f32; 2], + /// Radius. + radius: f32, + }, + /// Axis-aligned rectangle: a box. + Rect { + /// Lowest `[x, y]`. + min: [f32; 2], + /// Highest `[x, y]`. + max: [f32; 2], + }, +} + +impl Collider { + /// Vertical cylinder (a column, a tree trunk). + pub fn cylinder(center: [f32; 2], radius: f32, height: f32) -> Self { + Self { + shape: Footprint::Circle { center, radius }, + height, + uphill: None, + layers: layer::DEFAULT, + } + } + + /// Axis-aligned box between two floor corners (a wall, a crate). + pub fn aabb(a: [f32; 2], b: [f32; 2], height: f32) -> Self { + Self { + shape: Footprint::Rect { + min: [a[0].min(b[0]), a[1].min(b[1])], + max: [a[0].max(b[0]), a[1].max(b[1])], + }, + height, + uphill: None, + layers: layer::DEFAULT, + } + } + + /// A ramp over the rectangle between two floor corners: its top climbs + /// from the floor at one edge to `height` at the opposite one + /// (`uphill`), with vertical sides and a vertical high end. + pub fn ramp(a: [f32; 2], b: [f32; 2], height: f32, uphill: Uphill) -> Self { + Self { + uphill: Some(uphill), + ..Self::aabb(a, b, height) + } + } + + /// Height and unit normal of the top at `[x, y]`, if over the footprint. + pub fn top_at(&self, at: [f32; 2]) -> Option<(f32, Vec3)> { + match self.shape { + Footprint::Circle { center, radius } => { + let (dx, dy) = (at[0] - center[0], at[1] - center[1]); + (dx * dx + dy * dy <= radius * radius).then_some((self.height, [0.0, 0.0, 1.0])) + } + Footprint::Rect { min, max } => { + if at[0] < min[0] || at[0] > max[0] || at[1] < min[1] || at[1] > max[1] { + return None; + } + match self.ramp_plane(min, max) { + None => Some((self.height, [0.0, 0.0, 1.0])), + Some((normal, d)) => { + // n·(x, y, z) = d on the top. + let z = (d - normal[0] * at[0] - normal[1] * at[1]) / normal[2]; + Some((z.clamp(0.0, self.height), normal)) + } + } + } + } + } + + /// A ramp's top as the plane `n·p = d` (unit `n`, pointing up and + /// downhill). + fn ramp_plane(&self, min: [f32; 2], max: [f32; 2]) -> Option<(Vec3, f32)> { + let uphill = self.uphill?; + let (low, run) = match uphill { + Uphill::PosX => (min[0], max[0] - min[0]), + Uphill::NegX => (max[0], max[0] - min[0]), + Uphill::PosY => (min[1], max[1] - min[1]), + Uphill::NegY => (max[1], max[1] - min[1]), + }; + if run <= 0.0 { + return None; + } + let k = self.height / run; + let [ux, uy] = uphill.dir(); + // z = k·(u·p − u·low_edge) ⇔ −k·u·p + z = −k·(u·low_edge). + let low_along = match uphill { + Uphill::PosX | Uphill::PosY => low, + Uphill::NegX | Uphill::NegY => -low, + }; + let raw = [-k * ux, -k * uy, 1.0]; + let n = norm(raw); + Some((scale(raw, 1.0 / n), -k * low_along / n)) + } + + /// Put it on these layers. + pub fn on_layers(mut self, layers: u32) -> Self { + self.layers = layers; + self + } + + /// Entry distance and normal of `ray` (ignoring its mask). + pub fn raycast(&self, ray: &Ray) -> Option<(f32, Vec3)> { + if ray.max_dist <= 0.0 { + return None; + } + let (t, normal) = match self.shape { + Footprint::Circle { center, radius } => { + ray_cylinder(ray.origin, ray.dir, center, radius, self.height)? + } + Footprint::Rect { min, max } => { + let (lo, hi) = ([min[0], min[1], 0.0], [max[0], max[1], self.height]); + match self.ramp_plane(min, max) { + None => ray_box(ray.origin, ray.dir, lo, hi)?, + Some(top) => ray_wedge(ray.origin, ray.dir, lo, hi, top)?, + } + } + }; + (t <= ray.max_dist).then_some((t, normal)) + } + + /// Push a circle of `radius` at `[x, y]` out of this footprint, if it + /// overlaps (heights ignored: for movers on the floor). + fn push_out(&self, at: [f32; 2], radius: f32) -> Option<[f32; 2]> { + match self.shape { + Footprint::Circle { center, radius: r } => { + let (ox, oy) = (at[0] - center[0], at[1] - center[1]); + let d2 = ox * ox + oy * oy; + let min = radius + r; + if d2 >= min * min { + return None; + } + let d = d2.sqrt(); + let (ux, uy) = if d > 1e-4 { + (ox / d, oy / d) + } else { + (1.0, 0.0) + }; + Some([center[0] + ux * min, center[1] + uy * min]) + } + Footprint::Rect { min, max } => { + let cx = at[0].clamp(min[0], max[0]); + let cy = at[1].clamp(min[1], max[1]); + let (ox, oy) = (at[0] - cx, at[1] - cy); + let d2 = ox * ox + oy * oy; + if d2 >= radius * radius { + return None; + } + if d2 > 1e-8 { + let d = d2.sqrt(); + return Some([cx + ox / d * radius, cy + oy / d * radius]); + } + // Centre inside: out through the nearest side. + let exits = [ + (at[0] - min[0], [min[0] - radius, at[1]]), + (max[0] - at[0], [max[0] + radius, at[1]]), + (at[1] - min[1], [at[0], min[1] - radius]), + (max[1] - at[1], [at[0], max[1] + radius]), + ]; + exits + .into_iter() + .min_by(|a, b| a.0.total_cmp(&b.0)) + .map(|(_, p)| p) + } + } + } +} + +/// A zone's level geometry ([`Ctx::set_colliders`](crate::Ctx::set_colliders)). +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Colliders { + shapes: Vec, + terrain: Option<(Heightfield, u32)>, +} + +impl Colliders { + /// No geometry. + pub fn new() -> Self { + Self::default() + } + + /// Add a collider (builder). + pub fn with(mut self, collider: Collider) -> Self { + self.shapes.push(collider); + self + } + + /// Add a collider; returns its index ([`Target::Static`]). + pub fn push(&mut self, collider: Collider) -> usize { + self.shapes.push(collider); + self.shapes.len() - 1 + } + + /// Terrain under everything, on `layers` (builder). + pub fn with_terrain(mut self, field: Heightfield, layers: u32) -> Self { + self.terrain = Some((field, layers)); + self + } + + /// The terrain, if any. + pub fn terrain(&self) -> Option<&Heightfield> { + self.terrain.as_ref().map(|(field, _)| field) + } + + /// The collider at `index`. + pub fn get(&self, index: usize) -> Option<&Collider> { + self.shapes.get(index) + } + + /// Every collider, by index. + pub fn iter(&self) -> impl Iterator { + self.shapes.iter() + } + + /// How many. + pub fn len(&self) -> usize { + self.shapes.len() + } + + /// None at all. + pub fn is_empty(&self) -> bool { + self.shapes.is_empty() + } + + /// Closest collider on `ray` (its mask applies). + pub fn raycast(&self, ray: &Ray) -> Option { + let mut best: Option = None; + for (index, collider) in self.shapes.iter().enumerate() { + if !ray.meets(collider.layers) { + continue; + } + if let Some((distance, normal)) = collider.raycast(ray) { + if best.is_none_or(|b| distance < b.distance) { + best = Some(RayHit { + target: Target::Static(index), + distance, + point: ray.at(distance), + normal, + }); + } + } + } + if let Some((field, layers)) = &self.terrain { + if ray.meets(*layers) { + // Only nearer than the best so far. + let near = Ray { + max_dist: best.map_or(ray.max_dist, |b| b.distance), + ..*ray + }; + if let Some((distance, normal)) = field.raycast(&near) { + if best.is_none_or(|b| distance < b.distance) { + best = Some(RayHit { + target: Target::Terrain, + distance, + point: ray.at(distance), + normal, + }); + } + } + } + } + best + } + + /// The highest top surface on `mask` under `[x, y]`. + pub fn ground_at(&self, at: [f32; 2], mask: u32) -> Option { + let mut best: Option = None; + for (index, collider) in self.shapes.iter().enumerate() { + if mask & collider.layers == 0 { + continue; + } + if let Some((height, normal)) = collider.top_at(at) { + if best.is_none_or(|b| height > b.height) { + best = Some(Ground { + target: Target::Static(index), + height, + normal, + }); + } + } + } + if let Some((field, layers)) = &self.terrain { + if mask & layers != 0 { + if let Some((height, normal)) = field.height_at(at) { + if best.is_none_or(|b| height > b.height) { + best = Some(Ground { + target: Target::Terrain, + height, + normal, + }); + } + } + } + } + best + } + + /// Where a circle of `radius` at `[x, y]` ends up once pushed out of + /// every collider on `mask` it overlaps (a few passes, so it settles + /// between neighbours). Floor movers only: heights are ignored. + pub fn push_out(&self, at: [f32; 2], radius: f32, mask: u32) -> [f32; 2] { + let mut at = at; + for _ in 0..3 { + let mut moved = false; + for collider in self.shapes.iter().filter(|c| mask & c.layers != 0) { + if let Some(next) = collider.push_out(at, radius) { + at = next; + moved = true; + } + } + if !moved { + break; + } + } + at + } +} + +/// Closest of `entities`, each at its position (their layers, the ray's +/// ignore, `accept`), and `colliders`. +pub(crate) fn raycast<'a>( + entities: impl IntoIterator, + colliders: &Colliders, + ray: &Ray, + mut accept: impl FnMut(u32) -> bool, +) -> Option { + let mut best = colliders.raycast(ray); + if ray.max_dist <= 0.0 { + return best; + } + let query = ray.query(); + for (e, pos) in entities { + if !ray.meets(e.layers) || ray.ignore == Some(e.id) || !accept(e.id) { + continue; + } + let Some(distance) = crate::rewind::intersect_at(&query, &e.shape, pos) else { + continue; + }; + if best.is_none_or(|b| distance < b.distance) { + let point = ray.at(distance); + best = Some(RayHit { + target: Target::Entity(e.id), + distance, + point, + normal: entity_normal(e, pos, point, ray.dir), + }); + } + } + best +} + +/// Outward normal of an entity's volume at `pos` at `point` (back along +/// `dir` when the point is on its axis). +fn entity_normal(e: &Historic, pos: Vec3, point: Vec3, dir: Vec3) -> Vec3 { + let (pa, pb) = e.shape.segment(pos); + let axis = crate::rewind::closest_on_segment(point, pa, pb); + unit_or(sub(point, axis), scale(dir, -1.0)) +} + +fn unit_or(v: Vec3, fallback: Vec3) -> Vec3 { + let n = norm(v); + if n > 1e-6 { + scale(v, 1.0 / n) + } else { + fallback + } +} + +/// Entry of `ro + t·rd` (`rd` unit) into a vertical cylinder standing on +/// the floor: side wall or top cap; inside = 0. +fn ray_cylinder(ro: Vec3, rd: Vec3, c: [f32; 2], r: f32, h: f32) -> Option<(f32, Vec3)> { + let (ox, oy) = (ro[0] - c[0], ro[1] - c[1]); + let inside_xy = ox * ox + oy * oy <= r * r; + if inside_xy && (0.0..=h).contains(&ro[2]) { + return Some((0.0, scale(rd, -1.0))); + } + let mut best: Option<(f32, Vec3)> = None; + let mut consider = |t: f32, normal: Vec3| { + if t >= 0.0 && best.is_none_or(|(b, _)| t < b) { + best = Some((t, normal)); + } + }; + // Side wall. + let a = rd[0] * rd[0] + rd[1] * rd[1]; + if a > 1e-12 { + let b = ox * rd[0] + oy * rd[1]; + let k = ox * ox + oy * oy - r * r; + let disc = b * b - a * k; + if disc >= 0.0 { + let t = (-b - disc.sqrt()) / a; + let z = ro[2] + rd[2] * t; + if (0.0..=h).contains(&z) { + let (px, py) = (ox + rd[0] * t, oy + rd[1] * t); + consider(t, unit_or([px, py, 0.0], scale(rd, -1.0))); + } + } + } + // Top cap (from above) and floor cap (from below the floor). + if rd[2].abs() > 1e-12 { + for (z, nz) in [(h, 1.0), (0.0, -1.0)] { + let t = (z - ro[2]) / rd[2]; + let (px, py) = (ox + rd[0] * t, oy + rd[1] * t); + if rd[2] * nz < 0.0 && px * px + py * py <= r * r { + consider(t, [0.0, 0.0, nz]); + } + } + } + best +} + +/// Entry of `ro + t·rd` into the box `lo..hi` (slab test); inside = 0. +fn ray_box(ro: Vec3, rd: Vec3, lo: Vec3, hi: Vec3) -> Option<(f32, Vec3)> { + let inside = (0..3).all(|i| ro[i] >= lo[i] && ro[i] <= hi[i]); + if inside { + return Some((0.0, scale(rd, -1.0))); + } + let mut t_enter = f32::NEG_INFINITY; + let mut t_exit = f32::INFINITY; + let mut normal = [0.0; 3]; + for i in 0..3 { + if rd[i].abs() < 1e-12 { + if ro[i] < lo[i] || ro[i] > hi[i] { + return None; + } + continue; + } + let (mut t0, mut t1) = ((lo[i] - ro[i]) / rd[i], (hi[i] - ro[i]) / rd[i]); + let mut side = -1.0; + // By direction, not by order: a flat box (a floor) has t0 == t1. + if rd[i] < 0.0 { + std::mem::swap(&mut t0, &mut t1); + side = 1.0; + } + if t0 > t_enter { + t_enter = t0; + normal = [0.0; 3]; + normal[i] = side; + } + t_exit = t_exit.min(t1); + if t_enter > t_exit { + return None; + } + } + (t_enter >= 0.0).then_some((t_enter, normal)) +} + +/// Entry of `ro + t·rd` into a box `lo..hi` whose top is cut by the plane +/// `n·p ≤ d` (a ramp): clip the ray by each half-space; inside = 0. +fn ray_wedge(ro: Vec3, rd: Vec3, lo: Vec3, hi: Vec3, top: (Vec3, f32)) -> Option<(f32, Vec3)> { + let planes = [ + ([-1.0, 0.0, 0.0], -lo[0]), + ([1.0, 0.0, 0.0], hi[0]), + ([0.0, -1.0, 0.0], -lo[1]), + ([0.0, 1.0, 0.0], hi[1]), + ([0.0, 0.0, -1.0], -lo[2]), + ([0.0, 0.0, 1.0], hi[2]), + top, + ]; + let dot = |a: Vec3, b: Vec3| a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + if planes.iter().all(|&(n, d)| dot(n, ro) <= d) { + return Some((0.0, scale(rd, -1.0))); + } + let mut t_enter = f32::NEG_INFINITY; + let mut t_exit = f32::INFINITY; + let mut normal = [0.0; 3]; + for (n, d) in planes { + let along = dot(n, rd); + let over = dot(n, ro) - d; + if along.abs() < 1e-12 { + if over > 0.0 { + return None; + } + continue; + } + let t = -over / along; + if along < 0.0 { + if t > t_enter { + t_enter = t; + normal = n; + } + } else { + t_exit = t_exit.min(t); + } + if t_enter > t_exit { + return None; + } + } + (t_enter >= 0.0).then_some((t_enter, normal)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// [`super::raycast`] with each entity at its own position. + fn raycast( + entities: &[Historic], + colliders: &Colliders, + ray: &Ray, + accept: impl FnMut(u32) -> bool, + ) -> Option { + super::raycast(entities.iter().map(|e| (e, e.pos)), colliders, ray, accept) + } + + fn close(a: f32, b: f32) -> bool { + (a - b).abs() < 1e-4 + } + + fn close3(a: Vec3, b: Vec3) -> bool { + (0..3).all(|i| close(a[i], b[i])) + } + + #[test] + fn a_ray_meets_a_cylinder_side_and_passes_over_its_top() { + let column = Colliders::new().with(Collider::cylinder([5.0, 0.0], 1.0, 2.0)); + let hit = column + .raycast(&Ray::new([0.0, 0.0, 1.0], [1.0, 0.0, 0.0], 100.0)) + .unwrap(); + assert_eq!(hit.target, Target::Static(0)); + assert!(close(hit.distance, 4.0), "{hit:?}"); + assert!(close3(hit.point, [4.0, 0.0, 1.0])); + assert!(close3(hit.normal, [-1.0, 0.0, 0.0])); + // Over the top. + assert!(column + .raycast(&Ray::new([0.0, 0.0, 2.5], [1.0, 0.0, 0.0], 100.0)) + .is_none()); + // Too short. + assert!(column + .raycast(&Ray::new([0.0, 0.0, 1.0], [1.0, 0.0, 0.0], 3.9)) + .is_none()); + } + + #[test] + fn a_falling_ray_lands_on_the_top_cap() { + let column = Colliders::new().with(Collider::cylinder([0.0, 0.0], 1.0, 2.0)); + let hit = column + .raycast(&Ray::new([0.0, 0.0, 5.0], [0.0, 0.0, -1.0], 100.0)) + .unwrap(); + assert!(close(hit.distance, 3.0)); + assert!(close3(hit.normal, [0.0, 0.0, 1.0])); + } + + #[test] + fn a_ray_enters_a_box_through_the_face_it_meets() { + let wall = Colliders::new().with(Collider::aabb([2.0, -1.0], [3.0, 1.0], 3.0)); + let hit = wall + .raycast(&Ray::new([0.0, 0.0, 1.0], [2.0, 0.0, 0.0], 100.0)) + .unwrap(); + assert!(close(hit.distance, 2.0)); + assert!(close3(hit.normal, [-1.0, 0.0, 0.0])); + let from_far_side = wall + .raycast(&Ray::new([6.0, 0.5, 1.0], [-1.0, 0.0, 0.0], 100.0)) + .unwrap(); + assert!(close(from_far_side.distance, 3.0)); + assert!(close3(from_far_side.normal, [1.0, 0.0, 0.0])); + let onto_top = wall + .raycast(&Ray::new([2.5, 0.0, 9.0], [0.0, 0.0, -1.0], 100.0)) + .unwrap(); + assert!(close3(onto_top.normal, [0.0, 0.0, 1.0])); + assert!(wall + .raycast(&Ray::new([0.0, 5.0, 1.0], [1.0, 0.0, 0.0], 100.0)) + .is_none()); + assert!(wall + .raycast(&Ray::new([0.0, 0.0, 3.5], [1.0, 0.0, 0.0], 100.0)) + .is_none()); + } + + #[test] + fn a_flat_box_is_a_floor_from_either_side() { + let floor = Colliders::new().with(Collider::aabb([-5.0, -5.0], [5.0, 5.0], 0.0)); + let down = floor + .raycast(&Ray::new([0.0, 0.0, 2.0], [1.0, 0.0, -1.0], 100.0)) + .unwrap(); + assert!( + close(down.point[2], 0.0) && close(down.point[0], 2.0), + "{down:?}" + ); + assert!(close3(down.normal, [0.0, 0.0, 1.0])); + let up = floor + .raycast(&Ray::new([0.0, 0.0, -1.0], [0.0, 0.0, 1.0], 100.0)) + .unwrap(); + assert!(close3(up.normal, [0.0, 0.0, -1.0])); + assert!(floor + .raycast(&Ray::new([0.0, 0.0, 1.0], [1.0, 0.0, 0.0], 100.0)) + .is_none()); + } + + #[test] + fn a_ray_starting_inside_hits_at_once() { + let wall = Colliders::new().with(Collider::aabb([-1.0, -1.0], [1.0, 1.0], 3.0)); + let hit = wall + .raycast(&Ray::new([0.0, 0.0, 1.0], [1.0, 0.0, 0.0], 100.0)) + .unwrap(); + assert_eq!(hit.distance, 0.0); + assert!(close3(hit.normal, [-1.0, 0.0, 0.0])); + } + + #[test] + fn the_closest_of_walls_and_entities_wins_and_masks_apply() { + const MOBS: u32 = 1 << 1; + let walls = Colliders::new() + .with(Collider::aabb([10.0, -1.0], [11.0, 1.0], 3.0)) + .with(Collider::cylinder([3.0, 0.0], 0.5, 1.0)); + let mob = Historic::sphere(7, [6.0, 0.0, 1.5], 0.5).on_layers(MOBS); + let shooter = Historic::sphere(1, [0.0, 0.0, 1.5], 0.5); + let entities = [shooter, mob]; + // Over the short column, the mob before the wall; the shooter's own + // volume (the ray starts inside it) is skipped. + let ray = Ray::new([0.0, 0.0, 1.5], [1.0, 0.0, 0.0], 100.0).ignoring(1); + let hit = raycast(&entities, &walls, &ray, |_| true).unwrap(); + assert_eq!(hit.target, Target::Entity(7)); + assert!(close(hit.distance, 5.5)); + assert!(close3(hit.normal, [-1.0, 0.0, 0.0])); + // Lower: the column first. + let low = Ray::new([0.0, 0.0, 0.5], [1.0, 0.0, 0.0], 100.0).ignoring(1); + assert_eq!( + raycast(&entities, &walls, &low, |_| true).unwrap().target, + Target::Static(1) + ); + // A mask without mobs: the wall. + let walls_only = ray.mask(layer::DEFAULT); + assert_eq!( + raycast(&entities, &walls, &walls_only, |_| true) + .unwrap() + .target, + Target::Static(0) + ); + // Without the ignore, the shooter is hit at 0. + let careless = Ray::new([0.0, 0.0, 1.5], [1.0, 0.0, 0.0], 100.0); + assert_eq!( + raycast(&entities, &walls, &careless, |_| true) + .unwrap() + .target, + Target::Entity(1) + ); + // A transparent mob: the wall. + let ghost = [Historic::sphere(7, [6.0, 0.0, 1.5], 0.5).on_layers(layer::NONE)]; + assert_eq!( + raycast(&ghost, &walls, &ray, |_| true).unwrap().target, + Target::Static(0) + ); + } + + #[test] + fn a_degenerate_ray_hits_nothing() { + let walls = Colliders::new().with(Collider::cylinder([0.0, 0.0], 1.0, 2.0)); + let ray = Ray::new([5.0, 0.0, 1.0], [0.0, 0.0, 0.0], 100.0); + assert!(raycast( + &[Historic::sphere(1, [5.0, 0.0, 1.0], 1.0)], + &walls, + &ray, + |_| true + ) + .is_none()); + } + + /// A 30° ramp climbing +x over x 0..√3·2, 2 m high. + fn ramp30() -> Collider { + Collider::ramp([0.0, -1.0], [2.0 * 3f32.sqrt(), 1.0], 2.0, Uphill::PosX) + } + + #[test] + fn a_ray_meets_a_ramp_on_its_slope_its_side_and_its_high_end() { + let ramp = Colliders::new().with(ramp30()); + let (s, c) = (0.5f32, 3f32.sqrt() / 2.0); + // Straight down onto the middle of the slope. + let down = ramp + .raycast(&Ray::new([3f32.sqrt(), 0.0, 5.0], [0.0, 0.0, -1.0], 100.0)) + .unwrap(); + assert!(close(down.distance, 4.0), "{down:?}"); + assert!(close3(down.normal, [-s, 0.0, c]), "{down:?}"); + // Along +x, low: into the slope near the low edge. + let along = ramp + .raycast(&Ray::new([-1.0, 0.0, 0.5], [1.0, 0.0, 0.0], 100.0)) + .unwrap(); + assert!(close(along.point[0], 0.5 * 3f32.sqrt()), "{along:?}"); + assert!(close3(along.normal, [-s, 0.0, c])); + // From the side: the vertical face. + let side = ramp + .raycast(&Ray::new([3.0, -5.0, 0.5], [0.0, 1.0, 0.0], 100.0)) + .unwrap(); + assert!(close3(side.normal, [0.0, -1.0, 0.0]), "{side:?}"); + // From behind: the vertical high end. + let back = ramp + .raycast(&Ray::new([9.0, 0.0, 1.0], [-1.0, 0.0, 0.0], 100.0)) + .unwrap(); + assert!(close3(back.normal, [1.0, 0.0, 0.0]), "{back:?}"); + // Over it, and past its low edge. + assert!(ramp + .raycast(&Ray::new([-1.0, 0.0, 2.5], [1.0, 0.0, 0.0], 100.0)) + .is_none()); + assert!(ramp + .raycast(&Ray::new([-0.5, 0.0, 5.0], [0.0, 0.0, -1.0], 100.0)) + .is_none()); + } + + #[test] + fn every_way_up_has_its_own_slope() { + for (uphill, n) in [ + (Uphill::PosX, [-1.0, 0.0]), + (Uphill::NegX, [1.0, 0.0]), + (Uphill::PosY, [0.0, -1.0]), + (Uphill::NegY, [0.0, 1.0]), + ] { + let ramp = Collider::ramp([0.0, 0.0], [4.0, 4.0], 4.0, uphill); + let (h, normal) = ramp.top_at([1.0, 1.0]).unwrap(); + let low = match uphill { + Uphill::PosX | Uphill::PosY => 1.0, + Uphill::NegX | Uphill::NegY => 3.0, + }; + assert!(close(h, low), "{uphill:?} {h}"); + let r = std::f32::consts::FRAC_1_SQRT_2; + assert!( + close3(normal, [n[0] * r, n[1] * r, r]), + "{uphill:?} {normal:?}" + ); + // The ray straight down agrees with the surface. + let (t, _) = ramp + .raycast(&Ray::new([1.0, 1.0, 9.0], [0.0, 0.0, -1.0], 100.0)) + .unwrap(); + assert!(close(9.0 - t, low), "{uphill:?} {t}"); + } + } + + #[test] + fn ground_is_the_highest_top_and_walkable_means_under_about_45_degrees() { + let steep = Collider::ramp([5.0, -1.0], [6.0, 1.0], 2.0, Uphill::PosX); // 63° + let world = Colliders::new() + .with(ramp30()) + .with(steep) + .with(Collider::cylinder([3.0, 0.0], 0.2, 2.5)); + let on_ramp = world.ground_at([1.0, 0.5], layer::ALL).unwrap(); + assert_eq!(on_ramp.target, Target::Static(0)); + assert!(close(on_ramp.height, 1.0 / 3f32.sqrt()), "{on_ramp:?}"); + assert!(walkable(on_ramp.normal)); + let column = world.ground_at([3.0, 0.0], layer::ALL).unwrap(); + assert_eq!((column.target, column.height), (Target::Static(2), 2.5)); + assert!(walkable(column.normal)); + assert!(!walkable( + world.ground_at([5.5, 0.0], layer::ALL).unwrap().normal + )); + assert!(world.ground_at([9.0, 0.0], layer::ALL).is_none()); + assert!(world.ground_at([1.0, 0.5], layer::NONE).is_none()); + // 45.0° is walkable, 46° is not. + let at = |deg: f32| { + let t = deg.to_radians().tan(); + Collider::ramp([0.0, 0.0], [1.0, 1.0], t, Uphill::PosY) + .top_at([0.5, 0.5]) + .unwrap() + .1 + }; + assert!(walkable(at(45.0))); + assert!(!walkable(at(46.0))); + } + + #[test] + fn reflect_mirrors_about_the_normal() { + assert!(close3( + reflect([1.0, -1.0, 0.0], [0.0, 1.0, 0.0]), + [1.0, 1.0, 0.0] + )); + assert!(close3( + reflect([0.0, 0.0, -2.0], [0.0, 0.0, 1.0]), + [0.0, 0.0, 2.0] + )); + } + + #[test] + fn a_bounce_reflects_off_walls_and_stops_at_an_entity() { + // A wall at x = 5 facing -x; a mob on the mirrored line. + let walls = Colliders::new().with(Collider::aabb([5.0, -50.0], [6.0, 50.0], 3.0)); + let mob = [Historic::sphere(9, [0.0, 10.0, 1.0], 0.5)]; + let ray = Ray::new([0.0, 0.0, 1.0], [1.0, 1.0, 0.0], 100.0); + let trace = bounce(ray, 4, |r| raycast(&mob, &walls, r, |_| true)); + assert_eq!(trace.hits.len(), 2, "{trace:?}"); + assert_eq!(trace.hits[0].target, Target::Static(0)); + assert!(close3(trace.hits[0].point, [5.0, 5.0, 1.0])); + assert!(close3(trace.hits[0].normal, [-1.0, 0.0, 0.0])); + assert_eq!(trace.entity(), Some(9)); + // Nothing but the wall: it flies off for the rest of its length. + let alone = bounce(ray, 4, |r| walls.raycast(r)); + assert_eq!(alone.hits.len(), 1); + let left = 100.0 - 50f32.sqrt(); + let far = [5.0 - left * 0.70710677, 5.0 + left * 0.70710677, 1.0]; + assert!( + (0..3).all(|i| (alone.end[i] - far[i]).abs() < 1e-2), + "{alone:?}" + ); + // No bounces allowed: it stops at the wall. + let once = bounce(ray, 0, |r| walls.raycast(r)); + assert_eq!(once.hits.len(), 1); + assert!(close3(once.end, [5.0, 5.0, 1.0])); + // Between two walls it runs out of bounces. + let corridor = Colliders::new() + .with(Collider::aabb([5.0, -50.0], [6.0, 50.0], 3.0)) + .with(Collider::aabb([-6.0, -50.0], [-5.0, 50.0], 3.0)); + let pinball = bounce(Ray::new([0.0, 0.0, 1.0], [1.0, 0.1, 0.0], 100.0), 3, |r| { + corridor.raycast(r) + }); + assert_eq!(pinball.hits.len(), 4); + assert_eq!(pinball.end, pinball.hits[3].point); + } + + /// A hill `1 − (x² + y²)/16` (r 4) on a 20 m grid, a hole at x > 6. + fn hill() -> Heightfield { + Heightfield::new([-10.0, -10.0], 0.5, 41, 41, |x, y| { + if x > 6.0 { + HOLE + } else { + (1.0 - (x * x + y * y) / 16.0).max(0.0) + } + }) + } + + #[test] + fn terrain_has_heights_normals_and_holes() { + let field = hill(); + let (h, n) = field.height_at([0.0, 0.0]).unwrap(); + assert!(close(h, 1.0) && n[2] > 0.99, "{h} {n:?}"); + // On its flank the normal leans away from the top. + let (h, n) = field.height_at([2.0, 0.0]).unwrap(); + assert!((h - 0.75).abs() < 0.02, "{h}"); + assert!(n[0] > 0.2 && n[1].abs() < 0.05 && n[2] > 0.9, "{n:?}"); + assert!(walkable(n)); + assert!(field.height_at([8.0, 0.0]).is_none(), "a hole"); + assert!(field.height_at([11.0, 0.0]).is_none(), "off the grid"); + let world = Colliders::new() + .with(Collider::aabb([-1.0, 5.0], [1.0, 7.0], 1.5)) + .with_terrain(field, layer::DEFAULT); + assert_eq!( + world.ground_at([0.0, 0.0], layer::ALL).unwrap().target, + Target::Terrain + ); + let platform = world.ground_at([0.0, 6.0], layer::ALL).unwrap(); + assert_eq!((platform.target, platform.height), (Target::Static(0), 1.5)); + assert!(world.ground_at([8.0, 0.0], layer::ALL).is_none()); + } + + /// Rays with unbounded or invalid ranges end (marching is clipped to + /// the grid), and hit what a bounded ray hits. + #[test] + fn terrain_raycasts_end_for_any_range() { + let (done, results) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let field = hill(); + // Built as a struct: `Ray::new` turns a NaN range into 0. + let cast = |origin: Vec3, dir: Vec3, max_dist: f32| { + field.raycast(&Ray { + max_dist, + ..Ray::new(origin, dir, 1.0) + }) + }; + let mut got = Vec::new(); + for range in [f32::MAX, f32::INFINITY, f32::NAN] { + // Level over the grid, outward, from far away, down onto the + // hill, and a NaN ray. + got.push(cast([0.0, 0.0, 5.0], [1.0, 0.0, 0.0], range).map(|h| h.0)); + got.push(cast([0.0, 0.0, 5.0], [0.0, 0.0, 1.0], range).map(|h| h.0)); + got.push(cast([-1e4, 0.0, 0.5], [1.0, 0.0, 0.0], range).map(|h| h.0)); + got.push(cast([2.0, 0.0, 5.0], [0.0, 0.0, -1.0], range).map(|h| h.0)); + got.push(cast([f32::NAN, 0.0, 5.0], [0.0, 0.0, -1.0], range).map(|h| h.0)); + got.push(cast([8.0, 0.0, 5.0], [0.0, 0.0, -1.0], range).map(|h| h.0)); + } + let _ = done.send(got); + }); + let got = results + .recv_timeout(std::time::Duration::from_secs(10)) + .expect("raycasts ended"); + let hit = |t: Option, want: f32| t.is_some_and(|t| (t - want).abs() < 0.02); + for (range, cases) in ["MAX", "inf", "NaN"].iter().zip(got.as_chunks::<6>().0) { + if *range == "NaN" { + assert!(cases.iter().all(Option::is_none), "{range}: {cases:?}"); + continue; + } + assert_eq!(cases[0], None, "{range}: over the hill"); + assert_eq!(cases[1], None, "{range}: up"); + // r = sqrt(16 * 0.5) from the hill's centre. + assert!(hit(cases[2], 1e4 - 8f32.sqrt()), "{range}: {:?}", cases[2]); + assert!(hit(cases[3], 4.25), "{range}: {:?}", cases[3]); + assert_eq!(cases[4], None, "{range}: NaN origin"); + assert_eq!(cases[5], None, "{range}: down a hole"); + let buried = Ray { + max_dist: f32::INFINITY, + ..Ray::new([0.0, 0.0, -5.0], [0.0, 0.0, 1.0], 1.0) + }; + assert_eq!(hill().raycast(&buried).map(|h| h.0), Some(0.0), "under it"); + } + } + + #[test] + fn a_ray_lands_on_a_hill_and_bounces_off_its_flank() { + let world = Colliders::new().with_terrain(hill(), layer::DEFAULT); + let down = world + .raycast(&Ray::new([2.0, 0.0, 5.0], [0.0, 0.0, -1.0], 100.0)) + .unwrap(); + assert_eq!(down.target, Target::Terrain); + assert!((down.point[2] - 0.75).abs() < 0.02, "{down:?}"); + // Level, low: into the hill's side, thrown up and back. + let level = world + .raycast(&Ray::new([-9.0, 0.0, 0.5], [1.0, 0.0, 0.0], 100.0)) + .unwrap(); + assert!(level.point[0] < -2.0 && level.point[0] > -3.2, "{level:?}"); + let out = reflect([1.0, 0.0, 0.0], level.normal); + assert!(out[0] < 1.0 && out[2] > 0.0, "{out:?}"); + // Over the top, and down the hole. + assert!(world + .raycast(&Ray::new([-9.0, 0.0, 1.2], [1.0, 0.0, 0.0], 100.0)) + .is_none()); + assert!(world + .raycast(&Ray::new([8.0, 0.0, 5.0], [0.0, 0.0, -1.0], 100.0)) + .is_none()); + // A nearer wall still wins. + let walled = Colliders::new() + .with(Collider::aabb([-6.0, -1.0], [-5.5, 1.0], 3.0)) + .with_terrain(hill(), layer::DEFAULT); + assert_eq!( + walled + .raycast(&Ray::new([-9.0, 0.0, 0.5], [1.0, 0.0, 0.0], 100.0)) + .unwrap() + .target, + Target::Static(0) + ); + } + + #[test] + fn movers_are_pushed_out_of_columns_and_boxes() { + let walls = Colliders::new() + .with(Collider::cylinder([0.0, 0.0], 1.0, 2.0)) + .with(Collider::aabb([5.0, -1.0], [7.0, 1.0], 2.0)); + let out = walls.push_out([0.5, 0.0], 0.5, layer::ALL); + assert!(close(out[0], 1.5) && close(out[1], 0.0), "{out:?}"); + let beside = walls.push_out([4.8, 0.0], 0.5, layer::ALL); + assert!(close(beside[0], 4.5), "{beside:?}"); + let deep = walls.push_out([6.9, 0.2], 0.5, layer::ALL); + assert!(close(deep[0], 7.5), "{deep:?}"); + let clear = walls.push_out([3.0, 3.0], 0.5, layer::ALL); + assert_eq!(clear, [3.0, 3.0]); + assert_eq!(walls.push_out([0.5, 0.0], 0.5, layer::NONE), [0.5, 0.0]); + } + + fn statics(points: &[Vec3], end: Vec3) -> Trace { + Trace { + hits: points + .iter() + .enumerate() + .map(|(i, &point)| RayHit { + target: Target::Static(i), + distance: 0.0, + point, + normal: [-1.0, 0.0, 0.0], + }) + .collect(), + end, + } + } + + #[test] + fn a_trace_stops_at_the_first_collider_on_the_stop_layers() { + let colliders = Colliders::new() + .with(Collider::aabb([0.0, 0.0], [1.0, 1.0], 1.0)) + .with(Collider::aabb([2.0, 0.0], [3.0, 1.0], 1.0).on_layers(1 << 4)) + .with(Collider::aabb([4.0, 0.0], [5.0, 1.0], 1.0)); + let mut trace = statics(&[[1.0, 0.0, 0.5], [2.0, 0.0, 0.5], [4.0, 0.0, 0.5]], [9.0; 3]); + trace.stop_at(&colliders, 1 << 4); + assert_eq!(trace.hits.len(), 2); + assert_eq!(trace.end, [2.0, 0.0, 0.5]); + // Nothing on those layers: unchanged. + let mut other = statics(&[[1.0, 0.0, 0.5]], [9.0; 3]); + other.stop_at(&colliders, 1 << 5); + assert_eq!(other.end, [9.0; 3]); + } + + #[test] + fn a_leg_that_ends_on_a_side_does_not_leave_the_box() { + let half = 10.0; + let stopped = statics(&[[half, 8.0, 3.0]], [half, 8.0, 3.0]); + assert!(stopped.exit_box([0.0, 8.0, 1.5], half).is_none()); + // A hair short of the side in floating point: stays too. + let short = statics(&[[half - 1e-5, 8.0, 3.0]], [half - 1e-5, 8.0, 3.0]); + assert!(short.exit_box([0.0, 8.0, 1.5], half).is_none()); + } + + #[test] + fn a_trace_leaves_by_the_first_side_it_crosses() { + let half = 10.0; + let through = statics(&[], [60.0, 0.0, 1.5]); + let exit = through.exit_box([0.0, 0.0, 1.5], half).expect("leaves +x"); + assert_eq!(exit.side, [1, 0]); + assert!(close3(exit.point, [half, 0.0, 1.5])); + assert!(close(exit.travelled, half)); + assert_eq!(exit.leg, 0); + // Off a wall at x = 5, back out through −x on the second leg. + let bounced = statics(&[[5.0, 0.0, 1.0]], [-30.0, 0.0, 1.0]); + let exit = bounced.exit_box([0.0, 0.0, 1.0], half).expect("leaves −x"); + assert_eq!(exit.side, [-1, 0]); + assert_eq!(exit.leg, 1); + assert!(close(exit.travelled, 5.0 + 15.0)); + assert!(close3(exit.dir, [-1.0, 0.0, 0.0])); + // Diagonal through a corner region: the nearer side wins. + let diagonal = statics(&[], [30.0, 15.0, 0.0]); + assert_eq!(diagonal.exit_box([0.0, 0.0, 0.0], half).unwrap().side, [1, 0]); + } +} diff --git a/distributed_game/src/command_sink.rs b/distributed_game/src/command_sink.rs new file mode 100644 index 000000000..97ab018d7 --- /dev/null +++ b/distributed_game/src/command_sink.rs @@ -0,0 +1,767 @@ +//! [`CommandFactSink`]: a zone's facts dispatched as commands through any +//! [`FactHost`] — the same durable aggregates whether they are reached over +//! celld's internal HTTP path ([`CelldCommandHost`], feature `command-host`, +//! `POST {celld}/{kind}/{shard}/{command}`), object-to-object from a zone +//! running as a celld Durable Object +//! ([`CelldObjectHost`](crate::celld_zone::CelldObjectHost), feature +//! `celld-zone`, wasm32), or in an ordinary service over any repository +//! ([`LocalCommandHost`], feature `command-host`). +//! +//! One sink per zone (host) routes every fact by its command +//! ([`FactCommand::COMMAND`](crate::FactCommand::COMMAND)) to a registered +//! [`FactRoute`]: a cell kind and a shard function of the fact's input and +//! trusted session (principal + [`FactStamp`](crate::FactStamp)). A host +//! that addresses cells uses both; a service routes by command and its +//! handler picks the stream from the same session or input. Player +//! lifecycle facts (`zone.*`, [`crate::lifecycle`]) route to the presence +//! aggregate of the player's account ([`CommandFactSink::lifecycle_route`]). +//! +//! - **Exactly one commit per key.** The command id is +//! [`command_id_for`]`(service_id, fact key)`, so a retry after a timeout +//! replays through the aggregate's command ledger (`replayed` receipt). +//! - **Trusted identity.** The principal (bound by the zone host from the +//! verified ticket) is the session's `x-user-id`; the stamp travels as +//! `x-game-*` session variables (forwarded to cells as trusted metadata). +//! - **No local durable fallback.** A host that is slow or unreachable, a +//! 5xx, or a command still in progress is [`FactError::Retryable`]: the fact +//! stays in the zone's queue (use +//! [`RetryPolicy::until_settled`](crate::RetryPolicy::until_settled)). An +//! unrouted or rejected command is [`FactError::Permanent`]. + +use std::sync::Arc; +#[cfg(feature = "command-host")] +use std::time::Duration; + +#[cfg(feature = "command-host")] +use distributed::cell_host::{CelldCommandHost, InternalHttpSecret}; +#[cfg(feature = "command-host")] +use distributed::command_dispatch::{CommandHost, LocalCommandHost, VerifiedPrincipal}; +#[cfg(feature = "command-host")] +#[cfg(feature = "command-host")] +use distributed::microsvc::CausalDispatchError; +use distributed::microsvc::Session; +use serde_json::Value; + +use crate::cell::{command_id_for, session_stamp, trusted_session}; +use crate::facts::{ + commit_each, BoxFuture, Fact, FactBatchSink, FactCommand, FactError, FactReceipt, FactSink, +}; +use crate::lifecycle::LIFECYCLE_COMMANDS; +#[cfg(feature = "command-host")] +use crate::stamp::SESSION_PREFIX; + +type ShardFn = Arc Option + Send + Sync>; + +/// Where facts of one command go: an aggregate kind and a shard function of +/// the fact's input and trusted session. +#[derive(Clone)] +pub struct FactRoute { + command: String, + kind: String, + shard: ShardFn, +} + +impl FactRoute { + /// Route `command` to `{kind}/{shard(input, session)}`. The session holds + /// the fact's principal (`user_id()`) and stamp + /// ([`session_stamp`]). Return `None` when the fact cannot be routed. + pub fn new( + command: impl Into, + kind: impl Into, + shard: impl Fn(&Value, &Session) -> Option + Send + Sync + 'static, + ) -> Self { + Self { + command: command.into(), + kind: kind.into(), + shard: Arc::new(shard), + } + } + + /// Route the typed fact `C` to the aggregate of its principal. + pub fn by_principal(kind: impl Into) -> Self { + Self::new(C::COMMAND, kind, |_, session| { + session.user_id().map(str::to_string) + }) + } + + /// Route the typed fact `C` by a field of its input. + pub fn by_input_field(kind: impl Into, field: &'static str) -> Self { + Self::new(C::COMMAND, kind, move |input, _| { + match input.get(field)? { + Value::String(value) => Some(value.clone()), + Value::Number(value) => Some(value.to_string()), + _ => None, + } + }) + } + + /// Route the typed fact `C` to the aggregate of the zone that emitted it. + pub fn by_zone(kind: impl Into) -> Self { + Self::new(C::COMMAND, kind, |_, session| { + session_stamp(session).map(|stamp| stamp.zone_id) + }) + } + + /// The routed command. + pub fn command(&self) -> &str { + &self.command + } + + /// The aggregate kind (cell URL segment). + pub fn kind(&self) -> &str { + &self.kind + } + + /// The shard of a fact with `input` and `session`. + pub fn shard(&self, input: &Value, session: &Session) -> Option { + (self.shard)(input, session) + } +} + +/// One routed fact, ready for a [`FactHost`]. +#[derive(Debug, Clone)] +pub struct FactCall<'a> { + /// Durable command name. + pub command: &'a str, + /// Aggregate kind of the route. + pub kind: &'a str, + /// Validated shard (non-empty, printable ASCII, ≤ 256 bytes). + pub shard: String, + /// Deterministic command id ([`command_id_for`]). + pub command_id: String, + /// Command input. + pub input: &'a Value, + /// Verified principal of the fact (or the sink's system principal). + pub principal: String, + /// Trusted session: `x-user-id` + the `x-game-*` stamp. + pub session: Session, +} + +/// What a [`CommandFactSink`] dispatches through: anything that runs one +/// durable command idempotently by command id. Implemented for +/// [`CelldCommandHost`] and [`LocalCommandHost`] (feature `command-host`) +/// and for the celld object host (feature `celld-zone`). +pub trait FactHost: Send + Sync + 'static { + /// Learn `route` (a host that addresses aggregates by kind and shard + /// records it; one that routes by command ignores it). + fn register_fact_route(&mut self, _route: &FactRoute) {} + + /// Run `call` once per command id. Classify failures: unreachable, + /// 5xx, in progress → [`FactError::Retryable`]; anything else → + /// [`FactError::Permanent`]. + fn dispatch_fact<'a>( + &'a self, + call: FactCall<'a>, + ) -> BoxFuture<'a, Result>; + + /// The host's batch route, if it runs many facts for one aggregate in + /// one request (default none: one by one). Opting in and supplying the + /// batch dispatch are the same override, usually `Some(self)`; the + /// sink's [`FactSink::batches`] follows it. + fn fact_batches(&self) -> Option<&dyn FactBatchHost> { + None + } +} + +/// A [`FactHost`] with a batch route, handed out by +/// [`FactHost::fact_batches`]. +pub trait FactBatchHost: Send + Sync { + /// Run `calls` (consecutive facts for one aggregate: same kind and + /// shard) in order, under [`FactBatchSink::commit_batch`]'s contract: + /// the results end at the first retryable failure. + fn dispatch_fact_batch<'a>( + &'a self, + calls: Vec>, + ) -> BoxFuture<'a, Vec>>; +} + +/// See the module docs. +pub struct CommandFactSink { + host: Arc, + service_id: String, + system_principal: String, + routes: Vec, +} + +impl Clone for CommandFactSink { + fn clone(&self) -> Self { + Self { + host: self.host.clone(), + service_id: self.service_id.clone(), + system_principal: self.system_principal.clone(), + routes: self.routes.clone(), + } + } +} + +impl CommandFactSink { + /// A sink dispatching through `host` under command-ledger `service_id`; + /// zone facts without a player use `system_principal`. + pub fn new( + host: H, + service_id: impl Into, + system_principal: impl Into, + ) -> Result { + let service_id = service_id.into(); + let system_principal = system_principal.into(); + if service_id.trim().is_empty() || system_principal.trim().is_empty() { + return Err("a fact sink needs a service id and a system principal".into()); + } + Ok(Self { + host: Arc::new(host), + service_id, + system_principal, + routes: Vec::new(), + }) + } + + /// Add a route (before the sink is cloned). A later route for the same + /// command replaces the earlier. + pub fn route(mut self, route: FactRoute) -> Self { + Arc::get_mut(&mut self.host) + .expect("add fact routes before cloning the sink") + .register_fact_route(&route); + self.routes + .retain(|existing| existing.command != route.command); + self.routes.push(route); + self + } + + /// Route every player lifecycle fact (`zone.*`) to the presence + /// aggregate `{kind}/{principal}` (the player's account). + pub fn lifecycle_route(mut self, kind: impl Into) -> Self { + let kind = kind.into(); + for command in LIFECYCLE_COMMANDS { + self = self.route(FactRoute::new(command, kind.clone(), |_, session| { + session.user_id().map(str::to_string) + })); + } + self + } +} + +impl CommandFactSink { + /// The host. + pub fn host(&self) -> &H { + &self.host + } + + /// The command-ledger service id. + pub fn service_id(&self) -> &str { + &self.service_id + } + + /// The route a fact would take, if any. + pub fn route_for(&self, command: &str) -> Option<&FactRoute> { + self.routes.iter().find(|route| route.command == command) + } + + /// `(principal, trusted session, command id)` of a routed fact. + pub fn prepare(&self, fact: &Fact) -> Result<(String, Session, String), FactError> { + let (_, _, principal, session, command_id) = self.resolve(fact)?; + Ok((principal, session, command_id)) + } + + #[allow(clippy::type_complexity)] + fn resolve( + &self, + fact: &Fact, + ) -> Result<(&FactRoute, String, String, Session, String), FactError> { + let route = self.route_for(fact.command()).ok_or_else(|| { + FactError::Permanent(format!("no route for fact command `{}`", fact.command())) + })?; + let principal = fact + .principal() + .unwrap_or(&self.system_principal) + .to_string(); + let session = trusted_session(&principal, fact); + let shard = route + .shard(fact.input(), &session) + .filter(|shard| { + !shard.is_empty() + && shard.len() <= 256 + && shard.bytes().all(|byte| (0x21..=0x7e).contains(&byte)) + }) + .ok_or_else(|| { + FactError::Permanent(format!( + "fact `{}` has no valid `{}` shard", + fact.key(), + route.kind + )) + })?; + Ok(( + route, + shard, + principal, + session, + command_id_for(&self.service_id, fact.key()), + )) + } +} + +impl CommandFactSink { + fn call_for<'a>(&'a self, fact: &'a Fact) -> Result, FactError> { + let (route, shard, principal, session, command_id) = self.resolve(fact)?; + Ok(FactCall { + command: fact.command(), + kind: route.kind(), + shard, + command_id, + input: fact.input(), + principal, + session, + }) + } +} + +impl FactSink for CommandFactSink { + fn commit<'a>(&'a self, fact: &'a Fact) -> BoxFuture<'a, Result> { + Box::pin(async move { self.host.dispatch_fact(self.call_for(fact)?).await }) + } + + fn batches(&self) -> Option<&dyn FactBatchSink> { + self.host.fact_batches().map(|_| self as &dyn FactBatchSink) + } +} + +impl FactBatchSink for CommandFactSink { + /// Consecutive facts for the same aggregate go to the host together + /// ([`FactBatchHost::dispatch_fact_batch`]). + fn commit_batch<'a>( + &'a self, + facts: &'a [Fact], + ) -> BoxFuture<'a, Vec>> { + Box::pin(async move { + let Some(host) = self.host.fact_batches() else { + return commit_each(self, facts).await; + }; + let mut results = Vec::with_capacity(facts.len()); + let mut i = 0; + while i < facts.len() { + let call = match self.call_for(&facts[i]) { + Ok(call) => call, + Err(error) => { + results.push(Err(error)); + i += 1; + continue; + } + }; + let mut run = vec![call]; + let mut next = i + 1; + while let Some(fact) = facts.get(next) { + match self.call_for(fact) { + Ok(call) if call.kind == run[0].kind && call.shard == run[0].shard => { + run.push(call); + next += 1; + } + _ => break, + } + } + let n = run.len(); + let batch: Vec<_> = host + .dispatch_fact_batch(run) + .await + .into_iter() + .take(n) + .collect(); + let complete = + batch.len() == n && !matches!(batch.last(), Some(Err(FactError::Retryable(_)))); + results.extend(batch); + if !complete { + break; + } + i = next; + } + results + }) + } +} + +/// celld slow, down or still running the command: keep the fact queued. +#[cfg(feature = "command-host")] +fn classify(error: CausalDispatchError) -> FactError { + let detail = format!("{}: {error:?}", error.code()); + match &error { + CausalDispatchError::InProgress + | CausalDispatchError::ConcurrentWrite + | CausalDispatchError::Internal(_) => FactError::Retryable(detail), + CausalDispatchError::Rejected { status, .. } + if *status >= 500 || matches!(*status, 408 | 429) => + { + FactError::Retryable(detail) + } + CausalDispatchError::Handler(handler) if handler.status_code() >= 500 => { + FactError::Retryable(detail) + } + _ => FactError::Permanent(detail), + } +} + +/// Any [`CommandHost`]: `invoke` with the fact's trusted session. +#[cfg(feature = "command-host")] +fn invoke_command_host<'a, H: CommandHost>( + host: &'a H, + call: FactCall<'a>, +) -> BoxFuture<'a, Result> { + Box::pin(async move { + let principal = VerifiedPrincipal::internal(&call.principal) + .map_err(|error| FactError::Permanent(error.to_string()))?; + let result = host + .invoke( + call.command, + &call.command_id, + call.input.clone(), + call.session, + principal, + None, + ) + .await + .map_err(classify)?; + Ok(FactReceipt { + payload: result.payload().clone(), + replayed: result.replayed(), + }) + }) +} + +/// A service routes by command: its handler selects the stream. +#[cfg(feature = "command-host")] +impl FactHost for LocalCommandHost { + fn dispatch_fact<'a>( + &'a self, + call: FactCall<'a>, + ) -> BoxFuture<'a, Result> { + invoke_command_host(self, call) + } +} + +/// celld addresses cells: `{kind}/{shard}/{command}`. +#[cfg(feature = "command-host")] +impl FactHost for CelldCommandHost { + fn register_fact_route(&mut self, route: &FactRoute) { + let shard = route.shard.clone(); + self.add_cell_route(route.command(), route.kind(), move |input, session| { + shard(input, session) + }); + } + + fn dispatch_fact<'a>( + &'a self, + call: FactCall<'a>, + ) -> BoxFuture<'a, Result> { + invoke_command_host(self, call) + } +} + +/// Default per-request timeout of [`CelldFactSink`]. +#[cfg(feature = "command-host")] +pub const DEFAULT_CELLD_FACT_TIMEOUT: Duration = Duration::from_secs(10); + +/// Facts into celld cells over the internal path. +#[cfg(feature = "command-host")] +pub type CelldFactSink = CommandFactSink; + +#[cfg(feature = "command-host")] +impl CommandFactSink { + /// A sink for the cells at `celld_url` under command-ledger + /// `service_id`: a remote-only [`CelldCommandHost`] forwarding the fact + /// stamp (`x-game-*`). + pub fn celld( + celld_url: impl Into, + secret: InternalHttpSecret, + service_id: impl Into, + system_principal: impl Into, + ) -> Result { + Self::celld_with_timeout( + celld_url, + secret, + service_id, + system_principal, + DEFAULT_CELLD_FACT_TIMEOUT, + ) + } + + /// As [`celld`](Self::celld) with an explicit per-request timeout. + pub fn celld_with_timeout( + celld_url: impl Into, + secret: InternalHttpSecret, + service_id: impl Into, + system_principal: impl Into, + timeout: Duration, + ) -> Result { + let service_id = service_id.into(); + let host = CelldCommandHost::remote(celld_url, &service_id, secret, timeout) + .map_err(|error| format!("celld command host: {error:?}"))? + .forward_session_prefix(SESSION_PREFIX) + .map_err(|error| format!("celld command host: {error:?}"))?; + Self::new(host, service_id, system_principal) + } +} + +#[cfg(all(test, feature = "command-host"))] +mod tests { + use super::*; + use crate::stamp::FactStamp; + use serde_json::json; + + const SECRET: &str = "test-only-internal-secret-change-me-2026"; + + #[derive(serde::Serialize)] + struct Kill { + mob: String, + } + impl FactCommand for Kill { + const COMMAND: &'static str = "crawler.record_kill"; + } + #[derive(serde::Serialize)] + struct Result_ { + match_id: String, + } + impl FactCommand for Result_ { + const COMMAND: &'static str = "match.record_result"; + } + + fn sink() -> CelldFactSink { + CelldFactSink::celld( + "http://127.0.0.1:9/", + InternalHttpSecret::new(SECRET).unwrap(), + "zone-server", + "zone:pit-1", + ) + .unwrap() + .route(FactRoute::by_principal::("crawler")) + .route(FactRoute::by_input_field::("match", "match_id")) + .lifecycle_route("presence") + } + + fn fact(command: &str, input: Value, principal: Option<&str>) -> Fact { + Fact::trusted( + format!("{command}:pit-1:1:0"), + command, + input, + principal.map(str::to_string), + FactStamp { + zone_id: "pit-1".into(), + ..FactStamp::default() + }, + ) + } + + fn shard(sink: &CelldFactSink, fact: &Fact) -> Option { + let (_, session, _) = sink.prepare(fact).ok()?; + sink.route_for(fact.command())? + .shard(fact.input(), &session) + } + + #[test] + fn routes_by_command_to_kind_and_shard_with_a_stable_command_id() { + let sink = sink(); + let kill = fact("crawler.record_kill", json!({ "mob": "m1" }), Some("alice")); + let (principal, session, id) = sink.prepare(&kill).unwrap(); + assert_eq!(principal, "alice"); + assert_eq!(session.user_id(), Some("alice")); + assert_eq!(session_stamp(&session).unwrap().zone_id, "pit-1"); + assert_eq!(id, command_id_for("zone-server", kill.key())); + assert_eq!(sink.prepare(&kill).unwrap().2, id, "stable across retries"); + assert_eq!(sink.route_for(kill.command()).unwrap().kind(), "crawler"); + assert_eq!(shard(&sink, &kill).as_deref(), Some("alice")); + + let result = fact("match.record_result", json!({ "match_id": "m/7" }), None); + assert_eq!(shard(&sink, &result).as_deref(), Some("m/7")); + assert_eq!( + sink.prepare(&result).unwrap().0, + "zone:pit-1", + "zone facts use the system principal" + ); + let spaced = fact("match.record_result", json!({ "match_id": "m 7" }), None); + assert!(matches!( + sink.prepare(&spaced), + Err(FactError::Permanent(_)) + )); + + for command in LIFECYCLE_COMMANDS { + let lifecycle = fact(command, json!({ "zone": "pit-1" }), Some("alice")); + assert_eq!(sink.route_for(command).unwrap().kind(), "presence"); + assert_eq!(shard(&sink, &lifecycle).as_deref(), Some("alice")); + } + let by_zone = FactRoute::by_zone::("zone-log"); + let (_, session, _) = sink.prepare(&kill).unwrap(); + assert_eq!( + by_zone.shard(&json!({}), &session).as_deref(), + Some("pit-1") + ); + } + + #[test] + fn unknown_commands_and_unroutable_facts_are_permanent() { + let sink = sink(); + let unknown = fact("guild.whatever", json!({}), Some("alice")); + assert!(matches!( + sink.prepare(&unknown), + Err(FactError::Permanent(_)) + )); + let missing = fact("match.record_result", json!({}), None); + assert!(matches!( + sink.prepare(&missing), + Err(FactError::Permanent(_)) + )); + } + + #[test] + fn classifies_dispatch_errors() { + let retryable = |error| matches!(classify(error), FactError::Retryable(_)); + assert!(retryable(CausalDispatchError::InProgress)); + assert!(retryable(CausalDispatchError::Internal("down".into()))); + assert!(retryable(CausalDispatchError::Rejected { + code: "REJECTED", + status: 503, + message: String::new() + })); + assert!(retryable(CausalDispatchError::Rejected { + code: "REJECTED", + status: 429, + message: String::new() + })); + assert!(!retryable(CausalDispatchError::BadRequest("bad".into()))); + assert!(!retryable(CausalDispatchError::Forbidden)); + assert!(!retryable(CausalDispatchError::Rejected { + code: "UNAUTHORIZED", + status: 401, + message: String::new() + })); + assert!(!retryable(CausalDispatchError::Rejected { + code: "REJECTED", + status: 422, + message: String::new() + })); + } + + #[tokio::test] + async fn an_unreachable_host_is_retryable() { + let sink = sink(); + let kill = fact("crawler.record_kill", json!({ "mob": "m1" }), Some("alice")); + assert!(matches!( + sink.commit(&kill).await, + Err(FactError::Retryable(_)) + )); + } + + #[test] + fn rejects_bad_configuration() { + let secret = || InternalHttpSecret::new(SECRET).unwrap(); + assert!(CelldFactSink::celld("ftp://x", secret(), "s", "p").is_err()); + assert!(CelldFactSink::celld("http://x", secret(), " ", "p").is_err()); + assert!(CelldFactSink::celld("http://x", secret(), "s", " ").is_err()); + } +} + +#[cfg(test)] +mod batch_tests { + use std::sync::Mutex; + + use serde_json::json; + + use super::*; + + /// Records each batch as `(shard, commands)`; `busy` answers retryable. + #[derive(Default)] + struct RecordingHost { + batches: Mutex>, + busy: Option, + } + + impl FactHost for RecordingHost { + fn dispatch_fact<'a>( + &'a self, + _: FactCall<'a>, + ) -> BoxFuture<'a, Result> { + unreachable!("batches only") + } + + fn fact_batches(&self) -> Option<&dyn FactBatchHost> { + Some(self) + } + } + + impl FactBatchHost for RecordingHost { + fn dispatch_fact_batch<'a>( + &'a self, + calls: Vec>, + ) -> BoxFuture<'a, Vec>> { + Box::pin(async move { + let shard = calls[0].shard.clone(); + self.batches.lock().unwrap().push((shard, calls.len())); + let mut results = Vec::new(); + for call in &calls { + if self.busy.as_deref() == Some(call.input["n"].as_str().unwrap()) { + results.push(Err(FactError::Retryable("busy".into()))); + break; + } + results.push(Ok(FactReceipt { + payload: Value::Null, + replayed: false, + })); + } + results + }) + } + } + + fn sink(host: RecordingHost) -> CommandFactSink { + CommandFactSink::new(host, "zone-test", "zone:z1") + .unwrap() + .route(FactRoute::new("credit", "room", |input, _| { + input.get("room")?.as_str().map(str::to_string) + })) + } + + fn facts(rooms: &[&str]) -> Vec { + rooms + .iter() + .enumerate() + .map(|(i, room)| { + let command = if room.is_empty() { + "unrouted" + } else { + "credit" + }; + Fact::new( + format!("k{i}"), + command, + json!({ "room": room, "n": format!("n{i}") }), + ) + }) + .collect() + } + + #[tokio::test] + async fn consecutive_facts_for_one_aggregate_travel_together() { + let sink = sink(RecordingHost::default()); + let facts = facts(&["r1", "r1", "", "r2", "r2", "r2", "r1"]); + let results = sink.commit_batch(&facts).await; + assert_eq!(results.len(), 7); + assert!(matches!(results[2], Err(FactError::Permanent(_)))); + assert!(results.iter().enumerate().all(|(i, r)| i == 2 || r.is_ok())); + assert_eq!( + *sink.host.batches.lock().unwrap(), + [("r1".into(), 2), ("r2".into(), 3), ("r1".into(), 1)] + ); + } + + #[tokio::test] + async fn a_retryable_fact_ends_the_batch() { + let sink = sink(RecordingHost { + busy: Some("n3".into()), + ..RecordingHost::default() + }); + let facts = facts(&["r1", "r1", "r2", "r2", "r2", "r3"]); + let results = sink.commit_batch(&facts).await; + // r1 ×2, then r2 stops at its second fact; r3 is not attempted. + assert_eq!(results.len(), 4); + assert!(matches!(results[3], Err(FactError::Retryable(_)))); + assert_eq!( + *sink.host.batches.lock().unwrap(), + [("r1".into(), 2), ("r2".into(), 3)] + ); + } +} diff --git a/distributed_game/src/entity.rs b/distributed_game/src/entity.rs new file mode 100644 index 000000000..fbcd7c3a8 --- /dev/null +++ b/distributed_game/src/entity.rs @@ -0,0 +1,245 @@ +//! Zone entities and the views projected from them. +//! +//! A zone is the **aggregate root**: one authoritative boundary that owns +//! its state and changes it only on its own tick. The things inside it +//! (players, mobs, projectiles) are **entities**: server state with an +//! [`EntityId`], including data no client may see (targets, spawn points, +//! credits, principals). What clients receive are **views**, the zone's +//! **read models**: `#[derive(Replicated)]` structs projected from an +//! entity each patch. A view is a projection, not a copy: it may convert +//! (HP to a percent), derive (a telegraph from a timer), flatten nested +//! state, or omit the entity entirely (a dead mob). Durable outcomes leave +//! the zone as **facts**, its **domain events**, committed by cells. +//! +//! | game runtime | business side | +//! |---|---| +//! | zone | aggregate root | +//! | zone entity ([`Entity`]) | entity inside the aggregate | +//! | view ([`Replicated`], [`Project`]) | read model / projection | +//! | fact ([`Fact`](crate::Fact)) | domain event | +//! +//! **Declaring a projection.** A view names its entity type with +//! `#[replicated(.., of = Mob)]` and marks the fields that are straight +//! copies `#[from]` (same name) or `#[from(state.x)]` (a field path on the +//! entity). The derive then generates `MobView::project(&mob, MobViewRest +//! { .. })` where `MobViewRest` holds only the hand-filled fields, and the +//! zone writes the projection once: +//! +//! ```ignore +//! impl Project for Mob { +//! fn view(&self) -> Option { +//! (self.state != MobState::Dead).then(|| { +//! MobView::project(self, MobViewRest { hp: self.hp_percent(), tele: self.tele() }) +//! }) +//! } +//! } +//! ``` +//! +//! A view whose fields are all `#[from]` gets the `Project` impl generated. +//! A view without `of` is unchanged: build it by hand or implement +//! `Project` for any type. +//! +//! **Registering collections.** [`Zone::entities`](crate::Zone::entities) +//! returns the zone's entity collections once, at creation; every patch +//! the host calls [`Project::view`] on each entity (`None` omits it) and +//! then [`Zone::replicate`](crate::Zone::replicate) for anything else: +//! +//! ```ignore +//! fn entities() -> Entities { +//! Entities::new() +//! .each(|z: &Self| &z.players) +//! .each(|z: &Self| &z.mobs) +//! .one(|z: &Self| z) // the zone itself projects its HUD view +//! } +//! ``` +//! +//! Collections are visited in registration order and each in its own order +//! (`Vec`, slices, `VecDeque`, `BTreeMap` values, `Option`): the projected +//! world is deterministic, which the replicated state hash relies on. + +use std::collections::{BTreeMap, VecDeque}; +use std::fmt; + +use crate::authoring::{Pushed, Replicated}; +use crate::replication::WorldView; + +/// Id of a replicated zone entity (unique within the zone). +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +pub struct EntityId(pub u32); + +impl EntityId { + /// The raw id. + pub const fn get(self) -> u32 { + self.0 + } +} + +impl From for EntityId { + fn from(id: u32) -> Self { + Self(id) + } +} + +impl From for u32 { + fn from(id: EntityId) -> Self { + id.0 + } +} + +impl fmt::Display for EntityId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +/// A zone entity: anything the zone replicates under its own id. +pub trait Entity { + /// Its id. + fn entity_id(&self) -> EntityId; +} + +/// Projection of a zone entity (or the zone itself) into view `V`. +pub trait Project { + /// The view this patch; `None` leaves the entity out (clients that + /// know it get a remove). + fn view(&self) -> Option; +} + +/// Something holding entities, visited in a deterministic order. +pub trait EntityCollection { + /// Entity type. + type Item; + /// Visit every entity. + fn visit(&self, f: &mut dyn FnMut(&Self::Item)); +} + +impl EntityCollection for [E] { + type Item = E; + fn visit(&self, f: &mut dyn FnMut(&E)) { + self.iter().for_each(f); + } +} + +impl EntityCollection for Vec { + type Item = E; + fn visit(&self, f: &mut dyn FnMut(&E)) { + self.iter().for_each(f); + } +} + +impl EntityCollection for [E; N] { + type Item = E; + fn visit(&self, f: &mut dyn FnMut(&E)) { + self.iter().for_each(f); + } +} + +impl EntityCollection for VecDeque { + type Item = E; + fn visit(&self, f: &mut dyn FnMut(&E)) { + self.iter().for_each(f); + } +} + +impl EntityCollection for BTreeMap { + type Item = E; + fn visit(&self, f: &mut dyn FnMut(&E)) { + self.values().for_each(f); + } +} + +impl EntityCollection for Option { + type Item = E; + fn visit(&self, f: &mut dyn FnMut(&E)) { + self.iter().for_each(f); + } +} + +type Projection = Box; + +/// A zone's registered entity collections ([`Zone::entities`](crate::Zone::entities)). +pub struct Entities { + projections: Vec>, +} + +impl Default for Entities { + fn default() -> Self { + Self { + projections: Vec::new(), + } + } +} + +impl fmt::Debug for Entities { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Entities") + .field("collections", &self.projections.len()) + .finish() + } +} + +impl Entities { + /// No collections. + pub fn new() -> Self { + Self::default() + } + + /// Project every entity of a collection into view `V` (inferred when + /// the entity type projects into one view; otherwise + /// `.each::(..)`). + pub fn each(mut self, collection: fn(&Z) -> &C) -> Self + where + V: Replicated, + C: EntityCollection + ?Sized + 'static, + C::Item: Entity + Project, + { + self.projections.push(Box::new(move |zone, out| { + collection(zone).visit(&mut |entity| { + out.project::(entity); + }); + })); + self + } + + /// Project a single entity (the zone itself, `|z| z`, for a HUD view). + pub fn one(mut self, entity: fn(&Z) -> &E) -> Self + where + V: Replicated, + E: Entity + Project + ?Sized + 'static, + { + self.projections.push(Box::new(move |zone, out| { + out.project::(entity(zone)); + })); + self + } + + /// Collections registered. + pub fn len(&self) -> usize { + self.projections.len() + } + + /// True when nothing is registered. + pub fn is_empty(&self) -> bool { + self.projections.is_empty() + } + + /// Push every registered entity's view into `out`. + pub fn project(&self, zone: &Z, out: &mut WorldView) { + for projection in &self.projections { + projection(zone, out); + } + } +} + +impl WorldView { + /// Push `entity`'s view `V` under its id; `None` when the projection + /// omits it. For hand-written [`Zone::replicate`](crate::Zone::replicate). + pub fn project(&mut self, entity: &E) -> Option> + where + V: Replicated, + E: Entity + Project + ?Sized, + { + let view = entity.view()?; + Some(self.add(entity.entity_id(), &view)) + } +} diff --git a/distributed_game/src/facts.rs b/distributed_game/src/facts.rs new file mode 100644 index 000000000..49a52dbc3 --- /dev/null +++ b/distributed_game/src/facts.rs @@ -0,0 +1,1040 @@ +//! Non-blocking durable facts. +//! +//! A *fact* is a meaningful, durable outcome of simulation ("enemy killed, +//! credit XP to player P"). Zones emit facts during a tick through +//! [`Ctx::emit_fact`](crate::Ctx::emit_fact); the call only enqueues. A +//! [`FactSink`] commits them asynchronously on a worker ([`FactFeed::run`] or +//! `spawn_fact_worker` with the `runtime` feature) with bounded retries and +//! exponential backoff; the resulting [`FactSettlement`] is delivered back to +//! the zone (`Zone::on_fact_settled`) at the start of a later tick. +//! **The tick never awaits storage.** +//! +//! Guarantees: +//! - Bounded: at most `capacity` facts may be unsettled; beyond that +//! `emit_fact` returns [`EmitError::Backpressure`] and the game decides +//! (retry next tick, freeze, drop a cosmetic fact). +//! - Idempotent: each fact has a caller-chosen idempotency key. The queue +//! rejects a key already in flight; sinks must treat a repeated key as a +//! replay (the cell adapter maps it onto `dispatch_idempotent`). +//! - Trusted identity: the principal is bound by the host from the player's +//! verified ticket — zones and clients cannot set it. +//! +//! Ordering: by default (`max_concurrent_commits = 1`) one worker commits +//! facts strictly in emission order, one at a time, so a slow commit delays +//! every later fact. With [`FactFeed::with_max_concurrent_commits`]`(n > 1)` +//! up to `n` commits run at once, in **lanes by principal**: facts of the +//! same principal (and, separately, all zone/system facts without one) are +//! still committed one at a time in emission order, while facts of +//! different principals overlap. A key is never in flight twice (the queue +//! refuses duplicates), so per-key order always holds. Settlements arrive +//! in completion order. +//! +//! Batching: a sink that settles many facts in one round trip (the +//! celld object host: one `__batch` request per cell) returns its +//! [`FactBatchSink`] from [`FactSink::batches`]; the feed then hands it up +//! to [`FactFeed::with_max_batch`] (default [`DEFAULT_MAX_BATCH`]) +//! consecutive facts of one lane at once ([`FactBatchSink::commit_batch`]). +//! Other sinks keep getting one fact at a time, so their settlements flow +//! back per fact. A batch commits in order and stops at its first +//! retryable failure, which is retried from there, so order and +//! exactly-once hold as for single facts. + +use std::collections::{HashSet, VecDeque}; +use std::future::Future; +use std::pin::Pin; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc; +use std::sync::{Arc, Mutex}; +use std::task::{Context, Poll, Waker}; +use std::time::Duration; + +use serde_json::Value; + +use crate::stamp::FactStamp; + +/// Boxed `Send` future used by [`FactSink`]. +pub type BoxFuture<'a, T> = Pin + Send + 'a>>; + +/// Restart-safe idempotency key: `"{prefix}:{zone}:{epoch}:{part}:…"`. +/// +/// `epoch` must change between activations and grow across restarts +/// ([`Ctx::boot_epoch`](crate::Ctx::boot_epoch)). Keys derived only from the +/// tick or an entity generation **collide after a restart** — both counters +/// start again from zero — and an idempotent sink then treats the new +/// outcome as a replay of the old one (silently dropping it). +/// +/// ``` +/// use distributed_game::facts::fact_key; +/// assert_eq!(fact_key("kill", "pit-1", 7, &[&"mob-3", &42]), "kill:pit-1:7:mob-3:42"); +/// ``` +pub fn fact_key(prefix: &str, zone: &str, epoch: u64, parts: &[&dyn std::fmt::Display]) -> String { + use std::fmt::Write as _; + let mut key = format!("{prefix}:{zone}:{epoch}"); + for part in parts { + let _ = write!(key, ":{part}"); + } + key +} + +/// A cell command input a zone may emit as a typed fact +/// (`#[derive(FactCommand)]`, or implement by hand). +/// +/// `COMMAND` names the durable command the input belongs to: point it at +/// the same constant the cell mounts it under (`typed_command::(NAME)` +/// or `#[command]`'s generated `_COMMAND_ID`), so the zone and the +/// handler cannot disagree. [`Ctx::emit`](crate::Ctx::emit) then builds the +/// restart-safe key (`"{COMMAND}:{zone}:{boot_epoch}:{parts…}"`) from +/// [`dedupe_parts`](Self::dedupe_parts), or from the tick and emission order +/// when it returns none. +/// +/// Trust rules (enforced by the host, not by this trait): the principal is +/// bound from the player's verified ticket, never from the input; the input +/// reports *what happened* (which mob died) and the command handler decides +/// any reward or economy amount. The derive rejects identity-, reward- and +/// economy-looking field names (`user_id`, `xp`, `amount`, `gold`, …). +pub trait FactCommand: serde::Serialize { + /// Durable command name. + const COMMAND: &'static str; + + /// Parts that identify this logical outcome within one zone activation + /// (e.g. mob id + generation). Empty = use the tick and emission order. + fn dedupe_parts(&self) -> Vec { + Vec::new() + } +} + +/// A durable outcome to commit. +#[derive(Debug, Clone, PartialEq)] +pub struct Fact { + key: String, + command: String, + input: Value, + principal: Option, + stamp: FactStamp, +} + +impl Fact { + /// `key` must be unique per logical outcome **across restarts**: build it + /// with [`Ctx::fact_key`](crate::Ctx::fact_key) / [`fact_key`] (zone + + /// boot epoch + your parts), never from the tick alone; + /// `command` names the durable command; `input` is its payload. + pub fn new(key: impl Into, command: impl Into, input: Value) -> Self { + Self { + key: key.into(), + command: command.into(), + input, + principal: None, + stamp: FactStamp::default(), + } + } + + /// Typed fact: `C::COMMAND` with `input` serialized as its payload. + pub fn typed( + key: impl Into, + input: &C, + ) -> Result { + Ok(Self::new(key, C::COMMAND, serde_json::to_value(input)?)) + } + + /// True when this fact is a `C` command. + pub fn is(&self) -> bool { + self.command == C::COMMAND + } + + /// Idempotency key. + pub fn key(&self) -> &str { + &self.key + } + + /// Command name. + pub fn command(&self) -> &str { + &self.command + } + + /// Command input. + pub fn input(&self) -> &Value { + &self.input + } + + /// Verified principal (from the player's ticket), or None for zone/system facts. + pub fn principal(&self) -> Option<&str> { + self.principal.as_deref() + } + + /// Provenance stamp. + pub fn stamp(&self) -> &FactStamp { + &self.stamp + } + + pub(crate) fn bind(mut self, principal: Option, stamp: FactStamp) -> Self { + self.principal = principal; + self.stamp = stamp; + self + } + + /// Build a fact with an explicit principal/stamp. Only for sinks' own + /// tests and tooling; zones go through `Ctx::emit_fact_for`. + pub fn trusted( + key: impl Into, + command: impl Into, + input: Value, + principal: Option, + stamp: FactStamp, + ) -> Self { + Self::new(key, command, input).bind(principal, stamp) + } +} + +/// Sink failure classification. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum FactError { + /// Transient; retried with backoff. + Retryable(String), + /// Will never succeed; settles as failed immediately. + Permanent(String), +} + +/// Successful commit. +#[derive(Debug, Clone, PartialEq)] +pub struct FactReceipt { + /// Sink-specific result payload. + pub payload: Value, + /// True when the sink recognised the key as already committed. + pub replayed: bool, +} + +impl FactReceipt { + /// The sink's result payload as a typed value (e.g. the command output). + pub fn payload_as(&self) -> Result { + T::deserialize(&self.payload) + } +} + +/// Final outcome of one fact. +#[derive(Debug, Clone, PartialEq)] +pub enum FactOutcome { + /// Durably committed. + Committed(FactReceipt), + /// Gave up. + Failed { + /// Last error. + error: FactError, + /// Attempts made. + attempts: u32, + }, +} + +/// Delivered to the zone on a later tick. +#[derive(Debug, Clone, PartialEq)] +pub struct FactSettlement { + /// Idempotency key. + pub key: String, + /// Command name. + pub command: String, + /// Outcome. + pub outcome: FactOutcome, +} + +impl FactSettlement { + /// True when the settled fact was a `C` command. + pub fn is(&self) -> bool { + self.command == C::COMMAND + } +} + +/// Durable commit target. +pub trait FactSink: Send + Sync + 'static { + /// Commit one fact. Must be idempotent per [`Fact::key`]. + fn commit<'a>(&'a self, fact: &'a Fact) -> BoxFuture<'a, Result>; + + /// The sink's batch committer, if a batch is cheaper than its facts + /// one by one (default none: one fact at a time, each settlement + /// delivered as soon as it commits). Opting in and supplying the + /// batch commit are the same override, usually `Some(self)`. + fn batches(&self) -> Option<&dyn FactBatchSink> { + None + } +} + +/// A [`FactSink`] that settles many facts per round trip, handed to the +/// feed by [`FactSink::batches`]. +pub trait FactBatchSink: Send + Sync { + /// Commit `facts` in order: one result per fact attempted. The + /// results end at the first [`FactError::Retryable`] (included), or + /// earlier; facts past the end were not attempted and are retried. + fn commit_batch<'a>( + &'a self, + facts: &'a [Fact], + ) -> BoxFuture<'a, Vec>>; +} + +/// [`FactBatchSink::commit_batch`] for a sink without batches: its facts +/// one by one, stopping after the first retryable result. +pub(crate) async fn commit_each( + sink: &S, + facts: &[Fact], +) -> Vec> { + let mut results = Vec::with_capacity(facts.len()); + for fact in facts { + let result = sink.commit(fact).await; + let stop = matches!(result, Err(FactError::Retryable(_))); + results.push(result); + if stop { + break; + } + } + results +} + +/// Facts per [`FactBatchSink::commit_batch`] unless the feed says otherwise. +pub const DEFAULT_MAX_BATCH: usize = 16; + +/// Retry/backoff policy. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RetryPolicy { + /// Total attempts including the first (>= 1). + pub max_attempts: u32, + /// Delay after the first retryable failure; doubles each time. + pub base_backoff: Duration, + /// Backoff ceiling. + pub max_backoff: Duration, +} + +impl Default for RetryPolicy { + fn default() -> Self { + Self { + max_attempts: 8, + base_backoff: Duration::from_millis(50), + max_backoff: Duration::from_secs(5), + } + } +} + +impl RetryPolicy { + /// Retry retryable failures until the fact settles (backing off up to + /// `max_backoff`): a network sink whose target is down keeps the fact + /// pending in the queue, so the zone sees backpressure at capacity + /// instead of losing durable outcomes. Permanent failures still settle + /// immediately. + pub fn until_settled(base_backoff: Duration, max_backoff: Duration) -> Self { + Self { + max_attempts: u32::MAX, + base_backoff, + max_backoff, + } + } + + /// Backoff before attempt `attempt + 1` (attempt >= 1). + pub fn backoff(&self, attempt: u32) -> Duration { + let factor = 1u32 << attempt.saturating_sub(1).min(20); + self.base_backoff + .saturating_mul(factor) + .min(self.max_backoff) + } +} + +/// Why `emit_fact` refused a fact. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum EmitError { + /// `capacity` facts are unsettled. + Backpressure, + /// A fact with this key is already in flight. + DuplicateKey, + /// The host has no fact queue attached. + NoSink, + /// The player is unknown (cannot bind a principal). + UnknownPlayer, + /// A typed fact input did not serialize. + Encode(String), +} + +#[derive(Debug, Default)] +struct Shared { + queue: Mutex>, + waker: Mutex>, + closed: AtomicBool, +} + +impl Shared { + fn wake(&self) { + if let Some(waker) = self.waker.lock().expect("waker lock").take() { + waker.wake(); + } + } +} + +/// Zone-side handle: enqueue facts, collect settlements. Never blocks. +#[derive(Debug)] +pub struct FactQueue { + shared: Arc, + settlements: mpsc::Receiver, + in_flight: HashSet, + capacity: usize, + script: Option, + journal: Option>, +} + +/// Worker-side handle consumed by [`FactFeed::run`]. +#[derive(Debug)] +pub struct FactFeed { + shared: Arc, + settlements: mpsc::Sender, + policy: RetryPolicy, + max_concurrent: usize, + max_batch: usize, +} + +/// Create a queue allowing `capacity` unsettled facts. +pub fn fact_channel(capacity: usize, policy: RetryPolicy) -> (FactQueue, FactFeed) { + let shared = Arc::new(Shared::default()); + let (tx, rx) = mpsc::channel(); + ( + FactQueue { + shared: shared.clone(), + settlements: rx, + in_flight: HashSet::new(), + capacity: capacity.max(1), + script: None, + journal: None, + }, + FactFeed { + shared, + settlements: tx, + policy, + max_concurrent: 1, + max_batch: DEFAULT_MAX_BATCH, + }, + ) +} + +impl FactQueue { + /// Enqueue without blocking. + pub fn try_send(&mut self, fact: Fact) -> Result<(), EmitError> { + if self.in_flight.contains(fact.key()) { + return Err(EmitError::DuplicateKey); + } + if self.in_flight.len() >= self.capacity { + return Err(EmitError::Backpressure); + } + self.in_flight.insert(fact.key.clone()); + if let Some(journal) = self.journal.as_mut() { + journal.push(fact.clone()); + } + if self.script.is_some() { + return Ok(()); + } + self.shared + .queue + .lock() + .expect("fact queue lock") + .push_back(fact); + self.shared.wake(); + Ok(()) + } + + /// Keep a copy of every accepted fact until [`take_journal`](Self::take_journal): + /// a host that keeps its own durable outbox writes them there right + /// after the tick that emitted them (the celld zone host does). + pub fn with_journal(mut self) -> Self { + self.journal = Some(Vec::new()); + self + } + + /// Facts accepted since the last call (empty without a journal). + pub fn take_journal(&mut self) -> Vec { + self.journal + .as_mut() + .map(std::mem::take) + .unwrap_or_default() + } + + /// Settlements that arrived since the last call. + pub fn drain(&mut self) -> Vec { + let settled: Vec<_> = self.settlements.try_iter().collect(); + for s in &settled { + self.in_flight.remove(&s.key); + } + settled + } + + /// Unsettled facts. + pub fn in_flight(&self) -> usize { + self.in_flight.len() + } + + /// Unsettled facts allowed. + pub(crate) fn capacity(&self) -> usize { + self.capacity + } + + /// Close the queue dropping the facts its worker has not taken yet + /// (a plain drop lets the worker commit them first). + pub fn abandon(self) { + self.shared.queue.lock().expect("fact queue lock").clear(); + } + + /// Queue whose settlements come from a script instead of a worker + /// (record/replay). Emitted facts are tracked for backpressure and + /// duplicate keys exactly like a live queue but never committed. + pub fn scripted(capacity: usize) -> (Self, SettlementScript) { + let (mut queue, _feed) = fact_channel(capacity, RetryPolicy::default()); + let script = SettlementScript::default(); + queue.script = Some(script.clone()); + (queue, script) + } + + /// Settlements due at `tick`: scripted ones scheduled at or before it, + /// otherwise whatever the worker delivered. + pub(crate) fn drain_at(&mut self, tick: u64) -> Vec { + let Some(script) = &self.script else { + return self.drain(); + }; + let mut due = Vec::new(); + { + let mut queue = script.0.lock().expect("script lock"); + while queue.front().is_some_and(|(at, _)| *at <= tick) { + due.push(queue.pop_front().expect("front").1); + } + } + for s in &due { + self.in_flight.remove(&s.key); + } + due + } +} + +/// Feeds scripted settlements into a [`FactQueue::scripted`] queue. +#[derive(Debug, Clone, Default)] +pub struct SettlementScript(Arc>>); + +impl SettlementScript { + /// Deliver `settlement` on the first settlement point at or after `tick`. + pub fn push(&self, tick: u64, settlement: FactSettlement) { + self.0 + .lock() + .expect("script lock") + .push_back((tick, settlement)); + } + + /// Scheduled but not yet delivered. + pub fn len(&self) -> usize { + self.0.lock().expect("script lock").len() + } + + /// True when nothing is scheduled. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + +impl Drop for FactQueue { + fn drop(&mut self) { + self.shared.closed.store(true, Ordering::SeqCst); + self.shared.wake(); + } +} + +/// The next facts in emission order (at most `.1`). +struct NextFact<'a>(&'a Shared, usize); + +impl Future for NextFact<'_> { + type Output = Option>; + + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + let shared = self.0; + // Register before checking so a concurrent push cannot be missed. + *shared.waker.lock().expect("waker lock") = Some(cx.waker().clone()); + let mut queue = shared.queue.lock().expect("fact queue lock"); + if !queue.is_empty() { + let n = queue.len().min(self.1); + return Poll::Ready(Some(queue.drain(..n).collect())); + } + drop(queue); + if shared.closed.load(Ordering::SeqCst) { + return Poll::Ready(None); + } + Poll::Pending + } +} + +impl FactFeed { + /// Allow up to `n` commits at once (default 1: strict emission order). + /// Facts of one principal stay sequential; see the module docs. + pub fn with_max_concurrent_commits(mut self, n: usize) -> Self { + self.max_concurrent = n.max(1); + self + } + + /// Commits allowed at once. + pub fn max_concurrent_commits(&self) -> usize { + self.max_concurrent + } + + /// Hand a batching sink ([`FactSink::batches`]) up to `n` facts + /// of a lane at once (default [`DEFAULT_MAX_BATCH`]; 1 commits fact by + /// fact). + pub fn with_max_batch(mut self, n: usize) -> Self { + self.max_batch = n.max(1); + self + } + + /// Facts per batch at most. + pub fn max_batch(&self) -> usize { + self.max_batch + } + + /// Commit facts until the queue is dropped and drained: in emission + /// order, or with bounded concurrency in per-principal lanes + /// ([`with_max_concurrent_commits`](Self::with_max_concurrent_commits)). + /// `sleep` provides the runtime's timer for backoff. + pub async fn run(self, sink: S, sleep: F) + where + S: FactSink, + F: Fn(Duration) -> Fut, + Fut: Future, + { + let policy = self.policy; + let max_batch = if sink.batches().is_some() { + self.max_batch + } else { + 1 + }; + if self.max_concurrent <= 1 { + while let Some(facts) = NextFact(&self.shared, max_batch).await { + for settlement in commit_with_retries(&sink, facts, policy, &sleep).await { + let _ = self.settlements.send(settlement); + } + } + return; + } + let start = |facts: Vec| Box::pin(commit_with_retries(&sink, facts, policy, &sleep)); + Pump { + shared: &self.shared, + settlements: &self.settlements, + limit: self.max_concurrent, + max_batch, + start, + waiting: VecDeque::new(), + active: Vec::new(), + } + .await; + } +} + +/// Commit `facts` in order (through [`FactSink::batches`] if more than +/// one), retrying +/// from the first unsettled fact; `policy` bounds the attempts at each +/// fact as if it were committed alone. +async fn commit_with_retries( + sink: &S, + facts: Vec, + policy: RetryPolicy, + sleep: &F, +) -> Vec +where + S: FactSink, + F: Fn(Duration) -> Fut, + Fut: Future, +{ + let max_attempts = policy.max_attempts.max(1); + let mut settled = Vec::with_capacity(facts.len()); + let mut pending: VecDeque = facts.into(); + // Attempts at the head of `pending`. + let mut attempts = 0; + while !pending.is_empty() { + attempts += 1; + let results = match sink.batches() { + Some(batches) => batches.commit_batch(pending.make_contiguous()).await, + None => commit_each(sink, pending.make_contiguous()).await, + }; + let answered = results.len().min(pending.len()); + // A sink that answered for nothing is retried like a retryable head. + let mut retry = answered == 0; + for result in results.into_iter().take(answered) { + let outcome = match result { + Ok(receipt) => FactOutcome::Committed(receipt), + Err(FactError::Retryable(_)) if attempts < max_attempts => { + retry = true; + break; + } + Err(error) => FactOutcome::Failed { error, attempts }, + }; + let fact = pending.pop_front().expect("a result per attempted fact"); + settled.push(FactSettlement { + key: fact.key, + command: fact.command, + outcome, + }); + // The next result is the next fact's first attempt. + attempts = 1; + } + if !retry { + // The facts left (if any) were not attempted yet. + attempts = 0; + } else if answered == 0 && attempts >= max_attempts { + let fact = pending.pop_front().expect("a pending fact"); + settled.push(FactSettlement { + key: fact.key, + command: fact.command, + outcome: FactOutcome::Failed { + error: FactError::Retryable("the sink committed nothing".into()), + attempts, + }, + }); + attempts = 0; + } else { + sleep(policy.backoff(attempts)).await; + } + } + settled +} + +/// Concurrent commit driver: at most `limit` commits in flight, one per +/// principal lane, admitted in emission order. +struct Pump<'a, T, M> { + shared: &'a Shared, + settlements: &'a mpsc::Sender, + limit: usize, + max_batch: usize, + start: M, + waiting: VecDeque, + active: Vec<(Option, Pin>)>, +} + +impl Future for Pump<'_, T, M> +where + T: Future>, + M: FnMut(Vec) -> Pin> + Unpin, +{ + type Output = (); + + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { + let this = self.get_mut(); + // Register before checking so a concurrent push cannot be missed. + *this.shared.waker.lock().expect("waker lock") = Some(cx.waker().clone()); + loop { + this.waiting + .extend(this.shared.queue.lock().expect("fact queue lock").drain(..)); + // Admit in order; a lane is blocked by an active commit or by an + // earlier waiting fact of the same lane. + let mut blocked: HashSet> = + this.active.iter().map(|(lane, _)| lane.clone()).collect(); + let mut i = 0; + while i < this.waiting.len() && this.active.len() < this.limit { + let lane = this.waiting[i].principal.clone(); + if blocked.contains(&lane) { + i += 1; + continue; + } + // The lane's waiting facts, in order, up to a batch. + let mut batch = vec![this.waiting.remove(i).expect("index in range")]; + let mut k = i; + while k < this.waiting.len() && batch.len() < this.max_batch { + if this.waiting[k].principal == lane { + batch.push(this.waiting.remove(k).expect("index in range")); + } else { + k += 1; + } + } + blocked.insert(lane.clone()); + this.active.push((lane, (this.start)(batch))); + } + let mut progressed = false; + let mut j = 0; + while j < this.active.len() { + match this.active[j].1.as_mut().poll(cx) { + Poll::Ready(settlements) => { + for settlement in settlements { + let _ = this.settlements.send(settlement); + } + this.active.remove(j); + progressed = true; + } + Poll::Pending => j += 1, + } + } + if !progressed { + break; + } + } + let drained = this.active.is_empty() + && this.waiting.is_empty() + && this + .shared + .queue + .lock() + .expect("fact queue lock") + .is_empty(); + if drained && this.shared.closed.load(Ordering::SeqCst) { + return Poll::Ready(()); + } + Poll::Pending + } +} + +/// Run a [`FactFeed`] on the current Tokio runtime. +#[cfg(feature = "runtime")] +pub fn spawn_fact_worker(feed: FactFeed, sink: S) -> tokio::task::JoinHandle<()> { + tokio::spawn(feed.run(sink, tokio::time::sleep)) +} + +/// In-memory sink that records commits and replays repeated keys. +/// Useful for tests and local development. +#[derive(Debug, Default, Clone)] +pub struct MemoryFactSink { + committed: Arc>>, +} + +impl MemoryFactSink { + /// Empty sink. + pub fn new() -> Self { + Self::default() + } + + /// Facts committed so far (one per key). + pub fn committed(&self) -> Vec { + self.committed.lock().expect("sink lock").clone() + } +} + +impl FactSink for MemoryFactSink { + fn commit<'a>(&'a self, fact: &'a Fact) -> BoxFuture<'a, Result> { + Box::pin(async move { + let mut committed = self.committed.lock().expect("sink lock"); + let replayed = committed.iter().any(|f| f.key == fact.key); + if !replayed { + committed.push(fact.clone()); + } + Ok(FactReceipt { + payload: Value::Null, + replayed, + }) + }) + } +} + +impl FactSink for Arc { + fn commit<'a>(&'a self, fact: &'a Fact) -> BoxFuture<'a, Result> { + (**self).commit(fact) + } + + fn batches(&self) -> Option<&dyn FactBatchSink> { + (**self).batches() + } +} + +#[cfg(test)] +mod batch_tests { + use super::*; + + /// Commits whole batches, recording each; `flaky` answers retryable + /// `failures` times when it reaches that key. + #[derive(Default)] + struct BatchSink { + batches: Mutex>>, + committed: Mutex>, + flaky: Option<(String, Mutex)>, + } + + impl FactSink for BatchSink { + fn commit<'a>(&'a self, _: &'a Fact) -> BoxFuture<'a, Result> { + unreachable!("batches only") + } + + fn batches(&self) -> Option<&dyn FactBatchSink> { + Some(self) + } + } + + impl FactBatchSink for BatchSink { + fn commit_batch<'a>( + &'a self, + facts: &'a [Fact], + ) -> BoxFuture<'a, Vec>> { + Box::pin(async move { + let keys = facts.iter().map(|f| f.key().to_string()).collect(); + self.batches.lock().unwrap().push(keys); + let mut results = Vec::new(); + for fact in facts { + if let Some((key, failures)) = &self.flaky { + let mut failures = failures.lock().unwrap(); + if fact.key() == key && *failures > 0 { + *failures -= 1; + results.push(Err(FactError::Retryable("busy".into()))); + break; + } + } + let mut committed = self.committed.lock().unwrap(); + let replayed = committed.iter().any(|k| k == fact.key()); + if !replayed { + committed.push(fact.key().to_string()); + } + results.push(Ok(FactReceipt { + payload: Value::Null, + replayed, + })); + } + results + }) + } + } + + fn fact(key: &str, principal: Option<&str>) -> Fact { + Fact::new(key, "credit", Value::Null) + .bind(principal.map(str::to_string), FactStamp::default()) + } + + async fn settle(queue: &mut FactQueue, n: usize) -> Vec { + let mut settled = Vec::new(); + while settled.len() < n { + settled.extend(queue.drain()); + tokio::time::sleep(Duration::from_millis(1)).await; + } + settled + } + + fn keys(settled: &[FactSettlement]) -> Vec<&str> { + settled.iter().map(|s| s.key.as_str()).collect() + } + + fn policy(max_attempts: u32) -> RetryPolicy { + RetryPolicy { + max_attempts, + base_backoff: Duration::from_millis(1), + max_backoff: Duration::from_millis(2), + } + } + + #[tokio::test] + async fn a_lane_settles_in_batches_in_order() { + let (mut queue, feed) = fact_channel(64, policy(3)); + for i in 0..5 { + queue + .try_send(fact(&format!("a{i}"), Some("alice"))) + .unwrap(); + } + for i in 0..3 { + queue.try_send(fact(&format!("b{i}"), Some("bob"))).unwrap(); + } + let sink = Arc::new(BatchSink::default()); + let feed = feed.with_max_concurrent_commits(4).with_max_batch(4); + let worker = tokio::spawn(feed.run(sink.clone(), tokio::time::sleep)); + let settled = settle(&mut queue, 8).await; + drop(queue); + worker.await.unwrap(); + + let batches = sink.batches.lock().unwrap().clone(); + assert!(batches.contains(&vec!["a0".into(), "a1".into(), "a2".into(), "a3".into()])); + assert!(batches.contains(&vec!["b0".into(), "b1".into(), "b2".into()])); + assert!(batches.contains(&vec!["a4".into()])); + assert_eq!(batches.len(), 3); + let lane = |p: char| -> Vec<&str> { + keys(&settled) + .into_iter() + .filter(|k| k.starts_with(p)) + .collect() + }; + assert_eq!(lane('a'), ["a0", "a1", "a2", "a3", "a4"]); + assert_eq!(lane('b'), ["b0", "b1", "b2"]); + assert!(settled + .iter() + .all(|s| matches!(s.outcome, FactOutcome::Committed(_)))); + } + + /// Holds `f1` until released. + struct Gated(tokio::sync::Notify); + + impl FactSink for Gated { + fn commit<'a>(&'a self, fact: &'a Fact) -> BoxFuture<'a, Result> { + Box::pin(async move { + if fact.key() == "f1" { + self.0.notified().await; + } + Ok(FactReceipt { + payload: Value::Null, + replayed: false, + }) + }) + } + } + + #[tokio::test] + async fn a_sink_without_batches_settles_each_fact_as_it_commits() { + let (mut queue, feed) = fact_channel(64, policy(3)); + for i in 0..2 { + queue.try_send(fact(&format!("f{i}"), None)).unwrap(); + } + let sink = Arc::new(Gated(tokio::sync::Notify::new())); + let worker = tokio::spawn( + feed.with_max_batch(16) + .run(sink.clone(), tokio::time::sleep), + ); + // f0 settles while f1 is still committing. + let first = tokio::time::timeout(Duration::from_secs(5), settle(&mut queue, 1)) + .await + .expect("f0 settles before f1 commits"); + assert_eq!(keys(&first), ["f0"]); + sink.0.notify_one(); + assert_eq!(keys(&settle(&mut queue, 1).await), ["f1"]); + drop(queue); + worker.await.unwrap(); + } + + #[tokio::test] + async fn a_batch_retries_from_its_first_retryable_fact() { + let (mut queue, feed) = fact_channel(64, policy(3)); + for i in 0..5 { + queue.try_send(fact(&format!("f{i}"), None)).unwrap(); + } + let sink = Arc::new(BatchSink { + flaky: Some(("f2".into(), Mutex::new(1))), + ..BatchSink::default() + }); + let worker = tokio::spawn(feed.with_max_batch(8).run(sink.clone(), tokio::time::sleep)); + let settled = settle(&mut queue, 5).await; + drop(queue); + worker.await.unwrap(); + + assert_eq!(keys(&settled), ["f0", "f1", "f2", "f3", "f4"]); + assert!(settled + .iter() + .all(|s| matches!(s.outcome, FactOutcome::Committed(_)))); + // Exactly once each, in order; the retry resent only f2 onward. + assert_eq!( + *sink.committed.lock().unwrap(), + ["f0", "f1", "f2", "f3", "f4"] + ); + assert_eq!( + *sink.batches.lock().unwrap(), + [vec!["f0", "f1", "f2", "f3", "f4"], vec!["f2", "f3", "f4"]] + ); + } + + #[tokio::test] + async fn attempts_count_per_fact_in_a_batch() { + let (mut queue, feed) = fact_channel(64, policy(2)); + for i in 0..3 { + queue.try_send(fact(&format!("f{i}"), None)).unwrap(); + } + let sink = Arc::new(BatchSink { + flaky: Some(("f1".into(), Mutex::new(u32::MAX))), + ..BatchSink::default() + }); + let worker = tokio::spawn(feed.with_max_batch(8).run(sink.clone(), tokio::time::sleep)); + let settled = settle(&mut queue, 3).await; + drop(queue); + worker.await.unwrap(); + + assert_eq!(keys(&settled), ["f0", "f1", "f2"]); + assert!(matches!(settled[0].outcome, FactOutcome::Committed(_))); + assert!(matches!( + settled[1].outcome, + FactOutcome::Failed { + error: FactError::Retryable(_), + attempts: 2 + } + )); + assert!(matches!(settled[2].outcome, FactOutcome::Committed(_))); + assert_eq!(*sink.committed.lock().unwrap(), ["f0", "f2"]); + } +} diff --git a/distributed_game/src/handoff.rs b/distributed_game/src/handoff.rs new file mode 100644 index 000000000..01a88a3f5 --- /dev/null +++ b/distributed_game/src/handoff.rs @@ -0,0 +1,89 @@ +//! Zone handoff types (transport-agnostic). +//! +//! A zone moves a player with [`Ctx::handoff`](crate::Ctx::handoff): the +//! host asks its transfer issuer (installed by the driver, e.g. the `net` +//! server signs an HS256 transfer ticket) for a ticket, removes the player +//! with [`LeaveReason::Handoff`](crate::LeaveReason::Handoff) after the hook +//! returns and sends `Handoff(target, ticket)`. The target admits the ticket +//! with [`ZoneHost::join_transfer`](crate::ZoneHost::join_transfer), which +//! calls [`Zone::on_handoff_join`](crate::Zone::on_handoff_join) with the +//! carried bytes (the encoding of the [`Wire`](crate::Wire) value the +//! source passed). +//! +//! **Custody rule: the client holds the carried state, and it is delivered +//! at most once.** The source removes the player as soon as the hook +//! returns; from then on the carried state exists only in the signed +//! ticket. The issuer's transfer record (reserve / confirm / release) is in +//! the issuing host's memory. So a client that drops the ticket, or +//! discards one on purpose and joins afresh, an expired ticket, or an +//! issuer restart before the target reserves it (`unknown transfer`) loses +//! the carried state, and the player is in neither zone until it joins +//! again. What holds is no duplication: the player is never in both zones +//! and the ticket is single-use. State that must not be lost moves through +//! a durable record (a fact from the hook driving a saga), never through +//! `carried`. + +use crate::claims::TicketExtensions; +use crate::zone::TicketClaims; + +/// Largest carried state accepted in a handoff (it travels inside the +/// signed ticket, which travels inside Hello). +pub const MAX_CARRIED_BYTES: usize = 16 * 1024; + +/// What a zone asks the issuer to sign. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HandoffRequest { + /// Verified principal of the moving player. + pub principal: String, + /// The player's display name (from its admission ticket), carried over. + pub name: Option, + /// The player's ticket extension claims, carried over. + pub extensions: TicketExtensions, + /// Zone the player leaves. + pub source_zone: String, + /// Zone the player goes to. + pub target_zone: String, + /// Game state carried along (a position hint, buffs...): an encoded + /// [`Wire`](crate::Wire) value, in the client's custody (module docs). + pub carried: Vec, + /// Source stamp time of the departure (Unix ms): the facts the source + /// emits while the player leaves carry it, and the target stamps + /// everything after it ([`FactStamp`](crate::FactStamp) ordering). + pub departed_at_ms: u64, +} + +/// Verified transfer ticket contents. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Transfer { + /// Principal, target zone (`claims.zone`), expiry and single-use nonce. + pub claims: TicketClaims, + /// Zone the player left. + pub source_zone: String, + /// Host id that issued the ticket (holds the transfer record). + pub issuer: String, + /// Source zone ownership token at issue time. + pub generation: u64, + /// Carried state. + pub carried: Vec, + /// Source stamp time of the departure (Unix ms, see + /// [`HandoffRequest::departed_at_ms`]). + pub departed_at_ms: u64, +} + +/// Why [`Ctx::handoff`](crate::Ctx::handoff) refused. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum HandoffError { + /// No such player. + UnknownPlayer, + /// The host has no transfer issuer (no transport configured). + NoIssuer, + /// Carried state exceeds [`MAX_CARRIED_BYTES`]. + TooLarge, + /// Target equals the current zone. + SameZone, + /// The issuer refused (e.g. target unknown). + Refused, +} + +/// Transfer ticket issuer: `None` refuses the handoff. +pub type TransferIssuer = dyn FnMut(&HandoffRequest) -> Option + Send; diff --git a/distributed_game/src/host.rs b/distributed_game/src/host.rs new file mode 100644 index 000000000..ce5efd3fa --- /dev/null +++ b/distributed_game/src/host.rs @@ -0,0 +1,602 @@ +//! [`ZoneHost`]: drives one [`Zone`] — lifecycle, fixed timestep, activity +//! tiers, inputs, timers, facts and replication. +//! +//! The host is synchronous and transport-agnostic. Everything from outside +//! that changes the zone is one [`Stimulus`] applied with +//! [`apply`](ZoneHost::apply), which reads the injected [`Clock`] once (the +//! zone sees that time throughout) and, with [`HostConfig::record`], appends +//! it to the host's [`Recording`](crate::replay::Recording). A driver (the +//! `net` server, a celld zone object, a test, a custom loop) calls, as +//! shorthand for `apply`: +//! +//! - [`join`](ZoneHost::join) / [`reconnect`](ZoneHost::reconnect) / +//! [`disconnect`](ZoneHost::disconnect) for membership, +//! - [`push_input`](ZoneHost::push_input) for wire inputs, +//! - [`advance`](ZoneHost::advance) whenever time may have passed (it runs +//! due fixed steps and patches, and reports when it next wants to be +//! called), +//! +//! and [`drain_outbound`](ZoneHost::drain_outbound) to collect encoded +//! frames (outputs are never stimuli). +//! +//! **Cadence.** Ticks run at `tick_rate` with an accumulator and catch-up cap +//! ([`FixedTimestep`]). Patches (Deltas) run at `patch_rate` on the clock, +//! independent of the tick rate. +//! +//! **Tiers.** Hot while any client is connected, any player is inside its +//! reconnect grace window, or [`Zone::has_pending_work`] is true. Otherwise +//! Idle: ticks at `idle_tick_rate` (or not at all when `None`). After +//! `dormant_after` in Idle with no unsettled facts and +//! [`Zone::wants_background`] false the zone becomes Dormant: no ticks, +//! simulation time stops (timers pause) and the zone is eligible for +//! hibernation. Joins, reconnects and inputs wake it to Hot. Transitions are +//! reported in [`AdvanceReport::transitions`] and via +//! [`Zone::on_tier_changed`]. + +use std::collections::{BTreeMap, VecDeque}; +use std::sync::Arc; +use std::time::Duration; + +use crate::authoring::GameEvent; +use crate::clock::Clock; +use crate::codec::Wire; +use crate::collide::{Colliders, Ray, RayHit}; +use crate::facts::{EmitError, Fact, FactCommand, FactQueue, FactSettlement}; +use crate::handoff::{HandoffError, HandoffRequest, Transfer, TransferIssuer, MAX_CARRIED_BYTES}; +use crate::inbox::{Delivered, ZoneInbound}; +use crate::input::{ConsumePolicy, InputBuffer, PushOutcome, SequencedInput}; +use crate::interest::{InterestConfig, View}; +use crate::lifecycle::{ + ConnectionLost, JoinVia, LeftReason, LostCause, PlayerDisconnected, PlayerJoined, PlayerLeft, + PlayerReconnected, +}; +use crate::protocol::{error, feature, kick, Notice, Role, ServerMessage, Welcome}; +use crate::replay::{Entry, Observed, Recording}; +use crate::replication::{ClientReplica, DeltaStats, EncodedWorld, WorldView}; +use crate::rewind::{Rewind, RewindConfig, ShotTiming}; +use crate::rng::ZoneRng; +use crate::schema::EntitySchema; +use crate::stamp::FactStamp; +use crate::timers::{TimerId, Timers}; +use crate::timestep::{rate_to_step, FixedTimestep}; +use crate::world::{ChildEvent, FreezeState, StalePolicy}; +use crate::zone::{ + Admission, ClientId, JoinRequest, LeaveReason, ObserverId, ObserverInfo, PlayerId, PlayerInfo, + TicketClaims, Tier, Viewer, Zone, +}; +use crate::zone_message::{SeenIds, VerifiedPrincipal, ZoneEnvelope, ZoneMessageError, ZoneSender}; + +/// Host tuning. +#[derive(Debug, Clone, PartialEq)] +pub struct HostConfig { + /// Hot ticks per second. + pub tick_rate: u32, + /// Deltas per second (independent of `tick_rate`). + pub patch_rate: u32, + /// Idle ticks per second; `None` = no ticks while Idle. + pub idle_tick_rate: Option, + /// Time in Idle before Dormant. + pub dormant_after: Duration, + /// Max fixed steps per `advance` before backlog is dropped. + pub max_catch_up: u32, + /// Player capacity. + pub max_players: usize, + /// Observer capacity. + pub max_observers: usize, + /// Per-player input buffer bound. + pub input_capacity: usize, + /// How long a dropped player is kept for reconnect. + pub reconnect_grace: Duration, + /// Per-client create+update bytes per Delta. + pub byte_budget: usize, + /// Radius of views the zone has not set explicitly (centered at origin). + pub default_view_radius: f32, + /// Interest grid settings. + pub interest: InterestConfig, + /// Content version; when non-empty, clients must match it exactly. + pub content_version: String, + /// World seed; the zone RNG derives from it and the zone id. + pub world_seed: u64, + /// Lag-compensation history ([`Ctx::rewind`]). + pub rewind: RewindConfig, + /// Admission of clients whose content version differs from + /// `content_version` (see [`StalePolicy`]). + pub stale_policy: StalePolicy, + /// Epoch of this activation of the zone ([`Ctx::boot_epoch`]): must + /// differ between activations and grow across restarts so fact keys + /// built from it never collide with an earlier run's. `0` (default) = + /// Unix time in microseconds when the host is created. The `net` server + /// sets it to the activation's fencing token. + pub boot_epoch: u64, + /// Remote config version the zone runs (opaque; e.g. `"combat@12"`): + /// stamped on every fact ([`FactStamp::config_version`]). Change it at + /// runtime with [`ZoneHost::set_config_version`] / + /// [`Ctx::set_config_version`]. + pub config_version: String, + /// Emit the player lifecycle facts ([`crate::lifecycle`]: joined, + /// connection lost, reconnected, disconnected, left) on the zone's fact + /// queue, bound to each player's verified principal. Off by default. + pub lifecycle_facts: bool, + /// Keep a [`Recording`](crate::replay::Recording) of every + /// [`Stimulus`] from creation on ([`ZoneHost::recording`]), for + /// [`replay`](crate::replay::replay). Costs a state hash per tick and + /// memory for every stimulus. Off by default. + pub record: bool, +} + +impl Default for HostConfig { + fn default() -> Self { + Self { + tick_rate: 30, + patch_rate: 20, + idle_tick_rate: Some(1), + dormant_after: Duration::from_secs(30), + max_catch_up: 5, + max_players: 64, + max_observers: 16, + input_capacity: 32, + reconnect_grace: Duration::from_secs(15), + byte_budget: 4096, + default_view_radius: 64.0, + interest: InterestConfig::default(), + content_version: String::new(), + world_seed: 0, + rewind: RewindConfig::default(), + stale_policy: StalePolicy::Strict, + boot_epoch: 0, + config_version: String::new(), + lifecycle_facts: false, + record: false, + } + } +} + +/// Something for the transport to do. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Outbound { + /// Send this binary frame. + Frame { + /// Destination. + client: ClientId, + /// Encoded server message. + frame: Vec, + }, + /// Close the connection after previously queued frames. + Close { + /// Connection to close. + client: ClientId, + }, +} + +/// Result of [`ZoneHost::advance`]. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct AdvanceReport { + /// Fixed steps simulated. + pub ticks: u32, + /// Backlog dropped by the catch-up cap. + pub dropped: Duration, + /// Whether Deltas were produced. + pub patched: bool, + /// Tier transitions since the previous report. + pub transitions: Vec<(Tier, Tier)>, + /// Clock time at which the host next wants `advance` (None = only on + /// external events, i.e. Dormant). + pub next_wake: Option, + /// Fixed steps dropped by the catch-up cap (`dropped` / step). + pub dropped_ticks: u32, + /// Wall time spent in each simulated tick (metrics only; never fed back + /// into the simulation). + pub tick_durations: Vec, + /// Replicated entity count when a patch ran. + pub entities: Option, + /// One entry per Delta frame built. + pub frames: Vec, + /// Entity records encoded by the patches + /// ([`EncodedWorld::encodes`]: shared across clients). + pub encodes: usize, + /// Settlements delivered to the zone, with the tick they were delivered on. + pub settled: Vec<(u64, FactSettlement)>, + /// `(tick, state hash)` after each tick, when + /// [`ZoneHost::set_tick_hashing`] is on. + pub tick_hashes: Vec<(u64, u64)>, +} + +/// One Delta frame built by a patch. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct FrameStats { + /// Destination. + pub client: ClientId, + /// Encoded frame size. + pub bytes: usize, + /// Replication counters. + pub stats: DeltaStats, +} + +/// Admission failure (code from [`protocol::error`](crate::protocol::error)). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct JoinError { + /// Error code. + pub code: u32, + /// Message. + pub message: String, +} + +impl JoinError { + fn new(code: u32, message: impl Into) -> Self { + Self { + code, + message: message.into(), + } + } +} + +/// Successful admission. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Joined { + /// New connection id. + pub client: ClientId, + /// Player or observer it is bound to. + pub viewer: Viewer, +} + +/// Runs one zone. See the module docs. +pub struct ZoneHost { + zone: Z, + core: Core, + schema: EntitySchema, + entities: crate::Entities, + hot: FixedTimestep, + idle: Option, + last_advance: Duration, + idle_since: Duration, + next_patch: Duration, + transitions: Vec<(Tier, Tier)>, + frozen: bool, + freeze_request: Option, + disposed: bool, + token_source: Box String + Send>, + tape: Option, + pending: AdvanceReport, + hash_ticks: bool, + /// The last patch's world: the next one shares its unchanged entities + /// and encodes each change once for every client. + last_world: Option, + /// The view each patch is projected into (emptied, not reallocated). + view: WorldView, +} + +macro_rules! hook { + ($host:ident . $method:ident ( $($arg:expr),* )) => { + $host.zone.$method(&mut Ctx { core: &mut $host.core } $(, $arg)*) + }; +} + +mod content; +mod ctx; +mod membership; +mod outbound; +mod stimulus; +mod tick; + +pub(crate) use ctx::Core; +pub use ctx::Ctx; +use ctx::{ClientSlot, ObserverSlot, PlayerSlot}; +use stimulus::Tape; +pub use stimulus::{Outcome, Stimulus}; + +impl ZoneHost { + /// Create the zone (`on_create`). Starts Hot. + pub fn new( + zone_id: impl Into, + config: HostConfig, + clock: Arc, + zone_config: Z::Config, + ) -> Self { + let zone_id = zone_id.into(); + let now = clock.now(); + let mut config = config; + if config.boot_epoch == 0 { + config.boot_epoch = unix_micros(); + } + let mut core = Core { + rng: ZoneRng::for_zone(config.world_seed, &zone_id), + zone_id, + now, + unix_ms: clock.unix_ms(), + clock, + timers: Timers::default(), + tick: 0, + sim_time: Duration::ZERO, + dt: rate_to_step(config.tick_rate), + dropped_ticks: 0, + tier: Tier::Hot, + players: BTreeMap::new(), + observers: BTreeMap::new(), + departing: None, + clients: BTreeMap::new(), + next_id: 0, + outbound: Vec::new(), + facts: None, + pending_kicks: Vec::new(), + rewind: Rewind::new(config.rewind, config.tick_rate), + colliders: Colliders::new(), + transfer_issuer: None, + pending_handoffs: Vec::new(), + upward: Vec::new(), + child_inbox: Vec::new(), + dropped_frozen: 0, + fact_seq: (0, 0), + stamped: 0, + stamp_floor_ms: 0, + pinned_stamp_ms: None, + backlog: VecDeque::new(), + zone_out: Vec::new(), + zone_seq: 0, + zone_seen: SeenIds::default(), + config, + }; + let zone = Z::on_create(&mut Ctx { core: &mut core }, zone_config); + let hot = FixedTimestep::from_rate(core.config.tick_rate, core.config.max_catch_up); + let idle = core + .config + .idle_tick_rate + .map(|hz| FixedTimestep::from_rate(hz, core.config.max_catch_up)); + let mut host = Self { + zone, + core, + schema: Z::schema(), + entities: Z::entities(), + hot, + idle, + last_advance: now, + idle_since: now, + next_patch: now, + transitions: Vec::new(), + frozen: false, + freeze_request: None, + disposed: false, + token_source: Box::new(default_token), + tape: None, + pending: AdvanceReport::default(), + hash_ticks: false, + last_world: None, + view: WorldView::default(), + }; + if host.core.config.record { + host.hash_ticks = true; + host.tape = Some(Tape { + recording: Recording { + zone_id: host.core.zone_id.clone(), + // As resolved (the boot epoch), and replayed unrecorded. + config: HostConfig { + record: false, + ..host.core.config.clone() + }, + created_at: now, + created_unix_ms: host.core.unix_ms, + fact_capacity: None, + entries: Vec::new(), + }, + tokens: Vec::new(), + }); + } + host.process_kicks(); + host + } + + /// Attach the zone side of a fact channel. + pub fn with_facts(mut self, facts: FactQueue) -> Self { + if let Some(tape) = &mut self.tape { + tape.recording.fact_capacity = Some(facts.capacity()); + } + self.core.facts = Some(facts); + self + } + + /// Replace the reconnect/session token generator (must be unpredictable). + pub fn with_token_source(mut self, source: impl FnMut() -> String + Send + 'static) -> Self { + self.token_source = Box::new(source); + self + } + + /// Install the transfer-ticket issuer used by [`Ctx::handoff`]. + pub fn with_transfer_issuer( + mut self, + issuer: impl FnMut(&HandoffRequest) -> Option + Send + 'static, + ) -> Self { + self.core.transfer_issuer = Some(Box::new(issuer)); + self + } + + /// [`Stimulus::Restore`]. + fn restore_snapshot(&mut self, state: &[u8], saved_version: &str) { + hook!(self.on_restore(state, saved_version)); + self.process_kicks(); + } + + /// Durable snapshot for hibernation ([`Zone::hibernate`]). + pub fn hibernate_state(&self) -> Option> { + self.zone.hibernate() + } + + /// Zone id. + pub fn zone_id(&self) -> &str { + &self.core.zone_id + } + + /// The game state. + pub fn zone(&self) -> &Z { + &self.zone + } + + /// Mutable game state (operator tooling): not a [`Stimulus`], so a + /// recording does not see it and its replay diverges. + pub fn zone_mut(&mut self) -> &mut Z { + &mut self.zone + } + + /// Host configuration. + pub fn config(&self) -> &HostConfig { + &self.core.config + } + + /// Replicated schema. + pub fn schema(&self) -> &EntitySchema { + &self.schema + } + + /// Current tier. + pub fn tier(&self) -> Tier { + self.core.tier + } + + /// Ticks simulated. + pub fn tick(&self) -> u64 { + self.core.tick + } + + /// Players (including those in the grace window). + pub fn player_count(&self) -> usize { + self.core.players.len() + } + + /// Players (including those in the grace window). + pub fn players(&self) -> impl Iterator + '_ { + self.core.players.values().map(|slot| &slot.info) + } + + /// Observers. + pub fn observers(&self) -> impl Iterator + '_ { + self.core.observers.values().map(|slot| &slot.info) + } + + /// Live connections. + pub fn client_count(&self) -> usize { + self.core.clients.len() + } + + /// Observers. + pub fn observer_count(&self) -> usize { + self.core.observers.len() + } + + /// Lag-compensation history. + pub fn rewind(&self) -> &Rewind { + &self.core.rewind + } + + /// Report a state hash after every tick in + /// [`AdvanceReport::tick_hashes`] (record/replay; costs a hash per tick). + pub fn set_tick_hashing(&mut self, on: bool) { + self.hash_ticks = on; + } + + /// Deterministic digest of tick, simulation time, RNG state and + /// [`Zone::state_hash`] (or, when the zone has none, its replicated + /// [`WorldView`]). + pub fn state_hash(&self) -> u64 { + let zone = self + .zone + .state_hash() + .unwrap_or_else(|| crate::replay::hash_world(&self.world_view())); + let mut h = crate::rng::Fnv64::new(); + h.write_u64(self.core.tick) + .write_u64(self.core.sim_time.as_nanos() as u64) + .write_u64(self.core.rng.clone().next_u64()) + .write_u64(zone); + h.finish() + } + + /// Viewer bound to a connection. + pub fn viewer_of(&self, client: ClientId) -> Option { + self.core.clients.get(&client).map(|slot| slot.viewer) + } + + /// Unsettled facts. + pub fn facts_in_flight(&self) -> usize { + self.core.in_flight() + } + + /// Detach the fact queue without committing what it holds (the zone + /// lost its ownership: nothing more may reach the store). Queued facts + /// are dropped, the worker stops after any commit already in flight, + /// and later emits answer [`EmitError::NoSink`]. Returns the facts + /// left unsettled. + pub fn abandon_facts(&mut self) -> usize { + let unsettled = self.core.in_flight(); + self.core.backlog.clear(); + if let Some(queue) = self.core.facts.take() { + queue.abandon(); + } + unsettled + } + + /// Facts emitted since the last call, when the fact queue keeps a + /// journal ([`FactQueue::with_journal`]); empty otherwise. + pub fn take_emitted_facts(&mut self) -> Vec { + self.core + .facts + .as_mut() + .map(FactQueue::take_journal) + .unwrap_or_default() + } + + /// True after [`dispose`](Self::dispose). + pub fn is_disposed(&self) -> bool { + self.disposed + } + + /// True while frozen. + pub fn is_frozen(&self) -> bool { + self.frozen + } + + /// Server clock in ms (for Pong): read now, not frozen. + pub fn server_time_ms(&self) -> f64 { + self.core.clock.now().as_secs_f64() * 1000.0 + } + + /// Send every client the current state now, without ticking (a host + /// that is not ticking — a celld zone with only passive observers — + /// greets a new observer with it). + pub fn patch_now(&mut self) { + if !self.core.clients.is_empty() { + self.patch(); + } + } + + /// Frames and closes produced since the last call, in order. + pub fn drain_outbound(&mut self) -> Vec { + std::mem::take(&mut self.core.outbound) + } + + /// Inputs dropped because the zone was frozen. + pub fn inputs_dropped_frozen(&self) -> u64 { + self.core.dropped_frozen + } +} + +fn unix_micros() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(1, |d| d.as_micros() as u64) + .max(1) +} + +pub(crate) fn default_token() -> String { + use std::collections::hash_map::RandomState; + use std::hash::{BuildHasher, Hasher}; + use std::sync::atomic::{AtomicU64, Ordering}; + static COUNTER: AtomicU64 = AtomicU64::new(0); + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()); + let mut out = String::with_capacity(32); + for _ in 0..2 { + let mut hasher = RandomState::new().build_hasher(); + hasher.write_u64(COUNTER.fetch_add(1, Ordering::Relaxed)); + hasher.write_u128(nanos); + out.push_str(&format!("{:016x}", hasher.finish())); + } + out +} diff --git a/distributed_game/src/host/content.rs b/distributed_game/src/host/content.rs new file mode 100644 index 000000000..4e44ffb9a --- /dev/null +++ b/distributed_game/src/host/content.rs @@ -0,0 +1,135 @@ +//! Content versions, reloads and the freeze around a content rollout. + +use super::*; + +impl ZoneHost { + /// [`Stimulus::Reload`]. + pub(super) fn reload(&mut self, player: PlayerId) { + let now = self.core.now; + let grace = self.core.config.reconnect_grace; + let message = ServerMessage::Kick { + code: kick::RELOAD, + message: format!("content {} required", self.core.config.content_version), + }; + let Some(slot) = self.core.players.get_mut(&player) else { + return; + }; + let client = slot.client.take(); + slot.info.connected = false; + slot.inputs.clear(); + slot.grace_until = Some(now + grace); + if let Some(client) = client { + self.core.clients.remove(&client); + self.core.server_message(client, &message); + self.core.outbound.push(Outbound::Close { client }); + self.connection_lost(player, LostCause::Reload); + } + } + + /// [`Stimulus::ReloadStale`]. + pub(super) fn reload_stale(&mut self) -> usize { + let expected = self.core.config.content_version.clone(); + if expected.is_empty() { + return 0; + } + let stale: Vec<_> = self + .core + .players + .values() + .filter(|slot| slot.client.is_some() && slot.content_version != expected) + .map(|slot| slot.info.id) + .collect(); + for player in &stale { + self.reload(*player); + } + stale.len() + } + + /// [`Stimulus::Content`]. + pub(super) fn patch_content(&mut self, client: ClientId, version: &str) -> bool { + if version != self.core.config.content_version { + return false; + } + let Some(Viewer::Player(player)) = self.viewer_of(client) else { + return false; + }; + match self.core.players.get_mut(&player) { + Some(slot) => { + slot.content_version = version.to_string(); + true + } + None => false, + } + } + + /// Content version a player's client reported. + pub fn player_content_version(&self, player: PlayerId) -> Option<&str> { + self.core + .players + .get(&player) + .map(|slot| slot.content_version.as_str()) + } + + /// [`Stimulus::ContentVersion`]. + pub(super) fn switch_content(&mut self, version: String) { + if version == self.core.config.content_version { + return; + } + let previous = std::mem::replace(&mut self.core.config.content_version, version.clone()); + hook!(self.on_content_version_changed(&previous, &version)); + self.process_kicks(); + } + + /// Freeze: ticks stop and inputs are rejected; clients get Freeze. + pub(super) fn freeze(&mut self, notice: Notice) { + self.freeze_request = None; + self.frozen = true; + self.broadcast(&ServerMessage::Freeze(notice)); + } + + /// [`Stimulus::RequestFreeze`]. + pub(super) fn ask_freeze(&mut self, notice: Notice) -> FreezeState { + if !self.frozen { + self.freeze_request = Some(notice); + self.try_freeze(); + } + self.freeze_state() + } + + /// [`Stimulus::CancelFreeze`]. + pub(super) fn abort_freeze(&mut self, notice: Notice) { + self.freeze_request = None; + if self.frozen { + self.thaw(notice); + } + } + + /// Freeze progress. + pub fn freeze_state(&self) -> FreezeState { + if self.frozen { + FreezeState::Frozen + } else if self.freeze_request.is_some() { + FreezeState::Freezing + } else { + FreezeState::Running + } + } + + pub(super) fn try_freeze(&mut self) { + if self.freeze_request.is_some() && !self.disposed && self.zone.freeze_ready() { + let notice = self.freeze_request.take().expect("checked"); + self.freeze(notice); + } + } + + /// [`Stimulus::Resume`]: the frozen backlog is not simulated. + pub(super) fn thaw(&mut self, notice: Notice) { + self.freeze_request = None; + self.frozen = false; + self.hot.reset(); + if let Some(idle) = &mut self.idle { + idle.reset(); + } + self.broadcast(&ServerMessage::Resume(notice)); + } +} diff --git a/distributed_game/src/host/ctx.rs b/distributed_game/src/host/ctx.rs new file mode 100644 index 000000000..af90ae8ec --- /dev/null +++ b/distributed_game/src/host/ctx.rs @@ -0,0 +1,835 @@ +//! The host state hooks reach ([`Core`]) and the zone's API to it ([`Ctx`]). + +use super::*; + +pub(super) struct PlayerSlot { + pub(super) info: PlayerInfo, + pub(super) inputs: InputBuffer, + pub(super) client: Option, + pub(super) view: View, + pub(super) grace_until: Option, + pub(super) reconnect_token: String, + pub(super) session_id: String, + pub(super) content_version: String, + /// Lifecycle facts emitted for this slot (part of their keys). + pub(super) transitions: u32, +} + +pub(super) struct ObserverSlot { + pub(super) info: ObserverInfo, + pub(super) client: ClientId, + pub(super) view: View, +} + +pub(super) struct ClientSlot { + pub(super) viewer: Viewer, + pub(super) replica: ClientReplica, +} + +/// Host state reachable from hooks through [`Ctx`]. +pub(crate) struct Core { + pub(super) zone_id: String, + pub(super) config: HostConfig, + pub(super) clock: Arc, + /// The clock read when the current stimulus arrived + /// ([`ZoneHost::apply`]): every time the host and the zone see while it + /// runs, so a recording that keeps it replays exactly. + pub(super) now: Duration, + /// Wall time (Unix ms) read with [`now`](Self::now). + pub(super) unix_ms: u64, + pub(super) rng: ZoneRng, + pub(super) timers: Timers, + pub(super) tick: u64, + pub(super) sim_time: Duration, + pub(super) dt: Duration, + /// Ticks dropped (catch-up cap) since the last simulated tick; seen by + /// the next `on_tick` through `Ctx::dropped_ticks`, then reset. + pub(super) dropped_ticks: u32, + pub(super) tier: Tier, + pub(super) players: BTreeMap>, + pub(super) observers: BTreeMap, + /// Observer being removed while `on_unobserve` runs. + pub(super) departing: Option, + pub(super) clients: BTreeMap, + pub(super) next_id: u32, + pub(super) outbound: Vec, + pub(super) facts: Option, + pub(super) pending_kicks: Vec<(PlayerId, String)>, + pub(super) rewind: Rewind, + pub(super) colliders: Colliders, + pub(super) transfer_issuer: Option>, + /// Handoffs to finish after the hook: player, `Handoff` message and the + /// departure stamp time signed into the transfer ticket. + pub(super) pending_handoffs: Vec<(PlayerId, ServerMessage, u64)>, + pub(super) upward: Vec, + pub(super) child_inbox: Vec, + pub(super) dropped_frozen: u64, + /// Typed facts keyed without dedupe parts this tick: `(tick, count)`. + pub(super) fact_seq: (u64, u32), + /// Facts stamped this activation ([`FactStamp::seq`] of the latest). + pub(super) stamped: u64, + /// Stamps are never earlier than this (Unix ms): raised past a handoff + /// source's departure time when a transfer is admitted. + pub(super) stamp_floor_ms: u64, + /// Stamp time forced while a handoff departure runs `on_leave`, so the + /// source's departure facts carry exactly the time in the ticket. + pub(super) pinned_stamp_ms: Option, + /// Bound facts waiting for queue capacity, in emission order: the + /// lifecycle facts and [`Ctx::emit_queued`]'s. + pub(super) backlog: VecDeque, + /// Zone messages sent since the driver last took them. + pub(super) zone_out: Vec, + /// Zone messages sent this activation (their ids). + pub(super) zone_seq: u64, + /// Zone message ids delivered lately (repeats are dropped). + pub(super) zone_seen: SeenIds, +} + +impl Core { + pub(super) fn next_id(&mut self) -> u32 { + self.next_id += 1; + self.next_id + } + + pub(super) fn client_of(&self, viewer: Viewer) -> Option { + match viewer { + Viewer::Player(p) => self.players.get(&p).and_then(|s| s.client), + Viewer::Observer(o) => self.observers.get(&o).map(|s| s.client), + } + } + + pub(super) fn send(&mut self, client: ClientId, frame: Vec) { + self.outbound.push(Outbound::Frame { client, frame }); + } + + pub(super) fn server_message(&mut self, client: ClientId, message: &ServerMessage) { + let frame = message.encode(&()).expect("non-delta messages encode"); + self.send(client, frame); + } + + pub(super) fn server_time_ms(&self) -> f64 { + self.now.as_secs_f64() * 1000.0 + } + + pub(super) fn in_flight(&self) -> usize { + self.facts.as_ref().map_or(0, FactQueue::in_flight) + self.backlog.len() + } + + /// Queue a lifecycle fact for `principal`'s slot `player` (transition + /// `n`), keyed restart-safely and stamped now. + pub(super) fn lifecycle( + &mut self, + player: PlayerId, + principal: &str, + n: u32, + input: C, + ) { + if !self.config.lifecycle_facts || self.facts.is_none() { + return; + } + let key = crate::facts::fact_key( + C::COMMAND, + &self.zone_id, + self.config.boot_epoch, + &[&format_args!("p{}", player.0), &n], + ); + let Ok(fact) = Fact::typed(key, &input) else { + return; + }; + let fact = fact.bind(Some(principal.to_string()), self.stamp_fact()); + self.queue(fact); + } + + /// Queue a bound fact behind the backlog and send what fits. + pub(super) fn queue(&mut self, fact: Fact) { + self.backlog.push_back(fact); + self.flush_backlog(); + } + + /// Send backlogged facts while the queue has room. + pub(super) fn flush_backlog(&mut self) { + let Some(queue) = self.facts.as_mut() else { + self.backlog.clear(); + return; + }; + while let Some(fact) = self.backlog.front() { + match queue.try_send(fact.clone()) { + Err(EmitError::Backpressure) => return, + // Sent, or a duplicate already in flight: done either way. + _ => { + self.backlog.pop_front(); + } + } + } + } + + /// Next transition number of a slot. + pub(super) fn transition(&mut self, player: PlayerId) -> Option<(String, u32)> { + let slot = self.players.get_mut(&player)?; + slot.transitions += 1; + Some((slot.info.principal.clone(), slot.transitions)) + } + + pub(super) fn emit_lifecycle(&mut self, player: PlayerId, input: C) { + if !self.config.lifecycle_facts { + return; + } + if let Some((principal, n)) = self.transition(player) { + self.lifecycle(player, &principal, n, input); + } + } + + /// Wall time stamped on anything produced now (Unix ms). + pub(super) fn stamp_ms(&self) -> u64 { + self.pinned_stamp_ms + .unwrap_or_else(|| self.unix_ms.max(self.stamp_floor_ms)) + } + + pub(super) fn stamp(&self) -> FactStamp { + FactStamp { + zone_id: self.zone_id.clone(), + tick: self.tick, + content_version: self.config.content_version.clone(), + emitted_at_ms: self.stamp_ms(), + activation: self.config.boot_epoch, + config_version: self.config.config_version.clone(), + seq: self.stamped, + } + } + + /// Stamp for a fact: the next emission sequence number. + pub(super) fn stamp_fact(&mut self) -> FactStamp { + self.stamped += 1; + self.stamp() + } +} + +/// Hook context: everything a zone may touch besides its own state. +pub struct Ctx<'a, Z: Zone> { + pub(super) core: &'a mut Core, +} + +impl Ctx<'_, Z> { + /// Zone id. + pub fn zone_id(&self) -> &str { + &self.core.zone_id + } + + /// Ticks simulated so far (the current tick inside `on_tick`). + pub fn tick(&self) -> u64 { + self.core.tick + } + + /// Step length of the current tick (Hot or Idle rate). + pub fn dt(&self) -> Duration { + self.core.dt + } + + /// Ticks the host dropped right before this one: the clock ran further + /// ahead than `max_catch_up` steps, so the rest of the backlog was not + /// simulated (0 normally). Simulated ticks then lag wall-clock time; a + /// zone that paces players' inputs per tick credits these so inputs + /// sent in real time do not queue up for good. + pub fn dropped_ticks(&self) -> u32 { + self.core.dropped_ticks + } + + /// Step length in seconds. + pub fn dt_secs(&self) -> f32 { + self.core.dt.as_secs_f32() + } + + /// Simulation time (sum of all step lengths). + pub fn sim_time(&self) -> Duration { + self.core.sim_time + } + + /// Host clock when the current stimulus arrived (the same throughout + /// one [`ZoneHost::apply`]; recorded, so it replays). + pub fn now(&self) -> Duration { + self.core.now + } + + /// Current activity tier. + pub fn tier(&self) -> Tier { + self.core.tier + } + + /// Content version. + pub fn content_version(&self) -> &str { + &self.core.config.content_version + } + + /// Content version `player`'s client runs (what it presented on its + /// last Hello; differs from [`content_version`](Self::content_version) + /// for a stale client kept under [`StalePolicy::SafeRoom`]). + pub fn player_content_version(&self, player: PlayerId) -> Option<&str> { + self.core + .players + .get(&player) + .map(|slot| slot.content_version.as_str()) + } + + /// True when `player`'s client runs older content than the zone (it + /// may only be handed off into a gate zone, unless the policy roams). + pub fn is_stale(&self, player: PlayerId) -> bool { + let expected = &self.core.config.content_version; + !expected.is_empty() + && self + .player_content_version(player) + .is_some_and(|version| version != expected) + } + + /// The host's [`StalePolicy`]. + pub fn stale_policy(&self) -> StalePolicy { + self.core.config.stale_policy + } + + /// Remote config version ([`HostConfig::config_version`]). + pub fn config_version(&self) -> &str { + &self.core.config.config_version + } + + /// Switch the remote config version (e.g. on a config-changed + /// message); facts and stamps produced afterwards carry it. + pub fn set_config_version(&mut self, version: impl Into) { + self.core.config.config_version = version.into(); + } + + /// Epoch of this zone activation ([`HostConfig::boot_epoch`]): unique + /// per activation and increasing across restarts and hibernation. + /// Tick counts and entity generations restart with the process, so a + /// fact key built only from them **collides after a restart** (and the + /// sink replays the old commit instead of recording the new outcome); + /// include this epoch, e.g. via [`fact_key`](Self::fact_key). + pub fn boot_epoch(&self) -> u64 { + self.core.config.boot_epoch + } + + /// Restart-safe fact idempotency key: + /// `"{prefix}:{zone}:{boot_epoch}:{part}:{part}…"` (see + /// [`fact_key`](crate::facts::fact_key)). + pub fn fact_key(&self, prefix: &str, parts: &[&dyn std::fmt::Display]) -> String { + crate::facts::fact_key( + prefix, + &self.core.zone_id, + self.core.config.boot_epoch, + parts, + ) + } + + /// The zone's deterministic RNG. + pub fn rng(&mut self) -> &mut ZoneRng { + &mut self.core.rng + } + + /// One-shot timer after `after` of simulation time. + pub fn set_timeout(&mut self, after: Duration, timer: Z::Timer) -> TimerId { + let now = self.core.sim_time; + self.core.timers.once(now, after, timer) + } + + /// Repeating timer every `every` of simulation time. + pub fn set_interval(&mut self, every: Duration, timer: Z::Timer) -> TimerId { + let now = self.core.sim_time; + self.core.timers.interval(now, every, timer) + } + + /// Cancel a timer. + pub fn cancel_timer(&mut self, id: TimerId) -> bool { + self.core.timers.cancel(id) + } + + /// Players (connected or within the reconnect grace window). + pub fn players(&self) -> impl Iterator + '_ { + self.core.players.values().map(|slot| &slot.info) + } + + /// One player. + pub fn player(&self, id: PlayerId) -> Option<&PlayerInfo> { + self.core.players.get(&id).map(|slot| &slot.info) + } + + /// Observers currently subscribed. + pub fn observers(&self) -> impl Iterator + '_ { + self.core.observers.values().map(|slot| &slot.info) + } + + /// One observer (verified principal, display name). Also answers for + /// the observer leaving during [`Zone::on_unobserve`]. + pub fn observer(&self, id: ObserverId) -> Option<&ObserverInfo> { + self.core.observers.get(&id).map(|slot| &slot.info).or(self + .core + .departing + .as_ref() + .filter(|info| info.id == id)) + } + + /// Observers whose verified principal is `principal` (a principal may + /// observe through several connections). + pub fn observers_of<'p>(&'p self, principal: &'p str) -> impl Iterator + 'p { + self.observers() + .filter(move |info| info.principal == principal) + .map(|info| info.id) + } + + /// Consume buffered inputs of `player`; advances its ack. + pub fn take_inputs( + &mut self, + player: PlayerId, + policy: ConsumePolicy, + ) -> Vec> { + self.core + .players + .get_mut(&player) + .map(|slot| slot.inputs.take(policy)) + .unwrap_or_default() + } + + /// Typed fact for a cell command input, keyed restart-safely: + /// `"{C::COMMAND}:{zone}:{boot_epoch}:{parts…}"` with the input's + /// [`dedupe_parts`](FactCommand::dedupe_parts), or `t{tick}:{n}` (the + /// n-th such fact this tick) when it has none. Emit it with + /// [`emit_fact_for`](Self::emit_fact_for) (e.g. to keep it in a retry + /// backlog) or use [`emit`](Self::emit) directly. + pub fn fact(&mut self, input: &C) -> Result { + let parts = input.dedupe_parts(); + let key = if parts.is_empty() { + let tick = self.core.tick; + if self.core.fact_seq.0 != tick { + self.core.fact_seq = (tick, 0); + } + let n = self.core.fact_seq.1; + self.core.fact_seq.1 += 1; + self.fact_key(C::COMMAND, &[&format_args!("t{tick}"), &n]) + } else { + let parts: Vec<&dyn std::fmt::Display> = + parts.iter().map(|p| p as &dyn std::fmt::Display).collect(); + self.fact_key(C::COMMAND, &parts) + }; + Fact::typed(key, input).map_err(|e| EmitError::Encode(e.to_string())) + } + + /// [`fact`](Self::fact) with explicit dedupe parts (overriding the + /// input's own). + pub fn fact_with_key( + &self, + input: &C, + parts: &[&dyn std::fmt::Display], + ) -> Result { + Fact::typed(self.fact_key(C::COMMAND, parts), input) + .map_err(|e| EmitError::Encode(e.to_string())) + } + + /// Emit a typed cell command input on behalf of `player`: the principal + /// is bound from the player's verified ticket (the input carries no + /// identity), the key is derived as in [`fact`](Self::fact). Returns + /// the key. Never blocks. + pub fn emit( + &mut self, + player: PlayerId, + input: C, + ) -> Result { + let fact = self.fact(&input)?; + let key = fact.key().to_string(); + self.emit_fact_for(player, fact).map(|()| key) + } + + /// [`emit`](Self::emit) with explicit dedupe parts. + pub fn emit_keyed( + &mut self, + player: PlayerId, + input: C, + parts: &[&dyn std::fmt::Display], + ) -> Result { + let fact = self.fact_with_key(&input, parts)?; + let key = fact.key().to_string(); + self.emit_fact_for(player, fact).map(|()| key) + } + + /// Emit a typed zone/system fact (no principal; the sink's system + /// principal applies). Returns the key. + pub fn emit_zone(&mut self, input: C) -> Result { + let fact = self.fact(&input)?; + let key = fact.key().to_string(); + self.emit_fact(fact).map(|()| key) + } + + /// Emit a zone/system fact (no principal). Never blocks. + pub fn emit_fact(&mut self, fact: Fact) -> Result<(), EmitError> { + self.emit_bound(fact, None) + } + + /// Emit a fact on behalf of a principal verified elsewhere: one carried + /// by a zone message ([`ZoneSender::principal`]), e.g. the shooter of a + /// shot that crossed into this zone. Never blocks. + pub fn emit_fact_as( + &mut self, + principal: &VerifiedPrincipal, + fact: Fact, + ) -> Result<(), EmitError> { + self.emit_bound(fact, Some(principal.as_str().to_string())) + } + + /// `player`'s principal, bound from its verified ticket (for carrying + /// in game state; facts bind it themselves). + pub fn verified_principal(&self, player: PlayerId) -> Option { + self.core + .players + .get(&player) + .map(|slot| VerifiedPrincipal::new(slot.info.principal.clone())) + } + + /// Send `message` to the running zone `to` ([`crate::zone_message`]): + /// it arrives in [`Zone::on_zone_message`] there, at most once, or not + /// at all (a zone that is not running refuses it). + pub fn send_zone(&mut self, to: &str, message: &Z::Message) { + self.queue_zone(to, None, message); + } + + /// [`send_zone`](Self::send_zone) on behalf of `player`: its verified + /// principal travels with the message (the receiver may emit facts as + /// it). Nothing is sent for an unknown player. + pub fn send_zone_for(&mut self, player: PlayerId, to: &str, message: &Z::Message) { + if let Some(principal) = self.verified_principal(player) { + self.queue_zone(to, Some(principal), message); + } + } + + /// Send `message` on behalf of a principal this zone was itself sent + /// ([`ZoneSender::principal`]): e.g. passing a shot on again. + pub fn send_zone_as(&mut self, principal: &VerifiedPrincipal, to: &str, message: &Z::Message) { + self.queue_zone(to, Some(principal.clone()), message); + } + + pub(super) fn queue_zone( + &mut self, + to: &str, + principal: Option, + message: &Z::Message, + ) { + self.core.zone_seq += 1; + let id = format!( + "{}/{}/{}", + self.core.zone_id, self.core.config.boot_epoch, self.core.zone_seq + ); + self.core.zone_out.push(ZoneEnvelope { + id, + from: self.core.zone_id.clone(), + to: to.to_string(), + principal: principal.map(|p| p.as_str().to_string()), + type_id: message.event_id(), + payload: message.to_payload(), + }); + } + + /// Emit a fact on behalf of `player`; the principal is bound from the + /// player's verified ticket. Never blocks. + pub fn emit_fact_for(&mut self, player: PlayerId, fact: Fact) -> Result<(), EmitError> { + let principal = self + .core + .players + .get(&player) + .map(|slot| slot.info.principal.clone()) + .ok_or(EmitError::UnknownPlayer)?; + self.emit_bound(fact, Some(principal)) + } + + pub(super) fn emit_bound( + &mut self, + fact: Fact, + principal: Option, + ) -> Result<(), EmitError> { + let stamp = self.core.stamp_fact(); + self.core + .facts + .as_mut() + .ok_or(EmitError::NoSink)? + .try_send(fact.bind(principal, stamp)) + } + + /// [`emit`](Self::emit) that never answers [`EmitError::Backpressure`]: + /// when the fact queue is full the fact waits in the host's backlog, + /// in order behind facts queued earlier (the lifecycle facts use the + /// same backlog), and is sent as capacity frees, at the start of each + /// advance. It is stamped now and counts in + /// [`facts_in_flight`](Self::facts_in_flight) from now on, so the zone + /// does not go Dormant with it waiting; its settlement arrives in + /// [`Zone::on_fact_settled`] as any other. A key already in flight is + /// not sent twice (the waiting copy is dropped). A fact still waiting + /// when the queue is abandoned is lost with the queue. Returns the key. + pub fn emit_queued( + &mut self, + player: PlayerId, + input: C, + ) -> Result { + let fact = self.fact(&input)?; + let key = fact.key().to_string(); + self.queue_fact_for(player, fact).map(|()| key) + } + + /// [`emit_fact_for`](Self::emit_fact_for) through the backlog, as + /// [`emit_queued`](Self::emit_queued). + pub fn queue_fact_for(&mut self, player: PlayerId, fact: Fact) -> Result<(), EmitError> { + let principal = self + .core + .players + .get(&player) + .map(|slot| slot.info.principal.clone()) + .ok_or(EmitError::UnknownPlayer)?; + self.queue_bound(fact, Some(principal)) + } + + /// [`emit_fact_as`](Self::emit_fact_as) through the backlog, as + /// [`emit_queued`](Self::emit_queued). + pub fn queue_fact_as( + &mut self, + principal: &VerifiedPrincipal, + fact: Fact, + ) -> Result<(), EmitError> { + self.queue_bound(fact, Some(principal.as_str().to_string())) + } + + pub(super) fn queue_bound( + &mut self, + fact: Fact, + principal: Option, + ) -> Result<(), EmitError> { + if self.core.facts.is_none() { + return Err(EmitError::NoSink); + } + let stamp = self.core.stamp_fact(); + self.core.queue(fact.bind(principal, stamp)); + Ok(()) + } + + /// Unsettled facts (the backlog included). + pub fn facts_in_flight(&self) -> usize { + self.core.in_flight() + } + + /// Facts waiting in the backlog for queue capacity + /// ([`emit_queued`](Self::emit_queued)). + pub fn facts_queued(&self) -> usize { + self.core.backlog.len() + } + + /// Lag-compensation history (filled by [`Zone::record_rewind`]). + pub fn rewind(&self) -> &Rewind { + &self.core.rewind + } + + /// Set the zone's static level geometry (replaces any before). Call it + /// from [`Zone::on_create`], which runs on every wake. + pub fn set_colliders(&mut self, colliders: Colliders) { + self.core.colliders = colliders; + } + + /// The zone's static level geometry. + pub fn colliders(&self) -> &Colliders { + &self.core.colliders + } + + /// Closest hit of `ray` now: the latest recorded entities + /// ([`Zone::record_rewind`]) and the colliders. + pub fn raycast(&self, ray: &Ray) -> Option { + let rewind = &self.core.rewind; + match rewind.latest() { + Some(frame) => rewind.raycast_at(frame.time(), ray, &self.core.colliders, |_| true), + None => self.core.colliders.raycast(ray), + } + } + + /// Closest hit of `ray` with the entities as they were at `time` (from + /// [`Rewind::resolve`]) and the colliders. + pub fn raycast_at(&self, time: Duration, ray: &Ray) -> Option { + self.raycast_where(time, ray, |_| true) + } + + /// [`raycast_at`](Self::raycast_at) passing through the entities + /// `accept` refuses (game state a layer cannot say, e.g. a mob killed + /// since the shooter's view time). + pub fn raycast_where( + &self, + time: Duration, + ray: &Ray, + accept: impl FnMut(u32) -> bool, + ) -> Option { + self.core + .rewind + .raycast_at(time, ray, &self.core.colliders, accept) + } + + /// Lag-compensated shot: closest hit of `ray` with the entities as the + /// shooter saw them (`timing`, clamped by [`RewindConfig::max_rewind`]) + /// and the colliders; the latest state when the view time cannot be + /// resolved. + pub fn raycast_shot(&self, timing: ShotTiming, ray: &Ray) -> Option { + match self.core.rewind.resolve(timing) { + Some(resolved) => self.raycast_at(resolved.time, ray), + None => self.raycast(ray), + } + } + + /// Reliable event to one viewer (dropped if it has no live connection). + pub fn send_event(&mut self, to: impl Into, type_id: u32, payload: Vec) { + if let Some(client) = self.core.client_of(to.into()) { + self.core + .server_message(client, &ServerMessage::Event { type_id, payload }); + } + } + + /// Reliable event to every connection. + pub fn broadcast_event(&mut self, type_id: u32, payload: Vec) { + let frame = ServerMessage::Event { type_id, payload } + .encode(&()) + .expect("event encodes"); + let clients: Vec<_> = self.core.clients.keys().copied().collect(); + for client in clients { + self.core.send(client, frame.clone()); + } + } + + /// Typed reliable event to one viewer (dropped if it has no live + /// connection). + pub fn send(&mut self, to: impl Into, event: &E) { + self.send_event(to, event.event_id(), event.to_payload()); + } + + /// Typed reliable event to every connection. + pub fn broadcast(&mut self, event: &E) { + self.broadcast_event(event.event_id(), event.to_payload()); + } + + /// A viewer's area of interest (None for an unknown viewer). + pub fn view_of(&self, viewer: impl Into) -> Option { + match viewer.into() { + Viewer::Player(p) => self.core.players.get(&p).map(|slot| slot.view), + Viewer::Observer(o) => self.core.observers.get(&o).map(|slot| slot.view), + } + } + + /// Set a viewer's area of interest. + pub fn set_view(&mut self, viewer: impl Into, view: View) { + match viewer.into() { + Viewer::Player(p) => { + if let Some(slot) = self.core.players.get_mut(&p) { + slot.view = view; + } + } + Viewer::Observer(o) => { + if let Some(slot) = self.core.observers.get_mut(&o) { + slot.view = view; + } + } + } + } + + /// Remove a player after the current hook returns. + pub fn kick(&mut self, player: PlayerId, message: impl Into) { + self.core.pending_kicks.push((player, message.into())); + } + + /// Provenance of anything produced now (zone, activation, tick, wall + /// time, content and config version); embed it in events so clients + /// and logs can tell which content version produced them. + pub fn stamp(&self) -> FactStamp { + self.core.stamp() + } + + /// Move `player` to `target_zone` with `carried` state (any [`Wire`] + /// value, e.g. a `#[derive(GameRecord)]` struct; the target decodes it + /// in [`Zone::on_handoff_join`] with + /// [`codec::from_bytes`](crate::codec::from_bytes)). A signed transfer + /// ticket is issued now; after the current hook returns the player is + /// removed (`LeaveReason::Handoff`) and its client is told + /// `Handoff(target, ticket)`. The player can never be in both zones: it + /// leaves this one before the ticket is usable, and the ticket is + /// single-use. + /// + /// **Custody.** From then on the carried state exists only inside the + /// ticket, which the client holds: it is delivered at most once. A + /// client that drops the ticket (or deliberately discards one carrying + /// state it dislikes and joins afresh), a ticket that expires, or an + /// issuing host that restarts before the target reserves it + /// (`unknown transfer`) loses the carried state, and the player is in + /// neither zone until it joins again. Anything that must survive that + /// belongs in a durable record, moved by a fact from the hook (see the + /// handoff section of the README), not in `carried`. + pub fn handoff( + &mut self, + player: PlayerId, + target_zone: &str, + carried: &C, + ) -> Result<(), HandoffError> { + if target_zone == self.core.zone_id { + return Err(HandoffError::SameZone); + } + let carried = crate::codec::to_bytes(carried); + if carried.len() > MAX_CARRIED_BYTES { + return Err(HandoffError::TooLarge); + } + let (principal, name, extensions) = self + .core + .players + .get(&player) + .map(|slot| { + ( + slot.info.principal.clone(), + slot.info.name.clone(), + slot.info.extensions.clone(), + ) + }) + .ok_or(HandoffError::UnknownPlayer)?; + if self + .core + .pending_handoffs + .iter() + .any(|(queued, _, _)| *queued == player) + { + return Err(HandoffError::Refused); + } + let departed_at_ms = self.core.stamp_ms(); + let request = HandoffRequest { + principal, + name, + extensions, + source_zone: self.core.zone_id.clone(), + target_zone: target_zone.to_string(), + carried, + departed_at_ms, + }; + let issuer = self + .core + .transfer_issuer + .as_mut() + .ok_or(HandoffError::NoIssuer)?; + let ticket = issuer(&request).ok_or(HandoffError::Refused)?; + self.core.pending_handoffs.push(( + player, + ServerMessage::Handoff { + target_zone: request.target_zone, + transfer_ticket: ticket, + }, + departed_at_ms, + )); + Ok(()) + } + + /// Send a tier-up event to the parent zone (and, while `levels` remain, + /// further up). Delivered asynchronously on a later tick of the parent. + pub fn emit_upward(&mut self, kind: impl Into, payload: Vec, levels: u8) { + if levels == 0 { + return; + } + self.core.upward.push(ChildEvent { + origin_zone: self.core.zone_id.clone(), + from_zone: self.core.zone_id.clone(), + kind: kind.into(), + payload, + origin_tick: self.core.tick, + content_version: self.core.config.content_version.clone(), + levels, + }); + } +} diff --git a/distributed_game/src/host/membership.rs b/distributed_game/src/host/membership.rs new file mode 100644 index 000000000..ed8473867 --- /dev/null +++ b/distributed_game/src/host/membership.rs @@ -0,0 +1,520 @@ +//! Players and observers coming and going: admission, reconnects, +//! inputs, kicks and handoffs. + +use super::*; + +impl ZoneHost { + /// [`Stimulus::JoinTransfer`]: from now on this zone stamps facts later + /// than the source stamped the departure ([`Transfer::departed_at_ms`]), + /// whatever the two hosts' clocks say. + pub(super) fn admit_transfer( + &mut self, + transfer: &Transfer, + capabilities: u32, + content_version: &str, + ) -> Result { + if transfer.claims.role != Role::Player { + return Err(JoinError::new( + error::UNAUTHORIZED, + "transfers are for players", + )); + } + self.core.stamp_floor_ms = self + .core + .stamp_floor_ms + .max(transfer.departed_at_ms.saturating_add(1)); + self.admit( + &transfer.claims, + capabilities, + content_version, + Some((transfer.source_zone.as_str(), transfer.carried.clone())), + ) + } + + pub(super) fn admit( + &mut self, + claims: &TicketClaims, + capabilities: u32, + content_version: &str, + handoff: Option<(&str, Vec)>, + ) -> Result { + if self.disposed { + return Err(JoinError::new(error::NOT_FOUND, "zone disposed")); + } + if claims.zone != self.core.zone_id { + return Err(JoinError::new( + error::UNAUTHORIZED, + "ticket is for another zone", + )); + } + let expected = &self.core.config.content_version; + let mut reload = false; + if !expected.is_empty() && content_version != expected { + let allowed = match self.core.config.stale_policy { + StalePolicy::Strict => false, + StalePolicy::SafeRoom { roam } => { + let gate = self.zone.is_gate(); + reload = gate; + handoff.is_some() && claims.role == Role::Player && (gate || roam) + } + }; + if !allowed { + return Err(JoinError::new( + error::VERSION_MISMATCH, + format!("content version {content_version} != {expected}: reload"), + )); + } + } + let existing = self + .core + .players + .values() + .find(|slot| slot.info.principal == claims.principal) + .map(|slot| slot.info.id); + let capacity_ok = match claims.role { + Role::Player => { + existing.is_some() || self.core.players.len() < self.core.config.max_players + } + Role::Observer => self.core.observers.len() < self.core.config.max_observers, + }; + if !capacity_ok { + return Err(JoinError::new(error::ZONE_FULL, "zone is full")); + } + let request = JoinRequest { + claims, + capabilities, + content_version, + }; + if let Admission::Reject(message) = hook!(self.on_auth(&request)) { + self.process_kicks(); + return Err(JoinError::new(error::REJECTED, message)); + } + self.wake(); + let client = ClientId(self.core.next_id()); + let mut handoff = handoff; + let joined = match (claims.role, existing) { + (Role::Player, Some(player)) => { + if let Some(slot) = self.core.players.get_mut(&player) { + if claims.name.is_some() { + slot.info.name = claims.name.clone(); + } + slot.info.extensions = claims.extensions.clone(); + } + self.bind_player(player, client, capabilities); + let zone = self.core.zone_id.clone(); + if let Some((from, carried)) = handoff.take() { + self.core.emit_lifecycle( + player, + PlayerJoined { + zone, + via: JoinVia::Handoff, + from_zone: Some(from.to_string()), + }, + ); + hook!(self.on_handoff_join(player, from, carried)); + } else { + self.core.emit_lifecycle( + player, + PlayerJoined { + zone, + via: JoinVia::Rejoin, + from_zone: None, + }, + ); + hook!(self.on_rejoin(player)); + } + Joined { + client, + viewer: Viewer::Player(player), + } + } + (Role::Player, None) => { + let player = PlayerId(self.core.next_id()); + let radius = self.core.config.default_view_radius; + let capacity = self.core.config.input_capacity; + let session_id = self.next_token(); + self.core.players.insert( + player, + PlayerSlot { + info: PlayerInfo { + id: player, + principal: claims.principal.clone(), + name: claims.name.clone(), + extensions: claims.extensions.clone(), + capabilities, + connected: true, + }, + inputs: InputBuffer::new(capacity), + client: None, + view: View::new(0.0, 0.0, radius), + grace_until: None, + reconnect_token: String::new(), + session_id, + content_version: content_version.to_string(), + transitions: 0, + }, + ); + self.bind_player(player, client, capabilities); + let zone = self.core.zone_id.clone(); + match handoff.take() { + Some((from, carried)) => { + self.core.emit_lifecycle( + player, + PlayerJoined { + zone, + via: JoinVia::Handoff, + from_zone: Some(from.to_string()), + }, + ); + hook!(self.on_handoff_join(player, from, carried)); + } + None => { + self.core.emit_lifecycle( + player, + PlayerJoined { + zone, + via: JoinVia::Ticket, + from_zone: None, + }, + ); + hook!(self.on_join(player)); + } + } + Joined { + client, + viewer: Viewer::Player(player), + } + } + (Role::Observer, _) => { + let observer = ObserverId(self.core.next_id()); + let session_id = self.next_token(); + self.core.observers.insert( + observer, + ObserverSlot { + info: ObserverInfo { + id: observer, + principal: claims.principal.clone(), + name: claims.name.clone(), + extensions: claims.extensions.clone(), + capabilities, + }, + client, + view: View::new(0.0, 0.0, self.core.config.default_view_radius), + }, + ); + self.attach_client(client, Viewer::Observer(observer)); + self.welcome(client, session_id, String::new(), Role::Observer); + hook!(self.on_observe(observer)); + Joined { + client, + viewer: Viewer::Observer(observer), + } + } + }; + if let Viewer::Player(player) = joined.viewer { + if let Some(slot) = self.core.players.get_mut(&player) { + slot.content_version = content_version.to_string(); + } + if reload { + self.reload(player); + } + } + self.process_kicks(); + Ok(joined) + } + + pub(super) fn reconnect_as( + &mut self, + token: &str, + capabilities: u32, + content_version: Option<&str>, + ) -> Result { + let player = (!token.is_empty() && !self.disposed) + .then(|| { + self.core + .players + .values() + .find(|slot| slot.reconnect_token == token) + .map(|slot| slot.info.id) + }) + .flatten() + .ok_or_else(|| JoinError::new(error::RECONNECT_FAILED, "unknown or expired token"))?; + let expected = self.core.config.content_version.clone(); + let mut reload = false; + if let Some(version) = content_version { + if !expected.is_empty() && version != expected { + if self.core.config.stale_policy == StalePolicy::Strict { + return Err(JoinError::new( + error::VERSION_MISMATCH, + format!("content version {version} != {expected}: reload"), + )); + } + reload = self.zone.is_gate(); + } + } + self.wake(); + let client = ClientId(self.core.next_id()); + self.bind_player(player, client, capabilities); + if let Some(version) = content_version { + if let Some(slot) = self.core.players.get_mut(&player) { + slot.content_version = version.to_string(); + } + } + let zone = self.core.zone_id.clone(); + self.core.emit_lifecycle(player, PlayerReconnected { zone }); + hook!(self.on_reconnected(player)); + if reload { + self.reload(player); + } + self.process_kicks(); + Ok(Joined { + client, + viewer: Viewer::Player(player), + }) + } + + /// Grace started: lifecycle fact, then [`Zone::on_connection_lost`]. + pub(super) fn connection_lost(&mut self, player: PlayerId, cause: LostCause) { + let lost = ConnectionLost { + zone: self.core.zone_id.clone(), + grace_ms: self.core.config.reconnect_grace.as_millis() as u64, + cause, + }; + self.core.emit_lifecycle(player, lost); + hook!(self.on_connection_lost(player)); + } + + /// [`Stimulus::Focus`]. + pub(super) fn focus_observer(&mut self, client: ClientId, x: f32, y: f32) { + if let Some(Viewer::Observer(observer)) = self.viewer_of(client) { + hook!(self.on_observer_focus(observer, x, y)); + } + } + + pub(super) fn attach_client(&mut self, client: ClientId, viewer: Viewer) { + self.core.clients.insert( + client, + ClientSlot { + viewer, + replica: ClientReplica::new(), + }, + ); + } + + pub(super) fn bind_player(&mut self, player: PlayerId, client: ClientId, capabilities: u32) { + let token = self.next_token(); + let slot = self.core.players.get_mut(&player).expect("player exists"); + let previous = slot.client.replace(client); + slot.grace_until = None; + slot.info.connected = true; + slot.info.capabilities = capabilities; + slot.reconnect_token = token.clone(); + // Every Welcome restarts the client's input sequence (ticket or + // reconnect token), so forget the previous connection's. + slot.inputs.reset_sequence(); + let session_id = slot.session_id.clone(); + if let Some(old) = previous { + self.core.clients.remove(&old); + self.core.server_message( + old, + &ServerMessage::Kick { + code: kick::REPLACED, + message: "replaced by a newer connection".into(), + }, + ); + self.core.outbound.push(Outbound::Close { client: old }); + } + self.attach_client(client, Viewer::Player(player)); + self.welcome(client, session_id, token, Role::Player); + } + + pub(super) fn welcome( + &mut self, + client: ClientId, + session_id: String, + token: String, + role: Role, + ) { + let welcome = ServerMessage::Welcome(Welcome { + session_id, + zone_id: self.core.zone_id.clone(), + role, + tick_rate: self.core.config.tick_rate, + patch_rate: self.core.config.patch_rate, + server_tick: self.core.tick as u32, + server_time: self.core.server_time_ms(), + reconnect_token: token, + content_version: self.core.config.content_version.clone(), + schema: self.schema.clone(), + features: feature::ALL, + origin: self.zone.origin(), + }); + self.core.server_message(client, &welcome); + } + + /// [`Stimulus::Disconnect`]. + pub(super) fn drop_client(&mut self, client: ClientId, graceful: bool) { + let Some(slot) = self.core.clients.remove(&client) else { + return; + }; + match slot.viewer { + Viewer::Player(player) => { + if graceful { + self.remove_player(player, LeaveReason::Left, None); + } else if let Some(p) = self.core.players.get_mut(&player) { + p.client = None; + p.info.connected = false; + p.inputs.clear(); + p.grace_until = Some(self.core.now + self.core.config.reconnect_grace); + self.connection_lost(player, LostCause::Dropped); + } + } + Viewer::Observer(observer) => self.remove_observer(observer, None), + } + self.process_kicks(); + } + + /// [`Stimulus::Input`]: decoded and sanitized by the zone. + pub(super) fn offer_input( + &mut self, + client: ClientId, + seq: u32, + client_tick: u32, + payload: &[u8], + ) -> PushOutcome { + let Some(Viewer::Player(player)) = self.viewer_of(client) else { + return PushOutcome::UnknownClient; + }; + if self.frozen { + self.core.dropped_frozen += 1; + return PushOutcome::Rejected; + } + let Some(slot) = self.core.players.get(&player) else { + return PushOutcome::UnknownClient; + }; + if let Some(outcome) = slot.inputs.precheck(seq) { + return outcome; + } + let Some(input) = self + .zone + .decode_input(player, payload) + .and_then(|input| self.zone.sanitize_input(player, input)) + else { + return PushOutcome::Rejected; + }; + self.wake(); + self.core + .players + .get_mut(&player) + .expect("player exists") + .inputs + .push(seq, client_tick, input) + } + + /// [`Stimulus::Kick`]: every connection of `principal` goes (players + /// leave with [`LeaveReason::Kicked`]). + pub(super) fn kick_principal(&mut self, principal: &str, reason: String) -> Delivered { + let mut delivered = Delivered::default(); + let players: Vec<_> = self + .core + .players + .values() + .filter(|slot| slot.info.principal == principal) + .map(|slot| slot.info.id) + .collect(); + delivered.players_kicked = players.len(); + for player in players { + self.core.pending_kicks.push((player, reason.clone())); + } + let observers: Vec<_> = self + .core + .observers + .values() + .filter(|slot| slot.info.principal == principal) + .map(|slot| slot.info.id) + .collect(); + delivered.observers_kicked = observers.len(); + let bye = ServerMessage::Kick { + code: kick::BY_ZONE, + message: reason, + }; + for observer in observers { + self.remove_observer(observer, Some(&bye)); + } + self.process_kicks(); + delivered + } + + /// [`Stimulus::Handoff`]. + pub(super) fn hand_off(&mut self, player: PlayerId, target_zone: &str, transfer_ticket: &str) { + let message = ServerMessage::Handoff { + target_zone: target_zone.into(), + transfer_ticket: transfer_ticket.into(), + }; + self.remove_player(player, LeaveReason::Handoff, Some(message)); + self.process_kicks(); + } + + pub(super) fn remove_player( + &mut self, + player: PlayerId, + reason: LeaveReason, + last: Option, + ) { + let Some(slot) = self.core.players.remove(&player) else { + return; + }; + if let Some(client) = slot.client { + self.core.clients.remove(&client); + if let Some(message) = last { + self.core.server_message(client, &message); + } + self.core.outbound.push(Outbound::Close { client }); + } + hook!(self.on_leave(player, reason)); + if self.core.config.lifecycle_facts { + let zone = self.core.zone_id.clone(); + let (principal, n) = (slot.info.principal, slot.transitions + 1); + match LeftReason::from_leave(reason) { + Some(reason) => { + self.core + .lifecycle(player, &principal, n, PlayerLeft { zone, reason }) + } + None => self + .core + .lifecycle(player, &principal, n, PlayerDisconnected { zone }), + } + } + } + + pub(super) fn remove_observer(&mut self, observer: ObserverId, last: Option<&ServerMessage>) { + let Some(slot) = self.core.observers.remove(&observer) else { + return; + }; + self.core.clients.remove(&slot.client); + if let Some(message) = last { + self.core.server_message(slot.client, message); + self.core.outbound.push(Outbound::Close { + client: slot.client, + }); + } + self.core.departing = Some(slot.info); + hook!(self.on_unobserve(observer)); + self.core.departing = None; + } + + pub(super) fn process_kicks(&mut self) { + while let Some((player, message, departed_at_ms)) = self.core.pending_handoffs.pop() { + self.core.pinned_stamp_ms = Some(departed_at_ms); + self.remove_player(player, LeaveReason::Handoff, Some(message)); + self.core.pinned_stamp_ms = None; + } + while let Some((player, message)) = self.core.pending_kicks.pop() { + let kick = ServerMessage::Kick { + code: kick::BY_ZONE, + message, + }; + self.remove_player(player, LeaveReason::Kicked, Some(kick)); + } + } +} diff --git a/distributed_game/src/host/outbound.rs b/distributed_game/src/host/outbound.rs new file mode 100644 index 000000000..518a735ae --- /dev/null +++ b/distributed_game/src/host/outbound.rs @@ -0,0 +1,62 @@ +//! What leaves the zone besides Deltas: events to viewers, zone messages +//! and tier-up events. + +use super::*; + +impl ZoneHost { + /// Zone messages sent since the last call ([`crate::zone_message`]); + /// the driver hands each to its target's + /// [`deliver_zone`](Self::deliver_zone). + pub fn take_zone_messages(&mut self) -> Vec { + std::mem::take(&mut self.core.zone_out) + } + + /// [`Stimulus::ZoneMessage`]. + pub(super) fn deliver_envelope( + &mut self, + envelope: ZoneEnvelope, + ) -> Result<(), ZoneMessageError> { + if envelope.to != self.core.zone_id { + return Err(ZoneMessageError::WrongZone); + } + let message = Z::Message::decode_event(envelope.type_id, &envelope.payload) + .map_err(|e| ZoneMessageError::Decode(e.to_string()))? + .ok_or_else(|| ZoneMessageError::Decode(format!("type {}", envelope.type_id)))?; + if !self.core.zone_seen.first(&envelope.id) { + return Err(ZoneMessageError::Duplicate); + } + let sender = ZoneSender { + zone: envelope.from, + principal: envelope.principal.map(VerifiedPrincipal::new), + }; + hook!(self.on_zone_message(&sender, message)); + self.process_kicks(); + Ok(()) + } + + /// Tier-up events emitted (or forwarded) by this zone since the last + /// call; the driver routes them to the parent zone. + pub fn drain_upward(&mut self) -> Vec { + std::mem::take(&mut self.core.upward) + } + + /// Send a reliable event (operator/server side). + pub fn send_event(&mut self, to: Viewer, type_id: u32, payload: Vec) { + Ctx { + core: &mut self.core, + } + .send_event(to, type_id, payload); + } + + /// Send a typed event now (see [`Ctx::send`]). + pub fn send(&mut self, to: Viewer, event: &E) { + self.send_event(to, event.event_id(), event.to_payload()); + } + + pub(super) fn broadcast(&mut self, message: &ServerMessage) { + let clients: Vec<_> = self.core.clients.keys().copied().collect(); + for client in clients { + self.core.server_message(client, message); + } + } +} diff --git a/distributed_game/src/host/stimulus.rs b/distributed_game/src/host/stimulus.rs new file mode 100644 index 000000000..a12d2c2ff --- /dev/null +++ b/distributed_game/src/host/stimulus.rs @@ -0,0 +1,574 @@ +//! [`Stimulus`] and its dispatch ([`ZoneHost::apply`]), the recording tap +//! and the shorthands drivers call. + +use super::*; + +/// Something from outside the zone that changes it: the one way anything +/// does. [`ZoneHost::apply`] runs it with the clock read once on arrival; +/// the typed methods ([`join`](ZoneHost::join), +/// [`push_input`](ZoneHost::push_input), [`advance`](ZoneHost::advance), …) +/// are shorthand for it. A host with [`HostConfig::record`] keeps every +/// stimulus, with that clock reading and what it observed, in its +/// [`Recording`](crate::replay::Recording). +/// +/// Game messages travel encoded (`type_id` + payload, as on the wire), so +/// a stimulus is independent of the zone type. +#[derive(Debug, Clone, PartialEq)] +pub enum Stimulus { + /// Admit a verified ticket holder. + Join { + /// Verified claims. + claims: TicketClaims, + /// Hello capabilities. + capabilities: u32, + /// The client's content version. + content_version: String, + }, + /// Admit a player arriving with a verified transfer ticket: the zone + /// sees [`Zone::on_handoff_join`] with the carried state (also when the + /// principal is still present, e.g. inside its reconnect grace). + JoinTransfer { + /// Verified transfer. + transfer: Transfer, + /// Hello capabilities. + capabilities: u32, + /// The client's content version. + content_version: String, + }, + /// Resume a player's session with the token from its last Welcome. + /// With `content_version` (the client's, possibly reloaded) a stale + /// version is refused under [`StalePolicy::Strict`]; under `SafeRoom` + /// it is admitted to this zone and told `Kick(RELOAD)` again if this + /// zone is a gate. + Reconnect { + /// Reconnect token (in a recording: its place in the host's token + /// sequence, `token#N`). + token: String, + /// Hello capabilities. + capabilities: u32, + /// The client's content version, when it presented one. + content_version: Option, + }, + /// A connection ended. Graceful (Leave) removes the player now; + /// otherwise the player stays (disconnected) for `reconnect_grace`. + Disconnect { + /// Connection. + client: ClientId, + /// Leave vs drop. + graceful: bool, + }, + /// A wire input from `client`, decoded and sanitized by the zone. + Input { + /// Connection. + client: ClientId, + /// Sequence. + seq: u32, + /// Client tick. + client_tick: u32, + /// Encoded input. + payload: Vec, + }, + /// A client patched its content live and now runs `version` + /// (`ClientMessage::Content`): kept for its player only when it is the + /// zone's current version (a client can catch up, never get ahead). + Content { + /// Connection. + client: ClientId, + /// Version it runs. + version: String, + }, + /// An observer's `Focus` ([`Zone::on_observer_focus`]); ignored for + /// players and unknown clients. + Focus { + /// Connection. + client: ClientId, + /// Focus x. + x: f32, + /// Focus y. + y: f32, + }, + /// Service inbox ([`crate::inbox`]): remove every connection of + /// `principal` (players leave with [`LeaveReason::Kicked`]). + Kick { + /// Principal kicked. + principal: String, + /// Reason sent to its clients. + reason: String, + }, + /// Service inbox: an encoded `Z::Message` for [`Zone::on_message`]. + Message { + /// Message type id. + type_id: u32, + /// Encoded payload. + payload: Vec, + }, + /// A message from another zone ([`Zone::on_zone_message`]), unless its + /// id was seen lately. + ZoneMessage(ZoneEnvelope), + /// A tier-up event from a child zone: delivered to + /// [`Zone::on_child_event`] on a later tick (or the next advance when + /// the zone is not ticking), never while frozen. + ChildEvent(ChildEvent), + /// Barrier phase 1: freeze as soon as [`Zone::freeze_ready`] allows + /// (now, or at the end of a later advance; the zone keeps ticking until + /// then). + RequestFreeze(Notice), + /// Abort a barrier: drop a pending freeze request, and resume with the + /// notice if already frozen. + CancelFreeze(Notice), + /// Resume after a freeze; the frozen backlog is not simulated. + Resume(Notice), + /// Switch to a new content version + /// ([`Zone::on_content_version_changed`]); facts and stamps produced + /// afterwards carry it. + ContentVersion(String), + /// Switch the remote config version ([`HostConfig::config_version`]); + /// facts and stamps produced afterwards carry it. + ConfigVersion(String), + /// Tell a connected player to reload its content (`Kick(RELOAD)`) and + /// keep it in the reconnect grace window so it can reconnect with its + /// last Welcome's token after reloading. + Reload(PlayerId), + /// [`Reload`](Self::Reload) every connected player whose content + /// version differs from the zone's (hard rollout). + ReloadStale, + /// Kick a player now. + KickPlayer { + /// Player. + player: PlayerId, + /// Reason sent to its client. + message: String, + }, + /// Tell a player to move to `target_zone`, then remove it + /// (`LeaveReason::Handoff`); the transfer is the caller's concern. + Handoff { + /// Player. + player: PlayerId, + /// Zone it moves to. + target_zone: String, + /// Transfer ticket it presents there. + ticket: String, + }, + /// Hand a hibernated snapshot to the zone ([`Zone::on_restore`]), + /// right after construction. + Restore { + /// Snapshot bytes. + state: Vec, + /// Content version it was written under. + saved_version: String, + }, + /// Kick everyone (`on_leave(Disposed)` / `on_unobserve`), call + /// `on_dispose`, clear timers. The host stops ticking afterwards. + Dispose, + /// Run due ticks and patches for the time elapsed on the clock. + Advance, +} + +/// What a [`Stimulus`] answered. +#[derive(Debug, Clone, PartialEq)] +pub enum Outcome { + /// Nothing to report. + Done, + /// A join or reconnect. + Joined(Result), + /// An input. + Input(PushOutcome), + /// A kick or message from the service inbox. + Delivered(Delivered), + /// A zone message. + ZoneMessage(Result<(), ZoneMessageError>), + /// A freeze request. + Freeze(FreezeState), + /// Players told to reload. + Reloaded(usize), + /// Whether a client's content patch was kept. + Patched(bool), + /// An advance. + Advanced(AdvanceReport), +} + +/// Recording kept by a host with [`HostConfig::record`]. +pub(super) struct Tape { + pub(super) recording: Recording, + /// Tokens issued so far: a reconnect is recorded by its token's place + /// in this sequence, never the secret. + pub(super) tokens: Vec, +} + +impl ZoneHost { + /// Run one [`Stimulus`]: the single way the zone changes from outside. + /// The clock is read once here; the host and the zone see that time + /// throughout ([`Ctx::now`], fact stamps, grace deadlines). With + /// [`HostConfig::record`] the stimulus, that time and what it observed + /// (join and input outcomes, settlements and per-tick state hashes) are + /// appended to the [`recording`](Self::recording). + pub fn apply(&mut self, stimulus: Stimulus) -> Outcome { + // Never backwards, whatever the clock does. + self.core.now = self.core.clock.now().max(self.core.now); + self.core.unix_ms = self.core.clock.unix_ms().max(self.core.unix_ms); + let recorded = self.tape.as_ref().map(|tape| tape.redact(&stimulus)); + let outcome = self.dispatch(stimulus); + if let (Some(stimulus), Some(tape)) = (recorded, &mut self.tape) { + tape.recording.entries.push(Entry { + at: self.core.now, + unix_ms: self.core.unix_ms, + stimulus, + observed: Observed::of(&outcome), + }); + } + outcome + } + + pub(super) fn dispatch(&mut self, stimulus: Stimulus) -> Outcome { + match stimulus { + Stimulus::Join { + claims, + capabilities, + content_version, + } => Outcome::Joined(self.admit(&claims, capabilities, &content_version, None)), + Stimulus::JoinTransfer { + transfer, + capabilities, + content_version, + } => Outcome::Joined(self.admit_transfer(&transfer, capabilities, &content_version)), + Stimulus::Reconnect { + token, + capabilities, + content_version, + } => { + Outcome::Joined(self.reconnect_as(&token, capabilities, content_version.as_deref())) + } + Stimulus::Disconnect { client, graceful } => { + self.drop_client(client, graceful); + Outcome::Done + } + Stimulus::Input { + client, + seq, + client_tick, + payload, + } => Outcome::Input(self.offer_input(client, seq, client_tick, &payload)), + Stimulus::Content { client, version } => { + Outcome::Patched(self.patch_content(client, &version)) + } + Stimulus::Focus { client, x, y } => { + self.focus_observer(client, x, y); + Outcome::Done + } + Stimulus::Kick { principal, reason } => { + Outcome::Delivered(self.kick_principal(&principal, reason)) + } + Stimulus::Message { type_id, payload } => { + if let Ok(Some(message)) = Z::Message::decode_event(type_id, &payload) { + hook!(self.on_message(message)); + self.process_kicks(); + } + Outcome::Delivered(Delivered::default()) + } + Stimulus::ZoneMessage(envelope) => { + Outcome::ZoneMessage(self.deliver_envelope(envelope)) + } + Stimulus::ChildEvent(event) => { + self.core.child_inbox.push(event); + Outcome::Done + } + Stimulus::RequestFreeze(notice) => Outcome::Freeze(self.ask_freeze(notice)), + Stimulus::CancelFreeze(notice) => { + self.abort_freeze(notice); + Outcome::Done + } + Stimulus::Resume(notice) => { + self.thaw(notice); + Outcome::Done + } + Stimulus::ContentVersion(version) => { + self.switch_content(version); + Outcome::Done + } + Stimulus::ConfigVersion(version) => { + self.core.config.config_version = version; + Outcome::Done + } + Stimulus::Reload(player) => { + self.reload(player); + Outcome::Done + } + Stimulus::ReloadStale => Outcome::Reloaded(self.reload_stale()), + Stimulus::KickPlayer { player, message } => { + self.core.pending_kicks.push((player, message)); + self.process_kicks(); + Outcome::Done + } + Stimulus::Handoff { + player, + target_zone, + ticket, + } => { + self.hand_off(player, &target_zone, &ticket); + Outcome::Done + } + Stimulus::Restore { + state, + saved_version, + } => { + self.restore_snapshot(&state, &saved_version); + Outcome::Done + } + Stimulus::Dispose => { + self.dispose_zone(); + Outcome::Done + } + Stimulus::Advance => Outcome::Advanced(self.step()), + } + } + + /// The recording so far ([`HostConfig::record`]; `None` when off). + pub fn recording(&self) -> Option<&Recording> { + self.tape.as_ref().map(|tape| &tape.recording) + } + + pub(super) fn next_token(&mut self) -> String { + let token = (self.token_source)(); + if let Some(tape) = &mut self.tape { + tape.tokens.push(token.clone()); + } + token + } + + // ---- Shorthand for `apply` ---- + + /// [`Stimulus::Join`]. + pub fn join( + &mut self, + claims: &TicketClaims, + capabilities: u32, + content_version: &str, + ) -> Result { + self.apply(Stimulus::Join { + claims: claims.clone(), + capabilities, + content_version: content_version.into(), + }) + .joined() + } + + /// [`Stimulus::JoinTransfer`]. + pub fn join_transfer( + &mut self, + transfer: &Transfer, + capabilities: u32, + content_version: &str, + ) -> Result { + self.apply(Stimulus::JoinTransfer { + transfer: transfer.clone(), + capabilities, + content_version: content_version.into(), + }) + .joined() + } + + /// [`Stimulus::Reconnect`] without a content version. + pub fn reconnect(&mut self, token: &str, capabilities: u32) -> Result { + self.apply(Stimulus::Reconnect { + token: token.into(), + capabilities, + content_version: None, + }) + .joined() + } + + /// [`Stimulus::Reconnect`] presenting the client's content version. + pub fn reconnect_with_version( + &mut self, + token: &str, + capabilities: u32, + content_version: &str, + ) -> Result { + self.apply(Stimulus::Reconnect { + token: token.into(), + capabilities, + content_version: Some(content_version.into()), + }) + .joined() + } + + /// [`Stimulus::Disconnect`]. + pub fn disconnect(&mut self, client: ClientId, graceful: bool) { + self.apply(Stimulus::Disconnect { client, graceful }); + } + + /// [`Stimulus::Input`]. + pub fn push_input( + &mut self, + client: ClientId, + seq: u32, + client_tick: u32, + payload: &[u8], + ) -> PushOutcome { + match self.apply(Stimulus::Input { + client, + seq, + client_tick, + payload: payload.to_vec(), + }) { + Outcome::Input(outcome) => outcome, + other => unreachable!("input answered {other:?}"), + } + } + + /// [`Stimulus::Content`]: whether it was kept. + pub fn content_patched(&mut self, client: ClientId, version: &str) -> bool { + matches!( + self.apply(Stimulus::Content { + client, + version: version.into(), + }), + Outcome::Patched(true) + ) + } + + /// [`Stimulus::Focus`]. + pub fn observer_focus(&mut self, client: ClientId, x: f32, y: f32) { + self.apply(Stimulus::Focus { client, x, y }); + } + + /// Deliver a service message ([`crate::inbox`]): [`Stimulus::Kick`] or + /// [`Stimulus::Message`]. + pub fn deliver(&mut self, inbound: ZoneInbound) -> Delivered { + let stimulus = match inbound { + ZoneInbound::Kick { principal, reason } => Stimulus::Kick { principal, reason }, + ZoneInbound::Message(message) => Stimulus::Message { + type_id: message.event_id(), + payload: message.to_payload(), + }, + }; + match self.apply(stimulus) { + Outcome::Delivered(delivered) => delivered, + other => unreachable!("delivery answered {other:?}"), + } + } + + /// [`Stimulus::ZoneMessage`]. + pub fn deliver_zone(&mut self, envelope: ZoneEnvelope) -> Result<(), ZoneMessageError> { + match self.apply(Stimulus::ZoneMessage(envelope)) { + Outcome::ZoneMessage(result) => result, + other => unreachable!("zone message answered {other:?}"), + } + } + + /// [`Stimulus::ChildEvent`]. + pub fn deliver_child_event(&mut self, event: ChildEvent) { + self.apply(Stimulus::ChildEvent(event)); + } + + /// [`Stimulus::RequestFreeze`]: the resulting state. + pub fn request_freeze(&mut self, notice: Notice) -> FreezeState { + match self.apply(Stimulus::RequestFreeze(notice)) { + Outcome::Freeze(state) => state, + other => unreachable!("freeze request answered {other:?}"), + } + } + + /// [`Stimulus::CancelFreeze`]. + pub fn cancel_freeze(&mut self, notice: Notice) { + self.apply(Stimulus::CancelFreeze(notice)); + } + + /// [`Stimulus::Resume`]. + pub fn resume(&mut self, notice: Notice) { + self.apply(Stimulus::Resume(notice)); + } + + /// [`Stimulus::ContentVersion`]. + pub fn set_content_version(&mut self, version: impl Into) { + self.apply(Stimulus::ContentVersion(version.into())); + } + + /// [`Stimulus::ConfigVersion`]. + pub fn set_config_version(&mut self, version: impl Into) { + self.apply(Stimulus::ConfigVersion(version.into())); + } + + /// [`Stimulus::Reload`]. + pub fn reload_player(&mut self, player: PlayerId) { + self.apply(Stimulus::Reload(player)); + } + + /// [`Stimulus::ReloadStale`]: the number reloaded. + pub fn reload_stale_players(&mut self) -> usize { + match self.apply(Stimulus::ReloadStale) { + Outcome::Reloaded(n) => n, + other => unreachable!("reload answered {other:?}"), + } + } + + /// [`Stimulus::KickPlayer`]. + pub fn kick(&mut self, player: PlayerId, message: impl Into) { + self.apply(Stimulus::KickPlayer { + player, + message: message.into(), + }); + } + + /// [`Stimulus::Handoff`]. + pub fn handoff(&mut self, player: PlayerId, target_zone: &str, transfer_ticket: &str) { + self.apply(Stimulus::Handoff { + player, + target_zone: target_zone.into(), + ticket: transfer_ticket.into(), + }); + } + + /// [`Stimulus::Restore`]. + pub fn restore(&mut self, state: &[u8], saved_version: &str) { + self.apply(Stimulus::Restore { + state: state.to_vec(), + saved_version: saved_version.into(), + }); + } + + /// [`Stimulus::Dispose`]. + pub fn dispose(&mut self) { + self.apply(Stimulus::Dispose); + } + + /// [`Stimulus::Advance`]. + pub fn advance(&mut self) -> AdvanceReport { + match self.apply(Stimulus::Advance) { + Outcome::Advanced(report) => report, + other => unreachable!("advance answered {other:?}"), + } + } +} + +impl Outcome { + pub(super) fn joined(self) -> Result { + match self { + Self::Joined(result) => result, + other => unreachable!("join answered {other:?}"), + } + } +} + +impl Tape { + /// `stimulus` as recorded: a reconnect token becomes its place in the + /// token sequence (`token#N`; empty when this host never issued it). + pub(super) fn redact(&self, stimulus: &Stimulus) -> Stimulus { + match stimulus { + Stimulus::Reconnect { + token, + capabilities, + content_version, + } => Stimulus::Reconnect { + token: self + .tokens + .iter() + .position(|issued| issued == token) + .map_or_else(String::new, crate::replay::token_label), + capabilities: *capabilities, + content_version: content_version.clone(), + }, + other => other.clone(), + } + } +} diff --git a/distributed_game/src/host/tick.rs b/distributed_game/src/host/tick.rs new file mode 100644 index 000000000..5e8bbe52c --- /dev/null +++ b/distributed_game/src/host/tick.rs @@ -0,0 +1,290 @@ +//! The tick loop: tiers, fixed steps, settlements, patches and disposal. + +use super::*; + +impl ZoneHost { + /// [`Stimulus::Dispose`]. + pub(super) fn dispose_zone(&mut self) { + if self.disposed { + return; + } + let bye = ServerMessage::Kick { + code: kick::ZONE_DISPOSED, + message: "zone disposed".into(), + }; + let players: Vec<_> = self.core.players.keys().copied().collect(); + for player in players { + self.remove_player(player, LeaveReason::Disposed, Some(bye.clone())); + } + let observers: Vec<_> = self.core.observers.keys().copied().collect(); + for observer in observers { + self.remove_observer(observer, Some(&bye)); + } + hook!(self.on_dispose()); + self.core.pending_kicks.clear(); + self.core.timers.clear(); + self.disposed = true; + } + + pub(super) fn wake(&mut self) { + let now = self.core.now; + self.set_tier(Tier::Hot, now); + } + + pub(super) fn set_tier(&mut self, to: Tier, now: Duration) { + let from = self.core.tier; + if from == to { + return; + } + self.core.tier = to; + self.hot.reset(); + if let Some(idle) = &mut self.idle { + idle.reset(); + } + match to { + Tier::Hot => self.next_patch = now, + Tier::Idle => self.idle_since = now, + Tier::Dormant => {} + } + self.transitions.push((from, to)); + hook!(self.on_tier_changed(from, to)); + self.process_kicks(); + } + + pub(super) fn evaluate_tier(&mut self, now: Duration) { + let present = !self.core.players.is_empty() || !self.core.clients.is_empty(); + if present || self.zone.has_pending_work() { + self.set_tier(Tier::Hot, now); + return; + } + match self.core.tier { + Tier::Hot => self.set_tier(Tier::Idle, now), + Tier::Idle => { + if now.saturating_sub(self.idle_since) >= self.core.config.dormant_after + && self.core.in_flight() == 0 + && !self.zone.wants_background() + { + self.set_tier(Tier::Dormant, now); + } + } + Tier::Dormant => {} + } + } + + pub(super) fn deliver_settlements(&mut self) { + let tick = self.core.tick; + let settled = match &mut self.core.facts { + Some(queue) => queue.drain_at(tick), + None => return, + }; + for settlement in settled { + self.pending.settled.push((tick, settlement.clone())); + hook!(self.on_fact_settled(settlement)); + } + self.process_kicks(); + } + + pub(super) fn deliver_child_events(&mut self) { + if self.frozen || self.core.child_inbox.is_empty() { + return; + } + for event in std::mem::take(&mut self.core.child_inbox) { + hook!(self.on_child_event(&event)); + if event.levels > 1 { + let mut forward = event; + forward.levels -= 1; + forward.from_zone = self.core.zone_id.clone(); + self.core.upward.push(forward); + } + } + self.process_kicks(); + } + + pub(super) fn tick_once(&mut self, dt: Duration) { + // wasm32-unknown-unknown (celld) has no `Instant`: measure with the + // host clock there (the celld zone host). + #[cfg(not(target_arch = "wasm32"))] + let started = std::time::Instant::now(); + #[cfg(target_arch = "wasm32")] + let started = self.core.clock.now(); + self.core.tick += 1; + self.core.sim_time += dt; + self.core.dt = dt; + self.deliver_settlements(); + self.deliver_child_events(); + let due = self.core.timers.due(self.core.sim_time); + for (id, timer) in due { + hook!(self.on_timer(id, timer)); + } + hook!(self.on_tick()); + self.core.dropped_ticks = 0; + self.process_kicks(); + let mut frame = self.core.rewind.frame(); + self.zone.record_rewind(&mut frame); + let entities = frame.into_entities(); + if !entities.is_empty() || !self.core.rewind.is_empty() { + self.core + .rewind + .record(self.core.tick, self.core.sim_time, entities); + } + #[cfg(not(target_arch = "wasm32"))] + self.pending.tick_durations.push(started.elapsed()); + #[cfg(target_arch = "wasm32")] + self.pending + .tick_durations + .push(self.core.clock.now().saturating_sub(started)); + if self.hash_ticks { + let hash = self.state_hash(); + self.pending.tick_hashes.push((self.core.tick, hash)); + } + } + + /// This patch's replicated world: every registered entity collection's + /// projected views ([`Zone::entities`]), then [`Zone::replicate`]. + pub fn world_view(&self) -> WorldView { + let mut view = WorldView::default(); + self.entities.project(&self.zone, &mut view); + self.zone.replicate(&mut view); + view + } + + pub(super) fn patch(&mut self) { + let view = &mut self.view; + view.clear(); + self.entities.project(&self.zone, view); + self.zone.replicate(view); + let core = &mut self.core; + self.pending.entities = Some(view.entities().len()); + let interest = &core.config.interest; + let mut world = match self.last_world.take() { + Some(last) => last.next(&self.schema, view, interest), + None => EncodedWorld::build(&self.schema, view, interest), + }; + let tick = core.tick as u32; + let budget = core.config.byte_budget; + for (client, slot) in core.clients.iter_mut() { + let (view, ack) = match slot.viewer { + Viewer::Player(p) => match core.players.get(&p) { + Some(player) => (player.view, player.inputs.last_processed()), + None => continue, + }, + Viewer::Observer(o) => match core.observers.get(&o) { + Some(observer) => (observer.view, 0), + None => continue, + }, + }; + let (frame, stats) = slot.replica.build_delta( + &self.schema, + &mut world, + &core.config.interest, + &view, + budget, + tick, + ack, + ); + self.pending.frames.push(FrameStats { + client: *client, + bytes: frame.len(), + stats, + }); + core.outbound.push(Outbound::Frame { + client: *client, + frame, + }); + } + self.pending.encodes += world.encodes(); + self.last_world = Some(world); + } + + /// [`Stimulus::Advance`]. + pub(super) fn step(&mut self) -> AdvanceReport { + let mut report = std::mem::take(&mut self.pending); + if self.disposed { + return report; + } + let now = self.core.now; + let elapsed = now.saturating_sub(self.last_advance); + self.last_advance = now; + self.core.flush_backlog(); + + let expired: Vec<_> = self + .core + .players + .values() + .filter(|slot| slot.grace_until.is_some_and(|until| until <= now)) + .map(|slot| slot.info.id) + .collect(); + for player in expired { + self.remove_player(player, LeaveReason::Disconnected, None); + } + self.process_kicks(); + self.evaluate_tier(now); + + let (steps, dt) = match self.core.tier { + Tier::Hot => (self.hot.advance(elapsed), self.hot.step()), + Tier::Idle => match &mut self.idle { + Some(idle) => (idle.advance(elapsed), idle.step()), + None => Default::default(), + }, + Tier::Dormant => Default::default(), + }; + report.dropped = steps.dropped; + if !dt.is_zero() { + report.dropped_ticks = (steps.dropped.as_nanos() / dt.as_nanos()) as u32; + } + self.core.dropped_ticks = self.core.dropped_ticks.saturating_add(report.dropped_ticks); + if !self.frozen { + for _ in 0..steps.steps { + self.tick_once(dt); + } + report.ticks = steps.steps; + } + if report.ticks == 0 { + self.deliver_settlements(); + self.deliver_child_events(); + } + self.try_freeze(); + + let patch_interval = rate_to_step(self.core.config.patch_rate); + if self.core.tier == Tier::Hot && !self.core.clients.is_empty() && now >= self.next_patch { + self.patch(); + report.patched = true; + self.next_patch = if now - self.next_patch >= patch_interval { + now + patch_interval + } else { + self.next_patch + patch_interval + }; + } + + let mut wake = match self.core.tier { + Tier::Hot => { + let mut at = now + self.hot.until_next(); + if !self.core.clients.is_empty() { + at = at.min(self.next_patch); + } + Some(at) + } + Tier::Idle => { + let dormant_at = self.idle_since + self.core.config.dormant_after; + let tick_at = self.idle.as_ref().map(|idle| now + idle.until_next()); + Some(tick_at.map_or(dormant_at, |t| t.min(dormant_at)).max(now)) + } + Tier::Dormant => None, + }; + for slot in self.core.players.values() { + if let Some(until) = slot.grace_until { + wake = Some(wake.map_or(until, |w| w.min(until))); + } + } + report.next_wake = wake; + report.transitions = std::mem::take(&mut self.transitions); + let pending = std::mem::take(&mut self.pending); + report.tick_durations.extend(pending.tick_durations); + report.entities = pending.entities; + report.frames.extend(pending.frames); + report.encodes += pending.encodes; + report.settled.extend(pending.settled); + report.tick_hashes.extend(pending.tick_hashes); + report + } +} diff --git a/distributed_game/src/inbox.rs b/distributed_game/src/inbox.rs new file mode 100644 index 000000000..89e795f0b --- /dev/null +++ b/distributed_game/src/inbox.rs @@ -0,0 +1,69 @@ +//! The zone inbox: typed messages from services into a running zone. +//! +//! A zone declares [`Zone::Message`](crate::Zone::Message) — a +//! `#[derive(GameEvent)]` struct or enum, so messages have stable type ids +//! and the same typed binary payload codec as events (and appear in the +//! zone's [`GameSurface`](crate::GameSurface) under `messages`) — and +//! handles them in [`Zone::on_message`](crate::Zone::on_message). Zones that +//! take none use [`NoMessages`]. +//! +//! Delivery ([`ZoneHost::deliver`](crate::ZoneHost::deliver)) runs on the +//! zone's own task between ticks, never concurrently with one. The host +//! handles the built-in [`ZoneInbound::Kick`] itself (the player leaves with +//! `LeaveReason::Kicked` and, with lifecycle facts on, a `PlayerLeft` +//! fact). Over the network: `GameServer::send` locally, `POST +//! /admin/zone-message` for peers and services (admin secret), and +//! `net::ZoneInboxClient`, which finds the owning host through the +//! `ZoneDirectory` and follows `wrong_owner` answers. A message for a zone +//! that is not active is refused; it never activates the zone. + +use crate::authoring::GameEvent; +use crate::protocol::wire::{DecodeError, Writer}; +use crate::surface::{EventSurface, RecordSurface}; + +/// What a service can deliver into a zone. +#[derive(Debug, Clone, PartialEq)] +pub enum ZoneInbound { + /// Remove every connection of `principal` (players leave with + /// `LeaveReason::Kicked`, observers are unsubscribed). Clients get + /// `Kick(BY_ZONE, reason)`. + Kick { + /// Verified principal to remove (a service decision, e.g. a ban). + principal: String, + /// Shown to the client. + reason: String, + }, + /// A game message for [`Zone::on_message`](crate::Zone::on_message). + Message(M), +} + +/// Outcome of a delivery. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct Delivered { + /// Players removed by a kick. + pub players_kicked: usize, + /// Observers removed by a kick. + pub observers_kicked: usize, +} + +/// The message type of a zone that takes none. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NoMessages {} + +impl GameEvent for NoMessages { + fn event_id(&self) -> u32 { + match *self {} + } + + fn encode_payload(&self, _w: &mut Writer) { + match *self {} + } + + fn decode_event(_type_id: u32, _payload: &[u8]) -> Result, DecodeError> { + Ok(None) + } + + fn event_surfaces(_records: &mut Vec) -> Vec { + Vec::new() + } +} diff --git a/distributed_game/src/input.rs b/distributed_game/src/input.rs new file mode 100644 index 000000000..55f7b8429 --- /dev/null +++ b/distributed_game/src/input.rs @@ -0,0 +1,278 @@ +//! Per-player sequenced input buffers. +//! +//! Clients number inputs with a strictly increasing sequence starting at 1. +//! The buffer keeps inputs ordered by sequence, drops duplicates and inputs at +//! or below the last processed sequence, and is bounded (overflow drops the +//! oldest queued input so latency stays bounded). The zone consumes inputs +//! during a tick with a [`ConsumePolicy`]; the highest consumed sequence +//! becomes the **ack** sent back in every Delta so a predicting client can +//! discard confirmed inputs and replay the rest (reconciliation). +//! +//! Sanitizing (clamping/validating game input) happens before buffering via +//! [`Zone::sanitize_input`](crate::Zone::sanitize_input). + +use std::collections::VecDeque; + +/// How a tick consumes queued inputs. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ConsumePolicy { + /// Oldest queued input only (one input per tick; lockstep-style). + Next, + /// Newest queued input; older queued inputs are discarded but acked. + Latest, + /// Every queued input in sequence order. + Drain, +} + +/// Outcome of offering an input to a buffer. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PushOutcome { + /// Queued. + Accepted, + /// Same sequence already queued. + Duplicate, + /// Sequence at or below the last processed sequence. + Stale, + /// Queued after dropping the oldest queued input (buffer full). + AcceptedDroppedOldest, + /// Rejected by the zone's sanitize hook. + Rejected, + /// Sender is not an admitted player. + UnknownClient, +} + +/// One buffered input. +#[derive(Debug, Clone, PartialEq)] +pub struct SequencedInput { + /// Client sequence (>= 1). + pub seq: u32, + /// Client's predicted tick when the input was sampled (informational). + pub client_tick: u32, + /// Sanitized game input. + pub input: I, +} + +/// Bounded, deduplicating, ordered input queue for one player. +#[derive(Debug, Clone)] +pub struct InputBuffer { + queue: VecDeque>, + capacity: usize, + last_processed: u32, + dropped: u64, +} + +impl InputBuffer { + /// Buffer holding at most `capacity` (>= 1) inputs. + pub fn new(capacity: usize) -> Self { + Self { + queue: VecDeque::new(), + capacity: capacity.max(1), + last_processed: 0, + dropped: 0, + } + } + + /// Highest consumed sequence (0 = none). Sent to the client as `ack_seq`. + pub fn last_processed(&self) -> u32 { + self.last_processed + } + + /// Queued input count. + pub fn len(&self) -> usize { + self.queue.len() + } + + /// True when nothing is queued. + pub fn is_empty(&self) -> bool { + self.queue.is_empty() + } + + /// Inputs dropped by overflow so far. + pub fn dropped(&self) -> u64 { + self.dropped + } + + /// Check whether `seq` would be accepted, without inserting. + pub fn precheck(&self, seq: u32) -> Option { + if seq <= self.last_processed { + return Some(PushOutcome::Stale); + } + if self.queue.iter().any(|queued| queued.seq == seq) { + return Some(PushOutcome::Duplicate); + } + None + } + + /// Insert in sequence order. + pub fn push(&mut self, seq: u32, client_tick: u32, input: I) -> PushOutcome { + if let Some(outcome) = self.precheck(seq) { + return outcome; + } + let position = self + .queue + .iter() + .position(|queued| queued.seq > seq) + .unwrap_or(self.queue.len()); + self.queue.insert( + position, + SequencedInput { + seq, + client_tick, + input, + }, + ); + if self.queue.len() > self.capacity { + self.queue.pop_front(); + self.dropped += 1; + return PushOutcome::AcceptedDroppedOldest; + } + PushOutcome::Accepted + } + + /// Consume per `policy`, advancing the ack to the highest consumed or + /// discarded sequence. + pub fn take(&mut self, policy: ConsumePolicy) -> Vec> { + let taken: Vec<_> = match policy { + ConsumePolicy::Next => self.queue.pop_front().into_iter().collect(), + ConsumePolicy::Drain => self.queue.drain(..).collect(), + ConsumePolicy::Latest => { + let latest = self.queue.pop_back(); + self.queue.clear(); + latest.into_iter().collect() + } + }; + if let Some(last) = taken.last() { + self.last_processed = self.last_processed.max(last.seq); + } + taken + } + + /// Reset the queue (keeps the ack so stale resends are still rejected). + pub fn clear(&mut self) { + self.queue.clear(); + } + + /// Start a new sequence space (a new client session numbers its inputs + /// from 1 again): clears the queue and the last processed sequence. + pub fn reset_sequence(&mut self) { + self.queue.clear(); + self.last_processed = 0; + } +} + +/// Server-side input pacing: a player earns one input credit per tick (up +/// to `max`, the burst it may bank) and spends one per consumed input, so a +/// client can never simulate faster than real time by sending more inputs, +/// while jitter bursts (several inputs in one tick after a gap) are still +/// absorbed. Pair with a client sending one input per tick (the JS SDK's +/// `InputPacer`). New players start with a full bank. +/// +/// ```ignore +/// fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { +/// for player in self.players.keys().copied().collect::>() { +/// for input in self.credits.take(ctx, player) { /* step one command frame */ } +/// } +/// } +/// fn on_leave(&mut self, _: &mut Ctx<'_, Self>, player: PlayerId, _: LeaveReason) { +/// self.credits.remove(player); +/// } +/// ``` +#[derive(Debug, Clone)] +pub struct InputCredits { + max: u32, + bank: std::collections::BTreeMap, +} + +impl InputCredits { + /// Bank at most `max` (>= 1) credits per player. + pub fn new(max: u32) -> Self { + Self { + max: max.max(1), + bank: std::collections::BTreeMap::new(), + } + } + + /// Credit ceiling. + pub fn max(&self) -> u32 { + self.max + } + + /// Credits `player` has banked (a new player has `max`). + pub fn credits(&self, player: crate::PlayerId) -> u32 { + self.bank.get(&player).copied().unwrap_or(self.max) + } + + /// Earn this tick's credit, then consume queued inputs oldest first + /// while credits last. Call once per player per tick. + pub fn take( + &mut self, + ctx: &mut crate::Ctx<'_, Z>, + player: crate::PlayerId, + ) -> Vec> { + let max = self.max; + let credits = self.bank.entry(player).or_insert(max); + *credits = (*credits + 1).min(max); + let mut out = Vec::new(); + while *credits > 0 { + let Some(input) = ctx.take_inputs(player, ConsumePolicy::Next).pop() else { + break; + }; + out.push(input); + *credits -= 1; + } + out + } + + /// Forget a player (on leave). + pub fn remove(&mut self, player: crate::PlayerId) { + self.bank.remove(&player); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dedupes_orders_and_acks() { + let mut buf = InputBuffer::new(8); + assert_eq!(buf.push(2, 0, 'b'), PushOutcome::Accepted); + assert_eq!(buf.push(1, 0, 'a'), PushOutcome::Accepted); + assert_eq!(buf.push(2, 0, 'x'), PushOutcome::Duplicate); + let next = buf.take(ConsumePolicy::Next); + assert_eq!(next[0].input, 'a'); + assert_eq!(buf.last_processed(), 1); + assert_eq!(buf.push(1, 0, 'z'), PushOutcome::Stale); + assert_eq!(buf.take(ConsumePolicy::Drain).len(), 1); + assert_eq!(buf.last_processed(), 2); + } + + #[test] + fn latest_discards_but_acks_older() { + let mut buf = InputBuffer::new(8); + for seq in 1..=5 { + buf.push(seq, 0, seq); + } + let taken = buf.take(ConsumePolicy::Latest); + assert_eq!(taken.len(), 1); + assert_eq!(taken[0].input, 5); + assert_eq!(buf.last_processed(), 5); + assert!(buf.is_empty()); + } + + #[test] + fn bounded_drops_oldest() { + let mut buf = InputBuffer::new(2); + buf.push(1, 0, ()); + buf.push(2, 0, ()); + assert_eq!(buf.push(3, 0, ()), PushOutcome::AcceptedDroppedOldest); + assert_eq!(buf.len(), 2); + assert_eq!(buf.dropped(), 1); + let seqs: Vec<_> = buf + .take(ConsumePolicy::Drain) + .iter() + .map(|i| i.seq) + .collect(); + assert_eq!(seqs, vec![2, 3]); + } +} diff --git a/distributed_game/src/interest.rs b/distributed_game/src/interest.rs new file mode 100644 index 000000000..7f10432dd --- /dev/null +++ b/distributed_game/src/interest.rs @@ -0,0 +1,191 @@ +//! Interest management: a uniform spatial grid and circular views. +//! +//! Each connected client has a [`View`] (center + radius) on the zone's 2D +//! interest plane (games in 3D usually map x/z). An entity *enters* a view +//! when within `radius` and *leaves* only beyond `radius * (1 + leave_margin)` +//! (hysteresis prevents create/remove flicker at the edge). Entities marked +//! global are visible to everyone regardless of distance. +//! +//! [`UpdateRates`] thin out updates by distance: a known entity far from +//! the view centre is updated only every few patches (creates, removes and +//! global entities are never delayed). + +use std::collections::HashMap; + +/// A client's area of interest. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct View { + /// Center x. + pub x: f32, + /// Center y. + pub y: f32, + /// Enter radius. + pub radius: f32, +} + +impl View { + /// View at (x, y) with `radius`. + pub fn new(x: f32, y: f32, radius: f32) -> Self { + Self { x, y, radius } + } + + /// Distance from the view center. + pub fn distance(&self, x: f32, y: f32) -> f32 { + ((x - self.x).powi(2) + (y - self.y).powi(2)).sqrt() + } +} + +/// Grid, hysteresis and update-rate settings. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct InterestConfig { + /// Grid cell edge length (world units); ~view radius / 2 works well. + pub cell_size: f32, + /// Extra fraction of the radius before a known entity leaves the view. + pub leave_margin: f32, + /// Distance-based update rates ([`UpdateRates::every_patch`] turns them + /// off). + pub update_rates: UpdateRates, +} + +impl Default for InterestConfig { + fn default() -> Self { + Self { + cell_size: 16.0, + leave_margin: 0.1, + update_rates: UpdateRates::default(), + } + } +} + +/// Distance-based update rates (level of detail), as fractions of the view +/// radius. A changed entity the client already has is an update candidate +/// every patch within `near × radius`, every `mid_every`-th patch within +/// `mid × radius` and every `far_every`-th patch beyond. Which patches is +/// staggered by entity id, so a far entity's latest state arrives at most +/// `far_every - 1` patches late (budget permitting; keep `mid_every` a +/// divisor of `far_every`). Creates, removes, global entities and kinds +/// marked `#[replicated(.., every_patch)]` are never delayed. The default +/// is `near = 0.5`, `mid = 0.8`, every 2nd and every 4th patch: at 20 +/// patches/s, 10 Hz past half the radius and 5 Hz near its edge. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct UpdateRates { + /// Fraction of the radius updated every patch. + pub near: f32, + /// Fraction of the radius updated every `mid_every`-th patch. + pub mid: f32, + /// Patch interval between `near` and `mid` (1 = every patch). + pub mid_every: u32, + /// Patch interval beyond `mid` (1 = every patch). + pub far_every: u32, +} + +impl UpdateRates { + /// Every entity every patch (no distance-based rates). + pub fn every_patch() -> Self { + Self { + near: f32::INFINITY, + mid: f32::INFINITY, + mid_every: 1, + far_every: 1, + } + } + + /// Patch interval at `distance` from a view of `radius`. + pub fn interval(&self, distance: f32, radius: f32) -> u32 { + if distance <= self.near * radius { + 1 + } else if distance <= self.mid * radius { + self.mid_every.max(1) + } else { + self.far_every.max(1) + } + } +} + +impl Default for UpdateRates { + fn default() -> Self { + Self { + near: 0.5, + mid: 0.8, + mid_every: 2, + far_every: 4, + } + } +} + +/// Uniform grid of entity indices. +#[derive(Debug, Clone)] +pub struct SpatialGrid { + cell: f32, + cells: HashMap<(i32, i32), Vec>, +} + +impl SpatialGrid { + /// Empty grid with `cell_size` (clamped to > 0). + pub fn new(cell_size: f32) -> Self { + Self { + cell: if cell_size > 0.0 { cell_size } else { 1.0 }, + cells: HashMap::new(), + } + } + + fn key(&self, x: f32, y: f32) -> (i32, i32) { + ( + (x / self.cell).floor() as i32, + (y / self.cell).floor() as i32, + ) + } + + /// Remove everything. + pub fn clear(&mut self) { + self.cells.clear(); + } + + /// Empty it for the next patch with cells of `cell_size`: the cells + /// occupied since the last reset keep their allocation (the others are + /// dropped, so a moving crowd does not grow the map). + pub(crate) fn reset(&mut self, cell_size: f32) { + let cell = Self::new(cell_size).cell; + if cell != self.cell { + self.cell = cell; + self.cells.clear(); + return; + } + self.cells.retain(|_, items| { + let occupied = !items.is_empty(); + items.clear(); + occupied + }); + } + + /// Index an item at (x, y). + pub fn insert(&mut self, item: u32, x: f32, y: f32) { + let key = self.key(x, y); + self.cells.entry(key).or_default().push(item); + } + + /// Items in cells overlapping the circle's bounding box (caller filters + /// by exact distance). + pub fn query(&self, x: f32, y: f32, radius: f32, out: &mut Vec) { + let r = radius.max(0.0); + let (x0, y0) = self.key(x - r, y - r); + let (x1, y1) = self.key(x + r, y + r); + // Large views degrade to scanning occupied cells. + let span = (i64::from(x1) - i64::from(x0) + 1) * (i64::from(y1) - i64::from(y0) + 1); + if span > self.cells.len() as i64 { + for (&(cx, cy), items) in &self.cells { + if (x0..=x1).contains(&cx) && (y0..=y1).contains(&cy) { + out.extend_from_slice(items); + } + } + return; + } + for cx in x0..=x1 { + for cy in y0..=y1 { + if let Some(items) = self.cells.get(&(cx, cy)) { + out.extend_from_slice(items); + } + } + } + } +} diff --git a/distributed_game/src/lease.rs b/distributed_game/src/lease.rs new file mode 100644 index 000000000..f1122aea6 --- /dev/null +++ b/distributed_game/src/lease.rs @@ -0,0 +1,292 @@ +//! Entity leases between zones: one zone lends an entity (a mob chasing a +//! player through a doorway) to the zone next door without ever having it +//! live in both, and without losing it to a dropped message or a crashed +//! or sleeping zone. +//! +//! The *home* zone keeps the entity [`Lent`] (hidden there, its slot +//! reserved); the zone it went to keeps it [`Held`] while the lease holds. +//! The holder beats every [`LeaseTimings::beat`] ticks; the home answers +//! each beat with a renewal, or a recall when it no longer lends that +//! transfer. A [`Held`] entity whose last renewal is older than +//! [`LeaseTimings::lease`] lapses (the holder drops it); a [`Lent`] one +//! that has not been heard from for [`LeaseTimings::grace`] comes back +//! home. Grace is longer than the lease, so the holder always lets go +//! first: a lost message, or either zone stopping, costs the entity at +//! most the grace, never the entity. +//! +//! This module only keeps the state and the clock; the messages are the +//! game's own ([`Ctx::send_zone`](crate::Ctx::send_zone), typed by +//! [`Zone::Message`](crate::Zone::Message)). A game defines one per step: +//! +//! | Message | From → to | Receiver | +//! |---------|-----------|----------| +//! | arrive (the entity's state) | home → holder | [`LeaseTimings::hold`]; refuse with a recall | +//! | beat | holder → home | [`Lent::heard`] and renew, or recall if not lent | +//! | renew | home → holder | [`Held::renew`] | +//! | recall | either way | drop the [`Held`] / bring the [`Lent`] back | +//! | returned / ended | holder → home | the entity is back (or gone): end the [`Lent`] | +//! +//! Match every message to its lease with [`Lent::is`] / [`Held::is`] +//! (sending zone and [`TransferId`]); anything else is stale and ignored. +//! The zone-to-zone transport already drops repeats of one message, but an +//! arrive can be resent after a restart: check [`Held::is`] before taking +//! it twice. A zone that hibernates keeps its lent entities' zone and +//! transfer and, on restore, lends them again from now +//! ([`LeaseTimings::lend`]): their visitor's next beat renews them, or they +//! come back after a fresh grace. + +/// Names one lending of one entity: unique per lending zone across its +/// activations, and at most 2^53 − 1 (message codecs carry it exactly as a +/// JavaScript number). +pub type TransferId = u64; + +/// The largest integer a JavaScript number carries exactly. +const SAFE_INT: u64 = (1 << 53) - 1; + +/// Hands out [`TransferId`]s for one zone activation. +#[derive(Debug, Clone, Default)] +pub struct TransferIds { + count: u64, +} + +impl TransferIds { + /// The next id, from the activation's + /// [`boot_epoch`](crate::Ctx::boot_epoch) (so a restarted zone never + /// reuses one its previous activation handed out). + pub fn next(&mut self, boot_epoch: u64) -> TransferId { + self.count += 1; + ((boot_epoch << 20) ^ self.count) & SAFE_INT + } +} + +/// How often a holder beats and how long each side waits (ticks of each +/// zone's own clock). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct LeaseTimings { + beat: u64, + lease: u64, + grace: u64, +} + +impl LeaseTimings { + /// Beat every `beat` ticks; a holder keeps the entity `lease` ticks past + /// its last renewal; the home takes it back `grace` ticks after the last + /// beat it heard. `lease - beat` is the time a renewal has to arrive, + /// and `grace - lease` the time a renewal may take on the way (plus any + /// difference in the zones' tick rates). Make `lease` at least three + /// beats: with two, one lost beat (or a home restarting) lapses the + /// lease, since the next renewal lands a round trip after the beat. + /// + /// # Panics + /// Unless `0 < beat < lease < grace` (a compile error in a `const`). + pub const fn new(beat: u64, lease: u64, grace: u64) -> Self { + assert!(beat > 0, "a lease needs a beat"); + assert!(lease > beat, "a lease must outlast a beat"); + assert!(grace > lease, "the home's grace must outlast the lease"); + Self { beat, lease, grace } + } + + /// Ticks between beats. + pub const fn beat(&self) -> u64 { + self.beat + } + + /// Ticks a holder keeps the entity past its last renewal. + pub const fn lease(&self) -> u64 { + self.lease + } + + /// Ticks the home waits after the last beat before taking it back. + pub const fn grace(&self) -> u64 { + self.grace + } + + /// The home side of lending an entity to zone `to` at `tick`. + pub fn lend(&self, to: impl Into, transfer: TransferId, tick: u64) -> Lent { + Lent { + to: to.into(), + transfer, + grace: self.grace, + heard: tick, + } + } + + /// The holder's side of an entity zone `from` lent it at `tick`. + pub fn hold(&self, from: impl Into, transfer: TransferId, tick: u64) -> Held { + Held { + from: from.into(), + transfer, + beat: self.beat, + lease: self.lease, + until: tick + self.lease, + next_beat: tick + self.beat, + } + } +} + +/// An entity this zone lent out (home side). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Lent { + to: String, + transfer: TransferId, + grace: u64, + heard: u64, +} + +impl Lent { + /// The zone holding it. + pub fn to(&self) -> &str { + &self.to + } + + /// Its transfer. + pub fn transfer(&self) -> TransferId { + self.transfer + } + + /// Whether a message from zone `from` about `transfer` is about this one. + pub fn is(&self, from: &str, transfer: TransferId) -> bool { + self.to == from && self.transfer == transfer + } + + /// Its holder beat at `tick` (answer with a renewal). + pub fn heard(&mut self, tick: u64) { + self.heard = self.heard.max(tick); + } + + /// Not heard from for longer than the grace: take it back. + pub fn overdue(&self, tick: u64) -> bool { + tick > self.heard + self.grace + } +} + +/// An entity another zone lent this one (holder side). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Held { + from: String, + transfer: TransferId, + beat: u64, + lease: u64, + until: u64, + next_beat: u64, +} + +/// What a [`Held`] lease needs this tick. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Hold { + /// Still held; nothing to send. + Held, + /// Still held; send its home a beat. + Beat, + /// Not renewed in time: drop it (its home may have taken it back). + Lapsed, +} + +impl Held { + /// Its home zone. + pub fn from(&self) -> &str { + &self.from + } + + /// Its transfer. + pub fn transfer(&self) -> TransferId { + self.transfer + } + + /// Whether a message from zone `from` about `transfer` is about this one. + pub fn is(&self, from: &str, transfer: TransferId) -> bool { + self.from == from && self.transfer == transfer + } + + /// Its home renewed it at `tick`. + pub fn renew(&mut self, tick: u64) { + self.until = self.until.max(tick + self.lease); + } + + /// Once a tick: lapse it, or say a beat is due. + pub fn poll(&mut self, tick: u64) -> Hold { + if tick > self.until { + Hold::Lapsed + } else if tick >= self.next_beat { + self.next_beat = tick + self.beat; + Hold::Beat + } else { + Hold::Held + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const T: LeaseTimings = LeaseTimings::new(30, 60, 120); + + #[test] + #[should_panic(expected = "grace must outlast")] + fn grace_must_outlast_the_lease() { + LeaseTimings::new(30, 60, 60); + } + + #[test] + #[should_panic(expected = "outlast a beat")] + fn a_lease_must_outlast_a_beat() { + LeaseTimings::new(30, 30, 120); + } + + #[test] + fn a_held_entity_beats_and_lapses_without_renewals() { + let mut held = T.hold("pit.0.0", 7, 100); + assert_eq!(held.poll(129), Hold::Held); + assert_eq!(held.poll(130), Hold::Beat); + assert_eq!(held.poll(131), Hold::Held); + assert_eq!(held.poll(160), Hold::Beat); + assert_eq!(held.poll(161), Hold::Lapsed); + } + + #[test] + fn renewals_keep_it_and_an_old_one_never_shortens_the_lease() { + let mut held = T.hold("pit.0.0", 7, 0); + held.renew(50); + held.renew(10); + assert_eq!(held.poll(110), Hold::Beat); + assert_eq!(held.poll(111), Hold::Lapsed); + } + + #[test] + fn the_holder_always_lets_go_before_the_home_takes_it_back() { + // The home hears the last beat at 200; its renewal takes `d` ticks + // to arrive. With d below grace − lease the holder lapses first. + for d in 0..(T.grace() - T.lease()) { + let mut lent = T.lend("pit.1.0", 9, 0); + let mut held = T.hold("pit.0.0", 9, 0); + lent.heard(200); + held.renew(200 + d); + let lapsed = (200..).find(|&t| held.poll(t) == Hold::Lapsed).unwrap(); + let back = (200..).find(|&t| lent.overdue(t)).unwrap(); + assert!(lapsed < back, "d={d}: lapsed {lapsed}, back {back}"); + } + } + + #[test] + fn messages_match_by_zone_and_transfer() { + let lent = T.lend("pit.1.0", 9, 0); + assert!(lent.is("pit.1.0", 9)); + assert!(!lent.is("pit.1.0", 8)); + assert!(!lent.is("pit.0.1", 9)); + let held = T.hold("pit.0.0", 9, 0); + assert!(held.is("pit.0.0", 9)); + assert!(!held.is("pit.1.0", 9)); + } + + #[test] + fn transfer_ids_differ_across_activations_and_stay_safe_integers() { + let mut a = TransferIds::default(); + let mut b = TransferIds::default(); + let epoch = u64::MAX - 3; + let first = a.next(epoch); + assert!(first <= SAFE_INT); + assert_ne!(first, a.next(epoch)); + assert_ne!(first, b.next(epoch + 1)); + } +} diff --git a/distributed_game/src/lib.rs b/distributed_game/src/lib.rs new file mode 100644 index 000000000..da29671af --- /dev/null +++ b/distributed_game/src/lib.rs @@ -0,0 +1,185 @@ +//! Authoritative multiplayer zone runtime for `distributed`. +//! +//! - [`Zone`] (implemented by the game) + [`ZoneHost`] (runtime): lifecycle +//! hooks, capacity, per-zone timers, fixed timestep with catch-up cap, +//! activity tiers (Hot / Idle / Dormant), sequenced input buffers with acks. +//! - Determinism: injectable [`Clock`] and per-zone seeded [`ZoneRng`]. +//! - Durable outcomes: zones emit [`Fact`]s during a tick; a [`FactSink`] +//! commits them asynchronously and settlements come back on later ticks. +//! The `cell` feature has the helpers that dispatch them into a +//! `distributed` `AggregateCell` idempotently with a server-built Session +//! ([`cell`]). +//! - Replication: an [`EntitySchema`] shipped in Welcome, per-client deltas +//! against last-sent state, spatial interest and a byte budget with +//! priority accumulation. Wire format: [`protocol`] / `PROTOCOL.md`. +//! - Transport (`net` feature): axum WebSocket server hosting many zones +//! with HMAC-signed ticket admission ([`net`]). +//! - celld (`celld-zone` feature, wasm32): each zone is a celld Durable +//! Object; celld places, forwards, hibernates and recovers it +//! ([`celld_zone`]). +//! +//! - Authoring derives (re-exported from `distributed_game_macros`): +//! `#[derive(Replicated)]` views generate a kind's schema and field +//! encoding from one struct ([`schema!`], [`WorldView::add`]); +//! `#[derive(GameInput)]` generates the input codec and sanitize; +//! `#[derive(GameEvent)]` / `#[derive(GameRecord)]` give events stable ids +//! and typed binary payloads ([`Ctx::send`], [`Ctx::broadcast`]); +//! `#[derive(FactCommand)]` binds a cell command input to its command name +//! ([`Ctx::emit`]). The derives also describe the zone's +//! [`GameSurface`](surface::GameSurface), from which `distributed +//! game-client` generates typed TypeScript. +//! - Client prediction ([`prediction`]): `#[predict]` declares a zone's +//! predicted step once in Rust; `distributed game-wasm` compiles it to +//! WebAssembly (binary ABI, no JSON) and the generated client predicts +//! with it. +//! - Shared client logic and data ([`pure`], [`GameSurface::constant`](surface::GameSurface::constant)): +//! `#[game_pure]` compiles any other pure function (procedural content, +//! …) into the same module with a typed generated wrapper; constants and +//! standalone records are emitted as generated TypeScript data / codecs. +//! +//! Physics is out of scope: games bring their own and run it in `on_tick`. +//! +//! - World structure ([`world`]): zone directory and consistent-hash ring, +//! fenced ownership, hibernation snapshots, zone hierarchy with tier-up +//! events, handoff with carried state ([`handoff`]) and the content +//! barrier / safe-room policy. +//! - Zone to zone ([`zone_message`], [`lease`]): typed messages between +//! running zones with verified principals, and leases for lending an +//! entity (a chasing mob) to the zone next door without losing or +//! duplicating it. +//! +//! # Extension seams (later phases) +//! Metrics hook [`AdvanceReport`] and [`replication::DeltaStats`]; plain +//! work counts in [`WorkCounters`] ([`work`]). + +#![warn(missing_docs)] + +// Lets the authoring derives' `::distributed_game::…` paths resolve inside +// this crate too. +extern crate self as distributed_game; + +#[cfg(feature = "ticket")] +pub mod admission; +pub mod authoring; +#[cfg(feature = "bots")] +pub mod bots; +#[cfg(feature = "cell")] +pub mod cell; +#[cfg(feature = "celld")] +pub mod celld; +#[cfg(feature = "celld-zone")] +pub mod celld_zone; +pub mod claims; +pub mod clock; +pub mod codec; +pub mod collide; +#[cfg(feature = "cell")] +pub mod command_sink; +pub mod entity; +pub mod facts; +pub mod handoff; +pub mod host; +pub mod inbox; +pub mod input; +pub mod interest; +pub mod lease; +pub mod lifecycle; +#[cfg(feature = "metrics")] +pub mod metrics; +#[cfg(feature = "net")] +pub mod net; +pub mod netsim; +pub mod prediction; +pub mod protocol; +pub mod pure; +pub mod replay; +pub mod replication; +pub mod rewind; +pub mod rng; +pub mod schema; +pub mod stamp; +pub mod surface; +/// Signed admission tickets (also `net::ticket`); usable without the axum +/// server, e.g. by a celld zone host on wasm32. +#[cfg(feature = "ticket")] +#[path = "net/ticket.rs"] +pub mod ticket; +pub mod timers; +pub mod timestep; +pub mod work; +pub mod world; +pub mod zone; +pub mod zone_message; + +#[cfg(test)] +mod test_zone; + +pub use authoring::{GameEvent, GameInput, Pushed, Replicated}; +pub use claims::{ExtensionError, ExtensionSchema, TicketExtension, TicketExtensions}; +pub use clock::{Clock, ManualClock, SystemClock}; +pub use codec::{Wire, WireType}; +pub use collide::{Collider, Colliders, Ray, RayHit, Target}; +/// Authoring derives (see the crate docs and README). +pub use distributed_game_macros::{ + game_pure, predict, FactCommand, GameEvent, GameInput, GameRecord, Replicated, TicketExtension, +}; +pub use entity::{Entities, Entity, EntityCollection, EntityId, Project}; +#[cfg(feature = "runtime")] +pub use facts::spawn_fact_worker; +pub use facts::{ + fact_channel, fact_key, BoxFuture, EmitError, Fact, FactBatchSink, FactCommand, FactError, + FactFeed, FactOutcome, FactQueue, FactReceipt, FactSettlement, FactSink, MemoryFactSink, + RetryPolicy, SettlementScript, +}; +pub use handoff::{HandoffError, HandoffRequest, Transfer}; +pub use lease::{Held, LeaseTimings, Lent, TransferId, TransferIds}; +pub use host::{ + AdvanceReport, Ctx, FrameStats, HostConfig, JoinError, Joined, Outbound, Outcome, Stimulus, + ZoneHost, +}; +pub use inbox::{Delivered, NoMessages, ZoneInbound}; +pub use input::{ConsumePolicy, InputBuffer, InputCredits, PushOutcome, SequencedInput}; +pub use interest::{InterestConfig, UpdateRates, View}; +pub use prediction::{PredictContext, PredictStep}; +pub use protocol::{ClientMessage, ClientMirror, Origin, Role, ServerMessage, PROTOCOL_VERSION}; +pub use pure::GamePure; +pub use replay::{replay, Recording}; +pub use replication::{EntityState, WorldView}; +pub use rewind::{Historic, HitQuery, Rewind, RewindConfig, RewindFrame, ShotTiming}; +pub use rng::{Fnv64, ZoneRng}; +pub use schema::{Correction, EntitySchema, FieldType, FieldValue, KindDef}; +pub use stamp::{stamp_metadata, FactStamp}; +pub use surface::GameSurface; +pub use timers::TimerId; +pub use timestep::FixedTimestep; +pub use work::WorkCounters; +pub use world::{BarrierMode, ChildEvent, FreezeState, StalePolicy}; +pub use zone::{ + Admission, ClientId, JoinRequest, LeaveReason, ObserverId, ObserverInfo, PlayerId, PlayerInfo, + TicketClaims, Tier, Viewer, Zone, +}; +pub use zone_message::{VerifiedPrincipal, ZoneEnvelope, ZoneMessageError, ZoneSender}; + +/// Paths used by derive-generated code. Not public API. +#[doc(hidden)] +pub mod __private { + pub use crate::authoring::{decode_whole, records_of}; + pub use crate::codec::{ + special, ButtonBits, EntityField, InputField, LongString, QuantizedF32, Wire, WireType, + }; + #[cfg(target_arch = "wasm32")] + pub use crate::prediction::wasm_export; + pub use crate::protocol::wire::{DecodeError, Reader, Writer}; + #[cfg(target_arch = "wasm32")] + pub use crate::pure::wasm_export as pure_wasm_export; + pub use crate::schema::{Correction, FieldType, FieldValue, KindDef}; + pub use crate::surface::{ + EventPayload, EventSurface, InputSurface, PayloadField, RecordSurface, + }; + pub use serde; + pub use std; +} + +#[doc = include_str!("../README.md")] +#[cfg(doctest)] +pub struct ReadmeDoctests; diff --git a/distributed_game/src/lifecycle.rs b/distributed_game/src/lifecycle.rs new file mode 100644 index 000000000..f51c2f055 --- /dev/null +++ b/distributed_game/src/lifecycle.rs @@ -0,0 +1,209 @@ +//! Player lifecycle facts emitted by the host itself. +//! +//! With [`HostConfig::lifecycle_facts`](crate::HostConfig::lifecycle_facts) +//! on, every player transition becomes a durable fact on the zone's +//! [`FactQueue`](crate::FactQueue), bound to the player's **verified +//! principal** (never to anything a zone or client wrote): +//! +//! | Fact | Command | When | +//! |---|---|---| +//! | [`PlayerJoined`] | [`PLAYER_JOINED`] | admitted with a ticket, a fresh ticket for a held slot (rejoin) or a transfer ticket (handoff) | +//! | [`ConnectionLost`] | [`CONNECTION_LOST`] | the connection dropped (or was told to reload); the reconnect grace starts | +//! | [`PlayerReconnected`] | [`PLAYER_RECONNECTED`] | a reconnect token resumed the slot within the grace | +//! | [`PlayerDisconnected`] | [`PLAYER_DISCONNECTED`] | the grace expired; the slot is gone | +//! | [`PlayerLeft`] | [`PLAYER_LEFT`] | the slot was removed for any other [`LeftReason`] | +//! +//! Every slot ends with exactly one of [`PlayerLeft`] / [`PlayerDisconnected`]. +//! +//! **Keys** are `"{command}:{zone}:{boot_epoch}:p{slot}:{n}"` where `n` +//! counts the slot's transitions: computed once at emission (a retry keeps +//! it), never repeated within an activation, and distinct after a restart +//! (new boot epoch). **Order** per principal follows emission: the facts +//! travel in the principal's lane of the fact worker (also with +//! `max_concurrent_commits > 1`), and when the queue is full the host keeps +//! them in a backlog and sends them, in order, as capacity frees up — a +//! lifecycle fact is never dropped for backpressure. A `PlayerJoined` is +//! queued before anything the zone emits in `on_join`, a `PlayerLeft` after +//! `on_leave`. A handoff departure is stamped with the time in the transfer +//! ticket, so the target's `PlayerJoined` sorts after the source's +//! `PlayerLeft` ([`FactStamp::emission_order`](crate::FactStamp::emission_order)). + +use serde::{Deserialize, Serialize}; + +use crate::zone::LeaveReason; + +/// Command of [`PlayerJoined`]. +pub const PLAYER_JOINED: &str = "zone.player_joined"; +/// Command of [`PlayerLeft`]. +pub const PLAYER_LEFT: &str = "zone.player_left"; +/// Command of [`ConnectionLost`]. +pub const CONNECTION_LOST: &str = "zone.connection_lost"; +/// Command of [`PlayerReconnected`]. +pub const PLAYER_RECONNECTED: &str = "zone.player_reconnected"; +/// Command of [`PlayerDisconnected`]. +pub const PLAYER_DISCONNECTED: &str = "zone.player_disconnected"; + +/// Every lifecycle command, in the table's order. +pub const LIFECYCLE_COMMANDS: [&str; 5] = [ + PLAYER_JOINED, + CONNECTION_LOST, + PLAYER_RECONNECTED, + PLAYER_DISCONNECTED, + PLAYER_LEFT, +]; + +/// How a player entered the zone. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum JoinVia { + /// An admission ticket for a new slot. + Ticket, + /// A fresh ticket for a slot the principal already held (page reload, + /// second tab). + Rejoin, + /// A handoff transfer ticket. + Handoff, +} + +/// Player admitted. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, crate::FactCommand)] +#[fact(command = PLAYER_JOINED)] +pub struct PlayerJoined { + /// Zone id. + pub zone: String, + /// Ticket, rejoin or handoff. + pub via: JoinVia, + /// Source zone of a handoff. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub from_zone: Option, +} + +/// Why a slot was removed (a grace expiry is [`PlayerDisconnected`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum LeftReason { + /// The client left gracefully. + Left, + /// Kicked by the zone or the server (incl. the zone inbox). + Kicked, + /// Moved to another zone. + Handoff, + /// The zone was disposed (shutdown, hibernation with players is + /// impossible, ownership loss). + Disposed, +} + +impl LeftReason { + /// The fact reason for a host leave reason (`None` for `Disconnected`, + /// which is its own fact, and `Rejoined`, which keeps the slot). + pub fn from_leave(reason: LeaveReason) -> Option { + match reason { + LeaveReason::Left => Some(Self::Left), + LeaveReason::Kicked => Some(Self::Kicked), + LeaveReason::Handoff => Some(Self::Handoff), + LeaveReason::Disposed => Some(Self::Disposed), + LeaveReason::Disconnected | LeaveReason::Rejoined => None, + } + } +} + +/// Slot removed (terminal). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, crate::FactCommand)] +#[fact(command = PLAYER_LEFT)] +pub struct PlayerLeft { + /// Zone id. + pub zone: String, + /// Why. + pub reason: LeftReason, +} + +/// What ended the connection. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum LostCause { + /// The transport dropped. + Dropped, + /// The server told the client to reload its content (`Kick(RELOAD)`). + Reload, +} + +/// Connection lost; the slot is kept for `grace_ms`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, crate::FactCommand)] +#[fact(command = CONNECTION_LOST)] +pub struct ConnectionLost { + /// Zone id. + pub zone: String, + /// Reconnect grace (ms). + pub grace_ms: u64, + /// Dropped or told to reload. + pub cause: LostCause, +} + +/// Slot resumed with a reconnect token. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, crate::FactCommand)] +#[fact(command = PLAYER_RECONNECTED)] +pub struct PlayerReconnected { + /// Zone id. + pub zone: String, +} + +/// The reconnect grace expired; the slot is gone (terminal). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, crate::FactCommand)] +#[fact(command = PLAYER_DISCONNECTED)] +pub struct PlayerDisconnected { + /// Zone id. + pub zone: String, +} + +/// Any lifecycle fact input, decoded from a [`Fact`](crate::Fact) or +/// [`FactSettlement`](crate::FactSettlement) by command name. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Lifecycle { + /// [`PlayerJoined`]. + Joined(PlayerJoined), + /// [`ConnectionLost`]. + ConnectionLost(ConnectionLost), + /// [`PlayerReconnected`]. + Reconnected(PlayerReconnected), + /// [`PlayerDisconnected`]. + Disconnected(PlayerDisconnected), + /// [`PlayerLeft`]. + Left(PlayerLeft), +} + +impl Lifecycle { + /// Decode `input` of `command`; `None` for other commands or a + /// malformed input. + pub fn decode(command: &str, input: &serde_json::Value) -> Option { + let input = input.clone(); + Some(match command { + PLAYER_JOINED => Self::Joined(serde_json::from_value(input).ok()?), + CONNECTION_LOST => Self::ConnectionLost(serde_json::from_value(input).ok()?), + PLAYER_RECONNECTED => Self::Reconnected(serde_json::from_value(input).ok()?), + PLAYER_DISCONNECTED => Self::Disconnected(serde_json::from_value(input).ok()?), + PLAYER_LEFT => Self::Left(serde_json::from_value(input).ok()?), + _ => return None, + }) + } + + /// Decode a fact. + pub fn of(fact: &crate::Fact) -> Option { + Self::decode(fact.command(), fact.input()) + } + + /// Zone id. + pub fn zone(&self) -> &str { + match self { + Self::Joined(f) => &f.zone, + Self::ConnectionLost(f) => &f.zone, + Self::Reconnected(f) => &f.zone, + Self::Disconnected(f) => &f.zone, + Self::Left(f) => &f.zone, + } + } + + /// True for the terminal facts (the slot is gone). + pub fn is_terminal(&self) -> bool { + matches!(self, Self::Disconnected(_) | Self::Left(_)) + } +} diff --git a/distributed_game/src/metrics.rs b/distributed_game/src/metrics.rs new file mode 100644 index 000000000..f1955ba92 --- /dev/null +++ b/distributed_game/src/metrics.rs @@ -0,0 +1,728 @@ +//! Per-zone Prometheus metrics (`metrics` feature, no dependencies). +//! +//! Why not the core `distributed::metrics` registry: that registry is a +//! deliberately *fixed* set of framework families with typed keys behind a +//! process-global `OnceLock`, and `distributed_game` does not depend on +//! `distributed` at all outside the `cell` feature. Game metrics need an +//! instance-scoped registry (one per [`GameServer`](crate::net::GameServer), +//! parallel test servers) and a zone label, so this module renders its own +//! Prometheus text (exposition format 0.0.4). Both expositions can be served +//! side by side; family names are prefixed `distributed_game_`. +//! +//! **Cardinality guard.** Zone ids are unbounded, so only the first +//! [`GameMetrics::max_zone_labels`] live zones get their own `zone` label; +//! every other zone is folded into `zone="_other"` (counters and histograms +//! accumulate there, gauges are summed at render time). When a zone stops +//! ([`GameMetrics::forget_zone`]) its series are dropped and its label slot +//! is freed. Series count is therefore bounded by +//! `(max_zone_labels + 1) × families × fixed label values`. Other labels +//! (`tier`, `outcome`) have fixed value sets. Principals and player ids are +//! never labels. +//! +//! Families: +//! +//! | Name | Type | Labels | +//! |---|---|---| +//! | `distributed_game_zones` | gauge | – | +//! | `distributed_game_zone_tick_duration_seconds` | histogram | zone | +//! | `distributed_game_zone_ticks_total` | counter | zone | +//! | `distributed_game_zone_ticks_dropped_total` | counter | zone | +//! | `distributed_game_zone_tier` | gauge (one-hot) | zone, tier | +//! | `distributed_game_zone_players` / `_observers` / `_entities` | gauge | zone | +//! | `distributed_game_zone_inputs_total` | counter | zone, outcome | +//! | `distributed_game_zone_patches_total` | counter | zone | +//! | `distributed_game_zone_delta_bytes` | histogram (per Delta frame) | zone | +//! | `distributed_game_zone_delta_bytes_total` | counter | zone | +//! | `distributed_game_zone_delta_deferred_total` | counter | zone | +//! | `distributed_game_zone_facts_pending` | gauge | zone | +//! | `distributed_game_zone_facts_settled_total` | counter | zone, outcome | +//! | `distributed_game_hibernation_saves_total` | counter | outcome (`saved`, `stale`, `error`) | +//! | `distributed_game_activations_refused_total` | counter | reason (`not_found`, `unavailable`) | + +use crate::facts::FactOutcome; +use crate::host::{AdvanceReport, ZoneHost}; +use crate::input::PushOutcome; +use crate::zone::{Tier, Zone}; +use std::collections::BTreeMap; +use std::fmt::Write as _; +use std::sync::Mutex; + +/// Label for zones beyond the cardinality budget. +pub const OTHER_ZONE: &str = "_other"; + +const TICK_BUCKETS: [f64; 12] = [ + 0.000_05, 0.000_1, 0.000_25, 0.000_5, 0.001, 0.002_5, 0.005, 0.01, 0.016, 0.033, 0.05, 0.1, +]; +const BYTE_BUCKETS: [f64; 10] = [ + 16.0, 64.0, 128.0, 256.0, 512.0, 1024.0, 2048.0, 4096.0, 16384.0, 65536.0, +]; + +/// Input outcome label values (fixed set). +pub const INPUT_OUTCOMES: [&str; 8] = [ + "accepted", + "dropped_oldest", + "duplicate", + "stale", + "rejected", + "unknown_client", + "rate_limited", + "frozen", +]; + +fn input_label(outcome: PushOutcome) -> &'static str { + match outcome { + PushOutcome::Accepted => "accepted", + PushOutcome::AcceptedDroppedOldest => "dropped_oldest", + PushOutcome::Duplicate => "duplicate", + PushOutcome::Stale => "stale", + PushOutcome::Rejected => "rejected", + PushOutcome::UnknownClient => "unknown_client", + } +} + +#[derive(Debug, Clone)] +struct Histogram { + bounds: &'static [f64], + counts: Vec, + sum: f64, + count: u64, +} + +impl Histogram { + fn new(bounds: &'static [f64]) -> Self { + Self { + bounds, + counts: vec![0; bounds.len()], + sum: 0.0, + count: 0, + } + } + + fn observe(&mut self, v: f64) { + for (bound, count) in self.bounds.iter().zip(self.counts.iter_mut()) { + if v <= *bound { + *count += 1; + } + } + self.sum += v; + self.count += 1; + } +} + +/// Monotonic per-zone series. +#[derive(Debug, Clone)] +struct Counters { + tick_duration: Histogram, + ticks: u64, + ticks_dropped: u64, + inputs: BTreeMap<&'static str, u64>, + patches: u64, + delta_bytes: Histogram, + delta_bytes_total: u64, + delta_deferred: u64, + facts_committed: u64, + facts_failed: u64, +} + +impl Default for Counters { + fn default() -> Self { + Self { + tick_duration: Histogram::new(&TICK_BUCKETS), + ticks: 0, + ticks_dropped: 0, + inputs: BTreeMap::new(), + patches: 0, + delta_bytes: Histogram::new(&BYTE_BUCKETS), + delta_bytes_total: 0, + delta_deferred: 0, + facts_committed: 0, + facts_failed: 0, + } + } +} + +#[derive(Debug, Clone, Copy, Default)] +struct Gauges { + tier: Option, + players: usize, + observers: usize, + entities: usize, + facts_pending: usize, +} + +#[derive(Debug, Default)] +struct ZoneSeries { + labeled: bool, + counters: Counters, + gauges: Gauges, +} + +#[derive(Debug, Default)] +struct State { + zones: BTreeMap, + labeled: usize, + other: Counters, + /// Server-wide (zones are forgotten when they hibernate). + hibernation_saves: BTreeMap<&'static str, u64>, + /// Server-wide activations refused before the zone ran. + activations_refused: BTreeMap<&'static str, u64>, +} + +/// Hibernation snapshot save outcome label values (fixed set). +pub const HIBERNATION_OUTCOMES: [&str; 3] = ["saved", "stale", "error"]; + +/// Refused activation reason label values (fixed set). +pub const ACTIVATION_REFUSALS: [&str; 2] = ["not_found", "unavailable"]; + +impl State { + fn zone(&mut self, zone: &str, max: usize) -> &mut ZoneSeries { + if !self.zones.contains_key(zone) { + let labeled = self.labeled < max; + if labeled { + self.labeled += 1; + } + self.zones.insert( + zone.to_string(), + ZoneSeries { + labeled, + ..ZoneSeries::default() + }, + ); + } + self.zones.get_mut(zone).expect("inserted") + } + + fn counters(&mut self, zone: &str, max: usize) -> &mut Counters { + if self.zone(zone, max).labeled { + &mut self.zones.get_mut(zone).expect("present").counters + } else { + &mut self.other + } + } +} + +/// Instance-scoped game metrics registry. +#[derive(Debug)] +pub struct GameMetrics { + max_zone_labels: usize, + state: Mutex, +} + +impl Default for GameMetrics { + fn default() -> Self { + Self::new(64) + } +} + +impl GameMetrics { + /// Registry giving at most `max_zone_labels` live zones their own label. + pub fn new(max_zone_labels: usize) -> Self { + Self { + max_zone_labels, + state: Mutex::new(State::default()), + } + } + + /// Cardinality budget for the `zone` label. + pub fn max_zone_labels(&self) -> usize { + self.max_zone_labels + } + + fn lock(&self) -> std::sync::MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Record one [`ZoneHost::advance`] and the host's current gauges. + pub fn record_advance(&self, host: &ZoneHost, report: &AdvanceReport) { + let max = self.max_zone_labels; + let mut state = self.lock(); + let series = state.zone(host.zone_id(), max); + series.gauges = Gauges { + tier: Some(host.tier()), + players: host.player_count(), + observers: host.observer_count(), + entities: report.entities.unwrap_or(series.gauges.entities), + facts_pending: host.facts_in_flight(), + }; + let c = state.counters(host.zone_id(), max); + for d in &report.tick_durations { + c.tick_duration.observe(d.as_secs_f64()); + } + c.ticks += u64::from(report.ticks); + c.ticks_dropped += u64::from(report.dropped_ticks); + if report.patched { + c.patches += 1; + } + for frame in &report.frames { + c.delta_bytes.observe(frame.bytes as f64); + c.delta_bytes_total += frame.bytes as u64; + c.delta_deferred += frame.stats.deferred as u64; + } + for (_, s) in &report.settled { + match s.outcome { + FactOutcome::Committed(_) => c.facts_committed += 1, + FactOutcome::Failed { .. } => c.facts_failed += 1, + } + } + } + + /// Record an input offer outcome. + pub fn record_input(&self, zone: &str, outcome: PushOutcome) { + self.record_input_label(zone, input_label(outcome)); + } + + /// Record an input dropped by the transport's rate limiter. + pub fn record_rate_limited(&self, zone: &str) { + self.record_input_label(zone, "rate_limited"); + } + + /// Record an input dropped because the zone was frozen (world barrier). + pub fn record_frozen_input(&self, zone: &str) { + self.record_input_label(zone, "frozen"); + } + + fn record_input_label(&self, zone: &str, label: &'static str) { + let max = self.max_zone_labels; + *self + .lock() + .counters(zone, max) + .inputs + .entry(label) + .or_insert(0) += 1; + } + + /// Record a hibernation snapshot save: `"saved"`, `"stale"` (rejected by + /// the fenced store: a newer owner saved, or tokens went backwards) or + /// `"error"` (backend failure). Other labels are ignored. + pub fn record_hibernation_save(&self, outcome: &str) { + if let Some(label) = HIBERNATION_OUTCOMES.iter().find(|l| **l == outcome) { + *self.lock().hibernation_saves.entry(label).or_insert(0) += 1; + } + } + + /// A zone activation refused before the zone ran, by protocol error + /// code (`NOT_FOUND` → `not_found`, anything else → `unavailable`). + pub fn record_activation_refused(&self, code: u32) { + let label = if code == crate::protocol::error::NOT_FOUND { + "not_found" + } else { + "unavailable" + }; + *self.lock().activations_refused.entry(label).or_insert(0) += 1; + } + + /// Refused activations recorded with `reason`. + pub fn activations_refused(&self, reason: &str) -> u64 { + self.lock() + .activations_refused + .get(reason) + .copied() + .unwrap_or(0) + } + + /// Hibernation saves recorded with `outcome`. + pub fn hibernation_saves(&self, outcome: &str) -> u64 { + self.lock() + .hibernation_saves + .get(outcome) + .copied() + .unwrap_or(0) + } + + /// A zone stopped: drop its series and free its label slot. + pub fn forget_zone(&self, zone: &str) { + let mut state = self.lock(); + if let Some(series) = state.zones.remove(zone) { + if series.labeled { + state.labeled -= 1; + } + } + } + + /// Zones currently tracked. + pub fn zone_count(&self) -> usize { + self.lock().zones.len() + } + + /// Prometheus text exposition (format 0.0.4). + pub fn render(&self) -> String { + let state = self.lock(); + let mut out = String::new(); + let labeled: Vec<(&str, &ZoneSeries)> = state + .zones + .iter() + .filter(|(_, s)| s.labeled) + .map(|(z, s)| (z.as_str(), s)) + .collect(); + let overflow: Vec<&ZoneSeries> = state.zones.values().filter(|s| !s.labeled).collect(); + let mut counter_rows: Vec<(&str, &Counters)> = + labeled.iter().map(|(z, s)| (*z, &s.counters)).collect(); + if !overflow.is_empty() + || state.other.ticks > 0 + || !state.other.inputs.is_empty() + || state.other.patches > 0 + { + counter_rows.push((OTHER_ZONE, &state.other)); + } + let mut gauge_rows: Vec<(&str, Gauges, [u64; 3])> = labeled + .iter() + .map(|(z, s)| (*z, s.gauges, tier_hot(s.gauges.tier))) + .collect(); + if !overflow.is_empty() { + let mut sum = Gauges::default(); + let mut tiers = [0u64; 3]; + for s in &overflow { + sum.players += s.gauges.players; + sum.observers += s.gauges.observers; + sum.entities += s.gauges.entities; + sum.facts_pending += s.gauges.facts_pending; + for (t, v) in tiers.iter_mut().zip(tier_hot(s.gauges.tier)) { + *t += v; + } + } + gauge_rows.push((OTHER_ZONE, sum, tiers)); + } + + header(&mut out, "zones", "gauge", "Zones currently hosted."); + let _ = writeln!(out, "distributed_game_zones {}", state.zones.len()); + + header( + &mut out, + "zone_tick_duration_seconds", + "histogram", + "Wall time of one fixed simulation step.", + ); + for (zone, c) in &counter_rows { + histogram( + &mut out, + "zone_tick_duration_seconds", + zone, + &c.tick_duration, + ); + } + counter( + &mut out, + "zone_ticks_total", + "Fixed steps simulated.", + &counter_rows, + |c| c.ticks, + ); + counter( + &mut out, + "zone_ticks_dropped_total", + "Fixed steps dropped by the catch-up cap.", + &counter_rows, + |c| c.ticks_dropped, + ); + + header( + &mut out, + "zone_tier", + "gauge", + "Activity tier (one-hot; summed for _other).", + ); + for (zone, _, tiers) in &gauge_rows { + for (name, v) in ["hot", "idle", "dormant"].iter().zip(tiers) { + let _ = writeln!( + out, + "distributed_game_zone_tier{{zone=\"{}\",tier=\"{name}\"}} {v}", + escape(zone) + ); + } + } + gauge( + &mut out, + "zone_players", + "Players (incl. reconnect grace).", + &gauge_rows, + |g| g.players, + ); + gauge(&mut out, "zone_observers", "Observers.", &gauge_rows, |g| { + g.observers + }); + gauge( + &mut out, + "zone_entities", + "Replicated entities at the last patch.", + &gauge_rows, + |g| g.entities, + ); + gauge( + &mut out, + "zone_facts_pending", + "Unsettled facts.", + &gauge_rows, + |g| g.facts_pending, + ); + + header( + &mut out, + "zone_inputs_total", + "counter", + "Input offers by outcome.", + ); + for (zone, c) in &counter_rows { + for (label, v) in &c.inputs { + let _ = writeln!( + out, + "distributed_game_zone_inputs_total{{zone=\"{}\",outcome=\"{label}\"}} {v}", + escape(zone) + ); + } + } + counter( + &mut out, + "zone_patches_total", + "Patches (Delta rounds).", + &counter_rows, + |c| c.patches, + ); + header( + &mut out, + "zone_delta_bytes", + "histogram", + "Encoded size of one Delta frame.", + ); + for (zone, c) in &counter_rows { + histogram(&mut out, "zone_delta_bytes", zone, &c.delta_bytes); + } + counter( + &mut out, + "zone_delta_bytes_total", + "Delta bytes produced.", + &counter_rows, + |c| c.delta_bytes_total, + ); + counter( + &mut out, + "zone_delta_deferred_total", + "Entity changes deferred by the byte budget.", + &counter_rows, + |c| c.delta_deferred, + ); + header( + &mut out, + "zone_facts_settled_total", + "counter", + "Fact settlements delivered to zones by outcome.", + ); + for (zone, c) in &counter_rows { + for (label, v) in [("committed", c.facts_committed), ("failed", c.facts_failed)] { + let _ = writeln!( + out, + "distributed_game_zone_facts_settled_total{{zone=\"{}\",outcome=\"{label}\"}} {v}", + escape(zone) + ); + } + } + header( + &mut out, + "hibernation_saves_total", + "counter", + "Hibernation snapshot saves by outcome (stale = rejected by the fenced store).", + ); + for label in HIBERNATION_OUTCOMES { + let v = state.hibernation_saves.get(label).copied().unwrap_or(0); + let _ = writeln!( + out, + "distributed_game_hibernation_saves_total{{outcome=\"{label}\"}} {v}" + ); + } + header( + &mut out, + "activations_refused_total", + "counter", + "Zone activations refused before the zone ran (unknown zone, factory or allocation failure).", + ); + for label in ACTIVATION_REFUSALS { + let v = state.activations_refused.get(label).copied().unwrap_or(0); + let _ = writeln!( + out, + "distributed_game_activations_refused_total{{reason=\"{label}\"}} {v}" + ); + } + out + } +} + +fn tier_hot(tier: Option) -> [u64; 3] { + match tier { + Some(Tier::Hot) => [1, 0, 0], + Some(Tier::Idle) => [0, 1, 0], + Some(Tier::Dormant) => [0, 0, 1], + None => [0, 0, 0], + } +} + +fn escape(v: &str) -> String { + v.replace('\\', "\\\\") + .replace('"', "\\\"") + .replace('\n', "\\n") +} + +fn header(out: &mut String, name: &str, kind: &str, help: &str) { + let _ = writeln!(out, "# HELP distributed_game_{name} {help}"); + let _ = writeln!(out, "# TYPE distributed_game_{name} {kind}"); +} + +fn counter( + out: &mut String, + name: &str, + help: &str, + rows: &[(&str, &Counters)], + value: impl Fn(&Counters) -> u64, +) { + header(out, name, "counter", help); + for (zone, c) in rows { + let _ = writeln!( + out, + "distributed_game_{name}{{zone=\"{}\"}} {}", + escape(zone), + value(c) + ); + } +} + +fn gauge( + out: &mut String, + name: &str, + help: &str, + rows: &[(&str, Gauges, [u64; 3])], + value: impl Fn(&Gauges) -> usize, +) { + header(out, name, "gauge", help); + for (zone, g, _) in rows { + let _ = writeln!( + out, + "distributed_game_{name}{{zone=\"{}\"}} {}", + escape(zone), + value(g) + ); + } +} + +fn histogram(out: &mut String, name: &str, zone: &str, h: &Histogram) { + let zone = escape(zone); + for (bound, count) in h.bounds.iter().zip(&h.counts) { + let _ = writeln!( + out, + "distributed_game_{name}_bucket{{zone=\"{zone}\",le=\"{bound}\"}} {count}" + ); + } + let _ = writeln!( + out, + "distributed_game_{name}_bucket{{zone=\"{zone}\",le=\"+Inf\"}} {}", + h.count + ); + let _ = writeln!( + out, + "distributed_game_{name}_sum{{zone=\"{zone}\"}} {}", + h.sum + ); + let _ = writeln!( + out, + "distributed_game_{name}_count{{zone=\"{zone}\"}} {}", + h.count + ); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_zone::Dots; + use crate::{ClientMirror, ManualClock, Role, TicketClaims, ZoneHost}; + use std::sync::Arc; + use std::time::Duration; + + fn host(zone: &str, clock: &ManualClock) -> ZoneHost { + ZoneHost::new(zone, Default::default(), Arc::new(clock.clone()), 3) + } + + #[test] + fn records_zone_metrics_and_renders_prometheus() { + let metrics = GameMetrics::new(8); + let clock = ManualClock::new(); + let mut h = host("z1", &clock); + let claims = TicketClaims { + principal: "a".into(), + zone: "z1".into(), + expires_at: u64::MAX, + nonce: "n".into(), + role: Role::Player, + name: None, + extensions: Default::default(), + wake: false, + }; + let joined = h.join(&claims, 0, "").unwrap(); + metrics.record_input("z1", h.push_input(joined.client, 1, 0, &[1])); + metrics.record_input("z1", h.push_input(joined.client, 1, 0, &[1])); + metrics.record_rate_limited("z1"); + clock.advance(Duration::from_millis(100)); + let report = h.advance(); + assert_eq!(report.frames.len(), 1); + let mut mirror = ClientMirror::new(); + for o in h.drain_outbound() { + if let crate::Outbound::Frame { frame, .. } = o { + mirror.apply(&frame).unwrap(); + } + } + assert_eq!(mirror.entities.len(), 3); + metrics.record_advance(&h, &report); + let text = metrics.render(); + assert!(text.contains("distributed_game_zones 1"), "{text}"); + assert!( + text.contains("distributed_game_zone_ticks_total{zone=\"z1\"} 3"), + "{text}" + ); + assert!(text.contains("distributed_game_zone_tier{zone=\"z1\",tier=\"hot\"} 1")); + assert!(text.contains("distributed_game_zone_players{zone=\"z1\"} 1")); + assert!(text.contains("distributed_game_zone_entities{zone=\"z1\"} 3")); + assert!( + text.contains("distributed_game_zone_inputs_total{zone=\"z1\",outcome=\"accepted\"} 1") + ); + assert!(text + .contains("distributed_game_zone_inputs_total{zone=\"z1\",outcome=\"duplicate\"} 1")); + assert!(text.contains( + "distributed_game_zone_inputs_total{zone=\"z1\",outcome=\"rate_limited\"} 1" + )); + assert!(text.contains("distributed_game_zone_delta_bytes_count{zone=\"z1\"} 1")); + assert!(text.contains("distributed_game_zone_tick_duration_seconds_count{zone=\"z1\"} 3")); + assert!(text.contains("# TYPE distributed_game_zone_delta_bytes histogram")); + } + + #[test] + fn zone_label_cardinality_is_bounded() { + let metrics = GameMetrics::new(2); + let clock = ManualClock::new(); + let mut hosts: Vec<_> = (0..5).map(|i| host(&format!("zone-{i}"), &clock)).collect(); + clock.advance(Duration::from_millis(100)); + for h in &mut hosts { + let r = h.advance(); + metrics.record_advance(h, &r); + } + let text = metrics.render(); + let zones: std::collections::BTreeSet<&str> = text + .lines() + .filter(|l| l.starts_with("distributed_game_zone_ticks_total{")) + .map(|l| l.split('"').nth(1).unwrap()) + .collect(); + assert_eq!( + zones.into_iter().collect::>(), + vec!["_other", "zone-0", "zone-1"] + ); + assert!( + text.contains("distributed_game_zone_ticks_total{zone=\"_other\"} 0"), + "{text}" + ); + assert!(text.contains("distributed_game_zone_tier{zone=\"_other\",tier=\"hot\"} 0")); + assert!(text.contains("distributed_game_zone_tier{zone=\"_other\",tier=\"idle\"} 3")); + // A labeled zone stopping frees its slot for the next new zone. + metrics.forget_zone("zone-0"); + let mut late = host("late", &clock); + clock.advance(Duration::from_millis(100)); + let r = late.advance(); + metrics.record_advance(&late, &r); + assert!(metrics.render().contains("zone=\"late\"")); + assert_eq!(metrics.zone_count(), 5); + } +} diff --git a/distributed_game/src/net/connection.rs b/distributed_game/src/net/connection.rs new file mode 100644 index 000000000..bbb3ff384 --- /dev/null +++ b/distributed_game/src/net/connection.rs @@ -0,0 +1,410 @@ +//! A client's WebSocket: admission, then frames between the socket and +//! the zone task, through the dev network simulation when one is set. + +use super::*; + +pub(super) async fn upgrade( + ws: WebSocketUpgrade, + Path(zone_id): Path, + State(inner): State>>, +) -> Response +where + Z: Zone, + Z::Config: Send, +{ + let max = inner.config.max_frame_bytes; + ws.max_message_size(max) + .on_upgrade(move |socket| connection(inner, zone_id, socket)) +} + +pub(super) fn error_frame(code: u32, message: impl Into) -> Vec { + ServerMessage::Error { + code, + message: message.into(), + } + .encode(&()) + .expect("error encodes") +} + +pub(super) async fn reject(mut socket: WebSocket, code: u32, message: impl Into) { + let _ = socket + .send(Message::Binary(error_frame(code, message).into())) + .await; + close(socket).await; +} + +/// How long a closing connection keeps reading for the client's Close. +const CLOSE_LINGER: Duration = Duration::from_secs(2); + +/// Close so the frames sent before arrive: send Close, then read and +/// discard until the client answers (or hangs up, or [`CLOSE_LINGER`] +/// passes). A socket dropped with client frames still unread is reset +/// (TCP RST), and the client may lose what it had not read yet, such as +/// the Kick or Error saying why. +pub(super) async fn close(mut socket: WebSocket) { + if socket.send(Message::Close(None)).await.is_err() { + return; + } + let drain = async { while let Some(Ok(_)) = socket.recv().await {} }; + let _ = tokio::time::timeout(CLOSE_LINGER, drain).await; +} + +pub(super) async fn sleep_until_opt(at: Option) { + match at { + Some(at) => tokio::time::sleep_until(at).await, + None => std::future::pending().await, + } +} + +pub(super) enum Inbound { + Input { + seq: u32, + client_tick: u32, + payload: Vec, + }, + Ping(f64), + Content(String), + Focus(f32, f32), +} + +pub(super) async fn connection(inner: Arc>, zone_id: String, mut socket: WebSocket) +where + Z: Zone, + Z::Config: Send, +{ + let cfg = &inner.config; + // 1. Hello, admitted before anything else happens. + let first = tokio::time::timeout(cfg.admission.hello_timeout, socket.recv()).await; + let hello = match first { + Ok(Some(Ok(Message::Binary(bytes)))) => match ClientMessage::decode(&bytes) { + Ok(ClientMessage::Hello(hello)) => hello, + _ => return reject(socket, error::BAD_MESSAGE, "expected Hello").await, + }, + Ok(Some(Ok(_))) => return reject(socket, error::BAD_MESSAGE, "binary frames only").await, + _ => return, + }; + let now = unix_now(); + let admitted = match admit(&cfg.admission, &hello, &zone_id, now) { + Ok(admitted) => admitted, + Err(refusal) => return reject(socket, refusal.code, refusal.message).await, + }; + // Placement: another host owns this zone -> Redirect (ticket not consumed). + if let Some(host) = remote_owner(&inner, &zone_id) { + let url = match &inner.config.redirect_url { + Some(map) => (map.0)(&host, &zone_id), + None => host.zone_url(&zone_id), + }; + let redirect = ServerMessage::Redirect { + zone_id: zone_id.clone(), + url, + } + .encode(&()) + .expect("redirect encodes"); + let _ = socket.send(Message::Binary(redirect.into())).await; + return close(socket).await; + } + // A transfer is single use at its issuer: an arrival reserves it there + // (settled once the zone answered), a refused one returning to its + // source is recorded there as returned. + let mut reserved: Option<(String, String)> = None; + let custody = match &admitted { + Admitted::Arrival(t) => { + let result = transfer_op(&inner, &t.issuer, TransferOp::Reserve, &t.claims.nonce).await; + if result.is_ok() { + reserved = Some((t.issuer.clone(), t.claims.nonce.clone())); + } + result + } + Admitted::Return(t) => { + transfer_op(&inner, &t.issuer, TransferOp::Return, &t.claims.nonce).await + } + Admitted::Join(_) | Admitted::Reconnect(_) => Ok(()), + }; + if let Err(e) = custody { + return reject(socket, error::UNAUTHORIZED, e).await; + } + let consumed = admitted.consume(&mut inner.nonces.lock().expect("nonces"), now); + // Only now may the connection reach a zone: a ticket activates one on + // demand, a reconnect token only finds a running one. + let zone = match (&admitted, consumed) { + (_, Err(refusal)) => Err((refusal.code, refusal.message)), + (Admitted::Reconnect(_), Ok(())) => running_zone(&inner, &zone_id).ok_or(( + error::RECONNECT_FAILED, + "zone restarted; rejoin".to_string(), + )), + (_, Ok(())) => activate_local(&inner, &zone_id) + .map_err(|refused| (error::ZONE_UNAVAILABLE, refused.to_string())), + }; + let mut zone = match zone { + Ok(zone) => zone, + Err((code, message)) => { + if let Some((issuer, nonce)) = reserved.take() { + let _ = transfer_op(&inner, &issuer, TransferOp::Release, &nonce).await; + } + return reject(socket, code, message).await; + } + }; + let reconnecting = matches!(admitted, Admitted::Reconnect(_)); + let (out_tx, mut out_rx) = mpsc::channel(cfg.outbound_queue.max(1)); + let (reply_tx, reply_rx) = oneshot::channel(); + let cmd = match admitted { + Admitted::Join(claims) => ZoneCmd::Join { + claims, + transfer: None, + capabilities: hello.capabilities, + content_version: hello.content_version, + out: out_tx, + reply: reply_tx, + }, + Admitted::Arrival(transfer) | Admitted::Return(transfer) => ZoneCmd::Join { + claims: transfer.claims.clone(), + transfer: Some(transfer), + capabilities: hello.capabilities, + content_version: hello.content_version, + out: out_tx, + reply: reply_tx, + }, + Admitted::Reconnect(token) => ZoneCmd::Reconnect { + token, + capabilities: hello.capabilities, + content_version: hello.content_version, + out: out_tx, + reply: reply_tx, + }, + }; + // A zone that just hibernated closes its inbox; a join retries on the + // next activation (which restores the snapshot first). + let mut pending = cmd; + let mut attempts = 0; + loop { + match zone.send(pending).await { + Ok(()) => break, + Err(mpsc::error::SendError(cmd)) => { + attempts += 1; + match activate_local(&inner, &zone_id) { + Ok(tx) if attempts < 4 && !reconnecting => { + zone = tx; + pending = cmd; + } + _ => { + if let Some((issuer, nonce)) = reserved.take() { + let _ = transfer_op(&inner, &issuer, TransferOp::Release, &nonce).await; + } + return reject(socket, error::NOT_FOUND, "zone stopped").await; + } + } + } + } + } + let result = reply_rx.await; + if let Some((issuer, nonce)) = reserved.take() { + if matches!(result, Ok(Ok(_))) { + let inner = inner.clone(); + tokio::spawn(async move { + let _ = transfer_op(&inner, &issuer, TransferOp::Confirm, &nonce).await; + }); + } else { + // Release before the client hears the refusal: it may present + // the same ticket to its source right away, and the issuer only + // accepts that return once the reservation is released. + let _ = transfer_op(&inner, &issuer, TransferOp::Release, &nonce).await; + } + } + let client = match result { + Ok(Ok(joined)) => joined.client, + Ok(Err(e)) => return reject(socket, e.code, e.message).await, + Err(_) => return reject(socket, error::NOT_FOUND, "zone stopped").await, + }; + + // 2. Session loop. + let seed = u64::from(client.0) ^ unix_now(); + // Both directions' delay lines run on milliseconds since `origin`; the + // simulation is read live, so a change applies to the next message. + let sim = inner.net_sim.subscribe(); + let mut outbound: DelayLine = DelayLine::new(seed); + let mut inbound: DelayLine = DelayLine::new(!seed); + let origin = Instant::now(); + let ms = || origin.elapsed().as_secs_f64() * 1000.0; + let link = || Link { + sim: *sim.borrow(), + now_ms: ms(), + }; + let mut gate = InputGate::new(&cfg.admission, Duration::ZERO); + let mut graceful = false; + let mut notify_zone = true; + 'session: loop { + // Flush due delayed items. + while let Some(item) = outbound.pop_due(ms()) { + match send_out(&mut socket, item).await { + Ok(true) => {} + // The zone closed this connection and already forgot the client. + Ok(false) => { + notify_zone = false; + break 'session; + } + // The socket died under a write: the zone must still learn + // the connection is gone (grace + ConnectionLost). + Err(_) => break 'session, + } + } + while let Some(item) = inbound.pop_due(ms()) { + if !forward_in( + &inner, + &zone, + &mut socket, + &mut outbound, + link(), + client, + item, + ) + .await + { + break 'session; + } + } + let next = match (outbound.next_due(), inbound.next_due()) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + } + .map(|due| origin + Duration::from_secs_f64(due.max(0.0) / 1000.0)); + tokio::select! { + out = out_rx.recv() => { + let Some(out) = out else { notify_zone = false; break }; + let now = link(); + if let Some(out) = outbound.push(now.sim, now.now_ms, out) { + match send_out(&mut socket, out).await { + Ok(true) => {} + Ok(false) => { + notify_zone = false; + break; + } + Err(_) => break, + } + } + } + msg = socket.recv() => { + let bytes = match msg { + Some(Ok(Message::Binary(bytes))) => bytes, + Some(Ok(Message::Ping(_) | Message::Pong(_))) => continue, + Some(Ok(Message::Text(_))) => { + let _ = socket.send(Message::Binary(error_frame(error::BAD_MESSAGE, "binary frames only").into())).await; + break; + } + _ => break, + }; + let decoded = ClientMessage::decode(&bytes); + // Every client message but Leave (undecodable ones too) + // spends a token. + if !matches!(decoded, Ok(ClientMessage::Leave)) { + match gate.take(origin.elapsed()) { + Gate::Pass => {} + Gate::Drop { warn } => { + inner.metrics.record_rate_limited(&zone_id); + if warn { + let _ = socket.send(Message::Binary(error_frame(error::RATE_LIMITED, "message dropped").into())).await; + } + continue; + } + Gate::Kick => { + let kick = ServerMessage::Kick { code: kick::RATE_LIMITED, message: "message flood".into() }; + let _ = socket.send(Message::Binary(kick.encode(&()).expect("kick").into())).await; + break; + } + } + } + let item = match decoded { + Ok(ClientMessage::Input { seq, client_tick, payload }) => { + Inbound::Input { seq, client_tick, payload } + } + Ok(ClientMessage::Ping { client_time }) => Inbound::Ping(client_time), + Ok(ClientMessage::Content { content_version }) => Inbound::Content(content_version), + // Native zones keep observers' zones running already; + // nearness only matters to celld zones. + Ok(ClientMessage::Near { .. }) => continue, + Ok(ClientMessage::Focus { x, y }) => Inbound::Focus(x, y), + Ok(ClientMessage::Leave) => { graceful = true; break; } + Ok(ClientMessage::Hello(_)) => { + let _ = socket.send(Message::Binary(error_frame(error::BAD_MESSAGE, "already joined").into())).await; + continue; + } + Err(e) => { + let _ = socket.send(Message::Binary(error_frame(error::BAD_MESSAGE, e.to_string()).into())).await; + continue; + } + }; + let now = link(); + if let Some(item) = inbound.push(now.sim, now.now_ms, item) { + if !forward_in(&inner, &zone, &mut socket, &mut outbound, link(), client, item).await { + break; + } + } + } + _ = sleep_until_opt(next) => {} + } + } + if notify_zone { + let _ = zone.send(ZoneCmd::Disconnect { client, graceful }).await; + } + close(socket).await; +} + +/// Ok(false) when the connection should end. +pub(super) async fn send_out(socket: &mut WebSocket, out: ConnOut) -> Result { + match out { + ConnOut::Frame(frame) => { + socket.send(Message::Binary(frame.into())).await?; + Ok(true) + } + ConnOut::Close => Ok(false), + } +} + +/// The simulated link at the moment an item is forwarded. +#[derive(Clone, Copy)] +pub(super) struct Link { + pub(super) sim: Option, + pub(super) now_ms: f64, +} + +pub(super) async fn forward_in( + inner: &Arc>, + zone: &mpsc::Sender, + socket: &mut WebSocket, + outbound: &mut DelayLine, + link: Link, + client: ClientId, + item: Inbound, +) -> bool { + match item { + Inbound::Input { + seq, + client_tick, + payload, + } => zone + .send(ZoneCmd::Input { + client, + seq, + client_tick, + payload, + }) + .await + .is_ok(), + Inbound::Content(version) => zone + .send(ZoneCmd::Content { client, version }) + .await + .is_ok(), + Inbound::Focus(x, y) => zone.send(ZoneCmd::Focus { client, x, y }).await.is_ok(), + Inbound::Ping(client_time) => { + let pong = ServerMessage::Pong { + client_time, + server_time: inner.clock.now().as_secs_f64() * 1000.0, + } + .encode(&()) + .expect("pong encodes"); + match outbound.push(link.sim, link.now_ms, ConnOut::Frame(pong)) { + Some(out) => send_out(socket, out).await.unwrap_or(false), + None => true, + } + } + } +} diff --git a/distributed_game/src/net/inbox.rs b/distributed_game/src/net/inbox.rs new file mode 100644 index 000000000..9f3981cd3 --- /dev/null +++ b/distributed_game/src/net/inbox.rs @@ -0,0 +1,301 @@ +//! Zone inbox over the network: [`GameServer::send`](super::GameServer::send) +//! locally, `POST /admin/zone-message` for peers and services, and +//! [`ZoneInboxClient`] for services (see [`crate::inbox`]). +//! +//! `POST /admin/zone-message` (header `x-distributed-internal-secret`), JSON body: +//! +//! ```text +//! {"zone": "pit-1", "kick": {"principal": "u-42", "reason": "banned"}} +//! {"zone": "pit-1", "message": {"type_id": 3, "payload": ""}} +//! ``` +//! +//! | Status | Body | Meaning | +//! |---|---|---| +//! | 200 | `{ok, players_kicked, observers_kicked}` | delivered on the zone task | +//! | 400 | `{error}` | malformed body, unknown message id or bad payload | +//! | 401 | `{error: "unauthorized"}` | missing / wrong admin secret (or none configured) | +//! | 404 | `{error: "inactive"}` | the zone is not running here (never activated by a message) | +//! | 421 | `{error: "wrong_owner", owner, admin_url}` | another host owns the zone (directory) | + +use std::sync::Arc; +use std::time::Duration; + +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use base64::Engine; +use serde_json::{json, Value}; + +use super::peer::post_json; +use super::InternalHttpSecret; +use crate::authoring::GameEvent; +use crate::inbox::{Delivered, ZoneInbound}; +use crate::world::{HostAddr, ZoneDirectory}; + +/// Route path. +pub const ZONE_MESSAGE_PATH: &str = "/admin/zone-message"; + +/// Why a message was not delivered. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum InboxError { + /// The zone is not active on the host asked (it is not activated). + Inactive, + /// Another host owns the zone. + WrongOwner(HostAddr), + /// Malformed message (unknown id, payload that does not decode). + Invalid(String), + /// The admin secret was refused. + Unauthorized, + /// Transport failure or an unexpected answer. + Unavailable(String), +} + +impl std::fmt::Display for InboxError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Inactive => f.write_str("zone not active"), + Self::WrongOwner(host) => write!(f, "zone owned by {}", host.id), + Self::Invalid(why) => write!(f, "invalid zone message: {why}"), + Self::Unauthorized => f.write_str("admin secret refused"), + Self::Unavailable(why) => write!(f, "zone inbox unavailable: {why}"), + } + } +} + +impl std::error::Error for InboxError {} + +/// A zone message on the wire between tasks and hosts: decoded into +/// `Z::Message` on the zone's own task. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum WireInbound { + Kick { principal: String, reason: String }, + Message { type_id: u32, payload: Vec }, +} + +impl WireInbound { + pub(crate) fn of(inbound: &ZoneInbound) -> Self { + match inbound { + ZoneInbound::Kick { principal, reason } => Self::Kick { + principal: principal.clone(), + reason: reason.clone(), + }, + ZoneInbound::Message(message) => Self::Message { + type_id: message.event_id(), + payload: message.to_payload(), + }, + } + } + + pub(crate) fn decode(self) -> Result, InboxError> { + match self { + Self::Kick { principal, reason } => { + if principal.is_empty() { + return Err(InboxError::Invalid("kick needs a principal".into())); + } + Ok(ZoneInbound::Kick { principal, reason }) + } + Self::Message { type_id, payload } => match M::decode_event(type_id, &payload) { + Ok(Some(message)) => Ok(ZoneInbound::Message(message)), + Ok(None) => Err(InboxError::Invalid(format!( + "this zone declares no message {type_id}" + ))), + Err(e) => Err(InboxError::Invalid(format!("message {type_id}: {e:?}"))), + }, + } + } + + pub(crate) fn to_json(&self, zone: &str) -> Value { + match self { + Self::Kick { principal, reason } => { + json!({ "zone": zone, "kick": { "principal": principal, "reason": reason } }) + } + Self::Message { type_id, payload } => json!({ + "zone": zone, + "message": { "type_id": type_id, "payload": URL_SAFE_NO_PAD.encode(payload) }, + }), + } + } + + /// `(zone, inbound)` from a route body. + pub(crate) fn from_json(body: &Value) -> Result<(String, Self), String> { + let zone = body + .get("zone") + .and_then(Value::as_str) + .filter(|z| !z.is_empty()) + .ok_or("zone")? + .to_string(); + let text = |v: &Value, name: &str| v.get(name).and_then(Value::as_str).map(str::to_string); + let inbound = match (body.get("kick"), body.get("message")) { + (Some(kick), None) => Self::Kick { + principal: text(kick, "principal").ok_or("kick.principal")?, + reason: text(kick, "reason").unwrap_or_default(), + }, + (None, Some(message)) => Self::Message { + type_id: message + .get("type_id") + .and_then(Value::as_u64) + .and_then(|id| u32::try_from(id).ok()) + .ok_or("message.type_id")?, + payload: URL_SAFE_NO_PAD + .decode(text(message, "payload").ok_or("message.payload")?) + .map_err(|_| "message.payload")?, + }, + _ => return Err("exactly one of `kick` or `message`".into()), + }; + Ok((zone, inbound)) + } +} + +pub(crate) fn delivered_json(delivered: Delivered) -> Value { + json!({ + "ok": true, + "players_kicked": delivered.players_kicked, + "observers_kicked": delivered.observers_kicked, + }) +} + +/// Sends zone messages from a service: finds the owning host through the +/// [`ZoneDirectory`], posts to its `/admin/zone-message` and follows +/// `wrong_owner` answers (ownership moved) a bounded number of times. +#[derive(Clone)] +pub struct ZoneInboxClient { + directory: Arc, + secret: InternalHttpSecret, + timeout: Duration, + max_redirects: u32, +} + +impl std::fmt::Debug for ZoneInboxClient { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ZoneInboxClient") + .field("timeout", &self.timeout) + .finish_non_exhaustive() + } +} + +impl ZoneInboxClient { + /// Client over `directory` with the hosts' shared internal secret. + pub fn new(directory: Arc, secret: InternalHttpSecret) -> Self { + Self { + directory, + secret, + timeout: Duration::from_secs(3), + max_redirects: 3, + } + } + + /// Per-request timeout (default 3 s). + pub fn with_timeout(mut self, timeout: Duration) -> Self { + self.timeout = timeout; + self + } + + /// Deliver a typed game message to `zone`. + pub async fn send(&self, zone: &str, message: &M) -> Result<(), InboxError> { + self.post( + zone, + WireInbound::Message { + type_id: message.event_id(), + payload: message.to_payload(), + }, + ) + .await + .map(drop) + } + + /// Remove every connection of `principal` from `zone`. + pub async fn kick( + &self, + zone: &str, + principal: &str, + reason: &str, + ) -> Result { + self.post( + zone, + WireInbound::Kick { + principal: principal.into(), + reason: reason.into(), + }, + ) + .await + } + + async fn post(&self, zone: &str, inbound: WireInbound) -> Result { + let body = inbound.to_json(zone); + let mut admin_url = self + .directory + .locate(zone) + .ok_or(InboxError::Inactive)? + .admin_url; + for _ in 0..=self.max_redirects { + let (status, reply) = post_json( + &admin_url, + ZONE_MESSAGE_PATH, + &self.secret, + &body, + self.timeout, + ) + .await + .map_err(InboxError::Unavailable)?; + let error = || { + reply + .get("error") + .and_then(Value::as_str) + .unwrap_or_default() + .to_string() + }; + match status { + 200 => { + let count = + |name: &str| reply.get(name).and_then(Value::as_u64).unwrap_or(0) as usize; + return Ok(Delivered { + players_kicked: count("players_kicked"), + observers_kicked: count("observers_kicked"), + }); + } + 421 => { + admin_url = reply + .get("admin_url") + .and_then(Value::as_str) + .ok_or_else(|| { + InboxError::Unavailable("wrong_owner without admin_url".into()) + })? + .to_string(); + } + 400 => return Err(InboxError::Invalid(error())), + 401 => return Err(InboxError::Unauthorized), + 404 => return Err(InboxError::Inactive), + other => return Err(InboxError::Unavailable(format!("{other}: {}", error()))), + } + } + Err(InboxError::Unavailable( + "too many wrong_owner redirects".into(), + )) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn route_bodies_round_trip() { + for inbound in [ + WireInbound::Kick { + principal: "u-1".into(), + reason: "banned".into(), + }, + WireInbound::Message { + type_id: 7, + payload: vec![1, 2, 255], + }, + ] { + let (zone, back) = WireInbound::from_json(&inbound.to_json("pit-1")).unwrap(); + assert_eq!((zone.as_str(), back), ("pit-1", inbound)); + } + assert!(WireInbound::from_json(&json!({"zone": "z", "kick": {}})).is_err()); + assert!(WireInbound::from_json(&json!({"zone": "z"})).is_err()); + assert!(WireInbound::from_json( + &json!({"zone": "z", "kick": {"principal": "p"}, "message": {"type_id": 1, "payload": ""}}) + ) + .is_err()); + } +} diff --git a/distributed_game/src/net/mod.rs b/distributed_game/src/net/mod.rs new file mode 100644 index 000000000..7a4d13d84 --- /dev/null +++ b/distributed_game/src/net/mod.rs @@ -0,0 +1,984 @@ +//! WebSocket transport (`net` feature): one axum server hosting many zones. +//! +//! - Route: `GET /zones/{zone_id}` upgrades to a WebSocket. Zones are created +//! on first use through the game's async [`ZoneFactory`] and each runs on +//! its own Tokio task driving a [`ZoneHost`]. Creation (ownership claim, +//! snapshot, [`ZoneAllocation`](crate::world::ZoneAllocation) record, +//! factory) happens before the first tick; joins that arrive meanwhile +//! wait and are admitted afterwards, or answered `Error(NOT_FOUND)` (the +//! factory knows no such zone) / `Error(ZONE_UNAVAILABLE)` (it failed or +//! timed out). +//! - Binary frames only (one protocol message per frame); text frames get +//! `Error(BAD_MESSAGE)` and are closed. +//! - Admission ([`crate::admission`], shared with the celld zone host): the +//! first frame must be Hello within `admission.hello_timeout`. A fresh +//! join needs a ticket verified with the admission key or verifier +//! (signature, expiry, zone == route zone, extensions, single-use nonce). +//! The principal comes **only** from the verified ticket. A reconnect +//! presents the Welcome's reconnect token within the host's +//! `reconnect_grace`, and only reaches a running zone. Nothing is +//! activated before the Hello is admitted, and at most `max_zones` zones +//! run at once (`Error(ZONE_UNAVAILABLE)` beyond). +//! - Every client message after the Welcome but Leave goes through the +//! connection's [`InputGate`]: excess messages are dropped (one +//! `Error(RATE_LIMITED)` per second) and a flood is kicked. A zone handles +//! at most a bounded batch of queued commands between two looks at its +//! clock. +//! - [`NetSim`] adds latency/jitter/loss in both directions for development +//! (configurable from the environment with [`NetSim::from_env`]). +//! - `GET /metrics` serves per-zone Prometheus metrics ([`crate::metrics`]). +//! - [`GameServer::serve`] shuts down gracefully: every zone kicks its +//! clients with `Kick(SHUTDOWN)`, runs `on_dispose`, and connections close. +//! +//! World structure (see [`world`] and `crate::world`): +//! +//! - **Placement**: with a [`ZoneDirectory`], a Hello for a zone owned by +//! another host gets `Redirect(zone, url)` (ticket not consumed). +//! - **Ownership**: every activation acquires a fenced claim +//! ([`ZoneOwnership`], default [`LocalOwnership`]) and renews it. Without a +//! successful renewal the zone fences itself at `ttl - renew_every` after +//! the last one began (renewals time out at `renew_every / 2`); fenced or +//! `Lost`, it stops at once: nothing more is persisted, queued facts are +//! dropped uncommitted and clients are kicked. +//! - **Activate on demand / hibernate**: zones are created on first use; +//! one that stays Dormant for `hibernate_after` is snapshotted +//! ([`Zone::hibernate`]) into the [`ZoneStateStore`] under its fencing +//! token, disposed, and restored on its next activation. +//! - **Handoff**: [`Ctx::handoff`](crate::Ctx::handoff) issues a signed +//! transfer ticket; the target reserves/confirms it with the issuing host +//! (single use), a refused transfer may return to its source. +//! - **Tier-up events** are routed to the parent zone, locally or through +//! the admin endpoint of the host that owns it. +//! - **Barrier**: [`GameServer::prepare_barrier`] / `commit_barrier` / +//! `abort_barrier`, driven by a [`world::WorldCoordinator`]. + +pub mod inbox; +mod peer; +pub use crate::ticket; +mod connection; +pub mod transfer; +pub mod world; +mod zone_task; + +use connection::upgrade; +use zone_task::{run_zone, ZONE_ENVELOPE_PATH}; + +use std::any::Any; +use std::collections::HashMap; +use std::future::Future; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade}; +use axum::extract::{Path, State}; +use axum::response::Response; +use axum::routing::{get, post}; +use axum::Router; +use serde_json::json; +use tokio::sync::{mpsc, oneshot, watch}; +use tokio::task::JoinHandle; +use tokio::time::Instant; + +pub use crate::facts::BoxFuture; +/// The hosts' shared secret for peer calls ([`ServerConfig::admin_secret`]). +pub use distributed::cell_host::InternalHttpSecret; +pub use inbox::{InboxError, ZoneInboxClient, ZONE_MESSAGE_PATH}; +pub use ticket::{ + decode_hs256, NonceCache, SharedTicketVerifier, TicketError, TicketKey, TicketVerifier, + VerifiedTicket, +}; +pub use transfer::{TransferOp, TransferRegistry}; +pub use world::{ + AbortNotes, BarrierParticipant, RemoteHost, RolloutError, RolloutReport, WorldCoordinator, +}; + +use crate::admission::{admit, AdmissionConfig, Admitted, Gate, InputGate}; +use crate::clock::{Clock, SystemClock}; +use crate::facts::{fact_channel, spawn_fact_worker, FactQueue, FactSink, RetryPolicy}; +use crate::handoff::{HandoffRequest, Transfer}; +use crate::host::{HostConfig, JoinError, Joined, Outbound, ZoneHost}; +use crate::metrics::GameMetrics; +use crate::protocol::Role; +use crate::protocol::{error, kick, ClientMessage, Notice, ServerMessage}; +use crate::world::{ + BarrierMode, ChildEvent, DottedTopology, FreezeState, HostAddr, LocalOwnership, OwnershipError, + StalePolicy, StateError, StoredZoneState, ZoneActivation, ZoneAllocationStore, ZoneClaim, + ZoneCreateError, ZoneDirectory, ZoneOwnership, ZoneStateStore, ZoneTopology, +}; +use crate::zone::{ClientId, TicketClaims, Tier, Zone}; +use crate::zone_message::ZoneEnvelope; + +use crate::netsim::DelayLine; +pub use crate::netsim::NetSim; + +/// Server settings. +#[derive(Debug, Clone)] +pub struct ServerConfig { + /// Settings for every hosted zone. + pub host: HostConfig, + /// Tickets, Hello deadline and the per-connection message rate + /// ([`crate::admission`]). Its key also signs transfer tickets and + /// server tokens. + pub admission: AdmissionConfig, + /// Zones this server runs at once (activating, running or + /// hibernating); an activation past it is refused with + /// `Error(ZONE_UNAVAILABLE)`. + pub max_zones: usize, + /// Outbound frames buffered per connection before it is dropped as slow. + pub outbound_queue: usize, + /// Largest accepted inbound frame. + pub max_frame_bytes: usize, + /// Optional dev latency simulation (initial value; change it at runtime + /// with [`GameServer::set_net_sim`]). + pub net_sim: Option, + /// Zones that get their own `zone` metrics label (see [`crate::metrics`]). + pub metrics_zone_labels: usize, + /// Hibernate a zone after it has been Dormant this long (None = never). + pub hibernate_after: Option, + /// Zone ownership claim TTL. + pub ownership_ttl: Duration, + /// Claim renewal period (well below `ownership_ttl`). Each renewal may + /// take half of it; a zone whose renewals keep failing fences itself + /// (stops ticking and committing facts) `ownership_ttl - + /// ownership_renew_every` after its last successful renewal began, so + /// it is gone before its claim expires and another host may take it. + pub ownership_renew_every: Duration, + /// How long an activation waits for a held claim (e.g. the previous + /// activation still saving its snapshot) before refusing. The default + /// equals the default `ownership_ttl`, so a claim left by a crashed + /// incarnation expires within one activation's wait; keep it at least + /// `ownership_ttl`. + pub activation_timeout: Duration, + /// Transfer ticket lifetime (and target reservation bound). + pub transfer_ttl: Duration, + /// After a zone is disposed, how long to wait for its fact worker to + /// commit the facts still queued; whatever is unsettled after that is + /// dropped (native facts are at most once, see + /// [`GameServer::with_fact_sink`]). + pub settle_timeout: Duration, + /// The hosts' shared internal secret: enables the `/admin/*` routes + /// (which require it in [`CELL_INTERNAL_SECRET_HEADER`]) and peer calls. + /// + /// [`CELL_INTERNAL_SECRET_HEADER`]: distributed::cell_host::CELL_INTERNAL_SECRET_HEADER + pub admin_secret: Option, + /// Peer (host-to-host) request timeout. + pub peer_timeout: Duration, + /// Public URL clients are redirected to for a zone owned by another + /// host (`None` = the directory's [`HostAddr::zone_url`]). For + /// deployments behind a proxy whose URLs differ from the hosts' raw + /// addresses; see [`ServerConfig::with_redirect_url`]. + pub redirect_url: Option, + /// Fact commits each zone's worker may run at once (default 1 = strict + /// emission order). Above 1, facts of one principal stay sequential and + /// different principals overlap (see [`crate::facts`]). Read by + /// [`GameServer::with_fact_sink`]. + pub max_concurrent_commits: usize, +} + +/// `(owning host, zone id) -> Redirect URL`. +pub type RedirectUrlFn = dyn Fn(&HostAddr, &str) -> String + Send + Sync; + +/// Maps (owning host, zone id) to the URL sent in `Redirect`. +#[derive(Clone)] +pub struct RedirectUrl(pub Arc); + +impl std::fmt::Debug for RedirectUrl { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("RedirectUrl(..)") + } +} + +impl ServerConfig { + /// Build `Redirect` URLs with `url(owner, zone_id)`, e.g. + /// `|host, zone| format!("wss://game.example/{}/zones/{zone}", host.id)`. + /// Alternatively advertise per-host public URLs in the directory with + /// [`HostAddr::with_ws_url`]. + pub fn with_redirect_url( + mut self, + url: impl Fn(&HostAddr, &str) -> String + Send + Sync + 'static, + ) -> Self { + self.redirect_url = Some(RedirectUrl(Arc::new(url))); + self + } + + /// Defaults with the given ticket key. + pub fn new(ticket_key: TicketKey) -> Self { + Self { + host: HostConfig::default(), + admission: AdmissionConfig::new(ticket_key), + max_zones: 4096, + outbound_queue: 512, + max_frame_bytes: 64 * 1024, + net_sim: None, + metrics_zone_labels: 64, + hibernate_after: None, + ownership_ttl: Duration::from_secs(15), + ownership_renew_every: Duration::from_secs(5), + activation_timeout: Duration::from_secs(15), + transfer_ttl: Duration::from_secs(30), + settle_timeout: Duration::from_secs(2), + admin_secret: None, + peer_timeout: Duration::from_secs(3), + max_concurrent_commits: 1, + redirect_url: None, + } + } +} + +type Inspector = Box; + +#[allow(clippy::large_enum_variant)] // Join is rare; boxing buys nothing. +enum ZoneCmd { + Join { + claims: TicketClaims, + transfer: Option, + capabilities: u32, + content_version: String, + out: mpsc::Sender, + reply: oneshot::Sender>, + }, + Reconnect { + token: String, + capabilities: u32, + content_version: String, + out: mpsc::Sender, + reply: oneshot::Sender>, + }, + ChildEvent(ChildEvent), + Freeze { + notice: Notice, + ack: oneshot::Sender<()>, + }, + Commit { + version: String, + notes: String, + mode: BarrierMode, + }, + Abort { + notice: Notice, + }, + Inspect(Inspector), + Input { + client: ClientId, + seq: u32, + client_tick: u32, + payload: Vec, + }, + Disconnect { + client: ClientId, + graceful: bool, + }, + /// The client patched its content live. + Content { + client: ClientId, + version: String, + }, + /// An observer's `Focus`. + Focus { + client: ClientId, + x: f32, + y: f32, + }, + /// A zone inbox message (decoded into `Z::Message` on the zone task). + Deliver { + inbound: inbox::WireInbound, + reply: oneshot::Sender>, + }, + /// A message from another zone ([`crate::zone_message`]). + ZoneMessage(ZoneEnvelope), +} + +enum ConnOut { + Frame(Vec), + Close, +} + +type ZoneFactoryFn = + dyn Fn(ZoneActivation) -> BoxFuture<'static, Result, ZoneCreateError>> + Send + Sync; + +/// Creates the configuration of a zone being activated, or says it does +/// not exist (`Ok(None)` → `Error(NOT_FOUND)`) or cannot be created now +/// (`Err` → `Error(ZONE_UNAVAILABLE)`). Runs on the activation task before +/// the zone exists: it may await storage, and joins wait for it (bounded by +/// `ServerConfig::activation_timeout`). The tick never waits for it. +pub struct ZoneFactory(Box>); + +impl std::fmt::Debug for ZoneFactory { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("ZoneFactory(..)") + } +} + +impl ZoneFactory { + /// Async factory: `ZoneFactory::new(|activation| async move { … })`. + pub fn new(factory: F) -> Self + where + F: Fn(ZoneActivation) -> Fut + Send + Sync + 'static, + Fut: Future, ZoneCreateError>> + Send + 'static, + { + Self(Box::new(move |activation| Box::pin(factory(activation)))) + } + + /// Factory that needs no I/O (the zone id and the allocation record + /// decide): `ZoneFactory::sync(|a| a.zone_id.starts_with("arena-").then(Config::default))`. + pub fn sync(factory: impl Fn(&ZoneActivation) -> Option + Send + Sync + 'static) -> Self { + Self(Box::new(move |activation| { + let config = factory(&activation); + Box::pin(async move { Ok(config) }) + })) + } +} +type FactsFactory = dyn Fn(&str) -> Option<(FactQueue, JoinHandle<()>)> + Send + Sync; +type HostConfigFn = dyn Fn(&str, &mut HostConfig) + Send + Sync; + +struct ZoneEntry { + tx: mpsc::Sender, + activation: u64, +} + +/// World-wide content state of this server. +#[derive(Debug, Clone, Default)] +struct WorldState { + version: String, + /// Barrier in progress: zones activated now start frozen. + barrier: Option<(u64, Notice)>, +} + +impl WorldState { + fn is_current(&self, barrier: u64) -> bool { + self.barrier.as_ref().is_some_and(|(id, _)| *id == barrier) + } +} + +struct Inner { + config: ServerConfig, + clock: Arc, + factory: ZoneFactory, + allocations: Option>, + facts: Option>, + /// Per-zone adjustments of `config.host` (tick rates, capacity …). + host_config: Option>, + nonces: Mutex, + zones: Mutex>, + tasks: Mutex>>, + shutdown: watch::Sender, + token_counter: AtomicU64, + metrics: Arc, + host_id: String, + /// Tells this instance's ownership claims apart from a previous + /// incarnation's (holder `"{host_id}#{incarnation}#{activation}"`). + incarnation: String, + directory: Option>, + ownership: Arc, + state_store: Option>, + topology: Arc, + transfers: Mutex, + /// Lock order: `zones` before `world`. + world: Mutex, + activations: AtomicU64, + /// Live dev network simulation, read by every connection per message. + net_sim: watch::Sender>, +} + +/// Multi-zone WebSocket game server. +pub struct GameServer { + inner: Arc>, +} + +impl Clone for GameServer { + fn clone(&self) -> Self { + Self { + inner: self.inner.clone(), + } + } +} + +impl GameServer +where + Z: Zone, + Z::Config: Send, +{ + /// Server whose zones are configured by `factory` when they activate + /// (see [`ZoneFactory`]). + pub fn new(config: ServerConfig, factory: ZoneFactory) -> Self { + Self::with_clock(config, Arc::new(SystemClock::new()), factory) + } + + /// Same as [`new`](Self::new) with an explicit clock. + pub fn with_clock( + config: ServerConfig, + clock: Arc, + factory: ZoneFactory, + ) -> Self { + let (shutdown, _) = watch::channel(false); + let (net_sim, _) = watch::channel(config.net_sim); + let version = config.host.content_version.clone(); + Self { + inner: Arc::new(Inner { + clock, + factory, + allocations: None, + facts: None, + host_config: None, + nonces: Mutex::new(NonceCache::default()), + zones: Mutex::new(HashMap::new()), + tasks: Mutex::new(Vec::new()), + shutdown, + token_counter: AtomicU64::new(0), + metrics: Arc::new(GameMetrics::new(config.metrics_zone_labels)), + config, + host_id: "local".into(), + incarnation: incarnation(), + directory: None, + ownership: Arc::new(LocalOwnership::new()), + state_store: None, + topology: Arc::new(DottedTopology), + transfers: Mutex::new(TransferRegistry::default()), + world: Mutex::new(WorldState { + version, + barrier: None, + }), + activations: AtomicU64::new(0), + net_sim, + }), + } + } + + fn configure(mut self, f: impl FnOnce(&mut Inner)) -> Self { + f(Arc::get_mut(&mut self.inner).expect("configure before sharing the server")); + self + } + + /// This host's id (directory entry, ownership holder prefix, transfer + /// issuer). Default `"local"`. + pub fn with_host_id(self, host_id: impl Into) -> Self { + let host_id = host_id.into(); + self.configure(|inner| inner.host_id = host_id) + } + + /// Route zones owned by other hosts (Redirect, peer calls). + pub fn with_directory(self, directory: Arc) -> Self { + self.configure(|inner| inner.directory = Some(directory)) + } + + /// Fenced zone ownership shared by every host of the world. + pub fn with_ownership(self, ownership: Arc) -> Self { + self.configure(|inner| inner.ownership = ownership) + } + + /// Where zone allocation records are read at activation + /// ([`ZoneActivation::allocation`]); a store error refuses the + /// activation with `ZONE_UNAVAILABLE`. + pub fn with_allocation_store(self, store: Arc) -> Self { + self.configure(|inner| inner.allocations = Some(store)) + } + + /// Where hibernated zone snapshots go. + pub fn with_state_store(self, store: Arc) -> Self { + self.configure(|inner| inner.state_store = Some(store)) + } + + /// Adjust the [`HostConfig`] of each zone at activation, e.g. a slow + /// tick rate for a province and a hot one for its neighborhoods. `f` + /// receives the zone id and a copy of `config.host`; the world content + /// version is applied afterwards and cannot be changed here. + pub fn with_host_config( + self, + f: impl Fn(&str, &mut HostConfig) + Send + Sync + 'static, + ) -> Self { + self.configure(|inner| inner.host_config = Some(Box::new(f))) + } + + /// Zone hierarchy for tier-up events (default [`DottedTopology`]). + pub fn with_topology(self, topology: Arc) -> Self { + self.configure(|inner| inner.topology = topology) + } + + /// Host id. + pub fn host_id(&self) -> &str { + &self.inner.host_id + } + + /// The world content version this server runs. + pub fn content_version(&self) -> String { + self.inner.world.lock().expect("world").version.clone() + } + + /// True when `zone_id` is active (or being created) on this server. + pub fn is_active(&self, zone_id: &str) -> bool { + self.inner + .zones + .lock() + .expect("zones") + .get(zone_id) + .is_some_and(|e| !e.tx.is_closed()) + } + + /// Run `f` against an **active** zone's host (ops tooling and tests). + /// None when the zone is not active here. + pub async fn inspect( + &self, + zone_id: &str, + f: impl FnOnce(&ZoneHost) -> R + Send + 'static, + ) -> Option { + let tx = { + let zones = self.inner.zones.lock().expect("zones"); + zones.get(zone_id)?.tx.clone() + }; + let (reply, rx) = oneshot::channel(); + let inspector: Inspector = Box::new(move |any: &dyn Any| { + if let Some(host) = any.downcast_ref::>() { + let _ = reply.send(f(host)); + } + }); + tx.send(ZoneCmd::Inspect(inspector)).await.ok()?; + rx.await.ok() + } + + /// Deliver a zone inbox message ([`crate::inbox`]) to `zone_id` on this + /// server. Runs on the zone's task between ticks. Refused with + /// [`InboxError::Inactive`] when the zone is not running here (a message + /// never activates a zone) and [`InboxError::WrongOwner`] when the + /// directory places it on another host. + pub async fn send( + &self, + zone_id: &str, + inbound: crate::inbox::ZoneInbound, + ) -> Result { + self.deliver_wire(zone_id, inbox::WireInbound::of(&inbound)) + .await + } + + pub(crate) async fn deliver_wire( + &self, + zone_id: &str, + inbound: inbox::WireInbound, + ) -> Result { + if let Some(owner) = self + .inner + .directory + .as_ref() + .and_then(|d| d.locate(zone_id)) + .filter(|h| h.id != self.inner.host_id) + { + return Err(InboxError::WrongOwner(owner)); + } + let tx = { + let zones = self.inner.zones.lock().expect("zones"); + zones + .get(zone_id) + .filter(|e| !e.tx.is_closed()) + .map(|e| e.tx.clone()) + .ok_or(InboxError::Inactive)? + }; + let (reply, rx) = oneshot::channel(); + tx.send(ZoneCmd::Deliver { inbound, reply }) + .await + .map_err(|_| InboxError::Inactive)?; + rx.await.map_err(|_| InboxError::Inactive)? + } + + /// Start activating `zone_id` locally without waiting (it is registered + /// at once, so barriers and joins already reach it). False while + /// shutting down or at `max_zones`; an unknown zone unregisters itself + /// once its factory answers. + pub fn begin_activation(&self, zone_id: &str) -> bool { + activate_local(&self.inner, zone_id).is_ok() + } + + /// Activate `zone_id` locally (as if a client asked for it) and wait + /// until it runs. False when the factory knows no such zone, creation + /// failed, the server runs `max_zones` already or is shutting down. + pub async fn activate(&self, zone_id: &str) -> bool { + if activate_local(&self.inner, zone_id).is_err() { + return false; + } + self.inspect(zone_id, |_| ()).await.is_some() + } + + /// Barrier phase 1 on this server: freeze every active zone (and every + /// zone activated until commit/abort) with `notice`, then wait up to + /// `timeout` for all to acknowledge. `Err` lists zones that did not. + pub async fn prepare_barrier( + &self, + barrier: u64, + notice: Notice, + timeout: Duration, + ) -> Result<(), Vec> { + let targets: Vec<(String, mpsc::Sender)> = { + let zones = self.inner.zones.lock().expect("zones"); + self.inner.world.lock().expect("world").barrier = Some((barrier, notice.clone())); + zones + .iter() + .map(|(id, e)| (id.clone(), e.tx.clone())) + .collect() + }; + let deadline = Instant::now() + timeout; + let mut waiting = Vec::new(); + for (zone_id, tx) in targets { + let (ack, rx) = oneshot::channel(); + let cmd = ZoneCmd::Freeze { + notice: notice.clone(), + ack, + }; + match tokio::time::timeout_at(deadline, tx.send(cmd)).await { + Ok(Ok(())) => waiting.push((zone_id, tx, rx)), + // Zone task gone (hibernated / stopped): nothing to freeze. + Ok(Err(_)) => {} + Err(_) => waiting.push((zone_id, tx, oneshot::channel().1)), + } + } + let mut missing = Vec::new(); + for (zone_id, tx, rx) in waiting { + match tokio::time::timeout_at(deadline, rx).await { + Ok(Ok(())) => {} + Ok(Err(_)) if tx.is_closed() => {} + _ => missing.push(zone_id), + } + } + if missing.is_empty() { + Ok(()) + } else { + missing.sort(); + Err(missing) + } + } + + /// Barrier phase 2: switch every zone to `version` and resume it + /// (`Resume{version, notes}`); `BarrierMode::Hard` also reloads stale + /// clients. Only for the current barrier: a commit for another one (a + /// delayed message) changes nothing and answers false. + pub async fn commit_barrier( + &self, + barrier: u64, + version: &str, + notes: &str, + mode: BarrierMode, + ) -> bool { + let targets: Vec> = { + let zones = self.inner.zones.lock().expect("zones"); + let mut world = self.inner.world.lock().expect("world"); + if !world.is_current(barrier) { + return false; + } + world.version = version.to_string(); + world.barrier = None; + zones.values().map(|e| e.tx.clone()).collect() + }; + for tx in targets { + let _ = tx + .send(ZoneCmd::Commit { + version: version.to_string(), + notes: notes.to_string(), + mode, + }) + .await; + } + true + } + + /// Abort the current barrier: every zone resumes on the old version. + /// An abort for another barrier changes nothing and answers false. + pub async fn abort_barrier(&self, barrier: u64, notes: &str) -> bool { + let (targets, version): (Vec>, String) = { + let zones = self.inner.zones.lock().expect("zones"); + let mut world = self.inner.world.lock().expect("world"); + if !world.is_current(barrier) { + return false; + } + world.barrier = None; + ( + zones.values().map(|e| e.tx.clone()).collect(), + world.version.clone(), + ) + }; + let notice = Notice { + reason: "content_update_aborted".into(), + version, + notes: notes.to_string(), + }; + for tx in targets { + let _ = tx + .send(ZoneCmd::Abort { + notice: notice.clone(), + }) + .await; + } + true + } + + /// Commit every zone's facts through `sink` (one worker per zone). + /// Must be called before the server is cloned or served. + /// + /// **At most once across a crash.** Each zone's queue and backlog live + /// in this process: while it runs, every fact is committed exactly once + /// (retried per `policy` under its idempotent key), but a crash, a + /// kill, a disposal that outlives [`ServerConfig::settle_timeout`] or a + /// lost ownership drops the facts not yet settled. The celld zone + /// object spools its facts to storage instead (at least once). + pub fn with_fact_sink( + mut self, + sink: S, + capacity: usize, + policy: RetryPolicy, + ) -> Self { + let sink = Arc::new(sink); + let inner = Arc::get_mut(&mut self.inner).expect("configure before sharing the server"); + let concurrency = inner.config.max_concurrent_commits; + inner.facts = Some(Box::new(move |_zone: &str| { + let (queue, feed) = fact_channel(capacity, policy); + let feed = feed.with_max_concurrent_commits(concurrency); + let worker = spawn_fact_worker(feed, sink.clone()); + Some((queue, worker)) + })); + self + } + + /// axum router exposing `GET /zones/{zone_id}`, `GET /metrics` and, + /// when `admin_secret` is set, the `/admin/*` peer routes. + pub fn router(&self) -> Router { + let mut router = Router::new() + .route("/zones/{zone_id}", get(upgrade::)) + .route("/metrics", get(metrics_text::)); + if self.inner.config.admin_secret.is_some() { + router = router + .route("/admin/transfer", post(world::admin_transfer::)) + .route("/admin/child-event", post(world::admin_child_event::)) + .route(ZONE_MESSAGE_PATH, post(world::admin_zone_message::)) + .route(ZONE_ENVELOPE_PATH, post(world::admin_zone_envelope::)) + .route("/admin/barrier/{phase}", post(world::admin_barrier::)); + } + router.with_state(self.inner.clone()) + } + + /// Replace the dev network simulation at runtime (`None` disables it). + /// Applies to every message sent or received from now on, on existing + /// and new connections; messages already delayed keep their schedule + /// and order is always preserved. + pub fn set_net_sim(&self, sim: Option) { + self.inner.net_sim.send_replace(sim); + } + + /// Network simulation currently in effect. + pub fn net_sim(&self) -> Option { + *self.inner.net_sim.borrow() + } + + /// Per-zone metrics registry (also served at `GET /metrics`). + pub fn metrics(&self) -> &GameMetrics { + &self.inner.metrics + } + + /// Ids of zones currently hosted. + pub fn zone_ids(&self) -> Vec { + let mut ids: Vec<_> = self + .inner + .zones + .lock() + .expect("zones") + .iter() + .filter(|(_, e)| !e.tx.is_closed()) + .map(|(id, _)| id.clone()) + .collect(); + ids.sort(); + ids + } + + /// Begin graceful shutdown of every zone. + pub fn shutdown(&self) { + let _ = self.inner.shutdown.send(true); + } + + /// Serve until `signal` resolves, then shut every zone down and wait for + /// zone tasks to finish. + pub async fn serve( + self, + listener: tokio::net::TcpListener, + signal: impl Future + Send + 'static, + ) -> std::io::Result<()> { + self.serve_with(listener, Router::new(), signal).await + } + + /// [`serve`](Self::serve) with additional application routes merged + /// into [`router`](Self::router) (lobby, dev or health endpoints), keeping + /// the same graceful shutdown: zones kick their clients and every zone + /// task finishes before this returns. + pub async fn serve_with( + self, + listener: tokio::net::TcpListener, + extra: Router, + signal: impl Future + Send + 'static, + ) -> std::io::Result<()> { + let server = self.clone(); + let mut stopped = self.inner.shutdown.subscribe(); + axum::serve(listener, self.router().merge(extra)) + .with_graceful_shutdown(async move { + tokio::select! { + _ = signal => {} + _ = stopped.wait_for(|stop| *stop) => {} + } + server.shutdown(); + }) + .await?; + let tasks: Vec<_> = std::mem::take(&mut *self.inner.tasks.lock().expect("tasks")); + for task in tasks { + let _ = task.await; + } + Ok(()) + } +} + +/// The host the directory places `zone_id` on, when that is another host +/// (a lookup only: nothing is activated or recorded). +fn remote_owner(inner: &Inner, zone_id: &str) -> Option { + inner + .directory + .as_ref() + .and_then(|d| d.locate(zone_id)) + .filter(|h| h.id != inner.host_id) +} + +/// Sender of the running (or activating) local activation of `zone_id`. +fn running_zone(inner: &Inner, zone_id: &str) -> Option> { + let zones = inner.zones.lock().expect("zones"); + zones + .get(zone_id) + .filter(|e| !e.tx.is_closed()) + .map(|e| e.tx.clone()) +} + +/// Sender of the local activation of `zone_id`, creating it on demand; +/// `Err` (why not) while shutting down or at `max_zones`. +fn activate_local( + inner: &Arc>, + zone_id: &str, +) -> Result, &'static str> +where + Z: Zone, + Z::Config: Send, +{ + if *inner.shutdown.borrow() { + return Err("server shutting down"); + } + let mut zones = inner.zones.lock().expect("zones"); + if let Some(entry) = zones.get(zone_id).filter(|e| !e.tx.is_closed()) { + return Ok(entry.tx.clone()); + } + if zones.len() - usize::from(zones.contains_key(zone_id)) >= inner.config.max_zones { + return Err("server at zone capacity"); + } + let (tx, rx) = mpsc::channel(1024); + let activation = inner.activations.fetch_add(1, Ordering::Relaxed) + 1; + let world = inner.world.lock().expect("world").clone(); + zones.insert( + zone_id.to_string(), + ZoneEntry { + tx: tx.clone(), + activation, + }, + ); + let facts = inner.facts.as_ref().and_then(|f| f(zone_id)); + let task = tokio::spawn(run_zone::( + inner.clone(), + zone_id.to_string(), + facts, + rx, + activation, + world, + )); + let mut tasks = inner.tasks.lock().expect("tasks"); + tasks.retain(|t| !t.is_finished()); + tasks.push(task); + Ok(tx) +} + +async fn metrics_text(State(inner): State>>) -> Response { + Response::builder() + .header( + axum::http::header::CONTENT_TYPE, + "text/plain; version=0.0.4; charset=utf-8", + ) + .body(axum::body::Body::from(inner.metrics.render())) + .expect("static response") +} + +fn unix_now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) +} + +fn random_token(inner: &Inner, label: &str) -> String { + let n = inner.token_counter.fetch_add(1, Ordering::Relaxed); + let seed = format!( + "{label}|{}|{n}|{}", + inner.host_id, + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()) + ); + inner.config.admission.key.hmac(seed.as_bytes())[..16] + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +/// Apply a transfer-record operation at the issuing host (local or peer). +async fn transfer_op( + inner: &Arc>, + issuer: &str, + op: TransferOp, + nonce: &str, +) -> Result<(), String> { + let reserve_for = inner.config.transfer_ttl.as_secs().max(1); + if issuer == inner.host_id { + return inner + .transfers + .lock() + .expect("transfers") + .apply(op, nonce, unix_now(), reserve_for) + .map_err(str::to_string); + } + let host = inner + .directory + .as_ref() + .and_then(|d| d.host(issuer)) + .ok_or_else(|| format!("unknown issuing host {issuer}"))?; + let secret = inner + .config + .admin_secret + .as_ref() + .ok_or("no admin secret for peer calls")?; + let body = json!({ "op": op.as_str(), "nonce": nonce }); + match peer::post_json( + &host.admin_url, + "/admin/transfer", + secret, + &body, + inner.config.peer_timeout, + ) + .await? + { + (200, _) => Ok(()), + (_, reply) => Err(reply + .get("error") + .and_then(|e| e.as_str()) + .unwrap_or("transfer refused") + .to_string()), + } +} + +/// A nonce telling this server instance apart from every other +/// incarnation of the same host id (start time, process id and a +/// per-process count): a host that crashed and restarted inside the claim +/// TTL must not present its dead incarnation's holder, or it would get +/// that claim and its fencing token (the zones' `boot_epoch`) back. +fn incarnation() -> String { + static STARTED: AtomicU64 = AtomicU64::new(0); + let micros = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_micros()); + let n = STARTED.fetch_add(1, Ordering::Relaxed); + format!("{micros:x}.{:x}.{n}", std::process::id()) +} diff --git a/distributed_game/src/net/peer.rs b/distributed_game/src/net/peer.rs new file mode 100644 index 000000000..5b41a7225 --- /dev/null +++ b/distributed_game/src/net/peer.rs @@ -0,0 +1,43 @@ +//! Host-to-host admin calls (child events, transfer records, barrier +//! phases, zone messages): JSON over HTTP with `reqwest`, authenticated as +//! internal traffic ([`CELL_INTERNAL_SECRET_HEADER`] carrying the hosts' +//! shared [`InternalHttpSecret`]). + +use std::sync::OnceLock; +use std::time::Duration; + +use distributed::cell_host::{InternalHttpSecret, CELL_INTERNAL_SECRET_HEADER}; +use serde_json::Value; + +/// POST `body` to `{admin_url}{path}`; returns the status and the JSON +/// body (`Null` when empty). +pub(crate) async fn post_json( + admin_url: &str, + path: &str, + secret: &InternalHttpSecret, + body: &Value, + timeout: Duration, +) -> Result<(u16, Value), String> { + static CLIENT: OnceLock = OnceLock::new(); + let url = format!("{}{path}", admin_url.trim_end_matches('/')); + let response = CLIENT + .get_or_init(reqwest::Client::new) + .post(&url) + .header(CELL_INTERNAL_SECRET_HEADER, secret.header_value()) + .json(body) + .timeout(timeout) + .send() + .await + .map_err(|e| format!("peer {admin_url}: {e}"))?; + let status = response.status().as_u16(); + let bytes = response + .bytes() + .await + .map_err(|e| format!("peer {admin_url}: {e}"))?; + let value = if bytes.is_empty() { + Value::Null + } else { + serde_json::from_slice(&bytes).map_err(|e| format!("peer {admin_url}: {e}"))? + }; + Ok((status, value)) +} diff --git a/distributed_game/src/net/ticket.rs b/distributed_game/src/net/ticket.rs new file mode 100644 index 000000000..3f3bfa50d --- /dev/null +++ b/distributed_game/src/net/ticket.rs @@ -0,0 +1,584 @@ +//! HMAC-SHA256 signed admission tickets (JWT HS256 compact form). +//! +//! `base64url(header) "." base64url(claims) "." base64url(HMAC-SHA256(key, +//! base64url(header) "." base64url(claims)))`, unpadded base64url. The header +//! must be `{"alg":"HS256",...}`; claims are +//! `{"sub","zone","exp","nonce","role"?}` where `exp` is Unix seconds and +//! `role` is `"player"` (default) or `"observer"`; an optional `wake: true` +//! lets an observer wake the zone when near (celld zones, +//! [`TicketClaims::wake`]). Any HS256 JWT library can mint them. The +//! principal is taken **only** from a verified `sub`. +//! +//! **Transfer tickets** (zone handoff) are the same format with +//! `"kind":"transfer"` plus `src` (source zone), `iss` (issuing host id), +//! `gen` (source ownership token), `left` (source departure stamp time, +//! Unix ms) and `carry` (base64url carried state). +//! [`TicketKey::verify`] rejects them ([`TicketError::WrongKind`]); use +//! [`TicketKey::verify_ticket`] to accept either kind. +//! +//! **Extension claims.** An optional `ext` object carries game-declared +//! claims ([`TicketExtensions`]: match id, team…). Join and transfer +//! tickets sign them alike; the server admits them only when they match +//! `AdmissionConfig::extensions` (see [`crate::claims`]). +//! +//! **Custom admission tickets.** Join tickets go through a +//! [`TicketVerifier`] (`AdmissionConfig::verifier`); the default is the +//! `TicketKey` itself. A game whose web backend already mints its own tickets +//! (different claim names, issuer/audience checks, no `zone`/`nonce`) +//! implements `TicketVerifier` (or passes a closure) and maps them onto +//! [`TicketClaims`]: `zone` is the route zone the client asked for, `nonce` +//! the replay key (e.g. the `jti`). The server still enforces +//! `claims.zone == route zone`, expiry and single use. Transfer tickets are +//! always minted and verified by the server's own `TicketKey`. +//! [`decode_hs256`] helps verifiers of other HS256 JWTs. + +use std::cmp::Reverse; +use std::collections::{BinaryHeap, HashMap}; + +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use base64::Engine; +use hmac::{Hmac, Mac}; +use serde_json::{json, Value}; +use sha2::Sha256; + +use crate::claims::TicketExtensions; +use crate::handoff::Transfer; +use crate::protocol::Role; +use crate::zone::TicketClaims; + +type HmacSha256 = Hmac; + +/// Why a ticket was refused. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TicketError { + /// Not three base64url segments of JSON. + Malformed, + /// Header `alg` is not HS256. + UnsupportedAlgorithm, + /// Signature mismatch. + BadSignature, + /// Required claim missing or mistyped. + MissingClaim(&'static str), + /// `exp` in the past. + Expired, + /// Nonce already used. + Replayed, + /// A transfer ticket where a join ticket was expected (or vice versa). + WrongKind, + /// Signed for another zone than the one requested. + WrongZone, + /// Refused by a custom [`TicketVerifier`] (issuer, audience, ...). + Invalid(String), + /// The single-use record is full of unexpired nonces: try again later + /// (forgetting one would let its ticket be replayed). + NonceCacheFull, +} + +/// Verifies **join** tickets presented in Hello. +/// +/// `zone` is the zone id of the route the client connected to and `now_unix` +/// the current Unix time in seconds. Return the verified claims (principal +/// only ever from the verified token); the server then checks +/// `claims.zone == zone`, `claims.expires_at > now_unix` and that +/// [`TicketClaims::replay_key`] was not used before. +/// +/// Implemented by [`TicketKey`] (the built-in HS256 format) and by any +/// `Fn(&str, &str, u64) -> Result` closure. +pub trait TicketVerifier: Send + Sync + 'static { + /// Verify `token` for `zone` at `now_unix`. + fn verify(&self, token: &str, zone: &str, now_unix: u64) -> Result; +} + +impl TicketVerifier for TicketKey { + fn verify(&self, token: &str, zone: &str, now_unix: u64) -> Result { + let claims = TicketKey::verify(self, token, now_unix)?; + if claims.zone != zone { + return Err(TicketError::WrongZone); + } + Ok(claims) + } +} + +impl TicketVerifier for F +where + F: Fn(&str, &str, u64) -> Result + Send + Sync + 'static, +{ + fn verify(&self, token: &str, zone: &str, now_unix: u64) -> Result { + self(token, zone, now_unix) + } +} + +/// A shared [`TicketVerifier`] (`AdmissionConfig::verifier`). +#[derive(Clone)] +pub struct SharedTicketVerifier(pub std::sync::Arc); + +impl SharedTicketVerifier { + /// Wrap a verifier. + pub fn new(verifier: impl TicketVerifier) -> Self { + Self(std::sync::Arc::new(verifier)) + } +} + +impl std::fmt::Debug for SharedTicketVerifier { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("SharedTicketVerifier(..)") + } +} + +/// Verify the signature of a compact HS256 JWT with `secret` and return its +/// claims object (no claim is interpreted, not even `exp`). For custom +/// [`TicketVerifier`]s over tickets minted elsewhere. +pub fn decode_hs256(token: &str, secret: &[u8]) -> Result { + TicketKey::new(secret).decode(token) +} + +/// A verified ticket of either kind. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum VerifiedTicket { + /// Lobby-issued admission ticket. + Join(TicketClaims), + /// Server-issued handoff transfer ticket. + Transfer(Transfer), +} + +/// Shared HMAC key. +#[derive(Clone)] +pub struct TicketKey { + secret: Vec, +} + +impl std::fmt::Debug for TicketKey { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("TicketKey([redacted])") + } +} + +impl TicketKey { + /// Key from secret bytes. + pub fn new(secret: impl Into>) -> Self { + Self { + secret: secret.into(), + } + } + + fn mac(&self) -> HmacSha256 { + HmacSha256::new_from_slice(&self.secret).expect("HMAC accepts any key length") + } + + /// HMAC-SHA256 of `data`. + pub fn hmac(&self, data: &[u8]) -> Vec { + let mut mac = self.mac(); + mac.update(data); + mac.finalize().into_bytes().to_vec() + } + + /// Mint a ticket (dev tooling and tests; production issuers can use any + /// HS256 JWT library). + pub fn sign(&self, claims: &TicketClaims) -> String { + let body = json!({ + "sub": claims.principal, + "zone": claims.zone, + "exp": claims.expires_at, + "nonce": claims.nonce, + "role": match claims.role { Role::Player => "player", Role::Observer => "observer" }, + }); + self.sign_body(&with_name(body, claims)) + } + + /// Mint a transfer ticket for a handoff. + pub fn sign_transfer(&self, transfer: &Transfer) -> String { + let claims = &transfer.claims; + let body = json!({ + "sub": claims.principal, + "zone": claims.zone, + "exp": claims.expires_at, + "nonce": claims.nonce, + "role": "player", + "kind": "transfer", + "src": transfer.source_zone, + "iss": transfer.issuer, + "gen": transfer.generation, + "left": transfer.departed_at_ms, + "carry": URL_SAFE_NO_PAD.encode(&transfer.carried), + }); + self.sign_body(&with_name(body, claims)) + } + + /// Sign an arbitrary JSON claims object as an HS256 JWT (tests and dev + /// tooling for custom [`TicketVerifier`] formats). + pub fn sign_json(&self, claims: &Value) -> String { + self.sign_body(claims) + } + + fn sign_body(&self, body: &Value) -> String { + let header = URL_SAFE_NO_PAD.encode(br#"{"alg":"HS256","typ":"JWT"}"#); + let payload = URL_SAFE_NO_PAD.encode(body.to_string()); + let signing_input = format!("{header}.{payload}"); + let sig = URL_SAFE_NO_PAD.encode(self.hmac(signing_input.as_bytes())); + format!("{signing_input}.{sig}") + } + + /// Verify a join or transfer ticket (signature, expiry, claims). + pub fn verify_ticket( + &self, + ticket: &str, + now_unix: u64, + ) -> Result { + let (claims, body) = self.verify_inner(ticket, now_unix)?; + match body.get("kind").and_then(Value::as_str) { + None | Some("join") => Ok(VerifiedTicket::Join(claims)), + Some("transfer") => { + let text = |name: &'static str| { + body.get(name) + .and_then(Value::as_str) + .filter(|v| !v.is_empty()) + .map(str::to_string) + .ok_or(TicketError::MissingClaim(name)) + }; + let carried = URL_SAFE_NO_PAD + .decode( + body.get("carry") + .and_then(Value::as_str) + .ok_or(TicketError::MissingClaim("carry"))?, + ) + .map_err(|_| TicketError::MissingClaim("carry"))?; + if claims.role != Role::Player { + return Err(TicketError::MissingClaim("role")); + } + Ok(VerifiedTicket::Transfer(Transfer { + source_zone: text("src")?, + issuer: text("iss")?, + generation: body + .get("gen") + .and_then(Value::as_u64) + .ok_or(TicketError::MissingClaim("gen"))?, + departed_at_ms: body + .get("left") + .and_then(Value::as_u64) + .ok_or(TicketError::MissingClaim("left"))?, + carried, + claims, + })) + } + Some(_) => Err(TicketError::WrongKind), + } + } + + /// Verify signature and expiry (`now_unix` seconds) of a **join** + /// ticket. Nonce reuse is checked separately with a [`NonceCache`]. + pub fn verify(&self, ticket: &str, now_unix: u64) -> Result { + match self.verify_ticket(ticket, now_unix)? { + VerifiedTicket::Join(claims) => Ok(claims), + VerifiedTicket::Transfer(_) => Err(TicketError::WrongKind), + } + } + + /// Signature check only; returns the claims object. + fn decode(&self, ticket: &str) -> Result { + let mut parts = ticket.split('.'); + let (Some(h), Some(p), Some(s), None) = + (parts.next(), parts.next(), parts.next(), parts.next()) + else { + return Err(TicketError::Malformed); + }; + let header: Value = decode_json(h)?; + if header.get("alg").and_then(Value::as_str) != Some("HS256") { + return Err(TicketError::UnsupportedAlgorithm); + } + let sig = URL_SAFE_NO_PAD + .decode(s) + .map_err(|_| TicketError::Malformed)?; + let mut mac = self.mac(); + mac.update(h.as_bytes()); + mac.update(b"."); + mac.update(p.as_bytes()); + mac.verify_slice(&sig) + .map_err(|_| TicketError::BadSignature)?; + decode_json(p) + } + + fn verify_inner( + &self, + ticket: &str, + now_unix: u64, + ) -> Result<(TicketClaims, Value), TicketError> { + let claims = self.decode(ticket)?; + let text = |name: &'static str| { + claims + .get(name) + .and_then(Value::as_str) + .filter(|v| !v.is_empty()) + .map(str::to_string) + .ok_or(TicketError::MissingClaim(name)) + }; + let expires_at = claims + .get("exp") + .and_then(Value::as_u64) + .ok_or(TicketError::MissingClaim("exp"))?; + if expires_at <= now_unix { + return Err(TicketError::Expired); + } + let role = match claims.get("role").and_then(Value::as_str) { + None | Some("player") => Role::Player, + Some("observer") => Role::Observer, + Some(_) => return Err(TicketError::MissingClaim("role")), + }; + Ok(( + TicketClaims { + principal: text("sub")?, + zone: text("zone")?, + expires_at, + nonce: text("nonce")?, + role, + name: claims + .get("name") + .and_then(Value::as_str) + .filter(|v| !v.is_empty()) + .map(str::to_string), + extensions: match claims.get("ext") { + None => TicketExtensions::new(), + Some(ext) => TicketExtensions::from_json(ext.clone()) + .map_err(|e| TicketError::Invalid(e.to_string()))?, + }, + wake: claims.get("wake").and_then(Value::as_bool) == Some(true), + }, + claims, + )) + } +} + +fn with_name(mut body: Value, claims: &TicketClaims) -> Value { + if let Some(object) = body.as_object_mut() { + if let Some(name) = &claims.name { + object.insert("name".into(), Value::String(name.clone())); + } + if !claims.extensions.is_empty() { + object.insert("ext".into(), claims.extensions.to_json()); + } + if claims.wake { + object.insert("wake".into(), Value::Bool(true)); + } + } + body +} + +fn decode_json(segment: &str) -> Result { + let bytes = URL_SAFE_NO_PAD + .decode(segment) + .map_err(|_| TicketError::Malformed)?; + serde_json::from_slice(&bytes).map_err(|_| TicketError::Malformed) +} + +/// Remembers used nonces until their ticket expires (single-use tickets), +/// at most `capacity` at once. Nonces leave in expiry order (each insert +/// drops the ones expired by then, `O(log n)` each). +#[derive(Debug)] +pub struct NonceCache { + seen: HashMap, + by_expiry: BinaryHeap>, + capacity: usize, +} + +impl Default for NonceCache { + /// Room for 262 144 live nonces. + fn default() -> Self { + Self::with_capacity(1 << 18) + } +} + +impl NonceCache { + /// Room for `capacity` unexpired nonces. + pub fn with_capacity(capacity: usize) -> Self { + Self { + seen: HashMap::new(), + by_expiry: BinaryHeap::new(), + capacity, + } + } + + /// Unexpired nonces held (as of the last insert). + pub fn len(&self) -> usize { + self.seen.len() + } + + /// No nonce held. + pub fn is_empty(&self) -> bool { + self.seen.is_empty() + } + + /// Record `nonce`; `Err(Replayed)` if already used and unexpired, + /// `Err(NonceCacheFull)` when `capacity` unexpired nonces are held. + pub fn check_and_insert( + &mut self, + nonce: &str, + expires_at: u64, + now_unix: u64, + ) -> Result<(), TicketError> { + while let Some(Reverse((exp, _))) = self.by_expiry.peek() { + if *exp > now_unix { + break; + } + let Some(Reverse((exp, expired))) = self.by_expiry.pop() else { + break; + }; + // A nonce re-used after expiry has a newer entry: keep it. + if self.seen.get(&expired) == Some(&exp) { + self.seen.remove(&expired); + } + } + if self.seen.contains_key(nonce) { + return Err(TicketError::Replayed); + } + if self.seen.len() >= self.capacity { + return Err(TicketError::NonceCacheFull); + } + self.seen.insert(nonce.to_string(), expires_at); + self.by_expiry + .push(Reverse((expires_at, nonce.to_string()))); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn claims() -> TicketClaims { + TicketClaims { + principal: "alice".into(), + zone: "z1".into(), + expires_at: 2_000, + nonce: "n1".into(), + role: Role::Player, + name: None, + extensions: Default::default(), + wake: false, + } + } + + /// Expired nonces leave as they expire (not in a sweep of every live + /// one per insert), and a cache full of live nonces refuses new ones + /// instead of forgetting one that could then be replayed. + #[test] + fn the_nonce_cache_expires_in_order_and_is_bounded() { + let mut cache = NonceCache::with_capacity(3); + cache.check_and_insert("a", 10, 0).unwrap(); + cache.check_and_insert("b", 20, 0).unwrap(); + cache.check_and_insert("c", 30, 0).unwrap(); + assert_eq!( + cache.check_and_insert("d", 40, 5), + Err(TicketError::NonceCacheFull) + ); + assert_eq!( + cache.check_and_insert("a", 10, 5), + Err(TicketError::Replayed) + ); + // "a" expired: room for one, and "a" may be seen again. + cache.check_and_insert("d", 40, 10).unwrap(); + assert_eq!(cache.len(), 3); + assert_eq!( + cache.check_and_insert("b", 20, 15), + Err(TicketError::Replayed) + ); + cache.check_and_insert("e", 50, 30).unwrap(); + assert_eq!(cache.len(), 2, "b and c expired"); + // A re-used nonce after expiry keeps its new expiry. + cache.check_and_insert("a", 60, 30).unwrap(); + assert_eq!( + cache.check_and_insert("a", 60, 45), + Err(TicketError::Replayed) + ); + } + + #[test] + fn signs_and_verifies() { + let key = TicketKey::new("secret"); + let ticket = key.sign(&claims()); + assert_eq!(key.verify(&ticket, 1_000).unwrap(), claims()); + assert_eq!(key.verify(&ticket, 2_000), Err(TicketError::Expired)); + assert_eq!( + TicketKey::new("other").verify(&ticket, 1_000), + Err(TicketError::BadSignature) + ); + } + + #[test] + fn the_wake_grant_round_trips_and_defaults_to_off() { + let key = TicketKey::new("secret"); + let mut watcher = claims().with_wake(true); + watcher.role = Role::Observer; + let ticket = key.sign(&watcher); + assert!(key.verify(&ticket, 1_000).unwrap().wake); + let passive = key.sign(&TicketClaims { + role: Role::Observer, + ..claims() + }); + assert!(!key.verify(&passive, 1_000).unwrap().wake); + } + + #[test] + fn tampered_principal_is_rejected() { + let key = TicketKey::new("secret"); + let ticket = key.sign(&claims()); + let parts: Vec<_> = ticket.split('.').collect(); + let forged = + URL_SAFE_NO_PAD.encode(r#"{"sub":"mallory","zone":"z1","exp":2000,"nonce":"n1"}"#); + let forged = format!("{}.{}.{}", parts[0], forged, parts[2]); + assert_eq!(key.verify(&forged, 1_000), Err(TicketError::BadSignature)); + } + + #[test] + fn transfer_tickets_round_trip_and_are_not_join_tickets() { + let key = TicketKey::new("secret"); + let transfer = Transfer { + claims: claims(), + source_zone: "z0".into(), + issuer: "h1".into(), + generation: 9, + carried: vec![1, 2, 3], + departed_at_ms: 1_700_000_000_123, + }; + let ticket = key.sign_transfer(&transfer); + assert_eq!( + key.verify_ticket(&ticket, 1_000).unwrap(), + VerifiedTicket::Transfer(transfer) + ); + assert_eq!(key.verify(&ticket, 1_000), Err(TicketError::WrongKind)); + let join = key.sign(&claims()); + assert_eq!( + key.verify_ticket(&join, 1_000).unwrap(), + VerifiedTicket::Join(claims()) + ); + } + + #[test] + fn names_round_trip_and_default_verifier_checks_zone() { + let key = TicketKey::new("secret"); + let named = claims().with_name("Ana"); + let ticket = key.sign(&named); + assert_eq!( + TicketVerifier::verify(&key, &ticket, "z1", 1_000), + Ok(named) + ); + assert_eq!( + TicketVerifier::verify(&key, &ticket, "z2", 1_000), + Err(TicketError::WrongZone) + ); + assert!(decode_hs256(&ticket, b"secret").is_ok()); + assert_eq!( + decode_hs256(&ticket, b"other"), + Err(TicketError::BadSignature) + ); + } + + #[test] + fn nonce_is_single_use() { + let mut cache = NonceCache::default(); + assert!(cache.check_and_insert("n", 10, 1).is_ok()); + assert_eq!( + cache.check_and_insert("n", 10, 2), + Err(TicketError::Replayed) + ); + assert!(cache.check_and_insert("n", 20, 11).is_ok()); + } +} diff --git a/distributed_game/src/net/transfer.rs b/distributed_game/src/net/transfer.rs new file mode 100644 index 000000000..eb1ab37a9 --- /dev/null +++ b/distributed_game/src/net/transfer.rs @@ -0,0 +1,155 @@ +//! Issued-transfer records: make every transfer ticket single-use across +//! hosts, and let a failed handoff return to its source. +//! +//! The host that issues a transfer ticket (the source zone's host) keeps a +//! record per nonce: +//! +//! ```text +//! Pending ──reserve(target)──► Reserved ──confirm──► Consumed +//! │ │ └──release (target refused)──► Pending +//! │ └──(reservation expires)──► Consumed +//! └──return(source)──► Consumed +//! ``` +//! +//! The target reserves before admitting and confirms after; the source +//! accepts the same ticket back ("return") only while Pending. A reservation +//! that is never confirmed or released counts as consumed: if in doubt the +//! player is *not* let back into the source (never in two zones; worst +//! case it needs a fresh lobby ticket). + +use std::collections::HashMap; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum State { + Pending, + Reserved { until: u64 }, + Consumed, +} + +/// Registry operation (also the admin wire name). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TransferOp { + /// Target is about to admit. + Reserve, + /// Target admitted. + Confirm, + /// Target refused; the ticket may be used again (e.g. to return). + Release, + /// Source re-admits the player. + Return, +} + +impl TransferOp { + /// Wire name. + pub fn as_str(self) -> &'static str { + match self { + Self::Reserve => "reserve", + Self::Confirm => "confirm", + Self::Release => "release", + Self::Return => "return", + } + } + + /// Parse a wire name. + pub fn parse(name: &str) -> Option { + Some(match name { + "reserve" => Self::Reserve, + "confirm" => Self::Confirm, + "release" => Self::Release, + "return" => Self::Return, + _ => return None, + }) + } +} + +/// Transfer records of the tickets this host issued. +#[derive(Debug, Default)] +pub struct TransferRegistry { + entries: HashMap, +} + +impl TransferRegistry { + /// Record a newly issued ticket (`expires_at` Unix seconds). + pub fn issue(&mut self, nonce: &str, expires_at: u64) { + self.entries + .insert(nonce.to_string(), (State::Pending, expires_at)); + } + + /// Apply `op` at `now` (Unix seconds); `reserve_for` bounds a reservation. + pub fn apply( + &mut self, + op: TransferOp, + nonce: &str, + now: u64, + reserve_for: u64, + ) -> Result<(), &'static str> { + if self.entries.len() > 4096 { + self.entries.retain(|_, (_, exp)| *exp + reserve_for > now); + } + let Some((state, expires_at)) = self.entries.get_mut(nonce) else { + return Err("unknown transfer"); + }; + if let State::Reserved { until } = *state { + if until <= now { + *state = State::Consumed; + } + } + match (op, *state) { + (TransferOp::Reserve, State::Pending) if *expires_at > now => { + *state = State::Reserved { + until: now + reserve_for, + }; + Ok(()) + } + (TransferOp::Confirm, State::Reserved { .. }) => { + *state = State::Consumed; + Ok(()) + } + (TransferOp::Release, State::Reserved { .. }) => { + *state = State::Pending; + Ok(()) + } + (TransferOp::Return, State::Pending) if *expires_at > now => { + *state = State::Consumed; + Ok(()) + } + (_, State::Reserved { .. }) => Err("transfer in progress"), + (_, State::Consumed) => Err("transfer already used"), + _ => Err("transfer expired"), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn single_use_with_release_and_return() { + let mut r = TransferRegistry::default(); + r.issue("n", 100); + r.apply(TransferOp::Reserve, "n", 10, 5).unwrap(); + assert!(r.apply(TransferOp::Return, "n", 11, 5).is_err()); + r.apply(TransferOp::Release, "n", 11, 5).unwrap(); + r.apply(TransferOp::Return, "n", 12, 5).unwrap(); + assert!(r.apply(TransferOp::Reserve, "n", 13, 5).is_err()); + + r.issue("m", 100); + r.apply(TransferOp::Reserve, "m", 10, 5).unwrap(); + r.apply(TransferOp::Confirm, "m", 11, 5).unwrap(); + assert!(r.apply(TransferOp::Return, "m", 12, 5).is_err()); + + // An unconfirmed reservation that lapses counts as used. + r.issue("k", 100); + r.apply(TransferOp::Reserve, "k", 10, 5).unwrap(); + assert_eq!( + r.apply(TransferOp::Return, "k", 20, 5), + Err("transfer already used") + ); + r.issue("e", 15); + assert_eq!( + r.apply(TransferOp::Reserve, "e", 20, 5), + Err("transfer expired") + ); + } +} diff --git a/distributed_game/src/net/world.rs b/distributed_game/src/net/world.rs new file mode 100644 index 000000000..84a780b36 --- /dev/null +++ b/distributed_game/src/net/world.rs @@ -0,0 +1,648 @@ +//! Admin peer routes and the world barrier coordinator. +//! +//! # Admin routes (`ServerConfig::admin_secret`) +//! +//! `POST` with header `x-distributed-internal-secret: ` (the +//! internal secret convention) and a JSON body: +//! +//! | Route | Body | Effect | +//! |---|---|---| +//! | `/admin/transfer` | `{op: reserve\|confirm\|release\|return, nonce}` | transfer record at the issuing host | +//! | `/admin/child-event` | `{zone, event}` | deliver a tier-up event to a local zone | +//! | `/admin/zone-message` | `{zone, kick: {principal, reason}}` or `{zone, message: {type_id, payload}}` | zone inbox ([`super::inbox`]): 404 inactive, 421 wrong owner | +//! | `/admin/zone-envelope` | a [`ZoneEnvelope`](crate::ZoneEnvelope) | a zone message from a zone on a peer ([`crate::zone_message`]): 204 queued, 404 not running here, 503 queue full | +//! | `/admin/barrier/prepare` | `{barrier, reason, version, notes, timeout_ms}` | freeze all zones, wait for acks (409 + `missing`) | +//! | `/admin/barrier/commit` | `{barrier, version, notes, mode: rolling\|hard}` | apply version, resume (409 for another barrier than the current one) | +//! | `/admin/barrier/abort` | `{barrier, notes}` | resume on the old version (409 likewise) | +//! +//! # Barrier +//! +//! [`WorldCoordinator::rollout`] runs a two-phase barrier over every +//! participant (local [`GameServer`]s and [`RemoteHost`]s): +//! +//! 1. **prepare**: each host freezes all its zones (`Freeze{reason, +//! version}`) and acknowledges once every zone is frozen (a zone may +//! delay with [`Zone::freeze_ready`]). Zones +//! activated during the barrier start frozen. +//! 2. if every host acknowledged within the timeout, the `apply` callback +//! installs the new content (sync, or awaited with +//! [`WorldCoordinator::rollout_async`] — zones stay frozen meanwhile); +//! then **commit**: every zone switches to the new version and resumes +//! (`Resume{version, notes}`). A **rolling** commit also reloads stale +//! clients already inside a safe-room gate ([`Zone::is_gate`] under +//! `StalePolicy::SafeRoom`): they reached a safe point, so they reload +//! there instead of waiting to walk into another gate. +//! +//! Any missing ack (or a failed `apply`) **aborts**: every zone resumes on +//! the old version with [`AbortNotes`] ([`WorldCoordinator::with_abort_notes`]). No zone ever simulates the new version while another +//! still simulates the old one outside the barrier: nothing resumes before +//! every zone is frozen. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +use axum::body::Bytes; +use axum::extract::{Path, State}; +use axum::http::{HeaderMap, StatusCode}; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use base64::Engine; +use serde_json::{json, Value}; + +use super::inbox::{delivered_json, InboxError, WireInbound}; +use super::peer::post_json; +use super::InternalHttpSecret; +use super::{ + activate_local, running_zone, transfer_op, unix_now, GameServer, Inner, TransferOp, ZoneCmd, +}; +use crate::facts::BoxFuture; +use crate::protocol::Notice; +use crate::world::{BarrierMode, ChildEvent, HostAddr}; +use crate::zone::Zone; +use crate::zone_message::ZoneEnvelope; +use distributed::cell_host::CELL_INTERNAL_SECRET_HEADER; + +type Reply = (StatusCode, String); + +fn reply(status: StatusCode, body: Value) -> Reply { + (status, body.to_string()) +} + +fn authorize(inner: &Inner, headers: &HeaderMap, body: &[u8]) -> Result { + let presented = headers + .get(CELL_INTERNAL_SECRET_HEADER) + .and_then(|v| v.to_str().ok()); + let allowed = match (&inner.config.admin_secret, presented) { + (Some(secret), Some(presented)) => secret.matches(presented), + _ => false, + }; + if !allowed { + return Err(reply( + StatusCode::UNAUTHORIZED, + json!({"ok": false, "error": "unauthorized"}), + )); + } + serde_json::from_slice(body).map_err(|e| { + reply( + StatusCode::BAD_REQUEST, + json!({"ok": false, "error": e.to_string()}), + ) + }) +} + +fn text(body: &Value, name: &str) -> String { + body.get(name) + .and_then(Value::as_str) + .unwrap_or_default() + .to_string() +} + +pub(super) fn child_event_json(event: &ChildEvent) -> Value { + json!({ + "origin_zone": event.origin_zone, + "from_zone": event.from_zone, + "kind": event.kind, + "payload": URL_SAFE_NO_PAD.encode(&event.payload), + "origin_tick": event.origin_tick, + "content_version": event.content_version, + "levels": event.levels, + }) +} + +fn child_event_from_json(v: &Value) -> Option { + Some(ChildEvent { + origin_zone: v.get("origin_zone")?.as_str()?.to_string(), + from_zone: v.get("from_zone")?.as_str()?.to_string(), + kind: v.get("kind")?.as_str()?.to_string(), + payload: URL_SAFE_NO_PAD.decode(v.get("payload")?.as_str()?).ok()?, + origin_tick: v.get("origin_tick")?.as_u64()?, + content_version: v.get("content_version")?.as_str()?.to_string(), + levels: u8::try_from(v.get("levels")?.as_u64()?).ok()?, + }) +} + +pub(super) async fn admin_transfer( + State(inner): State>>, + headers: HeaderMap, + body: Bytes, +) -> Reply +where + Z: Zone, + Z::Config: Send, +{ + let body = match authorize(&inner, &headers, &body) { + Ok(body) => body, + Err(r) => return r, + }; + let Some(op) = TransferOp::parse(&text(&body, "op")) else { + return reply(StatusCode::BAD_REQUEST, json!({"ok": false, "error": "op"})); + }; + let host_id = inner.host_id.clone(); + match transfer_op(&inner, &host_id, op, &text(&body, "nonce")).await { + Ok(()) => reply(StatusCode::OK, json!({"ok": true})), + Err(e) => reply(StatusCode::CONFLICT, json!({"ok": false, "error": e})), + } +} + +pub(super) async fn admin_zone_message( + State(inner): State>>, + headers: HeaderMap, + body: Bytes, +) -> Reply +where + Z: Zone, + Z::Config: Send, +{ + let body = match authorize(&inner, &headers, &body) { + Ok(body) => body, + Err(r) => return r, + }; + let (zone, inbound) = match WireInbound::from_json(&body) { + Ok(parsed) => parsed, + Err(e) => return reply(StatusCode::BAD_REQUEST, json!({"ok": false, "error": e})), + }; + let server = GameServer { inner }; + match server.deliver_wire(&zone, inbound).await { + Ok(delivered) => reply(StatusCode::OK, delivered_json(delivered)), + Err(InboxError::WrongOwner(owner)) => reply( + StatusCode::MISDIRECTED_REQUEST, + json!({"ok": false, "error": "wrong_owner", "owner": owner.id, "admin_url": owner.admin_url}), + ), + Err(InboxError::Inactive) => reply( + StatusCode::NOT_FOUND, + json!({"ok": false, "error": "inactive"}), + ), + Err(e) => reply( + StatusCode::BAD_REQUEST, + json!({"ok": false, "error": e.to_string()}), + ), + } +} + +/// A zone message from a zone on a peer host ([`crate::zone_message`]): +/// queued for the target when it runs here (204), else 404; it never +/// activates a zone. +pub(super) async fn admin_zone_envelope( + State(inner): State>>, + headers: HeaderMap, + body: Bytes, +) -> Reply +where + Z: Zone, + Z::Config: Send, +{ + let body = match authorize(&inner, &headers, &body) { + Ok(body) => body, + Err(r) => return r, + }; + let Ok(envelope) = serde_json::from_value::(body) else { + return reply( + StatusCode::BAD_REQUEST, + json!({"ok": false, "error": "a zone message is required"}), + ); + }; + let Some(tx) = running_zone(&inner, &envelope.to) else { + return reply( + StatusCode::NOT_FOUND, + json!({"ok": false, "error": "inactive"}), + ); + }; + match tx.try_send(ZoneCmd::ZoneMessage(envelope)) { + Ok(()) => (StatusCode::NO_CONTENT, String::new()), + Err(_) => reply( + StatusCode::SERVICE_UNAVAILABLE, + json!({"ok": false, "error": "zone busy"}), + ), + } +} + +pub(super) async fn admin_child_event( + State(inner): State>>, + headers: HeaderMap, + body: Bytes, +) -> Reply +where + Z: Zone, + Z::Config: Send, +{ + let body = match authorize(&inner, &headers, &body) { + Ok(body) => body, + Err(r) => return r, + }; + let Some(event) = body.get("event").and_then(child_event_from_json) else { + return reply( + StatusCode::BAD_REQUEST, + json!({"ok": false, "error": "event"}), + ); + }; + // Deliver here only (never re-forward): a peer sent it because its + // directory says we own the zone. + match activate_local(&inner, &text(&body, "zone")) { + Ok(tx) => { + let _ = tx.send(ZoneCmd::ChildEvent(event)).await; + reply(StatusCode::OK, json!({"ok": true})) + } + Err(refused) => reply( + StatusCode::SERVICE_UNAVAILABLE, + json!({"ok": false, "error": refused}), + ), + } +} + +pub(super) async fn admin_barrier( + State(inner): State>>, + Path(phase): Path, + headers: HeaderMap, + body: Bytes, +) -> Reply +where + Z: Zone, + Z::Config: Send, +{ + let body = match authorize(&inner, &headers, &body) { + Ok(body) => body, + Err(r) => return r, + }; + let server = GameServer { inner }; + let barrier = body.get("barrier").and_then(Value::as_u64).unwrap_or(0); + match phase.as_str() { + "prepare" => { + let notice = Notice { + reason: text(&body, "reason"), + version: text(&body, "version"), + notes: text(&body, "notes"), + }; + let timeout = Duration::from_millis( + body.get("timeout_ms") + .and_then(Value::as_u64) + .unwrap_or(5_000), + ); + match server.prepare_barrier(barrier, notice, timeout).await { + Ok(()) => reply(StatusCode::OK, json!({"ok": true})), + Err(missing) => reply( + StatusCode::CONFLICT, + json!({"ok": false, "missing": missing}), + ), + } + } + "commit" => { + let mode = match text(&body, "mode").as_str() { + "hard" => BarrierMode::Hard, + _ => BarrierMode::Rolling, + }; + let applied = server + .commit_barrier( + barrier, + &text(&body, "version"), + &text(&body, "notes"), + mode, + ) + .await; + barrier_reply(applied) + } + "abort" => barrier_reply(server.abort_barrier(barrier, &text(&body, "notes")).await), + _ => reply(StatusCode::NOT_FOUND, json!({"ok": false})), + } +} + +/// 200, or 409 for a phase of another barrier than the current one. +fn barrier_reply(applied: bool) -> Reply { + if applied { + reply(StatusCode::OK, json!({"ok": true})) + } else { + reply( + StatusCode::CONFLICT, + json!({"ok": false, "error": "stale barrier"}), + ) + } +} + +/// One host taking part in a world barrier. +pub trait BarrierParticipant: Send + Sync + 'static { + /// Display name (host id). + fn name(&self) -> String; + + /// Freeze everything; `Err` names what did not acknowledge in time. + fn prepare<'a>( + &'a self, + barrier: u64, + notice: &'a Notice, + timeout: Duration, + ) -> BoxFuture<'a, Result<(), Vec>>; + + /// Switch to `version` and resume. + fn commit<'a>( + &'a self, + barrier: u64, + version: &'a str, + notes: &'a str, + mode: BarrierMode, + ) -> BoxFuture<'a, Result<(), String>>; + + /// Resume on the old version. + fn abort<'a>(&'a self, barrier: u64, notes: &'a str) -> BoxFuture<'a, Result<(), String>>; +} + +impl BarrierParticipant for GameServer +where + Z: Zone, + Z::Config: Send, +{ + fn name(&self) -> String { + self.inner.host_id.clone() + } + + fn prepare<'a>( + &'a self, + barrier: u64, + notice: &'a Notice, + timeout: Duration, + ) -> BoxFuture<'a, Result<(), Vec>> { + Box::pin(async move { + let host = self.inner.host_id.clone(); + self.prepare_barrier(barrier, notice.clone(), timeout) + .await + .map_err(|missing| missing.into_iter().map(|z| format!("{host}/{z}")).collect()) + }) + } + + fn commit<'a>( + &'a self, + barrier: u64, + version: &'a str, + notes: &'a str, + mode: BarrierMode, + ) -> BoxFuture<'a, Result<(), String>> { + Box::pin(async move { + if self.commit_barrier(barrier, version, notes, mode).await { + Ok(()) + } else { + Err(format!("{}: stale barrier", self.inner.host_id)) + } + }) + } + + fn abort<'a>(&'a self, barrier: u64, notes: &'a str) -> BoxFuture<'a, Result<(), String>> { + Box::pin(async move { + if self.abort_barrier(barrier, notes).await { + Ok(()) + } else { + Err(format!("{}: stale barrier", self.inner.host_id)) + } + }) + } +} + +/// A host reached through its admin endpoint. +#[derive(Debug, Clone)] +pub struct RemoteHost { + host: HostAddr, + secret: InternalHttpSecret, + /// Extra time allowed on top of the barrier timeout for the HTTP call. + slack: Duration, +} + +impl RemoteHost { + /// Remote participant using the hosts' shared internal secret. + pub fn new(host: HostAddr, secret: InternalHttpSecret) -> Self { + Self { + host, + secret, + slack: Duration::from_secs(2), + } + } + + async fn call(&self, path: &str, body: Value, timeout: Duration) -> Result { + match post_json(&self.host.admin_url, path, &self.secret, &body, timeout).await? { + (200, reply) => Ok(reply), + (status, reply) => Err(format!("{} {status}: {reply}", self.host.id)), + } + } +} + +impl BarrierParticipant for RemoteHost { + fn name(&self) -> String { + self.host.id.clone() + } + + fn prepare<'a>( + &'a self, + barrier: u64, + notice: &'a Notice, + timeout: Duration, + ) -> BoxFuture<'a, Result<(), Vec>> { + Box::pin(async move { + let body = json!({ + "barrier": barrier, "reason": notice.reason, "version": notice.version, + "notes": notice.notes, "timeout_ms": timeout.as_millis() as u64, + }); + match post_json( + &self.host.admin_url, + "/admin/barrier/prepare", + &self.secret, + &body, + timeout + self.slack, + ) + .await + { + Ok((200, _)) => Ok(()), + Ok((_, reply)) => Err(reply + .get("missing") + .and_then(Value::as_array) + .map(|zones| { + zones + .iter() + .filter_map(Value::as_str) + .map(|z| format!("{}/{z}", self.host.id)) + .collect() + }) + .unwrap_or_else(|| vec![self.host.id.clone()])), + Err(_) => Err(vec![self.host.id.clone()]), + } + }) + } + + fn commit<'a>( + &'a self, + barrier: u64, + version: &'a str, + notes: &'a str, + mode: BarrierMode, + ) -> BoxFuture<'a, Result<(), String>> { + Box::pin(async move { + let mode = match mode { + BarrierMode::Rolling => "rolling", + BarrierMode::Hard => "hard", + }; + let body = + json!({"barrier": barrier, "version": version, "notes": notes, "mode": mode}); + self.call("/admin/barrier/commit", body, self.slack * 2) + .await + .map(|_| ()) + }) + } + + fn abort<'a>(&'a self, barrier: u64, notes: &'a str) -> BoxFuture<'a, Result<(), String>> { + Box::pin(async move { + let body = json!({"barrier": barrier, "notes": notes}); + self.call("/admin/barrier/abort", body, self.slack * 2) + .await + .map(|_| ()) + }) + } +} + +/// Successful rollout. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RolloutReport { + /// Barrier id. + pub barrier: u64, + /// Version now running everywhere. + pub version: String, + /// Commit calls that failed (the host must catch up out of band). + pub commit_errors: Vec, +} + +/// Failed (aborted) rollout: every zone resumed on the old version. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RolloutError { + /// Zones/hosts that did not acknowledge the freeze in time. + NotAcked(Vec), + /// The apply callback failed. + ApplyFailed(String), +} + +/// Notes sent with `Resume` when a rollout aborts +/// ([`WorldCoordinator::with_abort_notes`]). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AbortNotes { + /// A zone or host did not acknowledge the freeze in time. + pub not_acked: String, + /// The `apply` callback failed; `{error}` is replaced by its message. + pub apply_failed: String, +} + +impl Default for AbortNotes { + fn default() -> Self { + Self { + not_acked: "rollout aborted: freeze not acknowledged".into(), + apply_failed: "rollout aborted: apply failed".into(), + } + } +} + +/// Runs content-version barriers across every participant of one world. +pub struct WorldCoordinator { + participants: Vec>, + ack_timeout: Duration, + next: AtomicU64, + abort_notes: AbortNotes, +} + +impl WorldCoordinator { + /// Coordinator waiting `ack_timeout` for freeze acknowledgements. + pub fn new(ack_timeout: Duration) -> Self { + Self { + participants: Vec::new(), + ack_timeout, + next: AtomicU64::new(1), + abort_notes: AbortNotes::default(), + } + } + + /// Notes clients see in `Resume(content_update_aborted)` when a rollout + /// aborts (defaults: "rollout aborted: freeze not acknowledged" / + /// "rollout aborted: apply failed"). + pub fn with_abort_notes(mut self, notes: AbortNotes) -> Self { + self.abort_notes = notes; + self + } + + /// Add a participant. + pub fn participant(mut self, participant: Arc) -> Self { + self.participants.push(participant); + self + } + + /// Freeze everything, `apply(version)`, resume everything on `version`; + /// abort (resume on the old version) if any zone fails to acknowledge + /// or `apply` fails. Synchronous `apply`; see + /// [`rollout_async`](Self::rollout_async) for one that awaits. + pub async fn rollout( + &self, + version: &str, + notes: &str, + mode: BarrierMode, + apply: impl FnOnce(&str) -> Result<(), String>, + ) -> Result { + self.rollout_async(version, notes, mode, |v: String| { + let result = apply(&v); + std::future::ready(result) + }) + .await + } + + /// [`rollout`](Self::rollout) with an async `apply(version)`, awaited + /// while every zone is frozen (e.g. staging a content pack, so clients + /// see an "applying update" pause). Nothing resumes before it returns. + pub async fn rollout_async( + &self, + version: &str, + notes: &str, + mode: BarrierMode, + apply: F, + ) -> Result + where + F: FnOnce(String) -> Fut, + Fut: std::future::Future>, + { + let barrier = (unix_now() << 20) ^ self.next.fetch_add(1, Ordering::Relaxed); + let notice = Notice { + reason: "content_update".into(), + version: version.to_string(), + notes: notes.to_string(), + }; + let mut prepares = tokio::task::JoinSet::new(); + for p in &self.participants { + let p = p.clone(); + let notice = notice.clone(); + let timeout = self.ack_timeout; + prepares.spawn(async move { p.prepare(barrier, ¬ice, timeout).await }); + } + let mut missing = Vec::new(); + while let Some(result) = prepares.join_next().await { + match result { + Ok(Ok(())) => {} + Ok(Err(zones)) => missing.extend(zones), + Err(e) => missing.push(e.to_string()), + } + } + if !missing.is_empty() { + missing.sort(); + self.abort_all(barrier, &self.abort_notes.not_acked).await; + return Err(RolloutError::NotAcked(missing)); + } + if let Err(e) = apply(version.to_string()).await { + let notes = self.abort_notes.apply_failed.replace("{error}", &e); + self.abort_all(barrier, ¬es).await; + return Err(RolloutError::ApplyFailed(e)); + } + let mut commit_errors = Vec::new(); + for p in &self.participants { + if let Err(e) = p.commit(barrier, version, notes, mode).await { + commit_errors.push(e); + } + } + Ok(RolloutReport { + barrier, + version: version.to_string(), + commit_errors, + }) + } + + async fn abort_all(&self, barrier: u64, notes: &str) { + for p in &self.participants { + let _ = p.abort(barrier, notes).await; + } + } +} diff --git a/distributed_game/src/net/zone_task.rs b/distributed_game/src/net/zone_task.rs new file mode 100644 index 000000000..fb6bd99b6 --- /dev/null +++ b/distributed_game/src/net/zone_task.rs @@ -0,0 +1,714 @@ +//! One zone's task: fenced activation, the loop driving its [`ZoneHost`], +//! commands from connections and peers, and what it sends on (frames, zone +//! messages, tier-up events). + +use super::*; + +/// Route a tier-up event to `parent` (local activation or peer host). +pub(super) fn deliver_child(inner: &Arc>, parent: String, event: ChildEvent) +where + Z: Zone, + Z::Config: Send, +{ + let local = match remote_owner(inner, &parent) { + Some(host) => Err(host), + None => Ok(activate_local(inner, &parent)), + }; + match local { + Ok(Ok(tx)) => { + if let Err(mpsc::error::TrySendError::Full(cmd)) = + tx.try_send(ZoneCmd::ChildEvent(event)) + { + tokio::spawn(async move { + let _ = tx.send(cmd).await; + }); + } + } + Ok(Err(refused)) => { + eprintln!("distributed_game: tier-up event for zone {parent} dropped: {refused}"); + } + Err(host) => { + let Some(secret) = inner.config.admin_secret.clone() else { + return; + }; + let timeout = inner.config.peer_timeout; + let body = json!({ "zone": parent, "event": world::child_event_json(&event) }); + tokio::spawn(async move { + let _ = peer::post_json( + &host.admin_url, + "/admin/child-event", + &secret, + &body, + timeout, + ) + .await; + }); + } + } +} + +pub(super) enum Exit { + Hibernate(Vec), + Shutdown, + Lost, +} + +pub(super) async fn acquire_claim( + inner: &Arc>, + zone_id: &str, + holder: &str, +) -> Result { + let deadline = Instant::now() + inner.config.activation_timeout; + loop { + let error = match inner + .ownership + .acquire(zone_id, holder, inner.config.ownership_ttl) + .await + { + Ok(claim) => return Ok(claim), + Err(OwnershipError::Held { holder }) => format!("zone is owned by {holder}"), + Err(e) => format!("{e:?}"), + }; + if Instant::now() >= deadline { + return Err(error); + } + tokio::time::sleep(Duration::from_millis(20)).await; + } +} + +/// Activation failed: answer everything queued with `code` and unregister. +pub(super) fn refuse_activation( + inner: &Arc>, + zone_id: &str, + activation: u64, + mut rx: mpsc::Receiver, + code: u32, + message: &str, +) { + { + let mut zones = inner.zones.lock().expect("zones"); + if zones + .get(zone_id) + .is_some_and(|e| e.activation == activation) + { + zones.remove(zone_id); + } + rx.close(); + } + while let Ok(cmd) = rx.try_recv() { + match cmd { + ZoneCmd::Join { reply, .. } | ZoneCmd::Reconnect { reply, .. } => { + let _ = reply.send(Err(JoinError { + code, + message: message.to_string(), + })); + } + // Nothing runs here, so nothing to freeze. + ZoneCmd::Freeze { ack, .. } => { + let _ = ack.send(()); + } + ZoneCmd::Deliver { reply, .. } => { + let _ = reply.send(Err(InboxError::Inactive)); + } + _ => {} + } + } +} + +/// How long a claim acquired or renewed at some instant stays usable: +/// `ttl - renew_every` (the margin covers the renewal's own timeout and +/// clock skew with the store), so a zone fences itself before its claim +/// can expire at the store. +pub(super) fn fence_after(config: &ServerConfig) -> Duration { + config + .ownership_ttl + .saturating_sub(config.ownership_renew_every) +} + +/// Keep the claim alive. Every successful renewal moves the fence (the +/// instant the zone must stop by) to when that renewal began plus +/// [`fence_after`]; failed or timed-out renewals leave it where it is. +/// `Lost` moves it to now. +pub(super) async fn renew_claim( + ownership: Arc, + current: Arc>, + config: (Duration, Duration, Duration), + fence: watch::Sender, +) { + let (every, ttl, fence_after) = config; + loop { + tokio::time::sleep(every).await; + let claim = current.lock().expect("claim").clone(); + let began = Instant::now(); + match tokio::time::timeout(every / 2, ownership.renew(&claim, ttl)).await { + Ok(Ok(renewed)) => { + *current.lock().expect("claim") = renewed; + fence.send_replace(began + fence_after); + } + Ok(Err(OwnershipError::Backend(_))) | Err(_) => continue, + Ok(Err(_)) => { + fence.send_replace(Instant::now()); + return; + } + } + } +} + +/// Wait for the fence to move (forever once the renewer stopped). +pub(super) async fn fence_moved(fence: &mut watch::Receiver) { + if fence.changed().await.is_err() { + std::future::pending::<()>().await; + } +} + +/// Commands a zone handles between two looks at its clock: a flood of +/// commands (inputs, focus, inbox messages) never holds a due tick back +/// longer than this many command handlers; the rest stay queued. +pub(super) const COMMANDS_PER_ITERATION: usize = 64; + +#[allow(clippy::too_many_arguments)] +pub(super) async fn run_zone( + inner: Arc>, + zone_id: String, + facts: Option<(FactQueue, JoinHandle<()>)>, + mut rx: mpsc::Receiver, + activation: u64, + world: WorldState, +) where + Z: Zone, + Z::Config: Send, +{ + // 1. Fenced ownership. + let holder = format!("{}#{}#{activation}", inner.host_id, inner.incarnation); + let acquired_at = Instant::now(); + let claim = match acquire_claim(&inner, &zone_id, &holder).await { + Ok(claim) => claim, + Err(message) => { + return refuse_activation( + &inner, + &zone_id, + activation, + rx, + error::ZONE_UNAVAILABLE, + &message, + ) + } + }; + // 2. Restore the hibernated snapshot, if any. + let saved = match &inner.state_store { + Some(store) => match store.load(&zone_id).await { + Ok(saved) => saved, + _ => { + inner.ownership.release(&claim).await; + return refuse_activation( + &inner, + &zone_id, + activation, + rx, + error::ZONE_UNAVAILABLE, + "zone state unavailable", + ); + } + }, + None => None, + }; + // 3. The allocation record and the game's factory, bounded together. + let created = tokio::time::timeout(inner.config.activation_timeout, async { + let allocation = match &inner.allocations { + Some(store) => store.load(&zone_id).await?, + None => None, + }; + (inner.factory.0)(ZoneActivation { + zone_id: zone_id.clone(), + activation: claim.token, + allocation, + }) + .await + }) + .await; + let zone_config = match created { + Ok(Ok(Some(config))) => config, + refused => { + inner.ownership.release(&claim).await; + let (code, message) = match refused { + Ok(Ok(None)) => (error::NOT_FOUND, "unknown zone".to_string()), + Ok(Err(e)) => (error::ZONE_UNAVAILABLE, e.to_string()), + _ => ( + error::ZONE_UNAVAILABLE, + "zone creation timed out".to_string(), + ), + }; + inner.metrics.record_activation_refused(code); + return refuse_activation(&inner, &zone_id, activation, rx, code, &message); + } + }; + let mut host_config = inner.config.host.clone(); + if let Some(adjust) = &inner.host_config { + adjust(&zone_id, &mut host_config); + } + host_config.content_version = world.version.clone(); + // Fencing tokens grow across activations and restarts: a restart-safe + // epoch for fact keys (`Ctx::boot_epoch`). + host_config.boot_epoch = claim.token; + let token_inner = inner.clone(); + let issuer_inner = inner.clone(); + let generation = claim.token; + let mut host = ZoneHost::::new( + zone_id.clone(), + host_config, + inner.clock.clone(), + zone_config, + ) + .with_token_source(move || random_token(&token_inner, "token")) + .with_transfer_issuer(move |request: &HandoffRequest| { + let inner = &issuer_inner; + let expires_at = unix_now() + inner.config.transfer_ttl.as_secs().max(1); + let nonce = random_token(inner, "transfer"); + inner + .transfers + .lock() + .expect("transfers") + .issue(&nonce, expires_at); + Some(inner.config.admission.key.sign_transfer(&Transfer { + claims: TicketClaims { + principal: request.principal.clone(), + zone: request.target_zone.clone(), + expires_at, + nonce, + role: Role::Player, + name: request.name.clone(), + extensions: request.extensions.clone(), + wake: false, + }, + source_zone: request.source_zone.clone(), + issuer: inner.host_id.clone(), + generation, + carried: request.carried.clone(), + departed_at_ms: request.departed_at_ms, + })) + }); + if let Some(saved) = &saved { + host.restore(&saved.state, &saved.content_version); + } + let mut fact_worker = match facts { + Some((queue, worker)) => { + host = host.with_facts(queue); + Some(worker) + } + None => None, + }; + if let Some((_, notice)) = world.barrier { + host.request_freeze(notice); + } + + // 4. Keep the claim alive; without it the zone stops at the fence. + let current = Arc::new(Mutex::new(claim)); + let (fence_tx, mut fence) = watch::channel(acquired_at + fence_after(&inner.config)); + let renewer = tokio::spawn(renew_claim( + inner.ownership.clone(), + current.clone(), + ( + inner.config.ownership_renew_every, + inner.config.ownership_ttl, + fence_after(&inner.config), + ), + fence_tx, + )); + + let mut conns: HashMap> = HashMap::new(); + let mut freeze_acks: Vec> = Vec::new(); + let mut dormant_since: Option = None; + let mut shutdown = inner.shutdown.subscribe(); + let exit = loop { + // Fenced: someone else may own the zone by now. Not one more tick. + let fenced_at = *fence.borrow_and_update(); + if Instant::now() >= fenced_at { + break Exit::Lost; + } + let report = host.advance(); + inner.metrics.record_advance(&host, &report); + route(&mut host, &mut conns); + forward_upward(&inner, &zone_id, &mut host); + send_zone_messages(&inner, &mut host); + if host.is_frozen() { + for ack in freeze_acks.drain(..) { + let _ = ack.send(()); + } + } + let now = inner.clock.now(); + if host.tier() == Tier::Dormant { + dormant_since.get_or_insert(now); + } else { + dormant_since = None; + } + let hibernate_at = match (inner.config.hibernate_after, dormant_since) { + (Some(after), Some(since)) + if conns.is_empty() + && host.freeze_state() == FreezeState::Running + && host.facts_in_flight() == 0 => + { + Some(since + after) + } + _ => None, + }; + if hibernate_at.is_some_and(|at| now >= at) { + if let Some(leftovers) = begin_hibernation(&inner, &zone_id, activation, &mut rx) { + break Exit::Hibernate(leftovers); + } + } + let wake = match (report.next_wake, hibernate_at) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + }; + let sleep_for = wake.map(|at| at.saturating_sub(now)); + tokio::select! { + biased; + _ = shutdown.wait_for(|stop| *stop) => { + let bye = ServerMessage::Kick { code: kick::SHUTDOWN, message: "server shutting down".into() }; + let frame = bye.encode(&()).expect("kick encodes"); + for out in conns.values() { + let _ = out.try_send(ConnOut::Frame(frame.clone())); + let _ = out.try_send(ConnOut::Close); + } + conns.clear(); + host.dispose(); + host.drain_outbound(); + break Exit::Shutdown; + } + // Checked at the top of the loop. + _ = fence_moved(&mut fence) => {} + _ = tokio::time::sleep_until(fenced_at) => {} + cmd = rx.recv() => { + let Some(cmd) = cmd else { + host.dispose(); + route(&mut host, &mut conns); + break Exit::Shutdown; + }; + handle_cmd(&mut host, &mut conns, &inner.metrics, &mut freeze_acks, cmd); + // Take what else is queued, up to a budget, before ticking + // again. + for _ in 1..COMMANDS_PER_ITERATION { + let Ok(cmd) = rx.try_recv() else { break }; + handle_cmd(&mut host, &mut conns, &inner.metrics, &mut freeze_acks, cmd); + } + route(&mut host, &mut conns); + } + _ = async { + match sleep_for { + Some(d) => tokio::time::sleep(d).await, + None => std::future::pending().await, + } + } => {} + } + }; + renewer.abort(); + let claim = current.lock().expect("claim").clone(); + match exit { + Exit::Hibernate(leftovers) => { + let snapshot = host.hibernate_state(); + let content_version = host.config().content_version.clone(); + host.dispose(); + host.drain_outbound(); + forward_upward(&inner, &zone_id, &mut host); + send_zone_messages(&inner, &mut host); + if let (Some(state), Some(store)) = (snapshot, inner.state_store.clone()) { + let id = zone_id.clone(); + let stored = StoredZoneState { + token: claim.token, + content_version, + state, + }; + // A stale token means a newer owner saved already: ours is + // dropped, but never silently (metrics + stderr). + let saved = store.save(&id, &stored).await; + let outcome = match &saved { + Ok(()) => "saved", + Err(StateError::Stale { .. }) => "stale", + Err(_) => "error", + }; + inner.metrics.record_hibernation_save(outcome); + if outcome != "saved" { + eprintln!( + "distributed_game: hibernation snapshot of zone {zone_id} (token {}) not saved: {saved:?}", + claim.token + ); + } + } + inner.ownership.release(&claim).await; + drop(host); + for cmd in leftovers { + if matches!( + cmd, + ZoneCmd::Input { .. } | ZoneCmd::Disconnect { .. } | ZoneCmd::ZoneMessage(_) + ) { + continue; + } + // Messages never activate a zone. + if let ZoneCmd::Deliver { reply, .. } = cmd { + let _ = reply.send(Err(InboxError::Inactive)); + continue; + } + if let Ok(tx) = activate_local(&inner, &zone_id) { + let _ = tx.send(cmd).await; + } + } + } + Exit::Shutdown => { + inner.ownership.release(&claim).await; + drop(host); + } + Exit::Lost => { + // Fenced: another host may run the zone. Nothing more is + // persisted or committed: queued facts are dropped (an + // in-flight commit cannot be recalled), the worker stops and + // the disposal's facts go nowhere. Clients are kicked. + let dropped = host.abandon_facts(); + if let Some(worker) = fact_worker.take() { + worker.abort(); + } + host.dispose(); + route(&mut host, &mut conns); + eprintln!( + "distributed_game: zone {zone_id} (token {}) fenced without a live claim; {dropped} unsettled facts dropped", + claim.token + ); + drop(host); + } + } + // The fact worker commits everything still queued once the queue is + // dropped; give it a bounded moment so nothing is lost on dispose. + if let Some(worker) = fact_worker { + let _ = tokio::time::timeout(inner.config.settle_timeout, worker).await; + } + let mut zones = inner.zones.lock().expect("zones"); + if zones + .get(&zone_id) + .is_some_and(|e| e.activation == activation) + { + zones.remove(&zone_id); + } + // Keep the series when a newer activation (after hibernation) runs. + if !zones.contains_key(&zone_id) { + inner.metrics.forget_zone(&zone_id); + } +} + +/// Unregister the zone and close its inbox atomically; None when commands +/// are pending (hibernation is retried later). +pub(super) fn begin_hibernation( + inner: &Arc>, + zone_id: &str, + activation: u64, + rx: &mut mpsc::Receiver, +) -> Option> { + let mut zones = inner.zones.lock().expect("zones"); + if !rx.is_empty() { + return None; + } + if zones + .get(zone_id) + .is_some_and(|e| e.activation == activation) + { + zones.remove(zone_id); + } + rx.close(); + drop(zones); + // Commands sent between the check and the close are re-routed to the + // next activation (which waits for our claim release). + let mut leftovers = Vec::new(); + while let Ok(cmd) = rx.try_recv() { + leftovers.push(cmd); + } + Some(leftovers) +} + +pub(super) fn forward_upward(inner: &Arc>, zone_id: &str, host: &mut ZoneHost) +where + Z: Zone, + Z::Config: Send, +{ + let events = host.drain_upward(); + if events.is_empty() { + return; + } + let Some(parent) = inner.topology.parent(zone_id) else { + return; + }; + for event in events { + deliver_child(inner, parent.clone(), event); + } +} + +/// Path of the peer route that takes a zone message for a zone this host +/// runs ([`send_zone_messages`]). +pub(super) const ZONE_ENVELOPE_PATH: &str = "/admin/zone-envelope"; + +/// Hand the zone messages `host` sent to their targets, off the tick: a +/// zone running here gets it on its queue, a zone the directory places on +/// a peer gets it over `ZONE_ENVELOPE_PATH`. As on celld, delivery is best +/// effort and at most once (the target drops a repeated id): a message for +/// a zone that is not running is dropped (it never wakes one), a full +/// queue or failed peer call drops it, nothing is retried, and messages +/// carry no order guarantee. +pub(super) fn send_zone_messages(inner: &Arc>, host: &mut ZoneHost) +where + Z: Zone, + Z::Config: Send, +{ + for envelope in host.take_zone_messages() { + if let Some(peer) = remote_owner(inner, &envelope.to) { + let Some(secret) = inner.config.admin_secret.clone() else { + continue; + }; + let timeout = inner.config.peer_timeout; + tokio::spawn(async move { + let body = serde_json::to_value(&envelope).expect("an envelope serializes"); + match peer::post_json(&peer.admin_url, ZONE_ENVELOPE_PATH, &secret, &body, timeout) + .await + { + Ok((204, _)) => {} + Ok((status, _)) => eprintln!( + "distributed_game: zone message {} to {} refused: {status}", + envelope.id, envelope.to + ), + Err(e) => { + eprintln!("distributed_game: zone message to {}: {e}", envelope.to) + } + } + }); + } else if let Some(tx) = running_zone(inner, &envelope.to) { + let _ = tx.try_send(ZoneCmd::ZoneMessage(envelope)); + } + } +} + +pub(super) fn handle_cmd( + host: &mut ZoneHost, + conns: &mut HashMap>, + metrics: &GameMetrics, + freeze_acks: &mut Vec>, + cmd: ZoneCmd, +) { + match cmd { + ZoneCmd::Join { + claims, + transfer, + capabilities, + content_version, + out, + reply, + } => { + let result = match &transfer { + Some(transfer) => host.join_transfer(transfer, capabilities, &content_version), + None => host.join(&claims, capabilities, &content_version), + }; + if let Ok(joined) = &result { + conns.insert(joined.client, out); + } + let _ = reply.send(result); + } + ZoneCmd::Reconnect { + token, + capabilities, + content_version, + out, + reply, + } => { + let result = host.reconnect_with_version(&token, capabilities, &content_version); + if let Ok(joined) = &result { + conns.insert(joined.client, out); + } + let _ = reply.send(result); + } + ZoneCmd::Input { + client, + seq, + client_tick, + payload, + } => { + let frozen_before = host.inputs_dropped_frozen(); + let outcome = host.push_input(client, seq, client_tick, &payload); + if host.inputs_dropped_frozen() > frozen_before { + metrics.record_frozen_input(host.zone_id()); + } else { + metrics.record_input(host.zone_id(), outcome); + } + } + ZoneCmd::Disconnect { client, graceful } => { + conns.remove(&client); + host.disconnect(client, graceful); + } + ZoneCmd::Content { client, version } => { + host.content_patched(client, &version); + } + ZoneCmd::Focus { client, x, y } => host.observer_focus(client, x, y), + ZoneCmd::ChildEvent(event) => host.deliver_child_event(event), + // Repeats and misaddressed messages are dropped, as on celld. + ZoneCmd::ZoneMessage(envelope) => { + let _ = host.deliver_zone(envelope); + } + ZoneCmd::Deliver { inbound, reply } => { + let _ = reply.send(inbound.decode::().map(|m| host.deliver(m))); + } + ZoneCmd::Freeze { notice, ack } => { + if host.request_freeze(notice) == FreezeState::Frozen { + let _ = ack.send(()); + } else { + freeze_acks.push(ack); + } + } + ZoneCmd::Commit { + version, + notes, + mode, + } => { + host.set_content_version(version.clone()); + if host.freeze_state() != FreezeState::Running { + host.resume(Notice { + reason: "content_update".into(), + version, + notes, + }); + } + // Hard reloads every stale client; Rolling reloads the ones + // already inside a safe-room gate (they will not walk into one). + let gate = host.zone().is_gate() + && matches!(host.config().stale_policy, StalePolicy::SafeRoom { .. }); + if mode == BarrierMode::Hard || gate { + host.reload_stale_players(); + } + freeze_acks.clear(); + } + ZoneCmd::Abort { notice } => { + host.cancel_freeze(notice); + freeze_acks.clear(); + } + ZoneCmd::Inspect(f) => f(&*host as &dyn Any), + } +} + +pub(super) fn route( + host: &mut ZoneHost, + conns: &mut HashMap>, +) { + for outbound in host.drain_outbound() { + match outbound { + Outbound::Frame { client, frame } => { + let Some(out) = conns.get(&client) else { + continue; + }; + if out.try_send(ConnOut::Frame(frame)).is_err() { + // Slow or gone: drop the connection; the player keeps its grace window. + let out = conns.remove(&client).expect("present"); + let _ = out.try_send(ConnOut::Close); + host.disconnect(client, false); + } + } + Outbound::Close { client } => { + if let Some(out) = conns.remove(&client) { + let _ = out.try_send(ConnOut::Close); + } + } + } + } +} diff --git a/distributed_game/src/netsim.rs b/distributed_game/src/netsim.rs new file mode 100644 index 000000000..44b7ad361 --- /dev/null +++ b/distributed_game/src/netsim.rs @@ -0,0 +1,290 @@ +//! Development network simulation (latency, jitter, loss), portable: the +//! native WebSocket server ([`crate::net`]) and the celld zone host +//! (`celld_zone`, wasm32) both apply it per connection and direction. +//! +//! [`NetSim`] is the setting; [`DelayLine`] is the order-preserving queue a +//! host puts one direction of one connection through, over plain +//! millisecond timestamps (so it runs on Tokio's clock and on `Date.now()`). + +use std::collections::VecDeque; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; + +use crate::rng::ZoneRng; + +/// Cell kind of a celld worker's dev settings object (binding `ZONE_DEV`, +/// `celld_zone::ZoneDevSettings`), where celld zone objects read the +/// network simulation. +pub const ZONE_DEV_KIND: &str = "zone-dev"; +/// Shard of the dev settings holding the network simulation ([`NetSimJson`]). +pub const NETSIM_SHARD: &str = "netsim"; + +/// Development network simulation, applied independently to each direction +/// of every connection. +/// +/// Semantics over WebSocket (a reliable, ordered stream): a message is never +/// dropped or reordered, because Deltas are encoded against the previous +/// one. `loss` models what TCP does with a lost segment instead: with +/// probability `loss` a message is delayed by an extra `retransmit` (repeated +/// with the same probability, at most 3 times), and since order is preserved +/// every later message queues behind it (head-of-line blocking). Total +/// one-way delay = `latency + U[0, jitter] + k·retransmit`. +#[derive(Debug, Clone, Copy, PartialEq, Default)] +pub struct NetSim { + /// Fixed one-way delay. + pub latency: Duration, + /// Extra uniform random delay in `[0, jitter]` (order is preserved). + pub jitter: Duration, + /// Probability in `[0, 1]` that a message needs a retransmission. + pub loss: f32, + /// Delay added per simulated retransmission (TCP minimum RTO ≈ 200 ms). + pub retransmit: Duration, +} + +impl NetSim { + /// Latency + jitter, no loss. + pub fn new(latency: Duration, jitter: Duration) -> Self { + Self { + latency, + jitter, + loss: 0.0, + retransmit: Duration::from_millis(200), + } + } + + /// Add simulated loss (see the type docs for WebSocket semantics). + pub fn with_loss(mut self, loss: f32, retransmit: Duration) -> Self { + self.loss = loss.clamp(0.0, 1.0); + self.retransmit = retransmit; + self + } + + /// Read `DG_NET_LATENCY_MS`, `DG_NET_JITTER_MS`, `DG_NET_LOSS` (fraction, + /// e.g. `0.02`) and `DG_NET_RETRANSMIT_MS` (default 200). `None` when + /// none of the first three is set or all are zero. + pub fn from_env() -> Option { + Self::from_lookup(|key| std::env::var(key).ok()) + } + + /// [`from_env`](Self::from_env) over any key lookup. + pub fn from_lookup(lookup: impl Fn(&str) -> Option) -> Option { + let ms = |key: &str| { + lookup(key) + .and_then(|v| v.trim().parse::().ok()) + .map(Duration::from_millis) + }; + let latency = ms("DG_NET_LATENCY_MS").unwrap_or_default(); + let jitter = ms("DG_NET_JITTER_MS").unwrap_or_default(); + let loss = lookup("DG_NET_LOSS") + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(0.0); + let retransmit = ms("DG_NET_RETRANSMIT_MS").unwrap_or(Duration::from_millis(200)); + (!latency.is_zero() || !jitter.is_zero() || loss > 0.0) + .then(|| Self::new(latency, jitter).with_loss(loss, retransmit)) + } + + /// One-way delay for one message. + pub fn delay(&self, rng: &mut ZoneRng) -> Duration { + let mut delay = self.latency + self.jitter.mul_f32(rng.next_f32()); + for _ in 0..3 { + if self.loss <= 0.0 || !rng.chance(self.loss) { + break; + } + delay += self.retransmit; + } + delay + } + + /// The JSON shape of dev controls (`{latencyMs, jitterMs, loss}`); `None` + /// reads as all zero. + pub fn to_json(sim: Option) -> NetSimJson { + let sim = sim.unwrap_or_default(); + NetSimJson { + latency_ms: sim.latency.as_millis() as u64, + jitter_ms: sim.jitter.as_millis() as u64, + loss: sim.loss, + } + } +} + +/// A [`NetSim`] as dev routes exchange it: milliseconds, loss as a +/// fraction (retransmit is the default 200 ms). +#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NetSimJson { + /// One-way latency (ms). + #[serde(default)] + pub latency_ms: u64, + /// Jitter (ms). + #[serde(default)] + pub jitter_ms: u64, + /// Loss (fraction, `0..=0.5`). + #[serde(default)] + pub loss: f32, +} + +impl NetSimJson { + /// The simulation (bounded for dev use: ≤ 2 s latency and jitter, ≤ 50 % + /// loss); `None` when everything is zero. + pub fn to_sim(self) -> Option { + let latency = Duration::from_millis(self.latency_ms.min(2_000)); + let jitter = Duration::from_millis(self.jitter_ms.min(2_000)); + let loss = if self.loss.is_finite() { + self.loss.clamp(0.0, 0.5) + } else { + 0.0 + }; + (!latency.is_zero() || !jitter.is_zero() || loss > 0.0) + .then(|| NetSim::new(latency, jitter).with_loss(loss, Duration::from_millis(200))) + } +} + +/// Order-preserving delay line for one direction of one connection, over +/// millisecond timestamps. +#[derive(Debug)] +pub struct DelayLine { + rng: ZoneRng, + queue: VecDeque<(f64, T)>, + last: f64, +} + +impl DelayLine { + /// An empty line (`seed` drives jitter and loss). + pub fn new(seed: u64) -> Self { + Self { + rng: ZoneRng::from_seed(seed), + queue: VecDeque::new(), + last: f64::MIN, + } + } + + /// Queue `item` sent at `now_ms` under `sim`. Returns it back when it is + /// due immediately (no simulation and nothing still queued: order is + /// preserved when the simulation is switched off mid-flight). + pub fn push(&mut self, sim: Option, now_ms: f64, item: T) -> Option { + let delay = match sim { + Some(sim) => sim.delay(&mut self.rng).as_secs_f64() * 1000.0, + None if self.queue.is_empty() => return Some(item), + None => 0.0, + }; + let at = (now_ms + delay).max(self.last); + self.last = at; + self.queue.push_back((at, item)); + None + } + + /// When the next item is due (ms), if any is queued. + pub fn next_due(&self) -> Option { + self.queue.front().map(|(at, _)| *at) + } + + /// The next item if it is due at `now_ms`. + pub fn pop_due(&mut self, now_ms: f64) -> Option { + if self.queue.front()?.0 <= now_ms { + self.queue.pop_front().map(|(_, item)| item) + } else { + None + } + } + + /// Items queued. + pub fn len(&self) -> usize { + self.queue.len() + } + + /// Nothing queued. + pub fn is_empty(&self) -> bool { + self.queue.is_empty() + } + + /// Drop everything queued. + pub fn clear(&mut self) { + self.queue.clear(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn from_env_and_loss_semantics() { + let env = |pairs: &'static [(&'static str, &'static str)]| { + move |k: &str| { + pairs + .iter() + .find(|(key, _)| *key == k) + .map(|(_, v)| v.to_string()) + } + }; + assert_eq!(NetSim::from_lookup(env(&[])), None); + let sim = NetSim::from_lookup(env(&[ + ("DG_NET_LATENCY_MS", "40"), + ("DG_NET_JITTER_MS", "10"), + ("DG_NET_LOSS", "0.5"), + ])) + .unwrap(); + assert_eq!(sim.latency, Duration::from_millis(40)); + assert_eq!(sim.jitter, Duration::from_millis(10)); + assert_eq!(sim.retransmit, Duration::from_millis(200)); + let mut rng = ZoneRng::from_seed(7); + let delays: Vec = (0..2000).map(|_| sim.delay(&mut rng)).collect(); + let base_max = Duration::from_millis(50); + let retransmitted = delays.iter().filter(|d| **d > base_max).count(); + // P(at least one retransmit) = 0.5. + assert!((850..1150).contains(&retransmitted), "{retransmitted}"); + assert!(delays.iter().all(|d| *d >= sim.latency)); + assert!(delays.iter().all(|d| *d <= base_max + sim.retransmit * 3)); + // Without loss the delay is bounded by latency + jitter. + let clean = NetSim::new(Duration::from_millis(40), Duration::from_millis(10)); + assert!((0..500).all(|_| clean.delay(&mut rng) <= base_max)); + } + + #[test] + fn switching_the_simulation_preserves_order() { + let mut line = DelayLine::new(1); + let on = Some(NetSim::new(Duration::from_millis(200), Duration::ZERO)); + assert_eq!(line.push(None, 0.0, 1), Some(1), "no simulation: immediate"); + assert_eq!( + line.push(on, 0.0, 2), + None, + "simulation switched on: delayed" + ); + assert_eq!(line.next_due(), Some(200.0)); + assert_eq!( + line.push(None, 10.0, 3), + None, + "switched off: queues behind 2" + ); + assert_eq!(line.pop_due(150.0), None); + assert_eq!(line.pop_due(200.0), Some(2)); + assert_eq!(line.pop_due(200.0), Some(3)); + assert_eq!( + line.push(None, 300.0, 4), + Some(4), + "drained: immediate again" + ); + } + + #[test] + fn json_round_trip_is_bounded() { + let json = NetSimJson { + latency_ms: 80, + jitter_ms: 20, + loss: 0.05, + }; + let sim = json.to_sim().expect("on"); + assert_eq!(NetSim::to_json(Some(sim)), json); + assert_eq!(NetSimJson::default().to_sim(), None); + let wild = NetSimJson { + latency_ms: 99_999, + jitter_ms: 0, + loss: f32::NAN, + } + .to_sim() + .expect("on"); + assert_eq!(wild.latency, Duration::from_millis(2_000)); + assert_eq!(wild.loss, 0.0); + } +} diff --git a/distributed_game/src/prediction.rs b/distributed_game/src/prediction.rs new file mode 100644 index 000000000..b3613e046 --- /dev/null +++ b/distributed_game/src/prediction.rs @@ -0,0 +1,363 @@ +//! Client prediction steps, declared once in Rust and compiled to +//! WebAssembly for the browser. +//! +//! A zone's **predicted step** is a pure function `(state, input, context, +//! dt) -> state` over the locally controlled entity. The server runs it in +//! `on_tick` (directly or through the code it wraps); the browser runs the +//! *same* function compiled to `wasm32-unknown-unknown`, so client prediction +//! cannot drift from the simulation. Declare it with the `#[predict]` +//! attribute: +//! +//! ```ignore +//! /// What a client predicts for its own `player` entity. +//! #[predict(ArenaStep, kind = "player")] +//! pub fn arena_step(state: &MoveState, input: &MoveInput, _: &(), _dt: f32) -> MoveState { +//! movement::step(*state, *input) +//! } +//! +//! pub fn game_surface() -> GameSurface { +//! GameSurface::for_zone::("arena").predict::() +//! } +//! ``` +//! +//! - `State` is a `#[derive(GameRecord)]` struct whose fields are named after +//! fields of the predicted kind (`x`, `vx`, `cd`, …) and use their plain +//! scalar types (`f32` for a quantized field). The client rebases on the +//! authoritative copy of those fields. +//! - `Input` is the zone's `#[derive(GameInput)]` type; the WASM side decodes +//! it with `from_payload`, so it sees exactly what the server simulates +//! (ranges clamped, unknown buttons cleared). +//! - `Context` is `()` or a `#[derive(GameRecord)]` struct the client sets +//! (`prediction.setContext(..)`), e.g. the world seed and cell a step +//! collides against. +//! - `dt` is the input's frame length in seconds as the client sent it. +//! Prefer fixed command frames (one input = one tick) and ignore it. +//! +//! # Binary ABI +//! +//! The attribute emits, on `wasm32` only, one export per step: +//! `dg_predict_(state_len, input_len, context_len, dt) -> i32`. The +//! module also exports `dg_predict_buffer() -> *mut u8` (a +//! [`SCRATCH_BYTES`] scratch area), `dg_predict_abi() -> u32` +//! ([`ABI_VERSION`]) and its memory, and imports nothing. The caller writes +//! `state ‖ input ‖ context` (codec encodings: `state` and `context` with +//! [`Wire`], `input` as its payload) into the buffer and calls the step; a +//! non-negative result is the length of the next state, written at the +//! start of the buffer; negative values are [`AbiError`] codes. No allocation +//! crosses the boundary and nothing is JSON: floats stay binary32. +//! +//! Pure functions (`#[game_pure]`, [`crate::pure`]) live in the same module +//! and share the buffer and ABI version: `dg_pure_(arg_len) -> i32`. +//! +//! # Determinism +//! +//! Native and WASM results are bit-identical when the step uses only +//! IEEE-754 operations that are correctly rounded on both targets: `+ - * /`, +//! `sqrt`, `abs`, `min`/`max`, `floor`/`ceil`/`trunc`/`round`, comparisons +//! and integer arithmetic. Rust never contracts `a * b + c` into an FMA on +//! its own. **Transcendentals are not portable**: `sin`, `cos`, `atan2`, +//! `exp`, `ln`, `powf` call the platform's libm natively and a different +//! implementation on `wasm32`, which may round differently. Use a +//! deterministic implementation on both sides (the `libm` crate, or a +//! polynomial in plain arithmetic) for anything the step computes with them. +//! NaN payloads may differ, so a step must not produce NaN. + +use crate::authoring::GameInput; +use crate::codec::{Wire, WireType}; +use crate::protocol::wire::{DecodeError, Reader, Writer}; +use crate::surface::RecordSurface; + +/// Version of the binary ABI exported as `dg_predict_abi`. +pub const ABI_VERSION: u32 = 1; + +/// Size of the scratch buffer behind `dg_predict_buffer` (state, input and +/// context together; the next state is written back into it). +pub const SCRATCH_BYTES: usize = 64 * 1024; + +/// A zone's client-predicted step (see the module docs). Implemented by the +/// `#[predict]` attribute; implement it by hand only when the attribute +/// does not fit (and then also export the step, see [`run_abi`]). +pub trait PredictStep { + /// Name of the predicted kind (the controlled entity's kind). + const KIND: &'static str; + /// Cargo package that declares the step (`env!("CARGO_PKG_NAME")`); the + /// CLI compiles this package to WebAssembly. + const PACKAGE: &'static str; + /// Export suffix: the step is `dg_predict_` in the module. + const EXPORT: &'static str; + /// Predicted fields of the kind (a `#[derive(GameRecord)]` struct). + type State: Wire; + /// The zone's input frame. + type Input: GameInput; + /// Read-only data the client provides (`()` for none). + type Context: PredictContext; + + /// Advance one input frame. + fn step( + state: &Self::State, + input: &Self::Input, + context: &Self::Context, + dt: f32, + ) -> Self::State; +} + +/// The context type of a [`PredictStep`]: `()` (nothing) or any record. +pub trait PredictContext: Sized { + /// Wire type, or `None` for `()`. + fn context_type() -> Option; + /// Push the records it mentions. + fn context_records(out: &mut Vec); + /// Decode a whole context. + fn decode_context(bytes: &[u8]) -> Result; + /// Encode (native tools and tests). + fn encode_context(&self) -> Vec; +} + +impl PredictContext for () { + fn context_type() -> Option { + None + } + fn context_records(_out: &mut Vec) {} + fn decode_context(bytes: &[u8]) -> Result { + if bytes.is_empty() { + Ok(()) + } else { + Err(DecodeError::Invalid("this step takes no context")) + } + } + fn encode_context(&self) -> Vec { + Vec::new() + } +} + +impl PredictContext for T { + fn context_type() -> Option { + Some(T::wire_type()) + } + fn context_records(out: &mut Vec) { + T::records(out); + } + fn decode_context(bytes: &[u8]) -> Result { + crate::codec::from_bytes(bytes) + } + fn encode_context(&self) -> Vec { + crate::codec::to_bytes(self) + } +} + +/// Negative results of a step export. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(i32)] +pub enum AbiError { + /// The lengths exceed the scratch buffer. + TooLarge = -1, + /// The state bytes do not decode. + State = -2, + /// The input payload does not decode or is rejected by sanitize. + Input = -3, + /// The context bytes do not decode. + Context = -4, + /// The next state (or a pure function's output) does not fit the + /// scratch buffer. + Output = -5, + /// A pure function's argument does not decode ([`crate::pure`]). + Argument = -6, +} + +/// One step over encoded bytes: what the WASM export does, callable +/// natively (tools, tests). Returns the encoded next state. +pub fn step_bytes( + state: &[u8], + input: &[u8], + context: &[u8], + dt: f32, +) -> Result, AbiError> { + let state = crate::codec::from_bytes::(state).map_err(|_| AbiError::State)?; + let input = P::Input::from_payload(input).ok_or(AbiError::Input)?; + let context = P::Context::decode_context(context).map_err(|_| AbiError::Context)?; + let next = P::step(&state, &input, &context, dt); + let mut w = Writer::new(); + next.encode(&mut w); + Ok(w.into_bytes()) +} + +/// The ABI over a buffer laid out as `state ‖ input ‖ context`: decodes, +/// steps and writes the next state at the start of `buffer`. Returns its +/// length or a negative [`AbiError`] code. The WASM exports call this on +/// the scratch buffer. +pub fn run_abi( + buffer: &mut [u8], + state_len: u32, + input_len: u32, + context_len: u32, + dt: f32, +) -> i32 { + let (s, i, c) = (state_len as usize, input_len as usize, context_len as usize); + let Some(total) = s.checked_add(i).and_then(|n| n.checked_add(c)) else { + return AbiError::TooLarge as i32; + }; + if total > buffer.len() { + return AbiError::TooLarge as i32; + } + let next = match step_bytes::

(&buffer[..s], &buffer[s..s + i], &buffer[s + i..total], dt) { + Ok(next) => next, + Err(error) => return error as i32, + }; + if next.len() > buffer.len() { + return AbiError::Output as i32; + } + buffer[..next.len()].copy_from_slice(&next); + next.len() as i32 +} + +/// Decode a state (native tools and tests). +pub fn decode_state(bytes: &[u8]) -> Result { + let mut r = Reader::new(bytes); + let state = P::State::decode(&mut r)?; + r.finish()?; + Ok(state) +} + +#[cfg(target_arch = "wasm32")] +mod wasm { + use std::cell::UnsafeCell; + + struct Scratch(UnsafeCell<[u8; super::SCRATCH_BYTES]>); + // wasm32-unknown-unknown without atomics is single-threaded. + unsafe impl Sync for Scratch {} + + static SCRATCH: Scratch = Scratch(UnsafeCell::new([0; super::SCRATCH_BYTES])); + + /// Address of the scratch buffer (`state ‖ input ‖ context` in, next state out). + #[unsafe(no_mangle)] + pub extern "C" fn dg_predict_buffer() -> *mut u8 { + SCRATCH.0.get().cast() + } + + /// [`super::ABI_VERSION`]. + #[unsafe(no_mangle)] + pub extern "C" fn dg_predict_abi() -> u32 { + super::ABI_VERSION + } + + /// The scratch buffer (generated step and pure function exports). + pub fn scratch() -> &'static mut [u8] { + // SAFETY: single-threaded; each export call borrows it once and + // returns before the next call. + unsafe { &mut *SCRATCH.0.get() } + } +} + +/// The module's scratch buffer (`wasm32` only). +#[cfg(target_arch = "wasm32")] +pub(crate) fn scratch_buffer() -> &'static mut [u8] { + wasm::scratch() +} + +/// Body of a generated step export (`#[predict]`, `wasm32` only). +#[cfg(target_arch = "wasm32")] +#[doc(hidden)] +pub fn wasm_export( + state_len: u32, + input_len: u32, + context_len: u32, + dt: f32, +) -> i32 { + run_abi::

(publisher: P, capacity: usize) -> Self + where + P: MessagePublisher + 'static, + { + let pending = Arc::new(Mutex::new(Pending { + boards: BTreeSet::new(), + all: false, + capacity: capacity.max(1), + })); + let (wake, mut woken) = mpsc::channel::<()>(1); + let queue = Arc::clone(&pending); + tokio::spawn(async move { + while woken.recv().await.is_some() { + let notices = queue.lock().expect("pending boards").take(); + for notice in notices { + publish(&publisher, notice.to_message()).await; + } + } + }); + Self { pending, wake } + } + + /// A projector change listener that queues a notice per changed board. + pub fn listener(&self) -> LeaderboardChangeListener { + let handle = self.clone(); + Arc::new(move |board: &Board| { + handle + .pending + .lock() + .expect("pending boards") + .add(board.name()); + let _ = handle.wake.try_send(()); + }) + } +} + +async fn publish(publisher: &P, message: Message) { + let mut delay = RETRY_FIRST; + loop { + match publisher.publish(message.clone()).await { + Ok(()) => return, + Err(error) if error.is_permanent() => { + tracing::warn!(%error, "leaderboard change notice refused; dropped"); + return; + } + Err(error) => { + tracing::warn!(%error, "leaderboard change notice failed; retrying"); + tokio::time::sleep(delay).await; + delay = (delay * 2).min(RETRY_MAX); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn notices_round_trip_and_reject_garbage() { + let board = Board::high_first("mobpit.xp").unwrap(); + let message = LeaderboardChanged::new(&board).to_message(); + assert_eq!(message.name, LEADERBOARD_CHANGED_EVENT); + assert_eq!(message.kind, MessageKind::Event); + assert!(message.id.is_some()); + assert_eq!( + LeaderboardChanged::from_message(&message).unwrap(), + LeaderboardChanged::new(&board) + ); + let all = LeaderboardChanged::all().to_message(); + assert_eq!(all.payload, b"{}"); + assert_eq!( + LeaderboardChanged::from_message(&all).unwrap().change_key(), + ALL_BOARDS_CHANGE_KEY + ); + let bad_board = Message::new( + LEADERBOARD_CHANGED_EVENT, + MessageKind::Event, + br#"{"board":"bad{tag}"}"#.to_vec(), + ); + assert!(LeaderboardChanged::from_message(&bad_board).is_err()); + let unknown = Message::new( + LEADERBOARD_CHANGED_EVENT, + MessageKind::Event, + br#"{"boards":"x"}"#.to_vec(), + ); + assert!(LeaderboardChanged::from_message(&unknown).is_err()); + } + + /// Forwards each publish attempt; fails the first `fail` ones with `error`. + struct Recording { + sent: mpsc::UnboundedSender>, + fail: Mutex>, + } + + impl MessagePublisher for Recording { + async fn publish(&self, message: Message) -> Result<(), TransportError> { + let notice = LeaderboardChanged::from_message(&message).unwrap(); + if let Some(error) = self.fail.lock().unwrap().pop() { + return Err(error); + } + self.sent.send(notice.board).unwrap(); + Ok(()) + } + } + + fn recording( + fail: Vec, + ) -> (Recording, mpsc::UnboundedReceiver>) { + let (sent, rx) = mpsc::unbounded_channel(); + ( + Recording { + sent, + fail: Mutex::new(fail), + }, + rx, + ) + } + + fn board(name: &str) -> Board { + Board::high_first(name).unwrap() + } + + // The current-thread runtime cannot run the publisher task until the + // test awaits, so every listener call below lands before any publish. + #[tokio::test(flavor = "current_thread")] + async fn repeated_changes_coalesce_per_board() { + let (publisher, mut sent) = recording(Vec::new()); + let notices = LeaderboardChangePublisher::spawn(publisher, 4); + let listener = notices.listener(); + for name in ["b", "a", "b", "a", "b"] { + listener(&board(name)); + } + assert_eq!(sent.recv().await.unwrap().as_deref(), Some("a")); + assert_eq!(sent.recv().await.unwrap().as_deref(), Some("b")); + drop((notices, listener)); + assert_eq!(sent.recv().await, None, "the task ends with its handles"); + } + + #[tokio::test(flavor = "current_thread")] + async fn overflow_resyncs_every_board_instead_of_growing() { + let (publisher, mut sent) = recording(Vec::new()); + let notices = LeaderboardChangePublisher::spawn(publisher, 2); + let listener = notices.listener(); + for index in 0..1_000 { + listener(&board(&format!("board-{index}"))); + } + { + let pending = notices.pending.lock().unwrap(); + assert!(pending.all && pending.boards.is_empty(), "{pending:?}"); + } + assert_eq!(sent.recv().await.unwrap(), None, "one every-board notice"); + listener(&board("after")); + assert_eq!( + sent.recv().await.unwrap().as_deref(), + Some("after"), + "per-board notices resume after the resync" + ); + drop((notices, listener)); + assert_eq!(sent.recv().await, None); + } + + #[tokio::test(flavor = "current_thread", start_paused = true)] + async fn retryable_failures_retry_and_permanent_ones_are_dropped() { + let (publisher, mut sent) = recording(vec![ + TransportError::retryable("bus down"), + TransportError::permanent("refused"), + ]); + let notices = LeaderboardChangePublisher::spawn(publisher, 4); + let listener = notices.listener(); + listener(&board("a")); + listener(&board("b")); + // `a` is refused permanently (dropped); `b` fails once, then lands. + assert_eq!(sent.recv().await.unwrap().as_deref(), Some("b")); + drop((notices, listener)); + assert_eq!(sent.recv().await, None, "`a` was not retried"); + } +} diff --git a/distributed_leaderboard/src/projector.rs b/distributed_leaderboard/src/projector.rs new file mode 100644 index 000000000..1711eea82 --- /dev/null +++ b/distributed_leaderboard/src/projector.rs @@ -0,0 +1,563 @@ +//! Event → leaderboard projection, with idempotent apply and rebuild. + +use std::collections::BTreeMap; +use std::sync::Arc; + +use distributed::bus::{Message, TransportError}; +use distributed::DomainEventOccurrence; + +use crate::{ApplyKey, ApplyOutcome, Board, LeaderboardError, LeaderboardStore, ScoreSubmission}; + +/// One score change a projection derives from an occurrence. +#[derive(Debug, Clone, PartialEq)] +pub struct LeaderboardChange { + /// The live board to change (the projector redirects it to staging during + /// a rebuild). + pub board: Board, + /// The submission. + pub submission: ScoreSubmission, +} + +impl LeaderboardChange { + /// Build a change. + pub fn new(board: Board, submission: ScoreSubmission) -> Self { + Self { board, submission } + } +} + +/// Maps domain event occurrences to leaderboard changes. +/// +/// Must be deterministic: replaying an occurrence must yield the same changes +/// in the same order, because each change's dedupe key is +/// `"#"`. Closures +/// `Fn(&DomainEventOccurrence) -> Result, LeaderboardError>` +/// implement this trait and handle every event name. +pub trait LeaderboardProjection: Send + Sync { + /// Whether this projection cares about the event name. Messages for other + /// names are acknowledged without decoding. + fn handles(&self, _event_name: &str) -> bool { + true + } + + /// Changes for one occurrence (possibly none). + fn project( + &self, + event: &DomainEventOccurrence, + ) -> Result, LeaderboardError>; +} + +impl LeaderboardProjection for F +where + F: Fn(&DomainEventOccurrence) -> Result, LeaderboardError> + Send + Sync, +{ + fn project( + &self, + event: &DomainEventOccurrence, + ) -> Result, LeaderboardError> { + self(event) + } +} + +/// Counts from applying one or more occurrences. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct ProjectionReport { + /// Changes applied. + pub applied: u64, + /// Changes skipped as already applied. + pub duplicates: u64, + /// Occurrences skipped because the projection does not handle them. + pub ignored: u64, +} + +impl ProjectionReport { + fn merge(&mut self, other: ProjectionReport) { + self.applied += other.applied; + self.duplicates += other.duplicates; + self.ignored += other.ignored; + } +} + +/// Called with each live board whose scores changed: after an applied (not +/// duplicate) change, and after a rebuild promotes a board. A GraphQL engine +/// turns this into `@live` invalidation +/// (`change_listener`, feature `graphql`). +pub type LeaderboardChangeListener = Arc; + +/// Applies a [`LeaderboardProjection`] to a [`LeaderboardStore`]. +pub struct LeaderboardProjector { + store: Arc, + projection: Arc

, + listeners: Vec, +} + +impl Clone for LeaderboardProjector { + fn clone(&self) -> Self { + Self { + store: Arc::clone(&self.store), + projection: Arc::clone(&self.projection), + listeners: self.listeners.clone(), + } + } +} + +impl LeaderboardProjector +where + S: LeaderboardStore + ?Sized, + P: LeaderboardProjection + ?Sized, +{ + /// A projector over a store and projection. + pub fn new(store: Arc, projection: Arc

) -> Self { + Self { + store, + projection, + listeners: Vec::new(), + } + } + + /// Notify `listener` whenever a live board's scores change. + pub fn with_change_listener(mut self, listener: LeaderboardChangeListener) -> Self { + self.listeners.push(listener); + self + } + + fn notify(&self, board: &Board) { + for listener in &self.listeners { + listener(board); + } + } + + /// The store. + pub fn store(&self) -> &Arc { + &self.store + } + + /// Apply one occurrence to the live boards, idempotently. + pub async fn apply_event( + &self, + event: &DomainEventOccurrence, + ) -> Result { + self.apply_to(event, false).await + } + + async fn apply_to( + &self, + event: &DomainEventOccurrence, + staging: bool, + ) -> Result { + if !self.projection.handles(&event.descriptor().name) { + return Ok(ProjectionReport { + ignored: 1, + ..ProjectionReport::default() + }); + } + let changes = self.projection.project(event)?; + self.apply_changes(event, changes, staging).await + } + + async fn apply_changes( + &self, + event: &DomainEventOccurrence, + changes: Vec, + staging: bool, + ) -> Result { + let mut report = ProjectionReport::default(); + for (index, change) in changes.into_iter().enumerate() { + let board = if staging { + change.board.staging() + } else { + change.board.live() + }; + let key = ApplyKey::new( + format!("{}#{index}", event.id()), + event.occurred_at_unix_ms(), + ); + match self.store.apply(&board, &change.submission, &key).await? { + ApplyOutcome::Applied { .. } => { + report.applied += 1; + if !staging { + self.notify(&board); + } + } + ApplyOutcome::Duplicate { .. } => report.duplicates += 1, + } + } + Ok(report) + } + + /// Decode an outbox/bus message carrying a canonical + /// [`DomainEventOccurrence`] and apply it. + /// + /// Suitable as a bus event handler body: an unavailable store maps to a + /// retryable [`TransportError`] (redelivery is safe thanks to dedupe), an + /// undecodable payload or invalid change to a permanent one. + pub async fn apply_message( + &self, + message: &Message, + ) -> Result { + if !self.projection.handles(message.name()) { + return Ok(ProjectionReport { + ignored: 1, + ..ProjectionReport::default() + }); + } + let event = + DomainEventOccurrence::from_canonical_bytes(message.payload()).map_err(|err| { + TransportError::permanent(format!("leaderboard: undecodable occurrence: {err}")) + })?; + self.apply_event(&event).await.map_err(Into::into) + } + + /// Start a rebuild of `boards` (live variants) into their staging + /// variants. Boards the projection touches during the rebuild but that are + /// not listed are added (and promoted) automatically; listed boards that + /// receive no changes are promoted empty. + pub async fn begin_rebuild( + &self, + boards: &[Board], + ) -> Result, LeaderboardError> { + let mut rebuild = LeaderboardRebuild { + projector: self.clone(), + boards: BTreeMap::new(), + report: ProjectionReport::default(), + }; + for board in boards { + rebuild.touch(board).await?; + } + Ok(rebuild) + } + + /// Rebuild from a complete event history in one call: begin, apply every + /// occurrence, commit. + pub async fn rebuild( + &self, + boards: &[Board], + events: I, + ) -> Result + where + I: IntoIterator, + I::Item: std::borrow::Borrow, + { + let mut rebuild = self.begin_rebuild(boards).await?; + for event in events { + rebuild + .apply_event(std::borrow::Borrow::borrow(&event)) + .await?; + } + rebuild.commit().await + } +} + +/// An in-progress rebuild; feed it the event history (from any sync or async +/// source) and [`commit`](LeaderboardRebuild::commit). +pub struct LeaderboardRebuild { + projector: LeaderboardProjector, + boards: BTreeMap, + report: ProjectionReport, +} + +impl LeaderboardRebuild +where + S: LeaderboardStore + ?Sized, + P: LeaderboardProjection + ?Sized, +{ + async fn touch(&mut self, board: &Board) -> Result<(), LeaderboardError> { + if !self.boards.contains_key(board.name()) { + self.projector.store.reset(&board.staging()).await?; + self.boards.insert(board.name().to_string(), board.live()); + } + Ok(()) + } + + /// Apply one historical occurrence to the staging boards. + pub async fn apply_event( + &mut self, + event: &DomainEventOccurrence, + ) -> Result<(), LeaderboardError> { + if !self.projector.projection.handles(&event.descriptor().name) { + self.report.ignored += 1; + return Ok(()); + } + let changes = self.projector.projection.project(event)?; + for change in &changes { + self.touch(&change.board).await?; + } + let report = self.projector.apply_changes(event, changes, true).await?; + self.report.merge(report); + Ok(()) + } + + /// Boards that will be promoted. + pub fn boards(&self) -> impl Iterator { + self.boards.values() + } + + /// Atomically promote every staging board over its live board. + pub async fn commit(self) -> Result { + for board in self.boards.values() { + self.projector.store.promote(board).await?; + self.projector.notify(board); + } + Ok(self.report) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{InMemoryLeaderboard, LeaderboardErrorKind, ScorePolicy}; + use distributed::bus::MessageKind; + use std::time::{Duration, UNIX_EPOCH}; + + #[derive(serde::Serialize, serde::Deserialize, distributed::DomainEvent)] + #[domain_event(name = "test.monster_slain", version = 1)] + struct MonsterSlain { + player: String, + xp: u32, + } + + #[derive(serde::Serialize, serde::Deserialize, distributed::DomainEvent)] + #[domain_event(name = "test.chat_sent", version = 1)] + struct ChatSent { + text: String, + } + + fn slain(position: u64, player: &str, xp: u32) -> DomainEventOccurrence { + DomainEventOccurrence::capture_external( + distributed::ExternalEventSource { + producer: "zone.sim".into(), + stream: "zone-1".into(), + position, + key: "kill".into(), + }, + UNIX_EPOCH + Duration::from_millis(position * 1_000), + Default::default(), + &MonsterSlain { + player: player.into(), + xp, + }, + ) + .unwrap() + } + + fn chat(position: u64) -> DomainEventOccurrence { + DomainEventOccurrence::capture_external( + distributed::ExternalEventSource { + producer: "zone.sim".into(), + stream: "zone-1".into(), + position, + key: "chat".into(), + }, + UNIX_EPOCH, + Default::default(), + &ChatSent { text: "hi".into() }, + ) + .unwrap() + } + + fn message(event: &DomainEventOccurrence) -> Message { + Message::new( + event.descriptor().name.to_string(), + MessageKind::Event, + event.canonical_bytes().unwrap(), + ) + .with_id(event.id()) + } + + struct XpProjection; + + impl LeaderboardProjection for XpProjection { + fn handles(&self, name: &str) -> bool { + name == "test.monster_slain" + } + + fn project( + &self, + event: &DomainEventOccurrence, + ) -> Result, LeaderboardError> { + let body: MonsterSlain = event + .decode_body() + .map_err(|err| LeaderboardError::invalid(err.to_string()))?; + Ok(vec![ + LeaderboardChange::new( + xp_board(), + ScoreSubmission::new(&body.player, f64::from(body.xp), ScorePolicy::Increment), + ), + LeaderboardChange::new( + best_board(), + ScoreSubmission::new(&body.player, f64::from(body.xp), ScorePolicy::Max), + ), + ]) + } + } + + fn xp_board() -> Board { + Board::high_first("xp").unwrap() + } + + fn best_board() -> Board { + Board::high_first("best-kill").unwrap() + } + + fn projector() -> LeaderboardProjector { + LeaderboardProjector::new(Arc::new(InMemoryLeaderboard::new()), Arc::new(XpProjection)) + } + + #[tokio::test] + async fn replayed_events_do_not_double_increment() { + let projector = projector(); + let events = [ + slain(1, "ann", 10), + slain(2, "bob", 30), + slain(3, "ann", 25), + ]; + for event in &events { + let report = projector.apply_event(event).await.unwrap(); + assert_eq!(report.applied, 2); + } + for event in &events { + let report = projector.apply_event(event).await.unwrap(); + assert_eq!(report.duplicates, 2); + assert_eq!(report.applied, 0); + } + let store = projector.store(); + assert_eq!(store.score(&xp_board(), "ann").await.unwrap(), Some(35.0)); + assert_eq!(store.score(&best_board(), "ann").await.unwrap(), Some(25.0)); + assert_eq!(store.rank(&xp_board(), "ann").await.unwrap(), Some(0)); + assert_eq!(store.rank(&best_board(), "bob").await.unwrap(), Some(0)); + } + + #[tokio::test] + async fn messages_decode_and_classify_errors() { + let projector = projector(); + let first = message(&slain(1, "ann", 10)); + assert_eq!(projector.apply_message(&first).await.unwrap().applied, 2); + assert_eq!(projector.apply_message(&first).await.unwrap().duplicates, 2); + + let ignored = projector.apply_message(&message(&chat(2))).await.unwrap(); + assert_eq!(ignored.ignored, 1); + + let garbage = Message::new("test.monster_slain", MessageKind::Event, b"nope".to_vec()); + assert!(projector + .apply_message(&garbage) + .await + .unwrap_err() + .is_permanent()); + + assert!(LeaderboardError::unavailable("down") + .into_transport_error() + .is_retryable()); + assert_eq!( + LeaderboardError::invalid("x").kind(), + LeaderboardErrorKind::Invalid + ); + } + + #[tokio::test] + async fn rebuild_replaces_drifted_live_boards_atomically() { + let projector = projector(); + let history = vec![ + slain(1, "ann", 10), + slain(2, "bob", 30), + slain(3, "ann", 25), + ]; + for event in &history { + projector.apply_event(event).await.unwrap(); + } + let store = Arc::clone(projector.store()); + // Drift: a direct write and a stale board that the history never touches. + store + .submit( + &xp_board(), + &ScoreSubmission::new("cheater", 1e9, ScorePolicy::Replace), + ) + .await + .unwrap(); + let stale = Board::high_first("retired").unwrap(); + store + .submit( + &stale, + &ScoreSubmission::new("x", 1.0, ScorePolicy::Replace), + ) + .await + .unwrap(); + + // Boards are discovered from the history; `stale` is listed so it empties. + let mut rebuild = projector + .begin_rebuild(std::slice::from_ref(&stale)) + .await + .unwrap(); + for event in &history[..2] { + rebuild.apply_event(event).await.unwrap(); + } + // Mid-rebuild, live reads still see the old boards. + assert_eq!( + store.score(&xp_board(), "cheater").await.unwrap(), + Some(1e9) + ); + rebuild.apply_event(&history[2]).await.unwrap(); + let names: Vec<_> = rebuild.boards().map(|b| b.name().to_string()).collect(); + assert_eq!(names, vec!["best-kill", "retired", "xp"]); + let report = rebuild.commit().await.unwrap(); + assert_eq!(report.applied, 6); + + assert_eq!(store.score(&xp_board(), "cheater").await.unwrap(), None); + assert_eq!(store.score(&xp_board(), "ann").await.unwrap(), Some(35.0)); + assert_eq!(store.len(&stale).await.unwrap(), 0); + // Tail replay after commit is deduplicated by the promoted applied keys. + let report = projector.apply_event(&history[2]).await.unwrap(); + assert_eq!(report.duplicates, 2); + + // The one-shot helper yields the same result. + let report = projector.rebuild(&[], &history).await.unwrap(); + assert_eq!(report.applied, 6); + assert_eq!(store.score(&xp_board(), "ann").await.unwrap(), Some(35.0)); + } + + #[tokio::test] + async fn closures_are_projections() { + let projection = |event: &DomainEventOccurrence| { + Ok(vec![LeaderboardChange::new( + Board::low_first("first-seen").unwrap(), + ScoreSubmission::new("zone", event.occurred_at_unix_ms() as f64, ScorePolicy::Min), + )]) + }; + let projector = + LeaderboardProjector::new(Arc::new(InMemoryLeaderboard::new()), Arc::new(projection)); + projector.apply_event(&slain(5, "a", 1)).await.unwrap(); + projector.apply_event(&slain(2, "a", 1)).await.unwrap(); + let board = Board::low_first("first-seen").unwrap(); + assert_eq!( + projector.store().score(&board, "zone").await.unwrap(), + Some(2_000.0) + ); + } + + #[tokio::test] + async fn listeners_hear_applied_changes_and_promotions_but_not_duplicates() { + let heard = Arc::new(std::sync::Mutex::new(Vec::::new())); + let log = heard.clone(); + let projector = projector().with_change_listener(Arc::new(move |board: &Board| { + log.lock().unwrap().push(board.name().to_string()); + })); + projector.apply_event(&slain(1, "ann", 10)).await.unwrap(); + projector.apply_event(&slain(1, "ann", 10)).await.unwrap(); + assert_eq!( + *heard.lock().unwrap(), + ["xp", "best-kill"], + "one per applied change; the duplicate is silent" + ); + let boards = [Board::high_first("xp").unwrap()]; + projector + .rebuild(&boards, [slain(1, "ann", 10), slain(2, "bob", 5)]) + .await + .unwrap(); + let heard = heard.lock().unwrap(); + assert_eq!( + heard.len(), + 4, + "one per promoted board, none for staging writes" + ); + assert!(heard[2..].contains(&"xp".to_string())); + assert!(heard[2..].contains(&"best-kill".to_string())); + } +} diff --git a/distributed_leaderboard/src/redis.rs b/distributed_leaderboard/src/redis.rs new file mode 100644 index 000000000..c33d29aed --- /dev/null +++ b/distributed_leaderboard/src/redis.rs @@ -0,0 +1,473 @@ +//! Redis sorted-set [`LeaderboardStore`]. +//! +//! # Key layout +//! +//! Each board variant owns two keys sharing the `{}` hash tag, so +//! every key a script touches lives in one Redis Cluster slot: +//! +//! - `:{}::scores` — `ZSET member → score`; +//! - `:{}::applied` — `ZSET apply-key → event ms`. +//! +//! # Atomicity +//! +//! [`apply`](LeaderboardStore::apply) runs one Lua script that checks the +//! applied set, changes the score (`ZADD GT|LT`, `ZADD` or `ZINCRBY`) and +//! records the key; Redis executes scripts atomically, so concurrent or +//! redelivered applies cannot double-count. [`around`](LeaderboardStore::around) +//! reads rank and range in one script, and [`promote`](LeaderboardStore::promote) +//! renames staging over live in one script. `ZADD GT/LT` requires Redis 6.2+. +//! +//! Scores cross the Lua boundary as strings (Lua numbers would truncate to +//! integers in replies), using Redis' round-trip-exact `%.17g` formatting. + +use std::time::Duration; + +use async_trait::async_trait; +use redis::aio::{ConnectionManager, ConnectionManagerConfig}; +use redis::{Client, Script, Value}; + +use crate::{ + validate_member, ApplyKey, ApplyOutcome, Board, LeaderboardEntry, LeaderboardError, + LeaderboardStore, ScoreOrder, ScoreSubmission, +}; + +/// Default key prefix. +pub const DEFAULT_REDIS_LEADERBOARD_PREFIX: &str = "distributed:lb"; + +const APPLY_SCRIPT: &str = r#" +local id = ARGV[4] +if id ~= '' and redis.call('ZSCORE', KEYS[2], id) then + return {0, redis.call('ZSCORE', KEYS[1], ARGV[1])} +end +local policy = ARGV[3] +local score +if policy == 'increment' then + score = redis.call('ZINCRBY', KEYS[1], ARGV[2], ARGV[1]) +else + if policy == 'max' then + redis.call('ZADD', KEYS[1], 'GT', ARGV[2], ARGV[1]) + elseif policy == 'min' then + redis.call('ZADD', KEYS[1], 'LT', ARGV[2], ARGV[1]) + else + redis.call('ZADD', KEYS[1], ARGV[2], ARGV[1]) + end + score = redis.call('ZSCORE', KEYS[1], ARGV[1]) +end +if id ~= '' then + redis.call('ZADD', KEYS[2], ARGV[5], id) +end +return {1, score} +"#; + +const AROUND_SCRIPT: &str = r#" +local high = ARGV[2] == 'high' +local rank +if high then + rank = redis.call('ZREVRANK', KEYS[1], ARGV[1]) +else + rank = redis.call('ZRANK', KEYS[1], ARGV[1]) +end +if not rank then + return {} +end +local radius = tonumber(ARGV[3]) +local start = rank - radius +if start < 0 then start = 0 end +local stop = rank + radius +local rows +if high then + rows = redis.call('ZREVRANGE', KEYS[1], start, stop, 'WITHSCORES') +else + rows = redis.call('ZRANGE', KEYS[1], start, stop, 'WITHSCORES') +end +table.insert(rows, 1, start) +return rows +"#; + +const PROMOTE_SCRIPT: &str = r#" +redis.call('DEL', KEYS[3], KEYS[4]) +if redis.call('EXISTS', KEYS[1]) == 1 then + redis.call('RENAME', KEYS[1], KEYS[3]) +end +if redis.call('EXISTS', KEYS[2]) == 1 then + redis.call('RENAME', KEYS[2], KEYS[4]) +end +return 1 +"#; + +/// A [`LeaderboardStore`] on Redis sorted sets. +/// +/// Uses a [`ConnectionManager`], which multiplexes requests and reconnects in +/// the background; [`connect`](RedisLeaderboard::connect) configures short +/// connection/response timeouts so callers fail fast (as +/// [`LeaderboardErrorKind::Unavailable`](super::LeaderboardErrorKind::Unavailable)) +/// instead of hanging while Redis is down. +#[derive(Clone)] +pub struct RedisLeaderboard { + conn: ConnectionManager, + prefix: String, + apply: Script, + around: Script, + promote: Script, +} + +pub(crate) fn unavailable(context: &str, err: redis::RedisError) -> LeaderboardError { + LeaderboardError::unavailable(format!("redis {context}: {err}")) +} + +impl RedisLeaderboard { + /// Default connection and response timeout used by [`connect`](Self::connect). + pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(2); + + /// Connect lazily to `url` (e.g. `redis://127.0.0.1:6379`). Construction + /// does not contact Redis, so service start-up never waits on it. + pub fn connect(url: &str) -> Result { + let client = Client::open(url) + .map_err(|err| LeaderboardError::invalid(format!("redis url: {err}")))?; + let config = ConnectionManagerConfig::new() + .set_connection_timeout(Some(Self::DEFAULT_TIMEOUT)) + .set_response_timeout(Some(Self::DEFAULT_TIMEOUT)) + .set_number_of_retries(1); + let conn = client + .get_connection_manager_lazy(config) + .map_err(|err| unavailable("connect", err))?; + Ok(Self::new(conn)) + } + + /// Wrap an existing connection manager. + pub fn new(conn: ConnectionManager) -> Self { + Self { + conn, + prefix: DEFAULT_REDIS_LEADERBOARD_PREFIX.to_string(), + apply: Script::new(APPLY_SCRIPT), + around: Script::new(AROUND_SCRIPT), + promote: Script::new(PROMOTE_SCRIPT), + } + } + + /// Use a different key prefix (e.g. per environment or per test). + pub fn with_prefix(mut self, prefix: impl Into) -> Self { + self.prefix = prefix.into(); + self + } + + fn key(&self, board: &Board, staging: bool, part: &str) -> String { + let variant = if staging { "staging" } else { "live" }; + format!("{}:{{{}}}:{variant}:{part}", self.prefix, board.name()) + } + + fn scores(&self, board: &Board) -> String { + self.key(board, board.is_staging(), "scores") + } + + fn applied(&self, board: &Board) -> String { + self.key(board, board.is_staging(), "applied") + } + + async fn run_apply( + &self, + board: &Board, + submission: &ScoreSubmission, + key: Option<&ApplyKey>, + ) -> Result<(bool, Option), LeaderboardError> { + submission.validate()?; + if let Some(key) = key { + key.validate()?; + } + let mut conn = self.conn.clone(); + let reply: Value = self + .apply + .key(self.scores(board)) + .key(self.applied(board)) + .arg(&submission.member) + .arg(format_score(submission.score)) + .arg(submission.policy.as_str()) + .arg(key.map_or("", |k| k.id.as_str())) + .arg(key.map_or(0, |k| k.at_unix_ms)) + .invoke_async(&mut conn) + .await + .map_err(|err| map_write_error("apply", err))?; + let Value::Array(items) = reply else { + return Err(LeaderboardError::unavailable( + "redis apply: unexpected reply", + )); + }; + let applied = matches!(items.first(), Some(Value::Int(1))); + let score = match items.get(1) { + Some(value) => parse_optional_score(value)?, + None => None, + }; + Ok((applied, score)) + } + + fn parse_rows( + &self, + values: &[Value], + first_rank: u64, + ) -> Result, LeaderboardError> { + values + .chunks(2) + .enumerate() + .map(|(offset, pair)| { + let [member, score] = pair else { + return Err(LeaderboardError::unavailable("redis: odd WITHSCORES reply")); + }; + Ok(LeaderboardEntry { + rank: first_rank + offset as u64, + member: parse_string(member)?, + score: parse_optional_score(score)? + .ok_or_else(|| LeaderboardError::unavailable("redis: missing score"))?, + }) + }) + .collect() + } +} + +/// A write that Redis rejects as an error reply (e.g. an increment overflowing +/// to infinity, or a server too old for `ZADD GT`) is not transient. +fn map_write_error(context: &str, err: redis::RedisError) -> LeaderboardError { + if err.kind() == redis::ErrorKind::Server(redis::ServerErrorKind::ResponseError) { + LeaderboardError::invalid(format!("redis {context}: {err}")) + } else { + unavailable(context, err) + } +} + +fn format_score(score: f64) -> String { + // Rust's shortest round-trip representation; Redis parses it with strtod. + format!("{score:?}") +} + +fn parse_string(value: &Value) -> Result { + match value { + Value::BulkString(bytes) => String::from_utf8(bytes.clone()) + .map_err(|_| LeaderboardError::unavailable("redis: non-utf8 member")), + Value::SimpleString(s) => Ok(s.clone()), + _ => Err(LeaderboardError::unavailable( + "redis: unexpected member reply", + )), + } +} + +fn parse_optional_score(value: &Value) -> Result, LeaderboardError> { + match value { + Value::Nil => Ok(None), + Value::Boolean(false) => Ok(None), + Value::Double(score) => Ok(Some(*score)), + Value::Int(score) => Ok(Some(*score as f64)), + other => { + let text = parse_string(other)?; + text.parse::() + .map(Some) + .map_err(|_| LeaderboardError::unavailable(format!("redis: bad score {text:?}"))) + } + } +} + +fn parse_rank(value: &Value) -> Result { + match value { + Value::Int(rank) if *rank >= 0 => Ok(*rank as u64), + _ => Err(LeaderboardError::unavailable( + "redis: unexpected rank reply", + )), + } +} + +#[async_trait] +impl LeaderboardStore for RedisLeaderboard { + async fn submit( + &self, + board: &Board, + submission: &ScoreSubmission, + ) -> Result { + let (_, score) = self.run_apply(board, submission, None).await?; + score.ok_or_else(|| LeaderboardError::unavailable("redis submit: missing score")) + } + + async fn apply( + &self, + board: &Board, + submission: &ScoreSubmission, + key: &ApplyKey, + ) -> Result { + match self.run_apply(board, submission, Some(key)).await? { + (true, Some(score)) => Ok(ApplyOutcome::Applied { score }), + (true, None) => Err(LeaderboardError::unavailable("redis apply: missing score")), + (false, score) => Ok(ApplyOutcome::Duplicate { score }), + } + } + + async fn score(&self, board: &Board, member: &str) -> Result, LeaderboardError> { + validate_member(member)?; + let mut conn = self.conn.clone(); + let value: Value = redis::cmd("ZSCORE") + .arg(self.scores(board)) + .arg(member) + .query_async(&mut conn) + .await + .map_err(|err| unavailable("ZSCORE", err))?; + parse_optional_score(&value) + } + + async fn rank(&self, board: &Board, member: &str) -> Result, LeaderboardError> { + validate_member(member)?; + let command = match board.order() { + ScoreOrder::HighFirst => "ZREVRANK", + ScoreOrder::LowFirst => "ZRANK", + }; + let mut conn = self.conn.clone(); + let value: Value = redis::cmd(command) + .arg(self.scores(board)) + .arg(member) + .query_async(&mut conn) + .await + .map_err(|err| unavailable(command, err))?; + match value { + Value::Nil => Ok(None), + other => parse_rank(&other).map(Some), + } + } + + async fn top( + &self, + board: &Board, + n: usize, + ) -> Result, LeaderboardError> { + if n == 0 { + return Ok(Vec::new()); + } + let command = match board.order() { + ScoreOrder::HighFirst => "ZREVRANGE", + ScoreOrder::LowFirst => "ZRANGE", + }; + let stop = i64::try_from(n - 1).unwrap_or(i64::MAX); + let mut conn = self.conn.clone(); + let value: Value = redis::cmd(command) + .arg(self.scores(board)) + .arg(0) + .arg(stop) + .arg("WITHSCORES") + .query_async(&mut conn) + .await + .map_err(|err| unavailable(command, err))?; + match value { + Value::Array(values) => self.parse_rows(&flatten_pairs(values), 0), + _ => Err(LeaderboardError::unavailable( + "redis: unexpected range reply", + )), + } + } + + async fn around( + &self, + board: &Board, + member: &str, + radius: usize, + ) -> Result, LeaderboardError> { + validate_member(member)?; + let order = match board.order() { + ScoreOrder::HighFirst => "high", + ScoreOrder::LowFirst => "low", + }; + // Keep the Lua arithmetic inside exact double range. + let radius = radius.min(1 << 40); + let mut conn = self.conn.clone(); + let value: Value = self + .around + .key(self.scores(board)) + .arg(member) + .arg(order) + .arg(radius) + .invoke_async(&mut conn) + .await + .map_err(|err| unavailable("around", err))?; + let Value::Array(values) = value else { + return Err(LeaderboardError::unavailable( + "redis: unexpected around reply", + )); + }; + let Some((first, rows)) = values.split_first() else { + return Ok(Vec::new()); + }; + self.parse_rows(rows, parse_rank(first)?) + } + + async fn len(&self, board: &Board) -> Result { + let mut conn = self.conn.clone(); + let value: Value = redis::cmd("ZCARD") + .arg(self.scores(board)) + .query_async(&mut conn) + .await + .map_err(|err| unavailable("ZCARD", err))?; + parse_rank(&value) + } + + async fn remove(&self, board: &Board, member: &str) -> Result { + validate_member(member)?; + let mut conn = self.conn.clone(); + let removed: i64 = redis::cmd("ZREM") + .arg(self.scores(board)) + .arg(member) + .query_async(&mut conn) + .await + .map_err(|err| unavailable("ZREM", err))?; + Ok(removed > 0) + } + + async fn reset(&self, board: &Board) -> Result<(), LeaderboardError> { + let mut conn = self.conn.clone(); + let _: i64 = redis::cmd("DEL") + .arg(self.scores(board)) + .arg(self.applied(board)) + .query_async(&mut conn) + .await + .map_err(|err| unavailable("DEL", err))?; + Ok(()) + } + + async fn promote(&self, board: &Board) -> Result<(), LeaderboardError> { + let mut conn = self.conn.clone(); + let _: i64 = self + .promote + .key(self.key(board, true, "scores")) + .key(self.key(board, true, "applied")) + .key(self.key(board, false, "scores")) + .key(self.key(board, false, "applied")) + .invoke_async(&mut conn) + .await + .map_err(|err| unavailable("promote", err))?; + Ok(()) + } + + async fn prune_applied( + &self, + board: &Board, + before_unix_ms: u64, + ) -> Result { + let mut conn = self.conn.clone(); + let removed: i64 = redis::cmd("ZREMRANGEBYSCORE") + .arg(self.applied(board)) + .arg("-inf") + .arg(format!("({before_unix_ms}")) + .query_async(&mut conn) + .await + .map_err(|err| unavailable("ZREMRANGEBYSCORE", err))?; + Ok(removed.max(0) as u64) + } +} + +/// RESP3 servers reply to `WITHSCORES` with `[[member, score], ...]`; RESP2 +/// with a flat list. Normalize to flat. +fn flatten_pairs(values: Vec) -> Vec { + if values.iter().all(|v| matches!(v, Value::Array(_))) { + values + .into_iter() + .flat_map(|v| match v { + Value::Array(pair) => pair, + other => vec![other], + }) + .collect() + } else { + values + } +} diff --git a/distributed_leaderboard/src/roots.rs b/distributed_leaderboard/src/roots.rs new file mode 100644 index 000000000..5d9fc3adf --- /dev/null +++ b/distributed_leaderboard/src/roots.rs @@ -0,0 +1,184 @@ +//! [`LeaderboardRoots`]: runs a [`LeaderboardSurface`]'s GraphQL roots +//! against a [`LeaderboardStore`]. + +use std::collections::BTreeMap; +use std::sync::Arc; + +use async_trait::async_trait; +use distributed::graphql::surface::{ + ExternalReadError, ExternalReadExecutor, ExternalReadResult, ExternalReadSource, +}; +use distributed::microsvc::Session; +use serde_json::{json, Value}; + +use crate::{ + leaderboard_change_key, LeaderboardEntry, LeaderboardGrant, LeaderboardOperation, + LeaderboardStore, LeaderboardSurface, ALL_BOARDS_CHANGE_KEY, +}; + +/// Default `radius` of an around-me query (capped by the surface). +const DEFAULT_RADIUS: u32 = 5; + +/// A leaderboard surface served from a store: register it with +/// `GraphqlEngineBuilder::external_read_source(Arc::new(LeaderboardRoots::new(surface, store)))`. +/// +/// The viewer-relative roots (`…LeaderboardAround`, `…MyRank`) read the +/// member from the session claim [`LeaderboardSurface::member_claim`], never +/// from an argument. +pub struct LeaderboardRoots { + surface: LeaderboardSurface, + store: Arc, +} + +impl LeaderboardRoots { + pub fn new(surface: LeaderboardSurface, store: Arc) -> Self { + Self { surface, store } + } +} + +fn string_arg( + arguments: &BTreeMap, + name: &str, +) -> Result, ExternalReadError> { + match arguments.get(name) { + None | Some(Value::Null) => Ok(None), + Some(Value::String(value)) => Ok(Some(value.clone())), + Some(_) => Err(ExternalReadError::bad_request(format!( + "`{name}` must be a string" + ))), + } +} + +fn bounded_arg( + arguments: &BTreeMap, + name: &str, + default: u32, + min: u32, + max: u32, +) -> Result { + let value = match arguments.get(name) { + None | Some(Value::Null) => return Ok(default), + Some(value) => value.as_i64().ok_or_else(|| { + ExternalReadError::bad_request(format!("`{name}` must be an integer")) + })?, + }; + if value < i64::from(min) || value > i64::from(max) { + return Err(ExternalReadError::bad_request(format!( + "`{name}` must be within {min}..={max}" + ))); + } + Ok(value as u32) +} + +fn entry_value(entry: &LeaderboardEntry) -> Value { + json!({ "rank": entry.rank, "member": entry.member, "score": entry.score }) +} + +#[async_trait] +impl ExternalReadExecutor for LeaderboardRoots { + fn source(&self) -> Arc { + Arc::new(self.surface.clone()) + } + + async fn execute( + &self, + root: &str, + arguments: &BTreeMap, + session: &Session, + ) -> Result { + let surface = &self.surface; + let all = LeaderboardGrant::read().rank_any_member(); + let operation = surface + .roots_for(all) + .into_iter() + .find(|(_, candidate)| candidate.name == root) + .map(|(operation, _)| operation) + .ok_or_else(|| ExternalReadError::internal("unknown leaderboard root"))?; + let board = surface + .board(string_arg(arguments, "board")?.as_deref()) + .map_err(ExternalReadError::bad_request)?; + let member = match operation { + LeaderboardOperation::AroundMe | LeaderboardOperation::MyRank => session + .get(surface.get_member_claim()) + .filter(|member| !member.is_empty()) + .map(str::to_string) + .ok_or_else(|| { + ExternalReadError::forbidden("the session has no leaderboard member claim") + })?, + LeaderboardOperation::Rank => string_arg(arguments, "member")? + .filter(|member| !member.is_empty()) + .ok_or_else(|| ExternalReadError::bad_request("member is required"))?, + LeaderboardOperation::Top => String::new(), + }; + let count = match operation { + LeaderboardOperation::Top => bounded_arg( + arguments, + "first", + surface.default_first(), + 1, + surface.max_first(), + )?, + LeaderboardOperation::AroundMe => bounded_arg( + arguments, + "radius", + DEFAULT_RADIUS.min(surface.max_radius()), + 0, + surface.max_radius(), + )?, + _ => 0, + } as usize; + let unavailable = |_| ExternalReadError::internal("leaderboard store unavailable"); + let value = match operation { + LeaderboardOperation::Top => Value::Array( + self.store + .top(&board, count) + .await + .map_err(unavailable)? + .iter() + .map(entry_value) + .collect(), + ), + LeaderboardOperation::AroundMe => Value::Array( + self.store + .around(&board, &member, count) + .await + .map_err(unavailable)? + .iter() + .map(entry_value) + .collect(), + ), + LeaderboardOperation::MyRank | LeaderboardOperation::Rank => { + let rank = self + .store + .rank(&board, &member) + .await + .map_err(unavailable)?; + let score = self + .store + .score(&board, &member) + .await + .map_err(unavailable)?; + match (rank, score) { + (Some(rank), Some(score)) => entry_value(&LeaderboardEntry { + rank, + member: member.clone(), + score, + }), + _ => Value::Null, + } + } + }; + Ok(ExternalReadResult { + value, + scope: json!({ + "board": board.name(), + "member": (!member.is_empty()).then_some(&member), + "count": count, + }), + change_keys: vec![ + leaderboard_change_key(board.name()), + ALL_BOARDS_CHANGE_KEY.to_string(), + ], + }) + } +} diff --git a/distributed_leaderboard/src/surface.rs b/distributed_leaderboard/src/surface.rs new file mode 100644 index 000000000..d582d97f0 --- /dev/null +++ b/distributed_leaderboard/src/surface.rs @@ -0,0 +1,604 @@ +//! Leaderboard surfaces: sorted-set boards exposed through the generated +//! GraphQL surface, client manifest and TS client as an +//! [`ExternalReadSource`]. +//! +//! A [`LeaderboardSurface`] declares one board (or one board *family*, keyed +//! by a `board` argument) and per-role grants. The pool-free client manifest +//! export (`Surface::with_external_sources`) and the runtime engine +//! ([`LeaderboardRoots`](crate::LeaderboardRoots)) share one declaration. +//! For a surface named `xp` the roots are: +//! +//! | Root | Grant | Arguments | Result | +//! |---|---|---|---| +//! | `xpLeaderboard` | `top` | `board` (family), `first` | `[LeaderboardEntry!]!` | +//! | `xpLeaderboardAround` | `around_me` | `board` (family), `radius` | `[LeaderboardEntry!]!` | +//! | `xpMyRank` | `my_rank` | `board` (family) | `LeaderboardEntry` | +//! | `xpRank` | `rank_any_member` | `board` (family), `member` | `LeaderboardEntry` | +//! +//! `xpLeaderboardAround` and `xpMyRank` rank the **viewer**: the member is the +//! verified session claim [`LeaderboardSurface::member_claim`] (default +//! `x-user-id`), never an argument. Ranking an arbitrary member needs the +//! separate `rank_any_member` grant, which adds `xpRank(member:)`. +//! `xpLeaderboard`, `xpLeaderboardAround` and `xpMyRank` also exist as +//! subscription roots for `@live`; they refresh when the board's change key +//! ([`leaderboard_change_key`]) or [`ALL_BOARDS_CHANGE_KEY`](crate::ALL_BOARDS_CHANGE_KEY) +//! is published. + +use std::collections::BTreeMap; +use std::sync::Arc; + +use distributed::graphql::surface::{ + ExternalField, ExternalReadSource, ExternalRoot, ExternalType, +}; +use distributed::microsvc::USER_ID_KEY; + +use crate::manifest::{ClientLeaderboard, ClientLeaderboardArgument, ClientLeaderboardRoot}; +use crate::{Board, ScoreOrder, LEADERBOARDS_SECTION}; + +/// GraphQL object type of one ranked row. +pub const LEADERBOARD_ENTRY_TYPE: &str = "LeaderboardEntry"; +/// Default `first` of a top-N query. +pub const LEADERBOARD_DEFAULT_FIRST: u32 = 10; +/// Default cap on `first`. +pub const LEADERBOARD_MAX_FIRST: u32 = 100; +/// Default cap on `radius`. +pub const LEADERBOARD_MAX_RADIUS: u32 = 25; +/// Longest board family key. +pub const MAX_LEADERBOARD_KEY_LEN: usize = 64; + +/// The live-invalidation key of a board: `leaderboard:{board name}`. Reads +/// also listen on [`ALL_BOARDS_CHANGE_KEY`](crate::ALL_BOARDS_CHANGE_KEY). +pub fn leaderboard_change_key(board: &str) -> String { + format!("leaderboard:{board}") +} + +/// Which boards a surface serves. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum LeaderboardBoards { + /// Exactly this board; roots take no `board` argument. + Single { board: String }, + /// Boards `{prefix}:{key}`; roots take `board: String!` = `key` + /// (1..=64 bytes of `[A-Za-z0-9._-]`), e.g. a season id. + Family { prefix: String }, +} + +/// What one role may ask of a leaderboard surface. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct LeaderboardGrant { + pub top: bool, + pub around_me: bool, + pub my_rank: bool, + pub rank_any_member: bool, +} + +impl LeaderboardGrant { + /// Top-N, the viewer's neighbourhood and the viewer's own rank. + pub fn read() -> Self { + Self { + top: true, + around_me: true, + my_rank: true, + rank_any_member: false, + } + } + + /// Top-N only. + pub fn top_only() -> Self { + Self { + top: true, + ..Self::default() + } + } + + /// Also allow ranking any member by id (moderation, support tools). + pub fn rank_any_member(mut self) -> Self { + self.rank_any_member = true; + self + } + + fn is_empty(&self) -> bool { + !(self.top || self.around_me || self.my_rank || self.rank_any_member) + } + + fn intersect(self, other: Self) -> Self { + Self { + top: self.top && other.top, + around_me: self.around_me && other.around_me, + my_rank: self.my_rank && other.my_rank, + rank_any_member: self.rank_any_member && other.rank_any_member, + } + } +} + +/// One leaderboard root operation. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum LeaderboardOperation { + Top, + AroundMe, + MyRank, + Rank, +} + +impl LeaderboardOperation { + pub fn as_str(self) -> &'static str { + match self { + Self::Top => "top", + Self::AroundMe => "around_me", + Self::MyRank => "my_rank", + Self::Rank => "rank", + } + } + + /// `true` for list results, `false` for a single nullable entry. + pub fn is_list(self) -> bool { + matches!(self, Self::Top | Self::AroundMe) + } + + /// Whether the operation has a subscription (`@live`) twin. + pub fn is_live(self) -> bool { + !matches!(self, Self::Rank) + } + + /// Whether the member comes from the viewer's session claim. + pub fn ranks_viewer(self) -> bool { + matches!(self, Self::AroundMe | Self::MyRank) + } +} + +/// A leaderboard (or board family) exposed through GraphQL. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LeaderboardSurface { + pub(crate) name: String, + pub(crate) boards: LeaderboardBoards, + pub(crate) order: ScoreOrder, + pub(crate) member_claim: String, + pub(crate) default_first: u32, + pub(crate) max_first: u32, + pub(crate) max_radius: u32, + pub(crate) grants: BTreeMap, +} + +impl LeaderboardSurface { + /// Serve exactly `board` under GraphQL base name `name` (lowerCamel, + /// `[A-Za-z][A-Za-z0-9]*`). + pub fn single(name: impl Into, board: &Board) -> Self { + Self::new( + name, + LeaderboardBoards::Single { + board: board.name().to_string(), + }, + board.order(), + ) + } + + /// Serve the family `{prefix}:{key}`; queries pass `board: key`. + pub fn family(name: impl Into, prefix: impl Into, order: ScoreOrder) -> Self { + Self::new( + name, + LeaderboardBoards::Family { + prefix: prefix.into(), + }, + order, + ) + } + + fn new(name: impl Into, boards: LeaderboardBoards, order: ScoreOrder) -> Self { + Self { + name: name.into(), + boards, + order, + member_claim: USER_ID_KEY.to_string(), + default_first: LEADERBOARD_DEFAULT_FIRST, + max_first: LEADERBOARD_MAX_FIRST, + max_radius: LEADERBOARD_MAX_RADIUS, + grants: BTreeMap::new(), + } + } + + /// Session claim that names the viewer's member (default `x-user-id`; + /// e.g. a character-id claim for character-keyed boards). + pub fn member_claim(mut self, claim: impl Into) -> Self { + self.member_claim = claim.into(); + self + } + + /// Default and maximum `first`, and maximum `radius`. + pub fn limits(mut self, default_first: u32, max_first: u32, max_radius: u32) -> Self { + self.default_first = default_first; + self.max_first = max_first; + self.max_radius = max_radius; + self + } + + /// Grant `role` these operations. A later grant for a role replaces it. + pub fn grant(mut self, role: impl Into, grant: LeaderboardGrant) -> Self { + self.grants.insert(role.into(), grant); + self + } + + pub fn name(&self) -> &str { + &self.name + } + + pub fn boards(&self) -> &LeaderboardBoards { + &self.boards + } + + pub fn order(&self) -> ScoreOrder { + self.order + } + + pub fn get_member_claim(&self) -> &str { + &self.member_claim + } + + pub fn default_first(&self) -> u32 { + self.default_first + } + + pub fn max_first(&self) -> u32 { + self.max_first + } + + pub fn max_radius(&self) -> u32 { + self.max_radius + } + + pub fn grants(&self) -> &BTreeMap { + &self.grants + } + + /// Operations this surface exposes: on a role or application selection + /// its one grant, on the catalog the union of every role's grant. + pub(crate) fn selected_grant(&self) -> LeaderboardGrant { + self.grants + .values() + .fold(LeaderboardGrant::default(), |all, grant| LeaderboardGrant { + top: all.top || grant.top, + around_me: all.around_me || grant.around_me, + my_rank: all.my_rank || grant.my_rank, + rank_any_member: all.rank_any_member || grant.rank_any_member, + }) + } + + /// Resolve the board a query names (`key` is the `board` argument). + pub fn board(&self, key: Option<&str>) -> Result { + let name = match (&self.boards, key) { + (LeaderboardBoards::Single { board }, None) => board.clone(), + (LeaderboardBoards::Family { prefix }, Some(key)) => { + if key.is_empty() + || key.len() > MAX_LEADERBOARD_KEY_LEN + || !key + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')) + { + return Err(format!( + "board must be 1..={MAX_LEADERBOARD_KEY_LEN} bytes of [A-Za-z0-9._-]" + )); + } + format!("{prefix}:{key}") + } + (LeaderboardBoards::Single { .. }, Some(_)) => { + return Err(format!( + "leaderboard `{}` takes no board argument", + self.name + )) + } + (LeaderboardBoards::Family { .. }, None) => { + return Err(format!( + "leaderboard `{}` requires a board argument", + self.name + )) + } + }; + Board::new(name, self.order).map_err(|error| error.message().to_string()) + } + + /// Roots for `grant`, with their operations ([`LeaderboardOperation::is_live`] + /// ones are `live`). + pub fn roots_for(&self, grant: LeaderboardGrant) -> Vec<(LeaderboardOperation, ExternalRoot)> { + let family = matches!(self.boards, LeaderboardBoards::Family { .. }); + let mut roots = Vec::new(); + let mut push = + |suffix: &str, operation: LeaderboardOperation, extra: Option| { + let mut arguments = Vec::new(); + if family { + arguments.push(ExternalField::new("board", "String", false)); + } + arguments.extend(extra); + roots.push(( + operation, + ExternalRoot { + name: format!("{}{suffix}", self.name), + arguments, + type_name: LEADERBOARD_ENTRY_TYPE.to_string(), + list: operation.is_list(), + live: operation.is_live(), + }, + )); + }; + if grant.top { + push( + "Leaderboard", + LeaderboardOperation::Top, + Some(ExternalField::new("first", "Int", true)), + ); + } + if grant.around_me { + push( + "LeaderboardAround", + LeaderboardOperation::AroundMe, + Some(ExternalField::new("radius", "Int", true)), + ); + } + if grant.my_rank { + push("MyRank", LeaderboardOperation::MyRank, None); + } + if grant.rank_any_member { + push( + "Rank", + LeaderboardOperation::Rank, + Some(ExternalField::new("member", "String", false)), + ); + } + roots + } + + /// Validate the declaration (names, limits, board, roles). + fn check(&self) -> Result<(), String> { + let mut chars = self.name.chars(); + if !chars.next().is_some_and(|c| c.is_ascii_lowercase()) + || !chars.all(|c| c.is_ascii_alphanumeric()) + { + return Err(format!( + "leaderboard surface name `{}` must be lowerCamel [a-z][A-Za-z0-9]*", + self.name + )); + } + if self.member_claim.trim().is_empty() { + return Err(format!("leaderboard `{}` needs a member claim", self.name)); + } + if self.default_first == 0 || self.default_first > self.max_first || self.max_radius == 0 { + return Err(format!( + "leaderboard `{}` limits must satisfy 0 < default_first <= max_first and max_radius > 0", + self.name + )); + } + match &self.boards { + LeaderboardBoards::Single { board } => Board::new(board.clone(), self.order) + .map(|_| ()) + .map_err(|error| error.message().to_string())?, + LeaderboardBoards::Family { prefix } => Board::new( + format!("{prefix}:{}", "k".repeat(MAX_LEADERBOARD_KEY_LEN)), + self.order, + ) + .map(|_| ()) + .map_err(|error| error.message().to_string())?, + } + for (role, grant) in &self.grants { + if role.trim().is_empty() { + return Err(format!("leaderboard `{}` grants an empty role", self.name)); + } + if grant.is_empty() { + return Err(format!( + "leaderboard `{}` grants role `{role}` nothing", + self.name + )); + } + } + Ok(()) + } + + /// The declaration as `roles` jointly see it (the intersection of their + /// grants), granted to `grantee`; `None` when nothing is common. + fn selected(&self, grantee: &str, roles: &[String]) -> Option { + let mut common: Option = None; + for role in roles { + let grant = *self.grants.get(role)?; + common = Some(common.map_or(grant, |common| common.intersect(grant))); + } + let common = common.filter(|grant| !grant.is_empty())?; + Some(Self { + grants: BTreeMap::from([(grantee.to_string(), common)]), + ..self.clone() + }) + } + + fn canonical_value(&self) -> serde_json::Value { + let grants = self + .grants + .iter() + .map(|(role, grant)| { + ( + role.clone(), + serde_json::json!({ + "top": grant.top, + "around_me": grant.around_me, + "my_rank": grant.my_rank, + "rank_any_member": grant.rank_any_member, + }), + ) + }) + .collect::>(); + serde_json::json!({ + "name": self.name, + "boards": match &self.boards { + LeaderboardBoards::Single { board } => serde_json::json!({"single": board}), + LeaderboardBoards::Family { prefix } => serde_json::json!({"family": prefix}), + }, + "order": order_str(self.order), + "member_claim": self.member_claim, + "default_first": self.default_first, + "max_first": self.max_first, + "max_radius": self.max_radius, + "grants": grants, + }) + } +} + +/// `high_first` / `low_first`. +fn order_str(order: ScoreOrder) -> &'static str { + match order { + ScoreOrder::HighFirst => "high_first", + ScoreOrder::LowFirst => "low_first", + } +} + +impl ExternalReadSource for LeaderboardSurface { + fn section(&self) -> &str { + LEADERBOARDS_SECTION + } + + fn name(&self) -> &str { + &self.name + } + + fn roles(&self) -> Vec { + self.grants.keys().cloned().collect() + } + + fn select(&self, grantee: &str, roles: &[String]) -> Option> { + self.selected(grantee, roles) + .map(|selected| Arc::new(selected) as Arc) + } + + fn types(&self) -> Vec { + vec![ExternalType { + name: LEADERBOARD_ENTRY_TYPE.to_string(), + fields: vec![ + ExternalField::new("rank", "Int", false), + ExternalField::new("member", "String", false), + ExternalField::new("score", "Float", false), + ], + }] + } + + fn roots(&self) -> Vec { + self.roots_for(self.selected_grant()) + .into_iter() + .map(|(_, root)| root) + .collect() + } + + fn claims(&self) -> Vec { + vec![self.member_claim.clone()] + } + + fn contract(&self) -> serde_json::Value { + self.canonical_value() + } + + fn client_manifest(&self, subscriptions: bool) -> serde_json::Value { + let manifest = ClientLeaderboard { + name: self.name.clone(), + entry_typename: LEADERBOARD_ENTRY_TYPE.to_string(), + order: order_str(self.order).to_string(), + boards: match self.boards { + LeaderboardBoards::Single { .. } => "single", + LeaderboardBoards::Family { .. } => "family", + } + .to_string(), + default_first: self.default_first, + max_first: self.max_first, + max_radius: self.max_radius, + roots: self + .roots_for(self.selected_grant()) + .into_iter() + .map(|(operation, root)| ClientLeaderboardRoot { + live: subscriptions && root.live, + list: root.list, + operation: operation.as_str().to_string(), + arguments: root + .arguments + .into_iter() + .map(|argument| ClientLeaderboardArgument { + name: argument.name, + type_name: argument.type_name, + nullable: argument.nullable, + }) + .collect(), + name: root.name, + }) + .collect(), + }; + serde_json::to_value(manifest).expect("a client leaderboard serializes") + } + + fn validate(&self) -> Result<(), String> { + self.check() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn xp() -> LeaderboardSurface { + LeaderboardSurface::single("xp", &Board::high_first("mobpit.xp").unwrap()) + .grant("user", LeaderboardGrant::read()) + .grant("moderator", LeaderboardGrant::read().rank_any_member()) + } + + #[test] + fn roots_follow_the_grant() { + let user = xp().roots_for(LeaderboardGrant::read()); + assert_eq!( + user.iter() + .map(|(_, root)| root.name.as_str()) + .collect::>(), + ["xpLeaderboard", "xpLeaderboardAround", "xpMyRank"] + ); + assert!(user + .iter() + .all(|(_, root)| root.arguments.iter().all(|arg| arg.name != "member"))); + let moderator = xp().roots_for(LeaderboardGrant::read().rank_any_member()); + let (operation, rank) = moderator.last().unwrap(); + assert_eq!(*operation, LeaderboardOperation::Rank); + assert_eq!(rank.name, "xpRank"); + assert!(!rank.live); + assert_eq!(rank.arguments[0].name, "member"); + } + + #[test] + fn families_take_a_validated_board_key() { + let season = LeaderboardSurface::family("season", "season.xp", ScoreOrder::HighFirst) + .grant("user", LeaderboardGrant::top_only()); + let roots = season.roots_for(LeaderboardGrant::top_only()); + assert_eq!(roots[0].1.arguments[0].name, "board"); + assert_eq!(season.board(Some("s3")).unwrap().name(), "season.xp:s3"); + assert!(season.board(None).is_err()); + assert!(season.board(Some("bad key")).is_err()); + assert!(season.board(Some("")).is_err()); + assert!(xp().board(Some("s3")).is_err()); + assert_eq!(xp().board(None).unwrap().name(), "mobpit.xp"); + } + + #[test] + fn role_and_application_selection_narrow_the_grant() { + assert!(xp().selected("guest", &["guest".into()]).is_none()); + let user = xp().selected("user", &["user".into()]).unwrap(); + assert_eq!(user.selected_grant(), LeaderboardGrant::read()); + let app = xp() + .selected("app", &["user".into(), "moderator".into()]) + .unwrap(); + assert_eq!(app.grants().keys().collect::>(), ["app"]); + assert_eq!(app.selected_grant(), LeaderboardGrant::read()); + assert!(xp().selected("app", &["guest".into()]).is_none()); + } + + #[test] + fn rejects_bad_declarations() { + assert!( + LeaderboardSurface::single("Xp", &Board::high_first("b").unwrap()) + .check() + .is_err() + ); + assert!(xp().limits(0, 10, 5).check().is_err()); + assert!(xp().limits(20, 10, 5).check().is_err()); + assert!(xp() + .grant("nobody", LeaderboardGrant::default()) + .check() + .is_err()); + assert!(xp().check().is_ok()); + } +} diff --git a/distributed_leaderboard/tests/graphql.rs b/distributed_leaderboard/tests/graphql.rs new file mode 100644 index 000000000..7377b6df5 --- /dev/null +++ b/distributed_leaderboard/tests/graphql.rs @@ -0,0 +1,659 @@ +//! Leaderboards through the generated GraphQL surface: role-structured roots, +//! viewer-bound `myRank`, `@live` top-N driven by the projector's change +//! listener, the client manifest section and the static SDL, all through the +//! engine's external read source extension point. + +#![cfg(feature = "graphql")] + +use distributed::graphql::IdentityConfig; +use std::sync::Arc; +use std::time::{Duration, UNIX_EPOCH}; + +use async_graphql::Request; +use distributed::graphql::client_manifest::{ + DistributedClientManifest, DistributedClientSurfaceExport, +}; +use distributed::graphql::sdl::graphql_sdl_from_surface; +use distributed::graphql::surface::{ + build_surface, surface_for_role, ExternalReadSource, SurfaceDialect, SurfaceOptions, +}; +use distributed::graphql::GraphqlEngine; +use distributed::microsvc::{Session, ROLE_KEY, USER_ID_KEY}; +use distributed::{DomainEventOccurrence, ExternalEventSource}; +use distributed_leaderboard::{ + Board, ClientLeaderboard, InMemoryLeaderboard, LeaderboardChange, LeaderboardError, + LeaderboardGrant, LeaderboardProjector, LeaderboardRoots, LeaderboardStore, LeaderboardSurface, + ScorePolicy, ScoreSubmission, LEADERBOARDS_SECTION, +}; +use futures_util::StreamExt; + +fn xp_board() -> Board { + Board::high_first("mobpit.xp").unwrap() +} + +fn xp_surface() -> LeaderboardSurface { + LeaderboardSurface::single("xp", &xp_board()) + .limits(3, 5, 2) + .grant("user", LeaderboardGrant::read()) + .grant("moderator", LeaderboardGrant::read().rank_any_member()) +} + +fn season_surface() -> LeaderboardSurface { + LeaderboardSurface::family( + "season", + "season.xp", + distributed_leaderboard::ScoreOrder::HighFirst, + ) + .grant("user", LeaderboardGrant::top_only()) +} + +async fn engine(store: Arc) -> GraphqlEngine { + let repo = distributed::SqliteRepository::connect_and_migrate("sqlite::memory:") + .await + .unwrap(); + let catalog = distributed::ReadModelCatalog::new("leaderboards"); + GraphqlEngine::from_schema_catalog(&catalog, repo.pool().clone()) + .unwrap() + .identity(IdentityConfig::dev_headers()) + .roles(&["user", "moderator"]) + .external_read_source(Arc::new(LeaderboardRoots::new(xp_surface(), store.clone()))) + .external_read_source(Arc::new(LeaderboardRoots::new(season_surface(), store))) + .build() + .expect("build engine") +} + +fn session(role: &str, user: Option<&str>) -> Session { + let mut session = Session::new(); + session.set(ROLE_KEY, role); + if let Some(user) = user { + session.set(USER_ID_KEY, user); + } + session +} + +async fn seed(store: &InMemoryLeaderboard) { + for (member, score) in [("ann", 50.0), ("bob", 40.0), ("cat", 30.0), ("dan", 20.0)] { + store + .submit( + &xp_board(), + &ScoreSubmission::new(member, score, ScorePolicy::Replace), + ) + .await + .unwrap(); + } +} + +async fn run(engine: &GraphqlEngine, session: &Session, query: &str) -> serde_json::Value { + let response = engine.execute(session, Request::new(query)).await; + serde_json::to_value(&response).unwrap() +} + +fn error_code(response: &serde_json::Value) -> Option<&str> { + response["errors"][0]["extensions"]["code"].as_str() +} + +#[tokio::test] +async fn top_around_and_my_rank_read_the_board_for_the_viewer() { + let store = Arc::new(InMemoryLeaderboard::new()); + seed(&store).await; + let engine = engine(store).await; + let cat = session("user", Some("cat")); + + let top = run(&engine, &cat, "{ xpLeaderboard { rank member score } }").await; + assert_eq!( + top["data"]["xpLeaderboard"], + serde_json::json!([ + { "rank": 0, "member": "ann", "score": 50.0 }, + { "rank": 1, "member": "bob", "score": 40.0 }, + { "rank": 2, "member": "cat", "score": 30.0 }, + ]), + "default first = 3" + ); + let around = run( + &engine, + &cat, + "{ xpLeaderboardAround(radius: 1) { member } }", + ) + .await; + assert_eq!( + around["data"]["xpLeaderboardAround"], + serde_json::json!([{ "member": "bob" }, { "member": "cat" }, { "member": "dan" }]) + ); + let mine = run(&engine, &cat, "{ xpMyRank { rank member score } }").await; + assert_eq!( + mine["data"]["xpMyRank"], + serde_json::json!({ "rank": 2, "member": "cat", "score": 30.0 }) + ); + let unranked = run( + &engine, + &session("user", Some("zed")), + "{ xpMyRank { rank } }", + ) + .await; + assert_eq!(unranked["data"]["xpMyRank"], serde_json::Value::Null); + + let season = run( + &engine, + &cat, + r#"{ seasonLeaderboard(board: "s1") { member } }"#, + ) + .await; + assert_eq!(season["data"]["seasonLeaderboard"], serde_json::json!([])); +} + +#[tokio::test] +async fn my_rank_is_bound_to_the_session_and_ranking_others_needs_the_grant() { + let store = Arc::new(InMemoryLeaderboard::new()); + seed(&store).await; + let engine = engine(store).await; + let cat = session("user", Some("cat")); + + // A user cannot name another member: no argument, no `xpRank` root. + let spoofed = run(&engine, &cat, r#"{ xpMyRank(member: "ann") { rank } }"#).await; + assert!(spoofed["errors"].is_array(), "{spoofed}"); + let other = run(&engine, &cat, r#"{ xpRank(member: "ann") { rank } }"#).await; + assert!(other["errors"].is_array(), "{other}"); + // Around-me is the viewer's neighbourhood only. + let around = run( + &engine, + &cat, + r#"{ xpLeaderboardAround(member: "ann") { rank } }"#, + ) + .await; + assert!(around["errors"].is_array(), "{around}"); + + // A moderator granted `rank_any_member` may rank anyone. + let moderator = session("moderator", Some("mod-1")); + let ranked = run( + &engine, + &moderator, + r#"{ xpRank(member: "ann") { rank score } }"#, + ) + .await; + assert_eq!( + ranked["data"]["xpRank"], + serde_json::json!({ "rank": 0, "score": 50.0 }) + ); + + // Without the member claim the viewer-relative roots fail closed. + let anonymous = run(&engine, &session("user", None), "{ xpMyRank { rank } }").await; + assert_eq!(error_code(&anonymous), Some("FORBIDDEN"), "{anonymous}"); +} + +#[tokio::test] +async fn arguments_are_validated() { + let store = Arc::new(InMemoryLeaderboard::new()); + let engine = engine(store).await; + let cat = session("user", Some("cat")); + for query in [ + "{ xpLeaderboard(first: 6) { rank } }", + "{ xpLeaderboard(first: 0) { rank } }", + "{ xpLeaderboardAround(radius: 3) { rank } }", + r#"{ seasonLeaderboard(board: "not a key") { rank } }"#, + ] { + let response = run(&engine, &cat, query).await; + assert_eq!( + error_code(&response), + Some("BAD_REQUEST"), + "{query}: {response}" + ); + } + let missing = run(&engine, &cat, "{ seasonLeaderboard { rank } }").await; + assert!( + missing["errors"].is_array(), + "family boards require `board`" + ); +} + +#[derive(serde::Serialize, serde::Deserialize, distributed::DomainEvent)] +#[domain_event(name = "test.xp_gained", version = 1)] +struct XpGained { + player: String, + xp: u32, +} + +fn gained(position: u64, player: &str, xp: u32) -> DomainEventOccurrence { + DomainEventOccurrence::capture_external( + ExternalEventSource { + producer: "zone.sim".into(), + stream: "zone-1".into(), + position, + key: "xp".into(), + }, + UNIX_EPOCH + Duration::from_millis(position), + Default::default(), + &XpGained { + player: player.into(), + xp, + }, + ) + .unwrap() +} + +#[tokio::test] +async fn live_top_n_updates_after_an_applied_score_change() { + let store = Arc::new(InMemoryLeaderboard::new()); + seed(&store).await; + let engine = engine(store.clone()).await; + let projection = + |event: &DomainEventOccurrence| -> Result, LeaderboardError> { + let body: XpGained = event + .decode_body() + .map_err(|error| LeaderboardError::invalid(error.to_string()))?; + Ok(vec![LeaderboardChange::new( + xp_board(), + ScoreSubmission::new(body.player, f64::from(body.xp), ScorePolicy::Increment), + )]) + }; + let projector = LeaderboardProjector::new(store.clone(), Arc::new(projection)) + .with_change_listener(distributed_leaderboard::change_listener(&engine)); + + let mut stream = engine.execute_stream( + &session("user", Some("dan")), + Request::new("subscription { xpLeaderboard(first: 2) { member score } }"), + ); + let first = tokio::time::timeout(Duration::from_secs(5), stream.next()) + .await + .unwrap() + .unwrap(); + assert_eq!( + serde_json::to_value(&first.data).unwrap()["xpLeaderboard"], + serde_json::json!([{ "member": "ann", "score": 50.0 }, { "member": "bob", "score": 40.0 }]) + ); + + // A change below the top two re-executes but does not push (hash gate). + projector.apply_event(&gained(1, "dan", 5)).await.unwrap(); + assert!( + tokio::time::timeout(Duration::from_millis(400), stream.next()) + .await + .is_err(), + "no push when the top-N is unchanged" + ); + + projector.apply_event(&gained(2, "dan", 100)).await.unwrap(); + let pushed = tokio::time::timeout(Duration::from_secs(5), stream.next()) + .await + .unwrap() + .unwrap(); + assert_eq!( + serde_json::to_value(&pushed.data).unwrap()["xpLeaderboard"], + serde_json::json!([{ "member": "dan", "score": 125.0 }, { "member": "ann", "score": 50.0 }]) + ); + + // A redelivered (duplicate) event changes nothing and pushes nothing. + projector.apply_event(&gained(2, "dan", 100)).await.unwrap(); + assert!( + tokio::time::timeout(Duration::from_millis(400), stream.next()) + .await + .is_err() + ); +} + +fn surfaces() -> distributed::graphql::surface::Surface { + let options = SurfaceOptions { + dialect: SurfaceDialect::Sqlite, + aggregates: false, + subscriptions: true, + default_limit: 100, + max_limit: 1000, + }; + build_surface(&[], &options) + .unwrap() + .with_external_sources(sources([xp_surface(), season_surface()])) + .unwrap() +} + +fn sources( + surfaces: [LeaderboardSurface; N], +) -> impl Iterator> { + surfaces + .into_iter() + .map(|surface| Arc::new(surface) as Arc) +} + +fn leaderboards(manifest: &DistributedClientManifest) -> Vec { + manifest + .external + .get(LEADERBOARDS_SECTION) + .into_iter() + .flatten() + .map(|value| serde_json::from_value(value.clone()).unwrap()) + .collect() +} + +fn role_manifest(role: &str) -> DistributedClientManifest { + let selected = surface_for_role(&surfaces(), role, &Default::default()).unwrap(); + DistributedClientSurfaceExport::from_selected("leaderboards", selected) + .unwrap() + .manifest() + .unwrap() + .clone() +} + +#[test] +fn board_queries_are_in_the_client_manifest_per_role() { + let user = role_manifest("user"); + assert!(user.capabilities.live_queries); + let user_boards = leaderboards(&user); + let names = user_boards + .iter() + .flat_map(|leaderboard| leaderboard.roots.iter().map(|root| root.name.as_str())) + .collect::>(); + assert_eq!( + names, + [ + "seasonLeaderboard", + "xpLeaderboard", + "xpLeaderboardAround", + "xpMyRank" + ] + ); + let xp = user_boards.iter().find(|l| l.name == "xp").unwrap(); + assert_eq!(xp.entry_typename, "LeaderboardEntry"); + assert_eq!(xp.order, "high_first"); + assert_eq!((xp.default_first, xp.max_first, xp.max_radius), (3, 5, 2)); + let my_rank = xp.roots.iter().find(|r| r.name == "xpMyRank").unwrap(); + assert!( + my_rank.arguments.is_empty(), + "the member is never an argument" + ); + assert!(my_rank.live && !my_rank.list); + + let moderator = role_manifest("moderator"); + let rank = leaderboards(&moderator)[0] + .roots + .clone() + .into_iter() + .find(|root| root.name == "xpRank") + .unwrap(); + assert!(!rank.live); + assert_eq!(rank.arguments[0].name, "member"); + + let guest = role_manifest("guest"); + assert!(guest.external.is_empty()); + let json = serde_json::to_value(&guest).unwrap(); + assert!(json.get("external").is_none(), "absent when empty"); + + // Round-trips through the strict manifest schema. + let encoded = serde_json::to_string(&user).unwrap(); + let decoded: DistributedClientManifest = serde_json::from_str(&encoded).unwrap(); + assert_eq!(decoded, user); + assert_ne!(user.schema_fingerprint, guest.schema_fingerprint); +} + +#[test] +fn sdl_declares_the_entry_type_and_role_roots() { + let user = surface_for_role(&surfaces(), "user", &Default::default()).unwrap(); + let sdl = graphql_sdl_from_surface(&user).unwrap(); + assert!(sdl + .contains("type LeaderboardEntry {\n rank: Int!\n member: String!\n score: Float!\n}")); + assert!(sdl.contains(" xpLeaderboard(first: Int): [LeaderboardEntry!]!\n")); + assert!(sdl.contains(" xpMyRank: LeaderboardEntry\n")); + assert!(sdl.contains(" seasonLeaderboard(board: String!, first: Int): [LeaderboardEntry!]!\n")); + assert!(!sdl.contains("xpRank")); + assert!(sdl.contains("type Subscription {")); +} + +/// With the causal client protocol on (as Mob Pit runs it), leaderboard +/// results carry an incomplete snapshot and, live, `snapshot` mode with reset. +#[tokio::test] +async fn protocol_envelopes_mark_leaderboards_as_snapshot_only() { + let store = Arc::new(InMemoryLeaderboard::new()); + seed(&store).await; + let repo = distributed::SqliteRepository::connect_and_migrate("sqlite::memory:") + .await + .unwrap(); + let catalog = distributed::ReadModelCatalog::new("leaderboards"); + let engine = GraphqlEngine::from_schema_catalog(&catalog, repo.pool().clone()) + .unwrap() + .identity(IdentityConfig::dev_headers()) + .roles(&["user", "moderator"]) + .protocol_token_key([7; 32]) + .external_read_source(Arc::new(LeaderboardRoots::new(xp_surface(), store.clone()))) + .build() + .expect("protocol engine"); + let cat = session("user", Some("cat")); + + let query = engine + .execute(&cat, Request::new("{ xpMyRank { rank } }")) + .await; + assert!(query.errors.is_empty(), "{:?}", query.errors); + let query = serde_json::to_value(&query).unwrap(); + let snapshot = &query["extensions"]["distributed"]["snapshot"]; + assert_eq!(snapshot["recordsComplete"], false, "{query}"); + assert_eq!(snapshot["indexesComparable"], false, "{query}"); + + let mut stream = engine.execute_stream( + &cat, + Request::new("subscription { xpLeaderboard(first: 1) { member } }"), + ); + let frame = tokio::time::timeout(Duration::from_secs(5), stream.next()) + .await + .unwrap() + .unwrap(); + assert!(frame.errors.is_empty(), "{:?}", frame.errors); + let frame = serde_json::to_value(&frame).unwrap(); + let live = &frame["extensions"]["distributed"]["live"]; + assert_eq!(live["mode"], "snapshot", "{frame}"); + assert_eq!(live["reset"], true, "{frame}"); +} + +/// The framework's manifest compiles with the CLI client compiler: the CLI +/// recomputes the same schema fingerprint and generates `leaderboards.ts`. +#[test] +fn the_cli_compiles_a_framework_leaderboard_manifest_into_the_ts_client() { + use distributed::graphql::read; + use distributed_cli::{ + compile_client, ClientCompileInput, ClientDocument, ClientSurfaceIdentity, + }; + + let items = distributed::TableSchema { + model_name: "ItemView".into(), + table_name: "items".into(), + columns: vec![ + distributed::TableColumn { + primary_key: true, + ..distributed::TableColumn::new("id", "id", distributed::ColumnType::Text) + }, + distributed::TableColumn::new("name", "name", distributed::ColumnType::Text), + ], + primary_key: distributed::PrimaryKey::new(["id"]), + version_column: Some("_sourced_version".into()), + indexes: Vec::new(), + relationships: Vec::new(), + kind: distributed::TableKind::ReadModel, + }; + let options = SurfaceOptions { + dialect: SurfaceDialect::Sqlite, + aggregates: false, + subscriptions: true, + default_limit: 100, + max_limit: 1000, + }; + let surface = build_surface(&[items], &options) + .unwrap() + .with_external_sources(sources([xp_surface()])) + .unwrap(); + let grants = std::collections::BTreeMap::from([("ItemView".to_string(), read().all_columns())]); + let selected = surface_for_role(&surface, "user", &grants).unwrap(); + let manifest = DistributedClientSurfaceExport::from_selected("leaderboards", selected) + .unwrap() + .manifest_json_pretty() + .unwrap(); + let project = compile_client(ClientCompileInput::new( + serde_json::from_str(&manifest).unwrap(), + ClientSurfaceIdentity::role("user"), + vec![ClientDocument::new( + "src/routes/items.graphql", + "query Items { items { name } }", + )], + )) + .expect("the CLI accepts the framework manifest"); + let leaderboards = project + .files + .iter() + .find(|file| file.path == "leaderboards.ts") + .expect("leaderboards.ts"); + assert!(leaderboards + .contents + .contains("export const XpMyRankLeaderboard = {")); + assert!(leaderboards + .contents + .contains(r#"document: "query XpLeaderboardAround($radius: Int) { xpLeaderboardAround(radius: $radius) { rank member score } }","#)); +} + +/// The projector runs in another process (here: another bus connection and +/// no shared engine): it publishes `distributed.leaderboard.changed` on the +/// bus, and the GraphQL process's bus handlers drive `@live` from it. +#[tokio::test] +async fn live_boards_follow_a_projector_in_another_process_over_the_bus() { + use distributed::bus::SqliteBus; + use distributed::bus::{BusConsumer, RunOptions}; + use distributed::outbox_worker::BusPublisher; + use distributed_leaderboard::LeaderboardChangePublisher; + + let path = std::env::temp_dir().join(format!( + "distributed-board-notices-{}-{}.db", + std::process::id(), + UNIX_EPOCH.elapsed().unwrap().as_nanos() + )); + let url = format!("sqlite://{}?mode=rwc", path.display()); + let open = || async { + let pool = sqlx::sqlite::SqlitePoolOptions::new() + .max_connections(2) + .connect_with( + url.parse::() + .unwrap() + .journal_mode(sqlx::sqlite::SqliteJournalMode::Wal) + .busy_timeout(Duration::from_secs(5)), + ) + .await + .unwrap(); + let bus = SqliteBus::new(pool); + bus.ensure_tables().await.unwrap(); + bus + }; + + // Shared board storage (Redis in production). + let store = Arc::new(InMemoryLeaderboard::new()); + seed(&store).await; + + // GraphQL process: engine + bus handlers under its own consumer group. + let engine = engine(store.clone()).await; + let handlers = distributed_leaderboard::change_handlers(&engine, "graphql-1-boards"); + let graphql_bus = open().await; + let consumer = tokio::spawn(async move { + graphql_bus + .subscribe(Arc::new(handlers), RunOptions::default()) + .await + }); + + // Projector process: no engine, only the bus. + let projector_bus = open().await; + let notices = LeaderboardChangePublisher::spawn(BusPublisher::new(Arc::new(projector_bus)), 64); + let projection = + |event: &DomainEventOccurrence| -> Result, LeaderboardError> { + let body: XpGained = event + .decode_body() + .map_err(|error| LeaderboardError::invalid(error.to_string()))?; + Ok(vec![LeaderboardChange::new( + xp_board(), + ScoreSubmission::new(body.player, f64::from(body.xp), ScorePolicy::Increment), + )]) + }; + let projector = LeaderboardProjector::new( + store.clone() as Arc, + Arc::new(projection), + ) + .with_change_listener(notices.listener()); + + let mut stream = engine.execute_stream( + &session("user", Some("dan")), + Request::new("subscription { xpLeaderboard(first: 2) { member score } }"), + ); + let first = tokio::time::timeout(Duration::from_secs(5), stream.next()) + .await + .unwrap() + .unwrap(); + assert_eq!( + serde_json::to_value(&first.data).unwrap()["xpLeaderboard"][0]["member"], + "ann" + ); + + projector.apply_event(&gained(1, "dan", 100)).await.unwrap(); + let pushed = tokio::time::timeout(Duration::from_secs(10), stream.next()) + .await + .expect("a projector in another process drives @live over the bus") + .unwrap(); + assert_eq!( + serde_json::to_value(&pushed.data).unwrap()["xpLeaderboard"], + serde_json::json!([{ "member": "dan", "score": 120.0 }, { "member": "ann", "score": 50.0 }]) + ); + + consumer.abort(); + for suffix in ["", "-wal", "-shm"] { + let _ = std::fs::remove_file(format!("{}{suffix}", path.display())); + } +} + +#[test] +fn an_application_manifest_carries_and_validates_its_leaderboards() { + let spec = distributed::SurfaceSpec::from_surface("boards", &surfaces()).unwrap(); + assert_eq!(spec.contract.external[LEADERBOARDS_SECTION].len(), 2); + let built = distributed::Application::new("boards") + .surface(spec.clone()) + .build() + .expect("a surface with leaderboards validates"); + let json = serde_json::to_value(built.manifest()).unwrap(); + assert!(json.to_string().contains("\"leaderboards\"")); + + // Tampering with the leaderboard section breaks the surface fingerprint. + let mut tampered = spec; + tampered + .contract + .external + .get_mut(LEADERBOARDS_SECTION) + .unwrap() + .pop(); + assert!(distributed::Application::new("boards") + .surface(tampered) + .build() + .is_err()); + + // Without leaderboards the section is absent (existing manifests keep + // their bytes). + let plain = distributed::SurfaceSpec::from_surface( + "plain", + &build_surface( + &distributed::ReadModelCatalog::new("plain").tables, + &SurfaceOptions::sqlite(), + ) + .unwrap(), + ) + .unwrap(); + assert!(!serde_json::to_string(&plain).unwrap().contains("external")); +} + +#[test] +fn attaching_sources_refuses_duplicates_and_root_collisions() { + let empty = || build_surface(&[], &SurfaceOptions::sqlite()).unwrap(); + let duplicate = empty() + .with_external_sources(sources([xp_surface(), xp_surface()])) + .unwrap_err(); + assert!(duplicate.contains("duplicate"), "{duplicate}"); + // `xpMy` + `Rank` collides with `xp` + `MyRank`. + let colliding = LeaderboardSurface::single("xpMy", &xp_board()) + .grant("moderator", LeaderboardGrant::read().rank_any_member()); + let collision = empty() + .with_external_sources(sources([xp_surface(), colliding])) + .unwrap_err(); + assert!(collision.contains("collides"), "{collision}"); + // Two sources share the entry type. + assert!(empty() + .with_external_sources(sources([xp_surface(), season_surface()])) + .is_ok()); + let invalid = empty() + .with_external_sources(sources([xp_surface().limits(0, 1, 1)])) + .unwrap_err(); + assert!(invalid.contains("limits"), "{invalid}"); +} diff --git a/distributed_leaderboard/tests/redis.rs b/distributed_leaderboard/tests/redis.rs new file mode 100644 index 000000000..0aac66e3f --- /dev/null +++ b/distributed_leaderboard/tests/redis.rs @@ -0,0 +1,239 @@ +//! Redis leaderboard store integration tests. +//! +//! Tests that need a server skip (with a logged reason) when `REDIS_URL` is +//! unset; the unavailable-server test always runs. +//! +//! REDIS_URL=redis://127.0.0.1:6379 cargo test -p distributed_leaderboard --features redis,graphql --test redis +#![cfg(feature = "redis")] + +use std::sync::Arc; +use std::time::{Duration, UNIX_EPOCH}; + +use distributed::bus::{Message, MessageKind}; +use distributed::DomainEventOccurrence; +use distributed_leaderboard::{ + conformance, Board, LeaderboardChange, LeaderboardError, LeaderboardErrorKind, + LeaderboardProjector, LeaderboardStore, RedisLeaderboard, ScorePolicy, ScoreSubmission, +}; + +use common::env as env_support; + +fn redis_url() -> Option { + env_support::require_service("REDIS_URL", "redis leaderboard test") +} + +fn unique(prefix: &str) -> String { + format!("{prefix}-{}", uuid::Uuid::now_v7().simple()) +} + +#[derive(serde::Serialize, serde::Deserialize, distributed::DomainEvent)] +#[domain_event(name = "dungeon.gold_looted", version = 1)] +struct GoldLooted { + player: String, + gold: u32, +} + +fn looted(position: u64, player: &str, gold: u32) -> DomainEventOccurrence { + DomainEventOccurrence::capture_external( + distributed::ExternalEventSource { + producer: "zone.sim".into(), + stream: "zone-7".into(), + position, + key: "loot".into(), + }, + UNIX_EPOCH + Duration::from_secs(position), + Default::default(), + &GoldLooted { + player: player.into(), + gold, + }, + ) + .unwrap() +} + +#[tokio::test] +async fn redis_store_satisfies_the_leaderboard_contract() { + let Some(url) = redis_url() else { return }; + let store = RedisLeaderboard::connect(&url) + .unwrap() + .with_prefix(unique("test:lb")); + conformance::run_store_contract(&store, "contract").await; +} + +#[tokio::test] +async fn redis_projector_dedupes_replays_and_rebuilds() { + let Some(url) = redis_url() else { return }; + let store = Arc::new( + RedisLeaderboard::connect(&url) + .unwrap() + .with_prefix(unique("test:lb")), + ); + let board = Board::high_first("gold").unwrap(); + let projection_board = board.clone(); + let projection = move |event: &DomainEventOccurrence| { + let body: GoldLooted = event + .decode_body() + .map_err(|err| LeaderboardError::invalid(err.to_string()))?; + Ok(vec![LeaderboardChange::new( + projection_board.clone(), + ScoreSubmission::new(body.player, f64::from(body.gold), ScorePolicy::Increment), + )]) + }; + let projector = LeaderboardProjector::new(Arc::clone(&store), Arc::new(projection)); + let history = vec![ + looted(1, "ann", 10), + looted(2, "bob", 7), + looted(3, "ann", 5), + ]; + + for event in &history { + let message = Message::new( + event.descriptor().name.to_string(), + MessageKind::Event, + event.canonical_bytes().unwrap(), + ) + .with_id(event.id()); + assert_eq!(projector.apply_message(&message).await.unwrap().applied, 1); + // Redelivery is a no-op. + assert_eq!( + projector.apply_message(&message).await.unwrap().duplicates, + 1 + ); + } + assert_eq!(store.score(&board, "ann").await.unwrap(), Some(15.0)); + + store + .submit( + &board, + &ScoreSubmission::new("drift", 99.0, ScorePolicy::Replace), + ) + .await + .unwrap(); + let report = projector + .rebuild(std::slice::from_ref(&board), &history) + .await + .unwrap(); + assert_eq!(report.applied, 3); + let top = store.top(&board, 10).await.unwrap(); + let rows: Vec<_> = top.iter().map(|e| (e.member.as_str(), e.score)).collect(); + assert_eq!(rows, vec![("ann", 15.0), ("bob", 7.0)]); + assert_eq!( + projector.apply_event(&history[2]).await.unwrap().duplicates, + 1 + ); + store.reset(&board).await.unwrap(); +} + +#[tokio::test] +async fn unreachable_redis_fails_fast_as_retryable() { + // Port 1 is never a Redis server; construction must not block. + let store = RedisLeaderboard::connect("redis://127.0.0.1:1").unwrap(); + let board = Board::high_first("gold").unwrap(); + let started = std::time::Instant::now(); + let err = store + .submit( + &board, + &ScoreSubmission::new("p", 1.0, ScorePolicy::Increment), + ) + .await + .unwrap_err(); + assert_eq!(err.kind(), LeaderboardErrorKind::Unavailable); + assert!(err.into_transport_error().is_retryable()); + assert!(started.elapsed() < Duration::from_secs(10)); +} + +/// The same Redis boards served through GraphQL: roots read the sorted sets +/// and an applied projector change refreshes a `@live` top-N. +#[cfg(feature = "graphql")] +#[tokio::test] +async fn redis_boards_serve_graphql_queries_and_live_updates() { + use distributed::graphql::{GraphqlEngine, IdentityConfig}; + use distributed::microsvc::{Session, ROLE_KEY, USER_ID_KEY}; + use distributed_leaderboard::{LeaderboardGrant, LeaderboardRoots, LeaderboardSurface}; + use futures_util::StreamExt; + + let Some(url) = redis_url() else { return }; + let store = Arc::new( + RedisLeaderboard::connect(&url) + .unwrap() + .with_prefix(unique("gql")), + ); + let board = Board::high_first("gold").unwrap(); + for (member, score) in [("ann", 30.0), ("bob", 20.0)] { + store + .submit( + &board, + &ScoreSubmission::new(member, score, ScorePolicy::Replace), + ) + .await + .unwrap(); + } + let repo = distributed::SqliteRepository::connect_and_migrate("sqlite::memory:") + .await + .unwrap(); + let engine = GraphqlEngine::from_schema_catalog( + &distributed::ReadModelCatalog::new("gold-service"), + repo.pool().clone(), + ) + .unwrap() + .identity(IdentityConfig::dev_headers()) + .roles(&["user"]) + .external_read_source(Arc::new(LeaderboardRoots::new( + LeaderboardSurface::single("gold", &board).grant("user", LeaderboardGrant::read()), + store.clone(), + ))) + .build() + .unwrap(); + let mut session = Session::new(); + session.set(ROLE_KEY, "user"); + session.set(USER_ID_KEY, "bob"); + + let mine = engine + .execute( + &session, + async_graphql::Request::new("{ goldMyRank { rank score } }"), + ) + .await; + assert!(mine.errors.is_empty(), "{:?}", mine.errors); + assert_eq!( + serde_json::to_value(&mine.data).unwrap()["goldMyRank"], + serde_json::json!({ "rank": 1, "score": 20.0 }) + ); + + let projector = LeaderboardProjector::new( + store.clone(), + Arc::new( + |event: &DomainEventOccurrence| -> Result, LeaderboardError> { + let body: GoldLooted = event + .decode_body() + .map_err(|error| LeaderboardError::invalid(error.to_string()))?; + Ok(vec![LeaderboardChange::new( + Board::high_first("gold").unwrap(), + ScoreSubmission::new(body.player, f64::from(body.gold), ScorePolicy::Increment), + )]) + }, + ), + ) + .with_change_listener(distributed_leaderboard::change_listener(&engine)); + let mut live = engine.execute_stream( + &session, + async_graphql::Request::new("subscription { goldLeaderboard(first: 1) { member } }"), + ); + let first = tokio::time::timeout(Duration::from_secs(5), live.next()) + .await + .unwrap() + .unwrap(); + assert_eq!( + serde_json::to_value(&first.data).unwrap()["goldLeaderboard"], + serde_json::json!([{ "member": "ann" }]) + ); + projector.apply_event(&looted(1, "bob", 50)).await.unwrap(); + let pushed = tokio::time::timeout(Duration::from_secs(5), live.next()) + .await + .unwrap() + .unwrap(); + assert_eq!( + serde_json::to_value(&pushed.data).unwrap()["goldLeaderboard"], + serde_json::json!([{ "member": "bob" }]) + ); +} diff --git a/distributed_macros/Cargo.toml b/distributed_macros/Cargo.toml index ef5c67d38..165b21a75 100644 --- a/distributed_macros/Cargo.toml +++ b/distributed_macros/Cargo.toml @@ -9,10 +9,6 @@ repository.workspace = true [lib] proc-macro = true -[features] -application-runtime = ["distributed/application-runtime"] -runtime = ["application-runtime"] - [dependencies] proc-macro-crate = "3.5" proc-macro2 = "1.0" @@ -28,3 +24,5 @@ trybuild = "=1.0.121" # Cargo permits dev-dependency cycles. distributed = { path = ".." } serde = { version = "1.0", features = ["derive"] } +# Reads `cargo check --message-format=json` in tests/rustc_fail.rs. +serde_json = "1" diff --git a/distributed_macros/src/aggregate.rs b/distributed_macros/src/aggregate.rs index a3101b14f..8dd0358f5 100644 --- a/distributed_macros/src/aggregate.rs +++ b/distributed_macros/src/aggregate.rs @@ -1,48 +1,54 @@ use proc_macro2::TokenStream as TokenStream2; use quote::{format_ident, quote}; use syn::{ - braced, parse::{Parse, ParseStream}, Ident, LitStr, Token, }; -/// Emit the `impl distributed::Aggregate` block shared by `aggregate!` and -/// `#[sourced]`. -/// -/// Both entry points produce a byte-identical impl: same associated -/// `ReplayError = String`, same `entity`/`entity_mut`/`replay_event` bodies, and -/// the same optional `aggregate_type` and upcasters methods. Only the replay -/// match arms differ in how they are built upstream, so this helper takes them -/// (already rendered) along with the type name and entity field. Keeping one -/// emitter prevents the replay semantics of the two macros from drifting. +/// Emit the `impl distributed::Aggregate` block of `#[sourced]`: the version +/// fence, then the replay match. The arms are built by the caller. /// /// It emits only the `impl` block; callers still place `#upcaster_wrappers` /// (the free upcaster fns) where they already do. pub(crate) fn aggregate_impl_tokens( + framework: &TokenStream2, type_name: &Ident, entity_field: &Ident, aggregate_type_method: &Option, + version_arms: &[TokenStream2], replay_arms: &[TokenStream2], upcasters_method: &TokenStream2, ) -> TokenStream2 { quote! { - impl distributed::Aggregate for #type_name { + impl #framework::Aggregate for #type_name { type ReplayError = String; #aggregate_type_method - fn entity(&self) -> &distributed::Entity { + fn entity(&self) -> &#framework::Entity { &self.#entity_field } - fn entity_mut(&mut self) -> &mut distributed::Entity { + fn entity_mut(&mut self) -> &mut #framework::Entity { &mut self.#entity_field } fn replay_event( &mut self, - event: &distributed::EventRecord, + event: &#framework::EventRecord, ) -> Result<(), Self::ReplayError> { + // Hydration runs upcasters first. Payload compatibility alone + // cannot establish that an event has the handler's semantics. + let expected_version: u64 = match event.event_name.as_str() { + #(#version_arms)* + _ => return Err(format!("Unknown event: {}", event.event_name)), + }; + if event.event_version != expected_version { + return Err(format!( + "Unsupported event version for {}: expected {}, got {}", + event.event_name, expected_version, event.event_version, + )); + } match event.event_name.as_str() { #(#replay_arms)* _ => return Err(format!("Unknown event: {}", event.event_name)), @@ -55,9 +61,6 @@ pub(crate) fn aggregate_impl_tokens( } } -// ============================================================================ -// aggregate! proc-macro -// ============================================================================ fn upcaster_wrapper_prefix(owner: &Ident) -> String { owner .to_string() @@ -99,6 +102,7 @@ pub(crate) fn event_variant_ident(event_name: &LitStr) -> Ident { } pub(crate) fn generate_upcaster_tokens( + framework: &TokenStream2, owner: &Ident, upcasters: &[UpcasterDef], ) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) { @@ -123,9 +127,9 @@ pub(crate) fn generate_upcaster_tokens( let transform_fn = &u.transform_fn; quote! { fn #wrapper( - event: &distributed::EventRecord, - ) -> Result, distributed::UpcastError> { - distributed::upcast_payload::<#source_type, #target_type>( + event: &#framework::EventRecord, + ) -> Result, #framework::UpcastError> { + #framework::upcast_payload::<#source_type, #target_type>( event, #to_version, #transform_fn, @@ -142,7 +146,7 @@ pub(crate) fn generate_upcaster_tokens( let from_version = &u.from_version; let to_version = &u.to_version; quote! { - distributed::EventUpcaster { + #framework::EventUpcaster { event_type: #event_name, from_version: #from_version, to_version: #to_version, @@ -152,8 +156,8 @@ pub(crate) fn generate_upcaster_tokens( }); let upcasters_method = quote! { - fn upcasters() -> &'static [distributed::EventUpcaster] { - static UPCASTERS: &[distributed::EventUpcaster] = &[ + fn upcasters() -> &'static [#framework::EventUpcaster] { + static UPCASTERS: &[#framework::EventUpcaster] = &[ #(#upcaster_entries),* ]; UPCASTERS @@ -170,97 +174,6 @@ pub(crate) fn generate_upcaster_tokens( ) } -// ============================================================================ -// #[enqueue] attribute macro -// ============================================================================ -pub(crate) fn expand_aggregate(input: TokenStream2) -> syn::Result { - let input = syn::parse2::(input)?; - - let agg_name = &input.agg_name; - let entity_field = &input.entity_field; - - // Generate replay match arms - deserialize and call method directly - let replay_arms: Vec<_> = input - .events - .iter() - .map(|evt| { - let event_name = &evt.event_name; - let method_name = &evt.method_name; - let args = &evt.args; - - // Determine what args to pass to the method - let call_args: Vec<_> = match &evt.method_args { - Some(method_args) => method_args.clone(), - None => args.clone(), - }; - - if args.is_empty() { - // No payload - quote! { - #event_name => { - self.#method_name().map_err(|e| e.to_string())?; - } - } - } else if call_args.is_empty() { - // Event has payload but method takes no args - quote! { - #event_name => { - self.#method_name().map_err(|e| e.to_string())?; - } - } - } else if args.len() == 1 { - // Single-element tuple needs trailing comma: (x,) not (x) - let arg = &args[0]; - let call_arg = &call_args[0]; - quote! { - #event_name => { - let (#arg,) = event.decode().map_err(|e| e.to_string())?; - self.#method_name(#call_arg).map_err(|e| e.to_string())?; - } - } - } else { - // Multi-element tuple - quote! { - #event_name => { - let (#(#args),*) = event.decode().map_err(|e| e.to_string())?; - self.#method_name(#(#call_args),*).map_err(|e| e.to_string())?; - } - } - } - }) - .collect(); - - let (upcaster_wrappers, upcasters_method) = - generate_upcaster_tokens(agg_name, &input.upcasters); - let aggregate_type_method = input.aggregate_type.as_ref().map(|aggregate_type| { - quote! { - fn aggregate_type() -> &'static str { - #aggregate_type - } - } - }); - - // ReplayError stays `String`: replay errors are flattened from - // heterogeneous sources (per-event `decode()` errors, user method errors of - // arbitrary `E`, and unknown-event messages) via `e.to_string()`. A typed - // error would have to be generic over each method's error type or erase - // them anyway, so `String` is the smaller, honest representation here. - let aggregate_impl = aggregate_impl_tokens( - agg_name, - entity_field, - &aggregate_type_method, - &replay_arms, - &upcasters_method, - ); - let expanded = quote! { - #upcaster_wrappers - - #aggregate_impl - }; - - Ok(expanded) -} - pub(crate) struct UpcasterDef { pub(crate) event_name: LitStr, pub(crate) from_version: syn::LitInt, @@ -317,21 +230,6 @@ pub(crate) fn parse_upcaster_list(content: ParseStream) -> syn::Result, - events: Vec, - upcasters: Vec, -} - -struct EventDef { - event_name: LitStr, - args: Vec, - method_name: Ident, - method_args: Option>, // None = use event args, Some([]) = no args, Some([x,y]) = specific args -} - pub(crate) fn validate_aggregate_type_literal(lit: &LitStr) -> syn::Result<()> { let value = lit.value(); if value.trim().is_empty() { @@ -348,90 +246,3 @@ pub(crate) fn validate_aggregate_type_literal(lit: &LitStr) -> syn::Result<()> { } Ok(()) } - -impl Parse for AggregateInput { - fn parse(input: ParseStream) -> syn::Result { - let agg_name: Ident = input.parse()?; - input.parse::()?; - let entity_field: Ident = input.parse()?; - let mut aggregate_type = None; - - if input.peek(Token![,]) { - input.parse::()?; - let kw: Ident = input.parse()?; - if kw != "aggregate_type" { - return Err(syn::Error::new(kw.span(), "expected `aggregate_type`")); - } - input.parse::()?; - let lit = input.parse::()?; - validate_aggregate_type_literal(&lit)?; - aggregate_type = Some(lit); - } - - let content; - braced!(content in input); - - let mut events = Vec::new(); - while !content.is_empty() { - let event_name: LitStr = content.parse()?; - - // Parse (arg1, arg2, ...) - let args_content; - syn::parenthesized!(args_content in content); - let args: syn::punctuated::Punctuated = - args_content.parse_terminated(Ident::parse, Token![,])?; - let args: Vec = args.into_iter().collect(); - - content.parse::]>()?; - let method_name: Ident = content.parse()?; - - // Check for optional method args: method() or method(a, b) - let method_args = if content.peek(syn::token::Paren) { - let method_args_content; - syn::parenthesized!(method_args_content in content); - let method_args: syn::punctuated::Punctuated = - method_args_content.parse_terminated(Ident::parse, Token![,])?; - Some(method_args.into_iter().collect()) - } else { - None // Use event args - }; - - events.push(EventDef { - event_name, - args, - method_name, - method_args, - }); - - // Optional trailing comma - if content.peek(Token![,]) { - content.parse::()?; - } - } - - // Parse optional `upcasters [...]` block - let mut upcasters = Vec::new(); - if input.peek(syn::Ident) { - let kw: Ident = input.parse()?; - if kw != "upcasters" { - return Err(syn::Error::new(kw.span(), "expected `upcasters`")); - } - - let upcaster_content; - syn::bracketed!(upcaster_content in input); - upcasters = parse_upcaster_list(&upcaster_content)?; - } - - Ok(AggregateInput { - agg_name, - entity_field, - aggregate_type, - events, - upcasters, - }) - } -} - -// ============================================================================ -// #[sourced] attribute macro -// ============================================================================ diff --git a/distributed_macros/src/aggregate_command.rs b/distributed_macros/src/aggregate_command.rs new file mode 100644 index 000000000..d2232211f --- /dev/null +++ b/distributed_macros/src/aggregate_command.rs @@ -0,0 +1,619 @@ +//! `#[command("aggregate.verb", ..)]` on an aggregate method inside a +//! `#[sourced]` impl: the method is the command. `#[sourced]` strips the +//! attribute and emits a portable mount (`pub struct Verb`) whose generated +//! handler binds the principal from the verified session, loads (or +//! creates) the aggregate, calls the method, maps its error to `Rejected`, +//! builds the payload and commits with publication. +//! +//! ```ignore +//! #[command("crawler.record_kill", shard = principal, load = or_create, outcome = succeeded)] +//! pub fn record_kill(&mut self, #[principal] principal: &str, input: RecordKillInput) +//! -> Result { .. } +//! ``` +//! +//! Options: `shard = ` (required unless +//! `load = create`), `load = required | or_create | create`, +//! `outcome = succeeded | eventual | Succeeded

| Eventual

`, +//! `payload = path` (`fn(&Aggregate) -> P`; otherwise the method's `Ok` +//! value is the payload), `roles = ["player", ..]`, `guard = expr`, +//! `field = "graphql_field"`, `input = Type` (map the remaining method +//! parameters to the input's fields by name instead of passing the whole +//! input), `transition = path` (override the domain transition witness), +//! `mount = Ident` (name of the generated struct). + +use proc_macro2::{Span, TokenStream}; +use quote::{format_ident, quote, quote_spanned}; +use syn::parse::{Parse, ParseStream}; +use syn::{Expr, FnArg, Ident, ImplItemFn, LitStr, Pat, Path, ReturnType, Token, Type}; + +#[derive(Clone, Copy, PartialEq)] +enum Load { + Required, + OrCreate, + Create, +} + +enum Outcome { + /// `succeeded` / `eventual`: the payload type is the method's `Ok` type. + Keyword { eventual: bool, span: Span }, + /// `Succeeded

` / `Eventual

`. + Type { ty: Box, eventual: bool }, +} + +struct Args { + name: LitStr, + shard: Option, + load: Load, + outcome: Outcome, + payload: Option, + roles: Option>, + guard: Option, + field: Option, + input: Option, + transition: Option, + mount: Option, +} + +impl Parse for Args { + fn parse(input: ParseStream<'_>) -> syn::Result { + let name: LitStr = input.parse().map_err(|_| { + input.error("#[command] on an aggregate method starts with the command name: #[command(\"aggregate.verb\", ..)]") + })?; + validate_name(&name)?; + let mut shard = None; + let mut load = None; + let mut outcome = None; + let mut payload = None; + let mut roles = None; + let mut guard = None; + let mut field = None; + let mut input_ty = None; + let mut transition = None; + let mut mount = None; + let mut seen = std::collections::HashSet::new(); + while !input.is_empty() { + input.parse::()?; + if input.is_empty() { + break; + } + let key: Ident = input.parse()?; + if !seen.insert(key.to_string()) { + return Err(syn::Error::new( + key.span(), + format!("duplicate #[command] option `{key}`"), + )); + } + input.parse::()?; + match key.to_string().as_str() { + "shard" => shard = Some(input.parse::()?), + "load" => { + let value: Ident = input.parse()?; + load = Some(match value.to_string().as_str() { + "required" => Load::Required, + "or_create" => Load::OrCreate, + "create" => Load::Create, + other => { + return Err(syn::Error::new( + value.span(), + format!("load must be `required`, `or_create` or `create`, not `{other}`"), + )) + } + }); + } + "outcome" => { + let ty: Type = input.parse()?; + outcome = Some(parse_outcome(ty)?); + } + "payload" => payload = Some(input.parse::()?), + "roles" => { + let expr: Expr = input.parse()?; + roles = Some(role_list(&expr)?); + } + "guard" => guard = Some(input.parse::()?), + "field" => field = Some(input.parse::()?), + "input" => input_ty = Some(input.parse::()?), + "transition" => transition = Some(input.parse::()?), + "mount" => mount = Some(input.parse::()?), + other => { + return Err(syn::Error::new( + key.span(), + format!( + "unknown #[command] option `{other}`; expected `shard`, `load`, `outcome`, `payload`, `roles`, `guard`, `field`, `input`, `transition` or `mount`" + ), + )) + } + } + } + let load = load.ok_or_else(|| { + syn::Error::new( + name.span(), + "#[command] needs `load = required | or_create | create`", + ) + })?; + let outcome = outcome.ok_or_else(|| { + syn::Error::new( + name.span(), + "#[command] needs `outcome = succeeded | eventual` (or `Succeeded

` / `Eventual

`)", + ) + })?; + if load != Load::Create && shard.is_none() { + return Err(syn::Error::new( + name.span(), + "#[command] needs `shard = ` to load the aggregate", + )); + } + Ok(Self { + name, + shard, + load, + outcome, + payload, + roles, + guard, + field, + input: input_ty, + transition, + mount, + }) + } +} + +pub(crate) fn validate_name(name: &LitStr) -> syn::Result<()> { + let value = name.value(); + let segments: Vec<&str> = value.split('.').collect(); + if segments.len() < 2 + || segments.iter().any(|segment| { + segment.is_empty() + || !segment + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_') + }) + { + return Err(syn::Error::new( + name.span(), + "command name must be 2+ dot-separated snake_case segments (e.g. \"character.equip\")", + )); + } + Ok(()) +} + +fn parse_outcome(ty: Type) -> syn::Result { + let Type::Path(path) = &ty else { + return Err(syn::Error::new_spanned( + &ty, + "outcome must be `succeeded`, `eventual`, `Succeeded

` or `Eventual

`", + )); + }; + let last = path.path.segments.last().expect("non-empty path"); + let ident = last.ident.to_string(); + let bare = path.path.segments.len() == 1 && last.arguments.is_empty(); + match ident.as_str() { + "succeeded" | "eventual" if bare => Ok(Outcome::Keyword { + eventual: ident == "eventual", + span: last.ident.span(), + }), + "Succeeded" | "Eventual" if !last.arguments.is_empty() => Ok(Outcome::Type { + eventual: ident == "Eventual", + ty: Box::new(ty.clone()), + }), + _ => Err(syn::Error::new_spanned( + &ty, + "outcome must be `succeeded`, `eventual`, `Succeeded

` or `Eventual

`", + )), + } +} + +pub(crate) fn role_list(expr: &Expr) -> syn::Result> { + let Expr::Array(array) = expr else { + return Err(syn::Error::new_spanned( + expr, + "roles must be an array of string literals, e.g. [\"player\"]", + )); + }; + let mut roles = Vec::new(); + for elem in &array.elems { + match elem { + Expr::Lit(syn::ExprLit { + lit: syn::Lit::Str(value), + .. + }) if !value.value().trim().is_empty() => roles.push(value.clone()), + other => { + return Err(syn::Error::new_spanned( + other, + "roles entries must be non-empty string literals", + )) + } + } + } + if roles.is_empty() { + return Err(syn::Error::new_spanned( + expr, + "roles must name at least one role (omit `roles` for an internal command)", + )); + } + Ok(roles) +} + +/// One parameter after `self`. +struct Param { + name: Ident, + ty: Type, +} + +/// A `#[command]` aggregate method, collected by `#[sourced]`. +pub(crate) struct CommandMethod { + args: Args, + method: Ident, + principal: Param, + /// Whole-input parameter (no `input = T`), or the parameters mapped to + /// input fields by name. + params: Vec, + /// Every parameter name after `self`, in declaration order. + order: Vec, + ok_type: Option, +} + +impl CommandMethod { + pub(crate) fn method(&self) -> &Ident { + &self.method + } +} + +/// Strip `#[command(..)]` (and `#[principal]`) from `method`; `None` when it +/// is not a command. +pub(crate) fn take(method: &mut ImplItemFn) -> syn::Result> { + let Some(index) = method + .attrs + .iter() + .position(|attr| attr.path().is_ident("command")) + else { + return Ok(None); + }; + let attr = method.attrs.remove(index); + let args: Args = attr.parse_args()?; + if method.sig.asyncness.is_some() { + return Err(syn::Error::new_spanned( + method.sig.asyncness, + "#[command] aggregate methods are synchronous decisions; the generated handler does the I/O", + )); + } + if !matches!( + method.sig.inputs.first(), + Some(FnArg::Receiver(receiver)) if receiver.reference.is_some() && receiver.mutability.is_some() + ) { + return Err(syn::Error::new_spanned( + &method.sig, + "#[command] methods take `&mut self`", + )); + } + let mut principal = None; + let mut params = Vec::new(); + let mut order = Vec::new(); + for arg in method.sig.inputs.iter_mut().skip(1) { + let FnArg::Typed(typed) = arg else { continue }; + let Pat::Ident(pat) = &*typed.pat else { + return Err(syn::Error::new_spanned( + &typed.pat, + "#[command] parameters must be plain identifiers", + )); + }; + let is_principal = typed + .attrs + .iter() + .any(|attr| attr.path().is_ident("principal")); + typed + .attrs + .retain(|attr| !attr.path().is_ident("principal")); + let param = Param { + name: pat.ident.clone(), + ty: (*typed.ty).clone(), + }; + order.push(param.name.clone()); + if is_principal { + if principal.is_some() { + return Err(syn::Error::new_spanned( + &typed.pat, + "only one #[principal] parameter", + )); + } + principal = Some(param); + } else { + params.push(param); + } + } + let principal = principal.ok_or_else(|| { + syn::Error::new_spanned( + &method.sig.inputs, + "a #[command] method needs a `#[principal]` parameter (`&str` or `String`): the actor comes from the verified session, never from the input", + ) + })?; + if args.input.is_none() && params.len() != 1 { + return Err(syn::Error::new_spanned( + &method.sig.inputs, + "a #[command] method takes `#[principal]` and one input parameter; with `input = Type` its other parameters are the input's fields by name", + )); + } + let ok_type = match &method.sig.output { + ReturnType::Type(_, ty) => result_ok_type(ty), + ReturnType::Default => None, + }; + if ok_type.is_none() { + return Err(syn::Error::new_spanned( + &method.sig, + "#[command] methods return `Result` (`E: Display` becomes the rejection; `T` is the payload unless `payload = ..` is set)", + )); + } + if let (Outcome::Keyword { span, .. }, Some(_)) = (&args.outcome, &args.payload) { + return Err(syn::Error::new( + *span, + "with `payload = ..` name the payload type: `outcome = Succeeded

` or `Eventual

`", + )); + } + Ok(Some(CommandMethod { + args, + method: method.sig.ident.clone(), + principal, + params, + order, + ok_type, + })) +} + +/// `T` of `Result` (any path ending in `Result` with two arguments, or +/// one for an alias like `SourcedResult`); `()` for a bare alias. +fn result_ok_type(ty: &Type) -> Option { + let Type::Path(path) = ty else { return None }; + let last = path.path.segments.last()?; + if !last.ident.to_string().ends_with("Result") { + return None; + } + match &last.arguments { + syn::PathArguments::AngleBracketed(args) => match args.args.first()? { + syn::GenericArgument::Type(ok) => Some(ok.clone()), + _ => None, + }, + syn::PathArguments::None => Some(syn::parse_quote!(())), + syn::PathArguments::Parenthesized(_) => None, + } +} + +fn is_reference(ty: &Type) -> bool { + matches!(ty, Type::Reference(_)) +} + +fn pascal(segment: &str) -> String { + segment + .split('_') + .filter(|part| !part.is_empty()) + .map(|part| { + let mut chars = part.chars(); + match chars.next() { + Some(first) => first.to_uppercase().collect::() + chars.as_str(), + None => String::new(), + } + }) + .collect() +} + +/// The mount, its handler and its registration. `transition` is the domain +/// transition witness `#[sourced]` discovered for the method, if any. +pub(crate) fn expand( + command: &CommandMethod, + aggregate: &Type, + transition: Option, + framework: &TokenStream, +) -> syn::Result { + let fw = framework; + let args = &command.args; + let name = &args.name; + let name_value = name.value(); + let last = name_value.rsplit('.').next().expect("validated"); + let mount = args + .mount + .clone() + .unwrap_or_else(|| format_ident!("{}", pascal(last), span = name.span())); + let method = &command.method; + let principal = &command.principal; + let principal_name = principal.name.to_string(); + + let input_ty: Type = match &args.input { + Some(ty) => ty.clone(), + None => command.params[0].ty.clone(), + }; + + // Payload type. + let payload_ty: Type = match &args.outcome { + Outcome::Type { ty, .. } => { + let Type::Path(path) = &**ty else { + unreachable!() + }; + let last = path.path.segments.last().expect("path"); + match &last.arguments { + syn::PathArguments::AngleBracketed(a) => match a.args.first() { + Some(syn::GenericArgument::Type(p)) => p.clone(), + _ => return Err(syn::Error::new_spanned(ty, "expected `Succeeded

`")), + }, + _ => return Err(syn::Error::new_spanned(ty, "expected `Succeeded

`")), + } + } + Outcome::Keyword { .. } => command.ok_type.clone().expect("checked"), + }; + let eventual = match &args.outcome { + Outcome::Keyword { eventual, .. } | Outcome::Type { eventual, .. } => *eventual, + }; + let outcome_ty = if eventual { + quote!(#fw::command::Eventual<#payload_ty>) + } else { + quote!(#fw::command::Succeeded<#payload_ty>) + }; + let terminal = if eventual { + quote!(eventual) + } else { + quote!(succeeded) + }; + + // Shard. + let shard_by_principal = args.shard.as_ref().is_some_and(|s| *s == principal.name); + let shard_fn = match &args.shard { + Some(field) if !shard_by_principal => Some(quote! { + /// Aggregate id (shard) of a command input. + pub fn shard(input: &#input_ty) -> ::std::string::String { + ::std::string::ToString::to_string(&input.#field) + } + }), + _ => None, + }; + let shard_expr = if shard_by_principal { + quote!(::std::clone::Clone::clone(&__principal)) + } else { + quote!(Self::shard(&input)) + }; + let load = match args.load { + Load::Required => quote!(#fw::microsvc::CommandLoad::Required(#shard_expr)), + Load::OrCreate => quote!(#fw::microsvc::CommandLoad::OrCreate(#shard_expr)), + Load::Create => quote!(#fw::microsvc::CommandLoad::Create(::std::option::Option::None)), + }; + + // Call arguments. + let principal_arg = if is_reference(&principal.ty) { + quote!(&__principal) + } else { + quote!(::std::convert::Into::into(::std::clone::Clone::clone( + &__principal + ))) + }; + let call_args: Vec = if args.input.is_some() { + command + .params + .iter() + .map(|param| { + let field = ¶m.name; + if is_reference(¶m.ty) { + quote_spanned!(field.span()=> &input.#field) + } else { + quote_spanned!(field.span()=> input.#field) + } + }) + .collect() + } else { + vec![quote!(input)] + }; + let payload = match &args.payload { + Some(payload) => quote! { + let _ = __out; + let __payload: #payload_ty = #payload(__checkout.aggregate()); + }, + None => quote! { let __payload: #payload_ty = __out; }, + }; + + // Compile-time principal check: no input field may be named like the + // principal parameter (the session is its only source). + let message = format!( + "#[command(\"{name_value}\")]: the input has a field named `{principal_name}`, the #[principal] parameter; the principal comes from the verified session only, so it can never be an input field" + ); + let principal_check = quote_spanned! {principal.name.span()=> + const _: () = { + if #fw::command::__input_has_field( + <#input_ty as #fw::command::CommandInputType>::FIELD_NAMES, + #principal_name, + ) { + ::core::panic!(#message); + } + }; + }; + + let transition = match &args.transition { + Some(path) => Some(quote!(#path)), + None => transition, + }; + let registration = match &transition { + Some(transition) => quote! { + routes.command_transition::<#transition, #input_ty, #outcome_ty>(Self::COMMAND) + }, + None => quote! { + routes.typed_command(#fw::command::typed_command::<#input_ty, #outcome_ty>(Self::COMMAND)) + }, + }; + let field = args.field.as_ref().map(|field| quote!(.field_name(#field))); + let roles = args + .roles + .as_ref() + .map(|roles| quote!(.roles([#(#roles),*]))); + let finish = match &args.guard { + Some(guard) => quote!(.guarded(#guard, Self::handle)), + None => quote!(.handle(Self::handle)), + }; + let doc = format!( + "Mounts `{name_value}` (`{}::{method}`): principal from the verified session, then load, call, commit.", + quote!(#aggregate).to_string().replace(' ', "") + ); + + let args_in_order = order_args(command, &principal_arg, &call_args); + + Ok(quote! { + #[doc = #doc] + #[derive(Debug, Clone, Copy, Default)] + pub struct #mount; + + #principal_check + + impl #mount { + /// Command name. + pub const COMMAND: &'static str = #name; + + #shard_fn + + /// The generated handler (also usable from a hand-written mount). + pub async fn handle( + ctx: &#fw::microsvc::CausalCommandContext<'_, #aggregate>, + input: #input_ty, + ) -> ::std::result::Result< + #fw::command::PreparedCommand<#outcome_ty>, + #fw::microsvc::HandlerError, + > { + // The principal: the verified session only. + let __principal: ::std::string::String = ctx.user_id()?.to_owned(); + let mut __checkout = #fw::microsvc::load_for_command(ctx, #load).await?; + let __out = __checkout + .aggregate_mut() + .#method(#(#args_in_order),*) + .map_err(|error| #fw::microsvc::HandlerError::Rejected(error.to_string()))?; + #payload + ctx.publish_events().commit(__checkout)?.#terminal(__payload) + } + } + + impl #fw::microsvc::PortableCommand for #mount + where + D: #fw::microsvc::CausalRouteDependencies + + ::std::marker::Send + + ::std::marker::Sync + + 'static, + { + fn install(self, routes: #fw::microsvc::Routes) -> #fw::microsvc::Routes { + #registration + #field + #roles + #finish + } + } + }) +} + +/// Arguments in the method's declaration order. +fn order_args( + command: &CommandMethod, + principal_arg: &TokenStream, + call_args: &[TokenStream], +) -> Vec { + let mut out = Vec::new(); + let mut rest = call_args.iter(); + for name in &command.order { + if *name == command.principal.name { + out.push(principal_arg.clone()); + } else if let Some(arg) = rest.next() { + out.push(arg.clone()); + } + } + out +} diff --git a/distributed_macros/src/application.rs b/distributed_macros/src/application.rs deleted file mode 100644 index 1004e4378..000000000 --- a/distributed_macros/src/application.rs +++ /dev/null @@ -1,123 +0,0 @@ -use proc_macro2::TokenStream; -use quote::{format_ident, quote}; -use syn::parse::{Parse, ParseStream}; -use syn::punctuated::Punctuated; -use syn::{Expr, Ident, LitStr, Token, Type, Visibility}; - -struct ApplicationInput { - visibility: Visibility, - name: Ident, - id: LitStr, - modules: Vec, - surfaces: Vec, - capabilities: Vec, - extensions: Vec, -} - -impl Parse for ApplicationInput { - fn parse(input: ParseStream<'_>) -> syn::Result { - let visibility: Visibility = input.parse()?; - let name: Ident = input.parse()?; - if input.peek(Token![:]) { - input.parse::()?; - let _: Type = input.parse()?; - } - if input.peek(Token![=]) { - input.parse::()?; - } - let content; - syn::braced!(content in input); - let mut output = Self { - visibility, - name, - id: LitStr::new("", proc_macro2::Span::call_site()), - modules: Vec::new(), - surfaces: Vec::new(), - capabilities: Vec::new(), - extensions: Vec::new(), - }; - while !content.is_empty() { - let field: Ident = content.parse()?; - content.parse::()?; - match field.to_string().as_str() { - "id" => output.id = content.parse()?, - "modules" => output.modules = parse_expr_array(&content)?, - "surfaces" => output.surfaces = parse_expr_array(&content)?, - "capabilities" | "required_capabilities" => { - output.capabilities = parse_expr_array(&content)? - } - "extensions" => output.extensions = parse_expr_array(&content)?, - other => { - return Err(syn::Error::new( - field.span(), - format!("unknown application field `{other}`"), - )) - } - } - if content.peek(Token![,]) { - content.parse::()?; - } - } - if output.id.value().is_empty() { - output.id = LitStr::new( - &output.name.to_string().to_ascii_lowercase(), - output.name.span(), - ); - } - Ok(output) - } -} - -fn parse_expr_array(input: ParseStream<'_>) -> syn::Result> { - let content; - syn::bracketed!(content in input); - Ok(Punctuated::::parse_terminated(&content)? - .into_iter() - .collect()) -} - -pub fn expand(input: proc_macro2::TokenStream) -> syn::Result { - let framework = crate::shared::framework_path()?; - let input = syn::parse2::(input)?; - let ApplicationInput { - visibility, - name, - id, - modules, - surfaces, - capabilities, - extensions, - } = input; - let accessor = format_ident!("{}", name.to_string().to_lowercase()); - let modules = modules.iter().map(|value| quote! { (&*#value).clone() }); - let surfaces = surfaces.iter().map(|value| quote! { (&*#value).clone() }); - let capabilities = capabilities - .iter() - .map(|value| quote! { #value }) - .collect::>(); - let extensions = extensions - .iter() - .map(|value| quote! { (&*#value).clone() }) - .collect::>(); - let capability_builder = if capabilities.is_empty() { - quote! {} - } else { - quote! { .required_capabilities([#(#capabilities),*]) } - }; - Ok(quote! { - #visibility static #name: ::std::sync::LazyLock<#framework::application::Application> = - ::std::sync::LazyLock::new(|| { - #framework::application::Application::new(#id) - .modules([#(#modules),*]) - .surfaces([#(#surfaces),*]) - .extensions([#(#extensions),*]) - #capability_builder - .build() - .unwrap_or_else(|error| panic!("invalid generated application: {error}")) - }); - - #visibility fn #accessor() -> &'static #framework::application::Application { - &#name - } - }) -} diff --git a/distributed_macros/src/command.rs b/distributed_macros/src/command.rs index f3871497d..35fa29316 100644 --- a/distributed_macros/src/command.rs +++ b/distributed_macros/src/command.rs @@ -1,142 +1,126 @@ +//! `command!` — domain command mounts (`PCH-DEC-001`). +//! +//! The handler attribute is already `#[command]`, so this function-like form +//! uses a distinct name. Spec sketches called it `command!`. + use proc_macro2::TokenStream; use quote::{format_ident, quote}; -use std::collections::HashSet; use syn::parse::{Parse, ParseStream}; -use syn::punctuated::Punctuated; -use syn::{Expr, FnArg, Ident, ItemFn, LitStr, PathArguments, ReturnType, Token, Type}; +use syn::{parenthesized, Expr, Ident, LitStr, Token, Type}; + +struct AuthenticatedUserField { + event: Type, + body: Type, + field: LitStr, +} + +impl Parse for AuthenticatedUserField { + fn parse(input: ParseStream<'_>) -> syn::Result { + let values; + parenthesized!(values in input); + let event = values.parse()?; + values.parse::()?; + let body = values.parse()?; + values.parse::()?; + let field = values.parse()?; + if !values.is_empty() { + return Err(values + .error("authenticated_user_field expects (EventType, BodyType, \"field_name\")")); + } + Ok(Self { event, body, field }) + } +} -#[derive(Default)] -struct CommandArgs { - id: Option, - field_name: Option, - input: Option, - outcome: Option, - roles: Option>, - emits: Vec, - applies: Option, +struct PortableCommandArgs { + name: LitStr, + transition: Type, + aggregate: Type, + input: Type, + outcome: Type, + shard: Expr, + field: LitStr, + roles: Vec, + load: LoadKind, + invoke: Option, + payload: Option, + handle: Option, + guard: Option, defaults: Option, - generated_defaults: Vec<(Ident, Ident)>, + constructor: Option, + authenticated_user_field: Option, + preview_reduce_known_record: Option, +} + +enum LoadKind { + Required, + OrCreate, + Create, + None, } -impl Parse for CommandArgs { +impl Parse for PortableCommandArgs { fn parse(input: ParseStream<'_>) -> syn::Result { - let mut args = Self::default(); - let mut seen_options = HashSet::new(); + let mut name = None; + let mut transition = None; + let mut aggregate = None; + let mut input_ty = None; + let mut outcome = None; + let mut shard = None; + let mut field = None; + let mut roles = Vec::new(); + let mut load = LoadKind::None; + let mut invoke = None; + let mut payload = None; + let mut handle = None; + let mut guard = None; + let mut defaults = None; + let mut constructor = None; + let mut authenticated_user_field = None; + let mut preview_reduce_known_record = None; + while !input.is_empty() { let key: Ident = input.parse()?; - let option = key.to_string(); - if !seen_options.insert(option.clone()) { - return Err(syn::Error::new( - key.span(), - format!("duplicate command option {option}"), - )); - } + input.parse::()?; match key.to_string().as_str() { - "roles" => { - let content; - syn::parenthesized!(content in input); - let values = Punctuated::::parse_terminated(&content)?; - let mut roles = Vec::new(); - let mut seen_roles = HashSet::new(); - for value in values { - let role = match value { - syn::Expr::Path(path) if path.path.segments.len() == 1 => LitStr::new( - &path.path.segments[0].ident.to_string(), - path.path.segments[0].ident.span(), - ), - syn::Expr::Lit(syn::ExprLit { - lit: syn::Lit::Str(value), - .. - }) => value, - other => { - return Err(syn::Error::new_spanned( - other, - "command roles must be identifiers or string literals", - )) - } - }; - if role.value().trim().is_empty() { + "name" => name = Some(input.parse()?), + "transition" => transition = Some(input.parse()?), + "aggregate" => aggregate = Some(input.parse()?), + "input" => input_ty = Some(input.parse()?), + "outcome" => outcome = Some(input.parse()?), + "shard" => shard = Some(input.parse()?), + "field" => field = Some(input.parse()?), + "invoke" => invoke = Some(input.parse()?), + "payload" => payload = Some(input.parse()?), + "handle" => handle = Some(input.parse()?), + "guard" => guard = Some(input.parse()?), + "defaults" => defaults = Some(input.parse()?), + "constructor" => constructor = Some(input.parse()?), + "authenticated_user_field" => authenticated_user_field = Some(input.parse()?), + "preview_reduce_known_record" => preview_reduce_known_record = Some(input.parse()?), + "load" => { + let ident: Ident = input.parse()?; + load = match ident.to_string().as_str() { + "required" => LoadKind::Required, + "or_create" => LoadKind::OrCreate, + "create" => LoadKind::Create, + other => { return Err(syn::Error::new( - role.span(), - "command roles must not be empty", - )); - } - if !seen_roles.insert(role.value()) { - return Err(syn::Error::new( - role.span(), - "command roles must not contain duplicates", - )); - } - roles.push(role); - } - if roles.is_empty() { - return Err(content.error( - "command roles must declare at least one role; use an explicit anonymous role when intended", - )); - } - args.roles = Some(roles); - } - "emits" => { - let content; - syn::parenthesized!(content in input); - args.emits = Punctuated::::parse_terminated(&content)? - .into_iter() - .collect(); - } - "applies" => { - let content; - syn::parenthesized!(content in input); - args.applies = Some(content.parse()?); - } - "defaults" | "input_defaults" => { - input.parse::()?; - args.defaults = Some(input.parse()?); - } - "default" => { - let content; - syn::parenthesized!(content in input); - let target: Ident = content.parse()?; - content.parse::()?; - let generator: Ident = content.parse()?; - if !content.is_empty() { - let arguments; - syn::parenthesized!(arguments in content); - if !arguments.is_empty() { - return Err( - arguments.error("input-default generators take no arguments") - ); + ident.span(), + format!( + "load must be `required`, `or_create` or `create`, not `{other}`" + ), + )) } - } - if !matches!(generator.to_string().as_str(), "uuid_v7" | "ulid") { - return Err(syn::Error::new( - generator.span(), - "unknown input-default generator; expected uuid_v7() or ulid()", - )); - } - args.generated_defaults.push((target, generator)); - } - "id" | "field" | "field_name" => { - input.parse::()?; - let value: LitStr = input.parse()?; - if key == "id" { - args.id = Some(value); - } else { - args.field_name = Some(value); - } + }; } - "input" | "outcome" => { - input.parse::()?; - let value: Type = input.parse()?; - if key == "input" { - args.input = Some(value); - } else { - args.outcome = Some(value); - } + "roles" => { + let expr: Expr = input.parse()?; + roles = crate::aggregate_command::role_list(&expr)?; } other => { return Err(syn::Error::new( key.span(), - format!("unknown command option `{other}`"), + format!("unknown command key `{other}`"), )) } } @@ -144,434 +128,189 @@ impl Parse for CommandArgs { input.parse::()?; } } - Ok(args) + + let name = name.ok_or_else(|| input.error("command requires `name: \"...\"`"))?; + Ok(Self { + name, + transition: transition.ok_or_else(|| input.error("command requires `transition:`"))?, + aggregate: aggregate.ok_or_else(|| input.error("command requires `aggregate:`"))?, + input: input_ty.ok_or_else(|| input.error("command requires `input:`"))?, + outcome: outcome.ok_or_else(|| input.error("command requires `outcome:`"))?, + shard: shard.ok_or_else(|| input.error("command requires `shard:`"))?, + field: field.ok_or_else(|| input.error("command requires `field:`"))?, + roles, + load, + invoke, + payload, + handle, + guard, + defaults, + constructor, + authenticated_user_field, + preview_reduce_known_record, + }) } } -fn validate_command_id(id: &LitStr) -> syn::Result<()> { - let value = id.value(); - let segments = value.split('.').collect::>(); - if value.len() > 128 - || segments.len() < 2 - || segments.iter().any(|segment| { - segment.is_empty() - || !segment.bytes().all(|byte| { - byte.is_ascii_lowercase() - || byte.is_ascii_digit() - || byte == b'_' - || byte == b'-' - }) +fn names_from_command(name: &LitStr) -> syn::Result<(Ident, Ident)> { + crate::aggregate_command::validate_name(name)?; + let value = name.value(); + let last = value.rsplit('.').next().unwrap_or(value.as_str()); + let pascal = last + .split('_') + .map(|part| { + let mut chars = part.chars(); + match chars.next() { + None => String::new(), + Some(first) => first.to_uppercase().collect::() + chars.as_str(), + } }) - { - return Err(syn::Error::new( - id.span(), - "command id must be 2+ dot-separated lowercase ASCII identifier segments", - )); - } - Ok(()) + .collect::(); + Ok((format_ident!("{pascal}"), Ident::new(last, name.span()))) } -pub fn expand( - attr: proc_macro2::TokenStream, - item: proc_macro2::TokenStream, -) -> syn::Result { +pub fn expand(input: TokenStream) -> syn::Result { let framework = crate::shared::framework_path()?; - let args = syn::parse2::(attr)?; - let function = syn::parse2::(item)?; - let id = args.id.ok_or_else(|| { - syn::Error::new( - function.sig.ident.span(), - "command declaration requires `id = \"...\"`", - ) - })?; - validate_command_id(&id)?; - let roles = args.roles.ok_or_else(|| { - syn::Error::new( - function.sig.ident.span(), - "command declaration requires explicit roles(...)", - ) - })?; - if !function.sig.asyncness.is_some() { - return Err(syn::Error::new_spanned( - &function.sig.fn_token, - "typed command handlers must be async", - )); - } - let typed_args = function - .sig - .inputs - .iter() - .filter_map(|argument| match argument { - FnArg::Typed(argument) => Some(argument), - FnArg::Receiver(_) => None, - }) - .collect::>(); - if function - .sig - .inputs - .iter() - .any(|argument| matches!(argument, FnArg::Receiver(_))) - || typed_args.len() != 2 - { - return Err(syn::Error::new_spanned( - &function.sig.inputs, - "typed command handler must have exactly `(context: &CausalCommandContext<'_, Aggregate>, input: Input)` parameters", - )); - } - let context_ty = &typed_args[0].ty; - if !is_causal_context_type(context_ty) { - return Err(syn::Error::new_spanned( - &typed_args[0].ty, - "first typed command parameter must be `&CausalCommandContext<'_, Aggregate>`", - )); - } - let aggregate = causal_context_aggregate_type(context_ty).ok_or_else(|| { - syn::Error::new_spanned( - context_ty, - "first typed command parameter must name the aggregate in `CausalCommandContext`", - ) - })?; - let inferred_input = (*typed_args[1].ty).clone(); - let declared_input = args.input.clone(); - let input = args.input.unwrap_or(inferred_input); - let outcome = args - .outcome - .or_else(|| infer_prepared_outcome(&function.sig.output)) - .ok_or_else(|| { - syn::Error::new_spanned( - &function.sig.output, - "command outcome is not inferable; provide `outcome = PreparedCommand`", + let args = syn::parse2::(input)?; + let (ty, default_ctor) = names_from_command(&args.name)?; + let ctor = args.constructor.as_ref().unwrap_or(&default_ctor); + let name = &args.name; + let transition = &args.transition; + let aggregate = &args.aggregate; + let input_ty = &args.input; + let outcome = &args.outcome; + let shard = &args.shard; + let field = &args.field; + let roles = &args.roles; + let defaults = args.defaults.as_ref().map(|defaults| { + quote! { .input_defaults(#defaults) } + }); + let authenticated_user_field = args.authenticated_user_field.as_ref().map(|value| { + let event = &value.event; + let body = &value.body; + let field = &value.field; + quote! { .authenticated_user_field::<#event, #body>(#field) } + }); + let preview_reduce_known_record = args.preview_reduce_known_record.as_ref().map(|preview| { + quote! { + .preview_reduce_known_record( + (#preview).declared_in_rust_package(env!("CARGO_PKG_NAME")) ) - })?; - validate_prepared_return(&function.sig.output, &outcome)?; - if let Some(input) = declared_input.as_ref() { - if !same_type(input, &typed_args[1].ty) { - return Err(syn::Error::new_spanned( - &typed_args[1].ty, - "handler input parameter does not match the declared `input = ...` type", - )); } - } - let field_name = args.field_name.unwrap_or_else(|| { - LitStr::new( - &id.value() - .chars() - .map(|character| { - if matches!(character, '.' | '-') { - '_' - } else { - character - } - }) - .collect::(), - id.span(), - ) }); - let function_name = &function.sig.ident; - let command_name = format_ident!("{}_command", function_name); - let spec_name = format_ident!("{}_spec", function_name); - let command_static = format_ident!("{}_COMMAND", function_name.to_string().to_uppercase()); - let spec_static = format_ident!("{}_SPEC", function_name.to_string().to_uppercase()); - let mount_name = format_ident!("{}_mount", function_name); - let mount_static = format_ident!("{}_MOUNT", function_name.to_string().to_uppercase()); - let definition_name = format_ident!("{}_definition", function_name); - let definition_static = - format_ident!("{}_DEFINITION", function_name.to_string().to_uppercase()); - let command_id_static = - format_ident!("{}_COMMAND_ID", function_name.to_string().to_uppercase()); - let accessor_name = format_ident!("{}_application_command", function_name); - let register_name = format_ident!("{}_register", function_name); - let visibility = &function.vis; - let emits = args.emits; - let applies = args.applies; - let defaults = args.defaults; - let generated_defaults = args.generated_defaults; - let mut builder = quote! { - #framework::graphql::typed_command::<#input, #outcome>(#id) - .field_name(#field_name) - }; - builder.extend(quote! { .roles([#(#roles),*]) }); - if !emits.is_empty() { - builder.extend(quote! { .emits(#framework::events!(#(#emits),*)) }); - } - if let Some(applies) = applies { - builder.extend(quote! { .applies(#applies) }); - } - if let Some(defaults) = defaults { - builder.extend(quote! { .input_defaults(#defaults) }); - } else if !generated_defaults.is_empty() { - let defaults = generated_defaults.iter().map(|(field, generator)| { - quote! { default input.#field = #generator(); } - }); - builder.extend(quote! { - .input_defaults(#framework::command_input_defaults! { - input: #input; - #(#defaults)* - }) - }); - } - Ok(quote! { - #[allow(unexpected_cfgs)] - #[cfg(feature = "application-runtime")] - #function - #visibility fn #command_name() -> #framework::graphql::TypedCommand<#input, #outcome> { - #builder + let install_body = if let Some(handle) = &args.handle { + if args.invoke.is_some() || args.payload.is_some() { + return Err(syn::Error::new_spanned( + handle, + "handle: is the escape hatch; do not also set invoke:/payload:", + )); } - - #visibility static #command_static: ::std::sync::LazyLock< - #framework::graphql::TypedCommand<#input, #outcome> - > = ::std::sync::LazyLock::new(#command_name); - - #visibility fn #spec_name() -> #framework::application::ApplicationResult< - #framework::application::CommandSpec - > { - (#command_static).spec() + let finish = match &args.guard { + Some(guard) => quote! { .guarded(#guard, #handle) }, + None => quote! { .handle(#handle) }, + }; + quote! { + routes + .command_transition::<#transition, #input_ty, #outcome>(Self::COMMAND) + .field_name(#field) + .roles([#(#roles),*].into_iter()) + #defaults + #authenticated_user_field + #preview_reduce_known_record + #finish + } + } else { + let invoke = args.invoke.as_ref().ok_or_else(|| { + syn::Error::new( + proc_macro2::Span::call_site(), + "thin command requires `invoke:` (or `handle:` as the escape hatch)", + ) + })?; + let payload = args.payload.as_ref().ok_or_else(|| { + syn::Error::new( + proc_macro2::Span::call_site(), + "thin command requires `payload:` (or `handle:` as the escape hatch)", + ) + })?; + let guard = args.guard.as_ref().map(|guard| quote! { .guard(#guard) }); + let load = + match args.load { + LoadKind::Required => quote! { .load_by(|input: &#input_ty| Self::shard(input)) }, + LoadKind::OrCreate => { + quote! { .load_or_create_by(|input: &#input_ty| Self::shard(input)) } + } + LoadKind::Create => quote! { .create_by(|input: &#input_ty| Self::shard(input)) }, + LoadKind::None => return Err(syn::Error::new( + proc_macro2::Span::call_site(), + "thin command requires `load: required`, `load: or_create` or `load: create`", + )), + }; + let finish = thin_finish(outcome, payload)?; + quote! { + routes + .command_transition::<#transition, #input_ty, #outcome>(Self::COMMAND) + .field_name(#field) + .roles([#(#roles),*].into_iter()) + #defaults + #authenticated_user_field + #preview_reduce_known_record + #load + #guard + .invoke(#invoke) + #finish } + }; - #visibility static #spec_static: ::std::sync::LazyLock< - #framework::application::CommandSpec - > = ::std::sync::LazyLock::new(|| - #spec_name().unwrap_or_else(|error| panic!("invalid generated command spec: {error}")) - ); + Ok(quote! { + pub struct #ty; - #visibility fn #accessor_name() -> &'static #framework::application::CommandSpec { - &#spec_static + pub fn #ctor() -> #ty { + #ty } - #visibility const #command_id_static: &str = #id; + impl #ty { + pub const COMMAND: &'static str = #name; - #[allow(unexpected_cfgs)] - #[cfg(feature = "application-runtime")] - #visibility fn #mount_name() -> #framework::application::CommandMount { - #framework::application::CommandMount::from_typed_route( - (#spec_static).clone(), - #id, - ) + pub fn shard(input: &#input_ty) -> String { + let shard: fn(&#input_ty) -> String = #shard; + shard(input) + } } - #[allow(unexpected_cfgs)] - #[cfg(feature = "application-runtime")] - #visibility static #mount_static: ::std::sync::LazyLock< - #framework::application::CommandMount - > = ::std::sync::LazyLock::new(#mount_name); - - #[allow(unexpected_cfgs)] - #[cfg(feature = "application-runtime")] - #visibility fn #register_name( - routes: #framework::microsvc::Routes, - ) -> #framework::microsvc::Routes + impl #framework::microsvc::PortableCommand for #ty where D: #framework::microsvc::CausalRouteDependencies + Send + Sync + 'static, - #aggregate: #framework::Aggregate + Send + Sync + 'static, - #input: #framework::__private::serde::de::DeserializeOwned + Send + 'static, - #outcome: #framework::graphql::CommandOutcome, { - routes - .typed_command((#command_static).clone()) - .mount((#mount_static).clone()) - .handle(#function_name) - } - - #[allow(unexpected_cfgs)] - #[cfg(feature = "application-runtime")] - #visibility fn #definition_name() -> #framework::application::CommandDefinition { - #framework::application::CommandDefinition::from_typed_command( - (#command_static).clone(), - Some((#mount_static).clone()), - ) - .unwrap_or_else(|error| panic!("invalid generated command definition: {error}")) - } - - #[allow(unexpected_cfgs)] - #[cfg(not(feature = "application-runtime"))] - #visibility fn #definition_name() -> #framework::application::CommandDefinition { - #framework::application::CommandDefinition::from_typed_command( - (#command_static).clone(), - None, - ) - .unwrap_or_else(|error| panic!("invalid generated command definition: {error}")) + fn install(self, routes: #framework::microsvc::Routes) -> #framework::microsvc::Routes { + #install_body + } } - - #visibility static #definition_static: ::std::sync::LazyLock< - #framework::application::CommandDefinition - > = ::std::sync::LazyLock::new(#definition_name); - }) -} - -fn is_causal_context_type(ty: &Type) -> bool { - let Type::Reference(reference) = ty else { - return false; - }; - let Type::Path(path) = reference.elem.as_ref() else { - return false; - }; - path.path - .segments - .last() - .is_some_and(|segment| segment.ident == "CausalCommandContext") -} - -fn causal_context_aggregate_type(ty: &Type) -> Option { - let Type::Reference(reference) = ty else { - return None; - }; - let Type::Path(path) = reference.elem.as_ref() else { - return None; - }; - let segment = path.path.segments.last()?; - if segment.ident != "CausalCommandContext" { - return None; - } - let PathArguments::AngleBracketed(arguments) = &segment.arguments else { - return None; - }; - arguments.args.iter().find_map(|argument| match argument { - syn::GenericArgument::Type(ty) => Some(ty.clone()), - _ => None, }) } -fn validate_prepared_return(output: &ReturnType, outcome: &Type) -> syn::Result<()> { - let Some((_, output)) = (match output { - ReturnType::Type(arrow, output) => Some((arrow, output.as_ref())), - ReturnType::Default => None, - }) else { - return Err(syn::Error::new_spanned( - output, - "typed command handler must return `Result, HandlerError>`", - )); - }; - let Type::Path(result) = output else { - return Err(syn::Error::new_spanned( - output, - "typed command handler must return `Result, HandlerError>`", - )); - }; - let Some(result_segment) = result.path.segments.last() else { - return Err(syn::Error::new_spanned( - output, - "missing Result return type", - )); - }; - if result_segment.ident != "Result" { - return Err(syn::Error::new_spanned( - output, - "typed command handler return type must be Result, HandlerError>", - )); - } - let PathArguments::AngleBracketed(arguments) = &result_segment.arguments else { - return Err(syn::Error::new_spanned( - output, - "typed command handler Result must declare PreparedCommand and HandlerError types", - )); - }; - let mut types = arguments.args.iter().filter_map(|argument| match argument { - syn::GenericArgument::Type(ty) => Some(ty), +fn thin_finish(outcome: &Type, payload: &Expr) -> syn::Result { + let last = match outcome { + Type::Path(path) => path + .path + .segments + .last() + .map(|segment| segment.ident.to_string()), _ => None, - }); - let Some(prepared) = types.next() else { - return Err(syn::Error::new_spanned( - output, - "missing PreparedCommand return type", - )); - }; - let Some(error) = types.next() else { - return Err(syn::Error::new_spanned( - output, - "missing HandlerError return type", - )); - }; - let Type::Path(prepared) = prepared else { - return Err(syn::Error::new_spanned( - prepared, - "first Result type must be PreparedCommand", - )); - }; - let Some(prepared_segment) = prepared.path.segments.last() else { - return Err(syn::Error::new_spanned( - prepared, - "missing PreparedCommand type", - )); - }; - if prepared_segment.ident != "PreparedCommand" { - return Err(syn::Error::new_spanned( - prepared, - "first Result type must be PreparedCommand", - )); - } - let PathArguments::AngleBracketed(prepared_args) = &prepared_segment.arguments else { - return Err(syn::Error::new_spanned( - prepared, - "PreparedCommand must declare its outcome type", - )); - }; - let Some(syn::GenericArgument::Type(actual_outcome)) = prepared_args.args.first() else { - return Err(syn::Error::new_spanned( - prepared, - "PreparedCommand must declare its outcome type", - )); - }; - if !same_type(actual_outcome, outcome) { - return Err(syn::Error::new_spanned( - actual_outcome, - "PreparedCommand outcome does not match the declared `outcome = ...` type", - )); - } - let Type::Path(error) = error else { - return Err(syn::Error::new_spanned( - error, - "second Result type must be HandlerError", - )); }; - if error - .path - .segments - .last() - .is_none_or(|segment| segment.ident != "HandlerError") - { - return Err(syn::Error::new_spanned( - error, - "second Result type must be HandlerError", - )); - } - Ok(()) -} - -fn same_type(left: &Type, right: &Type) -> bool { - quote!(#left).to_string().replace(' ', "") == quote!(#right).to_string().replace(' ', "") -} - -fn infer_prepared_outcome(output: &ReturnType) -> Option { - let ReturnType::Type(_, output) = output else { - return None; - }; - let Type::Path(path) = output.as_ref() else { - return None; - }; - let result = path.path.segments.last()?; - if result.ident != "Result" { - return None; - } - let PathArguments::AngleBracketed(arguments) = &result.arguments else { - return None; - }; - let first = arguments.args.first()?; - let syn::GenericArgument::Type(Type::Path(prepared)) = first else { - return None; - }; - let prepared = prepared.path.segments.last()?; - if prepared.ident != "PreparedCommand" { - return None; - } - let PathArguments::AngleBracketed(arguments) = &prepared.arguments else { - return None; - }; - match arguments.args.first()? { - syn::GenericArgument::Type(output) => Some(output.clone()), - _ => None, + match last.as_deref() { + Some("Eventual") => Ok(quote! { .eventual(#payload) }), + Some("Succeeded") => Ok(quote! { .succeeded(#payload) }), + Some("Atomic") => Err(syn::Error::new_spanned( + outcome, + "thin command does not yet support Atomic; use handle:", + )), + _ => Err(syn::Error::new_spanned( + outcome, + "thin command outcome must be Eventual<...> or Succeeded<...>", + )), } } diff --git a/distributed_macros/src/command_input_defaults.rs b/distributed_macros/src/command_input_defaults.rs index 24bebfd50..8f5ea5f81 100644 --- a/distributed_macros/src/command_input_defaults.rs +++ b/distributed_macros/src/command_input_defaults.rs @@ -65,7 +65,7 @@ impl CommandInputDefaults { .into_iter() .map(|default| default.expand(&input, &framework)); quote! { - #framework::graphql::__command_input_defaults::<#input>( + #framework::command::__command_input_defaults::<#input>( vec![#(#defaults),*] ) } @@ -123,10 +123,10 @@ impl InputDefault { let marker = marker_path(input, marker_name); match self.generator { InputDefaultGenerator::UuidV7 => quote! { - #framework::graphql::__input_default_uuid_v7::<#input, #marker>() + #framework::command::__input_default_uuid_v7::<#input, #marker>() }, InputDefaultGenerator::Ulid => quote! { - #framework::graphql::__input_default_ulid::<#input, #marker>() + #framework::command::__input_default_ulid::<#input, #marker>() }, } } diff --git a/distributed_macros/src/command_types.rs b/distributed_macros/src/command_types.rs new file mode 100644 index 000000000..39d0a83f4 --- /dev/null +++ b/distributed_macros/src/command_types.rs @@ -0,0 +1,724 @@ +//! Transport-neutral command data-shape derives. + +use proc_macro2::TokenStream; +use quote::{format_ident, quote}; +use syn::{ + punctuated::Punctuated, Attribute, Data, DeriveInput, Expr, Fields, GenericArgument, Lit, + LitStr, Meta, PathArguments, Token, Type, +}; + +#[derive(Clone, Copy)] +enum SerdeDirection { + Deserialize, + Serialize, +} + +impl SerdeDirection { + fn attribute_name(self) -> &'static str { + match self { + Self::Deserialize => "deserialize", + Self::Serialize => "serialize", + } + } + + fn derive_name(self) -> &'static str { + match self { + Self::Deserialize => "CommandInput", + Self::Serialize => "CommandOutput", + } + } +} + +#[derive(Clone, Copy)] +#[expect( + clippy::enum_variant_names, + reason = "variant names intentionally mirror serde's public rename_all terminology" +)] +enum RenameRule { + LowerCase, + UpperCase, + PascalCase, + CamelCase, + SnakeCase, + ScreamingSnakeCase, + KebabCase, + ScreamingKebabCase, +} + +impl RenameRule { + fn parse(value: &LitStr) -> syn::Result { + match value.value().as_str() { + "lowercase" => Ok(Self::LowerCase), + "UPPERCASE" => Ok(Self::UpperCase), + "PascalCase" => Ok(Self::PascalCase), + "camelCase" => Ok(Self::CamelCase), + "snake_case" => Ok(Self::SnakeCase), + "SCREAMING_SNAKE_CASE" => Ok(Self::ScreamingSnakeCase), + "kebab-case" => Ok(Self::KebabCase), + "SCREAMING-KEBAB-CASE" => Ok(Self::ScreamingKebabCase), + other => Err(syn::Error::new_spanned( + value, + format!( + "unsupported serde rename_all rule `{other}` for CommandInput/CommandOutput" + ), + )), + } + } + + fn apply(self, field: &str) -> String { + match self { + Self::KebabCase => field.replace('_', "-"), + Self::ScreamingKebabCase => field.replace('_', "-").to_ascii_uppercase(), + Self::LowerCase | Self::SnakeCase => field.to_string(), + Self::UpperCase | Self::ScreamingSnakeCase => field.to_ascii_uppercase(), + Self::PascalCase => { + let mut renamed = String::new(); + let mut capitalize = true; + for ch in field.chars() { + if ch == '_' { + capitalize = true; + } else if capitalize { + renamed.push(ch.to_ascii_uppercase()); + capitalize = false; + } else { + renamed.push(ch); + } + } + renamed + } + Self::CamelCase => { + let pascal = Self::PascalCase.apply(field); + let mut chars = pascal.chars(); + chars + .next() + .map(|first| first.to_ascii_lowercase().to_string() + chars.as_str()) + .unwrap_or_default() + } + } + } +} + +pub fn expand_command_input(input: DeriveInput) -> syn::Result { + let framework = crate::shared::framework_path()?; + expand( + input, + quote! { #framework::command::CommandInputType }, + quote! { #framework::command::CommandInputType }, + framework, + SerdeDirection::Deserialize, + ) +} + +pub fn expand_command_output(input: DeriveInput) -> syn::Result { + let framework = crate::shared::framework_path()?; + expand( + input, + quote! { #framework::command::CommandOutputType }, + quote! { #framework::command::CommandOutputType }, + framework, + SerdeDirection::Serialize, + ) +} + +fn expand( + input: DeriveInput, + trait_path: TokenStream, + nested_trait: TokenStream, + framework: TokenStream, + serde_direction: SerdeDirection, +) -> syn::Result { + let method = quote! { command_type }; + let type_def = quote! { #framework::command::CommandTypeDef }; + let type_field = quote! { #framework::command::CommandTypeField }; + let name = &input.ident; + let visibility = &input.vis; + validate_serde_container_shape(&input.attrs, serde_direction)?; + let rename_all = serde_rename_all(&input.attrs, serde_direction)?; + let Data::Struct(data) = &input.data else { + return Err(syn::Error::new_spanned( + &input, + "CommandInput/CommandOutput only support structs with named fields", + )); + }; + let Fields::Named(fields) = &data.fields else { + return Err(syn::Error::new_spanned( + &input, + "CommandInput/CommandOutput require named fields", + )); + }; + + let mut field_tokens = Vec::new(); + let mut effect_input_markers = Vec::new(); + let mut field_names: Vec = Vec::new(); + for field in &fields.named { + validate_serde_field_shape(&field.attrs, serde_direction)?; + let field_name = field + .ident + .as_ref() + .ok_or_else(|| syn::Error::new_spanned(field, "field must be named"))?; + let rust_field_name = field_name.to_string(); + let rust_field_name = rust_field_name + .strip_prefix("r#") + .unwrap_or(&rust_field_name); + let field_name_str = + serde_field_rename(&field.attrs, serde_direction)?.unwrap_or_else(|| { + rename_all + .map(|rule| rule.apply(rust_field_name)) + .unwrap_or_else(|| rust_field_name.to_string()) + }); + for name in [rust_field_name.to_string(), field_name_str.clone()] { + if !field_names.contains(&name) { + field_names.push(name); + } + } + let (type_name, nullable, list, item_nullable, nested) = + map_type(&field.ty, field, &nested_trait, &method)?; + let unsigned_integer = unsigned_integer_tokens(&field.ty, &framework); + let effect_path_kind = if !list && nested.is_some() { + quote! { #framework::command::EffectInputObjectKind } + } else { + quote! { #framework::command::EffectInputTerminalKind } + }; + let effect_wire = effect_input_wire_tokens(&framework, &type_name, list, nested.is_some()); + let nested_tokens = match nested { + Some(tokens) => quote! { Some(::std::boxed::Box::new(#tokens)) }, + None => quote! { None }, + }; + field_tokens.push(quote! { + #type_field { + name: #field_name_str.to_string(), + type_name: #type_name.to_string(), + nullable: #nullable, + list: #list, + item_nullable: #item_nullable, + unsigned_integer: #unsigned_integer, + nested: #nested_tokens, + } + }); + if matches!(serde_direction, SerdeDirection::Deserialize) { + let marker = format_ident!("__Distributed{}EffectInputField_{}", name, field_name); + let field_ty = &field.ty; + let nested_ty = effect_nested_type(field_ty); + let non_null_ty = effect_non_null_type(field_ty); + let nullability = if extract_path_arg(field_ty, "Option").is_some() { + quote! { #framework::command::EffectNullable } + } else { + quote! { #framework::command::EffectRequired } + }; + effect_input_markers.push(quote! { + #[doc(hidden)] + #[allow(non_camel_case_types)] + #visibility struct #marker; + + impl #framework::command::EffectInputFieldMarker for #marker { + type Input = #name; + type Value = #field_ty; + type NonNullValue = #non_null_ty; + type Nullability = #nullability; + type PathKind = #effect_path_kind; + type Wire = #effect_wire; + type Nested = #nested_ty; + fn path() -> ::std::vec::Vec<&'static str> { + vec![#field_name_str] + } + } + }); + } + } + + let type_name_str = name.to_string(); + let field_names_const = matches!(serde_direction, SerdeDirection::Deserialize).then(|| { + quote! { const FIELD_NAMES: &'static [&'static str] = &[#(#field_names),*]; } + }); + Ok(quote! { + impl #trait_path for #name { + #field_names_const + + fn #method() -> #type_def { + #type_def::new( + #type_name_str, + vec![#(#field_tokens),*], + ).with_type_id(::std::any::TypeId::of::<#name>()) + } + } + + #(#effect_input_markers)* + }) +} + +fn effect_input_wire_tokens( + framework: &TokenStream, + type_name: &str, + list: bool, + nested: bool, +) -> proc_macro2::TokenStream { + if list { + return quote! { #framework::command::EffectWireList }; + } + if nested { + return quote! { #framework::command::EffectWireObject }; + } + match type_name { + "String" | "ID" => quote! { #framework::command::EffectWireString }, + "Boolean" => quote! { #framework::command::EffectWireBoolean }, + "BigInt" | "Int" => quote! { #framework::command::EffectWireBigInt }, + "Float" => quote! { #framework::command::EffectWireFloat }, + "JSON" => quote! { #framework::command::EffectWireJson }, + "Bytea" => quote! { #framework::command::EffectWireBytea }, + "Timestamptz" => quote! { #framework::command::EffectWireTimestamp }, + _ => quote! { #framework::command::EffectWireUnsupported }, + } +} + +fn effect_non_null_type(mut ty: &Type) -> &Type { + while let Some(inner) = extract_path_arg(ty, "Option") { + ty = inner; + } + ty +} + +fn effect_nested_type(mut ty: &Type) -> &Type { + while let Some(inner) = extract_path_arg(ty, "Option") { + ty = inner; + } + if let Some(inner) = extract_path_arg(ty, "Vec") { + ty = inner; + while let Some(inner) = extract_path_arg(ty, "Option") { + ty = inner; + } + } + ty +} + +fn map_type( + ty: &Type, + span: &syn::Field, + nested_trait: &TokenStream, + method: &TokenStream, +) -> syn::Result<(String, bool, bool, bool, Option)> { + let mut current = ty; + let mut nullable = false; + while let Some(inner) = extract_path_arg(current, "Option") { + nullable = true; + current = inner; + } + + let mut list = false; + let mut item_nullable = false; + if let Some(inner) = extract_path_arg(current, "Vec") { + list = true; + current = inner; + while let Some(inner) = extract_path_arg(current, "Option") { + item_nullable = true; + current = inner; + } + if extract_path_arg(current, "Vec").is_some() { + return Err(syn::Error::new_spanned( + ty, + "nested lists are not supported for CommandInput/CommandOutput fields", + )); + } + } + + let path = match current { + Type::Path(p) => p, + _ => { + return Err(syn::Error::new_spanned( + span, + "unsupported field type for CommandInput/CommandOutput", + )); + } + }; + let last = path + .path + .segments + .last() + .ok_or_else(|| syn::Error::new_spanned(span, "empty type path"))?; + let ident = last.ident.to_string(); + + let scalar = match ident.as_str() { + "String" | "str" => Some("String"), + "bool" => Some("Boolean"), + "i8" | "i16" | "i32" | "i64" | "u8" | "u16" | "u32" | "u64" | "isize" | "usize" => { + Some("BigInt") + } + "f32" | "f64" => Some("Float"), + "Value" => Some("JSON"), + _ => None, + }; + + if let Some(s) = scalar { + return Ok((s.to_string(), nullable, list, item_nullable, None)); + } + + let nested = quote! { <#current as #nested_trait>::#method() }; + Ok((ident, nullable, list, item_nullable, Some(nested))) +} + +fn unsigned_integer_tokens(ty: &Type, framework: &TokenStream) -> TokenStream { + let mut current = ty; + while let Some(inner) = + extract_path_arg(current, "Option").or_else(|| extract_path_arg(current, "Vec")) + { + current = inner; + } + let Type::Path(path) = current else { + return quote! { None }; + }; + match path + .path + .segments + .last() + .map(|segment| segment.ident.to_string()) + .as_deref() + { + Some("u8") => quote! { Some(#framework::command::CommandUnsignedInteger::U8) }, + Some("u16") => quote! { Some(#framework::command::CommandUnsignedInteger::U16) }, + Some("u32") => quote! { Some(#framework::command::CommandUnsignedInteger::U32) }, + Some("u64") => quote! { Some(#framework::command::CommandUnsignedInteger::U64) }, + Some("usize") => quote! { + Some(match usize::BITS { + 16 => #framework::command::CommandUnsignedInteger::U16, + 32 => #framework::command::CommandUnsignedInteger::U32, + _ => #framework::command::CommandUnsignedInteger::U64, + }) + }, + _ => quote! { None }, + } +} + +fn extract_path_arg<'a>(ty: &'a Type, wrapper: &str) -> Option<&'a Type> { + let Type::Path(path) = ty else { + return None; + }; + let seg = path.path.segments.last()?; + if seg.ident != wrapper { + return None; + } + let PathArguments::AngleBracketed(args) = &seg.arguments else { + return None; + }; + args.args.iter().find_map(|arg| match arg { + GenericArgument::Type(t) => Some(t), + _ => None, + }) +} + +fn serde_rename_all( + attrs: &[Attribute], + direction: SerdeDirection, +) -> syn::Result> { + let value = serde_name_value(attrs, "rename_all", direction)?; + value.as_ref().map(RenameRule::parse).transpose() +} + +fn validate_serde_field_shape(attrs: &[Attribute], direction: SerdeDirection) -> syn::Result<()> { + for attr in attrs.iter().filter(|attr| attr.path().is_ident("serde")) { + let metas = attr.parse_args_with(Punctuated::::parse_terminated)?; + for meta in metas { + let unsupported = match &meta { + Meta::Path(path) if path.is_ident("skip") => Some("skip"), + Meta::Path(path) + if path.is_ident("skip_deserializing") + && matches!(direction, SerdeDirection::Deserialize) => + { + Some("skip_deserializing") + } + Meta::Path(path) + if path.is_ident("skip_serializing") + && matches!(direction, SerdeDirection::Serialize) => + { + Some("skip_serializing") + } + Meta::NameValue(name_value) + if name_value.path.is_ident("skip_serializing_if") + && matches!(direction, SerdeDirection::Serialize) => + { + Some("skip_serializing_if") + } + Meta::Path(path) if path.is_ident("flatten") => Some("flatten"), + Meta::Path(path) + if path.is_ident("default") + && matches!(direction, SerdeDirection::Deserialize) => + { + Some("default") + } + Meta::NameValue(name_value) + if name_value.path.is_ident("default") + && matches!(direction, SerdeDirection::Deserialize) => + { + Some("default") + } + Meta::NameValue(name_value) if name_value.path.is_ident("with") => Some("with"), + Meta::NameValue(name_value) + if name_value.path.is_ident("deserialize_with") + && matches!(direction, SerdeDirection::Deserialize) => + { + Some("deserialize_with") + } + Meta::NameValue(name_value) + if name_value.path.is_ident("serialize_with") + && matches!(direction, SerdeDirection::Serialize) => + { + Some("serialize_with") + } + Meta::NameValue(name_value) + if name_value.path.is_ident("alias") + && matches!(direction, SerdeDirection::Deserialize) => + { + Some("alias") + } + _ => None, + }; + if let Some(attribute) = unsupported { + return Err(syn::Error::new_spanned( + meta, + format!( + "#[serde({attribute})] is not supported by {} because it changes the declared command field shape; define a separate wire type", + direction.derive_name(), + ), + )); + } + } + } + Ok(()) +} + +fn validate_serde_container_shape( + attrs: &[Attribute], + direction: SerdeDirection, +) -> syn::Result<()> { + for attr in attrs.iter().filter(|attr| attr.path().is_ident("serde")) { + let metas = attr.parse_args_with(Punctuated::::parse_terminated)?; + for meta in metas { + let unsupported = match &meta { + Meta::Path(path) if path.is_ident("transparent") => Some("transparent"), + Meta::Path(path) if path.is_ident("untagged") => Some("untagged"), + Meta::NameValue(name_value) + if name_value.path.is_ident("tag") || name_value.path.is_ident("content") => + { + Some(if name_value.path.is_ident("tag") { + "tag" + } else { + "content" + }) + } + Meta::Path(path) + if path.is_ident("default") + && matches!(direction, SerdeDirection::Deserialize) => + { + Some("default") + } + Meta::NameValue(name_value) + if name_value.path.is_ident("default") + && matches!(direction, SerdeDirection::Deserialize) => + { + Some("default") + } + Meta::NameValue(name_value) + if (name_value.path.is_ident("from") + || name_value.path.is_ident("try_from")) + && matches!(direction, SerdeDirection::Deserialize) => + { + Some(if name_value.path.is_ident("from") { + "from" + } else { + "try_from" + }) + } + Meta::NameValue(name_value) + if name_value.path.is_ident("into") + && matches!(direction, SerdeDirection::Serialize) => + { + Some("into") + } + _ => None, + }; + if let Some(attribute) = unsupported { + return Err(syn::Error::new_spanned( + meta, + format!( + "#[serde({attribute})] is not supported by {} because it changes the declared command object shape; define a separate wire type", + direction.derive_name(), + ), + )); + } + } + } + Ok(()) +} + +fn serde_field_rename( + attrs: &[Attribute], + direction: SerdeDirection, +) -> syn::Result> { + Ok(serde_name_value(attrs, "rename", direction)?.map(|value| value.value())) +} + +fn serde_name_value( + attrs: &[Attribute], + key: &str, + direction: SerdeDirection, +) -> syn::Result> { + let mut found = None; + for attr in attrs.iter().filter(|attr| attr.path().is_ident("serde")) { + let metas = attr.parse_args_with(Punctuated::::parse_terminated)?; + for meta in metas { + match meta { + Meta::NameValue(name_value) if name_value.path.is_ident(key) => { + set_serde_name(&mut found, string_literal(&name_value.value, key)?, key)?; + } + Meta::List(list) if list.path.is_ident(key) => { + let directional = + list.parse_args_with(Punctuated::::parse_terminated)?; + for meta in directional { + if let Meta::NameValue(name_value) = meta { + if name_value.path.is_ident(direction.attribute_name()) { + set_serde_name( + &mut found, + string_literal(&name_value.value, key)?, + key, + )?; + } + } + } + } + _ => {} + } + } + } + Ok(found) +} + +fn set_serde_name(found: &mut Option, value: LitStr, key: &str) -> syn::Result<()> { + if found.is_some() { + return Err(syn::Error::new_spanned( + value, + format!("duplicate serde `{key}` rule for CommandInput/CommandOutput"), + )); + } + *found = Some(value); + Ok(()) +} + +fn string_literal(value: &Expr, key: &str) -> syn::Result { + match value { + Expr::Lit(expr) => match &expr.lit { + Lit::Str(value) => Ok(value.clone()), + _ => Err(syn::Error::new_spanned( + value, + format!("serde `{key}` must be a string literal"), + )), + }, + _ => Err(syn::Error::new_spanned( + value, + format!("serde `{key}` must be a string literal"), + )), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rename_all_rules_match_serde_field_rules() { + let field = "long_field_name"; + let cases = [ + ("lowercase", "long_field_name"), + ("UPPERCASE", "LONG_FIELD_NAME"), + ("PascalCase", "LongFieldName"), + ("camelCase", "longFieldName"), + ("snake_case", "long_field_name"), + ("SCREAMING_SNAKE_CASE", "LONG_FIELD_NAME"), + ("kebab-case", "long-field-name"), + ("SCREAMING-KEBAB-CASE", "LONG-FIELD-NAME"), + ]; + for (rule, expected) in cases { + let literal = LitStr::new(rule, proc_macro2::Span::call_site()); + assert_eq!(RenameRule::parse(&literal).unwrap().apply(field), expected); + } + } + + #[test] + fn directional_serde_names_follow_wire_direction() { + let input: DeriveInput = syn::parse_quote! { + #[serde(rename_all(deserialize = "camelCase", serialize = "SCREAMING_SNAKE_CASE"))] + struct CommandInput { + regular_field: String, + #[serde(rename(deserialize = "inputID", serialize = "OUTPUT_ID"))] + custom_id: String, + } + }; + let input_tokens = expand_command_input(input).unwrap().to_string(); + assert!(input_tokens.contains("\"regularField\"")); + assert!(input_tokens.contains("\"inputID\"")); + + let output: DeriveInput = syn::parse_quote! { + #[serde(rename_all(deserialize = "camelCase", serialize = "SCREAMING_SNAKE_CASE"))] + struct CommandOutput { + regular_field: String, + #[serde(rename(deserialize = "inputID", serialize = "OUTPUT_ID"))] + custom_id: String, + } + }; + let output_tokens = expand_command_output(output).unwrap().to_string(); + assert!(output_tokens.contains("\"REGULAR_FIELD\"")); + assert!(output_tokens.contains("\"OUTPUT_ID\"")); + } + + #[test] + fn nested_lists_and_shape_changing_serde_attrs_fail_closed() { + let nested: DeriveInput = syn::parse_quote! { + struct Nested { values: Option>>> } + }; + let error = expand_command_input(nested).unwrap_err().to_string(); + assert!(error.contains("nested lists are not supported"), "{error}"); + + let skipped: DeriveInput = syn::parse_quote! { + struct Skipped { + #[serde(skip_deserializing)] + value: String, + } + }; + let error = expand_command_input(skipped).unwrap_err().to_string(); + assert!( + error.contains("changes the declared command field shape"), + "{error}" + ); + + let defaulted: DeriveInput = syn::parse_quote! { + struct Defaulted { + #[serde(default)] + value: String, + } + }; + let error = expand_command_input(defaulted).unwrap_err().to_string(); + assert!(error.contains("#[serde(default)]"), "{error}"); + + let custom: DeriveInput = syn::parse_quote! { + struct Custom { + #[serde(deserialize_with = "decode_value")] + value: String, + } + }; + let error = expand_command_input(custom).unwrap_err().to_string(); + assert!(error.contains("#[serde(deserialize_with)]"), "{error}"); + + let transparent: DeriveInput = syn::parse_quote! { + #[serde(transparent)] + struct Transparent { value: String } + }; + let error = expand_command_output(transparent).unwrap_err().to_string(); + assert!(error.contains("#[serde(transparent)]"), "{error}"); + + let container_default: DeriveInput = syn::parse_quote! { + #[serde(default = "default_input")] + struct ContainerDefault { value: String } + }; + let error = expand_command_input(container_default) + .unwrap_err() + .to_string(); + assert!(error.contains("#[serde(default)]"), "{error}"); + } +} diff --git a/distributed_macros/src/digest.rs b/distributed_macros/src/digest.rs deleted file mode 100644 index fa5378747..000000000 --- a/distributed_macros/src/digest.rs +++ /dev/null @@ -1,92 +0,0 @@ -use proc_macro2::TokenStream as TokenStream2; -use quote::{format_ident, quote}; -use syn::{parse::Parser, Expr, Ident, ItemFn, LitStr, Token}; - -use crate::shared::{ - ensure_sourced_result_signature, extract_params_with_types, generate_digest_call, - framework_path, wrap_result_body_with_guard, -}; - -pub(crate) fn expand_digest(attr: TokenStream2, item: TokenStream2) -> syn::Result { - let args = parse_digest_args.parse2(attr)?; - let mut func = syn::parse2::(item)?; - - let framework = framework_path()?; - let signature_synthesized = - ensure_sourced_result_signature(&mut func.sig, "digest", &framework)?; - - let params = extract_params_with_types(&func.sig, "digest")?; - let param_names: Vec<&Ident> = params.iter().map(|(name, _)| name).collect(); - let digest_call = generate_digest_call( - &args.entity_field, - &args.event_name, - ¶m_names, - args.version.as_ref(), - ); - - let new_body = wrap_result_body_with_guard( - args.guard.as_ref(), - digest_call, - &func.block, - signature_synthesized, - ); - *func.block = new_body; - - Ok(quote! { #func }) -} - -pub(crate) struct DigestArgs { - pub(crate) entity_field: syn::Ident, - event_name: LitStr, - pub(crate) guard: Option, - pub(crate) version: Option, -} - -pub(crate) fn parse_digest_args(input: syn::parse::ParseStream) -> syn::Result { - // Check if first token is an identifier (potential entity field) or a string literal (event name) - let (entity_field, event_name) = if input.peek(LitStr) { - // No entity field specified, use default "entity" - let event_name: LitStr = input.parse()?; - (format_ident!("entity"), event_name) - } else { - // First token is an identifier - could be entity field or event name follows - let first_ident: syn::Ident = input.parse()?; - input.parse::()?; - let event_name: LitStr = input.parse()?; - (first_ident, event_name) - }; - - let mut guard = None; - let mut version = None; - - // Parse optional keyword arguments: `when = condition`, `version = N` - while input.peek(Token![,]) { - input.parse::()?; - // Allow (and ignore) a trailing comma. - if input.is_empty() { - break; - } - let ident: syn::Ident = input.parse()?; - if ident == "when" { - input.parse::()?; - guard = Some(input.parse()?); - } else if ident == "version" { - input.parse::()?; - version = Some(input.parse()?); - } else { - return Err(syn::Error::new_spanned( - &ident, - format!( - "unsupported key `{ident}` in #[digest(...)]; expected `when` or `version`" - ), - )); - } - } - - Ok(DigestArgs { - entity_field, - event_name, - guard, - version, - }) -} diff --git a/distributed_macros/src/domain_event.rs b/distributed_macros/src/domain_event.rs index b03be56fa..cdc2cc56b 100644 --- a/distributed_macros/src/domain_event.rs +++ b/distributed_macros/src/domain_event.rs @@ -4,8 +4,8 @@ use quote::quote; use syn::{Data, DeriveInput, Fields, LitInt, LitStr}; use crate::shared::{ - canonical_object_schema, projection_body_metadata_tokens, schema_fingerprint, - validate_domain_event_name_literal, framework_path, + canonical_object_schema, framework_path, projection_body_metadata_tokens, schema_fingerprint, + validate_domain_event_name_literal, }; pub(crate) fn derive_domain_event(input: TokenStream) -> TokenStream { @@ -85,6 +85,15 @@ pub(crate) fn expand_domain_event(input: DeriveInput) -> syn::Result for #name {} + impl #framework::command::CommandProjectionBody for #name { + fn command_projection_descriptor( + _: &'static str, + _: u64, + ) -> #framework::DomainEventDescriptor { + ::DESCRIPTOR.clone() + } + } + impl #framework::projection::lower::ProjectionBodyMetadata for #name { #projection_metadata } diff --git a/distributed_macros/src/enqueue.rs b/distributed_macros/src/enqueue.rs deleted file mode 100644 index fad4b5eb9..000000000 --- a/distributed_macros/src/enqueue.rs +++ /dev/null @@ -1,117 +0,0 @@ -use proc_macro2::TokenStream as TokenStream2; -use quote::{format_ident, quote}; -use syn::{parse::Parser, Expr, Ident, ItemFn, LitStr, Token}; - -use crate::shared::{ - ensure_sourced_result_signature, extract_params_with_types, framework_path, - wrap_result_body_with_guard, -}; - -pub(crate) fn expand_enqueue(attr: TokenStream2, item: TokenStream2) -> syn::Result { - let args = parse_enqueue_args.parse2(attr)?; - let mut func = syn::parse2::(item)?; - - let framework = framework_path()?; - let signature_synthesized = - ensure_sourced_result_signature(&mut func.sig, "enqueue", &framework)?; - - let emitter_field = &args.emitter_field; - let event_name = &args.event_name; - - // Use function parameters - serialize as tuple to JSON - let params = extract_params_with_types(&func.sig, "enqueue")?; - let param_names: Vec<&Ident> = params.iter().map(|(name, _)| name).collect(); - - let entity_field = &args.entity_field; - - let enqueue_call = if param_names.is_empty() { - quote! { - if !self.#entity_field.is_replaying() { - self.#emitter_field.enqueue(#event_name, ""); - }; - } - } else if param_names.len() == 1 { - // Single-element tuple needs trailing comma: (x,) not (x) - let param = ¶m_names[0]; - quote! { - if !self.#entity_field.is_replaying() { - self.#emitter_field.enqueue_with(#event_name, &(#param.clone(),))?; - }; - } - } else { - // Multi-element tuple - quote! { - if !self.#entity_field.is_replaying() { - self.#emitter_field.enqueue_with(#event_name, &(#(#param_names.clone()),*))?; - }; - } - }; - - let new_body = wrap_result_body_with_guard( - args.guard.as_ref(), - enqueue_call, - &func.block, - signature_synthesized, - ); - *func.block = new_body; - - Ok(quote! { #func }) -} - -pub(crate) struct EnqueueArgs { - pub(crate) emitter_field: syn::Ident, - pub(crate) entity_field: syn::Ident, - event_name: LitStr, - guard: Option, -} - -pub(crate) fn parse_enqueue_args(input: syn::parse::ParseStream) -> syn::Result { - // Check if first token is an identifier (potential emitter field) or a string literal (event name) - let (emitter_field, event_name) = if input.peek(LitStr) { - // No emitter field specified, use default "emitter" - let event_name: LitStr = input.parse()?; - (format_ident!("emitter"), event_name) - } else { - // First token is an identifier - emitter field name, event name follows - let first_ident: syn::Ident = input.parse()?; - input.parse::()?; - let event_name: LitStr = input.parse()?; - (first_ident, event_name) - }; - - let mut guard = None; - // Defaults to the conventional `entity` field; overridable so a renamed - // entity field still produces a correct `is_replaying()` guard. - let mut entity_field = format_ident!("entity"); - - // Parse optional keyword arguments: `when = condition`, `entity = field` - while input.peek(Token![,]) { - input.parse::()?; - // Allow (and ignore) a trailing comma. - if input.is_empty() { - break; - } - let ident: syn::Ident = input.parse()?; - if ident == "when" { - input.parse::()?; - guard = Some(input.parse()?); - } else if ident == "entity" { - input.parse::()?; - entity_field = input.parse()?; - } else { - return Err(syn::Error::new_spanned( - &ident, - format!( - "unsupported key `{ident}` in #[enqueue(...)]; expected `when` or `entity`" - ), - )); - } - } - - Ok(EnqueueArgs { - emitter_field, - entity_field, - event_name, - guard, - }) -} diff --git a/distributed_macros/src/entry_tests.rs b/distributed_macros/src/entry_tests.rs index db362a09b..442d3a55b 100644 --- a/distributed_macros/src/entry_tests.rs +++ b/distributed_macros/src/entry_tests.rs @@ -1,90 +1,13 @@ #[cfg(test)] mod tests { - use crate::{aggregate, digest, enqueue, sourced}; + use crate::{aggregate, sourced}; use quote::quote; use syn::parse::Parser; // ---- digest ---------------------------------------------------------- - #[test] - fn expand_digest_inserts_digest_call() { - let attr = quote! { "initialized" }; - let item = quote! { - fn initialize(&mut self, id: String) { - self.id = id; - } - }; - let out = digest::expand_digest(attr, item).unwrap().to_string(); - assert!(out.contains("digest"), "unexpected output: {out}"); - assert!(out.contains("\"initialized\""), "unexpected output: {out}"); - } - - #[test] - fn parse_digest_args_rejects_unknown_key() { - let attr = quote! { "x", versoin = 2 }; - let err = digest::parse_digest_args - .parse2(attr) - .err() - .expect("unknown key should error"); - let msg = err.to_string(); - assert!(msg.contains("unsupported key `versoin`"), "got: {msg}"); - assert!(msg.contains("version"), "got: {msg}"); - } - - #[test] - fn parse_digest_args_accepts_version_and_when() { - let attr = quote! { entity, "renamed", when = true, version = 2 }; - let args = digest::parse_digest_args.parse2(attr).unwrap(); - assert_eq!(args.entity_field, "entity"); - assert!(args.guard.is_some()); - assert!(args.version.is_some()); - } - // ---- enqueue --------------------------------------------------------- - #[test] - fn parse_enqueue_args_defaults_entity_field() { - let attr = quote! { "order.initialized" }; - let args = enqueue::parse_enqueue_args.parse2(attr).unwrap(); - assert_eq!(args.emitter_field, "emitter"); - assert_eq!(args.entity_field, "entity"); - } - - #[test] - fn parse_enqueue_args_overrides_entity_field() { - let attr = quote! { "order.initialized", entity = state }; - let args = enqueue::parse_enqueue_args.parse2(attr).unwrap(); - assert_eq!(args.entity_field, "state"); - } - - #[test] - fn expand_enqueue_uses_renamed_entity_field_in_guard() { - let attr = quote! { "order.initialized", entity = state }; - let item = quote! { - fn create(&mut self, id: String) { - self.id = id; - } - }; - let out = enqueue::expand_enqueue(attr, item).unwrap().to_string(); - assert!( - out.contains("self . state . is_replaying"), - "expected renamed entity guard, got: {out}" - ); - } - - #[test] - fn parse_enqueue_args_rejects_unknown_key() { - let attr = quote! { "x", wen = true }; - let err = enqueue::parse_enqueue_args - .parse2(attr) - .err() - .expect("unknown key should error"); - assert!( - err.to_string().contains("unsupported key `wen`"), - "got: {err}" - ); - } - // ---- event (parse) --------------------------------------------------- #[test] @@ -157,289 +80,25 @@ mod tests { } #[test] - fn expand_sourced_generates_enum_and_aggregate() { - let attr = quote! { entity }; - let item = quote! { - impl Todo { - #[event("initialized")] - pub fn initialize(&mut self, id: String) { - self.id = id; - } - } - }; - let out = sourced::expand_sourced(attr, item).unwrap().to_string(); - assert!(out.contains("enum TodoEvent"), "got: {out}"); - assert!( - out.contains("impl distributed :: Aggregate for Todo"), - "got: {out}" - ); - } - - #[test] - fn expand_sourced_places_state_capture_after_transition_body() { - let attr = quote! { - entity, - aggregate_type = "todo", - domain_state = TodoState, - }; - let item = quote! { - impl Todo { - #[event("todo.completed", version = 1, domain)] - pub fn complete(&mut self) { - self.completed = true; - } - } - }; - - let output = sourced::expand_sourced(attr, item).unwrap().to_string(); - let digest = output.find("digest_v").unwrap(); - let transition = output.find("self . completed = true").unwrap(); - let capture = output.find("capture_domain_state").unwrap(); - - assert!(digest < transition); - assert!(transition < capture); - assert!(output.contains("is_replaying")); - assert!(output.contains("pub enum TodoCompletedDomainEvent")); - assert!(output.contains( - "impl distributed :: domain_event :: DomainEventContract for TodoCompletedDomainEvent" - )); - assert!(output.contains("DomainEventBodyContract < TodoState >")); - } - - #[test] - fn expand_sourced_transition_exports_unconditional_known_state_values() { - let attr = quote! { - entity, - aggregate_type = "todo", - domain_state = TodoState, - }; - let item = quote! { - impl Todo { - pub fn complete(&mut self) { - self.record_completed().unwrap(); - } - - #[event("todo.completed", version = 1, domain)] - fn record_completed(&mut self) { - self.status = TodoStatus::Completed; - self.label = std::string::String::from("done"); - self.shadowed_label = String::from("not-known"); - self.assignee_id = None; - if self.audit_enabled { - self.audit_label = "conditional"; + fn known_values_need_a_domain_mode() { + let error = sourced::expand_sourced( + quote! { entity, aggregate_type = "todo", domain_state = TodoState }, + quote! { + impl Todo { + pub fn complete(&mut self) { + self.record_completed().unwrap(); } - } - } - }; - - let output = sourced::expand_sourced(attr, item).unwrap().to_string(); - - assert!( - output.contains("fn command_event_known_values"), - "got: {output}" - ); - assert!( - output.contains("__command_projection_state_known_values"), - "got: {output}" - ); - assert!(output.contains("\"status\""), "got: {output}"); - assert!(output.contains("TodoStatus :: Completed"), "got: {output}"); - assert!(output.contains("\"label\""), "got: {output}"); - assert!( - output.contains("std :: string :: String :: from (\"done\")"), - "got: {output}" - ); - assert!(!output.contains("\"shadowed_label\""), "got: {output}"); - assert!(output.contains("\"assignee_id\""), "got: {output}"); - assert!( - !output.contains("\"audit_label\""), - "conditional assignments are not safe preview facts: {output}" - ); - } - - #[test] - fn expand_sourced_identity_mode_generates_independent_public_descriptor() { - let attr = quote! { - entity, - aggregate_type = "todo", - }; - let item = quote! { - impl Todo { - #[event("todo.renamed", version = 2, domain = event)] - pub fn rename(&mut self, title: String) { - self.title = title; - } - } - }; - - let output = sourced::expand_sourced(attr, item).unwrap().to_string(); - - assert!(output.contains("pub struct TodoRenamedDomainEvent")); - assert!(output.contains( - "impl distributed :: domain_event :: DomainEventContract for TodoRenamedDomainEvent" - )); - assert!(output.contains("DomainEventBodyDescriptor :: distributed_json")); - assert!(output.contains("capture_domain_event")); - assert!(!output.contains("payload_bytes")); - } - - #[test] - fn expand_sourced_deletion_uses_aggregate_sequence_as_incarnation() { - let attr = quote! { - entity, - aggregate_type = "todo", - }; - let item = quote! { - impl Todo { - #[event("todo.purged", domain = deleted)] - pub fn purge(&mut self) { - self.purged = true; - } - } - }; - let output = sourced::expand_sourced(attr, item).unwrap().to_string(); - - assert!(output.contains("pub struct TodoDomainIdentity")); - assert!(output.contains("pub enum TodoPurgedDomainEvent")); - assert!(output.contains("DomainEventBodyContract < distributed :: DomainDeletion")); - assert!(output.contains("self . entity . version ()")); - assert!(output.contains("capture_domain_deletion")); - assert!(!output.contains("capture_domain_state")); - } - - #[test] - fn expand_sourced_custom_mode_type_checks_a_pure_function_pointer() { - let attr = quote! { - entity, - events = "TodoReplayEvent", - aggregate_type = "todo", - }; - let item = quote! { - impl Todo { - #[event( - "todo.completed", - domain = with(TodoCompleted, TodoCompleted::capture_after) - )] - pub fn complete(&mut self) { - self.completed = true; - } - } - }; - - let output = sourced::expand_sourced(attr, item).unwrap().to_string(); - - assert!(output.contains( - "fn (& Todo , & TodoReplayEvent) -> TodoCompleted = TodoCompleted :: capture_after" - )); - assert!(output.contains("if let Some")); - assert!(output.contains("capture_domain_event")); - assert!(output.contains("DomainEventContract > :: EVENT_NAME")); - assert!(output.contains("DomainEventContract > :: EVENT_VERSION")); - assert!(output.contains("DomainEventBodyContract < T >")); - assert!(output.contains("!= < TodoCompleted as distributed :: DomainEvent > :: DESCRIPTOR")); - } - - #[test] - fn expand_sourced_rejects_duplicate_event_names() { - let attr = quote! { entity }; - let item = quote! { - impl Todo { - #[event("done")] - pub fn complete(&mut self) {} - #[event("done")] - pub fn finish(&mut self) {} - } - }; - let err = sourced::expand_sourced(attr, item).expect_err("duplicate should error"); - assert!( - err.to_string().contains("duplicate #[event] name `done`"), - "got: {err}" - ); - } - - #[test] - fn expand_sourced_rejects_variant_ident_collisions() { - let attr = quote! { entity }; - let item = quote! { - impl Workflow { - #[event("user.completed")] - pub fn user_completed(&mut self) {} - #[event("admin.completed")] - pub fn admin_completed(&mut self) {} - } - }; - let err = sourced::expand_sourced(attr, item).expect_err("variant collision should error"); - let msg = err.to_string(); - assert!(msg.contains("`user.completed`"), "got: {msg}"); - assert!(msg.contains("`admin.completed`"), "got: {msg}"); - assert!(msg.contains("`Completed`"), "got: {msg}"); - } - - #[test] - fn expand_sourced_rejects_tuple_parameter_pattern() { - let attr = quote! { entity }; - let item = quote! { - impl Point { - #[event("moved")] - pub fn moved(&mut self, (x, y): (u8, u8)) { - self.x = x; - self.y = y; + #[event("todo.completed", version = 1, known(status: "completed"))] + fn record_completed(&mut self) { + self.status = TodoStatus::Completed; + } } - } - }; - let err = sourced::expand_sourced(attr, item).expect_err("tuple pattern should error"); - assert!( - err.to_string() - .contains("unsupported parameter pattern in #[event] method"), - "got: {err}" - ); - } - - #[test] - fn expand_digest_rejects_wildcard_parameter_pattern() { - let attr = quote! { "initialized" }; - let item = quote! { - fn initialize(&mut self, _: String) {} - }; - let err = digest::expand_digest(attr, item).expect_err("wildcard pattern should error"); - assert!( - err.to_string() - .contains("unsupported parameter pattern in #[digest] method"), - "got: {err}" - ); - } - - #[test] - fn expand_enqueue_rejects_struct_parameter_pattern() { - let attr = quote! { "order.initialized" }; - let item = quote! { - fn create(&mut self, Payload { id }: Payload) { - let _ = id; - } - }; - let err = enqueue::expand_enqueue(attr, item).expect_err("struct pattern should error"); - assert!( - err.to_string() - .contains("unsupported parameter pattern in #[enqueue] method"), - "got: {err}" - ); - } - - #[test] - fn expand_sourced_rejects_event_without_receiver() { - let attr = quote! { entity }; - let item = quote! { - impl Todo { - #[event("initialized")] - pub fn initialize(id: String) {} - } - }; - let err = sourced::expand_sourced(attr, item).expect_err("missing receiver should error"); - assert!( - err.to_string().contains("must take a `&mut self` receiver"), - "got: {err}" - ); + }, + ) + .unwrap_err() + .to_string(); + assert!(error.contains("needs one of those"), "{error}"); } // ---- upcasters ------------------------------------------------------- @@ -471,131 +130,56 @@ mod tests { assert_eq!(args.upcasters.len(), 1); } - #[test] - fn expand_aggregate_accepts_upcasters_block() { - let input = quote! { - Todo, entity { - "initialized"(id) => initialize, - } - upcasters [ - ("initialized", 1 => 2, OldPayload => NewPayload, upcast_fn), - ] - }; - let out = aggregate::expand_aggregate(input).unwrap().to_string(); - assert!(out.contains("upcasters"), "got: {out}"); - assert!(out.contains("upcast_fn"), "got: {out}"); - } - // ---- aggregate ------------------------------------------------------- - #[test] - fn expand_aggregate_generates_impl() { - let input = quote! { - Todo, entity { - "initialized"(id) => initialize, - } - }; - let out = aggregate::expand_aggregate(input).unwrap().to_string(); - assert!( - out.contains("impl distributed :: Aggregate for Todo"), - "got: {out}" - ); - assert!(out.contains("replay_event"), "got: {out}"); - } - - #[test] - fn expand_portable_command_emits_thin_mount() { - let input = quote! { - name: "todo.complete", - transition: domain_commands::Complete, + fn thin_command( + name: &str, + load: proc_macro2::TokenStream, + roles: proc_macro2::TokenStream, + ) -> syn::Result { + crate::command::expand(quote! { + name: #name, + transition: domain_commands::Create, aggregate: Todo, - input: TodoCompleteInput, - outcome: Eventual, + input: TodoCreateInput, + outcome: Eventual, shard: |input| input.todo_id.clone(), - load: required, - roles: ["user", "admin"], - field: "todos_complete", - invoke: |todo, _input, principal| todo.complete(principal), - payload: |todo| TodoStatusPayload::from_todo(&**todo), - }; - let out = crate::portable_command::expand(input) - .expect("expand") - .to_string(); - assert!(out.contains("struct Complete"), "{out}"); - assert!(out.contains("fn complete"), "{out}"); - assert!(out.contains("todo . complete"), "{out}"); - assert!(out.contains("load_by"), "{out}"); - assert!(out.contains("eventual"), "{out}"); - assert!(out.contains("PortableCommand"), "{out}"); - } - - #[test] - fn expand_portable_command_preserves_contract_projection_options() { - let input = quote! { - name: "chat.post", - transition: domain_commands::Post, - aggregate: ChatMessage, - input: ChatPostInput, - outcome: Eventual, - shard: |input| input.message_id.clone(), - roles: ["user", "admin"], - field: "chat_messages_post", - constructor: post_message, - authenticated_user_field: ( - ChatMessagePostedDomainEvent, - ChatMessageState, - "author_id" - ), - preview_reduce_known_record: blob_preview(), + load: #load, + roles: #roles, + field: "todos_create", guard: authenticated_user, - handle: handle_post, - }; - let out = crate::portable_command::expand(input) - .expect("expand") - .to_string(); - assert!(out.contains("authenticated_user_field"), "{out}"); - assert!(out.contains("fn post_message"), "{out}"); - assert!(out.contains("ChatMessagePostedDomainEvent"), "{out}"); - assert!(out.contains("ChatMessageState"), "{out}"); - assert!(out.contains("author_id"), "{out}"); - assert!(out.contains("preview_reduce_known_record"), "{out}"); - assert!(out.contains("blob_preview"), "{out}"); - assert!(out.contains("declared_in_rust_package"), "{out}"); - assert!(out.contains("CARGO_PKG_NAME"), "{out}"); + invoke: |todo, input, principal| todo.create(&input.todo_id, principal), + payload: |todo, principal| TodoCreatePayload::new(todo, principal), + }) + .map(|tokens| tokens.to_string()) } + /// The method form and `command!` reject the same names and roles. #[test] - fn expand_portable_command_allows_constructor_override_for_keyword_name() { - let input = quote! { - name: "blob.move", - transition: domain_commands::MoveDir, - aggregate: BlobGame, - input: BlobMoveInput, - outcome: Atomic, - shard: |input| input.game_id.clone(), - roles: ["user", "admin"], - field: "blob_games_move", - constructor: move_dir, - guard: authenticated_user, - handle: handle_move, - }; - let out = crate::portable_command::expand(input) - .expect("expand") - .to_string(); - assert!(out.contains("struct Move"), "{out}"); - assert!(out.contains("fn move_dir"), "{out}"); + fn expand_command_shares_name_and_role_rules_with_the_method_form() { + for name in ["create", "Todo.create", "todo..create", "todo.create-now"] { + let err = thin_command(name, quote!(create), quote!(["user"])).expect_err(name); + assert!( + err.to_string().contains("2+ dot-separated snake_case"), + "{name}: {err}" + ); + } + for roles in [quote!([]), quote!([""]), quote!([user])] { + let err = thin_command("todo.create", quote!(create), roles.clone()) + .expect_err("invalid roles"); + assert!(err.to_string().contains("roles"), "{roles}: {err}"); + } } #[test] - fn expand_portable_command_rejects_unknown_key() { + fn expand_command_rejects_unknown_key() { let input = quote! { name: "todo.complete", nope: 1, }; - let err = crate::portable_command::expand(input).expect_err("unknown key"); + let err = crate::command::expand(input).expect_err("unknown key"); assert!( - err.to_string() - .contains("unknown portable_command key `nope`"), + err.to_string().contains("unknown command key `nope`"), "got: {err}" ); } diff --git a/distributed_macros/src/graphql_types.rs b/distributed_macros/src/graphql_types.rs deleted file mode 100644 index dc2d50953..000000000 --- a/distributed_macros/src/graphql_types.rs +++ /dev/null @@ -1,690 +0,0 @@ -//! GraphqlInput / GraphqlOutput derive macros. - -use proc_macro2::TokenStream; -use quote::{format_ident, quote}; -use syn::{ - punctuated::Punctuated, Attribute, Data, DeriveInput, Expr, Fields, GenericArgument, Lit, - LitStr, Meta, PathArguments, Token, Type, -}; - -#[derive(Clone, Copy)] -enum SerdeDirection { - Deserialize, - Serialize, -} - -impl SerdeDirection { - fn attribute_name(self) -> &'static str { - match self { - Self::Deserialize => "deserialize", - Self::Serialize => "serialize", - } - } - - fn derive_name(self) -> &'static str { - match self { - Self::Deserialize => "GraphqlInput", - Self::Serialize => "GraphqlOutput", - } - } -} - -#[derive(Clone, Copy)] -#[expect( - clippy::enum_variant_names, - reason = "variant names intentionally mirror serde's public rename_all terminology" -)] -enum RenameRule { - LowerCase, - UpperCase, - PascalCase, - CamelCase, - SnakeCase, - ScreamingSnakeCase, -} - -impl RenameRule { - fn parse(value: &LitStr) -> syn::Result { - match value.value().as_str() { - "lowercase" => Ok(Self::LowerCase), - "UPPERCASE" => Ok(Self::UpperCase), - "PascalCase" => Ok(Self::PascalCase), - "camelCase" => Ok(Self::CamelCase), - "snake_case" => Ok(Self::SnakeCase), - "SCREAMING_SNAKE_CASE" => Ok(Self::ScreamingSnakeCase), - "kebab-case" | "SCREAMING-KEBAB-CASE" => Err(syn::Error::new_spanned( - value, - "serde kebab-case field names cannot be represented in GraphQL; use camelCase or snake_case", - )), - other => Err(syn::Error::new_spanned( - value, - format!( - "unsupported serde rename_all rule `{other}` for GraphqlInput/GraphqlOutput" - ), - )), - } - } - - fn apply(self, field: &str) -> String { - match self { - Self::LowerCase | Self::SnakeCase => field.to_string(), - Self::UpperCase | Self::ScreamingSnakeCase => field.to_ascii_uppercase(), - Self::PascalCase => { - let mut renamed = String::new(); - let mut capitalize = true; - for ch in field.chars() { - if ch == '_' { - capitalize = true; - } else if capitalize { - renamed.push(ch.to_ascii_uppercase()); - capitalize = false; - } else { - renamed.push(ch); - } - } - renamed - } - Self::CamelCase => { - let pascal = Self::PascalCase.apply(field); - let mut chars = pascal.chars(); - chars - .next() - .map(|first| first.to_ascii_lowercase().to_string() + chars.as_str()) - .unwrap_or_default() - } - } - } -} - -pub fn expand_graphql_input(input: DeriveInput) -> syn::Result { - let framework = crate::shared::framework_path()?; - expand( - input, - quote! { #framework::graphql::GraphqlInputType }, - quote! { #framework::graphql::GraphqlInputType }, - framework, - SerdeDirection::Deserialize, - ) -} - -pub fn expand_graphql_output(input: DeriveInput) -> syn::Result { - let framework = crate::shared::framework_path()?; - expand( - input, - quote! { #framework::graphql::GraphqlOutputType }, - quote! { #framework::graphql::GraphqlOutputType }, - framework, - SerdeDirection::Serialize, - ) -} - -fn expand( - input: DeriveInput, - trait_path: TokenStream, - nested_trait: TokenStream, - framework: TokenStream, - serde_direction: SerdeDirection, -) -> syn::Result { - let name = &input.ident; - let visibility = &input.vis; - validate_serde_container_shape(&input.attrs, serde_direction)?; - let rename_all = serde_rename_all(&input.attrs, serde_direction)?; - let Data::Struct(data) = &input.data else { - return Err(syn::Error::new_spanned( - &input, - "GraphqlInput/GraphqlOutput only support structs with named fields", - )); - }; - let Fields::Named(fields) = &data.fields else { - return Err(syn::Error::new_spanned( - &input, - "GraphqlInput/GraphqlOutput require named fields", - )); - }; - - let mut field_tokens = Vec::new(); - let mut effect_input_markers = Vec::new(); - for field in &fields.named { - validate_serde_field_shape(&field.attrs, serde_direction)?; - let field_name = field - .ident - .as_ref() - .ok_or_else(|| syn::Error::new_spanned(field, "field must be named"))?; - let rust_field_name = field_name.to_string(); - let rust_field_name = rust_field_name - .strip_prefix("r#") - .unwrap_or(&rust_field_name); - let field_name_str = - serde_field_rename(&field.attrs, serde_direction)?.unwrap_or_else(|| { - rename_all - .map(|rule| rule.apply(rust_field_name)) - .unwrap_or_else(|| rust_field_name.to_string()) - }); - validate_graphql_field_name(&field_name_str, field)?; - let (type_name, nullable, list, item_nullable, nested) = - map_type(&field.ty, field, &nested_trait)?; - let effect_path_kind = if !list && nested.is_some() { - quote! { #framework::graphql::EffectInputObjectKind } - } else { - quote! { #framework::graphql::EffectInputTerminalKind } - }; - let effect_wire = effect_input_wire_tokens(&framework, &type_name, list, nested.is_some()); - let nested_tokens = match nested { - Some(tokens) => quote! { Some(::std::boxed::Box::new(#tokens)) }, - None => quote! { None }, - }; - field_tokens.push(quote! { - #framework::graphql::GraphqlTypeField { - name: #field_name_str.to_string(), - type_name: #type_name.to_string(), - nullable: #nullable, - list: #list, - item_nullable: #item_nullable, - nested: #nested_tokens, - } - }); - if matches!(serde_direction, SerdeDirection::Deserialize) { - let marker = format_ident!("__Distributed{}EffectInputField_{}", name, field_name); - let field_ty = &field.ty; - let nested_ty = effect_nested_type(field_ty); - let non_null_ty = effect_non_null_type(field_ty); - let nullability = if extract_path_arg(field_ty, "Option").is_some() { - quote! { #framework::graphql::EffectNullable } - } else { - quote! { #framework::graphql::EffectRequired } - }; - effect_input_markers.push(quote! { - #[doc(hidden)] - #[allow(non_camel_case_types)] - #visibility struct #marker; - - impl #framework::graphql::EffectInputFieldMarker for #marker { - type Input = #name; - type Value = #field_ty; - type NonNullValue = #non_null_ty; - type Nullability = #nullability; - type PathKind = #effect_path_kind; - type Wire = #effect_wire; - type Nested = #nested_ty; - fn path() -> ::std::vec::Vec<&'static str> { - vec![#field_name_str] - } - } - }); - } - } - - let type_name_str = name.to_string(); - Ok(quote! { - impl #trait_path for #name { - fn graphql_type() -> #framework::graphql::GraphqlTypeDef { - #framework::graphql::GraphqlTypeDef::new( - #type_name_str, - vec![#(#field_tokens),*], - ).with_type_id(::std::any::TypeId::of::<#name>()) - } - } - - #(#effect_input_markers)* - }) -} - -fn effect_input_wire_tokens( - framework: &TokenStream, - type_name: &str, - list: bool, - nested: bool, -) -> proc_macro2::TokenStream { - if list { - return quote! { #framework::graphql::EffectWireList }; - } - if nested { - return quote! { #framework::graphql::EffectWireObject }; - } - match type_name { - "String" | "ID" => quote! { #framework::graphql::EffectWireString }, - "Boolean" => quote! { #framework::graphql::EffectWireBoolean }, - "BigInt" | "Int" => quote! { #framework::graphql::EffectWireBigInt }, - "Float" => quote! { #framework::graphql::EffectWireFloat }, - "JSON" => quote! { #framework::graphql::EffectWireJson }, - "Bytea" => quote! { #framework::graphql::EffectWireBytea }, - "Timestamptz" => quote! { #framework::graphql::EffectWireTimestamp }, - _ => quote! { #framework::graphql::EffectWireUnsupported }, - } -} - -fn effect_non_null_type(mut ty: &Type) -> &Type { - while let Some(inner) = extract_path_arg(ty, "Option") { - ty = inner; - } - ty -} - -fn effect_nested_type(mut ty: &Type) -> &Type { - while let Some(inner) = extract_path_arg(ty, "Option") { - ty = inner; - } - if let Some(inner) = extract_path_arg(ty, "Vec") { - ty = inner; - while let Some(inner) = extract_path_arg(ty, "Option") { - ty = inner; - } - } - ty -} - -fn map_type( - ty: &Type, - span: &syn::Field, - nested_trait: &TokenStream, -) -> syn::Result<(String, bool, bool, bool, Option)> { - let mut current = ty; - let mut nullable = false; - while let Some(inner) = extract_path_arg(current, "Option") { - nullable = true; - current = inner; - } - - let mut list = false; - let mut item_nullable = false; - if let Some(inner) = extract_path_arg(current, "Vec") { - list = true; - current = inner; - while let Some(inner) = extract_path_arg(current, "Option") { - item_nullable = true; - current = inner; - } - if extract_path_arg(current, "Vec").is_some() { - return Err(syn::Error::new_spanned( - ty, - "nested lists are not supported for GraphqlInput/GraphqlOutput fields", - )); - } - } - - let path = match current { - Type::Path(p) => p, - _ => { - return Err(syn::Error::new_spanned( - span, - "unsupported field type for GraphqlInput/GraphqlOutput", - )); - } - }; - let last = path - .path - .segments - .last() - .ok_or_else(|| syn::Error::new_spanned(span, "empty type path"))?; - let ident = last.ident.to_string(); - - let scalar = match ident.as_str() { - "String" | "str" => Some("String"), - "bool" => Some("Boolean"), - "i8" | "i16" | "i32" | "i64" | "u8" | "u16" | "u32" | "u64" | "isize" | "usize" => { - Some("BigInt") - } - "f32" | "f64" => Some("Float"), - "Value" => Some("JSON"), - _ => None, - }; - - if let Some(s) = scalar { - return Ok((s.to_string(), nullable, list, item_nullable, None)); - } - - let nested = quote! { <#current as #nested_trait>::graphql_type() }; - Ok((ident, nullable, list, item_nullable, Some(nested))) -} - -fn extract_path_arg<'a>(ty: &'a Type, wrapper: &str) -> Option<&'a Type> { - let Type::Path(path) = ty else { - return None; - }; - let seg = path.path.segments.last()?; - if seg.ident != wrapper { - return None; - } - let PathArguments::AngleBracketed(args) = &seg.arguments else { - return None; - }; - args.args.iter().find_map(|arg| match arg { - GenericArgument::Type(t) => Some(t), - _ => None, - }) -} - -fn serde_rename_all( - attrs: &[Attribute], - direction: SerdeDirection, -) -> syn::Result> { - let value = serde_name_value(attrs, "rename_all", direction)?; - value.as_ref().map(RenameRule::parse).transpose() -} - -fn validate_serde_field_shape(attrs: &[Attribute], direction: SerdeDirection) -> syn::Result<()> { - for attr in attrs.iter().filter(|attr| attr.path().is_ident("serde")) { - let metas = attr.parse_args_with(Punctuated::::parse_terminated)?; - for meta in metas { - let unsupported = match &meta { - Meta::Path(path) if path.is_ident("skip") => Some("skip"), - Meta::Path(path) - if path.is_ident("skip_deserializing") - && matches!(direction, SerdeDirection::Deserialize) => - { - Some("skip_deserializing") - } - Meta::Path(path) - if path.is_ident("skip_serializing") - && matches!(direction, SerdeDirection::Serialize) => - { - Some("skip_serializing") - } - Meta::NameValue(name_value) - if name_value.path.is_ident("skip_serializing_if") - && matches!(direction, SerdeDirection::Serialize) => - { - Some("skip_serializing_if") - } - Meta::Path(path) if path.is_ident("flatten") => Some("flatten"), - Meta::Path(path) - if path.is_ident("default") - && matches!(direction, SerdeDirection::Deserialize) => - { - Some("default") - } - Meta::NameValue(name_value) - if name_value.path.is_ident("default") - && matches!(direction, SerdeDirection::Deserialize) => - { - Some("default") - } - Meta::NameValue(name_value) if name_value.path.is_ident("with") => Some("with"), - Meta::NameValue(name_value) - if name_value.path.is_ident("deserialize_with") - && matches!(direction, SerdeDirection::Deserialize) => - { - Some("deserialize_with") - } - Meta::NameValue(name_value) - if name_value.path.is_ident("serialize_with") - && matches!(direction, SerdeDirection::Serialize) => - { - Some("serialize_with") - } - Meta::NameValue(name_value) - if name_value.path.is_ident("alias") - && matches!(direction, SerdeDirection::Deserialize) => - { - Some("alias") - } - _ => None, - }; - if let Some(attribute) = unsupported { - return Err(syn::Error::new_spanned( - meta, - format!( - "#[serde({attribute})] is not supported by {} because it changes the declared GraphQL field shape; define a separate wire type", - direction.derive_name(), - ), - )); - } - } - } - Ok(()) -} - -fn validate_serde_container_shape( - attrs: &[Attribute], - direction: SerdeDirection, -) -> syn::Result<()> { - for attr in attrs.iter().filter(|attr| attr.path().is_ident("serde")) { - let metas = attr.parse_args_with(Punctuated::::parse_terminated)?; - for meta in metas { - let unsupported = match &meta { - Meta::Path(path) if path.is_ident("transparent") => Some("transparent"), - Meta::Path(path) if path.is_ident("untagged") => Some("untagged"), - Meta::NameValue(name_value) - if name_value.path.is_ident("tag") || name_value.path.is_ident("content") => - { - Some(if name_value.path.is_ident("tag") { - "tag" - } else { - "content" - }) - } - Meta::Path(path) - if path.is_ident("default") - && matches!(direction, SerdeDirection::Deserialize) => - { - Some("default") - } - Meta::NameValue(name_value) - if name_value.path.is_ident("default") - && matches!(direction, SerdeDirection::Deserialize) => - { - Some("default") - } - Meta::NameValue(name_value) - if (name_value.path.is_ident("from") - || name_value.path.is_ident("try_from")) - && matches!(direction, SerdeDirection::Deserialize) => - { - Some(if name_value.path.is_ident("from") { - "from" - } else { - "try_from" - }) - } - Meta::NameValue(name_value) - if name_value.path.is_ident("into") - && matches!(direction, SerdeDirection::Serialize) => - { - Some("into") - } - _ => None, - }; - if let Some(attribute) = unsupported { - return Err(syn::Error::new_spanned( - meta, - format!( - "#[serde({attribute})] is not supported by {} because it changes the declared GraphQL object shape; define a separate wire type", - direction.derive_name(), - ), - )); - } - } - } - Ok(()) -} - -fn serde_field_rename( - attrs: &[Attribute], - direction: SerdeDirection, -) -> syn::Result> { - Ok(serde_name_value(attrs, "rename", direction)?.map(|value| value.value())) -} - -fn serde_name_value( - attrs: &[Attribute], - key: &str, - direction: SerdeDirection, -) -> syn::Result> { - let mut found = None; - for attr in attrs.iter().filter(|attr| attr.path().is_ident("serde")) { - let metas = attr.parse_args_with(Punctuated::::parse_terminated)?; - for meta in metas { - match meta { - Meta::NameValue(name_value) if name_value.path.is_ident(key) => { - set_serde_name(&mut found, string_literal(&name_value.value, key)?, key)?; - } - Meta::List(list) if list.path.is_ident(key) => { - let directional = - list.parse_args_with(Punctuated::::parse_terminated)?; - for meta in directional { - if let Meta::NameValue(name_value) = meta { - if name_value.path.is_ident(direction.attribute_name()) { - set_serde_name( - &mut found, - string_literal(&name_value.value, key)?, - key, - )?; - } - } - } - } - _ => {} - } - } - } - Ok(found) -} - -fn set_serde_name(found: &mut Option, value: LitStr, key: &str) -> syn::Result<()> { - if found.is_some() { - return Err(syn::Error::new_spanned( - value, - format!("duplicate serde `{key}` rule for GraphqlInput/GraphqlOutput"), - )); - } - *found = Some(value); - Ok(()) -} - -fn string_literal(value: &Expr, key: &str) -> syn::Result { - match value { - Expr::Lit(expr) => match &expr.lit { - Lit::Str(value) => Ok(value.clone()), - _ => Err(syn::Error::new_spanned( - value, - format!("serde `{key}` must be a string literal"), - )), - }, - _ => Err(syn::Error::new_spanned( - value, - format!("serde `{key}` must be a string literal"), - )), - } -} - -fn validate_graphql_field_name(name: &str, span: &syn::Field) -> syn::Result<()> { - let mut chars = name.chars(); - let first_valid = match chars.next() { - Some('_') => !name.starts_with("__"), - Some(first) => first.is_ascii_alphabetic(), - None => false, - }; - if first_valid && chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_') { - return Ok(()); - } - Err(syn::Error::new_spanned( - span, - format!( - "serde field name `{name}` is not a valid GraphQL name; use #[serde(rename = \"valid_name\")]" - ), - )) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn graphql_safe_rename_all_rules_match_serde_field_rules() { - let field = "long_field_name"; - let cases = [ - ("lowercase", "long_field_name"), - ("UPPERCASE", "LONG_FIELD_NAME"), - ("PascalCase", "LongFieldName"), - ("camelCase", "longFieldName"), - ("snake_case", "long_field_name"), - ("SCREAMING_SNAKE_CASE", "LONG_FIELD_NAME"), - ]; - for (rule, expected) in cases { - let literal = LitStr::new(rule, proc_macro2::Span::call_site()); - assert_eq!(RenameRule::parse(&literal).unwrap().apply(field), expected); - } - } - - #[test] - fn directional_serde_names_follow_wire_direction() { - let input: DeriveInput = syn::parse_quote! { - #[serde(rename_all(deserialize = "camelCase", serialize = "SCREAMING_SNAKE_CASE"))] - struct CommandInput { - regular_field: String, - #[serde(rename(deserialize = "inputID", serialize = "OUTPUT_ID"))] - custom_id: String, - } - }; - let input_tokens = expand_graphql_input(input).unwrap().to_string(); - assert!(input_tokens.contains("\"regularField\"")); - assert!(input_tokens.contains("\"inputID\"")); - - let output: DeriveInput = syn::parse_quote! { - #[serde(rename_all(deserialize = "camelCase", serialize = "SCREAMING_SNAKE_CASE"))] - struct CommandOutput { - regular_field: String, - #[serde(rename(deserialize = "inputID", serialize = "OUTPUT_ID"))] - custom_id: String, - } - }; - let output_tokens = expand_graphql_output(output).unwrap().to_string(); - assert!(output_tokens.contains("\"REGULAR_FIELD\"")); - assert!(output_tokens.contains("\"OUTPUT_ID\"")); - } - - #[test] - fn nested_lists_and_shape_changing_serde_attrs_fail_closed() { - let nested: DeriveInput = syn::parse_quote! { - struct Nested { values: Option>>> } - }; - let error = expand_graphql_input(nested).unwrap_err().to_string(); - assert!(error.contains("nested lists are not supported"), "{error}"); - - let skipped: DeriveInput = syn::parse_quote! { - struct Skipped { - #[serde(skip_deserializing)] - value: String, - } - }; - let error = expand_graphql_input(skipped).unwrap_err().to_string(); - assert!( - error.contains("changes the declared GraphQL field shape"), - "{error}" - ); - - let defaulted: DeriveInput = syn::parse_quote! { - struct Defaulted { - #[serde(default)] - value: String, - } - }; - let error = expand_graphql_input(defaulted).unwrap_err().to_string(); - assert!(error.contains("#[serde(default)]"), "{error}"); - - let custom: DeriveInput = syn::parse_quote! { - struct Custom { - #[serde(deserialize_with = "decode_value")] - value: String, - } - }; - let error = expand_graphql_input(custom).unwrap_err().to_string(); - assert!(error.contains("#[serde(deserialize_with)]"), "{error}"); - - let transparent: DeriveInput = syn::parse_quote! { - #[serde(transparent)] - struct Transparent { value: String } - }; - let error = expand_graphql_output(transparent).unwrap_err().to_string(); - assert!(error.contains("#[serde(transparent)]"), "{error}"); - - let container_default: DeriveInput = syn::parse_quote! { - #[serde(default = "default_input")] - struct ContainerDefault { value: String } - }; - let error = expand_graphql_input(container_default) - .unwrap_err() - .to_string(); - assert!(error.contains("#[serde(default)]"), "{error}"); - } -} diff --git a/distributed_macros/src/lib.rs b/distributed_macros/src/lib.rs index b075a46f0..4f04c6b14 100644 --- a/distributed_macros/src/lib.rs +++ b/distributed_macros/src/lib.rs @@ -1,14 +1,10 @@ mod aggregate; -mod application; +mod aggregate_command; mod command; mod command_input_defaults; -mod portable_command; -mod digest; +mod command_types; mod domain_event; mod domain_state; -mod enqueue; -mod graphql_types; -mod module; mod mutation; // Event-owning `projection!` authoring removed (mutation projectors cutover). mod read_model; @@ -19,67 +15,19 @@ mod sourced; use proc_macro::TokenStream; use syn::DeriveInput; -/// Generate one typed command's portable contract and optional executable -/// mount from the same handler declaration. -#[proc_macro_attribute] -pub fn command(attr: TokenStream, item: TokenStream) -> TokenStream { - command::expand(attr.into(), item.into()) - .unwrap_or_else(|error| error.to_compile_error()) - .into() -} - -/// Domain-owned portable command mount (`PCH-DEC-001`). +/// Declare a command on an aggregate transition: name, shard, load, payload +/// and outcome, with `handle:` for a hand-written handler. /// -/// Spec sketches used `command!`; that name is the handler attribute -/// [`command`]. This is the function-like form for shard + invoke + Eventual -/// (or a `handle:` escape hatch). -#[proc_macro] -pub fn portable_command(input: TokenStream) -> TokenStream { - portable_command::expand(input.into()) - .unwrap_or_else(|error| error.to_compile_error()) - .into() -} - -/// Register an explicit logical module. +/// The method form, `#[command("aggregate.verb", ..)]` on a method inside a +/// `#[sourced]` impl, is read by `#[sourced]` and declares the same thing +/// next to the transition. #[proc_macro] -pub fn module(input: TokenStream) -> TokenStream { - module::expand(input.into()) +pub fn command(input: TokenStream) -> TokenStream { + command::expand(input.into()) .unwrap_or_else(|error| error.to_compile_error()) .into() } -/// Register an explicit application and its selected modules/surfaces. -#[proc_macro] -pub fn application(input: TokenStream) -> TokenStream { - application::expand(input.into()) - .unwrap_or_else(|error| error.to_compile_error()) - .into() -} - -/// Attribute macro that automatically queues a local event for emission. -#[proc_macro_attribute] -pub fn enqueue(attr: TokenStream, item: TokenStream) -> TokenStream { - enqueue::expand_enqueue(attr.into(), item.into()) - .unwrap_or_else(|e| e.to_compile_error()) - .into() -} - -/// Attribute macro that automatically inserts a digest call at the beginning of a method. -#[proc_macro_attribute] -pub fn digest(attr: TokenStream, item: TokenStream) -> TokenStream { - digest::expand_digest(attr.into(), item.into()) - .unwrap_or_else(|e| e.to_compile_error()) - .into() -} - -/// Generates the Aggregate trait impl with replay logic. -#[proc_macro] -pub fn aggregate(input: TokenStream) -> TokenStream { - aggregate::expand_aggregate(input.into()) - .unwrap_or_else(|e| e.to_compile_error()) - .into() -} - /// Generate aggregate replay code and optionally capture typed outward domain events. /// /// Configure a [`DomainState`] body once with @@ -151,16 +99,6 @@ pub fn command_input_defaults(input: TokenStream) -> TokenStream { /// } /// } /// ``` -/// -/// Classic sugar still works: -/// -/// ```ignore -/// mutation! { -/// name: "SaveTodo"; -/// version: 1; -/// upsert Todos from input.todo; -/// } -/// ``` #[proc_macro] pub fn mutation(input: TokenStream) -> TokenStream { mutation::expand(input) @@ -182,21 +120,21 @@ pub fn mutation_file(input: TokenStream) -> TokenStream { mutation::expand_file(input) } -/// Derive `GraphqlInputType` for command mutation input structs. -#[proc_macro_derive(GraphqlInput, attributes(serde))] -pub fn derive_graphql_input(input: TokenStream) -> TokenStream { +/// Derive transport-neutral command input metadata from Serde field shapes. +#[proc_macro_derive(CommandInput, attributes(serde))] +pub fn derive_command_input(input: TokenStream) -> TokenStream { let input = syn::parse_macro_input!(input as DeriveInput); - match graphql_types::expand_graphql_input(input) { + match command_types::expand_command_input(input) { Ok(tokens) => tokens.into(), Err(err) => err.to_compile_error().into(), } } -/// Derive `GraphqlOutputType` for command mutation output structs. -#[proc_macro_derive(GraphqlOutput, attributes(serde))] -pub fn derive_graphql_output(input: TokenStream) -> TokenStream { +/// Derive transport-neutral command output metadata from Serde field shapes. +#[proc_macro_derive(CommandOutput, attributes(serde))] +pub fn derive_command_output(input: TokenStream) -> TokenStream { let input = syn::parse_macro_input!(input as DeriveInput); - match graphql_types::expand_graphql_output(input) { + match command_types::expand_command_output(input) { Ok(tokens) => tokens.into(), Err(err) => err.to_compile_error().into(), } diff --git a/distributed_macros/src/module.rs b/distributed_macros/src/module.rs deleted file mode 100644 index a1df31f3a..000000000 --- a/distributed_macros/src/module.rs +++ /dev/null @@ -1,165 +0,0 @@ -use proc_macro2::TokenStream; -use quote::{format_ident, quote}; -use syn::parse::{Parse, ParseStream}; -use syn::punctuated::Punctuated; -use syn::{Expr, Ident, LitStr, Token, Type, Visibility}; - -struct ModuleInput { - visibility: Visibility, - name: Ident, - id: LitStr, - commands: Vec, - projections: Vec, - surfaces: Vec, - capabilities: Vec, -} - -impl Parse for ModuleInput { - fn parse(input: ParseStream<'_>) -> syn::Result { - let visibility: Visibility = input.parse()?; - let name: Ident = input.parse()?; - if input.peek(Token![:]) { - input.parse::()?; - let _: Type = input.parse()?; - } - if input.peek(Token![=]) { - input.parse::()?; - } - let content; - syn::braced!(content in input); - let mut output = Self { - visibility, - name, - id: LitStr::new("", proc_macro2::Span::call_site()), - commands: Vec::new(), - projections: Vec::new(), - surfaces: Vec::new(), - capabilities: Vec::new(), - }; - while !content.is_empty() { - let field: Ident = content.parse()?; - content.parse::()?; - match field.to_string().as_str() { - "id" => output.id = content.parse()?, - "commands" => output.commands = parse_expr_array(&content)?, - "mounts" => { - return Err(syn::Error::new( - field.span(), - "command declarations derive their optional runtime mount; maintain one `commands: [*_DEFINITION]` list and remove `mounts`", - )) - } - "projections" => output.projections = parse_expr_array(&content)?, - "surfaces" => output.surfaces = parse_expr_array(&content)?, - "capabilities" | "required_capabilities" => { - output.capabilities = parse_expr_array(&content)? - } - other => { - return Err(syn::Error::new( - field.span(), - format!("unknown module field `{other}`"), - )) - } - } - if content.peek(Token![,]) { - content.parse::()?; - } - } - if output.id.value().is_empty() { - output.id = LitStr::new( - &output.name.to_string().to_ascii_lowercase(), - output.name.span(), - ); - } - Ok(output) - } -} - -fn parse_expr_array(input: ParseStream<'_>) -> syn::Result> { - let content; - syn::bracketed!(content in input); - Ok(Punctuated::::parse_terminated(&content)? - .into_iter() - .collect()) -} - -pub fn expand(input: proc_macro2::TokenStream) -> syn::Result { - let framework = crate::shared::framework_path()?; - let input = syn::parse2::(input)?; - let ModuleInput { - visibility, - name, - id, - commands, - projections, - surfaces, - capabilities, - } = input; - let accessor = format_ident!("{}", name.to_string().to_lowercase()); - let command_ids = commands - .iter() - .map(command_definition_id) - .collect::>>()?; - let commands = commands.iter().map(|value| quote! { (&*#value).clone() }); - let projections = projections - .iter() - .map(|value| quote! { (&*#value).clone() }); - let surfaces = surfaces.iter().map(|value| quote! { (&*#value).clone() }); - let capabilities = capabilities - .iter() - .map(|value| quote! { #value }) - .collect::>(); - let capability_builder = if capabilities.is_empty() { - quote! {} - } else { - quote! { .required_capabilities([#(#capabilities),*]) } - }; - Ok(quote! { - const _: () = #framework::application::assert_unique_command_ids( - &[#(#command_ids),*] - ); - - #visibility static #name: ::std::sync::LazyLock<#framework::application::Module> = - ::std::sync::LazyLock::new(|| { - #framework::application::Module::builder(#id) - .command_definitions([#(#commands),*]) - .projections([#(#projections),*]) - .surfaces([#(#surfaces),*]) - #capability_builder - .build() - .unwrap_or_else(|error| panic!("invalid generated module: {error}")) - }); - - #visibility fn #accessor() -> &'static #framework::application::Module { - &#name - } - }) -} - -fn command_definition_id(value: &Expr) -> syn::Result { - let Expr::Path(path) = value else { - return Err(syn::Error::new_spanned( - value, - "module command entries must be generated *_DEFINITION paths", - )); - }; - let mut id_path = path.path.clone(); - let Some(last) = id_path.segments.last_mut() else { - return Err(syn::Error::new_spanned( - value, - "module command entries must be generated *_DEFINITION paths", - )); - }; - if !last.ident.to_string().ends_with("_DEFINITION") { - return Err(syn::Error::new_spanned( - value, - "module command entries must use the generated *_DEFINITION value so spec and mount cannot diverge", - )); - } - let span = last.ident.span(); - let name = last.ident.to_string(); - let name = name - .strip_suffix("_DEFINITION") - .expect("checked generated definition suffix"); - last.ident = syn::Ident::new(&format!("{name}_COMMAND_ID"), span); - Ok(id_path) -} diff --git a/distributed_macros/src/mutation.rs b/distributed_macros/src/mutation.rs index d0f97d9af..b79c6bda4 100644 --- a/distributed_macros/src/mutation.rs +++ b/distributed_macros/src/mutation.rs @@ -1,7 +1,6 @@ //! `mutation!` macro: event-independent read-model mutation programs. //! -//! Supports classic sugar and GraphQL-looking syntax-only documents (not public -//! GraphQL schema fields): +//! GraphQL-looking, syntax-only documents (not public GraphQL schema fields): //! //! ```ignore //! mutation! { @@ -22,7 +21,7 @@ use std::path::PathBuf; use proc_macro2::TokenStream; use quote::quote; use syn::parse::{Parse, ParseStream}; -use syn::{braced, parenthesized, Ident, LitInt, LitStr, Path, Result, Token, Type}; +use syn::{braced, parenthesized, Ident, LitInt, LitStr, Path, Result, Token}; pub(crate) fn expand(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as MutationDeclaration); @@ -32,12 +31,22 @@ pub(crate) fn expand(input: proc_macro::TokenStream) -> proc_macro::TokenStream } /// Load a `.mutation.graphql` document relative to `CARGO_MANIFEST_DIR`. +/// +/// The expansion `include_str!`s the file, so the compiler tracks it and an +/// edit to the document rebuilds the crate. pub(crate) fn expand_file(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let path_lit = syn::parse_macro_input!(input as LitStr); - match load_graphql_file(&path_lit) { - Ok(decl) => expand_declaration(decl) - .unwrap_or_else(syn::Error::into_compile_error) - .into(), + let declaration = load_graphql_file(&path_lit).and_then(expand_declaration); + match declaration { + Ok(declaration) => quote! { + { + const _: &str = ::core::include_str!( + ::core::concat!(::core::env!("CARGO_MANIFEST_DIR"), "/", #path_lit) + ); + #declaration + } + } + .into(), Err(error) => error.to_compile_error().into(), } } @@ -65,38 +74,28 @@ fn load_graphql_file(path_lit: &LitStr) -> Result { } struct MutationDeclaration { - name: Option, + name: LitStr, version: Option, - input_ty: Option, operations: Vec, } type GraphqlFieldBinding = (Ident, Vec); enum MutationOpSyntax { - /// `upsert Model from input.root;` - SugarUpsert { model: Path, input_root: Vec }, - /// `upsert Model one { object: input.root, conflict: primary_key, update: all_input_fields };` - ExplicitUpsert { - model: Path, - object_root: Vec, - #[allow(dead_code)] - conflict_primary_key: bool, - #[allow(dead_code)] - update_all: bool, - }, - /// `delete Model by_pk { field: input.path, ... };` + /// `upsert_model(object: $input.root)` + Upsert { model: Path, input_root: Vec }, + /// `delete_model_by_pk(field: $input.path, ...)` DeleteByPk { model: Path, keys: Vec, }, - /// `update Model by_pk { key..., _set: { field: expr, ... } };` + /// `update_model_by_pk(pk_columns: {..}, _set: {..})` UpdateByPk { model: Path, keys: Vec, sets: Vec, }, - /// `insert Model one { object: input.root };` + /// `insert_model_one(object: $input.root)` InsertOne { model: Path, object_root: Vec, @@ -105,71 +104,10 @@ enum MutationOpSyntax { impl Parse for MutationDeclaration { fn parse(input: ParseStream<'_>) -> Result { - // GraphQL-looking form: `mutation Name { upsert_todos(...) }` - if input.peek(Ident) { - let keyword: Ident = input.fork().parse()?; - if keyword == "mutation" { - return parse_graphql_token_document(input); - } - } - - let mut name = None; - let mut version = None; - let mut input_ty = None; - let mut operations = Vec::new(); - - while !input.is_empty() { - if input.peek(Ident) { - let keyword: Ident = input.fork().parse()?; - match keyword.to_string().as_str() { - "name" => { - let _: Ident = input.parse()?; - input.parse::()?; - name = Some(input.parse()?); - parse_separator(input)?; - continue; - } - "version" => { - let _: Ident = input.parse()?; - input.parse::()?; - version = Some(input.parse()?); - parse_separator(input)?; - continue; - } - "input" => { - let _: Ident = input.parse()?; - input.parse::()?; - input_ty = Some(input.parse()?); - parse_separator(input)?; - continue; - } - "upsert" | "delete" | "update" | "insert" | "patch" => { - operations.push(parse_operation(input)?); - continue; - } - _ => {} - } - } - return Err(input.error( - "expected GraphQL-looking `mutation Name { … }`, classic mutation \ - operations (`upsert`, `insert`, `update`, `delete`), or \ - `name`/`version`/`input` metadata", - )); + if input.peek(Ident) && input.fork().parse::()? == "mutation" { + return parse_graphql_token_document(input); } - - if operations.is_empty() { - return Err(syn::Error::new( - proc_macro2::Span::call_site(), - "mutation! requires at least one operation", - )); - } - - Ok(Self { - name, - version, - input_ty, - operations, - }) + Err(input.error("expected `mutation Name { upsert_model(object: $input.field) … }`")) } } @@ -216,9 +154,8 @@ fn parse_graphql_token_document(input: ParseStream<'_>) -> Result) -> Result) -> Result> { parse_input_path(input) } -fn parse_separator(input: ParseStream<'_>) -> Result<()> { - if input.peek(Token![;]) { - input.parse::()?; - } else if input.peek(Token![,]) { - input.parse::()?; - } - Ok(()) -} - -fn parse_operation(input: ParseStream<'_>) -> Result { - let keyword: Ident = input.parse()?; - match keyword.to_string().as_str() { - "upsert" => parse_upsert(input), - "insert" => parse_insert(input), - "delete" => parse_delete(input), - "update" | "patch" => parse_update(input), - other => Err(syn::Error::new( - keyword.span(), - format!("unsupported mutation operation `{other}`"), - )), - } -} - -fn parse_upsert(input: ParseStream<'_>) -> Result { - let model: Path = input.parse()?; - if input.peek(Ident) { - let mode: Ident = input.fork().parse()?; - if mode == "from" { - let _: Ident = input.parse()?; - let input_root = parse_input_path(input)?; - parse_separator(input)?; - return Ok(MutationOpSyntax::SugarUpsert { model, input_root }); - } - } - let mode: Ident = input.parse()?; - if mode != "one" { - return Err(syn::Error::new( - mode.span(), - "expected `from` sugar or `one { ... }` explicit upsert", - )); - } - let content; - braced!(content in input); - let mut object_root = None; - let mut conflict_primary_key = false; - let mut update_all = false; - while !content.is_empty() { - let field: Ident = content.parse()?; - content.parse::()?; - match field.to_string().as_str() { - "object" => { - object_root = Some(parse_input_path(&content)?); - } - "conflict" => { - let target: Ident = content.parse()?; - if target != "primary_key" { - return Err(syn::Error::new( - target.span(), - "only `conflict: primary_key` is supported in v1", - )); - } - conflict_primary_key = true; - } - "update" => { - let mode: Ident = content.parse()?; - if mode != "all_input_fields" { - return Err(syn::Error::new( - mode.span(), - "only `update: all_input_fields` is supported in v1 sugar", - )); - } - update_all = true; - } - other => { - return Err(syn::Error::new( - field.span(), - format!("unknown upsert field `{other}`"), - )); - } - } - parse_separator(&content)?; - } - let object_root = object_root.ok_or_else(|| { - syn::Error::new(mode.span(), "explicit upsert requires `object: input...`") - })?; - parse_separator(input)?; - Ok(MutationOpSyntax::ExplicitUpsert { - model, - object_root, - conflict_primary_key, - update_all, - }) -} - -fn parse_insert(input: ParseStream<'_>) -> Result { - let model: Path = input.parse()?; - let mode: Ident = input.parse()?; - if mode != "one" { - return Err(syn::Error::new( - mode.span(), - "expected `insert Model one { ... }`", - )); - } - let content; - braced!(content in input); - let mut object_root = None; - while !content.is_empty() { - let field: Ident = content.parse()?; - content.parse::()?; - if field == "object" { - object_root = Some(parse_input_path(&content)?); - } else { - return Err(syn::Error::new(field.span(), "expected `object`")); - } - parse_separator(&content)?; - } - let object_root = object_root - .ok_or_else(|| syn::Error::new(mode.span(), "insert requires `object: input...`"))?; - parse_separator(input)?; - Ok(MutationOpSyntax::InsertOne { model, object_root }) -} - -fn parse_delete(input: ParseStream<'_>) -> Result { - let model: Path = input.parse()?; - let mode: Ident = input.parse()?; - if mode != "by_pk" { - return Err(syn::Error::new( - mode.span(), - "expected `delete Model by_pk { ... }`", - )); - } - let content; - braced!(content in input); - let mut keys = Vec::new(); - while !content.is_empty() { - let name: Ident = content.parse()?; - content.parse::()?; - let path = parse_input_path(&content)?; - keys.push((name, path)); - parse_separator(&content)?; - } - if keys.is_empty() { - return Err(syn::Error::new( - mode.span(), - "delete by_pk requires key fields", - )); - } - parse_separator(input)?; - Ok(MutationOpSyntax::DeleteByPk { model, keys }) -} - -fn parse_update(input: ParseStream<'_>) -> Result { - let model: Path = input.parse()?; - let mode: Ident = input.parse()?; - if mode != "by_pk" { - return Err(syn::Error::new( - mode.span(), - "expected `update Model by_pk { ... }`", - )); - } - let content; - braced!(content in input); - let mut keys = Vec::new(); - let mut sets = Vec::new(); - while !content.is_empty() { - let name: Ident = content.parse()?; - content.parse::()?; - if name == "_set" { - let set_content; - braced!(set_content in content); - while !set_content.is_empty() { - let field: Ident = set_content.parse()?; - set_content.parse::()?; - let path = parse_input_path(&set_content)?; - sets.push((field, path)); - parse_separator(&set_content)?; - } - } else { - let path = parse_input_path(&content)?; - keys.push((name, path)); - } - parse_separator(&content)?; - } - if keys.is_empty() || sets.is_empty() { - return Err(syn::Error::new( - mode.span(), - "update by_pk requires key fields and `_set { ... }`", - )); - } - parse_separator(input)?; - Ok(MutationOpSyntax::UpdateByPk { model, keys, sets }) -} - fn parse_input_path(input: ParseStream<'_>) -> Result> { // Accept `input.foo.bar` or bare `foo.bar` paths. let first: Ident = input.parse()?; @@ -635,286 +379,77 @@ fn parse_input_path(input: ParseStream<'_>) -> Result> { } fn expand_declaration(decl: MutationDeclaration) -> Result { - let name = decl - .name - .map(|lit| lit.value()) - .unwrap_or_else(|| "mutation".to_owned()); let version = decl .version .map(|lit| lit.base10_parse::()) .transpose()? .unwrap_or(1); - let input_ty = decl.input_ty.unwrap_or_else(|| syn::parse_quote!(())); - - let mut op_tokens = Vec::new(); - for (index, operation) in decl.operations.iter().enumerate() { - op_tokens.push(expand_operation(index as u32, operation)?); - } - - let name_lit = LitStr::new(&name, proc_macro2::Span::call_site()); + let framework = crate::shared::framework_path()?; + let steps = decl + .operations + .iter() + .map(|operation| expand_step(&framework, operation)); + let name_lit = decl.name; + // The declaration is data. `Mutation::program` builds and validates it and + // returns an error; nothing here can panic. Ok(quote! { { - let __operations = vec![ - #(#op_tokens),* - ]; - let __program = ::distributed::MutationProgram::try_new( - #name_lit, - #version, - __operations, - ).unwrap_or_else(|error| ::std::panic!("invalid mutation program: {error}")); - ::distributed::Mutation::<#input_ty>::from_program(__program) + const __STEPS: &[#framework::MutationStep] = &[#(#steps),*]; + #framework::Mutation::<()>::declare(#name_lit, #version, __STEPS) } }) } -fn expand_operation(index: u32, operation: &MutationOpSyntax) -> Result { +fn path_literals(path: &[Ident]) -> Vec { + path.iter() + .map(|ident| LitStr::new(&ident.to_string(), ident.span())) + .collect() +} + +fn expand_inputs(framework: &TokenStream, bindings: &[GraphqlFieldBinding]) -> TokenStream { + let inputs = bindings.iter().map(|(column, path)| { + let column = LitStr::new(&column.to_string(), column.span()); + let path = path_literals(path); + quote! { + #framework::MutationInput { column: #column, path: &[#(#path),*] } + } + }); + quote! { &[#(#inputs),*] } +} + +fn expand_step(framework: &TokenStream, operation: &MutationOpSyntax) -> TokenStream { + let schema = |model: &Path| { + quote! { <#model as #framework::RelationalReadModel>::schema } + }; match operation { - MutationOpSyntax::SugarUpsert { model, input_root } - | MutationOpSyntax::ExplicitUpsert { - model, - object_root: input_root, - .. - } => { - // Expand to runtime helper that uses ReadModel schema for key/fields. - let root_lits = input_root - .iter() - .map(|ident| LitStr::new(&ident.to_string(), ident.span())) - .collect::>(); - let op_id = format!("upsert-{index}"); - let op_id_lit = LitStr::new(&op_id, proc_macro2::Span::call_site()); - Ok(quote! { - { - use ::distributed::{ - MutationAssignment, MutationConflictTarget, MutationField, MutationKeyField, - MutationKind, MutationOperation, MutationExpression, ProjectionTarget, - ProjectionValueType, RelationalReadModel, - }; - let __schema = <#model as RelationalReadModel>::schema(); - let __target = ProjectionTarget::try_new( - __schema.model_name.clone(), - __schema.table_name.clone(), - ).expect("model target"); - let __root: &[&str] = &[#(#root_lits),*]; - let mut __key = ::std::vec::Vec::new(); - for (ordinal, column) in __schema.primary_key.columns.iter().enumerate() { - let mut path = __root.iter().map(|s| (*s).to_owned()).collect::>(); - path.push(column.clone()); - __key.push(MutationKeyField::try_new( - ordinal as u32, - column.clone(), - MutationExpression::input_path(ProjectionValueType::String, path) - .expect("key path"), - ).expect("key field")); - } - let mut __fields = ::std::vec::Vec::new(); - let mut __ordinal = 0u32; - for column in __schema.columns.iter().filter(|column| !column.skipped) { - let mut path = __root.iter().map(|s| (*s).to_owned()).collect::>(); - path.push(column.field_name.clone()); - __fields.push(MutationField::try_new( - __ordinal, - column.field_name.clone(), - MutationAssignment::set( - MutationExpression::input_path( - ProjectionValueType::String, - path, - ).expect("field path"), - ), - ).expect("field")); - __ordinal += 1; - } - MutationOperation::try_new( - #op_id_lit, - #index, - MutationKind::Upsert, - __target, - __key, - __fields, - Some(MutationConflictTarget::PrimaryKey), - ::std::vec::Vec::new(), - ::std::vec::Vec::new(), - None, - ).expect("upsert operation") - } - }) + MutationOpSyntax::Upsert { model, input_root } => { + let model = schema(model); + let object = path_literals(input_root); + quote! { + #framework::MutationStep::Upsert { model: #model, object: &[#(#object),*] } + } } MutationOpSyntax::InsertOne { model, object_root } => { - let root_lits = object_root - .iter() - .map(|ident| LitStr::new(&ident.to_string(), ident.span())) - .collect::>(); - let op_id = format!("insert-{index}"); - let op_id_lit = LitStr::new(&op_id, proc_macro2::Span::call_site()); - Ok(quote! { - { - use ::distributed::{ - MutationAssignment, MutationField, MutationKeyField, MutationKind, - MutationOperation, MutationExpression, ProjectionTarget, - ProjectionValueType, RelationalReadModel, - }; - let __schema = <#model as RelationalReadModel>::schema(); - let __target = ProjectionTarget::try_new( - __schema.model_name.clone(), - __schema.table_name.clone(), - ).expect("model target"); - let __root: &[&str] = &[#(#root_lits),*]; - let mut __key = ::std::vec::Vec::new(); - for (ordinal, column) in __schema.primary_key.columns.iter().enumerate() { - let mut path = __root.iter().map(|s| (*s).to_owned()).collect::>(); - path.push(column.clone()); - __key.push(MutationKeyField::try_new( - ordinal as u32, - column.clone(), - MutationExpression::input_path(ProjectionValueType::String, path) - .expect("key path"), - ).expect("key field")); - } - let mut __fields = ::std::vec::Vec::new(); - let mut __ordinal = 0u32; - for column in __schema.columns.iter().filter(|column| !column.skipped) { - let mut path = __root.iter().map(|s| (*s).to_owned()).collect::>(); - path.push(column.field_name.clone()); - __fields.push(MutationField::try_new( - __ordinal, - column.field_name.clone(), - MutationAssignment::set( - MutationExpression::input_path( - ProjectionValueType::String, - path, - ).expect("field path"), - ), - ).expect("field")); - __ordinal += 1; - } - MutationOperation::try_new( - #op_id_lit, - #index, - MutationKind::Insert, - __target, - __key, - __fields, - None, - ::std::vec::Vec::new(), - ::std::vec::Vec::new(), - None, - ).expect("insert operation") - } - }) + let model = schema(model); + let object = path_literals(object_root); + quote! { + #framework::MutationStep::Insert { model: #model, object: &[#(#object),*] } + } } MutationOpSyntax::DeleteByPk { model, keys } => { - let op_id = format!("delete-{index}"); - let op_id_lit = LitStr::new(&op_id, proc_macro2::Span::call_site()); - let key_tokens = keys.iter().enumerate().map(|(ordinal, (name, path))| { - let name_lit = LitStr::new(&name.to_string(), name.span()); - let path_lits = path - .iter() - .map(|ident| LitStr::new(&ident.to_string(), ident.span())) - .collect::>(); - let ordinal = ordinal as u32; - quote! { - MutationKeyField::try_new( - #ordinal, - #name_lit, - MutationExpression::input_path( - ProjectionValueType::String, - vec![#(#path_lits.to_owned()),*], - ).expect("key path"), - ).expect("key field") - } - }); - Ok(quote! { - { - use ::distributed::{ - MutationKeyField, MutationKind, MutationOperation, MutationExpression, - ProjectionTarget, ProjectionValueType, RelationalReadModel, - }; - let __schema = <#model as RelationalReadModel>::schema(); - let __target = ProjectionTarget::try_new( - __schema.model_name.clone(), - __schema.table_name.clone(), - ).expect("model target"); - MutationOperation::try_new( - #op_id_lit, - #index, - MutationKind::Delete, - __target, - vec![#(#key_tokens),*], - ::std::vec::Vec::new(), - None, - ::std::vec::Vec::new(), - ::std::vec::Vec::new(), - None, - ).expect("delete operation") - } - }) + let model = schema(model); + let key = expand_inputs(framework, keys); + quote! { + #framework::MutationStep::Delete { model: #model, key: #key } + } } MutationOpSyntax::UpdateByPk { model, keys, sets } => { - let op_id = format!("patch-{index}"); - let op_id_lit = LitStr::new(&op_id, proc_macro2::Span::call_site()); - let key_tokens = keys.iter().enumerate().map(|(ordinal, (name, path))| { - let name_lit = LitStr::new(&name.to_string(), name.span()); - let path_lits = path - .iter() - .map(|ident| LitStr::new(&ident.to_string(), ident.span())) - .collect::>(); - let ordinal = ordinal as u32; - quote! { - MutationKeyField::try_new( - #ordinal, - #name_lit, - MutationExpression::input_path( - ProjectionValueType::String, - vec![#(#path_lits.to_owned()),*], - ).expect("key path"), - ).expect("key field") - } - }); - let field_tokens = sets.iter().enumerate().map(|(ordinal, (name, path))| { - let name_lit = LitStr::new(&name.to_string(), name.span()); - let path_lits = path - .iter() - .map(|ident| LitStr::new(&ident.to_string(), ident.span())) - .collect::>(); - let ordinal = ordinal as u32; - quote! { - MutationField::try_new( - #ordinal, - #name_lit, - MutationAssignment::set( - MutationExpression::input_path( - ProjectionValueType::String, - vec![#(#path_lits.to_owned()),*], - ).expect("field path"), - ), - ).expect("field") - } - }); - Ok(quote! { - { - use ::distributed::{ - MutationAssignment, MutationField, MutationKeyField, MutationKind, - MutationOperation, MutationExpression, ProjectionTarget, - ProjectionValueType, RelationalReadModel, - }; - let __schema = <#model as RelationalReadModel>::schema(); - let __target = ProjectionTarget::try_new( - __schema.model_name.clone(), - __schema.table_name.clone(), - ).expect("model target"); - MutationOperation::try_new( - #op_id_lit, - #index, - MutationKind::Patch, - __target, - vec![#(#key_tokens),*], - vec![#(#field_tokens),*], - None, - ::std::vec::Vec::new(), - ::std::vec::Vec::new(), - None, - ).expect("patch operation") - } - }) + let model = schema(model); + let key = expand_inputs(framework, keys); + let set = expand_inputs(framework, sets); + quote! { + #framework::MutationStep::Patch { model: #model, key: #key, set: #set } + } } } } diff --git a/distributed_macros/src/portable_command.rs b/distributed_macros/src/portable_command.rs deleted file mode 100644 index a1a2e6ed0..000000000 --- a/distributed_macros/src/portable_command.rs +++ /dev/null @@ -1,351 +0,0 @@ -//! `portable_command!` — domain command mounts (`PCH-DEC-001`). -//! -//! The handler attribute is already `#[command]`, so this function-like form -//! uses a distinct name. Spec sketches called it `command!`. - -use proc_macro2::TokenStream; -use quote::{format_ident, quote}; -use syn::parse::{Parse, ParseStream}; -use syn::{parenthesized, Expr, Ident, LitStr, Token, Type}; - -struct AuthenticatedUserField { - event: Type, - state: Type, - field: LitStr, -} - -impl Parse for AuthenticatedUserField { - fn parse(input: ParseStream<'_>) -> syn::Result { - let values; - parenthesized!(values in input); - let event = values.parse()?; - values.parse::()?; - let state = values.parse()?; - values.parse::()?; - let field = values.parse()?; - if !values.is_empty() { - return Err(values - .error("authenticated_user_field expects (EventType, StateType, \"field_name\")")); - } - Ok(Self { - event, - state, - field, - }) - } -} - -struct PortableCommandArgs { - name: LitStr, - transition: Type, - aggregate: Type, - input: Type, - outcome: Type, - shard: Expr, - field: LitStr, - roles: Vec, - load: LoadKind, - invoke: Option, - payload: Option, - handle: Option, - guard: Option, - defaults: Option, - constructor: Option, - authenticated_user_field: Option, - preview_reduce_known_record: Option, -} - -enum LoadKind { - Required, - Create, - None, -} - -impl Parse for PortableCommandArgs { - fn parse(input: ParseStream<'_>) -> syn::Result { - let mut name = None; - let mut transition = None; - let mut aggregate = None; - let mut input_ty = None; - let mut outcome = None; - let mut shard = None; - let mut field = None; - let mut roles = Vec::new(); - let mut load = LoadKind::None; - let mut invoke = None; - let mut payload = None; - let mut handle = None; - let mut guard = None; - let mut defaults = None; - let mut constructor = None; - let mut authenticated_user_field = None; - let mut preview_reduce_known_record = None; - - while !input.is_empty() { - let key: Ident = input.parse()?; - input.parse::()?; - match key.to_string().as_str() { - "name" => name = Some(input.parse()?), - "transition" => transition = Some(input.parse()?), - "aggregate" => aggregate = Some(input.parse()?), - "input" => input_ty = Some(input.parse()?), - "outcome" => outcome = Some(input.parse()?), - "shard" => shard = Some(input.parse()?), - "field" => field = Some(input.parse()?), - "invoke" => invoke = Some(input.parse()?), - "payload" => payload = Some(input.parse()?), - "handle" => handle = Some(input.parse()?), - "guard" => guard = Some(input.parse()?), - "defaults" => defaults = Some(input.parse()?), - "constructor" => constructor = Some(input.parse()?), - "authenticated_user_field" => authenticated_user_field = Some(input.parse()?), - "preview_reduce_known_record" => preview_reduce_known_record = Some(input.parse()?), - "load" => { - let ident: Ident = input.parse()?; - load = match ident.to_string().as_str() { - "required" => LoadKind::Required, - "create" => LoadKind::Create, - other => { - return Err(syn::Error::new( - ident.span(), - format!("load must be `required` or `create`, not `{other}`"), - )) - } - }; - } - "roles" => { - let expr: Expr = input.parse()?; - roles = lit_strs_from_array(&expr)?; - } - other => { - return Err(syn::Error::new( - key.span(), - format!("unknown portable_command key `{other}`"), - )) - } - } - if input.peek(Token![,]) { - input.parse::()?; - } - } - - let name = name.ok_or_else(|| input.error("portable_command requires `name: \"...\"`"))?; - Ok(Self { - name, - transition: transition - .ok_or_else(|| input.error("portable_command requires `transition:`"))?, - aggregate: aggregate - .ok_or_else(|| input.error("portable_command requires `aggregate:`"))?, - input: input_ty.ok_or_else(|| input.error("portable_command requires `input:`"))?, - outcome: outcome.ok_or_else(|| input.error("portable_command requires `outcome:`"))?, - shard: shard.ok_or_else(|| input.error("portable_command requires `shard:`"))?, - field: field.ok_or_else(|| input.error("portable_command requires `field:`"))?, - roles, - load, - invoke, - payload, - handle, - guard, - defaults, - constructor, - authenticated_user_field, - preview_reduce_known_record, - }) - } -} - -fn lit_strs_from_array(expr: &Expr) -> syn::Result> { - let Expr::Array(array) = expr else { - return Err(syn::Error::new_spanned( - expr, - "roles must be an array of string literals, e.g. [\"user\", \"admin\"]", - )); - }; - array - .elems - .iter() - .map(|elem| match elem { - Expr::Lit(syn::ExprLit { - lit: syn::Lit::Str(value), - .. - }) => Ok(value.clone()), - other => Err(syn::Error::new_spanned( - other, - "roles entries must be string literals", - )), - }) - .collect() -} - -fn names_from_command(name: &LitStr) -> syn::Result<(Ident, Ident)> { - let value = name.value(); - let last = value.rsplit('.').next().unwrap_or(value.as_str()); - if last.is_empty() || !last.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { - return Err(syn::Error::new( - name.span(), - "command name must end in a snake_case ident (e.g. todo.complete)", - )); - } - let pascal = last - .split('_') - .map(|part| { - let mut chars = part.chars(); - match chars.next() { - None => String::new(), - Some(first) => first.to_uppercase().collect::() + chars.as_str(), - } - }) - .collect::(); - Ok((format_ident!("{pascal}"), Ident::new(last, name.span()))) -} - -pub fn expand(input: TokenStream) -> syn::Result { - let framework = crate::shared::framework_path()?; - let args = syn::parse2::(input)?; - let (ty, default_ctor) = names_from_command(&args.name)?; - let ctor = args.constructor.as_ref().unwrap_or(&default_ctor); - let name = &args.name; - let transition = &args.transition; - let aggregate = &args.aggregate; - let input_ty = &args.input; - let outcome = &args.outcome; - let shard = &args.shard; - let field = &args.field; - let roles = &args.roles; - let defaults = args.defaults.as_ref().map(|defaults| { - quote! { .input_defaults(#defaults) } - }); - let authenticated_user_field = args.authenticated_user_field.as_ref().map(|value| { - let event = &value.event; - let state = &value.state; - let field = &value.field; - quote! { .authenticated_user_field::<#event, #state>(#field) } - }); - let preview_reduce_known_record = args - .preview_reduce_known_record - .as_ref() - .map(|preview| { - quote! { - .preview_reduce_known_record( - (#preview).declared_in_rust_package(env!("CARGO_PKG_NAME")) - ) - } - }); - - let install_body = if let Some(handle) = &args.handle { - if args.invoke.is_some() || args.payload.is_some() { - return Err(syn::Error::new_spanned( - handle, - "handle: is the escape hatch; do not also set invoke:/payload:", - )); - } - let finish = match &args.guard { - Some(guard) => quote! { .guarded(#guard, #handle) }, - None => quote! { .handle(#handle) }, - }; - quote! { - routes - .command_transition::<#transition, #input_ty, #outcome>(Self::COMMAND) - .field_name(#field) - .roles([#(#roles),*].into_iter()) - #defaults - #authenticated_user_field - #preview_reduce_known_record - #finish - } - } else { - let invoke = args.invoke.as_ref().ok_or_else(|| { - syn::Error::new( - proc_macro2::Span::call_site(), - "thin portable_command requires `invoke:` (or `handle:` as the escape hatch)", - ) - })?; - let payload = args.payload.as_ref().ok_or_else(|| { - syn::Error::new( - proc_macro2::Span::call_site(), - "thin portable_command requires `payload:` (or `handle:` as the escape hatch)", - ) - })?; - if args.guard.is_some() { - return Err(syn::Error::new( - proc_macro2::Span::call_site(), - "guard: is only valid with handle:; thin commands admit via roles", - )); - } - let load = match args.load { - LoadKind::Required => quote! { .load_by(|input: &#input_ty| Self::shard(input)) }, - LoadKind::Create => quote! { .create() }, - LoadKind::None => { - return Err(syn::Error::new( - proc_macro2::Span::call_site(), - "thin portable_command requires `load: required` or `load: create`", - )) - } - }; - let finish = thin_finish(outcome, payload)?; - quote! { - routes - .command_transition::<#transition, #input_ty, #outcome>(Self::COMMAND) - .field_name(#field) - .roles([#(#roles),*].into_iter()) - #defaults - #authenticated_user_field - #preview_reduce_known_record - #load - .invoke(#invoke) - #finish - } - }; - - Ok(quote! { - pub struct #ty; - - pub fn #ctor() -> #ty { - #ty - } - - impl #ty { - pub const COMMAND: &'static str = #name; - - pub fn shard(input: &#input_ty) -> String { - let shard: fn(&#input_ty) -> String = #shard; - shard(input) - } - } - - impl #framework::microsvc::PortableCommand for #ty - where - D: #framework::microsvc::CausalRouteDependencies - + Send - + Sync - + 'static, - { - fn install(self, routes: #framework::microsvc::Routes) -> #framework::microsvc::Routes { - #install_body - } - } - }) -} - -fn thin_finish(outcome: &Type, payload: &Expr) -> syn::Result { - let last = match outcome { - Type::Path(path) => path - .path - .segments - .last() - .map(|segment| segment.ident.to_string()), - _ => None, - }; - match last.as_deref() { - Some("Eventual") => Ok(quote! { .eventual(#payload) }), - Some("Succeeded") => Ok(quote! { .succeeded(#payload) }), - Some("Atomic") => Err(syn::Error::new_spanned( - outcome, - "thin portable_command does not yet support Atomic; use handle:", - )), - _ => Err(syn::Error::new_spanned( - outcome, - "thin portable_command outcome must be Eventual<...> or Succeeded<...>", - )), - } -} diff --git a/distributed_macros/src/read_model/attrs.rs b/distributed_macros/src/read_model/attrs.rs index a21bcb703..1ad5abda4 100644 --- a/distributed_macros/src/read_model/attrs.rs +++ b/distributed_macros/src/read_model/attrs.rs @@ -2,7 +2,8 @@ use quote::quote; use syn::{Attribute, DeriveInput, Expr, ExprArray, ExprLit, Field, Lit, LitStr, Meta, Token}; use super::types::{ - option_inner_type, option_string_tokens, validate_relationship_target_type, vec_inner_type, + box_inner_type, option_inner_type, option_string_tokens, validate_relationship_target_type, + vec_inner_type, }; #[derive(Default)] @@ -98,6 +99,7 @@ impl FieldAttrs { pub(super) fn from_field(field: &Field) -> syn::Result { let mut attrs = Self::default(); let mut pending_foreign_key: Option = None; + let mut pending_references: Option = None; let mut pending_through: Option = None; let mut pending_target_foreign_key: Option = None; for attr in &field.attrs { @@ -152,10 +154,7 @@ impl FieldAttrs { attrs.jsonb = true; } else if meta.path.is_ident("text") { attrs.text = true; - } else if meta.path.is_ident("skip_query") - || meta.path.is_ident("skip") - || meta.path.is_ident("private") - { + } else if meta.path.is_ident("skip_query") { attrs.skip_query = true; } else if meta.path.is_ident("nullable") { attrs.nullable = true; @@ -164,6 +163,11 @@ impl FieldAttrs { if meta.input.peek(Token![=]) { attrs.default = Some(meta.value()?.parse::()?.value()); } + } else if meta.path.is_ident("references") { + if pending_references.is_some() { + return Err(meta.error("relationship references declared more than once")); + } + pending_references = Some(meta.value()?.parse::()?.value()); } else if meta.path.is_ident("foreign_key") { let value = meta.value()?.parse::()?.value(); if attrs.relationship.is_some() { @@ -184,6 +188,7 @@ impl FieldAttrs { } else if meta.path.is_ident("has_many") { let target = meta.value()?.parse::()?.value(); attrs.relationship = Some(RelationshipAttr { + references: None, kind: RelationshipKindAttr::HasMany, target_model: target, foreign_key: None, @@ -193,6 +198,7 @@ impl FieldAttrs { } else if meta.path.is_ident("belongs_to") { let target = meta.value()?.parse::()?.value(); attrs.relationship = Some(RelationshipAttr { + references: None, kind: RelationshipKindAttr::BelongsTo, target_model: target, foreign_key: None, @@ -202,6 +208,7 @@ impl FieldAttrs { } else if meta.path.is_ident("many_to_many") { let target = meta.value()?.parse::()?.value(); attrs.relationship = Some(RelationshipAttr { + references: None, kind: RelationshipKindAttr::ManyToMany, target_model: target, foreign_key: None, @@ -292,6 +299,19 @@ impl FieldAttrs { } } + if let Some(references) = pending_references { + let relationship = attrs.relationship.as_mut().ok_or_else(|| { + syn::Error::new_spanned(field, "`references` requires a direct relationship") + })?; + if matches!(relationship.kind, RelationshipKindAttr::ManyToMany) { + return Err(syn::Error::new_spanned( + field, + "`references` requires a direct relationship", + )); + } + relationship.references = Some(references); + } + if attrs.jsonb && attrs.text { return Err(syn::Error::new_spanned( field, @@ -320,6 +340,7 @@ impl FieldAttrs { &self, field_name: &str, ) -> syn::Result> { + let framework = crate::shared::framework(); let Some(relationship) = &self.relationship else { return Ok(None); }; @@ -330,17 +351,19 @@ impl FieldAttrs { )); }; let target_model = &relationship.target_model; + let references = option_string_tokens(relationship.references.as_deref()); let through = option_string_tokens(relationship.through.as_deref()); let target_foreign_key = option_string_tokens(relationship.target_foreign_key.as_deref()); let kind = match relationship.kind { - RelationshipKindAttr::HasMany => quote! { distributed::RelationshipKind::HasMany }, - RelationshipKindAttr::BelongsTo => quote! { distributed::RelationshipKind::BelongsTo }, + RelationshipKindAttr::HasMany => quote! { #framework::RelationshipKind::HasMany }, + RelationshipKindAttr::BelongsTo => quote! { #framework::RelationshipKind::BelongsTo }, RelationshipKindAttr::ManyToMany => { - quote! { distributed::RelationshipKind::ManyToMany } + quote! { #framework::RelationshipKind::ManyToMany } } }; Ok(Some(quote! { - distributed::RelationshipDef { + #framework::RelationshipDef { + references: #references, field_name: #field_name.to_string(), kind: #kind, target_model: #target_model.to_string(), @@ -360,6 +383,7 @@ impl FieldAttrs { proc_macro2::TokenStream, proc_macro2::TokenStream, )> { + let framework = crate::shared::framework(); let relationship = self.relationship.as_ref().ok_or_else(|| { syn::Error::new_spanned(field, "field is not a read-model relationship") })?; @@ -386,8 +410,8 @@ impl FieldAttrs { #field_name => { self.#ident = rows .into_iter() - .map(<#inner as distributed::RelationalReadModel>::from_row) - .collect::, distributed::TableStoreError>>()?; + .map(<#inner as #framework::RelationalReadModel>::from_row) + .collect::, #framework::TableStoreError>>()?; Ok(()) } }; @@ -395,11 +419,11 @@ impl FieldAttrs { #field_name => self .#ident .iter() - .map(distributed::RelationalReadModel::to_row) - .collect::, distributed::TableStoreError>>() + .map(#framework::RelationalReadModel::to_row) + .collect::, #framework::TableStoreError>>() }; let include_schema = quote! { - #field_name => Ok(<#inner as distributed::RelationalReadModel>::schema()) + #field_name => Ok(<#inner as #framework::RelationalReadModel>::schema()) }; Ok((hydrate, include_rows, include_schema)) } @@ -412,21 +436,33 @@ impl FieldAttrs { ), ) })?; + let boxed = box_inner_type(inner); + let inner = boxed.unwrap_or(inner); validate_relationship_target_type( field, inner, &relationship.target_model, field_name, )?; + let hydrated_value = if boxed.is_some() { + quote! { ::std::boxed::Box::new(<#inner as #framework::RelationalReadModel>::from_row(row)?) } + } else { + quote! { <#inner as #framework::RelationalReadModel>::from_row(row)? } + }; + let included_value = if boxed.is_some() { + quote! { value.as_ref() } + } else { + quote! { value } + }; let hydrate = quote! { #field_name => { let mut rows = rows.into_iter(); self.#ident = match rows.next() { - Some(row) => Some(<#inner as distributed::RelationalReadModel>::from_row(row)?), + Some(row) => Some(#hydrated_value), None => None, }; if rows.next().is_some() { - return Err(distributed::TableStoreError::Metadata(format!( + return Err(#framework::TableStoreError::Metadata(format!( "belongs_to relationship `{}` returned more than one row", #field_name ))); @@ -438,13 +474,13 @@ impl FieldAttrs { #field_name => { let mut rows = Vec::new(); if let Some(value) = &self.#ident { - rows.push(distributed::RelationalReadModel::to_row(value)?); + rows.push(#framework::RelationalReadModel::to_row(#included_value)?); } Ok(rows) } }; let include_schema = quote! { - #field_name => Ok(<#inner as distributed::RelationalReadModel>::schema()) + #field_name => Ok(<#inner as #framework::RelationalReadModel>::schema()) }; Ok((hydrate, include_rows, include_schema)) } @@ -472,6 +508,7 @@ pub(super) struct ForeignKeyParts { #[derive(Clone)] pub(super) struct RelationshipAttr { + pub(super) references: Option, pub(super) kind: RelationshipKindAttr, pub(super) target_model: String, pub(super) foreign_key: Option, @@ -578,10 +615,11 @@ fn parse_foreign_key(value: &str) -> syn::Result { } pub(super) fn foreign_key_tokens(foreign_key: &ForeignKeyParts) -> proc_macro2::TokenStream { + let framework = crate::shared::framework(); let table = &foreign_key.table; let column = &foreign_key.column; quote! { - distributed::ForeignKey { + #framework::ForeignKey { table: #table.to_string(), column: #column.to_string(), } diff --git a/distributed_macros/src/read_model/mod.rs b/distributed_macros/src/read_model/mod.rs index daa77e040..fc2f1734f 100644 --- a/distributed_macros/src/read_model/mod.rs +++ b/distributed_macros/src/read_model/mod.rs @@ -19,6 +19,7 @@ pub fn derive_read_model(input: TokenStream) -> TokenStream { } pub(crate) fn expand_read_model(input: DeriveInput) -> syn::Result { + let framework = crate::shared::framework_path()?; let name = &input.ident; let visibility = &input.vis; let struct_attrs = StructAttrs::from_input(&input)?; @@ -40,7 +41,7 @@ pub(crate) fn expand_read_model(input: DeriveInput) -> syn::Result &str { diff --git a/distributed_macros/src/read_model/relational.rs b/distributed_macros/src/read_model/relational.rs index 13ccb55ed..4bde39024 100644 --- a/distributed_macros/src/read_model/relational.rs +++ b/distributed_macros/src/read_model/relational.rs @@ -8,8 +8,8 @@ use crate::shared::{ use super::attrs::{foreign_key_tokens, FieldAttrs, RelationshipKindAttr, StructAttrs}; use super::types::{ - bytes_row_value_tokens, column_type_tokens, default_storage_name, effect_model_wire_tokens, - option_inner_type, option_string_tokens, vec_inner_type, + box_inner_type, bytes_row_value_tokens, column_type_tokens, default_storage_name, + effect_model_wire_tokens, option_inner_type, option_string_tokens, vec_inner_type, }; pub(super) fn expand_relational_read_model( @@ -20,6 +20,7 @@ pub(super) fn expand_relational_read_model( field_attrs: &[FieldAttrs], id_field: Option<&syn::Ident>, ) -> syn::Result { + let framework = crate::shared::framework(); let rust_name = name.to_string(); let model_name = struct_attrs .name @@ -38,50 +39,28 @@ pub(super) fn expand_relational_read_model( .map(|column| quote! { #column.to_string() }) .collect::>(); - let effect_key_name = format_ident!("__Distributed{}EffectKey", name); - let mut effect_key_fields = Vec::new(); - let mut effect_key_values = Vec::new(); for primary_key_column in &primary_key_fields { - let (field, _attrs) = fields - .iter() - .zip(field_attrs) - .find(|(field, attrs)| { - if attrs.relationship.is_some() || attrs.skip_query { - return false; - } - let Some(ident) = &field.ident else { - return false; - }; + let has_field = fields.iter().zip(field_attrs).any(|(field, attrs)| { + if attrs.relationship.is_some() || attrs.skip_query { + return false; + } + field.ident.as_ref().is_some_and(|ident| { let field_name = ident.to_string(); attrs.column.as_deref().unwrap_or(&field_name) == primary_key_column }) - .ok_or_else(|| { - syn::Error::new( - proc_macro2::Span::call_site(), - format!( - "primary-key column `{primary_key_column}` has no effect-key field on `{model_name}`" - ), - ) - })?; - let ident = field - .ident - .as_ref() - .expect("named read-model fields were validated"); - let ty = &field.ty; - let marker = format_ident!("__Distributed{}EffectModelField_{}", name, ident); - effect_key_fields.push(quote! { - pub #ident: distributed::graphql::TypedEffectExpression<#ty> - }); - effect_key_values.push(quote! { - distributed::graphql::__effect_key_field::<#marker>(value.#ident) }); + if !has_field { + return Err(syn::Error::new( + proc_macro2::Span::call_site(), + format!("primary-key column `{primary_key_column}` has no field on `{model_name}`"), + )); + } } let mut column_defs = Vec::new(); let mut row_inserts = Vec::new(); let mut row_fields = Vec::new(); let mut key_inserts = Vec::new(); - let mut foreign_keys = Vec::new(); let mut indexes = Vec::new(); let mut relationships = Vec::new(); let mut hydrate_include_arms = Vec::new(); @@ -114,7 +93,9 @@ pub(super) fn expand_relational_read_model( vec_inner_type(&field.ty).expect("relationship shape was validated") } RelationshipKindAttr::BelongsTo => { - option_inner_type(&field.ty).expect("relationship shape was validated") + let inner = + option_inner_type(&field.ty).expect("relationship shape was validated"); + box_inner_type(inner).unwrap_or(inner) } }; let marker = format_ident!("__Distributed{}EffectRelationship_{}", name, ident); @@ -123,13 +104,13 @@ pub(super) fn expand_relational_read_model( #[allow(non_camel_case_types)] #visibility struct #marker; - impl distributed::graphql::EffectRelationshipMarker for #marker { + impl #framework::command::EffectRelationshipMarker for #marker { type Source = #name; type Target = #target_ty; const FIELD: &'static str = #field_name; } - impl distributed::projection::lower::ProjectionRelationshipMetadata for #marker { + impl #framework::projection::lower::ProjectionRelationshipMetadata for #marker { type Source = #name; type Target = #target_ty; const FIELD: &'static str = #field_name; @@ -153,7 +134,7 @@ pub(super) fn expand_relational_read_model( #[allow(non_camel_case_types)] #visibility struct #effect_marker; - impl distributed::graphql::EffectModelFieldMarker for #effect_marker { + impl #framework::command::EffectModelFieldMarker for #effect_marker { type Model = #name; type Value = #field_ty; type Wire = #effect_wire; @@ -166,17 +147,14 @@ pub(super) fn expand_relational_read_model( let nullable = attrs.nullable || option_inner_type(&field.ty).is_some(); let column_type = column_type_tokens(&field.ty, attrs.jsonb, attrs.text); let default_tokens = option_string_tokens(attrs.default.as_deref()); - let foreign_key_value = attrs.foreign_key.as_ref().map(foreign_key_tokens); - let foreign_key = foreign_key_value + let foreign_key = attrs + .foreign_key .as_ref() + .map(foreign_key_tokens) .map(|foreign_key| quote! { Some(#foreign_key) }) .unwrap_or_else(|| quote! { None }); - if let Some(foreign_key) = &foreign_key_value { - foreign_keys.push(foreign_key.clone()); - } let delegated_from = option_string_tokens(attrs.delegated_from.as_deref()); let has_default = attrs.has_default; - let jsonb = attrs.jsonb; let projection_metadata = projection_field_metadata(field)?; let rust_type = projection_metadata.rust_type; let portable_kind = syn::Ident::new( @@ -189,12 +167,12 @@ pub(super) fn expand_relational_read_model( field_name, column_name, rust_type, portable_kind, nullable, required, primary_key )); projection_fields.push(quote! { - distributed::projection::lower::ProjectionModelFieldMetadata { + #framework::projection::lower::ProjectionModelFieldMetadata { field_name: #field_name, column_name: #column_name, rust_type: #rust_type, portable_type: - distributed::projection::lower::ProjectionPortableType::#portable_kind, + #framework::projection::lower::ProjectionPortableType::#portable_kind, nullable: #nullable, required: #required, primary_key: #primary_key, @@ -202,7 +180,7 @@ pub(super) fn expand_relational_read_model( }); column_defs.push(quote! { - distributed::TableColumn { + #framework::TableColumn { field_name: #field_name.to_string(), column_name: #column_name.to_string(), column_type: #column_type, @@ -212,7 +190,6 @@ pub(super) fn expand_relational_read_model( primary_key: #primary_key, foreign_key: #foreign_key, delegated_from: #delegated_from, - jsonb: #jsonb, skipped: false, } }); @@ -221,7 +198,7 @@ pub(super) fn expand_relational_read_model( row_inserts.push(quote! { row.insert( #column_name, - distributed::RowValue::from_text_serde( + #framework::RowValue::from_text_serde( &self.#ident, #nullable, #column_name, @@ -246,7 +223,7 @@ pub(super) fn expand_relational_read_model( key_inserts.push(quote! { key.values.insert( #column_name.to_string(), - distributed::RowValue::from_text_serde( + #framework::RowValue::from_text_serde( &self.#ident, #nullable, #column_name, @@ -261,7 +238,7 @@ pub(super) fn expand_relational_read_model( key_inserts.push(quote! { key.values.insert( #column_name.to_string(), - distributed::RowValue::from_serde(&self.#ident)?, + #framework::RowValue::from_serde(&self.#ident)?, ); }); } @@ -304,77 +281,62 @@ pub(super) fn expand_relational_read_model( syn::LitStr::new(&projection_schema_fingerprint, Span::call_site()); Ok(quote! { - #[doc(hidden)] - #[allow(non_camel_case_types)] - #visibility struct #effect_key_name { - #(#effect_key_fields),* - } - - impl ::core::convert::From<#effect_key_name> - for distributed::graphql::TypedEffectKey<#name> - { - fn from(value: #effect_key_name) -> Self { - distributed::graphql::__effect_key::<#name>(vec![#(#effect_key_values),*]) - } - } - #(#effect_markers)* - impl distributed::RelationalReadModel for #name { - fn schema() -> &'static distributed::TableSchema { - static SCHEMA: ::std::sync::LazyLock = - ::std::sync::LazyLock::new(|| distributed::TableSchema { + impl #framework::RelationalReadModel for #name { + fn schema() -> &'static #framework::TableSchema { + static SCHEMA: ::std::sync::LazyLock<#framework::TableSchema> = + ::std::sync::LazyLock::new(|| #framework::TableSchema { model_name: #model_name.to_string(), table_name: #table_name.to_string(), columns: vec![#(#column_defs),*], - primary_key: distributed::PrimaryKey { + primary_key: #framework::PrimaryKey { columns: vec![#(#primary_key_columns),*], }, - version_column: Some(distributed::DEFAULT_TABLE_VERSION_COLUMN.to_string()), - foreign_keys: vec![#(#foreign_keys),*], + version_column: Some(#framework::DEFAULT_TABLE_VERSION_COLUMN.to_string()), indexes: vec![#(#indexes),*], relationships: vec![#(#relationships),*], - kind: distributed::TableKind::ReadModel, + kind: #framework::TableKind::ReadModel, }); &SCHEMA } - fn primary_key(&self) -> Result { - let mut key = distributed::RowKey::default(); + fn primary_key(&self) -> Result<#framework::RowKey, #framework::TableStoreError> { + let mut key = #framework::RowKey::default(); #(#key_inserts)* Ok(key) } - fn to_row(&self) -> Result { - let mut row = distributed::RowValues::new(); + fn to_row(&self) -> Result<#framework::RowValues, #framework::TableStoreError> { + let mut row = #framework::RowValues::new(); #(#row_inserts)* Ok(row) } - fn from_row(row: distributed::RowValues) -> Result { + fn from_row(row: #framework::RowValues) -> Result { Ok(Self { #(#row_fields),* }) } } - impl distributed::projection::lower::ProjectionReadModelMetadata for #name { + impl #framework::projection::lower::ProjectionReadModelMetadata for #name { const PROJECTION_FIELDS: &'static [ - distributed::projection::lower::ProjectionModelFieldMetadata + #framework::projection::lower::ProjectionModelFieldMetadata ] = &[#(#projection_fields),*]; const PROJECTION_SCHEMA_FINGERPRINT: &'static str = #projection_schema_fingerprint; } - impl distributed::RelationalReadModelIncludes for #name { + impl #framework::RelationalReadModelIncludes for #name { fn hydrate_include( &mut self, include: &str, - rows: Vec, - ) -> Result<(), distributed::TableStoreError> { + rows: Vec<#framework::RowValues>, + ) -> Result<(), #framework::TableStoreError> { match include { #(#hydrate_include_arms,)* - _ => Err(distributed::TableStoreError::Metadata(format!( + _ => Err(#framework::TableStoreError::Metadata(format!( "read model `{}` has no hydratable relationship `{}`", #model_name, include @@ -385,10 +347,10 @@ pub(super) fn expand_relational_read_model( fn include_rows( &self, include: &str, - ) -> Result, distributed::TableStoreError> { + ) -> Result, #framework::TableStoreError> { match include { #(#include_rows_arms,)* - _ => Err(distributed::TableStoreError::Metadata(format!( + _ => Err(#framework::TableStoreError::Metadata(format!( "read model `{}` has no tracked relationship `{}`", #model_name, include @@ -398,10 +360,10 @@ pub(super) fn expand_relational_read_model( fn include_target_schema( include: &str, - ) -> Result<&'static distributed::TableSchema, distributed::TableStoreError> { + ) -> Result<&'static #framework::TableSchema, #framework::TableStoreError> { match include { #(#include_schema_arms,)* - _ => Err(distributed::TableStoreError::Metadata(format!( + _ => Err(#framework::TableStoreError::Metadata(format!( "read model `{}` has no tracked relationship `{}`", #model_name, include @@ -464,13 +426,14 @@ fn index_def_tokens( index_columns: Vec, unique: bool, ) -> proc_macro2::TokenStream { + let framework = crate::shared::framework(); let columns = index_columns .iter() .map(|column| quote! { #column.to_string() }) .collect::>(); quote! { - distributed::TableIndex { + #framework::TableIndex { name: Some(#index_name.to_string()), columns: vec![#(#columns),*], unique: #unique, diff --git a/distributed_macros/src/read_model/tests.rs b/distributed_macros/src/read_model/tests.rs index 9cffb946d..41dc84cab 100644 --- a/distributed_macros/src/read_model/tests.rs +++ b/distributed_macros/src/read_model/tests.rs @@ -3,188 +3,34 @@ use super::*; use syn::DeriveInput; #[test] -fn expand_read_model_accepts_named_id_field() { - let input: DeriveInput = syn::parse_quote! { - struct CounterView { - id: String, - value: i32, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("impl distributed :: ReadModel for CounterView")); - assert!(expanded.contains("fn id")); -} - -#[test] -fn expand_read_model_accepts_explicit_id_attribute() { - let input: DeriveInput = syn::parse_quote! { - struct CounterView { - id: String, - #[readmodel(id)] - counter_id: String, - value: i32, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("& self . counter_id")); - assert!(!expanded.contains("& self . id")); -} - -#[test] -fn expand_read_model_accepts_declared_name() { - let input: DeriveInput = syn::parse_quote! { - #[readmodel(name = "operational.todos", table = "operational_todos")] - struct OperationalTodos { - #[readmodel(id)] - todo_id: String, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - assert!( - expanded.contains("operational.todos") || expanded.contains("operational . todos"), - "{expanded}" - ); - assert!(!expanded.contains("model_name : \"OperationalTodos\"")); - assert!( - expanded.contains("operational_todos"), - "default table must come from the Rust type, not the declared name: {expanded}" - ); -} - -#[test] -fn expand_read_model_accepts_direct_collection_attribute() { - let input: DeriveInput = syn::parse_quote! { - #[collection("counter_views")] - struct CounterView { - #[id] - counter_id: String, - value: i32, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("const COLLECTION : & 'static str = \"counter_views\"")); - assert!(expanded.contains("& self . counter_id")); -} - -#[test] -fn expand_read_model_accepts_direct_table_and_id_column_attributes() { - let input: DeriveInput = syn::parse_quote! { - #[table = "counter_views"] - struct CounterView { - #[id("counter_id")] - id: String, - value: i32, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("table_name : \"counter_views\"")); - assert!(expanded.contains("column_name : \"counter_id\"")); -} - -#[test] -fn expand_read_model_accepts_direct_column_attribute() { - let input: DeriveInput = syn::parse_quote! { - #[table("counter_views")] - struct CounterView { - #[id] - id: String, - #[column("counter_value")] - value: i32, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("column_name : \"counter_value\"")); -} - -#[test] -fn expand_read_model_accepts_direct_index_attribute() { - let input: DeriveInput = syn::parse_quote! { - #[table("counter_views")] - struct CounterView { - #[id] - id: String, - #[index("idx_counter_views_value")] - value: i32, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("name : Some (\"idx_counter_views_value\"")); - assert!(expanded.contains("columns : vec ! [\"value\"")); - assert!(expanded.contains("unique : false")); +fn direct_relationship_references_need_one_belongs_to() { + for attributes in [ + "references = \"id\"", + "belongs_to = \"Object\", foreign_key = \"id\", references = \"id\", references = \"id\"", + "many_to_many = \"Object\", foreign_key = \"id\", through = \"links\", references = \"id\"", + ] { + let input = syn::parse_str(&format!( + "struct Ref {{ id: String, #[readmodel({attributes})] object: Option }}" + )) + .unwrap(); + assert!(expand_read_model(input).is_err(), "accepted {attributes}"); + } } #[test] -fn expand_read_model_accepts_direct_unique_attribute() { - let input: DeriveInput = syn::parse_quote! { - #[table("counter_views")] - struct CounterView { - #[id] - id: String, - #[unique("uq_counter_views_slug")] - slug: String, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("name : Some (\"uq_counter_views_slug\"")); - assert!(expanded.contains("columns : vec ! [\"slug\"")); - assert!(expanded.contains("unique : true")); -} - -#[test] -fn expand_read_model_accepts_struct_compound_index_attribute() { - let input: DeriveInput = syn::parse_quote! { - #[table("account_summaries")] - #[index(name = "idx_account_summaries_owner_created", columns = ["owner", "created_at"])] - struct AccountSummary { - #[id("account_id")] - id: String, - owner: String, - #[column("created_at_utc")] - created_at: String, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("name : Some (\"idx_account_summaries_owner_created\"")); - assert!(expanded.contains("columns : vec ! [\"owner\" . to_string () , \"created_at_utc\"")); - assert!(expanded.contains("unique : false")); -} - -#[test] -fn expand_read_model_accepts_struct_compound_unique_attribute() { - let input: DeriveInput = syn::parse_quote! { - #[table("accounts")] - #[unique(columns = ["tenant_id", "slug"])] - struct AccountSummary { - #[id("account_id")] - id: String, - tenant_id: String, - slug: String, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("name : Some (\"uq_accounts_tenant_id_slug\"")); - assert!(expanded.contains("columns : vec ! [\"tenant_id\"")); - assert!(expanded.contains("\"slug\"")); - assert!(expanded.contains("unique : true")); +fn boxed_belongs_to_rejects_anything_but_one_box_of_the_target() { + for ty in [ + "Option>", + "Option>>", + "Option>", + "Box", + "Vec>", + ] { + let input: DeriveInput = syn::parse_str(&format!( + "struct Parent {{ id: String, #[readmodel(belongs_to = \"Child\", foreign_key = \"id\")] child: {ty} }}" + )).unwrap(); + assert!(expand_read_model(input).is_err(), "accepted {ty}"); + } } #[test] @@ -242,23 +88,6 @@ fn expand_read_model_rejects_missing_id_field_for_document_models() { ); } -#[test] -fn expand_read_model_allows_composite_relational_models_without_string_id() { - let input: DeriveInput = syn::parse_quote! { - #[readmodel(table = "player_weapons", primary_key = ["player_id", "weapon_id"])] - struct PlayerWeapon { - #[readmodel(foreign_key = "players.player_id", delegated_from = "Player.player_id")] - player_id: String, - weapon_id: String, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("impl distributed :: RelationalReadModel for PlayerWeapon")); - assert!(!expanded.contains("impl distributed :: ReadModel for PlayerWeapon")); -} - #[test] fn expand_read_model_rejects_multiple_explicit_id_attributes() { let input: DeriveInput = syn::parse_quote! { @@ -318,43 +147,6 @@ fn expand_read_model_rejects_unknown_field_attributes() { ); } -#[test] -fn expand_read_model_accepts_relationship_metadata_before_relationship_kind() { - let input: DeriveInput = syn::parse_quote! { - #[readmodel(table = "players")] - struct Player { - #[readmodel(id, column = "player_id")] - id: String, - #[readmodel(foreign_key = "player_id", has_many = "PlayerWeapon")] - weapons: Vec, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("RelationshipKind :: HasMany")); - assert!(expanded.contains("foreign_key : Some (\"player_id\"")); -} - -#[test] -fn expand_read_model_accepts_through_before_many_to_many() { - let input: DeriveInput = syn::parse_quote! { - #[readmodel(table = "players")] - struct Player { - #[readmodel(id, column = "player_id")] - id: String, - #[readmodel(through = "player_weapon_links", foreign_key = "player_id", many_to_many = "Weapon")] - weapons: Vec, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!(expanded.contains("RelationshipKind :: ManyToMany")); - assert!(expanded.contains("through : Some (\"player_weapon_links\"")); - assert!(expanded.contains("foreign_key : Some (\"player_id\"")); -} - #[test] fn expand_read_model_rejects_tuple_structs() { let input: DeriveInput = syn::parse_quote! { @@ -467,22 +259,3 @@ fn default_storage_name_treats_ambiguous_terminal_s_as_plural() { assert_eq!(actual, expected); } - -#[test] -fn expand_read_model_shares_natural_default_between_document_and_relational_metadata() { - let input: DeriveInput = syn::parse_quote! { - struct BlobGames { - #[id] - game_id: String, - #[index] - owner_id: String, - } - }; - - let expanded = expand_read_model(input).unwrap().to_string(); - - assert!( - expanded.contains("const COLLECTION : & 'static str = \"blob_games\"") - && expanded.contains("table_name : \"blob_games\"") - ); -} diff --git a/distributed_macros/src/read_model/types.rs b/distributed_macros/src/read_model/types.rs index f500a2554..e4a10a12a 100644 --- a/distributed_macros/src/read_model/types.rs +++ b/distributed_macros/src/read_model/types.rs @@ -9,43 +9,44 @@ pub(super) fn option_string_tokens(value: Option<&str>) -> proc_macro2::TokenStr } pub(super) fn column_type_tokens(ty: &Type, jsonb: bool, text: bool) -> proc_macro2::TokenStream { + let framework = crate::shared::framework(); if jsonb { - return quote! { distributed::ColumnType::Json }; + return quote! { #framework::ColumnType::Json }; } if text { - return quote! { distributed::ColumnType::Text }; + return quote! { #framework::ColumnType::Text }; } let ty = option_inner_type(ty).unwrap_or(ty); if let Some(last) = last_type_segment(ty) { let ident = last.ident.to_string(); return match ident.as_str() { - "String" | "str" => quote! { distributed::ColumnType::Text }, - "bool" => quote! { distributed::ColumnType::Boolean }, + "String" | "str" => quote! { #framework::ColumnType::Text }, + "bool" => quote! { #framework::ColumnType::Boolean }, "i8" | "i16" | "i32" | "i64" | "isize" => { - quote! { distributed::ColumnType::Integer } + quote! { #framework::ColumnType::Integer } } "u8" | "u16" | "u32" | "u64" | "usize" => { - quote! { distributed::ColumnType::UnsignedInteger } + quote! { #framework::ColumnType::UnsignedInteger } } - "f32" | "f64" => quote! { distributed::ColumnType::Float }, + "f32" | "f64" => quote! { #framework::ColumnType::Float }, "Vec" => { if vec_inner_is_u8(last) { - quote! { distributed::ColumnType::Bytes } + quote! { #framework::ColumnType::Bytes } } else { - quote! { distributed::ColumnType::Json } + quote! { #framework::ColumnType::Json } } } - "HashMap" | "BTreeMap" | "Value" => quote! { distributed::ColumnType::Json }, + "HashMap" | "BTreeMap" | "Value" => quote! { #framework::ColumnType::Json }, _ => { let type_name = ty.to_token_stream().to_string(); - quote! { distributed::ColumnType::Unsupported(#type_name.to_string()) } + quote! { #framework::ColumnType::Unsupported(#type_name.to_string()) } } }; } let type_name = ty.to_token_stream().to_string(); - quote! { distributed::ColumnType::Unsupported(#type_name.to_string()) } + quote! { #framework::ColumnType::Unsupported(#type_name.to_string()) } } pub(super) fn effect_model_wire_tokens( @@ -53,28 +54,29 @@ pub(super) fn effect_model_wire_tokens( jsonb: bool, text: bool, ) -> proc_macro2::TokenStream { + let framework = crate::shared::framework(); if jsonb { - return quote! { distributed::graphql::EffectWireJson }; + return quote! { #framework::command::EffectWireJson }; } if text { - return quote! { distributed::graphql::EffectWireString }; + return quote! { #framework::command::EffectWireString }; } let ty = option_inner_type(ty).unwrap_or(ty); let Some(last) = last_type_segment(ty) else { - return quote! { distributed::graphql::EffectWireUnsupported }; + return quote! { #framework::command::EffectWireUnsupported }; }; match last.ident.to_string().as_str() { - "String" | "str" => quote! { distributed::graphql::EffectWireString }, - "bool" => quote! { distributed::graphql::EffectWireBoolean }, + "String" | "str" => quote! { #framework::command::EffectWireString }, + "bool" => quote! { #framework::command::EffectWireBoolean }, "i8" | "i16" | "i32" | "i64" | "isize" | "u8" | "u16" | "u32" | "u64" | "usize" => { - quote! { distributed::graphql::EffectWireBigInt } + quote! { #framework::command::EffectWireBigInt } } - "f32" | "f64" => quote! { distributed::graphql::EffectWireFloat }, - "Vec" if vec_inner_is_u8(last) => quote! { distributed::graphql::EffectWireBytea }, + "f32" | "f64" => quote! { #framework::command::EffectWireFloat }, + "Vec" if vec_inner_is_u8(last) => quote! { #framework::command::EffectWireBytea }, "Vec" | "HashMap" | "BTreeMap" | "Value" => { - quote! { distributed::graphql::EffectWireJson } + quote! { #framework::command::EffectWireJson } } - _ => quote! { distributed::graphql::EffectWireUnsupported }, + _ => quote! { #framework::command::EffectWireUnsupported }, } } @@ -82,6 +84,7 @@ pub(super) fn bytes_row_value_tokens( ty: &Type, value: proc_macro2::TokenStream, ) -> Option { + let framework = crate::shared::framework(); let option_inner = option_inner_type(ty); let ty = option_inner.unwrap_or(ty); let segment = last_type_segment(ty)?; @@ -92,13 +95,13 @@ pub(super) fn bytes_row_value_tokens( if option_inner.is_some() { Some(quote! { match &#value { - Some(value) => distributed::RowValue::Bytes(value.clone()), - None => distributed::RowValue::Null, + Some(value) => #framework::RowValue::Bytes(value.clone()), + None => #framework::RowValue::Null, } }) } else { Some(quote! { - distributed::RowValue::Bytes(#value.clone()) + #framework::RowValue::Bytes(#value.clone()) }) } } @@ -131,6 +134,24 @@ pub(super) fn vec_inner_type(ty: &Type) -> Option<&Type> { }) } +/// One allocation wrapper for a singular relationship, not a model or column. +pub(super) fn box_inner_type(ty: &Type) -> Option<&Type> { + let segment = last_type_segment(ty)?; + if segment.ident != "Box" { + return None; + } + let PathArguments::AngleBracketed(args) = &segment.arguments else { + return None; + }; + if args.args.len() != 1 { + return None; + } + match args.args.first()? { + GenericArgument::Type(ty) => Some(ty), + _ => None, + } +} + pub(super) fn validate_relationship_target_type( field: &Field, ty: &Type, diff --git a/distributed_macros/src/shared.rs b/distributed_macros/src/shared.rs index b0b8ff0df..cb035054b 100644 --- a/distributed_macros/src/shared.rs +++ b/distributed_macros/src/shared.rs @@ -14,6 +14,13 @@ use syn::{ /// Proc-macro output is compiled in the caller's crate, so a literal /// `::distributed` path is wrong when the dependency is renamed or re-exported. /// `FoundCrate::Itself` also keeps framework-internal macro tests hygienic. +/// [`framework_path`] for a helper below a macro's entry point. The entry +/// point has already resolved the dependency (and reported a missing one), so +/// the fallback is never what the user sees. +pub(crate) fn framework() -> proc_macro2::TokenStream { + framework_path().unwrap_or_else(|_| quote!(::distributed)) +} + pub(crate) fn framework_path() -> syn::Result { match crate_name("distributed") { Ok(FoundCrate::Itself) => Ok(quote!(crate)), @@ -61,37 +68,22 @@ pub(crate) fn extract_params_with_types( .collect() } -fn returns_result(sig: &syn::Signature) -> bool { - match &sig.output { - ReturnType::Default => false, - ReturnType::Type(_, ty) => match ty.as_ref() { - Type::Path(path) => path.path.segments.last().is_some_and(|segment| { - segment.ident == "Result" || segment.ident == "SourcedResult" - }), - _ => false, - }, - } -} - -pub(crate) fn ensure_sourced_result_signature( +/// A recorder returns nothing: the macro gives it `SourcedResult<()>` for the +/// digest. A recorder that could fail after the event is recorded would leave +/// an event whose state change never happened, so validation belongs in the +/// method that calls the recorder. +pub(crate) fn ensure_infallible_recorder_signature( sig: &mut syn::Signature, - attr_name: &str, framework: &proc_macro2::TokenStream, -) -> Result { - match &sig.output { - ReturnType::Default => { - sig.output = syn::parse_quote!(-> #framework::SourcedResult<()>); - Ok(true) - } - ReturnType::Type(_, _) if returns_result(sig) => Ok(false), - ReturnType::Type(_, ty) => Err(syn::Error::new_spanned( +) -> syn::Result<()> { + if let ReturnType::Type(_, ty) = &sig.output { + return Err(syn::Error::new_spanned( ty, - format!( - "#[{}] methods must return Result<(), E>, SourcedResult, or omit the return type", - attr_name - ), - )), + "#[event] methods must omit the return type: the event is recorded before the body runs, so the body cannot fail. Validate in the method that calls the recorder", + )); } + sig.output = syn::parse_quote!(-> #framework::SourcedResult<()>); + Ok(()) } /// Generate a digest call token stream. @@ -125,97 +117,33 @@ pub(crate) fn generate_digest_call( } } -/// Wrap a `Result<(), E>` command method with an optional guard and fallible prelude. -pub(crate) fn wrap_result_body_with_guard( - guard: Option<&Expr>, - prepend: proc_macro2::TokenStream, - original_block: &syn::Block, - signature_synthesized: bool, -) -> syn::Block { - wrap_result_body_with_guard_and_postlude( - guard, - prepend, - original_block, - proc_macro2::TokenStream::new(), - signature_synthesized, - ) -} - -/// Wrap a sourced method with an optional guard and successful postlude. -pub(crate) fn wrap_result_body_with_guard_and_postlude( +/// Wrap a recorder body: the prelude (digest), the body, then the postlude, +/// all behind the optional `when` guard. +pub(crate) fn wrap_recorder_body( guard: Option<&Expr>, prepend: proc_macro2::TokenStream, original_block: &syn::Block, append: proc_macro2::TokenStream, - signature_synthesized: bool, ) -> syn::Block { - match (guard, signature_synthesized) { - (Some(guard), true) => { - syn::parse_quote! { - { - if #guard { - #prepend - #original_block; - #append - } - Ok(()) - } - } - } - (Some(guard), false) => { - syn::parse_quote! { - { - if #guard { - #prepend - (|| #original_block)()?; - #append - } - Ok(()) - } - } - } - (None, true) => { - syn::parse_quote! { - { + match guard { + Some(guard) => syn::parse_quote! { + { + if #guard { #prepend #original_block; #append - Ok(()) } + Ok(()) } - } - (None, false) => { - syn::parse_quote! { - { - #prepend - (|| #original_block)()?; - #append - Ok(()) - } + }, + None => syn::parse_quote! { + { + #prepend + #original_block; + #append + Ok(()) } - } - } -} - -/// Generate an enqueue call token stream (for use within `#[sourced]`). -pub(crate) fn generate_enqueue_call( - entity_field: &Ident, - emitter_field: &Ident, - event_name: &LitStr, - param_names: &[&Ident], -) -> proc_macro2::TokenStream { - let enqueue_expr = if param_names.is_empty() { - quote! { self.#emitter_field.enqueue(#event_name, ""); } - } else if param_names.len() == 1 { - let param = param_names[0]; - quote! { self.#emitter_field.enqueue_with(#event_name, &(#param.clone(),))?; } - } else { - quote! { self.#emitter_field.enqueue_with(#event_name, &(#(#param_names.clone()),*))?; } - }; - quote! { - if !self.#entity_field.is_replaying() { - #enqueue_expr - }; + }, } } diff --git a/distributed_macros/src/snapshot.rs b/distributed_macros/src/snapshot.rs index 9ee447891..a8fed1c6b 100644 --- a/distributed_macros/src/snapshot.rs +++ b/distributed_macros/src/snapshot.rs @@ -11,6 +11,7 @@ pub fn derive_snapshot(input: TokenStream) -> TokenStream { } fn expand_snapshot(input: DeriveInput) -> syn::Result { + let framework = crate::shared::framework_path()?; let name = &input.ident; let snapshot_name = format_ident!("{}Snapshot", name); @@ -170,7 +171,7 @@ fn expand_snapshot(input: DeriveInput) -> syn::Result } } - impl distributed::Snapshottable for #name { + impl #framework::Snapshottable for #name { type Snapshot = #snapshot_name; #snapshot_version_const @@ -285,35 +286,6 @@ fn has_serde_skip(attrs: &[syn::Attribute]) -> bool { mod tests { use super::*; - #[test] - fn expand_snapshot_accepts_named_struct() { - let input: DeriveInput = syn::parse_quote! { - struct Todo { - entity: distributed::Entity, - task: String, - } - }; - - let expanded = expand_snapshot(input).unwrap().to_string(); - - assert!(expanded.contains("pub struct TodoSnapshot")); - assert!(expanded.contains("impl distributed :: Snapshottable for Todo")); - } - - #[test] - fn expand_snapshot_rejects_tuple_structs() { - let input: DeriveInput = syn::parse_quote! { - struct Todo(String); - }; - - let err = expand_snapshot(input).expect_err("tuple struct should return an error"); - - assert!( - err.to_string().contains("requires named fields"), - "unexpected error: {err}" - ); - } - #[test] fn expand_snapshot_rejects_enums() { let input: DeriveInput = syn::parse_quote! { @@ -431,42 +403,6 @@ mod tests { ); } - #[test] - fn expand_snapshot_without_version_attr_inherits_default() { - let input: DeriveInput = syn::parse_quote! { - struct Todo { - entity: distributed::Entity, - task: String, - } - }; - - let expanded = expand_snapshot(input).unwrap().to_string(); - - // No explicit const is emitted; the trait default (1) is inherited. - assert!( - !expanded.contains("const SNAPSHOT_VERSION"), - "default case must not emit a SNAPSHOT_VERSION const: {expanded}" - ); - } - - #[test] - fn expand_snapshot_emits_version_const() { - let input: DeriveInput = syn::parse_quote! { - #[snapshot(version = 3)] - struct Todo { - entity: distributed::Entity, - task: String, - } - }; - - let expanded = expand_snapshot(input).unwrap().to_string(); - - assert!( - expanded.contains("const SNAPSHOT_VERSION : u64 = 3"), - "expected emitted version const: {expanded}" - ); - } - #[test] fn expand_snapshot_rejects_zero_version() { let input: DeriveInput = syn::parse_quote! { diff --git a/distributed_macros/src/sourced.rs b/distributed_macros/src/sourced.rs index e1ca50e83..983c23384 100644 --- a/distributed_macros/src/sourced.rs +++ b/distributed_macros/src/sourced.rs @@ -3,7 +3,7 @@ use quote::{format_ident, quote}; use syn::{ parse::{ParseStream, Parser}, visit::Visit, - Expr, FnArg, Ident, ItemImpl, LitStr, Member, Path, Stmt, Token, Type, + Expr, FnArg, Ident, ItemImpl, LitStr, Path, Token, Type, }; use crate::aggregate::{ @@ -11,10 +11,9 @@ use crate::aggregate::{ validate_aggregate_type_literal, UpcasterDef, }; use crate::shared::{ - canonical_object_schema, ensure_sourced_result_signature, extract_params_with_types, - framework_path, generate_digest_call, generate_enqueue_call, projection_body_metadata_tokens, - schema_fingerprint, validate_domain_event_name_literal, - wrap_result_body_with_guard_and_postlude, + canonical_object_schema, ensure_infallible_recorder_signature, extract_params_with_types, + framework_path, generate_digest_call, projection_body_metadata_tokens, schema_fingerprint, + validate_domain_event_name_literal, wrap_recorder_body, }; pub(crate) struct SourcedArgs { @@ -22,7 +21,6 @@ pub(crate) struct SourcedArgs { enum_name: Option, aggregate_type: Option, domain_state: Option, - enqueue: Option, // Some(emitter_field) if enqueue enabled pub(crate) upcasters: Vec, } @@ -36,7 +34,6 @@ pub(crate) fn parse_sourced_args(input: ParseStream) -> syn::Result let mut enum_name = None; let mut aggregate_type = None; let mut domain_state = None; - let mut enqueue = None; let mut upcasters = Vec::new(); while input.peek(Token![,]) { @@ -63,15 +60,6 @@ pub(crate) fn parse_sourced_args(input: ParseStream) -> syn::Result } input.parse::()?; domain_state = Some(input.parse::()?); - } else if kw == "enqueue" { - // Optional custom emitter field: enqueue(my_emitter) - if input.peek(syn::token::Paren) { - let inner; - syn::parenthesized!(inner in input); - enqueue = Some(inner.parse::()?); - } else { - enqueue = Some(format_ident!("emitter")); - } } else if kw == "upcasters" { let upcaster_content; syn::parenthesized!(upcaster_content in input); @@ -80,7 +68,7 @@ pub(crate) fn parse_sourced_args(input: ParseStream) -> syn::Result return Err(syn::Error::new_spanned( &kw, format!( - "unsupported key `{kw}` in #[sourced(...)]; expected `events`, `aggregate_type`, `domain_state`, `enqueue`, or `upcasters`" + "unsupported key `{kw}` in #[sourced(...)]; expected `events`, `aggregate_type`, `domain_state`, or `upcasters`" ), )); } @@ -91,7 +79,6 @@ pub(crate) fn parse_sourced_args(input: ParseStream) -> syn::Result enum_name, aggregate_type, domain_state, - enqueue, upcasters, }) } @@ -101,6 +88,9 @@ pub(crate) struct EventAttr { guard: Option, version: Option, domain: Option, + /// `known(field: value, ..)`: state fields this recorder always leaves at + /// a fixed value, in the field grammar of `state_preview!`. + known: Option, } enum DomainMode { @@ -115,6 +105,7 @@ pub(crate) fn parse_event_args(input: ParseStream) -> syn::Result { let mut guard = None; let mut version: Option = None; let mut domain = None; + let mut known: Option<(Ident, TokenStream2)> = None; while input.peek(Token![,]) { input.parse::()?; @@ -166,16 +157,48 @@ pub(crate) fn parse_event_args(input: ParseStream) -> syn::Result { } else { DomainMode::State }); + } else if ident == "known" { + if known.is_some() { + return Err(syn::Error::new_spanned( + &ident, + "duplicate `known(...)` in #[event(...)]", + )); + } + let content; + syn::parenthesized!(content in input); + // `state_preview!` wants every field followed by one comma. + let mut fields: Vec = + content.parse::()?.into_iter().collect(); + if matches!(fields.last(), Some(proc_macro2::TokenTree::Punct(p)) if p.as_char() == ',') + { + fields.pop(); + } + if fields.is_empty() { + return Err(syn::Error::new_spanned( + &ident, + "`known(...)` needs at least one `field: value`", + )); + } + known = Some((ident, quote!(#(#fields)* ,))); } else { return Err(syn::Error::new_spanned( &ident, format!( - "unsupported key `{ident}` in #[event(...)]; expected `when`, `version`, or `domain`" + "unsupported key `{ident}` in #[event(...)]; expected `when`, `version`, `domain`, or `known`" ), )); } } + if let Some((key, _)) = &known { + if !matches!(domain, Some(DomainMode::State | DomainMode::Event)) { + return Err(syn::Error::new_spanned( + key, + "`known(...)` names fields of the domain state (`domain`) or of the event body (`domain = event`), so it needs one of those on the same #[event]", + )); + } + } + if domain.is_some() { validate_domain_event_name_literal(&event_name)?; if let Some(version) = &version { @@ -193,6 +216,7 @@ pub(crate) fn parse_event_args(input: ParseStream) -> syn::Result { guard, version, domain, + known: known.map(|(_, fields)| fields), }) } @@ -212,30 +236,19 @@ fn find_and_remove_event_attr( struct EventMethodInfo { event_name: LitStr, + version: syn::LitInt, method_name: Ident, params: Vec<(Ident, syn::Type)>, - /// Present when this recorder has `domain` and therefore a generated - /// outward domain-event marker type. + /// Present when this recorder has `domain` and therefore an exact outward + /// event contract (a generated marker or the explicitly declared body). command_event: Option, } #[derive(Clone)] struct DomainCommandEvent { - domain_event_type: Ident, + domain_event_type: Type, domain_state: Option, - known_state_values: Vec, -} - -#[derive(Clone)] -struct KnownStateValue { - field: Ident, - source: KnownStateValueSource, -} - -#[derive(Clone)] -enum KnownStateValueSource { - Constant(Expr), - Null, + known: Option, } /// Public aggregate method that may capture one or more domain events. @@ -251,7 +264,7 @@ struct DomainExpansion { uses_deletion_identity: bool, } -fn ensure_domain_body_has_no_early_exit(block: &syn::Block) -> syn::Result<()> { +fn ensure_recorder_body_has_no_early_exit(block: &syn::Block) -> syn::Result<()> { #[derive(Default)] struct EarlyExitVisitor { error: Option, @@ -262,7 +275,7 @@ fn ensure_domain_body_has_no_early_exit(block: &syn::Block) -> syn::Result<()> { if self.error.is_none() { self.error = Some(syn::Error::new_spanned( expression, - "domain-marked #[event] methods cannot use `?` in version one because it may skip post-transition capture", + "#[event] methods cannot use `?`: the event is already recorded when the body runs, so the body cannot fail", )); } } @@ -271,7 +284,7 @@ fn ensure_domain_body_has_no_early_exit(block: &syn::Block) -> syn::Result<()> { if self.error.is_none() { self.error = Some(syn::Error::new_spanned( expression, - "domain-marked #[event] methods cannot use `return` in version one because it skips post-transition capture", + "#[event] methods cannot use `return`: it would skip the rest of the recorded transition", )); } } @@ -285,9 +298,9 @@ fn ensure_domain_body_has_no_early_exit(block: &syn::Block) -> syn::Result<()> { } } -fn domain_capture_error(expression: TokenStream2) -> TokenStream2 { +fn domain_capture_error(framework: &TokenStream2, expression: TokenStream2) -> TokenStream2 { quote! { - #expression.map_err(|error| distributed::EventRecordError { + #expression.map_err(|error| #framework::EventRecordError { message: format!("domain-event capture failed: {error}"), })?; } @@ -353,13 +366,16 @@ fn expand_domain_capture( ) })?; let event_type = identity_domain_event_type(aggregate, event_name)?; - let capture = domain_capture_error(quote! { - self.#entity_field.capture_domain_state( - #aggregate_type, - distributed::DomainEventDescriptor::state::<#state>(#event_name, #version), - &__distributed_domain_state, - ) - }); + let capture = domain_capture_error( + &framework, + quote! { + self.#entity_field.capture_domain_state( + #aggregate_type, + #framework::DomainEventDescriptor::state::<#state>(#event_name, #version), + &__distributed_domain_state, + ) + }, + ); Ok(DomainExpansion { prepare: TokenStream2::new(), capture: quote! { @@ -373,19 +389,19 @@ fn expand_domain_capture( /// Exact outward event marker for this state-backed transition. pub enum #event_type {} - impl distributed::domain_event::DomainEventContract for #event_type { + impl #framework::domain_event::DomainEventContract for #event_type { const EVENT_NAME: &'static str = #event_name; const EVENT_VERSION: u64 = #version; - fn descriptor() -> distributed::DomainEventDescriptor { - distributed::DomainEventDescriptor::state::<#state>( + fn descriptor() -> #framework::DomainEventDescriptor { + #framework::DomainEventDescriptor::state::<#state>( #event_name, #version, ) } } - impl distributed::domain_event::DomainEventBodyContract<#state> + impl #framework::domain_event::DomainEventBodyContract<#state> for #event_type { } @@ -429,13 +445,13 @@ fn expand_domain_capture( #(#field_definitions),* } - impl distributed::DomainEvent for #body_type { - const DESCRIPTOR: distributed::DomainEventDescriptor = - distributed::DomainEventDescriptor { + impl #framework::DomainEvent for #body_type { + const DESCRIPTOR: #framework::DomainEventDescriptor = + #framework::DomainEventDescriptor { name: std::borrow::Cow::Borrowed(#event_name), version: #version, - body: distributed::DomainEventBodyDescriptor::distributed_json( - distributed::DomainEventBodyKind::Event, + body: #framework::DomainEventBodyDescriptor::distributed_json( + #framework::DomainEventBodyKind::Event, #body_type_name, #version, #schema, @@ -444,27 +460,39 @@ fn expand_domain_capture( }; } - impl distributed::domain_event::DomainEventContract for #body_type { + impl #framework::domain_event::DomainEventContract for #body_type { const EVENT_NAME: &'static str = #event_name; const EVENT_VERSION: u64 = #version; - fn descriptor() -> distributed::DomainEventDescriptor { - ::DESCRIPTOR.clone() + fn descriptor() -> #framework::DomainEventDescriptor { + ::DESCRIPTOR.clone() } } - impl distributed::domain_event::DomainEventBodyContract for #body_type {} + impl #framework::domain_event::DomainEventBodyContract for #body_type {} - impl distributed::projection::lower::ProjectionBodyMetadata for #body_type { + impl #framework::command::CommandProjectionBody for #body_type { + fn command_projection_descriptor( + _: &'static str, + _: u64, + ) -> #framework::DomainEventDescriptor { + ::DESCRIPTOR.clone() + } + } + + impl #framework::projection::lower::ProjectionBodyMetadata for #body_type { #projection_metadata } }; - let capture = domain_capture_error(quote! { - self.#entity_field.capture_domain_event( - #aggregate_type, - &__distributed_domain_event_body, - ) - }); + let capture = domain_capture_error( + &framework, + quote! { + self.#entity_field.capture_domain_event( + #aggregate_type, + &__distributed_domain_event_body, + ) + }, + ); Ok(DomainExpansion { prepare: quote! { let __distributed_domain_event_body = @@ -509,16 +537,16 @@ fn expand_domain_capture( /// Exact outward event marker for this deletion transition. pub enum #event_type {} - impl distributed::domain_event::DomainEventContract for #event_type { + impl #framework::domain_event::DomainEventContract for #event_type { const EVENT_NAME: &'static str = #event_name; const EVENT_VERSION: u64 = #version; - fn descriptor() -> distributed::DomainEventDescriptor { - distributed::DomainEventDescriptor { + fn descriptor() -> #framework::DomainEventDescriptor { + #framework::DomainEventDescriptor { name: std::borrow::Cow::Borrowed(#event_name), version: #version, - body: distributed::DomainEventBodyDescriptor::distributed_json( - distributed::DomainEventBodyKind::Deletion, + body: #framework::DomainEventBodyDescriptor::distributed_json( + #framework::DomainEventBodyKind::Deletion, #deletion_type_name, 1, #schema, @@ -528,41 +556,44 @@ fn expand_domain_capture( } } - impl distributed::domain_event::DomainEventBodyContract< - distributed::DomainDeletion<#identity> + impl #framework::domain_event::DomainEventBodyContract< + #framework::DomainDeletion<#identity> > for #event_type { } }; - let capture = domain_capture_error(quote! { - self.#entity_field.capture_domain_deletion( - #aggregate_type, - distributed::DomainEventDescriptor { - name: std::borrow::Cow::Borrowed(#event_name), - version: #version, - body: distributed::DomainEventBodyDescriptor::distributed_json( - distributed::DomainEventBodyKind::Deletion, - #deletion_type_name, - 1, - #schema, - #fingerprint, - ), - }, - &__distributed_domain_deletion, - ) - }); + let capture = domain_capture_error( + &framework, + quote! { + self.#entity_field.capture_domain_deletion( + #aggregate_type, + #framework::DomainEventDescriptor { + name: std::borrow::Cow::Borrowed(#event_name), + version: #version, + body: #framework::DomainEventBodyDescriptor::distributed_json( + #framework::DomainEventBodyKind::Deletion, + #deletion_type_name, + 1, + #schema, + #fingerprint, + ), + }, + &__distributed_domain_deletion, + ) + }, + ); Ok(DomainExpansion { prepare: TokenStream2::new(), capture: quote! { if !self.#entity_field.is_replaying() { let __distributed_domain_deletion = - distributed::DomainDeletion::new( + #framework::DomainDeletion::new( #identity { aggregate_id: self.#entity_field.id().to_owned(), }, self.#entity_field.version(), ) - .map_err(|error| distributed::EventRecordError { + .map_err(|error| #framework::EventRecordError { message: format!("domain-event capture failed: {error}"), })?; #capture @@ -580,12 +611,15 @@ fn expand_domain_capture( let fields = params.iter().map(|(name, _)| quote!(#name: #name.clone())); quote!(#event_enum::#variant { #(#fields),* }) }; - let capture = domain_capture_error(quote! { - self.#entity_field.capture_domain_event( - #aggregate_type, - &__distributed_domain_event_body, - ) - }); + let capture = domain_capture_error( + &framework, + quote! { + self.#entity_field.capture_domain_event( + #aggregate_type, + &__distributed_domain_event_body, + ) + }, + ); Ok(DomainExpansion { prepare: quote! { let __distributed_domain_event_source = @@ -597,8 +631,8 @@ fn expand_domain_capture( { fn __distributed_assert_domain_event_contract() where - T: distributed::DomainEvent - + distributed::domain_event::DomainEventBodyContract, + T: #framework::DomainEvent + + #framework::domain_event::DomainEventBodyContract, { } __distributed_assert_domain_event_contract::<#output>(); @@ -609,10 +643,10 @@ fn expand_domain_capture( &*self, __distributed_domain_event_source, ); - if <#output as distributed::domain_event::DomainEventContract>::descriptor() - != <#output as distributed::DomainEvent>::DESCRIPTOR + if <#output as #framework::domain_event::DomainEventContract>::descriptor() + != <#output as #framework::DomainEvent>::DESCRIPTOR { - return Err(distributed::EventRecordError { + return Err(#framework::EventRecordError { message: "domain-event capture failed: adapter output contract differs from its DomainEvent descriptor".to_owned(), }); } @@ -641,12 +675,12 @@ fn expand_domain_capture( } if !__distributed_same_str( - <#output as distributed::domain_event::DomainEventContract>::EVENT_NAME, + <#output as #framework::domain_event::DomainEventContract>::EVENT_NAME, #event_name, ) { panic!("domain adapter output event name differs from #[event]"); } - if <#output as distributed::domain_event::DomainEventContract>::EVENT_VERSION + if <#output as #framework::domain_event::DomainEventContract>::EVENT_VERSION != #version { panic!("domain adapter output event version differs from #[event]"); @@ -703,8 +737,13 @@ pub(crate) fn expand_sourced(attr: TokenStream2, item: TokenStream2) -> syn::Res let mut seen_variants: std::collections::HashMap = std::collections::HashMap::new(); + let mut commands = Vec::new(); for item in &mut impl_block.items { if let syn::ImplItem::Fn(method) = item { + if let Some(command) = crate::aggregate_command::take(method)? { + commands.push(command); + continue; + } match find_and_remove_event_attr(&mut method.attrs) { Ok(Some(event_attr)) => { // Event methods are replayed as `self.method(...)`, so they @@ -741,38 +780,14 @@ pub(crate) fn expand_sourced(attr: TokenStream2, item: TokenStream2) -> syn::Res } seen_variants.insert(variant.to_string(), event_attr.event_name.clone()); - if event_attr.domain.is_some() - && !matches!(method.sig.output, syn::ReturnType::Default) - { - return Err(syn::Error::new_spanned( - &method.sig.output, - "domain-marked #[event] methods must omit the return type in version one; fallible recorders cannot prove post-transition capture safety", - )); - } - if event_attr.domain.is_some() { - ensure_domain_body_has_no_early_exit(&method.block)?; - } + ensure_infallible_recorder_signature(&mut method.sig, &framework)?; + ensure_recorder_body_has_no_early_exit(&method.block)?; let state_domain = matches!(event_attr.domain.as_ref(), Some(DomainMode::State)); - let known_state_values = state_domain - .then(|| infer_unconditional_known_state_values(&method.block)) - .unwrap_or_default(); - let signature_synthesized = - ensure_sourced_result_signature(&mut method.sig, "event", &framework)?; - let params = extract_params_with_types(&method.sig, "event")?; let param_name_refs: Vec<&Ident> = params.iter().map(|(name, _)| name).collect(); - // Build prepend: optional enqueue + digest - let enqueue_call = args.enqueue.as_ref().map(|emitter_field| { - generate_enqueue_call( - &args.entity_field, - emitter_field, - &event_attr.event_name, - ¶m_name_refs, - ) - }); let digest_call = generate_digest_call( &args.entity_field, &event_attr.event_name, @@ -795,34 +810,40 @@ pub(crate) fn expand_sourced(attr: TokenStream2, item: TokenStream2) -> syn::Res let domain_prepare = domain.prepare; let domain_capture = domain.capture; let prepend = quote! { - #enqueue_call #digest_call #domain_prepare }; - let new_body = wrap_result_body_with_guard_and_postlude( + let new_body = wrap_recorder_body( event_attr.guard.as_ref(), prepend, &method.block, domain_capture, - signature_synthesized, ); method.block = new_body; - let command_event = if event_attr.domain.is_some() { + let command_event = if let Some(mode) = event_attr.domain.as_ref() { + let domain_event_type = match mode { + DomainMode::With { output, .. } => (**output).clone(), + _ => { + let marker = identity_domain_event_type( + &struct_name, + &event_attr.event_name, + )?; + syn::parse_quote!(#marker) + } + }; Some(DomainCommandEvent { - domain_event_type: identity_domain_event_type( - &struct_name, - &event_attr.event_name, - )?, + domain_event_type, domain_state: state_domain.then(|| args.domain_state.clone()).flatten(), - known_state_values, + known: event_attr.known.clone(), }) } else { None }; event_methods.push(EventMethodInfo { + version: event_version(event_attr.version.as_ref()), event_name: event_attr.event_name, method_name: method.sig.ident.clone(), params, @@ -835,8 +856,26 @@ pub(crate) fn expand_sourced(attr: TokenStream2, item: TokenStream2) -> syn::Res } } + let command_methods: std::collections::BTreeSet = commands + .iter() + .map(|command| command.method().to_string()) + .collect(); let domain_command_transitions = - discover_domain_command_transitions(&impl_block, &event_methods); + discover_domain_command_transitions(&impl_block, &event_methods, &command_methods); + let self_ty = (*impl_block.self_ty).clone(); + let command_mounts = commands + .iter() + .map(|command| { + let witness = domain_command_transitions + .iter() + .find(|transition| transition.method_name == *command.method()) + .map(|transition| { + let ty = method_name_to_type_ident(&transition.method_name); + quote!(domain_commands::#ty) + }); + crate::aggregate_command::expand(command, &self_ty, witness, &framework) + }) + .collect::>>()?; let deletion_identity = if uses_deletion_identity { let identity = format_ident!("{struct_name}DomainIdentity"); @@ -876,7 +915,7 @@ pub(crate) fn expand_sourced(attr: TokenStream2, item: TokenStream2) -> syn::Res pub aggregate_id: String, } - impl distributed::projection::lower::ProjectionDeletionMetadata for #identity { + impl #framework::projection::lower::ProjectionDeletionMetadata for #identity { const BODY_TYPE_NAME: &'static str = #deletion_type_name; const BODY_SCHEMA: &'static str = #deletion_schema; const BODY_FINGERPRINT: &'static str = #deletion_fingerprint; @@ -954,9 +993,9 @@ pub(crate) fn expand_sourced(attr: TokenStream2, item: TokenStream2) -> syn::Res }); let try_from_impl = quote! { - impl TryFrom<&distributed::EventRecord> for #enum_name { + impl TryFrom<&#framework::EventRecord> for #enum_name { type Error = String; - fn try_from(event: &distributed::EventRecord) -> Result { + fn try_from(event: &#framework::EventRecord) -> Result { match event.event_name.as_str() { #(#try_from_arms)* _ => Err(format!("Unknown event: {}", event.event_name)), @@ -967,6 +1006,14 @@ pub(crate) fn expand_sourced(attr: TokenStream2, item: TokenStream2) -> syn::Res // Generate impl Aggregate let entity_field = &args.entity_field; + let version_arms: Vec<_> = event_methods + .iter() + .map(|event| { + let name = &event.event_name; + let version = &event.version; + quote! { #name => #version, } + }) + .collect(); let replay_arms: Vec<_> = event_methods .iter() .map(|e| { @@ -999,7 +1046,7 @@ pub(crate) fn expand_sourced(attr: TokenStream2, item: TokenStream2) -> syn::Res .collect(); let (upcaster_wrappers, upcasters_method) = - generate_upcaster_tokens(&struct_name, &args.upcasters); + generate_upcaster_tokens(&framework, &struct_name, &args.upcasters); let aggregate_type_method = args.aggregate_type.as_ref().map(|aggregate_type| { quote! { fn aggregate_type() -> &'static str { @@ -1010,15 +1057,17 @@ pub(crate) fn expand_sourced(attr: TokenStream2, item: TokenStream2) -> syn::Res // ReplayError stays `String` — see the rationale on `expand_aggregate`. let aggregate_impl = aggregate_impl_tokens( + &framework, &struct_name, entity_field, &aggregate_type_method, + &version_arms, &replay_arms, &upcasters_method, ); let domain_commands_module = - expand_domain_commands_module(&struct_name, &domain_command_transitions); + expand_domain_commands_module(&framework, &struct_name, &domain_command_transitions); let expanded = quote! { #impl_block @@ -1028,6 +1077,7 @@ pub(crate) fn expand_sourced(attr: TokenStream2, item: TokenStream2) -> syn::Res #(#generated_domain_types)* #deletion_identity #domain_commands_module + #(#command_mounts)* #upcaster_wrappers #aggregate_impl }; @@ -1035,100 +1085,10 @@ pub(crate) fn expand_sourced(attr: TokenStream2, item: TokenStream2) -> syn::Res Ok(expanded) } -/// Collect only straight-line recorder assignments whose serialized value is -/// independent of command input and current aggregate state. Nested control -/// flow and arbitrary Rust expressions deliberately remain unknown. -fn infer_unconditional_known_state_values(block: &syn::Block) -> Vec { - let mut values = - std::collections::BTreeMap::)>::new(); - for statement in &block.stmts { - let Stmt::Expr(Expr::Assign(assign), _) = statement else { - continue; - }; - let Expr::Field(field) = ungroup_expr(&assign.left) else { - continue; - }; - if !is_self_receiver(&field.base) { - continue; - } - let Member::Named(name) = &field.member else { - continue; - }; - values.insert( - name.to_string(), - (name.clone(), known_state_value_source(&assign.right)), - ); - } - values - .into_values() - .filter_map(|(field, source)| source.map(|source| KnownStateValue { field, source })) - .collect() -} - -fn known_state_value_source(expression: &Expr) -> Option { - let expression = ungroup_expr(expression); - match expression { - Expr::Path(path) if path.path.is_ident("None") => Some(KnownStateValueSource::Null), - // Qualified paths cover enum variants and associated constants without - // treating a local variable as a compile-time value. - Expr::Path(path) if path.path.segments.len() >= 2 => { - Some(KnownStateValueSource::Constant(expression.clone())) - } - Expr::Lit(literal) - if matches!( - literal.lit, - syn::Lit::Bool(_) | syn::Lit::Str(_) | syn::Lit::Char(_) - ) => - { - Some(KnownStateValueSource::Constant(expression.clone())) - } - Expr::Call(call) - if call.args.len() == 1 - && matches!( - ungroup_expr(&call.func), - Expr::Path(path) - if path.path.segments.len() == 4 - && path.path.segments[0].ident == "std" - && path.path.segments[1].ident == "string" - && path.path.segments[2].ident == "String" - && path.path.segments[3].ident == "from" - ) - && matches!( - call.args.first().map(ungroup_expr), - Some(Expr::Lit(syn::ExprLit { - lit: syn::Lit::Str(_), - .. - })) - ) => - { - Some(KnownStateValueSource::Constant(expression.clone())) - } - Expr::Call(call) - if call.args.len() == 1 - && matches!( - ungroup_expr(&call.func), - Expr::Path(path) if path.path.is_ident("Some") - ) - && known_state_value_source(call.args.first().expect("one Some argument")) - .is_some() => - { - Some(KnownStateValueSource::Constant(expression.clone())) - } - _ => None, - } -} - -fn ungroup_expr(expression: &Expr) -> &Expr { - match expression { - Expr::Paren(paren) => ungroup_expr(&paren.expr), - Expr::Group(group) => ungroup_expr(&group.expr), - other => other, - } -} - fn discover_domain_command_transitions( impl_block: &ItemImpl, event_methods: &[EventMethodInfo], + command_methods: &std::collections::BTreeSet, ) -> Vec { let recorders: std::collections::BTreeMap = event_methods .iter() @@ -1143,24 +1103,47 @@ fn discover_domain_command_transitions( return Vec::new(); } + // Only decision methods belong in the helper graph. A recorder's rewritten + // implementation includes replay/capture plumbing, not another decision. + let methods = impl_block + .items + .iter() + .filter_map(|item| match item { + syn::ImplItem::Fn(method) + if !event_methods + .iter() + .any(|event| event.method_name == method.sig.ident) => + { + Some((method.sig.ident.to_string(), method)) + } + _ => None, + }) + .collect::>(); let mut transitions = Vec::new(); - for item in &impl_block.items { - let syn::ImplItem::Fn(method) = item else { - continue; - }; - // Domain recorders themselves are not command transitions. - if recorders.contains_key(&method.sig.ident.to_string()) { - continue; - } - if !matches!(method.vis, syn::Visibility::Public(_)) { + for (name, method) in &methods { + // Public methods are transitions; so is every `#[command]` method + // (its generated mount needs the witness whatever its visibility). + if !matches!(method.vis, syn::Visibility::Public(_)) && !command_methods.contains(name) { continue; } let mut finder = DomainEventCallFinder { recorders: &recorders, found: std::collections::BTreeMap::new(), + calls: std::collections::BTreeSet::new(), }; - finder.visit_block(&method.block); + let mut pending = vec![name.clone()]; + let mut visited = std::collections::BTreeSet::new(); + while let Some(name) = pending.pop() { + if !visited.insert(name.clone()) { + continue; + } + let Some(callee) = methods.get(&name) else { + continue; + }; + finder.visit_block(&callee.block); + pending.extend(std::mem::take(&mut finder.calls)); + } if finder.found.is_empty() { continue; } @@ -1175,15 +1158,23 @@ fn discover_domain_command_transitions( struct DomainEventCallFinder<'a> { recorders: &'a std::collections::BTreeMap, found: std::collections::BTreeMap, + calls: std::collections::BTreeSet, } impl<'ast> Visit<'ast> for DomainEventCallFinder<'_> { + // A nested function/impl has its own receiver scope. Its `self` must not + // be confused with the aggregate, even when a method name happens to match. + fn visit_item(&mut self, _: &'ast syn::Item) {} + fn visit_expr_method_call(&mut self, node: &'ast syn::ExprMethodCall) { if is_self_receiver(&node.receiver) { if let Some(command_event) = self.recorders.get(&node.method.to_string()) { + let event_type = &command_event.domain_event_type; self.found - .entry(command_event.domain_event_type.to_string()) + .entry(quote!(#event_type).to_string()) .or_insert_with(|| command_event.clone()); + } else { + self.calls.insert(node.method.to_string()); } } syn::visit::visit_expr_method_call(self, node); @@ -1216,6 +1207,7 @@ fn method_name_to_type_ident(method_name: &Ident) -> Ident { } fn expand_domain_commands_module( + framework: &TokenStream2, aggregate: &Ident, transitions: &[DomainCommandTransition], ) -> TokenStream2 { @@ -1223,7 +1215,9 @@ fn expand_domain_commands_module( return TokenStream2::new(); } - let transition_items = transitions.iter().map(|transition| { + let mut transition_items = Vec::new(); + let mut transition_impls = Vec::new(); + for transition in transitions { let type_name = method_name_to_type_ident(&transition.method_name); let method_name = transition.method_name.to_string(); let aggregate_name = aggregate.to_string(); @@ -1232,61 +1226,52 @@ fn expand_domain_commands_module( .iter() .map(|event| &event.domain_event_type) .collect::>(); + // `known(..)` on a recorder: declared once next to the event, checked + // when the command is registered. A state recorder names fields of the + // domain state; an event-mode recorder names fields of its own body (a + // distinct event per outcome carries its constant, e.g. a status). let known_value_items = transition.events.iter().filter_map(|event| { - let state = event.domain_state.as_ref()?; - if event.known_state_values.is_empty() { - return None; - } + let fields = event.known.as_ref()?; let event_type = &event.domain_event_type; - let fields = event.known_state_values.iter().map(|value| { - let field = value.field.to_string(); - let source = match &value.source { - KnownStateValueSource::Constant(expression) => quote! { - distributed::graphql::__command_projection_preview_constant(#expression) - }, - KnownStateValueSource::Null => quote! { - distributed::graphql::CommandProjectionPreviewSource::Null - }, - }; - quote! { (#field, #source) } - }); - Some(quote! { - distributed::graphql::__command_projection_state_known_values::< - super::#event_type, - #state, - >(vec![#(#fields),*]) + Some(match event.domain_state.as_ref() { + Some(state) => quote! { + #framework::state_preview! { #event_type => #state { #fields } } + }, + None => quote! { + #framework::event_preview! { #event_type => #event_type { #fields } } + }, }) }); - let has_known_values = transition - .events - .iter() - .any(|event| event.domain_state.is_some() && !event.known_state_values.is_empty()); + let has_known_values = transition.events.iter().any(|event| event.known.is_some()); let known_values_method = has_known_values.then(|| { quote! { fn command_event_known_values( - ) -> Vec { - #[allow(unused_imports)] - use super::*; + ) -> Vec<#framework::command::CommandProjectionPreview> { vec![#(#known_value_items),*] } } }); let doc = format!( "Outward domain-event set for `{aggregate_name}::{method_name}`.\n\n\ - Derived from direct `self.()` calls to `#[event(..., domain)]` \ - methods in this `#[sourced]` impl. Use with \ - [`distributed::graphql::TypedCommand::emits_events`]." + Derived from `self.()` calls to `#[event(..., domain)]` \ + methods, including through decision helpers in this `#[sourced]` impl. Use with \ + [`distributed::command::TypedCommand::emits_events`]." ); - quote! { + transition_items.push(quote! { #[doc = #doc] pub enum #type_name {} - - impl distributed::graphql::CommandEventSet for #type_name { - fn command_event_set() -> distributed::graphql::CommandProjectionEventSet { - distributed::graphql::__command_projection_events([ + }); + // Keep authored types in the aggregate's lexical scope. Moving an + // explicit `with(super::facts::Body, ...)` path inside domain_commands + // would silently change its meaning (and generated aliases do not exist + // for custom bodies). The public witness still lives in that module. + transition_impls.push(quote! { + impl #framework::command::CommandEventSet for domain_commands::#type_name { + fn command_event_set() -> #framework::command::CommandProjectionEventSet { + #framework::command::__command_projection_events([ #( - distributed::graphql::__command_projection_event_descriptor::< - super::#event_types, + #framework::command::__command_projection_event_descriptor::< + #event_types, >() ),* ]) @@ -1294,8 +1279,8 @@ fn expand_domain_commands_module( #known_values_method } - } - }); + }); + } let aggregate_name = aggregate.to_string(); let module_doc = format!( @@ -1312,6 +1297,7 @@ fn expand_domain_commands_module( pub mod domain_commands { #(#transition_items)* } + #(#transition_impls)* } } diff --git a/distributed_macros/tests/application.rs b/distributed_macros/tests/application.rs deleted file mode 100644 index 3fb9f1146..000000000 --- a/distributed_macros/tests/application.rs +++ /dev/null @@ -1,124 +0,0 @@ -#![allow(unexpected_cfgs)] -#![allow(dead_code)] -#![allow(unused_imports)] - -use distributed::graphql::Succeeded; -use distributed::microsvc::{CausalCommandContext, HandlerError}; -use distributed::{Aggregate, DomainEvent, Entity, EventRecord, GraphqlInput, GraphqlOutput}; -use serde::{Deserialize, Serialize}; - -#[derive(Default)] -pub struct FixtureAggregate { - entity: Entity, -} - -impl Aggregate for FixtureAggregate { - type ReplayError = String; - - fn aggregate_type() -> &'static str { - "application-macro-fixture" - } - - fn entity(&self) -> &Entity { - &self.entity - } - - fn entity_mut(&mut self) -> &mut Entity { - &mut self.entity - } - - fn replay_event(&mut self, _event: &EventRecord) -> Result<(), Self::ReplayError> { - Ok(()) - } -} - -#[derive(Clone, Deserialize, GraphqlInput)] -pub struct CreateInput { - id: String, - title: String, -} - -#[derive(Clone, Serialize, GraphqlOutput)] -pub struct CreateOutput { - id: String, -} - -#[derive(Clone, Serialize, DomainEvent)] -#[domain_event(name = "todo.created", version = 1)] -pub struct TodoCreated { - id: String, -} - -#[distributed::command( - id = "todo.create", - roles(user, admin), - emits(TodoCreated), - applies(distributed::event_preview! { - TodoCreated => TodoCreated { - id: input.id, - ..unknown - } - }), - default(title = uuid_v7), - input = CreateInput, - outcome = Succeeded -)] -pub async fn handle( - _context: &CausalCommandContext<'_, FixtureAggregate>, - _input: CreateInput, -) -> Result>, HandlerError> { - unimplemented!() -} - -distributed::module! { - pub TODO_MODULE { - id: "todo", - commands: [HANDLE_DEFINITION], - capabilities: ["events"], - } -} - -distributed::application! { - pub TODO_APPLICATION { - id: "todo-app", - modules: [TODO_MODULE], - capabilities: ["identity"], - } -} - -distributed::application! { - pub IMPLICIT_APPLICATION { - modules: [TODO_MODULE], - } -} - -#[test] -fn command_module_and_application_macros_share_one_portable_spec() { - let spec = handle_spec().expect("generated command spec"); - assert_eq!(spec.id, "todo.create"); - assert_eq!(spec.roles, ["admin", "user"]); - assert_eq!(spec.emits[0].name, "todo.created"); - assert!(spec.applies.as_array().is_some_and(|values| !values.is_empty())); - assert!(spec.defaults.as_array().is_some_and(|values| !values.is_empty())); - assert!(!spec.effects.is_null()); - assert!(!spec.fingerprint.is_empty()); - assert_eq!( - spec.canonical_bytes().unwrap(), - spec.canonical_bytes().unwrap() - ); - - assert_eq!(TODO_MODULE.manifest().commands[0], spec); - assert_eq!(TODO_APPLICATION.manifest().modules[0].id, "todo"); - assert_eq!(TODO_APPLICATION.manifest().name, "todo-app"); - assert_eq!( - TODO_APPLICATION.manifest().required_capabilities, - ["events", "identity"] - ); - assert_eq!(IMPLICIT_APPLICATION.manifest().name, "implicit_application"); - - #[cfg(feature = "application-runtime")] - { - assert_eq!(HANDLE_MOUNT.spec().id, "todo.create"); - assert_eq!(HANDLE_MOUNT.spec().fingerprint, spec.fingerprint); - } -} diff --git a/distributed_macros/tests/command_input_defaults.rs b/distributed_macros/tests/command_input_defaults.rs index c115d1e04..a6104fa3c 100644 --- a/distributed_macros/tests/command_input_defaults.rs +++ b/distributed_macros/tests/command_input_defaults.rs @@ -1,17 +1,17 @@ //! Compile-pass checks for command_input_defaults!. -use distributed::graphql::{typed_command, Succeeded}; -use distributed::{command_input_defaults, GraphqlInput}; +use distributed::command::{typed_command, Succeeded}; +use distributed::{command_input_defaults, CommandInput}; use serde::Deserialize; -#[derive(Clone, Deserialize, GraphqlInput)] +#[derive(Clone, Deserialize, CommandInput)] #[allow(dead_code)] struct PlanInput { id: String, title: String, } -#[derive(Clone, serde::Serialize, distributed::GraphqlOutput)] +#[derive(Clone, serde::Serialize, distributed::CommandOutput)] struct PlanOutput { id: String, } diff --git a/distributed_macros/tests/command_input_defaults_compile_fail/duplicate_input_default.rs b/distributed_macros/tests/command_input_defaults_compile_fail/duplicate_input_default.rs index e5d08c435..0fe6841ba 100644 --- a/distributed_macros/tests/command_input_defaults_compile_fail/duplicate_input_default.rs +++ b/distributed_macros/tests/command_input_defaults_compile_fail/duplicate_input_default.rs @@ -1,6 +1,6 @@ -use distributed::{command_input_defaults, GraphqlInput}; +use distributed::{command_input_defaults, CommandInput}; -#[derive(GraphqlInput)] +#[derive(CommandInput)] struct Input { id: String, } diff --git a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.rs b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.rs deleted file mode 100644 index 407564fbd..000000000 --- a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.rs +++ /dev/null @@ -1,13 +0,0 @@ -use distributed::{command_input_defaults, GraphqlInput}; - -#[derive(GraphqlInput)] -struct Input { - ids: Vec, -} - -fn main() { - let _ = command_input_defaults! { - input: Input; - default input.ids = ulid(); - }; -} diff --git a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.stderr b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.stderr deleted file mode 100644 index 7111ab6e4..000000000 --- a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_list.stderr +++ /dev/null @@ -1,21 +0,0 @@ -error[E0271]: type mismatch resolving `<__DistributedInputEffectInputField_ids as EffectInputFieldMarker>::Value == String` - --> tests/command_input_defaults_compile_fail/input_default_list.rs:11:23 - | -11 | default input.ids = ulid(); - | ^^^ type mismatch resolving `<__DistributedInputEffectInputField_ids as EffectInputFieldMarker>::Value == String` - | -note: expected this to be `std::string::String` - --> tests/command_input_defaults_compile_fail/input_default_list.rs:5:10 - | - 5 | ids: Vec, - | ^^^^^^^^^^^ - = note: expected struct `std::string::String` - found struct `Vec` -note: required by a bound in `distributed::graphql::__input_default_ulid` - --> $WORKSPACE/src/graphql/command_contract/effect_wire.rs - | - | pub fn __input_default_ulid() -> CompiledInputDefault - | -------------------- required by a bound in this function -... - | F: EffectInputFieldMarker, - | ^^^^^^^^^^^^^^ required by this bound in `__input_default_ulid` diff --git a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.rs b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.rs deleted file mode 100644 index 85b8563d7..000000000 --- a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.rs +++ /dev/null @@ -1,14 +0,0 @@ -use distributed::{command_input_defaults, GraphqlInput}; -use serde::Deserialize; - -#[derive(Deserialize, GraphqlInput)] -struct Input { - id: Option, -} - -fn main() { - let _ = command_input_defaults! { - input: Input; - default input.id = uuid_v7(); - }; -} diff --git a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.stderr b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.stderr deleted file mode 100644 index 217ed22db..000000000 --- a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_nullable.stderr +++ /dev/null @@ -1,21 +0,0 @@ -error[E0271]: type mismatch resolving `<__DistributedInputEffectInputField_id as EffectInputFieldMarker>::Value == String` - --> tests/command_input_defaults_compile_fail/input_default_nullable.rs:12:23 - | -12 | default input.id = uuid_v7(); - | ^^ type mismatch resolving `<__DistributedInputEffectInputField_id as EffectInputFieldMarker>::Value == String` - | -note: expected this to be `std::string::String` - --> tests/command_input_defaults_compile_fail/input_default_nullable.rs:6:9 - | - 6 | id: Option, - | ^^^^^^^^^^^^^^ - = note: expected struct `std::string::String` - found enum `std::option::Option` -note: required by a bound in `distributed::graphql::__input_default_uuid_v7` - --> $WORKSPACE/src/graphql/command_contract/effect_wire.rs - | - | pub fn __input_default_uuid_v7() -> CompiledInputDefault - | ----------------------- required by a bound in this function -... - | F: EffectInputFieldMarker, - | ^^^^^^^^^^^^^^ required by this bound in `__input_default_uuid_v7` diff --git a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_wrong_type.rs b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_wrong_type.rs deleted file mode 100644 index 79e278999..000000000 --- a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_wrong_type.rs +++ /dev/null @@ -1,13 +0,0 @@ -use distributed::{command_input_defaults, GraphqlInput}; - -#[derive(GraphqlInput)] -struct Input { - count: i64, -} - -fn main() { - let _ = command_input_defaults! { - input: Input; - default input.count = uuid_v7(); - }; -} diff --git a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_wrong_type.stderr b/distributed_macros/tests/command_input_defaults_compile_fail/input_default_wrong_type.stderr deleted file mode 100644 index 1785685f8..000000000 --- a/distributed_macros/tests/command_input_defaults_compile_fail/input_default_wrong_type.stderr +++ /dev/null @@ -1,19 +0,0 @@ -error[E0271]: type mismatch resolving `<__DistributedInputEffectInputField_count as EffectInputFieldMarker>::Value == String` - --> tests/command_input_defaults_compile_fail/input_default_wrong_type.rs:11:23 - | -11 | default input.count = uuid_v7(); - | ^^^^^ type mismatch resolving `<__DistributedInputEffectInputField_count as EffectInputFieldMarker>::Value == String` - | -note: expected this to be `std::string::String` - --> tests/command_input_defaults_compile_fail/input_default_wrong_type.rs:5:12 - | - 5 | count: i64, - | ^^^ -note: required by a bound in `distributed::graphql::__input_default_uuid_v7` - --> $WORKSPACE/src/graphql/command_contract/effect_wire.rs - | - | pub fn __input_default_uuid_v7() -> CompiledInputDefault - | ----------------------- required by a bound in this function -... - | F: EffectInputFieldMarker, - | ^^^^^^^^^^^^^^ required by this bound in `__input_default_uuid_v7` diff --git a/distributed_macros/tests/command_types_compile_fail.rs b/distributed_macros/tests/command_types_compile_fail.rs new file mode 100644 index 000000000..44321cdf7 --- /dev/null +++ b/distributed_macros/tests/command_types_compile_fail.rs @@ -0,0 +1,7 @@ +//! Compile-time diagnostics specific to CommandInput / CommandOutput. + +#[test] +fn command_types_compile_fail() { + let t = trybuild::TestCases::new(); + t.compile_fail("tests/command_types_compile_fail/*.rs"); +} diff --git a/distributed_macros/tests/command_types_compile_fail/nested_lists.rs b/distributed_macros/tests/command_types_compile_fail/nested_lists.rs new file mode 100644 index 000000000..60e698d4f --- /dev/null +++ b/distributed_macros/tests/command_types_compile_fail/nested_lists.rs @@ -0,0 +1,8 @@ +use distributed::CommandInput; + +#[derive(CommandInput)] +struct NestedLists { + values: Option>>>, +} + +fn main() {} diff --git a/distributed_macros/tests/command_types_compile_fail/nested_lists.stderr b/distributed_macros/tests/command_types_compile_fail/nested_lists.stderr new file mode 100644 index 000000000..5a7498fbf --- /dev/null +++ b/distributed_macros/tests/command_types_compile_fail/nested_lists.stderr @@ -0,0 +1,5 @@ +error: nested lists are not supported for CommandInput/CommandOutput fields + --> tests/command_types_compile_fail/nested_lists.rs:5:13 + | +5 | values: Option>>>, + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/distributed_macros/tests/command_types_compile_fail/serde_container_default.rs b/distributed_macros/tests/command_types_compile_fail/serde_container_default.rs new file mode 100644 index 000000000..43b73b2fe --- /dev/null +++ b/distributed_macros/tests/command_types_compile_fail/serde_container_default.rs @@ -0,0 +1,9 @@ +use distributed::CommandInput; + +#[derive(CommandInput)] +#[serde(default = "default_input")] +struct ContainerDefaultInput { + value: String, +} + +fn main() {} diff --git a/distributed_macros/tests/command_types_compile_fail/serde_container_default.stderr b/distributed_macros/tests/command_types_compile_fail/serde_container_default.stderr new file mode 100644 index 000000000..6a418939b --- /dev/null +++ b/distributed_macros/tests/command_types_compile_fail/serde_container_default.stderr @@ -0,0 +1,5 @@ +error: #[serde(default)] is not supported by CommandInput because it changes the declared command object shape; define a separate wire type + --> tests/command_types_compile_fail/serde_container_default.rs:4:9 + | +4 | #[serde(default = "default_input")] + | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/distributed_macros/tests/command_types_compile_fail/serde_default.rs b/distributed_macros/tests/command_types_compile_fail/serde_default.rs new file mode 100644 index 000000000..2ccfbcfd5 --- /dev/null +++ b/distributed_macros/tests/command_types_compile_fail/serde_default.rs @@ -0,0 +1,9 @@ +use distributed::CommandInput; + +#[derive(CommandInput)] +struct DefaultedInput { + #[serde(default)] + value: String, +} + +fn main() {} diff --git a/distributed_macros/tests/command_types_compile_fail/serde_default.stderr b/distributed_macros/tests/command_types_compile_fail/serde_default.stderr new file mode 100644 index 000000000..7c3c9e18d --- /dev/null +++ b/distributed_macros/tests/command_types_compile_fail/serde_default.stderr @@ -0,0 +1,5 @@ +error: #[serde(default)] is not supported by CommandInput because it changes the declared command field shape; define a separate wire type + --> tests/command_types_compile_fail/serde_default.rs:5:13 + | +5 | #[serde(default)] + | ^^^^^^^ diff --git a/distributed_macros/tests/command_types_compile_fail/serde_skip.rs b/distributed_macros/tests/command_types_compile_fail/serde_skip.rs new file mode 100644 index 000000000..26ff6f4fe --- /dev/null +++ b/distributed_macros/tests/command_types_compile_fail/serde_skip.rs @@ -0,0 +1,9 @@ +use distributed::CommandOutput; + +#[derive(CommandOutput)] +struct SkippedOutput { + #[serde(skip_serializing_if = "Option::is_none")] + value: Option, +} + +fn main() {} diff --git a/distributed_macros/tests/command_types_compile_fail/serde_skip.stderr b/distributed_macros/tests/command_types_compile_fail/serde_skip.stderr new file mode 100644 index 000000000..6c2a582b3 --- /dev/null +++ b/distributed_macros/tests/command_types_compile_fail/serde_skip.stderr @@ -0,0 +1,5 @@ +error: #[serde(skip_serializing_if)] is not supported by CommandOutput because it changes the declared command field shape; define a separate wire type + --> tests/command_types_compile_fail/serde_skip.rs:5:13 + | +5 | #[serde(skip_serializing_if = "Option::is_none")] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/distributed_macros/tests/command_types_compile_fail/serde_transparent.rs b/distributed_macros/tests/command_types_compile_fail/serde_transparent.rs new file mode 100644 index 000000000..10d99439c --- /dev/null +++ b/distributed_macros/tests/command_types_compile_fail/serde_transparent.rs @@ -0,0 +1,9 @@ +use distributed::CommandInput; + +#[derive(CommandInput)] +#[serde(transparent)] +struct TransparentInput { + value: String, +} + +fn main() {} diff --git a/distributed_macros/tests/command_types_compile_fail/serde_transparent.stderr b/distributed_macros/tests/command_types_compile_fail/serde_transparent.stderr new file mode 100644 index 000000000..9bcd53272 --- /dev/null +++ b/distributed_macros/tests/command_types_compile_fail/serde_transparent.stderr @@ -0,0 +1,5 @@ +error: #[serde(transparent)] is not supported by CommandInput because it changes the declared command object shape; define a separate wire type + --> tests/command_types_compile_fail/serde_transparent.rs:4:9 + | +4 | #[serde(transparent)] + | ^^^^^^^^^^^ diff --git a/distributed_macros/tests/command_types_compile_fail/serde_with.rs b/distributed_macros/tests/command_types_compile_fail/serde_with.rs new file mode 100644 index 000000000..29cd62f26 --- /dev/null +++ b/distributed_macros/tests/command_types_compile_fail/serde_with.rs @@ -0,0 +1,9 @@ +use distributed::CommandOutput; + +#[derive(CommandOutput)] +struct CustomOutput { + #[serde(with = "wire_value")] + value: String, +} + +fn main() {} diff --git a/distributed_macros/tests/command_types_compile_fail/serde_with.stderr b/distributed_macros/tests/command_types_compile_fail/serde_with.stderr new file mode 100644 index 000000000..eb0e9587a --- /dev/null +++ b/distributed_macros/tests/command_types_compile_fail/serde_with.stderr @@ -0,0 +1,5 @@ +error: #[serde(with)] is not supported by CommandOutput because it changes the declared command field shape; define a separate wire type + --> tests/command_types_compile_fail/serde_with.rs:5:13 + | +5 | #[serde(with = "wire_value")] + | ^^^^^^^^^^^^^^^^^^^ diff --git a/distributed_macros/tests/compile_fail.rs b/distributed_macros/tests/compile_fail.rs index ea5111b5a..a585d2a7a 100644 --- a/distributed_macros/tests/compile_fail.rs +++ b/distributed_macros/tests/compile_fail.rs @@ -5,6 +5,8 @@ //! regressions in diagnostic quality are caught. //! //! Regenerate `.stderr` snapshots with: +//! `rustup component add rust-src` (keeps standard-library source spans aligned +//! with CI), then: //! `TRYBUILD=overwrite cargo test -p distributed_macros` #[test] diff --git a/distributed_macros/tests/compile_fail/aggregate_command_missing_principal.rs b/distributed_macros/tests/compile_fail/aggregate_command_missing_principal.rs new file mode 100644 index 000000000..65412335f --- /dev/null +++ b/distributed_macros/tests/compile_fail/aggregate_command_missing_principal.rs @@ -0,0 +1,26 @@ +use distributed::{sourced, Entity}; +use serde::Deserialize; + +#[derive(Debug, Deserialize, distributed::CommandInput)] +pub struct EquipInput { + pub hero_id: String, + pub owner: String, +} + +#[derive(Default)] +pub struct Hero { + entity: Entity, +} + +#[sourced(entity, aggregate_type = "hero")] +impl Hero { + #[command("hero.equip", shard = hero_id, load = required, outcome = succeeded)] + pub fn equip(&mut self, input: EquipInput) -> Result<(), String> { + let _ = input.owner; + Ok(()) + } +} + +fn main() { + let _ = Hero::default().entity; +} diff --git a/distributed_macros/tests/compile_fail/aggregate_command_missing_principal.stderr b/distributed_macros/tests/compile_fail/aggregate_command_missing_principal.stderr new file mode 100644 index 000000000..fa6fbf4da --- /dev/null +++ b/distributed_macros/tests/compile_fail/aggregate_command_missing_principal.stderr @@ -0,0 +1,5 @@ +error: a #[command] method needs a `#[principal]` parameter (`&str` or `String`): the actor comes from the verified session, never from the input + --> tests/compile_fail/aggregate_command_missing_principal.rs:18:18 + | +18 | pub fn equip(&mut self, input: EquipInput) -> Result<(), String> { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/distributed_macros/tests/compile_fail/aggregate_command_outside_sourced.rs b/distributed_macros/tests/compile_fail/aggregate_command_outside_sourced.rs new file mode 100644 index 000000000..9e6eb6354 --- /dev/null +++ b/distributed_macros/tests/compile_fail/aggregate_command_outside_sourced.rs @@ -0,0 +1,11 @@ +use distributed::command; + +pub struct Hero; + +#[command("hero.equip", shard = hero_id, load = required, outcome = succeeded)] +pub fn equip(actor: &str) -> Result<(), String> { + let _ = actor; + Ok(()) +} + +fn main() {} diff --git a/distributed_macros/tests/compile_fail/aggregate_command_outside_sourced.stderr b/distributed_macros/tests/compile_fail/aggregate_command_outside_sourced.stderr new file mode 100644 index 000000000..001597311 --- /dev/null +++ b/distributed_macros/tests/compile_fail/aggregate_command_outside_sourced.stderr @@ -0,0 +1,11 @@ +error: cannot find attribute `command` in this scope + --> tests/compile_fail/aggregate_command_outside_sourced.rs:5:3 + | +5 | #[command("hero.equip", shard = hero_id, load = required, outcome = succeeded)] + | ^^^^^^^ + | +note: `command` is imported here, but it is a function-like macro + --> tests/compile_fail/aggregate_command_outside_sourced.rs:1:5 + | +1 | use distributed::command; + | ^^^^^^^^^^^^^^^^^^^^ diff --git a/distributed_macros/tests/compile_fail/aggregate_command_payload_needs_type.rs b/distributed_macros/tests/compile_fail/aggregate_command_payload_needs_type.rs new file mode 100644 index 000000000..7746646a6 --- /dev/null +++ b/distributed_macros/tests/compile_fail/aggregate_command_payload_needs_type.rs @@ -0,0 +1,29 @@ +use distributed::{sourced, Entity}; +use serde::Deserialize; + +#[derive(Debug, Deserialize, distributed::CommandInput)] +pub struct EquipInput { + pub hero_id: String, +} + +#[derive(Default)] +pub struct Hero { + entity: Entity, +} + +fn payload(_hero: &Hero) -> u32 { + 0 +} + +#[sourced(entity, aggregate_type = "hero")] +impl Hero { + #[command("hero.equip", shard = hero_id, load = required, outcome = eventual, payload = payload)] + pub fn equip(&mut self, #[principal] actor: &str, input: EquipInput) -> Result<(), String> { + let _ = (actor, input); + Ok(()) + } +} + +fn main() { + let _ = (Hero::default().entity, payload); +} diff --git a/distributed_macros/tests/compile_fail/aggregate_command_payload_needs_type.stderr b/distributed_macros/tests/compile_fail/aggregate_command_payload_needs_type.stderr new file mode 100644 index 000000000..af6ae6a9e --- /dev/null +++ b/distributed_macros/tests/compile_fail/aggregate_command_payload_needs_type.stderr @@ -0,0 +1,5 @@ +error: with `payload = ..` name the payload type: `outcome = Succeeded

` or `Eventual

` + --> tests/compile_fail/aggregate_command_payload_needs_type.rs:20:73 + | +20 | #[command("hero.equip", shard = hero_id, load = required, outcome = eventual, payload = payload)] + | ^^^^^^^^ diff --git a/distributed_macros/tests/compile_fail/aggregate_command_principal_input_field.rs b/distributed_macros/tests/compile_fail/aggregate_command_principal_input_field.rs new file mode 100644 index 000000000..73368d33e --- /dev/null +++ b/distributed_macros/tests/compile_fail/aggregate_command_principal_input_field.rs @@ -0,0 +1,35 @@ +use distributed::{sourced, Entity}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Deserialize, distributed::CommandInput)] +pub struct EquipInput { + pub hero_id: String, + pub actor: String, +} + +#[derive(Debug, Serialize, distributed::CommandOutput)] +pub struct Equipped { + pub hero_id: String, +} + +#[derive(Default)] +pub struct Hero { + entity: Entity, +} + +#[sourced(entity, aggregate_type = "hero")] +impl Hero { + #[command("hero.equip", shard = hero_id, load = required, outcome = succeeded)] + pub fn equip(&mut self, #[principal] actor: &str, input: EquipInput) -> Result { + let _ = (actor, input.actor); + self.touched().map_err(|e| e.to_string())?; + Ok(Equipped { hero_id: input.hero_id }) + } + + #[event("hero.touched")] + fn touched(&mut self) {} +} + +fn main() { + let _ = Hero::default().entity; +} diff --git a/distributed_macros/tests/compile_fail/aggregate_command_principal_input_field.stderr b/distributed_macros/tests/compile_fail/aggregate_command_principal_input_field.stderr new file mode 100644 index 000000000..87d11dc54 --- /dev/null +++ b/distributed_macros/tests/compile_fail/aggregate_command_principal_input_field.stderr @@ -0,0 +1,5 @@ +error[E0080]: evaluation panicked: #[command("hero.equip")]: the input has a field named `actor`, the #[principal] parameter; the principal comes from the verified session only, so it can never be an input field + --> tests/compile_fail/aggregate_command_principal_input_field.rs:23:42 + | +23 | pub fn equip(&mut self, #[principal] actor: &str, input: EquipInput) -> Result { + | ^^^^^ evaluation of `_` failed here diff --git a/distributed_macros/tests/compile_fail/aggregate_unknown_keyword.rs b/distributed_macros/tests/compile_fail/aggregate_unknown_keyword.rs deleted file mode 100644 index 5f0bfd236..000000000 --- a/distributed_macros/tests/compile_fail/aggregate_unknown_keyword.rs +++ /dev/null @@ -1,20 +0,0 @@ -use distributed::{aggregate, Entity}; - -struct Todo { - entity: Entity, -} - -impl Todo { - fn initialize(&mut self, id: String) -> distributed::SourcedResult<()> { - let _ = id; - Ok(()) - } -} - -// The only keyword argument accepted after the entity field is -// `aggregate_type = "..."`; `aggregate_kind` is rejected with a pointed error. -aggregate!(Todo, entity, aggregate_kind = "todos" { - "initialized"(id) => initialize, -}); - -fn main() {} diff --git a/distributed_macros/tests/compile_fail/aggregate_unknown_keyword.stderr b/distributed_macros/tests/compile_fail/aggregate_unknown_keyword.stderr deleted file mode 100644 index 50e5da522..000000000 --- a/distributed_macros/tests/compile_fail/aggregate_unknown_keyword.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: expected `aggregate_type` - --> tests/compile_fail/aggregate_unknown_keyword.rs:16:26 - | -16 | aggregate!(Todo, entity, aggregate_kind = "todos" { - | ^^^^^^^^^^^^^^ diff --git a/distributed_macros/tests/compile_fail/application_command_declared_type_mismatch.rs b/distributed_macros/tests/compile_fail/application_command_declared_type_mismatch.rs deleted file mode 100644 index 8c097363e..000000000 --- a/distributed_macros/tests/compile_fail/application_command_declared_type_mismatch.rs +++ /dev/null @@ -1,21 +0,0 @@ -struct MismatchAggregate; -struct ExpectedInput; -struct ActualInput; - -#[distributed::command( - id = "todo.mismatch", - roles(user), - input = ExpectedInput, - outcome = distributed::graphql::Succeeded -)] -async fn declared_type_mismatch( - _context: &distributed::microsvc::CausalCommandContext<'_, MismatchAggregate>, - _input: ActualInput, -) -> Result< - distributed::graphql::PreparedCommand>, - distributed::microsvc::HandlerError, -> { - unreachable!() -} - -fn main() {} diff --git a/distributed_macros/tests/compile_fail/application_command_declared_type_mismatch.stderr b/distributed_macros/tests/compile_fail/application_command_declared_type_mismatch.stderr deleted file mode 100644 index 436554e9e..000000000 --- a/distributed_macros/tests/compile_fail/application_command_declared_type_mismatch.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: handler input parameter does not match the declared `input = ...` type - --> tests/compile_fail/application_command_declared_type_mismatch.rs:13:13 - | -13 | _input: ActualInput, - | ^^^^^^^^^^^ diff --git a/distributed_macros/tests/compile_fail/application_command_duplicate_id.rs b/distributed_macros/tests/compile_fail/application_command_duplicate_id.rs deleted file mode 100644 index 38c11ade6..000000000 --- a/distributed_macros/tests/compile_fail/application_command_duplicate_id.rs +++ /dev/null @@ -1,45 +0,0 @@ -use std::sync::LazyLock; - -use distributed::application::{CommandDefinition, CommandSpec, CommandTypeField, CommandTypeSpec}; -use distributed::graphql::CommandConsistency; - -fn spec() -> CommandSpec { - CommandSpec::try_new( - "todo.duplicate", - "todo_duplicate", - CommandTypeSpec { - name: "DuplicateInput".into(), - fields: vec![CommandTypeField { - name: "id".into(), - type_name: "String".into(), - nullable: false, - list: false, - item_nullable: false, - nested: None, - }], - }, - CommandTypeSpec { - name: "DuplicateOutput".into(), - fields: Vec::new(), - }, - CommandConsistency::Eventual, - ) - .unwrap() -} - -static FIRST_DEFINITION: LazyLock = - LazyLock::new(|| CommandDefinition::contract(spec())); -static SECOND_DEFINITION: LazyLock = - LazyLock::new(|| CommandDefinition::contract(spec())); - -const FIRST_COMMAND_ID: &str = "todo.duplicate"; -const SECOND_COMMAND_ID: &str = "todo.duplicate"; - -distributed::module! { - pub DUPLICATE_MODULE { - id: "duplicates", - commands: [FIRST_DEFINITION, SECOND_DEFINITION], - } -} - -fn main() {} diff --git a/distributed_macros/tests/compile_fail/application_command_duplicate_id.stderr b/distributed_macros/tests/compile_fail/application_command_duplicate_id.stderr deleted file mode 100644 index 5377eae50..000000000 --- a/distributed_macros/tests/compile_fail/application_command_duplicate_id.stderr +++ /dev/null @@ -1,21 +0,0 @@ -error[E0080]: evaluation panicked: duplicate command identity in module declaration - --> tests/compile_fail/application_command_duplicate_id.rs:38:1 - | -38 | / distributed::module! { -39 | | pub DUPLICATE_MODULE { -40 | | id: "duplicates", -41 | | commands: [FIRST_DEFINITION, SECOND_DEFINITION], -42 | | } -43 | | } - | |_^ evaluation of `_` failed inside this call - | -note: inside `assert_unique_command_ids` - --> $RUST/core/src/panic.rs - | - | $crate::panicking::panic_fmt($crate::const_format_args!($($t)+)); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the failure occurred here - | - ::: $WORKSPACE/src/application/mod.rs - | - | panic!("duplicate command identity in module declaration"); - | ---------------------------------------------------------- in this macro invocation diff --git a/distributed_macros/tests/compile_fail/application_command_duplicate_option.rs b/distributed_macros/tests/compile_fail/application_command_duplicate_option.rs deleted file mode 100644 index bde61a0fe..000000000 --- a/distributed_macros/tests/compile_fail/application_command_duplicate_option.rs +++ /dev/null @@ -1,21 +0,0 @@ -struct Aggregate; -struct Input; - -#[distributed::command( - id = "todo.create", - id = "todo.rename", - roles(user), - input = Input, - outcome = distributed::graphql::Succeeded -)] -async fn duplicate_option( - _context: &distributed::microsvc::CausalCommandContext<'_, Aggregate>, - _input: Input, -) -> Result< - distributed::graphql::PreparedCommand>, - distributed::microsvc::HandlerError, -> { - unreachable!() -} - -fn main() {} diff --git a/distributed_macros/tests/compile_fail/application_command_duplicate_option.stderr b/distributed_macros/tests/compile_fail/application_command_duplicate_option.stderr deleted file mode 100644 index 3b93dc887..000000000 --- a/distributed_macros/tests/compile_fail/application_command_duplicate_option.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: duplicate command option id - --> tests/compile_fail/application_command_duplicate_option.rs:6:5 - | -6 | id = "todo.rename", - | ^^ diff --git a/distributed_macros/tests/compile_fail/application_command_duplicate_role.rs b/distributed_macros/tests/compile_fail/application_command_duplicate_role.rs deleted file mode 100644 index d498453c3..000000000 --- a/distributed_macros/tests/compile_fail/application_command_duplicate_role.rs +++ /dev/null @@ -1,20 +0,0 @@ -struct Aggregate; -struct Input; - -#[distributed::command( - id = "todo.create", - roles(user, user), - input = Input, - outcome = distributed::graphql::Succeeded -)] -async fn duplicate_role( - _context: &distributed::microsvc::CausalCommandContext<'_, Aggregate>, - _input: Input, -) -> Result< - distributed::graphql::PreparedCommand>, - distributed::microsvc::HandlerError, -> { - unreachable!() -} - -fn main() {} diff --git a/distributed_macros/tests/compile_fail/application_command_duplicate_role.stderr b/distributed_macros/tests/compile_fail/application_command_duplicate_role.stderr deleted file mode 100644 index e70a54a2c..000000000 --- a/distributed_macros/tests/compile_fail/application_command_duplicate_role.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: command roles must not contain duplicates - --> tests/compile_fail/application_command_duplicate_role.rs:6:17 - | -6 | roles(user, user), - | ^^^^ diff --git a/distributed_macros/tests/compile_fail/application_command_empty_roles.rs b/distributed_macros/tests/compile_fail/application_command_empty_roles.rs deleted file mode 100644 index 6846e99ac..000000000 --- a/distributed_macros/tests/compile_fail/application_command_empty_roles.rs +++ /dev/null @@ -1,20 +0,0 @@ -struct Aggregate; -struct Input; - -#[distributed::command( - id = "todo.create", - roles(), - input = Input, - outcome = distributed::graphql::Succeeded -)] -async fn empty_roles( - _context: &distributed::microsvc::CausalCommandContext<'_, Aggregate>, - _input: Input, -) -> Result< - distributed::graphql::PreparedCommand>, - distributed::microsvc::HandlerError, -> { - unreachable!() -} - -fn main() {} diff --git a/distributed_macros/tests/compile_fail/application_command_empty_roles.stderr b/distributed_macros/tests/compile_fail/application_command_empty_roles.stderr deleted file mode 100644 index 1c5b79d2f..000000000 --- a/distributed_macros/tests/compile_fail/application_command_empty_roles.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: unexpected end of input, command roles must declare at least one role; use an explicit anonymous role when intended - --> tests/compile_fail/application_command_empty_roles.rs:6:11 - | -6 | roles(), - | ^ diff --git a/distributed_macros/tests/compile_fail/application_command_invalid_id.rs b/distributed_macros/tests/compile_fail/application_command_invalid_id.rs deleted file mode 100644 index 722f23943..000000000 --- a/distributed_macros/tests/compile_fail/application_command_invalid_id.rs +++ /dev/null @@ -1,20 +0,0 @@ -struct Aggregate; -struct Input; - -#[distributed::command( - id = "../Admin", - roles(admin), - input = Input, - outcome = distributed::graphql::Succeeded -)] -async fn invalid_id( - _context: &distributed::microsvc::CausalCommandContext<'_, Aggregate>, - _input: Input, -) -> Result< - distributed::graphql::PreparedCommand>, - distributed::microsvc::HandlerError, -> { - unreachable!() -} - -fn main() {} diff --git a/distributed_macros/tests/compile_fail/application_command_invalid_id.stderr b/distributed_macros/tests/compile_fail/application_command_invalid_id.stderr deleted file mode 100644 index 54791173c..000000000 --- a/distributed_macros/tests/compile_fail/application_command_invalid_id.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: command id must be 2+ dot-separated lowercase ASCII identifier segments - --> tests/compile_fail/application_command_invalid_id.rs:5:10 - | -5 | id = "../Admin", - | ^^^^^^^^^^ diff --git a/distributed_macros/tests/compile_fail/application_command_missing_id.rs b/distributed_macros/tests/compile_fail/application_command_missing_id.rs deleted file mode 100644 index 79e63dbce..000000000 --- a/distributed_macros/tests/compile_fail/application_command_missing_id.rs +++ /dev/null @@ -1,4 +0,0 @@ -#[distributed::command] -async fn missing_id(_context: (), _input: ()) {} - -fn main() {} diff --git a/distributed_macros/tests/compile_fail/application_command_missing_id.stderr b/distributed_macros/tests/compile_fail/application_command_missing_id.stderr deleted file mode 100644 index 68126840f..000000000 --- a/distributed_macros/tests/compile_fail/application_command_missing_id.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: command declaration requires `id = "..."` - --> tests/compile_fail/application_command_missing_id.rs:2:10 - | -2 | async fn missing_id(_context: (), _input: ()) {} - | ^^^^^^^^^^ diff --git a/distributed_macros/tests/compile_fail/application_command_missing_roles.rs b/distributed_macros/tests/compile_fail/application_command_missing_roles.rs deleted file mode 100644 index d1aa37d18..000000000 --- a/distributed_macros/tests/compile_fail/application_command_missing_roles.rs +++ /dev/null @@ -1,19 +0,0 @@ -struct Aggregate; -struct Input; - -#[distributed::command( - id = "todo.create", - input = Input, - outcome = distributed::graphql::Succeeded -)] -async fn missing_roles( - _context: &distributed::microsvc::CausalCommandContext<'_, Aggregate>, - _input: Input, -) -> Result< - distributed::graphql::PreparedCommand>, - distributed::microsvc::HandlerError, -> { - unreachable!() -} - -fn main() {} diff --git a/distributed_macros/tests/compile_fail/application_command_missing_roles.stderr b/distributed_macros/tests/compile_fail/application_command_missing_roles.stderr deleted file mode 100644 index d81232cba..000000000 --- a/distributed_macros/tests/compile_fail/application_command_missing_roles.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: command declaration requires explicit roles(...) - --> tests/compile_fail/application_command_missing_roles.rs:9:10 - | -9 | async fn missing_roles( - | ^^^^^^^^^^^^^ diff --git a/distributed_macros/tests/compile_fail/application_command_wrong_handler.rs b/distributed_macros/tests/compile_fail/application_command_wrong_handler.rs deleted file mode 100644 index f022ebcc3..000000000 --- a/distributed_macros/tests/compile_fail/application_command_wrong_handler.rs +++ /dev/null @@ -1,17 +0,0 @@ -struct WrongAggregate; -struct WrongInput; - -#[distributed::command( - id = "todo.create", - roles(user), - input = WrongInput, - outcome = distributed::graphql::Succeeded -)] -async fn wrong_handler( - _context: &distributed::microsvc::CausalCommandContext<'_, WrongAggregate>, - _input: WrongInput, -) -> Result<(), distributed::microsvc::HandlerError> { - Ok(()) -} - -fn main() {} diff --git a/distributed_macros/tests/compile_fail/application_command_wrong_handler.stderr b/distributed_macros/tests/compile_fail/application_command_wrong_handler.stderr deleted file mode 100644 index fd9c910ee..000000000 --- a/distributed_macros/tests/compile_fail/application_command_wrong_handler.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: first Result type must be PreparedCommand - --> tests/compile_fail/application_command_wrong_handler.rs:13:13 - | -13 | ) -> Result<(), distributed::microsvc::HandlerError> { - | ^^ diff --git a/distributed_macros/tests/compile_fail/application_module_missing_spec.rs b/distributed_macros/tests/compile_fail/application_module_missing_spec.rs deleted file mode 100644 index 2f01bf299..000000000 --- a/distributed_macros/tests/compile_fail/application_module_missing_spec.rs +++ /dev/null @@ -1,9 +0,0 @@ -distributed::module! { - pub TODO_MODULE { - id: "todo", - commands: [], - mounts: [MISSING_COMMAND_MOUNT], - } -} - -fn main() {} diff --git a/distributed_macros/tests/compile_fail/application_module_missing_spec.stderr b/distributed_macros/tests/compile_fail/application_module_missing_spec.stderr deleted file mode 100644 index d6945e08c..000000000 --- a/distributed_macros/tests/compile_fail/application_module_missing_spec.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: command declarations derive their optional runtime mount; maintain one `commands: [*_DEFINITION]` list and remove `mounts` - --> tests/compile_fail/application_module_missing_spec.rs:5:9 - | -5 | mounts: [MISSING_COMMAND_MOUNT], - | ^^^^^^ diff --git a/distributed_macros/tests/compile_fail/application_module_unknown_field.rs b/distributed_macros/tests/compile_fail/application_module_unknown_field.rs deleted file mode 100644 index 58750c207..000000000 --- a/distributed_macros/tests/compile_fail/application_module_unknown_field.rs +++ /dev/null @@ -1,8 +0,0 @@ -distributed::module! { - pub TODO_MODULE { - id: "todo", - unknown: [], - } -} - -fn main() {} diff --git a/distributed_macros/tests/compile_fail/application_module_unknown_field.stderr b/distributed_macros/tests/compile_fail/application_module_unknown_field.stderr deleted file mode 100644 index 8557ec0c3..000000000 --- a/distributed_macros/tests/compile_fail/application_module_unknown_field.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: unknown module field `unknown` - --> tests/compile_fail/application_module_unknown_field.rs:4:9 - | -4 | unknown: [], - | ^^^^^^^ diff --git a/distributed_macros/tests/compile_fail/digest_unsupported_param_pattern.rs b/distributed_macros/tests/compile_fail/digest_unsupported_param_pattern.rs deleted file mode 100644 index 65eb5d1e2..000000000 --- a/distributed_macros/tests/compile_fail/digest_unsupported_param_pattern.rs +++ /dev/null @@ -1,15 +0,0 @@ -use distributed::{digest, Entity}; - -struct Todo { - entity: Entity, -} - -impl Todo { - // `_` has no name to record in the event payload, so the parameter would - // silently vanish from the digest call. Parameters must be plain - // identifiers. - #[digest("initialized")] - pub fn initialize(&mut self, _: String) {} -} - -fn main() {} diff --git a/distributed_macros/tests/compile_fail/digest_unsupported_param_pattern.stderr b/distributed_macros/tests/compile_fail/digest_unsupported_param_pattern.stderr deleted file mode 100644 index e52e15bab..000000000 --- a/distributed_macros/tests/compile_fail/digest_unsupported_param_pattern.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: unsupported parameter pattern in #[digest] method — use a plain identifier - --> tests/compile_fail/digest_unsupported_param_pattern.rs:12:34 - | -12 | pub fn initialize(&mut self, _: String) {} - | ^ diff --git a/distributed_macros/tests/compile_fail/domain_early_return_recorder.stderr b/distributed_macros/tests/compile_fail/domain_early_return_recorder.stderr index c635672c2..5361fd3fb 100644 --- a/distributed_macros/tests/compile_fail/domain_early_return_recorder.stderr +++ b/distributed_macros/tests/compile_fail/domain_early_return_recorder.stderr @@ -1,4 +1,4 @@ -error: domain-marked #[event] methods cannot use `return` in version one because it skips post-transition capture +error: #[event] methods cannot use `return`: it would skip the rest of the recorded transition --> tests/compile_fail/domain_early_return_recorder.rs:12:9 | 12 | return; diff --git a/distributed_macros/tests/compile_fail/domain_fallible_recorder.stderr b/distributed_macros/tests/compile_fail/domain_fallible_recorder.stderr index c0e6fed22..af3432927 100644 --- a/distributed_macros/tests/compile_fail/domain_fallible_recorder.stderr +++ b/distributed_macros/tests/compile_fail/domain_fallible_recorder.stderr @@ -1,5 +1,5 @@ -error: domain-marked #[event] methods must omit the return type in version one; fallible recorders cannot prove post-transition capture safety - --> tests/compile_fail/domain_fallible_recorder.rs:10:28 +error: #[event] methods must omit the return type: the event is recorded before the body runs, so the body cannot fail. Validate in the method that calls the recorder + --> tests/compile_fail/domain_fallible_recorder.rs:10:31 | 10 | fn complete(&mut self) -> distributed::SourcedResult { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/distributed_macros/tests/compile_fail/domain_inferred_try_recorder.stderr b/distributed_macros/tests/compile_fail/domain_inferred_try_recorder.stderr index 8fc4e601c..e4b7c99b6 100644 --- a/distributed_macros/tests/compile_fail/domain_inferred_try_recorder.stderr +++ b/distributed_macros/tests/compile_fail/domain_inferred_try_recorder.stderr @@ -1,4 +1,4 @@ -error: domain-marked #[event] methods cannot use `?` in version one because it may skip post-transition capture +error: #[event] methods cannot use `?`: the event is already recorded when the body runs, so the body cannot fail --> tests/compile_fail/domain_inferred_try_recorder.rs:18:9 | 18 | self.validate()?; diff --git a/distributed_macros/tests/compile_fail/enqueue_renamed_entity.rs b/distributed_macros/tests/compile_fail/enqueue_renamed_entity.rs deleted file mode 100644 index 72e49c0a1..000000000 --- a/distributed_macros/tests/compile_fail/enqueue_renamed_entity.rs +++ /dev/null @@ -1,28 +0,0 @@ -use distributed_macros::enqueue; - -struct Entity; - -struct EntityEmitter; - -impl EntityEmitter { - fn enqueue_with(&mut self, _: &str, _: &T) -> distributed::SourcedResult<()> { - Ok(()) - } -} - -// The entity field is named `state`, not `entity`. Without telling `#[enqueue]` -// about the rename (via `entity = state`), the generated replay guard references -// the non-existent `self.entity` field. The fix is `#[enqueue("...", entity = state)]`. -struct Order { - state: Entity, - emitter: EntityEmitter, -} - -impl Order { - #[enqueue("order.initialized")] - pub fn create(&mut self, id: String) { - let _ = id; - } -} - -fn main() {} diff --git a/distributed_macros/tests/compile_fail/enqueue_renamed_entity.stderr b/distributed_macros/tests/compile_fail/enqueue_renamed_entity.stderr deleted file mode 100644 index dabbb80cf..000000000 --- a/distributed_macros/tests/compile_fail/enqueue_renamed_entity.stderr +++ /dev/null @@ -1,7 +0,0 @@ -error[E0609]: no field `entity` on type `&mut Order` - --> tests/compile_fail/enqueue_renamed_entity.rs:22:5 - | -22 | #[enqueue("order.initialized")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unknown field - | - = note: this error originates in the attribute macro `enqueue` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/distributed_macros/tests/compile_fail/event_fallible_recorder.rs b/distributed_macros/tests/compile_fail/event_fallible_recorder.rs new file mode 100644 index 000000000..a194033b8 --- /dev/null +++ b/distributed_macros/tests/compile_fail/event_fallible_recorder.rs @@ -0,0 +1,23 @@ +use distributed::{sourced, Entity}; + +#[derive(Default)] +struct Todo { + entity: Entity, + title: String, +} + +#[sourced(entity)] +impl Todo { + // The event is recorded before this body runs: an `Err` here would leave + // a stored event whose state change never happened. + #[event("todo.renamed")] + fn rename(&mut self, title: String) -> Result<(), String> { + if title.is_empty() { + return Err("empty".into()); + } + self.title = title; + Ok(()) + } +} + +fn main() {} diff --git a/distributed_macros/tests/compile_fail/event_fallible_recorder.stderr b/distributed_macros/tests/compile_fail/event_fallible_recorder.stderr new file mode 100644 index 000000000..d4dd12c5e --- /dev/null +++ b/distributed_macros/tests/compile_fail/event_fallible_recorder.stderr @@ -0,0 +1,5 @@ +error: #[event] methods must omit the return type: the event is recorded before the body runs, so the body cannot fail. Validate in the method that calls the recorder + --> tests/compile_fail/event_fallible_recorder.rs:14:44 + | +14 | fn rename(&mut self, title: String) -> Result<(), String> { + | ^^^^^^^^^^^^^^^^^^ diff --git a/distributed_macros/tests/compile_fail/event_try_in_recorder.rs b/distributed_macros/tests/compile_fail/event_try_in_recorder.rs new file mode 100644 index 000000000..d42307c00 --- /dev/null +++ b/distributed_macros/tests/compile_fail/event_try_in_recorder.rs @@ -0,0 +1,22 @@ +use distributed::{sourced, Entity, SourcedResult}; + +#[derive(Default)] +struct Todo { + entity: Entity, +} + +impl Todo { + fn validate(&self) -> SourcedResult { + Ok(()) + } +} + +#[sourced(entity)] +impl Todo { + #[event("todo.completed")] + fn complete(&mut self) { + self.validate()?; + } +} + +fn main() {} diff --git a/distributed_macros/tests/compile_fail/event_try_in_recorder.stderr b/distributed_macros/tests/compile_fail/event_try_in_recorder.stderr new file mode 100644 index 000000000..fdc45f7fa --- /dev/null +++ b/distributed_macros/tests/compile_fail/event_try_in_recorder.stderr @@ -0,0 +1,5 @@ +error: #[event] methods cannot use `?`: the event is already recorded when the body runs, so the body cannot fail + --> tests/compile_fail/event_try_in_recorder.rs:18:9 + | +18 | self.validate()?; + | ^^^^^^^^^^^^^^^^ diff --git a/distributed_macros/tests/compile_fail/unknown_digest_key.rs b/distributed_macros/tests/compile_fail/unknown_digest_key.rs deleted file mode 100644 index d812f986b..000000000 --- a/distributed_macros/tests/compile_fail/unknown_digest_key.rs +++ /dev/null @@ -1,16 +0,0 @@ -use distributed::{digest, Entity}; - -struct Todo { - entity: Entity, -} - -impl Todo { - // Typo: `versoin` is not a recognized key. The diagnostic should name the - // bad key and list the valid ones. - #[digest("x", versoin = 2)] - pub fn initialize(&mut self, id: String) { - let _ = id; - } -} - -fn main() {} diff --git a/distributed_macros/tests/compile_fail/unknown_digest_key.stderr b/distributed_macros/tests/compile_fail/unknown_digest_key.stderr deleted file mode 100644 index f3ddfae53..000000000 --- a/distributed_macros/tests/compile_fail/unknown_digest_key.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: unsupported key `versoin` in #[digest(...)]; expected `when` or `version` - --> tests/compile_fail/unknown_digest_key.rs:10:19 - | -10 | #[digest("x", versoin = 2)] - | ^^^^^^^ diff --git a/distributed_macros/tests/graphql_compile_fail.rs b/distributed_macros/tests/graphql_compile_fail.rs deleted file mode 100644 index 2cbead39d..000000000 --- a/distributed_macros/tests/graphql_compile_fail.rs +++ /dev/null @@ -1,7 +0,0 @@ -//! Compile-time diagnostics specific to GraphqlInput / GraphqlOutput. - -#[test] -fn graphql_compile_fail() { - let t = trybuild::TestCases::new(); - t.compile_fail("tests/graphql_compile_fail/*.rs"); -} diff --git a/distributed_macros/tests/graphql_compile_fail/nested_lists.rs b/distributed_macros/tests/graphql_compile_fail/nested_lists.rs deleted file mode 100644 index 79e900306..000000000 --- a/distributed_macros/tests/graphql_compile_fail/nested_lists.rs +++ /dev/null @@ -1,8 +0,0 @@ -use distributed::GraphqlInput; - -#[derive(GraphqlInput)] -struct NestedLists { - values: Option>>>, -} - -fn main() {} diff --git a/distributed_macros/tests/graphql_compile_fail/nested_lists.stderr b/distributed_macros/tests/graphql_compile_fail/nested_lists.stderr deleted file mode 100644 index b3159e93f..000000000 --- a/distributed_macros/tests/graphql_compile_fail/nested_lists.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: nested lists are not supported for GraphqlInput/GraphqlOutput fields - --> tests/graphql_compile_fail/nested_lists.rs:5:13 - | -5 | values: Option>>>, - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/distributed_macros/tests/graphql_compile_fail/serde_container_default.rs b/distributed_macros/tests/graphql_compile_fail/serde_container_default.rs deleted file mode 100644 index deb0cb832..000000000 --- a/distributed_macros/tests/graphql_compile_fail/serde_container_default.rs +++ /dev/null @@ -1,9 +0,0 @@ -use distributed::GraphqlInput; - -#[derive(GraphqlInput)] -#[serde(default = "default_input")] -struct ContainerDefaultInput { - value: String, -} - -fn main() {} diff --git a/distributed_macros/tests/graphql_compile_fail/serde_container_default.stderr b/distributed_macros/tests/graphql_compile_fail/serde_container_default.stderr deleted file mode 100644 index 6ad3ec642..000000000 --- a/distributed_macros/tests/graphql_compile_fail/serde_container_default.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: #[serde(default)] is not supported by GraphqlInput because it changes the declared GraphQL object shape; define a separate wire type - --> tests/graphql_compile_fail/serde_container_default.rs:4:9 - | -4 | #[serde(default = "default_input")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/distributed_macros/tests/graphql_compile_fail/serde_default.rs b/distributed_macros/tests/graphql_compile_fail/serde_default.rs deleted file mode 100644 index ca4633108..000000000 --- a/distributed_macros/tests/graphql_compile_fail/serde_default.rs +++ /dev/null @@ -1,9 +0,0 @@ -use distributed::GraphqlInput; - -#[derive(GraphqlInput)] -struct DefaultedInput { - #[serde(default)] - value: String, -} - -fn main() {} diff --git a/distributed_macros/tests/graphql_compile_fail/serde_default.stderr b/distributed_macros/tests/graphql_compile_fail/serde_default.stderr deleted file mode 100644 index a2fc841e6..000000000 --- a/distributed_macros/tests/graphql_compile_fail/serde_default.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: #[serde(default)] is not supported by GraphqlInput because it changes the declared GraphQL field shape; define a separate wire type - --> tests/graphql_compile_fail/serde_default.rs:5:13 - | -5 | #[serde(default)] - | ^^^^^^^ diff --git a/distributed_macros/tests/graphql_compile_fail/serde_kebab_case.rs b/distributed_macros/tests/graphql_compile_fail/serde_kebab_case.rs deleted file mode 100644 index 375917b7e..000000000 --- a/distributed_macros/tests/graphql_compile_fail/serde_kebab_case.rs +++ /dev/null @@ -1,9 +0,0 @@ -use distributed::GraphqlOutput; - -#[derive(GraphqlOutput)] -#[serde(rename_all = "kebab-case")] -struct KebabCase { - field_name: String, -} - -fn main() {} diff --git a/distributed_macros/tests/graphql_compile_fail/serde_kebab_case.stderr b/distributed_macros/tests/graphql_compile_fail/serde_kebab_case.stderr deleted file mode 100644 index 1197d3830..000000000 --- a/distributed_macros/tests/graphql_compile_fail/serde_kebab_case.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: serde kebab-case field names cannot be represented in GraphQL; use camelCase or snake_case - --> tests/graphql_compile_fail/serde_kebab_case.rs:4:22 - | -4 | #[serde(rename_all = "kebab-case")] - | ^^^^^^^^^^^^ diff --git a/distributed_macros/tests/graphql_compile_fail/serde_skip.rs b/distributed_macros/tests/graphql_compile_fail/serde_skip.rs deleted file mode 100644 index e7f761f58..000000000 --- a/distributed_macros/tests/graphql_compile_fail/serde_skip.rs +++ /dev/null @@ -1,9 +0,0 @@ -use distributed::GraphqlOutput; - -#[derive(GraphqlOutput)] -struct SkippedOutput { - #[serde(skip_serializing_if = "Option::is_none")] - value: Option, -} - -fn main() {} diff --git a/distributed_macros/tests/graphql_compile_fail/serde_skip.stderr b/distributed_macros/tests/graphql_compile_fail/serde_skip.stderr deleted file mode 100644 index dde249172..000000000 --- a/distributed_macros/tests/graphql_compile_fail/serde_skip.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: #[serde(skip_serializing_if)] is not supported by GraphqlOutput because it changes the declared GraphQL field shape; define a separate wire type - --> tests/graphql_compile_fail/serde_skip.rs:5:13 - | -5 | #[serde(skip_serializing_if = "Option::is_none")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/distributed_macros/tests/graphql_compile_fail/serde_transparent.rs b/distributed_macros/tests/graphql_compile_fail/serde_transparent.rs deleted file mode 100644 index 238801538..000000000 --- a/distributed_macros/tests/graphql_compile_fail/serde_transparent.rs +++ /dev/null @@ -1,9 +0,0 @@ -use distributed::GraphqlInput; - -#[derive(GraphqlInput)] -#[serde(transparent)] -struct TransparentInput { - value: String, -} - -fn main() {} diff --git a/distributed_macros/tests/graphql_compile_fail/serde_transparent.stderr b/distributed_macros/tests/graphql_compile_fail/serde_transparent.stderr deleted file mode 100644 index c8d1159dc..000000000 --- a/distributed_macros/tests/graphql_compile_fail/serde_transparent.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: #[serde(transparent)] is not supported by GraphqlInput because it changes the declared GraphQL object shape; define a separate wire type - --> tests/graphql_compile_fail/serde_transparent.rs:4:9 - | -4 | #[serde(transparent)] - | ^^^^^^^^^^^ diff --git a/distributed_macros/tests/graphql_compile_fail/serde_with.rs b/distributed_macros/tests/graphql_compile_fail/serde_with.rs deleted file mode 100644 index a921590e1..000000000 --- a/distributed_macros/tests/graphql_compile_fail/serde_with.rs +++ /dev/null @@ -1,9 +0,0 @@ -use distributed::GraphqlOutput; - -#[derive(GraphqlOutput)] -struct CustomOutput { - #[serde(with = "wire_value")] - value: String, -} - -fn main() {} diff --git a/distributed_macros/tests/graphql_compile_fail/serde_with.stderr b/distributed_macros/tests/graphql_compile_fail/serde_with.stderr deleted file mode 100644 index 0707da8a9..000000000 --- a/distributed_macros/tests/graphql_compile_fail/serde_with.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: #[serde(with)] is not supported by GraphqlOutput because it changes the declared GraphQL field shape; define a separate wire type - --> tests/graphql_compile_fail/serde_with.rs:5:13 - | -5 | #[serde(with = "wire_value")] - | ^^^^^^^^^^^^^^^^^^^ diff --git a/distributed_macros/tests/rustc_fail.rs b/distributed_macros/tests/rustc_fail.rs new file mode 100644 index 000000000..f68ba46ec --- /dev/null +++ b/distributed_macros/tests/rustc_fail.rs @@ -0,0 +1,48 @@ +//! Compile failures whose message is rustc's, not the macro's (a trait bound +//! or a type mismatch in generated code). Each must fail and name its cause; +//! the full rendering is not pinned. See `tests/support/rustc_fail.rs`. + +#[path = "../../tests/support/rustc_fail.rs"] +mod rustc_fail; + +#[test] +fn rustc_rejects_generated_code_for_the_named_cause() { + rustc_fail::assert_fail_with( + env!("CARGO_MANIFEST_DIR"), + "tests/rustc_fail", + r#"distributed = { path = "{workspace}" } +serde = { version = "1", features = ["derive"] }"#, + &[ + // A generated input default only fits a `String` field. + ( + "input_default_list", + &[ + "E0271", + "Value == String", + "InputField_ids as EffectInputFieldMarker", + ], + ), + ( + "input_default_nullable", + &[ + "E0271", + "Value == String", + "InputField_id as EffectInputFieldMarker", + ], + ), + ( + "input_default_wrong_type", + &[ + "E0271", + "Value == String", + "InputField_count as EffectInputFieldMarker", + ], + ), + // Only methods that record on `self` become domain commands. + ( + "sourced_helper_other_receiver", + &["cannot find type `Unrelated` in module `domain_commands`"], + ), + ], + ); +} diff --git a/distributed_macros/tests/rustc_fail/input_default_list.rs b/distributed_macros/tests/rustc_fail/input_default_list.rs new file mode 100644 index 000000000..71e0cd81f --- /dev/null +++ b/distributed_macros/tests/rustc_fail/input_default_list.rs @@ -0,0 +1,13 @@ +use distributed::{command_input_defaults, CommandInput}; + +#[derive(CommandInput)] +struct Input { + ids: Vec, +} + +fn main() { + let _ = command_input_defaults! { + input: Input; + default input.ids = ulid(); + }; +} diff --git a/distributed_macros/tests/rustc_fail/input_default_nullable.rs b/distributed_macros/tests/rustc_fail/input_default_nullable.rs new file mode 100644 index 000000000..39e407d28 --- /dev/null +++ b/distributed_macros/tests/rustc_fail/input_default_nullable.rs @@ -0,0 +1,14 @@ +use distributed::{command_input_defaults, CommandInput}; +use serde::Deserialize; + +#[derive(Deserialize, CommandInput)] +struct Input { + id: Option, +} + +fn main() { + let _ = command_input_defaults! { + input: Input; + default input.id = uuid_v7(); + }; +} diff --git a/distributed_macros/tests/rustc_fail/input_default_wrong_type.rs b/distributed_macros/tests/rustc_fail/input_default_wrong_type.rs new file mode 100644 index 000000000..baef4e689 --- /dev/null +++ b/distributed_macros/tests/rustc_fail/input_default_wrong_type.rs @@ -0,0 +1,13 @@ +use distributed::{command_input_defaults, CommandInput}; + +#[derive(CommandInput)] +struct Input { + count: i64, +} + +fn main() { + let _ = command_input_defaults! { + input: Input; + default input.count = uuid_v7(); + }; +} diff --git a/distributed_macros/tests/rustc_fail/sourced_helper_other_receiver.rs b/distributed_macros/tests/rustc_fail/sourced_helper_other_receiver.rs new file mode 100644 index 000000000..ccf769d36 --- /dev/null +++ b/distributed_macros/tests/rustc_fail/sourced_helper_other_receiver.rs @@ -0,0 +1,40 @@ +use distributed::{sourced, Entity}; + +#[derive(Default)] +pub struct Todo { + entity: Entity, + completed: bool, +} + +#[sourced(entity, aggregate_type = "todo")] +impl Todo { + pub fn complete(&mut self) -> distributed::SourcedResult { + self.record_completed()?; + Ok(()) + } + + // Records on another receiver and through a nested item's `self`: neither + // is this aggregate's transition, so no `domain_commands::Unrelated`. + pub fn unrelated(&mut self, other: &mut Todo) { + other.record_completed().unwrap(); + struct Other; + impl Other { + #[allow(dead_code)] + fn record_completed(&mut self) {} + #[allow(dead_code)] + fn action(&mut self) { + self.record_completed(); + } + } + } + + #[event("todo.completed", domain = event)] + fn record_completed(&mut self) { + self.completed = true; + } +} + +fn main() { + let _: Option = None; + let _: Option = None; +} diff --git a/docs/application-composition.md b/docs/application-composition.md index 884d1b5e6..0dcc70652 100644 --- a/docs/application-composition.md +++ b/docs/application-composition.md @@ -4,7 +4,7 @@ **Goal:** Make the same packages easy to run as a monolith or as microservices, with persistence/locks/transports as a separate, boring plane. **Non-goal:** Back-compat aliases or dual public APIs for the same concept. -Related pain today: `tests/e2e-ui/crates/service/src/service.rs` (~projection catalog, surfaces, command walls) and `tests/e2e-ui/crates/runner/src/main.rs` (SQLite/Postgres × API/outbox/consumer wiring). +Motivating pain (now resolved): e2e-ui once had a single `service.rs` holding the projection catalog, surfaces and command walls, and a runner that hand-wired SQLite/Postgres × API/outbox/consumer. Today the composition root is `tests/e2e-ui/crates/service/src/application.rs` (surfaces, module inventory), infrastructure is `host.rs`, each bounded context is a module under `modules/` (listed by `modules/compose.rs`), and `crates/runner/src/main.rs` is a short entrypoint. --- @@ -147,7 +147,7 @@ Outbox dispatcher and eventual consumer are **role-selected**, not copy-pasted p | HTTP command routes | Optional / ingress only (e.g. Zitadel) | | OIDC / identity | API-facing processes | -Primary write path for apps remains GraphQL commands. HTTP command routes stay off unless a process calls `with_http_command_routes`. +Primary write path for apps remains GraphQL commands. HTTP command routes stay off: a process exposes one command with `with_http_command(command, edge)` (the edge authenticates the request), or every command with `with_http_command_routes` behind a trusted proxy. `command_gateway_routes` keeps every command path on the service binding of a gateway. --- @@ -187,7 +187,7 @@ Rough size: **~100–150 lines of product wiring** for logical app + a tiny depl 3. **Runtime::{sqlite, postgres, in_memory}** — pair repo + locks + bus. 4. **ProcessRole** — Full / CommandWriter / EventualProjector / QueryApi spawn policy. 5. **Atomic mount checks** — fail closed if Atomic is mounted without write path. -6. **Collapse e2e-ui `service.rs` + `runner`** onto the new APIs (no dual/legacy surface). +6. **Collapse e2e-ui `service.rs` + `runner`** onto the new APIs (no dual/legacy surface). Done: see `application.rs`, `host.rs` and `modules/` in `tests/e2e-ui/crates/service/src/`. No second application-owned optimism map: projection mutation IR is the source of cache effects. diff --git a/docs/bounded-read-model-scans.md b/docs/bounded-read-model-scans.md new file mode 100644 index 000000000..123c52db3 --- /dev/null +++ b/docs/bounded-read-model-scans.md @@ -0,0 +1,33 @@ +# Bounded read-model scans + +`RelationalReadModelQueryStore::scan_read_model` reads normalized rows with +declared types and row versions. It does not load aggregates, authorize commands, +or expose arbitrary SQL. Unsupported adapters return an explicit error. + +```rust,ignore +use distributed::read_model::ReadModelScanRequest; +let request = ReadModelScanRequest::new::(scope, 100, cursor)?; +let page = store.scan_read_model(request).await?; +let rows = page.typed::()?; +let cursor = page.next; +``` + +The initial capability supports a single non-null text primary key, at most 16 +typed equality filters and 1–100 returned rows. Filters support text, nullable +NULL, booleans and signed/unsigned integers within the SQL signed range. Text +filters and cursor keys are bounded to 4096 bytes; NUL is rejected. Composite +keys, joins, includes, offsets, JSON/float predicates and operational tables are +not supported. Schemas and filter types are validated before storage access. + +The opaque cursor binds the exact schema and equality scope. Only page size may +change. In-memory, queued and SQLite/PostgreSQL repositories retain row versions +and use bytewise ascending key order. The SQL adapter materializes at most one +extra row to decide whether a next page exists; the in-memory adapter keeps at +most that many selected rows while scanning its test/development store. + +Pages are separate current reads, not a multi-page transaction. Updates between +pages are visible; new keys before an already-consumed cursor are not revisited. +Consumers must validate command fences against the owning aggregate and provide +event-driven reconciliation for late rows. In particular, an empty first scan +does not prove a concurrently created row will never need processing. This API +does not provide an authorization bypass or replace a public GraphQL read policy. diff --git a/docs/bus-contract.md b/docs/bus-contract.md new file mode 100644 index 000000000..d297c0b17 --- /dev/null +++ b/docs/bus-contract.md @@ -0,0 +1,48 @@ +# Bus contract + +What every `Bus + BusConsumer` promises, and where a transport differs. The +promises are tested by one suite, `tests/common/src/transport/bus.rs`, which +the in-memory, SQLite, Postgres, NATS, Kafka and RabbitMQ buses all run. + +## What every bus does + +| Promise | Meaning | +| --- | --- | +| **At least once** | A message is delivered until a handler finishes it. A handler may see the same message more than once, so handlers must be idempotent. | +| **Commands are point-to-point** | `send` + `listen`: within one consumer group, one consumer handles each command. | +| **Events fan out** | `publish` + `subscribe`: every consumer group gets every event published after the group first subscribed. A group keeps its position between runs. | +| **The message arrives unchanged** | Name, kind, id, payload, content type and user metadata are what was sent. | +| **Retryable failures are redelivered** | The message is handed back and delivered again after a backoff that grows with each delivery (`RunOptions::with_backoff`, `with_max_attempts`). | +| **Permanent failures are dead-lettered** | The runner stores `{message, reason, consumer, attempts}` as a `distributed.dead_letter` event on the same bus, then acknowledges the delivery. Later messages are not held up. | +| **A consumer runs until shutdown** | A quiet transport does not end a run. `Shutdown::trigger` ends it with `Ok(())` after the delivery in hand is settled. `RunOptions::until_idle()` is the drain for tests. | + +Retry, the attempt limit, dead-lettering and shutdown are done by the runner +above the transport, which is why they are the same everywhere. A transport +only receives, acknowledges, and hands a delivery back with a delay. + +## Where transports differ + +These are not covered by the suite. Do not rely on them across transports. + +| Behaviour | In-memory | SQLite / Postgres | NATS | Kafka | RabbitMQ | +| --- | --- | --- | --- | --- | --- | +| Event order across names | per name only | publish order | publish order | per topic (one topic per name) | per group queue | +| A redelivered message blocks later ones | yes | yes (log); no (queue) | no | yes | no | +| Backoff delay honoured | no, redelivered at once | yes | yes | yes, by holding the consumer | yes, by holding the consumer | +| Delivery count seen by `max_attempts` | not counted | exact (queue); not counted (log) | exact | counted per consumer process | 1 or 2 only | +| Two consumers of one group, events | may both handle an event | may both handle an event | compete | compete | compete | +| Publishing the same id twice | stored once | stored once | stored once within the dedup window | stored twice | stored twice | +| Ordered-delivery evidence for projections | yes | yes | yes | no | no | +| Events published before a group first subscribes | delivered | delivered | delivered | delivered | dropped | + +An application that needs `created` before `shipped` for the same aggregate +must not depend on the bus for it on Kafka or the in-memory bus today. The +projection engine orders by its own cursor where the transport gives +ordered-delivery evidence. + +## Adding a transport + +Implement `BusHarness` in the transport's test target and call +`bus_conformance_tests!(TheHarness);`. `start` sets up an isolated namespace +and returns `None` when the service is not configured; `bus(group)` returns a +connected bus for that consumer group. diff --git a/docs/compact-projection-contracts.md b/docs/compact-projection-contracts.md new file mode 100644 index 000000000..820d8c66f --- /dev/null +++ b/docs/compact-projection-contracts.md @@ -0,0 +1,44 @@ +# Shared projection material in application manifests + +Several exact event selectors can apply the same mutation. This is common when +retained state events and current events update the same read model. The +`projection!` authoring form already accepts multiple events per mutation; +application manifests now share identical operation lists and selector body +schemas when that reduces their encoded size. No authoring change is required. + +The modeled projection's `program` value uses the explicit +`shared_projection_program_v1` encoding when smaller than the expanded form. +Its `program` retains all original fields and every exact arm, replacing only +`operations` with `operations_ref` and selector `body_schema` with +`body_schema_ref`. These zero-based references address the wrapper's canonical +`operation_sets` and `body_schemas` tables. Operations are interned by their +complete canonical JSON, including ordering, IDs, expressions and effects; +schemas are interned by exact string equality. No historical selector is +removed, merged, treated as current, or exempted from replay validation. + +The runtime projection IR, program and binding IDs, server execution and client +projection-program exports are unchanged. The application Surface's artifact +fingerprints change deterministically when shared storage is used. Rebuild the +service and generated clients together. Existing expanded manifests remain accepted +and retain their existing encoding and fingerprints when decoded and re-encoded. + +Tools reading the opaque modeled `program` JSON can use +`distributed::application::expand_projection_program_contract(&value)` to read +either representation. Expansion returns exactly the original program JSON. +Unsupported encodings, invalid references, inline/reference ambiguity, duplicate +or unused table entries, and noncanonical table order fail validation. + +The complete encoded application manifest is bounded at 16 MiB, matching CLI +manifest ingress. This aggregate budget accommodates complete current and +retained-selector catalogs composed from many independently bounded contracts. +Older framework readers capped at 4 MiB reject larger artifacts; rebuild tooling +and applications together. Existing bytes, fingerprints and encoding versions +are unchanged for manifests that already fit. + +Each opaque +modeled value remains bounded at 1 MiB; an expanded program also must fit the +existing 1 MiB budget. The decoder checks repeated byte costs before copying +shared values and validates programs individually, without retaining an expanded +copy of the whole application. Collection, string and depth limits remain +unchanged. Sharing is storage normalization, not a replacement for +retained-history replay. diff --git a/docs/consumer-delivery-lanes.md b/docs/consumer-delivery-lanes.md new file mode 100644 index 000000000..94878d7e6 --- /dev/null +++ b/docs/consumer-delivery-lanes.md @@ -0,0 +1,99 @@ +# Consumer delivery lanes and retry backoff + +One durable consumer (`listen`/`subscribe` group) delivers messages in broker +order and, by default, runs every registered route for a message before it +receives the next one. That is the simplest ordering contract, but it couples +latency across unrelated work: a process-manager policy that only turns a fact +into the next idempotent command waits behind every projection and slow +external effect registered for earlier messages. It also lets one message +that keeps failing monopolize the consumer. + +## Retry backoff for retryable failures + +A retryable failure NAKs the delivery so the broker redelivers it later. On +NATS JetStream the NAK carries a delay derived from the delivery count: +`base * 2^(delivered - 1)`, capped (defaults 50 ms and 5 s; +`NatsBus::with_nack_backoff` / `NatsJetStreamSource::with_nack_backoff`). +The first retry is still prompt. A message that fails every time stops +being redelivered ahead of newer messages in a hot loop. Retries remain +unlimited and the message is still retained; only the redelivery time moves. +Setting the base to zero restores an immediate NAK. + +This is not a substitute for classifying failures correctly. A command +rejection that is durably recorded under a deterministic command identity +replays the same rejection on every retry. The handler must return a +permanent error, which the configured failure policy (dead-letter by default) +settles and records in transport metrics. Transient infrastructure failures +stay retryable. + +## Lanes + +A router may partition its routes into named **lanes**. `Service::lane(name, +routes)` registers a route bundle in a lane. Plain `Service::routes` uses the +default lane. Lanes are opt-in. A service that registers no named lane runs +exactly as before. + +When a router has more than one lane and the source settles each delivery +independently (`MessageSource::settles_independently`, true for NATS +JetStream), the runner: + +1. receives messages in broker order and hands each one to every lane that + has a route for it; +2. runs each lane's messages strictly in receive order, one at a time, with + the lane's routes in registration order. This is the same order a + single-lane consumer gives those routes; +3. runs different lanes concurrently, so a slow route in one lane cannot delay + another lane; +4. settles a delivery only after every lane that received it has finished it. + Any retryable lane failure NAKs the delivery, and redelivery runs all of its + lanes again. A permanent failure applies the failure policy once; +5. bounds the number of received but unsettled deliveries + (`RunOptions::with_lane_window`, default 16). When the window is full the + runner stops receiving until a delivery settles; +6. stops a lane at its first stop-class failure (`FailurePolicy::Stop` or a + retain-and-stop error such as `ApplicationReloading`). That delivery is + settled as in sequential mode. Later deliveries queued for the halted lane + are NAKed, not skipped. Other in-flight deliveries finish and settle, then + the run returns the error. + +The default lane keeps its existing behavior, including route-order +dependencies between its routes within one delivery. + +Sources whose acknowledgement is positional (Kafka offset commits) or +lease-based (SQL table rows) report `settles_independently() == false`. For +them the runner keeps the sequential loop and dispatches every lane's routes +in order for each message. Lanes then change nothing about delivery. + +### What a lane must satisfy + +Put a route bundle in its own lane only when **no route in another lane +depends on its effects within the same delivery, and it depends on none of +theirs**. Typical examples are process-manager policies that read only the +delivered fact and send idempotent commands. A route that reads a projection +written by an earlier route for the same message must stay in that route's +lane. + +Lanes also reorder effects **across deliveries**: one lane may finish later +messages while another lane is still working on earlier ones. A route whose +correctness (or whose downstream readers' correctness) needs another lane's +effects from an *earlier* message — for example, a process policy that +completes a workflow the UI then reads through a projection maintained in +another lane — must share that lane, or its readers must tolerate the +projection arriving later. Forge hit this: provisioning completed before the +read-access projection existed, producing transient 404s, until the +derivation moved into the process lane. + +Lanes do not weaken existing guarantees: + +- **Ordering:** each lane observes deliveries in broker order. A redelivery + (after NAK or ack-wait expiry) can arrive after later messages. That is + already true for a single-lane consumer. +- **At-least-once:** a delivery is acknowledged only after all of its lanes + succeeded. A crash or failure before that redelivers it to every lane, so + every route must stay idempotent, as today. +- **Failure policy and DLQ:** unchanged, applied once per delivery after all + lanes finish. +- **Ack deadline:** a delivery waiting in a busy lane still counts against the + broker's ack wait. Keep the window small enough that a lane's backlog clears + well within it. An expired delivery is redelivered, which is safe under the + idempotency requirement. diff --git a/docs/coordination-primitives.md b/docs/coordination-primitives.md new file mode 100644 index 000000000..0c36d68ae --- /dev/null +++ b/docs/coordination-primitives.md @@ -0,0 +1,349 @@ +# Coordination primitives: sagas, durable timers and fenced leases + +A cell has one atomic boundary. Work that spans cells, or must happen later, +or must be owned by exactly one process at a time needs explicit +coordination. Three primitives cover the common shapes: a zone transfer, an +encounter settlement with a deadline, a boss controller that must never run +twice. + +| Need | Primitive | Module | +|------|-----------|--------| +| Change state in two cells with rollback | Saga / process manager | `distributed::saga` | +| Run something at a time in the future, across restarts | `OutboxMessage::deliver_at` | `distributed::outbox` | +| A cell schedules its own future or recurring work | Re-armable cell alarm | `distributed::cell_host` | +| One owner per key, with stale writers rejected | Lease with fencing token | `distributed::lease` | +| Deterministic time in tests | `Clock`, `ManualClock` | `distributed::clock` | + +All three are dependency-free in core. The SQL lease stores follow the +existing `sqlite` / `postgres` features. No new cargo feature was added and +default features are unchanged. + +## Durable timers: `deliver_at` + +```rust +let timer = OutboxMessage::create_to(id, "settle-encounter", "encounters", payload)? + .deliver_after(now, Duration::from_secs(10)); +repo.outbox(timer).commit(&mut encounter).await?; +``` + +A scheduled outbox row is committed with the change that arms it, so it is +exactly as durable as that change. Every claim path skips it until it is due: + +- the in-memory store (`OutboxMessage::is_claimable_at`); +- the SQLite and Postgres claim queries, which already filtered on the + `next_available_at` column. That column now stores `deliver_at` and falls + back to `created_at`, so **no schema change was needed** and existing rows + (and `None`) stay immediately deliverable; +- explicit-id claims (`ClaimOutboxMessages::for_ids`), so the after-commit + immediate publisher cannot bypass the schedule. + +The drain worker (`OutboxDrainRunner`) picks a due row up on its next poll, +so a timer fires within one poll interval of its deadline. `release` (a +retry) sets availability to now plus the retry backoff (250 ms doubling to +one minute), so a timer that failed to publish is retried soon, without a +tight loop while the broker is down. `OutboxMessage.deliver_at` is +`#[serde(default)]`. + +## Schedules: an aggregate schedules its own work + +`deliver_at` leaves the aggregate and needs a consumer to send a command +back. When an aggregate must act on itself later (a matchmaking tick, an +invite expiry, a daily reset, a lease expiry), a causal command handler +**schedules** it with its events (`distributed::schedule`): + +```rust +// on the route: what the command needs from its host +routes.typed_command(start).requires(Capability::Scheduling).requires(Capability::Clock) + +// in the handler +let now = ctx.now()?; // the host clock +ctx.schedule(Schedule::after("tick", Duration::from_secs(5), "pool.tick", &TickInput { pool })?)?; +ctx.cancel_schedule("invite-expiry")?; + +// in the schedule's own handler: re-schedule from the fired due time (no drift) +let due = ctx.scheduled_due().expect("fired by a schedule") + period; +ctx.schedule(Schedule::at("tick", due, "pool.tick", &input)?)?; +``` + +- Schedule rows are part of `CommitBatch` (`batch.schedules`) and commit in + the **same transaction** as the command's events, ledger receipt and + outbox rows, on every backend: a cell's own `cell_alarms` table (migration + 11), the in-memory repository's per-stream table, SQL's + `aggregate_schedules` (migration 12, keyed by the owning stream). A failed + command schedules nothing. The batch must commit exactly one aggregate, + which owns the schedule. `Schedule::after` resolves against the backend's + clock at commit (cell clock, injected `Clock`, database clock). +- One row per (owner, name). Scheduling a name again replaces it and bumps + its `generation`; `cancel_schedule` disarms it. +- When due, the host dispatches the command **into the owner** through its + command ledger, with a command id derived from `(name, generation)` and + the trusted session from `microsvc::schedule::schedule_session` (role + `schedule`, plus claims only the host sets). Guard schedule-only commands + with `microsvc::schedule::schedule_guard` + so callers cannot invoke them. A crash after the handler committed but + before the schedule settled replays the receipt; the handler never runs + twice for one arm. +- Rejections disarm the schedule (reported as `failed`). Retryable failures + back off from 1 s, doubling, up to 5 min (`retried`). At most 32 schedules + fire per wake, 16 schedule writes per command and 1,024 armed schedules + per aggregate. + +**Capabilities.** Backends declare what they provide (`Capabilities`): + +| Backend | Stores schedules | Dispatches them (`Scheduling`) | Clock (`Clock`) | +|---|---|---|---| +| Aggregate cell (celld; reference host) | `cell_alarms` | yes: the Durable Object alarm; `fire_due_schedules` on the reference host | DO clock / store clock | +| In-memory repository | per-stream table | with a schedule worker attached (`ScheduleWorker::attach`) | injected `Clock` (`with_clock`) | +| SQL (Postgres, SQLite) | `aggregate_schedules` | with a schedule worker attached (`ScheduleWorker::attach`) | database clock | + +A route declares what it needs with `.requires(..)`; registering it on a +backend without it panics with the missing capabilities while the service is +built, never at the first commit. `ctx.now()` answers only on routes that +declared `Clock` (the dispatcher stamps the host clock into the session and +removes any caller value); `ctx.schedule` refuses unless the route declared +`Scheduling`. + +**Shared stores: the schedule worker** (`distributed::microsvc::schedule`, +any Tokio runtime feature). SQL and in-memory repositories store schedules +for every aggregate in one table, so a worker process fires them: + +```rust +let (repo, schedules) = ScheduleWorker::attach( + PostgresRepository::connect_and_migrate(url).await?, + ScheduleWorkerConfig::default(), +); // repo now declares Scheduling +let service = Arc::new(build_service(repo.clone())); +let worker = schedules.spawn(service); // worker.stop().await on shutdown +``` + +- Each pass claims up to 32 due, unclaimed rows in one statement + (`UPDATE … WHERE … IN (SELECT … FOR UPDATE SKIP LOCKED) RETURNING`; + SQLite serializes writers instead), marking them `claimed_until_ms` + (default 30 s ahead). Concurrent workers in several processes get + disjoint rows. +- Each claimed arm is dispatched through the `Service` with + `schedule_session` and a command id derived from the owning stream, the + name and the generation (one ledger serves every aggregate here, so the + owner is part of the id). A worker that crashes after the command + committed leaves the claim to lapse; the next worker re-dispatches the + same id and the ledger replays it, so the arm fires once. +- Settlement touches only the generation that fired, like on celld. +- The scheduled command finds its aggregate through its input; the handler + that called `ctx.schedule` supplies that input. + +**Latency.** On celld the Durable Object alarm wakes the cell at the due +time (a few milliseconds late) without any extra process. The schedule +worker fires a due row within one poll interval (`poll_interval`, default +250 ms) plus the dispatch, and only while a worker runs; in the test suite +with a 20 ms poll the observed delay past due was about 20–45 ms on SQLite. +Lower the interval for tighter timing at the cost of one claim query per +interval per worker. + +**celld.** A Durable Object has one alarm. The outbox watchdog +(`CelldOutbox`) and due schedules share it: every `setAlarm` targets the +earliest of the next schedule and the next drain, so a watchdog rearm never +postpones a schedule and a far schedule never postpones a drain. The +Worker's `alarm()` handler calls `AggregateCell::alarm(&env)`, which fires +due schedules, then drains the outbox and re-plans the wake. Commands that +schedule move the wake earlier right after they commit. + +**Reference host.** The in-process host (unit tests; durable cells run on +celld) has no timer. Give the store a `ManualClock` +(`CellStreamStore::with_clock`), advance it and call +`AggregateCell::fire_due_schedules()`: the same ledger and settlement path +runs deterministically. + +## Leases with fencing tokens + +```rust +let lease = leases.acquire("boss:hydra", "zone-7", Duration::from_secs(15)).await?; +// every 5s +let lease = leases.renew(&lease, Duration::from_secs(15)).await?; // Err(Lost) => stop acting +// in the protected aggregate (same cell, same transaction as the write): +self.fence.admit("boss:hydra", cmd.fencing_token)?; // Err(StaleFence) => reject +``` + +- `acquire` gives a free, expired or released key to the caller with a token + strictly greater than any earlier token for that key. Re-acquiring a live + lease you already hold returns it unchanged (an idempotent retry). A key + held by someone else returns `LeaseError::Held`. +- `renew` extends a live lease and keeps its token. `release` ends it early. + The row is **kept**, with `expires_at = 0`, so the counter never resets. +- `Fence` is a serializable high-water mark to embed in the protected state. + It admits tokens greater than or equal to the newest one seen. This is the + authoritative check. `LeaseStore::check_fence` is only a point-in-time + advisory check. + +Backends: `InMemoryLeaseStore` (use a `ManualClock` in tests), +`SqliteLeaseStore` and `PostgresLeaseStore`. Every SQL operation is one +atomic conditional statement evaluated against the **database clock**. The +`coordination_leases` table comes from repository migration +`0010_coordination_leases` (inventory version 10), or from +`SqlxLeaseStore::migrate` for standalone pools. + +This is a sibling of `distributed::lock`, not an extension of it. The lock +module is `QueuedRepository`'s internal mutual-exclusion optimization. Its +`Lock` trait has no holder identity, renewal or token, and it deletes +`aggregate_locks` rows on release, which would reset a token. + +## Sagas + +A saga is an event-sourced aggregate, `Saga`, with one +stream per instance. The definition is pure. It lists the steps, says which +command performs each step and which command undoes it, and folds reply +payloads into the saga data. The framework owns the state machine. + +```text +start ─► dispatch(step 0) ─► reply ok ─► dispatch(step 1) ─► reply ok ─► Completed + │ │ + │ reply failed │ timeout (outcome unknown) + ▼ ▼ + compensate applied steps compensate applied steps + step 1 + in reverse ─► Compensated in reverse ─► Compensated + (or Stuck after MAX_COMPENSATION_ATTEMPTS) +``` + +Each transition returns outbox messages that are committed **with** the +saga's events: the participant command, plus a `saga-timeout` timer to the +saga's own `REPLY_TO` queue, scheduled with `deliver_at = now + step.timeout`. +A crash between deciding and sending is impossible. A timer for a step that +already finished arrives later and is `Ignored`. + +A participant is a typed command of a `Service`, delivered by the bus. It +declares the transport role (`.roles([TRANSPORT_ROLE])`); a typed command +that does not is refused when a bus delivers it. The handler builds the +reply from its session and stages it in the same commit as its state change: + +```rust +let reply = SagaReply::from_session(ctx.session()).map_err(rejected)?; +// ... load the aggregate, apply or refuse the step ... +let reply = reply.succeeded(output).map_err(rejected)?; +ctx.outbox(reply).commit(aggregate)?.succeeded(payload) +``` + +(`rejected` maps a `SagaError` to `HandlerError::Rejected`; +`tests/services/saga_transfer/mod.rs` is the complete participant.) + +`from_session` reads the saga headers, which arrive as session claims, and +the saga command id, which the transport puts in `TRANSPORT_MESSAGE_ID_CLAIM`. +A step the participant refuses is still a committed command: stage +`reply.failed(reason)` and return `Ok`. Returning `Err` records the rejection +in the ledger but stages no reply, so the saga would wait for its timeout. + +Inbound replies and timers become `SagaMessage::from_outbox` / `from_bus` and +go to `SagaRunner::handle`. Inside a `microsvc` handler you can also call +`Saga::handle` and commit with `ctx.repo().outbox(..)`. + +Guarantees and obligations: + +- **Idempotent.** The saga records every message id that changed its state, + so a redelivery is `Duplicate`. Late replies and superseded timers are + `Ignored`. Concurrent handlers are fenced by the saga stream's optimistic + version, and `SagaRunner` reloads and retries on `ConcurrentWrite`. +- **Deterministic ids.** Command ids are `type:saga:step:phase:attempt` and a + reply id is `:reply`. +- **Redelivery is deduplicated by the command ledger** for a typed + participant. The ledger command id is derived from the service name, the + command name and the saga command id, so the same saga command delivered + again replays the stored receipt: the handler does not run, no state + changes and no second reply is staged. The first reply cannot be missing, + because it was committed in the transaction that wrote the receipt. This + covers one command id only. A retry of a compensation is a new attempt + with a new command id, and the handler runs again. +- **A participant that is not a typed command of a `Service`** (it consumes + the outbox row or bus message itself and builds the reply with + `SagaReply::from_outbox` / `from_bus`) gets none of that. It must dedupe on + the saga command id itself (an inbox receipt or aggregate state) and must + not emit a second reply on redelivery. +- **A timeout means the outcome is unknown,** so the timed-out step is + compensated as well. Compensations must be idempotent and must tolerate + arriving *before* their action. The participant records a tombstone for + the saga id and rejects a late action. This is the participant's own + state on every path: the ledger knows command ids, not which transfer was + cancelled. +- **`on_step_succeeded` is replayed,** so keep it deterministic. + +### Fan-out steps + +A step can send commands to N cells chosen at run time, for example one +ticket reservation per party when a match starts. `action` returns +`SagaAction::FanOut(commands)` instead of a single command +(`SagaCommand` converts with `.into()`); `compensation` and +`on_step_succeeded` receive the member index (`0` for single steps). + +```rust +fn action(step: &str, saga_id: &str, d: &MatchStart) -> Result { + match step { + "reserve" => Ok(SagaAction::fan_out( + d.parties.iter().map(|p| SagaCommand::json(format!("party:{p}"), "ticket.reserve", &saga_id)) + .collect::, _>>()?, + )), + _ => Ok(SagaCommand::json("match", "match.confirm", &saga_id)?.into()), + } +} +fn compensation(step: &str, member: usize, saga_id: &str, d: &MatchStart) + -> Result, SagaError> { + match step { + "reserve" => { + SagaCommand::json(format!("party:{}", d.parties[member]), "ticket.release", &saga_id).map(Some) + } + _ => Ok(None), + } +} +``` + +- 1 to `MAX_SAGA_FAN_OUT` (64) members; an empty or larger fan-out is a + `Definition` error. Membership must be a deterministic function of the data. +- Every member gets its own command and timeout timer, both carrying + `saga-member` metadata. Command ids are + `type:saga:step:phase:attempt:member`, so retries dedupe per member. +- The step **succeeds** when every member replies `succeeded`. It + **settles** only after every member has replied or timed out, so the saga + knows which members applied. On any rejection or timeout the step fails and + only the members that applied, or timed out (outcome unknown), are + compensated, one at a time, highest index first. Members that rejected are + not compensated. +- A reply arriving after its member timed out is `Ignored`; the timeout + already settled that member and it will be compensated. +- Events: `saga.member_succeeded`, `saga.member_failed`, + `saga.fan_out_settled`. Replaying the stream reproduces the per-member + state (`Saga::fan_out`, `Saga::applied_members`). + +The tests are in `src/saga/fan_out_tests.rs` (N = 1..16, partial failure, +per-member timeouts and late replies, per-member compensation retries, +bounds, and replay from a repository). + +### Worked example + +`tests/services/saga_transfer/mod.rs` moves value between wallets in two separate +cells. The `debit` step goes to the source cell (compensated by `refund`) and +the `credit` step goes to the target cell (compensated by `reverse_credit`). +A test network delivers outbox rows whose `deliver_at` is due on a +`ManualClock`, so timeouts fire without sleeping. The scenarios are: + +- the happy path, including an idempotent restart and ignored leftover timers; +- target rejection, where the debit is refunded; +- source rejection, where nothing needs compensating; +- target timeout, where both steps are compensated and the late credit is + neutralized; +- the compensation arriving before the late action, where the tombstone + rejects the credit; +- compensation timeouts that are retried and then marked `Stuck`; +- duplicate command delivery and duplicate replies; +- saga state and its timer surviving a restart on a SQLite file database. + +## Tests + +```sh +cargo test --features sqlite,postgres --test services --test repositories -- saga_transfer:: coordination_lease:: scheduled_outbox:: +cargo test --features sqlite --lib -- outbox lease clock +cargo test --features cloudflare-workers --lib cell_host +(cd tests/celld/alarm-worker && worker-build --release) && node tests/celld/alarms.mjs +``` + +`tests/celld/alarms.mjs` owns its own `celld dev` process (no Docker; set +`CELLD_BIN` to choose the binary) and proves the alarm row commits atomically, +periodic re-arm at the alarm cadence, that the watchdog and domain alarms do +not starve each other, and exactly-once firing across a celld restart. + +The Postgres cases skip when `DATABASE_URL` is unset (see `compose.yaml`). diff --git a/docs/external-facts.md b/docs/external-facts.md new file mode 100644 index 000000000..e3cdef685 --- /dev/null +++ b/docs/external-facts.md @@ -0,0 +1,78 @@ +# Authenticated external facts + +`DomainEventOccurrence::capture_external` represents an authenticated fact from +an external ledger, webhook or other durable source. It does not create an +aggregate, command receipt or business authorization. The adapter must verify +the source before calling the typed constructor. Deserializing an occurrence +alone does not authenticate its origin. + +The source identity consists of producer, stream, numeric position and member +key. Members of one external transaction share its position, with distinct keys. +The logical occurrence ID depends only on that identity. Changing its descriptor, +body, timestamp or metadata preserves the ID and must fail the existing durable +input fingerprint fence. Retries must reproduce the same canonical bytes. When +the source has no timestamp, an adapter may explicitly use the Unix epoch as an +unknown-time sentinel; it must not present adapter receipt time as source time. + +An `external_snapshot` projection applies full-row source snapshots. It orders +each external stream/member independently of actual broker delivery positions; +it does not invent an aggregate sequence. Existing aggregate projection and +command APIs retain their authority and fencing rules. Derived external facts +retain their source provenance, but are not accepted as direct source snapshots. + +NATS publishes external facts with a content-bound broker dedup key and a +separate reserved logical occurrence ID header. Thus identical retries within +the broker dedup window collapse, but altered bytes reach durable validation. +Different logical source facts with identical bodies never collapse. Retained +archive reads verify these headers and preserve external occurrences for replay. +Malformed or ambiguous identity headers fail permanently before dispatch and +remain unacknowledged. The supervisor sees the error; the adapter does not +silently terminate the message or advance progress past it. + +An identical logical input redelivered at a new broker cursor advances only the +delivery checkpoint within its execution generation. It does not repeat row +changes, observations or business effects. A new execution generation applies +its first delivery normally. Original and alias cursor bindings remain immutable, +and one canonical topology-wide message identity arbitrates concurrent partition +claims. Migration 0009 adds delivery aliases without deleting canonical identity +or failure records. SQL mutation continues to use the existing partition lock. + +Permanent input identities and their aliases must be retained for the replay +and source-conflict horizon. A bounded broker dedup window is not such a fence. +An ingress that acknowledges an external cursor must first establish its own +required durable qualification (for example, a history projection atomically +committed with the protocol fingerprint), and retain source replay until then. +Publishing is not approval, and waiting for all UI consumers is unnecessary. + +Offline snapshot rebuild preserves these same identities. It distinguishes +original aggregate positions, original external stream/position/member keys, +and derived occurrence IDs; unrelated external facts cannot collide at empty +aggregate fields. Duplicate logical IDs must retain identical canonical bytes. +Aggregate projections still require a complete original aggregate sequence +prefix. External positions may be sparse or shared by different members, so +the source adapter must certify the complete retained source range instead of +inventing a contiguous aggregate history. Rebuild still rejects omitted stored +source versions, changed content at one source position, a different source +claiming an existing row, and derived facts used as snapshot authority. It does +not run business handlers, republish events, or reset delivery cursors. + +Some original aggregate records are intentionally private and therefore absent +from the public archive. Public-archive-only rebuild remains fail-closed at such +a gap. An offline adapter can instead supply `AggregateRebuildCoverage`, built +from a complete original quiescent event-store stream, its independently read +head, an explicit authored private-contract inventory, and the retained public +occurrences. Missing or reordered records, unknown private contracts, missing +publications, changed public identities, and cross-stream substitution fail. +Every witnessed public occurrence must remain byte-identical in the rebuild +history. No private record is fabricated as a public event. +This constructor deliberately supports only authored single-publication streams +(one ordinal-zero occurrence per non-private record). The adapter must establish +that emitter contract; arbitrary one-to-many publication completeness cannot be +inferred from archive absence and is not covered by this API. + +This is an operator trust boundary, not cryptographic authentication of an +arbitrary export: retain the original source provenance and review the artifact +digest. The digest prevents substitution of the reviewed artifact. It does not +prove arbitrary private payloads reconstruct a public JSON state. Authored +event-to-public contract mappings and typed projection body validation remain +required; an absent broker message never makes a source record private. diff --git a/docs/gateway/application.md b/docs/gateway/application.md new file mode 100644 index 000000000..5ad454f1b --- /dev/null +++ b/docs/gateway/application.md @@ -0,0 +1,31 @@ +# Application composition + +Declare a gateway alongside the typed service application: + +```rust,ignore +let application = service.application("site", surface)?.with_gateway("public", &gateway)?; +let adapter = NativeGateway::new(gateway, options, bindings, auth)?; +``` + +The manifest records logical binding IDs and capabilities as a versioned +application extension. Physical origins, route paths, secrets and host placement +are excluded, so changing them never rewrites application identity. Declaring a +gateway constructs nothing: the host builds the adapter it serves, and a gateway +does not start domain workers, projectors, stores or an embedded GraphQL server. +Native and Wasm UI/auth-only consumers remain independent of GraphQL execution +and SQL dependencies. + +The e2e-ui sample explicitly combines its existing domain host with the public +native gateway. `/graphql` owns API failures; `/auth` and `/api/auth` reach +SvelteKit, `/` serves UI, and service health/lifecycle/Zitadel ingress paths keep +explicit owners. SvelteKit is an internal upstream with no reverse API proxy. +`PUBLIC_ORIGIN` defaults to `http://localhost:8791`, `UI_INTERNAL_ORIGIN` to +`http://localhost:5180`. Configure OIDC callbacks for the public origin. +`GATEWAY_DELIVERY=none` (default) creates no delivery coordinator; `all` selects +bounded cache/flight/live resources and transactional dependency version hooks. +The logical application still uses the existing command sealing and lifecycle +protocols, including `APPLICATION_RELOADING`. + +Rollback consists of reverting the sample gateway mount and public-origin +configuration together. Disabling delivery independently preserves command and +query correctness and leaves persisted domain data intact. diff --git a/docs/gateway/live-sharing.md b/docs/gateway/live-sharing.md new file mode 100644 index 000000000..5b96365ac --- /dev/null +++ b/docs/gateway/live-sharing.md @@ -0,0 +1,65 @@ +# Shared live GraphQL + +Enable `gateway-graphql-native`, select `live_sharing` on the +GraphQL declaration, and bind `NativeDelivery::live(LiveLimits::default())`. +Snapshot caching, concurrent queries and live sharing can be selected separately +with `NativeDeliveryOptions`. The origin needs the authenticated delivery control +path and version coverage described in [snapshot-cache.md](snapshot-cache.md). +Custom embedded executor routers conservatively keep independent subscriptions; +the canonical engine and eligible remote whole-operation executors support sharing. + +Every consumer is admitted by the origin, including credentials supplied through +GraphQL `connection_init`. The gateway passes these credentials to the backend's +existing validator; it does not derive a subject from cookies or unverified JWTs. +A remote client initially uses a temporary origin WebSocket for the real connection +acknowledgement. It owns no subscription and closes before operation coordination. +Thus 100 clients incur 100 admissions and handshake costs but can share one steady +upstream subscription and producer. HTTP control requests do not execute result SQL. + +Groups bind the exact document, variables, origin subject/cache scope, policy, +schema and protocol. Each consumer keeps its own transport ID, expiry, queue and +freshness requirements. Different resume cursors start independent replay. Handoff +requires the same operation plus an exact resumable, comparable cursor vector and +matching data; the consumer's replay frames remain queued before future shared +frames. Unknown cursors keep independent streams. Equal data alone never proves +cursor equality. Duplicate suppression hashes the whole data and protocol envelope, +so new confirmation evidence is delivered even when values are unchanged. + +Cursorless `live.mode = "snapshot"` responses cannot prove shared replay handoff; +they retain independent authorized subscriptions and reconnect with fresh queries. +See [live query delivery](../live-query-delivery.md) for the wire contract. + +Defaults bound a coordinator to 256 groups, 1,024 consumers per group, 16 pending +frames per consumer, 1 MiB per full frame, eight retained history frames and a +one-hour group lifetime. Native ingress bounds socket/request counts and wire +message sizes as well. Frames share immutable storage across consumer queues. +If a slow consumer cannot preserve all evidence within its queue, it receives +`LIVE_RESET_REQUIRED`; a blocked socket is closed so it must reconnect. No +latest-value replacement silently discards confirmation proof. Group deadline, +upstream loss and incomplete/invalid origin envelopes also require recovery. +An origin failure frame (an error-only live execution result) carries no evidence +and is not fanned out; the group's consumers receive `LIVE_RESET_REQUIRED`. + +Dropping a consumer releases only its lease. Last leave aborts the actual upstream +stream, socket and origin change-feed receiver, including a pending origin SQL +read. An expired credential cannot continue receiving shared frames or own other +consumers' upstream: the remaining valid consumer reconnects with its own origin +credential and the last proven resume cursor. Normal GraphQL completion drains +queued frames; unexpected transport loss requires reset. Reconnect authenticates +again. Shared outbound sockets do not hibernate for free. + +These rules live once, in the sans-IO `delivery::LiveCoordinator` (and +`FlightTable` for query coalescing). Native and Worker adapters supply only +channels, tasks, timers and locks; both speak GraphQL-WS through one codec, +`graphql::ws`. + +`NativeDelivery::live_counts()` reports active groups, consumers, cumulative source +attempts, resets, upstream frames, exact duplicate frames and safe handoffs. Source +attempts include credential reconnects; they are not a count of active producers. +`GraphqlEngine::live_subscriber_count()` reports live subscriptions reaching the +origin and `live_producer_count()` its producers +(one per distinct origin live read; see `docs/live-query-delivery.md`). No credentials or subject identifiers appear in these counters. + +Disable `live_sharing` and remove the live delivery resource to restore independent +subscriptions. Existing client resume/reset and response-sealing behavior remains +in force. No migration or new credential is required by live coordination itself. diff --git a/docs/gateway/load-report.json b/docs/gateway/load-report.json new file mode 100644 index 000000000..57c9c38c0 --- /dev/null +++ b/docs/gateway/load-report.json @@ -0,0 +1,839 @@ +{ + "version": 1, + "revision": "eaa2d5d2bc6b104b89d6ccee12fd4fca11791a3e", + "candidateChanges": false, + "node": "v24.20.0", + "platform": "darwin", + "participants": 100, + "repetitions": 1, + "payloadCharacters": 4096, + "measurement": "actual HTTP bodies and WebSocket application frames; excludes headers/TLS/framing", + "limits": { + "snapshotEntries": 128, + "snapshotBytes": 2097152, + "entryBytes": 262144, + "flightGroups": 8, + "consumers": 128, + "flightBytes": 262144, + "liveGroups": 4, + "liveFrameBytes": 65536 + }, + "rows": [ + { + "host": "native", + "mode": "none", + "query": { + "origin": { + "producers": 0, + "resultExecutions": 100, + "validations": 0 + }, + "wire": { + "httpRequestBytes": 74600, + "httpResponseBytes": 519200, + "wsRequestBytes": 0, + "wsResponseBytes": 0, + "wsConnections": 0 + }, + "clientResponseBytes": 519200, + "latencyMs": { + "min": 147.129375, + "p50": 198.30575000000002, + "p95": 250.39304199999998, + "max": 257.099875 + } + }, + "live": { + "logicalSubscriptions": 100, + "upstreamProducers": 100, + "origin": { + "producers": 100, + "resultExecutions": 200, + "validations": 0 + }, + "wire": { + "httpRequestBytes": 0, + "httpResponseBytes": 0, + "wsRequestBytes": 76290, + "wsResponseBytes": 1104080, + "wsConnections": 100 + }, + "clientFrameBytes": 1104080, + "initialLatencyMs": { + "min": 21.134625000000142, + "p50": 23.260374999999954, + "p95": 24.767499999999927, + "max": 26.905917000000045 + }, + "commitFanoutMs": 299.9157919999998 + }, + "decisions": [], + "subjectControls": "query and live scope differ; separate producer", + "invalidation": "new projection returned; old cache envelope rejected" + }, + { + "host": "native", + "mode": "flights", + "query": { + "origin": { + "producers": 0, + "resultExecutions": 1, + "validations": 101 + }, + "wire": { + "httpRequestBytes": 76194, + "httpResponseBytes": 90330, + "wsRequestBytes": 0, + "wsResponseBytes": 0, + "wsConnections": 0 + }, + "clientResponseBytes": 528800, + "latencyMs": { + "min": 339.3542910000001, + "p50": 340.51858300000004, + "p95": 342.00416700000005, + "max": 342.293416 + } + }, + "live": { + "logicalSubscriptions": 100, + "upstreamProducers": 100, + "origin": { + "producers": 100, + "resultExecutions": 200, + "validations": 0 + }, + "wire": { + "httpRequestBytes": 0, + "httpResponseBytes": 0, + "wsRequestBytes": 76290, + "wsResponseBytes": 1104080, + "wsConnections": 100 + }, + "clientFrameBytes": 1104080, + "initialLatencyMs": { + "min": 20.867291999999907, + "p50": 23.03570899999977, + "p95": 24.76141699999971, + "max": 26.264917000000423 + }, + "commitFanoutMs": 306.95758300000034 + }, + "decisions": [ + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + null, + 1 + ], + "query": [ + 0, + 0, + 0 + ] + } + ], + "subjectControls": "query and live scope differ; separate producer", + "invalidation": "new projection returned; old cache envelope rejected" + }, + { + "host": "native", + "mode": "snapshots", + "query": { + "origin": { + "producers": 0, + "resultExecutions": 0, + "validations": 100 + }, + "wire": { + "httpRequestBytes": 74700, + "httpResponseBytes": 84200, + "wsRequestBytes": 0, + "wsResponseBytes": 0, + "wsConnections": 0 + }, + "clientResponseBytes": 528800, + "latencyMs": { + "min": 116.18020800000068, + "p50": 200.55029100000047, + "p95": 250.50162499999988, + "max": 255.24691600000006 + }, + "warmup": { + "origin": { + "producers": 0, + "resultExecutions": 1, + "validations": 2 + }, + "wire": { + "httpRequestBytes": 2241, + "httpResponseBytes": 6972, + "wsRequestBytes": 0, + "wsResponseBytes": 0, + "wsConnections": 0 + }, + "clientBytes": 5288 + } + }, + "live": { + "logicalSubscriptions": 100, + "upstreamProducers": 100, + "origin": { + "producers": 100, + "resultExecutions": 200, + "validations": 0 + }, + "wire": { + "httpRequestBytes": 0, + "httpResponseBytes": 0, + "wsRequestBytes": 76290, + "wsResponseBytes": 1104780, + "wsConnections": 100 + }, + "clientFrameBytes": 1104780, + "initialLatencyMs": { + "min": 20.942458000000443, + "p50": 22.93787499999962, + "p95": 24.133708000000297, + "max": 25.488624999999956 + }, + "commitFanoutMs": 301.81533299999865 + }, + "decisions": [ + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + { + "fillBypasses": 0, + "hits": 100, + "invalidations": 1, + "misses": 3, + "staleRejections": 1 + }, + 1 + ], + "query": [ + 0, + 0, + 0 + ] + } + ], + "subjectControls": "query and live scope differ; separate producer", + "invalidation": "new projection returned; old cache envelope rejected" + }, + { + "host": "native", + "mode": "live", + "recovery": { + "origin": { + "producers": 0, + "resultExecutions": 1, + "validations": 1 + }, + "wire": { + "httpRequestBytes": 928, + "httpResponseBytes": 842, + "wsRequestBytes": 1610, + "wsResponseBytes": 5470, + "wsConnections": 2 + }, + "clientFrameBytes": 5440, + "cursorResets": 1, + "slowClientResets": 0 + }, + "query": { + "origin": { + "producers": 0, + "resultExecutions": 100, + "validations": 0 + }, + "wire": { + "httpRequestBytes": 74600, + "httpResponseBytes": 519600, + "wsRequestBytes": 0, + "wsResponseBytes": 0, + "wsConnections": 0 + }, + "clientResponseBytes": 519600, + "latencyMs": { + "min": 140.48958400000083, + "p50": 213.07474999999977, + "p95": 254.67654200000106, + "max": 262.21537499999977 + } + }, + "live": { + "logicalSubscriptions": 100, + "upstreamProducers": 1, + "origin": { + "producers": 1, + "resultExecutions": 2, + "validations": 100 + }, + "wire": { + "httpRequestBytes": 75800, + "httpResponseBytes": 84200, + "wsRequestBytes": 66385, + "wsResponseBytes": 13564, + "wsConnections": 101 + }, + "clientFrameBytes": 1105180, + "initialLatencyMs": { + "min": 20.779709000000366, + "p50": 22.705541999999696, + "p95": 24.23895900000025, + "max": 25.080291999998735 + }, + "commitFanoutMs": 170.7697500000013 + }, + "decisions": [ + { + "live": [ + 0, + 0, + 3, + 0, + 4, + 0, + 0 + ], + "metrics": [ + null, + 0 + ], + "query": [ + 0, + 0, + 0 + ] + } + ], + "subjectControls": "query and live scope differ; separate producer", + "invalidation": "new projection returned; old cache envelope rejected" + }, + { + "host": "workerd", + "mode": "none", + "query": { + "origin": { + "producers": 0, + "resultExecutions": 100, + "validations": 0 + }, + "wire": { + "httpRequestBytes": 74600, + "httpResponseBytes": 519600, + "wsRequestBytes": 0, + "wsResponseBytes": 0, + "wsConnections": 0 + }, + "clientResponseBytes": 519600, + "latencyMs": { + "min": 225.62924999999996, + "p50": 400.4289169999993, + "p95": 453.3817910000016, + "max": 461.52195799999936 + } + }, + "live": { + "logicalSubscriptions": 100, + "upstreamProducers": 100, + "origin": { + "producers": 100, + "resultExecutions": 200, + "validations": 0 + }, + "wire": { + "httpRequestBytes": 0, + "httpResponseBytes": 0, + "wsRequestBytes": 76290, + "wsResponseBytes": 1105180, + "wsConnections": 100 + }, + "clientFrameBytes": 1105180, + "initialLatencyMs": { + "min": 23.570792000000438, + "p50": 25.99616700000115, + "p95": 28.189124999997148, + "max": 29.651667000001908 + }, + "commitFanoutMs": 346.484375 + }, + "decisions": [], + "subjectControls": "query and live scope differ; separate producer", + "invalidation": "new projection returned; old cache envelope rejected" + }, + { + "host": "workerd", + "mode": "flights", + "query": { + "origin": { + "producers": 0, + "resultExecutions": 1, + "validations": 101 + }, + "wire": { + "httpRequestBytes": 76194, + "httpResponseBytes": 90334, + "wsRequestBytes": 0, + "wsResponseBytes": 0, + "wsConnections": 0 + }, + "clientResponseBytes": 529200, + "latencyMs": { + "min": 744.4551250000004, + "p50": 755.8567079999993, + "p95": 767.9520410000005, + "max": 769.9147080000002 + } + }, + "live": { + "logicalSubscriptions": 100, + "upstreamProducers": 100, + "origin": { + "producers": 100, + "resultExecutions": 200, + "validations": 0 + }, + "wire": { + "httpRequestBytes": 0, + "httpResponseBytes": 0, + "wsRequestBytes": 144100, + "wsResponseBytes": 1108900, + "wsConnections": 200 + }, + "clientFrameBytes": 1127360, + "initialLatencyMs": { + "min": 22.836959000000206, + "p50": 25.345250000002125, + "p95": 28.244916999999987, + "max": 38.16112500000236 + }, + "commitFanoutMs": 335.93595800000185 + }, + "decisions": [ + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + null, + 0 + ], + "query": [ + 0, + 0, + 0 + ] + }, + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + null, + 0 + ], + "query": [ + 0, + 0, + 0 + ] + }, + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + null, + 0 + ], + "query": [ + 0, + 0, + 0 + ] + }, + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + null, + 1 + ], + "query": [ + 0, + 0, + 0 + ] + } + ], + "subjectControls": "query and live scope differ; separate producer", + "invalidation": "new projection returned; old cache envelope rejected" + }, + { + "host": "workerd", + "mode": "snapshots", + "query": { + "origin": { + "producers": 0, + "resultExecutions": 0, + "validations": 100 + }, + "wire": { + "httpRequestBytes": 74700, + "httpResponseBytes": 84200, + "wsRequestBytes": 0, + "wsResponseBytes": 0, + "wsConnections": 0 + }, + "clientResponseBytes": 529200, + "latencyMs": { + "min": 40.5157500000023, + "p50": 526.3143750000017, + "p95": 632.445499999998, + "max": 632.5337080000027 + }, + "warmup": { + "origin": { + "producers": 0, + "resultExecutions": 1, + "validations": 2 + }, + "wire": { + "httpRequestBytes": 2241, + "httpResponseBytes": 6976, + "wsRequestBytes": 0, + "wsResponseBytes": 0, + "wsConnections": 0 + }, + "clientBytes": 5292 + } + }, + "live": { + "logicalSubscriptions": 100, + "upstreamProducers": 100, + "origin": { + "producers": 100, + "resultExecutions": 200, + "validations": 0 + }, + "wire": { + "httpRequestBytes": 0, + "httpResponseBytes": 0, + "wsRequestBytes": 144100, + "wsResponseBytes": 1108900, + "wsConnections": 200 + }, + "clientFrameBytes": 1127360, + "initialLatencyMs": { + "min": 22.649750000000495, + "p50": 25.527957999998762, + "p95": 28.2020420000008, + "max": 40.410916000000725 + }, + "commitFanoutMs": 369.64583400000265 + }, + "decisions": [ + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + { + "fillBypasses": 0, + "hits": 100, + "invalidations": 1, + "misses": 3, + "staleRejections": 1 + }, + 0 + ], + "query": [ + 0, + 0, + 0 + ] + }, + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + { + "fillBypasses": 0, + "hits": 0, + "invalidations": 1, + "misses": 0, + "staleRejections": 0 + }, + 0 + ], + "query": [ + 0, + 0, + 0 + ] + }, + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + { + "fillBypasses": 0, + "hits": 0, + "invalidations": 1, + "misses": 0, + "staleRejections": 0 + }, + 0 + ], + "query": [ + 0, + 0, + 0 + ] + }, + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + { + "fillBypasses": 0, + "hits": 0, + "invalidations": 1, + "misses": 0, + "staleRejections": 0 + }, + 1 + ], + "query": [ + 0, + 0, + 0 + ] + } + ], + "subjectControls": "query and live scope differ; separate producer", + "invalidation": "new projection returned; old cache envelope rejected" + }, + { + "host": "workerd", + "mode": "live", + "recovery": { + "origin": { + "producers": 0, + "resultExecutions": 22, + "validations": 3 + }, + "wire": { + "httpRequestBytes": 2444, + "httpResponseBytes": 2526, + "wsRequestBytes": 3707, + "wsResponseBytes": 123326, + "wsConnections": 5 + }, + "clientFrameBytes": 131320, + "cursorResets": 1, + "slowClientResets": 1 + }, + "query": { + "origin": { + "producers": 0, + "resultExecutions": 100, + "validations": 0 + }, + "wire": { + "httpRequestBytes": 74600, + "httpResponseBytes": 519600, + "wsRequestBytes": 0, + "wsResponseBytes": 0, + "wsConnections": 0 + }, + "clientResponseBytes": 519600, + "latencyMs": { + "min": 143.1261669999949, + "p50": 374.0097079999978, + "p95": 432.9804170000061, + "max": 435.25541599999997 + } + }, + "live": { + "logicalSubscriptions": 100, + "upstreamProducers": 1, + "origin": { + "producers": 1, + "resultExecutions": 2, + "validations": 100 + }, + "wire": { + "httpRequestBytes": 75800, + "httpResponseBytes": 84200, + "wsRequestBytes": 66385, + "wsResponseBytes": 13564, + "wsConnections": 101 + }, + "clientFrameBytes": 1120811, + "initialLatencyMs": { + "min": 22.425999999999476, + "p50": 34.62895800000115, + "p95": 37.213792000002286, + "max": 69.46099999999569 + }, + "commitFanoutMs": 241.35470899999927 + }, + "decisions": [ + { + "live": [ + 0, + 0, + 4, + 1, + 25, + 0, + 0 + ], + "metrics": [ + null, + 0 + ], + "query": [ + 0, + 0, + 0 + ] + }, + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + null, + 0 + ], + "query": [ + 0, + 0, + 0 + ] + }, + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + null, + 0 + ], + "query": [ + 0, + 0, + 0 + ] + }, + { + "live": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "metrics": [ + null, + 0 + ], + "query": [ + 0, + 0, + 0 + ] + } + ], + "subjectControls": "query and live scope differ; separate producer", + "invalidation": "new projection returned; old cache envelope rejected" + } + ] +} diff --git a/docs/gateway/metrics.md b/docs/gateway/metrics.md new file mode 100644 index 000000000..719e7b07a --- /dev/null +++ b/docs/gateway/metrics.md @@ -0,0 +1,48 @@ +# Delivery measurements + +`GatewayVersionStore::metrics()` counts actual compiled result SQL separately +from authenticated origin validation requests. `NativeDelivery::metrics()` and +`WorkerCoordinator::metrics()` expose optional `SnapshotMetrics` plus query +admission bypass counts. Cache decisions include hits, misses, resident stale +rejections, fill bypasses and explicit invalidations. These are cumulative, +identifier-free observations within a coordinator lifetime. Live counts expose +active groups/consumers, upstream source attempts, resets, received frames, +duplicates and handoffs; query counts expose active flights/consumers. Export +these through application-owned telemetry, with deployment/host/mode labels only. +No subject, token, document, variables or scope hashes are metric labels. + +Run the actual load fixture after installing `tests/gateway-worker` and +worker-build as described in [worker.md](worker.md): + +```sh +cargo test --no-default-features --features gateway-graphql-native,sqlite --test graphql graphql_query_protocol::load::separate_origin_and_client_savings -- --ignored --nocapture +``` + +`tests/gateway-worker/load-runtime.mjs` writes its report to +`tests/gateway-worker/artifacts/load-report.json` (uploaded by CI, not +checked in); [`load-report.json`](load-report.json) beside this page is a +recorded run. The report records the source revision and +whether it was dirty, runtime/platform, repetitions, payload size and resource +limits. Native and workerd each run disabled, coalescing-only, snapshot-only and +live-only modes. A barrier holds actual SQL until 100 coalesced consumers join. +Snapshots report warmup separately before 100 hits. Every mode holds 100 live +consumers during a real projection commit; result SQL, origin validation, steady +producers and all ongoing/temporary origin WebSocket connections are measured. +Different-subject controls prove private isolation. External writes, explicit +cache invalidation, cursor-gap resets and a slow Worker consumer expose recovery +costs. Native bounded-queue behavior is additionally covered by native live tests. + +The metering proxy counts actual HTTP request/response bodies and WebSocket +application frames, including origin authentication/validation control traffic. +Browser/client response bytes are counted independently. Header, TLS and frame +encoding overhead are explicitly excluded. No per-browser byte savings are +inferred from producer savings. Latency distributions and full fanout completion +are reported without universal thresholds. The deterministic correctness gates +are SQL/producer counts, causal data equality, isolation and teardown. + +With only live sharing selected, ordinary HTTP queries do not incur query +validation. The Worker modern WebSocket adapter may perform temporary origin +authentication handshakes even when query-only delivery is selected; those +connections and bytes are included, not hidden as steady-state producers. +Outgoing live sockets do not hibernate. Disable metric export independently of +resource bounds/correctness; coordinator restart starts a new counter series. diff --git a/docs/gateway/query-coalescing.md b/docs/gateway/query-coalescing.md new file mode 100644 index 000000000..a120f4299 --- /dev/null +++ b/docs/gateway/query-coalescing.md @@ -0,0 +1,42 @@ +# Shared concurrent queries + +Mount `NativeDelivery::coalescing(FlightLimits)` with the GraphQL binding's +`coalescing` capability. This creates no snapshot cache. To select both, use +`NativeDelivery::new(NativeDeliveryOptions { snapshots: Some(...), coalescing: +Some(...), ..Default::default() })`. All capabilities remain explicit and independently removable. +The origin uses the authenticated delivery control path and version store +described in [snapshot-cache.md](snapshot-cache.md). + +Every consumer authenticates and validates at the origin before joining. A group +key binds the exact origin subject/scope, operation/variables/extensions, current +dependency validator, and exact freshness requirements. Different or stronger +floors conservatively form different groups; no minimum is weakened to improve +sharing. Mutations, status operations and unknown origin eligibility never join. +The result retains its own complete data and protocol envelope. In-flight sharing +can serve an otherwise successful admitted query that lacks future cache eligibility; +any required minima must still be proven by that response. + +An operation owns one shared future. The registry retains a weak reference, and +each consumer holds a cancellation lease. Dropping one lease leaves the other +consumers' work running. Dropping the last lease immediately drops the upstream +future; no detached task remains as a hidden owner. Each response waits for its +consumer's own credential expiry deadline, and expiry is checked again before +delivery. The origin is also revalidated after result execution to detect a +changed scope/policy. A completed group is removed when its consumers finish; +with the cache disabled, a later nonoverlapping query executes normally. + +Default limits are 256 active groups, 1,024 consumers per group, a 30-second +operation deadline, and 1 MiB of complete response bytes per group. Native ingress +capacity also bounds all active requests. A full registry rejects additional +joins without evicting work needed by existing consumers. Expired generation +identities cannot release a newer same-key group. Oversized streams, errors, +cookie-setting and otherwise nonshareable responses go to one consumer; other +consumers execute normally with their own admission and freshness. They are never +stored as successful shared snapshots. + +`NativeDelivery::flight_counts()` exposes active groups/consumers without +identifiers. Origin metrics distinguish result SQL from per-consumer validation. +Portable `FlightKey`, `FlightLimits` and `FlightRegistry` provide the same bounded +identity, generation and refcount contracts for runtime adapters. They contain +no timers, network clients, SQL pools, or detached tasks. The Worker/DO adapter +owns its own runtime scheduling and cancellation. diff --git a/docs/gateway/snapshot-cache.md b/docs/gateway/snapshot-cache.md new file mode 100644 index 000000000..c98971557 --- /dev/null +++ b/docs/gateway/snapshot-cache.md @@ -0,0 +1,65 @@ +# Origin-validated query snapshots + +Enable `gateway-graphql-native` and the origin's SQL adapter. +The portable `gateway` feature alone has no SQL or native runtime. +Caching is opt-in: mount `NativeBinding::GraphqlWithDelivery` with an explicit +`NativeDelivery::snapshots(SnapshotLimits)` resource and declare `snapshots` +on that binding. An unselected capability allocates no cache. + +On the origin, after framework and application migrations, install +`GatewayVersionStore::install(&pool, application_namespace, physical_tables)` +and pass the resulting store to `GraphqlEngine::builder(...).gateway_versions(store)`. +The inventory must cover every table touched by an eligible compiled query, +including relationship targets and intermediate join tables. Installed projection +proof tables are included automatically because even a no-op projection can +change the response's evidence. This is conservative across projection partitions. + +Each consumer sends an authenticated validation request to the configured origin +using the existing GraphQL endpoint with the reserved `gatewayDelivery` extension. +Origin authentication, schema validation and the compiler's row/field authorization +run for every request. Validation executes a single dependency-vector SQL statement +inside a primary read snapshot; it executes no result SQL. The gateway accepts the +identity and opaque validator only from that origin response. Public request metadata +cannot grant cache scope. The existing executor still owns commands and command status. + +A miss executes the query with its data, causal metadata and validator in the same +SQL snapshot. The gateway revalidates after the fill and installs only if its own +validator is still current. Every hit revalidates on the primary, so delayed or lost +invalidation notifications cannot certify old private data. Authentication/primary +failure never falls back to cached private data. Missing dependency hooks make the +operation bypass reuse; unknown/custom resolver dependencies, commands/status, +errors, partial results, cookie-setting responses, `no-store`, and `Vary: *` also +bypass storage. Required client freshness minima must be covered by the stored proof. + +Defaults are 1,024 entries, 16 MiB total response bytes and 1 MiB per response. +Oversized/streaming responses continue to the consumer without truncation or storage. +Native response-header/read deadlines bound validation and capture. Entries use LRU +eviction; `invalidate_all()` also fences fills that began before the reset. +`GatewayVersionStore::metrics()` reports origin validations separately from actual +result SQL executions; these counters do not contain subjects or query text. + +For explicitly public content, `store.public_snapshot(exact_document, operation_name, +max_age_seconds)` permits 1–86,400 seconds of content age. This applies to all variable +values of that exact operation. It still requires fresh origin admission and preserves +subject isolation. Age starts at the original origin validation and is never extended +by copying an entry, a new admission, or another cache layer. The default policy always +requires the current version vector. + +## Activation and rollback + +Migration `0006_gateway_dependency_versions` is additive and registered in the normal +SQLite/PostgreSQL migration inventory. No application data is backfilled or rewritten. +Activation installs transactional write hooks and starts a new random epoch. Normal +SQL producers, Eventual projectors, Atomic projection commits, deletes, and PostgreSQL +TRUNCATE all update versions in their data transaction. A failed transaction rolls +versions back with the data. Privileged writers that disable/drop hooks are unsupported +until coverage is restored; validation detects missing/disabled hooks and bypasses reuse. +Applications must not manually replace framework hooks with different implementations. + +Install after application migrations, before enabling cache bindings. Rebuild or change +writer coverage in a controlled migration window, reinstall hooks/start a new epoch, +then invalidate gateway stores before reopening traffic. `rotate_epoch` is available +for an explicit rebuild boundary. Epochs are random identities, not inferred wall clocks +or PostgreSQL WAL positions. Disable the cache binding on rollback; leave additive +metadata in place until a separately planned cleanup. Never apply cleanup to a live DB +as part of a gateway cache rollback. diff --git a/docs/gateway/worker.md b/docs/gateway/worker.md new file mode 100644 index 000000000..767c34114 --- /dev/null +++ b/docs/gateway/worker.md @@ -0,0 +1,105 @@ +# Worker ingress and Durable Object delivery + +Enable `gateway-worker` to use `distributed::gateway::worker`. It compiles to +`wasm32-unknown-unknown` with workers-rs and the portable gateway/delivery +contracts. It links no Axum, Tokio runtime, SQLx, GraphQL server or domain bus. +workers-rs includes Tokio with no features for utility types. Commands +continue to execute at the configured backend; the Worker is ingress. + +An application constructs `WorkerGateway` with its portable `GatewayConfig`, +explicit `WorkerBinding` resources, `WorkerOptions` and `WorkerAuth`. Mount +`gateway.fetch(request, env)` from the Worker fetch entrypoint. Bind handlers, +an asset service, UI/auth reverse proxies, zone hosts, or a whole remote GraphQL +endpoint. `WorkerGateway` implements `GatewayAdapter`, so dispatch is the same +`Gateway::dispatch` the native adapter and custom adapters use. +Routes use the same exact/longest-segment ownership as native ingress. A selected +handler's error is terminal. The public origin is configured, never taken from +incoming forwarding headers. The adapter retains Origin and duplicate cookies, +rewrites private-origin redirects and rejects proxy loops. Fetch requires Host +to match the fetched URL; trusted public authority reaches delegated handlers +through configured origin and forwarded headers. + +`WorkerAuth::new` accepts an application-owned asynchronous session/provider +implementation returning the shared `RequestContext`. It must validate the +credential before constructing identity or a backend bearer credential. +`WorkerAuth::anonymous()` accepts opaque UI/auth cookies but rejects HTTP bearer +input. It does not turn a cookie or decoded JWT into identity. Auth.js remains +the session/callback/refresh/logout owner when delegated; no second identity +store is introduced. GraphQL connection_init credentials are forwarded to and +validated by the backend. WebSocket commands/status stay on that backend socket +identity path. HTTP query reuse for a WebSocket operation requires explicit +origin control-protocol recognition; older/custom origins remain independent. + +## Optional coordination + +A `WorkerDeliveryBinding` declares namespace, epoch, shard count and independent +snapshot/coalescing/live resources. With `delivery: None`, forwarding creates no +coordinator. It also works with a backend that has no delivery control protocol. +Declare a workers-rs Durable Object in application code and construct one +`Rc` in its `new`. Route its fetch method through +`gateway.fetch_coordinated(request, env, coordinator)`. This is an in-process +mount; public headers cannot assert that admission already happened. + +All ingress instances must use the same namespace, binding name, epoch and shard +count. Operation documents, selected operation and canonical variables select a +shard. This routing hash conveys no authorization. The DO repeats provider +admission and obtains a fresh origin validation for **every** consumer before +reuse. The actual cache/flight/live keys retain origin-resolved application, +endpoint, subject scope, schema/policy versions and freshness floors. Private +hits still cost origin validation; 100 eligible query consumers can share one +result SQL execution. WebSocket queries require a control capability check +before the HTTP reuse path and therefore have additional validation overhead. + +Use Worker-sized limits, for example the explicit limits in +[`tests/gateway-worker/src/lib.rs`](../../tests/gateway-worker/src/lib.rs). +Native defaults intentionally do not fit the Worker retained-payload budget. +The adapter rejects selected configurations exceeding 16 MiB of reserved cache, +flight and live payload. Live-frame charges follow actual shared ownership, +including consumer queues retained across handoff, and force explicit reset if +the budget is exhausted. This bounds wire payload, not the entire runtime heap: +parsed JSON, credentials, active requests, sockets and the application's own +allocations need additional memory headroom. Groups, consumers, frame sizes, +queue length, response sizes and operation lifetimes have independent limits. + +Modern GraphQL subscriptions use standard ping/pong payload echo as delivery +credits: the supplied JS transport echoes the payload. Full data and confirmation +proof stay unchanged. A client that does not acknowledge is reset instead of +silently accumulating data. Raw UI and legacy GraphQL sockets cannot assume that +protocol; they have bounded callback queues and cumulative delivery limits, +after which reconnect is required. `websocket_buffer_bytes` bounds a complete +frame and aggregate queued wire bytes per socket; arbitrary UI delivery is +limited to eight times this value per connection. Customize limits for the UI's +protocol. Outgoing origin sockets remain active and do not hibernate. One shared +steady-state producer does not mean one lifetime handshake: every consumer is +independently authenticated at the origin before grouping. + +## Recovery and cancellation + +Coordinator state is volatile. Restart starts empty and requires fresh origin +validation/replay. No invalidation feed is needed for correctness: validators +cover committed projection data and proof state, including external SQL writes. +An epoch or shard change abandons old cache/work; clients reconnect and present +origin-verifiable cursors. Cursor gaps, incompatible freshness and queue overflow +cause origin recovery or explicit reset. Last-leave drops the actual upstream +socket; one expired consumer cannot terminate another valid consumer's group. +The upstream can reconnect with a remaining consumer's current credential. + +Set the `enable_request_signal` compatibility flag. The adapter preserves +Request.signal through rebuilt requests, and cancellation drops the associated +Rust work and shared-flight ownership. Plain HTTP disconnects before headers +did not produce that signal in the pinned local workerd fixture; those requests +remain bounded by the configured deadline. Explicit ingress abort signals, +response-stream cancellation and live last-leave teardown have separate actual +runtime tests. A cancelled command is never retried by the gateway; cancellation +does not imply that backend effects were rolled back. + +The fixture's migration declares a new `DeliveryCoordinator` SQLite DO class; +the adapter stores no cache entries or identity grants in durable storage. For +local reset, stop the runner and change its epoch (or use fresh disposable local +state). Rollback disables delivery bindings while retaining independent remote +forwarding. Do not reuse aggregate-cell classes or namespaces. Nothing in this +fixture provisions or deploys Cloudflare resources. + +Platform references: [request cancellation](https://developers.cloudflare.com/changelog/post/2025-05-22-handle-request-cancellation/), +[WebSocket API](https://developers.cloudflare.com/workers/runtime-apis/websockets/), +[outgoing socket lifecycle](https://developers.cloudflare.com/durable-objects/best-practices/websockets/). diff --git a/docs/graphql-query-cost.md b/docs/graphql-query-cost.md new file mode 100644 index 000000000..0fa9b3ab4 --- /dev/null +++ b/docs/graphql-query-cost.md @@ -0,0 +1,76 @@ +# GraphQL query cost + +What one GraphQL request may ask the database for, and where each limit is +enforced. The engine compiles every root field to one SQL statement; the +limits below bound that statement before it runs, and the statement timeout +bounds it while it runs. + +## The knobs + +Each knob has one unit and is checked in one place. All are set on +`GraphqlEngineBuilder`; the defaults live in `src/graphql/cost.rs`. + +| Builder method | Default | Unit | Enforced by | +|---|---|---|---| +| `max_depth` | 8 | nesting levels: fields in the document; relationships and `where` (boolean and relationship nesting) in the compiler | async-graphql `limit_depth`; the compiler | +| `max_fields` | 500 | selected fields in one document, each field once at every level | async-graphql `limit_complexity` | +| `max_rows` | 200,000 | model rows one root field's statement can produce (below) | the compiler, per root field | +| `default_limit` | 100 | page size of a list whose request gives no `limit` | the compiler, per list | +| `max_limit` | 1,000 | largest page size any list resolves to; a role's `limit` can lower it | the compiler, per list | +| `max_in_list` | 1,000 | entries in one `_in` / `_nin` list | the compiler | +| `max_bool_width` | 256 | entries in one `_and` / `_or` list | the compiler | +| `statement_timeout` | 5 s | wall clock per root field | PostgreSQL `statement_timeout`, plus an executor deadline on every backend | + +A request over a limit fails with `extensions.code` `BAD_REQUEST` and a fixed +message (`max depth exceeded`, `row budget exceeded`, `list too long`, …) +before any SQL runs. A statement that times out fails with `TIMEOUT` +(`statement timeout`). + +## Rows + +`max_rows` bounds how many model rows one root field can return, counted from +each list's *resolved* page size: the client's `limit`, else `default_limit`, +capped by the role's `limit` and by `max_limit`. + +- A page of `limit` rows costs `limit × (1 + rows nested under one of its rows)`. +- One object (a by-primary-key root, a belongs-to relationship) costs + `1 + rows nested under it`. +- Columns, `__typename` and `aggregate { count }` cost nothing. An aggregate's + `nodes` are a page. +- Siblings add. Arithmetic saturates, so an overflowing cost is refused, never + wrapped. + +For one chain of nested lists the cost is about the product of their limits: + +| Request | Rows | Default budget | +|---|---|---| +| `orders { id }` | 100 | admitted | +| `orders { id items { id } }` | 100 × (1 + 100) = 10,100 | admitted | +| `orders { items { parts { id } } }` | 100 × (1 + 100 × (1 + 100)) = 1,010,100 | refused | +| `orders(limit: 1000) { items(limit: 1000) { id } }` | 1000 × (1 + 1000) = 1,001,000 | refused | +| `orders(limit: 1000) { items { id } }` | 1000 × (1 + 100) = 101,000 | admitted | +| `orders { a { id } b { id } c { id } }` | 100 × (1 + 100 + 100 + 100) = 30,100 | admitted | +| `orders(limit: 1000) { items(limit: 199) { id } }` | 1000 × (1 + 199) = 200,000 | admitted | +| `orders_by_pk(id: 1) { customer { name } }` | 1 + 1 = 2 | admitted | + +`offset` is not part of the cost: skipped rows are scanned, not returned, and +the statement timeout bounds the scan. + +The budget is per root field. A document with several root fields is bounded +across fields by `max_fields`; a causal (protocol) request may carry only one +read root. + +## Client manifests + +Client manifests export the limits a generated client must respect as +`execution`: + +```json +{ "max_depth": 8, "max_fields": 500, "max_rows": 200000, "max_bool_width": 256, "max_in_list": 1000 } +``` + +The client compiler (`distributed client compile`) computes rows with the same +functions (`distributed::graphql::row_cost`) and refuses an operation whose +literal or default page sizes already exceed `max_rows`. A variable `limit` is +unknown at build time and counts as the field's default page size; the engine +checks the actual value on every request. diff --git a/docs/live-query-delivery.md b/docs/live-query-delivery.md new file mode 100644 index 000000000..f957ffb75 --- /dev/null +++ b/docs/live-query-delivery.md @@ -0,0 +1,201 @@ +# Live queries and authorization + +`@live` keeps an authorized query current. Resuming missed projection changes is +a separate capability: a partition-wide cursor can reveal activity outside a +row-filtered result, even when the rows themselves are protected. + +Every live response declares `extensions.distributed.live.mode`: + +- `snapshot`: a fresh authorized replacement result, with `reset: true` and + `cursors: []`. It carries no comparable index vector or projection observations. + The client keeps listening and reconnects with a fresh query, not a resume token. +- `resumable`: a result with matching, nonempty index and cursor vectors. Existing + resume validation, reset, replay and causal reconciliation rules apply. + +A failed execution has no result and therefore no `live` metadata. It is sent +as the terminal failure frame described below. + +## Shared execution at the origin + +Subscribers whose live roots are the same read share one producer. A catalog +root is the same read when its role, compiled SQL and every bind (row policies +and claim values included) match and, with the causal protocol on, its cache +scope does too; an external root when its role, root, arguments and session +match. The first subscriber's frame is the producer's first execution; a later +one opens with its own read, which honours its own resume cursors. After that, +each change that touches the read is debounced (100ms) and executed once, and +the frame goes to every subscriber, each with its own hash gate and envelope. +A subscriber whose cursors are not where a frame replays from (it joined +between frames, or skipped one while slow) catches up with one read of its +own, so replay stays exact. The producer keeps only the latest frame, so a +slow subscriber never holds the others back. + +At most `GraphqlEngineBuilder::live_concurrency` live executions (default +8) run at once per engine: first reads, refreshes and catch-ups together. +When the last subscriber of a read leaves, its producer stops. +`GraphqlEngine::live_producer_count()` counts producers (distinct reads); +`GraphqlEngine::live_subscriber_count()` counts subscription streams. + +## Failed live executions + +A live execution that fails (for example a storage error or statement timeout) +has no result. The server sends exactly one **failure frame** and then completes +the operation. The failure ends that subscription: the server sends no more +frames for it and never attaches a later execution's metadata to the failure +frame. A failed shared execution ends every subscription that shares it. A +failure frame has: + +- `data` that is `null` or absent; +- a nonempty `errors` array, where each entry is an object with a string + `message`; +- a valid base `extensions.distributed` envelope (`protocolVersion`, + `schemaHash`, `authorizationGeneration`, `cacheScope`, `operation`, and + `trustedPresets` when the surface has any), with no `snapshot`, `live` or + `command`. + +The client checks the envelope's binding, schema, operation and authorization +generation in the same way as for any other response. The failure frame then +works like an HTTP error response: it admits nothing. It writes no data or +membership, advances no cursor or operation generation, takes no ownership and +confirms no command. The client shows the original GraphQL errors for that +operation and keeps any previously admitted data readable. It closes the +failed stream. After a bounded backoff (1s, doubling to at most 30s, each +delay shortened by a random share of up to half so that clients do not reopen +in step), it refreshes the operation over HTTP and opens a fresh subscription +for the operation's current watches. That subscription resumes from the last +admitted cursors, if there are any. The backoff resets when an admitted frame +arrives, and that frame also replaces the errors. This is how a live query +recovers after its storage comes back, without a page reload. Disposing the +last watch or ending the authorization generation cancels a pending reopen. + +A lost connection takes the same path. The client keeps one WebSocket per +endpoint and credential and runs every live query over it as a separate +`graphql-transport-ws` subscription. When that socket errors or closes, each +of its subscriptions ends with a retryable error and is reopened as above; the +first one to reopen dials the socket again and the others share it. The +connection keeps its own backoff, so the queries of one page cause one dial +per attempt. A close that reconnecting cannot fix is not retried: a refused +`connection_init` (1002) and the 4400-4499 codes, except 4408 and 4401 with +the reason `token expired`. An `error` message for one subscription is retried +only when it is `LIVE_RESET_REQUIRED` or `FRESHNESS_SCOPE_CHANGED`. + +Whichever of the HTTP refresh and the reopened stream answers first is +admitted; the other is fenced by the operation generation, so the cache never +moves back. + +Only an error-only frame is a failure frame. A live frame that carries non-null +`data` (including partial data with errors) without both `snapshot` and `live` +is invalid, as are frames with `errors` that are absent, empty or malformed and +lack live metadata, and frames with a `snapshot` or `live` but not both. A +response without the `extensions.distributed` envelope is invalid as before. +Intermediaries that cannot relay a failure frame, such as shared gateway live +fan-out, end the consumer with `LIVE_RESET_REQUIRED` instead. + +Snapshot delivery does not relax read permissions or invent causal evidence. +Changes affecting only denied rows must not produce activity frames. A row +leaving the authorized result disappears from that operation's membership; +absence is not a globally authoritative deletion or tombstone. + +Within one current subscription, snapshot frames are ordered. The client fences +older HTTP requests when a live result takes ownership, and fences callbacks +from disposed subscriptions and previous authorization generations. Local cache +membership revisions are not server projection positions and cannot confirm +optimistic commands. + +A subscription also records its local start order. Snapshot delivery can take +over shared relationships owned by queries that preceded that subscription, +including SSR seeds from a layout or another island. This lets an initially +empty result acquire rows without waiting for another page load. It does not +override an independently active live stream or query ownership acquired after +the subscription started; those results have no safe cross-stream ordering. + +Independent streams often share an index without disagreeing about it. A +layout and a page may both select +`repositories(where: { id: { _eq: $id } }, limit: 1)` and then different +relationships below that row. A snapshot frame whose shared indexes have the +same membership as the independent owner's is admitted. Each such index must +contain the same normalized record keys in the same order and the same null +value, and the owner's index must be complete and not stale. The owner keeps +those shared indexes, and the frame writes only its other indexes and its +records. The resulting graph is exactly the frame's server result, so nothing +is fabricated and no cross-stream order is assumed. + +The whole frame is rejected as before if any shared membership differs or +cannot be established. That includes GraphQL errors, operation-local embedded +rows and rows without record evidence. The subscription is then reopened after +another operation next writes one of those shared indexes. The fresh result is +checked against the owner's new membership, so a stream whose frame arrived +before the owner caught up does not wait for its own next server change. + +When the last watch for a live operation is disposed, its local ownership is +retired at a monotonically increasing local boundary. A later live subscription +may take over an incomparable shared index only when that subscription started +after the retirement boundary. A subscription that started while the previous +stream was still active remains fenced against late frames from that stream. +Reopening the retired operation clears its retirement marker before transport +callbacks can arrive, so the reopened stream becomes an active owner again. +Retirement is local replica metadata; it does not claim that the server's +projection stopped or provide a server ordering signal. + +This is a breaking v5 protocol change: `mode` replaces the ambiguous `supported` +boolean. Upgrade server and generated-client runtime together. Old or unknown +wire forms fail closed; applications do not need a polling or reload workaround. + +## External read sources and leaderboard roots + +Roots that are not read-model roots come from an external read source +(`distributed::graphql::surface::ExternalReadSource`, attached to a catalog +Surface with `Surface::with_external_sources` and served with +`GraphqlEngineBuilder::external_read_source(executor)`). The source declares +its roots, result object types, per-role grants, the session claims it reads, +its contract entry and its client-manifest entry; the engine renders, +authorizes, fingerprints and exports them and runs each call through the +source's `ExternalReadExecutor`, which returns the value, a scope (bound +into the protocol scope token) and the change keys a live read waits on. + +Sorted-set leaderboards (the `distributed_leaderboard` crate, Redis with its +`redis` feature) are the one external read source: +`external_read_source(Arc::new(LeaderboardRoots::new(LeaderboardSurface, store)))`. For a surface +named `xp`, a role's grant (`LeaderboardGrant`) selects the roots: +`xpLeaderboard(first)`, `xpLeaderboardAround(radius)`, `xpMyRank` and, only +with `rank_any_member`, `xpRank(member)`. A board family +(`LeaderboardSurface::family`) adds `board: String!` to each. The viewer +roots take the member from the verified session claim (default `x-user-id`, +`LeaderboardSurface::member_claim`), never from an argument, and fail with +`FORBIDDEN` when the claim is absent. The same declaration feeds the static +SDL, the client manifest (`external.leaderboards`, omitted when empty so +other manifests and fingerprints are unchanged) and the generated +`leaderboards.ts` (typed documents and `@live` subscription documents). + +`xpLeaderboard`, `xpLeaderboardAround` and `xpMyRank` are also subscription +roots. They re-execute when the board's change key +(`leaderboard:{board}`) or the every-board key (`leaderboard:*`) is +published, which `distributed_leaderboard::change_listener(&engine)` does +when registered on the +`LeaderboardProjector` that writes the board (applied changes and rebuild +promotions; duplicates are silent). Pushes are hash-gated like SQL live +queries, and a failed execution is terminal. With the causal protocol on, +a leaderboard result carries an incomplete snapshot +(`recordsComplete: false`, `indexesComparable: false`) and live frames use +`snapshot` mode with `reset: true`: leaderboard rows are never normalized +into the replica cache or resumed from cursors. + +The listener is in-process. When the projector runs in another process +(a zone server projecting kills into Redis while a GraphQL service serves +the same boards), the change goes over the application's bus: + +- the projector's process registers `LeaderboardChangePublisher::listener()`, + which publishes a `distributed.leaderboard.changed` event + (`{ "board": "" }`) per changed board. Pending boards are a bounded + set (`spawn(publisher, capacity)`): repeated changes to a board coalesce, + and a change to one board more than fits replaces the set with a single + every-board notice (`{}`), so a slow or down bus costs bounded memory and + subscribers resync instead. Retryable publish errors are retried with + backoff; permanently refused notices are dropped; +- the GraphQL process runs `distributed_leaderboard::change_handlers(&engine, + group)` with `bus.subscribe(..)` under a consumer group of its own, so + every GraphQL process receives every notice and republishes + `leaderboard:{board}` (or `leaderboard:*`) on its `ChangeHub`. + +A notice only names the board; the subscriber re-reads its store, so +duplicate or replayed notices push nothing new. diff --git a/docs/live-retired-owner-handoff.md b/docs/live-retired-owner-handoff.md new file mode 100644 index 000000000..f0c46f441 --- /dev/null +++ b/docs/live-retired-owner-handoff.md @@ -0,0 +1,21 @@ +# Snapshot stream handoff after owner disposal + +A snapshot live stream can begin while a previous route still owns a shared +relationship index. Its buffered frames must not acquire that graph merely +because the old route later disposes: their start fence predates disposal. +However, retaining that fence forever leaves the new route permanently pending. + +When an incoming snapshot is blocked by a retired owner's index, reopen that +contending operation at a fresh local start fence. Reject the triggering old +frame and all subsequent callbacks from its retired transport. Only a new +server-authorized initial frame may take over the graph. A still-active owner +continues to block; normal same-scope hydration must not restart retained layout +subscriptions. No application polling, forced refresh, or optimistic-state +suppression is part of this recovery. + +Runtime evidence: Forge's creation page received completed/ready rows, but the +prior NewRepository operation owned a shared topology relationship at revision +24, retired at 27, after the new subscription had already started. Entity clocks +advanced while the complete-empty root index remained fenced. The existing +pre-disposal protocol test covers safety; a fresh-receiver continuation covers +liveness after the same boundary. diff --git a/docs/protocol-manifest-reuse.md b/docs/protocol-manifest-reuse.md new file mode 100644 index 000000000..93a610319 --- /dev/null +++ b/docs/protocol-manifest-reuse.md @@ -0,0 +1,44 @@ +# Immutable protocol manifest reuse + +Runtime contract: a selected client surface export owns immutable service, +role/application selection, surface IR and execution limits. Its derived manifest +can be initialized once and shared across clones. Public callers still receive +independently mutable manifest copies. Errors are deterministic for that export +and may be retained; creating another export/engine creates a separate cache. + +The engine must retain the exact exports already validated during protocol +construction, including distinct role and application identities. Request seeds +may borrow their compiled manifests, but must still validate principal, asserted +roles, resolved preset values, authorization generation, visibility surface, +cache-scope HMAC and issuance time for each request. No session, token, result row, +authorization decision or request seed is cached. + +Observed baseline in Forge: authenticated document TTFB around 2.9–4.1 seconds, +simple authenticated GraphQL queries around 1.1 seconds. Native sampling identifies +ProtocolProjectionRequestSeed::new → export.manifest → projection manifest +lowering as repeated CPU work. Validation must cover cache/clone concurrency, +mutable-return independence, role/application/limits isolation and existing +protocol privacy/authority tests, followed by same-route runtime measurements. +No deadline, authentication, SSR or live-subscription behavior may be weakened. + +## Measured local validation + +Same retained Forge stack, same authenticated user and paths, September 21: + +| Warm document (DOM ready) | Before | After | +| --- | ---: | ---: | +| Dashboard | 3140 ms | 116 ms | +| Personal repository, including default-ref redirect | 7445 ms | 291 ms | +| Organization People | 3350 ms | 192 ms | +| ChangeSets | 4123 ms | 97 ms | + +Three direct authenticated GraphQL queries fell from 1143/1135/1072 ms to +22/15/14 ms. These are local observations, not performance assertions or an SLA. +The first repository document after the development server restart still took +18.7 seconds; the warm comparison does not hide that cold-development cost. + +Framework library: 1052 passed, 3 explicit ignored. GraphQL/identity/causal HTTP +integration targets: 43 passed. Added tests exercise concurrent first use, +independent mutable returns, role/application/limit separation, rebuilt-engine +isolation, and actual repeated protocol accumulators retaining/releasing shared +metadata without retaining request authority. Existing auth/privacy checks remain. diff --git a/docs/reloading-event-delivery.md b/docs/reloading-event-delivery.md new file mode 100644 index 000000000..00e0969b9 --- /dev/null +++ b/docs/reloading-event-delivery.md @@ -0,0 +1,23 @@ +# Event delivery during application reload + +A supervisor generation gate is temporary infrastructure state, not a domain +rejection. The gate is an explicit value: the process resolves +`LifecycleGate::from_env()` once where it composes its services and passes it +to each with `Service::with_lifecycle`; a service given no gate is always open. +A GraphQL engine built from the service (`.service(&service)`) takes the same +gate. The gate answers from memory and follows the supervisor's membership file +in the background every 50 ms, so it lags the supervisor by at most that long; +the supervisor waits at least 500 ms after fencing before replacing a process. + +Both direct command admission and bus dispatch return typed +`ApplicationReloading` while closed. Bus conversion classifies it as retryable +and retains/stops the receive loop: NAK the exact delivery, then surface the +error to the host's bounded restart policy. It must never Ack, Term or apply +ordinary permanent-failure policy. After activation the same delivery can run. + +Business validation/authorization failures retain their existing permanent +classification and configured settlement policy. No gate bypass or implicit +success is introduced. The NAK uses the transport's ordinary retry spacing +(NATS JetStream: delivery-count backoff, see +[consumer delivery lanes and retry backoff](consumer-delivery-lanes.md)); the +gate adds no delay of its own. diff --git a/docs/reviews/v5-pre-release/00-summary.md b/docs/reviews/v5-pre-release/00-summary.md new file mode 100644 index 000000000..3ffa9ca44 --- /dev/null +++ b/docs/reviews/v5-pre-release/00-summary.md @@ -0,0 +1,225 @@ +# v5 pre-release review: consolidated summary + +Reviewed 2026-11-18 on branch `v5` (d9e9bd20). Thirteen reviewers each read one slice; their full +reports are files `01`–`13` in this directory, with `path:line` citations for every finding. + +**How to read this.** Nothing was compiled or run; every finding comes from reading code. Items +marked **[checked]** are ones the consolidating reviewer re-opened and confirmed in the source. The +rest are as reported by the slice reviewer (each marks its own findings CONFIRMED or PLAUSIBLE). +Each report opens with an exact list of what was not read. + +## 1. Fix regardless of the breaking-change plan + +### Authorization and identity +- **[checked] Multi-role application surface runs SQL with the first role's row filter.** + `src/graphql/engine/auth.rs:219-227` returns `first.row_filter` in both branches. Report 04 #1. +- **[checked] Identity fails open.** A `GraphqlEngine` without `.identity(..)` defaults to + `DevHeaders` (`engine/builder.rs:40`). `IdentityConfig::hybrid()` has no gateway secret, so a + request with no bearer is trusted from its headers (`identity/resolve.rs:351-357`). `?x-user-id=` + and `?x-roles=` are merged into headers on every WebSocket upgrade in every mode + (`graphql/http.rs:546-547`), and the gateway strips the headers but forwards the query string. + Reports 05 #1–3, 07 #1. +- Command-delta row policy is a fourth interpreter of `FilterExpr` with wrong NULL and numeric + semantics, so a command can push a row into a replica that the query would not return. + Report 05 #4. +- Gateway: Zones binding forwards the caller's bearer and cookies; worker `Handler`/`Assets` + bindings get unstripped client headers; `extensions.gatewayDelivery` can be forged by a client. + Report 07 #13–15. +- JWKS refresh has no failure backoff or stale-if-error, so an IdP outage turns into serial 5–10 s + timeouts and 401s. Report 05 #5. +- Origin WebSocket subscriptions outlive token expiry and have no keepalive or caps. Report 05 #6. + +### Data loss and correctness +- **[checked] `projection!` rebuilds and revalidates the whole program on every event and leaks a + string per event type each time** (`src/lib.rs:231-238`, `src/mutation/descriptor.rs:85,155`). + Reports 03 #1, 08 #3. +- **[checked] The default failure policy drops messages.** Kafka `dead_letter` commits past the + record; RabbitMQ queues have no dead-letter exchange; SQL deletes the row. Report 07 #2. +- **[checked] Outbox retry has no backoff** and counts every failure toward the ceiling, so a broker + outage sends the oldest rows terminal in seconds; there is no requeue API. Report 01 #5. +- Bus consumers return `Ok(())` when idle by default; Kafka and RabbitMQ have no long-running mode, + and the supervisor treats the clean exit as a host bug. Report 07 #3. +- `#[event]` records the event before a fallible recorder body runs. Report 08 #1. +- `mutation_file!` does not register its input with Cargo, so editing only the `.graphql` file + leaves the old program running. Report 08 #4. +- `QueuedRepository` **[checked: holds the stream lock after `get_stream` returns]** self-deadlocks + when combined with snapshots on a stale snapshot, and releases locks it does not own. + Report 01 #1–3. +- Plain `repo.commit(&mut agg)` with captured domain events persists replay events and publishes + nothing. Report 01 #4. +- Legacy JSON handlers are a second write path with no roles, ledger or canonical input, and they + are the only thing bus, Knative and saga commands can reach. `AggregateCell::dispatch` runs typed + commands with none of those checks and exists only for tests. Report 06 #2–3. +- `#[command(id = ..)]` wraps the user's handler in `#[cfg(feature = "application-runtime")]` + evaluated in the user's crate, with the lint suppressed. Reports 08 #6, 07 #9. +- Backends disagree: tombstoned-record observation (memory accepts, SQL rejects), tail load of a + missing stream, `_like`/`_ilike` case rules. Reports 03 #7, 01 #7, 04 #7. + +### Game runtime +- **[checked] An unauthenticated Hello activates a zone before the ticket is verified** + (`distributed_game/src/net/mod.rs:1689` vs `:1719`). Report 10 #1. +- Fencing token and `boot_epoch` can repeat after a crash-restart, so new facts are dropped as + replays; a zone keeps simulating and committing facts after lease renewal fails. Report 10 #2–3. +- Admission is implemented twice (native vs celld) with different ticket checks and no rate limit + on celld. Report 10 #4. + +### TypeScript client +- **[checked] A dropped live WebSocket is never reopened** (`impl-fetch-live.ts:347-362`); one + socket per live query. Report 11 #2. +- **[checked] Every cache transaction `structuredClone`s the whole cache**, then re-extracts and + re-materializes it several more times. Report 11 #1. +- **[checked] `gc()` has no caller**; per-operation and per-command maps never shrink. + Report 11 #3–5. + +### Tests that do not run +- **[checked] Five Postgres projection-protocol tests return early on an env var nothing sets**, so + they pass without executing, including the regression test for #297. Report 02 #1. +- The same early-return pattern covers every broker and Postgres integration test; several targets + are never run with their service in any workflow. GraphQL/RBAC is proven on SQLite only (about + 165 tests vs 4 on Postgres). Report 12 #1–2. + +### Tooling +- `distributed dev` orphans `cargo run` / `npm run dev` on anything but Ctrl-C; build cancel kills + only the direct child; a transient file error ends the session. Report 09 #11–12. +- The reference app contains a dual write (`auth_users` upserted directly and also projected). + Report 13 #9. + +## 2. Structural themes for the breaking-change pass + +### One contract, several hand-maintained copies +The client wire contract exists as Rust runtime types, a second Rust copy in the CLI (the CLI does +not depend on `distributed`), and hand-written TypeScript types and validators. Preview +canonicalisation, trusted presets, complexity estimation and `GameSurface` are also twinned, and +some have already drifted. Reports 09 #1–6, 05 #8–9, 11 #6–9. +**Change:** the CLI depends on `distributed` (default features off) and `distributed_game`; delete +the mirrors; emit Rust-generated fixtures for the response envelope and a much larger query-plan +corpus for the TS side. + +### Two (or more) of everything +| Concept | Parallel implementations | Report | +|---|---|---| +| Projection program IR | `MutationProgram` and `ProjectionProgram`, bridged by a per-field rewrite; 4 "kind" enums | 03 #2, #10 | +| Read permissions | `ReadPermission` and `RoleGrant`, two intersections, two validators | 04 #3 | +| Row-policy evaluation | SQL compiler, cell evaluator, delta evaluator, TS replica | 05 #4 | +| Commit assembly | `AggregateRepository::commit`, `CommitBuilder`, `AggregateCommit`, causal workspace | 01 #4 | +| Command declaration | 5–7 forms; the reference app uses the verbose one for all 11 commands | 08 #5, 06, 13 #2 | +| Typed command pipeline | 3 copies in `routes.rs` plus a parallel helper set for cells | 06 #1 | +| Command dispatch | `CommandHost` and an inert `CommandDispatcher`/remote envelope | 06 #6 | +| Immediate publish / timers / leases | mailbox vs born-InFlight; `deliver_at` vs `Schedule`; `lock/` vs `lease/` | 01 #11, #13, #14 | +| Gateway adapters | native and worker live/delivery state machines copied | 07 #10 | +| Game drivers | `net/` and `celld_zone/`, plus an unused `Recorder` wrapper | 10 #4, #13 | +| SQL dialect seam | `Statement/SqlExecutor` and `SqlxRepoBackend + QueryBuilder` | 02 #10 | + +### Backend parity is asserted, not enforced +The projection commit state machine is written twice (memory and SQL) and has diverged; bus adapters +differ on ordering, redelivery, grouping and poison handling; conformance suites cover a fraction of +either. Reports 03 #6, 02 #2–3, 07 #4, 12 #3–4, #14. +**Change:** move decisions above the store/transport traits as pure functions; one conformance macro +per contract (the repository one in `tests/persistent_repository_conformance` is the model), +instantiated for every backend, with exclusions as named capabilities. + +### Pre-release compatibility and unused surface +- `QueuedRepository` + `lock/` (about 2.3k lines; the service path already bypasses it). 01 #3 +- Roughly a third of `src/mutation/` has no production caller. 03 #4 +- Confirmations/obligations, the `CommandEffects` IR, half of `command_dispatch/`. 06 #4–6 +- Application deployment plan / capability / runtime-host layer (about 1.6k lines). 07 #8 +- About 2.7k lines of `distributed_cli/contracts/`; `contracts check` does not check drift; root + `build.rs` twins it. 09 #7–8 +- 13 migrations for an unreleased schema; the SQL bus runs a legacy upgrade under + `ACCESS EXCLUSIVE` on every `listen`. 02 #11, 07 #5 +- `aggregate!`, `#[digest]`, `#[enqueue]`, `emitter`, `impl_aggregate!`, `graphql_models!`, + `module!`/`application!`, bus `capabilities.rs`, game protocol v1 negotiation, `CellFactSink`. + 08 #7, 07 #18, 10 #10–11 +- Feature flags: `runtime` gates nothing; `application-runtime`; `leaderboard-background`; the + 17-times-copied "is tokio present" cfg list that omits `redis`. 01 #10, 07 #22–23 + +### Layering +- Typed command execution compiles only with the `graphql` feature; `ScheduleWorker` and projection + rebuild are gated on it too. 06 #16, 01 #9, 03 #13 +- Core imports `microsvc`, cell-host and Durable Object details. 01 #9 +- Leaderboard is a second projection system inside the core crate. 07 #21 +- Lifecycle write gate is an env var read from disk on every dispatch. 06 #12 +- The CLI and "framework-neutral" compiler are hard-wired to SvelteKit, npm and the e2e app. 09 #13 + +### Authoring experience +Adding one command to the reference app touches about 12 hand-edited sites. The module `routes()` +bounds wall, `projection_owners()`, `MODULE_IDS`, the hand-built manifest and the sqlite/postgres +host fork restate what the framework knows. e2e-celld copies the whole service layer (about 3.3k of +3.6k lines). The app-owned `distributed.config.js` is 300 lines of validation. Report 13 #1–8, +#12–13, #17. Framework gaps surfaced by workarounds in the apps: no client pagination primitive, no +`now()` input default, no per-row pending state, no routes without an aggregate, no integration +event → `projection!` path. Report 13 #9–10, #18–21. + +### Performance +- About 28 SQL statements per projected event; ownership-fence `FOR UPDATE` serialises read-model + commits per table; unindexed causation lookup; per-row snapshot loop. 02 #4–7 +- In-memory store clones all protocol state per commit. 03 #8 +- Live queries: one full query per subscriber per table-level change, no sharing. 05 #7 +- Query cost model ignores `limit`. 04 #4 +- Contract fingerprint recomputed per dispatch; post-commit ledger re-read; ledger never compacted. + 06 #7, #8, #11 +- Postgres bus: one contended row, about 7 statements per publish. 07 #16 +- Game: per-entity allocations per patch, no collision broadphase, O(N) clone per lag-comp query. + 10 #7–9 + +### Tests +Overall verdict from the test reviewer: the suite is mostly behavioural; the implementation-detail +tests are a small nameable set. +- Source-grep tests: `tests/legacy_authoring_absence.rs`, two in `e2e_ui_celld_nats_profile`. 12 #7 +- Golden SHA-256 hashes of whole SDL/manifest artefacts. 04 #17 +- Expansion-string `contains` tests in the macro crates (about 140 assertions); 18 rustc-pinned + trybuild snapshots. 08 #17–18 +- Tests of derives, constants and unreachable states (named lists in 01 #24, 03 #20, 06 #20, + 09 #19, 12 #9, 13 #27). +- Copy-paste where a conformance suite belongs: 804 shared lines between `sqlite_transport` and + `postgres_transport`; three near-identical projection-store test files (about 9k lines). + 12 #4, 03 #19, 02 #3 +- 87 test binaries, 51 empty under default features; about 12 Todo-like fixture aggregates. + 12 #13, #16 + +### Docs +`docs/application-composition.md` describes an API that does not exist and a role matrix the README +rejects. The README is 2,845 lines mixing pitch, runbook and reference, with several stale +statements. Reports 13 #23–25, 07 #24. + +## 3. Suggested order +1. Section 1 fixes, with a failing test first for each. +2. Make skipped tests fail (`require_service`), run the full matrix in CI, port the authz suite to + Postgres. +3. Deletions (they shrink everything that follows). +4. Unifications: one program IR, one permission type, one commit path, one command form, one typed + pipeline; CLI depends on the runtime crate. +5. Lift backend logic above the store and bus traits; conformance macros. +6. Performance work on the reduced code. +7. Authoring-surface and docs pass against the reference app. + +## 4. What the reviewers said not to change +Each report ends with a short list. Recurring items: `CommitBatch` as the single atomic unit; the +command ledger state machine and its conformance suite; canonical, domain-separated identities with +frozen fixtures; the one-compiler/`DialectOps` GraphQL design with bind-only values; live queries as +hash-gated re-execution through the one-shot path; the bus runner layering; `ZoneHost` being +synchronous and deterministic; three-valued query-plan evaluation in the replica; the repository +conformance macro; domain crates as plain structs. + +## Owner decisions (2026-11-18) +- v5 is a breaking release: prefer the clean structural change over a compatible patch wherever a + finding offers both, and do wire-level renames now. +- The demos (e2e-ui and e2e-celld with SvelteKit, and the game demos) must work at the end. They may + be rewritten to fit the new APIs; they are the acceptance gate, not a constraint on the design. +- The owner likes the e2e-ui demo experience and the principles as they are. Read the "Authoring + experience" theme and report 13 as optional polish: internal changes should preserve what e2e-ui + authors write and what its users see, and must not replace the forms it uses + (`portable_command!`, `projection!`, permissions beside the model, the page code). +- Rename `portable_command!` to `command!`. This requires removing the fn-form `#[command(id = ..)]` + attribute first (report 08 #5–6 already recommends it): both are exported from + `distributed_macros` and two macros cannot share the name `command`. The method form + `#[command("agg.verb", ..)]` is consumed by `#[sourced]`, not a macro of its own, so it can stay. +- `QueuedRepository` is kept. Fix its defects (report 01 #1-2); the recommendation to delete it and + `lock/` (report 01 #3, and its entry under "unused surface" below) is withdrawn. +- gitkb/metaforge (`twig-metaforge`) is pinned to `v5` and must still work after the refactors. +- Assumed, not confirmed: no deployed databases need an upgrade path, so migrations can be squashed + and legacy upgrade code deleted. + +## Housekeeping +GitKB in this repo was stuck in an interrupted 0.1→1.0 upgrade during the review +(`.kb/.migrate-*` present, every `git-kb` command erroring), so no task documents were created. diff --git a/docs/reviews/v5-pre-release/01-core-event-sourcing.md b/docs/reviews/v5-pre-release/01-core-event-sourcing.md new file mode 100644 index 000000000..4c38d0a47 --- /dev/null +++ b/docs/reviews/v5-pre-release/01-core-event-sourcing.md @@ -0,0 +1,232 @@ +## Assessment + +The core is in better shape than its size suggests: `CommitBatch` is one atomic unit on every backend, validation is shared, snapshots are a cache with a schema gate, and the outbox claim/settle model is sound. The weak part is the layer above it, where several generations of API coexist (queued/locking repo, four commit assemblers, two immediate-publish modes, two timer mechanisms). + +Nothing here was executed (the brief forbids builds), so "CONFIRMED" means confirmed by reading the cited lines. + +Three things most worth changing: +1. Delete `QueuedRepository` and with it `lock/`; it self-deadlocks on a stale snapshot, leaks locks, and the service path already bypasses it (findings 1-3). +2. Collapse the four commit paths into one, with the domain-event guard inside the shared validation (finding 4). +3. Give outbox retries a backoff and classify failures; today a broker outage sends the oldest rows terminal in seconds (finding 5). + +Not read: +- **Non-test code:** `src/entity/upcaster.rs` (signatures only), `src/emitter/local_event.rs`, `src/lease/in_memory.rs`, `src/lease/sqlx_store.rs` 200+, `src/lock/postgres_lock.rs` and `src/lock/sqlite_lock.rs` (constants only), `src/repository/sqlite_codec.rs`, `src/repository/sql/ledger.rs` 60+, `src/repository/error.rs` 120+, `src/repository/sql.rs` and `src/repository/sql/outbox.rs` tails beyond what is cited, `src/outbox_worker/testing.rs`. +- **In-module test bodies:** I listed every test fn name in the slice but read bodies only for `entity/entity.rs` 706-760, `entity/event_record.rs` 274-330, `outbox/table.rs` tests, `repository/sql.rs` 386-440, one test in `outbox_worker/store/tests.rs`, the head of the `in_memory_repo/repository.rs` tests, and `snapshot/repository.rs` and `queued_repo` tests. The test-quality question is therefore answered from names plus samples. +- **Out of slice:** `in_memory_repo/projection_protocol/`. + +All paths below are under `/Users/patrickleet/dev/hops-ops/hops/distributed/`. + +## Findings + +### 1. `.queued()` + `.with_snapshots()` self-deadlocks on a stale snapshot +- Category: E Severity: high Confidence: CONFIRMED (by reading; not executed) +- Where: `src/snapshot/repository.rs:339` and `:357`; `src/queued_repo/repository.rs:142-154`, `:169-183`; `src/lock/in_memory.rs:9-13`; `src/lock/sqlx_common.rs:57-65` +- What: Snapshot `get` calls `(reads.tail)`, which on a queued repo takes and holds the per-stream lock. On `SnapshotHydrationError::Cache` (for example after a `SNAPSHOT_VERSION` bump) it calls `(reads.full)`, which is `QueuedRepository::get_stream` and awaits the same lock again. `InMemoryLock` is non-reentrant and ownerless, and the SQLx lock's in-process gate is the same type with `max_wait` defaulting to `None`. +- Why it matters: The first `get()` of any aggregate whose snapshot schema changed hangs forever. That is exactly the scenario the cache-miss fallback exists for. The only queued+snapshot integration test is the happy path (`tests/snapshots/main.rs:290`); the stale case is tested only through causal reads (`causal_snapshots_use_only_tail_through_queued_wrappers`, `src/snapshot/repository.rs:455`). +- Change: Remove `QueuedRepository` (finding 3). If it stays, the lock must be taken once by the caller and returned as a guard, not by each read primitive. Size S if deleted, M otherwise. + +### 2. Queue locks leak and are released by non-owners +- Category: E Severity: high Confidence: CONFIRMED +- Where: `src/queued_repo/repository.rs:146-153`, `:267-295`; `src/lock/in_memory.rs:76-88`; `README.md:1229-1231` +- What: `get_stream` keeps the lock held after returning, including for `Ok(None)`. The README example returns `Err(NotFound)` without `abort`, which leaks the in-memory lock permanently (no TTL). `commit_batch` calls `ensure_lock(...).unlock()` for every committed stream whether or not this caller acquired it, and `unlock_core` has no owner check. +- Why it matters: A commit of a fresh or `peek`ed aggregate releases another task's lock, so the serialization guarantee is not real. Any early return leaks. +- Change: Same as finding 1. If per-stream serialization is wanted, make it an RAII guard returned by a single `checkout` call. Size M. + +### 3. `QueuedRepository` is a decorator that must forward every backend trait, and the service path already bypasses it +- Category: A/C/F Severity: high Confidence: CONFIRMED +- Where: `src/queued_repo/repository.rs` (854 lines; forwarding at `:315`, `:360-543`, `:839`; "legacy" comments at `:310`, `:782-788`; blanket `impl Queueable for T` at `:765`); `src/microsvc/service/defaults.rs:47` +- What: About 450 lines forward `CommandLedgerStore`, the `Causal*` traits, `ProjectionProtocolStore`, `SnapshotStore`, the read-model stores, `InboxStore`, and `microsvc::BackendHost`/`CausalHostProjections`. Core therefore imports `crate::microsvc` and `crate::projection_protocol`. The causal (service) path deliberately skips the locks (`:199-207`, `:303-312`) and the comments call the locking path legacy, yet `.queued()` is the documented default. `GetWithOpts`, `GetAllWithOpts`, `ReadOpts`, `UnlockableRepository` and `Queueable` exist only for it. +- Why it matters: This is the "wrapper type carrying one optimization" the owner does not want, and each new backend capability needs another forwarding block. Optimistic concurrency already fences writers (`tests/queued_repo/main.rs:255` asserts exactly that). +- Change (breaking): Delete `queued_repo/`, `lock/` (about 1,400 lines; its only consumer per `src/lock/mod.rs:3-4`) and the five helper traits. Move `RetryClass` out of `lock/error.rs` into the repository error module. Size M. + +### 4. Four hand-assembled commit paths with different guarantees +- Category: A/C/E Severity: high Confidence: CONFIRMED +- Where: `src/aggregate/repository.rs:316-366`; `src/commit_builder/mod.rs:53-57`, `:79-87`, `:170-188`; `src/outbox/commit.rs:233-311`; `src/microsvc/causal.rs:639`, `:838`; `src/repository/validation.rs:29-52` +- What: `AggregateRepository::commit*`, `CommitBuilder::commit_all`, `AggregateCommit::commit` and the causal workspace each build a `CommitBatch`. They differ in three ways: + - **Domain-event guard:** only the last two call `domain_event_commit_guard` / `pending_domain_events_for_commit` / `mark_domain_events_committed`. Plain `repo.commit(&mut agg)` with captured domain events persists the replay events, publishes nothing, and leaves the occurrences pending. `AggregateCommit` instead errors with "add `publish_events()`" (`outbox/commit.rs:307-311`). + - **Outbox source stamping:** `CommitBuilder` overwrites unconditionally; `AggregateCommit` stamps only when all three fields are `None` (`:238-245`). + - **Snapshots and immediate publish:** `CommitBuilder` hard-codes `snapshots: Vec::new()`, so the snapshot policy is silently skipped, and it never triggers immediate publish. +- Why it matters: The same aggregate gets different durability and publication semantics depending on which builder the handler used. The silent drop of domain events breaks principle 1. +- Change (breaking): Keep one commit builder (the `AggregateCommit` shape) and make `repo.commit(&mut a)` its zero-option form. Delete `commit_builder/`. Move the poison/pending-occurrence check into `validate_commit_batch` so no path can skip it. Size M-L. + +### 5. Outbox retry has no backoff and rows go terminal within seconds +- Category: E Severity: high Confidence: CONFIRMED +- Where: `src/outbox_worker/store/api.rs:200-215`; `src/repository/sql/outbox.rs:231-246`; `src/outbox/message.rs:571-582`; `src/outbox_worker/drain.rs:188-196` +- What: `record_failure` releases the row until `claim.attempt >= max_attempts`, then marks it `Failed`, regardless of error kind. Release makes the row immediately claimable (`next_available_at = now`). The drain loop sleeps `Duration::ZERO` whenever `claimed >= batch_size`. I found no API to requeue failed rows (rg for `requeue`/`retry_failed` in outbox, outbox_worker and repository returned nothing). +- Why it matters: With a broker down and a backlog of at least 32 rows, the oldest rows burn every attempt in a tight loop and become terminal while hot-spinning the database. The schedule worker has the opposite policy: exponential backoff and no ceiling (`src/schedule.rs:601-607`). +- Change: On release set `next_available_at = now + backoff(attempt)`. Do not count transient or unknown transport outcomes toward the ceiling. Add an explicit requeue for failed rows. Use one retry policy type for outbox and schedules. Size M. + +### 6. Direct read-model writes from command commits +- Category: A Severity: medium Confidence: CONFIRMED +- Where: `src/outbox/commit.rs:368`; `src/commit_builder/mod.rs:250-263`; `src/repository/traits.rs:37`; `src/repository/error.rs:38` +- What: Handlers can attach `TableWritePlan`s to the aggregate commit. The code's own error doc calls this "a raw/legacy repository batch". +- Why it matters: It is a second write path into read models that bypasses domain event → projection (principles 1 and 2), and the browser replica cannot reproduce those rows (principle 5). +- Change (breaking): Remove `read_model_plans` from the public commit surface and keep it crate-private for the projector. Port the tests and bomberman handlers that use it. Size M. + +### 7. SQL and in-memory disagree on tail load of a missing stream +- Category: A/E Severity: medium Confidence: CONFIRMED +- Where: `src/in_memory_repo/repository.rs:635-648`; `src/repository/sql.rs:309-321`; `src/snapshot/repository.rs:339-342`; `src/repository/traits.rs:124-127` +- What: In-memory returns `Ok(None)` for a missing stream and clamps the prefix to the true version. SQL `load_stream` with `Some(after)` and zero rows returns `Some(entity)` at version `after` ("Keep the existing SQL snapshot-only restore contract"). The snapshot code expects `None` and the trait doc promises clamping. +- Why it matters: On SQL a lingering or planted snapshot for a non-existent stream hydrates a live aggregate; in memory it does not (principle 7). +- Change: Make SQL read the stream version and return `None`/clamp. Add the case to the persistent conformance suite. Size S. + +### 8. Snapshots make `get_with`, `peek`, `get_all` and `peek_all` slower +- Category: D Severity: medium Confidence: CONFIRMED +- Where: `src/aggregate/repository.rs:279-308`, `:376-387`; `src/snapshot/repository.rs:257-305`; policy struct at `src/aggregate/repository.rs:40-106` +- What: Only `get` reads snapshot then tail. The other four load the full stream and then also fetch the snapshot(s). +- Why it matters: This is strictly more I/O than with snapshots off, which contradicts "optimizations are transparent". `SnapshotPolicy` also carries six function pointers to avoid trait bounds. +- Change: Route every read through the one snapshot-then-tail loader (batched with `get_snapshots` plus one tail query for `get_all`). Size M. + +### 9. Core depends on microsvc, GraphQL, Durable Objects and game vocabulary +- Category: A Severity: medium Confidence: CONFIRMED +- Where: `src/schedule.rs:50`, `:369-370`, `:437-448`, `:550`; `src/schedule.rs:52-53` with `src/schedule/worker.rs:54-56`; `src/repository/traits.rs:44`; `src/in_memory_repo/repository.rs:171-237`; `src/repository/migrations.rs:16-22`; `src/lease/mod.rs:3-5`, `:53-57`; `src/entity/entity.rs:355` +- What: + - `schedule.rs` uses `microsvc::Session`, `cell_host::CellCommandIdentity` and `CausalCommandContext`, and has a JS-safe-integer limit for Durable Object SQL. + - `ScheduleWorker` is gated on the `graphql` feature because it takes `graphql::identity::VerifiedPrincipal`. + - `CommitBatch` depends on `schedule::ScheduleWrite`, so repository ↔ microsvc is a cycle. + - `InMemoryRepository` exposes `clone_*/replace_*` hooks for DO persistence. + - `migrations.rs` hard-codes cell migration versions `1|2|4|8|11`. + - `lease` docs talk about "boss controller" and "encounter settlement". +- Why it matters: A layering inversion. A plain HTTP service cannot run schedules without GraphQL, and the reference backend carries an adapter's persistence API. +- Change: Split schedule into a core data type plus store trait (no session or cell types) and a worker in microsvc gated on a runtime feature. Move `VerifiedPrincipal` out of `graphql`. Move the DO hooks and the migration subset into `cell_host`. Scrub the game wording. Size M. + +### 10. The "is tokio present" cfg list is copied 17 times and is wrong +- Category: F Severity: medium Confidence: CONFIRMED +- Where: `src/lib.rs:6-9`, `:399-408`; `src/outbox/commit.rs:62-90`; `src/outbox_worker/mod.rs`; `src/microsvc/service/routes.rs:543-570`; `Cargo.toml:60-63` +- What: `any(feature="http","grpc","postgres","sqlite","nats","rabbitmq","kafka", test)` appears 17 times in `src`. It omits `redis` and `leaderboard-background`, which also enable `dep:tokio`. There is also a crate-level `allow(dead_code)` when no graphql/sqlite/postgres feature is on, and 16 `cfg_attr(not(feature = "graphql"), allow(dead_code))` sites. +- Why it matters: A redis-only build silently gets the fallback publish path. The dead-code allows hide genuinely dead items. +- Change: Add one internal `runtime-tokio` feature implied by every tokio-using feature and gate on that. Fix the layering in finding 9 so the graphql allows can go. Size S-M. + +### 11. Two immediate-publish mechanisms, and three docs that contradict each other +- Category: C/F Severity: medium Confidence: CONFIRMED +- Where: `src/outbox/commit.rs:31-94`, `:227-230`, `:252-266`; `src/outbox_worker/publish_hook.rs` (header); `src/microsvc/service/routes.rs:543-570`; `README.md:1390-1394`; `src/outbox/mod.rs:6` +- What: The mailbox path (rows stay pending, drain is hinted) and the "born InFlight" pre-claim plus `OutboxPublishHook` path both exist. `Service::with_bus` always installs the mailbox when a tokio feature is on, so the hook is reachable only in no-feature builds and tests. The README documents born-InFlight, the `commit` doc says rows stay pending, and `outbox/mod.rs` references a nonexistent `OutboxCommit`. +- Change: Keep the mailbox path only. Delete `publish_hook.rs`, `BusOutboxPublishHook` and the pre-claim branch. Fix the README. Size S-M. + +### 12. `outbox/table.rs` is a second outbox row encoding used only for throwaway validation +- Category: C/D Severity: medium Confidence: CONFIRMED +- Where: `src/outbox/table.rs:92`, `:118`, `:200-205`; `src/repository/validation.rs:70`; `src/repository/sql/outbox.rs:27-88` +- What: Every commit builds a `TableWritePlan` per outbox message (cloning the payload and serializing metadata to JSON) only to validate it, then discards it. The real insert is a hand-written 19-column statement that serializes metadata again. The two encodings differ: the table version truncates timestamps to whole seconds and always writes `published_at` as Null. +- Why it matters: A per-message payload clone on the command hot path, and two schemas to keep in sync. +- Change: Validate fields directly (lengths, ids), keep only the schema constant, and delete the plan/row helpers along with `outbox_insert_plan_uses_table_row_mutation`. Size S. + +### 13. `lock/` and `lease/` are two TTL-lease implementations +- Category: C Severity: medium Confidence: CONFIRMED +- Where: `src/lock/sqlx_common.rs:330-550` (`LockDialect`, `LeaseQueries`, `aggregate_locks`); `src/lease/sqlx_store.rs:1-200` (`LeaseDialect`, `coordination_leases`); `src/lease/mod.rs:27-35` +- What: Both are database-clock TTL rows with an owner token and parallel dialect traits. `lease` adds fencing and renewal; `lock` adds an in-process gate and deletes its row on release. +- Change: Falls out of finding 3 — delete `lock/` and keep `lease/` as the only coordination primitive. Size S after finding 3. + +### 14. Two durable timer mechanisms +- Category: C/F Severity: medium Confidence: CONFIRMED +- Where: `src/outbox/message.rs:396-416`; `src/saga/state.rs:709`; `src/schedule.rs`; `README.md:1377-1383` +- What: `OutboxMessage::deliver_at/deliver_after` (only production user is the saga) and `Schedule` + `aggregate_schedules` + `ScheduleWorker`. The README documents only the first. +- Change: Choose `Schedule` (it has generations and idempotent command ids), port the saga timeouts to it, and drop `deliver_at`. Size M. + +### 15. `Aggregate::aggregate_type` defaults to `type_name::()` +- Category: E/F Severity: medium Confidence: CONFIRMED +- Where: `src/aggregate/aggregate.rs:12-17` +- What: The default is the Rust type path, kept "so existing examples keep working". +- Why it matters: Renaming or moving a struct silently changes its stream identity and orphans its history. It is also a compat fallback. +- Change (breaking): Make it a required associated const and have the macros always emit it. Size S. + +### 16. Vestigial items on `Entity`, and the replay loop written twice +- Category: F/C Severity: low-medium Confidence: CONFIRMED +- Where: `src/entity/entity.rs:76`, `:102-135`, `:438-478`, `:496`, `:531-542`; `src/aggregate/aggregate.rs:125-138`; `src/snapshot/repository.rs:162-175` +- What: + - `Entity.timestamp` is written but read only by Debug/Clone and a serde test. + - `Entity::rehydrate` and `ReplayGuard` are used only by their own unit test; real replay uses `set_replaying` in two duplicated loops. + - `digest` and `digest_v` have duplicate bodies. + - The manual `Clone` impl equals the derive. + - `InMemoryRepository` reimplements `SnapshotStore` (`src/in_memory_repo/repository.rs:930-992`) identically to `InMemorySnapshotStore` (`src/snapshot/in_memory.rs:38-95`) instead of delegating to its own `snapshot_store` field. +- Change: Delete the dead items, keep one `replay_into` with one guard, and delegate. Size S. + +### 17. Dead or near-dead public API +- Category: F Severity: low-medium Confidence: CONFIRMED (rg over the whole repo excluding `target`) +- Where and what: + - `InboxOutcome` — no user outside `src/repository/{inbox,mod}.rs` and `src/lib.rs`. + - `InboxReceipt.processed_at` — no reader; documented as "forward compatibility" (`src/repository/inbox.rs:36-39`). + - `AggregateRepository::commit_entities` (`src/aggregate/repository.rs:357`) and `repo_mut()` — no callers. + - `impl_aggregate!` — no invocations outside its own recursion; `README.md:1295` only mentions it. + - `PayloadCodec` trait — one implementation, and `EventRecord::decode` hard-codes bitcode (`src/entity/event_record.rs:207-225`). + - `EventRecord::new`, `new_versioned` and `with_metadata` are three copies of one constructor (`:151-203`). + - `emitter/` (`EntityEmitter`, `event-emitter-rs`) — used only by the enqueue macros and their tests (`tests/enqueue`, `tests/sourced_enqueue`, `tests/sourced_snapshot`). It is an in-process string callback bus beside the outbox. +- Change: Delete them. For `emitter`, either delete the feature or justify it against principle 1. Size S each. + +### 18. Legacy "sourced" names and stale comments +- Category: F Severity: low Confidence: CONFIRMED +- Where: `src/outbox_worker/outbox_dispatch.rs:43` (`x-sourced-` prefix vs `x-distributed-*` in `src/schedule.rs:63-72`); `src/lib.rs:342` (`SourcedResult`); `src/repository/identity.rs:7-9`; `src/queued_repo/repository.rs:148`, `:272-275`; `src/outbox_worker/drain.rs:5` +- What: Two metadata prefixes are on the wire; comments refer to a removed sync API and an "old in-memory OutboxWorker". State-transition errors on `OutboxMessage` are typed `EventRecordError`. +- Change: Use one prefix (a wire break, so do it now), rename `SourcedResult`, and give outbox its own error. Size S. + +### 19. `OutboxMessage` constructor and field sprawl; `Published` state is unreachable in stores +- Category: F Severity: low-medium Confidence: CONFIRMED for the constructor sprawl, PLAUSIBLE for `Published` +- Where: `src/outbox/message.rs:169-274`, `:373`, `:427`, `:559-569`; `src/outbox_worker/store/api.rs:159-164`; `src/repository/sql/outbox.rs:226` +- What: All fields are public, plus `#[non_exhaustive]`, plus getters. There are seven constructors plus public `new()`/`initialize`. Stores delete rows on complete, so `OutboxMessageStatus::Published`, `complete()`, `is_published()` and the `published_at` column look vestigial. They are still referenced at `src/microsvc/runtime.rs:179`, `src/microsvc/cell_host/wire.rs:272` and in several tests, which I did not trace. +- Change: Make fields private with two constructors (typed and raw) and builder setters. Confirm the two microsvc uses and then drop `Published`. Size M. + +### 20. Per-commit overhead on the hot path +- Category: D Severity: low-medium Confidence: CONFIRMED +- Where: `src/repository/sql.rs:168-179`; `src/outbox_worker/outbox_dispatch.rs:225`, `:238`, `:298-315`; `src/repository/sql/outbox.rs:176-205`; `src/outbox_worker/store/in_memory.rs:96-99` +- What: + - `SqlBind::Text(String)` allocates four strings per event row, although `PreparedEventAppend`'s doc claims nothing is cloned (only payloads are borrowed). + - `backlog_stats()` runs COUNT/MIN after every dispatch when metrics are on ("deliberately unthrottled"), so once per command commit. + - SQLite claim does one UPDATE plus one SELECT per id. + - In-memory claim sorts every outbox id on each call. +- Change: Make `SqlBind::Text` a `Cow`, throttle backlog gauges to the drain tick, and batch the SQLite claim with `RETURNING`. Size S-M. + +### 21. Domain-event validation re-serializes on every call +- Category: D Severity: low Confidence: CONFIRMED +- Where: `src/domain_event/occurrence.rs:165`, `:382-389`, `:417-421`, `:425-482`; `src/domain_event/canonical.rs:21-28` +- What: `capture` builds the occurrence, then calls `canonical_bytes()`, which calls `validate()`. That re-parses the body to a `serde_json::Value`, re-canonicalizes it, and recomputes the SHA-256 id; the whole envelope is then serialized via `to_value` and the bytes are discarded. `from_canonical_bytes` validates twice (`:417` and again inside `:418`). +- Why it matters: Roughly three body encodings and two hashes per captured event, on bodies up to 1 MiB. Correct, but wasteful on the command path. +- Change: Check only the size at capture (the body was just produced canonically) and keep full validation for the parse path, once. Size S. + +### 22. `eprintln!` logging and silent no-ops in library code +- Category: E Severity: low Confidence: CONFIRMED +- Where: `src/schedule/worker.rs:262`; `src/outbox_worker/drain.rs:177`, `:197`; `src/in_memory_repo/repository.rs:270-275`, `:880-887` +- What: Worker errors go to stderr although `tracing` is an optional dependency used elsewhere. In-memory `purge_inbox_older_than` is a no-op and `inbox_contains` maps lock poison to `false` (principle 7). +- Change: Route through one error hook or `tracing`. Give in-memory receipts a timestamp so purge works, and return the poison error. Size S. + +### 23. Publish order is not preserved across failures +- Category: E Severity: low Confidence: PLAUSIBLE +- Where: `src/outbox_worker/outbox_dispatch.rs:184-191`, `:371-398` +- What: With concurrency 1 a failed row is released while later rows of the same aggregate in the same batch still publish. The doc promises "strictly in claim order". +- To check: Whether consumers rely on per-aggregate order or only on the sequence in the occurrence. If order matters, stop the batch at the first failure per aggregate. Size S. + +### 24. In-module tests: mostly behavioural, with a cluster that cannot fail or duplicates the conformance suite +- Category: B Severity: medium Confidence: CONFIRMED for bodies read, PLAUSIBLE where judged from names +- Where and what: + - **Good, keep:** `src/domain_event/mod.rs` and `derived_tests.rs` (for example `replay_suppresses_outward_capture_without_poisoning_the_entity`, `canonical_fixture_round_trips_and_fingerprints_exact_wire_bytes`), `src/outbox/commit.rs` (`captured_occurrences_require_an_explicit_publication_leg`), and `src/outbox_worker/outbox_dispatch.rs` and `drain.rs`. + - **Cannot fail / restate derives (read):** `entity/entity.rs` `new`, `clone`, `debug`, `serialize_deserialize`; `entity/event_record.rs` `new`, `clone`, `debug`, `payload_bytes`, `with_metadata_constructor`; `in_memory_repo/repository.rs` `new` (asserts a private map is empty); `entity::rehydrate` tests a function nothing else calls. + - **Same category (names only):** the six `snapshot/in_memory.rs` tests. + - **Implementation detail (read):** `outbox/table.rs::outbox_insert_plan_uses_table_row_mutation`; `repository/sql.rs::event_plan_borrows_only_new_payloads_and_respects_bind_limit` (matches on `Cow::Borrowed` inside statement parts; acceptable as a performance guard, but it is the only test of the statement builder). `repository/sql/outbox.rs::insert_plans_bound_rows_and_borrow_payloads` looks similar by name. + - **Misleading name (read):** `outbox_worker/store/tests.rs::already_published_message_is_not_completed_again` actually asserts `NotFound` because the row was deleted. + - **Duplicated setup (names):** the 16 in-memory tests in `outbox_worker/store/tests.rs` (`claim_*`, `competing_workers_only_claim_message_once`, `stale_*`, `complete_many_*`) cover the contract that `tests/persistent_repository_conformance/outbox.rs` runs against SQL. This is one contract with two suites. The 15 `commit_builder/mod.rs` tests disappear with finding 4. + - **Missing behavioural tests:** queued+snapshots with a stale snapshot (finding 1); plain `repo.commit` with captured domain events (finding 4); outbox failure with a full backlog (finding 5); tail load of a missing stream with a lingering snapshot on SQL (finding 7); `get_all` under a snapshot policy (finding 8). +- Change: Delete the derive tests. Run the outbox store tests as a conformance suite generic over `OutboxStore`, including in-memory. Add the five missing cases. Size M. + +### 25. `lib.rs` is a pile of re-exports +- Category: F Severity: medium Confidence: CONFIRMED +- Where: `src/lib.rs:49`, `:111-141`, `:175-316`, `:352`, `:447-491`; `src/aggregate/repository.rs:24-30`; `src/commit_builder/mod.rs:257` +- What: + - About 35 `pub use` blocks re-export hundreds of names at the root, while the modules are also `pub mod`, so everything has two public paths. + - A 140-line `projection!` macro and `graphql_models!` live in the crate root. + - `pub use microsvc::cell_host` sits at the root. + - There are two unrelated `aggregate` methods: the blanket `AggregateBuilder::aggregate::()` on every `T`, and `ReadModelWritePlanCommitExt::aggregate(&mut A)`. +- Why it matters: The public surface cannot be held in one's head, and every internal rename is a breaking change twice. +- Change (breaking): Make modules private by default and export a curated root plus a `prelude`. Move the macros into their modules. Remove the blanket impls on `T`. Size M. + +## Answers to the slice questions +- **Repository contract:** The trait family in `src/repository/traits.rs` is coherent, and `AggregateRepository::with_snapshots` keeps one type. The overlap sits above it: `QueuedRepository`, `CommitBuilder`, `AggregateCommit`, and the crate-private `Causal*` parallels. +- **Core awareness of adapters, GraphQL or the game:** Yes; see finding 9. +- **Outbox atomicity:** Append, outbox rows, schedules, snapshots and inbox receipts commit in one transaction on every backend, so there is no dual-write window. Publish is after-commit and at-least-once. Polling and batching are bounded (drain 32 rows/1 s, hint mailbox 256, schedules 32/250 ms). The problem is retry policy (finding 5). +- **`lock/` vs `lease/`:** They overlap (finding 13). +- **`lib.rs`:** A pile (findings 10 and 25). +- **Tests:** Mostly behaviour, with the exceptions in finding 24. + +## Things that are good and should not be changed +- `CommitBatch` as the single atomic unit, with `validate_commit_batch` as the shared preamble for all backends (`src/repository/validation.rs`), and the structural `Statement`/`SqlExecutor` shared by SQLx and cell SQL (`src/repository/sql.rs`). +- Snapshot-as-cache semantics: the schema-version gate, cache miss falling back to full replay, and the policy living on the same `AggregateRepository` type (`src/snapshot/repository.rs:50-93`). +- The outbox claim lease with attempt-scoped `OutboxClaimRef`, one `publish_and_settle` path shared by drain and immediate dispatch, and delete-on-complete. +- Domain-event occurrences: canonical bytes, content-independent retry-stable ids, poison-on-capture-failure, and replay suppression (`src/domain_event/`). +- `lease/` fencing tokens (`Fence::admit`) on the database clock, and schedule generation / command-id idempotency. diff --git a/docs/reviews/v5-pre-release/02-sql-persistence.md b/docs/reviews/v5-pre-release/02-sql-persistence.md new file mode 100644 index 000000000..62db68e2a --- /dev/null +++ b/docs/reviews/v5-pre-release/02-sql-persistence.md @@ -0,0 +1,279 @@ +## Assessment: SQL persistence slice + +**Overall health.** The Postgres/SQLite split is clean: one generic implementation over `SqlxRepoBackend` and `SqlxReadModelBackend`, with only four `DB::BACKEND == "postgres"` string branches and no per-dialect copies of logic. I found no injection surface. The weight and the risk sit in the projection protocol (7.2k non-test lines): its rules are implemented a second time for in-memory, it costs about 28 statements per projected event, and its Postgres tests never run in CI. + +**Three things most worth changing:** +1. Move the protocol decisions into pure functions that both backends call, and make the tests one conformance suite that actually runs on Postgres. +2. Cut round trips and locks on the hot paths: per-event projection commit, the table ownership-fence `FOR UPDATE`, the per-row execution snapshot loop, and the unindexed causation lookup. +3. Squash the 13 migrations into one schema with a single timestamp representation; this removes about half of the dialect trait, several unused indexes and the compat wording. + +**How this was read.** +- **Read in full by me:** `sqlx_repo/mod.rs`, all of `sqlx_repo/repo/`, `postgres_repo`, `sqlite_repo`, `sqlx_repo/read_model/*`, `table/sql.rs` (non-test), `table/plan.rs`, `table/mod.rs`, `projection_protocol/{mod,types,helpers,locks,partitions}.rs`, `store_impl.rs:1-700`, Postgres migrations except 0003 body (0003 reviewed by index/constraint grep), and `repository/sql.rs` + `sql/outbox.rs` for comparison. +- **Read by two sub-reviewers, spot-checked by me:** `reads.rs`, `identity.rs`, `store_impl.rs:649-1521`, `rebuild.rs`, both test files, in-memory `projection_protocol/`. Findings from them are marked "sub-review". Within that, test bodies at `tests.rs:1168-1384`, `1525-1994` and `2780-3095` and most in-memory test bodies were not read by anyone. +- **Only outlined or grepped:** `writes.rs:300-1200`, `table/{metadata,registry,mutation,catalog,error}.rs`, `read_model/{plan,workspace,in_memory,load}.rs`, SQLite migrations (diffed against Postgres only). +- **Not done:** a third sub-review of `table/` and `read_model/` could not be launched, so that area is thinner. Nothing was executed; query-plan claims are from reading SQL against DDL. + +--- + +### 1. Postgres projection-protocol tests never run in CI +- Category: B/E Severity: high Confidence: CONFIRMED +- Where: `src/sqlx_repo/projection_protocol/postgres_tests.rs:32,56,645,756,1017`; `.github/workflows/integration-postgres.yaml:28,41-66` +- What: all five tests begin with `let Ok(url) = std::env::var("DISTRIBUTED_TEST_POSTGRES_URL") else { return; }`. That variable appears nowhere else in the repo. The workflow sets `DATABASE_URL` and runs named `--lib` filters that do not include these tests. They are not `#[ignore]`d, so they report green. +- Why it matters: the only Postgres coverage of commit, repair, retention, `pg_notify` and REPEATABLE READ snapshots is vacuous. That includes `postgres_cancelled_begin_does_not_poison_the_next_read_snapshot`, the regression test for the most recent fix (d9e9bd20). +- Change: use the env var CI sets, fail when it is absent in CI, and use unique per-run topology ids (sub-review: `postgres_projection_protocol_runtime_conforms` uses fixed ids and is probably not re-runnable). S. + +### 2. Projection-protocol rules are implemented twice and already differ +- Category: C/A (principle 7) Severity: high Confidence: CONFIRMED +- Where (SQL vs in-memory): + - `writes.rs:298-383` vs `state_impl.rs:558-644` (`next_record`; I diffed them, identical apart from indentation). + - `identity.rs:845-1061` vs `state_impl.rs:124-362` (input classification). + - `reads.rs:271-438` vs `direct_projection.rs:7-131`. + - `store_impl.rs:1159-1252` vs in-memory `store_impl.rs:1124-1199` (repair). + - Also graph budgeting, change-read window, compaction bounds and the failure preamble. `PartitionState` and `InputDisposition` are each defined twice (`sqlx types.rs:4,65`). +- What: about 750 lines of semantic decisions are interleaved with fetches in each backend. A shared home already exists (`src/projection_protocol/store/backend_helpers.rs`, `validate_ownership_batch`, `validate_snapshot_write`). +- Divergences today (sub-review): + - Causation evidence is ordered by hashes in SQL (`reads.rs:1664-1666`) and by canonical bytes in memory (`store_impl.rs:852-867`). + - A live record owned by another partition returns `InvalidBatch` in memory (`state_impl.rs:4-33`); SQL has no pre-check and surfaces a unique-index storage error. + - `projection_changes` on SQL returns a corruption error for an empty or non-contiguous page (`reads.rs:2297-2315`); in-memory returns whatever is there. +- Change: pure functions over already-loaded facts (`next_record`, `classify_input(receipt_by_cursor, receipt_by_message, current_cursor, …)`, `plan_repair`, `change_read_start`, one ordering function). Backends only fetch and persist. L; start with `next_record`, which is S. + +### 3. Conformance suite covers six scenarios and has no Postgres implementation +- Category: B/C Severity: high Confidence: CONFIRMED (sub-review; I confirmed the suite file exists) +- Where: `src/projection_protocol/store/scenario_tests.rs` (trait `ProjectionProtocolScenario`, six scenarios); impls at sqlite `tests.rs:375` and in-memory `tests.rs:544`. +- What: everything else is written per backend (17 SQLite, 28 in-memory, 5 Postgres tests). + - Near-verbatim twins include `…coherent_execution_and_graph_snapshots…` (sqlite 2067 / pg 643 / mem 3398) and the `four_position_…_commit_failure_matrix` (2161 / 753 / 3601). + - Fixtures such as `graph_parent_schema`, `graph_codec`, `graph_mutation`, `input`, `batch` and `matrix_*` are copy-pasted three times (sqlite 148-302, pg 198-373, mem 102-259). + - Estimated removable: about 750 helper lines plus 600-700 twin-test lines. + - One Postgres test is 862 lines and replays about eight SQLite scenarios serially. +- Change: move fixtures and scenarios into the suite, add hooks `fail_nth_physical_write` and `corrupt_physical_row`, and add a Postgres impl. Keep backend-specific only what is: cancelled-BEGIN, `pg_notify` on commit/rollback, REPEATABLE READ, WAL restart. L. + +### 4. About 28 SQL statements per projected event +- Category: D Severity: high Confidence: CONFIRMED (counted from code) +- Where: `store_impl.rs:333-647` and its helpers. +- What, for one new input with one mutation and one owned model: + - BEGIN; `verify_registered_topology_in_tx` (1). + - `lock_partition_in_tx` (3: upsert, generation insert, generation verify; `partitions.rs:95-143`). + - `validate_input_identity_in_tx` (3); `classify_validated_input_in_tx` (3; `identity.rs:948,981,1006`). + - Inbox check (1); `ensure_partition_ownership_in_tx` (2 per declared model, every commit; `writes.rs:31-96`). + - Per mutation: `record_in_tx` + `physical_row_exists_in_tx` + row write + change insert + record upsert (5). + - Cursor (1), identity (2), receipt (1), inbox (1), head update (1), retention delete + second partition update (2; `writes.rs:1233-1270`), notify, COMMIT. + - The same `projection_partitions` row is written three times per event. +- Why it matters: every statement is a network round trip on Postgres with the partition row lock held, which caps a partition at roughly tens of events per second. Mutations are applied one statement per row (`store_impl.rs:588-596`). +- Change: + - Fold the partition lock, head and compacted-through into one final UPDATE. + - Load receipts, cursor and identity in one statement. + - Verify topology and model ownership once per process (it is immutable after registration), not per event. + - Multi-row insert for changes and observations. + - M-L; the pure-function refactor in #2 makes the fetch plan explicit. + +### 5. Ownership-fence `FOR UPDATE` serialises every same-transaction read-model commit per table +- Category: D Severity: high Confidence: CONFIRMED +- Where: `projection_protocol/locks.rs:60-99`; called from `repo/commit.rs:83` and `repo/read_models.rs:28`. +- What: for each table an ordinary write plan touches, the code runs `INSERT … ON CONFLICT DO NOTHING`, then `SELECT … FOR UPDATE` on `projection_table_ownership_fences` (Postgres), then a `SELECT` on `projection_causal_tables`. That is three statements per table, and an exclusive row lock held until COMMIT. +- Why it matters: two commands on different aggregates that stage a read-model row in the same table cannot commit concurrently on Postgres. The lock is taken before the stream-version check and event insert, so the whole commit is serialised. +- Change: writers take `FOR SHARE`; only `register_projection_models` (`store_impl.rs:52`) takes `FOR UPDATE`. Batch the tables into one statement with `= ANY($1)`. S. + +### 6. Causation-evidence query has no usable index and its table only grows +- Category: D Severity: high Confidence: CONFIRMED (query and DDL re-opened) +- Where: `reads.rs:1646-1668`; `migrations/postgres/0003_projection_protocol.sql:444-462,655-660`; caller `microsvc/dependencies.rs:131` (sub-review). +- What: the predicate is `causation_id = ? AND topology_hash IN (…)` with no `partition_hash`. The primary key and `projection_observations_causation_idx` both lead with `(topology_hash, partition_hash, causation_id)`. Observations are never deleted. The failures query at `reads.rs:1778` has the same shape. +- Change: index `(topology_hash, causation_id)` on observations and failures in both dialects; drop the current causation index, which is a strict prefix of the primary key. S. + +### 7. Execution snapshot batch issues one multi-join statement per row on the projector path +- Category: D Severity: high Confidence: CONFIRMED +- Where: `reads.rs:1086-1097` loops `read_projection_query_snapshot_in_executor` per request; bound `MAX_PROJECTION_QUERY_BATCH_ROWS` = 4096; caller `microsvc/projector/context.rs:109` (sub-review). +- What: the same pattern is at `store_impl.rs:985`, `reads.rs:1128,1152` (graph snapshot) and `rebuild.rs:42,118` (four statements per row, up to 10,000 rows, inventory run twice). +- Change: one keyed set query per model, as `read_projection_live_record_batch_in_executor` already does. M. + +### 8. Keyset scan forces `COLLATE "C"` on a key column created with the default collation +- Category: D Severity: medium Confidence: CONFIRMED for the mismatch, PLAUSIBLE for the plan +- Where: `sqlx_repo/read_model/scan.rs:26-61`; DDL at `table/sql.rs:140-144,251`. +- What: scans emit `WHERE "pk" COLLATE "C" > $1 ORDER BY "pk" COLLATE "C" LIMIT n`, but generated tables declare the key as plain `text`. On a database whose default collation is not C, the primary-key index cannot serve that predicate or ordering, so each page is a full scan plus sort. Equality filters get the same `COLLATE` (line 36-38), defeating declared indexes on text columns. +- Change: generate `text COLLATE "C"` for text columns on Postgres (this also makes ordering identical to SQLite and in-memory everywhere) and drop the per-query `COLLATE`. Breaking for existing table DDL. S. + +### 9. Timestamps are stored three or four ways per dialect, and that is half the dialect seam +- Category: F/C Severity: medium Confidence: CONFIRMED +- Where: `migrations/sqlite/0001` (TEXT `secs.nanos`, with `DEFAULT CURRENT_TIMESTAMP` in a different format the codec cannot parse; `repository/sqlite_codec.rs:23-35`), `sqlite/0004` (REAL epoch for the ledger), 0010 (REAL), 0012 (ms integers). Postgres mixes `timestamptz`, `double precision` and `BIGINT` ms. +- What this forces: + - `sqlite_repo/mod.rs:144-177` decodes "text, else real". + - `CAST(created_at AS REAL)` in ORDER BY and WHERE (`sqlite_repo/mod.rs:67`, `repository/sql/outbox.rs:134-167`), so `outbox_messages_claimable_idx` cannot serve range or order. + - About 13 of the roughly 27 items in `SqlxRepoBackend` exist only for timestamps (`repo/backend.rs:262-369`), plus four hand-written `EXTRACT(EPOCH …)` select lists in `postgres_repo/mod.rs:59-109`. +- Change: one representation for all framework tables in both dialects, BIGINT epoch micros (schedules already use ms). The select lists become dialect-identical and the timestamp hooks, `TimestampValue`, `ORDER_BY_CREATED_AT` and `SqlPart::TimestampCompare` go away. Breaking schema change; do it with #11. M. + +### 10. Two parallel dialect abstractions +- Category: C/F Severity: medium Confidence: CONFIRMED +- Where: `repository/sql.rs` (`Statement`/`SqlPart`/`SqlExecutor`, used by event store, ledger, outbox and schedules; runs on SQLx and cell SQL) vs `SqlxRepoBackend` + `SqlxReadModelBackend` + `QueryBuilder` (projection protocol and read models). +- What: + - `repo/executor.rs:119-127` mirrors eight consts from one trait to the other. + - `stream_version` exists in both (`repo/commit.rs:520` and `repository/sql.rs` `stream_version`). + - The Postgres claim's `RETURNING` list (`postgres_repo/mod.rs:300-318`) repeats `OUTBOX_SELECT` by hand. + - The `QueryBuilder` style costs 587 higher-ranked `where` lines in non-test `sqlx_repo` (419 of 7,204 lines in the five big protocol files), repeated on every function. + - The four string branches (`scan.rs:26`, `store_impl.rs:874`, `reads.rs:2169`, `locks.rs:78`) should be trait items. +- Change: pick one seam. Extending `Statement`/`SqlExecutor` to the protocol and read-model path removes the generic bounds entirely and is the only route to running the protocol on a cell executor; otherwise delete the mirrored consts and add `READ_SNAPSHOT_BEGIN`, `ROW_LOCK` and `TEXT_COLLATION` to the backend trait. L (or S for the minimal version). + +### 11. Thirteen migrations for an unreleased schema, hand-mirrored per dialect +- Category: F Severity: medium Confidence: CONFIRMED +- Where: `migrations/{postgres,sqlite}/0001-0013` (2,237 lines). +- What: + - 0004 rewrites `projected` to `atomic` (a PL/pgSQL constraint-drop loop on Postgres, a full table rebuild on SQLite). + - 0005, 0007, 0008 and 0013 are `ALTER … ADD COLUMN`. + - Comments describe data that cannot exist ("history written before program identities existed", "old cell-only rows"). + - `cell_alarms` (0011) is created in Postgres "so the inventory stays identical across dialects" although only cells use it. + - Real divergence: the outbox status-shape `CHECK` exists only in Postgres (`postgres/0001:76-100`; SQLite stops at `CHECK (attempts >= 0)`). Sub-review found 0003 otherwise equivalent apart from type and CHECK spelling. + - The outbox `published` status and `published_at` column are never written by SQL: completion deletes the row (`repository/sql/outbox.rs:228`). +- Change: squash to one initial migration per dialect, drop `published`, `published_at` and Postgres `cell_alarms`, and add a schema-parity test that introspects both. M. + +### 12. Indexes no query uses, including two on the append path +- Category: D Severity: medium Confidence: CONFIRMED by rg of every `FROM`/`JOIN` on these tables in `src/` +- Where and what: + - `aggregate_events_event_version_idx` and `aggregate_events_recorded_at_idx` (`postgres/0001:21-25`): every `aggregate_events` query filters on the primary key only (`repo/streams.rs:50`, `repo/commit.rs:533,577`, `repository/sql.rs:269,290`). + - `outbox_messages_source_idx`: no predicate on source columns anywhere. + - `projection_records_change_idx`, `projection_input_receipts_causation_idx`, `projection_changes_causation_idx`, `projection_changes_record_idx` (`0003:647-691`): changes are only read and deleted by primary key. +- Why it matters: two extra index writes per event appended, three per change row. +- Change: drop them in the squash. S. + +### 13. Tests coupled to internals, one compat test, some weak assertions +- Category: B Severity: medium Confidence: CONFIRMED (sub-review; I re-opened `tests.rs:1120-1135`) +- Where: + - `sqlite_rejects_tampered_failure_digest_before_any_protocol_write` (1490-1521): `COUNT(*)` on six internal tables plus an exact error string. + - `four_position_sqlite_…matrix…` (2227-2342) and `sqlite_retention_prunes_exact_prefix…` (2639, 2702): physical row counts where the trait read already proves the behaviour. + - `sqlite_modeled_projection_identity…null_history_stays_readable` (1125-1162): NULLs `program_id` to simulate pre-identity rows, which is pre-release compat. + - `sqlite_projection_change_executor_read_uses_existing_snapshot` (2720): no concurrent writer, so it would pass with no snapshot. + - About 32 assertions match `message.contains(…)` on `InvalidBatch`. + - 9 of 23 SQLite tests issue raw SQL. +- No test asserts exact generated SQL for the protocol. The `table/sql.rs` DDL tests use `contains` on rendered DDL, which is reasonable for a generator. +- Gaps: no SQL twin for `concurrent_same_input_applies_once` (in-memory 2889); `projection_failure_location` (`store_impl.rs:1461`) has no direct test in any of the three files. +- Change: keep trigger and corruption setup, replace count assertions with trait reads, delete the compat test, add typed error variants. M. + +### 14. Row decoding is written out by hand, column by column +- Category: C Severity: medium Confidence: CONFIRMED +- Where: `.try_get(` occurs 89 times in `reads.rs`, 44 in `identity.rs`, 37 in `writes.rs`, 20 in `partitions.rs`, each with its own `protocol_storage_error::("decode …")` closure (292 such calls across the five files). +- What repeats (sub-review): + - The source-scope block is decoded five times (`identity.rs:66-119,194-257,553-631,794-838`, `reads.rs:875-975`). + - Record metadata three times (`writes.rs:188-296`, `reads.rs:722-830,2063-2126`). + - The `0/1` boolean match eight times. + - `partitions.rs:374-492` is 120 lines decoding one optional joined failure. +- Change: `col::(row, name)` that derives the error context, `bool01`, `decode_source_scope`, `decode_record_metadata`. Roughly 600 lines removed. M. + +### 15. Oversized files doing several jobs +- Category: F Severity: medium Confidence: CONFIRMED +- Where and proposed split: + - `reads.rs` (2394): tests at 3-121 belong in tests; `apply_same_transaction_projection_in_tx` (271-438) is a write and belongs in `direct_projection.rs` (as in-memory has it); the 620-line `read_projection_query_snapshot_in_executor` (448-1069) splits into build/decode pieces; then `evidence.rs` (1306-1851), `live_records.rs` (1855-2135), `changes.rs` (2198-2394). + - `store_impl.rs` (1521): keep the trait impl as thin delegation; move `register_projection_models` (32-331, eight sequential lookups per declaration), failure recording (649-798), repair (1147-1333) and compaction (1335-1433) into their own modules. + - `identity.rs`: row lookups vs classification (the latter mostly disappears with #2). + - `tests.rs` and `postgres_tests.rs` are `include!`d (`mod.rs:84,87`) rather than declared as modules. +- Size: M, mostly mechanical after #2 and #14. + +### 16. Single-row protocol reads use two snapshots and can report corruption that is not there +- Category: E Severity: medium Confidence: CONFIRMED for the code, race by reasoning +- Where: `store_impl.rs:807-830` (`projection_checkpoint`), also 851-859, 1111-1119, 1443-1457. +- What: `load_partition(self.pool())` reads the partition on one connection, then a new `begin()` reads the cursor. A commit between the two makes `verify_stored_change` (`identity.rs:21-31`) see a change position above the head and return "corrupt projection protocol storage". The transaction is never committed. +- Change: one joined statement or `with_projection_read_snapshot`. The sub-review found no non-test caller for `projection_checkpoint`, `projection_observation`, `projection_graph_snapshot`, `projection_query_snapshot_batch`, `compact_projection_changes` and `projection_live_record_batch` on the trait (PLAUSIBLE; macro callers not ruled out), so deleting them may be the better fix. S. + +### 17. Corruption and caller errors share one variant +- Category: E Severity: low Confidence: CONFIRMED +- Where: `projection_protocol/helpers.rs:10-15` (`corrupt_storage` returns `ProjectionProtocolError::InvalidBatch`). +- Why it matters: callers cannot tell "stored data is damaged" from "your batch is wrong", and tests match on message text. +- Change: a `StorageCorruption` variant. S. + +### 18. Read-snapshot helper costs three extra round trips and is duplicated +- Category: D/E Severity: low Confidence: CONFIRMED +- Where: `reads.rs:2151-2196`; copy at `store_impl.rs:874-962`. +- What: `begin()`, then a separate `SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY`, then COMMIT, around reads of one or two statements. If rollback fails, the original error is discarded (`reads.rs:2187-2193`). `read_projection_changes_in_snapshot` carries a test-only `after_state` future in its production signature (`reads.rs:2360`; production passes `ready(())`). +- Change: one `BEGIN ISOLATION LEVEL …` via a backend hook, reuse the helper, return the original error, remove the seam. S. + +### 19. Outbox claim: Postgres index does not match the predicate; SQLite claims row by row +- Category: D Severity: medium Confidence: PLAUSIBLE (plan not run) +- Where: `postgres_repo/mod.rs:279-291`; `postgres/0001:103-109`; `repository/sql/outbox.rs:164-209`. +- What: + - Postgres: the candidate query is an `OR` across `pending`/`in_flight` filtered on `next_available_at` and ordered by `created_at`. `outbox_messages_pending_idx` is on `(created_at)` only, so scheduled-but-not-due rows are walked on every claim, and the `OR` blocks a single ordered index scan. Since the outbox doubles as the durable timer (comment at `outbox.rs:56`), cost grows with the number of future timers and with backlog. + - SQLite: one candidate SELECT, then an UPDATE and a SELECT per message (1 + 2N statements). +- Change: order and index pending rows by `next_available_at`; reclaim expired leases as a separate arm (`UNION ALL` with per-arm LIMIT); use `UPDATE … RETURNING` on SQLite. S-M. + +### 20. `table` vs `read_model`: the "neutral table" generalisation has no production user +- Category: F Severity: medium Confidence: CONFIRMED by rg across repo +- Where and what: + - `TableModel` (`table/mod.rs:45`) has one implementor, `OutboxMessage` (`outbox/table.rs:141`). `outbox_message_schema()` is referenced only from tests (`table/sql.rs:388,417,564`, `tests/sqlite_repository/main.rs:239`). The real outbox uses migrations and `repository/sql/outbox.rs`. + - `TableSchemaRegistryExt::register_table` has no caller. + - `TableKind::Operational` exists for that one schema. + - `table/` is not neutral: `table/registry.rs:21` and `table/catalog.rs` depend on `read_model::RelationalReadModel`, the catalog is named `ReadModelCatalog`, and its error text says "read model". + - Five alias imports rename table types back (`sqlx_repo/repo/mod.rs:62-64`, `postgres_repo/mod.rs:32`, `sqlite_repo/mod.rs:35`). +- Change: keep `table::` as the schema/mutation vocabulary; delete `TableModel`, `TableSchemaRegistryExt`, `outbox/table.rs` and `TableKind::Operational` (or make the outbox genuinely use it and delete the hand DDL); move `ReadModelCatalog` and `register` to `read_model`; remove the aliases. M, breaking public re-exports. + +### 21. Capability and outcome types that never vary +- Category: F Severity: medium Confidence: CONFIRMED +- Where and what: + - `TableAdapterCapabilities` (`table/plan.rs:6-20`) is all-true in every backend (`sqlx_repo/read_model/validation.rs:6-12`, `read_model/in_memory.rs:47`). + - `ReadModelQueryCapabilities.relationship_includes` is true in both (`repo/read_models.rs:64`, `in_memory.rs:355`). + - `TableCommitOutcome` is a unit struct whose `was_applied()` always returns true (`plan.rs:35-47`), yet it is branched on at `repo/read_models.rs:34`. + - `TableSchemaAdapter` (`table/registry.rs:701-729`) has one non-test implementor, which sets `schema_verification: false, dev_bootstrap: false` (`table/sql.rs:40-46`). `verify_schema` is implemented and called only in `tests/read_model_schema_bootstrap`. `SqlxRepository::bootstrap_table_schema_for_dev` bypasses the trait. + - `SqlxRepository` and `SqlxOutboxStore` duplicate three schema methods (`repo/types.rs:178-198` vs `223-242`). +- Change: delete both capability structs, both `*_capabilities()` trait methods and `validate_for`; make `commit_write_plan` return `()`; delete `TableSchemaAdapter`, its capabilities, verification and issue types; drop the schema methods from the outbox store. M, breaking. + +### 22. Read-model helpers duplicated between in-memory and SQL +- Category: C Severity: medium Confidence: CONFIRMED (`validate_row_expected_version` compared line by line) +- Where: `read_model/in_memory.rs:149,163,194,217,408,472-535` vs `sqlx_repo/read_model/validation.rs:22,45,59,95`, `schema_registry.rs:41` and `load.rs`. +- What: expected-version rules, patch/key reconciliation, include resolution and relationship row selection each exist twice. The SQL module documents them as "pure helpers (no sqlx types)". +- Change: move them next to `table::mutation` and call from both. S-M. + +### 23. Vestigial schema fields, one with a latent bug +- Category: F/E Severity: low Confidence: CONFIRMED +- Where and what: + - `TableColumn.jsonb` (`table/metadata.rs:100`): the macro already maps it to `ColumnType::Json` (`distributed_macros/src/read_model/types.rs:12`), and `table/sql.rs:256-257` has two identical arms that both return `"jsonb"`. + - `TableSchema.foreign_keys` (`metadata.rs:197`): the macro fills it with clones of the column-level `foreign_key` (`relational.rs:176-178`) and every other construction site passes an empty vec. For an entry not declared on a column, `table/sql.rs:202-207` emits `FOREIGN KEY (fk.column) REFERENCES table (fk.column)`, using the referenced column name as the local column. +- Change: delete both fields. S, breaking for hand-built `TableSchema` literals. + +### 24. Postgres conflict recovery takes a second pool connection while holding the first +- Category: E Severity: low Confidence: CONFIRMED for the mechanism, PLAUSIBLE for the stall +- Where: `repo/commit.rs:452-470`. +- What: after an event-insert unique violation the transaction is aborted but still open, and the code calls `pool.acquire()` to re-read stream versions. With the default pool of five (`repo/backend.rs:295-298`) and five simultaneous losers whose winner is another process, all connections are held while each waits for one more, until the acquire timeout. +- Change: roll the transaction back before the re-read, or report `ConcurrentWrite` from the versions already read at `commit.rs:87`. S. + +### 25. Dropped-BEGIN guard only applies to pools the repository opens, and costs a query per release +- Category: E/D Severity: low Confidence: CONFIRMED +- Where: `postgres_repo/mod.rs:122-138`; `repo/types.rs:61,126-134`. +- What: `after_release` runs `SELECT now() <> statement_timestamp()` on every connection release. It is installed in `connect()`, so `SqlxRepository::new(pool)` with a caller-built pool lacks the protection. +- Change: document or enforce that pools come from `pool_options`, for example a constructor that takes `PgPoolOptions`. S. + +### 26. Dead or misleading items +- Category: F Severity: low Confidence: CONFIRMED by rg +- Where: + - `commit_read_model_write_plan` (`sqlx_repo/read_model/write_plan.rs:37-63`): `#[allow(dead_code)]`, `pub(crate)`, "kept for adapter authors". + - Stale `#[allow(dead_code)]` on used items: `partitions.rs:183` (`load_partition`), `reads.rs:2359`. + - Single-field wrappers `StoredRecord{metadata}` and `StoredFailure{failure}` (`types.rs:55-63`). + - `load_partition` / `_in_tx` / `_in_connection` repeat the same SQL three times (`partitions.rs:184-268`). + - u64/i64 conversion exists four times (`sqlx_repo/mod.rs:13-54`, `projection_protocol/helpers.rs:17-35`, `repository/sql.rs` `signed`/`unsigned`). + - `validate_sql_write_plan` runs twice per commit (`repo/commit.rs:50` and `write_plan.rs:76`). +- Change: delete or collapse. S. + +### 27. Two ways to write read models in the command transaction +- Category: A (principles 1 and 5) Severity: medium Confidence: PLAUSIBLE (design intent is outside this slice) +- Where: `repo/commit.rs:128-135` applies handler-authored `batch.read_model_plans`; `commit.rs:137-153` applies `direct_projection` (the projection program in the same transaction); `locks.rs:11` exists to keep the first away from tables owned by the second. +- What: raw plans are used by real handlers (`tests/bomberman/handlers/*`, `tests/e2e-celld/…/project_auth_user.rs`, `microsvc/service/handlers.rs:228`). They are read-model writes not derived from events by a projection program. +- Change: decide whether raw plans survive v5. Removing them deletes the ownership fences (#5), `reject_causal_table_writes_in_tx`, `projection_table_ownership_fences` and the "legacy rows" registration check (`store_impl.rs:84-103`). L, breaking. + +### 28. `with_schedule_worker` returns a tuple; schedule and rebuild SQL are gated on `graphql` +- Category: F Severity: low Confidence: CONFIRMED +- Where: `repo/commit.rs:765-772` returns `(Self, ScheduleWorker)`; `commit.rs:687,746`, `projection_protocol/mod.rs:61`, `store_impl.rs:16,24` use `#[cfg(feature = "graphql")]`. +- Change: split into a builder flag that returns `Self` plus `ScheduleWorker::new(&repo, config)`; gate on a feature that names the capability. S. + +### 29. Migration inventory test restates the inventory +- Category: B Severity: low Confidence: CONFIRMED +- Where: `repo/backend.rs:37-126,130-219` (`generated_sqlite_inventory_preserves_order_descriptions_and_bytes` and the Postgres twin). +- What: 190 lines listing versions, descriptions and `include_str!` for each of 13 files, to be edited on every migration; `migrations/inventory.json` already carries sha256 per file. +- Change: delete after the squash, or replace with the parity test from #11. S. + +### 30. Relationship includes are unbounded and not one snapshot +- Category: D/E Severity: low Confidence: CONFIRMED +- Where: `sqlx_repo/read_model/load.rs:85-93,173-190`. +- What: the root and each include are separate statements on the pool with no transaction, and a has-many include has no LIMIT. +- Change: read in one snapshot and cap or page the children. S. + +--- + +### Things that are good and should not be changed +- One generic repository over a small backend trait, with type aliases `PostgresRepository` and `SqliteRepository`; no per-dialect copies of logic. +- No value is ever interpolated: `Statement`/`SqlPart` are structural, every identifier goes through `quote_identifier` (doubles embedded quotes; `validation.rs:186`, `table/sql.rs:268`), and DDL defaults pass an allowlist (`table/sql.rs:289-365`). +- `commit_sqlx_batch` is one transaction with the fenced ledger completion as the last statement before COMMIT (`repo/commit.rs:172-181`); event and outbox inserts are multi-row and chunked to the bind limit. +- Read-model upsert is a single `INSERT … ON CONFLICT DO UPDATE`, with re-reads only on the miss path (`write_plan.rs:110-118,405-478`). +- The generic test fixture pattern in `reads.rs:36-121` (one body, run for SQLite and Postgres) and the `ProjectionProtocolScenario` trait are the right model; extend them rather than replace. diff --git a/docs/reviews/v5-pre-release/03-projection-engine.md b/docs/reviews/v5-pre-release/03-projection-engine.md new file mode 100644 index 000000000..e13ad4975 --- /dev/null +++ b/docs/reviews/v5-pre-release/03-projection-engine.md @@ -0,0 +1,217 @@ +## Assessment + +The slice works and is carefully fail-closed, but it does not have one canonical IR. `MutationProgram` (authoring) is rewritten into `ProjectionProgram` (execution), which is resolved, lowered to `TableWritePlan`, then re-associated and re-normalised in the executor. The browser consumes yet another artifact (`ProjectionDelta` / command-projection metadata, owned by `src/graphql/projection_delta`). The protocol store is one trait, but the commit algorithm is implemented twice (memory, sqlx) with copy-pasted pure logic and at least one behavioural divergence. + +The three things most worth changing: +1. **Build the program once.** The `projection!` descriptor recompiles the whole program on every event and leaks memory each time. +2. **Collapse `mutation/` and `projection/` program types into one IR.** About a third of `mutation/` is test-only scaffolding. +3. **Lift the commit state machine above the store trait.** Then replace the two 3k-line store test files with one conformance suite, following the pattern `projection/source_snapshot_tests.rs` already uses. + +Not read, or only outlined: +- **Outline only:** `projection_protocol/codec/*`, `store/query.rs`, `store/identity.rs`, `store/replay.rs`, `store/commit.rs`, `projection_protocol.rs` (lines 1–110 read), `projection_protocol/workspace.rs` (struct only), `projection/provenance.rs`, `projection/error.rs`, `mutation/error.rs`. +- **Partly read:** `projection/placement.rs` (outline only), `projection/catalog.rs` (589–735 only), `projection/expression.rs` (outline only), `projection/executor.rs` tests, `projection/rebuild.rs` 1–195. +- **In-memory store:** `state.rs`, `read_helpers.rs`, `direct_projection.rs`, `util.rs` outline only; `store_impl.rs` only `commit_projection`; `state_impl.rs` only `next_record` / `validate_physical_record`. +- **Tests:** in-memory `tests.rs` and sqlx `tests.rs` by test names plus one paired body; `projection/tests.rs`, `mutation/tests.rs`, `relationship_fixture.rs`, `store/tests.rs`, `codec/tests.rs` by names only (except the mutation golden test). +- **sqlx (comparison only):** `commit_projection`, `next_record`, `failure_matches_batch`. + +## Findings + +### 1. `projection!` recompiles the whole program on every event and leaks memory each time +- Category: D/E Severity: high Confidence: CONFIRMED +- Where: `src/lib.rs:231-238` (`__resolve` calls `__handlers()?`), `src/lib.rs:196-230`, `src/mutation/descriptor.rs:85` and `:155` (`Box::leak`), `src/projection/lower.rs:529-535`, callers `src/microsvc/projector/runtime.rs:211`, `src/microsvc/causal.rs:782`, `src/projection/rebuild.rs:422` +- What: `ProjectionServerExecutorDescriptor::plan` calls the macro-generated `__resolve`, which calls `__handlers()` per occurrence. That re-runs `$mutation()` (the `mutation_file!` expansion builds a `MutationProgram` via `try_new`), and then for every event type in every arm it: + - clones the program and builds body bindings from `M::schema()`; + - leaks a string: `let mount_id = Box::leak(descriptor.name.replace('.', "-").into_boxed_str());` + - rewrites the mutation into a `ProjectionArm` and re-validates it. +- Why it matters: the e2e `TODOS` projection (8 event types, `tests/e2e-ui/crates/projections/src/todos.rs:32-57`) leaks 8 strings and performs 8 rewrites plus full validation per projected event. A long-running projector's memory grows without bound. A 100k-event rebuild does this 100k times. +- Change: have `ProjectionDescriptor` hold a `OnceLock`/`LazyLock` compiled program (program, id, selector index), built once at registration. `resolve` takes `&CompiledProgram`. Make `arm_id` an owned `String` or `&'static str` from `stringify!`, and delete both `Box::leak` calls. Breaking: `ProjectionResolver` fn-pointer type and `descriptor_from_factories` signature. Size M. + +### 2. Two parallel program IRs, joined by a per-field rewrite +- Category: A/C Severity: high Confidence: CONFIRMED +- Where: `src/mutation/program.rs:276-426` vs `src/projection/program.rs:375-493`; `src/mutation/expression.rs:51-73` vs `src/projection/expression.rs:359`; `src/mutation/program.rs:558-616`; `src/mutation/bind.rs:146-229` +- What: the two operation structs carry the same fields and near-identical `try_new` validation. The kind enums are 9 vs 8 variants. Expression enums differ only in `InputPath` vs `BodyPath`/`Envelope`. Static-ambiguity checks, ordinal validators, id digest/parse and canonical JSON are all duplicated. They are bridged by `rewrite_to_projection`, driven by an `InputPathBinder` with three fallback lookup strategies. +- Why it matters: Principle 5 says one program. Today the mutation program is what authors write and hash (`mp1:`), while the projection program is what executes and is pinned in the catalog (`ProjectionProgramId`). Validation rules already differ: the projection side requires complete-row key fields to use the exact key expression (`program.rs:447-467`); the mutation side does not, so a valid mutation program can fail only at rewrite. +- Change: one IR. A program is `{partition, arms: [{selector, input bindings, operations}]}` with a single expression type that has an `Input(path)` leaf resolved through the arm's bindings at evaluation time. Delete `rewrite_to_projection*`, `InputPathBinder`, and one of the two program modules. Breaking: public `Mutation*` / `Projection*` type surface and the two fixture files. Size L. + +### 3. The binder detects a body path by serialising the expression to JSON +- Category: A/D Severity: medium Confidence: CONFIRMED +- Where: `src/mutation/bind.rs:215-229` +- What: `body_path_segments` calls `serde_json::to_value(expression)` and inspects `value["kind"] == "body_path"`, with the comment "ProjectionExpression does not expose body path publicly beyond as_ref which is crate-private". `mutation` is in the same crate, so `ProjectionExpressionRef` is reachable. +- Why it matters: this runs once per field per event type per event (via finding 1) and silently returns `None` if the serde tag is ever renamed. +- Change: goes away with finding 2. Otherwise match on `expression.as_ref()`. Size S. + +### 4. About a third of `mutation/` has no production caller +- Category: F/C Severity: high Confidence: CONFIRMED (rg across `src`, `tests`, `examples`, `distributed_cli`, `distributed_game`, `distributed_macros`, `js`) +- Where and what: + - `src/mutation/server.rs`: `MutationServerInterpreter` is used only by `preview.rs`; `rewrite_program_with_binder` has no users; `simple_body_bindings` is tests only. + - `src/mutation/preview.rs`: `compose_event_preview`, `causal_scopes`, `zero_binding_preview` are tests only; `reconcile_with_actual`, `rewrite_binding_ops`, `ComposedPreviewLayer`, `MutationCausalScope` have no users. + - `src/mutation/handler.rs`: `MutationHandlerCatalog` / `MutationHandlerRegistration` / `MutationHandlerPlacement` are tests only; `CustomMutationHandler`, `bindings_from_expressions`, `portable_binding` have no users. + - `src/mutation/cache.rs`: `lower_mutation_cache` is reached only through `preview.rs` and tests; `lower_projection_ops_cache` has no users; `is_cache_writable` and `presence_label` ("Placeholder for shared golden-vector evaluation") are tests only. + - `src/mutation/capabilities.rs`: `ReadModelMutationCapabilities` is tests only; no macro emits it. + - Also unused: `MutationOperation::state_upsert` (`program.rs:434-500`), `MutationReturning`, `identity_body_path_binder`, `required_input_paths`, `assert_mutation_backed_program`, and `MutationExpression::resolve` (`expression.rs:259-342`). + - Keep-alive stubs: `fn _projection_program_id_type` (`handler.rs:386`), `fn _use_mutation_expression` (`bind.rs:283`). + - Empty branches left in `MutationOperation::try_new` (`program.rs:372-382`). +- Why it matters: this is a second writer-conflict catalog (`handler.rs:229-292`) and a second placement enum, shadowing the real ones in `projection/catalog.rs:669` and `placement.rs:40`. It is a second interpreter surface re-exported from the crate root (`src/lib.rs:127-141`). +- Change: delete `server.rs`, `preview.rs`, `handler.rs`, `cache.rs`, `capabilities.rs` and the listed functions with their tests. The cache/preview pair needs the owner's call (finding 5). Size M, mostly deletion. + +### 5. `lower_mutation_cache` has a hand-written TypeScript mirror, and neither side is used by a runtime +- Category: A/C Severity: medium Confidence: CONFIRMED (JS usage checked only in `js/src` and `tests/e2e-ui/ui/src`) +- Where: `src/mutation/cache.rs:81-215`, `js/src/replica/mutation-cache.ts:4` ("Mirrors `distributed::mutation::cache::lower_mutation_cache`"), export at `js/src/replica/index.ts:251`, test `js/tests/mutation-cache-lowering.test.mjs:22` +- What: Rust and TS each implement the visibility-to-effect lowering. The shared fixture is only the input program (`tests/fixtures/mutation-program-v1.json`); expected effects are asserted separately on each side. The replica's real path is `projection-delta/` plus `command-projection-metadata-v1.json`. +- Why it matters: this is exactly the "TypeScript twin" Principle 5 forbids, and it is not load-bearing. +- Change: delete both. If role-safe cache lowering is wanted, emit it server-side into the client manifest so TS only interprets data. For the TS reviewer, the Rust definitions the replica must mirror today are: the `ProjectionProgram` wire form (`projection/program.rs`), `ProjectionExpression`/`ProjectionValue` (`projection/expression.rs`), `ProjectionScalarTransform`, key/partition canonical bytes (`projection/canonical.rs`), and whatever `graphql/projection_delta` derives from them. Shared fixtures exist for program bytes and delta (`tests/fixtures/projection-program-v1.json`, `projection-delta-v1.json`). I found no shared fixture for resolved plans (input occurrence → expected `ResolvedProjectionPlan` bytes), which is the fixture that would prove one set of semantics. Size S. + +### 6. The projection commit state machine is implemented twice, including an 85-line byte-identical function +- Category: C/A Severity: high Confidence: CONFIRMED +- Where: `src/in_memory_repo/projection_protocol/store_impl.rs:105-435` vs `src/sqlx_repo/projection_protocol/store_impl.rs:333-647`; `next_record` at `src/in_memory_repo/projection_protocol/state_impl.rs:558-644` vs `src/sqlx_repo/projection_protocol/writes.rs:298-383`; `failure_matches_batch` wrapper at `writes.rs:1449`; `InputDisposition` declared in `in_memory_repo/.../state.rs:290`, `sqlx_repo/.../types.rs:65` and `store/identity.rs:183` +- What: both stores hand-code the same sequence: classify input, handle pending retry and redelivery, compute next revision per mutation, validate the snapshot write, allocate a change, resolve observation targets, emit a fallback checkpoint change, write receipt/identity/inbox, apply retention. Only `change_kind_for_mutation`, `checked_next`, `validate_snapshot_write` and `failure_matches_batch` are shared (`store/backend_helpers.rs`, 242 lines). `record_projection_failure`, `repair_projection` and the rebuild commit are duplicated in the same style. +- Why it matters: Principle 7. Every protocol rule must be changed in two places, and they have already drifted (finding 7). +- Change: move the algorithm above the trait as one `fn plan_commit(batch, &impl CommitState) -> CommitEffects`, where the store supplies a small transactional read/write primitive set (load record, load physical-exists, load observation, classify input, apply effects). `next_record`, physical-row validation and observation resolution live once in `projection_protocol/store/`. Breaking: `ProjectionProtocolStore` shrinks to primitives. Size L. + +### 7. Backends disagree on observing a tombstoned existing record +- Category: E Severity: medium Confidence: CONFIRMED (by reading both; not executed) +- Where: `src/sqlx_repo/projection_protocol/store_impl.rs:506-510` vs `src/in_memory_repo/projection_protocol/store_impl.rs:288-303` +- What: for `ProjectionObservationTarget::ExistingRecord`, sqlx returns `RecordTombstoned` when `metadata.tombstone && metadata.source_snapshot.is_none()`. The in-memory path checks only the revision and accepts the observation. `rg RecordTombstoned src/in_memory_repo` finds no hit in the observation path. +- Why it matters: a command confirmation against a deleted row succeeds on the memory backend and fails on SQLite/Postgres, so tests on memory cannot catch it. +- Change: falls out of finding 6. Until then, add the check to memory and a conformance scenario. Size S. + +### 8. In-memory store clones the entire protocol state and inbox on every commit +- Category: D Severity: medium Confidence: CONFIRMED +- Where: `src/in_memory_repo/projection_protocol/store_impl.rs:174-175` (commit), `:532-533` (failure), `:44`, `:1218`; `rebuild.rs` `protocol.clone()` + `rows.clone()` +- What: `let mut staged_protocol = protocol.clone(); let mut staged_inbox = inbox.clone();` copies every record, change, input, receipt and observation of every partition per projected event, to get rollback. +- Why it matters: cost per event is O(total state), so a test or dev run is O(n²). The in-memory repo backs most of the test suite and local dev. +- Change: stage a delta (touched keys only, as already done for rows at `:192-197`) and merge on success. Size M; simpler after finding 6. + +### 9. Per-event resolve/lower does avoidable serialisation and whole-plan clones +- Category: D Severity: medium Confidence: CONFIRMED +- Where: `src/projection/plan.rs:414` (`program.id()?`), `plan.rs:441`, `src/projection/lower.rs:1117`, `plan.rs:631` / `src/projection/canonical.rs:13-21`, `src/projection/lower.rs:1523-1538`, `src/projection/executor.rs:211-221`, `executor.rs:124` +- What, per event after finding 1 is fixed: + - the program id is recomputed (serialise whole program to `Value`, sort, re-serialise, SHA-256); + - the occurrence is cloned into the plan, then the whole plan is cloned again in `finish_lowering`; + - each key and partition goes through `to_value` → sort → `to_vec`; + - numbers are stored as decimal strings in `ProjectionValue` and parsed back per field when lowering to `RowValue`; + - the executor re-derives which logical mutation each physical mutation came from with an O(P×L) key-equality scan that recomputes `resolved_row_key` per pair; + - `workspace.clone()` per stage. +- Change: cache the id in the compiled program. Have `LoweredProjectionPlan` own the resolved plan (lower by value) and hold the occurrence by `Arc` or reference. Have lowering emit `(logical index, TableMutation)` pairs so the executor does not re-match. Size M. + +### 10. Too many intermediate representations between declaration and store +- Category: A/F Severity: medium Confidence: CONFIRMED +- Where: `src/projection/executor.rs:27-36` (`LifecycleIntent`), `executor.rs:11` (`ProjectionMutationKind as LogicalMutationKind`), `src/projection_protocol/store/identity.rs:236`, `src/projection/program.rs:173`, `src/mutation/program.rs:218`; `executor.rs:611-670`; `src/projection/program.rs:79` vs `src/projection_protocol.rs:365`; `src/projection/plan.rs:88` vs `src/projection_protocol.rs:96` +- What: + - Kind is represented four times: `MutationKind` (9), `projection::ProjectionMutationKind` (8), `LifecycleIntent` (6), `projection_protocol::ProjectionMutationKind` (3). Two different enums share one name, hence the import alias. + - There are two unrelated `ProjectionPartition` types and two `ResolvedProjectionKey` types. + - Lowering picks a `RowWriteMode`/`ExpectedVersion`, then the executor's `normalize_create/save/patch/delete` overwrites that choice from the snapshot. Rebuild overwrites it a third time (`rebuild.rs:430-438`). +- Change: lower straight from `ResolvedProjectionMutation` plus snapshot to `ProjectionRecordMutation` in one step, dropping the intermediate `TableWritePlan` and the normalise pass. Rename the protocol enum (e.g. `RecordTransition { Upsert, Delete, Recreate }`) and the protocol partition (e.g. `PartitionId`). Size M–L. + +### 11. Store trait has test-only methods and fail-closed defaults that `QueuedRepository` falls through +- Category: E/F Severity: high (the default trap) / medium (dead surface) Confidence: CONFIRMED for missing forwarding and caller counts; PLAUSIBLE for production impact +- Where: `src/projection_protocol/store/trait.rs:99-128` (defaults), `src/queued_repo/repository.rs:360-545`, caller `src/microsvc/projector/context.rs:109`, `src/projection_protocol/store/mod.rs:9-13` +- What: + - The trait has 22 methods. `projection_execution_snapshot_batch` and `projection_graph_snapshot` default to `Err("adapter does not support …")`. `QueuedRepository` forwards 18 methods but not those two, so a projector on a `QueuedRepository` gets the error on every stage that needs a snapshot read. I did not confirm that any service mounts a projector on one. + - No non-test caller (besides `queued_repo` delegation) for: `projection_checkpoint`, `projection_query_snapshot_batch`, `projection_graph_snapshot`, `projection_live_record_batch`, `projection_observation`, `compact_projection_changes`, `projection_failure`. + - The module carries a blanket `#![allow(dead_code)]` with the comment "the store trait + query vocabulary is wider than the production call graph". +- Why it matters: defaults "for older adapters" are a pre-release compat shim. They turn a compile error into a runtime failure on one backend wrapper. The graph-snapshot path alone is roughly 300 lines across `in_memory_repo/.../read_helpers.rs:24-175` and `sqlx_repo/.../reads.rs:1101-1305`, plus `workspace.rs:277` and `backend_helpers.rs:54-165`. +- Change: remove every default body so each implementor must implement or forward. Delete the methods with no production caller, with their request/response types and tests. Drop the blanket allow. Size M. + +### 12. Source-snapshot fencing is threaded through every layer as flags +- Category: A/F Severity: medium Confidence: CONFIRMED +- Where: `src/projection/program.rs:646-649` and `:708-743`; `src/projection/plan.rs:372-373`, `:390-400`; `src/projection/executor.rs:42`, `:137-156`, `:468-515`; `next_record(…, source_snapshot: bool)` in both stores; `src/sqlx_repo/projection_protocol/store_impl.rs:506`; `src/projection_protocol/source_snapshot.rs:14-23` +- What: the policy is two bools on the program, a bool on the plan, an `Option` on each execution mutation, a parallel `stage_source_snapshot` beside `stage_for_snapshot`, and a bool parameter that relaxes delete-of-tombstone in `next_record`. `SourceSnapshotVersion` has an `external: bool` that reuses `aggregate_type`/`aggregate_id` for external producers by writing `format!("external:{:x}", …)` into `aggregate_id`. The illegal state `external_source_snapshots && !source_snapshots` is representable. +- Why it matters: this is the "special cases threaded with flags" pattern. The delete-tombstone relaxation lives inside the generic revision function. +- Change: one enum on the program, `SourceOrdering { Position, AggregateSnapshot, ExternalSnapshot }`, matching the macro's `source:` keyword. `SourceSnapshotVersion` becomes an enum over aggregate/external identities. Model staging as a strategy chosen once from the enum, not per-mutation `Option` checks. The store then sees an explicit transition (idempotent tombstone refresh), not a bool. Size M. + +### 13. Rebuild is not orthogonal: snapshot-only, unit-partition-only, and depends on GraphQL surface types +- Category: A/F Severity: medium Confidence: CONFIRMED +- Where: `src/projection/rebuild.rs:4` (`use crate::graphql::SurfaceProjector`), `:279-305`, `src/projection/mod.rs:25-26` (`#[cfg(feature = "graphql")] pub mod rebuild`), `src/projection_protocol/store/trait.rs:18-41`, `rebuild.rs:276` (`#[allow(private_bounds)]`), `src/projection/local_mounts.rs:9` +- What: `SnapshotProjectionRebuild::begin` takes a `SurfaceProjector`, requires exactly one modeled binding, a local route and `source_snapshots()`. The two trait methods exist only under the `graphql` feature and default to "does not support". The public API is bounded by a `pub(crate)` trait. Delta/patch projections have no rebuild path. +- Why it matters: core projection maintenance depends on the API layer and on a feature flag. "Rebuild" covers only one fencing policy. +- Change: `begin` takes `(descriptor/executor, compiled topology, epoch)`, with the surface layer adapting. Remove the cfg and the defaults. Either name the type for what it is (snapshot reconciliation) or generalise it. Size M. + +### 14. Rebuild coverage check is O(streams × history) +- Category: D Severity: low Confidence: CONFIRMED +- Where: `src/projection/rebuild.rs:491-511` +- What: for each relevant stream that has a coverage witness, the code filters the whole `history` slice again. Limits are 10,000 streams and 100,000 events (`:12-13`). +- Change: group event ids by stream in the first pass (the loop at `:382` already builds `sequences` per stream). Size S. + +### 15. IR surface that authoring cannot reach +- Category: F Severity: medium Confidence: CONFIRMED for macro output; PLAUSIBLE that nothing else needs these +- Where: `distributed_macros/src/mutation.rs:729,792,839,907`; `src/mutation/program.rs:218-237`; `src/projection/lower.rs:1025-1032`, `:1045-1103`; `src/lib.rs:225` +- What: + - The mutation macro emits only `Upsert`, `Insert`, `Delete`, `Patch`. + - `projection!` always lowers with `lower_single_model`, which rejects `InsertRelated`/`UpsertRelated`. + - `projection!` hard-codes `ProjectionPartition::Unit`. Expression partitions are reachable only through the `program:` escape hatch, and in-repo use is tests only (`tests/typed_commands/main.rs:413`, `tests/domain_event_projection_server.rs:179`). + - `Invalidate`, `Recreate`, `UpsertPatch`, `MutationReturning`, relationship effects and `lower_related_mutation` are used only by tests and `tests/domain_event_projection_server.rs`. +- Change: decide per feature whether it ships. Where it does not, remove the variant, its validation, lowering, executor arms and tests. Size M. + +### 16. `lower.rs` holds four jobs; half of it is the superseded authoring path +- Category: F Severity: medium Confidence: CONFIRMED (usage via rg) +- Where: `src/projection/lower.rs` +- What and seams: + - (a) Derive-facing metadata traits and const asserts, `:30-245`. `assert_state_upsert_compatible` and `assert_explicit_field_compatible` are referenced only in this file. + - (b) `ProjectionDescriptor` / executor descriptor plus a process-global `PLACEMENT_SELECTED_DIRECT` registry, `:247-591`. + - (c) The pre-mutation authoring builders, `:674-980`, `:1182-1336`, `:1617-1660`: `state_upsert_operation`, `model_operation`, `related_operation`, `ProjectionAuthoringField`, `state_selector`, `deletion_selector`, `event_selector`, `resolve_typed`, `projection_program`, `output_relationship`. Their only users are `tests/domain_event_projection_server.rs`, plus `state_selector` in two tests. `ProjectionPlanTemplate` / `ProjectionEventSet` have the same users plus `command/`. + - (d) The actual resolved-to-row lowering, `:982-1119`, `:1338-1609`. +- Also: the registry at `:543-564` is a global `RwLock` keyed by model name, silently replaces entries "so tests can rebuild services", and swallows a poisoned lock. This is hidden global state against Principle 6; the owning microsvc reviewer should confirm. +- Change: delete (c) with its test file. Split into `metadata.rs`, `descriptor.rs`, `lower.rs`. Move the registry into the Service. Size M. + +### 17. Other oversized files: where the seams are +- Category: F Severity: low Confidence: CONFIRMED (structure) +- What: + - `projection/catalog.rs` (2,125 lines) is about 830 lines of code and 1,290 of in-file tests. Move tests to `catalog/tests.rs`. `ProjectionCompatibilityPins` / `compatibility_pins` (`:303-395`) are referenced only inside this file. + - `projection/placement.rs` (1,523) mixes wire-schema value types (`:40-575`), binding identity/materialisation (`:577-1167`) and the direct-eligibility proof (`:1357-1460`). Split into `binding.rs`, `schema.rs`, `direct.rs`. + - `projection/executor.rs` (1,682) is about 795 lines of code and 885 of tests. `prepare_graph_projection` (`:253-279`) is test-only by its own attribute and should go. + - `projection_protocol.rs` (1,649) is about 1,040 lines of identity/cursor newtypes with hand-written serde, plus 610 of tests. Move the newtypes to `projection_protocol/identity.rs`. + - Small helpers are copied: `hex_nibble` ×4 (`program.rs:987`, `placement.rs:1485`, `mutation/program.rs:963`, `replay.rs:419`), `program_id_serde` ×2 (`catalog.rs:810`, `placement.rs:1501`), `body_kind_rank` ×2 (`placement.rs:1493`, `provenance.rs:328`), `sort_value`/`canonical_json_bytes` ×4 (`projection/canonical.rs`, `mutation/canonical.rs`, `projection_protocol/codec/catalog.rs:24`, `domain_event/canonical.rs:21`), `ProjectionValue → JSON` ×4 (`lower.rs:1559`, `executor.rs:353`, `mutation/expression.rs:480`, `graphql/projection_delta/runtime.rs:1493`). +- Change: one `canonical` module, one `hex` helper, one `ProjectionValue::to_json`. Size S–M. + +### 18. `MutationExpression::resolve` is a second evaluator with different semantics +- Category: E/C Severity: low (test-only today) Confidence: CONFIRMED +- Where: `src/mutation/expression.rs:259-342`, `:480-488` +- What: it evaluates `Transform` as an error ("transform evaluation requires projection rewrite"), ignores the declared `value_type` (`let _ = value_type;`), and its JSON conversion turns I64/U64/F64 into JSON strings, where `lower.rs:1565-1588` emits numbers. +- Why it matters: a public method on the "canonical" IR gives different answers from the real evaluator (`projection/expression.rs:618`). +- Change: delete it (part of finding 4). Size S. + +### 19. Store tests are duplicated per backend instead of one conformance suite +- Category: B/C Severity: high Confidence: CONFIRMED (names for all; body for one pair) +- Where: `src/in_memory_repo/projection_protocol/tests.rs` (3,787 lines, 34 tests), `src/sqlx_repo/projection_protocol/tests.rs` (3,236, 23 tests), `src/sqlx_repo/projection_protocol/postgres_tests.rs` (1,876, 5 tests), `src/projection_protocol/store/scenario_tests.rs` (631, 6 shared scenarios) +- What: a shared `ProjectionProtocolScenario` trait exists and both backends call its 6 scenarios. The rest is copy-paste. `query_snapshot_never_mixes_row_revision_checkpoint_or_resume_head` (memory `:924`) and `sqlite_query_snapshot_never_mixes_…` (sqlx `:671`) are line-for-line identical except the loop bound (64 vs 32). Other pairs by name: + - `four_position_in_memory_…` / `four_position_sqlite_…` / `four_position_postgres_projection_commit_failure_matrix_rolls_back_every_side_effect` + - `coherent_execution_and_graph_snapshots_use_fk_references_and_unique_scope_budgets` / `sqlite_coherent_…` / `postgres_coherent_…` + - `physical_rows_must_match_projection_record_metadata` / `sqlite_record_metadata_is_fenced_against_physical_row_drift` + - `table_failure_rolls_back_rows_protocol_and_inbox` / `sqlite_row_failure_rolls_back_protocol_receipt_inbox_and_domain_row` + - `lengthening_retention_never_restores_a_compacted_prefix` / `sqlite_retention_prunes_exact_prefix_and_never_restores_it` + - `registration_is_global_and_rejects_unowned_rows_atomically` / `sqlite_registration_rejects_legacy_rows_and_cross_topology_table_owners` +- Coverage holes by name: memory-only `concurrent_same_input_applies_once`, `observations_are_immutable_and_staged_records_reuse_row_changes`, `repair_generation_retries_only_the_exact_failed_input`; sqlite-only `sqlite_non_gap_repair_requires_failed_cursor_before_later_input`. The divergence in finding 7 has no scenario. +- Postgres tests return early when `DISTRIBUTED_TEST_POSTGRES_URL` is unset (`postgres_tests.rs:32,56,645,756,1017`), so they report as passed without running. +- Change: move every backend-agnostic scenario into `scenario_tests.rs`, generic over the store, as `source_snapshot_tests.rs:246` (`async fn matrix(store: &impl ProjectionProtocolStore)`) already does. Instantiate per backend with a macro. Keep per-backend files only for backend-specific behaviour (restart durability, SQL snapshot isolation, cancelled `begin`). Make Postgres `#[ignore]` or fail loudly when not configured. Expect roughly 5k fewer test lines. Size L. + +### 20. Low-value or unable-to-fail tests in the mutation module +- Category: B Severity: medium Confidence: CONFIRMED for the first bullet; the rest PLAUSIBLE from names and the code they cover +- Where: `src/mutation/tests.rs`, `src/mutation/relationship_fixture.rs`, `tests/legacy_authoring_absence.rs` +- What: + - `golden_fixture_round_trip_matches_canonical_program` (`tests.rs:595-615`) writes the fixture into the source tree if it is missing and then compares the program to itself. It also compares parsed JSON, not bytes; the projection twin `canonical_program_matches_frozen_vector` (`projection/tests.rs:476`) compares bytes. + - `presence_labels_cover_lattice`, `read_model_capabilities_are_internal_metadata` and `preview_composition_zero_binding_and_multi_owner` (asserts `!zero_binding_preview().has_optimism()` on `Default`) test helpers that exist only for tests. + - `portable_handler_catalog_rejects_duplicate_owner_event_epoch` and all five tests in `relationship_fixture.rs` exercise the unused `MutationHandlerCatalog`, preview and cache code. + - `mutation_program_contains_no_event_selector_fields` asserts absence of struct fields via JSON. + - `tests/legacy_authoring_absence.rs` (outside my slice) greps `src/lib.rs` text for substrings. +- Missing behavioural tests: no test that `projection!` resolve does not rebuild or leak per event (finding 1); no Rust/TS shared vector for occurrence → resolved plan (finding 5). +- Change: delete with finding 4. Make the golden test byte-exact and never self-writing. Size S. + +### 21. `DirectCandidate` is described as compiler-generated but is typed by the author +- Category: F Severity: low Confidence: CONFIRMED +- Where: `src/projection/lower.rs:247-259`, `:344-349`; `src/lib.rs:179` (`$desc_ty:ty`) +- What: the docs say "The macro emits this marker only for the exact full-state upsert shorthand". In `projection!` the author writes the descriptor type by hand, so the marker is an opt-in and `.direct()` revalidation does the real work. +- Change: drop the type parameter and expose `descriptor.direct()` returning `Result`, or have the macro compute it. Fix the docs either way. Size S. + +### 22. Stringly-typed errors and stale wording in the public mount API +- Category: F Severity: low Confidence: CONFIRMED +- Where: `src/projection/local_mounts.rs:114-248` (every method returns `Result<_, String>`, `#![allow(missing_docs)]`); `src/projection/lower.rs:413`, `:422`, `:1615` ("task-7"); `src/mutation/mod.rs:8-9` ("The old event-owning projection proc-macro authoring path is gone"); `src/projection/mod.rs:15-17` ("empty seams intentionally expose no … contract before their owning tasks define one" above modules that are fully populated); `src/mutation/cache.rs` header (a sentence that stops mid-phrase: "During the this module rewrites…") +- Change: add a typed `ProjectionMountError` and scrub task-history comments. Size S. + +## Things that are good and should not be changed + +- Canonical, domain-separated, length-prefixed digests for program/key/partition identity, with frozen byte fixtures (`projection/canonical.rs`, `tests/fixtures/projection-program-v1.json`). Keep the design; just deduplicate the code. +- The executor's separation of store-free preflight (`prepare_portable_projection`) from snapshot-driven lifecycle selection (`PreparedProjectionExecution::stage`), with exact scope-matched (not positional) snapshot validation and atomic staging into the workspace. +- `validate_snapshot_write` as a last-line check at the commit boundary, shared by both stores (`projection_protocol/source_snapshot.rs:105`). The fencing semantics are sound; only the flag plumbing needs reshaping. +- `projection/source_snapshot_tests.rs`: one `matrix(store)` / `rebuild_matrix(store)` run against memory, SQLite and Postgres. This is the template for the conformance suite in finding 19. +- Catalog/activation separation (`ProjectionCatalog` vs `ActiveProjectionBindings`): program identity independent of epoch/route, with writer-overlap and same-epoch-takeover rejected at construction. It is explicit topology composition as Principle 6 intends. diff --git a/docs/reviews/v5-pre-release/04-graphql-query-side.md b/docs/reviews/v5-pre-release/04-graphql-query-side.md new file mode 100644 index 000000000..dec06196c --- /dev/null +++ b/docs/reviews/v5-pre-release/04-graphql-query-side.md @@ -0,0 +1,207 @@ +## Assessment + +The slice is in reasonable shape with one real authorization hole. One compiler serves both dialects, each root field becomes one SQL statement (no N+1), client values are always binds, and the integration tests are mostly behavioural. Nothing I read on the query path writes domain state; `delivery/versions.rs` (described at `engine/builder.rs:65` as "installing version coverage in the engine's database") was not read, so that part is unverified. + +The three things most worth changing: +1. **Permissions live in two parallel representations.** The SQL compiler reads `ReadPermission`; the schema, SDL, manifest and protocol read `RoleGrant`/`SurfaceRowPolicy`. They are intersected by two different functions that disagree, and that disagreement is the hole (finding 1). +2. **Row policy is enforced by convention.** Eight hand-written sites each have to remember to pair a projection with `compile_where`; no single scan builder makes omission impossible (finding 2). +3. **The executor and result path are doubled.** There are four executor arms (plain/protocol × SQLite/Postgres), stringly-typed errors matched by substring, and several passes over the result JSON (findings 5, 6, 9, 10). + +Not read, or only partly read: +- **Outline only:** `http.rs` (mostly identity/websocket, assumed part 2), `sdl.rs`, `naming.rs`, `surface/{build,commands,effects,identity,leaderboard,projections,roots,validation}.rs`. +- **Not read:** `commands.rs`, `compile/evidence.rs`, `engine/{live_resume,metrics,read_routing}.rs`, `delivery/versions.rs`, `protocol/` (assumed part 2). +- **Partial:** `leaderboard_roots.rs` (350-382), `surface/types.rs` (465-600), `filter.rs` (388-590), `query_protocol.rs` (1-1000 read, rest outlined), `engine/delivery.rs` (1-120), `engine/introspection.rs` (1-80). +- **Tests:** `engine/tests.rs` read at 860-950, 1286-1420, 1814-2065, 2295-2383, 2505-2521. `surface/tests.rs` and `engine/composite_relationship_tests.rs` by test names and assertion counts only. + +Ownership calls: I took `engine/auth.rs` and `engine/protocol.rs` because they decide which grants SQL uses. + +## Findings + +### 1. Multi-role application surface runs SQL with the alphabetically-first role's row filter +- Category: E/A Severity: high Confidence: CONFIRMED (by reading; not executed) +- Where: `src/graphql/engine/auth.rs:219-227`; `engine/builder.rs:391-392, 981-1032`; `engine/protocol.rs:33-43, 128-138`; `surface/application.rs:687-692` +- What: `insert_synthetic_privilege_permissions` builds the `ReadPermission` stored under `app:{name}`. Both arms of its `if` return `first.row_filter.clone()`, and the comment admits it: "Fail closed to first role's filter is wrong … otherwise keep first for SQL". `schema_roles` is sorted, so `first` is the alphabetically first role. The surface side turns differing policies into `ServerOnly`, promising the server enforces them. Any principal holding any eligible role may open the surface and gets `privilege_role = app:{name}`. +- Why it matters: with `client_application_surface("console", ["admin","user"], ["admin","user"])`, `admin` unrestricted and `user` owner-filtered, a `user`-only principal gets SQL with no row filter. No test covers this: `named_application_protocol_selection_is_registered_exact_and_role_bound` (`engine/tests.rs:863`) uses `grant_all` for both roles. +- Change: make the synthetic filter the AND of all schema roles' filters, or reject differing policies at build. Better, delete this function via finding 3. Add a behavioural test that seeds rows and queries as `user` through the app surface. Size S (fix), M (with 3). + +### 2. Row and column RBAC is re-applied per path, not enforced at one choke point +- Category: A Severity: medium Confidence: CONFIRMED +- Where: `compile/projection.rs:572, 642, 685, 734`; `compile/relationship.rs:84, 137, 299, 382`; `compile/filter.rs:390`; `compile/projection.rs:522-526, 866, 899, 939, 966-972`; `schema.rs:759-767` +- What: the row predicate lives in one function (`compile_where`), but nine call sites must each remember to call it next to a hand-written `SELECT … FROM "table" alias WHERE …` template. I found no site that omits it today. Other enforcement is implicit: + - `compile_root` does not check `perm.aggregations` for `RootKind::Aggregate`; only the per-role schema hides that root. + - Ungranted columns and relationship targets are silently `continue`d rather than rejected. + - `execute_cell_by_key` projects `row.get(&child.field_name)` with no `allows_column` check, again relying on the schema. + - Many-to-many joins traverse the through table without consulting any grant on it. +- Why it matters: principle 4. A new access path (sum/avg aggregates, cursor pagination) leaks rows if its author forgets the pairing. +- Change: introduce one `ModelScan { from_sql, where_sql }` constructor that takes (model, privilege) and always includes the policy. Every list, by-pk, count, nodes, relationship and EXISTS path builds from it. Turn the silent `continue`s into internal errors, and check `aggregations` in the compiler. Size M. + +### 3. Parallel permission types: `ReadPermission` vs `RoleGrant`, two intersections, two validators +- Category: C/F Severity: medium Confidence: CONFIRMED +- Where: `permissions.rs:32-136`; `surface/application.rs:6-58`; `engine/core.rs:167-169, 241, 260`; `engine/validation.rs:63-162` vs `surface/application.rs:439-554`; `engine/builder.rs:698-714` vs `surface/application.rs:404-417`; `compile/projection.rs:1093-1108` vs `surface/types.rs:488-511`; `engine/auth.rs:93-120` vs `filter.rs:535-561` +- What: + - `ReadPermission` and `RoleGrant` carry the same five facts and are mapped by `role_grant_from_read_permission`. + - `EngineInner` holds both `permissions` (used by SQL) and `role_surfaces` (used by everything else). + - The row-policy validator is written twice, near line-for-line. So is the column-allowlist check, although `build()` already calls `surface_for_role`, which runs the surface copy. + - "Has client-normalized identity" exists twice with slightly different rules, despite the comment at `types.rs:485` saying "this single predicate". + - The claim-key walker in `auth.rs` duplicates `FilterExpr::visit_claims`. + - `RoleModelPerm` is a one-field wrapper. +- Why it matters: this is the owner's "no parallel types" rule, and it is the structural cause of finding 1. +- Change (breaking): one grant type (keep `ReadPermission` as the authoring API). The selected role/application `Surface` keeps the executable `FilterExpr` plus a derived "client-portable?" flag. The compiler reads `role_surfaces[privilege].models[..]`. Delete `EngineInner.permissions`, `RoleModelPerm`, `RoleGrant`, `validate_filter*`, `insert_synthetic_privilege_permissions` and the duplicate predicate. Size L. + +### 4. Query cost limits ignore `limit`, so one request can ask for about a million rows +- Category: D Severity: medium Confidence: CONFIRMED (arithmetic from code) +- Where: `complexity.rs:89-96`; `complexity_contract.rs:32-47`; `engine/builder.rs:22-25`; `compile/projection.rs:539-543, 809-818`; `schema.rs:380-382` +- What: complexity uses a fixed `list_fanout: 5` regardless of the requested limit. `orders(limit:1000){ items(limit:1000){ id } }` costs 3 + 5×(10 + 5×1) = 78 against a budget of 500, and `max_limit` (1000) applies per level. `offset` has no cap. The budget is per root field; only async-graphql's flat field count spans the document. +- Why it matters: the only bound on result size is the 5-second statement timeout. The JSON is materialised in the database, then passed through `serde_json` and `async_graphql::Value`. +- Change: multiply by the resolved limit to get a row budget (e.g. product of limits ≤ `max_rows`, default around 10k), or give nested lists a smaller default. Collapse the three overlapping knobs into one documented cost model: async-graphql `limit_depth`/`limit_complexity`, the compiler's `max_depth` (which also counts boolean nesting, `compile/filter.rs:25, 64`), and `estimate_root_complexity`. The same `max_complexity` number currently means two different units. Size M. + +### 5. Errors are `String` end to end and classified by substring +- Category: E/F Severity: medium Confidence: CONFIRMED +- Where: `schema.rs:901-937`; `compile/projection.rs:655`; `engine/builder.rs:88`; `execute.rs:13, 56`; `compile/filter.rs:569-579` +- What: + - `sanitize_compile_error` picks the client message with `e.contains("max depth")`, `"_in list"`, `"cell-by-key"` and so on. + - `client_error_for_execute_err` maps any error text containing `"timeout"` to `TIMEOUT`, which may also catch sqlx pool-acquire timeouts (not verified). + - By-pk decides whether to AND the filter with `where_sql == "TRUE" || where_sql == "true"`. + - The builder swallows shadow-catalog errors with `!e.0.contains("identical")`. `insert_catalog` itself never emits that word (`schema.validate()` errors, outside the slice, were not checked), so the test is effectively always true. +- Why it matters: rewording a message silently changes the client error code. Comments in `compile/filter.rs` already warn that messages "must stay free of SQL fragments so sanitize maps to a stable code". +- Change: a `CompileError` enum (`TooDeep`, `TooComplex`, `ListTooLong`, `InvalidFilter`, `UnsupportedOnCellStore`, `Internal`) and an `ExecuteError { Timeout, Database }`. Have `compile_where` return `Option` instead of the `"TRUE"` sentinel. Size M. + +### 6. Four executor arms; Postgres pays 4-5 round trips per root field +- Category: C/D Severity: medium Confidence: CONFIRMED +- Where: `execute.rs:84-127, 215-287`; `query_protocol.rs:620-669` vs `670-732`; `execute.rs:226-231` and `query_protocol.rs:683-690` +- What: plain and protocol execution are separate functions, each with a SQLite and a Postgres arm. The two protocol arms are near-identical closures of about 50 lines, even though `finish_protocol_query` is already generic over `DB`. The plain Postgres path does `BEGIN`, `SET LOCAL statement_timeout`, optionally `SELECT pg_is_in_recovery()`, the query, then `COMMIT`, for every root field. `plan.sql.clone()` runs per execution, and `plan.clone()` twice per protocol request (`query_protocol.rs:614, 625`). +- Why it matters: latency on the hottest read path, and two places to keep the timeout and primary-check logic identical. +- Change: one `execute_plan(executor, plan)` generic over the backend. The plain path becomes "protocol path with no evidence consumer". Set the timeout once per connection, or fold it into one round trip with `set_config(..., true)`. Hold the plan in an `Arc`. Size M. + +### 7. `_like` / `_ilike` behave differently on SQLite and Postgres +- Category: A (principle 7) Severity: medium Confidence: CONFIRMED (code and repo-wide rg; standard SQLite behaviour, not executed) +- Where: `compile/filter.rs:102-103, 545-546`; `compile/dialect.rs:45` +- What: `_like` emits `LIKE` on both dialects and `_ilike` maps to `LIKE` on SQLite. SQLite's `LIKE` is ASCII-case-insensitive by default and nothing in the repo sets `case_sensitive_like`. So `_like` is case-sensitive on Postgres and insensitive on SQLite, and `_ilike` is Unicode-aware only on Postgres. +- Why it matters: the same query returns different rows per backend, with no error. `order_by` already pins `COLLATE "C"`/`BINARY` for exactly this reason. +- Change: pick one semantics. For example, `_like` on SQLite becomes `GLOB`-equivalent or the connection sets `PRAGMA case_sensitive_like=ON`; `_ilike` becomes `lower(col) LIKE lower(?)` on both. Add a cross-dialect conformance test. Size S-M. + +### 8. Plans are extracted for gateway delivery by throwing a sentinel error from resolvers +- Category: A/F Severity: medium Confidence: CONFIRMED +- Where: `schema.rs:296-320, 804-817`; `delivery/mod.rs:35-39`; `engine/delivery.rs:109-120` +- What: under `gateway-delivery`, `validate_delivery` runs the real schema executor with a `PlanCapture` in request data. Each root resolver compiles, pushes the `SqlPlan` into a mutex-guarded `Vec`, and returns `Err("gateway query plan captured")`. The caller reads the vector back. +- Why it matters: control flow by error string, `cfg` branches inside the hot resolver, and a third execution mode beside plain and protocol. +- Change: expose `GraphqlEngine::plan(session, request) -> Result, _>` that walks validated root selections and calls `compile_query` directly. Remove `PlanCapture` and `CAPTURED`. Size M. + +### 9. SQLite JSON subtype loss is patched in two post-processing layers instead of in the SQL +- Category: D/A Severity: medium Confidence: CONFIRMED (workaround exists); PLAUSIBLE (fix, needs a SQLite run) +- Where: `compile/projection.rs:586-589` vs `compile/relationship.rs:179, 331, 405` and `compile/projection.rs:757`; `execute.rs:180-212`; `schema.rs:714-721` +- What: only the root list wraps rows with `json(root)`. Nested aggregates emit `json_group_array(obj)` unwrapped, so SQLite returns elements as JSON strings. `deep_parse_json_strings` then re-parses any array element that looks like `{…}` or `[…]`, and `passthrough_key` re-parses a string parent on every child-field resolution (a belongs-to object with N selected fields is parsed N times). +- Why it matters: a per-request heuristic tree walk plus repeated parsing, on SQLite only, where the dialect table already has a `json_cast_fn`. +- Change: apply `json(...)` to every nested object and array expression in the SQLite dialect, then delete `deep_parse_json_strings` and the string branch of `passthrough_key`. Also check whether a `Json` column on SQLite reaches the client as a string (`column_json_expr` emits the bare column, `projection.rs:1121-1122`); I found no test asserting either way. Size S-M. + +### 10. Result JSON is walked several times, and field lookup is a linear scan with deep clones +- Category: D Severity: low-medium Confidence: CONFIRMED +- Where: `execute.rs:130-136, 289-293`; `schema.rs:771-783`; `compile/projection.rs:846, 1015-1091`; `execute.rs:26-28` +- What: database text goes through `serde_json::from_str`, then (SQLite) `deep_parse_json_strings`, `rewrite_hex_bytes`, `extract_evidence_and_strip`, `Value::from_json`, and finally the dynamic resolvers. `lookup_key` iterates the whole map comparing keys instead of using `map.get`, and clones the value. For a relationship field that is the entire subtree, cloned again at each level. Hidden evidence columns are added to every object on every request, even when `inner.protocol` is `None` and the plain path throws the evidence away. +- Change: use `IndexMap::get`. Emit and strip evidence columns only when a protocol accumulator exists. Size S for those two; the remaining passes fall out of finding 9. + +### 11. `execute` and `execute_stream` duplicate about 70 lines; operation selection is written three times +- Category: C Severity: low-medium Confidence: CONFIRMED +- Where: `engine/request.rs:31-102` vs `118-193`; `engine/request.rs:333-349`, `engine/protocol.rs:297-313`, `engine/introspection.rs:15-35`; fragment walkers at `engine/protocol.rs:325-393` and `engine/introspection.rs:43-80` +- What: the lifecycle check, authority resolution, schema selection, multi-root check, accumulator, read routing and data injection are repeated for the streaming entry point. "Pick the named or sole operation" appears three times, and the budgeted fragment walk twice. +- Change: one `prepare(session, request) -> Result` used by both entry points, and one `selected_operation(&mut Request)` helper. Size S. + +### 12. Privilege-role fallback written "for schema unit tests" sits on the production path, twice +- Category: E Severity: low-medium Confidence: CONFIRMED +- Where: `schema.rs:867-882`; `leaderboard_roots.rs:354-366` +- What: if `ExecutionAuthority` is absent from request data, both helpers authorise as `session.roles().first()`, else anonymous. `GraphqlEngine::execute` always injects authority, so this only fires if a future entry point forgets to. In that case a multi-role session gets its first role's grants while executing against whichever schema the caller picked. +- Change: make missing authority an `INTERNAL` error, keep one helper, and have tests inject an authority. Size S. + +### 13. Cell-by-key read path: primary-key check only accepts strings; field lookup is inconsistent +- Category: E Severity: low-medium Confidence: PLAUSIBLE (depends on how sealed rows encode integer keys) +- Where: `schema.rs:742-748, 760-766`; `compile/projection.rs:158-166, 436-438` +- What: a numeric key argument is stringified, then compared with `row.get(key).and_then(Value::as_str)`. A row whose key is a JSON number always fails with "does not match request", surfaced as `INTERNAL`. The policy evaluator looks up `field_name` then `column_name`; the projection looks up only the GraphQL field name. +- Change: compare using the column type (reuse `cell_values_equal`) and use one lookup helper. Size S. + +### 14. `query_protocol.rs` (1.8k) does three jobs; `schema.rs` (1.4k) does four +- Category: F Severity: low-medium Confidence: CONFIRMED +- Where: `query_protocol.rs:41-540` (build-time projector topology), `542-918` (snapshot execution and evidence), `920-1440` (live-resume cursor and wire assembly); `schema.rs:27-387` (schema construction), `725-865` (root and cell execution), `884-959` (error mapping), `1068-1200` (command and status resolvers) +- What: each file mixes build-time compilation with request-time execution. `query_protocol.rs` also has nine `.expect("comparable … plans retain …")` on request paths (803, 807, 966, 970, 1025, 1029, 1102, 1247, 1251), guarding an invariant held in two `Option` fields. +- Change: split into `query_protocol/{topology,execute,live}.rs` and `schema/{build,resolve,errors,commands}.rs`. Make the index plan carry a `ResumableProjector { partition, epoch }` so the `expect`s disappear. Size M, mechanical. + +### 15. Aggregate compilation is copy-pasted between root and relationship; the list template appears six times +- Category: C Severity: low Confidence: CONFIRMED +- Where: `compile/projection.rs:668-781` vs `compile/relationship.rs:68-204`; list templates at `projection.rs:592, 757`, `relationship.rs:179, 319, 331, 405` +- What: the `aggregate`/`count`/`nodes` match (validation, where, limit/offset binds, evidence) is duplicated, differing only in FROM and join predicate. `compile_where` is re-run, and binds duplicated, for each of `count` and `nodes`. +- Change: falls out of finding 2's `ModelScan`: one `compile_aggregate(scan, selection)` and one `compile_list(scan, selection)`. Size M (with 2). + +### 16. Dead code and vestigial API +- Category: F Severity: low Confidence: CONFIRMED (rg over the whole repo found only definitions and re-exports) +- Unused: + - `compile_list_sql_for_test` (`compile/projection.rs:1279`) + - `dialect_name` (`execute.rs:342`) + - `ReadPermission::allowed_columns_for` (`permissions.rs:101`) + - `core_sdl_for_catalog` (`engine/mod.rs:102`, `engine/validation.rs:170`) + - `graphql_sdl_from_schemas` (`sdl.rs:635`) + - `role_grants_for_role` (`surface/application.rs:64`) + - `QueryProtocolRuntime::is_empty` (`query_protocol.rs:243`) +- No-ops and stale attributes: + - `filter.visit_columns(|col| { let _ = col; })` (`engine/validation.rs:56-58`) + - Empty `if` body in `sdl_for_role` (`engine/public_api.rs:26-28`) + - `let _ = primary;` (`execute.rs:23`) + - `#[allow(dead_code)]` on `max_complexity`, which is used (`engine/core.rs:247`); on `introspection_for_anonymous`, which I did not rg (`:255`); and blanket `#[allow(unused_imports)]` in `compile/mod.rs:27-37` +- Pure aliases: + - `client_application_surface` just calls `…_with_schema_roles` with the same three arguments (`engine/builder.rs:349-356`) + - `surface_for_application` just calls `…_contract`, used only by tests (`surface/application.rs:566-580`) +- Change: delete; keep one name per pair. Size S. + +### 17. Golden SHA-256 hashes of whole SDL and manifest artefacts +- Category: B Severity: low-medium Confidence: CONFIRMED +- Where: `engine/tests.rs:532, 1416, 1551, 1997-2022`, asserted at `1954-1966` +- What: `sqlite_restricted_admin_full_artifact_matrix`, `postgres_restricted_admin_full_artifact_matrix`, `one_role_surface_drives_runtime_sdl_manifest_and_limits` and others compare hashes of the full manifest JSON, static SDL and runtime SDL to hard-coded constants (12 in the matrix alone). +- Why it matters: any intentional change, including async-graphql's SDL whitespace, fails with two opaque hashes and no diff. The fix is always "paste the new hash", so they detect change but not incorrectness. The structural assertions just above them (`definition_inventory` parity, root sets, field sets) are the valuable part. +- Change: drop the hashes, or replace with reviewable snapshot files. Keep one test that the fingerprint is stable across two builds. Size S. + +### 18. A test that only tests SQLite +- Category: B Severity: low Confidence: CONFIRMED +- Where: `engine/tests.rs:2507-2520`, `sqlite_nocase_can_equate_unequal_code_unit_strings` +- What: runs `SELECT 'A' = 'a' COLLATE NOCASE` and asserts 1, then `assert_ne!("A","a")`. No framework code is exercised. +- Change: delete, or replace with a test that the engine's `order_by` and `_eq` use binary collation. Size S. + +### 19. Behavioural RBAC gaps +- Category: B (inverse) Severity: medium Confidence: PLAUSIBLE (searched `tests/graphql_*` and in-slice tests by name and grep, not exhaustively) +- What exists: list, by-pk and root-count row isolation (`tests/graphql_harden/authz.rs:15, 57, 97`); column allowlist at root and nested (`:130, :169`); relationship-`where` applying the target policy (`engine/tests.rs:2299`); ungranted nested target (`tests/graphql_harden/residual.rs:14, 85`). +- What I could not find, executing with seeded rows: + - Multi-role application surface with differing row filters (finding 1). + - Nested has-many, many-to-many and belongs-to projection where the target has a row policy; only `where` is covered. + - `_aggregate { count nodes }` under a target row policy. + - Root `_aggregate { nodes }` under a row policy. + - Role `limit()` actually clamping rows. + - A cross-dialect run of the authorisation suite; it is SQLite-only and `tests/graphql_postgres/main.rs` is 63 lines. +- Change: one table-driven suite, access path × {row policy, column policy}, run on both dialects. Size M. + +### 20. Static SDL emitter and dynamic schema builder are two renderings held together by parity tests +- Category: C Severity: low Confidence: CONFIRMED (deliberate per `mod.rs:3-6`) +- Where: `sdl.rs:148-633` vs `schema.rs:27-685`; same-named helpers `command_shape_uses_type_name`/`command_type_uses_name` at `sdl.rs:356-374` and `schema.rs:425-441` (bodies compared only on the `schema.rs` side); parity tests at `engine/tests.rs:1323-1336, 1827-1833` and `schema.rs:1306` +- What: every schema feature is implemented in the Surface IR, `sdl.rs`, `schema.rs` and the client manifest. The reason is that the CLI emits SDL without the `graphql` feature. +- Change: keep both, but move the shared naming and collision helpers into `surface` or `naming`, and express "what types and fields exist" once as an iterator over the Surface that both renderers consume. Size M. Do not merge the renderers. + +### 21. Small allocations on the compile hot path +- Category: D Severity: low Confidence: CONFIRMED +- Where: `compile/projection.rs:524, 897, 968`; `compile/filter.rs:376` +- What: every permission lookup builds `(model.to_string(), role.to_string())` because the map key is `(String, String)`. Column lookups are linear `find`s per selected field. Each request recompiles from scratch; because the `where` shape comes from variables, plans are not trivially cacheable. +- Change: resolve once to a per-privilege `&BTreeMap` (free with finding 3). No plan cache. Size S. + +## Answers to the slice questions + +- **RBAC in one place?** No. One predicate function, nine call sites, plus implicit reliance on the per-role schema (finding 2). One confirmed bypass exists (finding 1). +- **Injection surface:** clean for client input. Aliases are checked by `validate_response_key`, values are binds, `_icontains` escapes wildcards, and order direction is mapped to fixed tokens. Identifiers are quoted without escaping and come from developer-declared `TableSchema`; `validate_generated_names` covers only exposed models (`engine/validation.rs:7`). That is acceptable, since the developer is trusted. +- **Intermediate representations:** + - *Per request:* document → async-graphql AST and `SelectionField` → `SelectionNode` → `SqlPlan` (SQL, binds, parallel `QueryEvidencePlan`) inside `QueryPlan::{Sql, CellByKey}` → JSON → `async_graphql::Value`. + - *Build time:* `TableSchema` → catalog `Surface` → role or application `Surface` → {dynamic schema, static SDL, manifest}. + - *Redundant or parallel:* `ReadPermission` vs `RoleGrant`; plain vs protocol executors; the plan-capture mode. There is no separate Postgres-vs-SQLite compiler. +- **Does the query layer write?** Not in anything I read (`SELECT`, `SET LOCAL`, `pg_is_in_recovery()` only). Mutations go to `SharedCommandHost::invoke`. +- **Tests asserting SQL strings?** Essentially no, on the counts I took: 14 and 1 `contains(` assertions in the two engine test files, 69 in `surface/tests.rs` (mostly error-message and SDL field-presence checks, judged from test names and grep, not from reading bodies). The low-value pattern is the golden hashes (finding 17). + +## Things that are good and should not be changed + +- One compiler with a `DialectOps` table rather than per-backend compile paths, producing one statement per root field through correlated JSON subqueries. +- Client values are always bind parameters; response keys and identifiers are validated before being embedded; compile errors are sanitised before reaching the client. +- Fail-closed defaults: `strict_where: true`, deny-by-default `read()`, an always-appended primary-key tiebreak with binary collation for deterministic pagination, and SQL three-valued logic preserved in `cell_row_matches`. +- Relationship `where` compiles the full target `compile_where`, so the target's row policy applies (`compile/filter.rs:387-401`), and it has a behavioural test. +- The role `Surface` as the single input to the runtime schema, SDL and manifest, with crate-private fields and a redacting `Debug` impl; and the per-role schema selected by the same `ExecutionAuthority` that the compiler uses. diff --git a/docs/reviews/v5-pre-release/05-graphql-live-manifest-identity.md b/docs/reviews/v5-pre-release/05-graphql-live-manifest-identity.md new file mode 100644 index 000000000..4a36c9c0d --- /dev/null +++ b/docs/reviews/v5-pre-release/05-graphql-live-manifest-identity.md @@ -0,0 +1,231 @@ +## Assessment — GraphQL layer part 2 (live delivery, deltas, manifest, identity) + +**Overall health:** the security-sensitive core is careful and mostly fail-closed. The slice is weakest in three places: + +1. **Identity defaults and modes.** The engine defaults to trusting client headers; `Hybrid` trusts headers whenever the bearer is absent; WS query-string identity is merged in every mode; JWKS refresh has no failure backoff. +2. **Row policy has four interpreters.** The one used for command deltas has wrong NULL semantics. +3. **The client wire contract is hand-maintained in five or more places.** The CLI does not depend on the core crate, so ~4k lines of Rust mirror types plus ~3k lines of TS validators restate it. + +Live queries share the one-shot RBAC path (compile once, full re-execution), so they cannot leak rows or columns. The cost is one full query per subscriber per table-level change, with no sharing and no caps. + +**Read fully:** `subscribe.rs`, `http.rs`, `execute.rs`, `commands.rs`, `identity/{mod,gateway,claims,resolve}.rs`, `identity/oidc.rs` 1–760, `engine/{auth,delivery,live_resume,request}.rs`, `protocol/token.rs`, `delivery/mod.rs`, `projection_delta/{mod,authorization}.rs`, `client_manifest/{mod,capabilities}.rs`, the four docs. + +**Read in part:** +- `projection_delta/runtime.rs`: 1–420, 1440–1570, 1795–2085, plus the `manifest()` call sites +- `projection_delta/types.rs`: type declarations and `DeltaValue::validate` only +- `projection_delta/{lower.rs 36–130, canonical.rs 1–80}` +- `protocol/accumulator.rs`: 80–300, 920–1060 +- `delivery/versions.rs`: 1–330 +- `client_manifest/projections.rs`: 584–700, 1265–1372 +- `client_manifest/export.rs`: 1–200; `validation.rs`: 1–48 +- `leaderboard_roots.rs`: 255–491; `read_store.rs`: 1–140 +- `schema.rs`: 300–345, 1067–1205; `compile/projection.rs`: 178–200, 326–500; `compile/filter.rs`: 70–135 +- CLI `projection_delta/wire.rs` (parts) and `manifest/types.rs` (head); TS `projection-delta/{types,validate}.ts` (outline and float code) + +**Not read:** +- `runtime.rs` 420–1440 and 1570–1795; `lower.rs` 130–1209; `canonical.rs` 80–724 +- `protocol/{types,projection_metadata}.rs` +- `client_manifest/{build,codec,commands,identity,limits,types}.rs` and the rest of `validation.rs` +- `complexity*.rs`, `filter.rs`, `naming.rs`, `permissions.rs`, `sdl.rs` +- `leaderboard_roots.rs` 1–255; `oidc.rs` 760–929 +- Test bodies beyond the samples cited below +- `docs/session-refresh-continuity.md` and `docs/compact-projection-contracts.md` describe `js/sveltekit` and `src/application`, which are outside this directory; neither was verified against code. + +--- + +### 1. WS identity query params are merged into headers in every identity mode +- Category: E Severity: high Confidence: CONFIRMED +- Where: `src/graphql/http.rs:546-547`, `745-767`; `http.rs:627-642`; `identity/resolve.rs:351-357`, `465-467` +- What: `graphql_ws_upgrade` always calls `merge_identity_query_params`, which copies `?x-user-id=` and `?x-roles=` from the URL into the header map when those headers are absent. In `Hybrid`, `resolve_ws_identity` clones those headers and, with no bearer in `connection_init`, falls into `hybrid_proxy_session`, which builds the session from all headers. The doc comment at `http.rs:483` says query params are a DevHeaders convenience. +- Why it matters: a gateway that strips client `x-user-id`/`x-roles` headers but forwards the URL lets any client assert identity and roles for live reads via `wss://…/graphql/ws?x-user-id=admin&x-roles=admin`. +- Change: apply the merge only when `mode == DevHeaders` (or delete it; GraphiQL already uses `wsConnectionParams`). Size S. + +### 2. `Hybrid` trusts all headers when no bearer is present; `TrustedProxy` can never carry identity +- Category: F/E Severity: high Confidence: CONFIRMED +- Where: `identity/resolve.rs:81-87`, `340-357`, `10-17`; `tests/graphql_identity/main.rs:367` and `431` +- What: `IdentityConfig::hybrid(oidc)` uses `TrustedProxyConfig::with_defaults()`, whose `gateway_secret_header` is `None`. A request without `Authorization` therefore gets `session_from_all_headers`. Test `f6_hybrid_missing_bearer_trusts_proxy_headers` pins this. Conversely `TrustedProxy` checks the optional secret and then strips `x-user-id`/`x-roles` even from the proxy, so it always yields an anonymous session. The enum doc ("configure gateway secret then trust") describes behaviour the code does not have. +- Why it matters: `Hybrid` is DevHeaders for anyone who omits the token unless the operator knows to set a secret. `TrustedProxy` is misnamed, and its secret buys nothing. +- Change (breaking): collapse to three modes — `OidcBearer`, `Gateway { secret }` with the secret required, and `DevHeaders`. Remove `Hybrid`'s secretless path and the strip-list configuration. Size M. + +### 3. Engine default identity is `DevHeaders` +- Category: E/F Severity: high Confidence: CONFIRMED +- Where: `engine/builder.rs:40`; `identity/resolve.rs:31-32`, `61-69` +- What: a `GraphqlEngine` built without `.identity(..)` trusts client `x-user-id`/`x-roles` for read RBAC. Only the generated scaffold opts into OIDC. Leaderboard "viewer" roots read the member from this same session. +- Why it matters: fail-open default on the RBAC boundary. Mutations are safe because they require a `VerifiedPrincipal`. +- Change (breaking): no `Default` for `IdentityMode`/`IdentityConfig`. Either make `.identity()` mandatory at build, or default to OIDC with the unset placeholder that `public_oidc_identity_from_env_vars` already uses. Size S. + +### 4. Row policy is interpreted four ways; the delta one has wrong NULL and numeric semantics +- Category: C/E (principle 4) Severity: high Confidence: CONFIRMED +- Where: `projection_delta/runtime.rs:1963-2067`; `compile/projection.rs:334-496`; `compile/filter.rs:84-118`; `js/src/replica/query-plan/filter.ts:500-518` +- What: the same `FilterExpr` is evaluated by the SQL compiler, by `evaluate_cell_filter` (typed, three-valued, NULL is unknown), by `evaluate_filter` for command deltas, and by the TS replica. The delta evaluator uses raw JSON equality: `CmpOp::Neq => Some(left != &right)`. + - A row whose policy column is NULL under `status <> 'x'` is denied by SQL but `Authorized` here. + - `Not(Eq)` on a NULL column and `Eq` against `Lit(Null)` also evaluate to true. + - A `Float` column against an `I64` literal never compares equal, so `Neq` is always true. +- Why it matters: an `Authorized` after-state lowers to an `Upsert` carrying all granted columns. A command can therefore push into the caller's replica a row that the one-shot query would never return. +- Change: one `FilterExpr::evaluate(schema, row, claims) -> Truth` in `filter.rs`, typed by column like the cell version. Delete `evaluate_filter`/`policy_operand`. Add a parity test table run against SQL and this evaluator, ideally exported as vectors for the TS one. Size M. + +### 5. JWKS refresh has no failure backoff or stale-if-error +- Category: E/D Severity: high Confidence: CONFIRMED +- Where: `identity/oidc.rs:373-379`, `415-445`, `476-488` +- What: once the 300s TTL passes, `ensure_jwks` calls `refresh_jwks` under an async mutex. On HTTP failure nothing is recorded (`refreshed_at` and `generation` are unchanged) and the request returns `Err(Jwks)`, which becomes 401. The next waiter takes the lock and repeats its own fetch with a 5s timeout, plus another 5s if discovery is not cached. +- Why it matters: during an IdP outage every authenticated request queues serially behind 5–10s timeouts and then fails, even though valid cached keys exist. Single-flight only deduplicates successes. +- Change: on failure keep serving the cached keys and record `last_failed_refresh` with a backoff. Fail only when there are no keys at all. Size S. + +### 6. Origin WebSocket subscriptions outlive the token and have no keepalive or caps +- Category: E/D Severity: medium Confidence: CONFIRMED +- Where: `http.rs:581-613`; `subscribe.rs:107-139`; `identity/oidc.rs:182` +- What: session and principal are fixed at `connection_init`, and the plan (with claim binds) is compiled once. `VerifiedPrincipal::expires_at` is consulted only in `engine/delivery.rs:105` and under `src/gateway`. Without a gateway `GraphqlConnectionGuard`, `serve.await` runs unbounded. No `keepalive_timeout` is set and nothing limits subscriptions per connection or globally. +- Why it matters: a revoked or expired user keeps receiving live frames with stale claims indefinitely. Half-open sockets keep producers alive, because a hash-gated producer never writes. One connection can open unlimited live queries. +- Change: bound the socket by `min(exp, max lifetime)` on the origin as well. Set a keepalive. Add `max_live_queries_per_connection`. Size S–M. + +### 7. Live delivery costs one full query per subscriber per table-level change +- Category: D Severity: medium Confidence: CONFIRMED +- Where: `subscribe.rs:128-224`, `305-311`, `319-344`; `execute.rs:215-240`; `leaderboard_roots.rs:402-446` +- What: + - Footprint is a set of table names, so a write to another tenant's `todos` row wakes every subscriber on `todos`. + - All subscribers sleep the same fixed 100ms and then re-execute at the same instant, with no concurrency limit and no sharing between identical (plan, binds) subscriptions. + - On Postgres each refresh is `BEGIN`, `SET LOCAL`, the query, `COMMIT`, plus `pg_is_in_recovery()` under `gateway-delivery`. + - The result is serialized to a JSON string solely to hash it. +- Why it matters: N subscribers produce an N-query burst on the shared pool per write burst, starving one-shot queries. Buffers themselves are bounded (mpsc 8, broadcast 256 with lag treated as all-dirty) and tasks do stop on `tx.closed()`. +- Change: a registry keyed by (role, plan SQL, binds) that executes once and fans out; a semaphore on live refreshes; hash the value directly. Size M. + +### 8. The client wire contract is re-described in at least five places +- Category: C (principle 5) Severity: high Confidence: CONFIRMED +- Where: + - `src/graphql/projection_delta/types.rs` (1256 lines) + - `distributed_cli/src/client_compiler/projection_delta/wire.rs` (1015 lines; header says "compiler-owned mirror of the frozen wire contract" and carries `#![cfg_attr(not(test), allow(dead_code))]`; only the version constant is used, at `preview.rs:747`) + - `js/src/replica/projection-delta/types.ts` (425) and `validate.ts` (2589) + - `src/graphql/client_manifest/types.rs` (74 types) versus `distributed_cli/src/client_compiler/manifest/types.rs` (90 types, 1149 lines) plus `manifest/model_validation.rs` (1609) +- What: `distributed_cli/Cargo.toml` has no dependency on `distributed`, so every shape, bound and canonical-number rule is hand-copied. The F64 canonical check exists at `types.rs:709-721`, `wire.rs:400-413` and as a re-implementation of serde_json float formatting in `validate.ts:2520` (`rustRyuFloat`). The only cross-check is one golden file, `tests/fixtures/projection-delta-v1.json`. +- Why it matters: every wire change is a three-language edit guarded by a single fixture, and the CLI mirror is dead code outside tests. +- Change (breaking for the build graph): move the pool-free contract types (`client_manifest`, `projection_delta::types`, `protocol` types) into a small crate that the CLI depends on, and delete the CLI mirrors. Generate the TS types and validators from those types, or ship generated vectors for every variant instead of one golden. Size L. + +### 9. The projection value/kind enums are copied 1:1 inside the core crate +- Category: C/F Severity: medium Confidence: CONFIRMED +- Where: `client_manifest/projections.rs:1269-1343`; `projection_delta/types.rs:629-676`; `projection_delta/runtime.rs:1458-1500` +- What: `ProjectionValue` is converted to `ClientProjectionValue`, `DeltaValue` and `serde_json::Value` by three hand-written matches. `ProjectionMutationKind` to `ClientProjectionMutationKind` is an identity mapping over eight variants. `ProjectionValueType` and `ProjectionEnvelopeField` have the same treatment, the latter with `unreachable!` arms. +- Why it matters: these are parallel types that exist only to attach serde attributes. Adding a variant means editing each copy. +- Change: give the core projection enums the wire serde representation and use them directly in the manifest and delta. Size M. + +### 10. Request paths still deep-clone the whole client manifest +- Category: D Severity: medium Confidence: CONFIRMED +- Where: `client_manifest/export.rs:122-124`; `projection_delta/runtime.rs:534`, `586`, `769`, `1546`, `1636`, `1649`, `1738`; `projection_delta/lower.rs:39`, `67-69` +- What: `manifest()` is `manifest_ref().cloned()`. `try_new` at 1546 clones and immediately drops it, just to check `is_ok`. `verify_partition_token` at 1738 clones it to compare the surface identity. `ProjectionDeltaAuthority` stores an owned copy per lowering. +- Why it matters: this is the same hot spot `docs/protocol-manifest-reuse.md` set out to remove ("request seeds may borrow their compiled manifests"). Only line 108 borrows. +- Change: use `manifest_ref()` at all eight sites and hold `&DistributedClientManifest` in `ProjectionDeltaAuthority`. Size S. + +### 11. Gateway version triggers serialize all writers on one counter row per table +- Category: D Severity: medium Confidence: PLAUSIBLE (read from SQL, not measured) +- Where: `delivery/versions.rs:196-228`, `13-28` +- What: `install_sql` adds a per-statement trigger running `UPDATE distributed_gateway_versions SET version=version+1 WHERE namespace=… AND table_name=…` on every covered table and on all 14 `PROOF_TABLES` (including `projection_changes` and `projection_records`). +- Why it matters: concurrent transactions touching the same table block on that row until commit. Since every projector writes the proof tables, enabling gateway caching likely serializes projection commits. +- Change: derive versions from an existing monotonic source such as the projection change cursor, or use a sequence. Size M. + +### 12. `PROOF_TABLES` hard-codes the projection store's schema inside `graphql/delivery` +- Category: A/C Severity: medium Confidence: CONFIRMED +- Where: `delivery/versions.rs:13-28`, `197-201`; `engine/delivery.rs:130`, `143` +- What: the GraphQL layer keeps a literal list of `projection_*` table names. A table added by the projection store is silently uncovered and cached envelopes go stale. The same module also includes a file under `migrations/postgres/` for SQLite, detects plan capture by comparing an error message to a sentinel string, and classifies errors with `error.starts_with("dependency ")`. +- Change: have the projection store export its evidence table list; return the captured plan through a typed channel; use an error enum. Size S–M. + +### 13. Two copies of the live producer loop +- Category: C Severity: medium Confidence: CONFIRMED +- Where: `subscribe.rs:91-228`; `leaderboard_roots.rs:385-446` +- What: both define `LiveItem`, an mpsc(8) stream wrapper, "initial, wait for matching change, sleep 100ms, drain, re-execute, hash-gate, terminal on error". They have already drifted: the SQL loop returns on `TryRecvError::Closed` while the leaderboard loop does not. +- Change: one `live_refresh_stream(hub, matches, execute)` generic over the executor. Size S. + +### 14. `test_oidc` mints production principals and can panic +- Category: E/F Severity: medium Confidence: CONFIRMED +- Where: `identity/oidc.rs:133-168`; callers `src/microsvc/wait_path.rs:70`, `src/schedule/worker.rs:192` +- What: `from_trusted_transport` calls `test_oidc`, which is documented as test-only and contains three `assert!`s. It stamps a fake issuer `https://distributed.local/wait-path`. +- Why it matters: a constructor described as impossible ("no constructor from a Session or header map") exists and is used at runtime. It also contradicts `resolve.rs:490`'s test that ambient identity never mints a principal. +- Change: an explicit `VerifiedPrincipal::internal(subject) -> Result` variant with its own provenance; gate `test_oidc` behind `cfg(test)` or a test feature. Size S. + +### 15. Claim mapping special-cases Zitadel and cannot map custom claims +- Category: A/F Severity: medium Confidence: CONFIRMED +- Where: `identity/claims.rs:63-72`, `84-89`, `97-107`, `115-126`; `identity/oidc.rs:751` +- What: the generic mapper always scans `urn:zitadel:iam:org:project:*:roles`, silently grants `user` when no role matched, and copies only `email` and `org_id`/`orgId` to `x-email`/`x-org-id`. There is no configurable claim-to-session mapping, so a row policy such as `claim("x-tenant-id")` cannot be satisfied in OIDC mode. `claim_path` is duplicated as `claim_at_path`. +- Change: `ClaimMapConfig { session_claims: Vec<(claim_path, session_key)>, default_role: Option }`; move the Zitadel scan into a preset; one path helper. Size S. + +### 16. Secret comparison is not constant-time, and it leaks into the session +- Category: E Severity: low-medium Confidence: CONFIRMED +- Where: `identity/resolve.rs:333` (`if got != expected`); `identity/mod.rs:25-33` +- What: the secret is compared with string inequality. `session_from_all_headers` then copies every header into `Session`, including the gateway secret, `authorization` and `cookie`, and that session is passed on to command dispatch. +- Change: `subtle::ConstantTimeEq`; drop credential headers when building the session. Size S. + +### 17. Public identity helpers rebuild the validator per call +- Category: D/F Severity: low-medium Confidence: CONFIRMED +- Where: `identity/resolve.rs:359-367`, `434-441`, `479-482`; `identity/oidc.rs:34`, `498-513`, `279-281` +- What: `resolve_session` builds a new `IdentityResolver`, validator and `reqwest::Client` on each call, so there is no JWKS cache at all. `resolve_session_sync` re-parses the static JWKS each call. `alg_allowlist: Vec` can only ever narrow RS256/ES256 because other algorithms are rejected by the match. `is_anonymous_identity` and the JWK `use_` field are `#[allow(dead_code)]`. +- Change: keep `IdentityResolver` as the only entry point; remove both free functions and the dead items. Size S. + +### 18. HTTP glue triplication and dead statements +- Category: C/F Severity: low Confidence: CONFIRMED +- Where: `http.rs:378-461`, `228-301`, `398`, `449-451`, `692-717`, `769-803`; `subscribe.rs:54-60`; `execute.rs:23`, `341` +- What: + - Three near-identical POST handlers and five router constructors; `graphql_router_with_dispatcher` only forwards. + - `let _ = engine.identity_config().mode == IdentityMode::DevHeaders;` does nothing. + - `.expect("graphql route mounted without engine")` on a request path. + - The non-DevHeaders branch of `session_from_connection_init` is reachable only for `TrustedProxy` and sets a session key `authorization`. + - A hand-rolled percent decoder decodes bytes as Latin-1. + - `ChangeHub::publish` has an empty `if` body; `execute_sql_on_pool` has `let _ = primary;`; `dialect_name` is dead. +- Change: one handler over `(engine, Option, Option)` and one router builder. Size S. + +### 19. Live frame metadata travels in a side FIFO separate from the value +- Category: E/F Severity: low-medium Confidence: CONFIRMED (design hazard, no bug found) +- Where: `protocol/accumulator.rs:95`, `926-947`, `1018-1036`; `subscribe.rs:9-14` +- What: the producer pushes an envelope onto `stream_frames` and then sends the value through mpsc. `attach` pops by position and falls back to the base envelope when the queue is empty. The module comment explains failures must be terminal precisely because of this coupling. The accumulator also has seven mutexes and five copies of "lock seed, clone, clone cache_scope" (135–270). +- Change: carry the envelope with the value (for example, wrap the yielded value and unwrap it in the `execute_stream` map). Size M. + +### 20. No behavioural test for the non-`Eq` paths of delta row policy or for SQL parity +- Category: B Severity: medium Confidence: CONFIRMED +- Where: `projection_delta/tests.rs:485` (`production_predicate_authorizes_only_complete_actual_after_rows`) +- What: only `owner = claim` is exercised. A search of the file for `Neq`, `IsNull` and `evaluate_filter` finds nothing. No test covers the expired-token WS case (#6) or the query-param merge under non-Dev modes (#1); `http.rs` tests only cover DevHeaders parsing. +- Change: add them with the fixes for #1, #4 and #6. + +### 21. Test duplication and weak negative assertions +- Category: B Severity: low Confidence: CONFIRMED +- Where: `projection_delta/tests.rs` versus `vector_tests.rs`; `client_manifest/tests.rs` +- What: + - Four tests in `tests.rs` are strict subsets of `vector_tests.rs`: `strict_decode_rejects_unknown_wire_fields` (65) ⊂ vector 240; `authoritative_zero_actual_occurrences_is_valid_and_deterministic` (74) ⊂ 218; `tagged_values_distinguish_null_absent_and_unset_and_bound_numbers` (131) ⊂ 381; `value_depth_key_partition_and_body_limits_fail_closed` (165) ⊂ 544. + - Several tests are 290–330 lines each, e.g. `wait_path_observation_proof_requires_the_persisted_semantic_program_identity` (1155), `active_metadata_revalidates_but_remains_queryable_while_projection_is_draining` (1718) and `lifecycle_status_rejects_changed_deployment_identity_and_mixed_fanout_tampering` (2019). + - `users()`/`todos()` table fixtures are redefined in both test files. + - Leak checks are `!json.contains("user_id")`-style at `client_manifest/tests.rs:603-605`, `945-947`, `2419-2421`; they pass vacuously if a field is renamed. +- What is fine: both suites otherwise assert behaviour (authorization matrices, tamper rejection, determinism), not exact JSON. Exact bytes are asserted only for the deliberate golden vector. +- Change: delete the four subsumed tests; share fixtures; pair each negative `contains` with a positive assertion that the public counterpart is present. Size S. + +### 22. Work-in-progress scaffolding left in the delta module +- Category: F Severity: low Confidence: CONFIRMED +- Where: `projection_delta/mod.rs:14-18`; `authorization.rs:123-134`; `lower.rs:46`; `protocol/accumulator.rs:408`, `461`, `505`, `972`; `client_manifest/build.rs:5`, `mod.rs:52` +- What: `#[allow(dead_code, reason = "Task 11 …")]` markers and four dead-code-suppressed accumulator methods. `ProjectionAuthorization`, `ProjectionPartitionScopeEncoder` and `ProjectionDeltaRequestAuthority` each have exactly one production implementation, and `SelectedSurfaceAuthorization<'a, R, R>` is instantiated with the same type twice. `SelectedSurfacePolicyVisibility` survives only to serve `relationship_transition`. +- Change: collapse the three traits into the concrete `ProtocolProjectionDeltaRequestAuthority` (tests construct it with a test codec) and delete the suppressed items. Size M. + +### 23. Audience check accepts `azp`/`client_id` when `aud` is absent or `"account"` +- Category: E Severity: low Confidence: CONFIRMED (deliberate, documented in code) +- Where: `identity/oidc.rs:636-704` +- What: any token issued to the configured client is accepted regardless of its intended resource server. Everything else in the validator checks out: HS* and `none` are rejected, the key type is tied to the algorithm, `iss`/`exp`/`nbf` are checked with 60s leeway, and `token_use` and `sub` are enforced. +- Change: make the fallback opt-in (`accept_authorized_party: bool`, default false). Size S. + +### 24. Multi-role application surface keeps the first role's row filter when filters differ +- Category: E Severity: low Confidence: CONFIRMED (in part 1's directory; flagged because it is authorization) +- Where: `engine/auth.rs:219-227` +- What: both branches of the `if` return `first.row_filter.clone()`, and the comment contradicts itself. Columns are intersected across roles, but rows follow whichever role sorts first. +- Change: AND the filters, matching the intersection semantics used for columns, or reject differing filters at build. Size S. + +--- + +### Answers to the slice questions not covered above +- **RBAC on live frames:** same code path as one-shot. `compile::compile_query` runs with the session at subscribe time and every refresh is a full re-execution, so there are no row-level live deltas and nothing can leak when a row leaves the permitted set. Resumable cursors are offered only when every owning projector's models are `Unrestricted` (`client_manifest/capabilities.rs:62-96`), which matches `docs/live-query-delivery.md`. The gap is claims changing mid-session (#6). +- **Command proxy:** clean. `resolve_command` (`schema.rs:1067-1138`) reads the input and `commandId`, requires a `VerifiedPrincipal`, calls `host.invoke`, records the receipt and returns the payload. No writes or side channels. +- **Protocol tokens:** HMAC-SHA256 with domain separation and `verify_slice`, so comparison is constant-time (`protocol/token.rs:202-206`). + +### Where code and docs disagree +- `docs/protocol-manifest-reuse.md` says seeds borrow compiled manifests; eight runtime sites still deep-clone (#10). +- `http.rs:483` and the `IdentityMode` docs describe query-param identity as DevHeaders-only and `TrustedProxy` as "configure secret then trust"; the code does neither (#1, #2). +- `docs/live-query-delivery.md` calls the leaderboard member claim "verified"; under the default identity mode it is a client header (#3). + +### Things that are good and should not be changed +- Mutations as pure dispatch through `SharedCommandHost`, with `Arc` kept out of request data and durable commands requiring a `VerifiedPrincipal`. +- Opaque, purpose-separated HMAC protocol tokens with no plaintext payload, and the strict bounded parsers (`deny_unknown_fields`, canonical-bytes round trip, 128-item and 64-depth limits). +- Live queries as hash-gated full re-execution through the one-shot compiler, with terminal failure frames and lag treated as all-dirty. Optimise by sharing executions, not by adding a second delta path. +- `DistributedClientSurfaceExport` deriving identity from the selected Surface and caching the manifest in a `OnceLock` shared across clones. +- Fail-closed visibility lowering (`Unknown` becomes model recovery, never keyed operations) and the cross-language golden vector; extend the vectors, do not drop them. diff --git a/docs/reviews/v5-pre-release/06-service-runtime-write-path.md b/docs/reviews/v5-pre-release/06-service-runtime-write-path.md new file mode 100644 index 000000000..6d8892f38 --- /dev/null +++ b/docs/reviews/v5-pre-release/06-service-runtime-write-path.md @@ -0,0 +1,220 @@ +## Assessment + +The typed command path is sound at its core: one backend transaction commits events, outbox, read-model plans and the fenced ledger completion, and authoring is thin (examples use only `#[command]`). The problem is what surrounds it. The same pipeline is written three times, and a second unledgered, role-less "legacy JSON" write path is still the only thing bus, Knative and saga commands can reach. Several half-removed mechanisms (confirmations/obligations, the `CommandEffects` IR, the remote dispatcher, direct-projection terminals) are still threaded through hot-path code. + +The three changes most worth making: +1. Collapse the three typed pipelines in `routes.rs` (and the parallel helper set in `cell_host/causal.rs`) into one, and split `routes.rs`. +2. Make it one write path: delete `RegisteredHandler::Legacy`, `routes!` and `invoke_cell`, and let bus and saga commands reach typed, ledgered commands through an explicit trusted-ingress principal. +3. Delete the vestigial contract machinery and the dead half of `command_dispatch/`; compute the contract fingerprint once at bind time. + +Not read or only skimmed (all paths under `/Users/patrickleet/dev/hops-ops/hops/distributed/src/`): +- **Not read:** `microsvc/projector/*`, `microsvc/cell_host/{store,sql_store,sql_executor,celld_outbox,wire,internal_auth,command}.rs`, `microsvc/{context,session,error,descriptor}.rs`, `command/{projections,direct_projection,projection_proof,effect_wire,types,tests}.rs`, `command_ledger/{ids,error}.rs`, `saga/{fan_out_tests,error}.rs`, the proc-macro expansion code in `distributed_macros`. +- **Outline or partial only:** `microsvc/service/tests.rs` and `command_ledger/tests.rs` (fn outline plus about six test bodies), `command_ledger/record.rs`, `microsvc/dependencies.rs`, `microsvc/cell_host/causal.rs`, `microsvc/causal.rs` tests (line 849 onward), `command/input.rs` after line 330, `microsvc/grpc.rs` wait-path middle section. +- **Docs:** the four docs were read early; only the disagreements listed in finding 22 were verified against code. +- **Line numbers:** those in `routes.rs`, `runtime.rs` and `handlers.rs` come from full reads; the load-bearing ones were re-opened at the end, and a few neighbouring ranges may be off by a few lines. + +## Findings + +### 1. The typed command pipeline is implemented three times +- Category: C/F Severity: high Confidence: CONFIRMED +- Where: `src/microsvc/service/routes.rs:1669-1917` (`dispatch_cell_causal`), `:1933-2343` (`dispatch`), `:2542-2598` (`invoke_cell`); helper twins at `src/microsvc/service/causal.rs:694-950` and `src/microsvc/cell_host/causal.rs:228-438` +- What: `dispatch_cell_causal` and `dispatch` are ~250-line near-copies of the same sequence, from admit and canonicalize through reserve, handler, `commit_causal_batch` and the ledger re-read. Each has about 15 hand-rolled `return abandon_causal_attempt(...)` blocks. The cell copy has its own `CellDispatchError`/`CellDispatchResult` and its own `handler_error_code`, `internal_ledger_error`, `replay_result`, `replay_rejection`, `commit_rejection`, `load_committed_result`, `abandon_attempt`, `recover_commit_error` and `resolve_ambiguous_lookup`, each mirroring a `service/causal.rs` function. +- Why it matters: every fix to the write path must be made twice or three times, and the copies have already diverged (findings 2 and 9). It also contradicts the owner's "no parallel types" preference. +- Change: one `execute_typed_command(ctx, reservation_source, terminal_policy)` returning one result/error type; cell and GraphQL differ only in how the result is rendered to wire and which terminal states are allowed. Delete `CellDispatchError`/`CellDispatchResult` in favour of `CausalDispatchError`/`CausalDispatchResult` plus a wire encoder (breaking for celld callers). Wrap the attempt in a guard so abandonment is one code path. L. + +### 2. `AggregateCell::dispatch` / `invoke_cell` runs typed commands with no roles, no ledger and no canonical input +- Category: A/E Severity: high Confidence: CONFIRMED +- Where: `src/microsvc/service/routes.rs:2542-2598`; public entry `src/microsvc/cell_host/cell.rs:209-226` +- What: `invoke_cell` skips the role check (`admit_command_session`/`ensure_causal_grant`), the ledger reservation and `canonicalize_command_input` (it uses plain `serde_json::from_value`). It stamps a random `Uuid::now_v7` causation and commits via plain `TransactionalCommit::commit_batch`. `rg` finds callers only in `src/microsvc/cell_host/tests.rs`. +- Why it matters: it is a public API that runs the same handler without the authorization and idempotency every other typed ingress enforces, and it exists only for tests. +- Change: delete `AggregateCell::dispatch` and `invoke_cell`; move the tests to `dispatch_idempotent`. Breaking, S. + +### 3. A second write path (legacy JSON handlers) is the only thing bus, Knative and saga commands can reach +- Category: A Severity: high Confidence: CONFIRMED +- Where: `src/microsvc/service/routes.rs:159-166` (`RegisteredHandler::Legacy`), `:1557-1561`; `src/microsvc/mod.rs:209` (`routes!`); `src/microsvc/http.rs` and `src/microsvc/grpc.rs:210` (fallback `service.dispatch`); `src/microsvc/message_router.rs:25-30`; `src/saga/definition.rs:62-63` +- What: `Service::dispatch`, `dispatch_request` and `dispatch_message` only run `Legacy` handlers. A typed command reached there returns `Unauthorized("typed causal commands require a verified GraphQL bearer envelope")`. Legacy handlers have no role declaration, no ledger and no input canonicalization, and they commit through the queued/locking repo rather than the causal workspace. Saga participant commands arrive over the bus, so they can only be legacy handlers; `SagaCommand::json` is documented as "what `microsvc` handlers decode with `ctx.input`". The saga's deterministic command id is never offered to the command ledger, so participants hand-roll dedupe (`docs/coordination-primitives.md:226-231`). +- Why it matters: two authoring models with different guarantees for the same concept. Principle 1's command step has an unaudited side door, and the framework's own coordination primitive cannot use the ledger. No file under `examples/` uses the legacy builder or `routes!` (0 hits; examples use `#[command]`). `routes!` matches in 24 test files and the legacy `.command("..")` builder appears on 12 lines under `tests/`. +- Change: + - Remove `RegisteredHandler::Legacy`, `Routes::command(name).handle`, `routes!` command arms and the fire-and-forget HTTP/gRPC body shape. + - Give trusted ingress (bus consumer, Knative, schedule worker) an explicit `VerifiedPrincipal::from_trusted_transport` and route commands through `CommandHost::invoke`, with the message id (saga command id) as the ledger command id. + - Event handlers and projectors stay as they are. + - Breaking, L. + +### 4. Confirmations/obligations machinery is vestigial but still on the hot path +- Category: F Severity: high Confidence: CONFIRMED +- Where: `src/command/typed_command.rs:131-238` (`resolve_projection_obligations*`, with `#[allow(dead_code)]` at 131); `src/microsvc/service/routes.rs:2122`, `:2220`, `:2701-2748`; `src/microsvc/service/causal.rs:1135-1232`; `src/command_ledger/state.rs:83-156`; `src/command_ledger/record.rs:574`; `src/command_ledger/reservation.rs:464` +- What: `TypedCommandContract.confirmations` is only ever non-empty in `src/command/tests.rs:530,590` (repo-wide `rg`; `typed_command()` sets `Vec::new()` and there is no builder). Yet dispatch still resolves obligations, checks "cannot mix modeled projection metadata with legacy confirmations", stores `projection_obligations` in the ledger and evaluates a separate legacy evidence branch on status. Validators in `state.rs` and tests such as `completion_rejects_malformed_projection_obligations` guard data production never writes. +- Why it matters: roughly a thousand lines of dead protocol in the most security-sensitive code, and readers must hold two projection-evidence models to follow dispatch. +- Change: delete `confirmations`, `CommandProjectionConfirmation`, `resolve_projection_obligations*`, `complete_with_obligations`, ledger `projection_obligations`, `CausalCommandProjectionObligation`, the legacy branch of `evaluate_pending_projection_evidence`, and the GraphQL `sanitize_/validate_command_confirmations`. Breaking for ledger row format, M-L. + +### 5. `CommandEffects` IR is dead: every contract is `CommandEffects::revalidate()` +- Category: F Severity: medium Confidence: CONFIRMED +- Where: `src/command/effects.rs:20-26` (`EffectExpression::InvalidConstant`, `#[allow(dead_code)]`, "no longer constructed after macro removal"); `src/command/typed_command.rs:491-519`; `src/command/effect_wire.rs` (341 lines, not read) +- What: `CommandEffect::*` variants and `CommandEffects::new` are constructed only in tests (`rg`). The contract still carries `effects`, fingerprints it, and validates `InvalidConstant` in `TypedServiceCommandBinding::from_contracts`. +- Why it matters: vestigial field plus wire format; `tests/legacy_authoring_absence.rs` asserts the macro is gone but the runtime half remains. +- Change: remove `effects` from the contract and delete `effects.rs`/`effect_wire.rs` (check the JS client for consumers of the wire shape first). Breaking, M. + +### 6. Half of `command_dispatch/` is unused scaffolding; two "dispatch" abstractions coexist +- Category: F Severity: medium Confidence: CONFIRMED +- Where: `src/command_dispatch/remote.rs`, `envelope.rs`, `local.rs`, `host.rs:695-721`; `src/application/runtime_host.rs:1-110` +- What: + - `CommandDispatcher` → `LocalCommandDispatcher::dispatch` calls `service.dispatch_request`, which returns 401 for every typed command. + - `RemoteCommandDispatcher`, `RemoteDispatchConfig`, `RemoteTrustMode`, `APPROVED_REMOTE_DISPATCH_PROFILE`, `CommandDispatchEnvelope` and `CommandDispatchReceipt` have no users outside the module and `lib.rs` re-exports. + - The only `RemoteCommandTransport` impl is `LoopbackRemoteTransport` (`#[allow(dead_code)]`). + - Envelope fields `command_fingerprint`, `idempotency_key`, `causation_id` and `deadline_unix_ms` are always `None`; `timeout_ms` is never read. + - `SharedCommandDispatcher` is stored but never called by `runtime_host.rs` ("skeleton (task 12)"). + - The real path is `CommandHost` (`LocalCommandHost`, `HttpCommandHost`), plus `impl CommandHost for LocalCommandDispatcher`, which builds a `LocalCommandHost` per call. +- Why it matters: public API that looks like the remote story but is inert; "which trait do I implement" has two answers. +- Change: keep `CommandHost` and its two impls only; delete `CommandDispatcher`, the remote dispatcher, envelope and receipt; `graphql/http.rs:832` takes a `LocalCommandHost` directly. Breaking, M. + +### 7. Contract fingerprint is recomputed on every dispatch and per handler on every status poll +- Category: D Severity: medium Confidence: CONFIRMED +- Where: `src/command/typed_command.rs:64-73`; callers `src/microsvc/service/routes.rs:1704`, `:1971`, `:2450`, `:2392`; status loops `routes.rs:2829-2867` and `src/microsvc/service/runtime.rs:962-984` +- What: `fingerprint_bytes()` calls `canonical_value()` each time. That clones roles, effects, defaults and projections, sorts with a serializing comparator, builds JSON, serializes and hashes. It runs once per command. On a status poll it runs once per causal handler in every route bundle, each followed by its own ledger lookup. +- Why it matters: avoidable allocation and SHA-256 on the hottest path, and status polling is O(routes × handlers) DB lookups for a command id that belongs to exactly one command. +- Change: compute the fingerprint once in `register_typed_handler`/bind and store `[u8; 32]` on the registered handler. For status, look the row up once by `(service, principal partition, command id)` and match its stored contract hash to a handler. S-M. + +### 8. Nothing compacts the command ledger +- Category: E/D Severity: medium Confidence: CONFIRMED +- Where: `src/command_ledger/traits.rs:63-68` (`#[allow(dead_code)] fn compact_expired_commands`) +- What: every backend implements it, but the only non-delegating call in the repo is the conformance test at `src/command_ledger/tests.rs:1186`. Rows live for 30 days by policy, then forever. +- Why it matters: one row per command ever issued, unbounded, on the table every command reads and writes. +- Change: run compaction from the existing framework worker (next to the outbox drain) with a bounded batch, or drop the method and document operator-owned retention. S-M. + +### 9. Attempts leak as `InProgress` on `?` after reservation +- Category: E Severity: medium Confidence: CONFIRMED +- Where: `src/microsvc/service/routes.rs:1873-1877`, `:1884`, `:2299` +- What: after the reservation is acquired, these `.map_err(...)?` returns exit without `abandon_causal_attempt`, unlike the ~15 sibling sites. +- Why it matters: the row stays `InProgress` until the 30-second lease expires, so a client retry with the same command id gets `InProgress` instead of an immediate re-run. +- Change: falls out of finding 1 (one abandon-on-error guard). S. + +### 10. Version conflicts on typed commands surface as a 500; the `locks` argument is unused on this path +- Category: E/F Severity: medium Confidence: CONFIRMED (code path) / PLAUSIBLE (client-visible impact) +- Where: `src/microsvc/service/routes.rs:2306-2341`; `src/microsvc/service/causal.rs:900-950`; `src/queued_repo/repository.rs:303-312` +- What: causal loads "deliberately bypass this wrapper's queue locks". A `ConcurrentWrite` from `commit_causal_batch` goes to `recover_causal_commit_error`, which marks the row retryable and returns `CausalDispatchError::Internal(detail)`. There is no in-process reload-and-retry, although `SagaRunner` does exactly that (`src/saga/runner.rs:108-118`). `Routes::for_aggregate(repo, locks, read_models)` still requires a lock manager that typed commands never use. +- Why it matters: two concurrent commands on one aggregate give one success and one INTERNAL. Whether the JS client retries that transparently is what I did not check. The `locks` parameter is dead configuration for apps with only typed commands. +- Change: retry handler and commit a bounded number of times on `ConcurrentWrite` inside the same attempt (the handler is a pure function of loaded state), and surface a distinct retryable code otherwise. Drop `locks` from `for_aggregate` once finding 3 removes legacy handlers. M. + +### 11. Per-command JSON round-trips, clones and a post-commit ledger re-read +- Category: D Severity: medium Confidence: CONFIRMED +- Where: `src/command/input.rs:68`, `:116`; `src/microsvc/service/routes.rs:2014`, `:1736`, `:2251`, `:2319-2329`, `:1896-1904`; `src/microsvc/service/runtime.rs:636-642`, `:719-722`, `:1045-1076`, `:1237` +- What, per command: + - input is canonicalized (BTreeMap per object), serialized for the digest, cloned to decode, then serialized again for the `Message` payload; + - outbox causation is stamped three times; + - after a successful commit the ledger row is re-read and its payload compared to the value just written (an extra DB round trip to detect a condition the transaction already guarantees); + - `seal_wait_path_dispatch` calls `typed_command_contracts()`, which clones every contract in the service; + - name lookup happens twice (service index, then route bundle). +- Why it matters: this is the command hot path; the re-read alone adds a query per command. +- Change: serialize canonical input once and reuse the bytes for digest and message; stamp causation only in `CausalCommitBatch::build`; build the result from the in-memory completion and drop the re-read; index contracts by name at registration. M. + +### 12. Lifecycle write gate is an ambient env-var flag that does blocking file I/O per dispatch +- Category: A/D Severity: medium Confidence: CONFIRMED +- Where: `src/microsvc/mod.rs:153-158`; `src/microsvc/lifecycle.rs:78-103`; call sites `src/microsvc/service/runtime.rs:363`, `:748`, `:887`, `:1051`, `:1142` plus `src/graphql/http.rs:384,410,441` and `src/graphql/engine/request.rs:38,125` +- What: when `DISTRIBUTED_LIFECYCLE_DIR` is set, each check does `symlink_metadata`, opens and reads `dev.json` (up to 1 MiB), parses it and reads three more env vars. This is synchronous, inside async dispatch, and happens more than once per mutation (GraphQL layer, then `Service`). +- Why it matters: process behaviour changes through an environment variable no composition code mentions (Principle 6, and README 07's "you do not set a runtime role flag"). It also blocks the executor. +- Change: resolve membership once into an explicit `Service::with_lifecycle(LifecycleGate)` (file watcher or cached atomic) and check it at one layer. M. + +### 13. `HttpCommandHost` reports every failure as a rejection and every status as unknown +- Category: E Severity: medium Confidence: CONFIRMED +- Where: `src/command_dispatch/host.rs:665-676`, `:680-689` +- What: any `status >= 400`, including 5xx, becomes `CausalDispatchError::Rejected { code: "REJECTED", .. }`. `status()` validates the session and returns `CausalCommandPublicStatus::unknown(command_id)` unconditionally. +- Why it matters: behaviour differs silently between local and HTTP hosts (Principle 7). A transient remote failure looks like a business rejection, and status polling can never resolve for remotely hosted commands. +- Change: map 5xx to `Internal`/retryable, carry the remote error code through the wire body, and implement status against the remote (or remove `status` from the trait and serve it from the ledger owner only). M. + +### 14. Dead terminals and dead placeholders in the commit builder +- Category: F Severity: medium Confidence: CONFIRMED +- Where: `src/microsvc/service/handlers.rs:458-477`, `:496-521`, `:523-541`; `src/command/outcomes.rs` (`finalize_after_commit`); `src/microsvc/service/routes.rs:2319` +- What: the `atomic` impls for `DirectReadModelProjection` and `ProjectionDescriptor` are unreachable, because no builder method produces those type parameters. `DirectReadModelProjection`/`direct_read_model` are public with zero users repo-wide. `NoDirectProjection::atomic` is documented as "legacy / registry path ... remains for compatibility". `finalize_after_commit` returns `(K, Value)` and both callers bind `_committed`, so the typed outcome value is never consumed after commit. +- Change: delete the two unreachable impls and `direct_read_model`; keep one `atomic` terminal; make `finalize_after_commit` return just the `Value`. Breaking for the public exports, S. + +### 15. `routes.rs` (2992 lines) does about seven jobs +- Category: F/C Severity: medium Confidence: CONFIRMED +- Where: `src/microsvc/service/routes.rs`; also `src/microsvc/service/runtime.rs:754-759`, `:784-789`, `:803-808`, `:893-898`, `:1005-1010`, `:414-468` +- What: the file contains: + - handler spec types; + - erased traits; + - bus publisher and outbox wiring (the 7-feature `cfg(any(...))` list appears three times at 478-588 and again in `src/microsvc/runtime.rs:95-104`); + - four builders; + - registration; + - the three pipelines; + - external reservations; + - `ErasedRoutes for Routes`, with six copy-pasted "find causal handler by name else BadRequest `is not a typed causal command`" blocks (2761-2953). + + Further duplication: `ThinEventualHandler` and `ThinSucceededHandler` differ in one expression (590-1043); `CommandMountRegistrar for Routes` (1604-1655) duplicates `Service::register_command_mount_inner`; the route-index lookup block is repeated five times in `runtime.rs`. +- Change: split into `spec.rs`, `builder.rs`, `registry.rs`, `execute.rs` (the single pipeline) and `outbox_wiring.rs`. Add one `fn causal_handler(&self, name) -> Result<&dyn ErasedCausalHandler, _>`, one thin handler generic over the terminal, and one `cfg` alias for the 7-feature list (or drop the gate, since `test` is already in it). M. + +### 16. Typed command execution is compiled only with the `graphql` feature +- Category: F Severity: medium Confidence: CONFIRMED +- Where: `src/microsvc/service/causal.rs` (every item individually `#[cfg(feature = "graphql")]`); `src/microsvc/causal.rs:1` (`#![cfg_attr(not(feature = "graphql"), allow(dead_code))]`); `src/microsvc/wait_path.rs` +- What: the ledgered pipeline, HTTP/gRPC wait path and `CommandHost` exist only when the GraphQL engine is enabled. Without it a service has only legacy handlers. +- Why it matters: the write path's safety properties depend on a read-API feature flag, and per-item cfg makes the file hard to audit. +- Change: make typed dispatch unconditional (it does not need async-graphql; the protocol accumulator can be an optional parameter) and gate only the GraphQL transport. M. + +### 17. Two files named `causal.rs` with unrelated responsibilities; `Atomic` means two things +- Category: F Severity: low Confidence: CONFIRMED +- Where: `src/microsvc/causal.rs` (workspace/unit-of-work staging) vs `src/microsvc/service/causal.rs` (dispatch results, status, ledger recovery); `src/microsvc/service/causal.rs:1343-1356` +- What: there is no logic overlap between the two files, only a shared name. `collapse_projection_evidence` returns `CausalCommandPublicState::Atomic` when all Eventual obligations are observed, the same name as the same-transaction terminal state. `causal_handler_error_code` (694-703) restates `CausalDispatchError::code` (61-68). +- Change: rename to `workspace.rs` and `dispatch_result.rs`/`status.rs`; name the collapsed public state for what it is (e.g. `Projected`). Breaking wire name, S. + +### 18. `CausalRepository` and `get`/`load` duplicate the context API +- Category: C/F Severity: low Confidence: CONFIRMED +- Where: `src/microsvc/service/handlers.rs` (`CausalRepository` delegating `get/create/commit/publish_events/publish/read_models/readmodel/outbox`; `get` and `load` identical at 610-626); `src/microsvc/dependencies.rs:372-470` (`RepoDependencies`, `ReadModelStoreDependencies`, `RepoReadModelDependencies`) +- What: two facades for the same operations in handlers, and three dependency wrapper structs each re-implementing `HasRepo`/`CausalRouteDependencies`. +- Change: keep the context methods and drop `CausalRepository` and one of `get`/`load`; consider one `Dependencies`. Breaking, S-M. + +### 19. Panics and `eprintln!` on runtime and registration paths +- Category: E Severity: low Confidence: CONFIRMED +- Where: `src/microsvc/service/routes.rs:881`, `:910`, `:972`, `:1033`, `:1276-1353`, `:2299` (`unreachable!`); `src/microsvc/service/runtime.rs` (`validate_projector_registrations`); `src/microsvc/workers.rs:65-73`; `src/microsvc/http.rs`, `grpc.rs:200,221`, `knative_ingress.rs:88` +- What: + - `.expect("invoke must be chained...")` and `.expect("load_by")` fire at dispatch time for states the type-state builder already rules out. + - `register_modeled_projection` panics on misconfiguration, although `try_with_graphql` shows a fallible style exists. + - Server faults are logged with `eprintln!` (7 sites in `src/microsvc`). + - `spawn_service_consumer_loop` rebuilds the whole service every 100 ms forever on error, with no backoff. + - `spawn_outbox_publish_loop` discards the drain handle. +- Change: encode the thin-builder state in types so the `Option`s disappear; return `Result` from registration; use the crate's logging/metrics; add exponential backoff. S-M. + +### 20. Tests asserting removed behaviour or internals, and heavy duplicated setup +- Category: B Severity: medium Confidence: CONFIRMED (outline plus sampled bodies) +- Where: `src/microsvc/service/tests.rs`, `src/command_ledger/tests.rs`, `tests/legacy_authoring_absence.rs` +- What: + - `causal_dispatch_replay_contains_resolved_projection_obligation` (`service/tests.rs:2367`) now asserts `replay.projection_obligations.is_empty()`: the name says the opposite, and it tests a removed feature. + - `durable_success_states_use_only_the_succeeded_vocabulary` (`command_ledger/tests.rs:2207`) asserts `parse("accepted")` fails, i.e. the absence of an old name. + - `cell_ledger_external_binding_round_trips_and_legacy_rows_stay_unbound` (`:1668`) pins a compat fallback for rows "written before external dispatch existed", pre-release. + - `completion_rejects_*projection_obligation*` and `replay_rejects_*projection_obligation*` (`:1383-1530`) test the vestigial path from finding 4. + - `in_memory_adapter_reclaims_and_replays_with_a_stable_causation` (`:2018`), `concurrent_in_memory_reservations_have_one_winner_and_one_cause` (`:2082`) and `sqlite_adapter_enforces_attempt_fence_and_replays` (`:2109`) repeat the generic conformance functions at 878, 694 and 1051 for one backend each. + - `tests/legacy_authoring_absence.rs` is an `include_str!` source-text gate that cannot detect the legacy things still present (findings 3-6). + - Roughly ten tests reach through `Service::lookup_causal_command`, which is `#[allow(dead_code)]` in production (`runtime.rs:992`) and kept alive only by them. + - `service/tests.rs` has 1,100 lines of setup before the first test: four near-identical `*_program/_resolve/_lower/_inventory` quads (195-466) and a 300-line `AmbiguousCommitRepository` (809-1120) hand-delegating about 25 trait methods to inject one commit fault. +- Change: delete the removed-behaviour tests with finding 4; fold the per-backend duplicates into `run_command_ledger_adapter_conformance`; replace `lookup_causal_command` assertions with the public status API; add a fault-injection hook on `InMemoryRepository` instead of the wrapper; parameterize the projection program fixture. M. + +### 21. Missing behavioural tests +- Category: B Severity: medium Confidence: PLAUSIBLE (searched by test name in my slice only, not `tests/`) +- What I found no test for: + - two concurrent typed commands on the same aggregate (finding 10); + - an error after reservation leaving the row re-runnable immediately (finding 9); + - `HttpCommandHost` 5xx mapping and status (finding 13); + - ledger compaction running in a live service (finding 8); + - a saga participant implemented as a typed command — `tests/sagas/microsvc_saga.rs:60-63` uses `routes!` legacy handlers. +- Change: add these as backend-generic scenarios next to the ledger conformance suite. M. + +### 22. Docs and comments that disagree with code +- Category: F Severity: low Confidence: CONFIRMED +- Where and what: + - README principle 07 ("You do not set a runtime role flag") vs `DISTRIBUTED_LIFECYCLE_DIR` (finding 12) and the `graphql` feature deciding whether typed commands exist (finding 16). + - `docs/coordination-primitives.md:226-231` tells participants to dedupe on the saga command id themselves; nothing connects that id to the command ledger (finding 3). + - `src/microsvc/runtime.rs:19-23` says a crash hands the row "to a separately operated polling worker", while `:39-42` says the in-process worker polls and a separate drainer is optional. + - `src/microsvc/service/handlers.rs:160-164`, `:335`, `:465`, `:510` still describe the removed `project(PROJECTION)` and `.projected`. + - `src/command_dispatch/*` and `src/application/runtime_host.rs` comments cite "task 12"/"task 20". +- Change: fix alongside the corresponding findings. S. + +Answers to slice questions not covered above: +- **Sagas** are built from the same primitives. `Saga` is an ordinary event-sourced aggregate whose transitions return outbox messages (command plus `deliver_at` timer), committed in one batch (`src/saga/runner.rs:120-136`), with deterministic command ids, a processed-id set and a version-fence retry. The only structural problem is finding 3. +- **`command/` vs `command_dispatch/`**: the boundary is real (contract types vs transport hosts). +- **Declaration surfaces**: there are seven — `#[command(id=..)]` on a fn, `#[command(..)]` inside `#[sourced]`, `portable_command!` (including the `handle:` escape hatch), the thin builder `.load_by/.invoke/.eventual`, `typed_command(..).handle`, legacy `.command(name).handle`, and `routes!`. Examples use only the first two; the last two are the vestigial ones. `.load_by(` appears four times in the whole repo (two in `src`, one in `tests`, one in the CLI/macros crates), so the thin builder is probably just the macro's expansion target and could be made non-public — I did not read the expansion to confirm. + +## Things that are good and should not be changed +- Single-transaction `CausalCommitBatch` (events, outbox, read-model plans, snapshots, schedules, fenced ledger completion and optional direct projection) with the reservation as a separate short transaction and an attempt fence (`src/sqlx_repo/repo/commit.rs:242-253`). +- The ledger state machine lives once in `command_ledger/record.rs` and is shared by all backends, verified by one generic conformance suite (`run_command_ledger_adapter_conformance`) run against in-memory, SQLite and Postgres. +- Canonical input hashing plus contract fingerprint for detecting command-id reuse, and principal-partitioned ledger keys. +- Capability-restricted `CausalCommandContext` with an owned `AggregateCheckout`: handlers stage work and the framework commits, which keeps handlers thin. +- The saga design: a pure `SagaDefinition`, an event-sourced state machine, timers as delayed outbox rows, and timeout treated as "maybe applied, so compensate". diff --git a/docs/reviews/v5-pre-release/07-transports-gateway-application.md b/docs/reviews/v5-pre-release/07-transports-gateway-application.md new file mode 100644 index 000000000..05c8d70ca --- /dev/null +++ b/docs/reviews/v5-pre-release/07-transports-gateway-application.md @@ -0,0 +1,268 @@ +## Slice review: transports, gateway, composition + +All paths are relative to `/Users/patrickleet/dev/hops-ops/hops/distributed/`. Nothing was built or run; every finding is from reading code. + +### Assessment + +- **Bus:** the layering is right. One `MessageSource`/`ReceivedMessage`/`MessagePublisher` contract, one `run_source` runner that owns failure policy, metrics and tracing, and adapters that do not re-implement the loop. The problem is underneath the contract: adapters differ silently on ordering, redelivery, dead-lettering and idle behaviour, and the conformance suite covers three behaviours. +- **Gateway:** the portable core is small and fail-closed. The native and worker adapters each re-implement the live/delivery state machines, and there are identity leaks at ingress. +- **application/:** half of it is a real contract artifact. The other half (about 1.6k lines of deployment plan, capability and runtime-host code) has no production consumer. +- **Three things most worth changing:** + 1. Make delivery semantics a tested contract: real dead-lettering, shared backoff, a long-running default, an adapter-level conformance suite. + 2. Close the gateway identity side channels (findings 1, 13, 14, 15). + 3. Delete the unconsumed layers: the application deployment plan, the vestigial bus API, and the `application-runtime`/`runtime` features. +- **How it was read:** I read `src/bus` (all non-test code; `sqlite_bus.rs` only by diff against `postgres_bus.rs`; `runner/lane_tests.rs` and `runner/tests.rs` by test name only), `src/metrics` (`api.rs` and the top 330 lines of `registry.rs`; `prometheus.rs`, `http.rs`, `tests.rs` not read), `telemetry.rs`, `trace_context.rs`, the `Cargo.toml` features, and `src/leaderboard` (`mod.rs`, `projector.rs`, `background.rs`, `notify.rs`; `redis.rs`, `in_memory.rs`, `conformance.rs` not read). `src/gateway` + `docs/gateway` and `src/application` + its two docs were read by two sub-reviewers; I re-opened the cited lines for findings 1, 7, 8, 9, 13 and 24, and the rest of theirs are relayed and marked as such. +- **Not read:** `docs/external-facts.md` behavioural claims (symbols checked only), `docs/gateway/load-report.json`, most `tests/gateway*` and `tests/*_transport` bodies (names plus two bodies), and the worker JS runners. + +--- + +### 1. Client can assert `x-user-id` / `x-roles` through the gateway via the WebSocket query string +- Category: E (security) Severity: high Confidence: CONFIRMED by code path, not executed +- Where: `src/gateway/native/graphql.rs:412-418`; `src/graphql/http.rs:546-547, 745-767`; also `src/gateway/native/live_transport.rs:107-111`, `src/gateway/worker/live_transport.rs:22-28`, `src/gateway/worker/proxy.rs:164-169` +- What: the gateway strips identity headers (`native/proxy.rs:41-55`), but `rewrite_path` keeps the client query string. The origin's `graphql_ws_upgrade` calls `merge_identity_query_params` in every identity mode, which inserts `x-user-id`/`x-roles` from the query when the header is absent. The header is absent precisely because the gateway stripped it. The sub-reviewer traced the Hybrid-mode fallback to header claims at `src/graphql/identity/resolve.rs:465-467`; I did not re-open that file. +- Why it matters: `wss://gw/graphql?x-user-id=alice&x-roles=admin` with no token becomes alice/admin at a Hybrid or DevHeaders origin. The strip is also a denylist (`gateway/auth.rs:76-91`), while Hybrid trusts any header as a claim. +- Change: restrict `merge_identity_query_params` to DevHeaders; drop the query on gateway GraphQL WS upgrades; forward an allowlist of headers to GraphQL origins. Add a regression test with a Hybrid origin. Size S. + +### 2. The default failure policy `DeadLetter` discards the message on every broker adapter +- Category: E/A (Principle 7) Severity: high Confidence: CONFIRMED +- Where: `src/bus/failure_policy.rs:53-61`; `src/bus/nats.rs:550-557`; `src/bus/kafka.rs:285-292`; `src/bus/rabbitmq.rs:269-289` with `src/bus/rabbitmq_bus.rs:219-232`; `src/bus/sql_bus_common.rs:606-616, 753-759` +- What: per adapter, "dead-letter" does this: + - NATS: `AckKind::Term`. + - Kafka: commits the offset past the record ("A DLQ-topic producer is a follow-up"). + - RabbitMQ: reject without requeue, but `RabbitBus::declare_queue` passes `FieldTable::default()`, so no dead-letter exchange exists. + - SQL queue: deletes the row. SQL log: advances the offset. + - In-memory: falls back to `nack`, which loses a command and redelivers an event forever. + - Every implementation ignores `_reason`. Only `OutboxSource` records a failure (`src/outbox_worker/outbox_source.rs:164`). +- Why it matters: `failure_policy.rs:27` says `LogAndAck` is "the only action that discards a failed message", and `source.rs:100-104` says a message "is never silently dropped". In practice the default drops a permanently failed event with no log line and no stored copy. +- Change: one framework dead-letter destination above the trait: the runner publishes `{message, reason, consumer, attempts}` to a `{namespace}.dlq` destination (or a `bus_dead_letter` table for SQL) through the same `MessagePublisher`, then acks. Remove `dead_letter`/`park` from `ReceivedMessage`, and remove `Park` unless something implements it differently. Breaking trait change. Size M. + +### 3. Consumers drain to idle and return `Ok(())` by default; Kafka and RabbitMQ have no long-running mode +- Category: E/F Severity: high Confidence: CONFIRMED +- Where: `src/bus/sql_bus_common.rs:369, 567-570, 676-679`; `src/bus/nats_bus.rs:116` and `src/bus/nats.rs:443`; `src/bus/kafka.rs:166, 180` (`DEFAULT_FETCH_TIMEOUT` 8 s, `kafka_bus.rs:33`); `src/bus/rabbitmq.rs:202`; `src/microsvc/workers.rs:62-78`; `src/bus/postgres_bus.rs:26-36` +- What: an empty source returns `Ok(None)`, the runner stops, and `listen`/`subscribe`/`Service::run` return `Ok(())`. SQL and NATS buses default `idle_poll` to zero and need `.with_idle_poll(..)` to keep running. `KafkaBus` and `RabbitBus` have no such option: Kafka stops after 8 s of quiet, RabbitMQ the moment its queues are empty. `spawn_service_consumer_loop` treats `Ok(())` as "host bug": it prints with `eprintln!` and returns, so the consumer is gone until restart. +- Why it matters: the test behaviour is the default and the production behaviour is opt-in per adapter under different names. A Kafka or RabbitMQ service cannot be hosted with the framework's own worker loop. +- Change: `recv` waits until a message or shutdown. `run_source` takes a shutdown signal and runs until cancelled. Tests call an explicit `run_until_idle`. Delete `idle_poll`, the fetch-timeout-as-drain, and `CONSUMER_IDLE_POLL`. Breaking. Size M. + +### 4. Adapters differ silently on ordering, redelivery and grouping; conformance covers three behaviours +- Category: A (Principle 7) Severity: high Confidence: CONFIRMED +- Where: per-row citations below; `tests/transport_conformance/mod.rs:787-880` +- What: + + | Behaviour | In-memory | SQL | NATS | Kafka | RabbitMQ | + |---|---|---|---|---|---| + | Event order across names | grouped by name, not publish order (`in_memory_bus.rs:222`) | global `seq` | stream sequence | none: one topic per name, key = message id (`kafka.rs:83`) | one queue per group | + | Nack | command lost (`in_memory_bus.rs:188`, `:304`); event retried at once | immediate re-read, blocks the head | delayed, later messages overtake | seek back, blocks the partition | requeue at once | + | Two replicas, same group, events | n/a | both process every event: `log_read` takes no claim (`postgres_bus.rs:587-625`) | compete | compete | compete | + | `ordered_delivery` (causal projectors need it, `ordered_delivery.rs:6`) | yes | yes | yes | no | no | + | Undecodable delivery | n/a | through the failure policy (`decode_error`) | `recv` returns `Err`, run ends (`nats.rs:436-440`) | decoded lossily | decoded lossily | + | `content_type` round-trip | yes | yes | yes | lost: `owned_headers` never writes it (`kafka.rs:60-77`) | yes | + | Namespace isolation | none | none: `SqlBus` ignores namespace | yes | yes | yes | + + The generic suite run against real buses has three tests: point-to-point, fan-out across groups, named service as group. +- Why it matters: an app proven on the in-memory bus sees different event order, no command redelivery, and different poison handling on a broker. A projection that needs `created` before `shipped` is not safe on Kafka or in-memory. +- Change: write the contract down (per-aggregate order, at-least-once, backoff, dead-letter, competing within a group) and make it a generic conformance suite every `Bus + BusConsumer` runs. Then fix each adapter: Kafka key = aggregate/stream id with one topic per kind; in-memory as one global log with redelivery; a per-group claim on the SQL log. Size L. + +### 5. The SQL bus runs a legacy schema upgrade under `ACCESS EXCLUSIVE` on every `listen` and `subscribe` +- Category: D/F Severity: high Confidence: CONFIRMED (Postgres read; SQLite twin located at `sqlite_bus.rs:296-375`) +- Where: `src/bus/sql_bus_common.rs:413-421, 479, 499`; `src/bus/postgres_bus.rs:299-376` +- What: `listen` and `subscribe` each call `ensure_tables()`, which runs the DDL and then `ensure_ordered_log_schema`. That function takes `LOCK TABLE bus_log IN ACCESS EXCLUSIVE MODE`, runs two `ALTER TABLE bus_offset`, deletes offsets with empty epochs, scans the whole log for duplicate `message_id`s, and creates the unique index. Its comments call this "legacy duplicate inspection" for "writers that predate this framework". +- Why it matters: every consumer start blocks all publishers and readers and scans the full log. It is a compatibility path in an unreleased framework. It is pinned by `legacy_equivalent_stable_id_duplicates_retain_the_minimum_cursor` and `legacy_conflicting_stable_id_duplicates_fail_preflight_without_mutation` in both `tests/postgres_transport` and `tests/sqlite_transport`. +- Change: put the final schema (unique index, `NOT NULL` epoch) in `SCHEMA`/migrations. Delete `ensure_ordered_log_schema` and the four legacy tests. Run `ensure_tables` once at construction or migration, not per consumer. Size S. + +### 6. Retry/backoff is per-adapter and exists only on NATS; elsewhere a retryable failure is a hot loop +- Category: C/E Severity: high Confidence: CONFIRMED +- Where: `src/bus/nats.rs:264-301, 539-545`; `src/bus/sql_bus_common.rs:600-604, 748-751`; `src/bus/postgres_bus.rs:558, 654-666`; `src/bus/kafka.rs:260-282`; `src/bus/rabbitmq.rs:257-267`; `src/microsvc/workers.rs:74` +- What: `NackBackoff` is NATS-only. SQL queue `release_claim` clears the lock with no delay. SQL log `nack` is `Ok(())` and the next `recv` re-reads the same row. Kafka seeks back; RabbitMQ requeues. `bus_queue.attempts` is incremented but never read, and `available_at` is never set after insert. The supervisor restart sleep is a fixed 100 ms with no jitter. +- Why it matters: a downstream outage turns each consumer into a tight broker/DB loop. There is no attempt bound anywhere, so `FailurePolicy::Retry` plus a poison message is infinite. +- Change: backoff and max-attempts belong in `RunOptions` above the trait. The runner computes the delay from the delivery count and calls `nack(delay)`; adapters map it (JetStream `Nak(delay)`, `available_at = now() + delay`, a delay queue). After max attempts the message goes to the dead-letter path in finding 2. Size M. + +### 7. Gateway coalescing and live sharing are not transparent: a full registry fails the request +- Category: A/E Severity: high Confidence: CONFIRMED (`coordinator.rs` re-opened; adapter mappings relayed from sub-review) +- Where: `src/gateway/delivery/coordinator.rs:57-59, 69-71`; `src/gateway/native/flight.rs:156-157`; `src/gateway/worker/coordinator.rs:421-450`; `src/gateway/native/live.rs:199, 219-222` +- What: `CoordinatorRegistry::join` returns `Unavailable` at 256 groups or 1024 consumers. Native maps that to 503. Live maps it, and a freshness mismatch, to `LIVE_RESET_REQUIRED`. +- Why it matters: the flight key includes the per-user cache scope, so the 257th concurrent distinct private query gets a 503 that it would not get with coalescing off. A reset subscriber reconnects into the same full registry. This breaks "optimizations must be transparent". +- Change: on a full registry or freshness mismatch, execute independently (the bypass path exists). Keep 503 for the ingress permit only. Size S–M. + +### 8. The application deployment-plan / capability / topology / runtime-host layer has no production consumer +- Category: F/A (Principle 6) Severity: high Confidence: CONFIRMED +- Where: `src/application/plan.rs`, `capability.rs`, `topology.rs`, `runtime_host.rs`, most of `runtime.rs`, `mount.rs:77-131` +- What: outside `src/application/`, `RuntimeHost`, `CapabilityProviders`, `bind_single_process`, `TopologyIntent` and `compile_deployment_plan` appear only in `tests/application_plans.rs` and `tests/gateway_mounts.rs`. `runtime_host.rs:1` calls itself a "skeleton (task 12)". `capability.rs:376-379` computes a SHA-256 and discards it. `plan.rs:432-434` is `let _ = APPLICATION_MANIFEST_SCHEMA_VERSION;` to silence an unused import. The sub-review found the only non-test use of `Runtime` is e2e-ui using it as a selector-to-gateway map. +- Why it matters: this is the parallel topology description Principle 6 warns about, and no host runs from it. The contract half (`ApplicationManifest`, `Module`, `CommandSpec`, `ContractCompiler`) is derived from `Service` + `Surface` and is not parallel; keep it. +- Change: delete those files, `ProcessPreset`, `Runtime`/`RuntimeDialect`, and the two test files; remove the crate-root re-exports. Also remove `required_capabilities: Vec` (`module.rs:700`, `manifest.rs:130`), which is hashed into identity but which the sub-review found nothing reads (not re-checked). Breaking. Size M, nearly all deletion. + +### 9. `application-runtime` is evaluated in the user's crate; `runtime` gates nothing +- Category: F Severity: high Confidence: CONFIRMED +- Where: `Cargo.toml:37, 49`; `distributed_macros/src/command.rs:325-327, 355-401`; `distributed_macros/Cargo.toml:13-14` +- What: the `#[command]` macro emits `#[allow(unexpected_cfgs)] #[cfg(feature = "application-runtime")]` around the handler function, the mount, `register_*` and the mounted definition. That cfg resolves against the declaring crate's features. In `distributed` itself the feature gates only three test items (`src/microsvc/service/tests.rs:654, 657, 1332`). `feature = "runtime"` has zero hits in the root crate. +- Why it matters: a user who enables `distributed/application-runtime` without declaring a same-named feature in their own crate gets the handler compiled out, with the lint that would say so suppressed. It is a compile-time role flag by naming convention. +- Change: remove both features. The macro always emits the handler; contract-only is an explicit macro argument or a separate macro. Breaking. Size M. + +### 10. Native and worker gateway live/delivery coordinators are copy-pasted +- Category: C Severity: high Confidence: relayed from sub-review, not re-verified +- Where: `src/gateway/native/live.rs:1-469` vs `worker/live.rs:1-541`; `native/delivery.rs:134-449` vs `worker/coordinator.rs:377-668`; `native/flight.rs:17-183` vs `worker/coordinator.rs:669-751` +- What: about 410 of 469 non-test lines of `native/live.rs` appear verbatim in `worker/live.rs`; the differences are `Arc` vs `Rc` and the channel type. `mark` is byte-identical in both. The GraphQL-WS protocol loop exists four times in the gateway plus the origin's own. "lifetime = min(limit, identity expiry)" is written six times. +- Drift already present: hop limits `>512 bytes, >=8` on native vs `>1024, >8` on the worker; native rejects duplicate `Authorization`, the worker joins them; the worker has no Zones binding and bypasses the `GatewayAdapter` trait, whose only production implementation is native. +- Change: move the group/consumer/history state machine and the validate→lookup→fill→install decision into `gateway/delivery/` as plain `&mut self` structs returning effects, plus one portable WS frame codec. Adapters keep spawn, timer, socket and lock. Either make the worker implement `GatewayAdapter` or delete the trait. Size L. + +### 11. The Surface is stored three ways in the manifest, with a hand-written re-serializer to prove they agree +- Category: C Severity: high Confidence: relayed from sub-review, not re-verified +- Where: `src/application/module.rs:266-330, 377-513`; `src/application/manifest.rs:1487-1493, 1746-1881` +- What: `SurfaceSpec` carries flattened typed mirrors of the Surface IR and also `contract: serde_json::Value`, documented as the identity authority. `surface_contract_from_spec` rebuilds the contract JSON from the mirror key by key so validation can require equality. Enum identities come from `format!("{:?}", ..).to_ascii_lowercase()` (`module.rs:493, 588`). The surface fingerprint also includes the SQL dialect and physical table names, though `manifest.rs:107-110` says they are absent. +- Why it matters: each new Surface field needs three hand edits or manifests fail as non-canonical. Renaming a Rust variant changes fingerprints. The same app on Postgres has a different "placement-independent" identity. +- Change: one authority: `SurfaceSpec { id, contract, fingerprint }` with inventories derived by deserializing the contract, serde names instead of `Debug`, and no `dialect`. Breaking manifest schema. Size L. + +### 12. Message↔wire encoding is written seven times and disagrees +- Category: C/E Severity: medium Confidence: CONFIRMED +- Where: `src/bus/nats.rs:214-232`; `src/bus/kafka.rs:60-77, 196-211`; `src/bus/rabbitmq.rs:66-85`; `src/bus/redis_streams.rs:147-162`; `src/bus/knative_bus.rs:95-107`; `src/bus/sql_bus_common.rs:107-147`; `src/bus/celld_queue.rs` +- What: only NATS filters reserved keys out of user metadata. On Kafka and RabbitMQ a metadata entry named `x-sourced-kind` (or `x-sourced-id` on Kafka) overrides the real one, because metadata is written after it and `message_from_wire` takes the last match. Name validation happens only in RabbitMQ, Redis and celld, though `message.rs:125-131` says "publish boundaries call this". Header names are `Nats-Msg-Id`/`X-Sourced-Kind`, `x-sourced-id`/`x-sourced-kind`, `ce-sourcedkind`, and newer `X-Distributed-Occurrence-Id`. `x-sourced-*` is a legacy name on the wire. +- Change: one `WireEnvelope` in bus core (reserved-key set, validation, `Message` ↔ ordered `(key, bytes)` pairs) used by every adapter. Validate name and id once in a publish wrapper above `MessagePublisher`. Rename the headers to `x-distributed-*` now. `RabbitBus::publish_confirmed` (`rabbitmq_bus.rs:251-275`) duplicates `RabbitPublisher::publish` and should reuse it. Size M. + +### 13. The Zones binding forwards the caller's bearer token and cookies; docs say it forwards no credential +- Category: E (security)/B Severity: medium-high Confidence: CONFIRMED (code re-opened; the docs and test parts relayed) +- Where: `src/gateway/native/mod.rs:427-431`; `src/gateway/native/proxy.rs:56-62`; claims at `src/gateway/config.rs:92-95`; test `tests/gateway_ui.rs:650-661` +- What: Zones calls `proxy::forward` with the admitted context, and `prepare_headers` inserts `Authorization: Bearer ` whenever the provider supplies one. `Cookie` is never removed. The test asserts no `authorization` header but sends an anonymous request with a fixture that always returns no credential, so it cannot fail. +- Change: Zones forwards with no backend credential and strips `Cookie`. Make the test send a valid bearer. Size S. + +### 14. Worker `Handler` and `Assets` bindings receive raw client headers; native strips them +- Category: A/E Severity: medium Confidence: relayed from sub-review, not re-verified +- Where: `src/gateway/worker/mod.rs:301-307` vs `src/gateway/native/mod.rs:410-415` +- What: the same portable `BindingKind::Handler` runs `prepare_headers` on native and passes the original request on the worker. A handler reading `x-user-id` or `x-forwarded-host` is safe on one adapter and spoofable on the other. +- Change: one portable header-rewrite rule applied by both adapters for every binding kind. Size S. + +### 15. `extensions.gatewayDelivery` is an in-band control channel a client can forge +- Category: E (security) Severity: medium Confidence: relayed from sub-review, not re-verified +- Where: `src/gateway/native/graphql.rs:359-378`; `src/gateway/native/delivery.rs:377-388`; `src/graphql/http.rs:336-346` +- What: native forwards a client-supplied `gatewayDelivery` unchanged when its action is not `"execute"`, and for all mutations. `mark` overwrites `action` but keeps a client-supplied `connectionInit`, from which the origin then resolves identity instead of the request headers. +- Change: strip `extensions.gatewayDelivery` from every client request at ingress and set it only from gateway code, ideally behind a gateway-to-origin secret. Size S–M. + +### 16. Postgres fan-out is serialized on one row, with about 7 statements per publish and 2–3 transactions per consumed event +- Category: D Severity: medium Confidence: CONFIRMED +- Where: `src/bus/postgres_bus.rs:177-258, 388-470, 627-642, 668-700`; `src/bus/sql_bus_common.rs:653` +- What: every `publish` opens a transaction, runs `INSERT .. ON CONFLICT DO NOTHING` on `bus_log_identity`, `SELECT .. FOR UPDATE` on the singleton, `SELECT MAX(seq) FROM bus_log`, the insert, an `UPDATE high_water`, and commit. Every consumer `recv` runs `verify_log_epoch` (its own transaction taking `FOR SHARE` on the same row) even when rows are already buffered, and every ack runs another locked transaction. +- Why it matters: all publishers and consumers contend on one row. The singleton lock is what makes commit order equal `seq` order, so it should stay; the surrounding per-message work is the cost. +- Change: keep one lock per publish but drop the identity upsert and `MAX(seq)` from the hot path (startup only). Verify the epoch inside the `log_read` and `advance_offset` transactions that already lock it. Advance the offset once per batch. Size M. + +### 17. `postgres_bus.rs` and `sqlite_bus.rs` are roughly three-quarters the same text +- Category: C Severity: medium Confidence: CONFIRMED (normalized diff: 309 differing lines of 1,433) +- Where: `src/bus/postgres_bus.rs` (702 lines), `src/bus/sqlite_bus.rs` (731 lines) +- What: `SqlBusDialect` is cut at whole-operation granularity, so `reconcile_log_identity`, `ensure_ordered_log_schema`, `insert_log`, `log_read` and `advance_offset` are copied with placeholder and clock changes. +- Change: the dialect supplies only placeholders, clock expression, name-list binding and claim-token minting; the control flow moves into `sql_bus_common` using `QueryBuilder`, as `sqlx_repo` already does. Removes about 500 lines. Size M. + +### 18. Vestigial bus API +- Category: F Severity: medium Confidence: CONFIRMED +- Where and what: + - `src/bus/capabilities.rs` (275 lines): `TransportCapabilities`, `ConsumerAckKind`, `KnativeIntegrationKind` have no reader anywhere outside their own file, the re-export, and a README table row. No adapter exposes one, and SQLite, Redis and celld are missing. + - `src/bus/run_options.rs:14-60`: `InboxHook`, `ConsumerDeliveryMode`, `NoInbox` and the `I` generic on `RunOptions` and `run_source`. The doc calls it a "placeholder shape for the future consumer inbox". Inbox mode only validates the id (`receive_loop.rs:44-46`), `BusConsumer::listen` cannot accept it, and the tests pass `()`. The real inbox is `InboxStore` on the repository. + - `MessagePublisher::publish_batch` (`src/bus/publisher.rs:44-55`): no caller and no override outside its own two tests. + - `Message` has public fields plus getters (`message.rs:68-140`). + - `src/bus/mod.rs:29, 37-39` still says the Kafka adapter is a "separate slice" and the inbox is "future". +- Change: delete all of it; `RunOptions` becomes a plain struct. Breaking. Size S. + +### 19. The GraphQL metric label `root_field` is the client's alias +- Category: E (cardinality) Severity: medium Confidence: CONFIRMED +- Where: `src/graphql/engine/request.rs:109-113`; `src/metrics/registry.rs` (`graphql_request_total`, `graphql_request_duration`) +- What: the label is the first key of `response.data`, which in GraphQL is the response key, i.e. the alias the client chose. `{ a8f3: todos { id } }` records `root_field="a8f3"`. +- Why it matters: any client can create unlimited series, each a counter plus an 11-bucket histogram, held forever in the process-global registry and exported on every scrape. The telemetry privacy list forbids ids as labels; this bypasses it. +- Change: take the label from the resolved schema field name and map anything not in the generated root set to `"_"`. Size S. + +### 20. Metrics cost about ten `String` allocations and five global mutex locks per consumed message +- Category: D Severity: medium Confidence: CONFIRMED +- Where: `src/metrics/api.rs:19-52`; `src/metrics/registry.rs:227-252, 388-390` +- What: `record_microsvc_dispatch` builds four owned strings, clones them into separate counter and histogram keys, and locks `dispatch_total`, `dispatch_duration` and `service_info`. `record_transport_message` allocates four more and locks two more. `note_service` re-inserts the service name under a lock on every record. The registry is a process-global `OnceLock`, which is why tests need `lock_for_tests`. +- Change: keys of `&'static str` plus an interned service/message handle, resolved once per route at registration to atomic counters. Register the service once in `describe_service`. `telemetry.rs` and `trace_context.rs` do not overlap and are otherwise clean. Size M. + +### 21. Leaderboard is a second projection system in the core crate, with a lossy path and an unbounded queue +- Category: A (Principles 1, 5)/F Severity: medium Confidence: CONFIRMED for the code facts; the placement judgement is mine +- Where: `src/leaderboard/` (2.5k lines, always compiled, `src/lib.rs:42`); `src/leaderboard/background.rs:104-115`; `src/leaderboard/notify.rs:107-121`; `Cargo.toml:59-63` +- What: it has its own projector trait, idempotency keys, rebuild/promote, change listeners, and a framework bus event `distributed.leaderboard.changed`. It reaches into `src/graphql` (seven files including a 491-line `leaderboard_roots.rs`), `src/application/{module,manifest}.rs`, and the CLI client compiler. + - The bus-fed path (`apply_message`) respects the flow. + - `BackgroundLeaderboard::submit` is `try_send` that drops when full and gives up after three attempts: a best-effort dual write beside the outbox. + - `LeaderboardChangePublisher` uses an unbounded channel and retries any publish error forever, including permanent ones, so one bad notice blocks the queue while it grows. + - `redis` bundles two unrelated things (leaderboard and `RedisStreamPublisher`) and force-enables `leaderboard-background`, a feature that only means "tokio is available" and also gates the unrelated change publisher. The Redis Streams publisher has no consumer in the repo. +- Change: move leaderboard to its own crate (`distributed_leaderboard`) that plugs into GraphQL through a generic external-read-source extension point. Delete `BackgroundLeaderboard`; bound the change publisher and drop permanent errors. Split `redis` into `redis-streams` and the leaderboard crate's own feature; delete `leaderboard-background`. Size L. + +### 22. The gateway feature lattice: six names, with the bulk behind an unnamed combination +- Category: F Severity: medium Confidence: relayed from sub-review; the 65 `gateway-delivery` cfg hits in `src` are my count +- Where: `Cargo.toml:39-48`; `src/gateway/native/mod.rs:122, 215, 439, 467-479` +- What: `gateway-delivery = ["gateway-graphql"]` adds no dependency. `gateway-graphql` alone has no consumer and no CI job. `native/{delivery,flight,live,live_transport}.rs` (2.1k lines) compile only under `all(gateway-graphql-native, gateway-delivery)`, which is what e2e-ui and CI use. `gateway-delivery` also switches origin behaviour inside `src/graphql`. +- Change: fold `gateway-graphql` and `gateway-delivery` into `gateway`. Keep `gateway-native`, `gateway-graphql-native` (now including native delivery, still opt-in at runtime) and `gateway-worker`. The only loss is that UI-only consumers pull in `async-graphql-parser`. Breaking. Size M. + +### 23. Other feature flags +- Category: F Severity: low-medium Confidence: CONFIRMED +- What: + - `runtime`: alias, no gate (finding 9). Delete. + - `metrics = []`: real (42 cfg sites), dependency-free. Keep. + - `emitter`: gates `src/emitter` (230 lines) and `#[enqueue]`, an in-process event emitter embedded in entities. Used only by `tests/enqueue` and `tests/sourced_enqueue`. It is a side channel beside the outbox and puts an emitter inside aggregates (Principles 1, 3). Delete unless a real project uses it. + - `workers-rs` vs `gateway-worker`: both pull `dep:worker` independently and no cfg combines them. `workers-rs` actually gates the cell host (`src/microsvc/cell_host`, 121 cfg sites) and the celld queue publisher. Rename to what it gates (for example `cell-host`). + - `KnativeBus` and `knative_triggers` are gated on `http` (`src/bus/mod.rs:96-99`), so every GraphQL build compiles the manifest generator. Give it a `knative` feature. + +### 24. `docs/application-composition.md` describes an API that does not exist and a role matrix the code rejects +- Category: F (docs) Severity: medium Confidence: CONFIRMED +- Where: `docs/application-composition.md:82-88, 132, 188`; `src/application/runtime.rs:70` +- What: the doc specifies `SystemSlice`, `ProcessRole::Full / CommandWriter / EventualProjector / QueryApi`, and `runtime.app(..).role(..)`. None of these names exists in any `.rs` file. `runtime.rs:70` says "There is no process-role setter." The sub-review found the doc is linked from the CLI's usage skill and the e2e-ui README. `docs/gateway/live-sharing.md:35` and `docs/gateway/worker.md:62-69` also contradict the code per the sub-review. +- Change: rewrite as what exists (`Service` + `Module`/`Application` + `ContractCompiler`, explicit hosts) or delete it. Size S. + +### 25. Per-message round trips and copies on the consume path +- Category: D Severity: medium Confidence: CONFIRMED (bus), relayed (gateway) +- Where and what: + - `src/bus/nats.rs:424-431`: one pull request with `max_messages(1)` per `recv`, even though lanes allow 16 in flight. `:461` copies the payload while keeping the raw message. + - `src/bus/rabbitmq.rs:184-191`: `basic_get` polling, one round trip per message, no consumer or prefetch. + - `src/bus/runner/receive_loop.rs:509`: lane mode clones the full `Message` into an `Arc` per delivery; `:374-376` allocates the service name per accept and per settle. + - `src/bus/celld_queue.rs:60-72`: the envelope is serialized once to measure size and again to send; `into_message` re-validates by serializing a third time. + - Gateway (relayed): a delivered query has its document parsed four or more times and its JSON deep-cloned five times, and the JWT is verified twice at the gateway (`native/graphql.rs:342-365`, `native/delivery.rs:189-190`). A snapshot hit parses and copies up to 1 MiB under the global cache mutex (`delivery/snapshot.rs:321-379`). Live fan-out deep-clones and re-serializes the payload per consumer (`native/live_transport.rs:548, 421`). +- Change: fetch a batch sized to `lane_window` on NATS; use `basic_consume` with prefetch on RabbitMQ; have `ReceivedMessage` hand out `Arc`. In the gateway, admit once into a struct, keep bodies as `Bytes`, and extract evidence at install. Size M. + +### 26. Smaller correctness hazards in adapters +- Category: E Severity: medium-low Confidence: CONFIRMED +- What: + - `src/bus/kafka.rs:176-179`: every consumer error (auth failure, unknown topic) is discarded as `_transient` with no log or metric; the source then reports "drained". + - `src/bus/sql_bus_common.rs:52, 58, 553-566`: the queue claims 16 rows under one 30 s lease, handles them sequentially, and never renews. If the batch takes longer, tail rows are re-claimed and run twice concurrently. + - `src/bus/sql_bus_common.rs:209`: a `seq` decode failure becomes `0`. + - `src/bus/in_memory_bus.rs:66-73`: publish with an id scans every retained message in every topic. `:165`: each `subscribe` call starts a fresh cursor and replays the whole retained log. + - `src/bus/postgres_bus.rs:561, 602`: `OR name IS NULL` on a `NOT NULL` column. + - `src/bus/knative_bus.rs:132`: an unmapped event silently renders the broker `UNMAPPED-events` into the manifest. + - `src/gateway/worker/frontend.rs:95-104, 497-501` (relayed): the worker closes every non-delivery GraphQL socket after 256 KiB cumulative bytes. + - Library code logs with `eprintln!` (`receive_loop.rs:158, 284`, `leaderboard/notify.rs:118`, `microsvc/workers.rs:66, 73`). + +### 27. Tests: duplicated runner tests, per-adapter copies, a test that proves what the library does not do +- Category: B Severity: medium Confidence: CONFIRMED where I name line numbers; the application items are relayed +- What: + - `tests/transport_conformance/mod.rs:226-340`: the nine `source_*` functions restate `src/bus/runner/tests.rs` (for example `source_dispatches_before_ack` ≙ `success_dispatches_then_acks_in_order`) against a `FakeSource`. They are called only from `tests/transport_in_memory` and never touch a real adapter. + - `publish_then_consume_round_trips_through_*`, `message_id_and_metadata_survive_the_round_trip`, `retryable_failure_is_redelivered_then_succeeds` and `undecodable_payload_dead_letters_without_blocking` are re-written in each of `tests/{kafka,rabbitmq,nats}_transport/main.rs`. The names already show the divergence: Kafka's is `permanent_failure_skips_record_without_redelivery`. + - `tests/rabbitmq_transport/main.rs:380-431` `permanent_failure_routes_to_dead_letter_destination` declares its own dead-letter exchange in a test helper (`source_with_dlq`, `:283`). `RabbitBus` never declares one. + - Broker tests return early when the env var is unset (`let Some(url) = amqp_url() else { return }`), so they pass without running. + - `src/bus/capabilities.rs:186-275`: seven tests assert constants of a type nothing reads. + - Legacy tests listed in finding 5. + - Missing: cross-name ordering, same-group event competition, redelivery after nack on in-memory, content-type on Kafka, behaviour after idle, real dead-letter contents. + - Gateway (relayed): no direct tests for `SnapshotCache`, `CoordinatorRegistry`, `Minimum::covers` or `LiveFrame::from_origin`, and no Rust tests for the worker coordinator. + - Application (relayed): `no_linker_inventory_is_needed_for_explicit_application_selection`, `capability_closure_is_explained_and_schema_has_one_owner` (cannot fail), `stale_manifest_predecessor_is_retained_exactly`, and `json_contract_can_exceed_the_old_256_kib_limit`. +- Change: move every per-adapter behaviour test into the generic conformance suite from finding 4; delete the `source_*` copies; make broker tests fail (or be `#[ignore]`) when the broker is absent. Size M. + +### 28. `manifest.rs` does eight jobs; primitive validators are duplicated across three files +- Category: C/F Severity: medium Confidence: relayed from sub-review, not re-verified +- Where: `src/application/manifest.rs` (2,266 lines, tests only at 2158-2266) +- What: jobs by range: wire types (1-182), composition (184-386), canonical encoding and fingerprints (387-470, 645-673), top-level validation (472-643), per-entity validation (675-1485), the surface re-serializer (1487-1493, 1746-1881), ownership checks (1495-1744), primitive validators (1883-2156). `validate_text`/`validate_sha256`/`validate_json_contract` in `command.rs:564-654` duplicate `manifest.rs:1948-2047`. The "zero the fingerprint, canonicalize, hash" block is written eight times. `fingerprint()` encodes, decodes, validates and re-encodes to return a field. +- Change: split into `manifest/{wire,compose,canonical,validate,ownership}.rs` plus one `application/validate.rs`; one `Fingerprinted` trait. Also reduce `CommandMount` to the typed-route token (the erased-handler path is test-only, `command.rs:687-758`). Size M. + +### 29. `NatsBus::retained_domain_events` is a domain-archive reader inside one transport adapter +- Category: A (layering) Severity: low-medium Confidence: CONFIRMED +- Where: `src/bus/nats_bus.rs:240-327`; `src/bus/nats.rs:32-175` +- What: 90 lines on `NatsBus` read the whole JetStream stream (capped at 100k messages / 64 MiB) and decode `DomainEventOccurrence`s. `nats.rs` has about 140 lines of external-occurrence identity logic (`external_dedup_id`, `restore_external_identity`) that no other adapter has. +- Why it matters: "replay retained events" and "external fact identity" are framework features that exist on one backend. On the others, external facts get different dedup behaviour. +- Change: lift external-occurrence identity into the shared envelope (finding 12). Make archive replay a trait an adapter may implement, or source it from the event store. Size M. + +### 30. Gateway public metrics are positional 7-tuples +- Category: F Severity: low Confidence: relayed from sub-review, not re-verified +- Where: `src/gateway/native/delivery.rs:74, 107, 120`; `src/gateway/worker/coordinator.rs:151, 164, 176` +- What: `live_counts() -> (usize, usize, u64, u64, u64, u64, u64)`, with different shapes on native and worker; tests index `.5` and `.6`. +- Change: `LiveMetrics` and `FlightMetrics` structs beside `SnapshotMetrics`, the same from both adapters. Size S. + +--- + +### Things that are good and should not be changed + +- **The bus layering.** `MessageRouter` / `MessageSource` / `ReceivedMessage` with one `run_source` that owns ack-after-effects, failure classification, metrics and tracing (`src/bus/runner/receive_loop.rs`). The bus does not depend on `microsvc`. Fix the adapters and the contract, not the shape. +- **`OrderedDelivery` is crate-private to construct** (`src/bus/ordered_delivery.rs`), so application metadata cannot mint ordering evidence. The SQL log's epoch, high-water and fenced-reset design, including the singleton lock that makes commit order equal `seq` order, is deliberate. So is fenced queue settlement by `seq` + `claim_token`. +- **Gateway per-consumer origin admission before any cache, flight or live join**, with keys hashing the origin-issued identity and install fenced by generation (`src/gateway/delivery/identity.rs:89-92`, `snapshot.rs:293-364`). Also the fail-closed config and route normalization (`config.rs:155-339`, `route.rs:180-211`) and the proxy client with redirects, retries and env proxies disabled (`native/mod.rs:261-272`). +- **The manifest's single serialized authority**: derived inventories are rebuilt on decode with `deny_unknown_fields`, encoding is byte-exact, ordering is deterministic (`BTreeMap`, sorted vecs), and registration is explicit `Application::new(..).module(..)` with no linker inventory. +- **Metrics with no SDK dependency and a tested label allowlist** (`src/telemetry.rs` `privacy_policy`); trace context carried as ordinary message metadata so it works on every transport without `otel`. diff --git a/docs/reviews/v5-pre-release/08-macros-authoring-surface.md b/docs/reviews/v5-pre-release/08-macros-authoring-surface.md new file mode 100644 index 000000000..4871bee5c --- /dev/null +++ b/docs/reviews/v5-pre-release/08-macros-authoring-surface.md @@ -0,0 +1,234 @@ +# Slice review: procedural macros and the authoring surface (v5) + +## Assessment + +The newer macros are in good shape: `distributed_game_macros` and `aggregate_command.rs`, `command_types.rs`, `domain_state.rs` and `domain_event.rs` expand thinly, resolve crate paths and span their errors. The older core (`sourced.rs`, `aggregate.rs`, `snapshot.rs`, `read_model/*`, `mutation.rs`) hard-codes `distributed::` paths, duplicates runtime logic and carries three generations of authoring surface at once. + +The three things most worth changing: +1. **One command surface, not four.** `#[command(id = ..)]` on a handler fn, `#[command("a.b", ..)]` on an aggregate method, `portable_command!` and raw `routes.command_transition` overlap. `module!`, `application!`, `aggregate!`, `#[digest]` and `#[enqueue]` have no users outside framework tests and fixtures. +2. **Two correctness hazards in `#[sourced]`.** The event is recorded before a fallible recorder body runs (finding 1). Optimistic "known values" are inferred syntactically from recorder assignments and can be wrong (finding 2). +3. **Macros that should expand to one runtime call.** `projection!` recompiles its program on every event, `mutation!` re-implements program builders inline with drift, and `mutation_file!` does not track its input file. + +Principle 3 is only partly honoured (finding 8). + +Nothing was compiled or run; every finding is from reading code and `rg`. + +Not read or only skimmed: +- `distributed_macros/src/read_model/{attrs,relational,types}.rs`: attribute key list and grep only. +- `distributed_macros/src/command_types.rs`: lines 100–620 not read. +- `distributed_macros/src/command_input_defaults.rs`: symbol list only. +- `distributed_macros/src/mutation.rs`: parser section (lines 67–636) not read. +- `distributed_macros/src/snapshot.rs`: tests after line 330 not read. +- `distributed_game_macros/src/{replicated,event,input,pure}.rs`: grep only. +- `.rs` fixtures under the `compile_fail` dirs: sampled about 8; all 75 `.stderr` files classified by script. +- Root `tests/sourced/*`, `tests/enqueue/*`, `tests/aggregate_command/*`: grep only. +- `examples/`: only `examples/game/server/crawler`. +- `macro_rules!` other than `projection!`, `graphql_models!` and `impl_aggregate!` (`routes!`, `events!`, `state_preview!`, `event_preview!`): usage-counted, not read. + +## Authoring surface inventory + +Usage counts are from `rg` over the repo, excluding the macro crates themselves. + +| Macro | Arguments | Usage outside macro crates | +|---|---|---| +| `#[sourced(entity, ..)]` | `events = "Name"`, `aggregate_type = "x"`, `domain_state = Type`, `enqueue[(field)]`, `upcasters(..)` | 79 | +| `#[event("name", ..)]` | `version`, `when = expr`, `domain` / `domain = state\|event\|deleted\|with(T, f)` | `domain = with`: 3 (tests only); `domain = state` spelled out: 1 | +| `#[command("a.b", ..)]` on an aggregate method, with `#[principal]` | `shard`, `load`, `outcome`, `payload`, `roles`, `guard`, `field`, `input`, `transition`, `mount` | 1 example (crawler), plus `tests/aggregate_command` | +| `#[command(id = "..", ..)]` on an async fn | `roles(a, b)`, `emits(..)`, `applies(..)`, `defaults`/`input_defaults`, `default(f = gen)`, `field`/`field_name`, `input`, `outcome` | 3 test/fixture sites, 0 apps | +| `portable_command! { .. }` | 17 keys: `name, transition, aggregate, input, outcome, shard, field, roles, load, invoke, payload, handle, guard, defaults, constructor, authenticated_user_field, preview_reduce_known_record` | 17 (11 in e2e and examples) | +| `module!`, `application!` | `id, commands, projections, surfaces, capabilities`/`required_capabilities, modules, extensions` | fixtures only | +| `aggregate!`, `#[digest]`, `#[enqueue]`, `impl_aggregate!` | — | `tests/` only; `impl_aggregate!` has 0 uses | +| `mutation!` (two syntaxes), `mutation_file!` | — | `mutation!`: 2 (one test); `mutation_file!`: 18 | +| `command_input_defaults!` | — | 4 | +| `projection!` (two arms) | — | 17 | +| `graphql_models!` | — | 0 call sites (one CLI-generated comment) | +| derive `Snapshot` | `#[snapshot(entity = "f", id = "f", version = N)]` | 43 | +| derive `DomainState` / `DomainEvent` | `#[domain_state(version)]` / `#[domain_event(name, version)]` | 25 / 25 | +| derive `CommandInput` / `CommandOutput` | — | 76 / 43 | +| derive `ReadModel` | `#[readmodel(..)]` plus bare `#[table] #[collection] #[column] #[id] #[index] #[unique]` | 128 | +| Game: `Replicated, GameInput, GameEvent, GameRecord, FactCommand, TicketExtension`, `#[predict]`, `#[game_pure]` | — | coherent, see end | + +## Findings + +### 1. `#[event]` records the event before a fallible recorder body runs +- Category: E Severity: high Confidence: CONFIRMED +- Where: `distributed_macros/src/shared.rs:145-198` (arms at 165-175 and 187-196); prelude built at `distributed_macros/src/sourced.rs:816-828` +- What: For a recorder that returns `Result`, the expansion is `{ #prepend (|| #original_block)()?; #append Ok(()) }`. `#prepend` is the `enqueue` call plus `self.entity.digest_v(..)?`. The event is pushed onto `entity.events` (and enqueued on the emitter) before the body runs. If the body returns `Err`, the event stays pending with the state change not applied. +- Why it matters: A caller that handles the error and still commits persists an event whose handler fails; replay then fails forever at `replay_event`. Domain-marked recorders are protected by compile errors (`sourced.rs:761-771`); plain `#[event]`, `#[digest]` and `#[enqueue]` are not. The test `explicit_digest_validates_before_recording_events` in `tests/sourced/main.rs` shows the hand-written workaround. No test covers a failing macro recorder body. +- Change: Make recorders infallible, as domain recorders already are: reject `-> Result` on `#[event]` methods. Validation belongs in the public decision method. Breaking. Size S. + +### 2. `#[sourced]` infers optimistic "known state values" by syntax, and can be wrong +- Category: A/E Severity: high Confidence: CONFIRMED (code path); client-visible impact PLAUSIBLE +- Where: `distributed_macros/src/sourced.rs:1102-1180` (inference), `1470-1507` (emission); consumed at `src/command/projections.rs:715-753` and `805-815` +- What: The macro scans top-level `self.field = ` statements of a state-domain recorder. It treats literals, `None`, `Some(lit)`, `std::string::String::from("..")` and any path of two or more segments as a proven value. The value is published as the predicted value of the `DomainState` field with the same Rust name, serialised with serde from the aggregate-side expression. Three things break it: + - A later `if c { self.status = X }` or a helper call such as `self.advance_snapshot_generation()` does not invalidate an earlier assignment, because non-assign statements are skipped (`1106-1108`). + - The real body is `From<&Aggregate> for State`, which is arbitrary code. `TodoState.status` is a `String` built by a hand-written `match` (`tests/e2e-ui/crates/todo-domain/src/models/todo_state.rs`), while the macro predicts `serde(TodoStatus::Completed)`. They agree only because `TodoStatus` carries `#[serde(rename_all = "snake_case")]`. + - The same field name on aggregate and state is assumed to mean the same thing. +- Why it matters: The command preview says "this field will be X" while the server writes Y, so the optimistic UI flickers or shows wrong data. Nothing fails at compile time or in tests. It is a second, heuristic implementation of the state mapping (Principle 5). The rules are invisible to authors: `String::from("x")` is not known but `std::string::String::from("x")` is (see `expand_sourced_transition_exports_unconditional_known_state_values` in `src/entry_tests.rs:210`). +- Change: Delete the inference (`KnownStateValue*`, `infer_unconditional_known_state_values`, `flat_literal`, `command_event_known_values`). Authors who want a preview declare it with the existing `state_preview!` / `event_preview!`. Roughly 330 lines removed. Breaking. Size M. + +### 3. `projection!` recompiles the whole projection program for every event +- Category: D Severity: high Confidence: CONFIRMED +- Where: `src/lib.rs:231-237` and `283-289` (`__resolve`), `196-229` (`__handlers`); hot caller `src/projection/lower.rs:529-535`, used at `src/microsvc/projector/runtime.rs:211` and `src/microsvc/causal.rs:782` +- What: `__resolve(occurrence)` is `resolve_mutation_program(&__handlers()?, occurrence)`. `__handlers()` rebuilds every mutation (`$mutation().program().clone()`), re-reads `RelationalReadModel::schema()`, re-binds every event and runs `compile_projection`. I found no caching in `src/mutation/descriptor.rs`. +- Why it matters: Projection apply is the hottest read-side path. Each event pays allocation and validation proportional to (events × columns) of the projection. +- Change: Build the program once: a `static OnceLock>` in the expansion, or have `ProjectionDescriptor` own a lazily built program and take `resolve(&program, occurrence)`. Size S. + +### 4. `mutation_file!` does not register its input file with Cargo +- Category: E Severity: high Confidence: CONFIRMED (code); stale-build symptom PLAUSIBLE +- Where: `distributed_macros/src/mutation.rs:35-66`, expansion at `637-668` +- What: The macro reads `CARGO_MANIFEST_DIR/` with `std::fs::read_to_string` and emits only the compiled program. There is no `include_str!` or tracked path anywhere in the crate, and the e2e projections crate has no `build.rs`. +- Why it matters: Editing only `save_todo.mutation.graphql` leaves rustc's dependency info unchanged, so the old program keeps running. I did not run a build to confirm. +- Change: Emit `const _: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/", #path));` in the expansion. Size S. + +### 5. Four overlapping ways to declare a command +- Category: F/C Severity: high Confidence: CONFIRMED +- Where: `distributed_macros/src/command.rs` (588 lines), `aggregate_command.rs` (630), `portable_command.rs` (344); builder at `routes.command_transition::` +- What: Each form produces a typed command plus a mount. They disagree on spelling and validation: + - Roles: `roles(user, admin)` with dedupe and non-empty checks (`command.rs:35-78`); `roles = ["a"]` non-empty (`aggregate_command.rs:206-235`); `roles: ["a"]` with no validation (`portable_command.rs:153`). + - Name: `validate_command_id` allows `-` and caps at 128 bytes (`command.rs:151`); `validate_name` allows no `-` and has no cap (`aggregate_command.rs:161`); `portable_command!` checks only the last segment (`portable_command.rs:176`). + - GraphQL field: required in `portable_command!`, optional in the method form, defaulted from the id in the fn form. + - Load: `required|create` versus `required|or_create|create`. + - Outcome: detected by the last path segment being `"Eventual"`/`"Succeeded"` (`portable_command.rs:323-343`, `aggregate_command.rs:180-204`); a type alias defeats it. +- Why it matters: A new author cannot tell which form is canonical. The README shows none of the method forms in Principle 3. The e2e app uses `portable_command!` with 9–13 keys per command, where `aggregate`, `transition` and, for thin commands, `shard` and `payload` restate what the aggregate method already says. +- Change: Keep `#[command("agg.verb", ..)]` on the aggregate method as the one declarative form. Give it the missing options from `portable_command!` (`defaults`, `authenticated_user_field`, `preview_reduce_known_record`, `load = create`). Keep the plain `Routes` builder as the escape hatch for hand-written handlers. Delete `portable_command!` and the fn-form `#[command(id = ..)]`. Put role, name and outcome validation in one runtime function that both paths call. Breaking. Size L. + +### 6. `#[command(id = ..)]` gates the user's handler on a feature of the user's crate +- Category: A/F Severity: high Confidence: CONFIRMED +- Where: `distributed_macros/src/command.rs:325-327`, also `354-413` +- What: The expansion emits `#[allow(unexpected_cfgs)] #[cfg(feature = "application-runtime")] #function`. The cfg is evaluated in the caller's crate. A user crate without a feature literally named `application-runtime` silently loses its handler, mount and register fn, with the warning suppressed. Each command also emits four `LazyLock` statics and seven functions; two of them panic at first access (`:346`, `:398`, `:408`). +- Why it matters: This is a hidden runtime matrix (Principle 6). It is used only by `tests/fixtures/application-contract-only`, `tests/fixtures/renamed-dependency-trybuild`, `distributed_macros/tests/application.rs` and one test in `src/microsvc/service/tests.rs`. No example or the e2e app uses it; the e2e app composes by hand in `tests/e2e-ui/crates/service/src/application.rs`. +- Change: Remove with finding 5, together with `module!`, `application!`, the `*_DEFINITION`/`*_COMMAND_ID` naming protocol (`module.rs:139-165` rewrites identifier suffixes) and the `application-runtime`/`runtime` features of `distributed_macros`. If contract-only builds are still wanted, gate inside the framework crate. Breaking. Size M. + +### 7. Vestigial first- and second-generation authoring macros are still public and documented +- Category: F Severity: medium Confidence: CONFIRMED (rg over the repo) +- Where: `distributed_macros/src/{digest.rs, enqueue.rs}`, `aggregate.rs:187-475`, `src/aggregate/aggregate.rs:34-95` (`impl_aggregate!`), `src/lib.rs:480` (`graphql_models!`), `mutation.rs` classic syntax (`435-636`), README lines 1017-1090 +- What: + - `aggregate!`, `#[digest]`, `#[enqueue]` and `#[sourced(.., enqueue)]` are used only under `tests/` (`upcasting`, `enqueue`, `sourced_enqueue`, `replay_event_version`). + - `impl_aggregate!` has no call site. + - `graphql_models!` has no call site and assumes a `$m::Model` layout the e2e app does not use; it is referenced only in a CLI-generated comment and one skill doc. + - Inline `mutation!` has two grammars; the only non-macro-crate use is one test in `tests/e2e-ui/crates/projections/src/todos.rs:122-132`. + - Alias keys exist for the same option: `defaults|input_defaults`, `field|field_name` (`command.rs:91`, `:118`), `capabilities|required_capabilities` (`module.rs:53`, `application.rs:46`), `skip_query|skip|private` (`read_model/attrs.rs:157-159`). `module.rs:45` keeps a tombstone error for a removed `mounts` key. +- Why it matters: This is roughly 900 lines of macro source plus about 300 README lines for surface the README itself says `#[sourced]` replaces. +- Change: Delete all of the above and the tests that exist only for them. Keep one mutation grammar (the GraphQL-looking one) and one spelling per key. Breaking. Size M. + +### 8. Principle 3 is only partly honoured: framework plumbing lives in the domain struct +- Category: A Severity: medium Confidence: CONFIRMED +- Where: `tests/e2e-ui/crates/todo-domain/src/models/todo.rs:8-10` and `:96`; `distributed_macros/src/aggregate_command.rs:476-486`; `distributed_macros/src/snapshot.rs:173-187` +- What: An aggregate must carry `#[serde(skip, default)] pub entity: Entity`, name that field in `#[sourced(entity, ..)]`, and call `self.entity.set_id(&id)` inside its creation recorder (11 such calls across e2e and examples). The generated handler knows the id: in `load = or_create` it computes `__id` and then calls `ctx.create()` without it, relying on the domain method to set it. `#[snapshot(id = "todo_id")]` then tells the snapshot derive which domain field equals the entity id so it can call `set_id` again on restore. Domain unit tests reach into `t.entity.events()`. +- Why it matters: Forgetting `set_id` is a silent domain bug that the framework has the information to prevent. The README's "plain types" example shows `self.entity.set_id(..)` in its first snippet. +- Change: Have the framework own identity: `ctx.create(id)` or `repo.create_with_id(id)` sets it, and replay and snapshot restore set it from the stream id. Then drop `#[snapshot(id = ..)]` and the `id` field synthesised into `XSnapshot`. Keeping an `entity: Entity` field is a reasonable minimum; default the field name to `entity` so `#[sourced]` needs no positional argument. Breaking. Size M. + +### 9. Stringly-typed and redundant arguments +- Category: F Severity: medium Confidence: CONFIRMED +- Where: `distributed_macros/src/sourced.rs:49-56` and `697-701`; `snapshot.rs:210-216`; `portable_command.rs:17-32` +- What: + - `events = "TodoEvent"` is a string turned into an identifier, and the default is already `{Struct}Event`. 25 of the 27 uses spell out exactly the default; the other two are test renames. + - `#[snapshot(entity = "state", id = "todo_id")]` takes field names as strings, while `#[sourced(entity)]` and `#[enqueue(.., entity = f)]` take bare identifiers. + - `aggregate_type = "todo"` is repeated on `#[sourced]` and consumed as a string again in every capture call. + - `authenticated_user_field: (Event, State, "author_id")` names a field by string. + - `#[readmodel(primary_key = ["todo_id"])]` plus `#[readmodel(id)]` on the same field (`tests/e2e-ui/crates/readmodels/src/models/todos.rs`) says the same thing twice. + - Every ReadModel option has two spellings (`#[table("x")]` 67 uses versus `#[readmodel(table = "x")]` 38; `#[id]` 19 versus `#[readmodel(id)]` 11). The derive claims the generic helper names `id`, `index`, `table`, `column`, `unique` and `collection` (`lib.rs:113-116`), which collide with other derives. +- Change: Remove `events =` (or make it an identifier); use identifiers in `#[snapshot]`; keep only namespaced `#[readmodel(..)]`; a single-column `primary_key` implies `id`. Breaking. Size S–M. + +### 10. Generated `…Event` enum and `TryFrom<&EventRecord>` are a second, unused decode path +- Category: C/F Severity: medium Confidence: CONFIRMED (generation); "unused" by rg +- Where: `distributed_macros/src/sourced.rs:940-1017` (enum, `event_name()`, `TryFrom`), versus replay arms at `1029-1058` +- What: Every `#[sourced]` impl emits a public enum with one variant per event, `event_name()`, and a `TryFrom` that repeats the tuple decode of each replay arm. `rg` for `Event::try_from(` and for uses of the enum finds only `tests/sourced*` and the `domain = with(T, adapter)` adapter signature (`:617-618`), which itself has three uses, all in tests. +- Why it matters: Every aggregate pays compile time for it, there are two decode implementations per event, and the pascal-cased last name segment causes a variant-collision error class (`:710-759`) that exists only because of this enum. +- Change: Either route replay through it (decode once to the enum, then one `match`), or drop the enum and give `domain = with` adapters the typed parameters. I would drop `domain = with` as well: `domain = event` and derive `DomainEvent` cover it. Breaking. Size M. + +### 11. Generated code hard-codes `distributed::`, `serde::` and `std::` +- Category: E Severity: medium Confidence: CONFIRMED +- Where: `sourced.rs` (52 bare `distributed::` sites, e.g. `:293`, `:379`, `:1008`), `aggregate.rs:30-66`, `snapshot.rs:162-187`, `read_model/{mod,relational,types,attrs}.rs` (about 77 sites), `mutation.rs:657-664` and every operation (`::distributed::`); `serde::Serialize` at `sourced.rs:430` and `:923`, `snapshot.rs:162` +- What: `framework_path()` exists (`shared.rs:17-32`) and `sourced.rs:675` even calls it, but uses the result only for `SourcedResult`. The renamed-dependency fixture exercises only `command`, `module!`, `application!`, `CommandInput`/`CommandOutput` and `DomainEvent`. So `framework = { package = "distributed" }` works for the newest macros and fails for `#[sourced]`, `Snapshot`, `ReadModel` and `mutation!`. `command.rs:382` shows the right pattern for serde: `#framework::__private::serde`. +- Related: `distributed_macros` maps `FoundCrate::Itself` to `crate` (`shared.rs:19`), while the game crate maps it to `::distributed_game` (`distributed_game_macros/src/shared.rs:14`). `src/lib.rs:12` already has `extern crate self as distributed`, so `::distributed` would work in both cases. +- Change: Use one `framework_path()` everywhere and re-export serde through `__private`. Extend the renamed-dependency fixture to cover `#[sourced]`, `Snapshot` and `ReadModel`. Size M, mechanical. + +### 12. `mutation!` inlines program-building logic that already exists in the runtime, with drift +- Category: C Severity: medium Confidence: CONFIRMED (duplication); behavioural impact PLAUSIBLE +- Where: `distributed_macros/src/mutation.rs:670-920`; runtime twins `src/mutation/descriptor.rs:324-380` (`state_upsert_program_for_model`) and `:387` (`delete_by_pk_program_for_model`) +- What: Each upsert, insert, delete or patch expands to 40–60 lines that loop over `RelationalReadModel::schema()` at run time, with about 20 `.expect("key path")`-style panics whose messages name neither model nor field. The runtime helper types each field with `projection_value_type_for_column(&column.column_type)`. The macro copy uses `ProjectionValueType::String` for every key and field (`mutation.rs:705`, `:719`, `:768`, `:782`, …). I did not trace whether a later bind step corrects the types. +- Why it matters: The same semantics are built twice, and the copies have already diverged. Bad schemas panic with opaque messages instead of returning `Result`. +- Change: The macro should emit data only: `MutationProgram::from_ops(name, version, [MutationOpSpec::Upsert { model: schema::, root: &[..] }, ..])`, with one fallible builder in `src/mutation`. Have the `Mutation` constructor return `Result`, or keep one panic with the model name. Size M. + +### 13. `Snapshot` generates a parallel struct and leaves layout versioning to memory +- Category: A/E Severity: medium Confidence: CONFIRMED (code); corruption scenario PLAUSIBLE +- Where: `distributed_macros/src/snapshot.rs:44-187`; contract at `src/snapshot/snapshottable.rs:15-36` +- What: The derive emits `XSnapshot` with every non-skipped field cloned, `fn snapshot()`, and a restore that assigns field by field. Skip detection (`:263`) recognises only `#[serde(skip)]`. `SNAPSHOT_VERSION` defaults to 1, and the trait docs state the encoding is positional bitcode, so reordering two same-typed fields "decodes successfully into the wrong state". The macro has the field names and types and already fingerprints schemas for `DomainState` (`shared.rs:223-259`, `:564`). +- Why it matters: This is a parallel type of the kind the owner's preferences rule out. An optimisation that needs a manual version bump to stay correct is not transparent. +- Change: Emit an automatic layout fingerprint (hash of ordered field names and types) as the version, or as an extra component alongside a manual bump. Consider snapshotting the aggregate itself, since it already derives `Serialize`/`Deserialize` with `entity` skipped. Breaking. Size M. + +### 14. `domain = event` re-implements `#[derive(DomainEvent)]`; deletion descriptor is built three times +- Category: C Severity: medium Confidence: CONFIRMED +- Where: `distributed_macros/src/sourced.rs:429-473` versus `domain_event.rs:60-104`; `sourced.rs:502-519`, `552-562`, `894-912` +- What: The generated flat body struct plus its five impls are a hand-copied version of the derive's output, with bare paths. The `DomainDeletion` schema, fingerprint and descriptor literal are computed three times in the same file. +- Change: Share one codegen function between derive and `domain = event`. Add a runtime `DomainEventDescriptor::deletion::(name, version)` and call it from all three sites. Size S. + +### 15. Helpers reinvented within and across the macro crates +- Category: C Severity: low Confidence: CONFIRMED +- Where: + - snake-to-Pascal: `sourced.rs:1435`, `aggregate_command.rs:384`, `portable_command.rs:176`, `mutation.rs:335`, `aggregate.rs:81`, `shared.rs:471-487`. + - serde `rename_all`: `shared.rs:471-509` and `command_types.rs:37-99`. The two differ on `lowercase` (one lowercases, the other returns the name unchanged). + - `named_fields`: `domain_state.rs`, `domain_event.rs`, `read_model/mod.rs:79`, and the game `shared.rs`. + - `parse_expr_array` and the whole parse skeleton: `module.rs` and `application.rs` are near-identical files. + - `enqueue.rs:26-48` re-implements `shared::generate_enqueue_call` (`shared.rs:201-220`). + - "ident-or-string first, then `key = value` loop" is hand-written four times (`sourced.rs:29-97`, `113-197`, `digest.rs`, `enqueue.rs`). +- Change: One `names.rs` and one `serde_attrs.rs`; use `syn::meta::parser` or `parse_nested_meta` for key/value lists. Most of this disappears with findings 5–7. Size S–M. + +### 16. Type-name heuristics stand in for trait bounds +- Category: E Severity: low Confidence: CONFIRMED +- Where: `distributed_macros/src/shared.rs:64-73` (`Result`/`SourcedResult` by last segment), `:511-528` (`portable_projection_kind` by identifier), `command.rs:416-446` (`CausalCommandContext` by identifier), `command.rs:548` (`same_type` by token string), `aggregate_command.rs:364-378` +- What: A type alias, a user type named `Value` or `Vec`, or `std::string::String` versus `String` changes the result. The `DomainState` fingerprint hashes type tokens (`shared.rs:234`), so `String` and `std::string::String` produce different contract fingerprints for the same wire shape. +- Change: Where a trait exists (`CommandOutcome`, a `PortableKind` trait implemented for primitives), emit `::CONST` and let rustc resolve it. Size M; the `portable_projection_kind` case first. + +### 17. Compile-fail suite: mostly valuable, with 18 rustc-pinned snapshots +- Category: B Severity: medium Confidence: CONFIRMED +- Where: `distributed_macros/tests/{compile_fail, command_types_compile_fail, command_input_defaults_compile_fail}/`, `distributed_game_macros/tests/compile_fail/` +- What: There are 75 `.stderr` snapshots (39 + 6 + 4 in core, 26 in game). 57 contain only the macro's own `error:` text; these are short (5–8 lines) and worth keeping. 18 are rustc `error[E…]` output. + - Brittle, with standard-library spans, "and $N others" lists or trait-solver wording: `application_command_duplicate_id.stderr` (prints `$RUST/core/src/panic.rs` internals), `input_default_nullable.stderr`, `input_default_list.stderr`, `input_default_wrong_type.stderr`, `game_pure_unsupported_output.stderr`, `input_buttons_on_float.stderr`, `input_unsupported_field.stderr`, `replicated_unsupported_type.stderr`, `replicated_quant_on_integer.stderr`, `predict_returns_state.stderr`. + - Short rustc errors that test a deliberate const-panic or type check; these are acceptable: `domain_adapter_contract_{name,version}_mismatch`, `aggregate_command_principal_input_field`, `domain_adapter_{mismatch,output_mismatch}`, `replicated_from_{missing_field,wrong_type}`. + - `enqueue_renamed_entity.stderr` pins rustc's "no field `entity`" for a macro slated for removal. + - Maintenance cost shows in the tooling: `trybuild` is pinned to `=1.0.121` in both macro crates and `=1.0.118` in `tests/fixtures/renamed-dependency-trybuild/Cargo.toml:15`, and `compile_fail.rs` says regeneration needs `rust-src`. + - Fixtures repeat a 10–15 line aggregate/input/handler preamble across the 11 `application_command_*.rs` files (188 lines in total). + - Two files under `distributed_macros/tests/compile_fail/` belong to no documented macro mode after the removals above: `enqueue_renamed_entity`, `aggregate_unknown_keyword`. +- Change: Keep the 57 macro-diagnostic snapshots. For the 10 brittle ones, either assert that the build fails with a substring (a small harness over `cargo check --message-format=json`) or move the check into the macro so the error is its own. Share one fixture prelude via `include!`. Size M. + +### 18. Expansion-string tests assert token text instead of behaviour +- Category: B Severity: medium Confidence: CONFIRMED +- Where: `distributed_macros/src/entry_tests.rs` (35 tests, 75 `contains(..)` assertions), `src/read_model/tests.rs` (31 tests, 49), `src/snapshot.rs` (13 tests, 18) +- What: Tests assert on `quote!` output text with token spacing, for example: + - `expand_sourced_generates_enum_and_aggregate` checks `out.contains("impl distributed :: Aggregate for Todo")`. + - `expand_sourced_places_state_capture_after_transition_body` compares the string offsets of `digest_v`, `self . completed = true` and `capture_domain_state`. + - `expand_portable_command_emits_thin_mount` checks `contains("load_by")`. + - `expand_snapshot_accepts_named_struct` and `expand_read_model_accepts_named_id_field` check `contains("fn id")`. + - `expand_digest_inserts_digest_call` checks `out.contains("digest")`, which is true of the input attribute name. + + These break on any refactor, including finding 11, and pass when the generated code is wrong. The `*_rejects_*` tests on error messages duplicate trybuild fixtures: `expand_sourced_rejects_duplicate_event_names` and `duplicate_event_names.rs`; `expand_sourced_rejects_variant_ident_collisions` and `sourced_variant_collision.rs`; `expand_snapshot_rejects_tuple_structs` and `snapshot_tuple_struct.rs`. + + Low-value tests in the authoring examples: + - `create_uses_handle_escape_hatch` and `post_uses_handle_escape_hatch` (todo-domain `commands/create.rs`, chat-domain `commands/post.rs`) are `assert_eq!(X::COMMAND, "..."); let _ = handle;` and cannot fail meaningfully. + - `shard_is_todo_id` is copied once per command file to test a one-line closure. + - `tests/legacy_authoring_absence.rs` greps `src/lib.rs` for substrings to prove removed macros stay removed. +- Missing behavioural tests: a failing fallible `#[event]` body (finding 1); a conditional overwrite after a "known" assignment (finding 2); a renamed dependency with `#[sourced]`, `Snapshot` or `ReadModel` (finding 11); staleness of `mutation_file!` (finding 4). +- Change: Keep parser unit tests such as `parse_*_args_*` and the fingerprint-freeze tests (`expansion_freezes_domain_state_schema_and_fingerprint` pins a wire contract). Replace `contains` tests with the existing behavioural suites under `tests/sourced` and `tests/aggregate_command`, and delete the duplicated rejects. Size M. + +### 19. Generated panics on runtime paths +- Category: E Severity: low Confidence: CONFIRMED +- Where: `distributed_macros/src/command.rs:346`, `:398`, `:408`; `module.rs:129`; `application.rs:116`; `mutation.rs:664` and the `.expect` calls from `696` to `915` +- What: These are `LazyLock` initialisers with `unwrap_or_else(|e| panic!(..))`. The first access panics, possibly while serving a request, and the lock is poisoned afterwards. The mutation `.expect("field")` messages carry no model or column. +- Why it matters: `sourced.rs` and `aggregate_command.rs` are clean here (errors map to `EventRecordError` and `HandlerError`), so this is confined to code that findings 5, 6 and 12 remove or rewrite. +- Change: Covered by 5, 6 and 12; whatever remains should return `Result` from a function validated at `Service` build time. + +### 20. `FactCommand` and `TicketExtension` reject field names by a deny list +- Category: F Severity: low Confidence: CONFIRMED +- Where: `distributed_game_macros/src/trusted.rs` (`FORBIDDEN`, 24 names including `user`, `amount`, `cost`, `credit`, `grant`, `sub`), mirrored in `distributed_game/tests/fixtures/trusted_field_denylist.json` +- What: The derive fails compilation when a field or serde rename normalises to a listed word. It is a lint, not a security boundary (`gold_amt` passes), and it blocks legitimate names such as `amount` of damage or `cost` of a path. The test `deny_list_matches_the_shared_fixture` parses the JSON by string slicing. +- Change: Keep it if the owner values the guard rail, but add an opt-out (`#[fact(allow_name)]`) and say in the error that it is a lint. Otherwise leave it alone. + +## Things that are good and should not be changed +- **`distributed_game_macros` as the template.** Expansions are thin calls into generic runtime functions (`#rt::__private::wasm_export::(..)`, `::encode`). Crate paths are resolved once, items use `::core`/`::std` paths, errors are spanned at the user's token with `quote_spanned!`, and multiple errors are combined (`trusted.rs` `reject_forbidden`). +- **`aggregate_command.rs`.** The `#[principal]` parameter is bound only from the verified session, with a compile-time check that the input has no field of the same name (`:520-534`). The generated handler is small and panic-free. This is the right canonical command form. +- **Domain-recorder restrictions in `#[sourced]`.** No return type, no `?`, no `return` (`sourced.rs:257-289`, `761-771`), each with a pointed error. Finding 1 extends this rule; it does not relax it. +- **Compile-time schema fingerprints and typed descriptors** for `DomainState` and `DomainEvent`, and keeping the state DTO separate from the aggregate. The freeze tests on these fingerprints are worth keeping. +- **The 57 short compile-fail snapshots of the macros' own diagnostics**, and the duplicate-name and unknown-key checks behind them. diff --git a/docs/reviews/v5-pre-release/09-cli-client-compiler.md b/docs/reviews/v5-pre-release/09-cli-client-compiler.md new file mode 100644 index 000000000..6e9ef0f4a --- /dev/null +++ b/docs/reviews/v5-pre-release/09-cli-client-compiler.md @@ -0,0 +1,246 @@ +## Assessment: CLI and client code generator (`distributed_cli/`, root `build.rs`, `Makefile`, `distributed.contracts.json`) + +The slice works, but it is roughly twice the size it needs to be. The CLI does not depend on the `distributed` crate (`distributed_cli/Cargo.toml:17-30`), so it re-declares the runtime's wire types and re-implements its semantics in a second Rust copy. About 18.5k non-test lines of `client_compiler/` exist largely for that reason. Version skew cannot justify it: `cli.rs:2824` already requires the manifest's framework release to equal the CLI's `CARGO_PKG_VERSION`. + +The three changes most worth making: +1. **Make the CLI depend on `distributed` (default features off) and `distributed_game`.** Deserialize `DistributedClientManifest` and `GameSurface` directly, share one merge/lowering implementation, and delete the mirrors and dead wire code (findings 1–6). +2. **Shrink `contracts/` and the lifecycle "file adapter" to what is wired.** About 2.7k non-test lines of `contracts/` have no production caller, and `contracts check` does not check what the README says (findings 7–10). +3. **Fix `dev`/`build` process handling and move SvelteKit/npm/e2e-app specifics behind one adapter** (findings 11–15). + +How this was read: I read `client_compiler/{mod, manifest/parse, projection_delta/preview (non-test, about 60%), projection_delta/mod}` and about 45% of `cli.rs` myself, and compared them against `src/graphql/{projection_delta, client_manifest, complexity}`. Three helper agents read `contracts/`, `lifecycle/`, `generate/`, the game/skills/render code and the tests; I re-opened the cited lines for the findings marked CONFIRMED and mark the rest PLAUSIBLE. No cargo or npm was run. + +Not read, or outline only: +- `client_compiler/graphql/{operation, objects, fragments, variables, types, arguments, query_plan}.rs` (outline only) and `graphql/validation.rs` beyond lines 1-110 +- `client_compiler/manifest/{model_validation (lines 1-45 and 1340-1500 only), projections, projectors, roots, leaderboards, util}.rs` +- `client_compiler/command_manifest/{effects, confirmations, shape, support, protocol}.rs` bodies +- `client_compiler/projection_delta/wire.rs` beyond line 60, and `islands.rs` +- `client_compiler/tests.rs` about 55% (helper), `tests/cli_client.rs` 520-795, `tests/cli_skills_init.rs`, `tests/bats/lifecycle.bats` +- `skills/*/SKILL.md` end to end, most fixture files, `distributed_cli/README.md` + +All paths below are under `/Users/patrickleet/dev/hops-ops/hops/distributed/`. + +--- + +### 1. The CLI is a second implementation of the runtime's client-manifest contract +- Category: C/A Severity: high Confidence: CONFIRMED +- Where: `distributed_cli/Cargo.toml:17-30` (no `distributed` dependency); `distributed_cli/src/client_compiler/manifest/types.rs:9-1149` versus `src/graphql/client_manifest/types.rs:129` (and the rest of that file); `client_compiler/manifest/parse.rs:13-53`, `:255-281`; `client_compiler/manifest/mod.rs:20-29`; `src/lib.rs:40` +- What: `client_compiler/manifest/types.rs` re-declares the runtime's `Client*` types as about 110 `Manifest*` serde types. + - Both sides use `deny_unknown_fields`. + - The CLI recomputes `schema_fingerprint` from its own mirror (`parse.rs:255`). + - The CLI hard-codes the protocol fingerprint as a literal (`mod.rs:22-23`), which the runtime computes in `src/graphql/client_manifest/codec.rs:258`. + - Seven version constants are copied (`mod.rs:20-29`; `cli.rs:47-48` adds a third copy of the manifest version). + - `pub mod graphql` is not feature-gated (`src/lib.rs:40`), and `src/graphql/client_manifest/mod.rs:5` calls itself "intentionally pool-free". +- Why it matters: this is Principle 5 inside Rust. Every manifest change is a hand-synchronised edit in two crates. Byte-exact fixtures catch drift only where one exists. +- Change: `distributed_cli` depends on `distributed` with `default-features = false`. `compile_client` takes `DistributedClientManifest`. Delete `manifest/types.rs`, the fingerprint recomputation, and the copied constants. Breaking: the `compile_client` input type. Size L. + +### 2. Preview canonicalisation and lowering are near-verbatim twins of the runtime's +- Category: C Severity: high Confidence: CONFIRMED +- Where: `client_compiler/projection_delta/preview.rs:1781-1988` versus `src/graphql/projection_delta/canonical.rs:8-305`; `preview.rs:1037-1202` versus `src/graphql/projection_delta/lower.rs:572-784`; `preview.rs:835-842` and `:1090-1094` versus `lower.rs:775-784` +- What: `canonicalize_operations`, `canonicalize_recoveries`, `merge_operation`, `merge_mutation` and `merge_refs` are copied arm for arm, with identical error strings ("patch fields must belong to the upsert replacement mask"). + - They differ already: the runtime re-sorts by `canonical_order` (`canonical.rs:21`, `:65`); the CLI relies on the `BTreeMap` order of `PreviewOperationScope`. + - `lower_record` repeats the runtime's decision table (complete write → Upsert; otherwise Patch plus `IfRecordMissing` recovery; otherwise `Always` recovery) over symbolic `Knowledge` instead of concrete values. + - The "complete write" kind set is written three times. + - The runtime already has a preview source (`ProjectionMutationSource::Preview`, `lower.rs:302`), but it is `#[cfg(test)]`. +- Why it matters: optimistic preview and server delta must agree on merge and recovery semantics, or clients flicker and revalidate. No shared vector pins the two. +- Change: make the canonical merge generic over the value type (`DeltaValue` versus `PreviewExpression`) in the runtime crate and call it from the CLI. Longer term, lower previews through the runtime's `Preview` source. Size M for canonicalisation, L for lowering. + +### 3. Trusted-preset derivation, command-operation text and complexity estimation are also twins +- Category: C Severity: medium Confidence: CONFIRMED +- Where: + - `client_compiler/manifest/model_validation.rs:1348-1487` versus `src/graphql/client_manifest/validation.rs:3-150` + - `client_compiler/command_manifest/shape.rs:239-258` versus `src/graphql/client_manifest/commands.rs:221-242` + - `client_compiler/graphql/validation.rs:3-102` versus `src/graphql/complexity.rs:17-112` +- What: the first two pairs are copied line for line; the CLI regenerates the command mutation text only to byte-compare it with the manifest (`command_manifest/validation.rs:122-129`). + - The complexity estimator has diverged. The runtime floors an empty selection at `w.scalar` (`complexity.rs:53-55`); the CLI folds to 0. + - The CLI uses the manifest's weights; the runtime calls `default_weights()` (`complexity.rs:27`). +- Why it matters: an operation can pass the build-time limit and be rejected by the server, or the reverse. +- Change: with finding 1 done, call the runtime functions. Export one `estimate_complexity(weights, shape)` used by both. Size M. + +### 4. `projection_delta/wire.rs` is about 800 lines of dead mirror code +- Category: F Severity: medium Confidence: CONFIRMED +- Where: `client_compiler/projection_delta/wire.rs:1-7`, `:18`; `projection_delta/mod.rs:11` +- What: the file opens with `allow(dead_code, reason = "...runtime consumption lands in Task 16")`. A search of `distributed_cli/src` shows the only thing used outside the file is the constant `PROJECTION_DELTA_WIRE_VERSION`. The rest mirrors `src/graphql/projection_delta/types.rs` (the wire types, validation and canonical bytes), exercised only by nine in-file tests. +- Why it matters: a third copy of the wire contract with no caller. +- Change: delete the file and take the constant from the runtime. Size S. + +### 5. Legacy "effects/confirmations" command authority is unreachable +- Category: F Severity: medium Confidence: CONFIRMED +- Where: `client_compiler/command_manifest/validation.rs:131-137` then `:149-178`; `client_compiler/manifest/types.rs:520-546`; `manifest/commands.rs:69-74`; `command_manifest/effects.rs:154` (`validate_effect`), `confirmations.rs:17`; `src/graphql/client_manifest/types.rs:518-545` +- What: `extensions.version != 2` returns an error, and the next block is `if extensions.version == 1 { … }`. + - Both fields deserialize through `reject_legacy_command_authority`, which always errors, so they are never `Some`. + - Canonicalisation and tests still exist for them (`command_manifest_tests.rs:261`, `tests.rs:3998`, `:1225`). + - The runtime types carry the same rejecting fields. +- Why it matters: this guards a format that never shipped. `deny_unknown_fields` already rejects the keys. +- Change: delete the fields on both sides, the dead block, `validate_effect`, `validate_confirmations`, and their tests. `validate_defaults`, `validate_trusted_preset_inventory` and `validate_projector_inventory` are live and stay. Size M. + +### 6. `game_client.rs` mirrors `distributed_game`'s `GameSurface` +- Category: C Severity: high Confidence: CONFIRMED (constants and the no-op at `:483` re-opened; the type-by-type comparison is the helper's) +- Where: `distributed_cli/src/game_client.rs:31-34`, `:60-229`, `:483`; `distributed_game/src/surface.rs:40` +- What: 13 private serde types duplicate the surface schema. `GAME_SURFACE_SCHEMA_VERSION = 3` and `PREDICT_ABI_VERSION = 1` are second copies. `protocol_version` is read and discarded: `let _ = (surface.schema_version, surface.protocol_version);`. +- Why it matters: same drift problem as finding 1. Game concepts are compiled into the CLI unconditionally anyway. +- Change: keep the game commands in the one CLI (matches the single-CLI preference), but depend on `distributed_game`, deserialize `GameSurface`, and move structural validation to one `GameSurface::validate()`. Size M. + +### 7. `contracts check` does not check drift, and most of `contracts/` has no production caller +- Category: A/F Severity: high Confidence: CONFIRMED +- Where: `cli.rs:1347-1355`; `distributed.contracts.json:4-16`; `contracts/migrations.rs` (1,513 lines), `snapshots.rs`, `classification.rs`, `closeout.rs`, `program.rs`, `chain.rs`; `lib.rs:36-55`; `Makefile:57-58` +- What: the CLI calls `contracts_check(&catalog, &root, std::iter::empty())`. The check validates catalog structure and that declared paths exist; nothing compares an identity to a baseline. + - The repo catalog has one entry, whose identity is the literal `"ref:migrations"`. + - `check_migration_history`, `check_migration_inventory`, `classify_snapshot_diff`, `close_local_contract_chain` and `classify_release_programs` appear only in `contracts/` and the `lib.rs` re-export. + - Helper-reported, not re-opened: diagnostics tell users to pass `--base `, which `ContractsCheckArgs` does not have; the README says check "exits non-zero on drift"; the check gates CI jobs. +- Why it matters: the gate proves only that `migrations/inventory.json` exists, while carrying compatibility machinery (history immutability, program compatibility classes, five `schema_version` constants that have only ever been 1). +- Caveat: the repo has tags up to v4.x. If migration immutability against a released baseline is wanted, wire `--base` rather than deleting the history half. +- Change: either dispatch per kind so `check` runs the migration check, or delete the subcommand, the Makefile target and the unwired modules. Keep a catalog of `{kind, owner, sources, generator, outputs, predecessor}` for the lifecycle graph. Breaking: the `distributed_cli::contracts` public surface and catalog schema. Size L, mostly deletion. + +### 8. Root `build.rs` and `contracts/migrations.rs` are twins, and the one that runs is `build.rs` +- Category: C Severity: high Confidence: CONFIRMED (constants on both sides re-opened; function-level pairs are the helper's) +- Where: `build.rs:9-18` versus `contracts/migrations.rs:27-45`; helper-listed pairs include `validate_json_nesting` (`build.rs:338` / `migrations.rs:817`), `collect_sql_files` (`:418` / `:1158`), `read_bounded_file` (`:383` / `:1378`), `sha256_hex` (`:571` / `:1422`) +- What: eight identical limit constants and about eight identical functions, roughly 450 of `build.rs`'s 576 lines. The CLI copy is the unreachable one (finding 7). The helper found they have diverged: the CLI adds a `validate_json_value` pass that `build.rs` lacks. There is no third copy in `src/`. +- Why it matters: hostile-input limits (JSON depth 24, 4,096 directories, path redaction) applied to the repo's own checked-in inventory, twice. +- Change: slim `build.rs` to parse, check consecutive versions, verify sha256 and emit; delete the CLI copy with finding 7. Size M. + +### 9. `contracts accept` ignores its scope and its rollback is best-effort +- Category: E Severity: medium Confidence: CONFIRMED for the rollback lines; PLAUSIBLE for the rest (helper) +- Where: `contracts/transaction.rs:167-178`; helper cites `:108-191`, `:224-236` +- What: per file it runs `create_dir_all(...)?`, which returns after earlier files were already replaced. Rollback errors are discarded (`let _ = rollback(root, &prior);`). The staging name is `path.with_extension("distributed-accept-staging")`, so `a.json` and `a.ts` collide. Helper-reported: `scope` is only echoed in the report, and nothing in the repo produces the staged JSON it consumes. +- Why it matters: a command that writes arbitrary paths under root with a label for a scope and no caller. +- Change: delete `accept` until something produces its input. If kept, resolve the scope to the catalog entry's `outputs` and write all temp files before any rename. Size S. + +### 10. The lifecycle "file adapter" path exists only for old fixtures +- Category: F Severity: medium Confidence: CONFIRMED +- Where: `cli.rs:156-164`, `:190-198` ("Deprecated alias", hidden `--root`/`--catalog`/`--config`), `:786-901`, `:984-1003`, `:1302-1328`; `lifecycle/build.rs:180` ("retained for the compatibility file-adapter API"); `lib.rs:58-60` +- What: `resolve_lifecycle_project` has two modes, `Discovered` and `Files`. The `Files` mode needs `distributed.lifecycle.json`, which does not exist at the repo root. The helper found it referenced only by `cli.rs` and `tests/cli_lifecycle.rs`. That gives two option types (`LifecycleBuildOptions`/`LifecycleDevOptions` versus the project-plan types) and two entry points. +- Why it matters: `cli_lifecycle.rs`, the behavioural test suite for build/dev, exercises only the legacy adapter; the discovered path is touched only by the bats file. +- Change: delete the adapter and hidden flags; port `cli_lifecycle.rs` to build a project plan and call `run_lifecycle_project_build/dev`. Size M. + +### 11. `dev` orphans its children on anything but Ctrl-C +- Category: E Severity: high Confidence: CONFIRMED (static read; not run) +- Where: `distributed_cli/Cargo.toml:22` (`ctrlc = "3"`, no `termination` feature); `cli.rs:1270`; `lifecycle/dev.rs:1183`, `:1283` (`command.process_group(0)`); the only `Drop` impls in `lifecycle/` are `BuildLock` (`build.rs:1253`) and `DevStateStore` (`dev.rs:824`) +- What: the handler catches SIGINT only. Children run in their own process groups, so the terminal's signal does not reach them, and there is no `Drop` cleanup for the child set. +- Why it matters: closing the terminal, `kill`, a container stop, or a panic in the supervisor leaves `cargo run` and `npm run dev` holding ports 8791/5180. +- Change: enable `ctrlc`'s `termination` feature and add a `Drop` that signals each group. Size S. + +### 12. Build cancellation kills only the direct child; a transient file error ends the dev session +- Category: E Severity: high Confidence: CONFIRMED for the code paths; the editor-race trigger is PLAUSIBLE +- Where: `lifecycle/build.rs:677-689` (executor spawned without a process group); `lifecycle/dev.rs:335`, `:381-387` +- What: the executor child is `distributed describe`, which itself blocks in `cargo run`; cancel kills the leader and leaves cargo/rustc running on the same harness target dir. Separately, the watch loop does `let next = lifecycle_input_snapshot(...)?;`, so any error from the directory walk returns from the loop and shuts everything down. +- Why it matters: `dev` cancels on every superseding edit, so "cancel" saves nothing and the next build queues behind the orphan. A file removed between `read_dir` and `open` (editor swap file, `git checkout`) ends the session. +- Change: spawn executors with `process_group(0)` and reuse the dev group-kill helpers; in the watch loop treat snapshot errors as "not quiet yet" and retry. Size S/M. + +### 13. The generic lifecycle and compiler are hard-wired to SvelteKit, npm and the repo's e2e app +- Category: A Severity: medium Confidence: CONFIRMED +- Where: `lifecycle/project.rs:271`, `:355`, `:364`, `:1007`, `:1012`, `:1065-1068`; `cli.rs:1139-1183`, `:1228-1243`; `client_compiler/render/project.rs:78-79`, `:323-385`; `render/commands.rs:229`, `:237`; `client_compiler/mod.rs:1`, `:137-141` +- What: + - The lifecycle executor is `"distributed.sveltekit-clients"` at `node_modules/@hops-ops/distributed/dist/sveltekit/lifecycle-compiler.js`. + - The package manager is `npm` (`ci`/`install`/`run`) only. + - Every UI process gets `E2E_API_ORIGIN` and an `AUTH_SECRET` default; the helper found `E2E_API_ORIGIN` read only under `tests/e2e-*`. + - Ports default to 8791 and 5180. + - The compiler's module doc says "Pure, framework-neutral… Svelte, Vite, and router concepts must never enter this type", yet `render_project` always emits `sveltekit.ts` and fails compilation on SvelteKit naming collisions, and `pures.ts` imports through `$lib/…`. +- Why it matters: a layering inversion. `js/src/react` exists, but a React or pnpm project gets SvelteKit output and npm behaviour, and a test fixture's env contract ships in the product. +- Change: one UI adapter fed by `[workspace.metadata.distributed.ui]` (command, env, package manager); drop `E2E_API_ORIGIN`/`AUTH_*` (the e2e app's `.env` is already loaded by `cli.rs:903`); make `sveltekit.ts` and the `$lib` alias a `--target` render pass. Breaking: generated file set. Size M. + +### 14. The manifest harness resolves dependencies separately from the user's workspace +- Category: E Severity: medium Confidence: CONFIRMED structurally (`manifest_harness.rs:87-113` re-opened); consequences PLAUSIBLE +- Where: `manifest_harness.rs:75-125`, `:185-196`; `cli.rs:2884-2911` +- What: it writes a temporary crate under `/distributed-manifest-harness//` with its own `[workspace]`, takes an unbounded `lock_exclusive`, and runs `cargo run --quiet`. Helper-reported: the user's `Cargo.lock` and `[patch]` are not applied; schema modes need a local `distributed` checkout found by walking ancestors; the extern name is derived from the package name, so a custom `[lib] name` breaks. +- Why it matters: the manifest can be produced from different dependency versions than the app runs, and each Rust save compiles the service in two target dirs. +- Change: copy the workspace lockfile into the harness, take the lib target name and `distributed` path from `cargo metadata`, add a lock timeout. Better: have the runtime binary emit the manifest. Size M. + +### 15. `describe` writes WASM into a watched input directory; generations are never pruned +- Category: A/E Severity: medium Confidence: CONFIRMED for the write site and the absence of pruning; loop consequences PLAUSIBLE +- Where: `cli.rs:1750-1760`; `wasm_pures.rs:92-99`, `:594-621` (helper); `rg remove_dir_all distributed_cli/src/lifecycle` returns nothing +- What: when `DISTRIBUTED_LIFECYCLE_ROOT` is set, `describe` calls `build_declared_wasm_pures`, which the helper traced to `ui/src/lib`, a declared input of the clients node. So a read-style command changes behaviour on ambient env vars and mutates inputs mid-build. Separately, every rebuild adds a directory under `generations/` and nothing removes old ones. +- Why it matters: this bypasses the staged, atomic generation model the lifecycle is built around, and a dev session grows the generation store by a full client tree per save. +- Change: make WASM a catalog node with staged outputs; prune to active plus the last N generations under the build lock. Size M. + +### 16. `cli.rs` holds business logic, two identical command enums, and never-shipped compatibility +- Category: F Severity: medium Confidence: CONFIRMED +- Where: `cli.rs:58-90` versus `:117-149`; `:712-732` versus `:763-783`; `:761-762`; `:318-327`, `:603-605`, `:2631-2647`; `:2152-2155`, `:2193-2228`, `:3133`; `:1091-1097`; `:1773-2367` +- What: + - `DistributedCommands` and `ServiceCommands` are the same 14 variants with two identical dispatchers and a test (`:3234`) to keep them in sync. The doc on `run` says hosts call it "without mounting the aggregate contracts surface", but it mounts `Contracts`. + - About 600 lines of generated-directory ownership logic and about 230 lines of skills wiring live in the clap file. + - Compatibility for things that never shipped: `--kind` "Compatibility alias", `--http`/`--knative` "Compatibility shortcut", a single-variant `Framework` enum, and `compiler_manifest_version` `Some(1 | 2)` with a v1 `routes.ts` cleanup branch. + - Error phase is classified by substring: `error.contains("manifest harness failed for package")`. +- Command surface: `build`, `dev`, `contracts {check, accept}`, `scaffold` (alias `create`), `describe`, `client`, `client-manifest`, `game-manifest`, `game-client`, `game-wasm`, `schema`, `skills {init, list}`, hidden `__probe`, `__js-watch`. +- Overlap and vestige: `describe`/`client-manifest`/`game-manifest`/`schema` are four modes of one harness with repeated flag sets. `contracts accept` is vestigial (finding 9). `client-manifest` output gets only a shallow third validator (`cli.rs:2834-2882`). +- Change: one command enum with a `command_prefix` parameter; move client-output writing to its own module; delete the compatibility flags and the v1 branch; give the harness error a typed variant. Size M. + +### 17. Two generated-directory writers with different guarantees +- Category: C/E Severity: medium Confidence: CONFIRMED +- Where: `cli.rs:1986-2018`, `:2060-2115`, `:2255-2297` (GraphQL client) versus `:2469-2547` (game client) +- What: the GraphQL writer refuses symlinked path components and tracks ownership through `manifest.json`, then rewrites every file unconditionally (`:2014`). The game writer has no symlink or path checks and judges ownership by a `// @generated` first line, but skips unchanged files so watchers do not reload (`:2537-2542`). The two `--check` loops are near-identical. +- Why it matters: each generator has the protection the other lacks; the GraphQL writer triggers dev-server reloads on every run. +- Change: one `GeneratedDir { write, check }` with symlink refusal and skip-unchanged, used by both. Size M. + +### 18. TypeScript emission is scattered `format!`, with twin helpers across the two generators +- Category: C Severity: medium Confidence: PLAUSIBLE (helper's read; I re-opened only `render/commands.rs:226-240`) +- Where: `game_client.rs:262-355`, `:901-918`, `:1951`; `client_compiler/render/common.rs:3-16`; `render/commands.rs:240`; `render/leaderboards.rs:47`; `render/typescript.rs:185-201` +- What: no emitter abstraction in either generator. + - String literals: a hand escaper plus a weaker `key()` in the game generator, versus `serde_json::to_string` in three error-handling styles in `render/`. + - `commands.rs:240` falls back to `"\"\""` on a serialization "failure" that cannot occur for `&str`. + - Two `pascal` functions, four codec→TS tables, tabs in some files and two spaces in others. +- Determinism: output is deterministic through `BTreeMap`/explicit sorts. The helper flagged two sites that pretty-print a `serde_json::Value` without the canonicaliser used elsewhere (`render/commands.rs:339-342`, `game_client.rs:412-415`); these would change bytes if a consumer's build enables serde_json `preserve_order`. +- Change: one small `ts` module (literal, property, identifier casing, indented block) and one codec→TS table; canonicalise the two JSON sites. Size M. + +### 19. Low-value tests in `client_compiler` and `contracts` +- Category: B Severity: medium Confidence: CONFIRMED for the named tests I opened (`tests.rs:3077`, the six `preview.rs` tests); the rest are the helpers' reads +- Where and what: + - `client_compiler/tests.rs:3077` `command_protocol_and_extensions_are_preserved_exactly`: about 825 lines, about 25 manifest variants, around 100 `contains("\"version\": 2")`-style substring checks on pretty-printed output. These strings occur in many places, so the test can pass for the wrong reason. + - `preview.rs:2253`, `:2270`, `:2386`, `:2416`, `:2590`, `:2605`: these exercise `Knowledge::Unset`/`CacheUnowned`, variants marked `allow(dead_code)` and "reserved" at `preview.rs:23-33`, which production never constructs. + - `command_manifest_tests.rs:261`, `tests.rs:3998`, `:1225`: legacy authority that serde can never deliver (finding 5). + - `tests.rs:2055-2063`, `runtime_bridge_tests.rs:106-112`: `contains` checks already implied by the byte-exact golden beside them. + - `tests.rs:4481`: the lazy-commands golden is compared after a `.replace(...)`, so it is not real output. + - `contracts/transaction.rs:304` `check_report_is_no_write` builds `ok: true` and asserts it; `contracts/tests.rs:1254` asserts `canonical_bytes() == canonical_bytes()`; `contracts/tests.rs:1272` compares fixture files to literals without running production code. + - `tests/cli_scaffold.rs`: six tests repeat `contains` checks already in `generate/mod.rs` through a subprocess; `bus_variants_render_gitops_bus_config` pins `HOPS_BUS`, which nothing reads (finding 21). + - Setup duplication: 40 call sites hand-build `ClientCompileInput` next to existing helpers; the `todo.create` manifest is written out at least twice; `cli_client.rs:11-274` carries another 264-line hand-written manifest. + - Goldens: nine GraphQL golden files have no regeneration path; `UPDATE_GOLDEN` exists only in `tests/cli_game_client.rs:57`. +- Change: split the megatest per scenario and assert on parsed artifact JSON; delete the tests of unreachable states; one `assert_golden` helper honouring `UPDATE_GOLDEN`. Size M. + +### 20. Generated output with no behavioural test +- Category: B Severity: medium Confidence: PLAUSIBLE (helper searched; I did not repeat the search) +- Where: `client_compiler/render/commands.rs:164-258` (`pures.ts`); `render/project.rs:99-170`, `:323-525` +- What: GraphQL `pures.ts` has no assertion anywhere in the compiler tests, `distributed_cli/tests`, `js/tests` or root `tests/`. It interpolates manifest strings raw into import statements (`commands.rs:229-232`, re-opened). `sveltekit.ts`, `islands.ts`, `protocol.ts` and `index.ts` are only substring-checked, and `generated-commands.ts` type-checks against a hand-written `protocol.d.ts` stub rather than the generated `protocol.ts`. +- What is covered well: the game chain runs Rust derives → pinned TS → `tsc` → a byte-for-byte codec round trip in Node. Operation and command JSON artifacts are executed by `js/tests/replica-*`. Real-Rust end-to-end exists but is `#[ignore]` by default (`tests/cli_manifest.rs:124`, `tests/cli_game_client.rs:175`). +- Change: generate one whole project (commands, pures, live, leaderboards) into a pinned directory included in the JS type-check; validate `client_module`/`client_export`/`wasm_package` as path/identifier grammar. Size M. + +### 21. Scaffold flags that do nothing, and org-specific templates +- Category: F/A Severity: medium Confidence: CONFIRMED for `HOPS_BUS`, the in-memory default and the org strings; the rest PLAUSIBLE (helper) +- Where: `generate/gitops.rs:120`, `:127`, `:330`; `generate/service_crate.rs:134-139`; `generate/github.rs:112`, `:154`, `:230`; `cli.rs:2737-2769` +- What: + - `--bus` emits a `HOPS_BUS` env var that appears only in the generator, one test and a skill doc. + - Helper-reported: without `--query-api`, `--store postgres` still generates `service::in_memory()` and only adds a cargo feature. + - Templates are `format!` raw strings pinned to `unbounded-tech/workflows-gitops/...@v1`, `workflow-vnext-tag@v1.21.3`, image `ghcr.io/hops-ops/` and label `hops.ops.com.ai/service`. + - `--github` runs `gh repo create --private`. + - No Upbound packages are referenced. +- Why it matters: dead configuration, and one organisation's deployment conventions inside the framework CLI. +- Change: wire or drop `--store`/`--bus`; move gitops/github generation to the host `hops` CLI, which already mounts these commands, or behind one explicit preset. Size M. + +### 22. Duplicated plumbing across lifecycle, harness and WASM modules +- Category: C Severity: low Confidence: PLAUSIBLE (helper's line list; not re-opened) +- Where: `cargo metadata` wrappers at `lifecycle/project.rs:417`, `wasm_pures.rs:260`, `manifest_harness.rs:285`; bounded directory walkers at `lifecycle/build.rs:927`, `js_framework.rs:609`, `wasm_pures.rs:374`, `:455`; atomic write at `dev.rs:656`, `build.rs:1075`, `js_framework.rs:360`; `toml_string`/`is_rust_ident` in both `generate/names.rs` and `manifest_harness.rs`; two WASM stamp formats (`game_wasm.rs:47-57` versus `wasm_pures.rs:69-76`) +- What: three sets of metadata structs, four walkers with duplicated limits, and two staleness rules for "compile a Rust function for the browser" (one hashes the module, one checks file existence). +- Change: one file-utility module and one cargo-metadata module loaded once per invocation; one stamp type. Size M. + +### 23. Generated `predict.ts`/`input.ts` may reference undeclared record constants +- Category: E Severity: medium Confidence: PLAUSIBLE (helper's read; not executed and not re-opened) +- Where: `game_client.rs:921-936`, `:1083-1129`, `:1579-1586`, `:723-727` +- What: a record-typed field lowers to a bare `{NAME}_TYPE` identifier. Those constants are declared only in `events.ts` (unexported) and `pures.ts`. `predict.ts` builds its context layout from record fields but imports neither, and `check_predict` only checks that the context record exists. The pinned sample has a scalar-only context, so nothing would catch it. +- Change: reject non-scalar context/input fields in validation, or emit the type constants as `pures_ts` does; add a nested-record context to the authoring fixture. Size S. + +### 24. `skills.rs` is reasonable but its content partly targets the framework repo +- Category: F Severity: low Confidence: PLAUSIBLE (helper) +- Where: `skills.rs:36-83`, `:127-131`; `cli.rs:1432-1570`; `skills/distributed-usage/SKILL.md:177-178`, `:286`, `:314-322` +- What: it embeds five `SKILL.md` files with `include_str!`. `skills init` writes them under `.distributed/skills/`, links them into hard-coded `.claude/skills/` and `.agents/skills/`, and adds a marked block to `AGENTS.md`. + - No stale commands or flags were found against clap. + - `distributed-usage` tells an agent in a user project to copy `tests/e2e-ui/` and run `cd tests/e2e-ui && make`, which do not exist there. + - The game skill does not mention `game-manifest`/`game-client`/`game-wasm`. +- Verdict: it belongs. The skills version with the command surface; the cost is the hard-coded harness directories. +- Change: fix the content; move the wiring logic out of `cli.rs`. Size S. + +--- + +## Things that are good and should not be changed +- `compile_client` is a pure function (manifest plus documents in, sorted files out) with stable, source-located error codes. Keep that boundary when switching its input type. +- Deterministic output by construction: `BTreeMap`/`BTreeSet` and explicit sorts throughout, with provenance written last so an interrupted run never advertises a complete generation (`cli.rs:2005-2008`). +- The exact release handshake between manifest and CLI (`cli.rs:2824`). It is what makes sharing types with the runtime safe. +- The game generator's test chain (Rust derives → pinned TS → `tsc` → Node codec round trip, with `UPDATE_GOLDEN`). It is the model the GraphQL goldens should follow. +- The staged-generation build with an flock-guarded activation, and `tests/cli_lifecycle.rs`'s real-binary, descendant-leak-checking style. Keep the tests; point them at the project path instead of the legacy adapter. diff --git a/docs/reviews/v5-pre-release/10-game-runtime.md b/docs/reviews/v5-pre-release/10-game-runtime.md new file mode 100644 index 000000000..a6f539a37 --- /dev/null +++ b/docs/reviews/v5-pre-release/10-game-runtime.md @@ -0,0 +1,211 @@ +## Assessment — realtime game runtime slice (`distributed_game`, `examples/game`, `tests/celld`, `tests/bomberman`, two docs) + +The simulation core is in good shape: `ZoneHost` is synchronous and transport-agnostic, keeps players/clients/observers in `BTreeMap`s, uses a seeded RNG and sim-time timers, and has bounds-checked wire decoders. Durable state goes through idempotent commands into aggregates (facts, `ZoneLease`, `ZoneState`), so the unidirectional principle is honoured. The weak layer is everything around the core: there are two full drivers (`net/mod.rs` and `celld_zone/object.rs`) that each re-implement admission, tick loop, netsim, hibernation and fact plumbing, with different security and durability behaviour. + +Nothing here was compiled or run (per the brief); every finding is from reading the cited lines. + +The three things most worth changing: +1. **Ownership and activation safety on the native server** — unauthenticated activation (finding 1), fencing-token reuse after a crash-restart (2), and no self-fencing when lease renewal fails (3). +2. **One driver contract instead of two-and-a-half** — a single admission function and a single stimulus enum shared by `net`, `celld_zone` and `replay` (4, 5, 13). +3. **Pre-release cleanup** — drop protocol v1 negotiation, `CellFactSink`, the hand-rolled HTTP peer client and the duplicate `DelayLine` (10, 11, 12, 14). + +Core-crate contamination is minimal: only doc comments mentioning bomberman/zones, `BindingKind::Zones` in the gateway config, and the game-flavoured `src/leaderboard` (2.5k lines, another reviewer's slice). + +**Not read, or only skimmed:** +- `src/`: `celld_zone/cells.rs`, `celld_zone/plan.rs`, `world/{watch,zone_status,zone_activity,content_rollout,allocation,directory,topology,barrier}.rs`, `surface.rs`, `schema.rs` (only `MAX_FIELDS`), `authoring.rs` (partial), `pure.rs`, `prediction.rs`, `bots.rs`, `stamp.rs`, `claims.rs`, `work.rs`, `metrics.rs` body, `net/inbox.rs`, `net/world.rs` body, `net/ticket.rs` (only `NonceCache`), `replay.rs` (header, outline and `replay_with` start only), `collide.rs` shape maths (lines 136–660, 870–990). +- `object.rs`: read 455–975, 1064–1292, 1407–1530, 1795–2234; the rest outlined only. +- Tests: only function lists for `golden`, `replication`, `netcode`, `authoring`; other test bodies unread. +- `examples/game`: only `rooms/src/zone.rs` 1196–1330, the `zone/cross.rs` header and outlines; client TS, sveltekit, `tiers`, `crawler`, `service`, `cells` unread. +- `tests/celld/*` workers unread; `tests/bomberman` only the `main.rs` header and `tick_saga.rs`. +- `docs/coordination-primitives.md`: headings only. + +--- + +### 1. Unauthenticated Hello activates zones and writes durable state before the ticket is verified +- Category: E Severity: high Confidence: CONFIRMED +- Where: `distributed_game/src/net/mod.rs:1689` (`route_zone`) runs before `:1719` (`verify_hello_ticket`); `activate_local` `:831-866`; `run_zone` `:1082-1137`; default `hibernate_after: None` `:215` +- What: Any client that sends a well-formed Hello with a supported protocol version triggers `activate_local`. That inserts into `zones`, calls the facts factory (spawning a fact worker, `:853`), spawns `run_zone`, acquires an ownership claim, loads the state store and allocation store, and runs the game's factory. The ticket is only checked afterwards. +- Why it matters: With `CellZoneOwnership`, each garbage Hello for a new zone id creates a `ZoneLease` aggregate plus `zone.activated`/`zone.released` events and read-model rows for an attacker-chosen id. For ids the factory accepts (the doc example is `starts_with("arena-")`), the zone starts Hot and, with `hibernate_after: None`, is never removed. That is unbounded memory, tasks and lease renewals from unauthenticated traffic. +- Change: Verify signature, expiry and zone match first; use `directory.locate` alone for the Redirect path; only then activate, and consume the nonce after. Add a `max_zones` cap. (M) + +### 2. Fencing token and `boot_epoch` can repeat after a crash-restart, so new facts are dropped as replays +- Category: E Severity: high Confidence: CONFIRMED (code path; not executed) +- Where: `net/mod.rs:432,844,1083` (holder is `"{host_id}#{activation}"`, a per-process counter from 1); `:1145` (`boot_epoch = claim.token`); `world/zone_lease.rs:285-293`, `src/lease/in_memory.rs:99`, `src/lease/sqlx_store.rs:196` (same holder re-acquiring gets the same token) +- What: A host that crashes without releasing and restarts inside the TTL (15 s) builds the same holder string for any zone that gets the same activation ordinal, for example the first zone activated after boot. Durable ownership then returns the old claim and token. +- Why it matters: `host.rs:98-103` says `boot_epoch` must differ between activations. With the same epoch and tick/player ids restarting from zero, keys like `{cmd}:{zone}:{epoch}:t{tick}:{n}` and lifecycle keys collide with the previous run. The command ledger treats them as replays, so kills, XP and join facts vanish with a "committed (replayed)" receipt. +- Change: Put a per-process nonce (start micros or a UUID) in the holder: `"{host_id}#{process_nonce}#{activation}"`. Add a conformance test: a restarted holder gets a larger token. (S) + +### 3. A zone keeps simulating and committing facts after its lease may have expired +- Category: E Severity: high Confidence: CONFIRMED +- Where: `net/mod.rs:1049-1068` (`Err(OwnershipError::Backend(_)) => continue`, forever); `:1262-1267` and `:1343-1347` (after `Exit::Lost`, `dispose()` runs `on_leave` hooks and the fact worker still drains the queue) +- What: Renewal that fails with backend errors retries indefinitely with no local deadline; `ZoneClaim.expires_at` is never consulted. The zone ticks through a partition while another host can acquire it. Even on a clean `Lost`, queued and dispose-time facts are committed, and facts carry no fencing check (the stamp's `activation` is informational). +- Why it matters: This is a split-brain window bounded only by partition length. Snapshots are fenced, facts are not, so two activations of a zone can both credit kills. +- Change: Track the last successful renewal and self-fence (freeze, then drop without dispose-time facts) at `ttl − margin`. Put a timeout on the renew call. On `Lost`, close the fact queue without draining, or have the sink pass the token so the cell can reject stale activations. (M) + +### 4. Admission is implemented twice with different rules (native vs celld) +- Category: A/C (principle 7) Severity: high Confidence: CONFIRMED +- Where: `net/mod.rs:1659-1838` plus `verify_hello_ticket` `:1954-1985`; `celld_zone/object.rs:1795-1992` +- What: Both do protocol check, ticket verify, zone match, nonce, join/transfer/reconnect. They differ in these ways: + - **Ticket checks:** native runs `validate_extensions`, the custom `ticket_verifier`, and empty-principal/nonce checks; celld calls only `key.verify_ticket` (no `validate_extensions` or `ticket_verifier` hit under `src/celld_zone/`). + - **Transfers:** native uses Reserve/Confirm/Release/Return with the issuer's registry; celld persists a nonce in object storage and has no return-to-source path. + - **Rate limiting:** native has a per-connection token bucket (`:1622`); celld has none (`object.rs:1136-1160` feeds every Input to the host). + - **Hello deadline:** native enforces `hello_timeout`; celld accepts any upgrade (`:1102-1104`), keeps it indefinitely, and answers unauthenticated Pings (`:1166`). +- Why it matters: A game configured with ticket extensions gets them enforced on one backend and silently ignored on the other. Every admission fix has to be made twice. +- Change: Extract one transport-agnostic `admit(hello, now, &mut NonceStore, &TransferLedger, &AdmissionConfig) -> AdmitDecision` plus one `InputGate` (the bucket) into the crate core; both drivers call them. Breaking: `ServerConfig` ticket fields move into a shared `AdmissionConfig`. (L) + +### 5. Un-rate-limited message types and an unbounded command drain can starve the tick +- Category: E/D Severity: medium Confidence: CONFIRMED +- Where: `net/mod.rs:1902-1935` (only `Input` goes through `bucket.take()`; `Focus`, `Content`, `Ping`, repeated `Hello` and malformed frames are unlimited); `:1274-1278` (`while let Ok(cmd) = rx.try_recv()` with no budget); `:843` (one 1024-slot command channel shared by all connections) +- What: A client can flood `Focus`/`Content` (each `Content` carries a string up to the 64 KiB frame limit). Each becomes a `ZoneCmd` on the shared channel, and the zone task drains until empty before the next `advance()`. +- Why it matters: A few flooding connections delay ticks and other players' inputs behind FIFO backpressure. `on_observer_focus` is a game hook, so the per-command cost is game-defined. +- Change: Run every post-Hello client message through the bucket and kick on sustained decode errors. Cap the drain per iteration (N commands or until the next tick is due). Coalesce `Focus` per connection. (S) + +### 6. `Heightfield::raycast` can hang a zone on a long or infinite ray +- Category: E Severity: medium Confidence: CONFIRMED +- Where: `distributed_game/src/collide.rs:426-458`; `Ray::new` `:88-101` allows `max_dist = INFINITY` +- What: The march advances `t` by `cell/2` until `t >= max_dist`, with no clipping to the heightfield's bounds. Off-grid `under()` is false, so the loop continues. With `f32::INFINITY` or `f32::MAX` the loop never ends once `t + step == t`; with a large finite range it does millions of `height_at` calls. +- Why it matters: `Ray::new(o, d, f32::MAX)` is an idiomatic "no limit" ray. A hang is worse than a panic: the zone task spins and the lease keeps renewing. +- Change: Clip the ray to the heightfield AABB (xy extent, `[min_h, top]`) before marching and march only that interval. (S) + +### 7. Lag compensation clones and interpolates every entity per query and allocates per entity per tick +- Category: D Severity: medium Confidence: CONFIRMED +- Where: `rewind.rs:391-402` (`at_time` builds a fresh `Vec`, each with a cloned `fields: Vec`); callers `:441`, `:461`, `:500`; `host.rs:770-775` (`Ctx::raycast` at "now" also goes through `at_time`); `host.rs:2159-2166` (new `RewindFrame` Vec per tick) +- What: Each shot, raycast or overlap costs O(N) clones and allocations with no spatial filter. Recording allocates a new frame, plus one Vec per entity with fields, every tick. +- Why it matters: M shooters × N entities per tick with heap churn on the hottest gameplay path. A bouncing laser calls it once per leg. +- Change: Iterate frames by reference and lerp position on the fly, materialising `Historic` only for the winning hit. Recycle the popped frame's Vec in `record`. Store fields in a small inline array or one flat `Vec` per frame. (M) + +### 8. Static `Colliders` have no broadphase +- Category: D Severity: medium Confidence: CONFIRMED +- Where: `collide.rs:728-760` (`raycast`), `:768-800` (`ground_at`), `:803-818` (`push_out`: three passes over all shapes) +- What: Every query scans every shape; movers call `push_out` and `ground_at` each tick. +- Why it matters: Cost is O(movers × shapes × 3) per tick. Geometry is static (set once in `on_create`) and `interest::SpatialGrid` already exists in the crate. +- Change: Build a uniform grid of shape indices in `set_colliders` / `Colliders::push` and query candidates from it. API unchanged. (M) + +### 9. Each patch allocates at least three times per entity even when nothing changed +- Category: D Severity: medium Confidence: CONFIRMED +- Where: `replication.rs:297-318` (per entity: `Writer::new()`, `offsets` Vec, `data` Vec, then compared with the previous payload); `replication.rs:64` (`fields: Vec` per entity per patch); `host.rs:2181-2186` (fresh `WorldView` each patch); `interest.rs:120` (grid `HashMap<_, Vec>` rebuilt each patch) +- What: The encode-once/shared-revision design is good, but the "unchanged" check happens after building the full dynamic `FieldValue` vector and encoding into fresh buffers. `build_delta` also takes `&EncodedWorld` and locks an internal `Mutex` (`:249,454`) for what is single-threaded scratch. +- Why it matters: An idle world of 1,000 entities at 20 Hz does 60k+ allocations per second per zone. +- Change: Have `Replicated` encode straight into a per-patch arena (`Vec` plus an offsets table) and compare against the previous payload slice, allocating an `Arc` only on change. Reuse `WorldView` and grid buffers across patches. Pass the update cache as `&mut` instead of a `Mutex`. Breaking: `EntityState.fields` / `FieldValue` leave the hot path. (M–L) + +### 10. Wire protocol carries v1/v2 negotiation before first release +- Category: F Severity: medium Confidence: CONFIRMED +- Where: `protocol/messages.rs:10-18` (`PROTOCOL_VERSION = 2`, `MIN_PROTOCOL_VERSION = 1`), `:498`, `:613-617`; `host.rs:979-980,1248-1251,1301,1511` (`next_protocol`, `speaking()`); `tests/golden/main.rs:639` `welcome_decodes_only_in_the_version_offered` +- What: The host keeps one-shot "protocol of the next admission" state so a v1 client gets a v1 Welcome. `feature::ALL` advertises a single `FOCUS` bit. +- Why it matters: Nothing is released, so this is compat for clients that do not exist. `speaking()` is a stateful one-call modifier that is easy to misuse. +- Change: One protocol version. Delete `MIN_PROTOCOL_VERSION`, `speaking`, `next_protocol`, the v1 Welcome branches and fixtures, and the `features` field until a second feature exists. (S) + +### 11. `CellFactSink` is superseded and unused outside its own test +- Category: C/F Severity: medium Confidence: CONFIRMED +- Where: `cell.rs:36-67,237-270`; rg over `*.rs` and `*.md` (not `js/`, which is TypeScript) finds it only in `lib.rs` docs, `README.md`, `cell.rs` and `tests/cell_sink/main.rs` +- What: This is a second in-process fact sink beside `CommandFactSink` (`command_sink.rs:428`). "Retryable" is classified three ways: + - `cell.rs:228-235`: only InProgress/Internal. + - `command_sink.rs:383-399`: also 5xx/408/429. + - `cell.rs:180-182`: by status code and error code string. +- Why it matters: Parallel types, and retry semantics differ by sink. +- Change: Delete `CellFactSink` and `tests/cell_sink`. Keep `command_id_for`, `trusted_session` and `run_fact_batch`, and use one `is_retryable` classification. (S) + +### 12. Host-to-host calls use a hand-rolled plaintext HTTP/1.1 client +- Category: E/F Severity: medium Confidence: CONFIRMED +- Where: `net/peer.rs:22-105` (raw `TcpStream`, `strip_prefix("http://")` only, `format!`-built request with the admin secret header, unbounded `read_to_end`, hand-written `dechunk`) +- What: Transfer reserve/confirm, child events, zone messages and barrier phases between hosts go over this client. +- Why it matters: The admin secret travels in clear text and cannot use TLS. There is no response size cap. The crate already depends on `reqwest` (feature `celld`), and core has `HttpCommandHost` and an internal-secret scheme. +- Change: Use `reqwest` with the core `InternalHttpSecret` header convention. Delete `post_inner` and `dechunk`. (S) + +### 13. `Recorder` is a hand-mirrored wrapper of `ZoneHost`, is not used by either driver, and has drifted +- Category: A/F Severity: medium Confidence: CONFIRMED +- Where: `replay.rs:1060-1408` (about 25 pass-through methods); rg finds `Recorder` only in `tests/world_host` and `tests/netcode`; no `deliver_zone`, `observer_focus` or `content_patched` in `replay.rs`; `put_config`/`get_config` `:566-680` hand-serialise `HostConfig` +- What: Record/replay only works if a caller drives the wrapper instead of the host. `net::run_zone` and `ZoneObject` call `ZoneHost` directly, so production sessions cannot be recorded. Zones that use zone messages (the mobpit example does) are not captured and will diverge on replay. Three parallel stimulus vocabularies exist: `replay::Event`, `net::ZoneCmd` (`net/mod.rs:232-290`) and `object.rs` `InItem`. +- Why it matters: This is the wrapper-type pattern the owner rejects, and 1.8k lines of the most valuable debugging tool are unreachable in production. +- Change: Define one `Stimulus` enum and `ZoneHost::apply(Stimulus) -> Outcome`. Make recording an optional tap inside the host (`with_recording(sink)`). `ZoneCmd` and `replay::Event` collapse onto it; `Recorder` is deleted. (L) + +### 14. Dev netsim is implemented twice and lives in both production paths +- Category: C Severity: low-medium Confidence: CONFIRMED +- Where: `netsim.rs:146-205` (`DelayLine`, f64 ms; used by `object.rs:696-697`) and a private copy at `net/mod.rs:1569-1613` (`Instant`-based) +- What: Two order-preserving delay lines. `ZoneObject` keeps per-socket `out_lines`/`in_lines` maps and routes every frame through `push` even with no simulation. +- Change: Use `netsim::DelayLine` in `net` (convert `Instant` to ms) and delete the copy. Give `DelayLine` a bound. (S) + +### 15. Native and celld give different fact durability +- Category: A (principle 7) Severity: medium Confidence: CONFIRMED +- Where: `facts.rs:351-356,412-433` (in-memory `VecDeque`); `net/mod.rs:1343-1347` (drain bounded by a 2 s `settle_timeout`, then the worker is detached); `object.rs:459-534` (`DurableFacts`: journal written to object storage after the tick and deleted on settle); `command_sink.rs:25-29` ("No local durable fallback") +- What: On celld, emitted facts survive a crash via the outbox. On the native server, unsettled facts are lost on crash and on a slow shutdown. The API and docs call both "durable facts". +- Why it matters: The same game code credits XP at-least-once on one backend and at-most-once on the other. +- Change: Make the journal a host-level seam (`FactJournal` trait: append after tick, delete on settle, list on wake). Native gets a sqlite/file implementation; celld keeps storage. Otherwise document native as at-most-once and rename accordingly. (M) + +### 16. The example re-implements a fact backlog the host already has privately +- Category: C/F Severity: medium Confidence: CONFIRMED +- Where: `examples/game/server/rooms/src/zone.rs:1292-1330` (`flush_backlog`: retry queue on `Backpressure`, `pending` map keyed by fact key); `host.rs:296,356-370` (`lifecycle_backlog` / `flush_lifecycle`, the same pattern, private) +- What: `Ctx::emit*` returns `EmitError::Backpressure` and every game must keep its own queue plus key→context map to correlate `on_fact_settled`. Hand-written `encode_carried`/`decode_carried` (`zone.rs:1098-1130`) also sit beside the `Wire` derive. +- Change: Add `Ctx::emit_queued(player, input)` backed by one host backlog (lifecycle facts use it too); `Backpressure` stops being a routine caller concern. Make `Ctx::handoff` carried state a `Wire` type. (M) + +### 17. Handoff custody of carried state is the client, and the issuer registry is in memory +- Category: E Severity: medium Confidence: CONFIRMED (design) +- Where: `host.rs:881-938,2052-2056` (player removed from the source as soon as the hook returns; state rides in the signed ticket sent to the client); `net/transfer.rs:66-123` (`TransferRegistry` is a `HashMap` in the issuing process); `net/mod.rs:1734-1746` +- What: The no-duplication guarantee holds. But a client that drops the ticket, or an issuer restart ("unknown transfer"), loses the carried state: the player exists in neither zone. A client can also deliberately discard a ticket carrying bad state and rejoin fresh. +- Change: Either document handoff as at-most-once and client-droppable and tell games to carry only non-authoritative state, or park the departure in the source zone until Confirm or TTL (the example's `Parked` at `zone.rs:971-980` already does this in game code). (M) + +### 18. Lease renewal is an event-sourced heartbeat +- Category: D Severity: low-medium Confidence: PLAUSIBLE (stream growth inferred, not measured) +- Where: `world/zone_lease.rs:132-135,319-344` (`zone_lease.renewed` event per renew); `net/mod.rs:216-217` (renew every 5 s) +- What: Each running zone appends about 17k `renewed` events per day to its `ZoneLease` stream and reschedules its expiry alarm each time. +- Change: Renew at about TTL/3 with a longer TTL (for example 60 s / 20 s), and confirm cell compaction drops events behind the snapshot. (S) + +### 19. `commit_barrier` / `abort_barrier` ignore the barrier id +- Category: E/F Severity: low Confidence: CONFIRMED +- Where: `net/mod.rs:641-647` (`_barrier: u64`), `:667` +- What: A delayed commit or abort from an older barrier applies to whatever barrier is current. `world.barrier` holds the id but is never compared. +- Change: Check the id against `world.barrier` and no-op on mismatch, or remove the parameter. (S) + +### 20. Ownership contention is reported as NOT_FOUND, and a crash-restart refuses joins for up to the TTL +- Category: E Severity: low Confidence: CONFIRMED +- Where: `net/mod.rs:1084-1088` (acquire failure → `error::NOT_FOUND`); `activation_timeout` 5 s vs `ownership_ttl` 15 s (`:216-218`) +- What: "Zone is owned by X" surfaces to clients as not found. After an unclean restart (once finding 2 is fixed, the holder always differs) joins fail for up to 15 s although only 5 s is waited. +- Change: Return `ZONE_UNAVAILABLE` and make `activation_timeout >= ownership_ttl` by default. (S) + +### 21. `NonceCache` does an O(n) sweep per join once past 1,024 live nonces and is unbounded +- Category: D Severity: low Confidence: CONFIRMED +- Where: `net/ticket.rs:382-384` (`retain` on every insert while `len > 1024`), under the global `inner.nonces` mutex (`net/mod.rs:1762`) +- Change: Sweep on a time interval or use an expiry-ordered queue; cap the size. (S) + +### 22. Test fixtures: about ten bespoke test zones, one duplicated inside `src` +- Category: B Severity: low Confidence: CONFIRMED (structure; bodies mostly unread) +- Where: + - `impl Zone for` in `tests/{entities,zone_runtime/arena,authoring,inbox,netcode,world/realm,celld_zone_lease,zone_message}`. + - `Dots` defined twice: `src/metrics.rs:641` and `src/work.rs:125`. + - No test found for a restarted holder's token (finding 2), renew-failure self-fencing (3), admission parity between drivers (4), or a heightfield ray with a huge range (6). +- What is valuable and should stay: `tests/golden` (cross-language byte fixtures), `tests/netcode` `recorded_session_replays_identically` and `mutated_input_diverges_at_the_consuming_tick`, and `ownership_conformance` (`world/ownership.rs:274`). +- Change: One shared `tests/support` zone; an admission conformance suite run against both drivers; add the four missing tests. (M) + +### 23. Giant files: jobs and seams +- Category: F Severity: medium Confidence: CONFIRMED +- `celld_zone/object.rs` (2580 lines) holds eight jobs: `CelldObjectHost` fact transport (253-457), durable outbox (459-534), JS clock/random (545-600), netsim plumbing (716-833), the DO entry points (1069-1282), world-watch reconcile (1527-1795), admission (1795-1992), and tick/persist/hibernate/alarm (2043-2440). Seams: `object_host.rs`, `outbox.rs`, `platform.rs`, `watch_sync.rs`, `lifecycle.rs`; admission goes to the shared module from finding 4. +- `net/mod.rs` (2063 lines): server config and builder (100-802), activation and ownership (804-1068), `run_zone` (1071-1405), command handling (1407-1536), connection (1538-2038). Seams: `server.rs`, `activation.rs`, `zone_task.rs`, `connection.rs`. +- `host.rs` (2351 lines): `Ctx` (414-956) is a separate job from `ZoneHost`. Admission (1253-1554) has near-duplicate `PlayerJoined` blocks at 1366-1386 and 1419-1441. Seams: `ctx.rs`, `membership.rs`, `advance.rs`. +- `replay.rs` (1792 lines): binary codec (442-1045) vs recorder vs replayer; shrinks to codec plus replayer after finding 13. +- `collide.rs` (1.4k lines) is half a kinematic physics library (`push_out`, `ground_at`, ramps, heightfield, `walkable`) in a crate whose docs say "Physics is out of scope" (`lib.rs:40`). The example's character controller (`examples/game/server/sim/src/mobpit.rs:273-470`) is the other half every 3D game would copy. Decide: move `collide` and a controller into an optional `distributed_game_physics` crate, or own it. + +### 24. Small duplications and leftovers +- Category: C Severity: low Confidence: CONFIRMED +- `encode_segment` exists twice (`celld.rs:27`, `celld_zone/object.rs:234`); the shard/segment validity predicate three times (`celld.rs:21-25`, `command_sink.rs:281-285`, `FactCall` docs). +- `default_token` (`host.rs:2335-2351`) builds session tokens from `RandomState`, which is not a CSPRNG contract and is a fixed key on wasm32-unknown-unknown; both drivers override it. `ZoneHost::new` should take the token source as a required argument. Same for `unix_micros()` when `boot_epoch == 0` (`host.rs:1000-1002`). +- Two game models coexist without guidance: `tests/bomberman` (every tick is aggregates plus a saga) and `distributed_game` (in-memory zone plus facts). `src/microsvc/cell_host/store.rs:48,186` doc comments describe the generic parent-shard cell in bomberman terms. +- `docs/external-facts.md` is 78 lines with no headings or examples and is not game-specific; restructure it or fold it into the core docs. + +### Look-alike modules: verdicts +| Game module | Core counterpart | Verdict | +|---|---|---| +| `lease.rs` (entity lending between zones) | `src/lease` | Different concept, tick-based and message-driven. Keep, but rename (`lend.rs` / `EntityLoan`) to stop the name collision. | +| `world/ownership.rs` + `world/zone_lease.rs` | `src/lease`, `schedule` | Reuses core correctly. | +| `facts.rs` (queue/feed/pump) | `src/outbox` | Justified: the tick must never await. Not durable on native (finding 15). | +| `timers.rs` | `src/schedule` | Justified: sim-time and deterministic. Fine. | +| `clock.rs` | `src/clock.rs` | Justified: monotonic `Duration` vs wall `SystemTime`, and the crate works without `distributed`. The same names (`Clock`, `ManualClock`, `SystemClock`) in both crates will confuse; consider `ZoneClock`. | +| `inbox.rs` | bus | Justified: direct to a running zone, at-most-once. | +| `metrics.rs` | `src/metrics` | Rationale is documented at the top of the file (instance-scoped, zone label cap). Acceptable, though a hand-written Prometheus renderer is a second one in the repo. | +| `command_sink.rs` / `cell.rs` | commands | Reuses core. `cell.rs` `CellFactSink` is redundant (finding 11). | + +### Things that are good and should not be changed +- `ZoneHost` being synchronous, transport-agnostic and clock-injected, with `BTreeMap` state, a seeded `ZoneRng`, sim-time timers and per-tick state hashes. This is what makes replay and both drivers possible. +- Facts as idempotent commands with host-bound principals and restart-safe keys (`fact_key` plus deterministic `command_id_for`); zones never write durable state directly. +- `ZoneLease` / `ZoneState` as event-sourced cells with fencing tokens and schedule-declared expiry, and `FencedLeaseOwnership` over the core `LeaseStore`. +- The replication design: encode once per patch, shared revisions, a priority accumulator that never starves, hysteresis, deterministic candidate ordering. Optimise its allocations (finding 9), not its shape. +- Bounds-checked wire decoding (`Reader::raw`, count ≤ remaining before `with_capacity`, 1 MiB blob cap) and the golden byte fixtures shared with the JS client. diff --git a/docs/reviews/v5-pre-release/11-typescript-client.md b/docs/reviews/v5-pre-release/11-typescript-client.md new file mode 100644 index 000000000..026e6b4db --- /dev/null +++ b/docs/reviews/v5-pre-release/11-typescript-client.md @@ -0,0 +1,242 @@ +## Assessment: TypeScript client (`js/`) + +Health is mixed. The causal protocol layer is careful and well tested: fences on every async boundary, three-valued filter/order evaluation that falls back to revalidation, bounded parsers, clean layering (core never imports a binding), and almost no `any` or `ts-ignore`. The engine underneath it is still the "executable spike", though. Every cache transaction deep-clones and re-sorts the whole cache several times, nothing in the package ever calls `gc()`, and a dropped WebSocket is never reopened automatically. Structurally, the big modules were split mechanically ("body-split") rather than along real seams. + +The three things most worth changing: +1. **Cache engine cost model.** Replace the O(whole cache) × ~6 per-transaction work with structural sharing and an undo log, and wire eviction (findings 1, 3, 4). +2. **Live transport.** Add automatic reconnect with resume cursors, and multiplex subscriptions over one socket (finding 2). +3. **Rust↔TS contract.** There is no golden protocol-envelope fixture, the query-plan corpus has 4 cases, a dead TS twin of a Rust function is exported publicly, and the same state format is parsed by three hand-written parsers (findings 6–9). + +Not read, or only skimmed: +- **`impl.ts`:** lines 1760–1975 and 2294–3060 (membership fences, shared-index disposition, record-evidence resolution) were not read. +- **`command-runtime/create.ts`:** lines 1–430 and 650–1190 were only outlined. +- **`projection-delta/validate.ts` and `commands/validate.ts`:** outline plus spot reads only. +- **`replica/identity/codec.ts`:** first 110 lines only. +- **Not opened:** `normalize.ts`, `materialize.ts`, `selection.ts`, `revalidation.ts`, `persistence/outbox.ts`, `sveltekit/lifecycle.ts`, `boundary-lifecycle.ts`, `boundary-variables.ts`, `server-replica.ts`, `leaderboard.ts`, `sveltekit/game/*`, and all of `game/*` beyond imports and `codec.ts` head. +- **`sveltekit/vite.ts`:** outline plus lines 1655–1806 only; `islands/boundaries.ts` outline only. +- **Tests:** sampled, not read end to end (`replica-protocol`, `replica-command-runtime`, `sveltekit-vite`, `cache-engine-conformance`, the corpus and bridge tests). Type-tests were sized only. + +Race correctness inside `#writeProtocolResult` was not audited beyond reading lines 1133–1732 once. Nothing was executed. + +### 1. Every cache transaction is O(entire cache) several times over +- Category: D Severity: high Confidence: CONFIRMED +- Where: `js/src/internal/cache-engine/engine.ts:1603-1632` (`#transaction`), `:1659-1672` (`#backup`), `:973-986` and `:1001-1004` (`#reconcileDerivedIndexes` → `extract()`), `:357-416` (`extract`), `:701-742` (`#materialize`), `:536-548` (`#reader`), `:1634-1643` (`#flushWatchers`) +- What: + - `#transaction` starts every outermost transaction with `structuredClone` of all records, indexes and layers. This covers each live frame, HTTP result, optimistic layer create/replace/accept/confirm/reject, and `markIndexStale`. + - Each transaction then calls `#reconcileDerivedIndexes`, which runs `this.extract()` (a full deep clone that sorts every record key and field name with `localeCompare`) plus two full `#materialize()` copies. + - Layer operations add two more `#materialize()` calls (before/after). + - Each affected watcher re-runs `#select`, which calls `#reader` and therefore `#materialize()` again, then `deepEqual`s the whole result. + - The code says so itself at `:540-543`: "V1 executable-spike tradeoff: materializing the visible graph is O(records + indexes + overlay operations) per selector." + - On top of that, the reconciler in `impl.ts:2229-2268` copies every record again (`index-maintenance/engine.ts:298-324`) and instantiates all plans against all indexes. +- Why it matters: Replica apply and live delivery are the hot path for a realtime framework. Cost per delta grows linearly with session cache size, with a large constant, and the cache is never evicted (finding 3). +- Change: Keep the `CacheEngine` interface and replace the internals. Use persistent/structurally-shared maps (rollback becomes keeping the old root), maintain the visible graph incrementally per touched key, and hand the reconciler a changed-keys view instead of `extract()`. Drop `localeCompare` for code-unit compare. Size L. Add a scaling test (10k records, 50 watchers, 100 deltas). + +### 2. A dropped live WebSocket is never reopened; one socket per live query +- Category: E/D Severity: high Confidence: CONFIRMED +- Where: `js/src/replica/distributed-replica/impl-fetch-live.ts:347-362` (error handler), `:363-366` (complete), `:507-548` (`failLive`, the only path with a retry timer); `js/src/websocket.ts:123` (`new WebSocketImpl` per `subscribe`), `:124` (`operationId = '1'`), `:201-209` (onerror/onclose); `js/src/replica/graphql-transport.ts:237-245`; test `terminal live errors close their stream and allow a later HTTP retry` at `js/tests/replica-protocol.test.mjs:2762` +- What: + - A transport error deletes the live entry, sets `state.live = 'error'` and stops. No timer, no HTTP fallback. + - The following `complete` is ignored because the entry is gone, and the transport wrapper has already closed. + - The stream reopens only if some unrelated result ingestion calls `resumeLiveWatches()` or the app calls `watch.refresh()`. The test codifies the manual refresh. + - Backoff exists only for server failure frames. The game client has its own reconnect with backoff (`game/connection.ts:236-288`); the main client has none. + - `subscribe()` opens a dedicated socket with a hard-coded operation id, so N live queries means N sockets and N `connection_init` handshakes. + - No `online` or `visibilitychange` handling exists in any binding (rg found none). +- Why it matters: After a server restart, network blip or laptop sleep, live queries silently stop updating until something else happens to write. +- Change: Make the live transport a single multiplexed connection that reconnects with jittered backoff and re-subscribes with `resumeCursors`. Treat transport error like `failLive` (inactive sentinel plus retry timer) and do an HTTP refresh on reconnect. Share the backoff/scheduler helper with `game/connection.ts`. Breaking: `subscribe()` signature and connection ownership. Size M. + +### 3. Nothing evicts: `gc()` has no caller and causal maps only clear on auth purge +- Category: D/E Severity: high Confidence: CONFIRMED +- Where: `js/src/replica/distributed-replica/impl.ts:2017-2029` (`gc`), `:217-219` (`#recordClocks`, `#recordKeysByScope`, `#projectedRecordFences`), `:212`, `:215-216`; clears only at `impl-protocol.ts:195-210` and `impl-hydration-orchestrate.ts:526-539` +- What: + - `rg "\.gc\(\)"` across `js/src`, `tests/e2e-ui/ui/src` and `examples` finds only the definition. No binding, timer or watch teardown calls it. + - `gc()` returns the collected keys, but the replica does not use them to drop `#recordClocks` or `#recordKeysByScope` entries. + - `#queryStates`, `#operationProtocols` and `#operationGenerations` gain an entry per (operation, variables) and are never deleted when a watch is destroyed. + - Only `#anonymousRecordClocks` is bounded (`MAX_ANONYMOUS_RECORD_CLOCKS`). +- Why it matters: A long-lived SPA session with paging or search grows without bound, and finding 1 makes every delta pay for that growth. +- Change: Tie retention to watches. On last-watch destroy (after a grace period), drop the operation's protocol state and run an incremental collect that also prunes record clocks for collected keys. Remove public `retainRecord`/`releaseRecord`/`gc` unless a binding uses them. Size M. + +### 4. `replica.read()` registers plans that are only released by `dehydrate()` +- Category: E/D Severity: medium Confidence: CONFIRMED +- Where: `impl.ts:872-884` (`read` → `#rememberRenderedOperation(..., 'read')`), `:2189-2190`, `:2199-2211` (`#forgetRenderedWatch` skips disposal when `#readOperationKeys.has(key)`), `impl-hydration-orchestrate.ts:223-237` (only place `readOperationKeys` is cleared); `js/src/react/query.ts:66-72` +- What: `read()` adds the key to `#readOperationKeys` and registers an index-maintenance plan. That set is cleared only by `finishDehydration`, which is an SSR path. React's `getSnapshot` calls `replica.read()` before `subscribe`, so every (operation, variables) a React app renders keeps its `#renderedOperations` entry and plan after unmount. +- Why it matters: It is a leak, and every leaked plan is re-evaluated on every reconcile. +- Change: Make `read()` side-effect free (no registration). Have the SSR collector register explicitly via a scoped handle the server disposes. Size S–M. + +### 5. Command runtime keeps one canonical delta string per command forever +- Category: E Severity: medium Confidence: CONFIRMED +- Where: `js/src/replica/command-runtime/create.ts:482-483`, `:638-644` +- What: `projectionReplays.set(commandId, canonical)` and `projectionRevalidations.set(...)` have no `.delete` or `.clear` anywhere (rg confirms), including in dispose. +- Why it matters: Memory grows per eventual-consistency command for the lifetime of the runtime. +- Change: Delete both entries when the layer retires or rejects, where `pending` and `unmanagedLayers` are already cleaned. Size S. + +### 6. No shared golden for the response protocol envelope +- Category: C/B Severity: high Confidence: CONFIRMED +- Where: `js/src/protocol.ts` (1038 lines; limits at `:252-261`), Rust `src/graphql/protocol/types.rs`, `src/graphql/query_protocol.rs:559` (`MAX_PROTOCOL_EVIDENCE_ITEMS = 4_096`), `src/graphql/compile/evidence.rs:11`; `js/src/replica/distributed-replica/constants.ts:5-6` +- What: + - `extensions.distributed` (snapshot, live, command, trustedPresets) is hand-parsed in TS against shapes Rust serde defines. + - Shared fixtures exist for the projection delta, command projection metadata, mutation program, operation artifact and query-plan corpus. None exists for the envelope: no JSON fixture in `tests/fixtures` or `distributed_cli/tests/fixtures` contains `authorizationGeneration`. + - Both sides build envelopes by hand in tests (`js/tests/replica-rust-artifact-bridge.test.mjs:49-80`, `src/graphql/protocol/tests.rs`). + - Limits are duplicated as literals in three files. A comment at `constants.ts:5` reads "Matches protocol.ts MAX_EVIDENCE_ITEMS without making it public API". +- Why it matters: This is the hottest Rust↔TS seam, and a renamed or added field on either side will pass both test suites. +- Change: Have a Rust test emit `tests/fixtures/protocol-envelope-v1.json` (query snapshot, live snapshot and delta frames, failure frame, each command state). Parse it in a TS test and feed it to `writeResult`. Emit the limits into that fixture or the generated artifact. Size M. + +### 7. `lowerMutationCache` is a public, unused TS twin of Rust `lower_mutation_cache` +- Category: A/F Severity: medium Confidence: CONFIRMED +- Where: `js/src/replica/mutation-cache.ts:1-168` (header: "Mirrors `distributed::mutation::cache::lower_mutation_cache`"), exported at `js/src/replica/index.ts:250-263` +- What: Whole-repo rg (excluding `node_modules`, `dist`, `target`) finds no caller in `js/src`, the CLI renderers, e2e-ui or examples. The only consumer is `js/tests/mutation-cache-lowering.test.mjs`. +- Why it matters: It is exactly the "TypeScript twin" principle 5 forbids, shipped as public API with no runtime use. +- Change: Delete the module, its exports and its test. Rust keeps the fixture. Size S. + +### 8. The dehydrated-state format has three independent parsers +- Category: C Severity: medium Confidence: CONFIRMED +- Where: `js/src/replica/distributed-replica/hydration.ts:88-616`; `js/src/replica/persistence/state.ts:349-1094`; cache engine `parseSnapshot` via `restore` (`engine.ts:418-419`) +- What: + - Hydration and persistence each parse the same `ReplicaDehydratedState`, with their own `parseAuthoritativeScope`, `parseRecordClock`, operation-state parser and primitive helpers. + - The two `parseAuthoritativeScope` copies already differ: one returns `undefined`, the other throws; one uses `hydrationOpaque`, the other `nonEmptyString`. + - `persistence/state.ts:515-521` canonicalises by constructing a whole cache engine, restoring and extracting. + - Decimal comparison exists three times with three algorithms: `protocol.ts:1019` (length then `<`), `clocks.ts:197` (`localeCompare`), `state.ts:1090` (`BigInt`). + - `modelFromRecordKey` is duplicated (`clocks.ts:39`, `state.ts:921`). +- Why it matters: About 1,700 lines must be kept in lockstep by hand, and they already disagree on error behaviour. +- Change: One `parseDehydratedState()` owned by the replica core. Persistence becomes policy-filter-then-store over the parsed value. One decimal comparator in `protocol.ts`. Size M. + +### 9. Filter/order/pagination evaluator is checked against Rust by only 4 cases +- Category: B/A Severity: medium Confidence: CONFIRMED +- Where: `tests/fixtures/client-query-plan-corpus.json` (4 cases, 5 records, columns `id`/`priority`/`completed`, all non-null); consumers `js/tests/replica-query-plan-corpus.test.mjs:43` and `tests/graphql_compile/main.rs:156` (SQLite only); evaluator `js/src/replica/query-plan/filter.ts` (987 lines), `order.ts`, `pagination.ts` +- What: The shared corpus is the right mechanism. It does not cover string ordering (`compareUtf8` against `COLLATE "C"`/`BINARY`), nullable columns and nulls-first/last, tie-breakers, `_in`/`_nin` with NULL, empty `_and`/`_or`, row policies, trusted presets, relationship filters, float/int32 edges, or Postgres at all. Those are tested only in `replica-query-plan.test.mjs` (1307 lines) against expectations written from the TS side. +- Why it matters: This is the largest unavoidable re-implementation of server semantics, and its only cross-language proof is trivial. +- Change: Grow the corpus to cover each operator × codec × nullability × direction, plus row-policy cases and "expected: unknown" cases. Run it on SQLite and Postgres. Retire TS-only tests that then duplicate it. Size M. + +### 10. String `_eq`/`_neq`/`_in` on non-identical strings is "unknown", so string-filtered lists are never maintained locally +- Category: A/D Severity: medium Confidence: CONFIRMED (code); PLAUSIBLE (user-visible impact) +- Where: `js/src/replica/query-plan/filter.ts:507-518`, `:589-598`; `js/src/replica/index-maintenance/engine.ts:623-624`; orphaned doc comment at `filter.ts:660-664`; Rust `src/graphql/compile/projection.rs:1227-1248` +- What: + - `{status: {_eq: "open"}}` against a row with `status: "done"` returns `collation_not_portable`, and `maintainEntityIndex` then marks the index stale. + - ORDER BY is treated differently: the server emits binary collation and TS orders by UTF-8 bytes. + - So the commonest filter shape cannot optimistically remove or exclude a row. An optimistic status change always forces a network revalidation of the list. + - The comment at `:660-664` describes the binary-collation contract but is attached to no function, which looks like a split leftover. +- Why it matters: This undercuts the README's "automatic client side optimism" for the canonical todo-by-status case, and the two halves of the query plan follow different rules. +- Change: Extend the binary-collation contract to equality and IN. Have the SQL compiler emit the same `COLLATE` for textual `=`/`IN`, or declare text read-model columns binary. Then make string `_eq`/`_neq`/`_in` decidable in TS and add corpus cases. I did not measure how often this path fires in the demo apps. Size S (TS) + S (Rust). + +### 11. `impl.ts` split is cosmetic: 370 lines of "Host" accessor bags over one mutable object +- Category: F Severity: medium Confidence: CONFIRMED +- Where: `js/src/replica/distributed-replica/impl.ts:262-570` (five `#xHost()` factories of getters/setters onto `#private` fields), `:2092-2227` (about 25 one-line `fooOn(this.#host())` forwarders), `:3061-3120` (underscore "package-internal" methods for `ReplicaWatchState`); `#writeProtocolResult` at `:1133-1732` is one 600-line method +- What: The `impl-*.ts` siblings are free functions that read and write the class's private maps through host objects such as `ProtocolHost` (about 40 members, including `setProtocolGeneration`, `setNextIndexRevision`, `clearIndexMaintenance`). State ownership is unchanged; it is the same object with indirection. The same pattern appears elsewhere: + - `commands/implementation.ts:1` says "Re-export surface for command implementation modules (body-split)". + - There are three barrel layers per module (`replica/identity.ts` → `identity/index.ts` → `identity/keys.ts`; `index-maintenance.ts` → `index.ts` → `implementation.ts` → `engine.ts`). + - Former privates are now `export function` (`index-maintenance/engine.ts` exports about 40 helpers such as `write`, `stale`, `reason`, `plan`), and tests import them. +- Why it matters: The file count went up and comprehensibility did not. Any function can still mutate any map. +- Change: Split by owned state. Candidates: `RecordClockLedger` (clocks, scopes, anonymous clocks, projected fences), `OperationProtocolTable` (operation protocols, generations, cursors), `LiveCoordinator` (lives, in-flight), `OptimisticReceipts`. Each owns its maps behind a small API, and `#writeProtocolResult` becomes plan (pure, returns a decision struct) then commit. Delete host bags and intermediate barrels; un-export helpers. Size L. + +### 12. Immutable compiler artifacts are fully re-validated on every call +- Category: D Severity: medium Confidence: CONFIRMED +- Where: `js/src/replica/identity/codec.ts:30-43`; `js/src/replica/operation-binding.ts:21-55`; `impl.ts:1025-1028`; `js/src/replica/commands/prepare.ts:97` and `commands/validate.ts:97`; `js/src/react/query.ts:148-152` +- What: + - `canonicalizeOperationVariables` runs `validateReplicaOperationBinding` and `validateVariableCodec`, rebuilding the registry Maps, with no memoisation. No `WeakMap` exists in these modules. + - `read`, `watch` and `writeResult` additionally call `#bindArtifact`, which validates the binding again. + - `useDistributedQuery` does all of this on every React render. + - Every command `invoke` re-runs `validateCommandProjectionArtifact` (part of the 2.6k-line validator) even though the inventory was validated at registration. +- Why it matters: Per-render and per-command CPU spent on frozen generated constants. +- Change: Validate once per artifact identity (a `WeakMap` or validate at inventory/registration) and pass the validated handle inward. Size S. + +### 13. Client assembly (auth fence, transport, hydration, pending receipts) lives in `sveltekit/`; React gets only a hook +- Category: C/F Severity: medium Confidence: CONFIRMED +- Where: `js/src/sveltekit/replica.ts:298-552`, `:899-976` (`PendingReceiptStore`, `wrapCommandTree`), `:1029-1128` (`createAuthorizationFence`, `validatedHydrationAuthority`, `sameReplicaScope`); `js/src/react/query.ts` (178 lines), `react/context.ts` +- What: + - Apart from the query store, nothing in `createDistributedSvelteKit` is Svelte-specific. It handles session → authorization fence → transport → replica → hydrate-before-command-registration ordering → command wrapping → reload registration. + - React exports only `DistributedProvider` and `useDistributedQuery` over a bare replica, so a React app must hand-build the auth fence and hydration ordering. + - No CLI output, example or e2e uses `@hops-ops/distributed/react`. rg finds only the js tests, type-test and pack-smoke. +- Why it matters: The core replica is framework-agnostic, but the composition root is not. React is a query-hook stub, not at parity. +- Change: Extract a framework-neutral `createDistributedClient({session, url, hydration, authority, createCommands})` into core. SvelteKit adds stores and boundaries; React adds the hook plus a pending-receipts hook. Otherwise cut `./react` from v5. Size M. + +### 14. `sveltekit/vite.ts` does seven jobs, and `game/vite` depends on it and so on `svelte/compiler` +- Category: F/A Severity: medium Confidence: CONFIRMED (structure, import chain); load failure without svelte not executed +- Where: `js/src/sveltekit/vite.ts`; `js/src/game/vite.ts:8-16`; `js/src/sveltekit/islands/boundaries.ts` (imports `parse` from `svelte/compiler`); `js/package.json` (svelte is an optional peer) +- What: `vite.ts` holds: + - the GraphQL dev proxy (`:78`); + - the SvelteKit plugin and aliases (`:380-760`, `:1018`); + - the dev-reload lifecycle HTTP middleware (`:802-970`); + - CLI child-process orchestration (`:973-1016`, `:2059-2160`); + - transactional staging, tree diffing and commit (`:1475-1650`, `:1808-2057`); + - a cross-process PID file lock (`:2254-2437`); + - boundary-module TS codegen (`:1725-1806`); + - game generation (`:2516-2765`). + + `game/vite.ts` is documented as "any Vite app (no SvelteKit required)" yet statically imports `../sveltekit/vite.js`, which statically imports `./islands/boundaries.js`, which imports `svelte/compiler`. +- Why it matters: 2.8k lines cannot be held in one head, and a non-Svelte Vite app importing `@hops-ops/distributed/game/vite` needs `svelte` installed to load the module. +- Change: Split into `vite/compiler-process.ts` (spawn, lock, staging), `vite/lifecycle-middleware.ts`, `sveltekit/vite.ts` (aliases, boundaries) and `game/vite.ts` (depends only on `vite/*`). Size M. + +### 15. Two generators own one file: the TS planner appends to the CLI-generated `sveltekit.ts` +- Category: A/C Severity: low-medium Confidence: CONFIRMED +- Where: `js/src/sveltekit/vite.ts:1795-1806` (`exposeBoundaryModule`), `:1729-1793` (`boundaryModuleSource`) +- What: After `distributed client` writes the entrypoint, vite.ts checks its "GENERATED by distributed client" marker and appends an `export { … } from './boundaries.js'` line, then writes `boundaries.ts` itself. `rg boundaries distributed_cli/src` finds nothing, so the CLI is unaware. Client codegen itself is not duplicated: vite.ts shells out to the CLI. Boundary analysis needs the Svelte import graph, so doing it in TS is legitimate. +- Why it matters: The generated tree is a product of two tools, and CLI `--check` output differs from the committed tree. +- Change: Have the CLI always emit the re-export, plus an empty `boundaries.ts` stub the planner overwrites. Otherwise make the planner own a separate entry module. Size S. + +### 16. `wasm-pack` and `graphql` are runtime dependencies of the browser package +- Category: F Severity: medium Confidence: CONFIRMED +- Where: `js/package.json` (`dependencies`); `distributed_cli/src/js_framework.rs:185-186`, `:381-386`; `js/src/document.ts:2`, `:14-16` +- What: `wasm-pack` (which downloads a binary on install) is a hard dependency because the CLI resolves `node_modules/wasm-pack/run.js` from the framework package; no TS file imports it. `graphql`'s `print` is statically imported into the core request and websocket path only to support `DocumentNode` inputs, while generated artifacts already carry string documents. +- Why it matters: Every consumer installs a Rust toolchain helper, and the GraphQL printer lands in every bundle. +- Change: Make `wasm-pack` an optional peer or have the CLI resolve it from the app. Make `GqlDocument` a `string` and drop `graphql` and `@graphql-typed-document-node/core`. Size S. + +### 17. Apollo spike vestiges +- Category: B/F Severity: low Confidence: CONFIRMED +- Where: tests `Apollo 4 public APIs pass basic layers/batching/extract but expose the causal ordering gap` (`js/tests/cache-engine-conformance.test.mjs:1099`) and `built declarations contain no Apollo/vendor types` (`:1146`); `js/scripts/measure-cache-engines.mjs`; devDependency `@apollo/client`; `createCacheEngine` factory with one implementation (`internal/cache-engine/create.ts:6-8`), class `PurposeBuiltCacheEngine`, "selected by the executable spike" at `engine.ts:80` +- What: The first test asserts Apollo's behaviour, not this package's. The second guards against a dependency that exists only for that test. The script benchmarks bundle size against Apollo. +- Change: Delete both tests, the script, the devDependency and the factory indirection; rename the class. Size S. + +### 18. Persistence: orphaned blobs are never pruned; a failed open is cached forever; no cross-tab handling +- Category: E Severity: medium Confidence: CONFIRMED (code); no in-repo consumer exercises it +- Where: `js/src/replica/persistence/state.ts:896-907`, `:887` (`storedAt` parsed, never used for expiry); `js/src/replica/persistence/idb.ts:204-211`, `:249-282`, `:52-69` +- What: + - The key includes `schemaHash` and `authorizationGeneration`, so every schema or auth-generation change leaves the previous whole-cache blob in IndexedDB with no sweep. + - `#databasePromise ??= openDatabase(...)` caches a rejected promise (for example `onblocked`) for the adapter's lifetime. + - There is no `onversionchange` → `close()`, so a second tab's upgrade blocks. + - `save` rewrites the entire state as one record; tabs are last-writer-wins. + - Corruption handling is good: parse failure deletes the entry and returns `undefined`. + - No binding, e2e or example wires `createReplicaIndexedDbPersistence` or `commandOutbox`; only the js README and tests reference them. +- Change: Either cut persistence and outbox from v5 (about 1,800 source lines plus 950 test lines with no consumer) or finish it: sweep by `storedAt` and identity prefix on open, reset the promise on failure, handle `versionchange`, and wire it into the client factory from finding 13. Size S (cut) / M (finish). + +### 19. Diagnostics do a full cache extract per write +- Category: D Severity: low Confidence: CONFIRMED +- Where: `js/src/replica/distributed-replica/impl.ts:1680-1699`; `impl-diagnostics.ts:35-38` +- What: When a diagnostics sink is present, each normalised result calls `engine.extract()` and then `cache.indexes.find` per index key, and `syncDiagnostics` extracts again. This is opt-in only. The event log itself is bounded (`diagnostics/event-log.ts:42-43`, `:170-173`). +- Change: Emit counts from the write summary and make the snapshot lazy (pull on inspect). Size S. + +### 20. Small duplicated helpers despite `src/lib/` +- Category: C Severity: low Confidence: CONFIRMED +- Where: canonical JSON ×3 (`internal/cache-engine/helpers.ts:648`, `replica/identity/clone.ts:55`, `replica/index-maintenance/engine.ts:1106`); `stableJson` ×2 (`sveltekit/boundary-variables.ts:389`, `sveltekit/islands/boundaries.ts:1149`); `compareUtf8` ×2 (`query-plan/order.ts:247`, `projection-delta/validate.ts:2228`); `compareCodeUnits` redefined at `command-runtime/create.ts:334`; `isWithin`/`isMissing`/`portable` in both `vite.ts` and `boundaries.ts`; `exactRecord` ×3; `recordKeyMatchesModel` ×2 +- What: The index-maintenance canonicaliser filters `undefined`, and the cache-key one does not. `sameValue(index.metadata.arguments, planValue.arguments)` at `index-maintenance/engine.ts:512` therefore compares with different rules from those that built the index key. +- Change: Move one of each into `src/lib/` and delete the rest. Size S. + +### 21. Tests reaching into internals +- Category: B Severity: low Confidence: CONFIRMED +- Where: + - `js/tests/unsigned-command-output.test.mjs` (imports `dist/replica/command-runtime/lib/output.js`) + - `js/tests/replica-index-maintenance.test.mjs:5-6` (imports `relationshipMembership` and `replaceOptimisticLayerOn` from implementation files) + - `js/tests/replica-protocol.test.mjs:3758`, `:3785` (imports the private `symbols.js`) + - `js/tests/replica-command-runtime.test.mjs:6` (imports `createCacheEngine`) +- What: These pin the body-split file layout. The suite is otherwise behaviour-first through `dist/replica/index.js`, and `tests/fixtures/adapter-conformance.mjs` is a real shared conformance harness for React and SvelteKit. +- Change: Re-express through `createDistributedReplica` and the command runtime, or move to the shared corpus. Size S. + +### 22. Important behaviour with no test +- Category: B Severity: medium Confidence: CONFIRMED (absence by rg/sampling) +- What: + - automatic live reconnect (finding 2; the existing test asserts the manual path); + - cache or replica scaling (no test with more than a handful of records); + - memory retention after watch destroy (findings 3–5); + - `game/vite` importable without svelte (finding 14); + - multi-tab persistence; + - a Rust-produced protocol envelope ingested by the TS replica (finding 6). + +### Smaller answers to the slice questions +- **Type safety:** clean. 6 `any` (all `GameClient` generics), 13 `as unknown as`, no `ts-ignore`/`ts-expect-error`. +- **`game/`:** a separate binary protocol with its own socket, codec and reconnect logic. It shares nothing with `websocket.ts`. The codec is tested against Rust goldens (`distributed_game/tests/fixtures/`), which is the pattern finding 6 asks for elsewhere. +- **Packaging:** `dist/` is gitignored and not committed (`git ls-files dist` = 0). The exports map is exhaustive and ESM-only, `sideEffects: false`, and node-only code is isolated behind `./sveltekit/vite` and `./game/vite`. + +## Things that are good and should not be changed +- **Three-valued query-plan evaluation** (`match`/`no_match`/`unknown` → mark stale and revalidate) with a typed reason code. Extend what is decidable (findings 9, 10) but keep fail-closed. +- **Server-authoritative replacement of the optimistic guess.** The client previews from the compiler-derived artifact, then swaps the layer for the server's actual projection delta, with capability checks (`command-runtime/create.ts:580-644`). The TS interpreter stays small (`projection-delta/resolve.ts`, `commands/resolve.ts`), and domain "pures" run as the Rust code compiled to WASM (`projection-delta/wasm-pure.ts`). +- **Generation and request-revision fences on every async boundary** (`impl-fetch-live.ts:142-152`, `:167-205`, `:270-318`), and transactional cache writes with rollback semantics. Keep the semantics; change the cost. +- **Shared Rust↔TS fixtures where they exist** (projection-delta, command-projection-metadata, mutation-program, runtime-bridge operation, game goldens), type-checking the CLI's generated fixtures against package types (`tsconfig.generated-tests.json`), and the adapter conformance fixture. +- **Core→binding layering.** `replica/` and `internal/` import nothing from `sveltekit/`, `react/` or `game/`, and `ReplicaWatch` is a framework-neutral primitive that both bindings wrap thinly. diff --git a/docs/reviews/v5-pre-release/12-integration-tests.md b/docs/reviews/v5-pre-release/12-integration-tests.md new file mode 100644 index 000000000..b258f5c8b --- /dev/null +++ b/docs/reviews/v5-pre-release/12-integration-tests.md @@ -0,0 +1,224 @@ +## Assessment + +The suite is mostly behavioural and stronger than the owner's worry suggests. The pure implementation-detail tests are a small, nameable set (roughly 40 functions plus two source-grep files). The larger problems are structural: + +1. **Service-backed tests skip silently, and CI never supplies the service for several of them.** A number of Postgres and broker tests are green without ever executing. +2. **Principle 7 is not actually tested.** GraphQL/RBAC is proven on SQLite only; the transport "conformance" suite mostly runs against fakes; in-memory, Redis and Knative buses run none of the shared bus scenarios. +3. **Copy-paste where a conformance suite should be.** `sqlite_transport` and `postgres_transport` share 804 identical lines; `sqlite_repository` and `postgres_repository` share 437; three broker suites hand-copy the same four failure-path tests. + +Beyond those: pre-release legacy/upgrade tests, and 87 separately linked test binaries with almost no shared fixtures. + +**What I read** +- **Fully:** `tests/support/*.rs`, `tests/legacy_authoring_absence.rs`, `tests/persistent_repository_conformance/mod.rs`, the three `*_repository_conformance/main.rs`, `tests/transport_in_memory/main.rs`, `tests/graphql_postgres/main.rs`, `tests/graphql_oidc_keycloak/main.rs`, `tests/named_read_models.rs`, the Makefile, and workflows `rust.yml`, `test-all-features`, `integration-{postgres,kafka,nats,rabbitmq}`, `on-pr-quality`. +- **Partially (outline plus 100–400 lines each):** `graphql_query_protocol/main.rs`, `typed_commands/main.rs`, `distributed_read_model/main.rs`, `application_composition.rs`, `sqlite_transport`, `postgres_transport` (mostly by diff against sqlite), `kafka_transport`, `nats_transport`, `rabbitmq_transport`, `transport_conformance/mod.rs`, `sqlite_repository`, `aggregate_command`, `sagas/orchestration.rs`, `e2e_ui_celld_nats_profile`, `core_command_contract.rs`, `upcasting`, `sourced_upcasting`, `sourced/main.rs`, `graphql_sdl`, `graphql_engine`, `graphql_harden/softskip.rs`, `sql_lock_manager`, `coordination_lease`, `schedule_worker`, and workflows `integration-gateway`, `integration-graphql`, `integration-observability`, `integration-e2e-ui` (job outline only). +- **Test names and grep only:** `causal_wait_path`, `graphql_sqlite`, `graphql_harden/{authz,dos,inject,errors,transport,residual,dialect}`, `graphql_identity`, `gateway_*.rs`, `edge_query_delivery*.rs`, `domain_event_projection_server.rs`, `read_model_*`, `replay_event_version.rs`, `application_plans.rs`, `microsvc/*`, `saga_transfer`, `snapshots`, `sourced_snapshot`, `enqueue`, `sourced_enqueue`, `todos`, `event_store`, `repository_api`, `queued_repo`, `replay_property`, `snapshot_sqlite_hardening`, `durable_enqueue_sqlite`, `scheduled_outbox`, `knative_cloudevents`, `redis_leaderboard`, `graphql_leaderboard`, `graphql_causal_transport`, `graphql_subscriptions_sqlite`, `graphql_commands`, `graphql_http`, `graphql_compile`, `graphql_literal_text`, `graphql_unique_key_live`, `metrics_exposition`, `otel_export`. +- **Not read:** `persistent_repository_conformance/{scenario,outbox,inbox,read_models}.rs` bodies, `graphql_oidc_common/mod.rs` body, `graphql_oidc_{authentik,zitadel}` (diffed only), `tests/gateway-{auth,native,portable,worker,postgres}` sources, `tests/fixtures/*` crate sources, `compose.yaml` (image lines only), and workflows `integration-celld`, `integration-game-demos`, `integration-js`, `integration-wasm32-domains`, `integration-distributed-cli`, `quality.yaml`, `on-v-tag-publish`. +- **No timing data:** nothing was built or run, so every CI-time statement is structural. + +## Findings + +### 1. Service-gated tests pass by returning early, and CI never sets the service for several targets +- Category: B/E Severity: high Confidence: CONFIRMED +- Where: `tests/support/env.rs:7`, `tests/support/postgres.rs:19-23`, `tests/persistent_repository_conformance/mod.rs:31-33` (the pattern in all 22 cases), `.github/workflows/integration-postgres.yaml:40-48`, `.github/workflows/test-all-features.yaml:8-11` +- What: Every broker/DB test does `let Some(x) = ...from_env() else { return };` and reports PASS. The all-features job states that service tests self-skip. The Postgres job then lists targets by hand: `postgres_repository`, `postgres_repository_conformance`, `postgres_transport`, `distributed_read_model`, `sql_lock_manager`, `graphql_literal_text`, `schedule_worker`. No workflow runs these with their service present: + - `graphql_postgres` and `graphql_query_protocol_postgres` (not named in any workflow). + - The Postgres halves of `coordination_lease` (`main.rs:309-360`) and `scheduled_outbox` (`main.rs:188`). + - Every broker cell of the read-model matrix (`distributed_read_model/main.rs:1001-1130` NATS/Rabbit/Kafka; `:1225-1264` Postgres×broker). The Postgres job runs that target with `--features postgres` only, and the broker jobs run only `--test _transport`. +- Why it matters: A silently skipped test cannot fail. The only place the full matrix executes is a developer running `make test-local`. +- Change: Replace the skip helpers with one `require_service(var)` that panics when `DISTRIBUTED_REQUIRE_SERVICES=1` (set in every integration job and in `make test-local`) and otherwise marks the test ignored rather than passed. Add one CI job that brings up `compose.yaml` and runs `cargo test --workspace --all-features` with that flag, replacing the hand-kept `--test` lists. Size M. + +### 2. GraphQL, RBAC and query-protocol behaviour is proven on SQLite only +- Category: B (gap) / A (Principle 7) Severity: high Confidence: CONFIRMED +- Where: `tests/graphql_postgres/main.rs:20-63`, `tests/graphql_query_protocol_postgres/main.rs:164`, `tests/graphql_harden/main.rs` (SQLite-gated), `tests/support/graphql.rs:50-72` +- What: About 165 GraphQL integration tests run through a SQLite pool. Postgres gets four: + - one list-query smoke test (never run with a database in CI); + - one query-envelope test (never run in CI); + - one literal-text test (run in CI); + - one `#[ignore]` standby-routing test (run by `tests/gateway-postgres/run.py`). + + Tenant row filters, column allowlists, nested relationship denial, strict-where, depth/in-list limits and all 22 non-gateway live-subscription tests in `graphql_query_protocol` have no Postgres run in `tests/`. `graphql_harden/dialect.rs` shows the two dialects genuinely differ (JSON comparison operators). +- Why it matters: Postgres is the production backend and RBAC is a headline principle. The suite cannot detect a Postgres-only authorization or SQL-compilation bug. +- Change: Make the GraphQL fixtures generic over a `GraphqlPool` factory (SQLite in-memory, Postgres schema from `support/postgres.rs`) and instantiate `graphql_harden::{authz,softskip,residual,inject,dos}` and `graphql_query_protocol` for both, as the repository conformance macro already does. Delete `graphql_postgres` and `graphql_query_protocol_postgres`. Size L. + +### 3. Transport "conformance" runs against fakes; real buses run 0–3 shared scenarios and hand-copy the rest +- Category: B/C/A (Principle 7) Severity: high Confidence: CONFIRMED +- Where: `tests/transport_conformance/mod.rs:226-515` (13 `source_*`/`dispatcher_*` scenarios using `FakeSource`/`FakePublisher`), `:787-880` (3 generic `bus_*` scenarios), `tests/transport_in_memory/main.rs` (whole file) +- What: + - `transport_in_memory` does not test `InMemoryBus`; it runs the 13 fake-based scenarios, which are really unit tests of `run_source` and `OutboxDispatcher`. No real adapter runs them. + - The three generic bus scenarios run on NATS, Postgres and SQLite (all 3), Kafka (2; `kafka_transport/main.rs:146` hand-rolls the listen case), RabbitMQ (1; `rabbitmq_transport/main.rs:168` and `:233` hand-roll the other two). + - `InMemoryBus`, Redis streams (`src/bus/redis_streams.rs`) and the Knative bus run none of them. + - Four failure-path tests are hand-written per broker under identical names in NATS, Kafka and RabbitMQ: `publish_then_consume_round_trips_through_*`, `message_id_and_metadata_survive_the_round_trip`, `retryable_failure_is_redelivered_then_succeeds`, `undecodable_payload_dead_letters_without_blocking`. SQLite has its own variants. + - A real divergence is enshrined in a test: Kafka's `permanent_failure_skips_record_without_redelivery` (`kafka_transport/main.rs:287-292`, "no native dead-letter destination: commits past the record") versus `permanent_failure_routes_to_dead_letter_destination` on NATS and RabbitMQ. +- Why it matters: The suite cannot detect a backend that redelivers, orders or dead-letters differently. The one known difference (Kafka drops poison messages) is documented only in a test comment. +- Change: Move the 13 fake scenarios into `src/bus` unit tests. Make `transport_conformance` one macro `bus_conformance_tests!(factory)` covering point-to-point, fan-out, named group, metadata round-trip, retryable redelivery, permanent failure and undecodable payload. Instantiate it for all eight buses. Express the Kafka dead-letter difference as a declared capability the suite branches on, or give Kafka a DLQ topic. Size L. + +### 4. `sqlite_transport` and `postgres_transport` are a copy-paste pair; so are `sqlite_repository` and `postgres_repository` +- Category: C Severity: high Confidence: CONFIRMED +- Where: `tests/sqlite_transport/main.rs:413-1092` vs `tests/postgres_transport/main.rs:473-1323`; `tests/sqlite_repository/main.rs` vs `tests/postgres_repository/main.rs` +- What: Line diff shows 804 of 1092 SQLite transport lines are identical in the Postgres file. Eleven tests have the same name and body shape, including `bus_listen_dead_letters_corrupt_queue_row_not_silently`, `stable_log_retry_keeps_the_original_cursor_and_rejects_conflicts`, `log_rewind_requires_an_explicit_fenced_reset` and `expired_queue_claim_cannot_be_settled_by_stale_worker`. The repository pair shares 437 of 756 lines and seven same-named tests, sitting outside the 22-case macro that already exists. +- Why it matters: Roughly 1,200 duplicated lines. A scenario added to one backend is not added to the other; SQLite has `retryable_event_failure_does_not_advance_offset` and Postgres does not. +- Change: Add `tests/sql_bus_conformance` generic over a small test trait for the SQL bus (construct, raw-execute, placeholder style), mirroring `src/bus/sql_bus_common.rs`. Fold the repository pair's shared tests into `persistent_repository_conformance`. Leave only truly dialect-specific cases per backend. Size M. + +### 5. Both transport suites assert through private table and index names +- Category: B Severity: medium Confidence: CONFIRMED +- Where: `tests/sqlite_transport/main.rs:437` (`SELECT count(*) FROM bus_queue`), `:488` (`SELECT last_seq FROM bus_offset WHERE consumer = 'projections'`), `:618` (`DROP INDEX bus_log_message_id_unique_idx`), `:633` (raw `INSERT INTO bus_log (...)`) +- What: 60 raw `sqlx::query` calls in the SQLite file and 56 in the Postgres file read or mutate bus tables directly. +- Why it matters: Any schema rename breaks dozens of tests with no behaviour change. Assertions like "offset equals max(seq)" restate the implementation. +- Change: Corrupt-row injection legitimately needs raw SQL; keep that behind one helper per dialect. Replace state assertions with observable behaviour: a second subscriber in the same group receives nothing; a re-publish with the same id is not redelivered. Size M, naturally done with finding 4. + +### 6. Tests guard upgrade paths from schemas that were never released +- Category: B/F Severity: medium Confidence: CONFIRMED (tests); PLAUSIBLE (that the `src` code is removable — outside my slice) +- Where: `tests/sqlite_transport/main.rs:614, 671`; `tests/postgres_transport/main.rs:768, 831`; `tests/sqlite_repository/main.rs:22-52, 169-232`; `tests/postgres_repository/main.rs:25, 191`; `tests/upcasting/main.rs:78, 85`; `tests/core_command_contract.rs:54` +- What: + - `legacy_equivalent_stable_id_duplicates_retain_the_minimum_cursor` and `legacy_conflicting_stable_id_duplicates_fail_preflight_without_mutation` (both backends) drop the unique index to "simulate legacy schema without uniqueness". + - `projected_command_ledger_rows_upgrade_to_atomic_*` builds a migrator from migrations 0001–0003 only, inserts a `'projected'` row, migrates, and asserts `MAX(version) == 13`. That number breaks on every new migration. + - `old_events_without_event_version_deserialize_as_v1` and `old_events_without_metadata_deserialize_with_empty_metadata` test deserialising pre-versioning records. + - `neutral_declarations_preserve_the_pre_extraction_artifact` compares against a JSON fixture "captured from d188010d before changing the command implementation" — a one-off refactor guard. +- Why it matters: Nothing is released, so these protect compatibility with states no user has. They imply 13 migrations plus preflight dedup code that could be squashed. +- Change (breaking): Squash migrations to one baseline per dialect, delete the legacy preflight paths and these seven tests. Either delete `core-command-contract-v1.json` or rename the test to state that it is the v1 wire contract. Size M. + +### 7. Two test files grep the repository's own source and docs +- Category: B Severity: medium Confidence: CONFIRMED +- Where: `tests/legacy_authoring_absence.rs:13-157`; `tests/e2e_ui_celld_nats_profile/main.rs:17-70` +- What: + - All seven tests in `legacy_authoring_absence.rs` `include_str!` files under `src/` and assert that substrings are absent (`"pub fn project<"`, `"CompiledCommandEffects"`, `"graph_workspace"`) or present (`"macro_rules! projection"`, `"mutation,"`, `"mod command_input_defaults"`). + - `default_e2e_ui_host_stays_one_process` and `optional_profile_is_named_and_not_the_playground` assert that `host.rs` contains the comment text "single backend process", that a README contains "optional" and "make run", that a compose file contains `nats:2-alpine`, and that a worker source contains the sentence "projectors are not methods on this class". + - The same pattern exists outside my slice at `tests/celld/main.rs:59,124,155` and `src/microsvc/cell_host/tests.rs:701`. +- Why it matters: The compiler already enforces absence of a deleted symbol. These fail on comment edits and formatting. The file's own comment at line 20 records a prior false positive ("Old gate rejected any `projection,` substring"). +- Change: Delete `legacy_authoring_absence.rs` and the two fixture-grep tests; keep the `live` module in the profile target. If an API-absence guarantee is wanted, use one trybuild compile-fail case. Size S. + +### 8. Two aggregate authoring forms mean four duplicated test targets +- Category: C/F Severity: medium Confidence: CONFIRMED +- Where: `tests/upcasting/aggregate.rs:21-38` (`#[digest]` + `aggregate!`) vs `tests/sourced_upcasting/aggregate.rs:19-33` (`#[sourced]` + `#[event]`); pairs `upcasting`/`sourced_upcasting`, `enqueue`/`sourced_enqueue`, `snapshots`/`sourced_snapshot`, `todos`/`sourced`; `tests/replay_event_version.rs` (`exact_version_replays_with_both_macros`, `snapshot_prefix_tail_checks_versions_for_both_macros`) +- What: The same behaviours (hydrate v1 to v3 through chained upcasters, replay does not re-enqueue, snapshot round-trip) are tested once per form, often under the same test name. Fixture files share 97 of 163 lines (upcasting) and 61 of 123 (enqueue). `#[digest(` appears in only two files in the repo, both test fixtures; `#[sourced` appears 76 times across 54 files. +- Why it matters: Roughly 1,500 lines of tests keep a second authoring surface alive that nothing else uses. +- Change (breaking): Pick `#[sourced]`, remove `#[digest]`/`aggregate!` as public authoring, and merge the four pairs into one `aggregate_authoring` target. Whether `aggregate!` is needed internally is the macro reviewer's call. Size M. + +### 9. Tests that cannot fail or assert nothing meaningful +- Category: B Severity: medium Confidence: CONFIRMED +- Where and what: + - `tests/graphql_oidc_keycloak/main.rs:17` `e0_skips_when_not_gated` (and its authentik and zitadel copies): body is an `eprintln!`. + - `tests/graphql_sdl/main.rs:234` `capture_sdl_to_scratch`: returns unless `GROK_SCRATCH_SDL` is set; it is a developer dump tool. + - `tests/graphql_engine/main.rs:162` `unknown_column_in_permission_via_grant_ok`: grants all columns on a valid schema and builds; no unknown column is involved. + - `tests/graphql_engine/main.rs:190` `pure_sql_compile_helper`: asserts the SDL contains `"type Item"`; no SQL is compiled. + - `tests/graphql_harden/softskip.rs:21` `default_engine_has_strict_where_on`: a getter check; `strict_unknown_where_key_errors` proves the behaviour. + - `tests/sourced/main.rs:96` `enum_variants_exist_and_compile`, `:253` `partial_equality_on_enum`, `:271` `no_upcasters_by_default`. + - `tests/sourced_enqueue/main.rs:96` `typed_event_enum_exists`, `:150` `custom_emitter_typed_enum`, `:159` `notifier_has_no_upcasters`. + - `tests/sourced_upcasting/main.rs:10-31` `v1_has_no_upcasters`, `v2_has_one_upcaster`, `v3_has_two_upcasters`, with twins in `tests/upcasting`; the hydrate tests already prove the chain. + - `tests/application_composition.rs:799` `no_linker_inventory_is_needed_for_explicit_application_selection`: asserts `module_ids() == ["todo"]`. +- Change: Delete them. Size S. + +### 10. `sagas/orchestration.rs` tests its own fixture domain, not the framework +- Category: B Severity: medium Confidence: CONFIRMED +- Where: `tests/sagas/orchestration.rs:23-455` (5 tests), `tests/sagas/order/*.rs` (about 490 lines of fixture aggregates) +- What: The test body is the orchestrator. It calls `inventory.reserve`, `saga.inventory_reserved()`, `payment.capture()` step by step and asserts fixture enum states. The only framework calls are `repo.get` and `repo.commit` on `InMemoryRepository`. The module doc describes it as an example. +- Why it matters: It can only fail if the fixture is wrong. There are four separate saga fixtures: `sagas/order`, `saga_transfer`, `persistent_repository_conformance/checkout_saga.rs`, and `distributed_read_model/checkout_saga_service`. +- Change: Delete `orchestration.rs`. Keep `microsvc_saga.rs` (`saga_orchestrated`, `saga_distributed`) and `saga_transfer` (timeouts, compensation, restart on SQLite), which drive `Service`, routes and the outbox. Move the order saga to `examples/` if it has documentation value. Size S. + +### 11. `typed_commands` hand-assembles projection programs instead of using the public macro +- Category: B Severity: medium Confidence: CONFIRMED +- Where: `tests/typed_commands/main.rs:403-1280` +- What: About 870 lines build `ProjectionProgram` values through `compile_projection`, `MutationEventBinding::try_new` and `descriptor_from_factories` (25 call sites). `projection! { ... }` is invoked in two places in my slice, both in `tests/sourced/flat_preview.rs`. Sixteen assertions match error text by substring (for example `:1326` `"TypeId mismatch"`, `:1350` `"structural fingerprint mismatch"`). +- Why it matters: The suite proves the intermediate representation works when built by hand. It does not prove that what a user writes with `projection!` yields a correct client manifest. Any change to the internal builder API breaks 870 lines of fixture. +- Change: Rewrite the eight fixture programs with `projection!`/`mutation!`; keep hand-built programs only for shapes the macro cannot express, moved into `src` unit tests. Replace substring error matches with a typed error kind. Size M. + +### 12. GraphQL tests hand-write DDL beside `#[derive(ReadModel)]` +- Category: B/A (Principle 4) Severity: medium Confidence: CONFIRMED +- Where: `tests/support/graphql.rs:14-24` (model) with `:57-63` (hand-written `CREATE TABLE orders`); `tests/graphql_sqlite/main.rs` (19 `CREATE TABLE`); `tests/graphql_harden/dos.rs` (8); about 51 across GraphQL targets, versus 16 uses of `bootstrap_table_schema_for_dev` +- What: Rows are inserted with raw SQL into tables whose shape is retyped by hand, bypassing the declared read-model schema and the projection path. +- Why it matters: The schema generated from the model is never what GraphQL is tested against, so a model/DDL mismatch such as nullability or JSON storage type goes unnoticed. It is also why porting to Postgres (finding 2) is expensive. +- Change: Add one fixture helper, `seed::(repo, rows)`, that bootstraps from the model registry and writes through a write plan. Size M, prerequisite for finding 2. + +### 13. Almost no shared fixtures: each target rebuilds its own aggregate, read model, session and pool +- Category: C Severity: medium Confidence: CONFIRMED +- Where: `tests/support/` (410 lines in six files: ids, env, outbox, sqlite, postgres, graphql) +- What: + - About 50 aggregate definitions across 40 files. + - Four near-identical `Todo` aggregates (`todos/aggregate.rs:5`, `sourced/aggregate.rs:4`, `snapshots/aggregate.rs:4`, `sourced_snapshot/aggregates.rs:9`), six `TodoV1..V3`, plus `DomainTodo` and `TodoHost`: 12 Todo-like aggregates. There are also separate `Counter` aggregates in `sqlite_repository`, `postgres_repository` and `microsvc`. + - 96 `derive(ReadModel)` in 38 files. + - 62 `sqlite::memory:` pool constructions in 33 files. + - 30 local `*session*` helper functions. + - `support/graphql.rs` is included by one target (`graphql_harden`). + - Sharing is via `#[path = "../support/x.rs"]`, each file carrying `#![allow(dead_code)]`. +- Why it matters: The cost is not line count; fixtures drift. The four `Todo`s already differ in field visibility and methods. +- Change: Create a `tests/common` library crate (dev-dependency, `publish = false`) exporting one Todo aggregate, one Order/Parent/Child read-model set, session builders, `TempDb`, `PostgresTestSchema`, and the conformance macros. This also removes the `#[path]`/`dead_code` idiom. Size M. + +### 14. Five different ways to run a scenario on several backends, and their case lists diverge +- Category: C/A (Principle 7) Severity: medium Confidence: CONFIRMED +- Where: + - `tests/persistent_repository_conformance/mod.rs:27` — macro, one target per backend. + - `tests/coordination_lease/main.rs:26-135` — generic `scenario_*` functions with hand-listed wrappers at `:137-360`. + - `tests/schedule_worker/main.rs:312` — local `scenarios!` macro. + - `tests/distributed_read_model/main.rs:865` — generic `run_matrix_cell`. + - The transport and repository pairs — plain copy-paste. +- What: In `coordination_lease`, the in-memory module runs `invalid_inputs_rejected` and `concurrent_takeover_after_expiry_has_one_winner` (`:161, :201`); the SQLite and Postgres modules do not, and each has its own hand-copy of expiry takeover (`:277, :346`). In `schedule_worker`, SQLite and Postgres run five scenarios while memory runs one different test (`:574`). +- Change: Standardise on the repository macro pattern, which is the good one, for leases, locks, schedules and buses. Every backend then runs the identical list, and exclusions become explicit named capabilities. Size M. + +### 15. Cross-backend work that should be kept and promoted +- Category: B (positive) Severity: n/a Confidence: CONFIRMED +- Where: `tests/persistent_repository_conformance/mod.rs:27-230`; `tests/graphql_oidc_common/mod.rs:141`; `tests/distributed_read_model/main.rs:865-1273` +- What: + - 22 repository scenarios are each written once and run on in-memory, SQLite and Postgres through three 10–23 line entry files, including `aggregate_conflict_rolls_back_outbox`, `publish_failure_after_commit_retains_outbox_row_until_delivered` and `consumer_inbox_records_dedupes_and_fences_with_real_effects`. + - The OIDC E1–E8 scenario is written once in `run_e1_through_e8`; per-provider files only mint tokens. Their only duplication is about 90 lines of `mint_client_credentials`/`decode_sub`/`urlencoding` shared by keycloak and authentik. CI correctly asserts the gate is set before running (`integration-graphql.yaml:69, 111, 151`). + - The read-model persistence×bus matrix is one generic function instantiated per cell. +- Change: None, apart from moving the token helpers into the common module (S). + +### 16. 87 test binaries; 51 are empty under default features; most jobs compile cold +- Category: D (CI) Severity: medium Confidence: CONFIRMED (structure); PLAUSIBLE (time saved — not measured) +- Where: `tests/` (70 `*/main.rs` plus 17 `*.rs`); `.github/workflows/on-pr-quality.yaml:39-43`; `test-all-features.yaml:34`; `integration-{kafka,nats,rabbitmq}.yaml` +- What: + - 51 of 87 targets carry `#![cfg(feature = ...)]`, so the default-feature `cargo test` in the quality job compiles and links 51 empty binaries. + - The all-features job links all 87 against a build that includes rdkafka, with no `rust-cache`. Kafka, NATS and RabbitMQ jobs also have no cache; Postgres, GraphQL, e2e-ui and celld do. + - A PR runs about 14 workflows that each compile the crate with a different feature set. + - `rust.yml` (coverage on main) repeats the all-features run under llvm-cov with no services, so coverage excludes every skipped test. +- Change: Consolidate into about eight integration binaries (`core`, `repository`, `transport`, `graphql`, `gateway`, `read_model`, `microsvc`, `observability`) with modules per current directory. Add `Swatinem/rust-cache` to the four uncached jobs. Merge the Postgres, NATS, RabbitMQ and Kafka jobs into the single compose-backed all-features job from finding 1, and collect coverage there. Size M. + +### 17. Gateway tests do not gate main or releases; one fixture crate is never run +- Category: E Severity: medium Confidence: CONFIRMED +- Where: `.github/workflows/integration-gateway.yaml:3-28`; `on-push-main-version-and-tag.yaml:12-62`; `on-pr-quality.yaml:75`; `tests/fixtures/renamed-dependency-trybuild/` +- What: + - The gateway workflow triggers on `pull_request` with path filters and manual dispatch only. It is not called from the main pipeline and is not in `version-and-tag`'s `needs`. It is the only place that runs the `#[ignore]`d `worker_*` tests, `tests/gateway-{portable,native,worker,auth}`, `gateway-postgres/run.py`, and `application_composition`/`application_plans`/`gateway_mounts` with their real feature set. + - `integration-game-demos` is called on PRs but not on main; it is the only job that sets `REDIS_URL` for `redis_leaderboard`. + - `renamed-dependency-trybuild` is a standalone crate with its own `[workspace]` and tests, referenced by no workflow, script or Makefile target. +- Change: Make the gateway workflow `workflow_call`, call it from both entry pipelines, and add it and `game-demos` to the release `needs`. Wire the trybuild fixture into the macros job or delete it. Size S. + +### 18. Wall-clock assertions against real brokers and short TTLs +- Category: B (flakiness) Severity: low Confidence: CONFIRMED +- Where: `tests/nats_transport/main.rs:763, 828` (`latency < 250ms` against live JetStream), `:919` (`m2_policy + 1000ms < m1_projection`); `tests/queued_repo/main.rs:72` (50 ms sleep then "must still be blocked"); `tests/sql_lock_manager/main.rs:116, 151, 165`; `tests/coordination_lease/main.rs:283, 352` (200 ms TTL, 350 ms sleep) +- What: About 38 `sleep(` calls across 18 files. There are no fixed bound ports (servers bind `127.0.0.1:0`), no serial requirements, and the polling loops I inspected have deadlines (`schedule_worker/main.rs:296-309`). +- Why it matters: The two NATS 250 ms bounds are the likeliest flakes on a loaded runner. The negative-window sleeps can pass falsely but not fail falsely. +- Change: For in-process cases use `tokio::time::pause`/`advance`, or the store clock that `schedule_worker`'s memory test already uses. For NATS, assert relative ordering (fresh message handled before the poison's nth retry) instead of an absolute bound. Size S. + +### 19. Test Postgres schemas are never dropped; local and CI service versions differ +- Category: E Severity: low Confidence: CONFIRMED +- Where: `tests/support/postgres.rs:13-101` (no `Drop`; `distributed_read_model/main.rs:1201` comments "The schema has no Drop"); `compose.yaml:68` (`nats:2.15-alpine`) vs `integration-nats.yaml` (`nats:2.10-alpine`) vs `e2e_ui_celld_nats_profile/main.rs:56` (`nats:2-alpine`); `compose.yaml:21` (`postgres:18`) vs CI (`postgres:18-alpine`) +- What: Each Postgres test leaves an `sr___` schema behind; with `KEEP_COMPOSE=1` they accumulate indefinitely. CI and local run different NATS versions. +- Change: Drop the schema at the end of the test via an async `cleanup()` or a per-run database. Have CI start services from `compose.yaml` (also fixes finding 1). Size S. + +### 20. Principle-level behaviours with no end-to-end test in `tests/` +- Category: B (gap) Severity: medium Confidence: PLAUSIBLE (searched by test name and grep; bodies of unread targets not checked) +- What I looked for and did not find: + - **Projection rebuild through the public service API** (drop a read model, replay from the event store, same rows and same GraphQL answer). Rebuild is tested only at store level in `src/projection/source_snapshot_tests.rs:719-1012` and for Redis in `redis_leaderboard/main.rs:68`. + - **RBAC on the live/subscription path on Postgres**, and RBAC on every query path on Postgres generally (finding 2). On SQLite, `row_filtered_surface_never_exposes_partition_wide_live_activity` (`graphql_query_protocol/main.rs:1223`) covers the live path. + - **Idempotent command retry on Postgres** (same command id twice yields one effect and the same receipt). SQLite and in-memory are covered by `causal_wait_path` (`cell_wait_path_replays_once_after_internal_failure`, `celld_host_reclaims_an_ambiguous_receipt_with_the_same_causation`). Postgres has only a lib test that CI runs by name. + - **Out-of-order or duplicate event delivery to a projector across real buses.** Only `src` has `source_snapshots_postgres_reordering_and_restart`; no bus-level conformance scenario delivers e2 before e1. + - **Server/browser mutation-program parity** is covered by shared golden fixtures consumed by both `src` tests and `js/tests` (`tests/fixtures/mutation-program-v1.json`, `projection-delta-v1.json`, `client-query-plan-corpus.json`). That is sound, but nothing regenerates the fixtures and fails on drift from the Rust compiler output, as far as I could see. +- What is covered: crash between event append and outbox publish (`publish_failure_after_commit_retains_outbox_row_until_delivered`, `expired_outbox_lease_is_reclaimed_by_second_worker`, both on all three repositories; `schedule_worker::crash_between_commit_and_settle_does_not_fire_twice` on SQLite and Postgres). +- Change: Add `projection_rebuild` and `command_retry` scenarios to the repository conformance macro, and a "duplicate plus reordered delivery" scenario to the bus conformance macro from finding 3. Size M. + +### 21. Manifest and contract tests are legitimate wire-contract tests but brittle +- Category: B Severity: low Confidence: CONFIRMED (sampled, not exhaustive) +- Where: `tests/application_composition.rs:600-660`; `tests/typed_commands/main.rs:1683-1730`; `tests/aggregate_command/main.rs:404-472` +- What: + - `application_manifest_is_byte_deterministic_and_contains_no_executable_data` asserts the bytes do not contain the substrings `"handler"` or `"application_composition"`; it would fail if a user named a column "handler". + - Many tests index `manifest.commands[0]` and `projection_programs[0].arms[0].operations[0]`. + - The `generated_*_equal_the_hand_written_*` tests compare the macro's output with a hand-written registration. That is a sound equivalence oracle; keep it. +- Change: Replace the substring-absence checks with structural ones (no key outside the schema). Find manifest entries by name, not index. Size S. + +## Things that are good and should not be changed + +- **`repository_conformance_tests!`** (`tests/persistent_repository_conformance/mod.rs`): one case list, three backends, real rollback, lease and inbox scenarios. Extend this pattern to buses, locks, leases and GraphQL; do not replace it. +- **The persistence×bus matrix** (`run_matrix_cell` in `tests/distributed_read_model/main.rs`) and the shared OIDC scenario `run_e1_through_e8`. Both are correct; they need CI to actually execute them. +- **Golden wire vectors in `tests/fixtures/*.json` consumed by both Rust and `js/tests`.** This is the right way to enforce "no TypeScript twin" (Principle 5). +- **`graphql_harden`** is organised by threat category, drives the shipped `GraphqlEngine::execute`, and checks that errors do not leak SQL (`assert_no_sql_leak`). **`graphql_query_protocol`** asserts the client-visible envelope, including that hidden aliases and omitted primary keys never leak. +- **Failure-injection tests on real stores:** `schedule_worker` (crash between commit and settle, concurrent workers, backoff), `saga_transfer` (timeouts, late-reply tombstones, restart on SQLite), `replay_property` (proptest that reload and snapshot hydration equal in-memory state), `snapshot_sqlite_hardening`. diff --git a/docs/reviews/v5-pre-release/13-example-apps-docs.md b/docs/reviews/v5-pre-release/13-example-apps-docs.md new file mode 100644 index 000000000..7957ba5cf --- /dev/null +++ b/docs/reviews/v5-pre-release/13-example-apps-docs.md @@ -0,0 +1,319 @@ +# Review: reference apps and docs (the framework as users experience it) + +All paths are relative to `/Users/patrickleet/dev/hops-ops/hops/distributed`. + +## Assessment + +The domain layer in the reference app is good: `todo-domain/src/models/todo.rs` is a plain struct with rules and solid behavioural unit tests, and the Todos page really is `Todos.use()` plus `commands.todo.*`. Everything around that core is heavy. One new Todo command touches about 12 hand-edited places, and the "copyable template" contains a dual write, a fake aggregate, hand-rolled HTTP endpoints, TypeScript twins of domain rules, and a 300-line security-hardened config loader in user code. No build outputs are tracked, and the three skill directories are symlinks, not copies. + +Three things most worth changing: +1. **One command authoring form.** There are five today. The flagship app uses the verbose one for every command, while `#[command]` on the aggregate method would cover 5 of 7 Todo commands. +2. **Make the service/host layer disappear.** The `routes()` generic wall, `bounds.rs`, `projection_owners()`, `MODULE_IDS`, the hand-built `application_manifest()`, and the sqlite/postgres host forks are restated framework knowledge. `docs/application-composition.md` already calls this the target, and it is not built. +3. **e2e-celld should be a different `main`, not a second app.** About 3,300 of its 3,583 Rust lines have an e2e-ui twin, most byte-identical. + +Not read, or only skimmed: +- README.md lines 700–1557, 1800–2054, 2175–2264, 2625–2713 were not read line by line; they were covered only by the path/link and symbol scripts. +- `docs/`: `coordination-primitives`, `consumer-delivery-lanes`, `external-facts`, `live-query-delivery`, `unsigned-command-inputs`, `compact-projection-contracts` were symbol-checked only. +- e2e-ui UI: `auth.ts`, `lib/server/*`, admin/session/login/signup routes, all `components/`, CSS, `ui/tests/*.mjs` not read. `demos.ts` was sampled, not checked snippet by snippet. +- e2e-ui Rust: `zitadel/map.rs` not read; `zitadel/scrape.rs` only lines 95–180; `projections/src/blob.rs` tests by name only; `suite/tests/behavioral.rs` only lines 1–125 and test names; blob/chat domain models not read. +- Playwright: `todos.user.spec.ts` partly read; `blob`, `chat`, `admin`, `unauth` specs by grep only. +- Ops: all `.gitops/` charts, `docker/`, `gateway/`, `scripts/up.sh` beyond line 60, `helm-contract-test.sh`, `lifecycle-*.mjs`, and the e2e-ui Makefile body. +- e2e-celld: `graphql-service/src/http.rs` (diff count only), `blob-service`, Makefile. `tests/celld/worker` is outside my slice. +- Repo scripts: `oidc-*.sh`, `ci-bootstrap-graphql-oidc.sh`, `check-wasm32-domains.sh` not read. +- Nothing was compiled or run. Every "what breaks when they disagree" statement is from reading and is marked PLAUSIBLE unless I saw the check. + +## Findings + +### 1. Adding one command touches about 12 hand-edited sites, most restating what `#[sourced]` knows +- Category: C/F Severity: high Confidence: CONFIRMED +- Where: `tests/e2e-ui/crates/todo-domain/src/commands/complete.rs:1-41`, `commands/mod.rs:6-24,54-62`, `lib.rs:12-24`, `models/mod.rs:8-13`, `projections/src/todos.rs:7-11,39-47,71`, `service/src/modules/todo.rs:41-47`, `tests/e2e-celld/crates/todo-service/src/routes.rs:39-45`, `todo-service/src/host.rs:8-16,47-80`, `service/src/modules/graphql.rs:632-641`, `suite/src/lib.rs:287-408`, `e2e/helpers/optimism.ts:11-20` +- What: `Todo::reassign` already has a domain method, an event and a projection arm (`todo.rs:155-178`) but no command. To expose it an author writes: + 1. A command file: Input struct, Payload struct, and a 12-key `portable_command!`. + 2. `mod` plus a four-name `pub use` in `commands/mod.rs`. + 3. The same names again in `lib.rs`, and the generated `…DomainEvent` type by name in `models/mod.rs` and `lib.rs`. + 4. The event import and an entry in `events: [...]` in the projection. + 5. `.mount(...)` in `modules/todo.rs`. + 6. `.mount(...)` again in e2e-celld. + 7. The name in `TODO_CELL_COMMANDS` and a `match` arm in `graphql_todo_payload`. + 8. Test inventories: `arms().len() == 8`, the subscription list, a suite helper, the `MutationNeedle` union. + 9. The page handler. + + Only the domain method (already written) and the page call carry new information. +- Why it matters: the pitch is "write the aggregate method; the rest is generated". The template teaches the opposite. Every list is a place to forget; a missed projection `events:` entry means the command succeeds and the read model silently never updates. +- Change (L, breaking): + - Make `#[command]` on the method the only form. Default `field` from the command name and model, `shard` from the aggregate id (`#[snapshot(id = "todo_id")]` already names it), `transition` from the method, and input from the parameters. + - Have `#[sourced]` emit `Todo::commands()` so hosts write `.mount(Todo::commands())`. + - Let a projection arm say `events: state_events(Todo)`, expanding to every `domain` event carrying `TodoState`, with deletion events routed to the delete arm. + - Glob-export generated event types. + +### 2. Five ways to declare a command; the reference app uses the long one for all 11 +- Category: F Severity: high Confidence: CONFIRMED +- Where: README.md:301-338, 1558-1612, 1618-1638, 1663-1700, 1757-1764, 2125-2146; `distributed_macros/src/portable_command.rs:60-125`; `distributed_macros/src/aggregate_command.rs:1-22` +- What: the README documents five forms: + - `#[command]` on the method. + - `portable_command!`. + - `typed_command::()` / `command_transition` builder with `.emits().applies()`. + - Untyped `.command(name).handle(|ctx| json!)`. + - `routes!(command handlers::x)` with the `COMMAND`/`guard`/`handle` file convention. + + The two macros have diverging option sets. `#[command]` has `load = or_create` but no `defaults`, `preview_reduce_known_record`, `authenticated_user_field`, or `Atomic`. `portable_command!` has those but rejects `or_create` (`portable_command.rs:101-108`). The repo-wide grep finds `#[command(` only in `examples/game` and `tests/aggregate_command`; `tests/e2e-ui` has none. +- Why it matters: a new user cannot tell which form is canonical. The README calls `#[command]` "the shortest form" and then shows the template not using it. +- Change (L, breaking): keep `#[command]` (with the missing options added) plus one explicit `handle:` escape hatch. Delete `portable_command!`'s thin form, the untyped JSON route style and `routes!` from the public authoring surface, or mark them integration-only. Convert e2e-ui. + +### 3. `todo.create` and `todo.force_archive` use `handle:` only because the thin path lacks `or_create`, payload-from-principal and a server default +- Category: A/F Severity: medium Confidence: CONFIRMED (code); PLAUSIBLE that `or_create` fully replaces `handle_create` +- Where: `todo-domain/src/commands/create.rs:24-65`, `force_archive.rs:22-55`, `chat-domain/src/commands/post.rs:39-75` +- What: `handle_create` does `repo.get(..).is_some()` → reject, `repo.create()`, call the domain, build the payload. The aggregate already rejects double create (`todo.rs:70-72`). `handle_force_archive` exists only to put `archived_by: admin` in the payload. Each test asserts nothing: `create_uses_handle_escape_hatch` is `assert_eq!(Create::COMMAND, …); let _ = handle_create;`. +- Why it matters: principle 3 (thin handlers). The existence rule is written twice, once in the handler and once in the domain. +- Change (M): add `load: or_create` plus `invoke` with principal, and let `payload` see the principal. Delete both handlers and the two `*_uses_handle_escape_hatch` tests. + +### 4. The module `routes()` wall: 18 lines of trait bounds per module, a copied `bounds.rs`, and four positional args each +- Category: C/F Severity: high Confidence: CONFIRMED +- Where: `service/src/modules/todo.rs:16-39`, `chat.rs:16-39`, `blob.rs:15-38`, `compose.rs:21-39`, `service/src/bounds.rs:1-40` (byte-identical in 5 e2e-celld crates), `blob.rs:23,39` +- What: every module repeats the same `where R: EventStore, L: Locks, S: ReadStore, QueuedRepository: …, AggregateRepository<…, A>: HasRepo + HasOutboxStore + ConfigurableOutboxPublisher…` block. `compose.rs` repeats it once per aggregate. `bounds.rs` exists only to shorten it and is copied six times. `blob::routes` takes `_blob_direct: SurfaceDirectProjection` and immediately discards it. +- Why it matters: this is the first Rust a template user reads after the domain, and it is entirely about framework internals. Adding an aggregate adds a bounds line to `build_service`. +- Change (L, breaking): ship one framework trait or struct, for example `Stores { events, locks, read_models }`, with the blanket bounds inside. Module signature becomes `fn routes(stores: &Stores) -> Routes`. Delete `bounds.rs` and the dead parameter. + +### 5. Projection name, epoch and model are each stated three times and mounted through a pass-through handler +- Category: C/F Severity: high Confidence: CONFIRMED (redundancy); PLAUSIBLE (effect of mismatch) +- Where: `projections/src/todos.rs:32-37`, `service/src/modules/projections.rs:21-41`, `service/src/modules/todo.rs:48-49`, `handlers/events/project_todos.rs:1-11`, `src/projection/local_mounts.rs:131-160` +- What: `projection!` declares `name: "project_todos"`, `epoch: "e2e-ui-todos-v2"`, `model: Todos`. `projection_owners()` then calls `.eventual_model::("project_todos", TODOS, "e2e-ui-todos-v2")` and looks it up again with `.projector("project_todos")`. The projector is passed to the module, which does `.modeled_projector(p).handle(project_todos::handle)`, where the handler is an 11-line file calling `projection.apply(TODOS, &context)`. `eventual_model` takes `owner` and `epoch` as free strings and does not compare them with the descriptor. +- Why it matters: three copies of name and epoch with no check I could find. A bumped epoch in one place plausibly creates a second binding identity at startup or silently keeps the old one. Six `.expect()`s sit on a path that is pure restatement. +- Change (M, breaking): `LocalProjectionMounts::from([TODOS.into(), CHAT_MESSAGES.into(), BLOB_GAMES.into()])` reading name, epoch and model from the descriptor, and `Routes::project(TODOS)` replacing `modeled_projector` + `handle` + the handler file. + +### 6. `MODULE_IDS`, `MODULE_DECLARATIONS` and a hand-built `application_manifest()` duplicate `Service::application` +- Category: C/F Severity: medium Confidence: CONFIRMED +- Where: `service/src/modules/compose.rs:15`, `application.rs:20-28`, `modules/graphql.rs:170-213,826-833`, `service/src/http.rs:141-145`, `src/microsvc/service/runtime.rs:663-702`, README.md:2541 +- What: the README says "Command namespaces … supply module names; there is no second module list to maintain", and `Service::application` implements that. The template still keeps `MODULE_IDS` (with a bare `"identity"` string) and `MODULE_DECLARATIONS`, documented as "compile-time proof" although it only pairs constants with prose. `application_manifest()` re-implements the prefix grouping by hand, while `http.rs` in the same crate calls `service.application(...)`. The "identity" module has zero commands because its commands are named `zitadel.*`. +- Why it matters: two different manifests of one application (CLI versus runtime gateway). The whole block is copied into e2e-celld. The test `module_inventory_lists_todo_chat_blob_identity` asserts a constant equals itself. +- Change (S): `application_manifest()` becomes `pool_free_service().application(NAME, surface)?.manifest()`. Delete `MODULE_ID`, `MODULE_IDS`, `MODULE_DECLARATIONS`, `E2E_UI_MODULE_IDS` and that test. + +### 7. The read-model list is spelled in six places and the role and surface lists in four +- Category: C Severity: medium Confidence: CONFIRMED +- Where: `readmodels/src/lib.rs:15-19,46-49`, `service/src/modules/graphql.rs:84-99,101-105,149-153,217-225`, `service/src/host.rs:74-79,141-146` +- What: Todos/ChatMessages/BlobGames/AuthUsers are listed as `.table_schema(...)` ×4, `add(&mut grants, X::permissions())` ×4, `.model::(X::permissions())` ×4, and twice as table-name strings (`"todos".into()…`) for `GatewayVersionStore::install`. Projection owners are listed twice. The surface role triples (`"e2e-ui", ["admin","user"], ["user"]`) are stated in `build_engine` and again in `distributed_client_surface()`. `application_grants()` is 30 lines of user code compiling `ModelPermissions` into a nested `BTreeMap`. +- Why it matters: principle 4 says permissions are declared next to the model. They are, and then re-registered by hand in three shapes. A model missing from `application_grants()` but present in `.model::<>()` would plausibly make generated-client and runtime fingerprints diverge. The test `graphiql_does_not_change_the_postgres_runtime_client_manifest` exists to catch exactly that class. +- Change (M, breaking): put `permissions()` on the `ReadModel` trait via `#[readmodel(permissions = …)]`. One `read_models![Todos, ChatMessages, BlobGames, AuthUsers]` catalog should feed schema bootstrap, grants, the engine, the version store and client export. Declare surfaces once as values used by both the engine builder and the export. + +### 8. The host forks SQLite and Postgres into two 65-line copies +- Category: C Severity: medium Confidence: CONFIRMED +- Where: `service/src/host.rs:53-118` vs `120-185`; `94,161`; `docs/application-composition.md:177,201` +- What: `run_sqlite` and `run_postgres` differ only in type names. Both spawn the outbox loop with magic `Duration::from_secs(30), 5`, build the service twice (once for serving, once inside the consumer closure), and create an unused `_dispatcher`. The design doc lists "Runner has one path for sqlite/postgres" as an unchecked acceptance item. +- Why it matters: this is the "copyable" host. Principle 7 (interchangeable backends) is not visible to the user. +- Change (M): either make `run` generic over a `Backend` trait pairing repo, locks and bus, or ship `distributed::host::run(build_service, HostOptions)`. Delete `_dispatcher`. + +### 9. Dual write in the reference app: scrape upserts `auth_users` directly and also publishes the event that projects the same row +- Category: A/E Severity: high Confidence: CONFIRMED +- Where: `service/src/handlers/ingestors/zitadel/scrape.rs:117-176`, `handlers/events/project_auth_user.rs:28-46` (both byte-identical in e2e-celld) +- What: `scrape_users_to_outbox` calls `materialize_auth_user` (a direct `ReadModelWritePlanBuilder` upsert) and then `publish_mapped_delivery` (outbox) as two separate commits. The comment says the direct write was added because "duplicate outbox ids used to skip this upsert". Duplicate detection is `err.to_lowercase().contains("unique") || contains("already exists")`. `project_auth_user` is a hand-written projector that selects behaviour with `name.contains("deactivated")`, so `auth_users` has no mutation program and no replica optimism. +- Why it matters: this violates principles 1 and 5 inside the template. The writes are non-atomic: the row can exist with no event, or a later stale event can overwrite a newer scrape. The string-matched error swallows any unrelated error containing "unique". +- Framework gap: no first-class integration-event → `projection!` path, and no typed "duplicate outbox id" error or idempotent publish. +- Change (M): let `projection!` accept integration-event contracts so `AUTH_USERS` is declared like the others. Add `OutboxCommitError::Duplicate` or `publish_idempotent`. Delete `materialize_auth_user`. + +### 10. Non-aggregate routes need a fake aggregate +- Category: A/F Severity: medium Confidence: CONFIRMED +- Where: `service/src/deps.rs:7-12`, `service/src/modules/chat.rs:44-60`, `tests/e2e-celld/crates/identity-service/src/aggregate.rs:1-29`, `identity-service/src/routes.rs:32` +- What: Zitadel ingress, scrape and the `auth_users` projector have no aggregate. e2e-ui mounts them on the chat module with `type AuthDeps = ChatDeps` ("share the chat aggregate repo for outbox/leaf access"). e2e-celld invents `struct Identity` with a no-op `replay_event` purely to call `Routes::for_aggregate::<_,_,Identity,_>`. +- Why it matters: the workaround is in both example apps, so every real app with a webhook will copy it. +- Change (S–M): add `Routes::for_stores(stores)` giving the outbox and read-model store without an aggregate type. + +### 11. Hand-written HTTP endpoints re-implement crate-private framework code +- Category: A/C Severity: medium Confidence: CONFIRMED +- Where: `service/src/http.rs:20-59,84-111,181-197`, `src/microsvc/http.rs:224`, `src/microsvc/service/runtime.rs:100-107` +- What: `with_http_command_routes()` is all-or-nothing, so the template writes its own `session_from_headers` (the framework's is `pub(crate)`), `status_for_error`, `dispatch_named` and two axum routes for `zitadel.ingress.v1` and `zitadel.scrape.v1`. It also loops over `command_specs()` to register "closed" routes so old command URLs do not fall through to the UI proxy. The copied `session_from_headers` puts every request header into the `Session`; safety depends entirely on the handler's own secret check. +- Why it matters: README principle 05 says "you do not write … a REST endpoint". The route names are strings repeated three times in one file (lines 85-86, 185-195), plus `COMMAND` constants elsewhere. +- Change (S): add `Service::with_http_commands(["zitadel.ingress.v1", …])` or a per-route `.http()`, and let the gateway own the default-closed rule for command paths. + +### 12. e2e-celld `graphql_todo_payload` is a JSON twin of the typed payloads, with domain defaults in it +- Category: A/C Severity: high Confidence: CONFIRMED +- Where: `tests/e2e-celld/crates/todo-service/src/host.rs:8-82`, `chat-service/src/host.rs:9-33` +- What: `CelldRoute::new(TODO_CELL_COMMANDS, "todo", todo_shard, graphql_todo_payload)` takes a hand-kept command-name list, the aggregate type as a string, and a shard function re-deriving `input.todo_id` (already `shard: |input| input.todo_id.clone()` in each declaration). It also takes a 50-line `match command { "todo.create" => json!({...}) … }` that rebuilds each payload from `remote`/`input`/`session`, with fallbacks such as `"todo.complete" => "completed"` and `owner_id` from the session. +- Why it matters: this is a second copy of `TodoCreatePayload` and the others, plus state-transition knowledge in a host. If the cell response lacks a field, the GraphQL payload is plausibly fabricated instead of failing. +- Change (M, breaking): `CelldCommandHost::route_aggregate::()` derived from mounted specs (kind = `aggregate_type`, shard = the declaration's shard, payload = the cell's typed response as-is). Delete both `host.rs` files. + +### 13. e2e-celld shares the domain, read-model, projection and UI crates but copies the entire service layer +- Category: C Severity: high Confidence: CONFIRMED +- Where: `tests/e2e-celld/crates/**` vs `tests/e2e-ui/crates/service/src/**` +- What: + - Shared by path dependency: the three domain crates, `e2e-readmodels`, `e2e-projections`, and the UI. + - Copied: `modules/graphql.rs` (803 lines; the diff is the missing delivery variant and "e2e-ui"→"e2e-celld" in `expect` strings, including about 500 lines of tests). + - Copied with 0 differing lines: the identity ingestor `zitadel/{auth,handle,map,mod,publish}.rs`, `zitadel_scrape.rs`, `util.rs`, `project_auth_user.rs`. + - Copied near-identically: `scrape.rs` (7 differing lines), `projections.rs`, `bounds.rs` ×5, the Todo mount list, `application.rs`, `compose.rs`, `spawn_zitadel_scrape`. + - Genuinely celld-specific: about 130 lines in the two `host.rs` route files plus `graphql-service/host.rs`. +- Why it matters: the README says the sibling "mounts the same declarations". The declarations yes, but an author cannot retarget a module without forking the service crate. Every fix to the ingestor or surface code must be made twice. +- Change (M): e2e-celld becomes one runner crate depending on `e2e-service` (or on shared `todo-module`, `chat-module`, `identity-module` crates), adding only a `CommandHost` and bus choice. This is also the real test of principle 6. + +### 14. `blob-domain` depends on the read-model crate and carries a duplicate mutation file +- Category: A/C Severity: medium Confidence: CONFIRMED +- Where: `blob-domain/Cargo.toml:15,25`, `blob-domain/src/commands/support.rs:25-34`, `blob-domain/src/mutations/save_blob_game.mutation.graphql` (identical to the one in `projections/src/mutations/`), `move_dir.rs:37-53`, `wasm.rs:29-38` +- What: for `Atomic` the domain crate imports `e2e_readmodels::BlobGames` and keeps its own private `SaveBlobGame()` because depending on `e2e-projections` would be circular. The WASM preview is wired by four strings (`"blob.simulate_move"`, `"blob/pkg/blob_wasm"`, `"blobSimulateMove"`, `"BlobGames"`) plus a string list of assigned columns that `wasm.rs` re-types by hand as JSON keys. +- Why it matters: a domain → read-model dependency is a layering inversion. Two copies of one mutation program can diverge between the command seal and the projector. A typo in the assign list or a WASM key plausibly fails closed at runtime (no preview), not at build. +- Change (M): + - Commands with Atomic outcomes belong in the crate that owns the projection, or `Atomic` should be keyed by the projection descriptor (`outcome: Atomic`) so the row and program come from one place. + - Generate the WASM export and `CommandProjectionPureReduce` from one annotated Rust function, for example `#[pure_reduce(model = BlobGames)] fn simulate_move(row: &BlobGames, args: MoveArgs) -> BlobGamesPatch`. + +### 15. `TodoState` and `Todos` are the same struct twice, with `status` degraded to `String` +- Category: C/F Severity: medium Confidence: CONFIRMED +- Where: `todo-domain/src/models/todo_state.rs:12-40`, `readmodels/src/models/todos.rs:10-20`, `todo_status.rs:3-10`, `ui/src/routes/todos/+page.svelte:35-37` +- What: `Todo` → `TodoState` (hand `From` mapping the enum to `"open"|"completed"|"archived"`) → `Todos` (same five columns plus the join) → TypeScript `todo.status === 'open'`. The enum exists and derives serde `snake_case`, but neither the domain state nor the read model uses it. The allowed values live in doc comments (`/// open | completed | archived`). +- Why it matters: field renames must be made in three structs with nothing tying them together except the upsert at program-build time (PLAUSIBLE: startup error). Status typos on the UI side are unchecked. +- Change (M): support enum columns in `ReadModel`, `DomainState` and the generated GraphQL/TypeScript. Allow `#[derive(DomainState)]` to project from the aggregate (`#[domain_state(from = Todo, skip(purged, snapshot_generation))]`). Consider letting the read model reuse the state struct plus relationships. + +### 16. Stringly-typed coupling the compiler cannot check +- Category: F Severity: medium Confidence: CONFIRMED (sites); failure modes as marked +- Where and what: + - **Command name, GraphQL field, client method:** `"todo.complete"` / `"todos_complete"` in `commands/complete.rs:30,38`. Re-typed in the `commands/mod.rs:54-62` test, celld `host.rs:8-16,43-77`, `suite/src/lib.rs:296-300`, `e2e/helpers/optimism.ts:11-20`, `graphql.rs:462-464`. The TypeScript client is generated, so the UI is checked. The celld route list silently falls back to local dispatch if a name is missing (PLAUSIBLE). + - **Roles:** `["user","admin"]` in 11 command declarations, `ModelPermissions.grant("user", …)` ×4, `.roles(&[…])` at `graphql.rs:84`, surface triples at `graphql.rs:85-95,217-225`, OIDC `engine_roles` at `graphql.rs:291`, `has_role("admin")` at `support.rs:26`, and TypeScript `ui/src/lib/roles.ts:8-12`. A grant for an undeclared role is a startup error (CONFIRMED, `src/graphql/engine/builder.rs:689`). A command `roles:` typo plausibly yields a command nobody can call. + - **`roles.ts` already diverges:** it treats group `admins` as admin, while the Rust `engine_roles` list has only `admin`. + - **Claim `"x-user-id"`:** `claim("x-user-id")` in `todos.rs:30` and `blob_games.rs:33`, although `USER_ID_KEY` exists (used in `util.rs:103`). A typo plausibly matches zero rows silently. + - **Mutation IR:** `upsert_todos`, `delete_todos_by_pk(todo_id:)`, `$input.todo` versus `input: { todo: body }`. The table name is parsed out of the field name (`distributed_macros/src/mutation.rs:259-301`). Model existence and key agreement are checked when the program is built (PLAUSIBLE: first `TODOS.program()`, guarded by `.expect` at startup). + - **Projection name and epoch:** see finding 5. + - **`aggregate_type = "todo"`** (`todo.rs:59`) re-typed as the cell kind `"todo"` in celld `host.rs:20`. A mismatch gives a wrong cell address at runtime. + - **Zitadel event names:** five strings in `project_auth_user.rs:11-17` plus `contains("deactivated")` dispatch. +- Change (M): role constants or an app `Role` enum accepted by `roles:`, `grant` and `.roles`, exported to TypeScript. A `claim::user_id()` helper. Mutation operations checked against the `model:` type at macro time (`upsert Todos from input.todo` already has the type). + +### 17. `ui/distributed.config.js` is 300 lines of security-hardened JSON loading in user code +- Category: C/F Severity: high Confidence: CONFIRMED +- Where: `tests/e2e-ui/ui/distributed.config.js:21-259,263-306`; also present at `examples/game/sveltekit/distributed.config.js`; `distributed_cli/src/lifecycle/project.rs` also reads the inventory +- What: the app-owned config implements symlink rejection, `O_NOFOLLOW`, a 1 MiB cap, a JSON nesting-depth scanner, a secret-looking-string regex, and path-portability checks for a 30-line `distributed.clients.json`. It then hand-builds `cargo run … -p distributed_cli … client-manifest --package e2e-service --distributed-path ../../..` argument arrays. A dedicated test (`ui/tests/client-inventory-parity.test.mjs`) exists to keep the config in line. +- Why it matters: a copyable template makes every app own framework validation code. The CLI already parses the same file, so there are two validators. +- Change (M): `distributedSvelteKit()` with no arguments reads `distributed.clients.json` and locates the CLI. Validation lives in `@hops-ops/distributed` and the CLI only. An app's `distributed.config.js` should be absent or under 10 lines. + +### 18. The chat page hand-rolls live pagination, de-duplication and ordering +- Category: A Severity: high Confidence: CONFIRMED +- Where: `ui/src/routes/chat/+page.svelte` script lines 51-134, 250-306; `ui/src/lib/chat/lobby-log.ts:74-108`; `routes/chat/+layout.graphql:2-8` +- What: the page keeps its own `history` array, `historyOffset`, `hasMoreHistory` and `historyExhaustedAtNewestId`. It opens ad-hoc `chat.use({limit, offset}, {live:false})` stores and calls `refetch()`, `get()`, `destroy()`. It merges pages by `message_id`, re-sorts by `created_at` in TypeScript, re-absorbs cached windows on soft navigation, and filters "sparse incomplete rows … possible mid-flight" with a type guard at lines 107-112 and 271-276. Pagination is offset-based under a live head, so every new message shifts the window, which is why the de-dup exists. +- Why it matters: README principle 08 says the page "does not patch arrays". The framework has keyset scans server-side (`docs/bounded-read-model-scans.md`), but I found no client pagination primitive in `js/src/sveltekit` (grep for `fetchMore|loadMore|paginate|cursor` returned nothing). Rows that do not match the generated type are leaking to app code. +- Change (L): a generated `Operation.useWindow()` / `fetchMore()` with keyset cursors that returns one ordered, de-duplicated list. The replica should never surface partially shaped rows through a typed operation. + +### 19. The client supplies the chat `created_at` and a millisecond-derived primary key +- Category: A/E Severity: medium Confidence: CONFIRMED (code); PLAUSIBLE (collision scenario) +- Where: `ui/src/routes/chat/+page.svelte` script 312-329, `chat-domain/src/commands/post.rs:25-27,44,77-106` +- What: the page sends `message_id = "m-" + Date.now().toString(16)` and `created_at: String(now)`. The server accepts the client timestamp if it is within five minutes, and skips even that check on wasm cells (`post.rs:92`). Two users posting in the same millisecond produce the same aggregate id. The second is rejected server-side ("already exists"), after its optimistic upsert has overwritten the other user's row in that replica. +- Why it matters: the ordering key of a shared room is client-controlled. The reason is that optimism needs the value before the server answers and `command_input_defaults!` offers only `uuid_v7()`. +- Framework gap: no `now()` default or server-stamped column that the optimistic row can hold provisionally. +- Change (M): add `default input.created_at = now_ms()`, where the client generates it for preview and the server overwrites it authoritatively. Use the existing `uuid_v7()` default for `message_id`, as Todo does. Remove `canonical_near_unix_millis`. + +### 20. Three pages, three id strategies, and hand-tracked pending state +- Category: A Severity: medium Confidence: CONFIRMED (code); PLAUSIBLE that existing `pending` receipts could replace it +- Where: `ui/src/routes/todos/+page.svelte:26,44-55`; `blob/[[gameId]]/+page.svelte` script 24-26,62-68,97-108; `chat/+page.svelte` script 51,320-343; README.md:410 +- What: + - **Ids:** Todos calls `createReplicaUuidV7()` and passes `todo_id` explicitly, although the command has `default input.todo_id = uuid_v7()` and the README shows `commands.todo.create({ title })`. Blob builds `blob-<12 hex>` from `crypto.randomUUID`. Chat uses the millisecond id from finding 19. + - **Pending state:** each page keeps its own (`pendingCreateIds` set, `pendingCommandCount`, `deliveryById`). On Todos a failed create never removes its id from `pendingCreateIds`, because the delete happens only on the success path. +- Why it matters: the page needs the id only to mark the optimistic row as "Saving…", so the framework does not expose "this row is optimistic or pending" on query rows. `sveltekit/replica.ts:159` has a `pending` receipts list, but the template does not use it. +- Change (M): expose per-row provenance (for example `$query.pending.has(row)`) and return the generated id from the command call synchronously. Then make the pages match the README. + +### 21. TypeScript twins of blob domain rules, and a test hook in page code +- Category: A/C Severity: medium Confidence: CONFIRMED +- Where: `ui/src/routes/blob/[[gameId]]/+page.svelte` script 111-137, 193-207; `ui/src/lib/blob/board.ts:6-13`; `blob-domain/src/core/tile.rs:3-8`; `readmodels/src/models/blob_games.rs:18` +- What: + - `canMove(direction)` re-implements the board-edge rule in TypeScript ("don't dispatch a predictably rejected command"), although the WASM pure already knows it. + - `TILE = {hole:0,…,player:9}` duplicates `tile.rs`, whose own comment says "client board + domain parity". + - The board is stored as `map_json: String`, parsed with `JSON.parse` and hand-validated on the client. + - The page calls `ensurePureFunctionsReady()` itself and installs `window.__distributedBlobRefetch` for Playwright. + - Todos has a milder case: `if (target.status !== 'open') return` (lines 58-91). +- Why it matters: principle 5 says "do not write a TypeScript twin", and the showcase for it has two. +- Change (M): JSON/array columns typed end to end. Enum or const export from Rust into the generated client. The generated command exposes `commands.blob.move.preview(input)` so the page can ask the same pure whether a move is a no-op. Warm WASM automatically. Drop the window hook. + +### 22. Every surface needs its own copy of the same GraphQL document +- Category: C Severity: low Confidence: CONFIRMED +- Where: `ui/src/routes/chat/+layout.graphql` vs `+layout.public.graphql` (identical bodies), `chat/+page.svelte` script 14-18,42-43, `chat/+layout.server.ts:18-37`, `ui/distributed.clients.json:4-28` +- What: user and anonymous surfaces need separate files ("authorization surfaces own distinct source files even when … intentionally equal"), two generated modules, a runtime `signedIn ? UserChatMessages : PublicChatMessages`, and a second `createDistributedSvelteKitServer`. Each protected page also has a `+page.server.ts` whose only job is `requireAuth`. +- Change (S–M): let one document be listed under several clients in `distributed.clients.json` (or a `# @surfaces(user, public)` pragma), and offer a route-level auth declaration. + +### 23. `docs/application-composition.md` describes an API that does not exist and contradicts the README +- Category: F Severity: high Confidence: CONFIRMED +- Where: `docs/application-composition.md:3,47-57,63-75,84-96,104-137,172-190`; README.md:347,377,551 +- What: it is marked "accepted direction". It documents `CommandDef`, `SystemSlice`, `ProcessRole::{Full,Writer,Projector,QueryApi}`, `Runtime::sqlite()`, `runtime.app().role().run()` and `projection_inventory!`, none of which my symbol script found in `src/`, `distributed_macros/` or `distributed_cli/src/`. Item 6 is marked "Done" while items 1–5 are not built. Its core concept is a process-role flag; the README says three times "You do not flip a `Runtime::role` flag". +- Why it matters: its "Target shape of e2e-ui" table is the same list as findings 4–8, so the diagnosis is right. The owner should decide between a role enum and explicit composition, then delete or rewrite the doc. +- Change (S): move it to GitKB as a spec, or rewrite it against the chosen design. Do not ship it under `docs/`. + +### 24. README: stale or wrong statements +- Category: F Severity: medium Confidence: CONFIRMED +- Where and what: + - **516-517, 2318:** "UI http://localhost:5180 / API http://127.0.0.1:8791". The app's own README (`tests/e2e-ui/README.md:49-51`) says the public UI is `http://localhost:8791` and 5180 is internal; the OIDC cookie only works on `localhost`, not `127.0.0.1` (`scripts/up.sh:11-12`). + - **1768-1790:** "Every registered command becomes a `POST /:command` endpoint", with a curl example. This contradicts 380-382 and `runtime.rs:100-104` (off unless `with_http_command_routes()`). + - **1640-1645:** a migration note ("This is a breaking Rust API change. Replace `GraphqlInput`/`GraphqlOutput` …") for types that no longer exist, in a pre-release README. Similar wire-version history sits at 2549-2552 and 2586-2591. + - **593-600:** the crate layout lists `readmodels/ # projections + read_model_catalog` and `service/ # thin command handlers…`. Projections are a separate crate, command handlers live in the domain crates, and `blob-domain`, `projections` and `suite` are missing. + - **402-413:** `commands.todo.create({ title: text })` does not match the page (finding 20). + - **2125-2165:** the "Mount on a service" example uses `typed_command(...).emits().applies(/* state_preview! */)` and `GraphqlEngine::from_schema_catalog(...).permission::()`. The APIs exist, but this is not how the template does it (`GraphqlEngine::builder(pool).model::(Todos::permissions())`), and e2e tests are named `…auto_derive_optimism_without_applies`. + - **607-620:** `distributed = "0.1"` and `cargo install distributed_cli` (2567) while the license section (2842-2845) says there is no licence file and npm is `UNLICENSED`. + - **Clean:** all 54 relative links and 51 backticked repo paths in README and docs resolve. The "Project Structure" tree matches the paths I spot-checked. + +### 25. README structure: pitch, operations runbook and API reference in one 2,845-line file +- Category: F Severity: medium Confidence: CONFIRMED +- Where: README.md:202-299, 646-2713 +- What: the "06 · Projections" principle contains about 100 lines on source-version fencing, migration `0005`, the `SnapshotProjectionRebuild` runbook and its 10,000-record / 64 MiB limits before it returns to "Handlers stay thin". The CLI section contains manifest byte budgets and NATS header notes (2541-2565). Nine of the twelve `docs/*.md` files are not linked from the README. +- Change (M): + - README: principles 01–10 at one screen each, "See it run", "Use as a dependency", a feature table, and links. Target about 400 lines. + - Move reference material to `docs/` as guides: aggregates, commands (one form), projections (including snapshots and rebuild), read models and GraphQL, bus/outbox, microsvc, CLI, testing. + - Move design notes that are incident write-ups from a downstream app (`live-retired-owner-handoff`, `protocol-manifest-reuse` with dated "Forge" timings, `session-refresh-continuity`, `reloading-event-delivery`) to `docs/design/` or GitKB. + - Delete migration notes. + +### 26. First run needs Docker, Zitadel and a 637-line bootstrap before a todo can be created +- Category: F Severity: medium Confidence: CONFIRMED (steps); PLAUSIBLE (no login-free UI path; `auth.ts` not read) +- Where: README.md:511-524, `tests/e2e-ui/README.md:16-47`, `tests/e2e-ui/Makefile:29,53-68`, `tests/e2e-ui/scripts/up.sh:1-60`, `crates/runner/src/main.rs:16-18`, `tests/e2e-celld/README.md:63-65` +- What: + - The README says `make up` then `distributed dev`. `distributed` is not on PATH from a checkout; the Makefile actually runs `cargo run --manifest-path ../../Cargo.toml -p distributed_cli --bin distributed -- dev .` via `make run`, which the root README does not mention. The README also says the CLI, crate and npm versions must match exactly, so `cargo install distributed_cli` cannot serve a checkout. + - `make up` needs docker, jq, curl and openssl, and bootstraps Zitadel plus Postgres. + - The runner itself defaults to SQLite and DevHeaders, but the UI goes through Auth.js/OIDC, so the zero-dependency backend is not reachable from the UI. + - "Option A" comes first in the app README and needs the external `hops` CLI plus kind and Crossplane. + - A cold compile can exceed the `distributed dev` five-minute readiness window (e2e-celld README). + - The only zero-dependency example is `examples/graphiql.rs`, which hand-builds a `TableSchema` literal and seeds with raw `CREATE TABLE`/`INSERT` (lines 23-70): no aggregate, command or projection. +- Change (M): add one no-Docker quickstart (`cargo run` → SQLite + DevHeaders + a dev login in the UI, or a tiny `examples/todo` using `#[sourced]`, `#[command]`, `projection!`, `ReadModel` and GraphiQL). Document `make run` as the checkout path. Put Option B before Option A. Replace the `graphiql.rs` seeding with real commands. + +### 27. Framework-internals tests and can't-fail tests inside the template +- Category: B Severity: medium Confidence: CONFIRMED (names and bodies cited); `blob.rs` test bodies not fully read +- Where and what: + - `projections/src/blob.rs:62-480`: about 400 lines of fixtures (`patch_blob_program`, `delete_blob_program`, `multi_row_blob_program`, a `BlobGameAudits` model) driving `lower_model_mutation`/`finish_lowering` for `patch_delete_and_multi_row_descriptors_are_not_direct_candidates`, plus `compile_fail` doctests for "removed authoring surfaces" (lines 44-60). These are framework lowering tests living in an app crate. + - `projections/src/todos.rs:116-142` `graphql_file_matches_inline_graphql_looking_form`: asserts three macro syntaxes share IR. A macro test, not an app test. + - `todos.rs:69-74` asserts `program.arms().len() == 8`. + - `shard_is_todo_id` ×7 and `shard_is_game_id` (for example `complete.rs:47-53`) restate the one-line closure. + - `create_uses_handle_escape_hatch`, `force_archive_uses_handle_escape_hatch`: cannot fail meaningfully. + - `blob-domain/src/commands/mod.rs:54-59` `client_preview_wasm_stays_in_blob_domain_wasm_module`: `include_str!("../wasm.rs").contains("blobSimulateMove")`. + - `graphql.rs:826-833` `module_inventory_lists_todo_chat_blob_identity`: a constant equals a literal. + - `service/src/handlers/util.rs:100-150`: five tests for helpers with no callers. + - All `graphql.rs` tests are duplicated in e2e-celld. +- Good and worth keeping: `models/todo.rs` tests (rules, idempotent no-ops, replay), `todo_commands_auto_derive_optimism_without_applies`, `application_todos_keep_portable_owner_row_policy…`, `public_surface_opens_and_queries_chat_without_identity`, and the `suite/tests/behavioral.rs` t0–t10 cases. +- Change (S): move the lowering and macro tests to the framework's own tests. Delete the restating ones. + +### 28. Dead and duplicated helpers in the template +- Category: C/F Severity: low Confidence: CONFIRMED +- Where: `service/src/handlers/util.rs:33-98`, `todo-domain/src/commands/support.rs`, `blob-domain/src/commands/support.rs:7-23`, `chat-domain/src/commands/post.rs:8-18`, `service/src/handlers/commands/mod.rs`, `modules/graphql.rs:25-34`, `util.rs:16-31` +- What: + - `require_user`, `require_admin`, `session_has_user`, `session_is_admin`, `causal_has_user`, `causal_is_admin`, `principal`, `rejected` in `util.rs` have no callers outside the file; only `decode_payload` and `read_model_error` are imported. + - `rejected`, `principal` and `authenticated_user` are defined identically in three domain crates. + - `handlers/commands/mod.rs` is an empty placeholder. + - `ClientSurfaceLocks` is a newtype around `Arc` used only to get `Clone`. + - `decode_payload` sniffs JSON versus bitcode by first byte. +- Change (S): the framework should provide `HandlerError::rejected(e)` and built-in guards (`guard: authenticated` / `guard: role("admin")`). `ctx.input::()` should decode by content type. `InMemoryLockManager` should be `Clone`. Then delete all of the above. + +### 29. Playwright suite: behavioural, but timing- and CSS-coupled and gated on the full stack +- Category: B Severity: low Confidence: CONFIRMED (todos spec, helpers, config); other specs by grep only +- Where: `tests/e2e-ui/e2e/todos.user.spec.ts:4,136-159,362,389,414,434,537`; `e2e/helpers/optimism.ts:34-57`; `playwright.config.ts:35-48`; `crates/suite/tests/behavioral.rs:102-120` +- What: + - **Strengths:** the tests assert real behaviour. Optimistic paint is proven by holding the mutation request; a per-animation-frame trace checks no intermediate mis-ordered frame; the mutation is counted as sent once. + - **Weaknesses:** five `page.waitForTimeout(750)` waits to "prove nothing regresses"; class selectors (`.panel`, `.item`, `.ch-msg`, `.ad-table tbody tr`) coupled to styling; `expectBinarySorted` assumes ids sort lexicographically; substring matching on POST bodies; `workers: 1`, 90 s timeouts. + - **Not the only whole-system check:** `suite/tests/behavioral.rs` boots SQLite, InMemoryBus, projector and HTTP in-process with no Docker and covers isolation, RBAC, purge and Atomic blob. It polls for projections with `sleep(30ms)` ×100 because a Rust caller has no "await projected". + - **Gap:** the browser/replica path (optimism, live, SSR) is verified only with Postgres and Zitadel up. There is no browser run against the in-process SQLite + DevHeaders stack. +- Change (M): add `data-testid`/role selectors. Replace fixed waits with waiting on the command receipt's `projected` promise (exposed for tests). Give the Rust suite a causal wait helper. Add one Playwright project against the no-Docker stack. + +### 30. Repo hygiene +- Category: F Severity: low Confidence: CONFIRMED +- Where and what: + - **Skill directories:** `.claude/skills/*` and `.codex/skills/*` are symlinks into `.kb/skills/` and `.agents/skills/`, not copies. Only `.codex/skills/rust-best-practices` is a real directory, and it is not exposed to `.claude`. `skills-lock.json` pins two third-party skills, one visible to each agent. + - **Stale script:** `scripts/graphql-skill-dry-run.sh:22` tests for `docs/graphql.md`, which does not exist, so the script fails. It references a task slug and `GROK_SCRATCH`, and nothing references it. + - **Unreferenced wrapper:** `scripts/setup-graphql-oidc-zitadel.sh` is a five-line `exec` of `oidc-zitadel-up.sh`. + - **AGENTS.md / CLAUDE.md:** identical five-line stubs pointing at `.kb/AGENTS.md`. That file is the older GitKB guide (`.kb/workspace/`, `git-kb commit --all`, mandatory banner) and disagrees with the parent repo's newer one. Neither says how to build or test the framework. The parent CLAUDE.md asks for the Crossplane/Upbound reminder to be copied into each sub-repo AGENTS.md; it is not here (and is not relevant). + - **Tracked files:** no build outputs, `node_modules`, generated clients, `.wasm` or `.db` files. The e2e-ui workspace has no tracked `Cargo.lock` while `examples/game/server` and `tests/gateway-*` do, so the template is not reproducible. + - **`walkthrough/demos.ts`:** 1,597 lines holding 84 hand-copied code snippets as strings (for example lines 709-720 re-type `MODULE_IDS`). This is a third copy of the source after code and README, and I found no test that references the walkthrough. + - **`tests/e2e-ui/PROJECTION_ROLLOUT.md`:** a production cut-over runbook ("name one accountable person or on-call rotation") inside a test fixture. + - **Location:** the flagship "copyable template" lives under `tests/`. +- Change (S): delete the two scripts. Write a real AGENTS.md (build, test, layout). Track `tests/e2e-ui/Cargo.lock`. Generate walkthrough snippets from source regions or drop them. Move the template to `examples/app` or `templates/`. + +## Things that are good and should not be changed +- **Domain crates as plain structs.** `todo-domain/src/models/todo.rs` puts rules in methods, uses `#[event(.., domain)]` recorders, has behavioural tests, and compiles with `default-features = false` for wasm. +- **Permissions next to the model.** `Todos::permissions()` with `col("owner_id").eq(claim(..))` is used for both server RLS and client-portable row policy. Keep the shape; only remove the re-registration. +- **The `projection!` + mutation IR model.** One program serves the server projector and the browser replica, and optimism is auto-derived from the transition (no `.applies`). The `todo_commands_auto_derive_optimism_without_applies` test is the right kind of test. +- **Lifecycle-owned client generation.** `distributed build`/`dev` owns it, nothing generated is tracked, clients are per surface, and colocated `.graphql` islands use GraphQL defaults as bindings. +- **The in-process behavioural suite and the held-mutation Playwright helper.** `crates/suite/tests/behavioral.rs` (GraphQL-only edge, owner isolation, HTTP command routes closed by default) and `expectOptimisticPaint` prove behaviour, not structure. diff --git a/docs/session-refresh-continuity.md b/docs/session-refresh-continuity.md new file mode 100644 index 000000000..8dd624d2e --- /dev/null +++ b/docs/session-refresh-continuity.md @@ -0,0 +1,29 @@ +# Session refresh continuity + +The server loader must pair a credential with independently authorized route +data on both document and SvelteKit data requests. A follow-up `invalidateAll` +request can rotate the credential again, or observe a cookie renewed by another +request. Returning only that credential leaves the browser no proof that its +existing replica scope remains authorized. + +Each request executes only its compiler-selected, bounded route/layout loads. +Routes without selections do no GraphQL work. This deliberately removes the +previous blanket data-request shortcut; data navigation remains client-side, +but selected reads run on the server to obtain fresh authority. There is no +token-derived scope, cached-proof reuse, or authorization fallback. + +The client keeps its existing rules: a fresh exact-scope transfer can rotate +transports without dropping rows or newer command state; missing, replayed, +tampered or different-scope authority still purges. SSR request isolation and +Auth.js request-local session memoization remain required. The gateway's original +Todo/Chat MutationObserver assertion is unchanged and detects transient removals, +not merely eventual recovery. + +## Retained layout navigation + +An authorized data seed for an unchanged credential and scope is a cache merge, +not a transport reauthorization. Child navigation must retain the layout's exact +live subscription and local operation fences until its last owner releases it. +Seed merging must not regress confirmed record clocks, live cursors or membership. +Credential changes still require independent authority and transport rotation; +missing authority and changed scope still invalidate the prior replica. diff --git a/docs/unsigned-command-inputs.md b/docs/unsigned-command-inputs.md new file mode 100644 index 000000000..1766768cd --- /dev/null +++ b/docs/unsigned-command-inputs.md @@ -0,0 +1,60 @@ +# Unsigned command inputs and optimistic projections + +Use the Rust type that expresses the domain boundary: + +```rust,ignore +#[derive(serde::Deserialize, distributed::CommandInput)] +pub struct UpdateDocumentInput { + pub document_id: String, + pub expected_revision: u64, +} +``` + +`CommandInput` and `CommandOutput` retain unsigned width automatically, including +optional fields and list elements. A field remains GraphQL `BigInt` and TypeScript +`number`. Its generated command codec carries the narrower unsigned contract: + +| Rust type | Command codec | Browser range | +| --- | --- | --- | +| `u8` | `uint8` | 0–255 | +| `u16` | `uint16` | 0–65,535 | +| `u32` | `uint32` | 0–4,294,967,295 | +| `u64` | `uint64_safe_integer` | 0–9,007,199,254,740,991 | + +`usize` follows the target's pointer width. Fixed-width types are preferable +for portable domain contracts. + +For example, an event preview can bind `input.expected_revision` to a typed +`u64` event field. The manifest compiler now proves that assignment from the +unsigned codec, and the generated command prepares the same integer in its +optimistic projection and transport input. No browser annotation or handwritten +optimistic mutation is needed. + +Command preparation rejects negative numbers, negative zero, fractions, +non-finite numbers, strings, and numbers above the codec's maximum before any +optimistic effect or dispatch. The same validation applies to generated command +results and trusted presets. Explicit trusted presets targeting U64 projection +slots must declare an unsigned codec; an unrestricted signed `BigInt` preset +cannot establish that proof. + +JavaScript numbers cannot represent every `u64` exactly. The browser boundary +deliberately stops at `Number.MAX_SAFE_INTEGER`. Rust command execution retains +the full unsigned range, and projection constants and stored aggregate state +retain their existing full-width U64 representation. Signed command codecs and +SQL read-model scalar codecs are unchanged. + +## Regeneration + +This changes command contract and protocol fingerprints. Rebuild the service +and generated clients together with `distributed build` or `distributed dev`. +Mixed old/new artifacts fail the existing fingerprint check. + +Code that manually constructs `CommandTypeField` or `SurfaceTypeField` must +set `unsigned_integer` to the matching `CommandUnsignedInteger` variant, or +`None` for unrefined fields. Prefer derives so this metadata follows the Rust +type. A refinement on a non-`BigInt` field is rejected. + +Typed application manifests preserve `unsigned_integer` in canonical Surface +command input and output contracts, including nested types. Decoding and +re-encoding retains the same contract bytes and fingerprints. Unrefined fields +omit this metadata, preserving their existing canonical representation. diff --git a/examples/game/.gitignore b/examples/game/.gitignore new file mode 100644 index 000000000..4688cb85f --- /dev/null +++ b/examples/game/.gitignore @@ -0,0 +1,6 @@ +# Mob Pit / Leaderboard local files and celld dev state (run.sh default MOBPIT_DATA_DIR). +/.data/ +# The Mob Pit cells worker build (worker-build) and celld state. +/cells/build/ +/cells/target/ +/cells/.celld/ diff --git a/examples/game/.gitops/local/Chart.yaml b/examples/game/.gitops/local/Chart.yaml new file mode 100644 index 000000000..23b72d309 --- /dev/null +++ b/examples/game/.gitops/local/Chart.yaml @@ -0,0 +1,5 @@ +apiVersion: v2 +name: mobpit-local +description: Mob Pit on Hops local (source-mounted dev workload); rooms on the mobpit-system celld fleet. +type: application +version: 0.1.0 diff --git a/examples/game/.gitops/local/templates/_helpers.tpl b/examples/game/.gitops/local/templates/_helpers.tpl new file mode 100644 index 000000000..09dbd49ab --- /dev/null +++ b/examples/game/.gitops/local/templates/_helpers.tpl @@ -0,0 +1,21 @@ +{{/* The checkout root (source.localPath is examples/game). */}} +{{- define "mobpit.repo" -}} +{{- .Values.source.localPath | dir | dir -}} +{{- end -}} + +{{- define "mobpit.game" -}} +{{- .Values.source.localPath -}} +{{- end -}} + +{{- define "mobpit.host" -}} +{{- .Values.host | default (printf "%s.%s" .Values.environment.name .Values.localDomain) -}} +{{- end -}} + +{{- define "mobpit.relayUrl" -}} +{{- printf "http://mobpit.%s.svc.cluster.local:2567/internal/celld-queue/relay" .Values.environment.namespace -}} +{{- end -}} + +{{- define "mobpit.labels" -}} +app.kubernetes.io/part-of: mobpit +hops.ops.com.ai/runtime: cluster-dev +{{- end -}} diff --git a/examples/game/.gitops/local/templates/deployer-script.yaml b/examples/game/.gitops/local/templates/deployer-script.yaml new file mode 100644 index 000000000..a2dca5832 --- /dev/null +++ b/examples/game/.gitops/local/templates/deployer-script.yaml @@ -0,0 +1,57 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: mobpit-worker-deployer + namespace: {{ .Values.environment.namespace }} + labels: + {{- include "mobpit.labels" . | nindent 4 }} +data: + deploy.sh: | + set -euo pipefail + export PATH="/tools:$PATH" + npm install --silent --no-audit --no-fund --prefix /tmp/esbuild "esbuild@$ESBUILD_VERSION" + export CELLD_ESBUILD=/tmp/esbuild/node_modules/.bin/esbuild + last="" + while true; do + # The build's outputs and the worker config; empty until built. + # A failed read (missing build, host share I/O error) skips the round. + if ! stamp="$(stat -c '%n %Y %s' "$CELLS/wrangler.jsonc" "$CELLS"/build/worker/* "$CELLS"/build/*.wasm "$CELLS"/build/*.js | sha256sum)"; then + sleep 3 + continue + fi + if [ -f "$CELLS/build/worker/shim.mjs" ] && [ "$stamp" != "$last" ]; then + rm -rf /tmp/worker && mkdir -p /tmp/worker + if ! cp -R "$CELLS/build" /tmp/worker/build || + ! node /deployer/wrangler.mjs "$CELLS/wrangler.jsonc" /tmp/worker/wrangler.json; then + echo "reading the build failed; retrying" >&2 + sleep 3 + continue + fi + echo "deploying the cells worker to $BUCKET" + if celld deploy /tmp/worker --bucket "$BUCKET"; then + last="$stamp" + else + echo "deploy failed; retrying" >&2 + sleep 10 + continue + fi + fi + sleep 3 + done + wrangler.mjs: | + // The worker config with this Environment's vars (secrets stay out of + // the checkout: they are inlined only into the deployed copy). + import { readFileSync, writeFileSync } from 'node:fs'; + const [source, target] = process.argv.slice(2); + const text = readFileSync(source, 'utf8') + .split('\n') + .filter((line) => !line.trimStart().startsWith('//')) + .join('\n'); + const config = JSON.parse(text); + for (const key of ['DISTRIBUTED_INTERNAL_SECRET', 'GAME_TICKET_SECRET', 'CELLD_QUEUE_RELAY_URL', 'CELLD_QUEUE_RELAY_MESH', 'ZONE_MAX_PLAYERS']) { + if (process.env[key]) config.vars[key] = process.env[key]; + } + for (const [key, value] of Object.entries(JSON.parse(process.env.WORKER_VARS || '{}'))) { + config.vars[key] = String(value); + } + writeFileSync(target, JSON.stringify(config)); diff --git a/examples/game/.gitops/local/templates/deployer.yaml b/examples/game/.gitops/local/templates/deployer.yaml new file mode 100644 index 000000000..0a8e6a057 --- /dev/null +++ b/examples/game/.gitops/local/templates/deployer.yaml @@ -0,0 +1,84 @@ +# Deploys the cells worker (rooms + cells, built on the host by +# `./run.sh build` into examples/game/cells/build) into the mobpit-system +# fleet, and again whenever that build changes. celld nodes adopt a new +# deployment in place. The worker's vars get this Environment's secrets and +# its relay URL (the last Environment to deploy owns the fleet). +{{- $repo := include "mobpit.repo" . }} +{{- $game := include "mobpit.game" . }} +apiVersion: apps/v1 +kind: Deployment +metadata: + name: mobpit-worker-deployer + namespace: {{ .Values.environment.namespace }} + labels: + {{- include "mobpit.labels" . | nindent 4 }} + app.kubernetes.io/name: mobpit-worker-deployer +spec: + replicas: 1 + strategy: + type: Recreate + selector: + matchLabels: + app.kubernetes.io/name: mobpit-worker-deployer + template: + metadata: + labels: + {{- include "mobpit.labels" . | nindent 8 }} + app.kubernetes.io/name: mobpit-worker-deployer + annotations: + checksum/script: {{ include (print $.Template.BasePath "/deployer-script.yaml") . | sha256sum }} + spec: + initContainers: + # celld's own CLI, from the fleet's image. + - name: celld + image: {{ .Values.celld.image }} + command: [/bin/sh, -c, 'cp "$(command -v celld)" /tools/celld'] + volumeMounts: + - {name: tools, mountPath: /tools} + containers: + - name: deployer + image: {{ .Values.images.node }} + command: [/bin/bash, /deployer/deploy.sh] + env: + - name: CELLS + value: {{ printf "%s/cells" $game | quote }} + - name: BUCKET + value: {{ .Values.celld.bucket | quote }} + - name: ESBUILD_VERSION + value: {{ .Values.esbuildVersion | quote }} + - name: CELLD_QUEUE_RELAY_URL + value: {{ include "mobpit.relayUrl" . | quote }} + # HTTP to the relay's Service, mTLS between Istio sidecars. + - name: CELLD_QUEUE_RELAY_MESH + value: "1" + {{- with .Values.rooms.maxPlayers }} + # Raised room cap (load tests); unset, the game's 32. + - name: ZONE_MAX_PLAYERS + value: {{ . | quote }} + {{- end }} + # `worker.vars`, as JSON (a change restarts this pod, which + # redeploys the worker). + - name: WORKER_VARS + value: {{ .Values.worker.vars | toJson | quote }} + - name: GAME_TICKET_SECRET + valueFrom: {secretKeyRef: {name: mobpit, key: GAME_TICKET_SECRET}} + - name: DISTRIBUTED_INTERNAL_SECRET + valueFrom: {secretKeyRef: {name: mobpit, key: DISTRIBUTED_INTERNAL_SECRET}} + envFrom: + # AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION, S3_ENDPOINT. + - secretRef: + name: mobpit-rustfs + volumeMounts: + - {name: source, mountPath: {{ $repo }}, readOnly: true} + - {name: tools, mountPath: /tools} + - {name: script, mountPath: /deployer} + volumes: + - name: source + hostPath: + path: {{ $repo }} + type: Directory + - name: tools + emptyDir: {} + - name: script + configMap: + name: mobpit-worker-deployer diff --git a/examples/game/.gitops/local/templates/mobpit.yaml b/examples/game/.gitops/local/templates/mobpit.yaml new file mode 100644 index 000000000..06287817a --- /dev/null +++ b/examples/game/.gitops/local/templates/mobpit.yaml @@ -0,0 +1,161 @@ +# The Mob Pit pod: the services behind the framework gateway (cargo, from +# the mounted checkout) and Vite (the client, `/` through the gateway). +# The pod has an Istio sidecar, like the celld pods, so the celld outbox +# relay (`/internal/celld-queue/relay` on the `mobpit` Service) is mTLS +# between the two (the worker opts in with CELLD_QUEUE_RELAY_MESH). +{{- $repo := include "mobpit.repo" . }} +{{- $game := include "mobpit.game" . }} +apiVersion: apps/v1 +kind: Deployment +metadata: + name: mobpit + namespace: {{ .Values.environment.namespace }} + labels: + {{- include "mobpit.labels" . | nindent 4 }} + app.kubernetes.io/name: mobpit +spec: + replicas: 1 + strategy: + type: Recreate + selector: + matchLabels: + app.kubernetes.io/name: mobpit + template: + metadata: + labels: + {{- include "mobpit.labels" . | nindent 8 }} + app.kubernetes.io/name: mobpit + istio.io/dataplane-mode: ambient + spec: + containers: + - name: services + image: {{ .Values.images.rust }} + workingDir: {{ $game }}/server + command: + - /bin/bash + - -c + - | + set -euo pipefail + # The typed game client is a build output (gitignored): generate + # it from the Rust surface before serving. The ui container's + # Node image has no cargo, so its Vite plugin leaves this to us. + distributed() { + cargo run --locked --quiet --manifest-path {{ $repo }}/Cargo.toml \ + -p distributed_cli --bin distributed -- "$@" + } + distributed game-manifest --manifest-path Cargo.toml \ + --entrypoint game_demos::mobpit::game_surface --out /tmp/mobpit.json + distributed game-client --manifest /tmp/mobpit.json \ + --out {{ $game }}/client/src/generated/mobpit + exec cargo run --locked --bin game-demos -- mobpit --dev --host 0.0.0.0 --port 2567 + env: + - name: CARGO_TARGET_DIR + value: /cache/target + - name: CARGO_HOME + value: /cache/cargo + - name: CELLD_URL + value: {{ .Values.celld.url | quote }} + - name: PUBLIC_ORIGIN + value: {{ printf "https://%s" (include "mobpit.host" .) | quote }} + - name: GAME_DEMOS_UI_ORIGIN + value: http://127.0.0.1:5173 + - name: MOBPIT_DATA_DIR + value: /cache/data + - name: DISTRIBUTED_GAME_SECRET + valueFrom: {secretKeyRef: {name: mobpit, key: GAME_TICKET_SECRET}} + - name: DISTRIBUTED_INTERNAL_SECRET + valueFrom: {secretKeyRef: {name: mobpit, key: DISTRIBUTED_INTERNAL_SECRET}} + - name: DG_DEMO_ADMIN_SECRET + valueFrom: {secretKeyRef: {name: mobpit, key: DG_DEMO_ADMIN_SECRET}} + ports: + - name: http + containerPort: 2567 + readinessProbe: + tcpSocket: {port: http} + periodSeconds: 5 + volumeMounts: + - {name: source, mountPath: {{ $repo }}} + - {name: cache, mountPath: /cache} + - name: ui + image: {{ .Values.images.node }} + workingDir: {{ $game }}/client + command: + - /bin/bash + - -c + - | + set -euo pipefail + npm ci --no-audit --no-fund + exec npx vite --host 127.0.0.1 --port 5173 --strictPort + env: + # Edits arrive through the host mount; inotify does not see them. + - name: CHOKIDAR_USEPOLLING + value: "true" + # No cargo here: the services container generates the game client. + - name: GAME_CODEGEN + value: external + volumeMounts: + - {name: source, mountPath: {{ $repo }}} + # Linux packages, not the host's. + - {name: client-node-modules, mountPath: {{ $game }}/client/node_modules} + volumes: + - name: source + hostPath: + path: {{ $repo }} + type: Directory + - name: cache + persistentVolumeClaim: + claimName: mobpit-cache + - name: client-node-modules + emptyDir: {} +--- +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: mobpit-cache + namespace: {{ .Values.environment.namespace }} + labels: + {{- include "mobpit.labels" . | nindent 4 }} +spec: + accessModes: [ReadWriteOnce] + {{- with .Values.cache.storageClassName }} + storageClassName: {{ . }} + {{- end }} + resources: + requests: + storage: {{ .Values.cache.size }} +--- +# The gateway: the page, its API, the rooms (`/zones/{room}`) and, in the +# cluster, the celld outbox relay. +apiVersion: v1 +kind: Service +metadata: + name: mobpit + namespace: {{ .Values.environment.namespace }} + labels: + {{- include "mobpit.labels" . | nindent 4 }} +spec: + selector: + app.kubernetes.io/name: mobpit + ports: + - name: http + port: 2567 + targetPort: http +--- +apiVersion: gateway.networking.k8s.io/v1 +kind: HTTPRoute +metadata: + name: mobpit + namespace: {{ .Values.environment.namespace }} + labels: + {{- include "mobpit.labels" . | nindent 4 }} +spec: + parentRefs: + - name: platform + namespace: istio-ingress + # No sectionName: attach to HTTP and, where the Gateway has it, HTTPS. + hostnames: + - {{ include "mobpit.host" . | quote }} + rules: + - backendRefs: + - name: mobpit + port: 2567 diff --git a/examples/game/.gitops/local/values.yaml b/examples/game/.gitops/local/values.yaml new file mode 100644 index 000000000..988c4aad5 --- /dev/null +++ b/examples/game/.gitops/local/values.yaml @@ -0,0 +1,34 @@ +# Hops injects: local, localDomain, environment.{name,namespace}, +# source.{localPath,path,type} (localPath = examples/game in this checkout). + +# Browser hostname (HTTPRoute, PUBLIC_ORIGIN). Empty gives +# .. +host: mobpit.localhost + +# The mobpit-system celld fleet. +celld: + url: http://celld.mobpit-celld.svc.cluster.local:8080 + bucket: s3://celld + image: ghcr.io/denoland/celld:0.6.3 + +# Players a room admits; empty keeps the game's 32 (load tests raise it). +rooms: + maxPlayers: "" + +# Extra cells-worker vars, e.g. the load test's A/B switches +# (`ZONE_WORLD_PUSH: "0"`, `ZONE_FACT_BATCH: "1"`, `ZONE_UPDATE_RATES: "0"`). +# Empty keeps the game's defaults. +worker: + vars: {} + +images: + rust: rust:1.99-bookworm + node: node:24-bookworm + +# Cargo target dir, registry cache and the services' data dir. +cache: + size: 20Gi + storageClassName: "" + +# esbuild for `celld deploy` (the worker bundle). +esbuildVersion: 0.25.5 diff --git a/examples/game/.gitops/mobpit-system/celld.yaml b/examples/game/.gitops/mobpit-system/celld.yaml new file mode 100644 index 000000000..d20c172b5 --- /dev/null +++ b/examples/game/.gitops/mobpit-system/celld.yaml @@ -0,0 +1,40 @@ +# The Mob Pit celld fleet: one node on in-cluster RustFS (bucket s3://celld) +# in namespace mobpit-celld, public listener +# http://celld.mobpit-celld.svc.cluster.local:8080. Each Mob Pit +# Environment deploys the cells worker into it (the last deploy wins). +# +# The celld pods get Istio sidecars, like the Mob Pit pods: the worker's +# outbox relay to a Mob Pit Service is mTLS between them. (kind-hops can't +# run ambient: istio-cni needs IPv6 policy routing, which the Dory kernel +# lacks. RustFS stays out of the mesh.) +apiVersion: hops.ops.com.ai/v1alpha1 +kind: CelldStack +metadata: + name: celld + namespace: mobpit-system +spec: + clusterName: mobpit + namespace: mobpit-celld + releaseName: celld + # Probes celld's own /.well-known/celld/health (hops-ops/celld-chart#23); + # earlier charts probe a path the deployed Worker answers. + chartVersion: "0.5.1" + rustfs: + enabled: true + credentialsSecretRef: + name: mobpit-rustfs-credentials + values: + resources: + # The chart's 1Gi OOMs under ~256 busy rooms, and again while + # celld reclaims them after a restart (lease renewals then miss + # their TTL and celld self-fences). + limits: + memory: 4Gi + requests: + cpu: 50m + memory: 128Mi + values: + podLabels: + # Ambient mesh: istio-cni redirects traffic before containers start, + # so celld can reach RustFS immediately; no sidecar to wait for. + istio.io/dataplane-mode: ambient diff --git a/examples/game/.gitops/mobpit-system/providerconfigs.yaml b/examples/game/.gitops/mobpit-system/providerconfigs.yaml new file mode 100644 index 000000000..ccd708a6e --- /dev/null +++ b/examples/game/.gitops/mobpit-system/providerconfigs.yaml @@ -0,0 +1,19 @@ +# The CelldStack below composes into this namespace; its Helm releases and +# Objects use these (the provider's own identity, like the machine defaults). +apiVersion: helm.m.crossplane.io/v1beta1 +kind: ProviderConfig +metadata: + name: mobpit + namespace: mobpit-system +spec: + credentials: + source: InjectedIdentity +--- +apiVersion: kubernetes.m.crossplane.io/v1alpha1 +kind: ProviderConfig +metadata: + name: mobpit + namespace: mobpit-system +spec: + credentials: + source: InjectedIdentity diff --git a/examples/game/README.md b/examples/game/README.md new file mode 100644 index 000000000..a2697e169 --- /dev/null +++ b/examples/game/README.md @@ -0,0 +1,811 @@ +# distributed_game demo: Mob Pit + +One playable game, **Mob Pit**, on the authoritative game runtime +([`distributed_game`](../../distributed_game/README.md)), its browser SDK +([`@hops-ops/distributed/game`](../../js/README.md#game-zones)) and celld. +Every mechanic of the earlier standalone demos (Arena, Endless Grid, Boss +Ripple, Shooting Gallery, The Freeze) now lives in it; the same game runs +behind a Vite page and a SvelteKit app. **Dev only**: the services mint +tickets for anonymous guests and let any page change the network +simulation. + +| Page | Run | What it shows | Durable state | +|---|---|---|---| +| **Mob Pit** | `./run.sh mobpit` (`--fleet` for a local multi-node celld) | A near-infinite seeded grid of rooms joined by doorways, **each room a celld Durable Object** (celld places, forwards, hibernates and recovers rooms; the debug overlay shows the node); authoritative melee combat vs. telegraphing mobs; **hoods, boroughs and a city** above the rooms (each tier a celld cell: a seeded boss room per hood, a boss kill raises the hood's tier — tougher rooms — and a saga ripples it up; the borough's weather and darkness lift as its bosses fall, fog thickens toward boss rooms); the **rooms next door** watched as passive observers (their mobs are drawn; a watcher never wakes a sleeping room or keeps one awake) — except the doorway rooms **in reach** (toggle N, on by default: walk up to a doorway and the room behind it wakes and stays live); a **network panel** (latency / jitter / loss applied by every room object on celld, client prediction of the Rust step as WASM with reconciliation, a server ghost, an interest ring: what is outside is not replicated); kills are **non-blocking durable facts** settled exactly once in per-player cells; rooms you leave go dormant then asleep (live minimap from the zone status read model) and come back with their mobs; seeded room layouts (obstacles in the authoritative and predicted step), **jumping**, a **bow** with lag-compensated hits and **first person**; borough **world events** (invasion, frenzy, blessing) on the boroughs' own schedules; **live content updates**: an admin rolls a content pack out to every live room (freeze → apply → resume with change notes; old clients held until the entrance reloads them; facts stamped with the content version) | celld: `pit..` rooms (snapshots), `crawler/{player}`, `presence/{player}`, `zone-activity/{room}`, `hood/…`, `borough/…`, `city/city`, `content-rollout/world`; crawler list, room status and boroughs = read models projected from the cells' events | +| **Leaderboard** | `./run.sh leaderboard` | Same setup as Mob Pit: kills/XP sorted-set boards (in-memory or Redis) fed from the projected crawler list with idempotent `max` updates, your rank + neighbours, rebuild from the cells' event history | celld (the Mob Pit cells); boards are a projection (memory or Redis) | +| **Mob Pit · SvelteKit** | `REDIS_URL=… ./run.sh sveltekit` | The same Mob Pit server behind a SvelteKit app: Auth.js session sign-in, admission tickets minted from the session (`createGameTicketHandler`), the game client and WASM step generated by the Vite plugin (`games`), a runes HUD (`useGame`) next to a plain canvas loop, the settled kills as a business-side read model (Crawler domain events projected by `mobpit-service` into SQL, read through generated `@load @live` GraphQL), and the zone server's Redis XP board through GraphQL board roots, live across processes over the bus. See [SvelteKit](#sveltekit) | celld (the Mob Pit cells) + `mobpit-service`'s SQL read model + the Redis boards | + +`./run.sh smoke` runs the smoke tests (Rust bots, headless JS, the generated +client checked current, the SvelteKit app driven headlessly); `./run.sh gen` +regenerates the client; `./run.sh list` lists the pages. + +**How the demos are written.** Each zone describes its world with the +`distributed_game` authoring derives: `#[derive(Replicated)]` view structs +for the kinds (`mobpit::zone::PlayerView`, `mobpit::zone::MobView`, …), +`#[derive(GameInput)]` for the input frame (`game_sim::mobpit::PitInput`), +`#[derive(GameEvent)]` enums for events +(`mobpit::zone::PitEvent`) and `#[derive(FactCommand)]` on the cell +command inputs they emit as facts (`mobpit::crawler::RecordKillInput`). +The movement that clients predict is declared once with `#[predict]` in +the `game_sim` crate (`server/sim/`, no server dependencies): +`pit_step`; the rooms call it in `on_tick`. The surface module +exports `game_surface()`; `run.sh gen` runs `distributed game-manifest` on +it, `distributed game-client` writes `client/src/generated//` +and `distributed game-wasm` compiles the step — and Mob Pit's +`#[game_pure]` room generation — to +`client/src/generated//wasm/.wasm`. All of it is a build output +(gitignored, never checked in), so it cannot drift from the Rust: the +client's Vite plugin (`@hops-ops/distributed/game/vite`) regenerates it on +dev start, Rust changes and build, `npm run check|build` generate before +`tsc`, and `run.sh ` generates it too (WASM rebuilt only when the +Rust sources change). The pages use +the generated `createClient`, which predicts with the compiled step, +typed field accessors (`mobFields(entity).hp`), the input encoder and typed +`on('kill', …)` handlers. + +No simulation or content code is written twice. Movement is the compiled +step; Mob Pit's rooms (biome, danger, mobs) come from the compiled +`pit_room` (`createMobpitPures`); static data the pages +draw is a generated constant from the Rust values (`PIT_WORLD` — room +size, doorways, pillars, capsule radius —, `WEATHER` names, `PIT_RULES` +tier radii, ranged reach, eye and hip heights, mob heights, +`CONTENT_PACKS`, `GATE_ROOM`). What TypeScript still mirrors is small and listed under +[Remaining client-side mirrors](#remaining-client-side-mirrors). + +Requirements: Rust (stable) with the `wasm32-unknown-unknown` target +(`rustup target add wasm32-unknown-unknown`), Node ≥ 22.18 (runs `.ts` +test imports natively). + +## Run + +```sh +examples/game/run.sh mobpit +# → open http://localhost:5173/mobpit/ (?name=Ana&zone=pit.1.0 optional) +``` + +The script builds the JS SDK if `js/dist` is stale, runs `npm ci` for the +client, builds `game-demos` and the cells worker, starts `celld dev` (the +rooms), the services on `127.0.0.1:2567` with `--dev` behind the framework +gateway (`distributed::gateway`: `/zones/{room}` → celld, the rest → the +services), then runs Vite, which proxies `/zones` and `/dev` to that gateway. +Ports: +`GAME_DEMOS_PORT`, `GAME_DEMOS_CLIENT_PORT`. Open a second browser (or +`?player=two`) to see another player interpolated. + +**The celld dev state only grows.** `celld dev` keeps every write +(`MOBPIT_DATA_DIR/celld/.celld/dev`; epoch GC, `CELLD_LTX_RETENTION_SECS`, +stalls rooms by ~20 % of their ticks while it deletes, so it stays off). +A room writes its snapshot every minute and when a player leaves, and its +crash watchdog alarm about every 3 minutes, but facts, the outbox queue +and rooms waking and sleeping around players add up: ~5k stored objects +per played room-hour. Past a few hundred cells, restarts get slow: a +crashed `celld dev` (run.sh stops it with SIGKILL) recovers every cell +before rooms answer (~2 min at ~730 cells). On a few-day state with +rebalancing on (~560 cells, 91k objects), rooms dropped 166 ticks per 30 s. +`run.sh` launches it with `CELLD_REBALANCE_INTERVAL_MS=0` (one node) and +warns at start past 500 cells or 100 MB (a 255-cell, 216 MB state, 2.5 +hours of play at 5 s snapshots, never became ready after a restart) (`CELLD_STATE_WARN_CELLS`, +`CELLD_STATE_WARN_MB`) with the reset command (deleting `.celld/dev` drops +the rooms, players and progress on celld). The debug overlay (rooms panel; +on by default, **O** toggles) shows the room's dropped ticks over the last ~30 s, red +when it degrades. `MOBPIT_SOAK=1 node --test +client/tests/mobpit-soak-headless.test.mjs` ages a state and checks rooms +still keep their pace (`MOBPIT_SOAK_FLEET=3` on a local fleet). + +Network panel (Mob Pit's HUD): **P** toggles client prediction (off = your +capsule is drawn like everyone else's, one RTT + the interpolation delay +behind your keys), **G** the wireframe ghost at the room's latest +authoritative position; the readout shows pending inputs, the last acked +input and corrections. The NetSim sliders set the simulated one-way latency +(applied in both directions), jitter and loss (a TCP-like retransmit delay) +for **every room on celld**: `/dev/netsim` writes the cells worker's dev +settings object (`zone-dev/netsim`), every room object reads it within a +second and delays its sockets' frames and inputs (`distributed_game::netsim`, +`ZONE_DEV_SETTINGS=1`). The dashed ring is your interest radius +(`hello.viewRadius`, 24 m): mobs and players outside it are not replicated. + +**Bow and first person** (Mob Pit, from the Shooting Gallery): **R** or a +click looses an arrow, **V** toggles first person (click to capture the +mouse; you face where you look and arrows leave from the eye with the +look's pitch — in third person they fly level at the hip along the +camera's heading), **C** toggles lag compensation per shot. The page +predicts the hit by ray-testing the mobs *as rendered* (a yellow marker); +the room resolves the arrow with `ctx.rewind()` at the shooter's view time +(`client_tick` minus the interpolation delay the input carries, clamped to +`MAX_REWIND_MS` = 600 ms; the mobs' hit capsules are recorded every tick) +and answers with a verdict: the marker turns green (hit) or red (miss). +Obstacles stop arrows; a jump raises the eye. The input frame carries the +aim (yaw, pitch), the shot id and the view delay (`PitInput`, 11–14 +bytes). The SvelteKit page aims with the mouse (top-down), and its "first +person" turns the canvas with the aim under pointer lock. + +**Live content updates** (Mob Pit, from The Freeze): `run.sh mobpit` +prints an admin link (`/mobpit/?admin=`, the services' admin secret +`DG_DEMO_ADMIN_SECRET`, kept in `MOBPIT_DATA_DIR/admin-secret`); add +`&old=1` in another tab for a client built before the update. The admin +panel rolls a content pack (`mobpit_rooms::content_packs`: Classic, +Frostfall — mobs 30 % slower, 20 % tougher, icy —, Emberfall — 25 % +faster, brittle, glowing) out to **every live room**: + +- `POST /dev/mobpit/rollout` (admin secret) starts the rollout on the + world's `content-rollout/world` cell + (`distributed_game::world::content_rollout`) for the services' admin + session — the body names a known pack, never a principal. +- The cell drives itself on its own schedule: `freezing` → (`freezeMs`, + default 3 s) `applied` → (3 s) `running`; each phase is an outward + event. Every room object follows it (`ZONE_CONTENT_ROLLOUT=world`: read + on wake and every second while it ticks): it freezes (the SYSTEM overlay + with the change notes; inputs are held by the SDK), switches to the pack + (`ZoneHost::set_content_version` → `on_content_version_changed`) and + resumes (`Resume` with the version). Facts from then on carry the new + version in their stamp. A room that slept through it catches up on wake + (a Hello on another version waits for the read, so a doorway admits on + the live version). +- The page patches live (`setContentVersion`, which tells the room — + protocol `Content`); an old client keeps its pack and is stale + (`StalePolicy::SafeRoom { roam: false }`): every doorway but the + entrance's stays closed to it (a `stale` notice), and the entrance + (`Zone::is_gate`) reloads it (`Kick(RELOAD)` → `reloadContent` → back + with the new version and the same body). A fresh join on old content is + told to reload. `hard` reloads stale clients at once instead. + +## Hops local (Kubernetes) + +Mob Pit also runs in the machine's Hops cluster (OrbStack k3s, context +`orbstack`; kind-hops until 2026-11-05), through the same +gateway, at a portless HTTPS address per checkout: +`https://.gitkb.localhost/mobpit/` (this checkout: +`https://distributed-mobpit-world.gitkb.localhost/mobpit/`). + +```sh +hops local env discover . # from the repo root +hops local env enable mobpit-system # once per machine: the celld fleet +hops local env enable distributed-mobpit-world +``` + +- **`mobpit-system`** (`.gitops/local/mobpit-system.yaml`, manifests in + `.gitops/mobpit-system/`): a `CelldStack` (celld-stack, RustFS) in + namespace `mobpit-celld`; its celld pods carry Istio sidecars. Shared by + every Mob Pit Environment; the last one to deploy its worker owns it. +- **The Environment** (`.gitops/local/mobpit.yaml`, chart + `.gitops/local/`): its setup (`scripts/hops/mobpit-setup.sh`) runs + `./run.sh build` on the host (JS SDK, WebAssembly, cells worker) and makes + the Environment's secrets. The pod (sidecar too) runs the services + + gateway (`cargo run` from the mounted checkout; target dir on a PVC) and + Vite (`/` through the gateway). A deployer `celld deploy`s the worker + whenever `cells/build` changes, with this Environment's secrets and relay + URL. +- Outbox relay: celld → `http://mobpit..svc.cluster.local:2567`, mTLS + between the sidecars (not ambient: kind-hops' Dory kernel has no IPv6 + policy routing, which istio-cni's ambient redirection needs). The worker opts in with `CELLD_QUEUE_RELAY_MESH=1` + (`CelldQueueHttpPublisher::new_mesh`: HTTP only to `*.svc` hosts); + without it the relay must be HTTPS. +- Traffic: browser → Dory (TLS) → Istio Gateway `platform` → HTTPRoute + `.gitkb.localhost` → gateway → `/zones/{room}` to celld, + `/dev` to the services, `/` to Vite. + +The cluster overlay (`.gitops/local/cluster/`) pins the celld-stack +package; the first boot compiles the services in the pod (minutes). + +## SvelteKit + +```sh +docker compose up -d redis # at the repo root: the leaderboard is the Redis board +REDIS_URL=redis://127.0.0.1:6379 examples/game/run.sh sveltekit +# → http://localhost:5573/ — sign in with any username +``` + +`sveltekit/` is Mob Pit as a SvelteKit app over its rooms on celld +(gameplay) and `mobpit-service` (the business-side read models). The +script starts `celld dev` with the rooms and cells (`cells/`; state in +`.data/mobpit-sveltekit/celld`; `run.sh sveltekit --fleet [N]` starts a +local multi-node fleet instead, see *Mob Pit*), then `game-demos mobpit` +(the services, no `--dev`) on `GAME_DEMOS_PORT` (default 2967 here; data in +`.data/mobpit-sveltekit`) with the rooms' ticket secret, `--redis-url +"$REDIS_URL"` (its kill boards) and `--projection-bus sqlite:…/bus.db` +(celld's outbox Queue relays the cells' domain events to it; the board +change notices go there too), then runs `distributed dev server/`: the +application lifecycle generates the `$distributed` GraphQL client, starts +`mobpit-service` on `MOBPIT_SERVICE_PORT` (default `GAME_DEMOS_PORT + 2`) +and `vite dev` on `SVELTEKIT_PORT` (default 5573). What each piece replaces: + +- **Sign-in and tickets.** `src/auth.ts` is Auth.js, the session mechanism + of the framework's SvelteKit apps (`tests/e2e-ui`): with `OIDC_ISSUER` + set it uses OIDC; locally `GAME_DEV_AUTH=1` enables a **dev-only** + username sign-in (`dev-` principal, same encrypted session + cookie, nothing external). `src/lib/server/game.ts` is the whole ticket + path: `createGameTicketHandler({ secret, getSession: (e) => + e.locals.auth(), zone })`, exported as `POST` from + `routes/api/game/ticket/+server.ts`. The principal comes from the session, + the room from the server: on a page load the room the player was last + in (its presence cell on celld, read with `CELLD_URL` / + `DISTRIBUTED_INTERNAL_SECRET`), else the entrance `pit.0.0`; or the room + a client rejoins (after a room restart closed its socket with 1012); moving + through doorways needs no ticket from here (the room signs a transfer + ticket). A body naming a principal is refused (400), something that is + not a room gets 409, another origin 403, no session 401. The page's + `load` uses `tickets.resolve(event)`. There is no `/dev/ticket` call and + no guest token. +- **Code generation.** `distributed.config.js` lists both surfaces. + `games`: the Mob Pit zone surface; the Vite plugin runs `game-manifest`, + `game-client` and `game-wasm` on start and on Rust changes (`server/src`, + `server/sim`; a failing Rust build is reported in the overlay and the dev + server keeps running), `src/lib/generated/mobpit/` (TypeScript and `wasm/`) is a build output, + gitignored like the GraphQL client; `npm run check` generates it before + `svelte-check`. `clients` (from `distributed.clients.json`): the `mobpit` + application surface of `mobpit_service`; `distributed build|dev server/` + generates it from `src/lib/pit/*.graphql` into the lifecycle's generation + store (never checked in), which is why the UI runs under the lifecycle + instead of plain `vite` (`server/Cargo.toml` points + `[workspace.metadata.distributed.ui]` at `../sveltekit`). +- **HUD.** `routes/pit/+page.svelte` calls `useGame(() => + createMobpitClient({ url, ticket: gameTicketSource() }), { zone, events: + EVENTS })` and renders `status`, `zone`, `rttMs`, `predictionReady`, + `error`, `events('kill')` and `events('saved')` as Svelte markup. + `src/lib/pit/loop.ts` is the canvas render and input loop (one input per + tick via `InputPacer`), plain TypeScript started from an `$effect`; Svelte + never sees per-frame state. **Auto-hunt** steers to the nearest mob (used + by the headless test). Kills show as "saving" until their `saved` event. +- **Settled read model (business side).** The *Settled* panel is two + generated GraphQL islands, both `@load @live`: + `src/lib/pit/MyStats.graphql` (my `player_stats` row; `$playerId` is bound + by `MyStats.graphql.bindings.js` to `sessionClaim('user', 'id')`, so the + value is the verified session's id for SSR and in the browser, never a URL + or form value) and `src/lib/pit/Leaderboard.graphql` (display names from + `player_stats`). The root layout's `createDistributedSvelteKitServer` runs + them during SSR, the page hydrates without refetching, and the + `graphql-transport-ws` subscription pushes every later settlement — to + every signed-in player. +- **Leaderboard (Redis, through GraphQL).** The ranking is the zone + server's Redis XP board, served by `mobpit-service` as GraphQL board roots + (`xpLeaderboard`, `xpLeaderboardAround`, `xpMyRank` and the `kills…` + twins; `leaderboard_surfaces()`), and generated into `$distributed` as + `XpLeaderboardLeaderboard` & co. (`leaderboards.ts`). The page `load` + (`routes/pit/+page.server.ts`) runs it once with + `loadDistributedLeaderboard` for SSR; `Leaderboard.svelte` follows it with + `useDistributedLeaderboard` (`@hops-ops/distributed/sveltekit`), which + subscribes to the `@live` document over the client's WebSocket. Pushes + cross processes on the bus: the zone server's `LeaderboardProjector` + publishes `distributed.leaderboard.changed` for each changed board + (`LeaderboardChangePublisher`), and `mobpit-service` subscribes with + `distributed_leaderboard::change_handlers` (`spawn_board_notices`). + Both processes use `REDIS_URL` and the same key prefix + (`MOBPIT_REDIS_PREFIX`, default `mobpit`). + The rows come from the cells (see *Mob Pit*, step 5). +- **Rooms.** `src/lib/pit/Rooms.graphql` (`zone_activities`, `@load + @live`) is the minimap: every room's status (active, dormant, asleep, + never ran) live as rooms wake, empty and sleep, with toasts when a room + goes to sleep or wakes from its snapshot. The debug overlay polls the + current room object's `GET /zones/{room}/info` (node, isolate, + activation). `GAME_ZONES_URL` lists celld's entry points (comma + separated for a local fleet); the page rotates over them per connection — + entry points, not placement: celld forwards each socket to the room's + node. +- **API identity.** `mobpit-service` trusts no identity header + (`IdentityConfig::OidcBearer`). Auth.js's `session` callback puts a Bearer + in `session.accessToken`: an ES256 JWT this server signs for the session's + verified `sub` (15 min, `src/lib/server/api-token.ts`; + `MOBPIT_API_SIGNING_JWK`), or, with OIDC and no signing key, the + provider's access token. `run.sh` and the smoke test generate a key pair per + run and give the service only the public JWKS (`MOBPIT_API_JWKS`). The + browser calls the service directly (`MOBPIT_PUBLIC_GRAPHQL_URL`, CORS for + `MOBPIT_UI_ORIGINS`, no cookies). + +`./run.sh smoke` generates the game client (and checks the generation is +deterministic), then `distributed build server/` (the +GraphQL client, `svelte-check`, `vite build` with the game codegen and WASM) +and `tests/pit.test.mjs`: the production build (`node build`) against the +rooms on a 3-node celld fleet (docker compose + RustFS; a single `celld +dev` when docker or the aws CLI is missing), the services and +`mobpit-service` (on the Redis in `REDIS_URL`, with a per-run key prefix) +in headless Chromium — sign-in, ticket rejection paths, an +unauthenticated GraphQL request refused, join, keyboard movement, auto-hunt +until a kill settles, the killer's stats and a second signed-in player's +leaderboard updating live without a reload, both players walking through +doorways (one into a room on another node, by the overlay), the room they +left asleep on the minimap and restored on return, another kill settled +live, the server-rendered numbers after a reload, navigation away, no page +errors. + +## Architecture + +``` + browser (Vite :5173 / SvelteKit) game-demos mobpit --dev (:2567) celld (cells worker) + ┌──────────────────────────────────┐ ┌──────────────────────────────┐ ┌────────────────────────────────┐ + │ src/mobpit/main.ts Babylon scene │ │ /dev/ticket guest tickets │ │ PitRoom one Durable Object │ + │ └ src/mobpit/client.ts │───►│ /dev/mobpit/* (rooms, tiers, │ │ per room pit..: │ + │ GameClient (SDK) │ │ boards, content, rollout) │────►│ ZoneHost 30 Hz │ + │ ├ GameConnection ws ────────┼─ /zones/{room} ─ gateway ───────────►│ └ game_sim::mobpit::pit_step │ + │ ├ EntityReplica (interp.) │ │ /internal/celld-queue/relay │◄────│ crawler · presence · activity │ + │ └ Predictor ── mobpit.wasm │ │ bus → read models, boards │ │ hood · borough · city · rollout│ + │ src/generated/mobpit (typed glue) │ └──────────────────────────────┘ │ outbox Queue → saga + relay │ + │ └ wasm/mobpit.wasm ◄════════════╪══ distributed game-wasm (same Rust, wasm32) └────────────────────────────────┘ + └──────────────────────────────────┘ +``` + +Prediction is exact because (1) every input is one command frame of exactly +one tick (sent by the SDK's `InputPacer`), consumed one per tick with a small +credit bank (`distributed_game::InputCredits`, a room's `MAX_CREDITS`), (2) the +client runs the server's own Rust step compiled to WebAssembly, over a +binary ABI that keeps every binary32 bit, and the step uses only operations +that round identically on every target (`+ - * /`, `sqrt`, comparisons; no +trig), and (3) the server snaps its state to the wire quantization after +each step, so the client rebases on exactly what the server holds. +`client/tests/prediction-wasm.test.mjs` replays the native traces of +`game-demos predict-trace` (recorded input streams per step function, and +recorded arguments per pure function) through every surface's module and +requires byte-identical states and results; it also times prediction +(≈ 1–3 µs per step, ≈ 10–30 µs for a reconciliation replaying 10 inputs) +and room generation. + +## Remaining client-side mirrors + +What the TypeScript still restates, and why it stays: + +- **Zone id formats and defaults** — `pit..` (`parseRoom` / + `roomZone` in `mobpit/client.ts`) and each page's default zone + (`pit.0.0`). They are addressing, needed synchronously before + any module loads; a mismatch fails loudly (the server rejects the zone). +- **Dev / admin HTTP JSON shapes** — `RoomStatus`, `TiersAround`, + `ContentInfo`, `BoardPosition`: debugging routes outside the game surface. +- **The predicted arrow hit** (`rayCapsule` over rendered mobs) — cosmetic + feedback; the room's rewound `HitQuery` decides. It could become a + `#[game_pure]` over the rendered mobs. +- **Presentation** — colors, tier display names, camera and HUD constants: + client-only by nature. + +## Layout + +``` +examples/game/ + run.sh one-command dev + smoke runner + scripts/round-robin.mjs dev TCP balancer in front of a local celld fleet (`run.sh mobpit --fleet`) + cells/ crate `game-demo-cells` (own workspace, wasm32, worker-build): Mob + Pit's rooms (`PitRoom`, one Durable Object per room) and the demos' + celld cells — Crawler + presence + zone activity + dev settings + (`ZoneDevObject`: the rooms' NetSim) + hood / borough / city tiers + + the world's content rollout (`ContentRolloutObject`), and the + `game-demo-outbox` Queue consumer (relay + the tier saga) + server/ Rust crate `game_demos`, its own cargo workspace (with sim/, + crawler/, rooms/, service/); also the `distributed build|dev` project + crawler/ crate `mobpit_crawler`: Crawler aggregate, RecordKill (XP rules), + `CrawlerState` domain event (shared by the zone and the service) + tiers/ crate `mobpit_tiers`: Hood / Borough / City aggregates, the boss + fact, the saga steps (tests/tiers.rs on the reference host) + rooms/ crate `mobpit_rooms` (wasm32-portable): the Mob Pit room zone + (combat, doorways, hibernation) and its `CelldZone` hooks + service/ crate `mobpit_service` (bin `mobpit-service`): player_stats and + zone_activities read models, projectors from the bus, the Redis + boards as GraphQL board roots (@live from bus notices), GraphQL + @live (Bearer only), tests/projection.rs (cells → bus → table → + live push, board push over bus notices, no mutations, 401) + sim/ crate `game_sim`: the `#[predict]` step (arena.rs planar movement, + mobpit.rs `pit_step` + `#[game_pure]` pit_room, doorways, obstacles), + grid.rs seeded noise, biomes and props); compiled natively for the + server and to wasm32 for the browser + src/main.rs `game-demos mobpit|leaderboard` (+ hidden `predict-trace`) + src/predict_trace.rs native traces of every step (recorded inputs) and pure function (arguments) + src/common/ shared: CLI options, dev ticket wire types, guests; + celld.rs (CelldOptions: celld URL + internal secret), + relay.rs (authenticated /internal/celld-queue/relay → SqliteBus), + zone_status.rs (zone lease/snapshot/activity status read model) + src/devcelld.rs `celld dev` harness for tests (own project, port, process tree) + src/mobpit/ Mob Pit services (the rooms run on celld): dev room tickets, relay, + crawler directory and room status projections, leaderboards + tests/ mobpit_smoke.rs (facts, rooms on celld, celld crash, boards, presence) + sveltekit/ SvelteKit app over the Mob Pit server + mobpit-service (see SvelteKit above) + distributed.config.js game surface (`games`) + GraphQL client (`clients`) for the Vite plugin + distributed.clients.json the `$distributed` client of `mobpit_service` (lifecycle-generated) + src/auth.ts Auth.js (OIDC, or dev username sign-in with GAME_DEV_AUTH=1) + + the session-bound API Bearer + src/lib/server/ game.ts (createGameTicketHandler), distributed.ts (SSR loader), + api-token.ts (ES256 Bearer for the session subject) + src/lib/generated/mobpit generated by the Vite plugin (build output, gitignored) + src/lib/pit/ loop.ts (canvas render + input loop, outside Svelte); + MyStats / Leaderboard .graphql islands (@load @live) + components + src/routes/+layout.* session + SSR seed, provideDistributed + src/routes/pit/ load (zone) + page (useGame HUD, settled panel) + tests/pit.test.mjs headless Playwright against `node build` + game-demos + mobpit-service + client/ Vite + TypeScript + Babylon.js 9.30 (multi-page) + index.html, mobpit/index.html, leaderboard/index.html + src/generated/mobpit/ generated by `run.sh gen` (do not edit): schema/input/events/client.ts, + predict.ts, pures.ts, constants.ts, surface.json, + wasm/mobpit.wasm (gitignored build output); also the leaderboard page's + src/shared/ hud.ts, input.ts, scene.ts, dev-api.ts, latest.ts, style.css + src/mobpit/ client.ts (headless + /dev/mobpit API), main.ts (Babylon), style.css + src/leaderboard/ main.ts (DOM page over the observer connection), style.css + tests/ prediction-wasm (native ↔ WASM exact match of steps + pure functions, cost), + mobpit-headless, mobpit-network-headless (NetSim on celld rooms, + exact prediction, interest), mobpit-restarts-headless, leaderboard-headless, + mobpit-neighbours-headless (passive watchers), mobpit-wake-headless (proximity wake: doorway rooms in reach wake and release, corners never, toggle off), mobpit-ranged-headless (lag-compensated arrows), mobpit-events-headless, mobpit-content-headless (live content rollout), + mobpit-respawn-headless (a respawn is a cut), mobpit-doorway-bow-headless + (a bow fight, then doorways into a sleeping room: exact, no jump), + mobpit-bosses-headless (hood → borough → city) (+ helpers/demo-server.mjs, + helpers/mobpit.mjs, helpers/celld.mjs for + a per-test `celld dev`) +``` + +The server crate is excluded from the root workspace (`Cargo.toml` +`exclude`), depends on `../../../distributed_game` by path and keeps its own +`Cargo.lock`; the client depends on the SDK via `file:../../../js` (the built +`dist`). + +## Mob Pit + +```sh +examples/game/run.sh mobpit # → http://localhost:5173/mobpit/ (rooms on `celld dev`) +examples/game/run.sh mobpit --fleet # same on a local 3-node celld (docker compose + RustFS) +examples/game/run.sh leaderboard # same, board page → http://localhost:5173/leaderboard/ +``` + +Mob Pit is a near-infinite grid of **rooms**: room `(x, y)` is zone +`pit..`, and **every room is a celld Durable Object** (the cells +worker declares `PitRoom` with `distributed_game::celld_zone_object!`; the +zone code is `server/rooms`, `mobpit_rooms`). celld decides where a room +runs — the node that first touched it, forwarded from any other node, +evicted when idle, moved when idle, recovered elsewhere if its node +crashes. The game never names a node; the debug overlay only *shows* the +one celld chose. + +Controls: WASD / stick move (predicted by `pit_step`, the Rust step as +WASM), **Space** attack (120° cone, 2.2 m), **R** / click / RT fire the +laser, **E** dash, **Q** jump, **V** first-person view, **O** debug +overlay, **P** prediction, **G** server ghost (see the network panel +under [Run](#run)). + +**Jumping** is part of the predicted step: Mob Pit's state is the Arena +capsule plus a height (`PitState`: `z`, `vz`; take-off 8.5 m/s, gravity +24 m/s², ≈ 1.5 m up, ≈ 0.7 s in the air), predicted in WASM and +reconciled like the rest, replicated to everyone (`z`), and carried +through a doorway mid-air (the handoff carries `z`/`vz`). A mob's slam +is a ring on the floor: a player 0.9 m up or higher clears it +(`SLAM_CLEARANCE`; ranged hits will test the height too). Like every +step, gravity runs per command frame (one input per tick). Walk through a **doorway** — the glowing gap in the +middle of each wall (go beside the pillar on its axis) — into the +neighbouring room. The rooms are **one continuous world**: room `(x, y)` +sits at world `(x, y) × 40 m` (they share walls), the rooms around yours +are drawn from their seeded layout, so you see into the next room, and +going through a doorway just carries on walking — no scene swap, no jump. Mobs wander near home, aggro within 7 m, chase, stop and +show a red **telegraph ring** that fills for 0.8 s, then hit everyone +inside it. Grunts (green, 10 XP), brutes (purple, 25 XP) and elites (red, +60 XP) respawn 4 s after dying. Level `n` starts at `40·(n−1)²` XP. + +**Ground.** Every room has rolling hills (a `Heightfield`), one to three +seeded **ramps** of 10–60° (45° or flatter you walk up; steeper ones are +walls you slide off, or bounce off if you hit them fast), jumpable +**platforms**, and some rooms have **holes**: fall in and you die. All of +it is in the predicted step (`step_among` in `game_sim::mobpit`) against +the room's colliders, so prediction matches the server bit for bit. About +a third of room sides are **open** (no wall: cross anywhere along them); +the others have a doorway in the middle. + +**The laser** (R / click / RT) fires from the eye along your view: 100 m, +up to four bounces off walls, pillars and ramps, 12 damage, lag +compensated up to 600 ms (the room rewinds the mobs to what you saw). +In third person a click fires on release and only if the mouse did not +move, so a left drag turns the camera without shooting. Walls stop it at any height (an invisible barrier on each wall line, so +it never clears a wall into the next room); through a doorway or an open +side it carries on into the next room (`PitMessage::LaserLeg`), which +resolves the rest against its own mobs and credits you for a kill. + +**Crossing rooms** (`server/rooms/src/zone/cross.rs`). A mob chasing you +when you leave follows you through the same side, and a mob you shoot +from the next room comes after you. The mob is *lent* to the room it +enters, on a lease (`distributed_game::lease`): the visitor renews it +every 2/3 s, its home takes it back 4 s after the last renewal, and the +visitor lets go at 2 s (so one lost renewal or a short restart of its +home room does not drop it), so a mob is never in two rooms and a lost message +or a crashed room only sends it home. Bosses stay home. + +**Feel.** Movement has coyote time and a jump buffer (3 ticks each), ground +grip with half the acceleration in the air, and a lift over corners you +clip. Drawing adds hit stop (50–100 ms on a hit), trauma screen shake, +eased popups and pooled beams and sparks (`client/src/shared/feel.ts`); +none of it touches the predicted step. Props and mobs have three levels +of detail with hysteresis, and entities off screen skip their per-frame +updates. `window.mobpit.feel()` reports the trauma, hit stops and pool use. + +**Coming back.** The same browser is the same player (the dev guest token +is kept in `localStorage`; `?player=(env: &Env, cell: &AggregateCell) -> Result +where + A: Aggregate + Send + Sync + 'static, +{ + let wake = cell + .alarm(env) + .await + .map_err(|error| Error::RustError(error.to_string()))?; + for error in &wake.drain.deferred { + worker::console_error!("drain deferred: {error}"); + } + Response::ok("ok") +} + +// ---------------------------------------------------------------- Rooms + +distributed_game::celld_zone_object!(PitRoom, mobpit_rooms::MobPit); + +// ---------------------------------------------------------------- Tiers + +/// Tier saga steps run only for the worker's own session. +fn saga_session(header: &dyn Fn(&str) -> Option) -> Option { + let principal = header(distributed::USER_ID_KEY)?; + (principal == SAGA_PRINCIPAL).then(|| { + let mut session = Session::new(); + session.set(distributed::USER_ID_KEY, principal); + session + }) +} + +/// A borough hears the saga (its hoods) and its rooms' own facts (a room +/// woke: the world event cycle); each command checks which it accepts. +fn borough_session(header: &dyn Fn(&str) -> Option) -> Option { + saga_session(header).or_else(|| fact_session(header)) +} + +async fn read_hood(cell: &AggregateCell) -> std::result::Result { + let hood = cell.load().await.map_err(|error| error.to_string())?; + serde_json::to_value(HoodRead::of(hood.as_ref())).map_err(|error| error.to_string()) +} + +async fn read_borough(cell: &AggregateCell) -> std::result::Result { + let borough = cell.load().await.map_err(|error| error.to_string())?; + serde_json::to_value(BoroughRead::of(borough.as_ref())).map_err(|error| error.to_string()) +} + +async fn read_city(cell: &AggregateCell) -> std::result::Result { + let city = cell.load().await.map_err(|error| error.to_string())?; + serde_json::to_value(CityRead::of(city.as_ref())).map_err(|error| error.to_string()) +} + +/// A hood: its boss rooms' facts and its own respawn schedule. +#[durable_object] +pub struct HoodCell { + cell: AggregateCell, + env: Env, + /// Rooms watching it (pushed after every change). + watchers: CellWatchers, +} + +impl DurableObject for HoodCell { + fn new(state: State, env: Env) -> Self { + console_error_panic_hook::set_once(); + let watchers = CellWatchers::new(HOOD_KIND, &state); + let cell = mount_hood( + AggregateCell::::from_state_with_snapshots(state, 50) + .expect("hood cell identity"), + ) + .with_celld_outbox(outbox(&env)); + Self { + cell, + env, + watchers, + } + } + + async fn fetch(&self, req: Request) -> Result { + self.watchers + .serve(&self.env, &self.cell, req, read_hood, fact_session) + .await + } + + async fn alarm(&self) -> Result { + self.watchers.alarm(&self.env, &self.cell, read_hood).await + } +} + +/// A borough: its hoods as the saga reports them. +#[durable_object] +pub struct BoroughCell { + cell: AggregateCell, + env: Env, + /// Rooms watching it (pushed after every change). + watchers: CellWatchers, +} + +impl DurableObject for BoroughCell { + fn new(state: State, env: Env) -> Self { + console_error_panic_hook::set_once(); + let watchers = CellWatchers::new(BOROUGH_KIND, &state); + let cell = mount_borough( + AggregateCell::::from_state_with_snapshots(state, 50) + .expect("borough cell identity"), + ) + .with_celld_outbox(outbox(&env)); + Self { + cell, + env, + watchers, + } + } + + async fn fetch(&self, req: Request) -> Result { + self.watchers + .serve(&self.env, &self.cell, req, read_borough, borough_session) + .await + } + + async fn alarm(&self) -> Result { + self.watchers + .alarm(&self.env, &self.cell, read_borough) + .await + } +} + +/// The city: its boroughs as the saga reports them. +#[durable_object] +pub struct CityCell { + cell: AggregateCell, + env: Env, + /// Rooms watching it (pushed after every change). + watchers: CellWatchers, +} + +impl DurableObject for CityCell { + fn new(state: State, env: Env) -> Self { + console_error_panic_hook::set_once(); + let watchers = CellWatchers::new(CITY_KIND, &state); + let cell = mount_city( + AggregateCell::::from_state_with_snapshots(state, 50) + .expect("city cell identity"), + ) + .with_celld_outbox(outbox(&env)); + Self { + cell, + env, + watchers, + } + } + + async fn fetch(&self, req: Request) -> Result { + self.watchers + .serve(&self.env, &self.cell, req, read_city, saga_session) + .await + } + + async fn alarm(&self) -> Result { + self.watchers.alarm(&self.env, &self.cell, read_city).await + } +} + +/// The tier saga's next step for an outbox message (hood → borough → +/// city), dispatched object to object as an idempotent command whose id +/// derives from the message id. +async fn saga(env: &Env, envelope: &CelldQueueEnvelope) -> std::result::Result<(), String> { + let message = &envelope.message; + let Some(step) = mobpit_tiers::saga_step(message.name(), message.payload()) else { + return Ok(()); + }; + let id = message.id().ok_or("tier event without an id")?; + let secret = env + .secret(CELL_INTERNAL_SECRET_ENV) + .map(|v| v.to_string()) + .or_else(|_| env.var(CELL_INTERNAL_SECRET_ENV).map(|v| v.to_string())) + .map_err(|_| "internal secret is required".to_string())?; + let headers = Headers::new(); + let set = |name: &str, value: &str| headers.set(name, value).map_err(|e| e.to_string()); + set(CELL_INTERNAL_SECRET_HEADER, &secret)?; + set(CELL_SERVICE_ID_HEADER, "mobpit-tiers")?; + set(CELL_PRINCIPAL_PARTITION_HEADER, SAGA_PRINCIPAL)?; + set(distributed::USER_ID_KEY, SAGA_PRINCIPAL)?; + set("content-type", "application/json")?; + let body = json!({ + "commandId": distributed_game::cell::command_id_for("mobpit-tiers", id), + "input": step.input, + }); + let mut init = RequestInit::new(); + init.with_method(Method::Post) + .with_headers(headers) + .with_body(Some(body.to_string().into())); + let url = format!("https://cell/{}/{}/{}", step.kind, step.shard, step.command); + let request = Request::new_with_init(&url, &init).map_err(|e| e.to_string())?; + let binding = match step.kind { + BOROUGH_KIND => "BOROUGH", + _ => "CITY", + }; + let namespace = env.durable_object(binding).map_err(|e| e.to_string())?; + let stub = namespace + .id_from_name(&step.shard) + .and_then(|id| id.get_stub()) + .map_err(|e| e.to_string())?; + let mut response = stub + .fetch_with_request(request) + .await + .map_err(|e| e.to_string())?; + let status = response.status_code(); + if (200..300).contains(&status) { + Ok(()) + } else { + let body = response.text().await.unwrap_or_default(); + // A refused step (bad input) never succeeds on retry: drop it. + if status == 400 || status == 403 || status == 422 { + worker::console_error!("tier saga step {} refused: {status} {body}", step.command); + Ok(()) + } else { + Err(format!("{} → HTTP {status}: {body}", step.command)) + } + } +} + +// ---------------------------------------------------------------- Content + +/// Principal prefix of the services' admin sessions. +pub const ADMIN_PREFIX: &str = "admin:"; + +/// A rollout starts only for an admin session the services built after +/// checking the admin's credential (an `admin:*` principal over the +/// internal path); it gets the content-admin role here. The rollout's own +/// schedule needs no session. +fn admin_session(header: &dyn Fn(&str) -> Option) -> Option { + let principal = header(distributed::USER_ID_KEY)?; + principal.starts_with(ADMIN_PREFIX).then(|| { + let mut session = Session::new(); + session.set(distributed::USER_ID_KEY, principal); + session.set(distributed::ROLE_KEY, CONTENT_ADMIN_ROLE); + session + }) +} + +/// The world's live content (`content-rollout/world`): every room follows +/// it (`ZONE_CONTENT_ROLLOUT`). +#[durable_object] +pub struct ContentRolloutObject { + cell: ContentRolloutCell, +} + +impl DurableObject for ContentRolloutObject { + fn new(state: State, env: Env) -> Self { + console_error_panic_hook::set_once(); + let outbox = outbox(&env); + Self { + cell: ContentRolloutCell::new(state, env, outbox, admin_session), + } + } + + async fn fetch(&self, req: Request) -> Result { + self.cell.fetch(req).await + } + + async fn alarm(&self) -> Result { + self.cell.alarm().await + } +} + +/// The rooms' dev settings (`zone-dev/{shard}`: the network simulation the +/// rooms apply, written by the services' `/dev/netsim`). +#[durable_object] +pub struct ZoneDevObject { + dev: ZoneDevSettings, +} + +impl DurableObject for ZoneDevObject { + fn new(state: State, env: Env) -> Self { + console_error_panic_hook::set_once(); + Self { + dev: ZoneDevSettings::new(state, env), + } + } + + async fn fetch(&self, req: Request) -> Result { + self.dev.fetch(req).await + } +} + +#[durable_object] +pub struct ZoneActivityObject { + cell: ZoneActivityCell, +} + +impl DurableObject for ZoneActivityObject { + fn new(state: State, env: Env) -> Self { + console_error_panic_hook::set_once(); + let outbox = outbox(&env); + Self { + cell: ZoneActivityCell::new(state, env, outbox), + } + } + + async fn fetch(&self, req: Request) -> Result { + self.cell.fetch(req).await + } + + async fn alarm(&self) -> Result { + self.cell.alarm().await + } +} + +#[event(fetch)] +async fn main(req: Request, env: Env, _ctx: Context) -> Result { + console_error_panic_hook::set_once(); + let url = req.url()?; + let path = url.path().to_string(); + if path == "/" || path == "/health" { + return Response::ok("mobpit cells\n"); + } + // A room is public: its WebSocket admits signed tickets only. + if path.starts_with("/zones/") { + return match forward_to_zone(req, &env, "PIT_ROOM", "/zones/").await? { + Some(response) => Ok(response), + None => json_status(json!({ "error": "no such room" }), 404), + }; + } + if let Err(error) = authenticate(&req, &env) { + return error_response(error); + } + let parts: Vec<&str> = path.split('/').filter(|part| !part.is_empty()).collect(); + let binding = match parts.first().copied() { + Some(CRAWLER_KIND) => "CRAWLER", + Some(PRESENCE_KIND) => "PRESENCE", + Some(ZONE_ACTIVITY_KIND) => "ZONE_ACTIVITY", + Some(distributed_game::netsim::ZONE_DEV_KIND) => "ZONE_DEV", + Some(HOOD_KIND) => "HOOD", + Some(BOROUGH_KIND) => "BOROUGH", + Some(CITY_KIND) => "CITY", + Some(CONTENT_ROLLOUT_KIND) => "CONTENT_ROLLOUT", + _ => return json_status(json!({ "error": "unknown cell kind" }), 404), + }; + let Some(shard) = parts.get(1) else { + return json_status(json!({ "error": "missing shard" }), 400); + }; + let shard = percent_decode(shard).ok_or_else(|| Error::RustError("bad shard".into()))?; + let stub = env + .durable_object(binding)? + .id_from_name(&shard)? + .get_stub()?; + stub.fetch_with_request(req).await +} + +/// Outbox Queue consumer: relay each canonical message to the zone server. +#[event(queue)] +pub async fn queue(batch: MessageBatch, env: Env, _ctx: Context) -> Result<()> { + console_error_panic_hook::set_once(); + let relay = match relay(&env) { + Ok(relay) => relay, + Err(error) => { + // Keep the messages: they are retried until a relay is configured. + worker::console_error!("mobpit outbox relay unavailable: {error}"); + batch.retry_all(); + return Ok(()); + } + }; + for delivery in batch.messages()? { + // The tier saga first: a failed step retries the whole delivery + // (each step is idempotent). + if let Err(error) = saga(&env, delivery.body()).await { + worker::console_error!("tier saga for {} deferred: {error}", delivery.id()); + delivery.retry(); + continue; + } + match relay.relay(delivery.body().clone()).await { + Ok(()) => delivery.ack(), + Err(error) => { + worker::console_error!( + "mobpit outbox relay failed for {}: {}", + delivery.id(), + error + ); + delivery.retry(); + } + } + } + Ok(()) +} + +fn relay(env: &Env) -> std::result::Result, String> { + let var = |name: &str| { + env.var(name) + .map(|value| value.to_string()) + .or_else(|_| env.secret(name).map(|value| value.to_string())) + .map_err(|_| format!("{name} is required")) + }; + let endpoint = var("CELLD_QUEUE_RELAY_URL")?; + let secret = var(CELL_INTERNAL_SECRET_ENV)?; + // `http://127.0.0.1` relays are dev-only. `CELLD_QUEUE_RELAY_MESH=1` + // (Hops local: celld and Mob Pit with Istio sidecars) allows HTTP to a + // cluster Service. Anything else must be HTTPS. + let local = + endpoint.starts_with("http://127.0.0.1") || endpoint.starts_with("http://localhost"); + let mesh = env + .var("CELLD_QUEUE_RELAY_MESH") + .is_ok_and(|value| value.to_string() == "1"); + let publisher = if local { + CelldQueueHttpPublisher::new_local_test(endpoint, &secret) + } else if mesh { + CelldQueueHttpPublisher::new_mesh(endpoint) + } else { + CelldQueueHttpPublisher::new(endpoint) + } + .map_err(|error| error.to_string())? + .with_header(CELL_INTERNAL_SECRET_HEADER, secret); + Ok(CelldQueueRelay::new(publisher)) +} + +fn percent_decode(segment: &str) -> Option { + let bytes = segment.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'%' { + out.push(u8::from_str_radix(segment.get(i + 1..i + 3)?, 16).ok()?); + i += 3; + } else { + out.push(bytes[i]); + i += 1; + } + } + String::from_utf8(out).ok() +} + +fn authenticate(req: &Request, env: &Env) -> std::result::Result<(), CausalDispatchError> { + let configured = env + .secret(CELL_INTERNAL_SECRET_ENV) + .map(|value| value.to_string()) + .or_else(|_| { + env.var(CELL_INTERNAL_SECRET_ENV) + .map(|value| value.to_string()) + }) + .map_err(|_| CausalDispatchError::Internal("internal secret is required".into()))?; + let secret = InternalHttpSecret::new(configured).map_err(CausalDispatchError::Internal)?; + let candidate = req + .headers() + .get(CELL_INTERNAL_SECRET_HEADER) + .ok() + .flatten() + .ok_or(CausalDispatchError::Unauthorized)?; + if secret.matches(&candidate) { + Ok(()) + } else { + Err(CausalDispatchError::Unauthorized) + } +} + +fn error_response(error: CausalDispatchError) -> Result { + json_status( + json!({ "error": error.client_message(), "code": error.code() }), + error.status_code(), + ) +} + +fn json_status(body: Value, status: u16) -> Result { + Ok(Response::from_json(&body)?.with_status(status)) +} diff --git a/examples/game/cells/wrangler.jsonc b/examples/game/cells/wrangler.jsonc new file mode 100644 index 000000000..1b6020ef9 --- /dev/null +++ b/examples/game/cells/wrangler.jsonc @@ -0,0 +1,66 @@ +// The game demos' cells and Mob Pit's rooms for `celld dev` (and `celld +// deploy`). The launcher (`examples/game/run.sh`, the test harnesses) writes +// `.dev.vars` beside a copy of this file with DISTRIBUTED_INTERNAL_SECRET, +// GAME_TICKET_SECRET (shared with whoever mints room tickets) and +// CELLD_QUEUE_RELAY_URL (the services' `/internal/celld-queue/relay`). +{ + "name": "game-demo-cells", + "main": "build/worker/shim.mjs", + "compatibility_date": "2026-01-01", + "durable_objects": { + "bindings": [ + { "name": "CRAWLER", "class_name": "CrawlerCell" }, + { "name": "PRESENCE", "class_name": "PresenceCell" }, + { "name": "PIT_ROOM", "class_name": "PitRoom" }, + { "name": "ZONE_ACTIVITY", "class_name": "ZoneActivityObject" }, + { "name": "ZONE_DEV", "class_name": "ZoneDevObject" }, + { "name": "HOOD", "class_name": "HoodCell" }, + { "name": "BOROUGH", "class_name": "BoroughCell" }, + { "name": "CITY", "class_name": "CityCell" }, + { "name": "CONTENT_ROLLOUT", "class_name": "ContentRolloutObject" } + ] + }, + // v2's ZoneLeaseCell / ZoneStateCell and v3's GemPouchCell / + // ContentLogCell (the deleted multi-host demos and The Freeze) are no + // longer exported; celld has no `deleted_classes` migration key. + "migrations": [ + { "tag": "v1", "new_sqlite_classes": ["CrawlerCell", "PresenceCell"] }, + { "tag": "v2", "new_sqlite_classes": ["ZoneLeaseCell", "ZoneStateCell"] }, + { "tag": "v3", "new_sqlite_classes": ["GemPouchCell", "ContentLogCell"] }, + { "tag": "v4", "new_sqlite_classes": ["PitRoom", "ZoneActivityObject"] }, + { "tag": "v5", "new_sqlite_classes": ["ZoneDevObject"] }, + { "tag": "v6", "new_sqlite_classes": ["HoodCell", "BoroughCell", "CityCell"] }, + { "tag": "v7", "new_sqlite_classes": ["ContentRolloutObject"] } + ], + "queues": { + "producers": [ + { "binding": "OUTBOX", "queue": "game-demo-outbox" } + ], + "consumers": [ + { + "queue": "game-demo-outbox", + "max_batch_size": 10, + "max_batch_timeout": 1, + "max_retries": 100, + "dead_letter_queue": "game-demo-outbox-dlq", + "retry_delay": 2 + } + ] + }, + "vars": { + "OUTBOX_DRAIN_INTERVAL_MS": "5000", + // Mob Pit rooms (distributed_game::celld_zone). GAME_TICKET_SECRET comes + // from .dev.vars (the launcher shares it with the ticket issuer). + "ZONE_TICK_HZ": "30", + "ZONE_PATCH_HZ": "20", + "ZONE_PERSIST_MS": "60000", + "ZONE_DORMANT_AFTER_MS": "10000", + "ZONE_HIBERNATE_AFTER_MS": "10000", + "ZONE_FACT_SERVICE": "mobpit-rooms", + // Dev demo: rooms apply the network simulation of the HUD sliders + // (`zone-dev/netsim`, written by the services' `/dev/netsim`). + "ZONE_DEV_SETTINGS": "1", + // Live content updates: rooms follow `content-rollout/world`. + "ZONE_CONTENT_ROLLOUT": "world" + } +} diff --git a/examples/game/client/.gitignore b/examples/game/client/.gitignore new file mode 100644 index 000000000..72ac10a9e --- /dev/null +++ b/examples/game/client/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +dist/ +# Generated game clients + WASM (`distributed game-client`/`game-wasm`), built +# from the Rust surfaces by the Vite plugin, scripts/games.mjs and run.sh gen. +src/generated/ diff --git a/examples/game/client/distributed.config.js b/examples/game/client/distributed.config.js new file mode 100644 index 000000000..83ef4cb9d --- /dev/null +++ b/examples/game/client/distributed.config.js @@ -0,0 +1,30 @@ +// @ts-nocheck — config script read by Node (Vite plugin, scripts, run.sh). +// +// `games`: the Mob Pit zone surface. Its typed client and WebAssembly are +// build outputs generated from the Rust definition by the Vite plugin (dev +// start, Rust changes, build) and by `scripts/games.mjs` before `tsc`; +// `src/generated/` is gitignored so it can never drift from the Rust surface. +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const app = dirname(fileURLToPath(import.meta.url)); +const repo = resolve(app, '../../..'); +const server = resolve(app, '../server'); + +/** @type {import('@hops-ops/distributed/game/vite').DistributedGamesViteOptions} */ +export const distributedGamesOptions = { + cwd: app, + // The CLI from this checkout (an installed `distributed` works the same). + command: 'cargo', + commandArgs: ['run', '--quiet', '--manifest-path', resolve(repo, 'Cargo.toml'), '-p', 'distributed_cli', '--bin', 'distributed', '--'], + games: [ + { + manifest: { + args: ['game-manifest', '--manifest-path', resolve(server, 'Cargo.toml'), '--entrypoint', 'game_demos::mobpit::game_surface'] + }, + out: 'src/generated/mobpit', + // The predicted step (`pit_step`) lives in the sim crate. + watch: [resolve(server, 'sim')] + } + ] +}; diff --git a/examples/game/client/index.html b/examples/game/client/index.html new file mode 100644 index 000000000..71357ad1c --- /dev/null +++ b/examples/game/client/index.html @@ -0,0 +1,19 @@ + + + + + + Game Demos + + + +

+

distributed_game demos

+

One game, Mob Pit, on celld: examples/game/run.sh mobpit (the leaderboard page runs with it).

+
    +
  • Mob Pit — a world of rooms on celld: authoritative melee and ranged combat with prediction and lag compensation, rooms you see into, hoods › boroughs › city with bosses, weather and world events, live content updates, durable facts into per-player cells.
  • +
  • Leaderboard — kills/XP sorted-set boards projected from the cells, pushed live, rebuilt from events (runs with Mob Pit).
  • +
+
+ + diff --git a/examples/game/client/leaderboard/index.html b/examples/game/client/leaderboard/index.html new file mode 100644 index 000000000..a2b5d6693 --- /dev/null +++ b/examples/game/client/leaderboard/index.html @@ -0,0 +1,40 @@ + + + + + + Leaderboard Demo + + + + +
+
+

Mob Pit leaderboard

+

+ Kills settle in the Crawler cells next to the rooms on celld; their events are projected into the crawler list + and from there into two sorted-set boards (idempotent `max` updates). The top 10 refreshes live; your rank is + read on each change. + Play the pit ↗ +

+
+
connecting…
+
+

Kills

+

XP

+
+

You

+
—
+

Entrance room (observer)

+ +
+
+
+ + Throws the boards away and replays every Crawler cell's durable event history into staging boards, then promotes them atomically. +

+			
+
+ + + diff --git a/examples/game/client/mobpit/index.html b/examples/game/client/mobpit/index.html new file mode 100644 index 000000000..f7f53dac3 --- /dev/null +++ b/examples/game/client/mobpit/index.html @@ -0,0 +1,14 @@ + + + + + + Mob Pit Demo + + + + +
+ + + diff --git a/examples/game/client/package-lock.json b/examples/game/client/package-lock.json new file mode 100644 index 000000000..1d1850627 --- /dev/null +++ b/examples/game/client/package-lock.json @@ -0,0 +1,1233 @@ +{ + "name": "game-demos-client", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "game-demos-client", + "version": "0.0.0", + "dependencies": { + "@babylonjs/core": "9.30.0", + "@hops-ops/distributed": "file:../../../js" + }, + "devDependencies": { + "typescript": "5.9.3", + "vite": "6.4.3" + }, + "engines": { + "node": ">=22.18.0" + } + }, + "../../../js": { + "name": "@hops-ops/distributed", + "version": "0.1.0", + "license": "UNLICENSED", + "dependencies": { + "@graphql-typed-document-node/core": "^3.2.0", + "graphql": "^16.14.0", + "wasm-pack": "0.15.0" + }, + "devDependencies": { + "@apollo/client": "^4.2.7", + "@types/node": "^20.0.0", + "@types/react": "19.2.18", + "esbuild": "^0.28.0", + "publint": "^0.3.22", + "react": "19.2.8", + "react-dom": "19.2.8", + "react-test-renderer": "19.2.8", + "svelte": "5.56.9", + "typescript": "5.9.3" + }, + "engines": { + "node": ">=20.3.0" + }, + "peerDependencies": { + "react": "^18.2.0 || ^19.0.0", + "svelte": "^5.0.0" + }, + "peerDependenciesMeta": { + "react": { + "optional": true + }, + "svelte": { + "optional": true + } + } + }, + "node_modules/@babylonjs/core": { + "version": "9.30.0", + "resolved": "https://registry.npmjs.org/@babylonjs/core/-/core-9.30.0.tgz", + "integrity": "sha512-rV+kc7B9oEtREaWh0YYNinoqYshRbHLHj7t4s4woDjDXFXWKHu1d8S914CNfs3KTOI8V8DvoVKLe2yDHZXfZEA==", + "license": "Apache-2.0" + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@hops-ops/distributed": { + "resolved": "../../../js", + "link": true + }, + "node_modules/@napi-rs/lzma-linux-x64-gnu": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", + "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^22.20 || ^24.12 || >=25" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.64.10.tgz", + "integrity": "sha512-oJ9ZfVIZjSjts0ZIYA48+5T0vurE5fQfX/Liad2U52Y6EN99x/OCdjGGuKMDP6jSk2i2lY6jwwA3X0drEc4PBg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.64.10.tgz", + "integrity": "sha512-LylBINgYYwgHNz8OMCy5+Y0w/LEgRYE0PcAIZfEuTuLNMf0S40GSLX6SFwqZsBLplS7RIHHy4zOAbl8Y5cQEvg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.64.10.tgz", + "integrity": "sha512-vbuT3VT1GBI2fAOoUJUrsHVoOg9nbrFXTM7e3DSnb9PYf4n6jZCN8v4Vo8O6x4u5B67+/c803b8BtCZe2nIeqA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.64.10.tgz", + "integrity": "sha512-qYUp/qYvM3T4cF+VWalPl+przBUESILxi+qZ1m1MVRHpg06vS+jHaxXubjCaRpXjLJPDFdXzOZ0FABDghHOhNQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.64.10.tgz", + "integrity": "sha512-v9NRQG+JztbP4DP/0yuhSyDcEJk047lYbqeNnqIgbXITcVDjGDS7OpkW5nadSY3tJ7MY8W1qIMMqP4Q3Q8BDjQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.64.10.tgz", + "integrity": "sha512-CHc9LBHdxhn6/NXfb9IegXCWoz5VlvcDOx9QrzZ9q+XYhFlfzwymSWJjOlZcEMMtC1zgMV7qxDe6U18AI1SG0A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.64.10.tgz", + "integrity": "sha512-ble2WR7kWfzZFJUd3ODMGCJn1XDszptfRC0QvWc0h9/EA6MxnrQ1mvbjPZifEdgHyfHhDrwWeKeJONDITcrHSg==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.64.10.tgz", + "integrity": "sha512-DMCYegihxBMKvLpODdk4OsvIgxtHTi+Oddf1Pm3d6wMVNjcBiG2pqyXjMPy55HgG1gCdEFr9VfhB1CmvuKn1lw==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.64.10.tgz", + "integrity": "sha512-HQ6HuVH9TmhvPWIas7MA/KeAROgdwqH3REpUU6hZq47NW7m1b1QCrHgM+M3+N/B8DfMt88x1/z79ppRc9RflCQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.64.10.tgz", + "integrity": "sha512-avBhxba1DdctX0kxKkN3JWdTSg72QsxSn6FdfhZ9MkL3TTYDOXqxY1GqbC7VNttlgviK7tCe2No5btfRkFgeIg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.64.10.tgz", + "integrity": "sha512-UtQMex7fiXq0W/GqcWRpy6XKqUbXgQeGKB+Bd5rJngmHzpI+3kjwpWFLAhKg02onFsIMSh+Zx0zp9JIMQ7/05A==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.64.10.tgz", + "integrity": "sha512-0Aum2pUsCSuOopi6oka+nR1DTj/nfvc1xjL979lvh6kXUjNa30TCX7sKFjyMsrX7bK3bNVs0FsJwQcE2HCWX1Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.64.10.tgz", + "integrity": "sha512-4dgsouKal3qfMFORgtNigLPt7K3HXiO6jTr7+nFJv1GWu1OkZx0kvQIXbK4sjrIGnaLBk0s80eQCQ9hPIelLrw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.64.10.tgz", + "integrity": "sha512-d7NE89try3jisYzBD7J9M5iwfgcrXYC4dwHEjQ3HIWBftvwch1U/cy3iZ26SthtUOyClKiu7iqYiFjQEwiOlqQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.64.10.tgz", + "integrity": "sha512-dqB5ChSBp91JWXxpCKAS5ZVAE38esKQvdfyqANm0lF5JPiQrXnYwgG3oVBQmuNRcQ1WHkA3j5qYLsrl2CtfhCA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.64.10.tgz", + "integrity": "sha512-7GMf3vbQQslorWLmfsbi5fdt9RVnglk205XpOMFvW6UY5jE5oJc6JLieQJPHtsYlZ2EO0PtC06nY9Hz/IG8guw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.64.10.tgz", + "integrity": "sha512-tuKbkB23DKc5LG+irPSUnZZztRHqC3CNmyxeWloueBteHB+i+1HkRCMzAE41lseLDlarybeLhqfibFitKOxKMg==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.64.10.tgz", + "integrity": "sha512-ntHtQOMw7oIshHRF1swV3vyBw+beQt9PeZ04O3D32EeDZUMoHMJuZKp4/fDllH/+xogeK0GUCONVfjjKusqKLg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.64.10.tgz", + "integrity": "sha512-Dlh8q8r145aYgh+N3gNIG1dz35Fz/FCxe5hs/43orDsffjP8S1P4Xz5I4FpSJsDS4LpQw1QmswZkQlUbkCldjQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.64.10.tgz", + "integrity": "sha512-VBJhHWz/55u45CWFv9OmfSRDgJDVENESgFxSAn13gIKJpTuFJbP4/7ymMZhDfeKFx1zGn1XBsLnNB7Ryy71qww==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.64.10.tgz", + "integrity": "sha512-Vjcazg+EEzUfIz+LcaxS6YtbQHo+sv0sCD+5VbwhY504bCKNW4OOreVgKq61pHT2esRQ/+AXYVPStDwxSvAOdw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.64.10.tgz", + "integrity": "sha512-jJAaP4El+HWxYkM0jeJghASaFgfnluY0FRHhyHXxU6STs/nBhKMIxIMDrJEFg2ftKz6orX9WAo4diVan5NugNA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.64.10.tgz", + "integrity": "sha512-bXXdRUfRx9PaHCToKt8R/7wjDV6Tbk/hmSHK0uQBKmD3rj4jkuYndct8uGX77ZuZsePrVkQbWUgPR2jJhCTMpQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.64.10.tgz", + "integrity": "sha512-57Idx+VkEOQeG6Ys6sZOBFT7FfbeyxGv9A3k1m+Lf/z2SwqT40rNWbAINzjPHSMoCCBvY7Fnb9RGZWQin/HHAw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.64.10.tgz", + "integrity": "sha512-vrvuasIpm/xf+BpZbzgirku0WnrQZMAc+H2Ai26jzqBxYEmQQE4DdJb7h8erkJMfRRipx0ma2Cty8jJwUm9ocQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.31", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.31.tgz", + "integrity": "sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/rollup": { + "version": "4.64.10", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.64.10.tgz", + "integrity": "sha512-8N52YH1B5JzBP+B1rkcBERG7rfRTGAM0RmUpyd76yyRfTljuG452GCNbVm6MPzs1+gXBha6Rw5/oHRFohOpfDg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@napi-rs/lzma-linux-x64-gnu": "1.5.1", + "@rollup/rollup-android-arm-eabi": "4.64.10", + "@rollup/rollup-android-arm64": "4.64.10", + "@rollup/rollup-darwin-arm64": "4.64.10", + "@rollup/rollup-darwin-x64": "4.64.10", + "@rollup/rollup-freebsd-arm64": "4.64.10", + "@rollup/rollup-freebsd-x64": "4.64.10", + "@rollup/rollup-linux-arm-gnueabihf": "4.64.10", + "@rollup/rollup-linux-arm-musleabihf": "4.64.10", + "@rollup/rollup-linux-arm64-gnu": "4.64.10", + "@rollup/rollup-linux-arm64-musl": "4.64.10", + "@rollup/rollup-linux-loong64-gnu": "4.64.10", + "@rollup/rollup-linux-loong64-musl": "4.64.10", + "@rollup/rollup-linux-ppc64-gnu": "4.64.10", + "@rollup/rollup-linux-ppc64-musl": "4.64.10", + "@rollup/rollup-linux-riscv64-gnu": "4.64.10", + "@rollup/rollup-linux-riscv64-musl": "4.64.10", + "@rollup/rollup-linux-s390x-gnu": "4.64.10", + "@rollup/rollup-linux-x64-gnu": "4.64.10", + "@rollup/rollup-linux-x64-musl": "4.64.10", + "@rollup/rollup-openbsd-x64": "4.64.10", + "@rollup/rollup-openharmony-arm64": "4.64.10", + "@rollup/rollup-win32-arm64-msvc": "4.64.10", + "@rollup/rollup-win32-ia32-msvc": "4.64.10", + "@rollup/rollup-win32-x64-gnu": "4.64.10", + "@rollup/rollup-win32-x64-msvc": "4.64.10", + "fsevents": "~2.3.2" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/vite": { + "version": "6.4.3", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz", + "integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + } + } +} diff --git a/examples/game/client/package.json b/examples/game/client/package.json new file mode 100644 index 000000000..2a50485fd --- /dev/null +++ b/examples/game/client/package.json @@ -0,0 +1,25 @@ +{ + "name": "game-demos-client", + "private": true, + "version": "0.0.0", + "description": "Babylon.js clients for the distributed_game demos (dev only)", + "type": "module", + "scripts": { + "dev": "vite", + "games": "node scripts/games.mjs", + "build": "node scripts/games.mjs && tsc --noEmit && vite build", + "check": "node scripts/games.mjs && tsc --noEmit", + "test": "node --test --test-concurrency=4 tests/*.test.mjs" + }, + "dependencies": { + "@babylonjs/core": "9.30.0", + "@hops-ops/distributed": "file:../../../js" + }, + "devDependencies": { + "typescript": "5.9.3", + "vite": "6.4.3" + }, + "engines": { + "node": ">=22.18.0" + } +} diff --git a/examples/game/client/scripts/games.mjs b/examples/game/client/scripts/games.mjs new file mode 100644 index 000000000..49c4622b4 --- /dev/null +++ b/examples/game/client/scripts/games.mjs @@ -0,0 +1,11 @@ +// Generate the game clients (+ WASM) from the Rust surfaces; `--check` then +// verifies generation is deterministic (a fresh run matches what was just +// written). Generated clients are never committed. +import { checkDistributedGames, generateDistributedGames } from '@hops-ops/distributed/game/vite'; +import { distributedGamesOptions } from '../distributed.config.js'; + +await generateDistributedGames(distributedGamesOptions); +if (process.argv.includes('--check')) { + await checkDistributedGames(distributedGamesOptions); + console.log('game client generation is deterministic'); +} diff --git a/examples/game/client/src/leaderboard/main.ts b/examples/game/client/src/leaderboard/main.ts new file mode 100644 index 000000000..1087f5443 --- /dev/null +++ b/examples/game/client/src/leaderboard/main.ts @@ -0,0 +1,179 @@ +/** + * Leaderboard page: renders the services' top-10 snapshots (a projection of + * the Crawler cells, polled), reads your rank and neighbours on every + * change, triggers a rebuild from the cells' event history, and observes + * the entrance room (no avatar) for a live mini map. + */ +import { + createMobpitClient, + isMob, + isPillar, + isPlayer, + mobFields, + pillarFields, + playerFields, + PIT_WORLD +} from '../generated/mobpit/index.ts'; +import { + createBoardWatcher, + DEFAULT_ZONE, + MobPitApi, + roomUrl, + TIERS, + type BoardPosition, + type BoardRow, + type BoardSnapshot +} from '../mobpit/client.ts'; +import { DevApi } from '../shared/dev-api.ts'; + +/** A room's floor, generated from the simulation's constants (`game_sim::mobpit::pit_world`). */ +const { half: HALF } = PIT_WORLD; + +const params = new URLSearchParams(location.search); +const zone = params.get('zone') ?? DEFAULT_ZONE; +const api = new DevApi(); +const pitApi = new MobPitApi(); +const watcher = createBoardWatcher(pitApi); +const { client } = createMobpitClient({ + url: (room) => roomUrl(room), + ticket: api.ticketSource(), + pingIntervalMs: 1000, + prediction: false +}); + +const $ = (k: string) => document.querySelector(`[data-k="${k}"]`) as HTMLElement; +const status = $('status'); +let pushes = 0; + +function table(el: HTMLElement, rows: readonly BoardRow[], unit: string, me: string | undefined): void { + if (rows.length === 0) { + el.innerHTML = 'No kills yet — go to the pit.'; + return; + } + el.replaceChildren( + ...rows.map((row) => { + const tr = document.createElement('tr'); + if (row.member === me) tr.className = 'me'; + for (const [text, cls] of [ + [`#${row.rank}`, 'num'], + [row.name, ''], + [`${row.score} ${unit}`, 'num'] + ] as const) { + const td = document.createElement('td'); + td.textContent = text; + if (cls !== '') td.className = cls; + tr.append(td); + } + return tr; + }) + ); +} + +function position(label: string, unit: string, p: BoardPosition | undefined, me: string): string { + if (p === undefined || p.rank === null) return `
${label}: not ranked yet
`; + const around = p.around + .map((r) => `${r.member === me ? '' : ''}#${r.rank} ${escape(r.name)} ${r.score}${r.member === me ? '' : ''}`) + .join('
'); + return `
${label}: #${p.rank} (${p.score} ${unit})
${around}
`; +} + +function escape(text: string): string { + return text.replace(/[&<>"]/g, (c) => `&#${c.charCodeAt(0)};`); +} + +async function render(board: BoardSnapshot): Promise { + pushes += 1; + const me = api.last?.principal; + table($('kills'), board.kills, 'kills', me); + table($('xp'), board.xp, 'XP', me); + status.textContent = `update #${pushes} · version ${board.version} · store ${board.backend} · ${board.members} ranked`; + status.classList.add('flash'); + setTimeout(() => status.classList.remove('flash'), 120); + if (me === undefined) return; + try { + const { me: mine } = await pitApi.leaderboard(me); + $('me').innerHTML = + `
${escape(api.last?.name ?? me)}
` + + position('Kills', 'kills', mine?.kills, me) + + position('XP', 'XP', mine?.xp, me); + } catch (error) { + $('me').textContent = `rank lookup failed: ${String(error)}`; + } +} + +watcher.on((board) => void render(board)); + +$('rebuild').addEventListener('click', async () => { + const button = $('rebuild') as HTMLButtonElement; + button.disabled = true; + $('report').textContent = 'rebuilding…'; + try { + const r = await pitApi.rebuild(); + $('report').textContent = + `${r.events} kill events from ${r.crawlers} cells → ${r.applied} board changes in ${r.tookMs.toFixed(1)} ms (${r.backend})\n` + + `top 10 identical to before: ${r.identicalTop ? 'yes ✓' : 'no (live board had drifted — now healed)'}\n` + + `every cell's kills/XP equal its board scores: ${r.matchesCells ? 'yes ✓' : `NO: ${JSON.stringify(r.mismatches)}`}`; + } catch (error) { + $('report').textContent = `rebuild failed: ${String(error)}`; + } finally { + button.disabled = false; + } +}); + +// ---- live minimap of the observed zone ---- +const map = $('map') as HTMLCanvasElement; +function drawMap(): void { + const ctx = map.getContext('2d'); + if (ctx !== null) { + const s = map.width / (HALF * 2); + const px = (v: number) => (v + HALF) * s; + ctx.clearRect(0, 0, map.width, map.height); + for (const e of client.render()) { + if (isPillar(e)) { + const { x, y, r } = pillarFields(e); + ctx.fillStyle = '#5d5566'; + ctx.beginPath(); + ctx.arc(px(x), map.height - px(y), r * s, 0, Math.PI * 2); + ctx.fill(); + } else if (isMob(e)) { + const { x, y, tier } = mobFields(e); + ctx.fillStyle = TIERS[tier]?.color ?? '#9ad16b'; + ctx.fillRect(px(x) - 3, map.height - px(y) - 3, 6, 6); + } else if (isPlayer(e)) { + const { x, y, dead } = playerFields(e); + ctx.fillStyle = dead ? '#555' : '#f2a65a'; + ctx.beginPath(); + ctx.arc(px(x), map.height - px(y), 4, 0, Math.PI * 2); + ctx.fill(); + } + } + } + requestAnimationFrame(drawMap); +} +requestAnimationFrame(drawMap); + +declare global { + interface Window { + leaderboard?: unknown; + } +} +window.leaderboard = { client, api, pitApi, watcher }; + +// A passive watcher: it never wakes the entrance; while it sleeps, retry. +const watchEntrance = () => { + client.unobserve(zone); + client.observe(zone).then( + () => { + if (status.textContent?.startsWith('the entrance')) status.textContent = ''; + }, + () => { + status.textContent = 'the entrance is asleep (nobody playing) — watching for it…'; + client.unobserve(zone); + setTimeout(watchEntrance, 3000); + } + ); +}; +client.on('zoneClosed', (closed) => { + if (closed === zone) setTimeout(watchEntrance, 3000); +}); +watchEntrance(); diff --git a/examples/game/client/src/leaderboard/style.css b/examples/game/client/src/leaderboard/style.css new file mode 100644 index 000000000..5aec51a9c --- /dev/null +++ b/examples/game/client/src/leaderboard/style.css @@ -0,0 +1,92 @@ +/* Leaderboard page (DOM only). */ +.lb { + max-width: 1100px; + margin: 0 auto; + padding: 16px; + box-sizing: border-box; +} +.lb h1 { + margin: 0 0 4px; + font-size: 18px; +} +.lb h2 { + margin: 0 0 6px; + font-size: 14px; +} +.lb a { + color: var(--accent); +} +.lb-hint { + color: var(--muted); +} +.lb-status { + margin: 10px 0; + padding: 6px 10px; + border-radius: 6px; + background: var(--panel); + transition: background 0.4s ease; +} +.lb-status.flash { + background: #1f3a2a; + transition: none; +} +.lb-grid { + display: grid; + grid-template-columns: 1fr 1fr 260px; + gap: 12px; +} +.lb-grid section { + padding: 10px 12px; + border-radius: 8px; + background: var(--panel); +} +.lb table { + width: 100%; + border-collapse: collapse; +} +.lb td { + padding: 3px 4px; + border-bottom: 1px solid #222a35; +} +.lb td.num { + text-align: right; +} +.lb tr.me td { + color: var(--accent); + font-weight: bold; +} +.lb-me canvas { + width: 100%; + max-width: 240px; + aspect-ratio: 1; + background: #0b0d12; + border-radius: 6px; +} +.lb-me .pos { + margin-bottom: 8px; +} +.lb-rebuild { + margin-top: 12px; + padding: 10px 12px; + border-radius: 8px; + background: var(--panel); +} +.lb-rebuild button { + font: inherit; + padding: 6px 12px; + margin-right: 8px; + border: 1px solid #3a4556; + border-radius: 6px; + background: #1a2230; + color: var(--text); + cursor: pointer; +} +.lb-rebuild pre { + margin: 8px 0 0; + white-space: pre-wrap; +} +@media (max-width: 860px) { + .lb-grid { + grid-template-columns: 1fr; + } +} diff --git a/examples/game/client/src/mobpit/client.ts b/examples/game/client/src/mobpit/client.ts new file mode 100644 index 000000000..7ef9c69f8 --- /dev/null +++ b/examples/game/client/src/mobpit/client.ts @@ -0,0 +1,802 @@ +/** + * Mob Pit networking without rendering (Node-testable): the generated + * `createMobpitClient` (the own capsule predicted by `pit_step`, the Rust + * Arena movement compiled to WebAssembly), the room's typed events folded + * into a small state object, the rooms' generated contents + * (`createMobpitPures().pitRoom`, the Rust room generator as WebAssembly), + * and the `/dev/mobpit/*` routes. + * + * Every room (`pit..`) is a celld Durable Object reached at + * `/zones/{room}`; celld forwards the socket to whichever node runs it. + * Walking through a doorway, the room hands the player to the next room + * (`Handoff`), and the SDK reconnects there with the transfer ticket. + * + * One continuous world: room `(x, y)` sits at world `(x, y) × ROOM_SIZE` + * and entity positions are room-local, so `worldOf` places anything from + * any room (the doorway arrival is the same world point, see + * `game_sim::mobpit`). + * + * Neighbours: the client also watches the 8 rooms around its own as an + * observer (`watchZones` over `neighbourRooms`), so their mobs are drawn where they are. + * The client tells the SDK where the player is (`setPosition`); every room + * says where it sits in the world (Welcome origin), so each watcher is + * focused on the player in that room's coordinates, and the room + * replicates only what is within the player's own view radius around it. On + * celld an observer is a passive watcher: it keeps no room awake and wakes + * none (a sleeping room answers `ASLEEP`; it is tried again every few + * seconds and shows nothing meanwhile). + * + * Proximity wake ("Wake rooms in reach", `wake`, default on): rooms connect + * only through the four mid-wall doorways, so only those four neighbours + * can be woken. Within `PIT_WORLD.wakeReach` (11 m) of a doorway — from the + * predicted position — the watcher of the room behind it says it is *near* + * (`watchZones(...).setNear`): the room wakes and stays live until the + * player is beyond `wakeRelease` (19 m) of that doorway (`rooms_in_reach`, + * shared Rust as WASM: at most the two doorways of a corner, nothing from + * the middle of the room, corner rooms never). The services grant `wake` + * only on observer tickets for rooms within two doorways of the player's + * last room. Off: every neighbour is a passive watcher. + * + * Live content updates: the page starts on the world's live content + * version (`/dev/mobpit/content`). An admin rollout freezes every room + * (`Freeze`, inputs held; the change notes on screen), switches them to the + * new pack and resumes them (`Resume` with the version). A normal client + * patches live (`setContentVersion`); a pinned one (`pinContent`, the page's + * `?old=1`) stays on its pack and is `stale`: the room keeps it from every + * doorway but the entrance (`stale` event) and reloads it there + * (`Kick(RELOAD)` → `reloadContent` → back with the new version). + * + * Event flow of one kill: `kill` (broadcast, the tick the mob dies — the + * fact is only *queued*) → `saved` (to the killer, when the durable cell + * commit settled) → `profile`. + */ +import { + watchZones, + type EntityFields, + type FreezeMessage, + type GameSocketFactory, + type RenderedEntity, + type ResumeMessage, + type WatchState +} from '@hops-ops/distributed/game'; + +import * as pit from '../generated/mobpit/index.ts'; +import type { DevApi } from '../shared/dev-api.ts'; +import { latest } from '../shared/latest.ts'; + +export const DEFAULT_ZONE = 'pit.0.0'; + +/** `pit..` → `[x, y]` (undefined for anything else). */ +export function parseRoom(zone: string): [number, number] | undefined { + const m = /^pit\.(-?\d+)\.(-?\d+)$/.exec(zone); + return m === null ? undefined : [Number(m[1]), Number(m[2])]; +} + +/** Room edge length (m): room `(x, y)` is centred at world `(x, y) × ROOM_SIZE`. */ +export const ROOM_SIZE = pit.PIT_WORLD.roomSize; + +/** World position (m) of a room-local point of `zone` (undefined for a non-room zone). */ +export function toWorldXY(zone: string, x: number, y: number): { x: number; y: number } | undefined { + const room = parseRoom(zone); + return room === undefined ? undefined : { x: room[0] * ROOM_SIZE + x, y: room[1] * ROOM_SIZE + y }; +} + +/** World position (m) of a rendered entity (every Mob Pit kind has local `x` / `y`). */ +export function worldOf(entity: RenderedEntity): { x: number; y: number } | undefined { + const { x, y } = entity.fields as { x?: unknown; y?: unknown }; + return typeof x === 'number' && typeof y === 'number' ? toWorldXY(entity.zoneId, x, y) : undefined; +} + +/** + * The own player's predicted fields re-expressed in the next room's frame + * (the same world point): lets the SDK keep predicting through a doorway + * handoff instead of holding the player still (`handoffFrame`). + */ +export function pitHandoffFrame(fields: EntityFields, from: string, to: string): EntityFields | undefined { + const a = parseRoom(from); + const b = parseRoom(to); + const { x, y } = fields as { x?: unknown; y?: unknown }; + if (a === undefined || b === undefined || typeof x !== 'number' || typeof y !== 'number') return undefined; + return { ...fields, x: x + (a[0] - b[0]) * ROOM_SIZE, y: y + (a[1] - b[1]) * ROOM_SIZE }; +} + +/** `[x, y]` → `pit..`. */ +export function roomZone(x: number, y: number): string { + return `pit.${x}.${y}`; +} + +/** The doorway neighbours of `room` behind `near` bits (`rooms_in_reach`: east, west, north, south). */ +export function reachRooms(room: readonly [number, number], near: number): string[] { + const doors: [number, [number, number]][] = [ + [1, [1, 0]], + [2, [-1, 0]], + [4, [0, 1]], + [8, [0, -1]] + ]; + return doors.filter(([bit]) => (near & bit) !== 0).map(([, [dx, dy]]) => roomZone(room[0] + dx, room[1] + dy)); +} + +/** The 8 rooms around `zone`. */ +/** Side (`MobView.from >> 16`) → step from a visitor's room to its home room. */ +const HOME_STEP: Readonly> = { 1: [1, 0], 2: [-1, 0], 3: [0, 1], 4: [0, -1] }; + +/** + * Rooms stream independently, so while a mob crosses, a viewer watching + * both rooms can briefly still hold its home copy after the visitor shows + * up. A visitor names that copy (`from`): draw the visitor, drop the copy. + */ +export function withoutHomeCopies(rendered: readonly T[]): T[] { + const hidden = new Set(); + for (const e of rendered) { + if (!pit.isMob(e) || e.stale) continue; + const from = pit.mobFields(e).from; + const step = HOME_STEP[from >>> 16]; + const room = parseRoom(e.zoneId); + if (step === undefined || room === undefined) continue; + hidden.add(`${roomZone(room[0] + step[0], room[1] + step[1])}:${from & 0xffff}`); + } + return hidden.size === 0 ? [...rendered] : rendered.filter((e) => !(pit.isMob(e) && hidden.has(e.key))); +} + +export function neighbourRooms(zone: string): string[] { + const at = parseRoom(zone); + if (at === undefined) return []; + const out: string[] = []; + for (let dy = -1; dy <= 1; dy += 1) { + for (let dx = -1; dx <= 1; dx += 1) if (dx !== 0 || dy !== 0) out.push(roomZone(at[0] + dx, at[1] + dy)); + } + return out; +} + + +/** + * WebSocket URL of a room. `base` is the http(s) origin rooms are reached + * at (the services' gateway, or celld itself in Node tests); in the browser + * the page's own origin (Vite proxies `/zones` to the gateway). + */ +export function roomUrl(zone: string, base?: string): string { + const origin = base ?? globalThis.location.origin; + return `${origin.replace(/^http/, 'ws')}/zones/${encodeURIComponent(zone)}`; +} +/** `state` names of the `mob` kind, by value (generated from the Rust `MOB_STATES`). */ +export const MOB_STATE = pit.PIT_RULES.states; +/** Presentation of each tier (client only). */ +const TIER_LOOK: Readonly> = { + 1: { name: 'Grunt', color: '#9ad16b' }, + 2: { name: 'Brute', color: '#b48cf2' }, + 3: { name: 'Elite', color: '#ff6b6b' }, + 4: { name: 'Boss', color: '#ff2d55' } +}; +/** + * Per tier: display name and color (client presentation), body and + * telegraph radius (the server's `tier_stats`, generated `PIT_RULES`). + */ +export const TIERS: Readonly> = Object.fromEntries( + pit.PIT_RULES.tiers.map((t) => [t.tier, { ...(TIER_LOOK[t.tier] ?? { name: `Tier ${t.tier}`, color: '#9ad16b' }), radius: t.radius, tele: t.tele }]) +); + +export type Vec3 = [number, number, number]; + +/** One ranged shot: what the client saw, then the room's verdict. */ +export type ShotRecord = { + id: number; + /** Room-local eye position and unit aim (z up). */ + origin: Vec3; + dir: Vec3; + zone: string; + compensated: boolean; + /** The mob the client saw the laser hit (undefined: a predicted miss). */ + predicted: number | undefined; + /** Where it met the predicted mob, or where it stops. */ + point: Vec3; + /** The predicted beam: each surface it bounced off (with its normal), + * then where it stops (normal undefined). */ + path: { point: Vec3; normal: Vec3 | undefined }[]; + delayMs: number; + verdict?: pit.ShotEvent; +}; + +/** Ranged numbers for the HUD and tests. */ +export type RangedStats = { + shots: number; + predictedHits: number; + confirmedHits: number; + /** Client and room agree (same mob, or both a miss). */ + agreed: number; + resolved: number; + clamped: number; + lastAgeMs: number; +}; + +/** Entry distance of a ray (unit `dir`) into a vertical capsule standing on the floor. */ +export function rayCapsule(origin: Vec3, dir: Vec3, x: number, y: number, radius: number, height: number): number | undefined { + // Horizontal circle first, then the height at the entry. + const flat = Math.hypot(dir[0], dir[1]); + if (flat < 1e-6) return undefined; + const ux = dir[0] / flat; + const uy = dir[1] / flat; + const ox = x - origin[0]; + const oy = y - origin[1]; + const along = ox * ux + oy * uy; + const off2 = ox * ox + oy * oy - along * along; + if (along <= 0 || off2 > radius * radius) return undefined; + const entry = (along - Math.sqrt(radius * radius - off2)) / flat; + const z = origin[2] + dir[2] * entry; + return z >= 0 && z <= height ? entry : undefined; +} + +/** Unit aim from yaw (radians from +x) and pitch (up positive). */ +export function aimDir(yaw: number, pitch: number): Vec3 { + const flat = Math.cos(pitch); + return [Math.cos(yaw) * flat, Math.sin(yaw) * flat, Math.sin(pitch)]; +} + +/** One leaderboard row (`/dev/mobpit/leaderboard`). */ +export type BoardRow = Readonly<{ rank: number; member: string; name: string; score: number }>; +/** The leaderboard snapshot the services keep (top-N, store, rebuilds). */ +export type BoardSnapshot = Readonly<{ + version: number; + backend: string; + members: number; + kills: BoardRow[]; + xp: BoardRow[]; + lastRebuild: RebuildReport | null; +}>; +export type RebuildReport = Readonly<{ + backend: string; + crawlers: number; + events: number; + applied: number; + duplicates: number; + identicalTop: boolean; + matchesCells: boolean; + mismatches: { member: string; cell: { kills: number; xp: number }; board: { kills: number; xp: number } }[]; + tookMs: number; +}>; +/** `/dev/mobpit/leaderboard` neighbourhood. */ +export type BoardPosition = Readonly<{ rank: number | null; score: number | null; around: BoardRow[] }>; + +/** A room as the `zone_status` read model knows it (`/dev/mobpit/rooms`). */ +export type RoomStatus = Readonly<{ + zone: string; + x: number; + y: number; + /** `active` · `dormant` · `hibernated` (unknown rooms are cold). */ + status: 'active' | 'dormant' | 'hibernated'; + players: number; + /** The current activation restored a snapshot. */ + restored: boolean; + activations: number; + /** celld node of the activation — a debug detail (empty when unknown). */ + node: string; + changedAtMs: number; +}>; + +/** The tiers around a room (`/dev/mobpit/tiers`): hoods, their boroughs, the city. */ +export type TiersAround = Readonly<{ + hoods: { hood: string; x: number; y: number; bossRoom: [number, number]; bossDown: boolean; tier: number }[]; + boroughs: { borough: string; x: number; y: number; bossesDown: number; weather: string }[]; + city: { bosses_down: number; boroughs_cleared: number; banner: string } | null; +}>; + +/** A room object's debug JSON (`/zones/{room}/info`). */ +export type RoomInfo = Readonly<{ + zone: string; + status: string; + awake: boolean; + activation: string; + restored: boolean; + wakes: number; + node: string; + isolate: string; + players: number; + /** Observers connected, and how many of them keep the room awake (near). */ + observers?: number; + near?: number; + /** The room is ticking (active). */ + ticking?: boolean; + tick: number; + hz: number; + lateMs: { p50: number; p99: number }; + droppedTicks: number; + /** The room's content version and freeze state (awake rooms only). */ + content: { version: string; freeze: 'running' | 'freezing' | 'frozen' } | null; +}>; + +/** The pack of a content version (unknown versions draw the built-in one). */ +export function contentPack(version: string): pit.ContentPack { + return pit.CONTENT_PACKS.find((p) => p.version === version) ?? pit.CONTENT_PACKS[0]!; +} + +/** What the client knows about live content. */ +export type ContentView = Readonly<{ + /** The content version this client runs (its pack). */ + version: string; + pack: pit.ContentPack; + /** The world's version (last Welcome / Resume of the own room). */ + worldVersion: string; + /** Running older content than the world. */ + stale: boolean; + /** The room's Freeze notice while frozen. */ + frozen: FreezeMessage | undefined; + lastResume: ResumeMessage | undefined; + /** The room's last `stale` notice (only the entrance lets you through). */ + staleNotice: pit.StaleEvent | undefined; + /** Reloads the rooms required (room, version). */ + reloads: readonly { zone: string; version: string }[]; +}>; + +/** The world's live content as `/dev/mobpit/content` reports it. */ +export type ContentInfo = Readonly<{ + world: string; + state: Readonly<{ version: string; target: string; phase: string; notes: string; since_ms: number; hard: boolean }> | null; + packs: readonly pit.ContentPack[]; +}>; + +export type MobPitClient = pit.MobpitClient & + Readonly<{ + hello(): pit.HelloEvent | undefined; + /** The tiers above the room (hood, borough, city), latest. */ + world(): pit.WorldTiers | undefined; + profile(): pit.Profile | undefined; + /** The room the player is in (authority zone). */ + room(): string | undefined; + /** The own player as rendered now (predicted; held through a handoff). */ + me(): RenderedEntity | undefined; + /** World position (m) of the own player as rendered now. */ + position(): { x: number; y: number } | undefined; + /** Kills by me whose fact has not settled yet (key → event). */ + unsaved: ReadonlyMap; + /** The rooms' generated contents (the Rust generator as WASM). */ + pures: ReturnType; + /** Resolves on the first hello, once the predicted step is loaded. */ + ready: Promise; + /** Ranged shots by id (latest 256). */ + shots: Map; + rangedStats: RangedStats; + /** + * Prepare a ranged shot along `yaw`/`pitch` from the own eye: the + * predicted hit (ray against the mobs as rendered) and the input + * fields to send this frame (shot id, view delay, the fire bits). + */ + aimShot(yaw: number, pitch: number, compensated: boolean, firstPerson?: boolean): { record: ShotRecord; input: Pick } | undefined; + /** Resolves with the verdict of shot `id`. */ + verdict(id: number): Promise; + /** The neighbour rooms watched (`watchZones` over `neighbourRooms`), when enabled. */ + neighbours(): ReadonlyMap; + /** The doorway neighbours kept awake now (proximity wake; empty when off). */ + near(): ReadonlySet; + /** Proximity wake ("Wake rooms in reach") on? */ + wakeRooms(): boolean; + /** Turn proximity wake on or off (off: every neighbour passive). */ + setWakeRooms(on: boolean): void; + /** Live content (version, pack, freeze, staleness). */ + content(): ContentView; + /** Stop watching neighbours and close the client. */ + close(): void; + }>; + +export type MobPitClientOptions = Readonly<{ + api: DevApi; + /** http(s) origin of the rooms (celld); default the page's origin. */ + roomsBase?: string; + socket?: GameSocketFactory; + /** Watch the 8 neighbour rooms (default true). */ + neighbours?: boolean; + /** Proximity wake: keep the doorway neighbours in reach awake (default true). */ + wake?: boolean; + /** Content version to start on (the world's live one; default ''). */ + contentVersion?: string; + /** Simulate an old client: never patch content live on Resume. */ + pinContent?: boolean; + /** The world's live version, for a reload no room named (default ''). */ + liveVersion?: () => Promise; +}>; + +export function createMobPitClient(options: MobPitClientOptions): MobPitClient { + const reloads: { zone: string; version: string }[] = []; + let typedRef: pit.MobpitClient | undefined; + const typed = pit.createMobpitClient({ + contentVersion: options.contentVersion ?? '', + // A room required a reload (the entrance, for a stale client; or a + // fresh join on old content): "load" the pack of the version it + // named (the packs are built in), else the world's live one. + reloadContent: async (request) => { + const version = request.version ?? (await options.liveVersion?.()) ?? ''; + reloads.push({ zone: typedRef?.client.authority?.zoneId ?? '', version }); + return version; + }, + url: (zone) => roomUrl(zone, options.roomsBase), + ticket: options.api.ticketSource(), + socket: options.socket, + pingIntervalMs: 500, + inputDtMs: 1000 / 30, + // Prediction: the generated default, `pit_step` compiled to WASM, + // carried on through doorways in the next room's frame. + prediction: { handoffFrame: pitHandoffFrame } + }); + typedRef = typed; + // ---- live content ---- + let worldVersion = options.contentVersion ?? ''; + let frozen: FreezeMessage | undefined; + let lastResume: ResumeMessage | undefined; + let staleNotice: pit.StaleEvent | undefined; + typed.client.on('authority', (_zone, welcome) => { + worldVersion = welcome.contentVersion; + frozen = typed.client.authority?.connection.frozen ? frozen : undefined; + staleNotice = undefined; + }); + typed.client.on('freeze', (zone, message) => { + if (zone === typed.client.authority?.zoneId) frozen = message; + }); + typed.client.on('resume', (zone, message) => { + if (zone !== typed.client.authority?.zoneId) return; + frozen = undefined; + lastResume = message; + worldVersion = message.version; + // Patch live (the packs are built in) unless simulating an old build. + if (options.pinContent !== true && message.version !== typed.client.contentVersion) typed.client.setContentVersion(message.version); + }); + typed.on('stale', (notice, zoneId) => { + if (zoneId === typed.client.authority?.zoneId) staleNotice = notice; + }); + const content = (): ContentView => { + const version = typed.client.contentVersion; + return { + version, + pack: contentPack(version), + worldVersion, + stale: version !== worldVersion, + frozen, + lastResume, + staleNotice: version !== worldVersion ? staleNotice : undefined, + reloads + }; + }; + const hello = latest( + (h) => typed.on('hello', h), + (value) => typed.client.setControlledEntity(value.entity) + ); + // The predicted step's context is the room (its seeded obstacles are + // generated inside the step): follow the authority and the world seed. + const setRoomContext = () => { + const room = parseRoom(typed.client.authority?.zoneId ?? ''); + if (room === undefined) return; + typed.prediction?.setContext({ seed: hello.get()?.seed ?? pit.PIT_WORLD.defaultSeed, x: room[0], y: room[1] }); + }; + typed.client.on('authority', setRoomContext); + typed.on('hello', setRoomContext); + const profile = latest((h) => typed.on('profile', h)); + // Only the own room's view of the tiers (watched neighbours send theirs too). + let world: pit.WorldTiers | undefined; + typed.on('world', (w, zoneId) => { + if (zoneId === typed.client.authority?.zoneId) world = w; + }); + const unsaved = new Map(); + typed.on('kill', (kill, zoneId) => { + // Entity ids are per room: only kills in your own room can be yours. + if (zoneId === typed.client.authority?.zoneId && kill.killer === hello.get()?.entity) unsaved.set(kill.key, kill); + }); + typed.on('saved', (saved) => unsaved.delete(saved.key)); + const pures = pit.createMobpitPures(); + + // ---- ranged: predicted hits, verdicts ---- + const shots = new Map(); + const waiters = new Map void>(); + const rangedStats: RangedStats = { shots: 0, predictedHits: 0, confirmedHits: 0, agreed: 0, resolved: 0, clamped: 0, lastAgeMs: 0 }; + let nextShot = 0; + typed.on('shot', (verdict) => { + const shot = shots.get(verdict.shot); + if (shot === undefined || shot.verdict !== undefined) return; + shot.verdict = verdict; + rangedStats.resolved += 1; + if (verdict.hit !== undefined) rangedStats.confirmedHits += 1; + if (verdict.hit === shot.predicted) rangedStats.agreed += 1; + if (verdict.clamped) rangedStats.clamped += 1; + rangedStats.lastAgeMs = verdict.ageMs; + waiters.get(verdict.shot)?.(verdict); + waiters.delete(verdict.shot); + }); + const heights = pit.PIT_RULES.mobHeights; + const range = pit.PIT_RULES.range; + const aimShot = (yaw: number, pitch: number, compensated: boolean, firstPerson = false) => { + const zone = typed.client.authority; + const meNow = me(); + if (zone === undefined || meNow === undefined || !zone.connection.canSendInput()) return undefined; + const p = pit.playerFields(meNow); + // First person: from the eye along the look; else level at the hip. + const origin: Vec3 = [p.x, p.y, p.z + (firstPerson ? pit.PIT_RULES.eyeHeight : pit.PIT_RULES.hipHeight)]; + const dir = aimDir(yaw, firstPerson ? pitch : 0); + // The view time: the room rewinds to exactly what is drawn. + const context = typed.client.inputContext(zone)!; + const renderTime = zone.connection.serverNow() - context.interpolationDelayMs; + const delayMs = Math.max(0, zone.connection.tickTime(context.clientTick) - renderTime); + // The beam through the room's geometry (the room's own pure), then + // the first drawn mob along any of its legs. + const room = parseRoom(zone.zoneId); + const bounces: { point: Vec3; normal: Vec3 | undefined }[] = + pures.loaded() && room !== undefined + ? pures + .laserPath({ + seed: hello.get()?.seed ?? pit.PIT_WORLD.defaultSeed, + roomX: room[0], + roomY: room[1], + x: origin[0], + y: origin[1], + z: origin[2], + dx: dir[0], + dy: dir[1], + dz: dir[2] + }) + .map((h) => ({ + point: [h.x, h.y, h.z] as Vec3, + normal: h.nx === 0 && h.ny === 0 && h.nz === 0 ? undefined : ([h.nx, h.ny, h.nz] as Vec3) + })) + : [{ point: [origin[0] + dir[0] * range, origin[1] + dir[1] * range, origin[2] + dir[2] * range], normal: undefined }]; + const mobs = typed.client + .render() + .filter((e) => pit.isMob(e) && !e.stale && e.zoneId === zone.zoneId) + .map((e) => ({ id: e.id, m: pit.mobFields(e) })); + let predicted: number | undefined; + let point: Vec3 = bounces[bounces.length - 1]!.point; + const path: { point: Vec3; normal: Vec3 | undefined }[] = []; + let from = origin; + for (const leg of bounces) { + const [ax, ay, az] = from; + const span = Math.hypot(leg.point[0] - ax, leg.point[1] - ay, leg.point[2] - az); + if (span > 1e-6) { + const unit: Vec3 = [(leg.point[0] - ax) / span, (leg.point[1] - ay) / span, (leg.point[2] - az) / span]; + let best = span; + for (const { id, m } of mobs) { + const t = TIERS[m.tier]; + const d = rayCapsule(from, unit, m.x, m.y, t?.radius ?? 0.5, heights[m.tier] ?? 1); + if (d !== undefined && d < best) { + best = d; + predicted = id; + } + } + if (predicted !== undefined) { + point = [ax + unit[0] * best, ay + unit[1] * best, az + unit[2] * best]; + path.push({ point, normal: undefined }); + break; + } + } + path.push(leg); + from = leg.point; + } + nextShot = (nextShot % 0xffff) + 1; + const record: ShotRecord = { + id: nextShot, + origin, + dir, + zone: zone.zoneId, + compensated, + predicted, + point, + path, + delayMs + }; + shots.set(record.id, record); + if (shots.size > 256) shots.delete(shots.keys().next().value!); + rangedStats.shots += 1; + if (predicted !== undefined) rangedStats.predictedHits += 1; + const buttons = pit.BUTTON.fire | (compensated ? 0 : pit.BUTTON.noComp) | (firstPerson ? pit.BUTTON.aim : 0); + return { record, input: { buttons, shot: record.id, delayMs: Math.min(0xffff, Math.round(delayMs)), yaw, pitch } }; + }; + // The own player: the predicted entity, or (mid-handoff) the SDK's + // bridge, the last predicted state in the room just left. + const me = () => { + const id = hello.get()?.entity; + // Never a watched neighbour's player (entity ids are per room). + const rendered = typed.client.render().filter((e) => pit.isPlayer(e) && typed.client.zone(e.zoneId)?.role !== 'observer'); + return rendered.find((e) => e.predicted) ?? rendered.find((e) => e.id === id && e.zoneId === typed.client.authority?.zoneId) ?? rendered.find((e) => e.id === id); + }; + const watcher = options.neighbours === false ? undefined : watchZones(typed.client, neighbourRooms); + // ---- proximity wake ---- + let wake = options.wake ?? true; + let reachRoom: string | undefined; + let reachBits = 0; + let near: ReadonlySet = new Set(); + let openKey = ''; + let openBits = 0; + const updateReach = () => { + if (watcher === undefined) return; + const room = typed.client.authority?.zoneId; + const at = parseRoom(room ?? ''); + // The hysteresis is per room (a doorway re-frames everything). + if (room !== reachRoom) { + reachRoom = room; + reachBits = 0; + } + const meNow = me(); + // Each watched room (placed in the world by its Welcome origin) + // applies the player's own view around it: its interest radius + // carries on across the wall. + if (meNow !== undefined) { + const p = pit.playerFields(meNow); + typed.client.setPosition(p.x, p.y, meNow.zoneId); + } + let bits = 0; + if (wake && at !== undefined && meNow !== undefined && meNow.zoneId === room && pures.loaded()) { + const p = pit.playerFields(meNow); + // Reach runs to the whole of an open side (its layout, once per room). + const seed = hello.get()?.seed ?? pit.PIT_WORLD.defaultSeed; + const key = `${seed}:${room}`; + if (openKey !== key && at !== undefined) { + openKey = key; + openBits = pures.pitRoom({ seed, x: at[0], y: at[1] }).open; + } + bits = pures.roomsInReach({ x: p.x, y: p.y, near: reachBits, open: openBits }).near; + } + reachBits = bits; + const rooms = at === undefined ? [] : reachRooms(at, bits); + if (rooms.length === near.size && rooms.every((z) => near.has(z))) return; + near = new Set(rooms); + watcher.setNear(rooms); + }; + const reachTimer = setInterval(updateReach, 100); + // Never keep a Node process alive for this. + (reachTimer as { unref?: () => void }).unref?.(); + return { + ...typed, + hello: hello.get, + world: () => world, + profile: profile.get, + room: () => typed.client.authority?.zoneId, + me, + position: () => { + const entity = me(); + return entity === undefined ? undefined : worldOf(entity); + }, + unsaved, + pures, + ready: Promise.all([hello.ready, typed.prediction?.ready, pures.ready]).then(([h]) => h), + neighbours: () => watcher?.states() ?? new Map(), + near: () => near, + wakeRooms: () => wake, + setWakeRooms(on) { + wake = on; + updateReach(); + }, + content, + shots, + rangedStats, + aimShot, + verdict(id) { + const known = shots.get(id)?.verdict; + if (known !== undefined) return Promise.resolve(known); + return new Promise((resolve) => waiters.set(id, resolve)); + }, + close: () => { + clearInterval(reachTimer); + watcher?.stop(); + typed.client.close(); + } + }; +} + +/** Polls the services' leaderboard snapshot (the board is a projection of the cells). */ +export function createBoardWatcher(pitApi: MobPitApi, everyMs = 500): Readonly<{ + board(): BoardSnapshot | undefined; + on(handler: (value: BoardSnapshot) => void): () => void; + stop(): void; +}> { + let current: BoardSnapshot | undefined; + const handlers = new Set<(value: BoardSnapshot) => void>(); + let stopped = false; + const poll = async () => { + while (!stopped) { + try { + const { snapshot } = await pitApi.leaderboard(); + if (current === undefined || snapshot.version !== current.version) { + current = snapshot; + for (const h of handlers) h(snapshot); + } + } catch { + // Services restarting: try again. + } + await new Promise((r) => setTimeout(r, everyMs)); + } + }; + void poll(); + return { + board: () => current, + on: (handler) => { + handlers.add(handler); + return () => handlers.delete(handler); + }, + stop: () => { + stopped = true; + } + }; +} + +/** `/dev/mobpit/*` (dev only; none of these take an identity or a reward). */ +export class MobPitApi { + readonly base: string; + readonly roomsBase: string; + + /** `base`: the services' origin; `roomsBase`: celld's (both default to the page's). */ + constructor(base = '', roomsBase = base) { + this.base = base; + this.roomsBase = roomsBase; + } + + /** + * The room a returning guest starts in: its last room (presence cell, + * verified on the server from the guest token), else the entrance. + */ + async startRoom(guest: string | undefined): Promise { + const { zone } = await this.#json<{ zone: string; resumed: boolean }>('/dev/mobpit/start', guest === undefined ? {} : { guest }); + return parseRoom(zone) === undefined ? DEFAULT_ZONE : zone; + } + + /** The hoods around `room`, their boroughs and the city (tier cells). */ + tiers(room: string): Promise { + return this.#json(`/dev/mobpit/tiers?room=${encodeURIComponent(room)}`); + } + + /** Every room the zone status read model knows. */ + rooms(): Promise<{ rooms: RoomStatus[] }> { + return this.#json('/dev/mobpit/rooms'); + } + + /** A room object's debug JSON, straight from the room on celld (does not wake it). */ + async roomInfo(zone: string): Promise { + const response = await fetch(`${this.roomsBase}/zones/${encodeURIComponent(zone)}/info`); + if (!response.ok) throw new Error(`room info ${zone}: HTTP ${response.status}`); + return (await response.json()) as RoomInfo; + } + + /** The player's presence cell. */ + presence(principal: string): Promise<{ presence: { zone: string; status: string } | null }> { + return this.#json(`/dev/mobpit/presence?principal=${encodeURIComponent(principal)}`); + } + + stats(): Promise> { + return this.#json('/dev/mobpit/stats'); + } + + crawlers(): Promise<{ crawlers: { principal: string; name: string; xp: number; kills: number; level: number }[] }> { + return this.#json('/dev/mobpit/crawlers'); + } + + leaderboard(member?: string): Promise<{ snapshot: BoardSnapshot; me: { kills: BoardPosition; xp: BoardPosition } | null }> { + const query = member === undefined ? '' : `?member=${encodeURIComponent(member)}`; + return this.#json(`/dev/mobpit/leaderboard${query}`); + } + + rebuild(): Promise { + return this.#json('/dev/mobpit/leaderboard/rebuild', {}); + } + + /** The world's live content and every pack. */ + content(): Promise { + return this.#json('/dev/mobpit/content'); + } + + /** + * **Admin** (the services' admin secret): roll `version` out to every + * room (freeze → apply → resume with `notes`; `hard` reloads old + * clients at once instead of at the entrance). + */ + async rollout(secret: string, request: { version: string; notes?: string; hard?: boolean; freezeMs?: number }): Promise<{ version: string; notes: string }> { + const response = await fetch(`${this.base}/dev/mobpit/rollout`, { + method: 'POST', + headers: { 'content-type': 'application/json', 'x-game-admin-secret': secret }, + body: JSON.stringify(request) + }); + if (!response.ok) throw new Error(`rollout: HTTP ${response.status} ${await response.text()}`); + return (await response.json()) as { version: string; notes: string }; + } + + async #json(path: string, body?: unknown): Promise { + const response = await fetch(`${this.base}${path}`, { + method: body === undefined ? 'GET' : 'POST', + headers: body === undefined ? undefined : { 'content-type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body) + }); + if (!response.ok) throw new Error(`${path}: HTTP ${response.status} ${await response.text()}`); + return (await response.json()) as T; + } +} diff --git a/examples/game/client/src/mobpit/main.ts b/examples/game/client/src/mobpit/main.ts new file mode 100644 index 000000000..794b8e5b2 --- /dev/null +++ b/examples/game/client/src/mobpit/main.ts @@ -0,0 +1,2087 @@ +/** + * Mob Pit page: Babylon scene over `createMobPitClient`. + * + * What to look at: rooms are celld Durable Objects on a near-infinite + * seeded grid, laid out as one continuous world (room `(x, y)` at + * `(x, y) × ROOM_SIZE`): the rooms around yours are drawn from the seeded + * layout (`pitRoom`, Rust as WASM: biome floor, walls, doorways, pillars), + * so you see into the next room before you go. Walk through a doorway (the + * gaps in the middle of each wall) and you are simply in the next room — + * the room hands you over at the same world point; nothing moves. A + * floating origin at your room keeps coordinates small. The minimap (bottom right) shows every known room + * live — active, dormant (just left), hibernated (asleep in storage) — from + * the `zone_status` read model. Come back to a room after it slept: it + * wakes from its snapshot with the mobs you left (toast). Kill a mob + * (Space): the grey "saving…" popup turns into "+XP saved ✓" when the kill + * settled in your Crawler cell. The debug overlay (O) shows which celld + * node and isolate run the room — celld decides, the game never does. + * + * Network panel (the HUD): latency / jitter / loss sliders apply to every + * room on celld (each room object delays its sockets' frames both ways); + * your capsule is predicted (the Rust step as WASM) and reconciled — P + * turns prediction off to feel the raw round trip, G shows the server's + * authoritative position as a wireframe ghost, and the readout counts + * pending inputs and corrections. The ring on the floor is your interest + * radius: mobs and players beyond it are not replicated to you. + * + * Next door: the 8 rooms around yours are watched (their mobs drawn where + * they are) without keeping them awake. "Wake rooms in reach" (N, on by + * default, remembered): walk toward a doorway and the room behind it wakes + * and stays live until you walk away (minimap: solid cyan border = kept + * awake, dashed = watched only). + */ +import type { StandardMaterial } from '@babylonjs/core/Materials/standardMaterial'; +import { DynamicTexture } from '@babylonjs/core/Materials/Textures/dynamicTexture'; +import { Color3, Color4 } from '@babylonjs/core/Maths/math.color'; +import { Scene } from '@babylonjs/core/scene'; +import { Frustum } from '@babylonjs/core/Maths/math.frustum'; +import { Matrix, Vector3 } from '@babylonjs/core/Maths/math.vector'; +import type { Plane } from '@babylonjs/core/Maths/math.plane'; +import { Mesh } from '@babylonjs/core/Meshes/mesh'; +import { VertexData } from '@babylonjs/core/Meshes/mesh.vertexData'; +import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder'; +import { TransformNode } from '@babylonjs/core/Meshes/transformNode'; +import type { AbstractMesh } from '@babylonjs/core/Meshes/abstractMesh'; +import { InputPacer, type RenderedEntity } from '@hops-ops/distributed/game'; + +import { + BUTTON, + CONTENT_PACKS, + GATE_ROOM, + PIT_RULES, + PIT_WORLD, + isMob, + isPillar, + isPit, + mobFields, + PATTERNS, + WEATHER, + pitFields, + playerFields, + type PitFields, + type ContentPack, + type PitInput, + type Platform, + type Ramp, + type RoomTerrain +} from '../generated/mobpit/index.ts'; +import { DevApi } from '../shared/dev-api.ts'; +import { Hud } from '../shared/hud.ts'; +import { cameraRelative, InputSampler, PAD, toAxis } from '../shared/input.ts'; +import { easeOutCubic, Pool, Trauma, tween } from '../shared/feel.ts'; +import { createRing, createStage, material } from '../shared/scene.ts'; +import { + createBoardWatcher, + createMobPitClient, + DEFAULT_ZONE, + MobPitApi, + parseRoom, + ROOM_SIZE, + roomZone, + TIERS, + withoutHomeCopies, + type BoardSnapshot, + type ShotRecord, + type RoomInfo, + type RoomStatus, + type TiersAround +} from './client.ts'; + +/** The rooms' floor, generated from the simulation's constants (`game_sim::mobpit::pit_world`). */ +const { half: HALF, playerRadius: PLAYER_RADIUS, pillars: PILLARS } = PIT_WORLD; +/** Rooms drawn around yours (2 → 5×5). */ +const ROOM_VIEW = 2; +/** Wall thickness and height (m), drawn just outside each room's floor: + * the box a laser bounces off (`game_sim::mobpit::room_colliders`). */ +const WALL_T = PIT_WORLD.wallThickness; +const WALL_H = PIT_WORLD.wallHeight; +/** Swing cone, from the server's rules: reach to a mob's edge, plus the body. */ +const { attackRange, attackHalfAngle: SWING_HALF, swingFrames: SWING_FRAMES } = PIT_RULES; +const ATTACK_REACH = attackRange + PLAYER_RADIUS; +/** A player's full health (`PLAYER_HP` in the room, `server/rooms/src/zone.rs`). */ +const PLAYER_HP = 100; + +const params = new URLSearchParams(location.search); +/** `?zone=` forces a room; otherwise you start where you last were (`/dev/mobpit/start`). */ +const forcedZone = params.get('zone') ?? undefined; +const storedName = (() => { + try { + return localStorage.getItem('game-demos.name') ?? undefined; + } catch { + return undefined; + } +})(); +const name = params.get('name') ?? storedName; + +const api = new DevApi({ name: () => name }); +const pitApi = new MobPitApi(); +// `?old=1` simulates a client built before the next content update: it +// keeps its pack when the rooms move on, and only the entrance reloads it. +const pinContent = params.has('old'); +/** "Wake rooms in reach" (proximity wake), remembered per browser. */ +const WAKE_KEY = 'game-demos.mobpit.wake'; +const wakeInitial = (() => { + try { + return localStorage.getItem(WAKE_KEY) !== 'off'; + } catch { + return true; + } +})(); +const pit = createMobPitClient({ + api, + pinContent, + wake: wakeInitial, + liveVersion: async () => (await pitApi.content()).state?.version ?? '' +}); +const { client } = pit; + +const canvas = document.getElementById('stage') as HTMLCanvasElement; +const stage = createStage(canvas, { half: HALF, background: '#120f14' }); +const { scene } = stage; + +// ---- weather and darkness (Boss Ripple's sky, now the borough's) ---- +// The borough's weather lifts as its bosses fall (storm → rain → clearing → +// clear); within it, the fog thickens and the light dims the closer the room +// is to a boss room (`boss_distance`, the shared Rust room generator). +// The fog is linear and starts at the player, not at the camera: whatever the +// zoom (or first person), the ground around you stays readable and only the +// distance fades. `clearM` is how far past the player it stays clear, `fadeM` +// how much further until the fog is solid. +scene.fogMode = Scene.FOGMODE_LINEAR; +const SKY: Record = { + storm: { clear: '#1c2230', clearM: 12, fadeM: 34, light: 0.7 }, + rain: { clear: '#2e3a4a', clearM: 16, fadeM: 40, light: 0.8 }, + clearing: { clear: '#56708c', clearM: 24, fadeM: 50, light: 0.95 }, + clear: { clear: '#8fc3f0', clearM: 36, fadeM: 70, light: 1.1 } +}; +const lights = scene.lights.map((l) => ({ light: l, base: l.intensity })); +/** Light tint per biome (highlands, steppe, forest, meadow). */ +const BIOME_LIGHT = ['#d6dcea', '#ffe1b3', '#b9dfb4', '#eaf6cf']; +/** Fog and darkness of the current room: its borough's weather × closeness to a boss. */ +function roomSky(): { clear: string; clearM: number; fadeM: number; light: number; near: number } { + const sky = SKY[WEATHER[pit.world()?.weather ?? 0] ?? 'storm'] ?? SKY.storm!; + const here = parseRoom(pit.room() ?? DEFAULT_ZONE); + const seed = pit.hello()?.seed ?? PIT_WORLD.defaultSeed; + const distance = here !== undefined && pit.pures.loaded() ? pit.pures.pitRoom({ seed, x: here[0], y: here[1] }).bossDistance : 6; + // 1 in a boss room, 0 six rooms away. Near a boss the fog closes in to + // half the distance and the light drops by a fifth, never to black. + const near = Math.max(0, 1 - distance / 6); + const close = 1 - 0.5 * near; + return { clear: sky.clear, clearM: sky.clearM * close, fadeM: sky.fadeM * close, light: sky.light * (1 - 0.2 * near), near }; +} +let fogClearM = SKY.storm!.clearM; +let fogFadeM = SKY.storm!.fadeM; +function applySky(dtMs: number): void { + const target = roomSky(); + const want = Color4.FromHexString(`${target.clear}ff`).scale(1 - 0.25 * target.near); + const k = 1 - Math.exp(-dtMs / 600); + scene.clearColor = Color4.Lerp(scene.clearColor, new Color4(want.r, want.g, want.b, 1), k); + scene.fogColor = new Color3(scene.clearColor.r, scene.clearColor.g, scene.clearColor.b); + fogClearM += (target.clearM - fogClearM) * k; + fogFadeM += (target.fadeM - fogFadeM) * k; + // Measured from the camera, so offset by the camera's distance to the player. + const toPlayer = stage.view() === 'first' ? 0 : stage.camera.radius; + scene.fogStart = toPlayer + fogClearM; + scene.fogEnd = scene.fogStart + fogFadeM; + const storm = (pit.world()?.weather ?? 0) === 0; + const flash = storm && Math.random() < 0.004 ? 1.8 : 1; + for (const { light, base } of lights) light.intensity += (base * target.light * flash - light.intensity) * Math.min(1, k * (flash > 1 ? 20 : 1)); + // The room's biome tints the light. + const here = parseRoom(pit.room() ?? DEFAULT_ZONE); + if (here !== undefined && pit.pures.loaded()) { + const seed = pit.hello()?.seed ?? PIT_WORLD.defaultSeed; + const tint = Color3.FromHexString(BIOME_LIGHT[pit.pures.pitRoom({ seed, x: here[0], y: here[1] }).biome] ?? '#ffffff'); + for (const { light } of lights) light.diffuse = Color3.Lerp(light.diffuse, tint, k); + } + canvas.dataset.fog = `${fogClearM.toFixed(1)}/${fogFadeM.toFixed(1)}`; +} + +const hud = new Hud({ + title: 'Mob Pit', + hint: 'WASD move · Space attack · R / click laser (bounces off walls, ramps, the floor) · E dash · Q jump (over a slam, onto ramps) · V first person · C lag compensation · walk through a doorway to the next room · N wake rooms in reach · O debug overlay · P prediction · G server ghost. Controller: left stick move · right stick look · X / RB attack · RT laser · B / LB dash · A jump · R3 first person · View lag compensation. Rooms run on celld; kills are durable facts.', + client, + devApi: api +}); +let debug = params.get('debug') !== '0'; +hud.toggle('Debug overlay (celld node per room)', debug, (on) => (debug = on), 'o'); +hud.toggle('Client prediction', true, (on) => client.setPredictionEnabled(on), 'p'); +hud.toggle('First-person view (click to look, R / click / RT fires)', false, (on) => stage.setView(on ? 'first' : 'third'), 'v', PAD.r3); +hud.toggle('Lag compensation (ranged)', true, (on) => (compensated = on), 'c', PAD.view); +let ghostOn = true; +hud.toggle('Server ghost', true, (on) => (ghostOn = on), 'g'); +let cullOn = true; +hud.toggle('Skip off-screen entities', true, (on) => (cullOn = on), 'k'); +let lodOn = true; +hud.toggle('Level of detail (props and mobs)', true, (on) => (lodOn = on), 'l'); +hud.toggle( + 'Wake rooms in reach (doorway neighbours you walk up to)', + wakeInitial, + (on) => { + pit.setWakeRooms(on); + try { + localStorage.setItem(WAKE_KEY, on ? 'on' : 'off'); + } catch { + // Not remembered (private mode); still applied. + } + }, + 'n' +); +let corrections = 0; +let lastCorrection = 0; +client.on('correction', (c) => { + corrections += 1; + lastCorrection = Math.hypot(c.errors.x ?? 0, c.errors.y ?? 0); +}); + +// ---- side panels: XP bar, durable facts graph, mini leaderboard ---- +const xpPanel = div('pit-xp', document.body); +// First person: your health in the HUD (your own head and its bar are hidden). +const hpRow = div('pit-hp', xpPanel); +const hpLabel = div('pit-hp-label', hpRow); +const hpFillBar = div('pit-hp-fill', div('pit-hp-bar', hpRow)); +hpRow.style.display = 'none'; +const xpLabel = div('pit-xp-label', xpPanel); +const xpBar = div('pit-xp-bar', xpPanel); +const xpFill = div('pit-xp-fill', xpBar); +const factsPanel = div('pit-facts', document.body); +factsPanel.innerHTML = `

Durable facts

+
0 pending 0 saved ✓
+ +
■ pending facts ■ tick interval (ms)
+
+

Leaderboard open ↗

+
    `; +const graph = factsPanel.querySelector('canvas') as HTMLCanvasElement; +const field = (k: string) => factsPanel.querySelector(`[data-k="${k}"]`) as HTMLElement; +const deathBanner = div('pit-death', document.body); +// Top centre, one column: the borough's world event (scheduled by its cell; +// a banner while it runs), then the toasts under it. +const topStack = div('pit-top', document.body); +const eventBanner = div('pit-event', topStack); +eventBanner.style.display = 'none'; +const EVENT_TEXT: Record = { + invasion: 'INVASION — the mobs of this borough come at you from afar and rise again at once', + frenzy: 'FRENZY — the mobs of this borough are 40 % faster', + blessing: 'BLESSING — you heal five times as fast in this borough' +}; +deathBanner.style.display = 'none'; +// ---- live content: freeze overlay, old-client banner, admin panel ---- +const freezeOverlay = div('pit-freeze', document.body); +freezeOverlay.style.display = 'none'; +const staleBanner = div('pit-stale', document.body); +staleBanner.style.display = 'none'; +client.on('resume', (zone, message) => { + if (zone !== client.authority?.zoneId || message.version === '' && message.notes === '') return; + const pack = CONTENT_PACKS.find((p) => p.version === message.version); + toast(`World updated to ${pack?.name ?? message.version}${message.notes === '' ? '' : ` — ${message.notes}`}`); +}); +const adminParam = params.get('admin'); +const adminSecret = (() => { + try { + if (adminParam !== null) localStorage.setItem('game-demos.mobpit.admin', adminParam); + return adminParam ?? localStorage.getItem('game-demos.mobpit.admin') ?? undefined; + } catch { + return adminParam ?? undefined; + } +})(); +if (adminSecret !== undefined && adminSecret !== '') { + const panel = div('pit-admin', document.body); + panel.innerHTML = `

    World admin (dev, admin secret)

    + + +
    `; + const q = (k: string) => panel.querySelector(`[data-k="${k}"]`) as HTMLInputElement; + for (const pack of CONTENT_PACKS) { + const button = document.createElement('button'); + button.textContent = `Roll out ${pack.name}`; + button.addEventListener('click', () => { + q('result').textContent = 'rolling out…'; + pitApi + .rollout(adminSecret, { version: pack.version, notes: q('notes').value.trim() || undefined, hard: q('hard').checked }) + .then(() => (q('result').textContent = `rolling out ${pack.name}: every room freezes, then resumes on it`)) + .catch((error: unknown) => (q('result').textContent = String(error))); + }); + q('packs').append(button); + } +} + +function div(className: string, parent: HTMLElement): HTMLDivElement { + const d = document.createElement('div'); + d.className = className; + parent.append(d); + return d; +} + +// ---- rooms: minimap from the zone status read model, toasts, debug ---- +const roomsPanel = div('pit-rooms', document.body); +roomsPanel.innerHTML = `

    Rooms

    + +
    ■ active ■ dormant ■ asleep ■ never ran ┄ watched □ kept awake ▲ you ● players ● mobs
    +
    `; +const roomsMap = roomsPanel.querySelector('canvas') as HTMLCanvasElement; +const roomsField = (k: string) => roomsPanel.querySelector(`[data-k="${k}"]`) as HTMLElement; +const toasts = div('pit-toasts', topStack); +const rooms = new Map(); +let roomInfo: RoomInfo | undefined; +/** Recent room info samples (one activation), for the dropped-tick rate. */ +const tickSamples: { at: number; activation: string; dropped: number }[] = []; +/** Window of the overlay's dropped-tick count. */ +const DROP_WINDOW_MS = 30_000; +const STATUS_COLOR: Record = { active: '#4caf50', dormant: '#f2c94c', hibernated: '#6c7aa0' }; +const BIOME_COLOR = ['#8a8f99', '#c9a86a', '#3f7d4e', '#7fbf6a']; + +function toast(text: string): void { + const t = div('pit-toast', toasts); + t.textContent = text; + setTimeout(() => t.remove(), 5000); +} + +async function pollRooms(): Promise { + for (;;) { + try { + const { rooms: rows } = await pitApi.rooms(); + for (const row of rows) { + const before = rooms.get(row.zone); + if (before !== undefined && before.status !== row.status) { + if (row.status === 'active' && row.restored && row.activations > before.activations) { + toast(`${row.zone} woke up from hibernation — its mobs are back`); + } else if (row.status === 'hibernated') { + toast(`${row.zone} went to sleep (snapshot in celld storage)`); + } + } + rooms.set(row.zone, row); + } + } catch { + // The services restarting: keep the last view. + } + await new Promise((r) => setTimeout(r, 500)); + } +} +void pollRooms(); + +async function pollRoomInfo(): Promise { + for (;;) { + const here = pit.room(); + if (debug && here !== undefined) { + roomInfo = await pitApi.roomInfo(here).catch(() => roomInfo); + if (roomInfo !== undefined && roomInfo.zone === here) { + const now = performance.now(); + const last = tickSamples.at(-1); + if (last !== undefined && last.activation !== `${roomInfo.zone}/${roomInfo.activation}`) tickSamples.length = 0; + tickSamples.push({ at: now, activation: `${roomInfo.zone}/${roomInfo.activation}`, dropped: roomInfo.droppedTicks }); + while (tickSamples.length > 1 && now - tickSamples[0]!.at > DROP_WINDOW_MS) tickSamples.shift(); + } + } + await new Promise((r) => setTimeout(r, 1000)); + } +} +void pollRoomInfo(); + +let tiers: TiersAround | undefined; +async function pollTiers(): Promise { + for (;;) { + const here = pit.room(); + if (here !== undefined) tiers = await pitApi.tiers(here).catch(() => tiers); + await new Promise((r) => setTimeout(r, 2000)); + } +} +void pollTiers(); + +/** A dot on the minimap, in world metres (room (x, y) is centred on (x, y) × ROOM_SIZE). */ +type MiniDot = { wx: number; wy: number; kind: 'me' | 'player' | 'mob'; tier: number; face: number; dead: boolean }; +const miniDots: MiniDot[] = []; +let miniMe: MiniDot | undefined; +/** Metres across the minimap; the mouse wheel zooms. */ +let miniSpanM = 4 * ROOM_SIZE; +roomsMap.addEventListener( + 'wheel', + (event) => { + event.preventDefault(); + miniSpanM = Math.min(12 * ROOM_SIZE, Math.max(1.5 * ROOM_SIZE, miniSpanM * Math.exp(event.deltaY * 0.0015))); + }, + { passive: false } +); +type Box = { x0: number; y0: number; x1: number; y1: number }; +type MiniLayout = { biome: number; obstacles: { x: number; y: number; r: number }[]; ramps: readonly Ramp[]; holes: readonly Box[]; platforms: readonly Platform[]; open: number }; +const roomLayouts = new Map(); +function roomLayout(seed: number, x: number, y: number): MiniLayout | undefined { + if (!pit.pures.loaded()) return undefined; + const key = `${seed}:${x}:${y}`; + let layout = roomLayouts.get(key); + if (layout === undefined) { + const room = pit.pures.pitRoom({ seed, x, y }); + layout = { biome: room.biome, obstacles: room.obstacles.map(({ x, y, r }) => ({ x, y, r })), ramps: room.ramps, holes: room.holes, platforms: room.platforms, open: room.open }; + if (roomLayouts.size > 400) roomLayouts.clear(); + roomLayouts.set(key, layout); + } + return layout; +} +const mod = (n: number, m: number) => ((n % m) + m) % m; + +/** + * The minimap: a top-down map that follows you every frame. Rooms show their + * biome floor, walls with doorway gaps and obstacles; the room's state (zone + * status read model) is the tile's border; you, other players and mobs are + * dots at their live positions (your room and the watched rooms next door). + * A watched neighbour has a dashed cyan border; one you keep awake + * (proximity wake) a solid one. + */ +function drawRooms(): void { + const ctx = roomsMap.getContext('2d'); + const here = parseRoom(pit.room() ?? DEFAULT_ZONE); + if (ctx === null || here === undefined) return; + const { width, height } = roomsMap; + const s = width / miniSpanM; + // Centre on you (between frames of a handoff: your room's centre). + const cx = miniMe?.wx ?? here[0] * ROOM_SIZE; + const cy = miniMe?.wy ?? here[1] * ROOM_SIZE; + const toMap = (wx: number, wy: number): [number, number] => [width / 2 + (wx - cx) * s, height / 2 - (wy - cy) * s]; + ctx.fillStyle = '#0b0d12'; + ctx.fillRect(0, 0, width, height); + const seed = pit.hello()?.seed ?? PIT_WORLD.defaultSeed; + const reach = Math.ceil(miniSpanM / ROOM_SIZE / 2) + 1; + const rx0 = Math.round(cx / ROOM_SIZE); + const ry0 = Math.round(cy / ROOM_SIZE); + const door = PIT_WORLD.doorHalf; + // Node names only say something when the rooms run on more than one node. + const manyNodes = new Set([...rooms.values()].map((r) => r.node).filter((n) => n !== '')).size > 1; + ctx.font = '10px monospace'; + for (let ry = ry0 - reach; ry <= ry0 + reach; ry++) { + for (let rx = rx0 - reach; rx <= rx0 + reach; rx++) { + const zone = roomZone(rx, ry); + const row = rooms.get(zone); + const layout = roomLayout(seed, rx, ry); + const [x0, y0] = toMap(rx * ROOM_SIZE - HALF, ry * ROOM_SIZE + HALF); + const size = HALF * 2 * s; + // Floor: biome colour, dimmer for rooms that never ran. + ctx.fillStyle = `${BIOME_COLOR[layout?.biome ?? 0] ?? '#333'}${row === undefined ? '33' : '66'}`; + ctx.fillRect(x0, y0, size, size); + // Obstacles. + if (layout !== undefined && s > 0.6) { + ctx.fillStyle = '#0b0d12aa'; + for (const o of layout.obstacles) { + const [ox, oy] = toMap(rx * ROOM_SIZE + o.x, ry * ROOM_SIZE + o.y); + ctx.beginPath(); + ctx.arc(ox, oy, Math.max(1, o.r * s), 0, Math.PI * 2); + ctx.fill(); + } + } + // Ramps: their footprint, red when too steep to walk. + if (layout !== undefined && s > 0.6) { + for (const r of layout.ramps) { + const [ax, ay] = toMap(rx * ROOM_SIZE + r.x0, ry * ROOM_SIZE + r.y1); + ctx.fillStyle = r.degrees <= 45 ? '#c9c2b088' : '#d0703f99'; + ctx.fillRect(ax, ay, (r.x1 - r.x0) * s, (r.y1 - r.y0) * s); + } + // Holes black, then platforms and stepping stones over them. + const box = (b: Box, fill: string) => { + const [ax, ay] = toMap(rx * ROOM_SIZE + b.x0, ry * ROOM_SIZE + b.y1); + ctx.fillStyle = fill; + ctx.fillRect(ax, ay, (b.x1 - b.x0) * s, (b.y1 - b.y0) * s); + }; + for (const h of layout.holes) box(h, '#000000ee'); + for (const p of layout.platforms) box(p, p.height > 0 ? '#b8a88caa' : '#8c7f6acc'); + } + // Walls with a doorway gap in the middle of each. + ctx.strokeStyle = '#9aa3b2'; + ctx.lineWidth = 1; + const wall = (ax: number, ay: number, bx: number, by: number) => { + ctx.beginPath(); + ctx.moveTo(...toMap(rx * ROOM_SIZE + ax, ry * ROOM_SIZE + ay)); + ctx.lineTo(...toMap(rx * ROOM_SIZE + bx, ry * ROOM_SIZE + by)); + ctx.stroke(); + }; + // Open sides (no wall) are left out. + const open = layout?.open ?? 0; + for (const sign of [-1, 1]) { + if ((open & (sign > 0 ? 4 : 8)) === 0) { + wall(-HALF, sign * HALF, -door, sign * HALF); + wall(door, sign * HALF, HALF, sign * HALF); + } + if ((open & (sign > 0 ? 1 : 2)) === 0) { + wall(sign * HALF, -HALF, sign * HALF, -door); + wall(sign * HALF, door, sign * HALF, HALF); + } + } + // Room state as the tile's inner border. + const status = row === undefined ? undefined : STATUS_COLOR[row.status]; + if (status !== undefined) { + ctx.strokeStyle = status; + ctx.lineWidth = 2; + ctx.strokeRect(x0 + 3, y0 + 3, size - 6, size - 6); + } + const watched = pit.neighbours().get(zone); + if (pit.near().has(zone)) { + ctx.strokeStyle = '#4dd0e1'; + ctx.lineWidth = 2; + ctx.strokeRect(x0 + 6, y0 + 6, size - 12, size - 12); + } else if (watched === 'watching' && !(rx === here[0] && ry === here[1])) { + ctx.strokeStyle = '#4dd0e1'; + ctx.lineWidth = 1; + ctx.setLineDash([3, 3]); + ctx.strokeRect(x0 + 6, y0 + 6, size - 12, size - 12); + ctx.setLineDash([]); + } + if (size > 36) { + ctx.fillStyle = '#e6e9ef'; + if (row !== undefined && row.players > 0) ctx.fillText(`${row.players}p`, x0 + 6, y0 + 14); + if (debug && manyNodes && row !== undefined && row.node !== '') ctx.fillText(row.node.replace(/^(celld-|node-)/, ''), x0 + 6, y0 + size - 6); + } + // Boss rooms: a red mark (grey while the boss is down) and the hood's tier. + const hood = tiers?.hoods.find((h) => h.bossRoom[0] === rx && h.bossRoom[1] === ry); + if (hood !== undefined) { + const [bx, by] = toMap(rx * ROOM_SIZE, ry * ROOM_SIZE); + ctx.fillStyle = hood.bossDown ? '#777' : '#ff2d55'; + ctx.beginPath(); + ctx.arc(bx, by, Math.max(4, 3 * s), 0, Math.PI * 2); + ctx.fill(); + ctx.fillStyle = '#fff'; + ctx.fillText(`T${hood.tier}`, bx + 7, by - 5); + } + } + } + // Hood (3 × 3 rooms) and borough (9 × 9) borders: the left / bottom wall of + // every room whose index is a multiple of 3 (9). + for (let r = rx0 - reach; r <= rx0 + reach; r++) { + if (mod(r, 3) !== 0) continue; + const borough = mod(r, 9) === 0; + const [x] = toMap(r * ROOM_SIZE - HALF, 0); + ctx.strokeStyle = borough ? '#ffd166' : '#8a6dd1'; + ctx.lineWidth = borough ? 2.5 : 1.25; + ctx.beginPath(); + ctx.moveTo(x, 0); + ctx.lineTo(x, height); + ctx.stroke(); + } + for (let r = ry0 - reach; r <= ry0 + reach; r++) { + if (mod(r, 3) !== 0) continue; + const borough = mod(r, 9) === 0; + const [, y] = toMap(0, r * ROOM_SIZE - HALF); + ctx.strokeStyle = borough ? '#ffd166' : '#8a6dd1'; + ctx.lineWidth = borough ? 2.5 : 1.25; + ctx.beginPath(); + ctx.moveTo(0, y); + ctx.lineTo(width, y); + ctx.stroke(); + } + // Your interest ring. + const viewRadius = pit.hello()?.viewRadius; + if (miniMe !== undefined && viewRadius !== undefined) { + ctx.strokeStyle = '#ffffff22'; + ctx.lineWidth = 1; + ctx.beginPath(); + ctx.arc(width / 2, height / 2, viewRadius * s, 0, Math.PI * 2); + ctx.stroke(); + } + // Mobs, other players, then you on top. + for (const d of miniDots) { + const [x, y] = toMap(d.wx, d.wy); + if (x < -4 || y < -4 || x > width + 4 || y > height + 4) continue; + ctx.fillStyle = d.kind === 'mob' ? (d.tier >= 4 ? '#ff2d55' : '#ff8a65') : d.dead ? '#666' : '#64b5f6'; + ctx.beginPath(); + ctx.arc(x, y, d.kind === 'mob' ? (d.tier >= 4 ? 3.5 : 2) : 3, 0, Math.PI * 2); + ctx.fill(); + } + if (miniMe !== undefined) { + const [x, y] = toMap(miniMe.wx, miniMe.wy); + const f = miniMe.face; + const tip = (a: number, r: number): [number, number] => [x + Math.cos(f + a) * r, y - Math.sin(f + a) * r]; + ctx.fillStyle = miniMe.dead ? '#888' : '#ffffff'; + ctx.strokeStyle = '#0b0d12'; + ctx.lineWidth = 1.5; + ctx.beginPath(); + ctx.moveTo(...tip(0, 8)); + ctx.lineTo(...tip(2.5, 5)); + ctx.lineTo(...tip(-2.5, 5)); + ctx.closePath(); + ctx.stroke(); + ctx.fill(); + } +} + +function renderDebug(): void { + const el = roomsField('debug'); + roomsField('here').textContent = pit.room() ?? ''; + if (!debug) { + el.textContent = ''; + return; + } + const info = roomInfo; + if (info === undefined || info.zone !== pit.room()) { + el.textContent = 'room object: …'; + return; + } + const node = info.node === '' ? 'unknown (celld does not tell code its node; set CELLD_ZONE_NODES)' : info.node; + el.innerHTML = `celld object ${info.zone}
    node ${node}
    isolate ${info.isolate} · activation ${info.activation}` + + `
    wakes ${info.wakes} · ${info.restored ? 'restored from snapshot' : 'fresh'} · ${info.players} players` + + `
    tick ${info.hz} Hz · late p50 ${info.lateMs.p50.toFixed(1)} / p99 ${info.lateMs.p99.toFixed(1)} ms` + + `
    ${tickHealth(info)}`; +} + +/** + * Dropped ticks over the last ~30 s: a room on a degraded celld state shows + * a rising count (and a late p99 in the hundreds of ms) before play feels + * it. Red past 1 % of the window's ticks. + */ +function tickHealth(info: RoomInfo): string { + const first = tickSamples[0]; + const last = tickSamples.at(-1); + if (first === undefined || last === undefined || last.at - first.at < 2000) { + return `dropped ticks ${info.droppedTicks} (measuring…)`; + } + const span = last.at - first.at; + const recent = last.dropped - first.dropped; + const bad = recent > (info.hz * span) / 1000 / 100 || info.lateMs.p99 > 50; + const color = bad ? '#ff6b6b' : '#7bd88f'; + return `dropped ticks ${recent} in ${Math.round(span / 1000)} s · ${info.droppedTicks} this activation`; +} + +// ---- materials and templates ---- +const mats = { + me: material(scene, 'me', '#6cc4ff'), + other: material(scene, 'other', '#f2a65a'), + dead: material(scene, 'dead', '#555555', 0.4), + pillar: material(scene, 'pillar', '#5d5566'), + blade: material(scene, 'blade', '#e8eef7'), + swing: material(scene, 'swing', '#4da3ff', 0.3), + hpBack: material(scene, 'hp-back', '#1b1b1b'), + hpFill: material(scene, 'hp-fill', '#e04848'), + playerHpFill: material(scene, 'player-hp-fill', '#4caf50'), + tele: material(scene, 'tele', '#ff3b3b', 0.25), + teleFill: material(scene, 'tele-fill', '#ff3b3b', 0.45), + ghost: material(scene, 'ghost', '#ffffff', 0.25) +}; +mats.ghost.wireframe = true; +for (const m of [mats.swing, mats.tele, mats.teleFill, mats.hpFill, mats.playerHpFill]) m.emissiveColor = m.diffuseColor.clone(); +// Slam warnings lie on the floor: both faces, drawn over it where they meet +// (the floor's triangles and the room's bilinear ground differ by a few cm). +for (const m of [mats.tele, mats.teleFill]) { + m.backFaceCulling = false; + m.zOffset = -2; +} +mats.blade.emissiveColor = new Color3(0.6, 0.6, 0.7); +const tierMats = new Map(); +for (const [tier, t] of Object.entries(TIERS)) tierMats.set(Number(tier), material(scene, `mob-${tier}`, t.color)); +// The content pack this client runs tints the mobs (its own pack: an old +// client keeps drawing the old one). +let tintedFor: string | undefined; +function tintMobs(pack: ContentPack): void { + if (tintedFor === pack.version) return; + tintedFor = pack.version; + const tint = Color3.FromHexString(`#${pack.tint.toString(16).padStart(6, '0')}`); + for (const [tier, t] of Object.entries(TIERS)) { + const base = Color3.FromHexString(t.color); + tierMats.get(Number(tier))!.diffuseColor = pack.tint === 0 ? base : Color3.Lerp(base, tint, 0.6); + } +} + +// ---- the world: rooms at fixed places, floating origin at your room ---- +// The stage's single floor and walls give way to one chunk per room. +for (const mesh of [...scene.meshes]) if (mesh.name === 'floor' || mesh.name === 'wall') mesh.dispose(); +type Room = readonly [number, number]; +let origin: Room = parseRoom(forcedZone ?? DEFAULT_ZONE) ?? [0, 0]; + +/** Scene position of a room-local point of room `room`. */ +function place(room: Room, x: number, y: number, height = 0): Vector3 { + return new Vector3((room[0] - origin[0]) * ROOM_SIZE + x, height, (room[1] - origin[1]) * ROOM_SIZE + y); +} + +/** Scene position of a room-local point of zone `zoneId` (the origin room if it is not a room). */ +function placeIn(zoneId: string, x: number, y: number, height = 0): Vector3 { + return place(parseRoom(zoneId) ?? origin, x, y, height); +} + +// ---- level of detail ---- +// Round props and the bigger mobs come in three levels, about 100 %, 30 % +// and 10 % of the full level's triangles; an object's level follows its +// distance from the camera, past LOD_AT[0] the middle one, past LOD_AT[1] +// the coarsest. Around each threshold a 10 % band (±5 %): a coarser level +// only past T × 1.05, a finer one only inside T × 0.95, so an object +// standing near a threshold does not flicker between levels. +const LOD_AT = [18, 45]; +const LOD_BAND = 0.05; +type Lod = { node: TransformNode; levels: readonly AbstractMesh[]; level: number }; +/** Three template meshes of one shape (level 0 the finest), hidden: objects are instances of them. */ +function lodTemplates(name: string, mat: StandardMaterial, make: (name: string, level: 0 | 1 | 2) => Mesh): Mesh[] { + return ([0, 1, 2] as const).map((l) => { + const mesh = make(`${name}-lod${l}`, l); + mesh.material = mat; + mesh.isPickable = false; + mesh.setEnabled(false); + return mesh; + }); +} +/** An object of `templates` (one instance per level under `node`; the finest shown). */ +function lodOf(node: TransformNode, templates: readonly Mesh[]): Lod { + const levels = templates.map((t, l) => { + const instance = t.createInstance(`${node.name}-lod${l}`); + instance.parent = node; + instance.isPickable = false; + instance.setEnabled(l === 0); + return instance; + }); + return { node, levels, level: 0 }; +} +/** The level for distance `d` (m) from `level`, with the band round each threshold. */ +function lodLevel(level: number, d: number, count: number): number { + let l = level; + while (l < count - 1 && d > LOD_AT[l]! * (1 + LOD_BAND)) l += 1; + while (l > 0 && d < LOD_AT[l - 1]! * (1 - LOD_BAND)) l -= 1; + return l; +} +/** Objects per level this frame (for the HUD). */ +const lodCounts = [0, 0, 0]; +function applyLod(lod: Lod, eye: Vector3): void { + const want = lodOn ? lodLevel(lod.level, Vector3.Distance(eye, lod.node.getAbsolutePosition()), lod.levels.length) : 0; + lodCounts[want] = (lodCounts[want] ?? 0) + 1; + if (want === lod.level) return; + lod.levels[lod.level]!.setEnabled(false); + lod.levels[want]!.setEnabled(true); + lod.level = want; +} + +/** Room templates, instanced per room: floor per biome, wall segment, doorway gate, pillar. */ +const templates = (() => { + const px = 1024; + const texture = new DynamicTexture('room-grid', { width: px, height: px }, scene, true); + const ctx = texture.getContext() as CanvasRenderingContext2D; + ctx.fillStyle = '#ffffff'; + ctx.fillRect(0, 0, px, px); + const lines = HALF * 2; + for (let i = 0; i <= lines; i += 1) { + const p = (i / lines) * px; + ctx.strokeStyle = i % 5 === 0 ? '#9aa0aa' : '#c8ccd2'; + ctx.lineWidth = i % 5 === 0 ? 3 : 1.5; + ctx.beginPath(); + ctx.moveTo(p, 0); + ctx.lineTo(p, px); + ctx.moveTo(0, p); + ctx.lineTo(px, p); + ctx.stroke(); + } + texture.update(); + const floors = BIOME_COLOR.map((color, biome) => { + const m = material(scene, `floor-${biome}`, color); + m.diffuseTexture = texture; + m.diffuseColor = Color3.FromHexString(color).scale(0.42); + m.specularColor = Color3.Black(); + const ground = MeshBuilder.CreateGround(`floor-${biome}`, { width: HALF * 2, height: HALF * 2 }, scene); + ground.material = m; + ground.isPickable = false; + ground.setEnabled(false); + return ground; + }); + const wallMat = material(scene, 'room-wall', '#4b5668'); + const segment = HALF - PIT_WORLD.doorHalf; + const wall = MeshBuilder.CreateBox('room-wall', { width: segment, depth: WALL_T, height: WALL_H }, scene); + wall.material = wallMat; + wall.isPickable = false; + wall.setEnabled(false); + const doorMat = material(scene, 'door', '#4dd0e1', 0.55); + doorMat.emissiveColor = Color3.FromHexString('#4dd0e1'); + const gate = MeshBuilder.CreateBox('door', { width: PIT_WORLD.doorHalf * 2, depth: 0.3, height: 0.08 }, scene); + gate.material = doorMat; + gate.isPickable = false; + gate.setEnabled(false); + // Columns, boulders and trees have three levels of detail (LOD_DETAIL). + const pillar = lodTemplates('room-pillar', mats.pillar, (name, l) => + MeshBuilder.CreateCylinder(name, { diameter: 1, height: 2.4, tessellation: [40, 12, 4][l] }, scene) + ); + // Obstacle looks of the seeded layouts: 0 column · 1 boulder · 2 tree · 3 crystal. + const boulder = lodTemplates('room-boulder', material(scene, 'boulder', '#6e6a62'), (name, l) => + MeshBuilder.CreateSphere(name, { diameter: 1, segments: [16, 8, 4][l] }, scene) + ); + const tree = lodTemplates('room-tree', material(scene, 'tree', '#2f6b3a'), (name, l) => + MeshBuilder.CreateCylinder(name, { diameterTop: 0, diameterBottom: 1.6, height: 3.2, tessellation: [40, 12, 4][l] }, scene) + ); + const crystalMat = material(scene, 'crystal', '#7fe3ff', 0.85); + crystalMat.emissiveColor = Color3.FromHexString('#2a6f88'); + const crystal = MeshBuilder.CreateBox('room-crystal', { size: 1 }, scene); + crystal.material = crystalMat; + crystal.isPickable = false; + crystal.setEnabled(false); + // Walls take the biome's tone. + const walls = BIOME_COLOR.map((color, biome) => { + const w = wall.clone(`room-wall-${biome}`); + w.material = material(scene, `room-wall-${biome}`, Color3.FromHexString(color).scale(0.55).toHexString()); + w.setEnabled(false); + return w; + }); + // Ramps: stone you can walk up; rust-red where it is too steep (over + // about 45°, `walkable` in the room) and you slide off. + const rampMats = { + walk: material(scene, 'ramp-walk', '#9a9384'), + steep: material(scene, 'ramp-steep', '#b5653b') + }; + for (const m of Object.values(rampMats)) { + m.backFaceCulling = false; + m.specularColor = Color3.Black(); + } + // Holes: an open-topped dark shaft (inside faces only), scaled per hole. + const shaft = MeshBuilder.CreateBox('room-hole', { size: 1, sideOrientation: Mesh.BACKSIDE }, scene); + const shaftMat = material(scene, 'room-hole', '#07050a'); + shaftMat.specularColor = Color3.Black(); + shaft.material = shaftMat; + shaft.isPickable = false; + shaft.setEnabled(false); + // Platforms: boxes to jump onto; stepping stones are columns rising out of a hole. + const platform = MeshBuilder.CreateBox('room-platform', { size: 1 }, scene); + platform.material = material(scene, 'room-platform', '#8c7f6a'); + platform.isPickable = false; + platform.setEnabled(false); + return { floors, wall, walls, segment, gate, pillar, boulder, tree, crystal, rampMats, shaft, platform }; +})(); + +/** Each built room's terrain, for standing mobs on it. */ +const terrains = new Map(); + +/** Whether terrain sample `h` lies over a hole (`TERRAIN_HOLE`, -1000). */ +const isHole = (h: number) => h < -100; + +/** Terrain height at room-local `(x, y)` of zone `zoneId` (bilinear; 0 off the terrain or over a hole). */ +function groundAt(zoneId: string, x: number, y: number): number { + const t = terrains.get(zoneId); + if (t === undefined) return 0; + const fx = (x - t.minX) / t.cell; + const fy = (y - t.minY) / t.cell; + const i = Math.floor(fx); + const j = Math.floor(fy); + if (i < 0 || j < 0 || i + 1 >= t.nx || j + 1 >= t.ny) return 0; + const at = (a: number, b: number) => t.heights[b * t.nx + a]!; + const c = [at(i, j), at(i + 1, j), at(i, j + 1), at(i + 1, j + 1)]; + if (c.some(isHole)) return 0; + const u = fx - i; + const v = fy - j; + return (c[0]! * (1 - u) + c[1]! * u) * (1 - v) + (c[2]! * (1 - u) + c[3]! * u) * v; +} + +/** A room's ground as one mesh (room-local, scene axes: x, up, y): cells touching a hole are left open. */ +function terrainMesh(name: string, t: RoomTerrain, biome: number): Mesh { + const positions: number[] = []; + const uvs: number[] = []; + const indices: number[] = []; + for (let j = 0; j < t.ny; j += 1) { + for (let i = 0; i < t.nx; i += 1) { + const x = t.minX + i * t.cell; + const y = t.minY + j * t.cell; + const h = t.heights[j * t.nx + i]!; + positions.push(x, isHole(h) ? 0 : h, y); + uvs.push(x / (HALF * 2) + 0.5, y / (HALF * 2) + 0.5); + } + } + for (let j = 0; j + 1 < t.ny; j += 1) { + for (let i = 0; i + 1 < t.nx; i += 1) { + const a = j * t.nx + i; + const corners = [a, a + 1, a + t.nx, a + t.nx + 1]; + if (corners.some((k) => isHole(t.heights[k]!))) continue; + // Same winding as the ramps' top (front faces up, normals up). + indices.push(a, a + 1, a + t.nx + 1, a, a + t.nx + 1, a + t.nx); + } + } + const data = new VertexData(); + data.positions = positions; + data.indices = indices; + data.uvs = uvs; + const normals: number[] = []; + VertexData.ComputeNormals(positions, indices, normals); + data.normals = normals; + const mesh = new Mesh(name, scene); + data.applyToMesh(mesh); + mesh.material = templates.floors[biome]?.material ?? null; + mesh.isPickable = false; + return mesh; +} + +/** One ramp of a room as a wedge mesh (room-local, scene axes: x, up, y). */ +function rampMesh(name: string, r: Ramp): Mesh { + // Corner heights: 0 on the low edge, `height` on the high one. + const corners: [number, number][] = [ + [r.x0, r.y0], + [r.x1, r.y0], + [r.x1, r.y1], + [r.x0, r.y1] + ]; + const top = ([x, y]: [number, number]) => { + const high = r.uphill === 0 ? x === r.x1 : r.uphill === 1 ? x === r.x0 : r.uphill === 2 ? y === r.y1 : y === r.y0; + return high ? r.height : 0; + }; + const positions: number[] = []; + const indices: number[] = []; + const quad = (a: number[], b: number[], c: number[], d: number[]) => { + const base = positions.length / 3; + positions.push(...a, ...b, ...c, ...d); + indices.push(base, base + 1, base + 2, base, base + 2, base + 3); + }; + const up = corners.map((c) => [c[0], top(c), c[1]]); + const down = corners.map((c) => [c[0], 0, c[1]]); + quad(up[0]!, up[1]!, up[2]!, up[3]!); + for (let i = 0; i < 4; i += 1) { + const j = (i + 1) % 4; + quad(down[i]!, down[j]!, up[j]!, up[i]!); + } + const data = new VertexData(); + data.positions = positions; + data.indices = indices; + const normals: number[] = []; + VertexData.ComputeNormals(positions, indices, normals); + data.normals = normals; + const mesh = new Mesh(name, scene); + data.applyToMesh(mesh); + mesh.material = r.degrees <= 45 ? templates.rampMats.walk : templates.rampMats.steep; + mesh.isPickable = false; + return mesh; +} + +type Chunk = { room: Room; node: TransformNode; biome: number | undefined; seed: number; lods: Lod[] }; +const chunks = new Map(); + +/** One room's static geometry under a node at the room's centre. */ +function createChunk(room: Room): Chunk { + const key = roomZone(room[0], room[1]); + const node = new TransformNode(`room-${key}`, scene); + const seed = pit.hello()?.seed ?? PIT_WORLD.defaultSeed; + const biome = pit.pures.loaded() ? pit.pures.pitRoom({ seed, x: room[0], y: room[1] }).biome : undefined; + const addAt = (mesh: Mesh, name: string, x: number, y: number, height: number, turn = 0) => { + const instance = mesh.createInstance(`${key}-${name}`); + instance.parent = node; + instance.position.set(x, height, y); + instance.rotation.y = turn; + instance.isPickable = false; + return instance; + }; + const add = addAt; + const layout = pit.pures.loaded() ? pit.pures.pitRoom({ seed, x: room[0], y: room[1] }) : undefined; + if (layout !== undefined && biome !== undefined) { + const terrain = pit.pures.terrain({ seed, x: room[0], y: room[1] }); + terrains.set(key, terrain); + terrainMesh(`${key}-terrain`, terrain, biome).parent = node; + // Each hole: a shaft 4 m deep (falling past 2 m kills). + layout.holes.forEach((h, i) => { + const instance = add(templates.shaft, `hole-${i}`, (h.x0 + h.x1) / 2, (h.y0 + h.y1) / 2, -2); + instance.scaling.set(h.x1 - h.x0, 4, h.y1 - h.y0); + }); + // Platforms; a stepping stone (height 0) is a column from the bottom of its hole up to the floor. + layout.platforms.forEach((p, i) => { + const bottom = p.height > 0 ? 0 : -4; + const top = p.height > 0 ? p.height : 0; + const instance = add(templates.platform, `platform-${i}`, (p.x0 + p.x1) / 2, (p.y0 + p.y1) / 2, (bottom + top) / 2); + instance.scaling.set(p.x1 - p.x0, top - bottom, p.y1 - p.y0); + }); + } else { + terrains.delete(key); + add(templates.floors[biome ?? 0]!, 'floor', 0, 0, 0); + } + // Each wall: two segments either side of its doorway gap, just outside + // the floor (the neighbour's wall stands right behind it). + const off = PIT_WORLD.doorHalf + templates.segment / 2; + const out = HALF + WALL_T / 2; + const wall = templates.walls[biome ?? 0] ?? templates.wall; + // An open side (no wall, crossed anywhere) has neither wall nor door + // gate; the corner posts always stand. + const open = layout?.open ?? 0; + for (const side of [-1, 1]) { + const openH = (open & (side > 0 ? 4 : 8)) !== 0; + const openV = (open & (side > 0 ? 1 : 2)) !== 0; + for (const along of [-1, 1]) { + if (!openH) add(wall, `wall-h${side}${along}`, along * off, side * out, WALL_H / 2); + if (!openV) add(wall, `wall-v${side}${along}`, side * out, along * off, WALL_H / 2, Math.PI / 2); + const post = add(wall, `post-${side}${along}`, side * out, along * out, WALL_H / 2); + post.scaling.set(WALL_T / templates.segment, 1, 1); + } + if (!openH) add(templates.gate, `door-h${side}`, 0, side * HALF, 0.04); + if (!openV) add(templates.gate, `door-v${side}`, side * HALF, 0, 0.04, Math.PI / 2); + } + const lods: Lod[] = []; + // The room's seeded obstacles (what the step collides with). + const obstacles = pit.pures.loaded() ? pit.pures.pitRoom({ seed, x: room[0], y: room[1] }).obstacles : PILLARS.map((p) => ({ ...p, look: 0 })); + obstacles.forEach(({ x, y, r, look }, i) => { + // Each stands on the level patch the terrain leaves it (on a hill, not in it). + const base = groundAt(key, x, y); + const add = (mesh: Mesh, name: string, x: number, y: number, height: number) => addAt(mesh, name, x, y, base + height); + // A three-level prop: a node at its place, its levels under it. + const addLod = (levels: readonly Mesh[], name: string, x: number, y: number, height: number) => { + const prop = new TransformNode(`${key}-${name}`, scene); + prop.parent = node; + prop.position.set(x, base + height, y); + lods.push(lodOf(prop, levels)); + return prop; + }; + if (look === 1) { + const instance = addLod(templates.boulder, `obstacle-${i}`, x, y, r * 0.55); + instance.scaling.set(r * 2, r * 1.3, r * 2); + } else if (look === 2) { + const instance = addLod(templates.tree, `obstacle-${i}`, x, y, 1.6); + instance.scaling.set(r * 1.25, 1, r * 1.25); + } else if (look === 3) { + const instance = add(templates.crystal, `obstacle-${i}`, x, y, r); + instance.scaling.set(r * 1.4, r * 2, r * 1.4); + instance.rotation.y = 0.6; + } else { + const instance = addLod(templates.pillar, `pillar-${i}`, x, y, 1.2); + instance.scaling.set(r * 2, 1, r * 2); + } + }); + // Its sloped ramps (what the step walks on and the laser bounces off). + const ramps = pit.pures.loaded() ? pit.pures.pitRoom({ seed, x: room[0], y: room[1] }).ramps : []; + ramps.forEach((r, i) => { + rampMesh(`${key}-ramp-${i}`, r).parent = node; + }); + return { room, node, biome, seed, lods }; +} + +/** Keep the rooms within `ROOM_VIEW` of the origin built and placed. */ +function syncChunks(): void { + const wanted = new Set(); + for (let dy = -ROOM_VIEW; dy <= ROOM_VIEW; dy += 1) { + for (let dx = -ROOM_VIEW; dx <= ROOM_VIEW; dx += 1) { + const room: Room = [origin[0] + dx, origin[1] + dy]; + const key = roomZone(room[0], room[1]); + wanted.add(key); + const chunk = chunks.get(key); + // Built before the world module loaded or the seed was known: rebuild. + const seed = pit.hello()?.seed ?? PIT_WORLD.defaultSeed; + if (chunk !== undefined && chunk.seed === seed && (chunk.biome !== undefined || !pit.pures.loaded())) continue; + chunk?.node.dispose(); + chunks.set(key, createChunk(room)); + } + } + for (const [key, chunk] of chunks) { + if (!wanted.has(key)) { + chunk.node.dispose(); + chunks.delete(key); + terrains.delete(key); + continue; + } + chunk.node.position.copyFrom(place(chunk.room, 0, 0)); + } +} + +/** Re-centre on `to` without a visible move: the camera shifts with the world. */ +function moveOrigin(to: Room): void { + if (to[0] === origin[0] && to[1] === origin[1]) return; + const shift = new Vector3((to[0] - origin[0]) * ROOM_SIZE, 0, (to[1] - origin[1]) * ROOM_SIZE); + origin = to; + stage.camera.setTarget(stage.camera.target.subtract(shift), false, false, true); + syncChunks(); +} +syncChunks(); +pit.pures.ready.then(syncChunks, () => undefined); +pit.on('hello', () => syncChunks()); + +// Doorway labels of your room: anchors at its doors (the origin room, so +// they never move), named after the room behind each. +const DOORS: { dx: number; dy: number }[] = [ + { dx: 1, dy: 0 }, + { dx: -1, dy: 0 }, + { dx: 0, dy: 1 }, + { dx: 0, dy: -1 } +]; +const doorAnchors = DOORS.map(({ dx, dy }, i) => { + const anchor = MeshBuilder.CreateBox(`door-anchor-${i}`, { size: 0.01 }, scene); + anchor.isVisible = false; + anchor.isPickable = false; + anchor.position.set(dx * HALF, 0.1, dy * HALF); + return anchor; +}); +let shownRoom = ''; + +function showRoom(zone: string): void { + const at = parseRoom(zone); + if (at === undefined || zone === shownRoom) return; + shownRoom = zone; + DOORS.forEach(({ dx, dy }, i) => { + stage.labels.set(`door-${i}`, doorAnchors[i]!, `→ ${roomZone(at[0] + dx, at[1] + dy)}`, 0.6, 'door'); + }); + const seed = pit.hello()?.seed ?? PIT_WORLD.defaultSeed; + if (pit.pures.loaded()) { + const room = pit.pures.pitRoom({ seed, x: at[0], y: at[1] }); + hud.row('Room', `${zone} · ${PIT_WORLD.biomes[room.biome] ?? '?'} · ${PATTERNS[room.pattern] ?? '?'} · danger ${room.danger} · ${room.mobs.length} mobs${room.boss ? ' · BOSS ROOM' : ''}`); + } +} + +// ---- network panel: server ghost and interest ring ---- +const ghost = MeshBuilder.CreateCapsule('ghost', { radius: PLAYER_RADIUS, height: 1.8 }, scene); +ghost.material = mats.ghost; +ghost.isPickable = false; +ghost.setEnabled(false); +/** Unit ring scaled to the room's interest radius (`hello.viewRadius`). */ +const interestRing = createRing(scene, 1, '#6cc4ff'); +interestRing.isPickable = false; +interestRing.setEnabled(false); + +type HpBar = { hpBack: Mesh; hpFill: Mesh; /** The fill drawn (eases to the health). */ hpShown: number }; +/** `culled`: off screen, every mesh disabled and nothing updated. */ +type Culled = { + culled: boolean; + /** Health share last frame (a drop is a hit); NaN until seen. */ + lastHp: number; + /** Hit stop: drawn frozen until then (performance.now ms). */ + stopUntil: number; +}; +type PlayerVisual = { kind: 'player'; body: Mesh; blade: Mesh; arc: Mesh; nose: Mesh } & HpBar & Culled; +/** + * `edge`: last seen near its room's side (it may be crossing); `slide`: it + * just came across from the room next door and glides from where its old + * room last drew it. + */ +type MobVisual = { + kind: 'mob'; + /** A mesh, or (the round tiers) a node over its levels of detail. */ + body: TransformNode; + lod?: Lod; + ring: Mesh; + fill: Mesh; + tier: number; + edge: boolean; + slide?: { from: Vector3; start: number }; + /** The floor its slam warning lies on (fetched when a windup starts there). */ + area?: SlamArea; +} & HpBar & + Culled; +type Visual = PlayerVisual | MobVisual; +const visuals = new Map(); + +function flatDisc(id: string, radius: number, mat: StandardMaterial, arc = 1): Mesh { + const disc = MeshBuilder.CreateDisc(id, { radius, arc, tessellation: 48, sideOrientation: Mesh.DOUBLESIDE }, scene); + disc.rotation.x = Math.PI / 2; + disc.material = mat; + disc.isPickable = false; + return disc; +} + +function createPlayer(entity: RenderedEntity, mine: boolean): PlayerVisual { + const body = MeshBuilder.CreateCapsule(entity.key, { radius: PLAYER_RADIUS, height: 1.8 }, scene); + body.material = mine ? mats.me : mats.other; + const nose = MeshBuilder.CreateBox(`${entity.key}-nose`, { width: 0.35, height: 0.15, depth: 0.2 }, scene); + nose.material = mats.blade; + const blade = MeshBuilder.CreateBox(`${entity.key}-blade`, { width: 1.6, height: 0.08, depth: 0.14 }, scene); + blade.material = mats.blade; + // Swing wedge: 120° (the server's cone), flat on the floor. + const arc = flatDisc(`${entity.key}-arc`, ATTACK_REACH, mats.swing, SWING_HALF / Math.PI); + return { kind: 'player', body, blade, arc, nose, culled: false, lastHp: Number.NaN, stopUntil: 0, ...hpBar(entity.key, mats.playerHpFill) }; +} + +// ---- slam warnings, draped on the floor ---- +// A mob's slam hits anyone within its reach standing on whatever floor is +// under them (terrain, ramp or platform top), as the room's `floor_at` +// says; the warning lies on that floor (the `floor_patch` pure, the room's +// own ground) instead of a flat disc that hills and ramps cut off. +const SLAM_RINGS = 6; +const SLAM_SEGMENTS = 32; +const SLAM_LIFT = 0.05; +type SlamArea = { zone: string; x: number; y: number; radius: number; heights: readonly number[] }; +function drapedDisc(id: string, mat: StandardMaterial): Mesh { + const mesh = new Mesh(id, scene); + const n = 1 + SLAM_RINGS * SLAM_SEGMENTS; + const index = (r: number, k: number) => (r === 0 ? 0 : 1 + (r - 1) * SLAM_SEGMENTS + (k % SLAM_SEGMENTS)); + const indices: number[] = []; + for (let k = 0; k < SLAM_SEGMENTS; k += 1) indices.push(0, index(1, k + 1), index(1, k)); + for (let r = 1; r < SLAM_RINGS; r += 1) { + for (let k = 0; k < SLAM_SEGMENTS; k += 1) { + indices.push(index(r, k), index(r, k + 1), index(r + 1, k + 1), index(r, k), index(r + 1, k + 1), index(r + 1, k)); + } + } + const data = new VertexData(); + data.positions = new Array(n * 3).fill(0); + data.normals = Array.from({ length: n * 3 }, (_, i) => (i % 3 === 1 ? 1 : 0)); + data.indices = indices; + data.applyToMesh(mesh, true); + mesh.material = mat; + mesh.isPickable = false; + // Its bounds change as it is draped: always considered for drawing. + mesh.alwaysSelectAsActiveMesh = true; + return mesh; +} +/** The floor under a slam of `radius` at room-local `(x, y)`: fetched once per spot. */ +function slamArea(visual: MobVisual, zone: string, x: number, y: number, radius: number): SlamArea { + const old = visual.area; + if (old !== undefined && old.zone === zone && old.radius === radius && Math.hypot(old.x - x, old.y - y) < 0.05) return old; + const room = parseRoom(zone); + const heights = + room !== undefined && pit.pures.loaded() + ? pit.pures.floorPatch({ seed: pit.hello()?.seed ?? PIT_WORLD.defaultSeed, roomX: room[0], roomY: room[1], x, y, radius, rings: SLAM_RINGS, segments: SLAM_SEGMENTS }) + : new Array(1 + SLAM_RINGS * SLAM_SEGMENTS).fill(groundAt(zone, x, y)); + visual.area = { zone, x, y, radius, heights }; + drape(visual.ring, visual.area, 1); + return visual.area; +} +/** + * Lay `mesh` (a `drapedDisc`) on `area` at `scale` of its radius: each + * ring's height is read along its ray from the area's rings. Over a hole + * it sinks in. + */ +function drape(mesh: Mesh, area: SlamArea, scale: number): void { + const at = (r: number, k: number) => area.heights[r === 0 ? 0 : 1 + (r - 1) * SLAM_SEGMENTS + k]!; + const height = (f: number, k: number) => { + const r = Math.min(Math.floor(f), SLAM_RINGS - 1); + const t = Math.min(f - r, 1); + const a = at(r, k); + const b = at(r + 1, k); + const ha = isHole(a) ? at(0, k) - 3 : a; + const hb = isHole(b) ? at(0, k) - 3 : b; + return ha + (hb - ha) * t + SLAM_LIFT; + }; + const positions = new Float32Array((1 + SLAM_RINGS * SLAM_SEGMENTS) * 3); + positions[1] = height(0, 0); + for (let r = 1; r <= SLAM_RINGS; r += 1) { + const f = r * scale; + const d = (area.radius * r * scale) / SLAM_RINGS; + for (let k = 0; k < SLAM_SEGMENTS; k += 1) { + const a = (Math.PI * 2 * k) / SLAM_SEGMENTS; + const i = (1 + (r - 1) * SLAM_SEGMENTS + k) * 3; + positions[i] = d * Math.cos(a); + positions[i + 1] = height(f, k); + positions[i + 2] = d * Math.sin(a); + } + } + mesh.updateVerticesData('position', positions); +} + +/** Three-level bodies of the round tiers (3: a spike, 4: the boss), made on first use. */ +const mobLods = new Map(); +function mobLodTemplates(tier: number): Mesh[] | undefined { + if (tier !== 3 && tier !== 4) return undefined; + let levels = mobLods.get(tier); + if (levels === undefined) { + const t = TIERS[tier]!; + const top = tier === 4 ? t.radius * 0.8 : 0; + const height = tier === 4 ? 2.8 : 2; + levels = lodTemplates(`mob-tier${tier}`, tierMats.get(tier) ?? mats.other, (name, l) => + MeshBuilder.CreateCylinder(name, { diameterTop: top, diameterBottom: t.radius * 2, height, tessellation: [40, 12, 4][l] }, scene) + ); + mobLods.set(tier, levels); + } + return levels; +} + +function createMob(entity: RenderedEntity): MobVisual { + const tier = mobFields(entity).tier || 1; + const t = TIERS[tier] ?? TIERS[1]!; + // The round tiers in three levels; a box (grunt, brute) cannot go lower. + const levels = mobLodTemplates(tier); + let body: TransformNode; + let lod: Lod | undefined; + if (levels !== undefined) { + body = new TransformNode(entity.key, scene); + lod = lodOf(body, levels); + } else { + const box = MeshBuilder.CreateBox(entity.key, { width: t.radius * 2, depth: t.radius * 2, height: tier === 2 ? 1.5 : 0.9 }, scene); + box.material = tierMats.get(tier) ?? mats.other; + body = box; + } + const ring = drapedDisc(`${entity.key}-tele`, mats.tele); + const fill = drapedDisc(`${entity.key}-tele-fill`, mats.teleFill); + return { kind: 'mob', body, lod, ring, fill, tier, edge: false, culled: false, lastHp: Number.NaN, stopUntil: 0, ...hpBar(entity.key, mats.hpFill) }; +} + +// ---- mobs crossing between rooms ---- +// A mob that follows a player across leaves its room (its entity goes) and +// arrives next door as a new entity a message later. Its mesh is held a +// moment where it vanished at a side; the newcomer of the same tier beside +// it takes the mesh over and glides into place: no blink, no hop. +const CROSS_HOLD_MS = 500; +const CROSS_SLIDE_MS = 150; +/** How near (m) a newcomer must be to a held mob to be it. */ +const CROSS_MATCH = 3; +const crossing = new Map(); +/** Mobs just killed (their entity goes too, but they are not crossing). */ +const killedAt = new Map(); +function adoptCrossing(entity: RenderedEntity): MobVisual | undefined { + const m = mobFields(entity); + const arriving = placeIn(entity.zoneId, m.x, m.y, 0); + for (const [key, held] of crossing) { + const at = held.visual.body.position; + if (held.visual.tier !== (m.tier || 1) || Math.hypot(at.x - arriving.x, at.z - arriving.z) > CROSS_MATCH) continue; + crossing.delete(key); + held.visual.slide = { from: at.clone(), start: performance.now() }; + return held.visual; + } + return undefined; +} + +function visualFor(entity: RenderedEntity, mine: boolean): Visual { + let visual = visuals.get(entity.key); + if (visual !== undefined) return visual; + if (isMob(entity)) { + visual = adoptCrossing(entity) ?? createMob(entity); + } else { + visual = createPlayer(entity, mine); + } + visuals.set(entity.key, visual); + return visual; +} + +function dispose(visual: Visual): void { + // (The bar's fill goes with its back, a body's levels with their node.) + for (const node of Object.values(visual)) if (node instanceof TransformNode && !node.isDisposed()) node.dispose(); +} + +const HP_W = 1.2; +const HP_FILL_W = 1.16; +/** + * A health bar over a head: a billboarded back with the fill as its child, + * just in front of it (never z-fighting with it) and anchored at its left + * edge, so it drains right to left. + */ +function hpBar(key: string, fillMat: StandardMaterial): HpBar { + const hpBack = MeshBuilder.CreatePlane(`${key}-hpb`, { width: HP_W, height: 0.14 }, scene); + hpBack.material = mats.hpBack; + hpBack.billboardMode = Mesh.BILLBOARDMODE_ALL; + hpBack.isPickable = false; + const hpFill = MeshBuilder.CreatePlane(`${key}-hpf`, { width: HP_FILL_W, height: 0.1 }, scene); + // Origin at the left edge: scaling x shortens it from the right. + hpFill.position.x = HP_FILL_W / 2; + hpFill.bakeCurrentTransformIntoVertices(); + hpFill.material = fillMat; + hpFill.isPickable = false; + hpFill.parent = hpBack; + // A plane faces -z; the billboard turns that toward the camera. + hpFill.position.set(-HP_FILL_W / 2, 0, -0.01); + return { hpBack, hpFill, hpShown: Number.NaN }; +} + +/** Place the bar at `at` and ease its fill toward `share` (0..1). */ +function showHp(bar: HpBar, at: Vector3, share: number, dtMs: number): void { + bar.hpBack.position.copyFrom(at); + const target = Math.max(0, Math.min(1, share)); + bar.hpShown = Number.isNaN(bar.hpShown) ? target : bar.hpShown + (target - bar.hpShown) * (1 - Math.exp(-dtMs / 90)); + if (Math.abs(target - bar.hpShown) < 1e-3) bar.hpShown = target; + bar.hpFill.scaling.x = Math.max(1e-3, bar.hpShown); + bar.hpFill.isVisible = bar.hpShown > 2e-3; +} + +// ---- kill / saved popups (DOM labels anchored to invisible meshes) ---- +type Popup = { mesh: Mesh; until: number; zone: string; x: number; y: number; born: number }; +/** A popup rises this far (m) over POPUP_RISE_MS as it appears. */ +const POPUP_RISE = 0.5; +const POPUP_RISE_MS = 300; +const popups = new Map(); +let popupSeq = 0; + +/** The room a kill happened in, from its fact key (`…:pit..:…`). */ +function killRoom(key: string, fallback: string): string { + return /:(pit\.-?\d+\.-?\d+):/.exec(key)?.[1] ?? fallback; +} + +function popup(key: string, zoneId: string, x: number, y: number, text: string, className: string, ttlMs: number): void { + let p = popups.get(key); + if (p === undefined) { + const mesh = MeshBuilder.CreateBox(`popup-${popupSeq++}`, { size: 0.01 }, scene); + mesh.isVisible = false; + p = { mesh, until: 0, zone: killRoom(key, zoneId), x, y, born: performance.now() }; + mesh.position.copyFrom(placeIn(p.zone, x, y, 1.2)); + popups.set(key, p); + } + p.until = performance.now() + ttlMs; + stage.labels.set(`popup:${key}`, p.mesh, text, 0.6, `pit-pop ${className}`); +} + +// A laser that came through from the room next door: that room's leg of it. +pit.on('beam', (b, zoneId) => { + const points = [placeIn(zoneId, b.x, b.y, b.z), ...b.path.map((h) => placeIn(zoneId, h.x, h.y, h.z)), placeIn(zoneId, b.endX, b.endY, b.endZ)]; + beam(points, b.hit !== undefined ? beamMats.hit : beamMats.miss, 0.04, BEAM_MS * 2); +}); +pit.on('kill', (kill, zoneId) => { + // Killed, not crossing: never held at the side. + const key = `${zoneId}:${kill.mob}`; + killedAt.set(key, performance.now()); + const held = crossing.get(key); + if (held !== undefined) { + dispose(held.visual); + crossing.delete(key); + } + // Entity ids are per room: a kill next door is never yours. + const mine = zoneId === pit.room() && kill.killer === pit.hello()?.entity; + const tier = TIERS[kill.tier]?.name ?? 'Mob'; + if (mine) popup(kill.key, zoneId, kill.x, kill.y, `${tier} slain · saving…`, 'pending', 60_000); + else popup(kill.key, zoneId, kill.x, kill.y, `${kill.killerName} slew a ${tier}`, 'other', 2000); +}); +let savedCount = 0; +pit.on('saved', (saved, zoneId) => { + if (saved.ok) { + savedCount += 1; + const waited = saved.waitedMs >= 200 ? ` (${(saved.waitedMs / 1000).toFixed(1)} s)` : ''; + popup(saved.key, zoneId, saved.x, saved.y, `+${saved.xp} XP saved ✓${waited}`, 'saved', 2500); + } else { + popup(saved.key, zoneId, saved.x, saved.y, `save failed: ${saved.error ?? '?'}`, 'failed', 4000); + } +}); +pit.on('bossDown', (b, zoneId) => { + if (zoneId === pit.room()) toast(`${b.by} felled the boss! The hood is now tier ${b.hoodTier} — its rooms get tougher`); +}); +let lastWeather: number | undefined; +let lastEvent = ''; +pit.on('world', (w, zoneId) => { + if (zoneId !== pit.room()) return; + if (w.event !== lastEvent && w.event !== '') toast(`World event in borough ${w.boroughX},${w.boroughY}: ${w.event}`); + lastEvent = w.event; + if (lastWeather !== undefined && w.weather > lastWeather) toast(`The sky over the borough lifts: ${WEATHER[w.weather]}`); + lastWeather = w.weather; +}); +pit.on('died', (d) => { + deathBanner.textContent = 'You died — respawning…'; + deathBanner.style.display = ''; + setTimeout(() => (deathBanner.style.display = 'none'), d.respawnMs); +}); +pit.on('hello', (hello) => { + if (hello.restored) toast(`You entered ${roomZone(hello.roomX, hello.roomY)}: restored from hibernation (${hello.roomKills} kills here so far)`); +}); +const boards = createBoardWatcher(pitApi, 1000); +boards.on((board) => renderBoard(board)); + +function renderBoard(board: BoardSnapshot): void { + const me = api.last?.principal; + const list = field('board'); + list.replaceChildren( + ...board.kills.slice(0, 5).map((row) => { + const li = document.createElement('li'); + li.textContent = `${row.name} — ${row.score} kills`; + if (row.member === me) li.className = 'me'; + return li; + }) + ); +} + +// ---- durable-facts graph ---- +type Sample = { pending: number; tick: number }; +const samples: Sample[] = []; +let lastSampleAt = 0; + +function drawGraph(): void { + const ctx = graph.getContext('2d'); + if (ctx === null) return; + const { width, height } = graph; + ctx.clearRect(0, 0, width, height); + ctx.strokeStyle = '#2a3240'; + ctx.beginPath(); + ctx.moveTo(0, height - 0.5); + ctx.lineTo(width, height - 0.5); + ctx.stroke(); + const maxPending = Math.max(4, ...samples.map((s) => s.pending)); + const series = (pick: (s: Sample) => number, max: number, color: string) => { + ctx.strokeStyle = color; + ctx.lineWidth = 2; + ctx.beginPath(); + samples.forEach((s, i) => { + const x = (i / 119) * width; + const y = height - 2 - (Math.min(pick(s), max) / max) * (height - 6); + if (i === 0) ctx.moveTo(x, y); + else ctx.lineTo(x, y); + }); + ctx.stroke(); + }; + series((s) => s.tick, 100, '#6cc4ff'); + series((s) => s.pending, maxPending, '#f2a65a'); + ctx.fillStyle = '#8793a6'; + ctx.font = '10px monospace'; + ctx.fillText(`pending max ${maxPending}`, 4, 10); + ctx.fillText('tick 0–100 ms', width - 80, 10); +} + +// ---- input ---- +const sampler = new InputSampler(); +const commandFrames = new InputPacer({ tickRate: () => client.authority?.connection.welcome?.tickRate }); + +// Ranged: R, a click or RT fires along the view (first person: where you +// look; third person: the camera's heading). The laser bounces off walls, +// obstacles, ramps and the floor; the room resolves it lag-compensated +// (C toggles it per shot). +let fireQueued = false; +let lastFireAt = 0; +let compensated = true; +window.addEventListener('keydown', (e) => { + if (e.code === 'KeyR' && !e.repeat) fireQueued = true; +}); +// Third person, a left drag orbits the camera: fire on release, and only +// if the mouse stayed put. Pointer events, not mouse events: Babylon +// cancels pointerdown, so Chromium sends no mousedown/mouseup. +const CLICK_SLOP_PX = 5; +let clickFrom: { x: number; y: number } | undefined; +canvas.addEventListener('pointerdown', (e) => { + if (e.button !== 0) return; + if (stage.view() === 'first') { + // The first click only captures the mouse. + if (document.pointerLockElement === canvas) fireQueued = true; + return; + } + clickFrom = { x: e.clientX, y: e.clientY }; +}); +window.addEventListener('pointerup', (e) => { + if (e.button !== 0 || clickFrom === undefined) return; + if (Math.hypot(e.clientX - clickFrom.x, e.clientY - clickFrom.y) <= CLICK_SLOP_PX) fireQueued = true; + clickFrom = undefined; +}); + +function sendCommandFrame(): void { + const s = sampler.sample(); + // RT held fires at the fire cooldown. + if (s.fire) fireQueued = true; + const move = cameraRelative(s, stage.cameraForward()); + const aim = stage.aim(); + const first = stage.view() === 'first'; + let input: PitInput = { + mx: toAxis(move.x), + my: toAxis(move.y), + buttons: (s.action ? BUTTON.attack : 0) | (s.alt ? BUTTON.dash : 0) | (s.jump ? BUTTON.jump : 0) | (first ? BUTTON.aim : 0), + yaw: aim.yaw, + pitch: aim.pitch, + shot: 0, + delayMs: 0 + }; + const now = performance.now(); + if (fireQueued && now - lastFireAt >= (PIT_RULES.fireCooldown * 1000) / 30) { + const shot = pit.aimShot(aim.yaw, aim.pitch, compensated, first); + if (shot !== undefined) { + input = { ...input, ...shot.input, buttons: input.buttons | shot.input.buttons }; + lastFireAt = now; + marker(shot.record); + } + } + fireQueued = false; + client.sendInput(input); +} + +// ---- shot markers: yellow where you saw it land, then green (the room +// confirmed the hit) or red (it missed) ---- +const markerMats = { + pending: material(scene, 'marker-pending', '#ffd166'), + hit: material(scene, 'marker-hit', '#3ddc84'), + miss: material(scene, 'marker-miss', '#ff5252') +}; +for (const m of Object.values(markerMats)) m.emissiveColor = m.diffuseColor.clone(); +const beamMats = { + shot: material(scene, 'laser-beam', '#ff3b5c'), + hit: material(scene, 'laser-hit', '#3ddc84'), + miss: material(scene, 'laser-miss', '#ff8a8a') +}; +for (const m of Object.values(beamMats)) { + m.emissiveColor = m.diffuseColor.clone(); + m.disableLighting = true; +} +const sparkMat = material(scene, 'laser-spark', '#ffe28a'); +sparkMat.emissiveColor = sparkMat.diffuseColor.clone(); +sparkMat.disableLighting = true; +sparkMat.backFaceCulling = false; +/** How long a beam and its impact marks stay (ms). */ +const BEAM_MS = 220; +const SPARK_MS = 700; +// Beams, impact marks and shot balls come from pools sized for the peak +// (a shot every 0.4 s: about three in flight, each with a predicted and a +// room beam, up to four marks and a ball that waits for its verdict). +/** Points in every pooled beam: the longest path (origin, LASER_BOUNCES + 1 hits, an end). */ +const BEAM_POINTS = 8; +type Beam = { tube: Mesh; born: number; ms: number }; +const liveBeams = new Set(); +let beamSeq = 0; +const beamPool = new Pool( + 'beams', + 16, + () => { + const path = Array.from({ length: BEAM_POINTS }, (_, i) => new Vector3(i, 0, 0)); + const tube = MeshBuilder.CreateTube(`laser-${beamSeq++}`, { path, radius: 0.05, tessellation: 6, cap: Mesh.CAP_ALL, updatable: true }, scene); + tube.isPickable = false; + return { tube, born: 0, ms: 1 }; + }, + (b) => b.tube.setEnabled(false) +); +/** `points` stretched to BEAM_POINTS by splitting its last leg evenly (no zero-length legs). */ +function beamPath(points: Vector3[]): Vector3[] { + const path = points.slice(0, BEAM_POINTS); + const to = path.pop()!; + const from = path[path.length - 1]!; + const parts = BEAM_POINTS - path.length; + for (let i = 1; i <= parts; i += 1) path.push(Vector3.Lerp(from, to, i / parts)); + return path; +} +/** Draw a beam through `points` (scene space) that fades out. */ +function beam(points: Vector3[], mat: StandardMaterial, radius: number, ms: number): void { + if (points.length < 2) return; + const b = beamPool.take(); + MeshBuilder.CreateTube('', { path: beamPath(points), radius, instance: b.tube }); + b.tube.refreshBoundingInfo(); + b.tube.material = mat; + b.tube.visibility = 1; + b.tube.setEnabled(true); + b.born = performance.now(); + b.ms = ms; + liveBeams.add(b); +} +scene.onBeforeRenderObservable.add(() => { + const now = performance.now(); + for (const b of liveBeams) { + const t = (now - b.born) / b.ms; + b.tube.visibility = Math.max(0, 1 - t); + if (t < 1) continue; + liveBeams.delete(b); + beamPool.release(b); + } +}); +let sparkSeq = 0; +const sparkPool = new Pool( + 'sparks', + 24, + () => { + const disc = MeshBuilder.CreateDisc(`spark-${sparkSeq++}`, { radius: 0.22, tessellation: 10 }, scene); + disc.material = sparkMat; + disc.isPickable = false; + return disc; + }, + (disc) => disc.setEnabled(false) +); +/** An impact mark at a bounce, lying on the surface (facing its normal). */ +function spark(at: Vector3, normal: Vector3): void { + const disc = sparkPool.take(); + disc.position.copyFrom(at.add(normal.scale(0.02))); + disc.lookAt(at.add(normal)); + disc.setEnabled(true); + setTimeout(() => sparkPool.release(disc), SPARK_MS); +} +let ballSeq = 0; +const ballPool = new Pool( + 'shot-balls', + 12, + () => { + const ball = MeshBuilder.CreateSphere(`shot-${ballSeq++}`, { diameter: 0.35, segments: 6 }, scene); + ball.isPickable = false; + return ball; + }, + (ball) => ball.setEnabled(false) +); +/** A room-local normal in scene axes. */ +const sceneNormal = (n: readonly [number, number, number]) => new Vector3(n[0], n[2], n[1]); +function marker(record: ShotRecord): void { + // The beam leaves from just below the aim (in first person one from the + // eye itself would sit on the crosshair) and follows the predicted + // bounces, one impact mark per surface it met. + const [ox, oy, oz] = record.origin; + const points = [placeIn(record.zone, ox, oy, oz - 0.3), ...record.path.map((p) => placeIn(record.zone, p.point[0], p.point[1], p.point[2]))]; + beam(points, beamMats.shot, 0.05, BEAM_MS); + record.path.forEach((p, i) => { + if (p.normal !== undefined) spark(points[i + 1]!, sceneNormal(p.normal)); + }); + const ball = ballPool.take(); + ball.material = markerMats.pending; + ball.position.copyFrom(points[points.length - 1]!); + ball.setEnabled(true); + // The verdict and the give-up timer both put it back (only the first counts). + let back = false; + const release = () => { + if (back) return; + back = true; + ballPool.release(ball); + }; + const done = () => setTimeout(release, 1200); + pit.verdict(record.id).then((v) => { + if (!back) { + ball.material = v.hit !== undefined ? markerMats.hit : markerMats.miss; + ball.position.copyFrom(placeIn(record.zone, v.x, v.y, v.z)); + } + // The room's own beam, thin: green if it hit. + const room = [placeIn(record.zone, ox, oy, oz - 0.3), ...v.path.map((h) => placeIn(record.zone, h.x, h.y, h.z))]; + if (v.path.length === 0) room.push(placeIn(record.zone, v.x, v.y, v.z)); + beam(room, v.hit !== undefined ? beamMats.hit : beamMats.miss, 0.02, BEAM_MS * 2); + if (v.hit !== undefined) landed(0.3); + done(); + }); + setTimeout(release, 4000); +} +// ---- off-screen culling ---- +// Babylon skips drawing what is off screen, but still computes the world +// matrix and bounds of every enabled mesh, and the frame loop would still +// place and animate it. An entity wholly outside the view (with a margin) +// has every mesh disabled and is not updated at all; it snaps to its +// current state when it comes back. +const CULL_MARGIN = 1; +const viewProjection = new Matrix(); +const frustumPlanes: Plane[] = Frustum.GetPlanes(Matrix.IdentityReadOnly); +/** This frame's view (the eye's rotation is already this frame's; its position lags a frame, which the margin covers). */ +function updateFrustum(): void { + const camera = scene.activeCamera; + if (camera === null) return; + camera.getViewMatrix(true).multiplyToRef(camera.getProjectionMatrix(true), viewProjection); + Frustum.GetPlanesToRef(viewProjection, frustumPlanes); +} +function onScreen(centre: Vector3, radius: number): boolean { + const r = radius + CULL_MARGIN; + return frustumPlanes.every((plane) => plane.dotCoordinate(centre) > -r); +} +function setCulled(visual: Visual, culled: boolean): void { + if (visual.culled === culled) return; + visual.culled = culled; + // Disabled: off Babylon's active-mesh pass. The bar's fill goes with its + // back (the frame re-enables only top-level meshes). + if (culled) for (const node of Object.values(visual)) if (node instanceof TransformNode && node.parent === null) node.setEnabled(false); + // Back on screen: the bar snaps to the health instead of easing from the old one. + else visual.hpShown = Number.NaN; +} +/** Per-frame cost of the entity loop and of Babylon's render (CPU), smoothed. */ +const cullStats = { drawn: 0, culled: 0, loopMs: 0, renderMs: 0 }; +const smooth = (avg: number, sample: number) => avg + (sample - avg) * 0.05; +let renderStart = 0; +scene.onBeforeRenderObservable.add(() => (renderStart = performance.now())); +scene.onAfterRenderObservable.add(() => (cullStats.renderMs = smooth(cullStats.renderMs, performance.now() - renderStart))); + +// ---- hit feel: hit stop and screen shake ---- +// Drawing only: the rooms simulate everyone at one pace, so a stop freezes +// the drawn attacker and target and they catch up after it. Input is read +// and sent throughout; bars, beams and marks keep moving. +/** How long a hit freezes them (ms): the least, and the most for a big hit. */ +const STOP_MS = [50, 100] as const; +/** A hit taking this share of health (or more) stops longest and shakes hardest. */ +const BIG_HIT = 0.25; +const trauma = new Trauma({ x: 0.2, y: 0.14, roll: 0.05 }); +/** A mob this close to you when you are hit is taken as the one that hit you (m). */ +const ATTACKER_NEAR = 5; +const hitSize = (drop: number) => Math.min(1, drop / BIG_HIT); +/** Hit stops so far (for tests and the console). */ +let hitStops = 0; +function hitStop(visual: Visual, size: number): void { + hitStops += 1; + visual.stopUntil = Math.max(visual.stopUntil, performance.now() + STOP_MS[0] + (STOP_MS[1] - STOP_MS[0]) * size); +} +/** Your drawn self (set by the frame loop). */ +let myVisual: PlayerVisual | undefined; +let mySwing = 0; +/** One of your hits landed (`size` 0..1): you pause and the view jolts a little. */ +function landed(size: number): void { + if (myVisual !== undefined) hitStop(myVisual, size); + trauma.add(0.3); +} +type Hit = { visual: Visual; size: number }; +/** Hits seen this frame (health drops), attributed once every entity is placed. */ +const hits: Hit[] = []; +function attributeHits(): void { + for (const { visual, size } of hits) { + hitStop(visual, size); + if (visual === myVisual) { + trauma.add(0.3 + 0.3 * size); + // The nearest mob is taken as the one that hit you. + let nearest: Visual | undefined; + let best = ATTACKER_NEAR; + for (const other of visuals.values()) { + if (other.kind !== 'mob' || other.culled) continue; + const d = Vector3.Distance(other.body.position, visual.body.position); + if (d < best) [nearest, best] = [other, d]; + } + if (nearest !== undefined) hitStop(nearest, size); + } else if (visual.kind === 'mob' && myVisual !== undefined && mySwing > 0) { + // Struck while your blade is out and within its reach: yours. + if (Vector3.Distance(visual.body.position, myVisual.body.position) < ATTACK_REACH + 1) landed(size); + } + } + hits.length = 0; +} +/** Note a hit when `visual`'s health share fell since last frame. */ +function watchHealth(visual: Visual, share: number): void { + const drop = visual.lastHp - share; + if (drop > 1e-6) hits.push({ visual, size: hitSize(drop) }); + visual.lastHp = share; +} + +// A crosshair in first person. +const crosshair = div('pit-crosshair', document.body); +crosshair.textContent = '+'; + +// ---- frame ---- +stage.onFrame((now, dtMs) => { + applySky(dtMs); + commandFrames.update(now, sendCommandFrame); + const here = pit.room(); + const hereRoom = here === undefined ? undefined : parseRoom(here); + if (hereRoom !== undefined) moveOrigin(hereRoom); + const hello = pit.hello(); + const authority = client.authority; + // One copy of a mob crossing between two watched rooms. + const rendered = withoutHomeCopies(client.render()); + miniDots.length = 0; + const seen = new Set(); + let me: { at: Vector3; hp: number; dead: boolean } | undefined; + let stats: PitFields | undefined; + const loopStart = performance.now(); + updateFrustum(); + // Levels of detail from the camera (its last rendered spot; the band absorbs a frame's move). + const eye = scene.activeCamera?.globalPosition ?? Vector3.ZeroReadOnly; + lodCounts.fill(0); + for (const chunk of chunks.values()) for (const lod of chunk.lods) applyLod(lod, eye); + let drawn = 0; + let culled = 0; + for (const entity of rendered) { + if (isPit(entity)) { + if (entity.zoneId === here) stats = pitFields(entity); + continue; + } + // Pillars are static: every room's are drawn with its chunk. + if (isPillar(entity)) continue; + // Yours: predicted, or the SDK's hold of it during a doorway handoff. + const mine = + entity.predicted || (authority !== undefined && hello !== undefined && entity.zoneId === authority.zoneId && entity.id === hello.entity); + const at = (x: number, y: number, height: number) => placeIn(entity.zoneId, x, y, height); + const visual = visualFor(entity, mine); + seen.add(entity.key); + const visible = !entity.stale; + const entityRoom = parseRoom(entity.zoneId); + if (entityRoom !== undefined && visible) { + const base = { wx: entityRoom[0] * ROOM_SIZE, wy: entityRoom[1] * ROOM_SIZE }; + if (visual.kind === 'mob') { + const m = mobFields(entity); + miniDots.push({ wx: base.wx + m.x, wy: base.wy + m.y, kind: 'mob', tier: visual.tier, face: m.face, dead: false }); + } else { + const p = playerFields(entity); + const dot: MiniDot = { wx: base.wx + p.x, wy: base.wy + p.y, kind: mine ? 'me' : 'player', tier: 0, face: p.face, dead: p.dead }; + if (mine) miniMe = dot; + else miniDots.push(dot); + } + } + if (visual.kind === 'mob') watchHealth(visual, mobFields(entity).hp / 100); + else { + const p = playerFields(entity); + watchHealth(visual, p.dead ? 0 : p.hp / PLAYER_HP); + if (mine) { + myVisual = visual; + mySwing = p.swing; + } + } + // Off screen (never your own): nothing to place or animate. + if (cullOn && !mine && visible) { + const f = visual.kind === 'mob' ? mobFields(entity) : playerFields(entity); + const lift = visual.kind === 'mob' ? groundAt(entity.zoneId, f.x, f.y) : 'z' in f ? f.z : 0; + const radius = visual.kind === 'mob' ? Math.max(TIERS[visual.tier]?.tele ?? 1, 1.5) : ATTACK_REACH; + const out = !onScreen(at(f.x, f.y, lift + 1), radius); + setCulled(visual, out); + if (out) { + culled += 1; + continue; + } + } else setCulled(visual, false); + drawn += 1; + if (visual.kind === 'mob') { + const mob = mobFields(entity); + // Hit stop: held where it was (the bar still drains). + if (now < visual.stopUntil) { + showHp(visual, visual.hpBack.position, mob.hp / 100, dtMs); + continue; + } + const { x, y } = mob; + const ground = groundAt(entity.zoneId, x, y); + const height = ground + (visual.tier === 4 ? 1.4 : visual.tier === 3 ? 1 : visual.tier === 2 ? 0.75 : 0.45); + visual.edge = Math.max(Math.abs(x), Math.abs(y)) > ROOM_SIZE / 2 - CROSS_MATCH; + const slide = visual.slide; + const k = slide === undefined ? 1 : (now - slide.start) / CROSS_SLIDE_MS; + if (slide !== undefined && k < 1) visual.body.position.copyFrom(Vector3.Lerp(slide.from, at(x, y, height), easeOutCubic(k))); + else { + visual.slide = undefined; + visual.body.position.copyFrom(at(x, y, height)); + } + visual.body.rotation.y = -mob.face; + if (visual.lod !== undefined) applyLod(visual.lod, eye); + const hp = mob.hp / 100; + const top = height * 2 - ground + 0.35; + showHp(visual, at(x, y, top), hp, dtMs); + const tele = mob.tele / 255; + const winding = mob.state === 2; + visual.ring.setEnabled(visible && winding); + visual.fill.setEnabled(visible && winding); + if (winding) { + const area = slamArea(visual, entity.zoneId, x, y, TIERS[visual.tier]?.tele ?? 1); + visual.ring.position.copyFrom(at(x, y, 0)); + visual.fill.position.copyFrom(at(x, y, 0.01)); + drape(visual.fill, area, Math.max(0.05, tele)); + } + visual.body.scaling.setAll(winding ? 1 + 0.15 * tele : 1); + for (const m of [visual.body, visual.hpBack]) m.setEnabled(visible); + } else { + const player = playerFields(entity); + const { x, y, z, dead, face, swing } = player; + if (now < visual.stopUntil) { + showHp(visual, visual.hpBack.position, dead ? 0 : player.hp / PLAYER_HP, dtMs); + if (mine) me = { at: visual.body.position, hp: player.hp, dead }; + continue; + } + visual.body.position.copyFrom(at(x, y, 0.9 + z)); + visual.body.material = dead ? mats.dead : mine ? mats.me : mats.other; + visual.nose.position.copyFrom(at(x + Math.cos(face) * 0.5, y + Math.sin(face) * 0.5, 1.3 + z)); + visual.nose.rotation.y = -face; + // Blade sweeps through the swing cone while `swing` counts down to 0. + const sweep = swing > 0 ? ((SWING_FRAMES - swing) / SWING_FRAMES) * 2 * SWING_HALF - SWING_HALF : -Math.PI / 2.5; + const a = face + sweep; + visual.blade.position.copyFrom(at(x + Math.cos(a) * 0.8, y + Math.sin(a) * 0.8, 1.0 + z)); + visual.blade.rotation.y = -a; + visual.blade.setEnabled(visible && !dead); + visual.arc.setEnabled(visible && swing > 0); + if (swing > 0) { + visual.arc.position.copyFrom(at(x, y, 0.05)); + // Disc arcs start at +x and run counter-clockwise; centre it on `face`. + visual.arc.rotation.y = -(face - SWING_HALF); + } + const label = `${player.name} · L${player.level}`; + // First person: you are the camera (no body, no label or bar of your own). + const hidden = mine && stage.view() === 'first'; + if (hidden) stage.labels.delete(entity.key); + else stage.labels.set(entity.key, visual.body, mine ? `${label} (you)` : label, 1.4, mine ? 'me' : ''); + const top = 2.05 + z; + showHp(visual, at(x, y, top), dead ? 0 : player.hp / PLAYER_HP, dtMs); + visual.hpBack.setEnabled(visible && !hidden); + visual.body.setEnabled(visible && !hidden); + visual.nose.setEnabled(visible && !dead && !hidden); + if (mine) me = { at: visual.body.position, hp: player.hp, dead }; + } + } + attributeHits(); + cullStats.drawn = drawn; + cullStats.culled = culled; + cullStats.loopMs = smooth(cullStats.loopMs, performance.now() - loopStart); + for (const [key, visual] of visuals) { + if (seen.has(key)) continue; + // Gone at a side, not killed: it may be crossing (held a moment). + if (visual.kind === 'mob' && visual.edge && !visual.culled && !killedAt.has(key)) { + crossing.set(key, { visual, until: now + CROSS_HOLD_MS }); + visuals.delete(key); + continue; + } + dispose(visual); + stage.labels.delete(key); + visuals.delete(key); + } + for (const [key, held] of crossing) { + if (now < held.until) continue; + dispose(held.visual); + crossing.delete(key); + } + for (const [key, at] of killedAt) if (now - at > 2000) killedAt.delete(key); + for (const [key, p] of popups) { + p.mesh.position.copyFrom(placeIn(p.zone, p.x, p.y, 1.2 + tween(0, POPUP_RISE, now - p.born, POPUP_RISE_MS))); + if (now < p.until) continue; + p.mesh.dispose(); + stage.labels.delete(`popup:${key}`); + popups.delete(key); + } + if (me !== undefined) stage.follow(me.at.x, me.at.z, dtMs, me.at.y - 0.9); + stage.shake(trauma.update(dtMs / 1000)); + crosshair.style.display = stage.view() === 'first' ? '' : 'none'; + hpRow.style.display = stage.view() === 'first' && me !== undefined ? '' : 'none'; + if (me !== undefined) { + const share = me.dead ? 0 : Math.max(0, Math.min(1, me.hp / PLAYER_HP)); + hpLabel.textContent = me.dead ? 'HP — dead' : `HP ${me.hp} / ${PLAYER_HP}`; + hpFillBar.style.width = `${share * 100}%`; + hpFillBar.className = `pit-hp-fill${share < 0.3 ? ' low' : share < 0.6 ? ' mid' : ''}`; + } + + // The server's own copy of you (authoritative, behind by the round + // trip): a wireframe ghost in the room that owns you. + const authoritative = client.predictor?.authoritative(); + let ghostGap: number | undefined; + if (authoritative !== undefined && authority !== undefined) { + const g = playerFields({ fields: authoritative }); + ghost.position.copyFrom(placeIn(authority.zoneId, g.x, g.y, 0.9 + g.z)); + if (me !== undefined) ghostGap = Math.hypot(ghost.position.x - me.at.x, ghost.position.z - me.at.z); + } + ghost.setEnabled(ghostOn && authoritative !== undefined && !(stage.view() === 'first' && (ghostGap ?? 0) < 0.8)); + interestRing.setEnabled(me !== undefined && hello !== undefined); + if (me !== undefined && hello !== undefined) { + interestRing.position.set(me.at.x, 0, me.at.z); + interestRing.scaling.setAll(hello.viewRadius); + } + + // ---- HUD ---- + hud.frame({ entities: rendered.length }); + const pending = stats?.pending ?? 0; + const tickMs = stats?.tickMs ?? 0; + const tickMax = stats?.tickMaxMs ?? 0; + hud.row('You', api.last === undefined ? '—' : `${api.last.name} · ${api.last.principal}`); + hud.row('HP', me === undefined ? '—' : me.dead ? 'dead' : String(me.hp)); + hud.row('Facts pending (zone)', String(pending)); + hud.row('Facts saved (zone)', String(stats?.committed ?? 0)); + hud.row('My unsaved kills', String(pit.unsaved.size)); + hud.row('Kills in this room', String(stats?.kills ?? 0)); + hud.row('Room tick interval', `${tickMs.toFixed(1)} ms avg · ${tickMax.toFixed(1)} max`); + const predictor = client.predictor; + hud.row('Prediction', client.predictionEnabled ? 'on (pit_step as WASM)' : 'off (raw round trip)'); + hud.row('Pending inputs', String(predictor?.pending.length ?? 0)); + hud.row('Ack seq', String(predictor?.lastAck ?? 0)); + hud.row('Corrections', `${corrections} (last ${lastCorrection.toFixed(3)} m)`); + hud.row('Entities drawn / off screen', `${cullStats.drawn} / ${cullStats.culled}`); + hud.row('LOD near / mid / far', `${lodCounts[0]} / ${lodCounts[1]} / ${lodCounts[2]}${lodOn ? '' : ' (off: all full)'}`); + hud.row('Triangles drawn', String(Math.round(scene.getActiveIndices() / 3))); + hud.row('Frame CPU', `entities ${cullStats.loopMs.toFixed(2)} ms · render ${cullStats.renderMs.toFixed(2)} ms`); + hud.row('Ghost gap', ghostGap === undefined ? '—' : `${ghostGap.toFixed(2)} m`); + const around = [...pit.neighbours().values()]; + hud.row('Next door', `${around.filter((s) => s === 'watching').length} rooms watched · ${around.filter((s) => s === 'asleep').length} asleep (not woken)`); + const awake = [...pit.near()]; + hud.row('Wake rooms in reach (N)', pit.wakeRooms() ? `on · ${awake.length === 0 ? 'no doorway in reach' : `keeping ${awake.join(', ')} awake`}` : 'off (every neighbour a passive watcher)'); + const w = pit.world(); + hud.row('Hood', w === undefined ? '—' : `${w.hoodX},${w.hoodY} · tier ${w.hoodTier} · boss ${w.bossDown ? `down (${w.lastBy})` : 'standing'}`); + hud.row('Borough', w === undefined ? '—' : `${w.boroughX},${w.boroughY} · ${WEATHER[w.weather]} · ${w.boroughBossesDown}/9 bosses down`); + hud.row('City', w === undefined || w.banner === '' ? '—' : w.banner); + const left = w === undefined || w.event === '' ? 0 : Math.max(0, Math.round((w.eventUntilMs - Date.now()) / 1000)); + hud.row('World event', w === undefined || w.event === '' ? 'none (the borough schedules the next)' : `${w.event} · ${left} s left`); + eventBanner.style.display = w !== undefined && w.event !== '' ? '' : 'none'; + if (w !== undefined && w.event !== '') eventBanner.textContent = `${EVENT_TEXT[w.event] ?? w.event} · ${left} s`; + const c = pit.content(); + tintMobs(c.pack); + hud.row('Content', `${c.pack.name}${pinContent ? ' (old client: no live patch)' : ''} · world ${CONTENT_PACKS.find((p) => p.version === c.worldVersion)?.name ?? c.worldVersion}${c.reloads.length > 0 ? ` · ${c.reloads.length} reload(s)` : ''}`); + freezeOverlay.style.display = c.frozen === undefined ? 'none' : ''; + if (c.frozen !== undefined) { + const target = CONTENT_PACKS.find((p) => p.version === c.frozen!.version)?.name ?? c.frozen.version; + freezeOverlay.innerHTML = `SYSTEM: an administrator has paused the world to update it to ${target}.
    ${c.frozen.notes}`; + } + staleBanner.style.display = c.stale ? '' : 'none'; + if (c.stale) { + const world = CONTENT_PACKS.find((p) => p.version === c.worldVersion)?.name ?? c.worldVersion; + staleBanner.textContent = `Your client runs ${c.pack.name}; the world runs ${world}. Only the entrance (${GATE_ROOM}) lets you through — it updates you.${c.staleNotice === undefined ? '' : ' (that doorway is closed to you)'}`; + } + const r = pit.rangedStats; + hud.row('Ranged', `${r.shots} shots · ${r.confirmedHits} hits confirmed · ${r.agreed}/${r.resolved} as seen · last rewind ${r.lastAgeMs.toFixed(0)} ms${compensated ? '' : ' (compensation OFF)'}`); + hud.row('Interest', hello === undefined ? '—' : `${hello.viewRadius} m ring · ${rendered.filter((e) => isMob(e) && !e.stale).length} mobs replicated`); + const profile = pit.profile(); + if (profile !== undefined) { + const span = Math.max(1, profile.nextLevelXp - profile.levelXp); + xpFill.style.width = `${Math.min(100, ((profile.xp - profile.levelXp) / span) * 100).toFixed(1)}%`; + xpLabel.textContent = `Level ${profile.level} · ${profile.xp} XP · ${profile.kills} kills · next level at ${profile.nextLevelXp} XP (${profile.source === 'cell' ? 'loaded from cell' : 'saved'})`; + } else { + xpLabel.textContent = 'Loading your Crawler cell…'; + } + field('pending').textContent = String(pending); + field('saved').textContent = String(savedCount); + field('note').textContent = 'Kills settle in your Crawler cell next to the room on celld; the tick never waits for them.'; + if (here !== undefined) showRoom(here); + drawRooms(); + if (now - lastSampleAt > 250) { + renderDebug(); + lastSampleAt = now; + samples.push({ pending, tick: tickMs }); + if (samples.length > 120) samples.shift(); + drawGraph(); + } +}); + +declare global { + interface Window { + mobpit?: unknown; + } +} +window.mobpit = { + client, + api, + pitApi, + pit, + scene, + rooms, + boards, + camera: stage.camera, + origin: () => origin, + feel: () => ({ + trauma: trauma.value, + hitStops, + pools: Object.fromEntries([beamPool, sparkPool, ballPool].map((p) => [p.name, { size: p.size, active: p.active }])) + }) +}; + +// The same browser is the same player: back in the room you were last in. +(async () => { + // Start on the world's live content (the packs are built in). + const live = await pitApi.content().catch(() => undefined); + client.setContentVersion(live?.state?.version ?? ''); + const zone = forcedZone ?? (await pitApi.startRoom(api.guest).catch(() => DEFAULT_ZONE)); + origin = parseRoom(zone) ?? origin; + await client.connect(zone); +})().catch((error: unknown) => hud.row('Status', `failed: ${String(error)}`)); diff --git a/examples/game/client/src/mobpit/style.css b/examples/game/client/src/mobpit/style.css new file mode 100644 index 000000000..ab6edfdbe --- /dev/null +++ b/examples/game/client/src/mobpit/style.css @@ -0,0 +1,321 @@ +/* Easing (shared/feel.ts has the same curves for code). */ +:root { + --ease-out-cubic: cubic-bezier(0.33, 1, 0.68, 1); + --ease-out-back: cubic-bezier(0.34, 1.56, 0.64, 1); +} + +/* Mob Pit panels (layered over the shared HUD/stage styles). */ +.pit-xp { + position: fixed; + left: 50%; + bottom: 16px; + transform: translateX(-50%); + width: min(560px, calc(100% - 32px)); + padding: 8px 12px; + border-radius: 8px; + background: var(--panel); + box-sizing: border-box; +} +.pit-hp { + margin-bottom: 8px; +} +.pit-hp-label { + margin-bottom: 4px; + font-weight: 600; +} +.pit-hp-bar { + height: 12px; + border-radius: 6px; + background: #2a3240; + overflow: hidden; +} +.pit-hp-fill { + height: 100%; + width: 100%; + background: #4caf50; + transition: width 0.3s var(--ease-out-cubic); +} +.pit-hp-fill.mid { + background: #f2c94c; +} +.pit-hp-fill.low { + background: #e04848; +} +.pit-xp-label { + margin-bottom: 4px; + color: var(--muted); +} +.pit-xp-bar { + height: 10px; + border-radius: 5px; + background: #2a3240; + overflow: hidden; +} +.pit-xp-fill { + height: 100%; + width: 0; + background: linear-gradient(90deg, #f2c94c, #f2a65a); + transition: width 0.3s var(--ease-out-cubic); +} +.pit-facts { + position: fixed; + top: 12px; + right: 12px; + width: 284px; + padding: 10px 12px; + border-radius: 8px; + background: var(--panel); + box-sizing: border-box; +} +.pit-facts h2 { + margin: 0 0 6px; + font-size: 13px; +} +.pit-facts h2 a { + float: right; + font-weight: normal; + color: var(--accent); +} +.pit-facts canvas { + width: 100%; + height: 90px; + display: block; +} +.pit-big { + margin-bottom: 6px; +} +.pit-big span { + font-size: 22px; +} +.pit-big span[data-k='pending'] { + color: #f2a65a; +} +.pit-big span[data-k='saved'] { + color: #7ee787; + margin-left: 8px; +} +.pit-legend { + margin: 4px 0; + font-size: 11px; +} +.c-pending { + color: #f2a65a; +} +.c-tick { + color: #6cc4ff; +} +.pit-note { + margin: 4px 0 10px; + color: var(--muted); +} +.pit-facts ol { + margin: 0; + padding-left: 20px; +} +.pit-facts li.me { + color: var(--accent); +} +.pit-death { + position: fixed; + top: 40%; + left: 50%; + transform: translate(-50%, -50%); + padding: 12px 20px; + border-radius: 8px; + background: rgba(120, 20, 20, 0.85); + font-size: 18px; + animation: pit-pop-in 0.3s var(--ease-out-back); +} +.label.pit-pop { + font-weight: bold; + /* `scale`, not `transform`: the label layer owns transform. */ + animation: pit-pop-in 0.3s var(--ease-out-back); +} +@keyframes pit-pop-in { + from { + scale: 0.4; + } +} +.label.pit-pop.pending { + color: #b9c0cc; +} +.label.pit-pop.saved { + color: #7ee787; + background: rgba(10, 40, 16, 0.75); +} +.label.pit-pop.failed { + color: #ff7b72; +} +.label.pit-pop.other { + color: var(--muted); + font-weight: normal; +} +@media (max-width: 900px) { + .pit-facts { + top: auto; + bottom: 72px; + width: 220px; + } +} +/* Rooms minimap (zone status read model) and the debug overlay. */ +.pit-rooms { + position: fixed; + right: 12px; + bottom: 16px; + width: 280px; + padding: 10px 12px; + border-radius: 8px; + background: var(--panel); + box-sizing: border-box; +} +.pit-rooms h2 { + margin: 0 0 6px; + font-size: 13px; +} +.pit-rooms h2 small { + color: var(--muted); + font-weight: normal; +} +.pit-rooms .c-active { + color: #4caf50; +} +.pit-rooms .c-dormant { + color: #f2c94c; +} +.pit-rooms .c-hibernated { + color: #6c7aa0; +} +.pit-rooms .c-cold { + color: #556070; +} +.pit-rooms .c-watched { + color: #4dd0e1; +} +.pit-debug { + margin-top: 6px; + font: 11px/1.4 monospace; + color: var(--muted); + word-break: break-word; +} +/* Top centre: the world event banner, then the toasts (never overlapping); + clear of the facts panel on the right. */ +.pit-top { + position: fixed; + top: 12px; + left: 50%; + transform: translateX(-50%); + width: max-content; + max-width: max(280px, calc(100vw - 2 * 310px)); + display: flex; + flex-direction: column; + align-items: center; + gap: 6px; + pointer-events: none; + z-index: 10; +} +.pit-toasts { + display: flex; + flex-direction: column; + align-items: center; + gap: 6px; +} +.pit-toast { + padding: 8px 14px; + border-radius: 6px; + background: #1f3a4d; + color: #e8f4ff; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.4); + animation: pit-toast-in 0.3s var(--ease-out-cubic); +} +@keyframes pit-toast-in { + from { + translate: 0 -16px; + opacity: 0; + } +} +.label.door { + color: #4dd0e1; +} + +.pit-event { + padding: 8px 16px; + border-radius: 6px; + background: rgba(120, 30, 160, 0.85); + color: #fff; + font-weight: 600; + text-align: center; +} + +.pit-crosshair { + position: fixed; + left: 50%; + top: 50%; + transform: translate(-50%, -50%); + color: #fff; + font: 24px/1 monospace; + text-shadow: 0 0 3px #000; + pointer-events: none; + z-index: 6; +} + +.pit-freeze { + position: fixed; + top: 40%; + left: 50%; + transform: translate(-50%, -50%); + max-width: 520px; + padding: 16px 22px; + border-radius: 8px; + background: rgba(20, 60, 110, 0.92); + color: #fff; + text-align: center; + line-height: 1.5; + pointer-events: none; + z-index: 6; +} + +.pit-stale { + position: fixed; + bottom: 70px; + left: 50%; + transform: translateX(-50%); + padding: 8px 16px; + border-radius: 6px; + background: rgba(170, 110, 20, 0.9); + color: #fff; + font-weight: 600; + pointer-events: none; + z-index: 5; +} + +.pit-admin { + position: fixed; + right: 12px; + bottom: 12px; + width: 260px; + padding: 8px 10px; + border-radius: 6px; + background: rgba(18, 15, 20, 0.85); + color: #ddd; + font-size: 12px; + z-index: 5; +} + +.pit-admin input:not([type='checkbox']) { + width: 100%; + box-sizing: border-box; + margin-bottom: 4px; +} + +.pit-admin button { + margin: 4px 4px 0 0; +} +.pit-rooms .c-me { + color: #ffffff; +} +.pit-rooms .c-other { + color: #64b5f6; +} +.pit-rooms .c-mob { + color: #ff8a65; +} diff --git a/examples/game/client/src/shared/dev-api.ts b/examples/game/client/src/shared/dev-api.ts new file mode 100644 index 000000000..283d903d2 --- /dev/null +++ b/examples/game/client/src/shared/dev-api.ts @@ -0,0 +1,139 @@ +/** + * Client side of the demo server's **dev-only** routes (`/dev/ticket`, + * `/dev/netsim`, see `server/src/common/dev.rs`) plus zone URLs. + * + * A real game gets admission tickets from its authenticated lobby; the dev + * route mints one for a server-generated guest. We keep the server-signed + * guest token per browser (localStorage when available): a reload, a new + * tab or a reopened browser is the same player (a second tab takes the + * player over). `?player=

    (wasm::scratch(), state_len, input_len, context_len, dt) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{GameInput, GameRecord}; + + #[derive(Debug, Clone, Copy, PartialEq, GameRecord)] + struct Dot { + x: f32, + n: u8, + } + + #[derive(Debug, Clone, Copy, PartialEq, GameInput)] + struct Push { + #[range(min = -1, max = 1)] + dx: i8, + } + + #[derive(Debug, Clone, PartialEq, GameRecord)] + struct Wind { + speed: f32, + } + + struct DotStep; + impl PredictStep for DotStep { + const KIND: &'static str = "dot"; + const PACKAGE: &'static str = "test"; + const EXPORT: &'static str = "dot"; + type State = Dot; + type Input = Push; + type Context = Wind; + fn step(state: &Dot, input: &Push, context: &Wind, dt: f32) -> Dot { + Dot { + x: state.x + f32::from(input.dx) * context.speed * dt, + n: state.n.wrapping_add(1), + } + } + } + + #[test] + fn abi_steps_in_place_and_sanitizes_input() { + let state = crate::codec::to_bytes(&Dot { x: 1.5, n: 7 }); + let context = Wind { speed: 2.0 }.encode_context(); + let mut buffer = vec![0u8; 64]; + let mut at = 0; + for part in [&state[..], &[5u8][..], &context[..]] { + buffer[at..at + part.len()].copy_from_slice(part); + at += part.len(); + } + let n = run_abi::( + &mut buffer, + state.len() as u32, + 1, + context.len() as u32, + 0.5, + ); + assert!(n > 0); + // dx = 5 is clamped to 1, as the server would. + assert_eq!( + decode_state::(&buffer[..n as usize]).unwrap(), + Dot { x: 2.5, n: 8 } + ); + } + + #[test] + fn abi_reports_errors() { + let mut buffer = vec![0u8; 8]; + assert_eq!( + run_abi::(&mut buffer, 6, 3, 0, 0.0), + AbiError::TooLarge as i32 + ); + assert_eq!( + run_abi::(&mut buffer, 1, 1, 4, 0.0), + AbiError::State as i32 + ); + assert_eq!( + step_bytes::( + &crate::codec::to_bytes(&Dot { x: 0.0, n: 0 }), + &[], + &[0; 4], + 0.0 + ), + Err(AbiError::Input) + ); + assert_eq!( + step_bytes::( + &crate::codec::to_bytes(&Dot { x: 0.0, n: 0 }), + &[0], + &[0; 3], + 0.0 + ), + Err(AbiError::Context) + ); + assert!(<() as PredictContext>::decode_context(&[1]).is_err()); + } +} diff --git a/distributed_game/src/protocol/messages.rs b/distributed_game/src/protocol/messages.rs new file mode 100644 index 000000000..cae356339 --- /dev/null +++ b/distributed_game/src/protocol/messages.rs @@ -0,0 +1,786 @@ +//! Message types and their codecs (`PROTOCOL.md` §6–§7). + +use std::collections::BTreeMap; + +use super::wire::{DecodeError, Reader, Writer}; +use crate::schema::{EntitySchema, FieldValue}; + +/// The wire protocol version (`PROTOCOL.md` §6.0): clients send it in +/// Hello and servers refuse any other. +pub const PROTOCOL_VERSION: u32 = 2; + +/// Runtime feature bits a server announces in Welcome (`features`). +/// Unlike Hello's game-defined `capabilities`, the runtime defines these: a +/// client sends a message a feature covers only when the bit is set. +pub mod feature { + /// The server handles `Focus` (observers steer their view). + pub const FOCUS: u32 = 1 << 0; + /// Every feature this crate's runtime implements. + pub const ALL: u32 = FOCUS; +} + +/// Message type bytes. +pub mod tag { + /// Client → server Hello. + pub const HELLO: u8 = 0x01; + /// Client → server Input. + pub const INPUT: u8 = 0x02; + /// Client → server Ping. + pub const PING: u8 = 0x03; + /// Client → server Leave. + pub const LEAVE: u8 = 0x04; + /// Client → server Content (patched live to a content version). + pub const CONTENT: u8 = 0x05; + /// Client → server Near (an observer asks to keep the zone awake, or + /// lets go). + pub const NEAR: u8 = 0x06; + /// Client → server Focus (where an observer is looking, zone-local). + pub const FOCUS: u8 = 0x07; + /// Server → client Welcome. + pub const WELCOME: u8 = 0x80; + /// Server → client Delta. + pub const DELTA: u8 = 0x81; + /// Server → client Event. + pub const EVENT: u8 = 0x82; + /// Server → client Pong. + pub const PONG: u8 = 0x83; + /// Server → client Freeze. + pub const FREEZE: u8 = 0x84; + /// Server → client Resume. + pub const RESUME: u8 = 0x85; + /// Server → client Handoff. + pub const HANDOFF: u8 = 0x86; + /// Server → client Kick. + pub const KICK: u8 = 0x87; + /// Server → client Error. + pub const ERROR: u8 = 0x88; + /// Server → client Redirect (zone owned by another host). + pub const REDIRECT: u8 = 0x89; +} + +/// Kick reason codes. +pub mod kick { + /// Removed by zone logic. + pub const BY_ZONE: u32 = 1; + /// Same principal connected again; this connection was replaced. + pub const REPLACED: u32 = 2; + /// Server shutting down. + pub const SHUTDOWN: u32 = 3; + /// Input rate limit abuse. + pub const RATE_LIMITED: u32 = 4; + /// Zone disposed. + pub const ZONE_DISPOSED: u32 = 5; + /// Outbound queue overflow (client too slow). + pub const SLOW_CONSUMER: u32 = 6; + /// Client content is stale: reload, then reconnect with the last + /// Welcome's reconnect token inside the grace window. + pub const RELOAD: u32 = 7; +} + +/// Error codes. +pub mod error { + /// Malformed or unexpected message. + pub const BAD_MESSAGE: u32 = 1; + /// Ticket missing, invalid, expired or replayed. + pub const UNAUTHORIZED: u32 = 2; + /// Zone `on_auth` rejected the join. + pub const REJECTED: u32 = 3; + /// Zone at capacity. + pub const ZONE_FULL: u32 = 4; + /// Protocol or content version mismatch. + pub const VERSION_MISMATCH: u32 = 5; + /// Input dropped by rate limiting (sent at most once per second). + pub const RATE_LIMITED: u32 = 6; + /// Unknown zone. + pub const NOT_FOUND: u32 = 7; + /// Reconnect token unknown or grace window elapsed. + pub const RECONNECT_FAILED: u32 = 8; + /// The zone could not be created right now (its factory or allocation + /// store failed or timed out); retry later. + pub const ZONE_UNAVAILABLE: u32 = 9; + /// The zone is asleep and an observer does not wake it (zones hosted as + /// celld objects: observers are passive watchers); try again later. + pub const ASLEEP: u32 = 10; + /// An observer said it is near (Hello `near` / `Near`) but its ticket + /// does not grant `wake`: it stays a passive watcher. Sent after the + /// join, without closing; a fresh ticket may grant it. + pub const WAKE_DENIED: u32 = 11; +} + +/// Client handshake. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Hello { + /// [`PROTOCOL_VERSION`]; the server refuses any other with + /// `Error(VERSION_MISMATCH)` (message starting `protocol`) before + /// touching the ticket. + pub protocol_version: u32, + /// Game content version the client was built against. + pub content_version: String, + /// Game-defined capability bits (opaque to the runtime). + pub capabilities: u32, + /// Signed admission ticket (empty when reconnecting). + pub ticket: String, + /// Reconnect token from a previous Welcome (empty for a fresh join). + pub reconnect_token: String, + /// An observer that is *near* (e.g. its player is close to this zone): + /// on zones hosted as celld objects a near observer whose ticket grants + /// `wake` wakes a sleeping zone and keeps it awake like a player; + /// otherwise it is a passive watcher. Changed later with + /// [`ClientMessage::Near`]. Ignored for players. + pub near: bool, +} + +/// Messages a client sends. +#[derive(Debug, Clone, PartialEq)] +pub enum ClientMessage { + /// Handshake; must be the first message. + Hello(Hello), + /// Sequenced input. + Input { + /// Strictly increasing per connection lifetime, starting at 1. + seq: u32, + /// Client's predicted tick when sampled. + client_tick: u32, + /// Game-defined input bytes. + payload: Vec, + }, + /// Clock sync probe. + Ping { + /// Client clock in ms (echoed). + client_time: f64, + }, + /// Graceful leave (no reconnect grace). + Leave, + /// The client patched its content live (after a `Resume` with a new + /// version) and now runs `content_version`. Only the zone's current + /// version is accepted; anything else is ignored. + Content { + /// The version the client runs now. + content_version: String, + }, + /// An observer is near the zone (keep it awake) or no longer is + /// (passive watcher again); see [`Hello::near`]. + Near { + /// Near (true) or passive (false). + near: bool, + }, + /// Where an observer is looking, in the zone's local coordinates (a + /// player next door: its position seen from this zone). The zone + /// decides what it means ([`Zone::on_observer_focus`](crate::Zone::on_observer_focus); + /// by default the observer's view centre follows). Ignored for + /// players. + Focus { + /// x (zone-local). + x: f32, + /// y (zone-local). + y: f32, + }, +} + +impl ClientMessage { + /// Encode one message (one WebSocket binary frame). + pub fn encode(&self) -> Vec { + let mut w = Writer::new(); + match self { + Self::Hello(h) => { + w.u8(tag::HELLO) + .varuint(h.protocol_version) + .string(&h.content_version) + .varuint(h.capabilities) + .string(&h.ticket) + .string(&h.reconnect_token) + .bool(h.near); + } + Self::Input { + seq, + client_tick, + payload, + } => { + w.u8(tag::INPUT) + .varuint(*seq) + .varuint(*client_tick) + .bytes(payload); + } + Self::Ping { client_time } => { + w.u8(tag::PING).f64(*client_time); + } + Self::Leave => { + w.u8(tag::LEAVE); + } + Self::Content { content_version } => { + w.u8(tag::CONTENT).string(content_version); + } + Self::Near { near } => { + w.u8(tag::NEAR).bool(*near); + } + Self::Focus { x, y } => { + w.u8(tag::FOCUS).f32(*x).f32(*y); + } + } + w.into_bytes() + } + + /// Decode one message. + pub fn decode(bytes: &[u8]) -> Result { + let mut r = Reader::new(bytes); + let message = match r.u8()? { + tag::HELLO => Self::Hello(Hello { + protocol_version: r.varuint()?, + content_version: r.string()?, + capabilities: r.varuint()?, + ticket: r.string()?, + reconnect_token: r.string()?, + near: r.bool()?, + }), + tag::INPUT => Self::Input { + seq: r.varuint()?, + client_tick: r.varuint()?, + payload: r.bytes()?.to_vec(), + }, + tag::PING => Self::Ping { + client_time: r.f64()?, + }, + tag::LEAVE => Self::Leave, + tag::CONTENT => Self::Content { + content_version: r.string()?, + }, + tag::NEAR => Self::Near { near: r.bool()? }, + tag::FOCUS => Self::Focus { + x: r.f32()?, + y: r.f32()?, + }, + other => return Err(DecodeError::UnknownMessage(other)), + }; + r.finish()?; + Ok(message) + } +} + +/// Connection role. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Role { + /// Owns a player in the zone. Wire `0`. + Player, + /// Read-only observer. Wire `1`. + Observer, +} + +/// Where a zone sits in the world: its origin in world coordinates, so +/// world = origin + zone-local (`Zone::origin`). Clients use it to say +/// where their player is in a neighbour's coordinates (`Focus`). +#[derive(Debug, Clone, Copy, PartialEq, Default)] +pub struct Origin { + /// World x of the zone's local (0, 0). + pub x: f64, + /// World y of the zone's local (0, 0). + pub y: f64, +} + +impl Origin { + /// Origin at world `(x, y)`. + pub fn new(x: f64, y: f64) -> Self { + Self { x, y } + } + + /// A world point in this zone's local coordinates. + pub fn to_local(self, x: f64, y: f64) -> (f32, f32) { + ((x - self.x) as f32, (y - self.y) as f32) + } + + /// A zone-local point in world coordinates. + pub fn to_world(self, x: f32, y: f32) -> (f64, f64) { + (self.x + f64::from(x), self.y + f64::from(y)) + } +} + +/// Server handshake reply. +#[derive(Debug, Clone, PartialEq)] +pub struct Welcome { + /// Opaque session id (stable across reconnects of the same player). + pub session_id: String, + /// Zone joined. + pub zone_id: String, + /// Admitted role. + pub role: Role, + /// Simulation ticks per second (Hot tier). + pub tick_rate: u32, + /// Deltas per second. + pub patch_rate: u32, + /// Current server tick. + pub server_tick: u32, + /// Server clock in ms. + pub server_time: f64, + /// Token for Hello.reconnect_token after a drop. + pub reconnect_token: String, + /// Server content version. + pub content_version: String, + /// Replicated entity schema. + pub schema: EntitySchema, + /// Runtime features of the server ([`feature`]). + pub features: u32, + /// Where the zone sits in the world, when it says (`Zone::origin`). + pub origin: Option, +} + +/// Full entity state for a create. +#[derive(Debug, Clone, PartialEq)] +pub struct EntityCreate { + /// Entity id. + pub id: u32, + /// Kind id. + pub kind: u16, + /// Every field, schema order. + pub fields: Vec, +} + +/// Changed fields of a known entity. +#[derive(Debug, Clone, PartialEq)] +pub struct EntityUpdate { + /// Entity id. + pub id: u32, + /// Bit `i` set = field `i` present. + pub mask: u32, + /// Present fields in ascending index order. + pub fields: Vec, +} + +/// One replication patch. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Delta { + /// Server tick the state belongs to. + pub server_tick: u32, + /// Highest processed input sequence of this client (0 = none). + pub ack_seq: u32, + /// Ids to forget (applied first). + pub removes: Vec, + /// New entities (applied second). + pub creates: Vec, + /// Field changes (applied last). + pub updates: Vec, +} + +/// Freeze/Resume notice. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Notice { + /// Machine-readable reason. + pub reason: String, + /// Version involved (e.g. content version being rolled out). + pub version: String, + /// Human-readable notes. + pub notes: String, +} + +/// Messages the server sends. +#[derive(Debug, Clone, PartialEq)] +pub enum ServerMessage { + /// Handshake accepted. + Welcome(Welcome), + /// Replication patch. + Delta(Delta), + /// Reliable game event. + Event { + /// Game-defined event type. + type_id: u32, + /// Game-defined payload. + payload: Vec, + }, + /// Clock sync reply. + Pong { + /// Echoed client time (ms). + client_time: f64, + /// Server clock (ms). + server_time: f64, + }, + /// Simulation frozen (inputs ignored until Resume). + Freeze(Notice), + /// Simulation resumed. + Resume(Notice), + /// Move to another zone. + Handoff { + /// Destination zone id. + target_zone: String, + /// Ticket to present in the next Hello. + transfer_ticket: String, + }, + /// Removed from the zone; the server closes the socket. + Kick { + /// See [`kick`]. + code: u32, + /// Text. + message: String, + }, + /// Request-level error; handshake errors are followed by close. + Error { + /// See [`error`]. + code: u32, + /// Text. + message: String, + }, + /// This host does not own `zone_id`: reconnect to `url` and send the + /// same Hello again (the ticket was not consumed). Followed by close. + Redirect { + /// Zone the client asked for. + zone_id: String, + /// Full WebSocket URL of the owning host's zone endpoint. + url: String, + }, +} + +/// What a decoder/encoder needs to know about the client's view: the +/// schema and the known ids (Deltas). +pub trait EntityKinds { + /// Schema from the Welcome. + fn schema(&self) -> Option<&EntitySchema>; + /// Kind of a known entity id. + fn kind_of(&self, id: u32) -> Option; +} + +/// No schema: Deltas cannot be decoded. +impl EntityKinds for () { + fn schema(&self) -> Option<&EntitySchema> { + None + } + fn kind_of(&self, _: u32) -> Option { + None + } +} + +/// Schema plus an explicit id→kind table (fixtures/tests). +impl EntityKinds for (EntitySchema, BTreeMap) { + fn schema(&self) -> Option<&EntitySchema> { + Some(&self.0) + } + fn kind_of(&self, id: u32) -> Option { + self.1.get(&id).copied() + } +} + +impl ServerMessage { + /// Encode one message. Deltas need `kinds` (schema + known ids). + pub fn encode(&self, kinds: &dyn EntityKinds) -> Result, DecodeError> { + let mut w = Writer::new(); + match self { + Self::Welcome(m) => { + w.u8(tag::WELCOME) + .string(&m.session_id) + .string(&m.zone_id) + .u8(match m.role { + Role::Player => 0, + Role::Observer => 1, + }) + .varuint(m.tick_rate) + .varuint(m.patch_rate) + .varuint(m.server_tick) + .f64(m.server_time) + .string(&m.reconnect_token) + .string(&m.content_version); + m.schema.encode(&mut w); + w.varuint(m.features).bool(m.origin.is_some()); + if let Some(origin) = m.origin { + w.f64(origin.x).f64(origin.y); + } + } + Self::Delta(d) => encode_delta(&mut w, d, kinds)?, + Self::Event { type_id, payload } => { + w.u8(tag::EVENT).varuint(*type_id).bytes(payload); + } + Self::Pong { + client_time, + server_time, + } => { + w.u8(tag::PONG).f64(*client_time).f64(*server_time); + } + Self::Freeze(n) | Self::Resume(n) => { + let t = if matches!(self, Self::Freeze(_)) { + tag::FREEZE + } else { + tag::RESUME + }; + w.u8(t) + .string(&n.reason) + .string(&n.version) + .string(&n.notes); + } + Self::Handoff { + target_zone, + transfer_ticket, + } => { + w.u8(tag::HANDOFF) + .string(target_zone) + .string(transfer_ticket); + } + Self::Kick { code, message } => { + w.u8(tag::KICK).varuint(*code).string(message); + } + Self::Error { code, message } => { + w.u8(tag::ERROR).varuint(*code).string(message); + } + Self::Redirect { zone_id, url } => { + w.u8(tag::REDIRECT).string(zone_id).string(url); + } + } + Ok(w.into_bytes()) + } + + /// Decode one message. Deltas need `kinds`. + pub fn decode(bytes: &[u8], kinds: &dyn EntityKinds) -> Result { + let mut r = Reader::new(bytes); + let message = match r.u8()? { + tag::WELCOME => Self::Welcome(decode_welcome(&mut r)?), + tag::DELTA => Self::Delta(decode_delta(&mut r, kinds)?), + tag::EVENT => Self::Event { + type_id: r.varuint()?, + payload: r.bytes()?.to_vec(), + }, + tag::PONG => Self::Pong { + client_time: r.f64()?, + server_time: r.f64()?, + }, + t @ (tag::FREEZE | tag::RESUME) => { + let notice = Notice { + reason: r.string()?, + version: r.string()?, + notes: r.string()?, + }; + if t == tag::FREEZE { + Self::Freeze(notice) + } else { + Self::Resume(notice) + } + } + tag::HANDOFF => Self::Handoff { + target_zone: r.string()?, + transfer_ticket: r.string()?, + }, + tag::KICK => Self::Kick { + code: r.varuint()?, + message: r.string()?, + }, + tag::ERROR => Self::Error { + code: r.varuint()?, + message: r.string()?, + }, + tag::REDIRECT => Self::Redirect { + zone_id: r.string()?, + url: r.string()?, + }, + other => return Err(DecodeError::UnknownMessage(other)), + }; + r.finish()?; + Ok(message) + } +} + +fn decode_welcome(r: &mut Reader<'_>) -> Result { + Ok(Welcome { + session_id: r.string()?, + zone_id: r.string()?, + role: match r.u8()? { + 0 => Role::Player, + 1 => Role::Observer, + _ => return Err(DecodeError::Invalid("role")), + }, + tick_rate: r.varuint()?, + patch_rate: r.varuint()?, + server_tick: r.varuint()?, + server_time: r.f64()?, + reconnect_token: r.string()?, + content_version: r.string()?, + schema: EntitySchema::decode(r)?, + features: r.varuint()?, + origin: match r.bool()? { + true => Some(Origin { + x: r.f64()?, + y: r.f64()?, + }), + false => None, + }, + }) +} + +fn kind_lookup( + id: u32, + created: &BTreeMap, + kinds: &dyn EntityKinds, +) -> Result { + created + .get(&id) + .copied() + .or_else(|| kinds.kind_of(id)) + .ok_or(DecodeError::UnknownEntity(id)) +} + +fn encode_delta(w: &mut Writer, d: &Delta, kinds: &dyn EntityKinds) -> Result<(), DecodeError> { + let schema = kinds + .schema() + .ok_or(DecodeError::Invalid("delta needs a schema"))?; + w.u8(tag::DELTA).varuint(d.server_tick).varuint(d.ack_seq); + w.varuint(d.removes.len() as u32); + for id in &d.removes { + w.varuint(*id); + } + let mut created = BTreeMap::new(); + w.varuint(d.creates.len() as u32); + for c in &d.creates { + let kind = schema.get(c.kind).ok_or(DecodeError::UnknownEntity(c.id))?; + if kind.fields.len() != c.fields.len() { + return Err(DecodeError::Invalid("create must carry every field")); + } + w.varuint(c.id).varuint(u32::from(c.kind)); + for (def, value) in kind.fields.iter().zip(&c.fields) { + def.ty.encode(w, value); + } + created.insert(c.id, c.kind); + } + w.varuint(d.updates.len() as u32); + for u in &d.updates { + let kind_id = kind_lookup(u.id, &created, kinds)?; + let kind = schema + .get(kind_id) + .ok_or(DecodeError::UnknownEntity(u.id))?; + w.varuint(u.id).varuint(u.mask); + let mut values = u.fields.iter(); + for (index, def) in kind.fields.iter().enumerate() { + if u.mask & (1 << index) != 0 { + let value = values + .next() + .ok_or(DecodeError::Invalid("mask/field count mismatch"))?; + def.ty.encode(w, value); + } + } + } + Ok(()) +} + +fn decode_delta(r: &mut Reader<'_>, kinds: &dyn EntityKinds) -> Result { + let schema = kinds + .schema() + .ok_or(DecodeError::Invalid("delta needs a schema"))?; + let mut delta = Delta { + server_tick: r.varuint()?, + ack_seq: r.varuint()?, + ..Delta::default() + }; + for _ in 0..r.varuint()? { + delta.removes.push(r.varuint()?); + } + let mut created = BTreeMap::new(); + for _ in 0..r.varuint()? { + let id = r.varuint()?; + let kind_id = u16::try_from(r.varuint()?).map_err(|_| DecodeError::Invalid("kind"))?; + let kind = schema.get(kind_id).ok_or(DecodeError::UnknownEntity(id))?; + let mut fields = Vec::with_capacity(kind.fields.len()); + for def in &kind.fields { + fields.push(def.ty.decode(r)?); + } + created.insert(id, kind_id); + delta.creates.push(EntityCreate { + id, + kind: kind_id, + fields, + }); + } + for _ in 0..r.varuint()? { + let id = r.varuint()?; + let kind = schema + .get(kind_lookup(id, &created, kinds)?) + .ok_or(DecodeError::UnknownEntity(id))?; + let mask = r.varuint()?; + if kind.fields.len() < 32 && mask >> kind.fields.len() != 0 { + return Err(DecodeError::Invalid("mask names a field the kind lacks")); + } + let mut fields = Vec::new(); + for (index, def) in kind.fields.iter().enumerate() { + if mask & (1 << index) != 0 { + fields.push(def.ty.decode(r)?); + } + } + delta.updates.push(EntityUpdate { id, mask, fields }); + } + Ok(delta) +} + +/// Mirrored entity on a client. +#[derive(Debug, Clone, PartialEq)] +pub struct MirrorEntity { + /// Kind id. + pub kind: u16, + /// Current decoded field values. + pub fields: Vec, +} + +/// Reference client-side state: decodes server frames and applies Deltas. +/// +/// This is the normative behaviour a client implementation (e.g. JS) must +/// match; it is also what the crate's own tests use. +#[derive(Debug, Clone, Default)] +pub struct ClientMirror { + /// Last Welcome. + pub welcome: Option, + /// Known entities. + pub entities: BTreeMap, + /// Last Delta tick. + pub server_tick: u32, + /// Last acked input sequence. + pub ack_seq: u32, +} + +impl EntityKinds for ClientMirror { + fn schema(&self) -> Option<&EntitySchema> { + self.welcome.as_ref().map(|w| &w.schema) + } + fn kind_of(&self, id: u32) -> Option { + self.entities.get(&id).map(|e| e.kind) + } +} + +impl ClientMirror { + /// Empty mirror. + pub fn new() -> Self { + Self::default() + } + + /// Decode a frame and apply it. Welcome resets all entities. + pub fn apply(&mut self, frame: &[u8]) -> Result { + let message = ServerMessage::decode(frame, self)?; + match &message { + ServerMessage::Welcome(w) => { + self.welcome = Some(w.clone()); + self.entities.clear(); + self.server_tick = w.server_tick; + } + ServerMessage::Delta(d) => { + for id in &d.removes { + self.entities.remove(id); + } + for c in &d.creates { + self.entities.insert( + c.id, + MirrorEntity { + kind: c.kind, + fields: c.fields.clone(), + }, + ); + } + for u in &d.updates { + let entity = self + .entities + .get_mut(&u.id) + .ok_or(DecodeError::UnknownEntity(u.id))?; + let mut values = u.fields.iter(); + for (index, slot) in entity.fields.iter_mut().enumerate() { + if u.mask & (1 << index) != 0 { + if let Some(v) = values.next() { + *slot = v.clone(); + } + } + } + } + self.server_tick = d.server_tick; + self.ack_seq = d.ack_seq; + } + _ => {} + } + Ok(message) + } +} diff --git a/distributed_game/src/protocol/mod.rs b/distributed_game/src/protocol/mod.rs new file mode 100644 index 000000000..080f41e30 --- /dev/null +++ b/distributed_game/src/protocol/mod.rs @@ -0,0 +1,30 @@ +//! Binary wire protocol (normative spec: `PROTOCOL.md`). +//! +//! One message per WebSocket binary frame; the first byte is the message +//! type. [`wire`] holds the primitives, [`messages`] the message codecs and +//! the reference [`ClientMirror`]. + +pub mod messages; +pub mod wire; + +pub use messages::*; +pub use wire::{DecodeError, Reader, Writer}; + +/// Length-prefix a frame (`varuint` length) for stream transports that lack +/// message boundaries (`PROTOCOL.md` §1.2). +pub fn frame_stream(message: &[u8]) -> Vec { + let mut w = Writer::new(); + w.bytes(message); + w.into_bytes() +} + +/// Split one length-prefixed frame off the front of `buf`; returns the frame +/// and the bytes consumed, or `None` when more data is needed. +pub fn unframe_stream(buf: &[u8]) -> Result, DecodeError> { + let mut r = Reader::new(buf); + match r.bytes() { + Ok(frame) => Ok(Some((frame, buf.len() - r.remaining()))), + Err(DecodeError::UnexpectedEof) => Ok(None), + Err(e) => Err(e), + } +} diff --git a/distributed_game/src/protocol/wire.rs b/distributed_game/src/protocol/wire.rs new file mode 100644 index 000000000..56f73fc8a --- /dev/null +++ b/distributed_game/src/protocol/wire.rs @@ -0,0 +1,331 @@ +//! Primitive wire encodings (see `PROTOCOL.md` §2). +//! +//! All multi-byte fixed-width numbers are little-endian. `varuint` is +//! unsigned LEB128 (7 bits per byte, low group first, high bit = continue); +//! encoders always emit the minimal form. `varint` is a zigzag-mapped +//! `varuint`. Strings are UTF-8 prefixed by a `varuint` byte length; short +//! strings use a single `u8` length. + +use std::fmt; + +/// Largest `string`/`bytes` length accepted by decoders (1 MiB). +pub const MAX_BLOB_LEN: usize = 1 << 20; + +/// Largest value [`Writer::varuint64`] / [`Reader::varuint64`] carry: +/// `2^53 - 1`, the largest integer a JavaScript `number` holds exactly. +pub const MAX_SAFE_U64: u64 = (1 << 53) - 1; + +/// Decoding failure. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DecodeError { + /// Input ended mid-value. + UnexpectedEof, + /// A varuint exceeded 32 bits. + VarintOverflow, + /// A string was not valid UTF-8. + InvalidUtf8, + /// Unknown message type byte. + UnknownMessage(u8), + /// Unknown field type tag in a schema. + UnknownFieldType(u8), + /// Delta referenced an entity kind / id the decoder does not know. + UnknownEntity(u32), + /// Structurally invalid value. + Invalid(&'static str), + /// Bytes left over after a complete message. + TrailingBytes(usize), +} + +impl fmt::Display for DecodeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{self:?}") + } +} + +impl std::error::Error for DecodeError {} + +/// Append-only encoder. +#[derive(Debug, Default, Clone)] +pub struct Writer { + buf: Vec, +} + +impl Writer { + /// Empty writer. + pub fn new() -> Self { + Self::default() + } + + /// Empty writer with room for `capacity` bytes. + pub(crate) fn with_capacity(capacity: usize) -> Self { + Self { + buf: Vec::with_capacity(capacity), + } + } + + /// Bytes written so far. + pub fn len(&self) -> usize { + self.buf.len() + } + + /// True if nothing was written. + pub fn is_empty(&self) -> bool { + self.buf.is_empty() + } + + /// Finish and take the bytes. + pub fn into_bytes(self) -> Vec { + self.buf + } + + /// Borrow the bytes. + pub fn as_bytes(&self) -> &[u8] { + &self.buf + } + + /// Discard contents, keeping capacity. + pub fn clear(&mut self) { + self.buf.clear(); + } + + /// Raw bytes, no prefix. + pub fn raw(&mut self, bytes: &[u8]) -> &mut Self { + self.buf.extend_from_slice(bytes); + self + } + + /// One byte. + pub fn u8(&mut self, v: u8) -> &mut Self { + self.buf.push(v); + self + } + + /// `0x00`/`0x01`. + pub fn bool(&mut self, v: bool) -> &mut Self { + self.u8(u8::from(v)) + } + + /// Unsigned LEB128 (max 5 bytes). + pub fn varuint(&mut self, mut v: u32) -> &mut Self { + loop { + let byte = (v & 0x7f) as u8; + v >>= 7; + if v == 0 { + self.buf.push(byte); + return self; + } + self.buf.push(byte | 0x80); + } + } + + /// Unsigned LEB128 of a `u64`, saturated to [`MAX_SAFE_U64`] so a + /// JavaScript `number` decodes it exactly. Only typed game payloads + /// ([`codec`](crate::codec)) use it; no protocol message does. + pub fn varuint64(&mut self, v: u64) -> &mut Self { + let mut v = v.min(MAX_SAFE_U64); + loop { + let byte = (v & 0x7f) as u8; + v >>= 7; + if v == 0 { + self.buf.push(byte); + return self; + } + self.buf.push(byte | 0x80); + } + } + + /// Zigzag-mapped signed varint: `(v << 1) ^ (v >> 31)`. + pub fn varint(&mut self, v: i32) -> &mut Self { + self.varuint(((v << 1) ^ (v >> 31)) as u32) + } + + /// IEEE-754 binary32, little-endian. + pub fn f32(&mut self, v: f32) -> &mut Self { + self.raw(&v.to_le_bytes()) + } + + /// IEEE-754 binary64, little-endian. + pub fn f64(&mut self, v: f64) -> &mut Self { + self.raw(&v.to_le_bytes()) + } + + /// `varuint` length + UTF-8. + pub fn string(&mut self, v: &str) -> &mut Self { + self.bytes(v.as_bytes()) + } + + /// `u8` length + UTF-8; truncated at a char boundary to <= 255 bytes. + pub fn short_string(&mut self, v: &str) -> &mut Self { + let mut end = v.len().min(255); + while !v.is_char_boundary(end) { + end -= 1; + } + self.u8(end as u8).raw(&v.as_bytes()[..end]) + } + + /// `varuint` length + raw bytes. + pub fn bytes(&mut self, v: &[u8]) -> &mut Self { + self.varuint(v.len() as u32).raw(v) + } +} + +/// Cursor over a byte slice. +#[derive(Debug, Clone)] +pub struct Reader<'a> { + buf: &'a [u8], + pos: usize, +} + +impl<'a> Reader<'a> { + /// Read from the start of `buf`. + pub fn new(buf: &'a [u8]) -> Self { + Self { buf, pos: 0 } + } + + /// Bytes not yet consumed. + pub fn remaining(&self) -> usize { + self.buf.len() - self.pos + } + + /// Error unless fully consumed. + pub fn finish(&self) -> Result<(), DecodeError> { + match self.remaining() { + 0 => Ok(()), + n => Err(DecodeError::TrailingBytes(n)), + } + } + + /// Next `n` raw bytes. + pub fn raw(&mut self, n: usize) -> Result<&'a [u8], DecodeError> { + if self.remaining() < n { + return Err(DecodeError::UnexpectedEof); + } + let slice = &self.buf[self.pos..self.pos + n]; + self.pos += n; + Ok(slice) + } + + /// One byte. + pub fn u8(&mut self) -> Result { + Ok(self.raw(1)?[0]) + } + + /// Strict bool (`0` or `1`). + pub fn bool(&mut self) -> Result { + match self.u8()? { + 0 => Ok(false), + 1 => Ok(true), + _ => Err(DecodeError::Invalid("bool must be 0 or 1")), + } + } + + /// Unsigned LEB128 up to 32 bits. + pub fn varuint(&mut self) -> Result { + let mut value: u32 = 0; + for index in 0..5 { + let byte = self.u8()?; + if index == 4 && byte > 0x0f { + return Err(DecodeError::VarintOverflow); + } + value |= u32::from(byte & 0x7f) << (7 * index); + if byte & 0x80 == 0 { + return Ok(value); + } + } + Err(DecodeError::VarintOverflow) + } + + /// Unsigned LEB128 up to [`MAX_SAFE_U64`] (`2^53 - 1`, exact in a + /// JavaScript `number`); longer or non-minimal-overflowing input is an error. + pub fn varuint64(&mut self) -> Result { + let mut value: u64 = 0; + for index in 0..8 { + let byte = self.u8()?; + value |= u64::from(byte & 0x7f) << (7 * index); + if byte & 0x80 == 0 { + if value > MAX_SAFE_U64 { + return Err(DecodeError::VarintOverflow); + } + return Ok(value); + } + } + Err(DecodeError::VarintOverflow) + } + + /// Zigzag signed varint. + pub fn varint(&mut self) -> Result { + let raw = self.varuint()?; + Ok(((raw >> 1) as i32) ^ -((raw & 1) as i32)) + } + + /// binary32 LE. + pub fn f32(&mut self) -> Result { + let bytes = self.raw(4)?; + Ok(f32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])) + } + + /// binary64 LE. + pub fn f64(&mut self) -> Result { + let mut bytes = [0u8; 8]; + bytes.copy_from_slice(self.raw(8)?); + Ok(f64::from_le_bytes(bytes)) + } + + /// `varuint` length + raw bytes. + pub fn bytes(&mut self) -> Result<&'a [u8], DecodeError> { + let len = self.varuint()? as usize; + if len > MAX_BLOB_LEN { + return Err(DecodeError::Invalid("length exceeds 1 MiB")); + } + self.raw(len) + } + + /// `varuint` length + UTF-8. + pub fn string(&mut self) -> Result { + let bytes = self.bytes()?; + String::from_utf8(bytes.to_vec()).map_err(|_| DecodeError::InvalidUtf8) + } + + /// `u8` length + UTF-8. + pub fn short_string(&mut self) -> Result { + let len = self.u8()? as usize; + String::from_utf8(self.raw(len)?.to_vec()).map_err(|_| DecodeError::InvalidUtf8) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn varuint_round_trips_and_is_minimal() { + for (value, hex) in [ + (0u32, "00"), + (1, "01"), + (127, "7f"), + (128, "8001"), + (300, "ac02"), + (u32::MAX, "ffffffff0f"), + ] { + let mut w = Writer::new(); + w.varuint(value); + let got: String = w.as_bytes().iter().map(|b| format!("{b:02x}")).collect(); + assert_eq!(got, hex); + assert_eq!(Reader::new(w.as_bytes()).varuint().unwrap(), value); + } + assert_eq!( + Reader::new(&[0xff, 0xff, 0xff, 0xff, 0x10]).varuint(), + Err(DecodeError::VarintOverflow) + ); + } + + #[test] + fn zigzag_round_trips() { + for (value, raw) in [(0, 0u32), (-1, 1), (1, 2), (-2, 3), (i32::MIN, u32::MAX)] { + let mut w = Writer::new(); + w.varint(value); + assert_eq!(Reader::new(w.as_bytes()).varuint().unwrap(), raw); + assert_eq!(Reader::new(w.as_bytes()).varint().unwrap(), value); + } + } +} diff --git a/distributed_game/src/pure.rs b/distributed_game/src/pure.rs new file mode 100644 index 000000000..d49d6f558 --- /dev/null +++ b/distributed_game/src/pure.rs @@ -0,0 +1,183 @@ +//! Pure game functions, declared once in Rust and compiled to WebAssembly +//! for the browser next to the zone's predicted step. +//! +//! Some client code is neither prediction nor protocol but must still agree +//! with the server exactly: procedural world content (terrain, props), a +//! loot table preview, a path cost. Declare such a function with +//! `#[game_pure]`, name it in the zone's [`GameSurface`](crate::GameSurface) +//! and the generated client calls the *same* code, compiled to +//! `wasm32-unknown-unknown`: +//! +//! ```ignore +//! /// Terrain and props of one cell. +//! #[game_pure(GridCellFn)] +//! pub fn grid_cell(cell: &CellRequest) -> CellContent { +//! /* … */ +//! } +//! +//! pub fn game_surface() -> GameSurface { +//! GameSurface::for_zone::("grid").pure::() +//! } +//! ``` +//! +//! The function takes nothing or one shared reference to a [`Wire`] value +//! (typically a `#[derive(GameRecord)]` struct) and returns a [`Wire`] +//! value. `distributed game-client` emits `pures.ts`, a typed wrapper per +//! function (`gridCell(cell: CellRequest): CellContent`), and `distributed +//! game-wasm` compiles it into the surface's module. +//! +//! # Binary ABI +//! +//! Pure functions share the module and the ABI of the predicted step +//! ([`crate::prediction`], v1): the same `memory`, `dg_predict_abi` and +//! `dg_predict_buffer` scratch area, and one export per function, +//! `dg_pure_(arg_len) -> i32`. The caller writes the argument's codec +//! encoding into the scratch buffer and calls the export; a non-negative +//! result is the length of the output's encoding, written at the start of +//! the buffer; negative values are [`AbiError`] codes. The output must fit +//! the 64 KiB buffer. No JSON, no allocation crosses the boundary. +//! +//! # Determinism +//! +//! The rules of [`crate::prediction`] apply: only correctly rounded IEEE-754 +//! operations (`+ - * /`, `sqrt`, `floor`, …), no platform transcendentals, +//! no NaN. The function must be a pure function of its argument (caching +//! inside is fine; the module is single-threaded). + +use crate::codec::{Wire, WireType}; +use crate::prediction::{AbiError, PredictContext}; +use crate::protocol::wire::Writer; +use crate::surface::RecordSurface; + +/// A pure game function compiled to WebAssembly (see the module docs). +/// Implemented by the `#[game_pure]` attribute. +pub trait GamePure { + /// Cargo package that declares the function (`env!("CARGO_PKG_NAME")`). + const PACKAGE: &'static str; + /// Export suffix: the function is `dg_pure_` in the module. + const EXPORT: &'static str; + /// Argument: `()` for none, otherwise any [`Wire`] value. + type Arg: PureArg; + /// Result. + type Output: Wire; + + /// Run the function. + fn call(arg: &Self::Arg) -> Self::Output; +} + +/// The argument of a [`GamePure`]: `()` (none) or any [`Wire`] value. Same +/// shape as a predicted step's context. +pub trait PureArg: PredictContext {} + +impl PureArg for T {} + +/// The wire type of `T`'s argument (`None` for `()`) and the records it +/// mentions. +pub(crate) fn arg_type(records: &mut Vec) -> Option { + F::Arg::context_records(records); + F::Arg::context_type() +} + +/// One call over encoded bytes: what the WASM export does, callable natively +/// (tools, tests). Returns the encoded output. +pub fn call_bytes(arg: &[u8]) -> Result, AbiError> { + let arg = F::Arg::decode_context(arg).map_err(|_| AbiError::Argument)?; + let out = F::call(&arg); + let mut w = Writer::new(); + out.encode(&mut w); + Ok(w.into_bytes()) +} + +/// The ABI over a buffer holding the encoded argument: decodes, calls and +/// writes the encoded output at the start of `buffer`. Returns its length or +/// a negative [`AbiError`] code. The WASM exports call this on the scratch +/// buffer. +pub fn run_abi(buffer: &mut [u8], arg_len: u32) -> i32 { + let len = arg_len as usize; + if len > buffer.len() { + return AbiError::TooLarge as i32; + } + let out = match call_bytes::(&buffer[..len]) { + Ok(out) => out, + Err(error) => return error as i32, + }; + if out.len() > buffer.len() { + return AbiError::Output as i32; + } + buffer[..out.len()].copy_from_slice(&out); + out.len() as i32 +} + +/// Body of a generated `dg_pure_` export (`#[game_pure]`, `wasm32` only). +#[cfg(target_arch = "wasm32")] +#[doc(hidden)] +pub fn wasm_export(arg_len: u32) -> i32 { + run_abi::(crate::prediction::scratch_buffer(), arg_len) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::GameRecord; + + #[derive(Debug, Clone, PartialEq, GameRecord)] + struct Span { + from: i32, + to: i32, + } + + struct Squares; + impl GamePure for Squares { + const PACKAGE: &'static str = "test"; + const EXPORT: &'static str = "squares"; + type Arg = Span; + type Output = Vec; + fn call(span: &Span) -> Vec { + (span.from..span.to).map(|i| (i * i) as u32).collect() + } + } + + struct Answer; + impl GamePure for Answer { + const PACKAGE: &'static str = "test"; + const EXPORT: &'static str = "answer"; + type Arg = (); + type Output = u8; + fn call(_: &()) -> u8 { + 42 + } + } + + #[test] + fn abi_calls_in_place() { + let arg = crate::codec::to_bytes(&Span { from: -2, to: 3 }); + let mut buffer = vec![0u8; 64]; + buffer[..arg.len()].copy_from_slice(&arg); + let n = run_abi::(&mut buffer, arg.len() as u32); + assert!(n > 0); + let out: Vec = crate::codec::from_bytes(&buffer[..n as usize]).unwrap(); + assert_eq!(out, [4, 1, 0, 1, 4]); + assert_eq!(call_bytes::(&[]).unwrap(), [42]); + } + + #[test] + fn abi_reports_errors() { + let mut buffer = vec![0u8; 4]; + assert_eq!( + run_abi::(&mut buffer, 9), + AbiError::TooLarge as i32 + ); + assert_eq!( + run_abi::(&mut buffer, 1), + AbiError::Argument as i32 + ); + assert_eq!(call_bytes::(&[1]), Err(AbiError::Argument)); + let arg = crate::codec::to_bytes(&Span { from: 0, to: 100 }); + let mut small = vec![0u8; 8]; + small[..arg.len()].copy_from_slice(&arg); + assert_eq!( + run_abi::(&mut small, arg.len() as u32), + AbiError::Output as i32 + ); + } +} diff --git a/distributed_game/src/replay.rs b/distributed_game/src/replay.rs new file mode 100644 index 000000000..68531c4b4 --- /dev/null +++ b/distributed_game/src/replay.rs @@ -0,0 +1,278 @@ +//! Deterministic record/replay. +//! +//! A host created with [`HostConfig::record`] keeps every [`Stimulus`] it +//! is [applied](ZoneHost::apply) — joins, reconnects, disconnects, inputs, +//! content patches, focus, inbox kicks and messages, zone messages, child +//! events, freeze/resume, version switches, reloads, kicks, handoffs, +//! restores, dispose and each advance — whichever driver applies it (the +//! native server, a celld zone object, a test). Each [`Entry`] carries the +//! clock reading the stimulus ran at (monotonic and wall: the host freezes +//! both for the whole stimulus, so every time the zone and its fact stamps +//! see is in the recording) and what it observed: join and input outcomes, +//! and for an advance the fact settlements delivered (tagged with their +//! tick) and a state hash after every tick. Timers, RNG draws and tier +//! changes are *not* logged: they are derived from those inputs and the +//! clock, so replay reproduces them. Handoffs issued by the zone replay +//! against a stub issuer that always signs (the ticket text is output, not +//! state); a recording made with an issuer that *refused* a handoff will +//! diverge. +//! +//! [`replay`] rebuilds a fresh host on the recorded clock readings, applies +//! the entries back (settlements through a [`FactQueue::scripted`] queue so +//! they land on the same tick) and compares join and input outcomes and the +//! per-tick hashes. The first mismatch is returned as a [`Divergence`] +//! whose `Display` shows the tick, the hashes and the stimuli applied since +//! the last matching advance. A successful replay returns the facts the +//! zone emitted ([`ReplaySummary::facts`]): the same keys, inputs, +//! principals and stamps as the live run's. +//! +//! Requirements for a zone to replay: all randomness from +//! [`Ctx::rng`](crate::Ctx::rng), all time from the [`Ctx`](crate::Ctx) +//! (never wall time read directly), no iteration over `HashMap`s that feeds +//! state. Override [`Zone::state_hash`] to cover unreplicated state. +//! +//! The file is compact binary (`DGR4`, varints; see [`Recording::encode`]). +//! Reconnect tokens are stored as their place in the host's token sequence +//! (`token#N`), never as secrets. [`replay`] takes the zone's `Z::Config`. + +use std::collections::BTreeMap; +use std::fmt; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use crate::clock::Clock; +use crate::facts::{Fact, FactError, FactOutcome, FactQueue, FactReceipt, FactSettlement}; +use crate::handoff::{HandoffRequest, Transfer}; +use crate::host::{HostConfig, JoinError, Joined, Outcome, Stimulus, ZoneHost}; +use crate::input::PushOutcome; +use crate::interest::InterestConfig; +use crate::protocol::wire::{DecodeError, Reader, Writer}; +use crate::protocol::{Notice, Role}; +use crate::replication::WorldView; +use crate::rewind::RewindConfig; +use crate::rng::Fnv64; +use crate::schema::FieldValue; +use crate::world::{ChildEvent, StalePolicy}; +use crate::zone::{ClientId, PlayerId, TicketClaims, Zone}; +use crate::zone_message::ZoneEnvelope; + +mod codec; +mod run; + +pub use run::{replay, replay_with, tick_hashes, Divergence, DivergenceKind, ReplaySummary}; + +/// FNV digest of a replicated world (entity order, ids, kinds, positions, +/// priorities and field values). +pub fn hash_world(view: &WorldView) -> u64 { + let mut h = Fnv64::new(); + for e in view.entities() { + h.write_u64(u64::from(e.id)) + .write_u64(u64::from(e.kind)) + .write_f32(e.x) + .write_f32(e.y) + .write_f32(e.priority) + .write(&[u8::from(e.global)]); + for f in &e.fields { + match f { + FieldValue::Bool(v) => h.write(&[0, u8::from(*v)]), + FieldValue::U(v) => h.write(&[1]).write_u64(u64::from(*v)), + FieldValue::I(v) => h.write(&[2]).write(&v.to_le_bytes()), + FieldValue::F(v) => h.write(&[3]).write_f32(*v), + FieldValue::Str(v) => h.write(&[4]).write_u64(v.len() as u64).write(v.as_bytes()), + FieldValue::Bytes(v) => h.write(&[5]).write_u64(v.len() as u64).write(v), + }; + } + } + h.finish() +} + +/// Result of a recorded join/reconnect. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum JoinResult { + /// Admitted on this connection id. + Joined(u32), + /// Refused with this error code. + Refused(u32), +} + +impl From<&Result> for JoinResult { + fn from(r: &Result) -> Self { + match r { + Ok(j) => Self::Joined(j.client.0), + Err(e) => Self::Refused(e.code), + } + } +} + +/// What a recorded stimulus observed that replay must reproduce. +#[derive(Debug, Clone, PartialEq)] +pub enum Observed { + /// Nothing checked. + Nothing, + /// A join or reconnect. + Join(JoinResult), + /// An input. + Input(PushOutcome), + /// An advance. + Advance { + /// Settlements delivered, with their delivery tick (the fact + /// sink's answers: replayed, not recomputed). + settled: Vec<(u64, FactSettlement)>, + /// `(tick, hash)` after each tick simulated. + hashes: Vec<(u64, u64)>, + }, +} + +impl Observed { + pub(crate) fn of(outcome: &Outcome) -> Self { + match outcome { + Outcome::Joined(result) => Self::Join(result.into()), + Outcome::Input(outcome) => Self::Input(*outcome), + Outcome::Advanced(report) => Self::Advance { + settled: report.settled.clone(), + hashes: report.tick_hashes.clone(), + }, + _ => Self::Nothing, + } + } +} + +/// One recorded stimulus. +#[derive(Debug, Clone, PartialEq)] +pub struct Entry { + /// Host clock when it ran. + pub at: Duration, + /// Wall time (Unix ms) when it ran. + pub unix_ms: u64, + /// The stimulus (a reconnect's token as `token#N`). + pub stimulus: Stimulus, + /// What it observed. + pub observed: Observed, +} + +/// The recorded name of the `n`-th token a host issued. +pub(crate) fn token_label(n: usize) -> String { + format!("token#{n}") +} + +impl fmt::Display for Entry { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "@{:.1}ms ", self.at.as_secs_f64() * 1000.0)?; + match &self.stimulus { + Stimulus::Join { claims, .. } => write!(f, "join {}", claims.principal)?, + Stimulus::JoinTransfer { transfer, .. } => write!( + f, + "join transfer {} from {}", + transfer.claims.principal, transfer.source_zone + )?, + Stimulus::Reconnect { + token, + content_version, + .. + } => match content_version { + Some(version) => write!(f, "reconnect {token} version {version}")?, + None => write!(f, "reconnect {token}")?, + }, + Stimulus::Disconnect { client, graceful } => { + write!(f, "disconnect client {} graceful={graceful}", client.0)? + } + Stimulus::Input { + client, + seq, + client_tick, + payload, + } => write!( + f, + "input client {} seq {seq} client_tick {client_tick} payload {payload:02x?}", + client.0 + )?, + Stimulus::Content { client, version } => { + write!(f, "content client {} {version}", client.0)? + } + Stimulus::Focus { client, x, y } => write!(f, "focus client {} {x},{y}", client.0)?, + Stimulus::Kick { principal, .. } => write!(f, "inbox kick {principal}")?, + Stimulus::Message { type_id, .. } => write!(f, "inbox message {type_id}")?, + Stimulus::ZoneMessage(envelope) => write!( + f, + "zone message {} from {} type {}", + envelope.id, envelope.from, envelope.type_id + )?, + Stimulus::ChildEvent(event) => { + write!(f, "child event {} from {}", event.kind, event.origin_zone)? + } + Stimulus::RequestFreeze(notice) => write!(f, "request freeze {}", notice.reason)?, + Stimulus::CancelFreeze(notice) => write!(f, "cancel freeze {}", notice.reason)?, + Stimulus::Resume(notice) => write!(f, "resume {}", notice.reason)?, + Stimulus::ContentVersion(version) => write!(f, "content version {version}")?, + Stimulus::ConfigVersion(version) => write!(f, "config version {version}")?, + Stimulus::Reload(player) => write!(f, "reload player {}", player.0)?, + Stimulus::ReloadStale => write!(f, "reload stale players")?, + Stimulus::KickPlayer { player, message } => { + write!(f, "kick player {}: {message}", player.0)? + } + Stimulus::Handoff { + player, + target_zone, + .. + } => write!(f, "handoff player {} to {target_zone}", player.0)?, + Stimulus::Restore { state, .. } => write!(f, "restore {} bytes", state.len())?, + Stimulus::Dispose => write!(f, "dispose")?, + Stimulus::Advance => write!(f, "advance")?, + } + match &self.observed { + Observed::Nothing => Ok(()), + Observed::Join(result) => write!(f, " -> {result:?}"), + Observed::Input(outcome) => write!(f, " -> {outcome:?}"), + Observed::Advance { settled, hashes } => { + match (hashes.first(), hashes.last()) { + (Some(a), Some(b)) => write!(f, " ticks {}..={}", a.0, b.0)?, + _ => write!(f, " no ticks")?, + } + write!(f, ", {} settled", settled.len()) + } + } + } +} + +/// A recorded session. +#[derive(Debug, Clone, PartialEq)] +pub struct Recording { + /// Zone id (seeds the RNG). + pub zone_id: String, + /// Host configuration, as resolved at creation (the boot epoch). + pub config: HostConfig, + /// Clock when the host was created. + pub created_at: Duration, + /// Wall time (Unix ms) when the host was created. + pub created_unix_ms: u64, + /// Fact queue capacity, when a queue was attached. + pub fact_capacity: Option, + /// Stimuli in order. + pub entries: Vec, +} + +/// File decode failure. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RecordingError { + /// Not a `DGR4` file. + BadMagic, + /// Malformed content. + Decode(String), +} + +impl fmt::Display for RecordingError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::BadMagic => write!(f, "not a distributed_game recording"), + Self::Decode(e) => write!(f, "malformed recording: {e}"), + } + } +} + +impl std::error::Error for RecordingError {} + +impl From for RecordingError { + fn from(e: DecodeError) -> Self { + Self::Decode(e.to_string()) + } +} diff --git a/distributed_game/src/replay/codec.rs b/distributed_game/src/replay/codec.rs new file mode 100644 index 000000000..8ab4d5703 --- /dev/null +++ b/distributed_game/src/replay/codec.rs @@ -0,0 +1,648 @@ +//! The recording file: compact binary (`DGR4`, varints). + +use super::*; + +pub(super) const MAGIC: &[u8; 4] = b"DGR4"; + +pub(super) fn bad(what: &'static str) -> RecordingError { + RecordingError::Decode(what.into()) +} + +pub(super) fn put_u64(w: &mut Writer, mut v: u64) { + loop { + let byte = (v & 0x7f) as u8; + v >>= 7; + if v == 0 { + w.u8(byte); + return; + } + w.u8(byte | 0x80); + } +} + +pub(super) fn get_u64(r: &mut Reader<'_>) -> Result { + let mut v = 0u64; + for i in 0..10 { + let byte = r.u8()?; + v |= u64::from(byte & 0x7f) << (7 * i); + if byte & 0x80 == 0 { + return Ok(v); + } + } + Err(bad("u64 varint overflow")) +} + +pub(super) fn put_dur(w: &mut Writer, d: Duration) { + put_u64(w, d.as_nanos() as u64); +} + +pub(super) fn get_dur(r: &mut Reader<'_>) -> Result { + Ok(Duration::from_nanos(get_u64(r)?)) +} + +pub(super) fn put_notice(w: &mut Writer, n: &Notice) { + w.string(&n.reason).string(&n.version).string(&n.notes); +} + +pub(super) fn get_notice(r: &mut Reader<'_>) -> Result { + Ok(Notice { + reason: r.string()?, + version: r.string()?, + notes: r.string()?, + }) +} + +pub(super) fn put_join_result(w: &mut Writer, j: &JoinResult) { + match j { + JoinResult::Joined(c) => w.u8(0).varuint(*c), + JoinResult::Refused(c) => w.u8(1).varuint(*c), + }; +} + +pub(super) fn get_join_result(r: &mut Reader<'_>) -> Result { + match r.u8()? { + 0 => Ok(JoinResult::Joined(r.varuint()?)), + 1 => Ok(JoinResult::Refused(r.varuint()?)), + _ => Err(bad("join result")), + } +} + +pub(super) const OUTCOMES: [PushOutcome; 6] = [ + PushOutcome::Accepted, + PushOutcome::Duplicate, + PushOutcome::Stale, + PushOutcome::AcceptedDroppedOldest, + PushOutcome::Rejected, + PushOutcome::UnknownClient, +]; + +pub(super) fn put_settlement(w: &mut Writer, tick: u64, s: &FactSettlement) { + put_u64(w, tick); + w.string(&s.key).string(&s.command); + match &s.outcome { + FactOutcome::Committed(receipt) => { + w.u8(0) + .string(&receipt.payload.to_string()) + .bool(receipt.replayed); + } + FactOutcome::Failed { error, attempts } => { + let (kind, msg) = match error { + FactError::Retryable(m) => (0, m), + FactError::Permanent(m) => (1, m), + }; + w.u8(1).u8(kind).string(msg).varuint(*attempts); + } + } +} + +pub(super) fn get_settlement(r: &mut Reader<'_>) -> Result<(u64, FactSettlement), RecordingError> { + let tick = get_u64(r)?; + let key = r.string()?; + let command = r.string()?; + let outcome = match r.u8()? { + 0 => { + let payload = serde_json::from_str(&r.string()?).map_err(|_| bad("receipt json"))?; + FactOutcome::Committed(FactReceipt { + payload, + replayed: r.bool()?, + }) + } + 1 => { + let kind = r.u8()?; + let msg = r.string()?; + let error = match kind { + 0 => FactError::Retryable(msg), + 1 => FactError::Permanent(msg), + _ => return Err(bad("fact error kind")), + }; + FactOutcome::Failed { + error, + attempts: r.varuint()?, + } + } + _ => return Err(bad("fact outcome")), + }; + Ok(( + tick, + FactSettlement { + key, + command, + outcome, + }, + )) +} + +pub(super) fn put_config(w: &mut Writer, c: &HostConfig) { + w.varuint(c.tick_rate).varuint(c.patch_rate); + match c.idle_tick_rate { + Some(hz) => w.u8(1).varuint(hz), + None => w.u8(0), + }; + put_dur(w, c.dormant_after); + w.varuint(c.max_catch_up); + put_u64(w, c.max_players as u64); + put_u64(w, c.max_observers as u64); + put_u64(w, c.input_capacity as u64); + put_dur(w, c.reconnect_grace); + put_u64(w, c.byte_budget as u64); + w.f32(c.default_view_radius) + .f32(c.interest.cell_size) + .f32(c.interest.leave_margin) + .string(&c.content_version); + put_u64(w, c.world_seed); + put_dur(w, c.rewind.max_rewind); + put_u64(w, c.rewind.max_frames as u64); + w.u8(match c.stale_policy { + StalePolicy::Strict => 0, + StalePolicy::SafeRoom { roam: false } => 1, + StalePolicy::SafeRoom { roam: true } => 2, + }); + put_u64(w, c.boot_epoch); + w.string(&c.config_version); + w.bool(c.lifecycle_facts); +} + +pub(super) fn put_claims(w: &mut Writer, claims: &TicketClaims) { + w.string(&claims.principal) + .string(&claims.zone) + .string(&claims.nonce); + put_u64(w, claims.expires_at); + w.u8(match claims.role { + Role::Player => 0, + Role::Observer => 1, + }); + match &claims.name { + Some(name) => w.u8(1).string(name), + None => w.u8(0), + }; + w.string(&claims.extensions.to_json().to_string()); +} + +pub(super) fn get_claims(r: &mut Reader<'_>) -> Result { + let principal = r.string()?; + let zone = r.string()?; + let nonce = r.string()?; + let expires_at = get_u64(r)?; + let role = match r.u8()? { + 0 => Role::Player, + _ => Role::Observer, + }; + let name = match r.u8()? { + 0 => None, + _ => Some(r.string()?), + }; + let extensions = serde_json::from_str(&r.string()?) + .ok() + .and_then(|value| crate::claims::TicketExtensions::from_json(value).ok()) + .ok_or_else(|| bad("extension claims"))?; + Ok(TicketClaims { + principal, + zone, + expires_at, + nonce, + role, + name, + extensions, + wake: false, + }) +} + +pub(super) fn get_config(r: &mut Reader<'_>) -> Result { + Ok(HostConfig { + tick_rate: r.varuint()?, + patch_rate: r.varuint()?, + idle_tick_rate: match r.u8()? { + 0 => None, + _ => Some(r.varuint()?), + }, + dormant_after: get_dur(r)?, + max_catch_up: r.varuint()?, + max_players: get_u64(r)? as usize, + max_observers: get_u64(r)? as usize, + input_capacity: get_u64(r)? as usize, + reconnect_grace: get_dur(r)?, + byte_budget: get_u64(r)? as usize, + default_view_radius: r.f32()?, + // Update rates only shape Deltas, never the replayed world. + interest: InterestConfig { + cell_size: r.f32()?, + leave_margin: r.f32()?, + ..InterestConfig::default() + }, + content_version: r.string()?, + world_seed: get_u64(r)?, + rewind: RewindConfig { + max_rewind: get_dur(r)?, + max_frames: get_u64(r)? as usize, + }, + stale_policy: match r.u8()? { + 0 => StalePolicy::Strict, + 1 => StalePolicy::SafeRoom { roam: false }, + _ => StalePolicy::SafeRoom { roam: true }, + }, + boot_epoch: get_u64(r)?, + config_version: r.string()?, + lifecycle_facts: r.bool()?, + record: false, + }) +} + +pub(super) fn put_opt_string(w: &mut Writer, v: Option<&str>) { + match v { + Some(v) => w.u8(1).string(v), + None => w.u8(0), + }; +} + +pub(super) fn get_opt_string(r: &mut Reader<'_>) -> Result, RecordingError> { + Ok(match r.u8()? { + 0 => None, + _ => Some(r.string()?), + }) +} + +pub(super) fn put_stimulus(w: &mut Writer, stimulus: &Stimulus) { + match stimulus { + Stimulus::Join { + claims, + capabilities, + content_version, + } => { + w.u8(0); + put_claims(w, claims); + w.varuint(*capabilities).string(content_version); + } + Stimulus::JoinTransfer { + transfer, + capabilities, + content_version, + } => { + w.u8(1); + put_claims(w, &transfer.claims); + w.string(&transfer.source_zone).string(&transfer.issuer); + put_u64(w, transfer.generation); + put_u64(w, transfer.departed_at_ms); + w.bytes(&transfer.carried) + .varuint(*capabilities) + .string(content_version); + } + Stimulus::Reconnect { + token, + capabilities, + content_version, + } => { + w.u8(2).string(token).varuint(*capabilities); + put_opt_string(w, content_version.as_deref()); + } + Stimulus::Disconnect { client, graceful } => { + w.u8(3).varuint(client.0).bool(*graceful); + } + Stimulus::Input { + client, + seq, + client_tick, + payload, + } => { + w.u8(4) + .varuint(client.0) + .varuint(*seq) + .varuint(*client_tick) + .bytes(payload); + } + Stimulus::Content { client, version } => { + w.u8(5).varuint(client.0).string(version); + } + Stimulus::Focus { client, x, y } => { + w.u8(6).varuint(client.0).f32(*x).f32(*y); + } + Stimulus::Kick { principal, reason } => { + w.u8(7).string(principal).string(reason); + } + Stimulus::Message { type_id, payload } => { + w.u8(8).varuint(*type_id).bytes(payload); + } + Stimulus::ZoneMessage(envelope) => { + w.u8(9) + .string(&envelope.id) + .string(&envelope.from) + .string(&envelope.to); + put_opt_string(w, envelope.principal.as_deref()); + w.varuint(envelope.type_id).bytes(&envelope.payload); + } + Stimulus::ChildEvent(event) => { + w.u8(10) + .string(&event.origin_zone) + .string(&event.from_zone) + .string(&event.kind) + .bytes(&event.payload); + put_u64(w, event.origin_tick); + w.string(&event.content_version).u8(event.levels); + } + Stimulus::RequestFreeze(notice) => { + w.u8(11); + put_notice(w, notice); + } + Stimulus::CancelFreeze(notice) => { + w.u8(12); + put_notice(w, notice); + } + Stimulus::Resume(notice) => { + w.u8(13); + put_notice(w, notice); + } + Stimulus::ContentVersion(version) => { + w.u8(14).string(version); + } + Stimulus::ConfigVersion(version) => { + w.u8(15).string(version); + } + Stimulus::Reload(player) => { + w.u8(16).varuint(player.0); + } + Stimulus::ReloadStale => { + w.u8(17); + } + Stimulus::KickPlayer { player, message } => { + w.u8(18).varuint(player.0).string(message); + } + Stimulus::Handoff { + player, + target_zone, + ticket, + } => { + w.u8(19) + .varuint(player.0) + .string(target_zone) + .string(ticket); + } + Stimulus::Restore { + state, + saved_version, + } => { + w.u8(20).bytes(state).string(saved_version); + } + Stimulus::Dispose => { + w.u8(21); + } + Stimulus::Advance => { + w.u8(22); + } + } +} + +pub(super) fn get_stimulus(r: &mut Reader<'_>) -> Result { + Ok(match r.u8()? { + 0 => Stimulus::Join { + claims: get_claims(r)?, + capabilities: r.varuint()?, + content_version: r.string()?, + }, + 1 => { + let claims = get_claims(r)?; + let source_zone = r.string()?; + let issuer = r.string()?; + let generation = get_u64(r)?; + let departed_at_ms = get_u64(r)?; + let carried = r.bytes()?.to_vec(); + Stimulus::JoinTransfer { + transfer: Transfer { + claims, + source_zone, + issuer, + generation, + carried, + departed_at_ms, + }, + capabilities: r.varuint()?, + content_version: r.string()?, + } + } + 2 => Stimulus::Reconnect { + token: r.string()?, + capabilities: r.varuint()?, + content_version: get_opt_string(r)?, + }, + 3 => Stimulus::Disconnect { + client: ClientId(r.varuint()?), + graceful: r.bool()?, + }, + 4 => Stimulus::Input { + client: ClientId(r.varuint()?), + seq: r.varuint()?, + client_tick: r.varuint()?, + payload: r.bytes()?.to_vec(), + }, + 5 => Stimulus::Content { + client: ClientId(r.varuint()?), + version: r.string()?, + }, + 6 => Stimulus::Focus { + client: ClientId(r.varuint()?), + x: r.f32()?, + y: r.f32()?, + }, + 7 => Stimulus::Kick { + principal: r.string()?, + reason: r.string()?, + }, + 8 => Stimulus::Message { + type_id: r.varuint()?, + payload: r.bytes()?.to_vec(), + }, + 9 => Stimulus::ZoneMessage(ZoneEnvelope { + id: r.string()?, + from: r.string()?, + to: r.string()?, + principal: get_opt_string(r)?, + type_id: r.varuint()?, + payload: r.bytes()?.to_vec(), + }), + 10 => Stimulus::ChildEvent(ChildEvent { + origin_zone: r.string()?, + from_zone: r.string()?, + kind: r.string()?, + payload: r.bytes()?.to_vec(), + origin_tick: get_u64(r)?, + content_version: r.string()?, + levels: r.u8()?, + }), + 11 => Stimulus::RequestFreeze(get_notice(r)?), + 12 => Stimulus::CancelFreeze(get_notice(r)?), + 13 => Stimulus::Resume(get_notice(r)?), + 14 => Stimulus::ContentVersion(r.string()?), + 15 => Stimulus::ConfigVersion(r.string()?), + 16 => Stimulus::Reload(PlayerId(r.varuint()?)), + 17 => Stimulus::ReloadStale, + 18 => Stimulus::KickPlayer { + player: PlayerId(r.varuint()?), + message: r.string()?, + }, + 19 => Stimulus::Handoff { + player: PlayerId(r.varuint()?), + target_zone: r.string()?, + ticket: r.string()?, + }, + 20 => Stimulus::Restore { + state: r.bytes()?.to_vec(), + saved_version: r.string()?, + }, + 21 => Stimulus::Dispose, + 22 => Stimulus::Advance, + _ => return Err(bad("stimulus tag")), + }) +} + +pub(super) fn put_observed(w: &mut Writer, observed: &Observed) { + match observed { + Observed::Nothing => { + w.u8(0); + } + Observed::Join(result) => { + w.u8(1); + put_join_result(w, result); + } + Observed::Input(outcome) => { + let code = OUTCOMES.iter().position(|o| o == outcome).unwrap_or(0) as u8; + w.u8(2).u8(code); + } + Observed::Advance { settled, hashes } => { + w.u8(3); + put_u64(w, settled.len() as u64); + for (tick, s) in settled { + put_settlement(w, *tick, s); + } + put_u64(w, hashes.len() as u64); + if let Some((first, _)) = hashes.first() { + put_u64(w, *first); + } + for (_, hash) in hashes { + w.raw(&hash.to_le_bytes()); + } + } + } +} + +pub(super) fn get_observed(r: &mut Reader<'_>) -> Result { + Ok(match r.u8()? { + 0 => Observed::Nothing, + 1 => Observed::Join(get_join_result(r)?), + 2 => Observed::Input(*OUTCOMES.get(r.u8()? as usize).ok_or(bad("input outcome"))?), + 3 => { + let n = get_u64(r)? as usize; + let mut settled = Vec::with_capacity(n.min(1 << 16)); + for _ in 0..n { + settled.push(get_settlement(r)?); + } + let n = get_u64(r)?; + let mut hashes = Vec::with_capacity((n as usize).min(1 << 16)); + if n > 0 { + let first = get_u64(r)?; + for i in 0..n { + let mut b = [0u8; 8]; + b.copy_from_slice(r.raw(8)?); + hashes.push((first + i, u64::from_le_bytes(b))); + } + } + Observed::Advance { settled, hashes } + } + _ => return Err(bad("observed tag")), + }) +} + +impl Recording { + /// Compact binary encoding: + /// `"DGR4" ‖ zone_id ‖ config ‖ created_at ‖ created_unix_ms ‖ + /// fact_capacity? ‖ varuint(entry count) ‖ entries`, each entry + /// `at ‖ unix_ms ‖ stimulus ‖ observed`. Integers are LEB128 varints, + /// durations are nanosecond varints, clock readings are delta-coded + /// against the previous entry (both clocks never go backwards in a + /// recording: the host clamps them), hashes are 8 raw bytes. + pub fn encode(&self) -> Vec { + let mut w = Writer::new(); + w.raw(MAGIC).string(&self.zone_id); + put_config(&mut w, &self.config); + put_dur(&mut w, self.created_at); + put_u64(&mut w, self.created_unix_ms); + match self.fact_capacity { + Some(c) => { + w.u8(1); + put_u64(&mut w, c as u64); + } + None => { + w.u8(0); + } + } + put_u64(&mut w, self.entries.len() as u64); + let (mut at, mut unix_ms) = (self.created_at, self.created_unix_ms); + for entry in &self.entries { + put_dur(&mut w, entry.at.saturating_sub(at)); + put_u64(&mut w, entry.unix_ms.saturating_sub(unix_ms)); + (at, unix_ms) = (entry.at, entry.unix_ms); + put_stimulus(&mut w, &entry.stimulus); + put_observed(&mut w, &entry.observed); + } + w.into_bytes() + } + + /// Decode [`encode`](Self::encode) output. + pub fn decode(bytes: &[u8]) -> Result { + let mut r = Reader::new(bytes); + if r.raw(4).map_err(|_| RecordingError::BadMagic)? != MAGIC { + return Err(RecordingError::BadMagic); + } + let zone_id = r.string()?; + let config = get_config(&mut r)?; + let created_at = get_dur(&mut r)?; + let created_unix_ms = get_u64(&mut r)?; + let fact_capacity = match r.u8()? { + 0 => None, + _ => Some(get_u64(&mut r)? as usize), + }; + let count = get_u64(&mut r)? as usize; + let mut entries = Vec::with_capacity(count.min(1 << 20)); + let (mut at, mut unix_ms) = (created_at, created_unix_ms); + for _ in 0..count { + at += get_dur(&mut r)?; + unix_ms = unix_ms + .checked_add(get_u64(&mut r)?) + .ok_or(bad("wall clock overflow"))?; + entries.push(Entry { + at, + unix_ms, + stimulus: get_stimulus(&mut r)?, + observed: get_observed(&mut r)?, + }); + } + r.finish()?; + Ok(Self { + zone_id, + config, + created_at, + created_unix_ms, + fact_capacity, + entries, + }) + } + + /// Write [`encode`](Self::encode) output to `path`. + pub fn save(&self, path: impl AsRef) -> std::io::Result<()> { + std::fs::write(path, self.encode()) + } + + /// Read a file written by [`save`](Self::save). + pub fn load(path: impl AsRef) -> std::io::Result { + let bytes = std::fs::read(path)?; + Self::decode(&bytes).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e)) + } + + /// Simulated ticks in the recording. + pub fn tick_count(&self) -> usize { + self.entries + .iter() + .map(|e| match &e.observed { + Observed::Advance { hashes, .. } => hashes.len(), + _ => 0, + }) + .sum() + } +} diff --git a/distributed_game/src/replay/run.rs b/distributed_game/src/replay/run.rs new file mode 100644 index 000000000..47c306d44 --- /dev/null +++ b/distributed_game/src/replay/run.rs @@ -0,0 +1,257 @@ +//! Replaying a [`Recording`] on a fresh host and finding where it diverges. + +use super::*; + +/// What diverged. +#[derive(Debug, Clone, PartialEq)] +pub enum DivergenceKind { + /// State hash after a tick differs. + StateHash { + /// Recorded. + expected: u64, + /// Replayed. + actual: u64, + }, + /// The advance simulated different ticks. + Ticks { + /// Recorded ticks. + expected: Vec, + /// Replayed ticks. + actual: Vec, + }, + /// An input was accepted/rejected differently. + InputOutcome { + /// Recorded. + expected: PushOutcome, + /// Replayed. + actual: PushOutcome, + }, + /// A join/reconnect resolved differently. + Join { + /// Recorded. + expected: JoinResult, + /// Replayed. + actual: JoinResult, + }, +} + +/// First point where a replay departed from its recording. +#[derive(Debug, Clone, PartialEq)] +pub struct Divergence { + /// Index into [`Recording::entries`]. + pub entry_index: usize, + /// Tick at which it was detected (the diverging tick for hashes). + pub tick: u64, + /// What differed. + pub kind: DivergenceKind, + /// Last matching tick (0 = none). + pub last_good_tick: u64, + /// Stimuli applied since the last matching advance (most likely cause). + pub suspects: Vec, +} + +impl fmt::Display for Divergence { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match &self.kind { + DivergenceKind::StateHash { expected, actual } => write!( + f, + "replay diverged at tick {} (entry #{}): state hash {actual:016x} != recorded {expected:016x}", + self.tick, self.entry_index + )?, + DivergenceKind::Ticks { expected, actual } => write!( + f, + "replay diverged at tick {} (entry #{}): simulated ticks {actual:?} != recorded {expected:?}", + self.tick, self.entry_index + )?, + DivergenceKind::InputOutcome { expected, actual } => write!( + f, + "replay diverged at tick {} (entry #{}): input outcome {actual:?} != recorded {expected:?}", + self.tick, self.entry_index + )?, + DivergenceKind::Join { expected, actual } => write!( + f, + "replay diverged at tick {} (entry #{}): join {actual:?} != recorded {expected:?}", + self.tick, self.entry_index + )?, + } + write!(f, "\n last matching tick: {}", self.last_good_tick)?; + if !self.suspects.is_empty() { + write!(f, "\n stimuli since then:")?; + for s in &self.suspects { + write!(f, "\n {s}")?; + } + } + Ok(()) + } +} + +impl std::error::Error for Divergence {} + +/// Successful replay summary. +#[derive(Debug, Clone, PartialEq)] +pub struct ReplaySummary { + /// Entries applied. + pub entries: usize, + /// Ticks simulated and verified. + pub ticks: u64, + /// Hash after the last tick. + pub final_hash: u64, + /// Facts the zone emitted, in order (a recording without a fact queue + /// emits none). + pub facts: Vec, +} + +/// The clock a replay runs on: exactly the recorded readings. +pub(super) struct ReplayClock(Mutex<(Duration, u64)>); + +impl ReplayClock { + pub(super) fn set(&self, at: Duration, unix_ms: u64) { + *self.0.lock().expect("replay clock") = (at, unix_ms); + } +} + +impl Clock for ReplayClock { + fn now(&self) -> Duration { + self.0.lock().expect("replay clock").0 + } + + fn unix_ms(&self) -> u64 { + self.0.lock().expect("replay clock").1 + } +} + +/// Replay `recording` through a fresh host on its recorded clock readings +/// and verify every join and input outcome and per-tick state hash. +pub fn replay( + recording: &Recording, + zone_config: Z::Config, +) -> Result { + replay_with::(recording, zone_config, |_| {}) +} + +/// [`replay`] with a callback after each entry (inspection, tooling). +pub fn replay_with( + recording: &Recording, + zone_config: Z::Config, + mut inspect: impl FnMut(&ZoneHost), +) -> Result { + let clock = Arc::new(ReplayClock(Mutex::new(( + recording.created_at, + recording.created_unix_ms, + )))); + let mut issued = 0usize; + let mut host = ZoneHost::::new( + recording.zone_id.clone(), + recording.config.clone(), + clock.clone(), + zone_config, + ) + .with_token_source(move || { + issued += 1; + token_label(issued - 1) + }) + .with_transfer_issuer(|_: &HandoffRequest| Some("replay-transfer".into())); + host.set_tick_hashing(true); + let mut script = None; + if let Some(capacity) = recording.fact_capacity { + let (queue, s) = FactQueue::scripted(capacity); + host = host.with_facts(queue.with_journal()); + script = Some(s); + } + let mut last_good_tick = 0u64; + let mut suspects: Vec = Vec::new(); + let mut last_hash = 0u64; + let mut ticks = 0u64; + let mut facts = Vec::new(); + for (index, entry) in recording.entries.iter().enumerate() { + clock.set(entry.at, entry.unix_ms); + if let (Some(script), Observed::Advance { settled, .. }) = (&script, &entry.observed) { + for (tick, s) in settled { + script.push(*tick, s.clone()); + } + } + let outcome = host.apply(entry.stimulus.clone()); + host.drain_outbound(); + facts.extend(host.take_emitted_facts()); + let diverged = + |tick: u64, kind: DivergenceKind, last_good_tick: u64, suspects: &[String]| { + let mut suspects = suspects.to_vec(); + suspects.push(entry.to_string()); + Divergence { + entry_index: index, + tick, + kind, + last_good_tick, + suspects, + } + }; + match (&entry.observed, Observed::of(&outcome)) { + (Observed::Join(expected), Observed::Join(actual)) if *expected != actual => { + let kind = DivergenceKind::Join { + expected: expected.clone(), + actual, + }; + return Err(diverged(host.tick(), kind, last_good_tick, &suspects)); + } + (Observed::Input(expected), Observed::Input(actual)) if *expected != actual => { + let kind = DivergenceKind::InputOutcome { + expected: *expected, + actual, + }; + return Err(diverged(host.tick(), kind, last_good_tick, &suspects)); + } + ( + Observed::Advance { hashes, .. }, + Observed::Advance { + hashes: actual_hashes, + .. + }, + ) => { + for ((tick, expected), (_, actual)) in hashes.iter().zip(&actual_hashes) { + if expected != actual { + let kind = DivergenceKind::StateHash { + expected: *expected, + actual: *actual, + }; + return Err(diverged(*tick, kind, last_good_tick, &suspects)); + } + last_good_tick = *tick; + } + let expected: Vec = hashes.iter().map(|(t, _)| *t).collect(); + let actual: Vec = actual_hashes.iter().map(|(t, _)| *t).collect(); + if expected != actual { + let kind = DivergenceKind::Ticks { expected, actual }; + return Err(diverged(host.tick(), kind, last_good_tick, &suspects)); + } + if let Some((_, h)) = actual_hashes.last() { + last_hash = *h; + ticks += actual_hashes.len() as u64; + suspects.clear(); + } + inspect(&host); + continue; + } + _ => {} + } + suspects.push(entry.to_string()); + inspect(&host); + } + Ok(ReplaySummary { + entries: recording.entries.len(), + ticks, + final_hash: last_hash, + facts, + }) +} + +/// Per-tick hashes of a recording (for diffing two recordings). +pub fn tick_hashes(recording: &Recording) -> BTreeMap { + recording + .entries + .iter() + .flat_map(|e| match &e.observed { + Observed::Advance { hashes, .. } => hashes.clone(), + _ => Vec::new(), + }) + .collect() +} diff --git a/distributed_game/src/replication.rs b/distributed_game/src/replication.rs new file mode 100644 index 000000000..1fe5cdc82 --- /dev/null +++ b/distributed_game/src/replication.rs @@ -0,0 +1,1224 @@ +//! Per-client delta replication with interest and a byte budget. +//! +//! Each patch the zone describes its replicated entities into a +//! [`WorldView`]. Field values are encoded once per patch; every client then +//! gets a Delta computed against **what was last sent to that client** +//! (valid because the transport is reliable and ordered): +//! +//! - entities entering the client's [`View`] → *create* (all fields); +//! - known entities with changed encoded fields → *update* (bitmask + fields); +//! - known entities gone or out of view → *remove* (id only, never budgeted). +//! +//! Creates and updates compete for the per-client byte budget. Each candidate +//! gets `priority = kind.priority × entity.priority × max(field priority) × +//! 1/(1 + distance/radius)` added to a per-entity **accumulator**; candidates +//! are sent in accumulator order until the budget is spent and sent entities +//! reset to zero. Starved entities keep accumulating, so everything is +//! eventually sent. At least one candidate is sent per patch even if it alone +//! exceeds the budget. Change detection compares encoded bytes, so +//! sub-quantum jitter never costs bandwidth. +//! +//! **Encode once.** Each distinct encoded state of an entity is a shared +//! *revision*; a client remembers the revision it was sent, not a copy. A +//! world built with [`EncodedWorld::next`] carries, per changed entity, the +//! update record from its previous state, so a client that is current costs +//! a revision compare and a copy. Clients with an older baseline (deferred +//! by the budget or by update rates) share one record per baseline, encoded +//! on first use in the patch. The bytes are those of encoding per client. +//! +//! **Update rates.** A changed entity the client already has is an update +//! candidate only every [`UpdateRates::interval`]-th patch for its distance +//! (staggered by id) unless it is global or its kind is `every_patch`; held +//! entities keep their accumulated priority. Creates and removes are never +//! held. + +use std::collections::hash_map::Entry; +use std::collections::HashMap; +use std::hash::{BuildHasherDefault, Hasher}; +use std::ops::Range; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; + +#[cfg(doc)] +use crate::interest::UpdateRates; +use crate::interest::{InterestConfig, SpatialGrid, View}; +use crate::protocol::{tag, Writer}; +use crate::schema::{EntitySchema, FieldValue}; + +/// One replicated entity as described by the zone for this patch. +#[derive(Debug, Clone, PartialEq)] +pub struct EntityState { + /// Game-assigned id (unique within the zone). + pub id: u32, + /// Kind id from the schema. + pub kind: u16, + /// Interest-plane x. + pub x: f32, + /// Interest-plane y. + pub y: f32, + /// Priority multiplier (default 1). + pub priority: f32, + /// Visible to every client regardless of view. + pub global: bool, + /// Field values in schema order (missing trailing fields encode as zero). + pub fields: Vec, +} + +impl EntityState { + /// Spatial entity at (x, y). + pub fn new(id: u32, kind: u16, x: f32, y: f32, fields: Vec) -> Self { + Self { + id, + kind, + x, + y, + priority: 1.0, + global: false, + fields, + } + } + + /// Mark visible to everyone. + pub fn global(mut self) -> Self { + self.global = true; + self + } + + /// Set the priority multiplier. + pub fn priority(mut self, p: f32) -> Self { + self.priority = p; + self + } +} + +/// Collector the zone fills in `Zone::replicate`. +#[derive(Debug, Clone, Default)] +pub struct WorldView { + entities: Vec, + /// Emptied field vectors of the entities before [`clear`](Self::clear), + /// refilled by [`add`](Self::add). + spare: Vec>, +} + +impl WorldView { + /// Add an entity. + pub fn push(&mut self, entity: EntityState) { + self.entities.push(entity); + } + + /// Entities pushed so far. + pub fn entities(&self) -> &[EntityState] { + &self.entities + } + + pub(crate) fn last_mut(&mut self) -> Option<&mut EntityState> { + self.entities.last_mut() + } + + /// Empty it for the next patch, keeping its allocations. + pub(crate) fn clear(&mut self) { + self.spare.extend(self.entities.drain(..).map(|entity| { + let mut fields = entity.fields; + fields.clear(); + fields + })); + } + + /// An empty field vector, kept from before [`clear`](Self::clear) when + /// there is one. + pub(crate) fn spare_fields(&mut self) -> Vec { + self.spare.pop().unwrap_or_default() + } +} + +/// Multiplicative hasher for the integer keys of the per-client maps, hashed +/// once per visible entity per client per patch (ids are assigned by the +/// game, not chosen by clients). +#[derive(Debug, Default, Clone, Copy)] +struct IdHasher(u64); + +impl IdHasher { + const K: u64 = 0x517c_c1b7_2722_0a95; + + fn mix(&mut self, n: u64) { + self.0 = (self.0.rotate_left(5) ^ n).wrapping_mul(Self::K); + } +} + +impl Hasher for IdHasher { + fn finish(&self) -> u64 { + self.0 + } + + fn write(&mut self, bytes: &[u8]) { + for b in bytes { + self.mix(u64::from(*b)); + } + } + + fn write_u32(&mut self, n: u32) { + self.mix(u64::from(n)); + } + + fn write_u64(&mut self, n: u64) { + self.mix(n); + } + + fn write_usize(&mut self, n: usize) { + self.mix(n as u64); + } +} + +type IdMap = HashMap>; + +/// Revisions are unique across all worlds: equal revisions are equal bytes, +/// whichever world or replica they came from. +static NEXT_REV: AtomicU64 = AtomicU64::new(1); + +/// One encoded state of an entity, shared by the worlds it is unchanged in +/// and by every client it was sent to. +#[derive(Debug)] +struct Payload { + rev: u64, + /// The create record: `varuint id, varuint kind, data`. + create: Vec, + /// Where the data starts in `create`. + data_start: usize, + /// Field boundaries in the data. + offsets: Box<[usize]>, +} + +/// Longest varuint encoding of a `u32`. +const MAX_VARUINT: usize = 5; + +impl Payload { + fn new(id: u32, kind: u16, data: &[u8], offsets: &[usize]) -> Self { + let mut create = Writer::with_capacity(2 * MAX_VARUINT + data.len()); + create.varuint(id).varuint(u32::from(kind)).raw(data); + let create = create.into_bytes(); + Self { + rev: NEXT_REV.fetch_add(1, Ordering::Relaxed), + data_start: create.len() - data.len(), + create, + offsets: offsets.into(), + } + } + + fn data(&self) -> &[u8] { + &self.create[self.data_start..] + } + + fn field(&self, index: usize) -> &[u8] { + &self.data()[self.offsets[index]..self.offsets[index + 1]] + } + + /// Mask of the first `fields` fields whose bytes differ from `old`. + fn changed_since(&self, old: &Payload, fields: usize) -> u32 { + let mut mask = 0u32; + for i in 0..fields { + if old.field(i) != self.field(i) { + mask |= 1 << i; + } + } + mask + } + + /// The update record `varuint id, varuint mask, masked fields`. + fn update(&self, id: u32, mask: u32, w: &mut Writer) { + w.varuint(id).varuint(mask); + for i in 0..self.offsets.len() - 1 { + if mask & (1 << i) != 0 { + w.raw(self.field(i)); + } + } + } +} + +/// An entity's update record from revision `base` to its current one. +#[derive(Debug)] +struct SharedUpdate { + base: u64, + mask: u32, + record: Vec, +} + +#[derive(Debug, Clone)] +struct EncodedEntity { + id: u32, + kind: u16, + x: f32, + y: f32, + priority: f32, + global: bool, + payload: Arc, + /// From its state in the previous world (kept while unchanged). + update: Option>, +} + +/// Update records for older baselines: `(entity index, baseline rev)` → +/// `(mask, record range)`, encoded on first use in a patch. +#[derive(Debug, Default)] +struct UpdateCache { + records: IdMap<(u32, u64), (u32, Range)>, + bytes: Vec, +} + +/// A patch's encoded world, shared by every client. +/// +/// Encoding allocates per patch a constant number of times (the entity +/// table and its id index), plus per changed entity its new payload and +/// update record: unchanged entities are encoded into a scratch buffer the +/// chain keeps from patch to patch and compared there, and the interest +/// grid keeps its cells. +#[derive(Debug)] +pub struct EncodedWorld { + entities: Vec, + by_id: IdMap, + grid: SpatialGrid, + globals: Vec, + patch: u32, + /// Records encoded building this world (changed entities' payloads and + /// shared updates). + encoded: usize, + cache: UpdateCache, + /// An entity's data, encoded before it is compared. + scratch: Writer, + /// Its field boundaries. + offsets: Vec, +} + +impl Clone for EncodedWorld { + fn clone(&self) -> Self { + Self { + entities: self.entities.clone(), + by_id: self.by_id.clone(), + grid: self.grid.clone(), + globals: self.globals.clone(), + patch: self.patch, + encoded: self.encoded, + cache: UpdateCache::default(), + scratch: Writer::new(), + offsets: Vec::new(), + } + } +} + +impl EncodedWorld { + /// Encode `view` against `schema` as the first patch. Entities of + /// unknown kinds or duplicate ids are skipped. + pub fn build(schema: &EntitySchema, view: &WorldView, interest: &InterestConfig) -> Self { + let mut world = Self::with_capacity(view.entities.len(), interest); + world.encode(schema, view, None); + world + } + + /// Encode the patch after `self`: unchanged entities keep their + /// revision, changed ones get one update record from their state here, + /// shared by every client that has it. Update rates count patches along + /// this chain, so build every patch after the first with `next`. + pub fn next(mut self, schema: &EntitySchema, view: &WorldView, interest: &InterestConfig) -> Self { + let mut world = Self::with_capacity(view.entities.len(), interest); + world.patch = self.patch.wrapping_add(1); + // The buffers move along the chain. + std::mem::swap(&mut world.grid, &mut self.grid); + world.grid.reset(interest.cell_size); + std::mem::swap(&mut world.globals, &mut self.globals); + world.globals.clear(); + std::mem::swap(&mut world.cache, &mut self.cache); + world.cache.records.clear(); + world.cache.bytes.clear(); + std::mem::swap(&mut world.scratch, &mut self.scratch); + std::mem::swap(&mut world.offsets, &mut self.offsets); + world.encode(schema, view, Some(&self)); + world + } + + fn with_capacity(entities: usize, interest: &InterestConfig) -> Self { + Self { + entities: Vec::with_capacity(entities), + by_id: IdMap::with_capacity_and_hasher(entities, Default::default()), + grid: SpatialGrid::new(interest.cell_size), + globals: Vec::new(), + patch: 0, + encoded: 0, + cache: UpdateCache::default(), + scratch: Writer::new(), + offsets: Vec::new(), + } + } + + fn encode(&mut self, schema: &EntitySchema, view: &WorldView, previous: Option<&EncodedWorld>) { + let zero = FieldValue::U(0); + for e in &view.entities { + let Some(kind) = schema.get(e.kind) else { + continue; + }; + if self.by_id.contains_key(&e.id) { + continue; + } + self.scratch.clear(); + self.offsets.clear(); + for (index, def) in kind.fields.iter().enumerate() { + self.offsets.push(self.scratch.len()); + def.ty + .encode(&mut self.scratch, e.fields.get(index).unwrap_or(&zero)); + } + self.offsets.push(self.scratch.len()); + let (data, offsets) = (self.scratch.as_bytes(), &self.offsets[..]); + let before = previous + .and_then(|p| p.by_id.get(&e.id).map(|&i| &p.entities[i])) + .filter(|p| p.kind == e.kind && p.payload.offsets.len() == offsets.len()); + let (payload, update) = match before { + Some(p) if p.payload.data() == data && *p.payload.offsets == *offsets => { + (p.payload.clone(), p.update.clone()) + } + _ => { + let payload = Arc::new(Payload::new(e.id, e.kind, data, offsets)); + self.encoded += 1 + usize::from(before.is_some()); + let update = before.map(|p| { + let mask = payload.changed_since(&p.payload, kind.fields.len()); + let mut w = Writer::with_capacity(2 * MAX_VARUINT + data.len()); + payload.update(e.id, mask, &mut w); + Arc::new(SharedUpdate { + base: p.payload.rev, + mask, + record: w.into_bytes(), + }) + }); + (payload, update) + } + }; + let index = self.entities.len() as u32; + if e.global { + self.globals.push(index); + } else { + self.grid.insert(index, e.x, e.y); + } + self.by_id.insert(e.id, index as usize); + self.entities.push(EncodedEntity { + id: e.id, + kind: e.kind, + x: e.x, + y: e.y, + priority: e.priority, + global: e.global, + payload, + update, + }); + } + } + + /// Entity count. + pub fn len(&self) -> usize { + self.entities.len() + } + + /// True when empty. + pub fn is_empty(&self) -> bool { + self.entities.is_empty() + } + + /// Entity records encoded for this patch so far: one payload (with its + /// create record) and one shared update per changed entity, plus the + /// update records for older baselines built for clients. Encoding per + /// client would cost one per record sent or deferred instead. + pub fn encodes(&self) -> usize { + self.encoded + self.cache.records.len() + } +} + +/// Counters from one Delta build. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct DeltaStats { + /// Creates sent. + pub creates: usize, + /// Updates sent. + pub updates: usize, + /// Removes sent. + pub removes: usize, + /// Candidates deferred by the budget. + pub deferred: usize, + /// Changed known entities held back by the update rates this patch. + pub held: usize, + /// Create+update section bytes (what the budget limits). + pub budget_bytes: usize, +} + +/// A visible or known entity of one client. +#[derive(Debug, Clone, Default)] +struct Slot { + /// What it was last sent. + known: Option>, + accum: f32, + /// Build that last saw it visible. + seen: u32, +} + +/// What one client has been sent. +#[derive(Debug, Clone, Default)] +pub struct ClientReplica { + slots: IdMap, + builds: u32, + scratch: DeltaScratch, +} + +/// One Delta build's working sets, kept (emptied) for the next build. +#[derive(Debug, Clone, Default)] +struct DeltaScratch { + hits: Vec, + candidates: Vec<(usize, Candidate, f32)>, + removes: Vec, + creates: Writer, + updates: Writer, +} + +#[derive(Debug, Clone)] +enum Candidate { + Create, + Shared, + Cached(Range), +} + +impl ClientReplica { + /// Fresh replica (client knows nothing). + pub fn new() -> Self { + Self::default() + } + + /// Forget everything (e.g. after reconnect the client gets fresh creates). + pub fn reset(&mut self) { + self.slots.clear(); + } + + /// Ids the client currently knows. + pub fn known_ids(&self) -> impl Iterator + '_ { + self.slots + .iter() + .filter(|(_, slot)| slot.known.is_some()) + .map(|(id, _)| *id) + } + + /// Build this client's Delta frame and update the last-sent state. + #[allow(clippy::too_many_arguments)] + pub fn build_delta( + &mut self, + schema: &EntitySchema, + world: &mut EncodedWorld, + interest: &InterestConfig, + view: &View, + budget: usize, + server_tick: u32, + ack_seq: u32, + ) -> (Vec, DeltaStats) { + self.builds = self.builds.wrapping_add(1); + let stamp = self.builds; + let radius = view.radius.max(0.0); + let stay_radius = radius * (1.0 + interest.leave_margin.max(0.0)); + let DeltaScratch { + hits, + candidates, + removes, + creates, + updates, + } = &mut self.scratch; + hits.clear(); + candidates.clear(); + removes.clear(); + creates.clear(); + updates.clear(); + world.grid.query(view.x, view.y, stay_radius, hits); + hits.extend_from_slice(&world.globals); + let cache = &mut world.cache; + + // Visible entities (indices are unique) become candidates with + // accumulated priority. + let mut visible = 0usize; + let mut held = 0usize; + for &index in hits.iter() { + let index = index as usize; + let e = &world.entities[index]; + let d = if e.global { + 0.0 + } else { + view.distance(e.x, e.y) + }; + let slot = match self.slots.entry(e.id) { + Entry::Occupied(slot) => { + let limit = if slot.get().known.is_some() { + stay_radius + } else { + radius + }; + if !e.global && d > limit { + continue; + } + slot.into_mut() + } + Entry::Vacant(slot) => { + if !e.global && d > radius { + continue; + } + slot.insert(Slot::default()) + } + }; + slot.seen = stamp; + visible += 1; + let Some(kind) = schema.get(e.kind) else { + slot.accum = 0.0; + continue; + }; + let (candidate, field_prio) = match &slot.known { + None => ( + Candidate::Create, + kind.fields + .iter() + .map(|f| f.priority) + .fold(1.0_f32, f32::max), + ), + Some(known) => { + if known.rev == e.payload.rev { + slot.accum = 0.0; + continue; + } + if !e.global && !kind.every_patch { + let every = interest.update_rates.interval(d, radius); + if every > 1 && !world.patch.wrapping_add(e.id).is_multiple_of(every) { + // Held: keeps its accumulated priority. + held += 1; + continue; + } + } + let fields = kind.fields.len(); + let (mask, candidate) = match &e.update { + Some(update) + if update.base == known.rev + && fields + 1 == e.payload.offsets.len() => + { + (update.mask, Candidate::Shared) + } + _ => { + let (mask, range) = cache + .records + .entry((index as u32, known.rev)) + .or_insert_with(|| { + let mask = e.payload.changed_since(known, fields); + let start = cache.bytes.len(); + let mut w = Writer::new(); + e.payload.update(e.id, mask, &mut w); + cache.bytes.extend_from_slice(w.as_bytes()); + (mask, start..cache.bytes.len()) + }) + .clone(); + (mask, Candidate::Cached(range)) + } + }; + if mask == 0 { + slot.accum = 0.0; + continue; + } + let prio = kind + .fields + .iter() + .enumerate() + .filter(|(i, _)| mask & (1 << i) != 0) + .fold(0.0_f32, |p, (_, def)| p.max(def.priority)); + (candidate, prio) + } + }; + let distance_factor = 1.0 / (1.0 + d / radius.max(f32::EPSILON)); + let gain = (kind.priority * e.priority * field_prio * distance_factor).max(1e-6); + slot.accum += gain; + candidates.push((index, candidate, slot.accum)); + } + + // Known entities gone or out of view. + if visible != self.slots.len() { + self.slots.retain(|id, slot| { + if slot.seen != stamp && slot.known.is_some() { + removes.push(*id); + } + slot.seen == stamp + }); + removes.sort_unstable(); + } + // Ids are unique: a total order, so an unstable sort is the same. + candidates.sort_unstable_by(|a, b| { + b.2.total_cmp(&a.2) + .then(world.entities[a.0].id.cmp(&world.entities[b.0].id)) + }); + + let mut stats = DeltaStats { + removes: removes.len(), + held, + ..DeltaStats::default() + }; + for (index, candidate, _) in candidates.iter() { + let index = *index; + let e = &world.entities[index]; + let record = match candidate { + Candidate::Create => &e.payload.create[..], + Candidate::Shared => &e.update.as_ref().expect("shared update").record[..], + Candidate::Cached(range) => &cache.bytes[range.clone()], + }; + let used = creates.len() + updates.len(); + if used > 0 && used + record.len() > budget { + stats.deferred += 1; + continue; + } + if let Candidate::Create = candidate { + creates.raw(record); + stats.creates += 1; + } else { + updates.raw(record); + stats.updates += 1; + } + let slot = self.slots.get_mut(&e.id).expect("candidate slot"); + slot.accum = 0.0; + slot.known = Some(e.payload.clone()); + } + stats.budget_bytes = creates.len() + updates.len(); + + let mut frame = Writer::with_capacity( + 1 + MAX_VARUINT * (5 + removes.len()) + creates.len() + updates.len(), + ); + frame + .u8(tag::DELTA) + .varuint(server_tick) + .varuint(ack_seq) + .varuint(removes.len() as u32); + for id in removes.iter() { + frame.varuint(*id); + } + frame + .varuint(stats.creates as u32) + .raw(creates.as_bytes()) + .varuint(stats.updates as u32) + .raw(updates.as_bytes()); + (frame.into_bytes(), stats) + } +} + +#[cfg(test)] +mod tests { + use std::collections::{HashMap, HashSet}; + use std::time::{Duration, Instant}; + + use super::*; + use crate::interest::UpdateRates; + use crate::rng::ZoneRng; + use crate::schema::{FieldType, KindDef}; + + struct Known { + rev: u64, + data: Vec, + offsets: Vec, + } + + enum RefCandidate { + Create, + Update(u32), + } + + /// The per-client path encode-once replaced (each client compares, + /// encodes and copies every entity itself) with the same update-rate + /// hold: the reference for byte equality, and "before" in the bench. + #[derive(Default)] + struct Reference { + known: HashMap, + accum: HashMap, + } + + impl Reference { + fn reset(&mut self) { + self.known.clear(); + self.accum.clear(); + } + + #[allow(clippy::too_many_arguments)] + fn build_delta( + &mut self, + schema: &EntitySchema, + world: &EncodedWorld, + interest: &InterestConfig, + view: &View, + budget: usize, + server_tick: u32, + ack_seq: u32, + ) -> (Vec, DeltaStats) { + let radius = view.radius.max(0.0); + let stay_radius = radius * (1.0 + interest.leave_margin.max(0.0)); + let mut hits = Vec::new(); + world.grid.query(view.x, view.y, stay_radius, &mut hits); + hits.extend_from_slice(&world.globals); + + let mut visible: Vec<(usize, f32)> = Vec::new(); + let mut seen = HashSet::new(); + for index in hits { + let index = index as usize; + let e = &world.entities[index]; + if !seen.insert(e.id) { + continue; + } + let d = if e.global { + 0.0 + } else { + view.distance(e.x, e.y) + }; + let limit = if self.known.contains_key(&e.id) { + stay_radius + } else { + radius + }; + if e.global || d <= limit { + visible.push((index, d)); + } + } + + let visible_ids: HashSet = + visible.iter().map(|(i, _)| world.entities[*i].id).collect(); + let mut removes: Vec = self + .known + .keys() + .copied() + .filter(|id| !visible_ids.contains(id)) + .collect(); + removes.sort_unstable(); + for id in &removes { + self.known.remove(id); + } + + let mut held = HashSet::new(); + let mut candidates: Vec<(usize, RefCandidate, f32)> = Vec::new(); + for (index, d) in visible { + let e = &world.entities[index]; + let p = &e.payload; + let Some(kind) = schema.get(e.kind) else { + continue; + }; + let (candidate, field_prio) = match self.known.get(&e.id) { + None => ( + RefCandidate::Create, + kind.fields + .iter() + .map(|f| f.priority) + .fold(1.0_f32, f32::max), + ), + Some(known) => { + let every = interest.update_rates.interval(d, radius); + if known.rev != p.rev + && !e.global + && !kind.every_patch + && every > 1 + && !world.patch.wrapping_add(e.id).is_multiple_of(every) + { + held.insert(e.id); + continue; + } + let mut mask = 0u32; + let mut prio = 0.0_f32; + for (i, def) in kind.fields.iter().enumerate() { + let old = &known.data[known.offsets[i]..known.offsets[i + 1]]; + if old != p.field(i) { + mask |= 1 << i; + prio = prio.max(def.priority); + } + } + if mask == 0 { + continue; + } + (RefCandidate::Update(mask), prio) + } + }; + let distance_factor = 1.0 / (1.0 + d / radius.max(f32::EPSILON)); + let gain = (kind.priority * e.priority * field_prio * distance_factor).max(1e-6); + let accum = self.accum.entry(e.id).or_insert(0.0); + *accum += gain; + candidates.push((index, candidate, *accum)); + } + let candidate_ids: HashSet = candidates + .iter() + .map(|(i, _, _)| world.entities[*i].id) + .collect(); + self.accum + .retain(|id, _| candidate_ids.contains(id) || held.contains(id)); + candidates.sort_by(|a, b| { + b.2.total_cmp(&a.2) + .then(world.entities[a.0].id.cmp(&world.entities[b.0].id)) + }); + + let mut stats = DeltaStats { + removes: removes.len(), + held: held.len(), + ..DeltaStats::default() + }; + let mut creates = Writer::new(); + let mut updates = Writer::new(); + let mut scratch = Writer::new(); + for (index, candidate, _) in candidates { + let e = &world.entities[index]; + let p = &e.payload; + scratch.clear(); + match candidate { + RefCandidate::Create => { + scratch + .varuint(e.id) + .varuint(u32::from(e.kind)) + .raw(p.data()); + } + RefCandidate::Update(mask) => { + scratch.varuint(e.id).varuint(mask); + for i in 0..p.offsets.len() - 1 { + if mask & (1 << i) != 0 { + scratch.raw(p.field(i)); + } + } + } + } + let used = creates.len() + updates.len(); + if used > 0 && used + scratch.len() > budget { + stats.deferred += 1; + continue; + } + match candidate { + RefCandidate::Create => { + creates.raw(scratch.as_bytes()); + stats.creates += 1; + } + RefCandidate::Update(_) => { + updates.raw(scratch.as_bytes()); + stats.updates += 1; + } + } + self.accum.remove(&e.id); + self.known.insert( + e.id, + Known { + rev: p.rev, + data: p.data().to_vec(), + offsets: p.offsets.to_vec(), + }, + ); + } + stats.budget_bytes = creates.len() + updates.len(); + + let mut frame = Writer::new(); + frame + .u8(tag::DELTA) + .varuint(server_tick) + .varuint(ack_seq) + .varuint(removes.len() as u32); + for id in &removes { + frame.varuint(*id); + } + frame + .varuint(stats.creates as u32) + .raw(creates.as_bytes()) + .varuint(stats.updates as u32) + .raw(updates.as_bytes()); + (frame.into_bytes(), stats) + } + } + + fn schema() -> EntitySchema { + let pos = FieldType::QuantF32 { + min: -200.0, + max: 200.0, + bits: 14, + }; + EntitySchema::new() + .kind( + KindDef::new(1, "thing") + .field("x", pos) + .field("y", pos) + .field_with_priority("hp", FieldType::U16, 3.0) + .field("name", FieldType::ShortStr) + .field("up", FieldType::Bool), + ) + .kind( + KindDef::new(2, "tag") + .field("x", FieldType::F32) + .field("y", FieldType::F32) + .field_with_priority("label", FieldType::ShortStr, 0.5) + .priority(0.5), + ) + .kind( + KindDef::new(3, "beacon") + .field("x", pos) + .field("y", pos) + .field("blob", FieldType::Bytes) + .priority(2.0) + .every_patch(), + ) + } + + /// Random entity pool evolving patch by patch: moves, small value sets + /// (so fields revert), spawns, despawns, duplicates and unknown kinds. + struct Pool { + rng: ZoneRng, + alive: Vec>, + } + + impl Pool { + fn new(seed: u64, n: usize) -> Self { + Self { + rng: ZoneRng::from_seed(seed), + alive: vec![None; n], + } + } + + fn fields(rng: &mut ZoneRng, kind: u16, x: f32, y: f32) -> Vec { + let names = ["", "a", "bc", "def"]; + match kind { + 1 => vec![ + FieldValue::F(x), + FieldValue::F(y), + FieldValue::U(rng.range_u32(0, 4) * 50), + FieldValue::Str(names[rng.range_u32(0, 4) as usize].into()), + FieldValue::Bool(rng.chance(0.5)), + ], + 2 => vec![ + FieldValue::F(x), + FieldValue::F(y), + FieldValue::Str(names[rng.range_u32(0, 4) as usize].into()), + ], + _ => vec![ + FieldValue::F(x), + FieldValue::F(y), + FieldValue::Bytes(vec![1; rng.range_u32(0, 3) as usize]), + ], + } + } + + fn step(&mut self) -> WorldView { + let rng = &mut self.rng; + for (i, slot) in self.alive.iter_mut().enumerate() { + let id = i as u32 + 1; + match slot { + None if rng.chance(0.2) => { + // A reused id keeps its kind: a kind change under a + // known id is outside the delta model. + let kind = 1 + (id % 3) as u16; + let (x, y) = (rng.next_f32() * 160.0 - 80.0, rng.next_f32() * 160.0 - 80.0); + let mut e = EntityState::new(id, kind, x, y, Self::fields(rng, kind, x, y)) + .priority(0.5 + rng.next_f32() * 2.0); + e.global = id.is_multiple_of(9); + *slot = Some(e); + } + Some(_) if rng.chance(0.03) => *slot = None, + Some(e) => { + if rng.chance(0.6) { + e.x = (e.x + rng.next_f32() * 6.0 - 3.0).clamp(-100.0, 100.0); + e.y = (e.y + rng.next_f32() * 6.0 - 3.0).clamp(-100.0, 100.0); + e.fields[0] = FieldValue::F(e.x); + e.fields[1] = FieldValue::F(e.y); + } + if rng.chance(0.2) { + let fresh = Self::fields(rng, e.kind, e.x, e.y); + let i = 2 + rng.range_u32(0, fresh.len() as u32 - 2) as usize; + e.fields[i] = fresh[i].clone(); + } + } + None => {} + } + } + let mut view = WorldView::default(); + for e in self.alive.iter().flatten() { + view.push(e.clone()); + } + if rng.chance(0.3) { + if let Some(e) = self.alive.iter().flatten().next() { + let mut dup = e.clone(); + dup.x += 1.0; + view.push(dup); + } + } + if rng.chance(0.2) { + view.push(EntityState::new(999, 9, 0.0, 0.0, vec![])); + } + view + } + } + + struct Pair { + new: ClientReplica, + old: Reference, + view: View, + budget: usize, + } + + fn compare(seed: u64, rates: UpdateRates) { + let schema = schema(); + let interest = InterestConfig { + cell_size: 12.0, + update_rates: rates, + ..InterestConfig::default() + }; + let mut pool = Pool::new(seed, 50); + let mut rng = ZoneRng::from_seed(seed ^ 0x5eed); + let budgets = [12, 40, 160, 600, 4096, 1 << 20]; + let mut pairs: Vec = (0..6) + .map(|_| Pair { + new: ClientReplica::new(), + old: Reference::default(), + view: View::new(0.0, 0.0, 20.0 + rng.next_f32() * 60.0), + budget: budgets[rng.range_u32(0, 6) as usize], + }) + .collect(); + let mut world: Option = None; + for patch in 0..150u32 { + let view = pool.step(); + let mut next = match world.take() { + // Sometimes a fresh chain: no shared updates, patch 0. + Some(prev) if !rng.chance(0.05) => prev.next(&schema, &view, &interest), + _ => EncodedWorld::build(&schema, &view, &interest), + }; + for (i, pair) in pairs.iter_mut().enumerate() { + pair.view.x = (pair.view.x + rng.next_f32() * 8.0 - 4.0).clamp(-90.0, 90.0); + pair.view.y = (pair.view.y + rng.next_f32() * 8.0 - 4.0).clamp(-90.0, 90.0); + if rng.chance(0.05) { + pair.budget = budgets[rng.range_u32(0, 6) as usize]; + } + if rng.chance(0.01) { + pair.new.reset(); + pair.old.reset(); + } + // Skipped clients fall behind: their baselines go stale. + if rng.chance(0.15) { + continue; + } + let new = pair.new.build_delta( + &schema, + &mut next, + &interest, + &pair.view, + pair.budget, + patch, + i as u32, + ); + let old = pair.old.build_delta( + &schema, + &next, + &interest, + &pair.view, + pair.budget, + patch, + i as u32, + ); + assert_eq!(new, old, "seed {seed} patch {patch} client {i}"); + let mut known: Vec = pair.new.known_ids().collect(); + let mut want: Vec = pair.old.known.keys().copied().collect(); + known.sort_unstable(); + want.sort_unstable(); + assert_eq!(known, want, "seed {seed} patch {patch} client {i}"); + } + world = Some(next); + } + } + + #[test] + fn encode_once_matches_per_client_encoding() { + for seed in 0..24 { + compare(seed, UpdateRates::every_patch()); + compare(seed, UpdateRates::default()); + compare( + seed, + UpdateRates { + near: 0.2, + mid: 0.6, + mid_every: 3, + far_every: 6, + }, + ); + } + } + + /// `n` players inside a disk of radius 10, each viewing 24 around + /// itself (everyone sees everyone), all moving every patch. + fn dense_room(n: u32, patches: u32, rates: UpdateRates, before: bool) -> (Duration, usize) { + let pos = FieldType::QuantF32 { + min: -40.0, + max: 40.0, + bits: 14, + }; + let schema = EntitySchema::new().kind( + KindDef::new(1, "player") + .field("x", pos) + .field("y", pos) + .field("hp", FieldType::U8) + .field("facing", FieldType::Angle { bits: 8 }) + .priority(2.0), + ); + let interest = InterestConfig { + update_rates: rates, + ..InterestConfig::default() + }; + let mut rng = ZoneRng::from_seed(u64::from(n)); + let mut players: Vec<(f32, f32, f32)> = (0..n) + .map(|_| { + let a = rng.next_f32() * std::f32::consts::TAU; + let r = rng.next_f32().sqrt() * 10.0; + (r * a.cos(), r * a.sin(), a) + }) + .collect(); + let mut new: Vec = (0..n).map(|_| ClientReplica::new()).collect(); + let mut old: Vec = (0..n).map(|_| Reference::default()).collect(); + let mut world: Option = None; + let (mut spent, mut bytes) = (Duration::ZERO, 0usize); + let warmup = 10; + for patch in 0..warmup + patches { + let mut view = WorldView::default(); + for (i, p) in players.iter_mut().enumerate() { + p.2 += 0.05; + p.0 = (p.0 + p.2.cos() * 0.2).clamp(-10.0, 10.0); + p.1 = (p.1 + p.2.sin() * 0.2).clamp(-10.0, 10.0); + view.push(EntityState::new( + i as u32 + 1, + 1, + p.0, + p.1, + vec![ + FieldValue::F(p.0), + FieldValue::F(p.1), + FieldValue::U(100), + FieldValue::F(p.2), + ], + )); + } + let started = Instant::now(); + let mut next = match (world.take(), before) { + (Some(prev), false) => prev.next(&schema, &view, &interest), + _ => EncodedWorld::build(&schema, &view, &interest), + }; + let mut sent = 0; + for (i, p) in players.iter().enumerate() { + let v = View::new(p.0, p.1, 24.0); + let (frame, _) = if before { + old[i].build_delta(&schema, &next, &interest, &v, 4096, patch, 0) + } else { + new[i].build_delta(&schema, &mut next, &interest, &v, 4096, patch, 0) + }; + sent += frame.len(); + } + if patch >= warmup { + spent += started.elapsed(); + bytes += sent; + } + world = Some(next); + } + (spent / patches, bytes / (patches as usize * n as usize)) + } + + /// `cargo test -p distributed_game --release --lib dense_room_patch_build -- --ignored --nocapture` + #[test] + #[ignore = "timing"] + fn dense_room_patch_build() { + for n in [64, 128] { + let (before, b0) = dense_room(n, 200, UpdateRates::every_patch(), true); + let (once, b1) = dense_room(n, 200, UpdateRates::every_patch(), false); + let (rates, b2) = dense_room(n, 200, UpdateRates::default(), false); + println!( + "{n} clients: per-client {before:?} ({b0} B/client), encode once {once:?} ({b1} B), + update rates {rates:?} ({b2} B)" + ); + } + } +} diff --git a/distributed_game/src/rewind.rs b/distributed_game/src/rewind.rs new file mode 100644 index 000000000..5b2c4b9cc --- /dev/null +++ b/distributed_game/src/rewind.rs @@ -0,0 +1,817 @@ +//! Lag compensation: bounded per-entity history and hit tests at the +//! shooter's view time. +//! +//! A client renders remote entities in the past (it interpolates between the +//! last few Deltas). When it fires, it aimed at what it *saw*, not at where +//! targets are on the server now. The host therefore keeps a short ring +//! buffer of entity hit volumes per tick ([`Zone::record_rewind`]) and a zone +//! resolves a shot against that history: +//! +//! ```text +//! view_time = time_of(client_tick) - interp_delay (client-reported) +//! age = latest_recorded_time - view_time +//! age = min(age, max_rewind) (anti-cheat clamp) +//! ``` +//! +//! `client_tick` is the input's [`SequencedInput::client_tick`]; the +//! interpolation delay is game-defined and travels **inside the game's input +//! payload** (no wire change), e.g. as a `u16` of milliseconds. Whatever the +//! client claims, the rewind never exceeds [`RewindConfig::max_rewind`] nor +//! the recorded history, and never goes into the future. +//! +//! Inside a hook: `ctx.rewind().hit_test_shot(timing, &HitQuery::ray(..), |id| id != me)`. +//! +//! Coordinates are 3D (`[x, y, z]`); 2D games use `z = 0` and spheres. +//! Capsules are vertical (axis along `z`), centred on the entity position. +//! +//! [`Zone::record_rewind`]: crate::Zone::record_rewind +//! [`SequencedInput::client_tick`]: crate::SequencedInput::client_tick + +use std::collections::VecDeque; +use std::time::Duration; + +/// 3D vector. +pub type Vec3 = [f32; 3]; + +/// Rewind tuning (part of [`HostConfig`](crate::HostConfig)). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct RewindConfig { + /// Furthest a shot may be evaluated in the past (cheat clamp). + pub max_rewind: Duration, + /// Hard cap on stored ticks regardless of tick rate. + pub max_frames: usize, +} + +impl Default for RewindConfig { + fn default() -> Self { + Self { + max_rewind: Duration::from_millis(500), + max_frames: 256, + } + } +} + +/// Hit volume of a historical entity. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Shape { + /// Sphere centred on the entity position. + Sphere { + /// Radius. + radius: f32, + }, + /// Vertical capsule centred on the entity position. + Capsule { + /// Distance from the centre to each cap centre along `z`. + half_height: f32, + /// Radius. + radius: f32, + }, +} + +impl Shape { + fn radius(&self) -> f32 { + match *self { + Self::Sphere { radius } | Self::Capsule { radius, .. } => radius, + } + } + + pub(crate) fn segment(&self, pos: Vec3) -> (Vec3, Vec3) { + match *self { + Self::Sphere { .. } => (pos, pos), + Self::Capsule { half_height, .. } => ( + [pos[0], pos[1], pos[2] - half_height], + [pos[0], pos[1], pos[2] + half_height], + ), + } + } +} + +/// One entity's state at one tick. +#[derive(Debug, Clone, PartialEq)] +pub struct Historic { + /// Entity id (same id space as replication). + pub id: u32, + /// Position. + pub pos: Vec3, + /// Hit volume. + pub shape: Shape, + /// Arbitrary numeric fields (interpolated linearly by [`Rewind::at_time`]). + pub fields: Vec, + /// Layer bits a [`Ray`](crate::collide::Ray) mask selects + /// ([`layer::DEFAULT`](crate::collide::layer::DEFAULT); `0` is never hit). + pub layers: u32, +} + +impl Historic { + /// Entity with a sphere hit volume. + pub fn sphere(id: u32, pos: Vec3, radius: f32) -> Self { + Self { + id, + pos, + shape: Shape::Sphere { radius }, + fields: Vec::new(), + layers: crate::collide::layer::DEFAULT, + } + } + + /// Entity with a vertical capsule hit volume. + pub fn capsule(id: u32, pos: Vec3, half_height: f32, radius: f32) -> Self { + Self { + id, + pos, + shape: Shape::Capsule { + half_height, + radius, + }, + fields: Vec::new(), + layers: crate::collide::layer::DEFAULT, + } + } + + /// Attach numeric fields. + pub fn with_fields(mut self, fields: Vec) -> Self { + self.fields = fields; + self + } + + /// Put it on these layers (`0`: rays pass through, e.g. a dead mob). + pub fn on_layers(mut self, layers: u32) -> Self { + self.layers = layers; + self + } +} + +/// All recorded entities at one tick. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct RewindFrame { + tick: u64, + time: Duration, + entities: Vec, +} + +impl RewindFrame { + /// Record an entity (filled by [`Zone::record_rewind`](crate::Zone::record_rewind)). + pub fn push(&mut self, entity: Historic) { + self.entities.push(entity); + } + + /// Tick this frame describes (state after that tick's `on_tick`). + pub fn tick(&self) -> u64 { + self.tick + } + + /// Simulation time of that tick. + pub fn time(&self) -> Duration { + self.time + } + + /// Entities, sorted by id. + pub fn entities(&self) -> &[Historic] { + &self.entities + } + + pub(crate) fn into_entities(self) -> Vec { + self.entities + } + + /// One entity. + pub fn get(&self, id: u32) -> Option<&Historic> { + self.entities + .binary_search_by_key(&id, |e| e.id) + .ok() + .map(|i| &self.entities[i]) + } +} + +/// What the client reports with a shot. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ShotTiming { + /// Server tick the client's view was based on (input `client_tick`). + pub client_tick: u32, + /// How far behind `client_tick` the client was rendering. + pub interp_delay: Duration, +} + +/// A shot time after clamping. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ResolvedTime { + /// Simulation time the shot is evaluated at. + pub time: Duration, + /// How far behind the latest recorded tick that is. + pub age: Duration, + /// Age the client asked for. + pub requested_age: Duration, + /// True when the request was limited by `max_rewind` or the history. + pub clamped: bool, +} + +/// Geometric query. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum HitQuery { + /// Segment `from → to` (rays are segments with a max distance). + Segment { + /// Start. + from: Vec3, + /// End. + to: Vec3, + }, + /// Sphere (melee, explosion, point-in-radius with `radius = 0`). + Sphere { + /// Centre. + center: Vec3, + /// Radius. + radius: f32, + }, +} + +impl HitQuery { + /// Ray from `origin` along `dir` (need not be normalised) up to `max_dist`. + pub fn ray(origin: Vec3, dir: Vec3, max_dist: f32) -> Self { + let n = norm(dir); + let to = if n > 0.0 { + add(origin, scale(dir, max_dist / n)) + } else { + origin + }; + Self::Segment { from: origin, to } + } + + /// Point-in-radius test. + pub fn point(at: Vec3, radius: f32) -> Self { + Self::Sphere { center: at, radius } + } +} + +/// Nearest hit of a query. +#[derive(Debug, Clone, PartialEq)] +pub struct RewindHit { + /// Entity hit. + pub id: u32, + /// Distance along the segment to the entry point (segments), or + /// centre-to-surface distance (spheres; 0 when overlapping the centre). + pub distance: f32, + /// The entity as it was at the evaluated time. + pub entity: Historic, +} + +/// Bounded ring buffer of [`RewindFrame`]s. Reached through +/// [`Ctx::rewind`](crate::Ctx::rewind). +#[derive(Debug, Clone)] +pub struct Rewind { + config: RewindConfig, + capacity: usize, + frames: VecDeque, + /// The entity buffer of the last frame dropped, for the next one. + spare: Vec, +} + +impl Rewind { + /// History sized for `max_rewind` at `tick_rate` (plus slack), capped by + /// `max_frames`. + pub fn new(config: RewindConfig, tick_rate: u32) -> Self { + let per_tick = 1.0 / f64::from(tick_rate.max(1)); + let needed = (config.max_rewind.as_secs_f64() / per_tick).ceil() as usize + 2; + Self { + capacity: needed.clamp(2, config.max_frames.max(2)), + config, + frames: VecDeque::new(), + spare: Vec::new(), + } + } + + /// Configuration. + pub fn config(&self) -> &RewindConfig { + &self.config + } + + /// Stored frames bound. + pub fn capacity(&self) -> usize { + self.capacity + } + + /// Store a frame (called by the host after each tick). Entities are + /// sorted by id; frames must arrive in tick order. + pub fn record(&mut self, tick: u64, time: Duration, mut entities: Vec) { + // Usually recorded in id order already: then sorting (which may + // allocate) is skipped. + if !entities.is_sorted_by_key(|e| e.id) { + entities.sort_by_key(|e| e.id); + } + if self.frames.len() >= self.capacity { + if let Some(oldest) = self.frames.pop_front() { + self.spare = oldest.entities; + self.spare.clear(); + } + } + self.frames.push_back(RewindFrame { + tick, + time, + entities, + }); + } + + /// An empty frame for the host to fill ([`Zone::record_rewind`]), + /// reusing the buffer of the last frame dropped. + /// + /// [`Zone::record_rewind`]: crate::Zone::record_rewind + pub(crate) fn frame(&mut self) -> RewindFrame { + RewindFrame { + entities: std::mem::take(&mut self.spare), + ..RewindFrame::default() + } + } + + /// Forget everything (e.g. after a teleport-everything reset). + pub fn clear(&mut self) { + self.frames.clear(); + } + + /// Newest frame (the state clients were last sent). + pub fn latest(&self) -> Option<&RewindFrame> { + self.frames.back() + } + + /// Oldest stored frame. + pub fn oldest(&self) -> Option<&RewindFrame> { + self.frames.front() + } + + /// Stored frame count. + pub fn len(&self) -> usize { + self.frames.len() + } + + /// True when nothing has been recorded. + pub fn is_empty(&self) -> bool { + self.frames.is_empty() + } + + /// Exact frame for `tick`. + pub fn at(&self, tick: u64) -> Option<&RewindFrame> { + let first = self.frames.front()?.tick; + let index = tick.checked_sub(first)? as usize; + self.frames + .get(index) + .filter(|f| f.tick == tick) + .or_else(|| self.frames.iter().find(|f| f.tick == tick)) + } + + /// Simulation time of `tick` (32-bit wire tick, unwrapped against the + /// latest frame). Ticks outside the history are extrapolated with the + /// latest step; future ticks map to the latest time. + pub fn time_of(&self, client_tick: u32) -> Option { + let latest = self.frames.back()?; + let behind = (latest.tick as u32).wrapping_sub(client_tick) as i32; + if behind <= 0 { + return Some(latest.time); + } + let tick = latest.tick.saturating_sub(behind as u64); + if let Some(frame) = self.at(tick) { + return Some(frame.time); + } + let step = self.step(); + Some( + latest + .time + .saturating_sub(step.saturating_mul(behind as u32)), + ) + } + + fn step(&self) -> Duration { + let n = self.frames.len(); + if n < 2 { + return Duration::ZERO; + } + let (a, b) = (&self.frames[n - 2], &self.frames[n - 1]); + let ticks = b.tick.saturating_sub(a.tick).max(1) as u32; + b.time.saturating_sub(a.time) / ticks + } + + /// Clamp a client's view time: never older than `max_rewind` or the + /// oldest frame, never newer than the latest frame. + pub fn resolve(&self, timing: ShotTiming) -> Option { + let latest = self.frames.back()?.time; + let oldest = self.frames.front()?.time; + let wanted = self + .time_of(timing.client_tick)? + .saturating_sub(timing.interp_delay); + let requested_age = latest.saturating_sub(wanted); + let floor = latest.saturating_sub(self.config.max_rewind).max(oldest); + let time = wanted.max(floor); + Some(ResolvedTime { + time, + age: latest - time, + requested_age, + clamped: time != wanted, + }) + } + + /// Entities at `time`, interpolated between the surrounding frames + /// (positions and numeric fields lerp; shape and membership come from + /// the earlier frame). Clamped to the stored range. + pub fn at_time(&self, time: Duration) -> Option> { + let (a, b, alpha) = self.bracket(time)?; + Some( + a.entities + .iter() + .map(|e| match b.get(e.id) { + Some(next) if alpha > 0.0 => lerp_entity(e, next, alpha), + _ => e.clone(), + }) + .collect(), + ) + } + + /// One entity at `time` (see [`at_time`](Self::at_time)). + pub fn entity_at(&self, id: u32, time: Duration) -> Option { + let (a, b, alpha) = self.bracket(time)?; + let e = a.get(id)?; + Some(match b.get(id) { + Some(next) if alpha > 0.0 => lerp_entity(e, next, alpha), + _ => e.clone(), + }) + } + + /// Entities at `time` by reference, each with its interpolated position + /// (as [`at_time`](Self::at_time) places it, without copying it). + fn positions_at(&self, time: Duration) -> impl Iterator { + let bracket = self.bracket(time); + bracket.into_iter().flat_map(|(a, b, alpha)| { + a.entities.iter().map(move |e| match b.get(e.id) { + Some(next) if alpha > 0.0 => (e, lerp_pos(e.pos, next.pos, alpha)), + _ => (e, e.pos), + }) + }) + } + + fn bracket(&self, time: Duration) -> Option<(&RewindFrame, &RewindFrame, f32)> { + let first = self.frames.front()?; + let last = self.frames.back()?; + if time <= first.time { + return Some((first, first, 0.0)); + } + if time >= last.time { + return Some((last, last, 0.0)); + } + let index = self.frames.partition_point(|f| f.time <= time); + let (a, b) = (&self.frames[index - 1], &self.frames[index]); + let span = (b.time - a.time).as_secs_f32(); + let alpha = if span > 0.0 { + (time - a.time).as_secs_f32() / span + } else { + 0.0 + }; + Some((a, b, alpha)) + } + + /// Nearest entity hit by `query` at `time` among those `filter` accepts. + pub fn hit_test( + &self, + time: Duration, + query: &HitQuery, + mut filter: impl FnMut(u32) -> bool, + ) -> Option { + let mut best: Option<(u32, f32)> = None; + for (e, pos) in self.positions_at(time) { + if !filter(e.id) { + continue; + } + if let Some(distance) = intersect_at(query, &e.shape, pos) { + if best.is_none_or(|(_, d)| distance < d) { + best = Some((e.id, distance)); + } + } + } + let (id, distance) = best?; + Some(RewindHit { + id, + distance, + entity: self.entity_at(id, time)?, + }) + } + + /// Every entity overlapping `query` at `time` (area effects). + pub fn overlaps(&self, time: Duration, query: &HitQuery) -> Vec { + let mut hits: Vec = self + .positions_at(time) + .filter_map(|(e, pos)| { + let distance = intersect_at(query, &e.shape, pos)?; + Some(RewindHit { + id: e.id, + distance, + entity: self.entity_at(e.id, time)?, + }) + }) + .collect(); + hits.sort_by(|a, b| a.distance.total_cmp(&b.distance).then(a.id.cmp(&b.id))); + hits + } + + /// Resolve the client's view time (clamped) and hit-test there. + pub fn hit_test_shot( + &self, + timing: ShotTiming, + query: &HitQuery, + filter: impl FnMut(u32) -> bool, + ) -> Option<(RewindHit, ResolvedTime)> { + let resolved = self.resolve(timing)?; + self.hit_test(resolved.time, query, filter) + .map(|hit| (hit, resolved)) + } + + /// Closest hit of `ray` among the entities as they were at `time` that + /// `accept` takes, and the static `colliders` (only the colliders before + /// any history). + pub fn raycast_at( + &self, + time: Duration, + ray: &crate::collide::Ray, + colliders: &crate::collide::Colliders, + accept: impl FnMut(u32) -> bool, + ) -> Option { + crate::collide::raycast(self.positions_at(time), colliders, ray, accept) + } +} + +fn lerp_entity(a: &Historic, b: &Historic, t: f32) -> Historic { + Historic { + id: a.id, + pos: lerp_pos(a.pos, b.pos, t), + shape: a.shape, + layers: a.layers, + fields: a + .fields + .iter() + .enumerate() + .map(|(i, v)| b.fields.get(i).map_or(*v, |w| lerp(*v, *w, t))) + .collect(), + } +} + +fn lerp_pos(a: Vec3, b: Vec3, t: f32) -> Vec3 { + [lerp(a[0], b[0], t), lerp(a[1], b[1], t), lerp(a[2], b[2], t)] +} + +fn lerp(a: f32, b: f32, t: f32) -> f32 { + a + (b - a) * t +} + +pub(crate) fn add(a: Vec3, b: Vec3) -> Vec3 { + [a[0] + b[0], a[1] + b[1], a[2] + b[2]] +} + +pub(crate) fn sub(a: Vec3, b: Vec3) -> Vec3 { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} + +pub(crate) fn scale(a: Vec3, s: f32) -> Vec3 { + [a[0] * s, a[1] * s, a[2] * s] +} + +pub(crate) fn dot(a: Vec3, b: Vec3) -> f32 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +pub(crate) fn norm(a: Vec3) -> f32 { + dot(a, a).sqrt() +} + +/// Closest point to `p` on segment `a → b`. +pub(crate) fn closest_on_segment(p: Vec3, a: Vec3, b: Vec3) -> Vec3 { + let ab = sub(b, a); + let len2 = dot(ab, ab); + if len2 <= f32::EPSILON { + return a; + } + let t = (dot(sub(p, a), ab) / len2).clamp(0.0, 1.0); + add(a, scale(ab, t)) +} + +/// Entry distance of the ray `ro + t·rd` (`rd` unit) into a sphere, if any +/// with `t >= 0` (0 when starting inside). +fn ray_sphere(ro: Vec3, rd: Vec3, center: Vec3, r: f32) -> Option { + let oc = sub(ro, center); + let c = dot(oc, oc) - r * r; + if c <= 0.0 { + return Some(0.0); + } + let b = dot(oc, rd); + let h = b * b - c; + if h < 0.0 || b > 0.0 { + return None; + } + Some(-b - h.sqrt()) +} + +/// Entry distance of a ray into a capsule `pa–pb` of radius `r`. +fn ray_capsule(ro: Vec3, rd: Vec3, pa: Vec3, pb: Vec3, r: f32) -> Option { + let closest = closest_on_segment(ro, pa, pb); + if dot(sub(ro, closest), sub(ro, closest)) <= r * r { + return Some(0.0); + } + let ba = sub(pb, pa); + let oa = sub(ro, pa); + let baba = dot(ba, ba); + let bard = dot(ba, rd); + let baoa = dot(ba, oa); + let rdoa = dot(rd, oa); + let oaoa = dot(oa, oa); + let a = baba - bard * bard; + let mut best: Option = None; + if a.abs() > 1e-9 { + let b = baba * rdoa - baoa * bard; + let c = baba * oaoa - baoa * baoa - r * r * baba; + let h = b * b - a * c; + if h >= 0.0 { + let t = (-b - h.sqrt()) / a; + let y = baoa + t * bard; + if t >= 0.0 && y > 0.0 && y < baba { + best = Some(t); + } + } + } + for cap in [pa, pb] { + if let Some(t) = ray_sphere(ro, rd, cap, r) { + best = Some(best.map_or(t, |b: f32| b.min(t))); + } + } + best +} + +/// Distance of `query` to a volume of `shape` at `pos` (see [`RewindHit::distance`]). +pub(crate) fn intersect_at(query: &HitQuery, shape: &Shape, pos: Vec3) -> Option { + let r = shape.radius(); + let (pa, pb) = shape.segment(pos); + match *query { + HitQuery::Segment { from, to } => { + let d = sub(to, from); + let len = norm(d); + if len <= f32::EPSILON { + let c = closest_on_segment(from, pa, pb); + return (norm(sub(from, c)) <= r).then_some(0.0); + } + let rd = scale(d, 1.0 / len); + ray_capsule(from, rd, pa, pb, r).filter(|t| *t <= len) + } + HitQuery::Sphere { center, radius } => { + let c = closest_on_segment(center, pa, pb); + let d = norm(sub(center, c)); + (d <= r + radius).then_some((d - r).max(0.0)) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const MS: fn(u64) -> Duration = Duration::from_millis; + + /// 30 Hz history of a target moving +x at 10 u/s along y = 10. + fn history(config: RewindConfig, ticks: u64) -> Rewind { + let mut rw = Rewind::new(config, 30); + let dt = Duration::from_secs(1) / 30; + for tick in 1..=ticks { + let t = dt * tick as u32; + let x = t.as_secs_f32() * 10.0; + rw.record( + tick, + t, + vec![ + Historic::sphere(7, [x, 10.0, 0.0], 0.5).with_fields(vec![x]), + Historic::capsule(9, [-50.0, 0.0, 1.0], 0.8, 0.4), + ], + ); + } + rw + } + + #[test] + fn ring_buffer_is_bounded_by_max_rewind() { + let rw = history(RewindConfig::default(), 200); + // 500 ms at 30 Hz = 15 ticks + 2 slack. + assert_eq!(rw.capacity(), 17); + assert_eq!(rw.len(), 17); + assert_eq!(rw.latest().unwrap().tick(), 200); + assert_eq!(rw.oldest().unwrap().tick(), 184); + assert!(rw.at(183).is_none()); + assert_eq!(rw.at(190).unwrap().tick(), 190); + } + + #[test] + fn at_time_interpolates_positions_and_fields() { + let rw = history(RewindConfig::default(), 60); + // Halfway between tick 50 and 51. + let t = (Duration::from_secs(1) / 30) * 50 + Duration::from_secs(1) / 60; + let e = rw.entity_at(7, t).unwrap(); + let expected = t.as_secs_f32() * 10.0; + assert!( + (e.pos[0] - expected).abs() < 1e-3, + "{} vs {expected}", + e.pos[0] + ); + assert!((e.fields[0] - expected).abs() < 1e-3); + } + + #[test] + fn laggy_shot_misses_now_but_hits_at_view_time() { + let rw = history(RewindConfig::default(), 60); + let latest = rw.latest().unwrap().time(); + // Client saw tick 54 rendered 100 ms behind: view = t(54) - 100 ms. + let timing = ShotTiming { + client_tick: 54, + interp_delay: MS(100), + }; + let view = rw.resolve(timing).unwrap(); + assert!(!view.clamped); + let seen_x = view.time.as_secs_f32() * 10.0; + // Shoot straight up (+y) through where the target was on screen. + let ray = HitQuery::ray([seen_x, 0.0, 0.0], [0.0, 1.0, 0.0], 100.0); + assert!( + rw.hit_test(latest, &ray, |_| true).is_none(), + "present-time target has moved on" + ); + let (hit, resolved) = rw.hit_test_shot(timing, &ray, |_| true).unwrap(); + assert_eq!(hit.id, 7); + assert!((hit.distance - 9.5).abs() < 1e-3, "{}", hit.distance); + assert_eq!(resolved, view); + } + + #[test] + fn rewind_beyond_max_is_clamped() { + let rw = history( + RewindConfig { + max_rewind: MS(250), + max_frames: 1024, + }, + 90, + ); + let latest = rw.latest().unwrap().time(); + // Cheater claims a 2 s old view to hit where the target was then. + let timing = ShotTiming { + client_tick: 90, + interp_delay: Duration::from_secs(2), + }; + let resolved = rw.resolve(timing).unwrap(); + assert!(resolved.clamped); + assert_eq!(resolved.age, MS(250)); + assert_eq!(resolved.requested_age, Duration::from_secs(2)); + let old_x = (latest - Duration::from_secs(2)).as_secs_f32() * 10.0; + let ray = HitQuery::ray([old_x, 0.0, 0.0], [0.0, 1.0, 0.0], 100.0); + assert!(rw.hit_test_shot(timing, &ray, |_| true).is_none()); + // Within the clamp the same request style still works. + let ok_x = (latest - MS(200)).as_secs_f32() * 10.0; + let ray = HitQuery::ray([ok_x, 0.0, 0.0], [0.0, 1.0, 0.0], 100.0); + let timing = ShotTiming { + client_tick: 90, + interp_delay: MS(200), + }; + assert_eq!(rw.hit_test_shot(timing, &ray, |_| true).unwrap().0.id, 7); + } + + #[test] + fn future_ticks_resolve_to_latest() { + let rw = history(RewindConfig::default(), 30); + let timing = ShotTiming { + client_tick: 40, + interp_delay: Duration::ZERO, + }; + let r = rw.resolve(timing).unwrap(); + assert_eq!(r.time, rw.latest().unwrap().time()); + assert_eq!(r.age, Duration::ZERO); + } + + #[test] + fn capsule_segment_and_point_queries() { + let rw = history(RewindConfig::default(), 5); + let now = rw.latest().unwrap().time(); + // Horizontal shot through the capsule's cylinder. + let shot = HitQuery::ray([-60.0, 0.0, 1.0], [1.0, 0.0, 0.0], 50.0); + let hit = rw.hit_test(now, &shot, |id| id == 9).unwrap(); + assert!( + (hit.distance - (10.0 - 0.4)).abs() < 1e-3, + "{}", + hit.distance + ); + // Through the upper cap: entry = 10 - sqrt(0.4² - 0.2²). + let cap = HitQuery::ray([-60.0, 0.0, 2.0], [1.0, 0.0, 0.0], 50.0); + let hit = rw.hit_test(now, &cap, |id| id == 9).unwrap(); + assert!((hit.distance - (10.0 - 0.12f32.sqrt())).abs() < 1e-3); + // Above the capsule (z = 2.3 > 1.8 + 0.4) misses. + let over = HitQuery::ray([-60.0, 0.0, 2.3], [1.0, 0.0, 0.0], 50.0); + assert!(rw.hit_test(now, &over, |id| id == 9).is_none()); + // Too short a segment misses. + let short = HitQuery::ray([-60.0, 0.0, 1.0], [1.0, 0.0, 0.0], 5.0); + assert!(rw.hit_test(now, &short, |_| true).is_none()); + // Point-in-radius. + assert_eq!( + rw.overlaps(now, &HitQuery::point([-50.2, 0.0, 0.5], 0.0))[0].id, + 9 + ); + assert!(rw + .overlaps(now, &HitQuery::point([-49.0, 0.0, 0.5], 0.2)) + .is_empty()); + // Filter excludes the shooter. + assert!(rw.hit_test(now, &shot, |id| id != 9).is_none()); + } +} diff --git a/distributed_game/src/rng.rs b/distributed_game/src/rng.rs new file mode 100644 index 000000000..bfa94f460 --- /dev/null +++ b/distributed_game/src/rng.rs @@ -0,0 +1,121 @@ +//! Seeded deterministic per-zone random numbers. +//! +//! [`ZoneRng`] is xoshiro256** seeded through SplitMix64. A zone's generator is +//! derived from the deployment's world seed and the zone id +//! ([`ZoneRng::for_zone`]), so the same world seed, zone id and input log +//! always reproduce the same simulation. Zones must take randomness only from +//! [`Ctx::rng`](crate::Ctx::rng) to stay deterministic. + +/// 64-bit FNV-1a, used for seed derivation and as a cheap state-hash helper. +#[derive(Debug, Clone, Copy)] +pub struct Fnv64(u64); + +impl Fnv64 { + const OFFSET: u64 = 0xcbf2_9ce4_8422_2325; + const PRIME: u64 = 0x0000_0100_0000_01b3; + + /// Fresh hasher. + pub fn new() -> Self { + Self(Self::OFFSET) + } + + /// Mix raw bytes. + pub fn write(&mut self, bytes: &[u8]) -> &mut Self { + for byte in bytes { + self.0 ^= u64::from(*byte); + self.0 = self.0.wrapping_mul(Self::PRIME); + } + self + } + + /// Mix a little-endian u64. + pub fn write_u64(&mut self, value: u64) -> &mut Self { + self.write(&value.to_le_bytes()) + } + + /// Mix an f32 by its bit pattern. + pub fn write_f32(&mut self, value: f32) -> &mut Self { + self.write(&value.to_bits().to_le_bytes()) + } + + /// Current digest. + pub fn finish(&self) -> u64 { + self.0 + } +} + +impl Default for Fnv64 { + fn default() -> Self { + Self::new() + } +} + +fn splitmix64(state: &mut u64) -> u64 { + *state = state.wrapping_add(0x9e37_79b9_7f4a_7c15); + let mut z = *state; + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^ (z >> 31) +} + +/// Deterministic xoshiro256** generator. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ZoneRng { + s: [u64; 4], +} + +impl ZoneRng { + /// Seed directly. + pub fn from_seed(seed: u64) -> Self { + let mut sm = seed; + let s = [ + splitmix64(&mut sm), + splitmix64(&mut sm), + splitmix64(&mut sm), + splitmix64(&mut sm), + ]; + Self { s } + } + + /// Derive a zone's generator: `seed = world_seed ^ fnv1a64(zone_id)`. + pub fn for_zone(world_seed: u64, zone_id: &str) -> Self { + Self::from_seed(world_seed ^ Fnv64::new().write(zone_id.as_bytes()).finish()) + } + + /// Next 64 random bits. + pub fn next_u64(&mut self) -> u64 { + let result = self.s[1].wrapping_mul(5).rotate_left(7).wrapping_mul(9); + let t = self.s[1] << 17; + self.s[2] ^= self.s[0]; + self.s[3] ^= self.s[1]; + self.s[1] ^= self.s[2]; + self.s[0] ^= self.s[3]; + self.s[2] ^= t; + self.s[3] = self.s[3].rotate_left(45); + result + } + + /// Next 32 random bits (high half of [`next_u64`](Self::next_u64)). + pub fn next_u32(&mut self) -> u32 { + (self.next_u64() >> 32) as u32 + } + + /// Uniform float in `[0, 1)` with 24 bits of precision. + pub fn next_f32(&mut self) -> f32 { + (self.next_u64() >> 40) as f32 * (1.0 / (1u32 << 24) as f32) + } + + /// Uniform integer in `[low, high)`; returns `low` when the range is empty. + pub fn range_u32(&mut self, low: u32, high: u32) -> u32 { + if high <= low { + return low; + } + let span = u64::from(high - low); + low + ((u64::from(self.next_u32()) * span) >> 32) as u32 + } + + /// Bernoulli trial with probability `p`. + pub fn chance(&mut self, p: f32) -> bool { + self.next_f32() < p + } +} diff --git a/distributed_game/src/schema.rs b/distributed_game/src/schema.rs new file mode 100644 index 000000000..1702b05c9 --- /dev/null +++ b/distributed_game/src/schema.rs @@ -0,0 +1,572 @@ +//! Entity schema: kinds, component fields, field types and quantization. +//! +//! The game describes what it replicates once ([`EntitySchema`]). The schema +//! is serialized into every Welcome so a generic client can decode Deltas +//! without generated code. Each kind has at most [`MAX_FIELDS`] fields; field +//! order is the wire order and the bit order of update masks. +//! +//! Quantization is specified bit-exactly in `PROTOCOL.md` §4 and computed in +//! `f64` so a JavaScript client (whose numbers are `f64`) reproduces the same +//! integers and decoded `f32` values. Use [`FieldType::quantize_linear`] / +//! [`FieldType::canonicalize`] on the server when prediction must match what +//! clients will see. + +use crate::protocol::wire::{DecodeError, Reader, Writer}; + +/// Maximum fields per entity kind (update masks are a 32-bit varuint). +pub const MAX_FIELDS: usize = 32; + +/// `2π` as used by angle quantization. +pub const TAU: f64 = std::f64::consts::TAU; + +/// Wire type of one component field. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum FieldType { + /// `u8` 0/1. Tag 0. + Bool, + /// One raw byte. Tag 1. + U8, + /// varuint, 0..=65535. Tag 2. + U16, + /// varuint. Tag 3. + U32, + /// zigzag varint. Tag 4. + I32, + /// binary32 LE. Tag 5. + F32, + /// Clamped linear quantization to `bits` (1..=32), sent as varuint. Tag 6. + QuantF32 { + /// Lower bound (inclusive). + min: f32, + /// Upper bound (inclusive). + max: f32, + /// Precision in bits. + bits: u8, + }, + /// Radians wrapped to `[0, 2π)` and quantized to `bits` (1..=32). Tag 7. + Angle { + /// Precision in bits. + bits: u8, + }, + /// `u8` length + UTF-8 (<= 255 bytes). Tag 8. + ShortStr, + /// varuint length + raw bytes. Tag 9. + Bytes, +} + +/// A field value. Decoded values use the canonical variant for the type: +/// Bool→`Bool`, U8/U16/U32→`U`, I32→`I`, F32/QuantF32/Angle→`F`, +/// ShortStr→`Str`, Bytes→`Bytes`. Encoding coerces numeric variants to the +/// field's type (saturating), so games may supply any numeric variant. +#[derive(Debug, Clone, PartialEq)] +pub enum FieldValue { + /// Boolean. + Bool(bool), + /// Unsigned integer. + U(u32), + /// Signed integer. + I(i32), + /// Float. + F(f32), + /// Text. + Str(String), + /// Opaque bytes. + Bytes(Vec), +} + +impl FieldValue { + fn as_f64(&self) -> f64 { + match self { + Self::Bool(v) => f64::from(u8::from(*v)), + Self::U(v) => f64::from(*v), + Self::I(v) => f64::from(*v), + Self::F(v) => f64::from(*v), + Self::Str(_) | Self::Bytes(_) => 0.0, + } + } +} + +impl FieldType { + /// `QuantF32` over `[-range, range - range / 2^(bits-1)]`: the grid step + /// is `range / 2^(bits-1)` and **zero is exactly representable**. + /// + /// A symmetric `[-r, r]` range has an odd number of intervals + /// (`2^bits - 1`), so 0 falls between two grid points: a velocity of 0 + /// decodes as ±half a step and a resting entity creeps. Use this for + /// signed quantities (velocities, offsets). `bits` must be 1..=32. + pub const fn quant_centered(range: f32, bits: u8) -> Self { + let half = (1u64 << (bits - 1)) as f32; + Self::QuantF32 { + min: -range, + max: range - range / half, + bits, + } + } + + /// Clamped linear quantization (`PROTOCOL.md` §4.1). + pub fn quantize_linear(v: f32, min: f32, max: f32, bits: u8) -> u32 { + let maxq = max_q(bits); + let (lo, hi) = (f64::from(min), f64::from(max)); + if hi <= lo { + return 0; + } + let mut x = f64::from(v); + if x.is_nan() { + x = lo; + } + let x = x.clamp(lo, hi); + let t = (x - lo) / (hi - lo); + (t * maxq + 0.5).floor().min(maxq) as u32 + } + + /// Inverse of [`quantize_linear`](Self::quantize_linear). + pub fn dequantize_linear(q: u32, min: f32, max: f32, bits: u8) -> f32 { + let maxq = max_q(bits); + let (lo, hi) = (f64::from(min), f64::from(max)); + (lo + (f64::from(q) / maxq) * (hi - lo)) as f32 + } + + /// Angle quantization (`PROTOCOL.md` §4.2). + pub fn quantize_angle(v: f32, bits: u8) -> u32 { + let steps = steps(bits); + let mut a = f64::from(v); + if !a.is_finite() { + return 0; + } + a %= TAU; + if a < 0.0 { + a += TAU; + } + let q = ((a / TAU) * steps + 0.5).floor(); + (q % steps) as u32 + } + + /// Inverse of [`quantize_angle`](Self::quantize_angle). + pub fn dequantize_angle(q: u32, bits: u8) -> f32 { + ((f64::from(q) * TAU) / steps(bits)) as f32 + } + + /// The value a client will decode for `value` (round-trip through the wire). + pub fn canonicalize(&self, value: &FieldValue) -> FieldValue { + let mut w = Writer::new(); + self.encode(&mut w, value); + self.decode(&mut Reader::new(w.as_bytes())) + .expect("encoded field must decode") + } + + /// Wire tag. + pub fn tag(&self) -> u8 { + match self { + Self::Bool => 0, + Self::U8 => 1, + Self::U16 => 2, + Self::U32 => 3, + Self::I32 => 4, + Self::F32 => 5, + Self::QuantF32 { .. } => 6, + Self::Angle { .. } => 7, + Self::ShortStr => 8, + Self::Bytes => 9, + } + } + + /// Encode a value of this type (coercing numerics). + pub fn encode(&self, w: &mut Writer, value: &FieldValue) { + let n = value.as_f64(); + match self { + Self::Bool => { + w.bool(n != 0.0); + } + Self::U8 => { + w.u8(n.clamp(0.0, 255.0) as u8); + } + Self::U16 => { + w.varuint(n.clamp(0.0, 65535.0) as u32); + } + Self::U32 => { + w.varuint(match value { + FieldValue::U(v) => *v, + _ => n.clamp(0.0, f64::from(u32::MAX)) as u32, + }); + } + Self::I32 => { + w.varint(match value { + FieldValue::I(v) => *v, + _ => n.clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32, + }); + } + Self::F32 => { + w.f32(n as f32); + } + Self::QuantF32 { min, max, bits } => { + w.varuint(Self::quantize_linear(n as f32, *min, *max, *bits)); + } + Self::Angle { bits } => { + w.varuint(Self::quantize_angle(n as f32, *bits)); + } + Self::ShortStr => { + w.short_string(match value { + FieldValue::Str(s) => s, + _ => "", + }); + } + Self::Bytes => { + w.bytes(match value { + FieldValue::Bytes(b) => b, + FieldValue::Str(s) => s.as_bytes(), + _ => &[], + }); + } + } + } + + /// Decode a value of this type. + pub fn decode(&self, r: &mut Reader<'_>) -> Result { + Ok(match self { + Self::Bool => FieldValue::Bool(r.bool()?), + Self::U8 => FieldValue::U(u32::from(r.u8()?)), + Self::U16 => { + let v = r.varuint()?; + if v > 65535 { + return Err(DecodeError::Invalid("u16 out of range")); + } + FieldValue::U(v) + } + Self::U32 => FieldValue::U(r.varuint()?), + Self::I32 => FieldValue::I(r.varint()?), + Self::F32 => FieldValue::F(r.f32()?), + Self::QuantF32 { min, max, bits } => { + let q = r.varuint()?; + if f64::from(q) > max_q(*bits) { + return Err(DecodeError::Invalid("quantized value out of range")); + } + FieldValue::F(Self::dequantize_linear(q, *min, *max, *bits)) + } + Self::Angle { bits } => { + let q = r.varuint()?; + if f64::from(q) >= steps(*bits) { + return Err(DecodeError::Invalid("angle out of range")); + } + FieldValue::F(Self::dequantize_angle(q, *bits)) + } + Self::ShortStr => FieldValue::Str(r.short_string()?), + Self::Bytes => FieldValue::Bytes(r.bytes()?.to_vec()), + }) + } + + fn write_def(&self, w: &mut Writer) { + w.u8(self.tag()); + match self { + Self::QuantF32 { min, max, bits } => { + w.f32(*min).f32(*max).u8(*bits); + } + Self::Angle { bits } => { + w.u8(*bits); + } + _ => {} + } + } + + fn read_def(r: &mut Reader<'_>) -> Result { + let tag = r.u8()?; + Ok(match tag { + 0 => Self::Bool, + 1 => Self::U8, + 2 => Self::U16, + 3 => Self::U32, + 4 => Self::I32, + 5 => Self::F32, + 6 => { + let (min, max, bits) = (r.f32()?, r.f32()?, r.u8()?); + check_bits(bits)?; + Self::QuantF32 { min, max, bits } + } + 7 => { + let bits = r.u8()?; + check_bits(bits)?; + Self::Angle { bits } + } + 8 => Self::ShortStr, + 9 => Self::Bytes, + other => return Err(DecodeError::UnknownFieldType(other)), + }) + } +} + +fn check_bits(bits: u8) -> Result<(), DecodeError> { + if (1..=32).contains(&bits) { + Ok(()) + } else { + Err(DecodeError::Invalid("quantization bits must be 1..=32")) + } +} + +fn max_q(bits: u8) -> f64 { + ((1u64 << bits.clamp(1, 32)) - 1) as f64 +} + +fn steps(bits: u8) -> f64 { + (1u64 << bits.clamp(1, 32)) as f64 +} + +/// How a predicting client resolves a misprediction of one field (the JS +/// SDK's `CorrectionPolicy`). Client metadata only: never sent on the wire, +/// exported in the [`GameSurface`](crate::surface::GameSurface) so generated +/// clients get per-field defaults. +#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)] +pub enum Correction { + /// Adopt the rebased value, easing the visual error out over `duration_ms`. + Ease { + /// Ease duration (ms). + #[serde(rename = "durationMs")] + duration_ms: u32, + /// An error larger than this cuts instead, every eased field of the + /// entity at once (a teleport — a respawn, a server-side move — is a + /// cut, not a misprediction to slide over). + #[serde(rename = "snapAbove", default, skip_serializing_if = "Option::is_none")] + snap_above: Option, + }, + /// Adopt the rebased value immediately. + Snap, + /// Server-owned: show the authoritative value, never replay inputs over it. + Replace, +} + +/// One component field of a kind. +#[derive(Debug, Clone, PartialEq)] +pub struct FieldDef { + /// Name (informational for generic clients). + pub name: String, + /// Wire type. + pub ty: FieldType, + /// Server-side replication priority multiplier (not sent on the wire). + pub priority: f32, + /// Client correction default (not sent on the wire; see [`Correction`]). + pub correction: Option, +} + +/// An entity kind: id, name and ordered fields. +#[derive(Debug, Clone, PartialEq)] +pub struct KindDef { + /// Kind id (varuint on the wire). + pub id: u16, + /// Name. + pub name: String, + /// Ordered fields (<= [`MAX_FIELDS`]). + pub fields: Vec, + /// Server-side priority multiplier (not sent on the wire). + pub priority: f32, + /// Exempt from distance-based update rates + /// ([`UpdateRates`](crate::UpdateRates); server-side, not on the wire). + pub every_patch: bool, +} + +impl KindDef { + /// New kind with priority 1. + pub fn new(id: u16, name: impl Into) -> Self { + Self { + id, + name: name.into(), + fields: Vec::new(), + priority: 1.0, + every_patch: false, + } + } + + /// Append a field with priority 1. + pub fn field(self, name: impl Into, ty: FieldType) -> Self { + self.field_with_priority(name, ty, 1.0) + } + + /// Append a field with an explicit priority. + pub fn field_with_priority(mut self, name: impl Into, ty: FieldType, p: f32) -> Self { + assert!(self.fields.len() < MAX_FIELDS, "at most 32 fields per kind"); + if let FieldType::QuantF32 { bits, .. } | FieldType::Angle { bits } = ty { + assert!((1..=32).contains(&bits), "quantization bits must be 1..=32"); + } + self.fields.push(FieldDef { + name: name.into(), + ty, + priority: p, + correction: None, + }); + self + } + + /// Set the client correction default of the last added field. + /// + /// # Panics + /// If the kind has no fields yet. + pub fn correct(mut self, correction: Correction) -> Self { + self.fields + .last_mut() + .expect("add a field before its correction") + .correction = Some(correction); + self + } + + /// Set the kind priority multiplier. + pub fn priority(mut self, p: f32) -> Self { + self.priority = p; + self + } + + /// Update every patch at any distance (no distance-based rates). + pub fn every_patch(mut self) -> Self { + self.every_patch = true; + self + } +} + +/// All replicated kinds of a zone type. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct EntitySchema { + kinds: Vec, +} + +impl EntitySchema { + /// Empty schema. + pub fn new() -> Self { + Self::default() + } + + /// Add a kind (ids must be unique). + pub fn kind(mut self, kind: KindDef) -> Self { + assert!(self.get(kind.id).is_none(), "duplicate kind id {}", kind.id); + self.kinds.push(kind); + self + } + + /// Kinds in declaration order. + pub fn kinds(&self) -> &[KindDef] { + &self.kinds + } + + /// Look up a kind. + pub fn get(&self, id: u16) -> Option<&KindDef> { + self.kinds.iter().find(|kind| kind.id == id) + } + + /// Serialize (`PROTOCOL.md` §5). + pub fn encode(&self, w: &mut Writer) { + w.varuint(self.kinds.len() as u32); + for kind in &self.kinds { + w.varuint(u32::from(kind.id)) + .string(&kind.name) + .varuint(kind.fields.len() as u32); + for field in &kind.fields { + w.string(&field.name); + field.ty.write_def(w); + } + } + } + + /// Deserialize; server-only priorities decode as 1. + pub fn decode(r: &mut Reader<'_>) -> Result { + let count = r.varuint()?; + let mut schema = Self::new(); + for _ in 0..count { + let id = r.varuint()?; + let id = u16::try_from(id).map_err(|_| DecodeError::Invalid("kind id > u16"))?; + let name = r.string()?; + let field_count = r.varuint()? as usize; + if field_count > MAX_FIELDS { + return Err(DecodeError::Invalid("more than 32 fields")); + } + let mut kind = KindDef::new(id, name); + for _ in 0..field_count { + let name = r.string()?; + let ty = FieldType::read_def(r)?; + kind = kind.field(name, ty); + } + if schema.get(id).is_some() { + return Err(DecodeError::Invalid("duplicate kind id")); + } + schema.kinds.push(kind); + } + Ok(schema) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn centered_quantization_represents_zero_exactly() { + for (range, bits) in [ + (16.0, 12), + (16.0, 14), + (20.0, 18), + (8.0, 12), + (64.0, 16), + (1.0, 2), + ] { + let ty = FieldType::quant_centered(range, bits); + assert_eq!(ty.canonicalize(&FieldValue::F(0.0)), FieldValue::F(0.0)); + assert_eq!( + ty.canonicalize(&FieldValue::F(-range)), + FieldValue::F(-range) + ); + let step = range / (1u64 << (bits - 1)) as f32; + assert_eq!(ty.canonicalize(&FieldValue::F(step)), FieldValue::F(step)); + } + // The symmetric range cannot: 0 lands half a step off. + let symmetric = FieldType::QuantF32 { + min: -16.0, + max: 16.0, + bits: 12, + }; + assert_ne!( + symmetric.canonicalize(&FieldValue::F(0.0)), + FieldValue::F(0.0) + ); + } + + #[test] + fn linear_quantization_rounds_half_up_and_clamps() { + let q = |v| FieldType::quantize_linear(v, -10.0, 10.0, 8); + assert_eq!(q(-10.0), 0); + assert_eq!(q(10.0), 255); + assert_eq!(q(99.0), 255); + assert_eq!(q(f32::NAN), 0); + assert_eq!(q(0.0), 128); // 127.5 rounds up + let back = FieldType::dequantize_linear(128, -10.0, 10.0, 8); + assert!((back - 0.039_215_688).abs() < 1e-6); + } + + #[test] + fn angle_wraps() { + let bits = 8; + assert_eq!(FieldType::quantize_angle(0.0, bits), 0); + assert_eq!(FieldType::quantize_angle(-0.000_001, bits), 0); + assert_eq!(FieldType::quantize_angle(std::f32::consts::PI, bits), 128); + assert_eq!( + FieldType::quantize_angle(-std::f32::consts::FRAC_PI_2, bits), + 192 + ); + } + + #[test] + fn schema_round_trips() { + let schema = EntitySchema::new().kind( + KindDef::new(3, "orb") + .field( + "x", + FieldType::QuantF32 { + min: 0.0, + max: 64.0, + bits: 12, + }, + ) + .field("yaw", FieldType::Angle { bits: 10 }) + .field("name", FieldType::ShortStr), + ); + let mut w = Writer::new(); + schema.encode(&mut w); + let mut r = Reader::new(w.as_bytes()); + assert_eq!(EntitySchema::decode(&mut r).unwrap(), schema); + r.finish().unwrap(); + } +} diff --git a/distributed_game/src/stamp.rs b/distributed_game/src/stamp.rs new file mode 100644 index 000000000..3268500db --- /dev/null +++ b/distributed_game/src/stamp.rs @@ -0,0 +1,259 @@ +//! Tick stamping: provenance of committed facts. +//! +//! Every [`Fact`](crate::Fact) carries a [`FactStamp`] filled in by the host +//! when the zone emits it: zone id, activation, tick, host wall time, +//! content version and config version. The cell adapter forwards the stamp +//! as trusted session variables; command handlers copy it into +//! `EventRecord.metadata` with [`stamp_metadata`] (or `stamp_event_record` +//! with the `cell` feature) so every durable event records exactly which +//! simulation tick produced it. +//! +//! **Ordering.** Commit order is not emission order: facts travel through +//! per-principal lanes and retries, and two zones commit independently. A +//! handler that must order facts (presence: "left A" vs "joined B" after a +//! handoff) compares stamps with [`FactStamp::emission_order`]. Within one +//! zone activation the emission sequence `seq` decides (the host numbers +//! every fact it stamps, so two facts of the same tick and millisecond +//! still have a strict order); across activations of one zone the +//! activation (it grows across restarts); across zones the host wall time +//! `emitted_at_ms`. A handoff target never stamps the arriving player's +//! facts earlier than the source stamped its departure: the transfer ticket +//! carries the departure time and the target's stamps start after it, even +//! when the two hosts' clocks disagree. + +use std::cmp::Ordering; +use std::collections::HashMap; + +/// Metadata key for the zone id. +pub const META_ZONE: &str = "game.zone"; +/// Metadata key for the zone tick (decimal). +pub const META_TICK: &str = "game.tick"; +/// Metadata key for the content version. +pub const META_CONTENT_VERSION: &str = "game.content_version"; +/// Metadata key for the host wall time at emission (Unix ms, decimal). +pub const META_EMITTED_AT_MS: &str = "game.emitted_at_ms"; +/// Metadata key for the zone activation (boot epoch, decimal). +pub const META_ACTIVATION: &str = "game.activation"; +/// Metadata key for the config version. +pub const META_CONFIG_VERSION: &str = "game.config_version"; +/// Metadata key for the per-activation emission sequence (decimal). +pub const META_SEQ: &str = "game.seq"; + +/// Session-variable prefix used to carry a stamp through a trusted Session. +pub const SESSION_PREFIX: &str = "x-game-"; + +/// Where and when a fact was produced. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct FactStamp { + /// Zone id. + pub zone_id: String, + /// Zone tick during which the fact was emitted. + pub tick: u64, + /// Content version the zone was running. + pub content_version: String, + /// Host wall time at emission, Unix milliseconds + /// ([`Clock::unix_ms`](crate::Clock::unix_ms), never earlier than a + /// handoff source's departure stamp). + pub emitted_at_ms: u64, + /// Zone activation ([`HostConfig::boot_epoch`](crate::HostConfig::boot_epoch): + /// the ownership fencing token under the `net` server); grows across + /// restarts and hibernation. + pub activation: u64, + /// Remote config version the zone was running + /// ([`HostConfig::config_version`](crate::HostConfig::config_version)). + pub config_version: String, + /// Emission sequence within the activation: the host numbers every fact + /// it stamps 1, 2, 3, ... so facts of one tick (a join and a dropped + /// socket in the same tick and millisecond) keep a strict order. A stamp + /// taken for anything else ([`Ctx::stamp`](crate::Ctx::stamp)) carries + /// the sequence of the last fact stamped before it. + pub seq: u64, +} + +impl FactStamp { + /// Metadata entries for this stamp. + pub fn entries(&self) -> [(&'static str, String); 7] { + [ + (META_ZONE, self.zone_id.clone()), + (META_TICK, self.tick.to_string()), + (META_CONTENT_VERSION, self.content_version.clone()), + (META_EMITTED_AT_MS, self.emitted_at_ms.to_string()), + (META_ACTIVATION, self.activation.to_string()), + (META_CONFIG_VERSION, self.config_version.clone()), + (META_SEQ, self.seq.to_string()), + ] + } + + /// Session variables (`x-game-zone`, `x-game-tick`, + /// `x-game-content-version`, `x-game-emitted-at-ms`, + /// `x-game-activation`, `x-game-config-version`, `x-game-seq`). + pub fn session_vars(&self) -> [(String, String); 7] { + [ + (format!("{SESSION_PREFIX}zone"), self.zone_id.clone()), + (format!("{SESSION_PREFIX}tick"), self.tick.to_string()), + ( + format!("{SESSION_PREFIX}content-version"), + self.content_version.clone(), + ), + ( + format!("{SESSION_PREFIX}emitted-at-ms"), + self.emitted_at_ms.to_string(), + ), + ( + format!("{SESSION_PREFIX}activation"), + self.activation.to_string(), + ), + ( + format!("{SESSION_PREFIX}config-version"), + self.config_version.clone(), + ), + (format!("{SESSION_PREFIX}seq"), self.seq.to_string()), + ] + } + + /// Read a stamp back from session variables (None if any is + /// absent/malformed). + pub fn from_session_vars(vars: &HashMap) -> Option { + let get = |name: &str| vars.get(&format!("{SESSION_PREFIX}{name}")); + Some(Self { + zone_id: get("zone")?.clone(), + tick: get("tick")?.parse().ok()?, + content_version: get("content-version")?.clone(), + emitted_at_ms: get("emitted-at-ms")?.parse().ok()?, + activation: get("activation")?.parse().ok()?, + config_version: get("config-version")?.clone(), + seq: get("seq")?.parse().ok()?, + }) + } + + /// Read a stamp back from event metadata written by [`stamp_metadata`] + /// (None if any entry is absent/malformed). + pub fn from_metadata(metadata: &HashMap) -> Option { + Some(Self { + zone_id: metadata.get(META_ZONE)?.clone(), + tick: metadata.get(META_TICK)?.parse().ok()?, + content_version: metadata.get(META_CONTENT_VERSION)?.clone(), + emitted_at_ms: metadata.get(META_EMITTED_AT_MS)?.parse().ok()?, + activation: metadata.get(META_ACTIVATION)?.parse().ok()?, + config_version: metadata.get(META_CONFIG_VERSION)?.clone(), + seq: metadata.get(META_SEQ)?.parse().ok()?, + }) + } + + /// Emission order of two stamps: same zone and activation by emission + /// sequence (then tick and wall time); same zone across activations by + /// activation; different + /// zones by wall time (then zone id, activation and tick, so the order + /// is total and deterministic). Commit order says nothing about this. + pub fn emission_order(&self, other: &Self) -> Ordering { + if self.zone_id == other.zone_id { + self.activation + .cmp(&other.activation) + .then(self.seq.cmp(&other.seq)) + .then(self.tick.cmp(&other.tick)) + .then(self.emitted_at_ms.cmp(&other.emitted_at_ms)) + } else { + self.emitted_at_ms + .cmp(&other.emitted_at_ms) + .then_with(|| self.zone_id.cmp(&other.zone_id)) + .then(self.activation.cmp(&other.activation)) + .then(self.seq.cmp(&other.seq)) + .then(self.tick.cmp(&other.tick)) + } + } + + /// True when this stamp was emitted after `other` + /// ([`emission_order`](Self::emission_order)). + pub fn emitted_after(&self, other: &Self) -> bool { + self.emission_order(other) == Ordering::Greater + } +} + +/// Insert the stamp into an event metadata map. +pub fn stamp_metadata(metadata: &mut HashMap, stamp: &FactStamp) { + for (key, value) in stamp.entries() { + metadata.insert(key.to_string(), value); + } +} + +/// Stamp a `distributed` event record's metadata. +#[cfg(feature = "cell")] +pub fn stamp_event_record(record: &mut distributed::EventRecord, stamp: &FactStamp) { + stamp_metadata(&mut record.metadata, stamp); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn stamp(zone: &str, activation: u64, tick: u64, at: u64) -> FactStamp { + FactStamp { + zone_id: zone.into(), + tick, + content_version: "c7".into(), + emitted_at_ms: at, + activation, + config_version: "combat@12".into(), + // Ticks only grow within an activation, so neither does seq. + seq: tick, + } + } + + #[test] + fn stamp_round_trips_through_session_vars_and_metadata() { + let stamp = stamp("z1", 9, 42, 1_700_000_000_123); + let vars: HashMap<_, _> = stamp.session_vars().into_iter().collect(); + assert_eq!(FactStamp::from_session_vars(&vars), Some(stamp.clone())); + let mut meta = HashMap::new(); + stamp_metadata(&mut meta, &stamp); + assert_eq!(meta[META_TICK], "42"); + assert_eq!(meta[META_ZONE], "z1"); + assert_eq!(meta[META_EMITTED_AT_MS], "1700000000123"); + assert_eq!(meta[META_ACTIVATION], "9"); + assert_eq!(meta[META_CONFIG_VERSION], "combat@12"); + assert_eq!(meta[META_SEQ], "42"); + assert_eq!(FactStamp::from_metadata(&meta), Some(stamp)); + } + + #[test] + fn missing_or_malformed_fields_are_rejected() { + let stamp = stamp("z1", 9, 42, 5); + let mut vars: HashMap<_, _> = stamp.session_vars().into_iter().collect(); + vars.remove("x-game-activation"); + assert_eq!(FactStamp::from_session_vars(&vars), None); + let mut vars: HashMap<_, _> = stamp.session_vars().into_iter().collect(); + vars.insert("x-game-emitted-at-ms".into(), "soon".into()); + assert_eq!(FactStamp::from_session_vars(&vars), None); + let mut meta = HashMap::new(); + stamp_metadata(&mut meta, &stamp); + meta.remove(META_CONFIG_VERSION); + assert_eq!(FactStamp::from_metadata(&meta), None); + } + + #[test] + fn emission_order_by_tick_activation_then_wall_time() { + // One activation: the tick wins over a wall clock read out of order. + assert!(stamp("a", 1, 11, 100).emitted_after(&stamp("a", 1, 10, 200))); + // A later activation of the same zone is later, ticks restart. + assert!(stamp("a", 2, 1, 50).emitted_after(&stamp("a", 1, 900, 60))); + // Different zones: wall time. + assert!(stamp("b", 1, 1, 201).emitted_after(&stamp("a", 7, 99, 200))); + assert!(!stamp("a", 7, 99, 200).emitted_after(&stamp("b", 1, 1, 201))); + // Ties are broken deterministically. + let (x, y) = (stamp("a", 1, 1, 5), stamp("b", 1, 1, 5)); + assert_eq!(x.emission_order(&y), y.emission_order(&x).reverse()); + // Same tick and millisecond: the emission sequence decides. + let (first, second) = ( + FactStamp { + seq: 7, + ..stamp("a", 1, 3, 9) + }, + FactStamp { + seq: 8, + ..stamp("a", 1, 3, 9) + }, + ); + assert!(second.emitted_after(&first)); + assert!(!first.emitted_after(&second)); + } +} diff --git a/distributed_game/src/surface.rs b/distributed_game/src/surface.rs new file mode 100644 index 000000000..3f721e7c1 --- /dev/null +++ b/distributed_game/src/surface.rs @@ -0,0 +1,888 @@ +//! The game surface manifest: everything a generated client needs to know +//! about one zone type, built from the authoring derives. +//! +//! A [`GameSurface`] lists the zone's replicated kinds (fields, wire types, +//! priorities, client correction defaults), its input layout, its events and +//! the records their payloads mention; optionally its client-predicted step +//! ([`GameSurface::predict`]), pure functions compiled to WebAssembly +//! ([`GameSurface::pure`]), constants the client needs +//! ([`GameSurface::constant`]) and standalone records it decodes +//! ([`GameSurface::record`]). It is versioned +//! ([`GAME_SURFACE_SCHEMA_VERSION`]) and serialized as JSON by an app export +//! function (conventionally `game_surface`), which `distributed +//! game-manifest` runs and `distributed game-client` turns into typed +//! TypeScript. +//! +//! ```ignore +//! pub fn game_surface() -> GameSurface { +//! GameSurface::for_zone::("arena").events::() +//! } +//! ``` +//! +//! It is deliberately separate from the strict GraphQL client manifest: game +//! clients speak the binary zone protocol (`PROTOCOL.md`), not GraphQL. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde::{Deserialize, Serialize}; + +use crate::codec::WireType; +use crate::prediction::{PredictContext, PredictStep}; +use crate::pure::GamePure; +use crate::schema::{Correction, EntitySchema}; +use crate::{GameEvent, GameInput, Wire, Zone}; + +/// Wire protocol version whose payload encodings (fields, inputs, events) +/// a surface describes. They have not changed since 1: protocol 2 only +/// added handshake negotiation (Welcome `features` and `origin`), which the +/// SDK handles, so generated clients stay valid for both. +pub const SURFACE_PROTOCOL_VERSION: u32 = 1; + +/// Version of the [`GameSurface`] JSON shape. +pub const GAME_SURFACE_SCHEMA_VERSION: u32 = 3; + +/// One zone type's client-facing surface. See the module docs. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct GameSurface { + /// [`GAME_SURFACE_SCHEMA_VERSION`]. + pub schema_version: u32, + /// Surface name (generated TypeScript prefixes exports with it). + pub name: String, + /// Zone wire protocol version of the payload encodings + /// ([`SURFACE_PROTOCOL_VERSION`]). + pub protocol_version: u32, + /// Replicated kinds in schema order. + pub kinds: Vec, + /// Input layout, if the zone takes typed input. + pub input: Option, + /// Events by id. + pub events: Vec, + /// Records mentioned by inputs, events or the predicted step, by name. + pub records: Vec, + /// The client-predicted step, compiled to WebAssembly (see + /// [`crate::prediction`]). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub predict: Option, + /// Pure functions compiled into the same WebAssembly module, by export + /// (see [`crate::pure`]). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub pures: Vec, + /// Constants emitted as generated TypeScript data, by name. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub constants: Vec, + /// Records with a standalone codec in the generated client + /// (`encode` / `decode`), by name. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub codecs: Vec, + /// Zone inbox messages ([`Zone::Message`], [`crate::inbox`]) by id: + /// what services may send into a running zone. Same payload encoding + /// as events. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub messages: Vec, +} + +/// A pure function compiled to WebAssembly ([`crate::pure::GamePure`]). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PureSurface { + /// Export suffix: the module exports `dg_pure_`. + pub export: String, + /// Cargo package declaring it (the surface's module is built from it). + pub package: String, + /// Argument type, if it takes one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub arg: Option, + /// Result type. + pub output: WireType, + /// Binary ABI version ([`crate::prediction::ABI_VERSION`]). + pub abi: u32, +} + +/// A constant value of the client (static data defined once in Rust). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ConstantSurface { + /// `snake_case` name (generated TypeScript: `SCREAMING_SNAKE`). + pub name: String, + /// Wire type of the value. + #[serde(rename = "type")] + pub ty: WireType, + /// The value as a client decodes it ([`crate::codec::to_json_value`]): + /// records keyed by Rust field name, exact float values. + pub value: serde_json::Value, +} + +/// The zone's client-predicted step ([`crate::prediction::PredictStep`]). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PredictSurface { + /// Predicted kind (the controlled entity's kind). + pub kind: String, + /// Cargo package declaring the step (compiled to WebAssembly). + pub package: String, + /// Export suffix: the module exports `dg_predict_`. + pub export: String, + /// State record (fields named after the kind's fields). + pub state: String, + /// Context record, if the step takes one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub context: Option, + /// Binary ABI version ([`crate::prediction::ABI_VERSION`]). + pub abi: u32, +} + +/// One replicated kind. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct KindSurface { + /// Kind id. + pub id: u16, + /// Kind name. + pub name: String, + /// Server-side priority multiplier. + pub priority: f32, + /// Ordered fields. + pub fields: Vec, +} + +/// One entity field. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct EntityFieldSurface { + /// Wire name (the key in `RenderedEntity.fields`). + pub name: String, + /// Wire type (always an entity field type). + #[serde(rename = "type")] + pub ty: WireType, + /// Server-side priority multiplier. + pub priority: f32, + /// Client correction default. + pub correction: Option, +} + +/// A payload field (input, event or record). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PayloadField { + /// Rust field name (generated TypeScript uses its camelCase form). + pub name: String, + /// Wire type. + #[serde(rename = "type")] + pub ty: WireType, + /// Input sanitize range `[min, max]` (inputs only). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub range: Option<[f64; 2]>, + /// Button names, bit 0 first (input bit-flag fields only). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub buttons: Vec, +} + +impl PayloadField { + /// Plain field. + pub fn new(name: impl Into, ty: WireType) -> Self { + Self { + name: name.into(), + ty, + range: None, + buttons: Vec::new(), + } + } +} + +/// The input layout. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct InputSurface { + /// Rust type name. + pub name: String, + /// Fields in wire order. + pub fields: Vec, +} + +/// One event type. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct EventSurface { + /// Stable type id (the Event message `type_id`). + pub id: u32, + /// Event name (snake_case). + pub name: String, + /// Payload: inline fields or one value. + pub payload: EventPayload, +} + +/// An event payload. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum EventPayload { + /// Named fields in wire order (struct events, struct-like variants). + Fields { + /// Fields. + fields: Vec, + }, + /// The payload is one value's encoding (`Variant(T)`), typically a + /// record shared with other code. + Value { + /// Value type. + #[serde(rename = "type")] + ty: WireType, + }, +} + +/// A named record (nested payload struct). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RecordSurface { + /// Rust type name. + pub name: String, + /// Fields in wire order. + pub fields: Vec, +} + +impl GameSurface { + /// Empty surface named `name`. + pub fn new(name: impl Into) -> Self { + Self { + schema_version: GAME_SURFACE_SCHEMA_VERSION, + name: name.into(), + protocol_version: SURFACE_PROTOCOL_VERSION, + kinds: Vec::new(), + input: None, + events: Vec::new(), + records: Vec::new(), + predict: None, + pures: Vec::new(), + constants: Vec::new(), + codecs: Vec::new(), + messages: Vec::new(), + } + } + + /// Kinds from the zone's [`Zone::schema`], its typed input and its + /// inbox messages ([`Zone::Message`]). + pub fn for_zone(name: impl Into) -> Self + where + Z: Zone, + Z::Input: GameInput, + { + Self::new(name) + .schema(&Z::schema()) + .input::() + .messages::() + } + + /// Add the zone inbox message type (done by [`for_zone`](Self::for_zone)). + /// Message ids and names must be unique among messages. + pub fn messages(mut self) -> Self { + let mut records = Vec::new(); + for message in M::event_surfaces(&mut records) { + assert!( + self.messages + .iter() + .all(|m| m.id != message.id && m.name != message.name), + "duplicate message id {} / name {} in game surface {}", + message.id, + message.name, + self.name + ); + self.messages.push(message); + } + self.messages.sort_by_key(|m| m.id); + self.add_records(records); + self + } + + /// Add every kind of `schema` (derived or hand-written). + pub fn schema(mut self, schema: &EntitySchema) -> Self { + for kind in schema.kinds() { + assert!( + self.kinds.iter().all(|k| k.id != kind.id), + "duplicate kind id {} in game surface {}", + kind.id, + self.name + ); + self.kinds.push(KindSurface { + id: kind.id, + name: kind.name.clone(), + priority: kind.priority, + fields: kind + .fields + .iter() + .map(|field| EntityFieldSurface { + name: field.name.clone(), + ty: WireType::of_field(field.ty), + priority: field.priority, + correction: field.correction, + }) + .collect(), + }); + } + self + } + + /// Set the input layout. + pub fn input(mut self) -> Self { + let mut records = Vec::new(); + self.input = Some(I::input_surface(&mut records)); + self.add_records(records); + self + } + + /// Add an event type (a `#[derive(GameEvent)]` enum adds all its + /// variants). Event ids and names must be unique across the surface. + pub fn events(mut self) -> Self { + let mut records = Vec::new(); + for event in E::event_surfaces(&mut records) { + assert!( + self.events + .iter() + .all(|e| e.id != event.id && e.name != event.name), + "duplicate event id {} / name {} in game surface {}", + event.id, + event.name, + self.name + ); + self.events.push(event); + } + self.events.sort_by_key(|e| e.id); + self.add_records(records); + self + } + + /// Declare the zone's client-predicted step (`#[predict]`). Checks that + /// it predicts a kind of this surface, takes the surface's input, and + /// that every state field names a field of the kind with a matching + /// scalar type; panics otherwise (surface export time). + pub fn predict(mut self) -> Self { + if let Some(pure) = self.pures.first() { + assert_eq!( + pure.package, + P::PACKAGE, + "predicted step {} of game surface {} must be declared in the Cargo package of its pure functions", + P::EXPORT, + self.name + ); + } + let mut records = Vec::new(); + let input = P::Input::input_surface(&mut records); + assert_eq!( + self.input.as_ref(), + Some(&input), + "predicted step {} of game surface {} must take the zone's input type", + P::EXPORT, + self.name + ); + let kind = self + .kinds + .iter() + .find(|k| k.name == P::KIND) + .unwrap_or_else(|| { + panic!( + "predicted step {} names kind {:?}, which game surface {} does not replicate", + P::EXPORT, + P::KIND, + self.name + ) + }) + .clone(); + let state = record_name(P::State::wire_type(), "state", P::EXPORT); + P::State::records(&mut records); + let state_record = records + .iter() + .find(|r| r.name == state) + .expect("a record pushes its own definition") + .clone(); + for field in &state_record.fields { + let entity = kind + .fields + .iter() + .find(|f| f.name == field.name) + .unwrap_or_else(|| { + panic!( + "predicted state {state} field {} is not a field of kind {}", + field.name, kind.name + ) + }); + assert!( + state_field_matches(&field.ty, &entity.ty), + "predicted state {state} field {} ({:?}) does not match kind {} field type {:?}", + field.name, + field.ty, + kind.name, + entity.ty + ); + } + let context = P::Context::context_type().map(|ty| record_name(ty, "context", P::EXPORT)); + P::Context::context_records(&mut records); + self.predict = Some(PredictSurface { + kind: P::KIND.to_string(), + package: P::PACKAGE.to_string(), + export: P::EXPORT.to_string(), + state, + context, + abi: crate::prediction::ABI_VERSION, + }); + self.add_records(records); + self + } + + /// Add a pure function (`#[game_pure]`) to the surface's WebAssembly + /// module. Every compiled function of a surface (and its predicted step) + /// must come from one Cargo package; export names must be unique. + pub fn pure(mut self) -> Self { + assert!( + self.pures.iter().all(|p| p.export != F::EXPORT), + "pure function {} added twice to game surface {}", + F::EXPORT, + self.name + ); + let package = self + .predict + .as_ref() + .map(|p| p.package.as_str()) + .or(self.pures.first().map(|p| p.package.as_str())); + if let Some(package) = package { + assert_eq!( + package, + F::PACKAGE, + "pure function {} of game surface {} is declared in Cargo package {}, but the surface's module is built from {package}", + F::EXPORT, + self.name, + F::PACKAGE + ); + } + let mut records = Vec::new(); + let arg = crate::pure::arg_type::(&mut records); + F::Output::records(&mut records); + self.pures.push(PureSurface { + export: F::EXPORT.to_string(), + package: F::PACKAGE.to_string(), + arg, + output: F::Output::wire_type(), + abi: crate::prediction::ABI_VERSION, + }); + self.pures.sort_by(|a, b| a.export.cmp(&b.export)); + self.add_records(records); + self + } + + /// Add a constant the generated client exports as TypeScript data + /// (`constant("arena_floor", &floor)` → `ARENA_FLOOR: ArenaFloor`). The + /// value is stored as the client would decode it (exact floats, + /// quantized fields quantized); its records join the surface. Names are + /// `snake_case` and unique; panics on a non-finite float. + pub fn constant(mut self, name: &str, value: &T) -> Self { + assert!( + !name.is_empty() + && name.starts_with(|c: char| c.is_ascii_lowercase()) + && name + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'), + "constant name {name:?} of game surface {} must be snake_case", + self.name + ); + assert!( + self.constants.iter().all(|c| c.name != name), + "constant {name} added twice to game surface {}", + self.name + ); + let value = crate::codec::to_json_value(value).unwrap_or_else(|error| { + panic!( + "constant {name} of game surface {} has no client value: {error:?}", + self.name + ) + }); + let mut records = Vec::new(); + T::records(&mut records); + self.constants.push(ConstantSurface { + name: name.to_string(), + ty: T::wire_type(), + value, + }); + self.constants.sort_by(|a, b| a.name.cmp(&b.name)); + self.add_records(records); + self + } + + /// Give a record (`#[derive(GameRecord)]`) a standalone codec in the + /// generated client (`encode` / `decode`), e.g. for a + /// payload served over HTTP. + pub fn record(mut self) -> Self { + let name = match T::wire_type() { + WireType::Record { name } => name, + other => { + panic!("GameSurface::record takes a #[derive(GameRecord)] struct, not {other:?}") + } + }; + let mut records = Vec::new(); + T::records(&mut records); + if !self.codecs.contains(&name) { + self.codecs.push(name); + self.codecs.sort(); + } + self.add_records(records); + self + } + + fn add_records(&mut self, records: Vec) { + for record in records { + match self.records.iter().find(|r| r.name == record.name) { + Some(existing) => assert_eq!( + existing, &record, + "two different records named {} in game surface {}", + record.name, self.name + ), + None => self.records.push(record), + } + } + self.records.sort_by(|a, b| a.name.cmp(&b.name)); + } + + /// Pretty JSON (deterministic: kinds in schema order, events by id, + /// records by name). + pub fn to_json(&self) -> String { + serde_json::to_string_pretty(self).expect("game surface serializes") + } + + /// Structural validity of a surface, however it was produced (the + /// builders above, or JSON read back by `distributed game-client`): + /// the versions this crate speaks, unique kinds, events, records, + /// fields and buttons, replicable kind field types, known and + /// non-recursive records, and a consistent predicted step, pure + /// functions, constants and codecs. + /// + /// Naming rules of one target language (collisions after case + /// conversion, reserved words) belong to that generator. + /// + /// # Errors + /// + /// The first violated rule, as a message naming the offending item. + pub fn validate(&self) -> Result<(), String> { + if self.schema_version != GAME_SURFACE_SCHEMA_VERSION { + return Err(format!( + "unsupported game surface schemaVersion {}; this version is {GAME_SURFACE_SCHEMA_VERSION}", + self.schema_version + )); + } + if self.protocol_version != SURFACE_PROTOCOL_VERSION { + return Err(format!( + "unsupported game surface protocolVersion {}; this version is {SURFACE_PROTOCOL_VERSION}", + self.protocol_version + )); + } + if self.name.is_empty() + || !self + .name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') + { + return Err(format!("invalid surface name {:?}", self.name)); + } + let mut records = BTreeMap::new(); + for record in &self.records { + if records.insert(record.name.as_str(), record).is_some() { + return Err(format!("duplicate record {}", record.name)); + } + } + let mut kind_ids = BTreeSet::new(); + let mut kind_names = BTreeSet::new(); + for kind in &self.kinds { + if !kind_ids.insert(kind.id) { + return Err(format!("duplicate kind id {}", kind.id)); + } + if kind.name.is_empty() || !kind_names.insert(kind.name.as_str()) { + return Err(format!("duplicate or empty kind name {:?}", kind.name)); + } + let mut names = BTreeSet::new(); + for field in &kind.fields { + if field.ty.field_type().is_none() { + return Err(format!( + "kind {} field {} has a non-entity wire type", + kind.name, field.name + )); + } + if !names.insert(field.name.as_str()) { + return Err(format!( + "kind {} fields collide as `{}`", + kind.name, field.name + )); + } + } + } + let mut event_ids = BTreeSet::new(); + let mut event_names = BTreeSet::new(); + for event in &self.events { + if !event_ids.insert(event.id) || !event_names.insert(event.name.as_str()) { + return Err(format!("duplicate event {} / {}", event.id, event.name)); + } + match &event.payload { + EventPayload::Fields { fields } => check_fields(fields, &event.name, &records)?, + EventPayload::Value { ty } => check_type(ty, &event.name, &records)?, + } + } + for record in &self.records { + check_fields(&record.fields, &record.name, &records)?; + } + if let Some(input) = &self.input { + check_fields(&input.fields, &input.name, &records)?; + let mut buttons = BTreeSet::new(); + for button in input.fields.iter().flat_map(|field| &field.buttons) { + if !buttons.insert(button.as_str()) { + return Err(format!("duplicate input button {button}")); + } + } + } + self.records_in_dependency_order()?; + self.validate_predict(&records)?; + self.validate_pures(&records)?; + let mut constants = BTreeSet::new(); + for constant in &self.constants { + let snake_case = constant.name.starts_with(|c: char| c.is_ascii_lowercase()) + && constant + .name + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'); + if !snake_case || !constants.insert(constant.name.as_str()) { + return Err(format!( + "constant name {:?} is not snake_case or is declared twice", + constant.name + )); + } + check_type(&constant.ty, &constant.name, &records)?; + } + for codec in &self.codecs { + if !records.contains_key(codec.as_str()) { + return Err(format!("codec record {codec} is missing")); + } + } + Ok(()) + } + + /// Records with every record a record uses before it. + /// + /// # Errors + /// + /// A record that (transitively) contains itself, or names a record the + /// surface does not list. + pub fn records_in_dependency_order(&self) -> Result, String> { + fn visit<'r>( + name: &str, + records: &BTreeMap<&'r str, &'r RecordSurface>, + done: &mut BTreeSet<&'r str>, + visiting: &mut BTreeSet<&'r str>, + order: &mut Vec<&'r RecordSurface>, + ) -> Result<(), String> { + if done.contains(name) { + return Ok(()); + } + let record = *records + .get(name) + .ok_or_else(|| format!("unknown record {name}"))?; + if !visiting.insert(record.name.as_str()) { + return Err(format!( + "record {name} is recursive; recursive records are not supported" + )); + } + for field in &record.fields { + if let Some(used) = record_of(&field.ty) { + visit(used, records, done, visiting, order)?; + } + } + visiting.remove(name); + done.insert(record.name.as_str()); + order.push(record); + Ok(()) + } + let records: BTreeMap<&str, &RecordSurface> = self + .records + .iter() + .map(|record| (record.name.as_str(), record)) + .collect(); + let mut order = Vec::new(); + let (mut done, mut visiting) = (BTreeSet::new(), BTreeSet::new()); + for name in records.keys() { + visit(name, &records, &mut done, &mut visiting, &mut order)?; + } + Ok(order) + } + + /// The predicted step names a kind of this surface, a state record whose + /// fields are fields of that kind (plain scalar types), an optional + /// context record, and this crate's ABI. + fn validate_predict(&self, records: &BTreeMap<&str, &RecordSurface>) -> Result<(), String> { + let Some(predict) = &self.predict else { + return Ok(()); + }; + if predict.abi != crate::prediction::ABI_VERSION { + return Err(format!( + "predicted step uses ABI v{}; this version speaks ABI v{}", + predict.abi, + crate::prediction::ABI_VERSION + )); + } + if !is_export_name(&predict.export) { + return Err(format!( + "invalid predicted step export {:?}", + predict.export + )); + } + if predict.package.is_empty() { + return Err("predicted step names no Cargo package".into()); + } + if self.input.is_none() { + return Err("a predicted step needs the zone's input type".into()); + } + let kind = self + .kinds + .iter() + .find(|kind| kind.name == predict.kind) + .ok_or_else(|| format!("predicted kind {:?} is not replicated", predict.kind))?; + let state = records + .get(predict.state.as_str()) + .ok_or_else(|| format!("predicted state record {} is missing", predict.state))?; + if state.fields.is_empty() { + return Err(format!("predicted state {} has no fields", state.name)); + } + for field in &state.fields { + let entity = kind + .fields + .iter() + .find(|entity| entity.name == field.name) + .ok_or_else(|| { + format!( + "predicted state {} field {} is not a field of kind {}", + state.name, field.name, kind.name + ) + })?; + if !state_field_matches(&field.ty, &entity.ty) { + return Err(format!( + "predicted state {} field {} does not match the type of kind {} field {}", + state.name, field.name, kind.name, entity.name + )); + } + } + if let Some(context) = &predict.context { + if !records.contains_key(context.as_str()) { + return Err(format!("predicted context record {context} is missing")); + } + } + Ok(()) + } + + /// Pure functions: valid unique exports, one Cargo package (the + /// predicted step's, if any), known types, this crate's ABI. + fn validate_pures(&self, records: &BTreeMap<&str, &RecordSurface>) -> Result<(), String> { + let mut exports = BTreeSet::new(); + let package = self + .predict + .as_ref() + .map(|predict| predict.package.as_str()) + .or_else(|| self.pures.first().map(|pure| pure.package.as_str())); + for pure in &self.pures { + if pure.abi != crate::prediction::ABI_VERSION { + return Err(format!( + "pure function {} uses ABI v{}; this version speaks ABI v{}", + pure.export, + pure.abi, + crate::prediction::ABI_VERSION + )); + } + if !is_export_name(&pure.export) { + return Err(format!("invalid pure function export {:?}", pure.export)); + } + if !exports.insert(pure.export.as_str()) { + return Err(format!("duplicate pure function {}", pure.export)); + } + if pure.package.is_empty() { + return Err(format!( + "pure function {} names no Cargo package", + pure.export + )); + } + let expected = package.expect("a surface with pures has a package"); + if pure.package != expected { + return Err(format!( + "pure function {} is declared in Cargo package {}, but the surface's module is built from {expected}", + pure.export, pure.package + )); + } + if let Some(arg) = &pure.arg { + check_type(arg, &pure.export, records)?; + } + check_type(&pure.output, &pure.export, records)?; + } + Ok(()) + } +} + +/// A WebAssembly export suffix (`dg_predict_`, `dg_pure_`). +fn is_export_name(export: &str) -> bool { + !export.is_empty() + && export + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_') +} + +/// The record a type names, through lists and optionals. +fn record_of(ty: &WireType) -> Option<&str> { + match ty { + WireType::List { item } | WireType::Optional { item } => record_of(item), + WireType::Record { name } => Some(name), + _ => None, + } +} + +fn check_type( + ty: &WireType, + owner: &str, + records: &BTreeMap<&str, &RecordSurface>, +) -> Result<(), String> { + match record_of(ty) { + Some(name) if !records.contains_key(name) => Err(format!("{owner}: unknown record {name}")), + _ => Ok(()), + } +} + +fn check_fields( + fields: &[PayloadField], + owner: &str, + records: &BTreeMap<&str, &RecordSurface>, +) -> Result<(), String> { + let mut names = BTreeSet::new(); + for field in fields { + if field.name.is_empty() || !names.insert(field.name.as_str()) { + return Err(format!( + "{owner}: field `{}` is empty or collides with another as `{}`", + field.name, field.name + )); + } + check_type(&field.ty, owner, records)?; + } + Ok(()) +} + +fn record_name(ty: WireType, what: &str, export: &str) -> String { + match ty { + WireType::Record { name } => name, + other => panic!( + "predicted step {export}: the {what} must be a #[derive(GameRecord)] struct, not {other:?}" + ), + } +} + +/// A state field holds the plain value of an entity field: `f32` for float +/// fields (quantized or not, the step works on full binary32), the same +/// integer / bool type otherwise. +fn state_field_matches(state: &WireType, entity: &WireType) -> bool { + match state { + WireType::F32 => matches!( + entity, + WireType::F32 | WireType::Quant { .. } | WireType::Angle { .. } + ), + WireType::Bool | WireType::U8 | WireType::U16 | WireType::U32 | WireType::I32 => { + state == entity + } + _ => false, + } +} diff --git a/distributed_game/src/test_zone.rs b/distributed_game/src/test_zone.rs new file mode 100644 index 000000000..8c2169029 --- /dev/null +++ b/distributed_game/src/test_zone.rs @@ -0,0 +1,46 @@ +//! The unit tests' zone. + +use crate::{ + Ctx, EntitySchema, EntityState, FieldType, FieldValue, KindDef, PlayerId, WorldView, Zone, +}; + +/// `n` dots (its config) on the x axis whose value changes every tick. +pub(crate) struct Dots { + n: u32, + ticks: u32, +} + +impl Zone for Dots { + type Config = u32; + type Input = u8; + type Timer = (); + type Message = crate::NoMessages; + + fn schema() -> EntitySchema { + EntitySchema::new().kind(KindDef::new(1, "dot").field("v", FieldType::U16)) + } + + fn on_create(_ctx: &mut Ctx<'_, Self>, n: u32) -> Self { + Self { n, ticks: 0 } + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { + payload.first().copied() + } + + fn on_tick(&mut self, _ctx: &mut Ctx<'_, Self>) { + self.ticks += 1; + } + + fn replicate(&self, out: &mut WorldView) { + for i in 0..self.n { + out.push(EntityState::new( + i, + 1, + i as f32, + 0.0, + vec![FieldValue::U(self.ticks + i)], + )); + } + } +} diff --git a/distributed_game/src/timers.rs b/distributed_game/src/timers.rs new file mode 100644 index 000000000..3d02fd581 --- /dev/null +++ b/distributed_game/src/timers.rs @@ -0,0 +1,127 @@ +//! Per-zone timers measured in simulation time. +//! +//! Timers are owned by the zone's host, fire only during ticks (in schedule +//! order, before `on_tick`), and are all cleared when the zone is disposed. +//! Because they run on simulation time they are deterministic and they pause +//! while a zone is Dormant (simulation time does not advance without ticks). + +use std::time::Duration; + +/// Handle for cancelling a timer. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct TimerId(pub u64); + +#[derive(Debug)] +struct Entry { + id: TimerId, + due: Duration, + every: Option, + payload: T, +} + +/// Timer set holding game-defined payloads `T`. +#[derive(Debug)] +pub struct Timers { + next_id: u64, + entries: Vec>, +} + +impl Default for Timers { + fn default() -> Self { + Self { + next_id: 1, + entries: Vec::new(), + } + } +} + +impl Timers { + /// Fire once at `now + after`. + pub fn once(&mut self, now: Duration, after: Duration, payload: T) -> TimerId { + self.insert(now + after, None, payload) + } + + /// Fire every `every` (minimum 1ns), first at `now + every`. + pub fn interval(&mut self, now: Duration, every: Duration, payload: T) -> TimerId { + let every = every.max(Duration::from_nanos(1)); + self.insert(now + every, Some(every), payload) + } + + fn insert(&mut self, due: Duration, every: Option, payload: T) -> TimerId { + let id = TimerId(self.next_id); + self.next_id += 1; + self.entries.push(Entry { + id, + due, + every, + payload, + }); + id + } + + /// Cancel; returns whether the timer existed. + pub fn cancel(&mut self, id: TimerId) -> bool { + let before = self.entries.len(); + self.entries.retain(|entry| entry.id != id); + before != self.entries.len() + } + + /// Number of live timers. + pub fn len(&self) -> usize { + self.entries.len() + } + + /// True when no timers are scheduled. + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// Remove every timer. + pub fn clear(&mut self) { + self.entries.clear(); + } + + /// Collect timers due at `now`, ordered by (due, id). Interval timers are + /// rescheduled; an interval fires at most once per call. + pub fn due(&mut self, now: Duration) -> Vec<(TimerId, T)> { + let mut fired: Vec<(Duration, TimerId, T)> = Vec::new(); + let mut index = 0; + while index < self.entries.len() { + if self.entries[index].due <= now { + let entry = &mut self.entries[index]; + fired.push((entry.due, entry.id, entry.payload.clone())); + if let Some(every) = entry.every { + while entry.due <= now { + entry.due += every; + } + index += 1; + } else { + self.entries.swap_remove(index); + } + } else { + index += 1; + } + } + fired.sort_by_key(|(due, id, _)| (*due, *id)); + fired.into_iter().map(|(_, id, p)| (id, p)).collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn once_and_interval_fire_in_order() { + let mut timers = Timers::default(); + let ms = Duration::from_millis; + let a = timers.once(ms(0), ms(30), "a"); + let b = timers.interval(ms(0), ms(10), "b"); + assert!(timers.due(ms(5)).is_empty()); + assert_eq!(timers.due(ms(10)), vec![(b, "b")]); + assert_eq!(timers.due(ms(30)), vec![(b, "b"), (a, "a")]); + assert!(timers.cancel(b)); + assert!(timers.due(ms(100)).is_empty()); + assert!(timers.is_empty()); + } +} diff --git a/distributed_game/src/timestep.rs b/distributed_game/src/timestep.rs new file mode 100644 index 000000000..91ef699a4 --- /dev/null +++ b/distributed_game/src/timestep.rs @@ -0,0 +1,115 @@ +//! Fixed timestep with an accumulator and a catch-up cap. +//! +//! Real elapsed time is added to an accumulator; whole steps are consumed +//! from it. When a host falls behind (GC pause, overloaded core, debugger) at +//! most `max_catch_up` steps run per advance and the remaining backlog is +//! **dropped** rather than carried forward, so a slow tick can never cause an +//! ever-growing backlog (the "spiral of death"). Arithmetic is in integer +//! nanoseconds so step counts are exact and reproducible. + +use std::time::Duration; + +/// Result of feeding elapsed time into a [`FixedTimestep`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct Steps { + /// Whole steps to simulate now. + pub steps: u32, + /// Backlog discarded because the catch-up cap was hit. + pub dropped: Duration, +} + +/// Accumulator for one fixed step length. +#[derive(Debug, Clone)] +pub struct FixedTimestep { + step_nanos: u64, + accumulator: u64, + max_catch_up: u32, +} + +impl FixedTimestep { + /// Steps of `step` length, running at most `max_catch_up` (>= 1) per call. + pub fn new(step: Duration, max_catch_up: u32) -> Self { + Self { + step_nanos: (step.as_nanos() as u64).max(1), + accumulator: 0, + max_catch_up: max_catch_up.max(1), + } + } + + /// Step for a rate in Hz. + pub fn from_rate(hz: u32, max_catch_up: u32) -> Self { + Self::new(rate_to_step(hz), max_catch_up) + } + + /// Length of one step. + pub fn step(&self) -> Duration { + Duration::from_nanos(self.step_nanos) + } + + /// Time accumulated toward the next step. + pub fn pending(&self) -> Duration { + Duration::from_nanos(self.accumulator) + } + + /// Time until the next whole step is available. + pub fn until_next(&self) -> Duration { + Duration::from_nanos(self.step_nanos.saturating_sub(self.accumulator)) + } + + /// Fraction of a step accumulated (render interpolation alpha). + pub fn alpha(&self) -> f32 { + self.accumulator as f32 / self.step_nanos as f32 + } + + /// Discard accumulated time (used on activity-tier changes). + pub fn reset(&mut self) { + self.accumulator = 0; + } + + /// Feed real elapsed time and take whole steps. + pub fn advance(&mut self, elapsed: Duration) -> Steps { + self.accumulator = self.accumulator.saturating_add(elapsed.as_nanos() as u64); + let available = self.accumulator / self.step_nanos; + let steps = available.min(u64::from(self.max_catch_up)); + self.accumulator -= steps * self.step_nanos; + let mut dropped = 0; + if available > steps { + // Keep only the sub-step remainder; drop the rest of the backlog. + dropped = self.accumulator - self.accumulator % self.step_nanos; + self.accumulator %= self.step_nanos; + } + Steps { + steps: steps as u32, + dropped: Duration::from_nanos(dropped), + } + } +} + +/// `1 / hz` seconds (zero Hz is treated as 1 Hz). +pub fn rate_to_step(hz: u32) -> Duration { + Duration::from_nanos(1_000_000_000 / u64::from(hz.max(1))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn accumulates_partial_steps() { + let mut ts = FixedTimestep::new(Duration::from_millis(10), 4); + assert_eq!(ts.advance(Duration::from_millis(7)).steps, 0); + assert_eq!(ts.advance(Duration::from_millis(7)).steps, 1); + assert_eq!(ts.pending(), Duration::from_millis(4)); + } + + #[test] + fn catch_up_is_capped_and_backlog_dropped() { + let mut ts = FixedTimestep::new(Duration::from_millis(10), 3); + let s = ts.advance(Duration::from_millis(1_005)); + assert_eq!(s.steps, 3); + assert_eq!(s.dropped, Duration::from_millis(970)); + assert_eq!(ts.pending(), Duration::from_millis(5)); + // Next normal frame is unaffected by the old backlog. + assert_eq!(ts.advance(Duration::from_millis(10)).steps, 1); + } +} diff --git a/distributed_game/src/work.rs b/distributed_game/src/work.rs new file mode 100644 index 000000000..3ae28f0a1 --- /dev/null +++ b/distributed_game/src/work.rs @@ -0,0 +1,163 @@ +//! Work counters: how much work a zone did, as plain integers. +//! +//! Timings on a loaded machine move with everything else running on it; +//! counts do not. Two runs of the same build with a switch flipped (fact +//! batches, update rates, pushed world views) compare exactly on these: +//! records encoded per patch, updates sent or held back, cell requests per +//! fact, world reads per room-second. +//! +//! The celld zone host keeps one [`WorkCounters`] per object (they survive +//! the zone's sleeps, not an eviction) and reports it as `work` in `GET +//! /zones/{zone}/info`; a watched cell reports its side +//! ([`WatcherStats`](crate::world::watch::WatcherStats)) at `GET +//! /{kind}/{shard}/__watchers`. `mobpit-load` reads both around each step. + +use serde::{Deserialize, Serialize}; + +use crate::host::AdvanceReport; + +/// Monotonic work counts of one zone (camelCase JSON). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct WorkCounters { + /// Patches (Delta rounds). + pub patches: u64, + /// Entity records encoded, shared by every client + /// ([`EncodedWorld::encodes`](crate::replication::EncodedWorld::encodes)). + pub encodes: u64, + /// Delta frames built (one per client per patch). + pub frames: u64, + /// Delta bytes, all clients. + pub delta_bytes: u64, + /// Entity creates sent. + pub creates: u64, + /// Entity updates sent. + pub updates: u64, + /// Entity updates held back by the update rates (a held entity counts + /// once per client per patch). + pub held: u64, + /// Creates and updates deferred by the byte budget. + pub deferred: u64, + /// Fact commands sent to cells (each entry of a batch counts). + pub fact_commands: u64, + /// Requests that carried them (a `__batch` counts once). + pub fact_requests: u64, + /// Of those, `__batch` requests. + pub fact_batches: u64, + /// Outbox delete calls for settled facts (one per batch when batched). + pub outbox_deletes: u64, + /// Reads of watched world cells (wake, reconcile, or polls when the + /// zone takes no pushes). + pub world_reads: u64, + /// World view pushes received. + pub world_pushes: u64, +} + +impl WorkCounters { + /// Add one [`ZoneHost::advance`](crate::ZoneHost::advance). + pub fn record_advance(&mut self, report: &AdvanceReport) { + self.patches += u64::from(report.patched); + self.encodes += report.encodes as u64; + for frame in &report.frames { + self.frames += 1; + self.delta_bytes += frame.bytes as u64; + self.creates += frame.stats.creates as u64; + self.updates += frame.stats.updates as u64; + self.held += frame.stats.held as u64; + self.deferred += frame.stats.deferred as u64; + } + } + + /// The work done since `earlier` (`None` when a count went backwards: + /// a different object instance). + pub fn since(&self, earlier: &Self) -> Option { + let d = |now: u64, then: u64| now.checked_sub(then); + Some(Self { + patches: d(self.patches, earlier.patches)?, + encodes: d(self.encodes, earlier.encodes)?, + frames: d(self.frames, earlier.frames)?, + delta_bytes: d(self.delta_bytes, earlier.delta_bytes)?, + creates: d(self.creates, earlier.creates)?, + updates: d(self.updates, earlier.updates)?, + held: d(self.held, earlier.held)?, + deferred: d(self.deferred, earlier.deferred)?, + fact_commands: d(self.fact_commands, earlier.fact_commands)?, + fact_requests: d(self.fact_requests, earlier.fact_requests)?, + fact_batches: d(self.fact_batches, earlier.fact_batches)?, + outbox_deletes: d(self.outbox_deletes, earlier.outbox_deletes)?, + world_reads: d(self.world_reads, earlier.world_reads)?, + world_pushes: d(self.world_pushes, earlier.world_pushes)?, + }) + } + + /// Element-wise sum (several zones). + pub fn add(&mut self, other: &Self) { + self.patches += other.patches; + self.encodes += other.encodes; + self.frames += other.frames; + self.delta_bytes += other.delta_bytes; + self.creates += other.creates; + self.updates += other.updates; + self.held += other.held; + self.deferred += other.deferred; + self.fact_commands += other.fact_commands; + self.fact_requests += other.fact_requests; + self.fact_batches += other.fact_batches; + self.outbox_deletes += other.outbox_deletes; + self.world_reads += other.world_reads; + self.world_pushes += other.world_pushes; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_zone::Dots; + use crate::{ManualClock, Role, TicketClaims, ZoneHost}; + use std::sync::Arc; + use std::time::Duration; + + fn claims(principal: &str) -> TicketClaims { + TicketClaims { + principal: principal.into(), + zone: "z".into(), + expires_at: u64::MAX, + nonce: principal.into(), + role: Role::Player, + name: None, + extensions: Default::default(), + wake: false, + } + } + + #[test] + fn counts_shared_encodes_and_per_client_records() { + let clock = ManualClock::new(); + // Eight dots that all move every tick. + let mut host: ZoneHost = + ZoneHost::new("z", Default::default(), Arc::new(clock.clone()), 8); + for p in ["a", "b", "c"] { + host.join(&claims(p), 0, "").unwrap(); + } + let mut work = WorkCounters::default(); + for _ in 0..10 { + clock.advance(Duration::from_millis(50)); + work.record_advance(&host.advance()); + } + assert!(work.patches >= 5, "{work:?}"); + assert_eq!(work.frames, work.patches * 3); + assert_eq!(work.creates, 8 * 3, "each client gets each dot once"); + // Every dot changes every patch and every client is current: one + // payload and one shared update per dot and patch (the first patch + // has no updates), however many clients. + assert_eq!(work.encodes, 8 + (work.patches - 1) * 16, "{work:?}"); + assert_eq!(work.updates + work.held, (work.patches - 1) * 8 * 3); + assert!(work.delta_bytes > 0); + let later = WorkCounters { + world_reads: 2, + ..work + }; + assert_eq!(later.since(&work).map(|d| d.world_reads), Some(2)); + assert_eq!(work.since(&later), None, "went backwards"); + } +} diff --git a/distributed_game/src/world/allocation.rs b/distributed_game/src/world/allocation.rs new file mode 100644 index 000000000..156b185aa --- /dev/null +++ b/distributed_game/src/world/allocation.rs @@ -0,0 +1,204 @@ +//! Zone allocation: what a zone is for, decided before it starts. +//! +//! A service that allocates a zone (game-services `Match`, a party +//! finder, an instance spawner) writes a [`ZoneAllocation`] record for the +//! zone id: roster, mode, config version, seed. When the zone activates, +//! the server loads the record and hands it to the async zone factory in a +//! [`ZoneActivation`] together with the activation's fencing token, so the +//! zone's `on_create` sees it before the first player joins. Joins that +//! arrive while the zone is being created wait; the tick never awaits. + +use std::collections::HashMap; +use std::fmt; +use std::sync::Mutex; + +use serde::de::DeserializeOwned; +use serde::Serialize; +use serde_json::Value; + +use crate::facts::BoxFuture; + +/// The record an allocating service writes for a zone. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ZoneAllocation { + /// Who allocated it (service name, e.g. `"game-services.match"`). + pub allocated_by: String, + /// Monotonic revision per zone id (a re-allocation bumps it). + pub revision: u64, + /// Game-defined payload (roster, mode, config version…). + pub payload: Value, +} + +impl ZoneAllocation { + /// Record with a typed payload. + pub fn new( + allocated_by: impl Into, + revision: u64, + payload: &impl Serialize, + ) -> Result { + Ok(Self { + allocated_by: allocated_by.into(), + revision, + payload: serde_json::to_value(payload)?, + }) + } + + /// Decode the payload. + pub fn payload_as(&self) -> Result { + serde_json::from_value(self.payload.clone()) + } +} + +/// Why an allocation store failed (the activation is refused with +/// `ZONE_UNAVAILABLE`, never admitted half-configured). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AllocationError(pub String); + +impl fmt::Display for AllocationError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "zone allocation store: {}", self.0) + } +} + +impl std::error::Error for AllocationError {} + +/// Where allocation records live. Async: typically a service's database or +/// read model, read once per activation. +pub trait ZoneAllocationStore: Send + Sync + 'static { + /// The record for `zone_id`, if any. + fn load<'a>( + &'a self, + zone_id: &'a str, + ) -> BoxFuture<'a, Result, AllocationError>>; + + /// Write a record. Refused when a record with a higher revision exists. + fn put<'a>( + &'a self, + zone_id: &'a str, + allocation: ZoneAllocation, + ) -> BoxFuture<'a, Result<(), AllocationError>>; + + /// Drop the record (the zone was released). + fn remove<'a>(&'a self, zone_id: &'a str) -> BoxFuture<'a, Result<(), AllocationError>>; +} + +/// In-memory allocation store (tests, single process). +#[derive(Debug, Default)] +pub struct MemoryZoneAllocationStore { + records: Mutex>, +} + +impl MemoryZoneAllocationStore { + /// Empty. + pub fn new() -> Self { + Self::default() + } +} + +impl ZoneAllocationStore for MemoryZoneAllocationStore { + fn load<'a>( + &'a self, + zone_id: &'a str, + ) -> BoxFuture<'a, Result, AllocationError>> { + let found = self.records.lock().expect("records").get(zone_id).cloned(); + Box::pin(async move { Ok(found) }) + } + + fn put<'a>( + &'a self, + zone_id: &'a str, + allocation: ZoneAllocation, + ) -> BoxFuture<'a, Result<(), AllocationError>> { + let mut records = self.records.lock().expect("records"); + let result = match records.get(zone_id) { + Some(current) if current.revision > allocation.revision => { + Err(AllocationError(format!( + "revision {} is older than the stored {}", + allocation.revision, current.revision + ))) + } + _ => { + records.insert(zone_id.to_string(), allocation); + Ok(()) + } + }; + Box::pin(async move { result }) + } + + fn remove<'a>(&'a self, zone_id: &'a str) -> BoxFuture<'a, Result<(), AllocationError>> { + self.records.lock().expect("records").remove(zone_id); + Box::pin(async { Ok(()) }) + } +} + +/// What the zone factory is told about the activation it configures. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ZoneActivation { + /// Zone id. + pub zone_id: String, + /// Activation epoch: the ownership fencing token, also the host's + /// `boot_epoch` and every fact stamp's `activation`. + pub activation: u64, + /// The allocation record, when an allocation store is configured and + /// holds one for this zone. + pub allocation: Option, +} + +/// The factory refused to create the zone because something it needs +/// failed (storage down, invalid allocation). Clients waiting to join get +/// `Error(ZONE_UNAVAILABLE)` with the message. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ZoneCreateError(pub String); + +impl ZoneCreateError { + /// Error with a message for the joining clients. + pub fn new(message: impl Into) -> Self { + Self(message.into()) + } +} + +impl fmt::Display for ZoneCreateError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for ZoneCreateError {} + +impl From for ZoneCreateError { + fn from(error: AllocationError) -> Self { + Self(error.to_string()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn block(f: impl std::future::Future) -> T { + let waker = std::task::Waker::noop(); + let mut cx = std::task::Context::from_waker(waker); + let mut f = std::pin::pin!(f); + loop { + if let std::task::Poll::Ready(v) = f.as_mut().poll(&mut cx) { + return v; + } + } + } + + #[test] + fn memory_store_keeps_the_newest_revision() { + let store = MemoryZoneAllocationStore::new(); + let record = |revision| { + ZoneAllocation::new("match", revision, &serde_json::json!({"mode": "duel"})).unwrap() + }; + block(store.put("m1", record(2))).unwrap(); + assert!(block(store.put("m1", record(1))).is_err()); + let loaded = block(store.load("m1")).unwrap().unwrap(); + assert_eq!(loaded.revision, 2); + let payload: serde_json::Value = loaded.payload_as().unwrap(); + assert_eq!(payload["mode"], "duel"); + block(store.remove("m1")).unwrap(); + assert_eq!(block(store.load("m1")).unwrap(), None); + } +} diff --git a/distributed_game/src/world/barrier.rs b/distributed_game/src/world/barrier.rs new file mode 100644 index 000000000..2481d9231 --- /dev/null +++ b/distributed_game/src/world/barrier.rs @@ -0,0 +1,52 @@ +//! Content-version policy shared by [`ZoneHost`](crate::ZoneHost) and the +//! world barrier (`net::WorldCoordinator`). +//! +//! A world runs one content version at a time. A rollout is a two-phase +//! barrier: every zone freezes (and acknowledges), the new version is +//! applied, every zone resumes on it. What happens to clients still running +//! the *old* client build is the [`StalePolicy`] plus the [`BarrierMode`]. + +/// What a host does with a client whose Hello content version differs from +/// the zone's current content version. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum StalePolicy { + /// Reject every admission with a different version + /// (`Error(VERSION_MISMATCH)`). Matches the pre-barrier behavior. + #[default] + Strict, + /// "Keep playing until a safe room": a stale client already in the world + /// keeps its current zone (reconnects are allowed) and may only be + /// handed off into a gate zone ([`Zone::is_gate`](crate::Zone::is_gate)) + /// unless `roam` is true. On entering a gate it is admitted, then told + /// `Kick(RELOAD)` and kept in the reconnect grace window, so the reloaded + /// client reconnects with its token and the new version. A fresh join + /// with a stale version is rejected (`VERSION_MISMATCH`, "reload"). + SafeRoom { + /// Also allow stale clients to be handed off into non-gate zones. + roam: bool, + }, +} + +/// How a committed rollout treats connected clients. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum BarrierMode { + /// Zones resume on the new version; stale clients keep playing under the + /// [`StalePolicy`] until they reach a gate (or reconnect). + #[default] + Rolling, + /// Zones resume on the new version and every stale client is sent + /// `Kick(RELOAD)` immediately (kept in the reconnect grace window). + Hard, +} + +/// Freeze progress of one zone. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FreezeState { + /// Simulating. + Running, + /// A freeze was requested; the zone is not ready yet + /// ([`Zone::freeze_ready`](crate::Zone::freeze_ready)) and still ticks. + Freezing, + /// Frozen: no ticks, inputs dropped and counted. + Frozen, +} diff --git a/distributed_game/src/world/content_rollout.rs b/distributed_game/src/world/content_rollout.rs new file mode 100644 index 000000000..84325fa70 --- /dev/null +++ b/distributed_game/src/world/content_rollout.rs @@ -0,0 +1,399 @@ +//! A world's live content rollout as a cell (feature `cell`): the barrier +//! the native `WorldCoordinator` runs across hosts, for zones hosted as +//! celld objects, where no process sees every zone. +//! +//! One `ContentRollout` cell per world (kind [`CONTENT_ROLLOUT_KIND`], +//! usually shard `world`) holds the live content version and the phase of a +//! rollout. An admin starts one ([`START`]); the cell then drives itself on +//! its own schedule (`ctx.schedule`): +//! +//! | phase | when | what every zone does (it reads the cell off the tick) | +//! |---|---|---| +//! | [`PHASE_FREEZING`] | [`START`] | freeze (Freeze notice with the change notes) | +//! | [`PHASE_APPLIED`] | `freeze_ms` later ([`APPLY`]) | switch to the new version, resume (Resume notice) | +//! | [`PHASE_RUNNING`] | `settle_ms` later ([`SETTLE`]) | — (zones that slept through it wake on the new version) | +//! +//! Zones apply the version through `ZoneHost::set_content_version` (facts +//! and stamps carry it from then on) and the host's +//! [`StalePolicy`](crate::world::StalePolicy) decides what happens to +//! clients still on the old version (e.g. held until a safe room; a hard +//! rollout reloads them at once). Every phase change is an outward domain +//! event ([`ContentState`]). +//! +//! Unlike the native barrier there is no acknowledgement round: a zone +//! that is not ready to freeze ([`Zone::freeze_ready`](crate::Zone::freeze_ready)) +//! keeps ticking until it is or until the version is applied. + +use std::time::{Duration, SystemTime}; + +use distributed::cell_host::AggregateCell; +use distributed::command::{typed_command, PreparedCommand, Succeeded}; +use distributed::microsvc::schedule::schedule_guard; +use distributed::microsvc::{ + CausalCommandContext, CausalRouteDependencies, HandlerError, PortableCommand, Routes, +}; +use distributed::schedule::{Capability, Schedule}; +use distributed::{sourced, Entity}; +use serde::{Deserialize, Serialize}; + +/// Cell kind (`content-rollout/{world}`). +pub const CONTENT_ROLLOUT_KIND: &str = "content-rollout"; +/// Role an admin's session must carry to start a rollout. +pub const CONTENT_ADMIN_ROLE: &str = "content-admin"; +/// Start a rollout (admin). +pub const START: &str = "content_rollout.start"; +/// Schedule only: apply the new version. +pub const APPLY: &str = "content_rollout.apply"; +/// Schedule only: the rollout is over. +pub const SETTLE: &str = "content_rollout.settle"; +/// No rollout in progress. +pub const PHASE_RUNNING: &str = "running"; +/// Zones freeze. +pub const PHASE_FREEZING: &str = "freezing"; +/// The new version is live; zones resume on it. +pub const PHASE_APPLIED: &str = "applied"; +const ALARM: &str = "rollout"; + +/// One world's content. +#[derive(Clone, Debug, Default, Serialize, Deserialize, distributed::Snapshot)] +pub struct ContentRollout { + entity: Entity, + /// Live content version ("" = the zones' built-in default). + pub version: String, + /// The version being rolled out (during a rollout). + pub target: String, + /// [`PHASE_RUNNING`], [`PHASE_FREEZING`] or [`PHASE_APPLIED`]. + pub phase: String, + /// Change notes of the last rollout. + pub notes: String, + /// When the phase began (cell clock, ms). + pub since_ms: u64, + /// Rollouts so far. + pub rollouts: u32, + /// Hard rollout: stale clients reload at once instead of at a gate. + pub hard: bool, +} + +/// What zones and read models see of the rollout. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, distributed::DomainState)] +#[domain_state(version = 1)] +pub struct ContentState { + /// The world (the cell's stream id). + pub world: String, + /// Live content version. + pub version: String, + /// The version being rolled out. + pub target: String, + /// The phase. + pub phase: String, + /// Change notes. + pub notes: String, + /// When the phase began (ms). + pub since_ms: u64, + /// Hard rollout: every stale client reloads on apply + /// (`ZoneHost::reload_stale_players`); else they keep playing under the + /// zones' `StalePolicy`. + pub hard: bool, +} + +impl From<&ContentRollout> for ContentState { + fn from(c: &ContentRollout) -> Self { + Self { + world: c.entity.id().to_string(), + version: c.version.clone(), + target: c.target.clone(), + phase: if c.phase.is_empty() { + PHASE_RUNNING.to_string() + } else { + c.phase.clone() + }, + notes: c.notes.clone(), + since_ms: c.since_ms, + hard: c.hard, + } + } +} + +#[sourced( + entity, + aggregate_type = "ContentRollout", + events = "ContentRolloutEvent", + domain_state = ContentState +)] +impl ContentRollout { + #[event("content.freezing", version = 1, domain)] + fn freezing(&mut self, world: String, target: String, notes: String, hard: bool, at_ms: u64) { + if self.entity.id().is_empty() { + self.entity.set_id(world); + } + self.hard = hard; + self.target = target; + self.notes = notes; + self.phase = PHASE_FREEZING.to_string(); + self.since_ms = at_ms; + } + + #[event("content.applied", version = 1, domain)] + fn applied(&mut self, at_ms: u64) { + self.version = std::mem::take(&mut self.target); + self.phase = PHASE_APPLIED.to_string(); + self.since_ms = at_ms; + self.rollouts += 1; + } + + #[event("content.settled", version = 1, domain)] + fn settled(&mut self, at_ms: u64) { + self.phase = PHASE_RUNNING.to_string(); + self.since_ms = at_ms; + } +} + +impl ContentRollout { + /// The outward state. + pub fn state(&self) -> ContentState { + ContentState::from(self) + } +} + +/// [`START`] input. +#[derive(Debug, Clone, Serialize, Deserialize, distributed::CommandInput)] +pub struct StartInput { + /// The world (the cell's shard). + pub world: String, + /// Version to roll out. + pub version: String, + /// Change notes shown to players. + pub notes: String, + /// How long zones stay frozen before the version is applied (ms). + pub freeze_ms: u64, + /// Reload every stale client at once (else: at a gate). + pub hard: bool, +} + +/// [`APPLY`] / [`SETTLE`] input. +#[derive(Debug, Clone, Serialize, Deserialize, distributed::CommandInput)] +pub struct PhaseInput { + /// The world. + pub world: String, +} + +/// A rollout command's answer. +#[derive(Debug, Clone, Serialize, Deserialize, distributed::CommandOutput)] +pub struct RolloutReceipt { + /// The phase after the command. + pub phase: String, + /// Live version after the command. + pub version: String, +} + +fn rejected(message: impl std::fmt::Display) -> HandlerError { + HandlerError::Rejected(message.to_string()) +} + +fn now_ms(ctx: &CausalCommandContext<'_, ContentRollout>) -> Result { + ctx.now()? + .duration_since(SystemTime::UNIX_EPOCH) + .map(|now| now.as_millis() as u64) + .map_err(|_| rejected("host clock is before the Unix epoch")) +} + +fn at(world: &str, at_ms: u64, command: &str) -> Result { + Schedule::at( + ALARM, + SystemTime::UNIX_EPOCH + Duration::from_millis(at_ms), + command, + &PhaseInput { + world: world.to_string(), + }, + ) + .map_err(rejected) +} + +/// How long zones keep resuming notices before the rollout is over (ms). +const SETTLE_MS: u64 = 3_000; + +fn is_admin(ctx: &CausalCommandContext<'_, ContentRollout>) -> bool { + ctx.session().has_role(CONTENT_ADMIN_ROLE) +} + +async fn handle_start( + ctx: &CausalCommandContext<'_, ContentRollout>, + input: StartInput, +) -> Result>, HandlerError> { + let version = input.version.trim().to_string(); + if version.is_empty() || version.len() > 64 { + return Err(rejected("version must be 1..=64 characters")); + } + let freeze_ms = input.freeze_ms.clamp(500, 60_000); + let now = now_ms(ctx)?; + let repo = ctx.repo(); + let mut rollout = match repo.get(&input.world).await? { + Some(r) => r, + None => repo.create(), + }; + if !rollout.phase.is_empty() && rollout.phase != PHASE_RUNNING { + return Err(rejected("a rollout is in progress")); + } + if rollout.version == version { + return Err(rejected("that version is live")); + } + let notes: String = input.notes.chars().take(500).collect(); + rollout + .freezing(input.world.clone(), version, notes, input.hard, now) + .map_err(rejected)?; + ctx.schedule(at(&input.world, now + freeze_ms, APPLY)?)?; + let receipt = RolloutReceipt { + phase: rollout.phase.clone(), + version: rollout.version.clone(), + }; + repo.publish_events().commit(rollout)?.succeeded(receipt) +} + +async fn handle_apply( + ctx: &CausalCommandContext<'_, ContentRollout>, + input: PhaseInput, +) -> Result>, HandlerError> { + let now = now_ms(ctx)?; + let repo = ctx.repo(); + let Some(mut rollout) = repo.get(&input.world).await? else { + return Err(rejected("no rollout")); + }; + if rollout.phase != PHASE_FREEZING { + let receipt = RolloutReceipt { + phase: rollout.phase.clone(), + version: rollout.version.clone(), + }; + return repo.commit(rollout)?.succeeded(receipt); + } + rollout.applied(now).map_err(rejected)?; + ctx.schedule(at(&input.world, now + SETTLE_MS, SETTLE)?)?; + let receipt = RolloutReceipt { + phase: rollout.phase.clone(), + version: rollout.version.clone(), + }; + repo.publish_events().commit(rollout)?.succeeded(receipt) +} + +async fn handle_settle( + ctx: &CausalCommandContext<'_, ContentRollout>, + input: PhaseInput, +) -> Result>, HandlerError> { + let now = now_ms(ctx)?; + let repo = ctx.repo(); + let Some(mut rollout) = repo.get(&input.world).await? else { + return Err(rejected("no rollout")); + }; + rollout.settled(now).map_err(rejected)?; + let receipt = RolloutReceipt { + phase: rollout.phase.clone(), + version: rollout.version.clone(), + }; + repo.publish_events().commit(rollout)?.succeeded(receipt) +} + +macro_rules! rollout_command { + ($name:ident, $command:expr, $input:ty, $guard:expr, $handler:expr) => { + struct $name; + impl PortableCommand for $name + where + D: CausalRouteDependencies + Send + Sync + 'static, + { + fn install(self, routes: Routes) -> Routes { + routes + .typed_command(typed_command::<$input, Succeeded>($command)) + .requires(Capability::Scheduling) + .requires(Capability::Clock) + .guarded($guard, $handler) + } + } + }; +} + +rollout_command!(Start, START, StartInput, is_admin, handle_start); +rollout_command!( + Apply, + APPLY, + PhaseInput, + schedule_guard::, + handle_apply +); +rollout_command!( + Settle, + SETTLE, + PhaseInput, + schedule_guard::, + handle_settle +); + +/// Mount every rollout command on a `ContentRollout` cell. +pub fn mount_content_rollout(cell: AggregateCell) -> AggregateCell { + cell.mount(Start).mount(Apply).mount(Settle) +} + +/// What a zone should do for a rollout state, given its own content +/// version and whether it is frozen. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ZoneStep { + /// Nothing to do. + Stay, + /// Freeze with the notes (the rollout began). + Freeze, + /// Switch to `version` (and resume if frozen). + Apply(String), +} + +/// The zone side of the barrier (pure; the celld zone host runs it). +pub fn zone_step(state: &ContentState, zone_version: &str, frozen: bool) -> ZoneStep { + match state.phase.as_str() { + PHASE_FREEZING if !frozen => ZoneStep::Freeze, + PHASE_FREEZING => ZoneStep::Stay, + _ if state.version != zone_version || frozen => ZoneStep::Apply(state.version.clone()), + _ => ZoneStep::Stay, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn state(phase: &str, version: &str) -> ContentState { + ContentState { + world: "world".into(), + version: version.into(), + target: String::new(), + phase: phase.into(), + notes: String::new(), + since_ms: 0, + hard: false, + } + } + + #[test] + fn zones_follow_the_phases() { + assert_eq!( + zone_step(&state(PHASE_RUNNING, ""), "", false), + ZoneStep::Stay + ); + assert_eq!( + zone_step(&state(PHASE_FREEZING, ""), "", false), + ZoneStep::Freeze + ); + assert_eq!( + zone_step(&state(PHASE_FREEZING, ""), "", true), + ZoneStep::Stay + ); + assert_eq!( + zone_step(&state(PHASE_APPLIED, "v2"), "", true), + ZoneStep::Apply("v2".into()) + ); + // A zone that slept through the rollout wakes on the new version. + assert_eq!( + zone_step(&state(PHASE_RUNNING, "v2"), "", false), + ZoneStep::Apply("v2".into()) + ); + assert_eq!( + zone_step(&state(PHASE_RUNNING, "v2"), "v2", false), + ZoneStep::Stay + ); + } +} diff --git a/distributed_game/src/world/directory.rs b/distributed_game/src/world/directory.rs new file mode 100644 index 000000000..2b0c0f47a --- /dev/null +++ b/distributed_game/src/world/directory.rs @@ -0,0 +1,283 @@ +//! Zone placement: which host owns a zone. +//! +//! A [`ZoneDirectory`] answers `locate(zone_id)` with the owning +//! [`HostAddr`]. It is advisory routing: actual ownership is enforced by a +//! fenced claim ([`ZoneOwnership`](super::ZoneOwnership)) when the zone is +//! activated, so a stale directory can at worst send a client to the wrong +//! host, which redirects it or refuses — it can never make two hosts run the +//! same zone. + +use std::collections::{BTreeMap, HashMap}; +use std::sync::RwLock; + +use crate::rng::Fnv64; + +/// A host in the world. +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct HostAddr { + /// Stable host id (also the ownership holder prefix). + pub id: String, + /// WebSocket base URL clients are redirected to, e.g. + /// `ws://10.0.0.2:2567` or, behind a proxy, `wss://game.example/h/a` + /// (clients connect to `{ws_url}/zones/{zone_id}`). Peers never use it. + pub ws_url: String, + /// Admin HTTP base URL, e.g. `http://10.0.0.2:2567` (peer calls). + pub admin_url: String, +} + +impl HostAddr { + /// Host listening on `addr` (`host:port`) for both WebSocket and admin. + pub fn new(id: impl Into, addr: impl AsRef) -> Self { + let addr = addr.as_ref(); + Self { + id: id.into(), + ws_url: format!("ws://{addr}"), + admin_url: format!("http://{addr}"), + } + } + + /// Advertise `ws_url` (e.g. the proxied public URL) instead of the raw + /// `ws://{addr}`; admin/peer calls keep using `admin_url`. + pub fn with_ws_url(mut self, ws_url: impl Into) -> Self { + self.ws_url = ws_url.into().trim_end_matches('/').to_string(); + self + } + + /// Client URL of `zone_id` on this host. + pub fn zone_url(&self, zone_id: &str) -> String { + format!("{}/zones/{zone_id}", self.ws_url) + } +} + +/// Zone → owning host lookup. +pub trait ZoneDirectory: Send + Sync + 'static { + /// Host that should own `zone_id` (None = unknown / not served). + fn locate(&self, zone_id: &str) -> Option; + + /// Host by id. + fn host(&self, host_id: &str) -> Option; + + /// Every known host. + fn hosts(&self) -> Vec; +} + +/// Explicit zone → host assignments with an optional fallback host. +#[derive(Debug, Default)] +pub struct StaticDirectory { + inner: RwLock, +} + +#[derive(Debug, Default)] +struct StaticInner { + hosts: BTreeMap, + zones: HashMap, + fallback: Option, +} + +impl StaticDirectory { + /// Empty directory. + pub fn new() -> Self { + Self::default() + } + + /// Register a host. + pub fn add_host(&self, host: HostAddr) -> &Self { + let mut inner = self.inner.write().expect("directory"); + inner.hosts.insert(host.id.clone(), host); + self + } + + /// Assign `zone_id` to `host_id` (also used to move a zone). + pub fn assign(&self, zone_id: impl Into, host_id: impl Into) -> &Self { + let mut inner = self.inner.write().expect("directory"); + inner.zones.insert(zone_id.into(), host_id.into()); + self + } + + /// Host for zones without an explicit assignment. + pub fn fallback(&self, host_id: impl Into) -> &Self { + self.inner.write().expect("directory").fallback = Some(host_id.into()); + self + } +} + +impl ZoneDirectory for StaticDirectory { + fn locate(&self, zone_id: &str) -> Option { + let inner = self.inner.read().expect("directory"); + let id = inner.zones.get(zone_id).or(inner.fallback.as_ref())?; + inner.hosts.get(id).cloned() + } + + fn host(&self, host_id: &str) -> Option { + self.inner + .read() + .expect("directory") + .hosts + .get(host_id) + .cloned() + } + + fn hosts(&self) -> Vec { + self.inner + .read() + .expect("directory") + .hosts + .values() + .cloned() + .collect() + } +} + +/// Consistent-hash ring over hosts with virtual nodes. +/// +/// Each host owns `vnodes` points on a 64-bit ring; a zone belongs to the +/// first point clockwise from its hash. Adding or removing one of N hosts +/// moves only ~1/N of the zones (those whose nearest point changed); every +/// other zone keeps its owner. +#[derive(Debug)] +pub struct HashRing { + vnodes: u32, + inner: RwLock, +} + +#[derive(Debug, Default)] +struct RingInner { + hosts: BTreeMap, + ring: BTreeMap, +} + +fn ring_hash(bytes: &[u8]) -> u64 { + // FNV-1a then a SplitMix64 finalizer for avalanche. + let mut z = Fnv64::new().write(bytes).finish(); + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^ (z >> 31) +} + +impl HashRing { + /// Empty ring with `vnodes` virtual nodes per host (>= 1; 64–256 typical). + pub fn new(vnodes: u32) -> Self { + Self { + vnodes: vnodes.max(1), + inner: RwLock::default(), + } + } + + /// Ring over `hosts`. + pub fn with_hosts(vnodes: u32, hosts: impl IntoIterator) -> Self { + let ring = Self::new(vnodes); + for host in hosts { + ring.add_host(host); + } + ring + } + + /// Add (or replace) a host. + pub fn add_host(&self, host: HostAddr) { + let mut inner = self.inner.write().expect("ring"); + for v in 0..self.vnodes { + let point = ring_hash(format!("{}#{v}", host.id).as_bytes()); + inner.ring.insert(point, host.id.clone()); + } + inner.hosts.insert(host.id.clone(), host); + } + + /// Remove a host; its zones move to their next points. + pub fn remove_host(&self, host_id: &str) { + let mut inner = self.inner.write().expect("ring"); + inner.hosts.remove(host_id); + inner.ring.retain(|_, id| id != host_id); + } + + /// Owning host id of `zone_id`. + pub fn owner_id(&self, zone_id: &str) -> Option { + let inner = self.inner.read().expect("ring"); + let h = ring_hash(zone_id.as_bytes()); + inner + .ring + .range(h..) + .next() + .or_else(|| inner.ring.iter().next()) + .map(|(_, id)| id.clone()) + } +} + +impl ZoneDirectory for HashRing { + fn locate(&self, zone_id: &str) -> Option { + let id = self.owner_id(zone_id)?; + self.host(&id) + } + + fn host(&self, host_id: &str) -> Option { + self.inner.read().expect("ring").hosts.get(host_id).cloned() + } + + fn hosts(&self) -> Vec { + self.inner + .read() + .expect("ring") + .hosts + .values() + .cloned() + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn host(i: usize) -> HostAddr { + HostAddr::new(format!("h{i}"), format!("10.0.0.{i}:2567")) + } + + fn owners(ring: &HashRing, zones: &[String]) -> Vec { + zones.iter().map(|z| ring.owner_id(z).unwrap()).collect() + } + + #[test] + fn ring_is_balanced_and_stable_under_add_and_remove() { + let ring = HashRing::with_hosts(128, (0..4).map(host)); + let zones: Vec = (0..4000).map(|i| format!("zone-{i}")).collect(); + let before = owners(&ring, &zones); + let mut counts: HashMap<&str, usize> = HashMap::new(); + for o in &before { + *counts.entry(o.as_str()).or_default() += 1; + } + for (_, n) in counts { + assert!((600..=1400).contains(&n), "unbalanced: {n}"); + } + + ring.add_host(host(4)); + let after = owners(&ring, &zones); + let moved = before.iter().zip(&after).filter(|(a, b)| a != b).count(); + // Ideal is 1/5 = 800; every moved zone moved to the new host. + assert!(moved > 400 && moved < 1300, "moved {moved}"); + assert!(before.iter().zip(&after).all(|(a, b)| a == b || b == "h4")); + + ring.remove_host("h4"); + assert_eq!(owners(&ring, &zones), before); + + ring.remove_host("h1"); + let without = owners(&ring, &zones); + assert!(before + .iter() + .zip(&without) + .all(|(a, b)| a == b || a == "h1")); + assert!(ring.locate("zone-1").is_some()); + assert_eq!(ring.hosts().len(), 3); + } + + #[test] + fn static_directory_assigns_with_fallback() { + let dir = StaticDirectory::new(); + dir.add_host(host(1)).add_host(host(2)); + dir.assign("realm.west", "h2").fallback("h1"); + assert_eq!(dir.locate("realm.west").unwrap().id, "h2"); + assert_eq!(dir.locate("anything").unwrap().id, "h1"); + assert_eq!( + dir.locate("realm.west").unwrap().zone_url("realm.west"), + "ws://10.0.0.2:2567/zones/realm.west" + ); + } +} diff --git a/distributed_game/src/world/mod.rs b/distributed_game/src/world/mod.rs new file mode 100644 index 000000000..585ae38e8 --- /dev/null +++ b/distributed_game/src/world/mod.rs @@ -0,0 +1,71 @@ +//! World structure: where zones live, how they nest, how their durable state +//! survives hibernation and how ownership is fenced. +//! +//! - [`directory`]: [`ZoneDirectory`] maps a zone id to its owning host +//! ([`StaticDirectory`], consistent-hash [`HashRing`]). +//! - [`ownership`]: [`ZoneOwnership`] fenced claims so two hosts never run +//! the same zone ([`LocalOwnership`]; `FencedLeaseOwnership` over +//! `distributed::lease` with the `lease` feature). +//! - [`state`]: [`ZoneStateStore`] for hibernated zone state +//! ([`MemoryZoneStateStore`] for unit tests; on celld, +//! `celld::CellZoneStateStore` over [`zone_state`] cells). +//! - [`topology`]: [`ZoneTopology`] parent links (province > city > borough +//! > neighborhood) and [`ChildEvent`] tier-up propagation. +//! - [`allocation`]: [`ZoneAllocation`] records written by the service that +//! allocates a zone, read before the zone is created +//! ([`ZoneActivation`], [`ZoneAllocationStore`]). +//! - `zone_activity` (feature `cell`): a celld-hosted zone's own lifecycle +//! reports (active / dormant / hibernated) as a cell. +//! - `zone_status` (feature `cell`): the read model of every zone's lease, +//! hibernation slot and activity, projected from the `zone_lease` / +//! `zone_state` / `zone_activity` cells' outward events (active / dormant +//! / hibernated / cold without opening a cell). +//! - `content_rollout` (feature `cell`): a world's live content rollout +//! (freeze → apply → resume across every celld-hosted zone) as a cell. +//! - [`watch`]: watched world views — a zone keeps pushed read models of +//! the world cells it cares about ([`watch::Watches`]); cells keep +//! in-memory watcher leases ([`watch::Watchers`]) and push each new +//! version; a slow reconcile read repairs lost pushes. +//! - [`barrier`]: content-version policy types shared by the host and the +//! world barrier ([`StalePolicy`], [`BarrierMode`]). + +pub mod allocation; +pub mod barrier; +#[cfg(feature = "cell")] +#[allow(missing_docs)] +pub mod content_rollout; +pub mod directory; +pub mod ownership; +pub mod state; +pub mod topology; +pub mod watch; +#[cfg(feature = "cell")] +#[allow(missing_docs)] +pub mod zone_activity; +#[cfg(feature = "cell")] +// The `sourced` and `Snapshot` derives generate undocumented public items. +#[allow(missing_docs)] +pub mod zone_lease; +#[cfg(feature = "cell")] +#[allow(missing_docs)] +pub mod zone_state; +#[cfg(feature = "cell")] +#[allow(missing_docs)] +pub mod zone_status; + +pub use crate::facts::BoxFuture; +pub use allocation::{ + AllocationError, MemoryZoneAllocationStore, ZoneActivation, ZoneAllocation, + ZoneAllocationStore, ZoneCreateError, +}; +pub use barrier::{BarrierMode, FreezeState, StalePolicy}; +pub use directory::{HashRing, HostAddr, StaticDirectory, ZoneDirectory}; +#[cfg(feature = "lease")] +pub use ownership::FencedLeaseOwnership; +#[doc(hidden)] +pub use ownership::{ownership_conformance, restart_conformance}; +pub use ownership::{LocalOwnership, OwnershipError, ZoneClaim, ZoneOwnership}; +#[doc(hidden)] +pub use state::state_store_conformance; +pub use state::{MemoryZoneStateStore, StateError, StoredZoneState, ZoneStateStore}; +pub use topology::{ChildEvent, DottedTopology, FlatTopology, ZoneTopology}; diff --git a/distributed_game/src/world/mutations/save_zone_activity.mutation.graphql b/distributed_game/src/world/mutations/save_zone_activity.mutation.graphql new file mode 100644 index 000000000..368e212f4 --- /dev/null +++ b/distributed_game/src/world/mutations/save_zone_activity.mutation.graphql @@ -0,0 +1,5 @@ +# Syntax-only read-model mutation → MutationProgram IR (not a public field). +# The row is the zone's post-transition `ZoneActivityStatus`. +mutation SaveZoneActivity { + upsert_zone_activities(object: $input.activity) +} diff --git a/distributed_game/src/world/mutations/save_zone_lease.mutation.graphql b/distributed_game/src/world/mutations/save_zone_lease.mutation.graphql new file mode 100644 index 000000000..a09fb8d2b --- /dev/null +++ b/distributed_game/src/world/mutations/save_zone_lease.mutation.graphql @@ -0,0 +1,5 @@ +# Syntax-only read-model mutation → MutationProgram IR (not a public field). +# The row is the lease's post-transition `ZoneLeaseStatus`. +mutation SaveZoneLease { + upsert_zone_leases(object: $input.lease) +} diff --git a/distributed_game/src/world/mutations/save_zone_snapshot.mutation.graphql b/distributed_game/src/world/mutations/save_zone_snapshot.mutation.graphql new file mode 100644 index 000000000..3683b586d --- /dev/null +++ b/distributed_game/src/world/mutations/save_zone_snapshot.mutation.graphql @@ -0,0 +1,5 @@ +# Syntax-only read-model mutation → MutationProgram IR (not a public field). +# The row is the hibernation slot's post-command `ZoneSnapshotStatus`. +mutation SaveZoneSnapshot { + upsert_zone_snapshots(object: $input.snapshot) +} diff --git a/distributed_game/src/world/ownership.rs b/distributed_game/src/world/ownership.rs new file mode 100644 index 000000000..7c5f32487 --- /dev/null +++ b/distributed_game/src/world/ownership.rs @@ -0,0 +1,425 @@ +//! Fenced zone ownership: at most one host runs a zone. +//! +//! A host activating a zone first acquires a claim on it +//! ([`ZoneOwnership::acquire`]) and keeps renewing it while the zone runs. +//! Every acquisition carries a fencing token strictly greater than any +//! earlier one for that zone, so writes made under an old claim (e.g. a +//! hibernation snapshot from a paused host) are rejected by fenced stores +//! ([`ZoneStateStore::save`](super::ZoneStateStore::save)). A host whose +//! renewal fails ([`OwnershipError::Lost`]) must stop the zone immediately +//! without persisting anything. +//! +//! The `net` server's holders are `"{host_id}#{incarnation}#{activation}"`: +//! a re-activation on the same host (after hibernation) waits for the +//! previous activation to release, and a host restarted inside the TTL (a +//! new incarnation) cannot take its dead incarnation's claim back; it gets +//! a larger token once that claim expired ([`restart_conformance`]). + +use std::collections::HashMap; +use std::sync::Mutex; +use std::time::{Duration, SystemTime}; + +use crate::facts::BoxFuture; + +/// A held claim. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ZoneClaim { + /// Zone id. + pub zone_id: String, + /// Holder (`host#activation`). + pub holder: String, + /// Monotonic fencing token. + pub token: u64, + /// Expiry as seen by the ownership store (`UNIX_EPOCH` = no TTL). + pub expires_at: SystemTime, +} + +/// Ownership failure. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum OwnershipError { + /// Someone else holds a live claim. + Held { + /// Current holder. + holder: String, + }, + /// The claim expired or was superseded: stop the zone. + Lost, + /// Transient backend failure. + Backend(String), +} + +/// Store of fenced zone claims. +pub trait ZoneOwnership: Send + Sync + 'static { + /// Acquire `zone_id` for `holder` for `ttl`. + fn acquire<'a>( + &'a self, + zone_id: &'a str, + holder: &'a str, + ttl: Duration, + ) -> BoxFuture<'a, Result>; + + /// Extend a live claim (keeps its token). + fn renew<'a>( + &'a self, + claim: &'a ZoneClaim, + ttl: Duration, + ) -> BoxFuture<'a, Result>; + + /// Release a claim early. + fn release<'a>(&'a self, claim: &'a ZoneClaim) -> BoxFuture<'a, ()>; +} + +/// Process-local ownership without TTLs (single host / tests). Tokens are +/// monotonic per zone, survive release and **keep increasing across process +/// restarts**: the first token of every zone is the instance's epoch (Unix +/// time in microseconds at creation), so a restarted host's claims outrank +/// snapshots its previous run saved in a durable +/// [`ZoneStateStore`](super::ZoneStateStore). +#[derive(Debug)] +pub struct LocalOwnership { + epoch: u64, + claims: Mutex, u64)>>, +} + +impl Default for LocalOwnership { + fn default() -> Self { + Self::new() + } +} + +impl LocalOwnership { + /// Empty, epoch = now (Unix microseconds). + pub fn new() -> Self { + let micros = SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .map_or(1, |d| d.as_micros() as u64); + Self::with_epoch(micros) + } + + /// Empty with an explicit epoch (first token of every zone; must exceed + /// every token a previous run used with the same state store). + pub fn with_epoch(epoch: u64) -> Self { + Self { + epoch: epoch.max(1), + claims: Mutex::new(HashMap::new()), + } + } + + /// First token handed out for each zone. + pub fn epoch(&self) -> u64 { + self.epoch + } +} + +impl ZoneOwnership for LocalOwnership { + fn acquire<'a>( + &'a self, + zone_id: &'a str, + holder: &'a str, + _ttl: Duration, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + let mut claims = self.claims.lock().expect("claims"); + let entry = claims.entry(zone_id.to_string()).or_insert((None, 0)); + match &entry.0 { + Some(current) if current != holder => Err(OwnershipError::Held { + holder: current.clone(), + }), + Some(_) => Ok(entry.1), + None => { + entry.0 = Some(holder.to_string()); + entry.1 = (entry.1 + 1).max(self.epoch); + Ok(entry.1) + } + } + .map(|token| ZoneClaim { + zone_id: zone_id.to_string(), + holder: holder.to_string(), + token, + expires_at: SystemTime::UNIX_EPOCH, + }) + }) + } + + fn renew<'a>( + &'a self, + claim: &'a ZoneClaim, + _ttl: Duration, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + let claims = self.claims.lock().expect("claims"); + match claims.get(&claim.zone_id) { + Some((Some(holder), token)) if *holder == claim.holder && *token == claim.token => { + Ok(claim.clone()) + } + _ => Err(OwnershipError::Lost), + } + }) + } + + fn release<'a>(&'a self, claim: &'a ZoneClaim) -> BoxFuture<'a, ()> { + Box::pin(async move { + let mut claims = self.claims.lock().expect("claims"); + if let Some(entry) = claims.get_mut(&claim.zone_id) { + if entry.0.as_deref() == Some(claim.holder.as_str()) && entry.1 == claim.token { + entry.0 = None; + } + } + }) + } +} + +/// Zone ownership over any `distributed::lease::LeaseStore` (in-memory, +/// SQLite or Postgres): key `zone:{zone_id}`, the lease's fencing token is +/// the claim token. +#[cfg(feature = "lease")] +#[derive(Debug, Clone)] +pub struct FencedLeaseOwnership { + store: S, +} + +#[cfg(feature = "lease")] +impl FencedLeaseOwnership { + /// Wrap a lease store. + pub fn new(store: S) -> Self { + Self { store } + } + + /// The lease store. + pub fn store(&self) -> &S { + &self.store + } +} + +#[cfg(feature = "lease")] +fn lease_key(zone_id: &str) -> String { + format!("zone:{zone_id}") +} + +#[cfg(feature = "lease")] +fn map_lease_error(error: distributed::lease::LeaseError) -> OwnershipError { + use distributed::lease::LeaseError; + match error { + LeaseError::Held { holder, .. } => OwnershipError::Held { holder }, + LeaseError::Lost { .. } | LeaseError::StaleFence { .. } => OwnershipError::Lost, + other => OwnershipError::Backend(other.to_string()), + } +} + +#[cfg(feature = "lease")] +fn claim_of(zone_id: &str, lease: distributed::lease::Lease) -> ZoneClaim { + ZoneClaim { + zone_id: zone_id.to_string(), + holder: lease.holder, + token: lease.token.get(), + expires_at: lease.expires_at, + } +} + +#[cfg(feature = "lease")] +impl ZoneOwnership for FencedLeaseOwnership +where + S: distributed::lease::LeaseStore + 'static, +{ + fn acquire<'a>( + &'a self, + zone_id: &'a str, + holder: &'a str, + ttl: Duration, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + let key = lease_key(zone_id); + self.store + .acquire(&key, holder, ttl) + .await + .map(|lease| claim_of(zone_id, lease)) + .map_err(map_lease_error) + }) + } + + fn renew<'a>( + &'a self, + claim: &'a ZoneClaim, + ttl: Duration, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + let lease = distributed::lease::Lease { + key: lease_key(&claim.zone_id), + holder: claim.holder.clone(), + token: distributed::lease::FencingToken::new(claim.token), + expires_at: claim.expires_at, + }; + self.store + .renew(&lease, ttl) + .await + .map(|lease| claim_of(&claim.zone_id, lease)) + .map_err(map_lease_error) + }) + } + + fn release<'a>(&'a self, claim: &'a ZoneClaim) -> BoxFuture<'a, ()> { + Box::pin(async move { + let lease = distributed::lease::Lease { + key: lease_key(&claim.zone_id), + holder: claim.holder.clone(), + token: distributed::lease::FencingToken::new(claim.token), + expires_at: claim.expires_at, + }; + let _ = self.store.release(&lease).await; + }) + } +} + +/// Behaviour every [`ZoneOwnership`] must show (exclusive claims, `Held`, +/// idempotent re-acquire, `Lost` after release, strictly increasing +/// fencing tokens). `zone_id` must be unused. Panics on a violation. +#[doc(hidden)] +pub async fn ownership_conformance(ownership: &dyn ZoneOwnership, zone_id: &str) { + let ttl = Duration::from_secs(30); + let first = ownership + .acquire(zone_id, "h1#1", ttl) + .await + .expect("first acquire"); + assert_eq!(first.zone_id, zone_id); + assert_eq!(first.holder, "h1#1"); + assert_eq!( + ownership.acquire(zone_id, "h2#1", ttl).await, + Err(OwnershipError::Held { + holder: "h1#1".into() + }), + "a live claim is exclusive" + ); + let again = ownership + .acquire(zone_id, "h1#1", ttl) + .await + .expect("re-acquire"); + assert_eq!( + again.token, first.token, + "the holder gets its own claim back" + ); + let renewed = ownership.renew(&first, ttl).await.expect("renew"); + assert_eq!(renewed.token, first.token, "renewal keeps the token"); + ownership.release(&first).await; + assert_eq!( + ownership.renew(&first, ttl).await, + Err(OwnershipError::Lost), + "a released claim is lost" + ); + let second = ownership + .acquire(zone_id, "h2#1", ttl) + .await + .expect("second acquire"); + assert!(second.token > first.token, "tokens strictly increase"); + assert_eq!( + ownership.renew(&first, ttl).await, + Err(OwnershipError::Lost), + "an old claim stays lost" + ); + ownership.release(&second).await; + let third = ownership + .acquire(zone_id, "h1#2", ttl) + .await + .expect("third acquire"); + assert!(third.token > second.token, "tokens survive release"); + ownership.release(&third).await; +} + +/// What every [`ZoneOwnership`] with a TTL must do for a crash-restarted +/// host. Its holder names the same host and activation ordinal as before +/// but a new process nonce (`"{host}#{nonce}#{activation}"`), and its +/// previous incarnation's claim was never released: while that claim +/// lives the new holder is `Held` (never handed the old claim and token), +/// and once `expire` has let it lapse (a manual clock, or waiting out a +/// `ttl` the backend's own clock measures) the new holder gets a strictly +/// larger token and the old claim stays lost. `zone_id` must be unused. +/// Panics on a violation. ([`LocalOwnership`] has no TTL: a restart is a +/// new instance, whose tokens start at a later epoch.) +#[doc(hidden)] +pub async fn restart_conformance( + ownership: &dyn ZoneOwnership, + zone_id: &str, + ttl: Duration, + expire: impl std::future::Future, +) { + let (dead, restarted) = ("h1#1a#1", "h1#2b#1"); + let old = ownership + .acquire(zone_id, dead, ttl) + .await + .expect("first incarnation acquires"); + assert_eq!( + ownership.acquire(zone_id, restarted, ttl).await, + Err(OwnershipError::Held { + holder: dead.into() + }), + "a restarted holder never gets its previous incarnation's live claim" + ); + expire.await; + let new = ownership + .acquire(zone_id, restarted, ttl) + .await + .expect("the restarted holder acquires once the dead claim lapsed"); + assert!( + new.token > old.token, + "a restarted holder gets a larger token ({} <= {})", + new.token, + old.token + ); + assert_eq!( + ownership.renew(&old, ttl).await, + Err(OwnershipError::Lost), + "the dead incarnation's claim is lost" + ); + ownership.release(&new).await; +} + +#[cfg(test)] +mod tests { + use super::*; + + fn block(f: impl std::future::Future) -> T { + // The local store never awaits anything; poll once. + let waker = std::task::Waker::noop(); + let mut cx = std::task::Context::from_waker(waker); + let mut f = std::pin::pin!(f); + match f.as_mut().poll(&mut cx) { + std::task::Poll::Ready(v) => v, + std::task::Poll::Pending => panic!("local ownership must not pend"), + } + } + + #[test] + fn local_claims_are_exclusive_and_tokens_monotonic() { + let own = LocalOwnership::new(); + let ttl = Duration::from_secs(1); + let a = block(own.acquire("z", "h1#1", ttl)).unwrap(); + assert_eq!( + block(own.acquire("z", "h2#1", ttl)), + Err(OwnershipError::Held { + holder: "h1#1".into() + }) + ); + assert_eq!(block(own.acquire("z", "h1#1", ttl)).unwrap(), a); + block(own.release(&a)); + assert_eq!(block(own.renew(&a, ttl)), Err(OwnershipError::Lost)); + let b = block(own.acquire("z", "h2#1", ttl)).unwrap(); + assert!(b.token > a.token); + } + + #[test] + fn local_ownership_passes_the_conformance_suite() { + block(ownership_conformance(&LocalOwnership::new(), "conformance")); + } + + #[test] + fn local_tokens_outrank_a_previous_process() { + let ttl = Duration::from_secs(1); + let before = LocalOwnership::with_epoch(100); + let old = block(before.acquire("z", "h#1", ttl)).unwrap(); + assert_eq!(old.token, 100); + // A restarted process starts from a later epoch. + let after = LocalOwnership::new(); + let new = block(after.acquire("z", "h#1", ttl)).unwrap(); + assert!(new.token > old.token); + assert_eq!(new.token, after.epoch()); + } +} diff --git a/distributed_game/src/world/state.rs b/distributed_game/src/world/state.rs new file mode 100644 index 000000000..098c2c1b3 --- /dev/null +++ b/distributed_game/src/world/state.rs @@ -0,0 +1,212 @@ +//! Durable zone state for hibernation. +//! +//! When a zone hibernates, the host asks it for a snapshot +//! ([`Zone::hibernate`](crate::Zone::hibernate)) and stores it here under +//! the zone's ownership token; the next activation (on any host) loads it +//! and hands it to [`Zone::on_restore`](crate::Zone::on_restore). +//! +//! Writes are **fenced**: `save` (and `delete`) with a token older than the +//! stored one fails with [`StateError::Stale`], so a host that lost +//! ownership while paused can never overwrite the state written by its +//! successor. An equal token is accepted (the same owner saving again). +//! +//! Durable snapshots live in celld: one `ZoneState:{zone_id}` cell per zone +//! ([`super::zone_state`], `celld::CellZoneStateStore`), so a sleeping zone +//! is a sleeping Durable Object. [`MemoryZoneStateStore`] is the in-process +//! store for unit tests. There is no native file store. + +use std::collections::HashMap; +use std::sync::Mutex; + +use crate::facts::BoxFuture; + +/// A stored snapshot. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StoredZoneState { + /// Ownership token it was written under. + pub token: u64, + /// Content version the zone was running. + pub content_version: String, + /// Opaque zone bytes. + pub state: Vec, +} + +/// Store failure. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StateError { + /// Write fenced off: a newer owner already saved. + Stale { + /// Presented token. + presented: u64, + /// Stored token. + current: u64, + }, + /// Backend failure. + Backend(String), +} + +impl std::fmt::Display for StateError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Stale { presented, current } => { + write!(f, "stale zone-state token {presented} (current {current})") + } + Self::Backend(e) => write!(f, "zone-state backend: {e}"), + } + } +} + +impl std::error::Error for StateError {} + +/// Fenced snapshot store. +pub trait ZoneStateStore: Send + Sync + 'static { + /// Latest snapshot of `zone_id` (`None` when none, or deleted). + fn load<'a>( + &'a self, + zone_id: &'a str, + ) -> BoxFuture<'a, Result, StateError>>; + + /// Store a snapshot if `state.token` >= the stored token. + fn save<'a>( + &'a self, + zone_id: &'a str, + state: &'a StoredZoneState, + ) -> BoxFuture<'a, Result<(), StateError>>; + + /// Drop the snapshot if `token` >= the stored token. The token stays + /// (a later save under an older token is still stale). + fn delete<'a>(&'a self, zone_id: &'a str, token: u64) -> BoxFuture<'a, Result<(), StateError>>; +} + +/// In-memory store (unit tests / single process). +#[derive(Debug, Default)] +pub struct MemoryZoneStateStore { + /// zone -> (highest token seen, snapshot). + states: Mutex)>>, +} + +impl MemoryZoneStateStore { + /// Empty. + pub fn new() -> Self { + Self::default() + } + + fn fenced( + &self, + zone_id: &str, + token: u64, + value: Option, + ) -> Result<(), StateError> { + let mut states = self.states.lock().expect("states"); + let entry = states.entry(zone_id.to_string()).or_insert((0, None)); + if entry.0 > token { + return Err(StateError::Stale { + presented: token, + current: entry.0, + }); + } + *entry = (token, value); + Ok(()) + } +} + +impl ZoneStateStore for MemoryZoneStateStore { + fn load<'a>( + &'a self, + zone_id: &'a str, + ) -> BoxFuture<'a, Result, StateError>> { + let state = self + .states + .lock() + .expect("states") + .get(zone_id) + .and_then(|(_, state)| state.clone()); + Box::pin(async move { Ok(state) }) + } + + fn save<'a>( + &'a self, + zone_id: &'a str, + state: &'a StoredZoneState, + ) -> BoxFuture<'a, Result<(), StateError>> { + let result = self.fenced(zone_id, state.token, Some(state.clone())); + Box::pin(async move { result }) + } + + fn delete<'a>(&'a self, zone_id: &'a str, token: u64) -> BoxFuture<'a, Result<(), StateError>> { + let result = self.fenced(zone_id, token, None); + Box::pin(async move { result }) + } +} + +/// The fencing contract every [`ZoneStateStore`] must meet (memory, celld). +#[doc(hidden)] +pub async fn state_store_conformance(store: &dyn ZoneStateStore, zone: &str, payload: Vec) { + let snap = |token: u64, bytes: Vec| StoredZoneState { + token, + content_version: "c1".into(), + state: bytes, + }; + assert_eq!(store.load(zone).await.unwrap(), None); + store.save(zone, &snap(2, b"a".to_vec())).await.unwrap(); + store.save(zone, &snap(2, payload.clone())).await.unwrap(); + assert_eq!( + store.load(zone).await.unwrap(), + Some(snap(2, payload.clone())) + ); + assert_eq!( + store.save(zone, &snap(1, b"old".to_vec())).await, + Err(StateError::Stale { + presented: 1, + current: 2 + }) + ); + assert_eq!( + store.delete(zone, 1).await, + Err(StateError::Stale { + presented: 1, + current: 2 + }) + ); + store.save(zone, &snap(3, b"c".to_vec())).await.unwrap(); + assert_eq!( + store.load(zone).await.unwrap(), + Some(snap(3, b"c".to_vec())) + ); + store.save(zone, &snap(4, payload.clone())).await.unwrap(); + store.delete(zone, 4).await.unwrap(); + assert_eq!(store.load(zone).await.unwrap(), None); + assert_eq!( + store.save(zone, &snap(3, b"late".to_vec())).await, + Err(StateError::Stale { + presented: 3, + current: 4 + }), + "the token survives a delete" + ); + store.save(zone, &snap(5, payload.clone())).await.unwrap(); + assert_eq!(store.load(zone).await.unwrap(), Some(snap(5, payload))); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn block_on(future: F) -> F::Output { + use std::task::{Context, Poll, Waker}; + let mut future = std::pin::pin!(future); + match future + .as_mut() + .poll(&mut Context::from_waker(Waker::noop())) + { + Poll::Ready(output) => output, + Poll::Pending => panic!("memory store futures are ready"), + } + } + + #[test] + fn memory_store_is_fenced() { + let store = MemoryZoneStateStore::new(); + block_on(state_store_conformance(&store, "z", vec![7; 300_000])); + } +} diff --git a/distributed_game/src/world/topology.rs b/distributed_game/src/world/topology.rs new file mode 100644 index 000000000..307801539 --- /dev/null +++ b/distributed_game/src/world/topology.rs @@ -0,0 +1,93 @@ +//! Zone hierarchy and tier-up event propagation. +//! +//! Zones can nest (province > city > borough > neighborhood). A +//! [`ZoneTopology`] names each zone's parent. A zone emits a tier-up event +//! with [`Ctx::emit_upward`](crate::Ctx::emit_upward); the driver +//! (`net::GameServer`) routes it to the parent — activating the parent on +//! demand, on another host through the directory if needed — and the +//! parent's host delivers it to [`Zone::on_child_event`](crate::Zone::on_child_event) +//! on a later tick. Nothing blocks: the child's tick only enqueues. +//! +//! After delivering, the parent's host forwards the event further up while +//! `levels` remain (`levels = 1` reaches only the parent; the default +//! reaches the root). + +/// Parent links between zones. +pub trait ZoneTopology: Send + Sync + 'static { + /// Parent zone id, None for a root. + fn parent(&self, zone_id: &str) -> Option; +} + +/// `"eldoria.port.docks"` → parent `"eldoria.port"` → `"eldoria"` → root. +#[derive(Debug, Clone, Copy, Default)] +pub struct DottedTopology; + +impl ZoneTopology for DottedTopology { + fn parent(&self, zone_id: &str) -> Option { + zone_id + .rsplit_once('.') + .map(|(parent, _)| parent.to_string()) + .filter(|p| !p.is_empty()) + } +} + +/// No hierarchy. +#[derive(Debug, Clone, Copy, Default)] +pub struct FlatTopology; + +impl ZoneTopology for FlatTopology { + fn parent(&self, _zone_id: &str) -> Option { + None + } +} + +impl ZoneTopology for F +where + F: Fn(&str) -> Option + Send + Sync + 'static, +{ + fn parent(&self, zone_id: &str) -> Option { + self(zone_id) + } +} + +/// A tier-up event travelling from a child zone towards the root. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ChildEvent { + /// Zone that emitted it originally. + pub origin_zone: String, + /// Zone it was forwarded from (the direct child of the receiver). + pub from_zone: String, + /// Game-defined kind, e.g. `"boss_defeated"`. + pub kind: String, + /// Game-defined payload. + pub payload: Vec, + /// Origin tick. + pub origin_tick: u64, + /// Content version of the origin zone when emitted. + pub content_version: String, + /// Remaining levels to travel (>= 1 while in flight). + pub levels: u8, +} + +impl ChildEvent { + /// Levels value that reaches the root. + pub const TO_ROOT: u8 = u8::MAX; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dotted_parents() { + let t = DottedTopology; + assert_eq!( + t.parent("eldoria.port.docks").as_deref(), + Some("eldoria.port") + ); + assert_eq!(t.parent("eldoria.port").as_deref(), Some("eldoria")); + assert_eq!(t.parent("eldoria"), None); + let f = |z: &str| (z == "a").then(|| "b".to_string()); + assert_eq!(f.parent("a").as_deref(), Some("b")); + } +} diff --git a/distributed_game/src/world/watch.rs b/distributed_game/src/world/watch.rs new file mode 100644 index 000000000..64447f27d --- /dev/null +++ b/distributed_game/src/world/watch.rs @@ -0,0 +1,718 @@ +//! Watched world views: zones keep pushed read models of the world cells +//! they care about instead of polling them. +//! +//! A world cell (a hood, the content rollout, …) is the write model. A zone +//! that cares about it **watches** it: the zone's read of the cell (`GET +//! /{kind}/{shard}?watch=&lease=`) returns the cell's view with +//! its `version` and leaves a lease, and after every commit that moves the +//! version the cell pushes [`WatchUpdate`] `{topic, version, view}` to the +//! zones whose lease is live. The zone keeps the highest version per topic +//! ([`TopicVersions`]), so a late push or read never rolls it back, and +//! re-reads each topic every [`RECONCILE_MS`] ± [`RECONCILE_JITTER_MS`] +//! (renewing its lease; repairing a lost push). Eventually consistent by +//! design: for display and world flavour, never for settling rewards. +//! +//! Cost: O(changes × watchers + zones / [`RECONCILE_MS`]) instead of every +//! zone reading every cell every second or two. +//! +//! Leases live in the cell's memory only ([`Watchers`]): a watch writes +//! nothing, and a cell that restarted relearns its watchers within one +//! reconcile. +//! +//! A zone declares what it watches with [`Watches`] (typed: each view +//! decodes into a plain serde struct and becomes one of the zone's +//! messages); the celld zone host does the reads, leases and pushes. + +use std::collections::BTreeMap; + +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// How long a watch lasts without a renewing read (ms). +pub const WATCH_LEASE_MS: u64 = 120_000; +/// How often a zone re-reads each watched topic (ms), on average. +pub const RECONCILE_MS: u64 = 45_000; +/// Spread of [`RECONCILE_MS`] (± ms), so zones that woke together do not +/// read together. +pub const RECONCILE_JITTER_MS: u64 = 15_000; +/// How often a zone that takes no pushes (no class binding, or +/// `ZONE_WORLD_PUSH=0`) polls each watched topic (ms). +pub const POLL_MS: u64 = 1_000; +/// Watchers pushed to at once by one cell. +pub const PUSH_CONCURRENCY: usize = 16; +/// Waits (ms) before each retry of a push that failed in transport or was +/// refused for load (5xx, 429): a busy zone still gets a rollout's freeze +/// within seconds instead of at its next reconcile. +pub const PUSH_RETRY_MS: [u64; 3] = [250, 1_000, 3_000]; + +/// Whether a push answered with `status` is worth retrying. A zone takes +/// every push it can parse with 204, asleep or not; other 4xx stay wrong. +pub fn push_retryable(status: u16) -> bool { + status == 429 || status >= 500 +} +/// Query parameter naming the watcher (`/`). +pub const WATCH_PARAM: &str = "watch"; +/// Query parameter with the lease (ms). +pub const LEASE_PARAM: &str = "lease"; +/// Path segment of the zone route that takes pushes (`POST …/__world`). +pub const PUSH_ROUTE: &str = "__world"; +/// Path segment of a watched cell's counters (`GET /{kind}/{shard}/__watchers`, +/// internal secret): its live watchers and [`WatcherStats`]. +pub const STATS_ROUTE: &str = "__watchers"; + +/// The topic of cell `kind/shard`. +pub fn topic(kind: &str, shard: &str) -> String { + format!("{kind}/{shard}") +} + +/// A watcher's address: the Durable Object namespace binding of its class +/// and its name (`PIT_ROOM/pit.0.0`). +pub fn watcher_address(binding: &str, name: &str) -> String { + format!("{binding}/{name}") +} + +/// `(binding, name)` of a [`watcher_address`]. +pub fn parse_watcher_address(address: &str) -> Option<(&str, &str)> { + address + .split_once('/') + .filter(|(binding, name)| !binding.is_empty() && !name.is_empty()) +} + +/// The class binding of a Durable Object class name, by convention +/// (`PitRoom` → `PIT_ROOM`). +pub fn class_binding(class: &str) -> String { + let mut binding = String::with_capacity(class.len() + 4); + for (i, c) in class.chars().enumerate() { + if c.is_uppercase() && i > 0 { + binding.push('_'); + } + binding.push(c.to_ascii_uppercase()); + } + binding +} + +/// What a cell pushes to its watchers (`POST …/__world`). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct WatchUpdate { + /// [`topic`] of the cell. + pub topic: String, + /// The cell's version (its aggregate version). + pub version: u64, + /// The cell's view (what its read route returns). + pub view: Value, +} + +/// A cell's watchers: leases by [`watcher_address`] (memory only). +#[derive(Debug, Default)] +pub struct Watchers { + leases: BTreeMap, + published: Option, + last_view: Option, + stats: WatcherStats, +} + +/// What a watched cell did for its watchers since it started (camelCase +/// JSON; the cell's `GET …/__watchers`). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct WatcherStats { + /// Watching reads (each leaves or renews a lease). + pub reads: u64, + /// Views published to the live watchers. + pub published: u64, + /// Views not published: unchanged apart from `version`, or not newer. + pub skipped: u64, + /// Pushes sent (one per live watcher of each published view). + pub pushes: u64, +} + +impl Watchers { + /// No watchers. + pub fn new() -> Self { + Self::default() + } + + /// `watcher` watches until `now_ms + lease_ms` (capped at + /// [`WATCH_LEASE_MS`]); a zero lease ends its watch. + pub fn watch(&mut self, watcher: &str, now_ms: u64, lease_ms: u64) { + self.stats.reads += 1; + if lease_ms == 0 { + self.leases.remove(watcher); + return; + } + let until = now_ms.saturating_add(lease_ms.min(WATCH_LEASE_MS)); + self.leases.insert(watcher.to_string(), until); + } + + /// The watchers with a live lease at `now_ms` (expired ones dropped). + pub fn live(&mut self, now_ms: u64) -> Vec { + self.leases.retain(|_, until| *until > now_ms); + self.leases.keys().cloned().collect() + } + + /// Whether `view` at `version` is news for the watchers: newer than + /// the last one published and different apart from its `version` + /// (a command that moves the aggregate but not its view, like a + /// heartbeat, pushes nothing). Records it when it is. + pub fn publish(&mut self, version: u64, view: &Value) -> bool { + let news = self.news(version, view); + if news { + self.stats.published += 1; + } else { + self.stats.skipped += 1; + } + news + } + + fn news(&mut self, version: u64, view: &Value) -> bool { + if self.published.is_some_and(|last| version <= last) { + return false; + } + self.published = Some(version); + let content = match view { + Value::Object(fields) => { + let mut fields = fields.clone(); + fields.remove("version"); + Value::Object(fields).to_string() + } + other => other.to_string(), + }; + if self.last_view.as_ref() == Some(&content) { + return false; + } + self.last_view = Some(content); + true + } + + /// `n` pushes were sent. + pub fn pushed(&mut self, n: usize) { + self.stats.pushes += n as u64; + } + + /// Counts so far. + pub fn stats(&self) -> WatcherStats { + self.stats + } +} + +/// `(watcher, lease ms)` from a read's query string, if it watches. +pub fn watch_query(query: &str) -> Option<(String, u64)> { + let mut watcher = None; + let mut lease = WATCH_LEASE_MS; + for pair in query.split('&') { + let (key, value) = pair.split_once('=').unwrap_or((pair, "")); + match key { + WATCH_PARAM => watcher = Some(decode_component(value)), + LEASE_PARAM => lease = value.parse().unwrap_or(WATCH_LEASE_MS), + _ => {} + } + } + watcher + .filter(|w| parse_watcher_address(w).is_some()) + .map(|w| (w, lease)) +} + +/// The query string a watching read sends. +pub fn watch_query_string(watcher: &str, lease_ms: u64) -> String { + format!( + "{WATCH_PARAM}={}&{LEASE_PARAM}={lease_ms}", + encode_component(watcher) + ) +} + +/// The view's version: its `version` field (0 when the cell does not +/// version its view: every read then applies). +pub fn view_version(view: &Value) -> u64 { + view.get("version").and_then(Value::as_u64).unwrap_or(0) +} + +/// A zone's highest version seen per topic. +#[derive(Debug, Default, Clone)] +pub struct TopicVersions { + seen: BTreeMap, +} + +impl TopicVersions { + /// Nothing seen. + pub fn new() -> Self { + Self::default() + } + + /// Whether `version` of `topic` should be applied: newer than any + /// seen, or unversioned (0) views, which always apply. + pub fn accept(&mut self, topic: &str, version: u64) -> bool { + if version == 0 { + return true; + } + match self.seen.get(topic) { + Some(&seen) if version <= seen => false, + _ => { + self.seen.insert(topic.to_string(), version); + true + } + } + } + + /// The highest version seen of `topic`. + pub fn get(&self, topic: &str) -> Option { + self.seen.get(topic).copied() + } + + /// Forget everything (a new activation re-hydrates). + pub fn clear(&mut self) { + self.seen.clear(); + } +} + +/// A zone's side of its watches: the highest version applied per topic +/// ([`TopicVersions`]) and when each topic is read next. A zone that takes +/// pushes reads each topic on wake and then every [`RECONCILE_MS`] ± +/// [`RECONCILE_JITTER_MS`] (renewing its lease, repairing a lost push); +/// one that does not polls every [`POLL_MS`]. +#[derive(Debug, Default)] +pub struct WorldSync { + versions: TopicVersions, + due: BTreeMap, +} + +impl WorldSync { + /// Nothing applied, every topic due. + pub fn new() -> Self { + Self::default() + } + + /// The `topics` to read at `now_ms` (every one with `all`, on wake), + /// each scheduled for its next read: a reconcile when the zone takes + /// `pushed` updates (`unit()` in `[0, 1)` choosing where in the + /// spread), else a poll. + pub fn due( + &mut self, + topics: impl IntoIterator, + now_ms: u64, + all: bool, + pushed: bool, + mut unit: impl FnMut() -> f64, + ) -> Vec { + let mut reads = Vec::new(); + for topic in topics { + let next = self.due.get(&topic).copied().unwrap_or(0); + if !all && now_ms < next { + continue; + } + let after = if pushed { + next_reconcile_ms(now_ms, unit()) + } else { + now_ms + POLL_MS + }; + self.due.insert(topic.clone(), after); + reads.push(topic); + } + reads + } + + /// Whether `version` of `topic` (read or pushed) should be applied + /// ([`TopicVersions::accept`]). + pub fn accept(&mut self, topic: &str, version: u64) -> bool { + self.versions.accept(topic, version) + } + + /// The highest version applied of `topic`. + pub fn version(&self, topic: &str) -> Option { + self.versions.get(topic) + } + + /// Forget everything (a new activation re-hydrates). + pub fn clear(&mut self) { + self.versions.clear(); + self.due.clear(); + } +} + +/// The next reconcile of a topic: [`RECONCILE_MS`] ± [`RECONCILE_JITTER_MS`] +/// after `now_ms`, `unit` in `[0, 1)` choosing where in the spread. +pub fn next_reconcile_ms(now_ms: u64, unit: f64) -> u64 { + let spread = (unit.clamp(0.0, 1.0) * 2.0 - 1.0) * RECONCILE_JITTER_MS as f64; + now_ms + (RECONCILE_MS as f64 + spread).max(1_000.0) as u64 +} + +type Decode = Box Option>; + +/// One watched cell: its topic and how its view becomes a message. +pub struct Watch { + /// Cell kind. + pub kind: String, + /// Cell shard. + pub shard: String, + decode: Decode, +} + +impl Watch { + /// [`topic`] of the cell. + pub fn topic(&self) -> String { + topic(&self.kind, &self.shard) + } + + /// The message for `view` (`None`: nothing to deliver, e.g. the cell + /// has no state yet or the view does not decode). + pub fn message(&self, view: Value) -> Option { + (self.decode)(view) + } +} + +/// What a zone watches, each cell's view decoding into a plain struct that +/// becomes a zone message: +/// +/// ``` +/// # use distributed_game::world::watch::Watches; +/// # #[derive(serde::Deserialize)] struct HoodRead { state: Option } +/// # enum Msg { Hood(u32) } +/// let watches: Watches = Watches::new() +/// .cell("hood", "0.0", |read: HoodRead| read.state.map(Msg::Hood)); +/// assert_eq!(watches.len(), 1); +/// ``` +pub struct Watches { + entries: Vec>, +} + +impl Default for Watches { + fn default() -> Self { + Self { + entries: Vec::new(), + } + } +} + +impl Watches { + /// Nothing watched. + pub fn new() -> Self { + Self::default() + } + + /// Watch cell `kind/shard`; its view decodes into `V` and `to` makes + /// the zone's message of it. + pub fn cell(mut self, kind: &str, shard: &str, to: F) -> Self + where + V: DeserializeOwned, + F: Fn(V) -> Option + 'static, + { + self.entries.push(Watch { + kind: kind.to_string(), + shard: shard.to_string(), + decode: Box::new(move |view| serde_json::from_value(view).ok().and_then(&to)), + }); + self + } + + /// Watched cells. + pub fn len(&self) -> usize { + self.entries.len() + } + + /// Nothing watched. + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// The watched cells. + pub fn iter(&self) -> impl Iterator> { + self.entries.iter() + } + + /// The watch of `topic`. + pub fn get(&self, topic: &str) -> Option<&Watch> { + self.entries.iter().find(|w| w.topic() == topic) + } +} + +fn encode_component(value: &str) -> String { + let mut encoded = String::with_capacity(value.len()); + for byte in value.bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + encoded.push(byte as char) + } + _ => encoded.push_str(&format!("%{byte:02X}")), + } + } + encoded +} + +fn decode_component(value: &str) -> String { + let bytes = value.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'%' if i + 2 < bytes.len() => match u8::from_str_radix(&value[i + 1..i + 3], 16) { + Ok(byte) => { + out.push(byte); + i += 3; + } + Err(_) => { + out.push(b'%'); + i += 1; + } + }, + b'+' => { + out.push(b' '); + i += 1; + } + byte => { + out.push(byte); + i += 1; + } + } + } + String::from_utf8_lossy(&out).into_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn leases_expire_and_renew() { + let mut watchers = Watchers::new(); + watchers.watch("PIT_ROOM/pit.0.0", 1_000, 10_000); + watchers.watch("PIT_ROOM/pit.1.0", 1_000, 60_000); + assert_eq!(watchers.live(5_000).len(), 2); + assert_eq!(watchers.live(12_000), vec!["PIT_ROOM/pit.1.0".to_string()]); + watchers.watch("PIT_ROOM/pit.1.0", 12_000, 0); + assert!(watchers.live(12_000).is_empty()); + // Leases are capped. + watchers.watch("PIT_ROOM/pit.2.0", 0, u64::MAX); + assert!(watchers.live(WATCH_LEASE_MS).is_empty()); + } + + #[test] + fn a_version_is_published_once() { + let mut watchers = Watchers::new(); + let view = |n: u64| json!({ "version": n, "tier": n }); + assert!(watchers.publish(3, &view(3))); + assert!(!watchers.publish(3, &view(3))); + assert!(!watchers.publish(2, &view(2))); + assert!(watchers.publish(4, &view(4))); + } + + #[test] + fn an_unchanged_view_is_not_pushed() { + let mut watchers = Watchers::new(); + assert!(watchers.publish(1, &json!({ "version": 1, "tier": 2 }))); + // The aggregate moved (a heartbeat) but its view did not. + assert!(!watchers.publish(2, &json!({ "version": 2, "tier": 2 }))); + assert!(watchers.publish(3, &json!({ "version": 3, "tier": 3 }))); + } + + #[test] + fn watchers_count_their_work() { + let mut watchers = Watchers::new(); + watchers.watch("PIT_ROOM/pit.0.0", 0, 1_000); + watchers.watch("PIT_ROOM/pit.0.0", 500, 1_000); + assert!(watchers.publish(1, &json!({ "version": 1, "tier": 1 }))); + let live = watchers.live(600).len(); + watchers.pushed(live); + assert!(!watchers.publish(2, &json!({ "version": 2, "tier": 1 }))); + assert_eq!( + watchers.stats(), + WatcherStats { + reads: 2, + published: 1, + skipped: 1, + pushes: 1, + } + ); + } + + /// A deterministic `[0, 1)` sequence (xorshift). + fn units(seed: u64) -> impl FnMut() -> f64 { + let mut x = seed.max(1); + move || { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + (x >> 11) as f64 / (1u64 << 53) as f64 + } + } + + /// One zone watching one cell on a fake clock: the cell changes now and + /// then, and pushes are lost with `loss` (0..=1). Returns the longest + /// time (ms) the zone was behind the cell. + fn longest_lag(seed: u64, loss: f64) -> u64 { + const ZONE: &str = "PIT_ROOM/pit.0.0"; + const STEP_MS: u64 = 100; + let hood = topic("hood", "0.0"); + let view = |v: u64| json!({ "version": v, "tier": v }); + let mut cell = Watchers::new(); + let mut cell_version = 1u64; + let mut zone = WorldSync::new(); + let mut unit = units(seed); + let mut chance = units(seed ^ 0xfeed); + let (mut behind_since, mut longest) = (None::, 0u64); + let mut now = 0u64; + let mut all = true; + while now < 30 * 60_000 { + // The cell changes about every 20 s; its push may be lost. + if now > 0 && chance() < STEP_MS as f64 / 20_000.0 { + cell_version += 1; + if cell.publish(cell_version, &view(cell_version)) { + let live = cell.live(now); + cell.pushed(live.len()); + if live.iter().any(|w| w == ZONE) && chance() >= loss { + zone.accept(&hood, cell_version); + } + } + } + // The zone's tick: due reads renew its lease and apply the view. + for topic in zone.due([hood.clone()], now, all, true, &mut unit) { + cell.watch(ZONE, now, WATCH_LEASE_MS); + zone.accept(&topic, cell_version); + } + all = false; + if zone.version(&hood) == Some(cell_version) { + behind_since = None; + } else { + let since = *behind_since.get_or_insert(now); + longest = longest.max(now - since); + } + now += STEP_MS; + } + assert!(cell.live(now).contains(&ZONE.to_string()), "lease renewed"); + longest + } + + #[test] + fn a_reconcile_repairs_a_missed_push() { + let period = RECONCILE_MS + RECONCILE_JITTER_MS; + for seed in 1..=8 { + // Every push lost: the next reconcile catches the zone up. + let lag = longest_lag(seed, 1.0); + assert!(lag > 0 && lag <= period, "seed {seed}: behind for {lag} ms"); + // Some pushes lost. + let lag = longest_lag(seed, 0.3); + assert!(lag <= period, "seed {seed}: behind for {lag} ms"); + } + // No push lost: the zone is never behind. + assert_eq!(longest_lag(3, 0.0), 0); + } + + #[test] + fn a_zone_without_pushes_polls() { + let mut zone = WorldSync::new(); + let topics = || [topic("hood", "0.0"), topic("city", "city")]; + assert_eq!(zone.due(topics(), 0, true, false, || 0.5).len(), 2); + assert!(zone + .due(topics(), POLL_MS - 1, false, false, || 0.5) + .is_empty()); + assert_eq!(zone.due(topics(), POLL_MS, false, false, || 0.5).len(), 2); + // Pushed: the next read is a reconcile period away. + assert_eq!( + zone.due(topics(), 2 * POLL_MS, false, true, || 0.5).len(), + 2 + ); + assert!(zone + .due( + topics(), + 2 * POLL_MS + RECONCILE_MS - 1, + false, + true, + || 0.5 + ) + .is_empty()); + } + + #[test] + fn zones_never_roll_back() { + let mut seen = TopicVersions::new(); + assert!(seen.accept("hood/0.0", 5)); + assert!(!seen.accept("hood/0.0", 5)); + assert!(!seen.accept("hood/0.0", 4), "a late push"); + assert!(seen.accept("hood/0.0", 6)); + assert!(seen.accept("borough/0.0", 1), "topics are independent"); + assert!(seen.accept("zone-dev/netsim", 0) && seen.accept("zone-dev/netsim", 0)); + seen.clear(); + assert!(seen.accept("hood/0.0", 2)); + } + + #[test] + fn watch_queries_round_trip() { + let query = watch_query_string("PIT_ROOM/pit.-1.2", 90_000); + assert_eq!(query, "watch=PIT_ROOM%2Fpit.-1.2&lease=90000"); + assert_eq!( + watch_query(&query), + Some(("PIT_ROOM/pit.-1.2".to_string(), 90_000)) + ); + assert_eq!( + watch_query("watch=PIT_ROOM%2Fpit.0.0"), + Some(("PIT_ROOM/pit.0.0".into(), WATCH_LEASE_MS)) + ); + assert_eq!( + watch_query("watch=A%2Fb%"), + Some(("A/b%".into(), WATCH_LEASE_MS)) + ); + assert_eq!(watch_query(""), None); + assert_eq!(watch_query("watch=nobinding"), None); + assert_eq!(watch_query("lease=5"), None); + } + + #[test] + fn class_bindings_follow_the_convention() { + assert_eq!(class_binding("PitRoom"), "PIT_ROOM"); + assert_eq!(class_binding("Room"), "ROOM"); + assert_eq!( + parse_watcher_address("PIT_ROOM/pit.0.0"), + Some(("PIT_ROOM", "pit.0.0")) + ); + assert_eq!(parse_watcher_address("/x"), None); + } + + #[test] + fn reconciles_spread_around_the_period() { + let low = next_reconcile_ms(0, 0.0); + let mid = next_reconcile_ms(0, 0.5); + let high = next_reconcile_ms(0, 0.999_999); + assert_eq!(low, RECONCILE_MS - RECONCILE_JITTER_MS); + assert_eq!(mid, RECONCILE_MS); + assert!(high <= RECONCILE_MS + RECONCILE_JITTER_MS && high > mid); + assert!(high < WATCH_LEASE_MS, "a zone renews before its lease ends"); + } + + #[test] + fn watches_decode_views_into_messages() { + #[derive(Deserialize)] + struct HoodRead { + state: Option, + } + #[derive(Deserialize, Debug, PartialEq)] + struct Hood { + tier: u32, + } + #[derive(Debug, PartialEq)] + enum Msg { + Hood(u32), + } + let watches: Watches = Watches::new().cell("hood", "1.2", |read: HoodRead| { + read.state.map(|h| Msg::Hood(h.tier)) + }); + let watch = watches.get("hood/1.2").expect("watched"); + assert_eq!( + watch.message(json!({"state": {"tier": 3}, "version": 7})), + Some(Msg::Hood(3)) + ); + assert_eq!(watch.message(json!({"state": null})), None); + assert_eq!(watch.message(json!("garbage")), None); + assert_eq!(view_version(&json!({"version": 7})), 7); + assert_eq!(view_version(&json!({})), 0); + } + + #[test] + fn a_push_is_retried_only_when_the_zone_could_not_take_it() { + for status in [429, 500, 502, 503] { + assert!(push_retryable(status), "{status}"); + } + for status in [200, 204, 400, 401, 404] { + assert!(!push_retryable(status), "{status}"); + } + } +} diff --git a/distributed_game/src/world/zone_activity.rs b/distributed_game/src/world/zone_activity.rs new file mode 100644 index 000000000..d9fbc31a3 --- /dev/null +++ b/distributed_game/src/world/zone_activity.rs @@ -0,0 +1,288 @@ +//! What a zone running as a celld object is doing, as a cell: +//! `ZoneActivity:{zone_id}` (cell kind [`ZONE_ACTIVITY_KIND`]). +//! +//! A zone hosted by [`celld_zone`](crate::celld_zone) reports its own +//! lifecycle — woke up (`active`, `restored` when it came back from a +//! snapshot), emptied (`dormant`), slept (`hibernated`) — as facts +//! ([`RecordActivity`], command [`RECORD`]) through its fact sink, so the +//! transitions are durable and exactly once like any other zone fact. +//! +//! | Command | Effect | Outward event | +//! |---|---|---| +//! | `zone_activity.record` | the reported status, if emitted after the one stored | `zone.activity_changed` | +//! +//! Facts can settle out of order (retries, concurrent commits): a report +//! emitted before the stored one ([`FactStamp::emission_order`]) is +//! ignored. The outward event carries the post-transition +//! [`ZoneActivityStatus`]; the [`zone_status`](super::zone_status) read model +//! projects it into `zone_activity` rows (minimaps, dashboards). +//! +//! Only the zone itself may report: the fact's principal must be the +//! zone's system principal [`zone_principal`]`(zone)`, and the stamp's zone +//! is the shard. +//! +//! `node` and `isolate` are debug details (which celld node and V8 isolate +//! ran the activation, when known); nothing may route by them. + +use distributed::cell_host::AggregateCell; +use distributed::command::{typed_command, PreparedCommand, Succeeded}; +use distributed::microsvc::{ + CausalCommandContext, CausalRouteDependencies, HandlerError, PortableCommand, Routes, +}; +use distributed::{sourced, Entity}; +use serde::{Deserialize, Serialize}; + +use crate::cell::session_stamp; +use crate::FactStamp; + +/// Aggregate type (cell `ZoneActivity:{zone_id}`). +pub const ZONE_ACTIVITY: &str = "ZoneActivity"; +/// Cell kind (URL segment / Durable Object routing) of zone-activity cells. +pub const ZONE_ACTIVITY_KIND: &str = "zone-activity"; +/// The one command (a zone fact). +pub const RECORD: &str = "zone_activity.record"; + +/// Status: ticking with players (or just woke up). +pub const ACTIVITY_ACTIVE: &str = "active"; +/// Status: empty, still in memory, snapshot written. +pub const ACTIVITY_DORMANT: &str = "dormant"; +/// Status: asleep; the next join restores the snapshot. +pub const ACTIVITY_HIBERNATED: &str = "hibernated"; + +/// The system principal a zone reports its own activity under. +pub fn zone_principal(zone_id: &str) -> String { + format!("zone:{zone_id}") +} + +/// One zone's activity. +#[derive(Clone, Debug, Default, Serialize, Deserialize, distributed::Snapshot)] +pub struct ZoneActivity { + entity: Entity, + status: String, + activation: String, + restored: bool, + players: u32, + node: String, + isolate: String, + activations: u64, + changed_at_ms: u64, + /// Ordering key of the report that set the current status. + last: Option, +} + +/// The emission-order key of the last applied report. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct StampKey { + /// Zone. + pub zone_id: String, + /// Activation epoch. + pub activation: u64, + /// Tick. + pub tick: u64, + /// Emission wall time. + pub emitted_at_ms: u64, + /// Emission sequence. + pub seq: u64, +} + +impl StampKey { + fn of(stamp: &FactStamp) -> Self { + Self { + zone_id: stamp.zone_id.clone(), + activation: stamp.activation, + tick: stamp.tick, + emitted_at_ms: stamp.emitted_at_ms, + seq: stamp.seq, + } + } + + fn stamp(&self) -> FactStamp { + FactStamp { + zone_id: self.zone_id.clone(), + activation: self.activation, + tick: self.tick, + emitted_at_ms: self.emitted_at_ms, + seq: self.seq, + ..FactStamp::default() + } + } +} + +/// The public state carried by `zone.activity_changed`: one +/// `zone_activity` read-model row. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, distributed::DomainState)] +#[domain_state(version = 1)] +pub struct ZoneActivityStatus { + /// Zone (the cell's stream id). + pub zone_id: String, + /// [`ACTIVITY_ACTIVE`], [`ACTIVITY_DORMANT`] or [`ACTIVITY_HIBERNATED`]. + pub status: String, + /// Id of the object activation that reported it. + pub activation: String, + /// That activation restored a snapshot. + pub restored: bool, + /// Players in the zone when reported. + pub players: u32, + /// celld node running the activation (debug; empty when unknown). + pub node: String, + /// V8 isolate running the activation (debug). + pub isolate: String, + /// Activations seen so far. + pub activations: u64, + /// When the zone reported it (zone clock, Unix ms). + pub changed_at_ms: u64, +} + +impl From<&ZoneActivity> for ZoneActivityStatus { + fn from(activity: &ZoneActivity) -> Self { + Self { + zone_id: activity.entity.id().to_string(), + status: activity.status.clone(), + activation: activity.activation.clone(), + restored: activity.restored, + players: activity.players, + node: activity.node.clone(), + isolate: activity.isolate.clone(), + activations: activity.activations, + changed_at_ms: activity.changed_at_ms, + } + } +} + +#[sourced( + entity, + aggregate_type = "ZoneActivity", + events = "ZoneActivityEvent", + domain_state = ZoneActivityStatus +)] +impl ZoneActivity { + #[event("zone.activity_changed", version = 1, domain)] + fn changed(&mut self, zone_id: String, report: RecordActivity, stamp: StampKey) { + if self.entity.id().is_empty() { + self.entity.set_id(zone_id); + } + if report.activation != self.activation { + self.activations += 1; + } + self.status = report.status; + self.activation = report.activation; + self.restored = report.restored; + self.players = report.players; + self.node = report.node; + self.isolate = report.isolate; + self.changed_at_ms = stamp.emitted_at_ms; + self.last = Some(stamp); + } +} + +impl ZoneActivity { + /// Current status (empty before the first report). + pub fn status(&self) -> &str { + &self.status + } + + /// The public row. + pub fn row(&self) -> ZoneActivityStatus { + self.into() + } +} + +/// `zone_activity.record` input: what the zone reports about itself. +#[derive( + Debug, + Clone, + PartialEq, + Eq, + Default, + Serialize, + Deserialize, + distributed::CommandInput, + crate::FactCommand, +)] +#[fact(command = "zone_activity.record")] +pub struct RecordActivity { + /// [`ACTIVITY_ACTIVE`], [`ACTIVITY_DORMANT`] or [`ACTIVITY_HIBERNATED`]. + pub status: String, + /// Object activation id. + pub activation: String, + /// The activation restored a snapshot. + pub restored: bool, + /// Players present. + pub players: u32, + /// celld node (debug; empty when unknown). + pub node: String, + /// V8 isolate (debug). + pub isolate: String, +} + +/// The applied (or ignored) report. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, distributed::CommandOutput)] +pub struct ActivityApplied { + /// False when a later-emitted report already set the status. + pub applied: bool, + /// The status after the command. + pub status: String, +} + +fn rejected(message: impl std::fmt::Display) -> HandlerError { + HandlerError::Rejected(message.to_string()) +} + +async fn handle_record( + ctx: &CausalCommandContext<'_, ZoneActivity>, + input: RecordActivity, +) -> Result>, HandlerError> { + if ![ACTIVITY_ACTIVE, ACTIVITY_DORMANT, ACTIVITY_HIBERNATED].contains(&input.status.as_str()) { + return Err(rejected(format!("unknown activity `{}`", input.status))); + } + let stamp = session_stamp(ctx.session()) + .ok_or_else(|| rejected("activity reports are zone facts and need a fact stamp"))?; + if ctx.user_id()? != zone_principal(&stamp.zone_id) { + return Err(rejected("only the zone itself reports its activity")); + } + let repo = ctx.repo(); + let mut activity = match repo.get(&stamp.zone_id).await? { + Some(activity) => activity, + None => repo.create(), + }; + let newer = activity + .last + .as_ref() + .is_none_or(|last| last.stamp().emission_order(&stamp) == std::cmp::Ordering::Less); + if !newer { + let status = activity.status.clone(); + return repo.commit(activity)?.succeeded(ActivityApplied { + applied: false, + status, + }); + } + let status = input.status.clone(); + activity + .changed(stamp.zone_id.clone(), input, StampKey::of(&stamp)) + .map_err(rejected)?; + repo.publish_events() + .commit(activity)? + .succeeded(ActivityApplied { + applied: true, + status, + }) +} + +struct Record; +impl PortableCommand for Record +where + D: CausalRouteDependencies + Send + Sync + 'static, +{ + fn install(self, routes: Routes) -> Routes { + routes + .typed_command(typed_command::>( + RECORD, + )) + .handle(handle_record) + } +} + +/// Mount the zone-activity command on a `ZoneActivity` cell. +pub fn mount_zone_activity(cell: AggregateCell) -> AggregateCell { + cell.mount(Record) +} diff --git a/distributed_game/src/world/zone_lease.rs b/distributed_game/src/world/zone_lease.rs new file mode 100644 index 000000000..fa6c27f8e --- /dev/null +++ b/distributed_game/src/world/zone_lease.rs @@ -0,0 +1,460 @@ +//! Zone ownership as a cell: `ZoneLease:{zone_id}`. +//! +//! The lease of a zone lives in its own aggregate cell (celld in deployment, +//! the in-process reference host in tests) instead of a store private to the +//! zone server, so services learn when a zone server dies: +//! +//! | Command | Effect | Outward event | +//! |---|---|---| +//! | `zone_lease.acquire` | new holder, token + 1, expiry scheduled | `zone.activated` | +//! | `zone_lease.renew` | later expiry, expiry rescheduled | none (no heartbeat events) | +//! | `zone_lease.release` | no holder, expiry cancelled | `zone.released` | +//! | `zone_lease.expire` (schedule only) | no holder, if still expired | `zone.lease_expired` | +//! +//! Outward events carry the lease's post-transition [`ZoneLeaseStatus`] +//! (zone, holder, token, `active` / `released` / `expired`); the +//! [`zone_status`](super::zone_status) read model projects them. +//! +//! Fencing tokens increase on every acquisition and are never reset. Expiry +//! is declared by a schedule ([`distributed::schedule::Schedule`]): the +//! expiry command re-reads the lease and expires it only when the holder's +//! expiry has passed by the host clock, so a renewal that races it never +//! produces a false expiry. All times are the host's clock (`ctx.now()`), +//! never the caller's. The commands declare `Capability::Scheduling` and +//! `Capability::Clock`: they mount on aggregate cells (celld; the reference +//! host in tests) and on any backend that dispatches schedules. +//! +//! Callers must hold the `zone-host` role (an internal identity; the +//! commands are not routed through the public GraphQL edge). + +use std::time::{Duration, SystemTime}; + +use distributed::cell_host::AggregateCell; +use distributed::command::{typed_command, PreparedCommand, Succeeded}; +use distributed::microsvc::schedule::schedule_guard; +use distributed::microsvc::{ + CausalCommandContext, CausalRouteDependencies, HandlerError, PortableCommand, Routes, +}; +use distributed::schedule::{Capability, Schedule}; +use distributed::{sourced, Entity}; +use serde::{Deserialize, Serialize}; + +/// Aggregate type (cell `ZoneLease:{zone_id}`). +pub const ZONE_LEASE: &str = "ZoneLease"; +/// Role a zone server's internal session carries. +pub const ZONE_HOST_ROLE: &str = "zone-host"; +/// Acquire command. +pub const ACQUIRE: &str = "zone_lease.acquire"; +/// Renew command. +pub const RENEW: &str = "zone_lease.renew"; +/// Release command. +pub const RELEASE: &str = "zone_lease.release"; +/// Alarm-only expiry command. +pub const EXPIRE: &str = "zone_lease.expire"; +/// Rejection message prefix when another holder has the lease. +pub const HELD_PREFIX: &str = "held:"; +/// Rejection message when a claim is no longer the live one. +pub const LOST: &str = "lost"; +/// The expiry schedule's name. +pub const EXPIRY_ALARM: &str = "expiry"; + +/// [`ZoneLeaseStatus::status`] of a held lease. +pub const STATUS_ACTIVE: &str = "active"; +/// [`ZoneLeaseStatus::status`] after `zone.released`. +pub const STATUS_RELEASED: &str = "released"; +/// [`ZoneLeaseStatus::status`] after `zone.lease_expired`. +pub const STATUS_EXPIRED: &str = "expired"; + +/// The lease of one zone. +#[derive(Clone, Debug, Default, Serialize, Deserialize, distributed::Snapshot)] +pub struct ZoneLease { + entity: Entity, + holder: Option, + token: u64, + expires_at_ms: u64, + /// Holder of the last claim (kept after release and expiry). + #[serde(default)] + last_holder: String, + /// How the last claim ended (`released` / `expired`; empty while held + /// or never claimed). + #[serde(default)] + ended: String, +} + +/// The public state of a lease carried by its outward events (versioned +/// independently of the replay events): one `zone_leases` read-model row. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, distributed::DomainState)] +#[domain_state(version = 1)] +pub struct ZoneLeaseStatus { + /// Zone (the cell's stream id). + pub zone_id: String, + /// Holder of the current or, once ended, the last claim. + pub holder: String, + /// Fencing token of that claim. + pub token: u64, + /// [`STATUS_ACTIVE`], [`STATUS_RELEASED`] or [`STATUS_EXPIRED`]. + pub status: String, +} + +impl From<&ZoneLease> for ZoneLeaseStatus { + fn from(lease: &ZoneLease) -> Self { + Self { + zone_id: lease.entity.id().to_string(), + holder: lease.last_holder.clone(), + token: lease.token, + status: if lease.holder.is_some() { + STATUS_ACTIVE.to_string() + } else { + lease.ended.clone() + }, + } + } +} + +#[sourced( + entity, + aggregate_type = "ZoneLease", + events = "ZoneLeaseEvent", + domain_state = ZoneLeaseStatus +)] +impl ZoneLease { + #[event("zone.activated", version = 1, domain)] + fn activated(&mut self, zone_id: String, holder: String, token: u64, expires_at_ms: u64) { + if self.entity.id().is_empty() { + self.entity.set_id(zone_id); + } + self.last_holder = holder.clone(); + self.holder = Some(holder); + self.token = token; + self.expires_at_ms = expires_at_ms; + self.ended.clear(); + } + + #[event("zone_lease.renewed", version = 1)] + fn renewed(&mut self, expires_at_ms: u64) { + self.expires_at_ms = expires_at_ms; + } + + #[event("zone.released", version = 1, domain)] + fn released(&mut self, zone_id: String, holder: String, token: u64) { + let _ = (zone_id, holder, token); + self.holder = None; + self.ended = STATUS_RELEASED.to_string(); + } + + #[event("zone.lease_expired", version = 1, domain)] + fn lease_expired(&mut self, zone_id: String, holder: String, token: u64) { + let _ = (zone_id, holder, token); + self.holder = None; + self.ended = STATUS_EXPIRED.to_string(); + } +} + +impl ZoneLease { + /// Current holder, if any. + pub fn holder(&self) -> Option<&str> { + self.holder.as_deref() + } + + /// Latest fencing token (kept after release and expiry). + pub fn token(&self) -> u64 { + self.token + } + + /// Expiry of the current holder (epoch ms, cell clock). + pub fn expires_at_ms(&self) -> u64 { + self.expires_at_ms + } +} + +/// `zone_lease.acquire` input. +#[derive(Debug, Serialize, Deserialize, distributed::CommandInput)] +pub struct AcquireInput { + pub zone_id: String, + pub holder: String, + pub ttl_ms: u64, +} + +/// `zone_lease.renew` input. +#[derive(Debug, Serialize, Deserialize, distributed::CommandInput)] +pub struct RenewInput { + pub zone_id: String, + pub holder: String, + pub token: u64, + pub ttl_ms: u64, +} + +/// `zone_lease.release` input. +#[derive(Debug, Serialize, Deserialize, distributed::CommandInput)] +pub struct ReleaseInput { + pub zone_id: String, + pub holder: String, + pub token: u64, +} + +/// `zone_lease.expire` input (scheduled by the lease itself). +#[derive(Debug, Serialize, Deserialize, distributed::CommandInput)] +pub struct ExpireInput { + pub zone_id: String, +} + +/// A held (or released) claim. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, distributed::CommandOutput)] +pub struct ClaimPayload { + pub zone_id: String, + pub holder: String, + pub token: u64, + pub expires_at_ms: u64, +} + +/// What an expiry schedule did. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, distributed::CommandOutput)] +pub struct ExpiryPayload { + pub expired: bool, +} + +/// Map a rejected lease command's message to an +/// [`OwnershipError`](super::OwnershipError). +pub fn ownership_error(message: &str) -> super::OwnershipError { + let message = message.strip_prefix("rejected: ").unwrap_or(message); + if let Some(holder) = message.strip_prefix(HELD_PREFIX) { + super::OwnershipError::Held { + holder: holder.to_string(), + } + } else if message == LOST { + super::OwnershipError::Lost + } else { + super::OwnershipError::Backend(message.to_string()) + } +} + +fn rejected(message: impl std::fmt::Display) -> HandlerError { + HandlerError::Rejected(message.to_string()) +} + +fn is_zone_host(ctx: &CausalCommandContext<'_, ZoneLease>) -> bool { + ctx.session().has_role(ZONE_HOST_ROLE) +} + +fn now_ms(ctx: &CausalCommandContext<'_, ZoneLease>) -> Result { + ctx.now()? + .duration_since(SystemTime::UNIX_EPOCH) + .map(|now| now.as_millis() as u64) + .map_err(|_| rejected("host clock is before the Unix epoch")) +} + +fn ttl(ttl_ms: u64) -> Result { + if ttl_ms == 0 || ttl_ms > 24 * 60 * 60 * 1_000 { + return Err(rejected("ttl_ms must be within 1..=86400000")); + } + Ok(ttl_ms) +} + +fn validate(zone_id: &str, holder: &str) -> Result<(), HandlerError> { + if zone_id.is_empty() || holder.is_empty() { + return Err(rejected("zone_id and holder must not be empty")); + } + Ok(()) +} + +fn expiry_schedule(zone_id: &str, expires_at_ms: u64) -> Result { + Schedule::at( + EXPIRY_ALARM, + SystemTime::UNIX_EPOCH + Duration::from_millis(expires_at_ms), + EXPIRE, + &ExpireInput { + zone_id: zone_id.to_string(), + }, + ) + .map_err(rejected) +} + +async fn handle_acquire( + ctx: &CausalCommandContext<'_, ZoneLease>, + input: AcquireInput, +) -> Result>, HandlerError> { + validate(&input.zone_id, &input.holder)?; + let ttl = ttl(input.ttl_ms)?; + let now = now_ms(ctx)?; + let repo = ctx.repo(); + let mut lease = match repo.get(&input.zone_id).await? { + Some(lease) => lease, + None => repo.create(), + }; + match lease.holder() { + // The holder re-acquiring its live claim gets it back unchanged. + Some(holder) if holder == input.holder => { + let claim = ClaimPayload { + zone_id: input.zone_id, + holder: input.holder, + token: lease.token, + expires_at_ms: lease.expires_at_ms, + }; + return repo.commit(lease)?.succeeded(claim); + } + // Held until the expiry schedule declares otherwise. + Some(holder) => return Err(rejected(format!("{HELD_PREFIX}{holder}"))), + None => {} + } + let token = lease.token + 1; + let expires_at_ms = now + ttl; + lease + .activated( + input.zone_id.clone(), + input.holder.clone(), + token, + expires_at_ms, + ) + .map_err(rejected)?; + ctx.schedule(expiry_schedule(&input.zone_id, expires_at_ms)?)?; + repo.publish_events() + .commit(lease)? + .succeeded(ClaimPayload { + zone_id: input.zone_id, + holder: input.holder, + token, + expires_at_ms, + }) +} + +async fn handle_renew( + ctx: &CausalCommandContext<'_, ZoneLease>, + input: RenewInput, +) -> Result>, HandlerError> { + validate(&input.zone_id, &input.holder)?; + let ttl = ttl(input.ttl_ms)?; + let now = now_ms(ctx)?; + let repo = ctx.repo(); + let mut lease = repo + .get(&input.zone_id) + .await? + .ok_or_else(|| rejected(LOST))?; + if lease.holder() != Some(input.holder.as_str()) || lease.token != input.token { + return Err(rejected(LOST)); + } + let expires_at_ms = now + ttl; + lease.renewed(expires_at_ms).map_err(rejected)?; + ctx.schedule(expiry_schedule(&input.zone_id, expires_at_ms)?)?; + // Internal state only: no outward event, so no outbox row. + repo.commit(lease)?.succeeded(ClaimPayload { + zone_id: input.zone_id, + holder: input.holder, + token: input.token, + expires_at_ms, + }) +} + +async fn handle_release( + ctx: &CausalCommandContext<'_, ZoneLease>, + input: ReleaseInput, +) -> Result>, HandlerError> { + validate(&input.zone_id, &input.holder)?; + let repo = ctx.repo(); + let mut lease = repo + .get(&input.zone_id) + .await? + .ok_or_else(|| rejected(LOST))?; + let claim = ClaimPayload { + zone_id: input.zone_id.clone(), + holder: input.holder.clone(), + token: input.token, + expires_at_ms: lease.expires_at_ms, + }; + if lease.holder() != Some(input.holder.as_str()) || lease.token != input.token { + // Releasing a claim that is already gone is a no-op. + return repo.commit(lease)?.succeeded(claim); + } + lease + .released(input.zone_id, input.holder, input.token) + .map_err(rejected)?; + ctx.cancel_schedule(EXPIRY_ALARM)?; + repo.publish_events().commit(lease)?.succeeded(claim) +} + +async fn handle_expire( + ctx: &CausalCommandContext<'_, ZoneLease>, + input: ExpireInput, +) -> Result>, HandlerError> { + let now = now_ms(ctx)?; + let repo = ctx.repo(); + let Some(mut lease) = repo.get(&input.zone_id).await? else { + return Err(rejected("no lease")); + }; + let expired = match lease.holder.clone() { + Some(holder) if now >= lease.expires_at_ms => { + let token = lease.token; + lease + .lease_expired(input.zone_id, holder, token) + .map_err(rejected)?; + true + } + // Renewed (or released) after this schedule was read: not expired. + _ => false, + }; + if expired { + repo.publish_events() + .commit(lease)? + .succeeded(ExpiryPayload { expired }) + } else { + repo.commit(lease)?.succeeded(ExpiryPayload { expired }) + } +} + +macro_rules! lease_command { + ($name:ident, $command:expr, $input:ty, $output:ty, $guard:expr, $handler:expr) => { + struct $name; + impl PortableCommand for $name + where + D: CausalRouteDependencies + Send + Sync + 'static, + { + fn install(self, routes: Routes) -> Routes { + routes + .typed_command(typed_command::<$input, Succeeded<$output>>($command)) + .requires(Capability::Scheduling) + .requires(Capability::Clock) + .guarded($guard, $handler) + } + } + }; +} + +lease_command!( + Acquire, + ACQUIRE, + AcquireInput, + ClaimPayload, + is_zone_host, + handle_acquire +); +lease_command!( + Renew, + RENEW, + RenewInput, + ClaimPayload, + is_zone_host, + handle_renew +); +lease_command!( + Release, + RELEASE, + ReleaseInput, + ClaimPayload, + is_zone_host, + handle_release +); +lease_command!( + Expire, + EXPIRE, + ExpireInput, + ExpiryPayload, + schedule_guard::, + handle_expire +); + +/// Mount every zone-lease command on a `ZoneLease` cell. +pub fn mount_zone_lease(cell: AggregateCell) -> AggregateCell { + cell.mount(Acquire) + .mount(Renew) + .mount(Release) + .mount(Expire) +} diff --git a/distributed_game/src/world/zone_state.rs b/distributed_game/src/world/zone_state.rs new file mode 100644 index 000000000..14dd7b838 --- /dev/null +++ b/distributed_game/src/world/zone_state.rs @@ -0,0 +1,610 @@ +//! Hibernated zone state as a cell: `ZoneState:{zone_id}`. +//! +//! A sleeping zone is a sleeping Durable Object: its last snapshot lives in +//! its own aggregate cell on celld (the in-process reference host in unit +//! tests), written and read by zone servers through +//! `celld::CellZoneStateStore`. +//! +//! | Command | Effect | +//! |---|---| +//! | `zone_state.save` | store the snapshot if `token` >= the stored token | +//! | `zone_state.delete` | drop the snapshot if `token` >= the stored token | +//! +//! Fencing equals the [`ZoneStateStore`](super::ZoneStateStore) contract: an +//! older token is rejected with `stale:{current}`, an equal one is accepted, +//! and the highest token survives a delete. +//! +//! **Size.** A snapshot up to [`ZONE_STATE_INLINE_MAX`] bytes is stored in +//! the cell itself (in the `zone_state.saved` event and the aggregate +//! snapshot). A larger one goes to object storage: the worker route +//! (`celld_worker::fetch`, feature `cloudflare-workers`) writes the bytes to an R2 bucket +//! binding of celld (the fleet bucket; RustFS in the Hops stack) under +//! `zone-state/{zone}/{token}-{sha256}` *before* the command, and the cell +//! records only `{key, sha256, len}`. The blob a save or delete supersedes +//! is deleted after the commit; a save refused as stale deletes its own +//! upload. Loads verify the length and digest. +//! +//! Every save is one small event (inline bytes or a blob reference); cells +//! load from the aggregate snapshot, which is refreshed on every commit. +//! +//! Both commands publish the post-command [`ZoneSnapshotStatus`] (zone, +//! token, whether a snapshot is stored, its content version and size, never +//! the bytes) as `zone_state.saved` / `zone_state.deleted` domain events; +//! the [`zone_status`](super::zone_status) read model projects them, so +//! "is this zone asleep with state?" is answered without opening its cell. +//! +//! Callers must hold the `zone-host` role (an internal identity on the +//! authenticated internal path). + +use distributed::cell_host::AggregateCell; +use distributed::command::{typed_command, PreparedCommand, Succeeded}; +use distributed::microsvc::{ + CausalCommandContext, CausalRouteDependencies, HandlerError, PortableCommand, Routes, +}; +use distributed::{sourced, Entity}; +use serde::{Deserialize, Serialize}; + +pub use super::zone_lease::ZONE_HOST_ROLE; + +/// Aggregate type (cell `ZoneState:{zone_id}`). +pub const ZONE_STATE: &str = "ZoneState"; +/// Save command. +pub const SAVE: &str = "zone_state.save"; +/// Delete command. +pub const DELETE: &str = "zone_state.delete"; +/// Rejection prefix of a stale token (`stale:{current}`). +pub const STALE_PREFIX: &str = "stale:"; +/// Largest snapshot kept inline in the cell; larger ones go to object +/// storage. +pub const ZONE_STATE_INLINE_MAX: usize = 64 * 1024; + +/// A snapshot stored in object storage. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, distributed::CommandInput)] +pub struct BlobRef { + /// Object key. + pub key: String, + /// Lowercase hex SHA-256 of the bytes. + pub sha256: String, + /// Length in bytes. + pub len: u64, +} + +/// Where a snapshot's bytes are. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum SnapshotBytes { + /// In the cell. + Inline(Vec), + /// In object storage. + Blob(BlobRef), +} + +impl SnapshotBytes { + fn blob_key(&self) -> Option<&str> { + match self { + Self::Blob(blob) => Some(&blob.key), + Self::Inline(_) => None, + } + } +} + +/// The hibernated state of one zone. +#[derive(Clone, Debug, Default, Serialize, Deserialize, distributed::Snapshot)] +pub struct ZoneState { + entity: Entity, + token: u64, + content_version: String, + bytes: Option, +} + +/// The public state of a zone's hibernation slot carried by its outward +/// events: one `zone_snapshots` read-model row (no snapshot bytes). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, distributed::DomainState)] +#[domain_state(version = 1)] +pub struct ZoneSnapshotStatus { + /// Zone (the cell's stream id). + pub zone_id: String, + /// Highest token seen. + pub token: u64, + /// A snapshot is stored. + pub stored: bool, + /// Content version of the stored snapshot (empty when none). + pub content_version: String, + /// Size of the stored snapshot in bytes (0 when none). + pub bytes: u64, +} + +impl From<&ZoneState> for ZoneSnapshotStatus { + fn from(state: &ZoneState) -> Self { + let bytes = match &state.bytes { + Some(SnapshotBytes::Inline(bytes)) => bytes.len() as u64, + Some(SnapshotBytes::Blob(blob)) => blob.len, + None => 0, + }; + Self { + zone_id: state.entity.id().to_string(), + token: state.token, + stored: state.bytes.is_some(), + content_version: if state.bytes.is_some() { + state.content_version.clone() + } else { + String::new() + }, + bytes, + } + } +} + +#[sourced( + entity, + aggregate_type = "ZoneState", + events = "ZoneStateEvent", + domain_state = ZoneSnapshotStatus +)] +impl ZoneState { + #[event("zone_state.saved", version = 1, domain)] + fn saved( + &mut self, + zone_id: String, + token: u64, + content_version: String, + bytes: SnapshotBytes, + ) { + if self.entity.id().is_empty() { + self.entity.set_id(zone_id); + } + self.token = token; + self.content_version = content_version; + self.bytes = Some(bytes); + } + + #[event("zone_state.deleted", version = 1, domain)] + fn deleted(&mut self, zone_id: String, token: u64) { + if self.entity.id().is_empty() { + self.entity.set_id(zone_id); + } + self.token = token; + self.bytes = None; + } +} + +impl ZoneState { + /// Highest token seen (kept after a delete). + pub fn token(&self) -> u64 { + self.token + } + + /// Content version of the stored snapshot. + pub fn content_version(&self) -> &str { + &self.content_version + } + + /// The stored snapshot, if any. + pub fn bytes(&self) -> Option<&SnapshotBytes> { + self.bytes.as_ref() + } +} + +/// `zone_state.save` input: exactly one of `inline_b64` (standard base64, +/// at most [`ZONE_STATE_INLINE_MAX`] bytes decoded) and `blob`. +#[derive(Debug, Serialize, Deserialize, distributed::CommandInput)] +pub struct SaveInput { + pub zone_id: String, + pub token: u64, + pub content_version: String, + pub inline_b64: Option, + pub blob: Option, +} + +/// `zone_state.delete` input. +#[derive(Debug, Serialize, Deserialize, distributed::CommandInput)] +pub struct DeleteInput { + pub zone_id: String, + pub token: u64, +} + +/// Outcome of a save or delete. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, distributed::CommandOutput)] +pub struct StatePayload { + pub zone_id: String, + pub token: u64, + /// Object key the command superseded (delete it after the commit). + pub superseded_blob: Option, +} + +/// Map a rejected command's message to a stale token, if it is one. +pub fn stale_current(message: &str) -> Option { + let message = message.strip_prefix("rejected: ").unwrap_or(message); + message.strip_prefix(STALE_PREFIX)?.parse().ok() +} + +fn rejected(message: impl std::fmt::Display) -> HandlerError { + HandlerError::Rejected(message.to_string()) +} + +fn is_zone_host(ctx: &CausalCommandContext<'_, ZoneState>) -> bool { + ctx.session().has_role(ZONE_HOST_ROLE) +} + +async fn fenced( + ctx: &CausalCommandContext<'_, ZoneState>, + zone_id: &str, + token: u64, +) -> Result, HandlerError> { + if zone_id.is_empty() { + return Err(rejected("zone_id must not be empty")); + } + let repo = ctx.repo(); + let state = match repo.get(zone_id).await? { + Some(state) => state, + None => repo.create(), + }; + if state.token > token { + return Err(rejected(format!("{STALE_PREFIX}{}", state.token))); + } + Ok(state) +} + +async fn handle_save( + ctx: &CausalCommandContext<'_, ZoneState>, + input: SaveInput, +) -> Result>, HandlerError> { + let bytes = match (input.inline_b64, input.blob) { + (Some(inline), None) => { + use base64::Engine as _; + let bytes = base64::engine::general_purpose::STANDARD + .decode(inline) + .map_err(|_| rejected("inline_b64 is not base64"))?; + if bytes.len() > ZONE_STATE_INLINE_MAX { + return Err(rejected(format!( + "inline snapshots are at most {ZONE_STATE_INLINE_MAX} bytes" + ))); + } + SnapshotBytes::Inline(bytes) + } + (None, Some(blob)) => { + let hex = blob.sha256.len() == 64 && blob.sha256.bytes().all(|b| b.is_ascii_hexdigit()); + if blob.key.is_empty() || !hex { + return Err(rejected("blob needs a key and a SHA-256")); + } + SnapshotBytes::Blob(blob) + } + _ => return Err(rejected("exactly one of inline_b64 and blob")), + }; + let mut state = fenced(ctx, &input.zone_id, input.token).await?; + let previous = state + .bytes + .as_ref() + .and_then(|b| b.blob_key()) + .map(str::to_string); + let superseded = previous.filter(|key| Some(key.as_str()) != bytes.blob_key()); + state + .saved( + input.zone_id.clone(), + input.token, + input.content_version, + bytes, + ) + .map_err(rejected)?; + ctx.repo() + .publish_events() + .commit(state)? + .succeeded(StatePayload { + zone_id: input.zone_id, + token: input.token, + superseded_blob: superseded, + }) +} + +async fn handle_delete( + ctx: &CausalCommandContext<'_, ZoneState>, + input: DeleteInput, +) -> Result>, HandlerError> { + let mut state = fenced(ctx, &input.zone_id, input.token).await?; + let superseded = state + .bytes + .as_ref() + .and_then(|b| b.blob_key()) + .map(str::to_string); + state + .deleted(input.zone_id.clone(), input.token) + .map_err(rejected)?; + ctx.repo() + .publish_events() + .commit(state)? + .succeeded(StatePayload { + zone_id: input.zone_id, + token: input.token, + superseded_blob: superseded, + }) +} + +struct Save; +impl PortableCommand for Save +where + D: CausalRouteDependencies + Send + Sync + 'static, +{ + fn install(self, routes: Routes) -> Routes { + routes + .typed_command(typed_command::>(SAVE)) + .guarded(is_zone_host, handle_save) + } +} + +struct Delete; +impl PortableCommand for Delete +where + D: CausalRouteDependencies + Send + Sync + 'static, +{ + fn install(self, routes: Routes) -> Routes { + routes + .typed_command(typed_command::>( + DELETE, + )) + .guarded(is_zone_host, handle_delete) + } +} + +/// Mount both zone-state commands on a `ZoneState` cell. +pub fn mount_zone_state(cell: AggregateCell) -> AggregateCell { + cell.mount(Save).mount(Delete) +} + +/// Lowercase hex SHA-256. +pub fn sha256_hex(bytes: &[u8]) -> String { + use sha2::{Digest, Sha256}; + Sha256::digest(bytes) + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +/// Object key of a large snapshot. +pub fn blob_key(zone_id: &str, token: u64, sha256: &str) -> String { + format!("zone-state/{zone_id}/{token}-{sha256}") +} + +/// celld worker glue: the `zone-state/{zone}` HTTP surface over a +/// `ZoneState` cell and an R2 bucket binding (see the module docs). The +/// caller authenticates the internal secret first. +#[cfg(all(feature = "cloudflare-workers", target_arch = "wasm32"))] +pub mod celld_worker { + use super::*; + use ::worker::{Bucket, Method, Request, Response, Result}; + use base64::Engine as _; + use distributed::cell_host::{ + CausalDispatchError, CellCommandIdentity, CellWaitPathRequest, + CELL_PRINCIPAL_PARTITION_HEADER, CELL_SERVICE_ID_HEADER, + }; + use distributed::microsvc::Session; + use serde_json::{json, Value}; + + /// Wire input of a save from `celld::CellZoneStateStore`. + #[derive(Deserialize)] + struct WireSave { + zone_id: String, + token: u64, + content_version: String, + state_b64: String, + } + + fn json_status(body: Value, status: u16) -> Result { + Ok(Response::from_json(&body)?.with_status(status)) + } + + fn error_response(error: CausalDispatchError) -> Result { + json_status( + json!({ "error": error.client_message(), "code": error.code() }), + error.status_code(), + ) + } + + /// The R2 bucket binding `name`. celld's R2 binding is not an instance + /// of the Workers runtime's `R2Bucket` class, which `Env::bucket` + /// checks for, but it has the same methods; take it unchecked. + pub fn bucket(env: &::worker::Env, name: &str) -> Result { + use ::worker::wasm_bindgen::{JsCast, JsValue}; + let env: &JsValue = env.as_ref(); + let binding = ::worker::js_sys::Reflect::get(env, &JsValue::from_str(name)) + .map_err(|_| ::worker::Error::RustError(format!("no binding `{name}`")))?; + if binding.is_undefined() { + return Err(::worker::Error::RustError(format!( + "R2 bucket binding `{name}` is not configured" + ))); + } + Ok(binding.unchecked_into::()) + } + + /// `GET /zone-state/{zone}` → `{state: null | {token, content_version, + /// state_b64}}`; `POST /zone-state/{zone}/zone_state.save|delete`. + pub async fn fetch( + cell: &AggregateCell, + bucket: &Bucket, + mut req: Request, + ) -> Result { + let url = req.url()?; + let command = url + .path() + .split('/') + .filter(|part| !part.is_empty()) + .nth(2) + .map(str::to_string); + match (req.method(), command.as_deref()) { + (Method::Get, None) => load(cell, bucket).await, + (Method::Post, Some(SAVE)) | (Method::Post, Some(DELETE)) => { + let command = command.unwrap(); + let body: Value = match req.json().await { + Ok(body) => body, + Err(_) => { + return error_response(CausalDispatchError::BadRequest( + "invalid JSON".into(), + )) + } + }; + let parsed = match CellWaitPathRequest::parse(body) { + Ok(parsed) => parsed, + Err(error) => return error_response(CausalDispatchError::BadRequest(error)), + }; + let header = |name: &str| req.headers().get(name).ok().flatten(); + let identity = match ( + header(CELL_SERVICE_ID_HEADER), + header(CELL_PRINCIPAL_PARTITION_HEADER), + ) { + (Some(service), Some(partition)) => { + match CellCommandIdentity::new(service, partition, &parsed.command_id) { + Ok(identity) => identity, + Err(error) => return error_response(error), + } + } + _ => return error_response(CausalDispatchError::Unauthorized), + }; + let mut session = Session::new(); + for key in [distributed::USER_ID_KEY, distributed::microsvc::ROLE_KEY] { + if let Some(value) = header(key) { + session.set(key, value); + } + } + if command == SAVE { + save(cell, bucket, &identity, parsed.input, session).await + } else { + dispatch(cell, bucket, DELETE, &identity, parsed.input, session, None).await + } + } + _ => json_status(json!({ "error": "not found" }), 404), + } + } + + async fn load(cell: &AggregateCell, bucket: &Bucket) -> Result { + let state = cell + .load() + .await + .map_err(|error| ::worker::Error::RustError(error.to_string()))?; + let Some(state) = state else { + return json_status(json!({ "state": null }), 200); + }; + let bytes = match state.bytes() { + None => return json_status(json!({ "state": null, "token": state.token() }), 200), + Some(SnapshotBytes::Inline(bytes)) => bytes.clone(), + Some(SnapshotBytes::Blob(blob)) => { + let object = bucket.get(blob.key.clone()).execute().await?; + let Some(body) = object.as_ref().and_then(|object| object.body()) else { + return error_response(CausalDispatchError::Internal(format!( + "zone-state blob {} is missing", + blob.key + ))); + }; + let bytes = body.bytes().await?; + if bytes.len() as u64 != blob.len || sha256_hex(&bytes) != blob.sha256 { + return error_response(CausalDispatchError::Internal(format!( + "zone-state blob {} does not match its digest", + blob.key + ))); + } + bytes + } + }; + json_status( + json!({ "state": { + "token": state.token(), + "content_version": state.content_version(), + "state_b64": base64::engine::general_purpose::STANDARD.encode(bytes), + }}), + 200, + ) + } + + async fn save( + cell: &AggregateCell, + bucket: &Bucket, + identity: &CellCommandIdentity, + input: Value, + session: Session, + ) -> Result { + let wire: WireSave = match serde_json::from_value(input) { + Ok(wire) => wire, + Err(error) => { + return error_response(CausalDispatchError::BadRequest(format!( + "zone_state.save input: {error}" + ))) + } + }; + let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(&wire.state_b64) else { + return error_response(CausalDispatchError::BadRequest( + "state_b64 is not base64".into(), + )); + }; + let (command_input, uploaded) = if bytes.len() <= ZONE_STATE_INLINE_MAX { + ( + json!({ + "zone_id": wire.zone_id, "token": wire.token, + "content_version": wire.content_version, + "inline_b64": wire.state_b64, "blob": null, + }), + None, + ) + } else { + let sha256 = sha256_hex(&bytes); + let key = blob_key(&wire.zone_id, wire.token, &sha256); + let len = bytes.len() as u64; + bucket.put(key.clone(), bytes).execute().await?; + ( + json!({ + "zone_id": wire.zone_id, "token": wire.token, + "content_version": wire.content_version, "inline_b64": null, + "blob": { "key": key, "sha256": sha256, "len": len }, + }), + Some(key), + ) + }; + dispatch( + cell, + bucket, + SAVE, + identity, + command_input, + session, + uploaded, + ) + .await + } + + async fn dispatch( + cell: &AggregateCell, + bucket: &Bucket, + command: &str, + identity: &CellCommandIdentity, + input: Value, + session: Session, + uploaded: Option, + ) -> Result { + match cell + .dispatch_idempotent(command, identity, input, session) + .await + { + Ok(dispatch) => { + let superseded = dispatch + .payload() + .get("superseded_blob") + .and_then(Value::as_str) + .map(str::to_string); + if let Some(key) = superseded { + if let Err(error) = bucket.delete(key.clone()).await { + ::worker::console_error!("superseded zone-state blob {key}: {error}"); + } + } + json_status(dispatch.wait_path_wire(), 200) + } + Err(error) => { + if let CausalDispatchError::Internal(message) = &error { + ::worker::console_error!("zone-state {command}: {message}"); + } + // Refused (stale or invalid): the upload is nobody's. + if let Some(key) = uploaded { + if let Err(error) = bucket.delete(key.clone()).await { + ::worker::console_error!("refused zone-state blob {key}: {error}"); + } + } + error_response(error) + } + } + } +} diff --git a/distributed_game/src/world/zone_status.rs b/distributed_game/src/world/zone_status.rs new file mode 100644 index 000000000..5ac3d4f12 --- /dev/null +++ b/distributed_game/src/world/zone_status.rs @@ -0,0 +1,353 @@ +//! Zone status read model: which zones are active (and on which holder), +//! which are asleep with a hibernation snapshot, and which never ran — +//! answered from SQL rows instead of opening one cell per zone. +//! +//! Projected from the outward events of the per-zone cells: +//! +//! | Source cell | Events | Row | +//! |---|---|---| +//! | [`ZoneLease`](super::zone_lease::ZoneLease) | `zone.activated`, `zone.released`, `zone.lease_expired` | [`ZoneLeases`] (`zone_leases`) | +//! | [`ZoneState`](super::zone_state::ZoneState) | `zone_state.saved`, `zone_state.deleted` | [`ZoneSnapshots`] (`zone_snapshots`) | +//! | [`ZoneActivity`](super::zone_activity::ZoneActivity) (zones hosted as celld objects) | `zone.activity_changed` | [`ZoneActivities`] (`zone_activities`) | +//! +//! Each event carries its cell's post-transition state, so a row is an +//! upsert of the body ([`ZONE_LEASES`], [`ZONE_SNAPSHOTS`], +//! [`ZONE_ACTIVITIES`]); the projector runtime orders and deduplicates per +//! stream. [`ZoneStatus::of`] combines a zone's rows: a zone hosted as a +//! celld object ([`crate::celld_zone`]) has only an activity row (active / +//! dormant / hibernated); a zone on the native multi-host server has lease +//! and snapshot rows. Mount [`projectors`] on a consumer service (any read +//! model store: SQLite, Postgres) fed by the bus the cells' outbox reaches. +//! +//! The read model is eventually consistent: it is for views (world maps, +//! minimaps, dashboards), never for decisions a zone server must fence — +//! ownership and restore always go to the cells. + +use distributed::graphql::SurfaceProjector; +use distributed::projection::lower::{EventualOnly, ProjectionDescriptor}; +use distributed::{ + mutation_file, LocalProjectionMountsBuilder, Mutation, ReadModel, ReadModelCatalog, + RelationalReadModel, +}; +use serde::{Deserialize, Serialize}; + +use super::zone_activity::{ + ZoneActivityActivityChangedDomainEvent, ACTIVITY_ACTIVE, ACTIVITY_DORMANT, ACTIVITY_HIBERNATED, +}; +use super::zone_lease::{ + ZoneLeaseActivatedDomainEvent, ZoneLeaseLeaseExpiredDomainEvent, ZoneLeaseReleasedDomainEvent, + STATUS_ACTIVE, +}; +use super::zone_state::{ZoneStateDeletedDomainEvent, ZoneStateSavedDomainEvent}; + +/// Application of the read model (catalog and projector owner; the +/// consumer service is named after it). +pub const APPLICATION: &str = "zone-status"; +/// Projector of [`ZoneLeases`]. +pub const LEASES_PROJECTOR: &str = "project_zone_leases"; +/// Projector of [`ZoneSnapshots`]. +pub const SNAPSHOTS_PROJECTOR: &str = "project_zone_snapshots"; +/// Epoch of [`ZONE_LEASES`] (bump to rebuild from the bus log). +pub const LEASES_EPOCH: &str = "zone-leases-v1"; +/// Epoch of [`ZONE_SNAPSHOTS`]. +pub const SNAPSHOTS_EPOCH: &str = "zone-snapshots-v1"; +/// Projector of [`ZoneActivities`]. +pub const ACTIVITIES_PROJECTOR: &str = "project_zone_activities"; +/// Epoch of [`ZONE_ACTIVITIES`]. +pub const ACTIVITIES_EPOCH: &str = "zone-activities-v1"; + +/// One `zone_leases` row: the last lease transition of a zone +/// ([`ZoneLeaseStatus`](super::zone_lease::ZoneLeaseStatus); the type is +/// named after its table, as `mutation_file!` requires). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ReadModel)] +#[table("zone_leases")] +pub struct ZoneLeases { + /// Zone id. + #[id("zone_id")] + pub zone_id: String, + /// Holder of the current (or last) claim. + pub holder: String, + /// Its fencing token. + pub token: i64, + /// `active`, `released` or `expired`. + pub status: String, +} + +/// One `zone_snapshots` row: the hibernation slot of a zone +/// ([`ZoneSnapshotStatus`](super::zone_state::ZoneSnapshotStatus)). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ReadModel)] +#[table("zone_snapshots")] +pub struct ZoneSnapshots { + /// Zone id. + #[id("zone_id")] + pub zone_id: String, + /// Highest token seen. + pub token: i64, + /// A snapshot is stored. + pub stored: bool, + /// Content version of the stored snapshot. + pub content_version: String, + /// Snapshot size in bytes. + pub bytes: i64, +} + +/// One `zone_activities` row: what a zone hosted as a celld object last +/// reported about itself +/// ([`ZoneActivityStatus`](super::zone_activity::ZoneActivityStatus)). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, ReadModel)] +#[table("zone_activities")] +pub struct ZoneActivities { + /// Zone id. + #[id("zone_id")] + pub zone_id: String, + /// `active`, `dormant` or `hibernated`. + pub status: String, + /// Object activation id. + pub activation: String, + /// The activation restored a snapshot. + pub restored: bool, + /// Players when reported. + pub players: i64, + /// celld node of the activation (debug; empty when unknown). + pub node: String, + /// V8 isolate of the activation (debug). + pub isolate: String, + /// Activations seen. + pub activations: i64, + /// When the zone reported it (Unix ms). + pub changed_at_ms: i64, +} + +/// Upsert a [`ZoneActivities`] row from a `zone.activity_changed` body. +#[allow(non_snake_case)] +pub fn SaveZoneActivity() -> Mutation<()> { + mutation_file!("src/world/mutations/save_zone_activity.mutation.graphql") +} + +/// Upsert a [`ZoneLeases`] from a lease event's state body. +#[allow(non_snake_case)] +pub fn SaveZoneLease() -> Mutation<()> { + mutation_file!("src/world/mutations/save_zone_lease.mutation.graphql") +} + +/// Upsert a [`ZoneSnapshots`] from a zone-state event's state body. +#[allow(non_snake_case)] +pub fn SaveZoneSnapshot() -> Mutation<()> { + mutation_file!("src/world/mutations/save_zone_snapshot.mutation.graphql") +} + +distributed::projection! { + pub const ZONE_LEASES: ProjectionDescriptor = { + name: "project_zone_leases", + version: 1, + epoch: "zone-leases-v1", + model: ZoneLeases, + on { + events: [ + ZoneLeaseActivatedDomainEvent, + ZoneLeaseReleasedDomainEvent, + ZoneLeaseLeaseExpiredDomainEvent, + ], + mutation: SaveZoneLease, + input: { lease: body }, + }, + }; +} + +distributed::projection! { + pub const ZONE_SNAPSHOTS: ProjectionDescriptor = { + name: "project_zone_snapshots", + version: 1, + epoch: "zone-snapshots-v1", + model: ZoneSnapshots, + on { + events: [ZoneStateSavedDomainEvent, ZoneStateDeletedDomainEvent], + mutation: SaveZoneSnapshot, + input: { snapshot: body }, + }, + }; +} + +distributed::projection! { + pub const ZONE_ACTIVITIES: ProjectionDescriptor = { + name: "project_zone_activities", + version: 1, + epoch: "zone-activities-v1", + model: ZoneActivities, + on { + events: [ZoneActivityActivityChangedDomainEvent], + mutation: SaveZoneActivity, + input: { activity: body }, + }, + }; +} + +/// Physical read-model catalog (`zone_leases`, `zone_snapshots`, +/// `zone_activities`). +pub fn read_model_catalog() -> ReadModelCatalog { + ReadModelCatalog::new(APPLICATION) + .table_schema(ZoneLeases::schema().clone()) + .table_schema(ZoneSnapshots::schema().clone()) + .table_schema(ZoneActivities::schema().clone()) +} + +/// The modeled projector of [`ZoneActivities`] alone (a consumer that +/// shows celld-hosted zones, e.g. a minimap service), applying +/// [`ZONE_ACTIVITIES`]. Mount it on a consumer service named +/// [`APPLICATION`] (or any name of the caller's, with its own cursor). +pub fn activity_projector() -> SurfaceProjector { + activity_projector_for(APPLICATION) +} + +/// [`activity_projector`] owned by `application` (when the consumer service +/// is not named [`APPLICATION`]). +pub fn activity_projector_for(application: &str) -> SurfaceProjector { + LocalProjectionMountsBuilder::new(application, "ordered-domain-events") + .expect("projection source") + .eventual_model::( + ACTIVITIES_PROJECTOR, + ZONE_ACTIVITIES, + ACTIVITIES_EPOCH, + ) + .expect("zone activities mount") + .build() + .expect("projection catalog") + .projector(ACTIVITIES_PROJECTOR) + .expect("zone activities projector") +} + +/// The modeled projector mounts `(leases, snapshots)`: mount both on one +/// consumer service named [`APPLICATION`], applying [`ZONE_LEASES`] and +/// [`ZONE_SNAPSHOTS`] respectively. +pub fn projectors() -> (SurfaceProjector, SurfaceProjector) { + let mounts = LocalProjectionMountsBuilder::new(APPLICATION, "ordered-domain-events") + .expect("projection source") + .eventual_model::(LEASES_PROJECTOR, ZONE_LEASES, LEASES_EPOCH) + .expect("zone leases mount") + .eventual_model::(SNAPSHOTS_PROJECTOR, ZONE_SNAPSHOTS, SNAPSHOTS_EPOCH) + .expect("zone snapshots mount") + .build() + .expect("projection catalog"); + ( + mounts + .projector(LEASES_PROJECTOR) + .expect("zone leases projector"), + mounts + .projector(SNAPSHOTS_PROJECTOR) + .expect("zone snapshots projector"), + ) +} + +/// What the read model knows about a zone. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "state", rename_all = "camelCase")] +pub enum ZoneStatus { + /// Running: a holder has the lease (native multi-host server; `holder` + /// is the host) or a celld object reported `active` (`holder` is its + /// node when known, a debug detail). + Active { + /// The lease holder, or the celld node (may be empty). + holder: String, + }, + /// A celld-hosted zone that emptied: still in memory, snapshot written, + /// about to hibernate. + Dormant, + /// No holder; a hibernation snapshot is stored. + Hibernated { + /// Snapshot size in bytes. + bytes: u64, + }, + /// No holder and no snapshot: never ran, or ran without hibernating. + Cold, +} + +impl ZoneStatus { + /// The status of a celld-hosted zone from its activity row. + pub fn of_activity(activity: Option<&ZoneActivities>) -> Self { + match activity.map(|row| row.status.as_str()) { + Some(ACTIVITY_ACTIVE) => Self::Active { + holder: activity.map(|row| row.node.clone()).unwrap_or_default(), + }, + Some(ACTIVITY_DORMANT) => Self::Dormant, + Some(ACTIVITY_HIBERNATED) => Self::Hibernated { bytes: 0 }, + _ => Self::Cold, + } + } + + /// Combine a zone's rows (either may be missing). + pub fn of(lease: Option<&ZoneLeases>, snapshot: Option<&ZoneSnapshots>) -> Self { + if let Some(lease) = lease.filter(|lease| lease.status == STATUS_ACTIVE) { + return Self::Active { + holder: lease.holder.clone(), + }; + } + match snapshot.filter(|snapshot| snapshot.stored) { + Some(snapshot) => Self::Hibernated { + bytes: u64::try_from(snapshot.bytes).unwrap_or(0), + }, + None => Self::Cold, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn status_prefers_an_active_lease_then_a_stored_snapshot() { + let lease = |status: &str| ZoneLeases { + zone_id: "z".into(), + holder: "A#1".into(), + token: 3, + status: status.into(), + }; + let snapshot = |stored| ZoneSnapshots { + zone_id: "z".into(), + token: 3, + stored, + content_version: "v".into(), + bytes: if stored { 42 } else { 0 }, + }; + assert_eq!( + ZoneStatus::of(Some(&lease("active")), Some(&snapshot(true))), + ZoneStatus::Active { + holder: "A#1".into() + } + ); + assert_eq!( + ZoneStatus::of(Some(&lease("released")), Some(&snapshot(true))), + ZoneStatus::Hibernated { bytes: 42 } + ); + assert_eq!( + ZoneStatus::of(Some(&lease("expired")), Some(&snapshot(false))), + ZoneStatus::Cold + ); + assert_eq!(ZoneStatus::of(None, None), ZoneStatus::Cold); + // The projections compile against the cells' outward events. + let (leases, snapshots) = projectors(); + drop((leases, snapshots, activity_projector())); + assert_eq!(read_model_catalog().tables.len(), 3); + let activity = |status: &str| ZoneActivities { + zone_id: "z".into(), + status: status.into(), + node: "node-a".into(), + ..ZoneActivities::default() + }; + assert_eq!( + ZoneStatus::of_activity(Some(&activity("active"))), + ZoneStatus::Active { + holder: "node-a".into() + } + ); + assert_eq!( + ZoneStatus::of_activity(Some(&activity("dormant"))), + ZoneStatus::Dormant + ); + assert_eq!( + ZoneStatus::of_activity(Some(&activity("hibernated"))), + ZoneStatus::Hibernated { bytes: 0 } + ); + assert_eq!(ZoneStatus::of_activity(None), ZoneStatus::Cold); + } +} diff --git a/distributed_game/src/zone.rs b/distributed_game/src/zone.rs new file mode 100644 index 000000000..e32dc27cc --- /dev/null +++ b/distributed_game/src/zone.rs @@ -0,0 +1,450 @@ +//! The [`Zone`] trait a game implements, and the identity types it sees. +//! +//! A zone is one authoritative simulation instance (a dungeon floor, a match, +//! a town shard). The [`ZoneHost`](crate::ZoneHost) owns it and calls these +//! hooks; every hook gets a [`Ctx`] for timers, RNG, inputs, +//! facts, events and views. Hooks are synchronous and must not block: durable +//! work goes through facts, never through awaited storage. +//! +//! Lifecycle: `on_create` → (`on_auth` → `on_join` | `on_observe`)* with +//! `on_tick`/`on_timer`/`on_fact_settled` interleaved → `on_leave` / +//! `on_unobserve` → `on_dispose`. + +use crate::claims::TicketExtensions; +use crate::facts::FactSettlement; +use crate::host::Ctx; +use crate::interest::View; +use crate::protocol::{Origin, Role}; +use crate::replication::WorldView; +use crate::rewind::RewindFrame; +use crate::schema::EntitySchema; +use crate::timers::TimerId; +use crate::world::ChildEvent; + +/// Stable id of a player within a zone (survives reconnects). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct PlayerId(pub u32); + +/// Id of a read-only observer. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct ObserverId(pub u32); + +/// Id of one transport connection (changes on reconnect). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct ClientId(pub u32); + +/// Anything that has a view and receives events. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum Viewer { + /// A player. + Player(PlayerId), + /// An observer. + Observer(ObserverId), +} + +impl From for Viewer { + fn from(id: PlayerId) -> Self { + Self::Player(id) + } +} + +impl From for Viewer { + fn from(id: ObserverId) -> Self { + Self::Observer(id) + } +} + +/// Claims from a **verified** admission ticket. The principal is the only +/// identity the runtime trusts; nothing in client payloads can change it. +/// +/// Built by a `net::TicketVerifier` (the default HS256 `net::TicketKey`, or a +/// game's own verifier for tickets minted by its web backend). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TicketClaims { + /// Verified principal (`sub`). + pub principal: String, + /// Zone the ticket admits to. + pub zone: String, + /// Expiry, Unix seconds. + pub expires_at: u64, + /// Single-use replay key (`nonce`, or a JWT `jti`): the server refuses + /// a second admission with the same key until `expires_at`. + pub nonce: String, + /// Player or observer. + pub role: Role, + /// Optional display name vouched for by the ticket issuer (never + /// identity: use `principal` for that). Exposed as + /// [`PlayerInfo::name`] / [`ObserverInfo::name`]. + pub name: Option, + /// Game-declared claims the issuer vouches for (match id, team…; the + /// ticket's `ext`), checked by the `net` server against + /// `AdmissionConfig::extensions`. Never identity or rewards. + pub extensions: TicketExtensions, + /// The issuer lets this **observer** wake the zone and keep it awake + /// while it declares itself near ([`Hello::near`](crate::protocol::Hello::near), + /// zones hosted as celld objects); the ticket's `wake` claim. The + /// issuer decides who may (e.g. only rooms next to the principal's + /// own). Ignored for players. + pub wake: bool, +} + +impl TicketClaims { + /// Claims without a display name. + pub fn new( + principal: impl Into, + zone: impl Into, + expires_at: u64, + nonce: impl Into, + role: Role, + ) -> Self { + Self { + principal: principal.into(), + zone: zone.into(), + expires_at, + nonce: nonce.into(), + role, + name: None, + extensions: TicketExtensions::new(), + wake: false, + } + } + + /// Grant an observer ticket the right to wake the zone when near + /// ([`wake`](Self::wake)). + pub fn with_wake(mut self, wake: bool) -> Self { + self.wake = wake; + self + } + + /// Attach extension claims. + pub fn with_extensions(mut self, extensions: TicketExtensions) -> Self { + self.extensions = extensions; + self + } + + /// Attach a display name. + pub fn with_name(mut self, name: impl Into) -> Self { + self.name = Some(name.into()); + self + } + + /// Key the server's replay cache records (the nonce / `jti`). + pub fn replay_key(&self) -> &str { + &self.nonce + } +} + +/// Admission request seen by [`Zone::on_auth`]. +#[derive(Debug, Clone, Copy)] +pub struct JoinRequest<'a> { + /// Verified claims. + pub claims: &'a TicketClaims, + /// Hello capabilities (game-defined bits). + pub capabilities: u32, + /// Client content version. + pub content_version: &'a str, +} + +/// `on_auth` decision. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Admission { + /// Let them in. + Admit, + /// Refuse with a message. + Reject(String), +} + +/// Why a player left. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LeaveReason { + /// Client sent Leave. + Left, + /// Connection lost and the reconnect grace window elapsed. + Disconnected, + /// Removed by the zone or operator. + Kicked, + /// Handed off to another zone. + Handoff, + /// Zone disposed. + Disposed, + /// A fresh ticket for the same principal started a new client session in + /// this slot (e.g. a page reload); see [`Zone::on_rejoin`]. + Rejoined, +} + +/// Player as seen by the zone. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PlayerInfo { + /// Stable id. + pub id: PlayerId, + /// Verified principal from the ticket. + pub principal: String, + /// Display name from the ticket ([`TicketClaims::name`]), if any. + pub name: Option, + /// Extension claims from the ticket ([`TicketClaims::extensions`]); + /// replaced by a fresh ticket's on rejoin, carried across handoffs. + pub extensions: TicketExtensions, + /// Hello capabilities. + pub capabilities: u32, + /// False while inside the reconnect grace window. + pub connected: bool, +} + +/// Observer as seen by the zone ([`Ctx::observer`](crate::Ctx::observer)). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ObserverInfo { + /// Observer id (address events with [`Ctx::send_event`](crate::Ctx::send_event)). + pub id: ObserverId, + /// Verified principal from the observer ticket. + pub principal: String, + /// Display name from the ticket, if any. + pub name: Option, + /// Extension claims from the ticket. + pub extensions: TicketExtensions, + /// Hello capabilities. + pub capabilities: u32, +} + +/// Activity tier of a zone. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Tier { + /// Clients connected or work pending: full tick rate, patches flowing. + Hot, + /// Empty: optional slow clock for background simulation. + Idle, + /// No ticks; eligible for hibernation. + Dormant, +} + +/// A game zone. See the module docs for the lifecycle. +pub trait Zone: Sized + Send + 'static { + /// Construction parameters. + type Config; + /// Decoded, sanitized player input. + type Input: Send + 'static; + /// Timer payload. + type Timer: Clone + Send + 'static; + /// Messages services deliver into the running zone + /// ([`on_message`](Self::on_message), [`crate::inbox`]): a + /// `#[derive(GameEvent)]` struct or enum, or [`NoMessages`](crate::NoMessages). + type Message: crate::GameEvent + Send + 'static; + + /// Replicated entity schema (called once at creation). + fn schema() -> EntitySchema; + + /// Build the zone. Timers and RNG are available through `ctx`. + fn on_create(ctx: &mut Ctx<'_, Self>, config: Self::Config) -> Self; + + /// Decide admission for a verified ticket (capacity is checked first). + fn on_auth(&mut self, _ctx: &mut Ctx<'_, Self>, _request: &JoinRequest<'_>) -> Admission { + Admission::Admit + } + + /// A player joined (not called on reconnect). + fn on_join(&mut self, _ctx: &mut Ctx<'_, Self>, _player: PlayerId) {} + + /// A player left for `reason` (not called on a disconnect still inside + /// the grace window: see [`on_connection_lost`](Self::on_connection_lost)). + fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, _player: PlayerId, _reason: LeaveReason) {} + + /// A player's connection dropped (or it was told to reload) and its + /// reconnect grace window started; the slot and its entity stay. + /// `on_leave(Disconnected)` follows if it does not come back in time. + fn on_connection_lost(&mut self, _ctx: &mut Ctx<'_, Self>, _player: PlayerId) {} + + /// A player resumed its slot with a reconnect token within the grace + /// window. + fn on_reconnected(&mut self, _ctx: &mut Ctx<'_, Self>, _player: PlayerId) {} + + /// A fresh ticket (not a reconnect token) arrived for a principal that + /// already holds a player slot here, e.g. the page was reloaded or opened + /// in another tab with the same identity. The old connection was + /// replaced (`Kick(REPLACED)`) and the new one is a new client session: + /// its input sequence starts again and it knows nothing about per-player + /// state the zone sent on join (own entity id, hello events…). + /// + /// Defaults to `on_leave(Rejoined)` then `on_join`, i.e. a fresh join in + /// the same [`PlayerId`]: the body is respawned. Override to keep + /// in-zone state and only resend what the client needs, so a reloaded + /// page takes over the same body (what players expect; the examples' + /// Mob Pit, Arena and Endless Grid do). + fn on_rejoin(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + self.on_leave(ctx, player, LeaveReason::Rejoined); + self.on_join(ctx, player); + } + + /// An observer subscribed. Its principal and name are available from + /// [`Ctx::observer`](crate::Ctx::observer); address it with + /// [`Ctx::send_event`](crate::Ctx::send_event)`(observer, ..)`. + fn on_observe(&mut self, _ctx: &mut Ctx<'_, Self>, _observer: ObserverId) {} + + /// An observer left. [`Ctx::observer`](crate::Ctx::observer) still + /// returns it during this hook (it can no longer receive events). + fn on_unobserve(&mut self, _ctx: &mut Ctx<'_, Self>, _observer: ObserverId) {} + + /// An observer says where it is looking, in this zone's local + /// coordinates (`Focus`; e.g. a player next door, so this zone's + /// interest management follows that player across the border). The + /// default centres the observer's view there with the zone's + /// [`view_radius`](Self::view_radius) (the player sees this zone as it + /// sees its own), else keeps the observer's radius; override to clamp, + /// resize or ignore it. Untrusted: it only steers what the observer + /// sees. + fn on_observer_focus(&mut self, ctx: &mut Ctx<'_, Self>, observer: ObserverId, x: f32, y: f32) { + if !(x.is_finite() && y.is_finite()) { + return; + } + if let Some(view) = ctx.view_of(observer) { + let radius = self.view_radius().unwrap_or(view.radius); + ctx.set_view(observer, View::new(x, y, radius)); + } + } + + /// Where this zone sits in the world: the world position of its local + /// (0, 0), for zones whose positions are local to a place in one + /// continuous world (a grid of rooms, map tiles). Sent in Welcome, so a + /// client that knows where its player is focuses every neighbour it + /// watches by itself (JS: `GameClient.setPosition`). Derive it from the + /// zone's config (e.g. the room parsed from its zone id). `None` + /// (default): the zone is not placed and clients focus it only by hand. + fn origin(&self) -> Option { + None + } + + /// How far a player sees in this zone (the radius the zone gives player + /// views), when it is one radius. The default + /// [`on_observer_focus`](Self::on_observer_focus) gives a player next + /// door the same view here. `None` (default): focused observers keep + /// their radius. + fn view_radius(&self) -> Option { + None + } + + /// Decode raw input bytes from the wire; `None` drops the input. + fn decode_input(&self, player: PlayerId, payload: &[u8]) -> Option; + + /// Validate/clamp an input before buffering; `None` rejects it. + fn sanitize_input(&self, _player: PlayerId, input: Self::Input) -> Option { + Some(input) + } + + /// One fixed simulation step (`ctx.dt()` is the step length of the tier). + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>); + + /// A message from a service ([`crate::inbox`]), delivered on the zone's + /// task between ticks (never during one). The built-in kick is handled + /// by the host and never reaches this hook. + fn on_message(&mut self, _ctx: &mut Ctx<'_, Self>, _message: Self::Message) {} + + /// A message from another zone ([`crate::zone_message`]), delivered on + /// the zone's task between ticks, at most once. `from` names the zone + /// and, for a message sent on behalf of a player, its verified + /// principal. Trusted internal input, but check what it claims against + /// your own state (a neighbour, a position on the shared boundary). + fn on_zone_message( + &mut self, + _ctx: &mut Ctx<'_, Self>, + _from: &crate::zone_message::ZoneSender, + _message: Self::Message, + ) { + } + + /// A timer fired (before `on_tick` of the same tick). + fn on_timer(&mut self, _ctx: &mut Ctx<'_, Self>, _id: TimerId, _timer: Self::Timer) {} + + /// A fact emitted earlier settled. + fn on_fact_settled(&mut self, _ctx: &mut Ctx<'_, Self>, _settlement: FactSettlement) {} + + /// The activity tier changed. + fn on_tier_changed(&mut self, _ctx: &mut Ctx<'_, Self>, _from: Tier, _to: Tier) {} + + /// True keeps the zone Hot even with nobody connected. + fn has_pending_work(&self) -> bool { + false + } + + /// True keeps an empty zone Idle (background clock) instead of Dormant. + fn wants_background(&self) -> bool { + false + } + + /// The zone's entity collections, registered once at creation + /// ([`entity`](crate::entity)): every patch the host pushes each + /// entity's [`Project`](crate::Project)ed view (in registration order), + /// then calls [`replicate`](Self::replicate). Default: none. + fn entities() -> crate::Entities { + crate::Entities::new() + } + + /// Describe replicated entities for this patch that are not projected + /// from a registered collection ([`entities`](Self::entities)). + /// Default: nothing. + fn replicate(&self, _out: &mut WorldView) {} + + /// Record hit volumes for lag compensation after each tick + /// ([`Ctx::rewind`](crate::Ctx::rewind)). Default: nothing recorded. + fn record_rewind(&self, _frame: &mut RewindFrame) {} + + /// Digest of the authoritative state for record/replay + /// ([`replay`](mod@crate::replay)). `None` hashes the replicated + /// [`WorldView`] instead, which misses unreplicated state. + fn state_hash(&self) -> Option { + None + } + + /// The zone is being destroyed; timers are cleared afterwards. + fn on_dispose(&mut self, _ctx: &mut Ctx<'_, Self>) {} + + // ---- World structure (all optional) ---- + + /// Durable snapshot taken when the zone hibernates (Dormant long + /// enough); `None` = nothing worth keeping. Stored in a + /// [`ZoneStateStore`](crate::world::ZoneStateStore) and handed to + /// [`on_restore`](Self::on_restore) on the next activation. + fn hibernate(&self) -> Option> { + None + } + + /// Restore a snapshot written by [`hibernate`](Self::hibernate) (called + /// right after `on_create`). `saved_version` is the content version it + /// was written under. + fn on_restore(&mut self, _ctx: &mut Ctx<'_, Self>, _state: &[u8], _saved_version: &str) {} + + /// A player arrived through a handoff from `from_zone` with `carried` + /// state (instead of `on_join`): the encoding of the [`Wire`](crate::Wire) + /// value the source passed to [`Ctx::handoff`](crate::Ctx::handoff); + /// decode it with [`codec::from_bytes`](crate::codec::from_bytes) (and + /// treat a failure as no state: the bytes crossed the client). Also + /// called when the principal was still present (reconnect grace), and + /// for a handoff that failed and returned to its source (`from_zone` is + /// then the zone it never reached). Defaults to `on_join`. + fn on_handoff_join( + &mut self, + ctx: &mut Ctx<'_, Self>, + player: PlayerId, + _from_zone: &str, + _carried: Vec, + ) { + self.on_join(ctx, player); + } + + /// A tier-up event from a descendant zone (see + /// [`world::topology`](crate::world::topology)). + fn on_child_event(&mut self, _ctx: &mut Ctx<'_, Self>, _event: &ChildEvent) {} + + /// True marks a safe-room gate: stale clients are told to reload here + /// (see [`StalePolicy`](crate::world::StalePolicy)). + fn is_gate(&self) -> bool { + false + } + + /// Barrier readiness: while false a requested freeze waits (the zone + /// keeps ticking), e.g. to finish a boss phase. A world barrier aborts + /// if a zone is not ready within its timeout. + fn freeze_ready(&self) -> bool { + true + } + + /// The content version changed (world barrier commit). + fn on_content_version_changed(&mut self, _ctx: &mut Ctx<'_, Self>, _from: &str, _to: &str) {} +} diff --git a/distributed_game/src/zone_message.rs b/distributed_game/src/zone_message.rs new file mode 100644 index 000000000..b1303ced4 --- /dev/null +++ b/distributed_game/src/zone_message.rs @@ -0,0 +1,131 @@ +//! Zone-to-zone messages: one running zone tells another something, e.g. a +//! shot that carries on into the room next door, or a mob that follows a +//! player across a boundary. +//! +//! A zone sends with [`Ctx::send_zone`](crate::Ctx::send_zone) (or +//! [`send_zone_for`](crate::Ctx::send_zone_for), which binds a player's +//! verified principal into the message, as facts do); the target handles +//! it in [`Zone::on_zone_message`](crate::Zone::on_zone_message). Messages +//! use the zone's own [`Zone::Message`](crate::Zone::Message) type and +//! codec. +//! +//! Each message is a [`ZoneEnvelope`] with an id unique to the sending +//! activation (`zone/boot_epoch/seq`). The driver takes them with +//! [`ZoneHost::take_zone_messages`](crate::ZoneHost::take_zone_messages) +//! and hands them to the target's +//! [`ZoneHost::deliver_zone`](crate::ZoneHost::deliver_zone), which drops +//! an id it has seen recently (at most once per activation; at-least-once +//! transports may resend). On celld the object posts envelopes to the +//! target's object with the internal secret (like a cell's push), never on +//! a public route. On the native `net` server the zone task hands each to +//! the target's queue when it runs on the same server, or posts it to the +//! host the directory places it on (`/admin/zone-envelope`, internal +//! secret). A message for a zone that is not running is refused: it +//! never wakes a zone. Delivery is best effort and unordered on both: a +//! refused or failed message is dropped, never retried. A protocol that must not +//! lose state (a mob crossing over) needs its own acks and timeouts: +//! [`lease`](crate::lease) keeps them for an entity lent to another zone. +//! +//! **Identity.** The receiving zone sees the sender's principal only as a +//! [`VerifiedPrincipal`], which game code cannot construct: it came from a +//! verified player ticket in the sending zone. Facts on behalf of it go +//! through [`Ctx::emit_fact_as`](crate::Ctx::emit_fact_as). + +use std::collections::{HashSet, VecDeque}; + +use serde::{Deserialize, Serialize}; + +/// A message between zones, as carried by a transport. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ZoneEnvelope { + /// Unique per sending activation (`zone/boot_epoch/seq`): the target + /// drops repeats. + pub id: String, + /// Sending zone id. + pub from: String, + /// Target zone id. + pub to: String, + /// The verified principal of the player the message is on behalf of. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub principal: Option, + /// Event type id of the message ([`GameEvent::event_id`](crate::GameEvent::event_id)). + pub type_id: u32, + /// Its encoded payload. + pub payload: Vec, +} + +/// A principal bound from a verified player ticket (in this zone or in the +/// zone that sent a message). Only the framework makes one. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct VerifiedPrincipal(String); + +impl VerifiedPrincipal { + pub(crate) fn new(principal: String) -> Self { + Self(principal) + } + + /// The principal. + pub fn as_str(&self) -> &str { + &self.0 + } +} + +/// Who sent a zone message. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ZoneSender { + /// The sending zone's id. + pub zone: String, + /// The player it was sent on behalf of + /// ([`send_zone_for`](crate::Ctx::send_zone_for)). + pub principal: Option, +} + +/// Why a zone message was not delivered. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ZoneMessageError { + /// Addressed to another zone. + WrongZone, + /// Seen before (a resend): dropped. + Duplicate, + /// Not a message of this zone's type. + Decode(String), +} + +impl std::fmt::Display for ZoneMessageError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::WrongZone => f.write_str("addressed to another zone"), + Self::Duplicate => f.write_str("duplicate message"), + Self::Decode(e) => write!(f, "bad message: {e}"), + } + } +} + +impl std::error::Error for ZoneMessageError {} + +/// Message ids seen lately (bounded: the oldest are forgotten first). +#[derive(Debug, Default)] +pub(crate) struct SeenIds { + ids: HashSet, + order: VecDeque, +} + +/// Ids remembered per activation. +const SEEN_CAPACITY: usize = 4096; + +impl SeenIds { + /// True the first time `id` is offered. + pub(crate) fn first(&mut self, id: &str) -> bool { + if self.ids.contains(id) { + return false; + } + if self.order.len() >= SEEN_CAPACITY { + if let Some(old) = self.order.pop_front() { + self.ids.remove(&old); + } + } + self.ids.insert(id.to_string()); + self.order.push_back(id.to_string()); + true + } +} diff --git a/distributed_game/tests/alloc/main.rs b/distributed_game/tests/alloc/main.rs new file mode 100644 index 000000000..d230d93fd --- /dev/null +++ b/distributed_game/tests/alloc/main.rs @@ -0,0 +1,326 @@ +//! Heap allocations on the hot loop, counted (not timed) by a counting +//! global allocator: a zone of `n` replicated entities ticking with `m` +//! clients, rewind recording and lag-compensated queries. +//! +//! The counter is per thread, so tests running in parallel do not see each +//! other's allocations and every count is deterministic. +//! +//! `cargo test -p distributed_game --test alloc -- --ignored --nocapture` +//! prints the per-site table (`alloc_report`). + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::cell::Cell; +use std::sync::Arc; +use std::time::Duration; + +use distributed_game::{ + schema, Collider, Colliders, Ctx, Entities, Entity, EntityId, EntitySchema, Historic, + HitQuery, HostConfig, ManualClock, PlayerId, Ray, RewindFrame, Role, TicketClaims, Zone, + ZoneHost, +}; + +struct Counting; + +thread_local! { + static ALLOCATIONS: Cell = const { Cell::new(0) }; +} + +fn count() { + let _ = ALLOCATIONS.try_with(|n| n.set(n.get() + 1)); +} + +// SAFETY: forwards every call to `System` unchanged; only counts. +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + count(); + unsafe { System.alloc(layout) } + } + + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + count(); + unsafe { System.alloc_zeroed(layout) } + } + + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + count(); + unsafe { System.realloc(ptr, layout, new_size) } + } + + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + unsafe { System.dealloc(ptr, layout) } + } +} + +#[global_allocator] +static GLOBAL: Counting = Counting; + +fn allocations() -> u64 { + ALLOCATIONS.with(Cell::get) +} + +/// What the zone does each tick. +#[derive(Debug, Clone, Copy, Default)] +struct Load { + /// Entities. + n: u32, + /// Project them into the replicated world. + replicate: bool, + /// Record them for lag compensation. + rewind: bool, + /// Raycasts and rewind hit tests per tick. + queries: u32, + /// Every entity moves every tick (else nothing changes). + moving: bool, +} + +struct Mob { + id: EntityId, + x: f32, + y: f32, + hp: u8, +} + +impl Entity for Mob { + fn entity_id(&self) -> EntityId { + self.id + } +} + +#[derive(Debug, Clone, PartialEq, distributed_game::Replicated)] +#[replicated(kind = "mob", id = 1, of = Mob)] +struct MobView { + #[from] + x: f32, + #[from] + y: f32, + #[from] + hp: u8, +} + +struct Swarm { + load: Load, + mobs: Vec, + hits: u32, +} + +impl Zone for Swarm { + type Config = Load; + type Input = u8; + type Timer = (); + type Message = distributed_game::NoMessages; + + fn schema() -> EntitySchema { + schema![MobView] + } + + fn entities() -> Entities { + Entities::new().each::(|z: &Swarm| { + if z.load.replicate { + &z.mobs[..] + } else { + &[] + } + }) + } + + fn on_create(ctx: &mut Ctx<'_, Self>, load: Load) -> Self { + let mut colliders = Colliders::new(); + for i in 0..16 { + colliders.push(Collider::cylinder( + [(i % 4) as f32 * 25.0 + 12.0, (i / 4) as f32 * 25.0 + 12.0], + 1.0, + 3.0, + )); + } + ctx.set_colliders(colliders); + let side = (load.n as f32).sqrt().ceil().max(1.0) as u32; + let mobs = (0..load.n) + .map(|i| Mob { + id: EntityId(i + 1), + x: (i % side) as f32 * 100.0 / side as f32, + y: (i / side) as f32 * 100.0 / side as f32, + hp: 100, + }) + .collect(); + Self { + load, + mobs: if load.replicate || load.rewind { + mobs + } else { + Vec::new() + }, + hits: 0, + } + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { + payload.first().copied() + } + + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + if self.load.moving { + for mob in &mut self.mobs { + mob.x = (mob.x + 0.5) % 100.0; + } + } + let now = ctx.rewind().latest().map(|f| f.time()); + for q in 0..self.load.queries { + let y = (q % 10) as f32 * 10.0 + 0.5; + let ray = Ray::new([-1.0, y, 0.0], [1.0, 0.0, 0.0], 200.0); + self.hits += u32::from(ctx.raycast(&ray).is_some()); + if let Some(time) = now { + let shot = HitQuery::ray([-1.0, y, 0.0], [1.0, 0.0, 0.0], 200.0); + let hit = ctx.rewind().hit_test(time, &shot, |id| id % 2 == 0); + self.hits += u32::from(hit.is_some()); + } + } + } + + fn record_rewind(&self, frame: &mut RewindFrame) { + if self.load.rewind { + for mob in &self.mobs { + frame.push(Historic::sphere(mob.id.get(), [mob.x, mob.y, 0.0], 0.5)); + } + } + } + + fn has_pending_work(&self) -> bool { + true + } +} + +/// A host running `load` with `clients` players that see everything. +fn host(load: Load, clients: u32) -> (ZoneHost, ManualClock) { + let clock = ManualClock::new(); + let config = HostConfig { + tick_rate: 20, + patch_rate: 20, + byte_budget: usize::MAX, + // Every client sees every entity. + default_view_radius: 500.0, + ..HostConfig::default() + }; + let mut host = ZoneHost::::new("swarm", config, Arc::new(clock.clone()), load); + for c in 0..clients { + let claims = TicketClaims::new( + format!("p{c}"), + "swarm", + u64::MAX, + format!("n{c}"), + Role::Player, + ); + host.join(&claims, 0, "").expect("joins"); + } + (host, clock) +} + +/// Mean allocations per tick over `ticks` ticks after a warm-up (every +/// client knows every entity; buffers reached their size). +fn per_tick(load: Load, clients: u32, ticks: u32) -> u64 { + let (mut host, clock) = host(load, clients); + let step = Duration::from_millis(50); + let mut tick = || { + clock.advance(step); + let report = host.advance(); + assert_eq!(report.ticks, 1, "one tick per advance"); + host.drain_outbound(); + drop(report); + }; + for _ in 0..40 { + tick(); + } + let before = allocations(); + for _ in 0..ticks { + tick(); + } + (allocations() - before) / u64::from(ticks) +} + +const SIZES: [u32; 3] = [50, 200, 1000]; + +#[test] +#[ignore = "report: --ignored --nocapture"] +fn alloc_report() { + let clients = 8; + let ticks = 20; + let base = |n| Load { + n, + ..Load::default() + }; + println!("allocations per tick ({clients} clients, {ticks} ticks after warm-up)"); + println!( + "{:>6} {:>9} {:>11} {:>11} {:>8} {:>10} {:>11} {:>11}", + "n", "baseline", "replicate", "repl+move", "rewind", "queries16", "all idle", "all moving" + ); + for n in SIZES { + let baseline = per_tick(base(n), clients, ticks); + let site = |load: Load| per_tick(load, clients, ticks).saturating_sub(baseline); + let replicate = site(Load { + replicate: true, + ..base(n) + }); + let replicate_moving = site(Load { + replicate: true, + moving: true, + ..base(n) + }); + let rewind = site(Load { + rewind: true, + ..base(n) + }); + let queries = site(Load { + rewind: true, + queries: 16, + ..base(n) + }) + .saturating_sub(rewind); + let all = Load { + n, + replicate: true, + rewind: true, + queries: 16, + moving: false, + }; + let idle = per_tick(all, clients, ticks); + let moving = per_tick( + Load { + moving: true, + ..all + }, + clients, + ticks, + ); + println!( + "{n:>6} {baseline:>9} {replicate:>11} {replicate_moving:>11} {rewind:>8} {queries:>10} {idle:>11} {moving:>11}" + ); + } +} + +/// The hot loop of an idle world (replication to 8 clients, rewind +/// recording, 16 raycasts and 16 rewind hit tests per tick) allocates the +/// same, small number of times per tick at any entity count; a moving one +/// adds a bounded number per changed entity (its new payload and update +/// record), nothing per unchanged one. +#[test] +fn hot_loop_allocates_only_on_change() { + let load = |n, moving| Load { + n, + replicate: true, + rewind: true, + queries: 16, + moving, + }; + let idle: Vec = SIZES.iter().map(|&n| per_tick(load(n, false), 8, 10)).collect(); + assert!( + idle.iter().all(|&a| a == idle[0]), + "idle allocations per tick grow with the entity count: {idle:?} for {SIZES:?}" + ); + assert!(idle[0] <= 24, "idle allocations per tick: {}", idle[0]); + for (&n, &idle) in SIZES.iter().zip(&idle) { + let moving = per_tick(load(n, true), 8, 10); + assert!( + moving - idle <= 5 * u64::from(n), + "{n} moving entities: {moving} allocations per tick, idle {idle}" + ); + } +} diff --git a/distributed_game/tests/authoring/main.rs b/distributed_game/tests/authoring/main.rs new file mode 100644 index 000000000..eedf45478 --- /dev/null +++ b/distributed_game/tests/authoring/main.rs @@ -0,0 +1,1034 @@ +//! Authoring derives: `Replicated`, `GameInput`, `GameEvent`, `GameRecord`, +//! `FactCommand`, the `GameSurface` they describe, and the typed `Ctx` +//! helpers. +//! +//! `fixtures/authoring.json` (sample surface + encoded samples) is the Rust +//! side of the generated-client round trip: `distributed_cli` generates +//! TypeScript from its surface (golden `js/tests/fixtures/game-generated/`) +//! and `js/tests/game-generated.test.mjs` encodes/decodes the samples with +//! it. Regenerate with `UPDATE_GOLDEN=1 cargo test -p distributed_game --test authoring`. + +use std::sync::Arc; +use std::time::Duration; + +use distributed_game::protocol::{Reader, Writer}; +use distributed_game::surface::{EventPayload, GameSurface}; +use distributed_game::{ + fact_channel, game_pure, predict, schema, Correction, Ctx, EntitySchema, FactCommand, + FactOutcome, FactSettlement, FieldType, FieldValue, GameEvent, GameInput, GameRecord, + HostConfig, ManualClock, MemoryFactSink, PlayerId, Replicated, RetryPolicy, Role, TicketClaims, + Wire, WireType, WorldView, Zone, ZoneHost, +}; +use serde::Serialize; +use serde_json::{json, Value}; + +// ---- sample surface ------------------------------------------------------- + +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "player", id = 1, priority = 2.0)] +pub struct PlayerView { + #[quant(centered = 20.0, bits = 18)] + #[correct(ease = 150)] + pub x: f32, + #[quant(centered = 20.0, bits = 18)] + #[correct(ease = 150, snap_above = 2.5)] + pub y: f32, + #[quant(min = -16.0, max = 16.0, bits = 12)] + #[correct(snap)] + pub vx: f32, + #[angle(bits = 8)] + #[correct(replace)] + pub face: f32, + #[priority(0.2)] + #[correct(replace)] + pub name: String, + pub hp: u8, + pub level: u16, + pub dead: bool, + pub score: i32, + pub raw: f32, + pub blob: Vec, + pub kills: u32, +} + +const POS: FieldType = FieldType::quant_centered(64.0, 16); + +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "marker", id = 2, x = px, y = py)] +pub struct MarkerView { + #[field_type(POS)] + pub px: f32, + #[field_type(POS)] + pub py: f32, + pub label: String, +} + +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "stats", id = 4, global, every_patch)] +pub struct StatsView { + pub slow_ms: u16, + pub tick_ms: f32, +} + +#[derive(Debug, Clone, Copy, PartialEq, GameInput)] +pub struct SampleInput { + #[range(min = -127, max = 127)] + pub mx: i8, + #[range(min = -127, max = 127)] + pub my: i8, + #[buttons(dash, attack)] + pub buttons: u8, + #[angle(bits = 10)] + pub aim: f32, + #[range(min = 0.0, max = 1.0)] + pub power: f32, + pub view_tick: u32, +} + +#[derive(Debug, Clone, PartialEq, Serialize, GameRecord)] +pub struct Row { + pub rank: u16, + pub name: String, + pub score: u64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, GameRecord)] +pub struct Board { + pub version: u32, + pub kills: Vec, + pub note: Option, + #[long] + pub motd: String, +} + +#[derive(Debug, Clone, PartialEq, GameEvent)] +pub enum SampleEvent { + #[game_event(id = 1)] + Hello { + entity: u32, + view_radius: f32, + #[quant(min = 0.0, max = 64.0, bits = 10)] + half: f32, + }, + #[game_event(id = 2)] + Board(Board), + #[game_event(id = 3, name = "respawned")] + Respawn, + #[game_event(id = 4)] + Shot { + hit: bool, + target: Option, + offset: i16, + small: i8, + at_ms: f64, + tags: Vec, + bytes: Vec, + total: u64, + }, +} + +/// What services may send into the sample zone (zone inbox). +#[derive(Debug, Clone, PartialEq, GameEvent)] +pub enum SampleMessage { + #[game_event(id = 1)] + Announce { + #[long] + text: String, + urgent: bool, + }, + #[game_event(id = 2)] + SetWind(SampleWind), +} + +#[derive(Debug, Clone, PartialEq, GameEvent)] +#[game_event(id = 9)] +pub struct Ping { + pub seq: u32, +} + +/// The cell command name, as the cell would mount it. +pub const RECORD_KILL: &str = "sample.record_kill"; + +#[derive(Debug, Clone, PartialEq, Serialize, FactCommand)] +#[fact(command = RECORD_KILL, key(mob, generation))] +pub struct RecordKill { + pub mob: u32, + pub generation: u32, + pub tier: u8, +} + +#[derive(Debug, Clone, PartialEq, Serialize, FactCommand)] +#[fact(command = "sample.tick_note")] +pub struct TickNote { + pub note: String, +} + +/// The predicted part of a `player` (fields named after the kind's). +#[derive(Debug, Clone, Copy, PartialEq, GameRecord)] +pub struct SampleState { + pub x: f32, + pub vx: f32, + pub hp: u8, + pub dead: bool, +} + +/// What a client tells the step. +#[derive(Debug, Clone, Copy, PartialEq, GameRecord)] +pub struct SampleWind { + pub speed: f32, + pub gusts: u16, +} + +/// The sample's client-predicted step. +#[predict(SampleStep, kind = "player")] +pub fn sample_step( + state: &SampleState, + input: &SampleInput, + wind: &SampleWind, + dt: f32, +) -> SampleState { + if state.dead { + return *state; + } + let vx = f32::from(input.mx) / 127.0 * wind.speed; + SampleState { + x: state.x + vx * dt, + vx, + ..*state + } +} + +/// A sample pure function compiled next to the step (generated `sampleMirror`). +#[game_pure(SampleMirrorFn)] +pub fn sample_mirror(wind: &SampleWind) -> SampleWind { + SampleWind { + speed: -wind.speed, + gusts: wind.gusts.wrapping_add(1), + } +} + +/// One without an argument (generated `sampleRows()`). +#[game_pure(SampleRowsFn)] +pub fn sample_rows() -> Vec { + sample_board().kills +} + +/// A record only a constant uses; its value is quantized like a payload. +#[derive(Debug, Clone, PartialEq, GameRecord)] +pub struct Spot { + #[quant(min = 0.0, max = 64.0, bits = 10)] + pub at: f32, + pub label: String, +} + +pub fn sample_spot() -> Spot { + Spot { + at: 1.3, + label: "dock".into(), + } +} + +pub fn sample_surface() -> GameSurface { + GameSurface::for_zone::("sample") + .events::() + .events::() + .predict::() + .pure::() + .pure::() + .constant("sample_board", &sample_board()) + .constant("sample_gusts", &vec![0.1f32, -2.5]) + .constant("sample_spot", &sample_spot()) + .record::() +} + +// ---- a zone using all of it ---------------------------------------------- + +#[derive(Default)] +pub struct Sample { + players: Vec, + pub settled: Vec, + pub keys: Vec, + pub last_input: Option, + kills: u32, +} + +impl Zone for Sample { + type Config = (); + type Input = SampleInput; + type Timer = (); + type Message = SampleMessage; + + fn schema() -> EntitySchema { + schema![PlayerView, MarkerView, StatsView] + } + + fn on_create(_ctx: &mut Ctx<'_, Self>, _config: ()) -> Self { + Self::default() + } + + fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + self.players.push(player); + ctx.send( + player, + &SampleEvent::Hello { + entity: 1000 + player.0, + view_radius: 14.0, + half: 20.0, + }, + ); + ctx.broadcast(&Ping { seq: player.0 }); + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { + SampleInput::from_payload(payload) + } + + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + for player in self.players.clone() { + for input in ctx.take_inputs(player, distributed_game::ConsumePolicy::Drain) { + self.last_input = Some(input.input); + if input.input.buttons & SampleInput::ATTACK != 0 { + self.kills += 1; + let key = ctx + .emit( + player, + RecordKill { + mob: 7, + generation: self.kills, + tier: 2, + }, + ) + .unwrap(); + self.keys.push(key); + // Two keyless facts in one tick get distinct keys. + self.keys + .push(ctx.emit_zone(TickNote { note: "a".into() }).unwrap()); + self.keys + .push(ctx.emit_zone(TickNote { note: "b".into() }).unwrap()); + } + } + } + } + + fn on_fact_settled(&mut self, _ctx: &mut Ctx<'_, Self>, settlement: FactSettlement) { + self.settled.push(settlement); + } + + fn replicate(&self, out: &mut WorldView) { + for (i, player) in self.players.iter().enumerate() { + out.add(1000 + player.0, &sample_player(i as f32)); + } + out.add( + 50, + &MarkerView { + px: 3.0, + py: -2.0, + label: "spawn".into(), + }, + ) + .priority(0.5); + out.add( + 900, + &StatsView { + slow_ms: 12, + tick_ms: 33.3, + }, + ); + } +} + +fn sample_player(offset: f32) -> PlayerView { + PlayerView { + x: 1.25 + offset, + y: -3.5, + vx: 0.5, + face: 1.0, + name: "Ada".into(), + hp: 90, + level: 3, + dead: false, + score: -12, + raw: 0.1, + blob: vec![1, 2, 3], + kills: 70_000, + } +} + +// ---- derive behaviour ----------------------------------------------------- + +#[test] +fn replicated_kind_def_and_values_share_one_field_order() { + let kind = PlayerView::kind_def(); + assert_eq!( + (kind.id, kind.name.as_str(), kind.priority), + (1, "player", 2.0) + ); + assert!(!kind.every_patch && StatsView::kind_def().every_patch); + let names: Vec<_> = kind.fields.iter().map(|f| f.name.as_str()).collect(); + assert_eq!( + names, + ["x", "y", "vx", "face", "name", "hp", "level", "dead", "score", "raw", "blob", "kills"] + ); + assert_eq!(kind.fields[0].ty, FieldType::quant_centered(20.0, 18)); + assert_eq!( + kind.fields[0].correction, + Some(Correction::Ease { + duration_ms: 150, + snap_above: None + }) + ); + assert_eq!( + kind.fields[1].correction, + Some(Correction::Ease { + duration_ms: 150, + snap_above: Some(2.5) + }) + ); + assert_eq!(kind.fields[2].correction, Some(Correction::Snap)); + assert_eq!(kind.fields[3].ty, FieldType::Angle { bits: 8 }); + assert_eq!(kind.fields[4].priority, 0.2); + assert_eq!(kind.fields[5].ty, FieldType::U8); + assert_eq!(kind.fields[6].ty, FieldType::U16); + assert_eq!(kind.fields[10].ty, FieldType::Bytes); + let view = sample_player(0.0); + let values = view.field_values(); + assert_eq!(values.len(), kind.fields.len()); + assert_eq!(values[4], FieldValue::Str("Ada".into())); + assert_eq!(values[8], FieldValue::I(-12)); + assert_eq!(view.position(), (1.25, -3.5)); + const { assert!(!PlayerView::GLOBAL) }; + const { assert!(StatsView::GLOBAL) }; + assert_eq!( + MarkerView { + px: 3.0, + py: 4.0, + label: String::new() + } + .position(), + (3.0, 4.0) + ); + assert_eq!(MarkerView::kind_def().fields[0].ty, POS); + + let schema = Sample::schema(); + assert_eq!(schema.kinds().len(), 3); + let mut view = WorldView::default(); + view.add( + 5, + &StatsView { + slow_ms: 1, + tick_ms: 2.0, + }, + ) + .local() + .priority(3.0); + view.add(6, &sample_player(0.0)).global(); + assert!(!view.entities()[0].global); + assert_eq!(view.entities()[0].priority, 3.0); + assert!(view.entities()[1].global); + assert_eq!(view.entities()[1].kind, PlayerView::KIND_ID); +} + +#[test] +fn game_input_codec_and_sanitize() { + let input = SampleInput { + mx: -128, + my: 64, + buttons: 0b1111, + aim: 1.0, + power: 2.0, + view_tick: 300, + }; + let bytes = input.to_payload(); + // i8, i8, u8, angle varuint (10 bits), f32, varuint. + assert_eq!(bytes[..3], [0x80, 0x40, 0x0f]); + let decoded = SampleInput::from_payload(&bytes).expect("valid"); + assert_eq!(decoded.mx, -127, "range clamps"); + assert_eq!( + decoded.buttons, + SampleInput::DASH | SampleInput::ATTACK, + "unknown bits cleared" + ); + assert_eq!(decoded.power, 1.0); + assert_eq!((SampleInput::DASH, SampleInput::ATTACK), (1, 2)); + let mut long = bytes.clone(); + long.push(0); + assert_eq!( + SampleInput::from_payload(&long), + None, + "trailing bytes reject" + ); + assert_eq!( + SampleInput::from_payload(&bytes[..4]), + None, + "short frames reject" + ); + let nan = SampleInput { + power: f32::NAN, + ..input + }; + assert_eq!( + SampleInput::from_payload(&nan.to_payload()), + None, + "non-finite floats reject" + ); +} + +#[test] +fn events_have_stable_ids_and_round_trip() { + let events = sample_events(); + for event in &events { + let payload = event.to_payload(); + let back = SampleEvent::decode_event(event.event_id(), &payload).unwrap(); + assert_eq!(back.as_ref(), Some(event)); + assert_eq!( + Ping::decode_event(event.event_id(), &payload).unwrap(), + None + ); + } + assert_eq!(SampleEvent::HELLO, 1); + assert_eq!(SampleEvent::RESPAWN, 3); + assert_eq!(Ping::EVENT_ID, 9); + assert_eq!(SampleEvent::decode_event(77, &[]).unwrap(), None); + assert!(SampleEvent::decode_event(1, &[1]).is_err()); + let ping = Ping { seq: 5 }; + assert_eq!( + Ping::decode_event(9, &ping.to_payload()).unwrap(), + Some(ping) + ); +} + +#[test] +fn records_round_trip_through_the_value_codec() { + let board = sample_board(); + let mut w = Writer::new(); + board.encode(&mut w); + let mut r = Reader::new(w.as_bytes()); + assert_eq!(Board::decode(&mut r).unwrap(), board); + r.finish().unwrap(); + assert_eq!( + Board::wire_type(), + WireType::Record { + name: "Board".into() + } + ); +} + +#[test] +fn surface_describes_everything_once() { + let surface = sample_surface(); + assert_eq!(surface.schema_version, 3); + assert_eq!(surface.kinds.len(), 3); + assert_eq!( + surface.kinds[0].fields[0].correction, + Some(Correction::Ease { + duration_ms: 150, + snap_above: None + }) + ); + let input = surface.input.as_ref().expect("typed input"); + assert_eq!(input.name, "SampleInput"); + assert_eq!(input.fields[0].range, Some([-127.0, 127.0])); + assert_eq!(input.fields[2].buttons, ["dash", "attack"]); + let ids: Vec<_> = surface + .events + .iter() + .map(|e| (e.id, e.name.as_str())) + .collect(); + assert_eq!( + ids, + [ + (1, "hello"), + (2, "board"), + (3, "respawned"), + (4, "shot"), + (9, "ping") + ] + ); + assert_eq!( + surface.events[1].payload, + EventPayload::Value { + ty: WireType::Record { + name: "Board".into() + } + } + ); + let records: Vec<_> = surface.records.iter().map(|r| r.name.as_str()).collect(); + assert_eq!( + records, + ["Board", "Row", "SampleState", "SampleWind", "Spot"] + ); + // JSON round trip (the CLI reads this shape). + let json = surface.to_json(); + let back: GameSurface = serde_json::from_str(&json).unwrap(); + assert_eq!(back, surface); +} + +#[test] +fn surface_validation_accepts_the_builders_output_and_names_the_broken_rule() { + let surface = sample_surface(); + surface + .validate() + .expect("the builders produce a valid surface"); + + type Break = fn(&mut GameSurface); + let cases: [(&str, Break); 8] = [ + ("schemaVersion", |s| s.schema_version += 1), + ("protocolVersion", |s| s.protocol_version += 1), + ("invalid surface name", |s| s.name = "a b".into()), + ("duplicate kind id", |s| s.kinds[1].id = s.kinds[0].id), + ("non-entity wire type", |s| { + s.kinds[0].fields[0].ty = WireType::Str + }), + ("duplicate event", |s| s.events[1].id = s.events[0].id), + ("unknown record Nope", |s| { + s.events[1].payload = EventPayload::Value { + ty: WireType::Record { + name: "Nope".into(), + }, + } + }), + ("is not replicated", |s| { + s.predict.as_mut().unwrap().kind = "ghost".into() + }), + ]; + for (expected, break_it) in cases { + let mut broken = surface.clone(); + break_it(&mut broken); + let error = broken.validate().unwrap_err(); + assert!(error.contains(expected), "{expected}: {error}"); + } +} + +#[test] +#[should_panic(expected = "duplicate event id")] +fn surface_rejects_duplicate_event_ids_across_types() { + #[derive(GameEvent)] + #[game_event(id = 1)] + struct Clash {} + let _ = sample_surface().events::(); +} + +// ---- typed facts through a real host ------------------------------------- + +fn claims(principal: &str) -> TicketClaims { + TicketClaims::new( + principal, + "z1", + u64::MAX, + format!("n-{principal}"), + Role::Player, + ) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn typed_facts_bind_the_principal_and_derive_restart_safe_keys() { + let sink = MemoryFactSink::new(); + let (queue, feed) = fact_channel(64, RetryPolicy::default()); + tokio::spawn(feed.run(sink.clone(), tokio::time::sleep)); + let clock = ManualClock::new(); + let config = HostConfig { + boot_epoch: 42, + ..HostConfig::default() + }; + let mut host = + ZoneHost::::new("z1", config, Arc::new(clock.clone()), ()).with_facts(queue); + let joined = host.join(&claims("alice"), 0, "").unwrap(); + let attack = SampleInput { + mx: 0, + my: 0, + buttons: SampleInput::ATTACK, + aim: 0.0, + power: 0.5, + view_tick: 0, + }; + host.push_input(joined.client, 1, 0, &attack.to_payload()); + clock.advance(Duration::from_millis(40)); + host.advance(); + let keys = host.zone().keys.clone(); + assert_eq!(keys[0], "sample.record_kill:z1:42:7:1"); + assert!( + keys[1].starts_with("sample.tick_note:z1:42:t"), + "{}", + keys[1] + ); + assert_ne!(keys[1], keys[2], "keyless facts are numbered within a tick"); + + for _ in 0..200 { + if sink.committed().len() == 3 { + break; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + let committed = sink.committed(); + let kill = committed + .iter() + .find(|f| f.is::()) + .expect("kill committed"); + assert_eq!( + kill.principal(), + Some("alice"), + "principal from the verified ticket" + ); + assert_eq!( + kill.input(), + &json!({ "mob": 7, "generation": 1, "tier": 2 }) + ); + let note = committed + .iter() + .find(|f| f.is::()) + .expect("zone fact"); + assert_eq!(note.principal(), None); + + for _ in 0..50 { + clock.advance(Duration::from_millis(40)); + host.advance(); + if host.zone().settled.len() == 3 { + break; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + let settled = &host.zone().settled; + assert!(settled.iter().any(|s| s.is::())); + assert!(settled + .iter() + .all(|s| matches!(s.outcome, FactOutcome::Committed(_)))); + assert_eq!(RecordKill::COMMAND, RECORD_KILL); +} + +// ---- golden fixture for the generated TypeScript -------------------------- + +fn sample_board() -> Board { + Board { + version: 7, + kills: vec![ + Row { + rank: 1, + name: "Ada".into(), + score: 9_007_199_254_740_991, + }, + Row { + rank: 2, + name: "Bob ✓".into(), + score: 3, + }, + ], + note: None, + motd: "x".repeat(300), + } +} + +fn sample_events() -> Vec { + vec![ + SampleEvent::Hello { + entity: 1001, + view_radius: 14.0, + half: 64.0, + }, + SampleEvent::Board(sample_board()), + SampleEvent::Respawn, + SampleEvent::Shot { + hit: true, + target: Some(42), + offset: -300, + small: -5, + at_ms: 1234.5, + tags: vec!["a".into(), "".into()], + bytes: vec![0, 255], + total: 1 << 40, + }, + SampleEvent::Shot { + hit: false, + target: None, + offset: 0, + small: 0, + at_ms: 0.0, + tags: vec![], + bytes: vec![], + total: 0, + }, + ] +} + +/// The TypeScript-side value of each sample (camelCase keys). +fn sample_event_values() -> Vec { + let board = json!({ + "version": 7, + "kills": [ + {"rank": 1, "name": "Ada", "score": 9_007_199_254_740_991u64}, + {"rank": 2, "name": "Bob ✓", "score": 3} + ], + "note": null, + "motd": "x".repeat(300), + }); + vec![ + json!({"entity": 1001, "viewRadius": 14.0, "half": 64.0}), + board, + json!({}), + json!({"hit": true, "target": 42, "offset": -300, "small": -5, "atMs": 1234.5, "tags": ["a", ""], "bytes": [0, 255], "total": 1u64 << 40}), + json!({"hit": false, "target": null, "offset": 0, "small": 0, "atMs": 0.0, "tags": [], "bytes": [], "total": 0}), + ] +} + +fn f32_of(ty: FieldType, v: f32) -> f64 { + match ty.canonicalize(&FieldValue::F(v)) { + FieldValue::F(v) => f64::from(v), + _ => unreachable!(), + } +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +#[test] +fn golden_fixture_is_current() { + use distributed_game::prediction::PredictContext; + use distributed_game::pure::call_bytes; + let input = SampleInput { + mx: -128, + my: 100, + buttons: 0b111, + aim: -1.0, + power: 0.25, + view_tick: 123_456, + }; + let sanitized = SampleInput::from_payload(&input.to_payload()).unwrap(); + let aim_wire = f32_of(FieldType::Angle { bits: 10 }, -1.0); + let events: Vec = sample_events() + .iter() + .zip(sample_event_values()) + .map(|(event, value)| { + let name = sample_surface() + .events + .into_iter() + .find(|e| e.id == event.event_id()) + .unwrap() + .name; + json!({ "id": event.event_id(), "name": name, "value": value, "hex": hex(&event.to_payload()) }) + }) + .collect(); + let fixture = json!({ + // Through `to_json` so floats keep their shortest binary32 form. + "surface": serde_json::from_str::(&sample_surface().to_json()).unwrap(), + "input": { + "value": {"mx": -128, "my": 100, "buttons": 7, "aim": -1.0, "power": 0.25, "viewTick": 123_456}, + "hex": hex(&input.to_payload()), + "decoded": {"mx": -128, "my": 100, "buttons": 7, "aim": aim_wire, "power": 0.25, "viewTick": 123_456}, + "sanitized": {"mx": sanitized.mx, "my": sanitized.my, "buttons": sanitized.buttons, "aim": aim_wire, "power": 0.25, "viewTick": 123_456}, + }, + "events": events, + // Zone inbox messages (`/admin/zone-message` payloads). + "messages": [ + { + "id": 1, + "name": "announce", + "value": { "text": "server restart in 5", "urgent": true }, + "hex": hex(&SampleMessage::Announce { text: "server restart in 5".into(), urgent: true }.to_payload()), + }, + { + "id": 2, + "name": "set_wind", + "value": { "speed": 2.5, "gusts": 7 }, + "hex": hex(&SampleMessage::SetWind(SampleWind { speed: 2.5, gusts: 7 }).to_payload()), + }, + ], + // Each constant's encoding: the generated literal must decode-equal it. + "constants": { + "sample_board": hex(&distributed_game::codec::to_bytes(&sample_board())), + "sample_gusts": hex(&distributed_game::codec::to_bytes(&vec![0.1f32, -2.5])), + "sample_spot": hex(&distributed_game::codec::to_bytes(&sample_spot())), + }, + // Native calls of the pure functions (argument → output bytes). + "pures": [ + { + "export": "sample_mirror", + "arg": hex(&SampleWind { speed: 1.5, gusts: 65535 }.encode_context()), + "output": hex(&call_bytes::(&SampleWind { speed: 1.5, gusts: 65535 }.encode_context()).unwrap()), + }, + { + "export": "sample_rows", + "arg": "", + "output": hex(&call_bytes::(&[]).unwrap()), + }, + ], + }); + let text = serde_json::to_string_pretty(&fixture).unwrap() + "\n"; + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/authoring.json"); + if std::env::var_os("UPDATE_GOLDEN").is_some() { + std::fs::write(path, &text).unwrap(); + } + let current = std::fs::read_to_string(path).unwrap_or_default(); + assert_eq!( + current, text, + "run with UPDATE_GOLDEN=1 to regenerate {path}" + ); +} + +// ---- predicted step --------------------------------------------------------- + +#[test] +fn the_predicted_step_is_declared_in_the_surface() { + use distributed_game::prediction::{step_bytes, PredictContext, PredictStep}; + let surface = sample_surface(); + let predict = surface.predict.as_ref().expect("predicted step"); + assert_eq!(predict.kind, "player"); + assert_eq!(predict.export, "sample_step"); + assert_eq!(predict.package, "distributed_game"); + assert_eq!(predict.state, "SampleState"); + assert_eq!(predict.context.as_deref(), Some("SampleWind")); + assert_eq!(predict.abi, distributed_game::prediction::ABI_VERSION); + for record in ["SampleState", "SampleWind"] { + assert!(surface.records.iter().any(|r| r.name == record), "{record}"); + } + assert_eq!(::KIND, "player"); + + // The ABI path: encoded state, input payload (sanitized) and context. + let state = SampleState { + x: 1.0, + vx: 0.0, + hp: 9, + dead: false, + }; + let input = SampleInput { + mx: -128, + my: 0, + buttons: 0, + aim: 0.0, + power: 0.0, + view_tick: 0, + }; + let wind = SampleWind { + speed: 2.0, + gusts: 3, + }; + let next = step_bytes::( + &distributed_game::codec::to_bytes(&state), + &input.to_payload(), + &wind.encode_context(), + 0.5, + ) + .unwrap(); + let next: SampleState = distributed_game::codec::from_bytes(&next).unwrap(); + // -128 is clamped to -127 before the step, as on the server. + assert_eq!( + next, + sample_step(&state, &input.sanitize().unwrap(), &wind, 0.5) + ); + assert_eq!((next.x, next.vx, next.hp), (0.0, -2.0, 9)); +} + +#[derive(Debug, Clone, Copy, PartialEq, GameRecord)] +pub struct NotAField { + pub mana: f32, +} + +#[predict(UnknownFieldStep, kind = "player")] +pub fn unknown_field_step(state: &NotAField, _: &SampleInput, _: &(), _: f32) -> NotAField { + *state +} + +#[derive(Debug, Clone, Copy, PartialEq, GameRecord)] +pub struct WrongType { + pub hp: f32, +} + +#[predict(WrongTypeStep, kind = "player")] +pub fn wrong_type_step(state: &WrongType, _: &SampleInput, _: &(), _: f32) -> WrongType { + *state +} + +#[predict(UnknownKindStep, kind = "ghost")] +pub fn unknown_kind_step(state: &SampleState, _: &SampleInput, _: &(), _: f32) -> SampleState { + *state +} + +#[predict(OtherInputStep, kind = "player")] +pub fn other_input_step(state: &SampleState, _: &Ping2, _: &(), _: f32) -> SampleState { + *state +} + +#[derive(Debug, Clone, Copy, PartialEq, GameInput)] +pub struct Ping2 { + pub n: u8, +} + +#[test] +#[should_panic(expected = "field mana is not a field of kind player")] +fn a_state_field_must_name_a_kind_field() { + let _ = GameSurface::for_zone::("sample").predict::(); +} + +#[test] +#[should_panic(expected = "does not match kind player field type")] +fn a_state_field_must_have_the_kind_field_type() { + let _ = GameSurface::for_zone::("sample").predict::(); +} + +#[test] +#[should_panic(expected = "names kind \"ghost\"")] +fn the_predicted_kind_must_be_replicated() { + let _ = GameSurface::for_zone::("sample").predict::(); +} + +#[test] +#[should_panic(expected = "must take the zone's input type")] +fn the_step_takes_the_zone_input() { + let _ = GameSurface::for_zone::("sample").predict::(); +} + +// ---- pure functions, constants, standalone codecs --------------------------- + +#[test] +fn pure_functions_constants_and_codecs_are_declared() { + use distributed_game::pure::{call_bytes, GamePure}; + let surface = sample_surface(); + let pures: Vec<_> = surface.pures.iter().map(|p| p.export.as_str()).collect(); + assert_eq!(pures, ["sample_mirror", "sample_rows"], "sorted by export"); + let mirror = &surface.pures[0]; + assert_eq!(mirror.package, "distributed_game"); + assert_eq!( + mirror.arg, + Some(WireType::Record { + name: "SampleWind".into() + }) + ); + assert_eq!(mirror.output, mirror.arg.clone().unwrap()); + assert_eq!(surface.pures[1].arg, None); + assert_eq!(::EXPORT, "sample_rows"); + let rows: Vec = + distributed_game::codec::from_bytes(&call_bytes::(&[]).unwrap()).unwrap(); + assert_eq!(rows, sample_board().kills); + + let names: Vec<_> = surface.constants.iter().map(|c| c.name.as_str()).collect(); + assert_eq!(names, ["sample_board", "sample_gusts", "sample_spot"]); + // Values are what a client decodes: exact binary32, quantized, Rust field names. + assert_eq!(surface.constants[1].value, json!([f64::from(0.1f32), -2.5])); + let spot = &surface.constants[2].value; + let quantized = f32_of( + FieldType::QuantF32 { + min: 0.0, + max: 64.0, + bits: 10, + }, + 1.3, + ); + assert_eq!(spot, &json!({"at": quantized, "label": "dock"})); + assert_ne!(quantized, f64::from(1.3f32)); + assert_eq!( + surface.constants[0].value["kills"][0]["score"], + 9_007_199_254_740_991u64 + ); + assert_eq!(surface.codecs, ["SampleWind"]); +} + +#[test] +#[should_panic(expected = "snake_case")] +fn constant_names_are_snake_case() { + let _ = sample_surface().constant("Bad", &1u8); +} + +#[test] +#[should_panic(expected = "added twice")] +fn pure_exports_are_unique() { + let _ = sample_surface().pure::(); +} diff --git a/distributed_game/tests/bots/main.rs b/distributed_game/tests/bots/main.rs new file mode 100644 index 000000000..0f21fe12a --- /dev/null +++ b/distributed_game/tests/bots/main.rs @@ -0,0 +1,104 @@ +//! ~50 bots against an in-process server: every bot joins with a signed +//! ticket, sends inputs, receives Deltas and measures RTT; `/metrics` +//! reflects the load. + +#[path = "../support/arena.rs"] +mod arena; + +use std::time::Duration; + +use arena::{Arena, ArenaConfig}; +use distributed_game::bots::{run_bots, BehaviourKind, BotConfig}; +use distributed_game::net::{GameServer, NetSim, ServerConfig, TicketKey, ZoneFactory}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +const SECRET: &str = "bots-secret"; + +async fn http_get(addr: std::net::SocketAddr, path: &str) -> String { + let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap(); + let request = format!("GET {path} HTTP/1.1\r\nHost: test\r\nConnection: close\r\n\r\n"); + stream.write_all(request.as_bytes()).await.unwrap(); + let mut body = String::new(); + stream.read_to_string(&mut body).await.unwrap(); + body +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn fifty_bots_join_play_and_receive_deltas() { + let mut config = ServerConfig::new(TicketKey::new(SECRET)); + config.host.tick_rate = 30; + config.host.patch_rate = 20; + config.host.max_players = 64; + // Mild simulated network so RTT is measurable but the test stays fast. + config.net_sim = Some(NetSim::new( + Duration::from_millis(5), + Duration::from_millis(5), + )); + let server = GameServer::::new( + config, + ZoneFactory::sync(|a| a.zone_id.starts_with("load").then(ArenaConfig::default)), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let serving = server.clone(); + let handle = tokio::spawn(async move { + serving + .serve(listener, std::future::pending()) + .await + .unwrap(); + }); + + let mut bots = BotConfig::new(format!("ws://{addr}"), "load-1", TicketKey::new(SECRET)); + bots.bots = 50; + bots.input_rate = 20.0; + bots.ping_interval = Duration::from_millis(200); + bots.duration = Duration::from_millis(1200); + bots.ramp_up = Duration::from_millis(200); + + // Scrape while the bots are connected. + let scrape = tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(900)).await; + http_get(addr, "/metrics").await + }); + let summary = run_bots(bots, |i| { + if i % 2 == 0 { + BehaviourKind::RandomWalk.build(i) + } else { + BehaviourKind::Circle.build(i) + } + }) + .await; + println!("{summary}"); + + assert_eq!(summary.joined(), 50, "{summary}"); + assert_eq!(summary.failed(), 0, "{summary}"); + assert!( + summary.min_deltas() > 5, + "every bot received deltas: {summary}" + ); + assert!( + summary.bots.iter().all(|b| b.last_ack > 0), + "inputs were acked" + ); + assert!(summary.bots.iter().all(|b| b.entities > 0)); + let p50 = summary.rtt_quantile(0.5).expect("rtt samples"); + assert!( + p50 >= Duration::from_millis(10), + "netsim adds 2x5ms: {p50:?}" + ); + assert!(summary.delta_bytes_per_sec_per_bot() > 0.0); + + let metrics = scrape.await.unwrap(); + assert!(metrics.starts_with("HTTP/1.1 200"), "{metrics}"); + assert!(metrics.contains("text/plain; version=0.0.4")); + assert!( + metrics.contains("distributed_game_zone_players{zone=\"load-1\"} 50"), + "{metrics}" + ); + assert!(metrics + .contains("distributed_game_zone_inputs_total{zone=\"load-1\",outcome=\"accepted\"}")); + assert!(metrics.contains("distributed_game_zone_delta_bytes_count{zone=\"load-1\"}")); + + server.shutdown(); + handle.await.unwrap(); +} diff --git a/distributed_game/tests/cell_facts/main.rs b/distributed_game/tests/cell_facts/main.rs new file mode 100644 index 000000000..04600dcfa --- /dev/null +++ b/distributed_game/tests/cell_facts/main.rs @@ -0,0 +1,181 @@ +//! Fact batches committed into a real `distributed` AggregateCell with a +//! server-built trusted Session. + +use distributed::cell_host::AggregateCell; +use distributed::command::{typed_command, PreparedCommand, Succeeded}; +use distributed::microsvc::{ + CausalCommandContext, CausalRouteDependencies, HandlerError, PortableCommand, Routes, +}; +use distributed::{sourced, Entity}; +use std::collections::HashMap; + +use distributed_game::cell::{ + command_id_for, fact_session_from_headers, run_fact_batch, session_stamp, +}; +use distributed_game::{stamp_metadata, FactStamp}; +use serde::{Deserialize, Serialize}; +use serde_json::json; + +#[derive(Clone, Default, Serialize, Deserialize, distributed::Snapshot)] +struct Hero { + entity: Entity, + xp: u32, +} + +#[sourced(entity, aggregate_type = "Hero", events = "HeroEvent")] +impl Hero { + #[event("hero.xp_credited", version = 1)] + fn credit(&mut self, id: String, amount: u32) { + self.entity.set_id(id); + self.xp += amount; + } +} + +#[derive(Debug, Deserialize, distributed::CommandInput)] +struct CreditInput { + amount: u32, +} + +#[derive(Debug, Serialize, distributed::CommandOutput)] +struct CreditPayload { + hero: String, + xp: u32, + tick: String, + /// The stamp the handler read from the trusted session, after a trip + /// through event metadata. + emitted_at_ms: u64, + activation: u64, + config_version: String, +} + +struct CreditXp; + +impl PortableCommand for CreditXp +where + D: CausalRouteDependencies + Send + Sync + 'static, +{ + fn install(self, routes: Routes) -> Routes { + routes + .typed_command(typed_command::>( + "hero.credit_xp", + )) + .guarded( + |ctx: &CausalCommandContext<'_, Hero>| ctx.session().user_id().is_some(), + handle_credit, + ) + } +} + +async fn handle_credit( + ctx: &CausalCommandContext<'_, Hero>, + input: CreditInput, +) -> Result>, HandlerError> { + // Identity comes from the trusted session, never from the input. + let principal = ctx.session().user_id().unwrap_or_default().to_string(); + let tick = ctx.session().get("x-game-tick").unwrap_or("").to_string(); + let stamp = session_stamp(ctx.session()) + .ok_or_else(|| HandlerError::Rejected("fact sessions carry a stamp".into()))?; + let mut metadata = HashMap::new(); + stamp_metadata(&mut metadata, &stamp); + let stamp = FactStamp::from_metadata(&metadata).expect("metadata round trip"); + let repo = ctx.repo(); + let mut hero = match repo.get(&principal).await? { + Some(hero) => hero, + None => repo.create(), + }; + hero.credit(principal.clone(), input.amount) + .map_err(|e| HandlerError::Rejected(e.to_string()))?; + let xp = hero.xp; + repo.commit(hero)?.succeeded(CreditPayload { + hero: principal, + xp, + tick, + emitted_at_ms: stamp.emitted_at_ms, + activation: stamp.activation, + config_version: stamp.config_version, + }) +} + +#[test] +fn command_ids_are_deterministic_uuidv7_shaped() { + let a = command_id_for("svc", "coin:z1:7"); + assert_eq!(a, command_id_for("svc", "coin:z1:7")); + assert_ne!(a, command_id_for("svc", "coin:z1:8")); + assert_eq!(&a[14..15], "7"); + assert!(matches!(&a[19..20], "8" | "9" | "a" | "b")); +} + +/// A `__batch` body of `amounts` for alice, one entry per amount; `None` +/// is an entry without a partition. +fn batch_body(amounts: &[Option]) -> serde_json::Value { + let entries: Vec<_> = amounts + .iter() + .enumerate() + .map(|(i, amount)| { + let mut session = serde_json::Map::new(); + session.insert("x-user-id".into(), json!("alice")); + let stamp = FactStamp { + zone_id: "z1".into(), + tick: i as u64, + ..FactStamp::default() + }; + for (name, value) in stamp.session_vars() { + session.insert(name, json!(value)); + } + let mut entry = json!({ + "command": "hero.credit_xp", + "commandId": command_id_for("game-svc", &format!("kill:z1:{i}")), + "input": { "amount": amount.unwrap_or(1) }, + "session": session, + }); + if amount.is_some() { + entry["partition"] = json!("alice"); + } + entry + }) + .collect(); + json!({ "entries": entries }) +} + +#[tokio::test] +async fn a_replayed_batch_answers_only_replays() { + let cell = AggregateCell::::new("alice").unwrap().mount(CreditXp); + let sessions = |header: &dyn Fn(&str) -> Option| fact_session_from_headers(header); + let body = batch_body(&[Some(10), Some(20), None, Some(30)]); + + let first = run_fact_batch(&cell, "game-svc", &body, sessions) + .await + .unwrap(); + let first = first["results"].as_array().unwrap().clone(); + let statuses: Vec<_> = first + .iter() + .map(|r| r["status"].as_u64().unwrap()) + .collect(); + // The entry without a partition is refused in its place; the rest commit. + assert_eq!(statuses, [200, 200, 400, 200]); + let xp: Vec<_> = first + .iter() + .map(|r| r["body"]["payload"]["xp"].clone()) + .collect(); + assert_eq!(xp, [json!(10), json!(30), json!(null), json!(60)]); + assert!(first + .iter() + .all(|r| r["body"]["receipt"]["replayed"] != json!(true))); + + // The whole batch again, same command ids: replays only, nothing new. + let replay = run_fact_batch(&cell, "game-svc", &body, sessions) + .await + .unwrap(); + let replay = replay["results"].as_array().unwrap().clone(); + assert_eq!(replay.len(), 4); + for (i, (replayed, original)) in replay.iter().zip(&first).enumerate() { + assert_eq!(replayed["status"], original["status"]); + if i == 2 { + continue; + } + assert_eq!(replayed["body"]["receipt"]["replayed"], json!(true)); + assert_eq!(replayed["body"]["payload"], original["body"]["payload"]); + } + assert_eq!(cell.load().await.unwrap().unwrap().xp, 60, "credited once"); + assert_eq!(cell.history().await.unwrap().len(), 3); +} diff --git a/distributed_game/tests/celld_facts/main.rs b/distributed_game/tests/celld_facts/main.rs new file mode 100644 index 000000000..2e61cedc8 --- /dev/null +++ b/distributed_game/tests/celld_facts/main.rs @@ -0,0 +1,358 @@ +//! Zone facts over the network into celld cells (`CelldFactSink`). +//! +//! Owns an isolated `celld dev` process (no Docker) serving +//! `tests/celld/fact-worker` (Kills, Match and Presence cells), and kills only +//! the processes it starts. Build the worker first: +//! +//! (cd tests/celld/fact-worker && worker-build --release) +//! cargo test -p distributed_game --features celld,runtime --test celld_facts +//! +//! `CELLD` selects the binary (default `celld` on PATH); `celld dev` needs +//! esbuild (`CELLD_ESBUILD`). Without a built worker the test skips, unless +//! `CELLD_FACTS_REQUIRED=1` (CI), which turns that into a failure. + +use std::time::{Duration, Instant}; + +use distributed::cell_host::InternalHttpSecret; +use distributed_game::celld::{CelldFactSink, FactRoute}; +use distributed_game::lifecycle::{JoinVia, LeftReason, PlayerJoined, PlayerLeft}; +use distributed_game::{ + fact_channel, spawn_fact_worker, EmitError, Fact, FactCommand, FactError, FactOutcome, + FactQueue, FactSettlement, FactSink, FactStamp, RetryPolicy, +}; +use serde_json::{json, Value}; + +#[path = "../support/celld.rs"] +mod celld_support; +use celld_support::{Celld, SECRET}; +const SERVICE: &str = "zone-server-test"; + +#[derive(serde::Serialize, FactCommand)] +#[fact(command = "kills.record")] +struct Kill { + mob: String, +} + +#[derive(serde::Serialize, FactCommand)] +#[fact(command = "match.record_result")] +struct MatchResult { + match_id: String, + winner_slot: u32, +} + +fn sink(base: &str, timeout: Duration) -> CelldFactSink { + CelldFactSink::celld_with_timeout( + base, + InternalHttpSecret::new(SECRET).unwrap(), + SERVICE, + "zone:pit-1", + timeout, + ) + .unwrap() + .route(FactRoute::by_principal::("kills")) + .route(FactRoute::by_input_field::( + "match", "match_id", + )) + .lifecycle_route("presence") +} + +fn stamp(tick: u64) -> FactStamp { + FactStamp { + zone_id: "pit-1".into(), + tick, + content_version: "c1".into(), + emitted_at_ms: 1_700_000_000_000 + tick, + activation: 1, + config_version: "cfg-1".into(), + seq: tick, + } +} + +fn fact(key: &str, input: &C, principal: Option<&str>, tick: u64) -> Fact { + Fact::trusted( + key, + C::COMMAND, + serde_json::to_value(input).unwrap(), + principal.map(str::to_string), + stamp(tick), + ) +} + +async fn state(base: &str, kind: &str, shard: &str) -> Value { + reqwest::Client::new() + .get(format!("{base}/{kind}/{shard}")) + .header("x-distributed-internal-secret", SECRET) + .send() + .await + .unwrap() + .json() + .await + .unwrap() +} + +/// Drain settlements until `count` arrive (or time out). +async fn settle(queue: &mut FactQueue, count: usize, within: Duration) -> Vec { + let deadline = Instant::now() + within; + let mut settled = Vec::new(); + while settled.len() < count && Instant::now() < deadline { + settled.extend(queue.drain()); + tokio::time::sleep(Duration::from_millis(50)).await; + } + settled +} + +fn committed(settlement: &FactSettlement) -> bool { + matches!(settlement.outcome, FactOutcome::Committed(_)) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn zone_facts_route_to_three_cell_kinds_and_survive_a_celld_outage() { + let Some(mut celld) = Celld::start_new() else { + return; + }; + let base = celld.base(); + let policy = RetryPolicy::until_settled(Duration::from_millis(100), Duration::from_millis(500)); + let (mut queue, feed) = fact_channel(4, policy); + let worker = spawn_fact_worker( + feed.with_max_concurrent_commits(2), + sink(&base, Duration::from_secs(10)), + ); + + // 1. One zone, one sink, three aggregate kinds (lifecycle -> presence). + let joined = PlayerJoined { + zone: "pit-1".into(), + via: JoinVia::Ticket, + from_zone: None, + }; + queue + .try_send(fact( + "zone.player_joined:pit-1:1:p0:0", + &joined, + Some("alice"), + 1, + )) + .unwrap(); + queue + .try_send(fact( + "kills.record:pit-1:1:k1", + &Kill { mob: "m1".into() }, + Some("alice"), + 2, + )) + .unwrap(); + queue + .try_send(fact( + "kills.record:pit-1:1:k2", + &Kill { mob: "m2".into() }, + Some("bob"), + 3, + )) + .unwrap(); + queue + .try_send(fact( + "match.record_result:pit-1:1:m-7", + &MatchResult { + match_id: "m-7".into(), + winner_slot: 2, + }, + None, + 4, + )) + .unwrap(); + let settled = settle(&mut queue, 4, Duration::from_secs(30)).await; + assert_eq!(settled.len(), 4, "{settled:?}"); + assert!(settled.iter().all(committed), "{settled:?}"); + let left = PlayerLeft { + zone: "pit-1".into(), + reason: LeftReason::Left, + }; + queue + .try_send(fact( + "zone.player_left:pit-1:1:p0:1", + &left, + Some("alice"), + 5, + )) + .unwrap(); + assert!(settle(&mut queue, 1, Duration::from_secs(30)) + .await + .iter() + .all(committed)); + + assert_eq!( + state(&base, "kills", "alice").await["state"]["mobs"], + json!(["m1"]) + ); + assert_eq!( + state(&base, "kills", "bob").await["state"]["mobs"], + json!(["m2"]) + ); + assert_eq!( + state(&base, "match", "m-7").await["state"]["results"], + json!([2]) + ); + assert_eq!( + state(&base, "presence", "alice").await["state"]["transitions"], + json!(["joined:pit-1:ticket", "left:pit-1:left"]), + "lifecycle facts go to presence, not to the player's kill cell" + ); + + // 2. The same key twice (a retry after a lost response) commits once and + // replays the ledger receipt. + let direct = sink(&base, Duration::from_secs(10)); + let again = fact( + "kills.record:pit-1:1:k1", + &Kill { mob: "m1".into() }, + Some("alice"), + 2, + ); + let replay = direct.commit(&again).await.unwrap(); + assert!(replay.replayed); + assert_eq!(state(&base, "kills", "alice").await["events"], 1); + // Forced timeout after commit: the first attempt gives up before the + // response; the retry finds the commit in the ledger. + let hasty = sink(&base, Duration::from_millis(1)); + let late = fact( + "kills.record:pit-1:1:k3", + &Kill { mob: "m3".into() }, + Some("alice"), + 6, + ); + assert!(matches!( + hasty.commit(&late).await, + Err(FactError::Retryable(_)) + )); + tokio::time::sleep(Duration::from_millis(500)).await; + let receipt = direct.commit(&late).await.unwrap(); + assert_eq!( + state(&base, "kills", "alice").await["state"]["mobs"], + json!(["m1", "m3"]), + "exactly one commit for the key (replayed: {})", + receipt.replayed + ); + + // 3. An unknown command settles Permanent without a network call. + queue + .try_send(Fact::trusted( + "guild.promote:pit-1:1:x", + "guild.promote", + json!({}), + Some("alice".into()), + stamp(7), + )) + .unwrap(); + let unknown = settle(&mut queue, 1, Duration::from_secs(10)).await; + assert!( + matches!( + &unknown[0].outcome, + FactOutcome::Failed { + error: FactError::Permanent(_), + attempts: 1 + } + ), + "{unknown:?}" + ); + + // 4. The cell worker rejects requests without the internal secret. + let forged = reqwest::Client::new() + .post(format!("{base}/kills/alice/kills.record")) + .header("x-distributed-service-id", SERVICE) + .header("x-distributed-principal-partition", "alice") + .header("x-user-id", "alice") + .json(&json!({ "commandId": "0190a000-0000-7000-8000-000000000001", "input": { "mob": "x" } })) + .send() + .await + .unwrap(); + assert_eq!(forged.status(), 401); + let forged_secret = reqwest::Client::new() + .post(format!("{base}/kills/alice/kills.record")) + .header("x-distributed-internal-secret", "forged-secret-for-red-team-request-0000") + .json(&json!({ "commandId": "0190a000-0000-7000-8000-000000000002", "input": { "mob": "x" } })) + .send() + .await + .unwrap(); + assert_eq!(forged_secret.status(), 401); + // With the secret but without the fact headers, handlers refuse. + let not_a_fact = reqwest::Client::new() + .post(format!("{base}/kills/alice/kills.record")) + .header("x-distributed-internal-secret", SECRET) + .header("x-distributed-service-id", SERVICE) + .header("x-distributed-principal-partition", "alice") + .header("x-user-id", "alice") + .json(&json!({ "commandId": "0190a000-0000-7000-8000-000000000003", "input": { "mob": "x" } })) + .send() + .await + .unwrap(); + assert!( + not_a_fact.status().is_client_error(), + "{}", + not_a_fact.status() + ); + assert_eq!( + state(&base, "kills", "alice").await["state"]["mobs"], + json!(["m1", "m3"]) + ); + + // 5. celld down: facts stay pending, the zone is never blocked, the + // queue reports Backpressure at capacity. + celld.crash(); + let outage = [ + ("alice", "a1", 10), + ("bob", "b1", 11), + ("alice", "a2", 12), + ("bob", "b2", 13), + ]; + for (principal, mob, tick) in outage { + let started = Instant::now(); + queue + .try_send(fact( + &format!("kills.record:pit-1:1:{mob}"), + &Kill { mob: mob.into() }, + Some(principal), + tick, + )) + .unwrap(); + assert!( + started.elapsed() < Duration::from_millis(50), + "emitting never waits on celld" + ); + } + assert_eq!( + queue.try_send(fact( + "kills.record:pit-1:1:a3", + &Kill { mob: "a3".into() }, + Some("alice"), + 14 + )), + Err(EmitError::Backpressure) + ); + assert!( + settle(&mut queue, 1, Duration::from_secs(3)) + .await + .is_empty(), + "nothing settles while celld is down" + ); + assert_eq!(queue.in_flight(), 4); + + // celld back: the backlog drains, each principal in emission order. + celld.start().expect("celld restarts"); + let drained = settle(&mut queue, 4, Duration::from_secs(60)).await; + assert_eq!(drained.len(), 4, "{drained:?}"); + assert!(drained.iter().all(committed), "{drained:?}"); + assert_eq!( + state(&base, "kills", "alice").await["state"]["mobs"], + json!(["m1", "m3", "a1", "a2"]) + ); + assert_eq!( + state(&base, "kills", "bob").await["state"]["mobs"], + json!(["m2", "b1", "b2"]) + ); + let counts = drained + .iter() + .map(|settlement| settlement.key.clone()) + .collect::>(); + assert_eq!(counts.len(), 4); + + drop(queue); + let _ = tokio::time::timeout(Duration::from_secs(5), worker).await; +} diff --git a/distributed_game/tests/celld_zone/main.rs b/distributed_game/tests/celld_zone/main.rs new file mode 100644 index 000000000..db4ad7ed8 --- /dev/null +++ b/distributed_game/tests/celld_zone/main.rs @@ -0,0 +1,696 @@ +//! Zones as celld Durable Objects (`celld_zone`), end to end against +#![allow(clippy::await_holding_lock)] // one celld at a time (`serial`) +//! `tests/celld/zone-worker` (a tally zone, its Tally cells and its +//! ZoneActivity cell): +//! +//! - `single_node`: `celld dev`. Join with a ticket, input, facts settle in +//! the player's cell, the empty zone goes dormant then hibernated, a new +//! join wakes it with its state, tickets and transfer tickets are single +//! use, a doorway hands the player to the next zone. +//! - `watchers`: `celld dev`. Observers are passive watchers: one is +//! refused (`ASLEEP`) by a zone that never ran or sleeps, without waking +//! it; it sees an awake zone, and does not keep it awake (dormant, then +//! hibernated, its socket closed). +//! - `near_watchers`: `celld dev`. An observer whose ticket grants `wake` +//! and that says it is near wakes a sleeping zone and keeps it ticking; +//! `Near { near: false }` lets it go dormant, `Near { near: true }` makes +//! it active again, and when it lets go for good the zone hibernates. +//! Without the grant, or without saying near, a watcher stays passive. +//! - `admission`: `celld dev`. The admission conformance suite +//! (`tests/support/admission.rs`), as the `net` server runs it. +//! - `fleet`: three celld nodes in production mode on one RustFS bucket +//! (docker compose). A zone is reached through a node that does not own +//! it, the owner is killed while 200 facts are in flight: the socket +//! closes with 1012, the client rejoins through another node, the zone +//! restores, and every fact reaches the cell exactly once. +//! +//! ```text +//! (cd tests/celld/zone-worker && worker-build --release) +//! CELLD_BIN=… CELLD_ESBUILD=… cargo test -p distributed_game \ +//! --features celld,net --test celld_zone +//! ``` +//! +//! Skips without a built worker / celld (and, for `fleet`, docker and the +//! aws CLI) unless `CELLD_ZONE_REQUIRED=1`. + +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +use distributed_game::protocol::{ + error, feature, ClientMessage, ClientMirror, Hello, ServerMessage, Welcome, PROTOCOL_VERSION, +}; +use distributed_game::ticket::TicketKey; +use distributed_game::{Role, TicketClaims}; +use futures_util::{SinkExt, StreamExt}; +use serde_json::Value; +use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode; +use tokio_tungstenite::tungstenite::Message; + +#[path = "../support/admission.rs"] +mod admission; +#[path = "../support/celld.rs"] +mod celld_support; +#[path = "../support/fleet.rs"] +mod fleet; + +const INTERNAL_SECRET: &str = "test-only-internal-secret-change-me-2026"; +const TICKET_SECRET: &str = "test-only-ticket-secret-change-me-2026"; +const REQUIRED: &str = "CELLD_ZONE_REQUIRED"; + +/// One `celld dev` at a time: two starting together race for the bundler. +static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +fn serial() -> std::sync::MutexGuard<'static, ()> { + SERIAL + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +fn worker() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../tests/celld/zone-worker") +} + +fn ticket(principal: &str, zone: &str) -> String { + ticket_as(principal, zone, Role::Player) +} + +fn ticket_as(principal: &str, zone: &str, role: Role) -> String { + let exp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() + + 120; + let nonce = format!( + "{principal}-{zone}-{}", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + ); + TicketKey::new(TICKET_SECRET) + .sign(&TicketClaims::new(principal, zone, exp, nonce, role).with_name(principal)) +} + +/// An observer ticket that grants `wake` (a near watcher may wake the zone). +fn wake_ticket(principal: &str, zone: &str) -> String { + let exp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() + + 120; + let nonce = format!( + "{principal}-{zone}-wake-{}", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + ); + TicketKey::new(TICKET_SECRET).sign( + &TicketClaims::new(principal, zone, exp, nonce, Role::Observer) + .with_name(principal) + .with_wake(true), + ) +} + +type Ws = + tokio_tungstenite::WebSocketStream>; + +#[derive(Debug)] +enum Got { + Server(ServerMessage), + Closed(Option), +} + +struct Player { + ws: Ws, + seq: u32, + /// Protocol version offered in Hello (Welcomes decode in it). + protocol: u32, +} + +impl Player { + async fn connect(base: &str, zone: &str) -> Self { + Self::try_connect(base, zone).await.expect("connect") + } + + async fn try_connect(base: &str, zone: &str) -> Result { + let url = format!("{}/zones/{zone}", base.replacen("http://", "ws://", 1)); + let (ws, _) = tokio_tungstenite::connect_async(url) + .await + .map_err(|e| e.to_string())?; + Ok(Self { + ws, + seq: 0, + protocol: PROTOCOL_VERSION, + }) + } + + async fn send(&mut self, message: ClientMessage) { + self.ws + .send(Message::Binary(message.encode().into())) + .await + .expect("send"); + } + + async fn hello(&mut self, ticket: &str) { + self.hello_near(ticket, false).await; + } + + async fn hello_near(&mut self, ticket: &str, near: bool) { + self.send(ClientMessage::Hello(Hello { + protocol_version: self.protocol, + content_version: String::new(), + capabilities: 0, + ticket: ticket.into(), + reconnect_token: String::new(), + near, + })) + .await; + } + + async fn input(&mut self, payload: &[u8]) { + self.seq += 1; + self.send(ClientMessage::Input { + seq: self.seq, + client_tick: 0, + payload: payload.to_vec(), + }) + .await; + } + + async fn next(&mut self, within: Duration) -> Option { + let deadline = Instant::now() + within; + loop { + let left = deadline.saturating_duration_since(Instant::now()); + let frame = tokio::time::timeout(left, self.ws.next()).await.ok()?; + match frame { + Some(Ok(Message::Binary(bytes))) => { + match ServerMessage::decode(&bytes, &ClientMirror::new()) { + Ok(message) => return Some(Got::Server(message)), + // Deltas need the Welcome's schema; these tests skip them. + Err(_) => continue, + } + } + Some(Ok(Message::Close(frame))) => { + return Some(Got::Closed(frame.map(|f| u16::from(f.code)))) + } + Some(Ok(_)) => continue, + Some(Err(_)) | None => return Some(Got::Closed(None)), + } + } + } + + /// The first message matching `pick`, skipping others (Deltas, Pongs). + async fn expect( + &mut self, + within: Duration, + what: &str, + mut pick: impl FnMut(&Got) -> Option, + ) -> T { + let deadline = Instant::now() + within; + while let Some(got) = self + .next(deadline.saturating_duration_since(Instant::now())) + .await + { + if let Some(value) = pick(&got) { + return value; + } + if let Got::Closed(code) = got { + panic!("closed ({code:?}) while waiting for {what}"); + } + } + panic!("timed out waiting for {what}"); + } + + async fn welcome(&mut self) { + self.welcome_message().await; + } + + async fn welcome_message(&mut self) -> Welcome { + self.expect(Duration::from_secs(20), "Welcome", |got| match got { + Got::Server(ServerMessage::Welcome(w)) => Some(w.clone()), + Got::Server(ServerMessage::Error { code, message }) => { + panic!("join refused: {code} {message}") + } + _ => None, + }) + .await + } + + /// Event `type_id` carrying a u64 total. + async fn total(&mut self, type_id: u32) -> u64 { + self.expect(Duration::from_secs(20), "a total event", |got| match got { + Got::Server(ServerMessage::Event { + type_id: t, + payload, + .. + }) if *t == type_id => Some(u64::from_le_bytes(payload[..8].try_into().unwrap())), + _ => None, + }) + .await + } + + async fn refused(&mut self) -> u32 { + self.expect(Duration::from_secs(20), "an Error", |got| match got { + Got::Server(ServerMessage::Error { code, .. }) => Some(*code), + Got::Server(ServerMessage::Welcome(_)) => panic!("admitted a used ticket"), + _ => None, + }) + .await + } +} + +/// GET a JSON route with the internal secret (Null on any failure: the +/// callers poll). +async fn get(base: &str, path: &str) -> Value { + let response = reqwest::Client::new() + .get(format!("{base}{path}")) + .header("x-distributed-internal-secret", INTERNAL_SECRET) + .send() + .await + .and_then(|r| r.error_for_status()); + match response { + Ok(response) => response.json().await.unwrap_or(Value::Null), + Err(_) => Value::Null, + } +} + +/// Poll `path` until `ok` (or panic after `within`). +async fn until(base: &str, path: &str, within: Duration, ok: impl Fn(&Value) -> bool) -> Value { + let deadline = Instant::now() + within; + loop { + let value = get(base, path).await; + if ok(&value) { + return value; + } + assert!(Instant::now() < deadline, "{path}: last {value}"); + tokio::time::sleep(Duration::from_millis(200)).await; + } +} + +fn status(value: &Value) -> &str { + value["activity"]["status"].as_str().unwrap_or("") +} + +fn exactly_once(value: &Value, count: u64) -> bool { + let hits: Vec<&str> = value["hits"] + .as_array() + .map(|a| a.iter().filter_map(Value::as_str).collect()) + .unwrap_or_default(); + let distinct: std::collections::HashSet<_> = hits.iter().collect(); + assert_eq!( + distinct.len(), + hits.len(), + "a fact committed twice: {value}" + ); + hits.len() as u64 == count +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn single_node() { + let _serial = serial(); + let Some(celld) = celld_support::Celld::start_worker(&worker(), REQUIRED) else { + return; + }; + let base = celld.base(); + let long = Duration::from_secs(30); + + // Join, input, facts. + let mut ana = Player::connect(&base, "room-a").await; + let first = ticket("ana", "room-a"); + ana.hello(&first).await; + ana.welcome().await; + assert_eq!(ana.total(1).await, 0); + let active = until(&base, "/zone-activity/room-a", long, |v| { + status(v) == "active" + }) + .await; + assert_eq!(active["activity"]["restored"], false); + ana.input(&[1, 5]).await; + assert_eq!(ana.total(2).await, 5); + until(&base, "/tally/ana", long, |v| exactly_once(v, 5)).await; + + // A Welcome carries the runtime features; a version the zone does not + // speak is refused before the ticket is used, so the same ticket then + // joins. + let mut new = Player::connect(&base, "room-a").await; + new.hello(&ticket_as("new", "room-a", Role::Observer)).await; + let w = new.welcome_message().await; + assert_eq!(w.features & feature::FOCUS, feature::FOCUS); + new.send(ClientMessage::Focus { x: 1.0, y: 2.0 }).await; + let mut future = Player::connect(&base, "room-a").await; + future.protocol = PROTOCOL_VERSION - 1; + let same = ticket_as("future", "room-a", Role::Observer); + future.hello(&same).await; + assert_eq!(future.refused().await, error::VERSION_MISMATCH); + let mut future = Player::connect(&base, "room-a").await; + future.hello(&same).await; + future.welcome().await; + drop((new, future)); + + // A used ticket is refused. + let mut replay = Player::connect(&base, "room-a").await; + replay.hello(&first).await; + assert_eq!(replay.refused().await, error::UNAUTHORIZED); + + // Empty: dormant, then hibernated (dropped from memory). + ana.send(ClientMessage::Leave).await; + until(&base, "/zone-activity/room-a", long, |v| { + status(v) == "dormant" + }) + .await; + until(&base, "/zone-activity/room-a", long, |v| { + status(v) == "hibernated" + }) + .await; + let info = get(&base, "/zones/room-a/info").await; + assert_eq!(info["awake"], false, "{info}"); + + // Wake with state. + let mut ana = Player::connect(&base, "room-a").await; + ana.hello(&ticket("ana", "room-a")).await; + ana.welcome().await; + assert_eq!(ana.total(1).await, 5, "restored from the snapshot"); + let woke = until(&base, "/zone-activity/room-a", long, |v| { + status(v) == "active" + }) + .await; + assert_eq!(woke["activity"]["restored"], true); + assert!(woke["activity"]["activations"].as_u64().unwrap() >= 2); + + // A doorway: handoff to room-b with a single-use transfer ticket. + ana.input(&[2, b'b']).await; + let transfer = ana + .expect(long, "Handoff", |got| match got { + Got::Server(ServerMessage::Handoff { + target_zone, + transfer_ticket, + }) => { + assert_eq!(target_zone, "room-b"); + Some(transfer_ticket.clone()) + } + _ => None, + }) + .await; + let mut ana_b = Player::connect(&base, "room-b").await; + ana_b.hello(&transfer).await; + ana_b.welcome().await; + let mut again = Player::connect(&base, "room-b").await; + again.hello(&transfer).await; + assert_eq!(again.refused().await, error::UNAUTHORIZED); + ana_b.input(&[1, 3]).await; + assert_eq!(ana_b.total(2).await, 3); + until(&base, "/tally/ana", long, |v| exactly_once(v, 8)).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn admission() { + let _serial = serial(); + let Some(celld) = celld_support::Celld::start_worker(&worker(), REQUIRED) else { + return; + }; + let base = celld.base(); + let probe = base.clone(); + admission::run(admission::Target { + base: base.replacen("http://", "ws://", 1), + key: TicketKey::new(TICKET_SECRET), + hello_timeout: Duration::from_secs(5), + awake: move |zone: String| { + let probe = probe.clone(); + async move { get(&probe, &format!("/zones/{zone}/info")).await["awake"] == true } + }, + }) + .await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn watchers() { + let _serial = serial(); + let Some(celld) = celld_support::Celld::start_worker(&worker(), REQUIRED) else { + return; + }; + let base = celld.base(); + let long = Duration::from_secs(30); + + // A zone that never ran is not woken by a watcher. + let mut eve = Player::connect(&base, "room-w").await; + eve.hello(&ticket_as("eve", "room-w", Role::Observer)).await; + assert_eq!(eve.refused().await, error::ASLEEP); + let info = get(&base, "/zones/room-w/info").await; + assert_eq!(info["awake"], false, "{info}"); + assert_eq!(info["wakes"], 0, "{info}"); + + // A player wakes it; a watcher then sees it. + let mut ana = Player::connect(&base, "room-w").await; + ana.hello(&ticket("ana", "room-w")).await; + ana.welcome().await; + let mut eve = Player::connect(&base, "room-w").await; + eve.hello(&ticket_as("eve", "room-w", Role::Observer)).await; + eve.welcome().await; + + // The watcher keeps nothing awake: the player leaves, the zone goes + // dormant and hibernates, and the watcher is let go. + ana.send(ClientMessage::Leave).await; + until(&base, "/zone-activity/room-w", long, |v| { + status(v) == "dormant" + }) + .await; + // A watcher joining the dormant zone is greeted, and it stays dormant. + let mut late = Player::connect(&base, "room-w").await; + late.hello(&ticket_as("late", "room-w", Role::Observer)) + .await; + late.welcome().await; + until(&base, "/zone-activity/room-w", long, |v| { + status(v) == "hibernated" + }) + .await; + let closed = eve + .expect(long, "the watcher let go", |got| match got { + Got::Closed(code) => Some(*code), + _ => None, + }) + .await; + assert_eq!(closed, Some(1000)); + let info = get(&base, "/zones/room-w/info").await; + assert_eq!(info["awake"], false, "{info}"); + + // Asleep: a watcher is refused again, the zone stays asleep. + let mut eve = Player::connect(&base, "room-w").await; + eve.hello(&ticket_as("eve", "room-w", Role::Observer)).await; + assert_eq!(eve.refused().await, error::ASLEEP); + let info = get(&base, "/zones/room-w/info").await; + assert_eq!(info["awake"], false, "{info}"); + assert_eq!(info["wakes"], 1, "woken once, by the player: {info}"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn near_watchers() { + let _serial = serial(); + let Some(celld) = celld_support::Celld::start_worker(&worker(), REQUIRED) else { + return; + }; + let base = celld.base(); + let long = Duration::from_secs(30); + let zone = "room-n"; + + // Near without the ticket's grant: passive, refused while asleep. + let mut eve = Player::connect(&base, zone).await; + eve.hello_near(&ticket_as("eve", zone, Role::Observer), true) + .await; + assert_eq!(eve.refused().await, error::ASLEEP); + // The grant without saying near: passive too. + let mut eve = Player::connect(&base, zone).await; + eve.hello_near(&wake_ticket("eve", zone), false).await; + assert_eq!(eve.refused().await, error::ASLEEP); + let info = get(&base, &format!("/zones/{zone}/info")).await; + assert_eq!(info["awake"], false, "{info}"); + assert_eq!(info["wakes"], 0, "{info}"); + + // Granted and near: wakes the zone, which ticks with no player. + let mut near = Player::connect(&base, zone).await; + near.hello_near(&wake_ticket("ana", zone), true).await; + near.welcome().await; + until(&base, &format!("/zone-activity/{zone}"), long, |v| { + status(v) == "active" + }) + .await; + // Kept awake past the hibernation delay (2 s here). + tokio::time::sleep(Duration::from_secs(4)).await; + let info = get(&base, &format!("/zones/{zone}/info")).await; + assert_eq!(info["ticking"], true, "{info}"); + assert_eq!(info["players"], 0, "{info}"); + assert_eq!(info["near"], 1, "{info}"); + assert_eq!( + status(&get(&base, &format!("/zone-activity/{zone}")).await), + "active" + ); + + // A watcher without the grant cannot become near. + let mut passive = Player::connect(&base, zone).await; + passive.hello(&ticket_as("bo", zone, Role::Observer)).await; + passive.welcome().await; + passive.send(ClientMessage::Near { near: true }).await; + let denied = passive + .expect(long, "WAKE_DENIED", |got| match got { + Got::Server(ServerMessage::Error { code, .. }) => Some(*code), + _ => None, + }) + .await; + assert_eq!(denied, error::WAKE_DENIED); + let info = get(&base, &format!("/zones/{zone}/info")).await; + assert_eq!(info["near"], 1, "{info}"); + + // Passive again: dormant; near again: active (no reconnect). + near.send(ClientMessage::Near { near: false }).await; + until(&base, &format!("/zone-activity/{zone}"), long, |v| { + status(v) == "dormant" + }) + .await; + near.send(ClientMessage::Near { near: true }).await; + until(&base, &format!("/zone-activity/{zone}"), long, |v| { + status(v) == "active" + }) + .await; + let info = until(&base, &format!("/zones/{zone}/info"), long, |v| { + v["ticking"] == true + }) + .await; + assert_eq!(info["wakes"], 1, "woken once: {info}"); + + // Let go for good: dormant, then hibernated; the watchers are closed. + near.send(ClientMessage::Near { near: false }).await; + until(&base, &format!("/zone-activity/{zone}"), long, |v| { + status(v) == "hibernated" + }) + .await; + for watcher in [&mut near, &mut passive] { + let closed = watcher + .expect(long, "the watcher let go", |got| match got { + Got::Closed(code) => Some(*code), + _ => None, + }) + .await; + assert_eq!(closed, Some(1000)); + } + let info = get(&base, &format!("/zones/{zone}/info")).await; + assert_eq!(info["awake"], false, "{info}"); + + // A near watcher that disconnects releases the zone too. + let mut near = Player::connect(&base, zone).await; + near.hello_near(&wake_ticket("ana", zone), true).await; + near.welcome().await; + until(&base, &format!("/zone-activity/{zone}"), long, |v| { + status(v) == "active" + }) + .await; + drop(near); + until(&base, &format!("/zone-activity/{zone}"), long, |v| { + status(v) == "hibernated" + }) + .await; + let info = get(&base, &format!("/zones/{zone}/info")).await; + assert_eq!(info["wakes"], 2, "{info}"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn fleet() { + let _serial = serial(); + let Some(mut fleet) = + fleet::Fleet::start(&worker(), 3, &[("CELLD_ZONE_NODES", "{nodes}")], REQUIRED) + else { + return; + }; + let long = Duration::from_secs(60); + // First touch through node-a places the zone (celld: first touch). + let a = fleet.base(0); + let mut probe = Player::connect(&a, "room-x").await; + probe.hello(&ticket("probe", "room-x")).await; + probe.welcome().await; + let info = until(&a, "/zones/room-x/info", long, |v| { + v["node"].as_str().is_some_and(|n| !n.is_empty()) + }) + .await; + let owner = fleet + .index(info["node"].as_str().unwrap()) + .expect("known node"); + probe.send(ClientMessage::Leave).await; + // Empty: the zone writes its snapshot and goes dormant. + until(&a, "/zone-activity/room-x", long, |v| { + status(v) == "dormant" + }) + .await; + let via = (owner + 1) % 3; + let rejoin_via = (owner + 2) % 3; + + // Play through a node that does not own the zone (forwarded). + let mut bo = Player::connect(&fleet.base(via), "room-x").await; + bo.hello(&ticket("bo", "room-x")).await; + bo.welcome().await; + bo.input(&[1, 200]).await; + assert_eq!(bo.total(2).await, 200); + // Crash the owner once the 200 facts are in the zone's outbox (written + // right after the tick that emitted them); some may already be + // committed, most are in flight. + until(&a, "/zones/room-x/info", long, |v| { + v["spooledFacts"].as_u64().unwrap_or(0) >= 200 + }) + .await; + fleet.kill(owner); + let closed = bo + .expect(Duration::from_secs(30), "the close", |got| match got { + Got::Closed(code) => Some(*code), + _ => None, + }) + .await; + assert_eq!( + closed, + Some(u16::from(CloseCode::Restart)), + "a forwarded socket of a crashed zone closes with 1012" + ); + + // Rejoin through the third node: celld recovers the zone elsewhere. + let base = fleet.base(rejoin_via); + let deadline = Instant::now() + long; + let (_bo, restored) = loop { + let mut bo = match Player::try_connect(&base, "room-x").await { + Ok(bo) => bo, + // celld answers 500 until the dead owner's lease expires. + Err(_) => { + assert!(Instant::now() < deadline, "the zone never came back"); + tokio::time::sleep(Duration::from_millis(500)).await; + continue; + } + }; + bo.hello(&ticket("bo", "room-x")).await; + let got = bo + .expect( + Duration::from_secs(20), + "Welcome or Error", + |got| match got { + Got::Server(ServerMessage::Welcome(_)) => Some(true), + Got::Server(ServerMessage::Error { .. }) => Some(false), + Got::Closed(_) => Some(false), + _ => None, + }, + ) + .await; + if got { + let total = bo.total(1).await; + break (bo, total); + } + assert!(Instant::now() < deadline, "the zone never came back"); + tokio::time::sleep(Duration::from_millis(500)).await; + }; + assert!(restored <= 200, "restored total {restored}"); + // Every hit the zone emitted reaches the cell exactly once. + until(&base, "/tally/bo", long, |v| exactly_once(v, 200)).await; + let activity = until(&base, "/zone-activity/room-x", long, |v| { + status(v) == "active" && v["activity"]["restored"] == true + }) + .await; + assert_ne!( + activity["activity"]["node"].as_str().unwrap_or(""), + fleet.nodes[owner].name, + "recovered on a live node" + ); +} diff --git a/distributed_game/tests/celld_zone_lease/main.rs b/distributed_game/tests/celld_zone_lease/main.rs new file mode 100644 index 000000000..46ce317e2 --- /dev/null +++ b/distributed_game/tests/celld_zone_lease/main.rs @@ -0,0 +1,178 @@ +//! Zone ownership as celld cells (`CellZoneOwnership` → `ZoneLease:{zone}`) +//! on an isolated `celld dev`: the ownership conformance suite, expiry +//! declared by the cell alarm when a holder stops renewing, renewals that +//! keep the lease, and a `GameServer` running a zone on it. +//! +//! (cd tests/celld/fact-worker && worker-build --release) +//! cargo test -p distributed_game --features celld,runtime,net --test celld_zone_lease + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use distributed::cell_host::InternalHttpSecret; +use distributed_game::celld::CellZoneOwnership; +use distributed_game::net::{GameServer, ServerConfig, TicketKey, ZoneFactory}; +use distributed_game::world::{ + ownership_conformance, restart_conformance, OwnershipError, ZoneOwnership, +}; +use serde_json::Value; + +#[path = "../support/arena.rs"] +mod arena; +#[path = "../support/celld.rs"] +mod celld_support; +use arena::{Arena, ArenaConfig}; +use celld_support::{Celld, SECRET}; + +fn ownership(base: &str, host: &str) -> CellZoneOwnership { + CellZoneOwnership::new( + base, + InternalHttpSecret::new(SECRET).unwrap(), + "zone-lease-test", + host, + ) + .unwrap() +} + +async fn lease(base: &str, zone: &str) -> Value { + reqwest::Client::new() + .get(format!("{base}/zone-lease/{zone}")) + .header("x-distributed-internal-secret", SECRET) + .send() + .await + .unwrap() + .json() + .await + .unwrap() +} + +fn count(state: &Value, event: &str) -> usize { + state["eventNames"].as_array().map_or(0, |names| { + names.iter().filter(|name| *name == event).count() + }) +} + +async fn until(what: &str, within: Duration, mut check: impl AsyncFnMut() -> bool) { + let deadline = Instant::now() + within; + while Instant::now() < deadline { + if check().await { + return; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + panic!("timed out: {what}"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn zone_leases_live_in_celld_cells() { + let Some(celld) = Celld::start_new() else { + return; + }; + let base = celld.base(); + let own = ownership(&base, "host-a"); + + // 1. Fenced, exclusive, strictly increasing tokens; Held and Lost. + ownership_conformance(&own, "zl-conformance").await; + let conformance = lease(&base, "zl-conformance").await; + assert_eq!(count(&conformance, "zone.activated"), 3); + assert_eq!(count(&conformance, "zone.released"), 3); + assert_eq!(count(&conformance, "zone.lease_expired"), 0); + + // 2. A holder that stops renewing: exactly one zone.lease_expired after + // the TTL, declared by the cell's own alarm (nobody calls the cell). + let dead = own + .acquire("zl-expire", "a#1", Duration::from_millis(1_500)) + .await + .unwrap(); + until("lease expiry", Duration::from_secs(20), async || { + lease(&base, "zl-expire").await["state"]["holder"].is_null() + }) + .await; + tokio::time::sleep(Duration::from_secs(2)).await; + let expired = lease(&base, "zl-expire").await; + assert_eq!(count(&expired, "zone.lease_expired"), 1, "{expired}"); + assert_eq!(expired["armedAlarms"], 0); + assert_eq!( + own.renew(&dead, Duration::from_secs(1)).await, + Err(OwnershipError::Lost) + ); + let next = own + .acquire("zl-expire", "b#1", Duration::from_secs(5)) + .await + .unwrap(); + assert!(next.token > dead.token); + own.release(&next).await; + + // 2b. A crash-restarted holder (same host, new incarnation): Held while + // the dead claim lives, a larger token once the cell expired it. + let base_for_expiry = base.clone(); + restart_conformance( + &own, + "zl-restart", + Duration::from_millis(1_500), + until("restart expiry", Duration::from_secs(20), async move || { + lease(&base_for_expiry, "zl-restart").await["state"]["holder"].is_null() + }), + ) + .await; + + // 3. Renewals keep the lease past many TTLs, without expiry or outward + // events. + let mut live = own + .acquire("zl-renew", "a#1", Duration::from_millis(1_500)) + .await + .unwrap(); + for _ in 0..10 { + tokio::time::sleep(Duration::from_millis(400)).await; + live = own + .renew(&live, Duration::from_millis(1_500)) + .await + .unwrap(); + } + let renewed = lease(&base, "zl-renew").await; + assert_eq!(renewed["state"]["holder"], "a#1"); + assert_eq!(count(&renewed, "zone.lease_expired"), 0); + assert_eq!(count(&renewed, "zone_lease.renewed"), 10); + own.release(&live).await; + + // 4. A zone server runs a zone under the celld lease: the cell sees the + // holder while the server renews, and the lease ends when it stops. + let mut config = ServerConfig::new(TicketKey::new("celld-lease-test-ticket-secret")); + config.ownership_ttl = Duration::from_secs(3); + config.ownership_renew_every = Duration::from_millis(500); + let server = GameServer::::new( + config, + ZoneFactory::sync(|_| Some(ArenaConfig::default())), + ) + .with_host_id("A") + .with_ownership(Arc::new(ownership(&base, "host-a"))); + assert!(server.activate("zl-game").await, "zone activated"); + let held = lease(&base, "zl-game").await; + let holder = held["state"]["holder"] + .as_str() + .unwrap_or_default() + .to_string(); + assert!(holder.starts_with("A#"), "{held}"); + tokio::time::sleep(Duration::from_secs(5)).await; + let kept = lease(&base, "zl-game").await; + assert_eq!( + kept["state"]["holder"], + holder.as_str(), + "renewed past the TTL" + ); + assert_eq!(count(&kept, "zone.lease_expired"), 0); + server.shutdown(); + until( + "lease end after shutdown", + Duration::from_secs(20), + async || lease(&base, "zl-game").await["state"]["holder"].is_null(), + ) + .await; + let ended = lease(&base, "zl-game").await; + assert_eq!( + count(&ended, "zone.released") + count(&ended, "zone.lease_expired"), + 1, + "exactly one terminal event: {ended}" + ); + drop(celld); +} diff --git a/distributed_game/tests/celld_zone_state/main.rs b/distributed_game/tests/celld_zone_state/main.rs new file mode 100644 index 000000000..bf1d2b1b8 --- /dev/null +++ b/distributed_game/tests/celld_zone_state/main.rs @@ -0,0 +1,61 @@ +//! Hibernation snapshots in celld cells (`CellZoneStateStore` → +//! `ZoneState:{zone}`) on an isolated `celld dev`: the zone-state fencing +//! contract for an inline snapshot and for one above the inline limit (in +//! celld's R2 object storage), and both surviving a celld crash. +//! +//! (cd tests/celld/fact-worker && worker-build --release) +//! cargo test -p distributed_game --features celld,runtime --test celld_zone_state + +use distributed::cell_host::InternalHttpSecret; +use distributed_game::celld::CellZoneStateStore; +use distributed_game::world::zone_state::ZONE_STATE_INLINE_MAX; +use distributed_game::world::{state_store_conformance, StoredZoneState, ZoneStateStore}; + +#[path = "../support/celld.rs"] +mod celld_support; +use celld_support::{Celld, SECRET}; + +fn store(base: &str) -> CellZoneStateStore { + CellZoneStateStore::new( + base, + InternalHttpSecret::new(SECRET).unwrap(), + "zone-state-test", + "host-a", + ) + .unwrap() +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn snapshots_are_fenced_inline_and_in_object_storage_and_survive_a_crash() { + let Some(mut celld) = Celld::start_new() else { + return; + }; + let states = store(&celld.base()); + state_store_conformance(&states, "grid.0.0", vec![1; 512]).await; + let big: Vec = (0..ZONE_STATE_INLINE_MAX * 3) + .map(|i| (i % 253) as u8) + .collect(); + state_store_conformance(&states, "grid.0.1", big.clone()).await; + + // celld crashes (process tree killed) and restarts on its state. + celld.crash(); + celld.start().expect("celld restarts"); + let states = store(&celld.base()); + let small = states.load("grid.0.0").await.unwrap().unwrap(); + assert_eq!((small.token, small.state.len()), (5, 512)); + let large = states.load("grid.0.1").await.unwrap().unwrap(); + assert_eq!(large.token, 5); + assert_eq!(large.state, big, "the object came back byte for byte"); + // Fencing state survived too. + assert!(states + .save( + "grid.0.1", + &StoredZoneState { + token: 4, + content_version: "c1".into(), + state: vec![0; 10], + }, + ) + .await + .is_err()); +} diff --git a/distributed_game/tests/command_facts/main.rs b/distributed_game/tests/command_facts/main.rs new file mode 100644 index 000000000..da31577ac --- /dev/null +++ b/distributed_game/tests/command_facts/main.rs @@ -0,0 +1,286 @@ +//! The fact routes a zone server uses with celld (`tests/celld_facts`), on +//! an ordinary service instead: `CommandFactSink` over an +//! in-memory repository. Kills land in the killer's stream, match results in +//! the match's stream, lifecycle facts in the player's — no cell involved — +//! with the trusted principal and stamp, exactly once per fact key. + +use std::sync::Arc; + +use distributed::command::{typed_command, PreparedCommand, Succeeded}; +use distributed::microsvc::{ + CausalCommandContext, CausalRouteDependencies, HandlerError, PortableCommand, Routes, Service, +}; +use distributed::{sourced, AggregateRepository, Entity, InMemoryRepository, LocalCommandHost}; +use distributed_game::cell::session_stamp; +use distributed_game::command_sink::{CommandFactSink, FactRoute}; +use distributed_game::lifecycle::{JoinVia, PlayerJoined, LIFECYCLE_COMMANDS}; +use distributed_game::{Fact, FactCommand, FactError, FactSink, FactStamp}; +use serde::{Deserialize, Serialize}; +use serde_json::json; + +#[derive(Serialize, FactCommand)] +#[fact(command = "kills.record")] +struct Kill { + mob: String, +} + +#[derive(Serialize, FactCommand)] +#[fact(command = "match.record_result")] +struct MatchResult { + match_id: String, + winner_slot: u32, +} + +/// One stream per routed shard: a player's kills and lifecycle, a match. +#[derive(Clone, Default, Serialize, Deserialize, distributed::Snapshot)] +struct Log { + entity: Entity, + entries: Vec, +} + +#[sourced(entity, aggregate_type = "Log", events = "LogEvent")] +impl Log { + #[event("log.recorded", version = 1)] + fn recorded(&mut self, id: String, entry: String) { + if self.entity.id().is_empty() { + self.entity.set_id(id); + } + self.entries.push(entry); + } +} + +#[derive(Debug, Deserialize, distributed::CommandInput)] +struct KillInput { + mob: String, +} + +#[derive(Debug, Deserialize, distributed::CommandInput)] +struct ResultInput { + match_id: String, + winner_slot: u32, +} + +#[derive(Debug, Deserialize, distributed::CommandInput)] +#[allow(dead_code)] +struct LifecycleInput { + zone: String, + via: Option, + from_zone: Option, + reason: Option, + grace_ms: Option, + cause: Option, +} + +#[derive(Debug, Serialize, distributed::CommandOutput)] +struct Recorded { + stream: String, + entries: usize, +} + +fn rejected(error: impl std::fmt::Display) -> HandlerError { + HandlerError::Rejected(error.to_string()) +} + +/// Append `entry` to stream `id` (the shard the route would address). +async fn record( + ctx: &CausalCommandContext<'_, Log>, + id: String, + entry: String, +) -> Result>, HandlerError> { + let repo = ctx.repo(); + let mut log = match repo.get(&id).await? { + Some(log) => log, + None => repo.create(), + }; + log.recorded(id.clone(), entry).map_err(rejected)?; + let entries = log.entries.len(); + repo.commit(log)?.succeeded(Recorded { + stream: id, + entries, + }) +} + +async fn handle_kill( + ctx: &CausalCommandContext<'_, Log>, + input: KillInput, +) -> Result>, HandlerError> { + // Same shard as `FactRoute::by_principal`: the trusted session's user. + let principal = ctx.user_id()?.to_string(); + let zone = session_stamp(ctx.session()) + .ok_or_else(|| rejected("no stamp"))? + .zone_id; + record( + ctx, + format!("kills/{principal}"), + format!("{}@{zone}", input.mob), + ) + .await +} + +async fn handle_result( + ctx: &CausalCommandContext<'_, Log>, + input: ResultInput, +) -> Result>, HandlerError> { + // Same shard as `FactRoute::by_input_field("match_id")`. + record( + ctx, + format!("match/{}", input.match_id), + format!("winner {}", input.winner_slot), + ) + .await +} + +async fn handle_joined( + ctx: &CausalCommandContext<'_, Log>, + input: LifecycleInput, +) -> Result>, HandlerError> { + let principal = ctx.user_id()?.to_string(); + record( + ctx, + format!("presence/{principal}"), + format!("joined {}", input.zone), + ) + .await +} + +struct Commands; +impl PortableCommand for Commands +where + D: CausalRouteDependencies + Send + Sync + 'static, +{ + fn install(self, routes: Routes) -> Routes { + routes + .typed_command(typed_command::>( + Kill::COMMAND, + )) + .handle(handle_kill) + .typed_command(typed_command::>( + MatchResult::COMMAND, + )) + .handle(handle_result) + .typed_command(typed_command::>( + LIFECYCLE_COMMANDS[0], + )) + .handle(handle_joined) + } +} + +fn stamp(tick: u64) -> FactStamp { + FactStamp { + zone_id: "pit-1".into(), + tick, + content_version: "c1".into(), + emitted_at_ms: 1_700_000_000_000 + tick, + activation: 1, + config_version: "cfg-1".into(), + seq: tick, + } +} + +fn fact( + key: &str, + input: &C, + principal: Option<&str>, + tick: u64, +) -> Fact { + Fact::trusted( + key, + C::COMMAND, + serde_json::to_value(input).unwrap(), + principal.map(str::to_string), + stamp(tick), + ) +} + +#[tokio::test] +async fn the_celld_fact_routes_land_on_a_service_over_any_repository() { + let repo = InMemoryRepository::new(); + let routes = Commands.install(Routes::new().with_repo(AggregateRepository::new(repo.clone()))); + let service = Arc::new(Service::new().named("zone-server-test").routes(routes)); + // The same routes as the celld fact-routing test. + let sink = CommandFactSink::new( + LocalCommandHost::new(service), + "zone-server-test", + "zone:pit-1", + ) + .unwrap() + .route(FactRoute::by_principal::("kills")) + .route(FactRoute::by_input_field::( + "match", "match_id", + )) + .lifecycle_route("presence"); + + let kill = fact("kill:1", &Kill { mob: "m1".into() }, Some("alice"), 1); + let first = sink.commit(&kill).await.unwrap(); + assert!(!first.replayed); + assert_eq!( + first.payload, + json!({ "stream": "kills/alice", "entries": 1 }) + ); + let again = sink.commit(&kill).await.unwrap(); + assert!(again.replayed, "same fact key replays through the ledger"); + assert_eq!(again.payload, first.payload); + let second = sink + .commit(&fact( + "kill:2", + &Kill { mob: "m2".into() }, + Some("alice"), + 2, + )) + .await + .unwrap(); + assert_eq!(second.payload["entries"], 2, "credited once per key"); + + let result = sink + .commit(&fact( + "result:1", + &MatchResult { + match_id: "m-7".into(), + winner_slot: 1, + }, + None, + 3, + )) + .await + .unwrap(); + assert_eq!(result.payload["stream"], "match/m-7"); + + let joined = PlayerJoined { + zone: "pit-1".into(), + via: JoinVia::Ticket, + from_zone: None, + }; + let lifecycle = Fact::trusted( + "joined:1", + LIFECYCLE_COMMANDS[0], + serde_json::to_value(&joined).unwrap(), + Some("alice".into()), + stamp(4), + ); + let presence = sink.commit(&lifecycle).await.unwrap(); + assert_eq!(presence.payload["stream"], "presence/alice"); + + // Unrouted commands are permanent; so is a command the service rejects. + let unrouted = Fact::trusted( + "x", + "guild.whatever", + json!({}), + Some("alice".into()), + stamp(5), + ); + assert!(matches!( + sink.commit(&unrouted).await, + Err(FactError::Permanent(_)) + )); + let forged = Fact::trusted( + "kill:3", + Kill::COMMAND, + json!({ "mob": "m3", "xp": 9999 }), + Some("alice".into()), + stamp(6), + ); + assert!(matches!( + sink.commit(&forged).await, + Err(FactError::Permanent(_)) + )); +} diff --git a/distributed_game/tests/content_rollout/main.rs b/distributed_game/tests/content_rollout/main.rs new file mode 100644 index 000000000..e6a423c38 --- /dev/null +++ b/distributed_game/tests/content_rollout/main.rs @@ -0,0 +1,123 @@ +//! The `ContentRollout` cell on the in-process reference host, driven by a +//! `ManualClock`: only a content admin starts a rollout, the cell freezes → +//! applies → settles on its own schedule, one rollout at a time, and a zone +//! following it (`zone_step`) freezes, then switches and resumes. + +use std::time::{Duration, SystemTime}; + +use distributed::cell_host::{ + AggregateCell, CausalDispatchError, CellCommandIdentity, CellStreamStore, +}; +use distributed::microsvc::{Session, ROLE_KEY, USER_ID_KEY}; +use distributed::{ManualClock, StreamIdentity}; +use distributed_game::cell::command_id_for; +use distributed_game::world::content_rollout::{ + mount_content_rollout, zone_step, ContentRollout, ZoneStep, CONTENT_ADMIN_ROLE, PHASE_APPLIED, + PHASE_FREEZING, PHASE_RUNNING, START, +}; +use serde_json::{json, Value}; + +const T0: u64 = 1_700_000_000_000; + +fn cell(clock: &ManualClock) -> AggregateCell { + let store = + CellStreamStore::for_identity(StreamIdentity::new("ContentRollout", "world").unwrap()) + .with_clock(clock.clone()); + mount_content_rollout(AggregateCell::from_store(store).unwrap()) +} + +fn session(admin: bool) -> Session { + let mut session = Session::new(); + session.set(USER_ID_KEY, "admin:dev"); + if admin { + session.set(ROLE_KEY, CONTENT_ADMIN_ROLE); + } + session +} + +async fn start( + cell: &AggregateCell, + id: &str, + version: &str, + admin: bool, +) -> Result { + let identity = CellCommandIdentity::new("test", "admin:dev", command_id_for("t", id)).unwrap(); + let input = json!({ + "world": "world", "version": version, "notes": format!("{version} notes"), + "freeze_ms": 2_000, "hard": false, + }); + cell.dispatch_idempotent(START, &identity, input, session(admin)) + .await + .map(|r| r.payload().clone()) +} + +async fn state( + cell: &AggregateCell, +) -> distributed_game::world::content_rollout::ContentState { + cell.load().await.unwrap().expect("rollout").state() +} + +#[tokio::test] +async fn an_admin_rolls_content_out_on_the_cells_own_schedule() { + let clock = ManualClock::new(SystemTime::UNIX_EPOCH + Duration::from_millis(T0)); + let cell = cell(&clock); + + assert!( + start(&cell, "a", "frostfall", false).await.is_err(), + "not a content admin" + ); + let receipt = start(&cell, "b", "frostfall", true).await.unwrap(); + assert_eq!(receipt["phase"], PHASE_FREEZING); + let s = state(&cell).await; + assert_eq!((s.version.as_str(), s.target.as_str()), ("", "frostfall")); + assert_eq!(s.notes, "frostfall notes"); + assert!( + start(&cell, "c", "emberfall", true).await.is_err(), + "one rollout at a time" + ); + // A zone following it freezes, once. + assert_eq!(zone_step(&s, "", false), ZoneStep::Freeze); + assert_eq!(zone_step(&s, "", true), ZoneStep::Stay); + + // The freeze holds for `freeze_ms`, then the version applies. + clock.advance(Duration::from_millis(1_999)); + assert!(cell.fire_due_schedules().await.unwrap().fired.is_empty()); + clock.advance(Duration::from_millis(1)); + assert_eq!(cell.fire_due_schedules().await.unwrap().fired.len(), 1); + let s = state(&cell).await; + assert_eq!(s.phase, PHASE_APPLIED); + assert_eq!(s.version, "frostfall"); + assert_eq!(zone_step(&s, "", true), ZoneStep::Apply("frostfall".into())); + + // …and the rollout settles; a zone that slept through it catches up. + clock.advance(Duration::from_millis(3_000)); + assert_eq!(cell.fire_due_schedules().await.unwrap().fired.len(), 1); + let s = state(&cell).await; + assert_eq!(s.phase, PHASE_RUNNING); + assert_eq!( + zone_step(&s, "", false), + ZoneStep::Apply("frostfall".into()) + ); + assert_eq!(zone_step(&s, "frostfall", false), ZoneStep::Stay); + assert!( + start(&cell, "d", "frostfall", true).await.is_err(), + "that version is live" + ); + start(&cell, "e", "emberfall", true).await.unwrap(); + + // Every phase change left as an outward event. + let events: Vec<_> = cell + .durable_outbox() + .unwrap() + .into_iter() + .map(|m| m.event_type) + .collect(); + for name in ["content.freezing", "content.applied", "content.settled"] { + assert!( + events + .iter() + .any(|e| e.contains(name.split('.').nth(1).unwrap())), + "{name} in {events:?}" + ); + } +} diff --git a/distributed_game/tests/entities/main.rs b/distributed_game/tests/entities/main.rs new file mode 100644 index 000000000..3b9c1ccf3 --- /dev/null +++ b/distributed_game/tests/entities/main.rs @@ -0,0 +1,247 @@ +//! Zone entities projected into views (`distributed_game::entity`): +//! `#[replicated(.., of = T)]` + `#[from]`, `Project`, and the host +//! projecting registered collections before `Zone::replicate`. + +use std::collections::BTreeMap; +use std::sync::Arc; + +use distributed_game::{ + schema, Ctx, Entities, Entity, EntityId, EntitySchema, FieldValue, HostConfig, ManualClock, + PlayerId, Project, Replicated, WorldView, Zone, ZoneHost, +}; + +#[derive(Debug, Clone, Copy, Default)] +struct Body { + x: f32, + y: f32, +} + +/// Server state: `home` and `hp` never leave the zone as such. +struct Mob { + id: EntityId, + body: Body, + home: (f32, f32), + hp: i32, + max_hp: i32, +} + +impl Entity for Mob { + fn entity_id(&self) -> EntityId { + self.id + } +} + +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "mob", id = 1, of = Mob)] +struct MobView { + #[from(body.x)] + x: f32, + #[from(body.y)] + y: f32, + /// HP percent. + hp: u8, +} + +impl Project for Mob { + fn view(&self) -> Option { + (self.hp > 0).then(|| { + MobView::project( + self, + MobViewRest { + hp: (self.hp * 100 / self.max_hp) as u8, + }, + ) + }) + } +} + +/// Every field `#[from]`: the `Project` impl is generated. +#[derive(Debug, Clone, Copy)] +struct Rock { + id: EntityId, + x: f32, + y: f32, + r: f32, +} + +impl Entity for Rock { + fn entity_id(&self) -> EntityId { + self.id + } +} + +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "rock", id = 2, global, of = Rock)] +struct RockView { + #[from] + x: f32, + #[from] + y: f32, + #[from] + r: f32, +} + +/// The zone projects its own HUD numbers. +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "hud", id = 3, global, of = Field)] +struct HudView { + alive: u8, +} + +/// A view without `of`, pushed by hand in `replicate`. +#[derive(Debug, Clone, PartialEq, Replicated)] +#[replicated(kind = "marker", id = 4)] +struct MarkerView { + x: f32, + y: f32, +} + +struct Field { + mobs: Vec, + rocks: BTreeMap, + boss: Option, +} + +impl Entity for Field { + fn entity_id(&self) -> EntityId { + EntityId(900) + } +} + +impl Project for Field { + fn view(&self) -> Option { + let alive = self.mobs.iter().filter(|m| m.hp > 0).count(); + Some(HudView::project(self, HudViewRest { alive: alive as u8 })) + } +} + +fn mob(id: u32, x: f32, hp: i32) -> Mob { + Mob { + id: EntityId(id), + body: Body { x, y: -x }, + home: (x, x), + hp, + max_hp: 40, + } +} + +impl Zone for Field { + type Config = (); + type Input = (); + type Timer = (); + type Message = distributed_game::NoMessages; + + fn schema() -> EntitySchema { + schema![MobView, RockView, HudView, MarkerView] + } + + fn entities() -> Entities { + Entities::new() + .each(|z: &Self| &z.mobs) + .each(|z: &Self| &z.rocks) + .each(|z: &Self| &z.boss) + .one(|z: &Self| z) + } + + fn on_create(_ctx: &mut Ctx<'_, Self>, _config: ()) -> Self { + Self { + mobs: vec![mob(1, 1.0, 40), mob(2, 2.0, 0), mob(3, 3.0, 10)], + rocks: [(7u8, 5.0f32), (3, 4.0)] + .into_iter() + .map(|(k, x)| { + ( + k, + Rock { + id: EntityId(100 + u32::from(k)), + x, + y: 0.0, + r: 0.5, + }, + ) + }) + .collect(), + boss: Some(mob(50, 9.0, 20)), + } + } + + fn decode_input(&self, _player: PlayerId, _payload: &[u8]) -> Option<()> { + None + } + + fn on_tick(&mut self, _ctx: &mut Ctx<'_, Self>) {} + + fn replicate(&self, out: &mut WorldView) { + out.add(EntityId(77), &MarkerView { x: 0.5, y: 0.5 }); + } +} + +#[test] +fn registered_collections_are_projected_in_order_then_replicate_runs() { + let host = ZoneHost::::new( + "field", + HostConfig::default(), + Arc::new(ManualClock::new()), + (), + ); + let view = host.world_view(); + let ids: Vec<(u32, u16)> = view.entities().iter().map(|e| (e.id, e.kind)).collect(); + assert_eq!( + ids, + [ + (1, 1), // mobs in Vec order; mob 2 is dead: no view + (3, 1), // + (103, 2), // rocks in BTreeMap key order (3, 7) + (107, 2), // + (50, 1), // the Option + (900, 3), // the zone itself + (77, 4), // replicate() last + ] + ); + let mob3 = &view.entities()[1]; + assert_eq!( + mob3.fields, + [FieldValue::F(3.0), FieldValue::F(-3.0), FieldValue::U(25)], + "#[from(body.x)] copied, hp derived" + ); + assert_eq!((mob3.x, mob3.y), (3.0, -3.0)); + assert!(view.entities()[2].global, "kind flags carry over"); + assert_eq!(view.entities()[5].fields, [FieldValue::U(2)]); + // Unreplicated server state stays put. + assert_eq!(host.zone().mobs[0].home, (1.0, 1.0)); +} + +#[test] +fn hand_written_replicate_can_project_entities_too() { + let mut out = WorldView::default(); + let dead = mob(9, 0.0, 0); + assert!(out.project::(&dead).is_none(), "None omits"); + out.project::(&mob(8, 1.0, 40)) + .expect("alive") + .priority(3.0); + let rock = Rock { + id: EntityId(5), + x: 1.0, + y: 2.0, + r: 0.25, + }; + out.project::(&rock); + assert_eq!(out.entities().len(), 2); + assert_eq!(out.entities()[0].priority, 3.0); + assert_eq!( + RockView::project(&rock), + RockView { + x: 1.0, + y: 2.0, + r: 0.25 + } + ); + assert_eq!(rock.view(), Some(RockView::project(&rock))); +} + +#[test] +fn entity_ids_convert_and_display_as_the_raw_id() { + let id = EntityId::from(1002); + assert_eq!(u32::from(id), 1002); + assert_eq!(id.get(), 1002); + assert_eq!(id.to_string(), "1002"); +} diff --git a/distributed_game/tests/fixtures/authoring.json b/distributed_game/tests/fixtures/authoring.json new file mode 100644 index 000000000..ff79bed15 --- /dev/null +++ b/distributed_game/tests/fixtures/authoring.json @@ -0,0 +1,771 @@ +{ + "constants": { + "sample_board": "07020103416461ffffffffffffff0f0207426f6220e29c930300ac02787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878", + "sample_gusts": "02cdcccc3d000020c0", + "sample_spot": "1504646f636b" + }, + "events": [ + { + "hex": "e90700006041ff07", + "id": 1, + "name": "hello", + "value": { + "entity": 1001, + "half": 64.0, + "viewRadius": 14.0 + } + }, + { + "hex": "07020103416461ffffffffffffff0f0207426f6220e29c930300ac02787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878787878", + "id": 2, + "name": "board", + "value": { + "kills": [ + { + "name": "Ada", + "rank": 1, + "score": 9007199254740991 + }, + { + "name": "Bob ✓", + "rank": 2, + "score": 3 + } + ], + "motd": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "note": null, + "version": 7 + } + }, + { + "hex": "", + "id": 3, + "name": "respawned", + "value": {} + }, + { + "hex": "01012ad704fb00000000004a9340020161000200ff808080808020", + "id": 4, + "name": "shot", + "value": { + "atMs": 1234.5, + "bytes": [ + 0, + 255 + ], + "hit": true, + "offset": -300, + "small": -5, + "tags": [ + "a", + "" + ], + "target": 42, + "total": 1099511627776 + } + }, + { + "hex": "000000000000000000000000000000", + "id": 4, + "name": "shot", + "value": { + "atMs": 0.0, + "bytes": [], + "hit": false, + "offset": 0, + "small": 0, + "tags": [], + "target": null, + "total": 0 + } + } + ], + "input": { + "decoded": { + "aim": 5.283030033111572, + "buttons": 7, + "mx": -128, + "my": 100, + "power": 0.25, + "viewTick": 123456 + }, + "hex": "806407dd060000803ec0c407", + "sanitized": { + "aim": 5.283030033111572, + "buttons": 3, + "mx": -127, + "my": 100, + "power": 0.25, + "viewTick": 123456 + }, + "value": { + "aim": -1.0, + "buttons": 7, + "mx": -128, + "my": 100, + "power": 0.25, + "viewTick": 123456 + } + }, + "messages": [ + { + "hex": "13736572766572207265737461727420696e203501", + "id": 1, + "name": "announce", + "value": { + "text": "server restart in 5", + "urgent": true + } + }, + { + "hex": "0000204007", + "id": 2, + "name": "set_wind", + "value": { + "gusts": 7, + "speed": 2.5 + } + } + ], + "pures": [ + { + "arg": "0000c03fffff03", + "export": "sample_mirror", + "output": "0000c0bf00" + }, + { + "arg": "", + "export": "sample_rows", + "output": "020103416461ffffffffffffff0f0207426f6220e29c9303" + } + ], + "surface": { + "codecs": [ + "SampleWind" + ], + "constants": [ + { + "name": "sample_board", + "type": { + "name": "Board", + "type": "record" + }, + "value": { + "kills": [ + { + "name": "Ada", + "rank": 1, + "score": 9007199254740991 + }, + { + "name": "Bob ✓", + "rank": 2, + "score": 3 + } + ], + "motd": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", + "note": null, + "version": 7 + } + }, + { + "name": "sample_gusts", + "type": { + "item": { + "type": "f32" + }, + "type": "list" + }, + "value": [ + 0.10000000149011612, + -2.5 + ] + }, + { + "name": "sample_spot", + "type": { + "name": "Spot", + "type": "record" + }, + "value": { + "at": 1.313783049583435, + "label": "dock" + } + } + ], + "events": [ + { + "id": 1, + "name": "hello", + "payload": { + "fields": [ + { + "name": "entity", + "type": { + "type": "u32" + } + }, + { + "name": "view_radius", + "type": { + "type": "f32" + } + }, + { + "name": "half", + "type": { + "bits": 10, + "max": 64.0, + "min": 0.0, + "type": "quant" + } + } + ], + "kind": "fields" + } + }, + { + "id": 2, + "name": "board", + "payload": { + "kind": "value", + "type": { + "name": "Board", + "type": "record" + } + } + }, + { + "id": 3, + "name": "respawned", + "payload": { + "fields": [], + "kind": "fields" + } + }, + { + "id": 4, + "name": "shot", + "payload": { + "fields": [ + { + "name": "hit", + "type": { + "type": "bool" + } + }, + { + "name": "target", + "type": { + "item": { + "type": "u32" + }, + "type": "optional" + } + }, + { + "name": "offset", + "type": { + "type": "i16" + } + }, + { + "name": "small", + "type": { + "type": "i8" + } + }, + { + "name": "at_ms", + "type": { + "type": "f64" + } + }, + { + "name": "tags", + "type": { + "item": { + "type": "short_str" + }, + "type": "list" + } + }, + { + "name": "bytes", + "type": { + "type": "bytes" + } + }, + { + "name": "total", + "type": { + "type": "u64" + } + } + ], + "kind": "fields" + } + }, + { + "id": 9, + "name": "ping", + "payload": { + "fields": [ + { + "name": "seq", + "type": { + "type": "u32" + } + } + ], + "kind": "fields" + } + } + ], + "input": { + "fields": [ + { + "name": "mx", + "range": [ + -127.0, + 127.0 + ], + "type": { + "type": "i8" + } + }, + { + "name": "my", + "range": [ + -127.0, + 127.0 + ], + "type": { + "type": "i8" + } + }, + { + "buttons": [ + "dash", + "attack" + ], + "name": "buttons", + "type": { + "type": "u8" + } + }, + { + "name": "aim", + "type": { + "bits": 10, + "type": "angle" + } + }, + { + "name": "power", + "range": [ + 0.0, + 1.0 + ], + "type": { + "type": "f32" + } + }, + { + "name": "view_tick", + "type": { + "type": "u32" + } + } + ], + "name": "SampleInput" + }, + "kinds": [ + { + "fields": [ + { + "correction": { + "durationMs": 150, + "mode": "ease" + }, + "name": "x", + "priority": 1.0, + "type": { + "bits": 18, + "max": 19.999847, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": { + "durationMs": 150, + "mode": "ease", + "snapAbove": 2.5 + }, + "name": "y", + "priority": 1.0, + "type": { + "bits": 18, + "max": 19.999847, + "min": -20.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "snap" + }, + "name": "vx", + "priority": 1.0, + "type": { + "bits": 12, + "max": 16.0, + "min": -16.0, + "type": "quant" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "face", + "priority": 1.0, + "type": { + "bits": 8, + "type": "angle" + } + }, + { + "correction": { + "mode": "replace" + }, + "name": "name", + "priority": 0.2, + "type": { + "type": "short_str" + } + }, + { + "correction": null, + "name": "hp", + "priority": 1.0, + "type": { + "type": "u8" + } + }, + { + "correction": null, + "name": "level", + "priority": 1.0, + "type": { + "type": "u16" + } + }, + { + "correction": null, + "name": "dead", + "priority": 1.0, + "type": { + "type": "bool" + } + }, + { + "correction": null, + "name": "score", + "priority": 1.0, + "type": { + "type": "i32" + } + }, + { + "correction": null, + "name": "raw", + "priority": 1.0, + "type": { + "type": "f32" + } + }, + { + "correction": null, + "name": "blob", + "priority": 1.0, + "type": { + "type": "bytes" + } + }, + { + "correction": null, + "name": "kills", + "priority": 1.0, + "type": { + "type": "u32" + } + } + ], + "id": 1, + "name": "player", + "priority": 2.0 + }, + { + "fields": [ + { + "correction": null, + "name": "px", + "priority": 1.0, + "type": { + "bits": 16, + "max": 63.998047, + "min": -64.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "py", + "priority": 1.0, + "type": { + "bits": 16, + "max": 63.998047, + "min": -64.0, + "type": "quant" + } + }, + { + "correction": null, + "name": "label", + "priority": 1.0, + "type": { + "type": "short_str" + } + } + ], + "id": 2, + "name": "marker", + "priority": 1.0 + }, + { + "fields": [ + { + "correction": null, + "name": "slow_ms", + "priority": 1.0, + "type": { + "type": "u16" + } + }, + { + "correction": null, + "name": "tick_ms", + "priority": 1.0, + "type": { + "type": "f32" + } + } + ], + "id": 4, + "name": "stats", + "priority": 1.0 + } + ], + "messages": [ + { + "id": 1, + "name": "announce", + "payload": { + "fields": [ + { + "name": "text", + "type": { + "type": "str" + } + }, + { + "name": "urgent", + "type": { + "type": "bool" + } + } + ], + "kind": "fields" + } + }, + { + "id": 2, + "name": "set_wind", + "payload": { + "kind": "value", + "type": { + "name": "SampleWind", + "type": "record" + } + } + } + ], + "name": "sample", + "predict": { + "abi": 1, + "context": "SampleWind", + "export": "sample_step", + "kind": "player", + "package": "distributed_game", + "state": "SampleState" + }, + "protocolVersion": 1, + "pures": [ + { + "abi": 1, + "arg": { + "name": "SampleWind", + "type": "record" + }, + "export": "sample_mirror", + "output": { + "name": "SampleWind", + "type": "record" + }, + "package": "distributed_game" + }, + { + "abi": 1, + "export": "sample_rows", + "output": { + "item": { + "name": "Row", + "type": "record" + }, + "type": "list" + }, + "package": "distributed_game" + } + ], + "records": [ + { + "fields": [ + { + "name": "version", + "type": { + "type": "u32" + } + }, + { + "name": "kills", + "type": { + "item": { + "name": "Row", + "type": "record" + }, + "type": "list" + } + }, + { + "name": "note", + "type": { + "item": { + "type": "short_str" + }, + "type": "optional" + } + }, + { + "name": "motd", + "type": { + "type": "str" + } + } + ], + "name": "Board" + }, + { + "fields": [ + { + "name": "rank", + "type": { + "type": "u16" + } + }, + { + "name": "name", + "type": { + "type": "short_str" + } + }, + { + "name": "score", + "type": { + "type": "u64" + } + } + ], + "name": "Row" + }, + { + "fields": [ + { + "name": "x", + "type": { + "type": "f32" + } + }, + { + "name": "vx", + "type": { + "type": "f32" + } + }, + { + "name": "hp", + "type": { + "type": "u8" + } + }, + { + "name": "dead", + "type": { + "type": "bool" + } + } + ], + "name": "SampleState" + }, + { + "fields": [ + { + "name": "speed", + "type": { + "type": "f32" + } + }, + { + "name": "gusts", + "type": { + "type": "u16" + } + } + ], + "name": "SampleWind" + }, + { + "fields": [ + { + "name": "at", + "type": { + "bits": 10, + "max": 64.0, + "min": 0.0, + "type": "quant" + } + }, + { + "name": "label", + "type": { + "type": "short_str" + } + } + ], + "name": "Spot" + } + ], + "schemaVersion": 3 + } +} diff --git a/distributed_game/tests/fixtures/messages.json b/distributed_game/tests/fixtures/messages.json new file mode 100644 index 000000000..72b8235d0 --- /dev/null +++ b/distributed_game/tests/fixtures/messages.json @@ -0,0 +1,685 @@ +{ + "messages": [ + { + "decoded": { + "capabilities": 5, + "content_version": "c1", + "near": false, + "protocol_version": 2, + "reconnect_token": "", + "ticket": "t.k.n", + "type": "Hello" + }, + "direction": "client_to_server", + "hex": "01020263310505742e6b2e6e0000", + "name": "hello" + }, + { + "decoded": { + "capabilities": 0, + "content_version": "c1", + "near": false, + "protocol_version": 2, + "reconnect_token": "abcd", + "ticket": "", + "type": "Hello" + }, + "direction": "client_to_server", + "hex": "01020263310000046162636400", + "name": "hello_reconnect" + }, + { + "decoded": { + "client_tick": 1000, + "payload": "01ff", + "seq": 300, + "type": "Input" + }, + "direction": "client_to_server", + "hex": "02ac02e8070201ff", + "name": "input" + }, + { + "decoded": { + "client_time": 1234.5, + "type": "Ping" + }, + "direction": "client_to_server", + "hex": "0300000000004a9340", + "name": "ping" + }, + { + "decoded": { + "type": "Leave" + }, + "direction": "client_to_server", + "hex": "04", + "name": "leave" + }, + { + "decoded": { + "content_version": "c2", + "type": "Content" + }, + "direction": "client_to_server", + "hex": "05026332", + "name": "content" + }, + { + "decoded": { + "capabilities": 0, + "content_version": "c1", + "near": true, + "protocol_version": 2, + "reconnect_token": "", + "ticket": "t.k.n", + "type": "Hello" + }, + "direction": "client_to_server", + "hex": "01020263310005742e6b2e6e0001", + "name": "hello_near" + }, + { + "decoded": { + "near": true, + "type": "Near" + }, + "direction": "client_to_server", + "hex": "0601", + "name": "near" + }, + { + "decoded": { + "near": false, + "type": "Near" + }, + "direction": "client_to_server", + "hex": "0600", + "name": "passive" + }, + { + "decoded": { + "type": "Focus", + "x": -25.5, + "y": 3.25 + }, + "direction": "client_to_server", + "hex": "070000ccc100005040", + "name": "focus" + }, + { + "decoded": { + "content_version": "c1", + "features": 1, + "origin": null, + "patch_rate": 20, + "reconnect_token": "rt", + "role": "player", + "schema": [ + { + "fields": [ + { + "name": "alive", + "type": "bool" + }, + { + "name": "level", + "type": "u8" + }, + { + "name": "hp", + "type": "u16" + }, + { + "name": "gold", + "type": "u32" + }, + { + "name": "dz", + "type": "i32" + }, + { + "name": "speed", + "type": "f32" + }, + { + "bits": 16, + "max": { + "bits": "42c80000", + "f32": 100.0 + }, + "min": { + "bits": "c2c80000", + "f32": -100.0 + }, + "name": "x", + "type": "quant_f32" + }, + { + "bits": 10, + "name": "yaw", + "type": "angle" + }, + { + "name": "name", + "type": "short_str" + }, + { + "name": "tag", + "type": "bytes" + } + ], + "id": 1, + "name": "hero" + }, + { + "fields": [ + { + "bits": 12, + "max": { + "bits": "42800000", + "f32": 64.0 + }, + "min": { + "bits": "00000000", + "f32": 0.0 + }, + "name": "x", + "type": "quant_f32" + } + ], + "id": 2, + "name": "orb" + } + ], + "server_tick": 42, + "server_time": 1000.25, + "session_id": "s1", + "tick_rate": 30, + "type": "Welcome", + "zone_id": "z1" + }, + "direction": "server_to_client", + "hex": "80027331027a31001e142a0000000000428f400272740263310201046865726f0a05616c69766500056c6576656c010268700204676f6c640302647a04057370656564050178060000c8c20000c8421003796177070a046e616d6508037461670902036f72620101780600000000000080420c0100", + "name": "welcome" + }, + { + "decoded": { + "content_version": "c1", + "features": 1, + "origin": { + "x": -48.0, + "y": 1000000.5 + }, + "patch_rate": 20, + "reconnect_token": "rt", + "role": "observer", + "schema": [ + { + "fields": [ + { + "name": "alive", + "type": "bool" + }, + { + "name": "level", + "type": "u8" + }, + { + "name": "hp", + "type": "u16" + }, + { + "name": "gold", + "type": "u32" + }, + { + "name": "dz", + "type": "i32" + }, + { + "name": "speed", + "type": "f32" + }, + { + "bits": 16, + "max": { + "bits": "42c80000", + "f32": 100.0 + }, + "min": { + "bits": "c2c80000", + "f32": -100.0 + }, + "name": "x", + "type": "quant_f32" + }, + { + "bits": 10, + "name": "yaw", + "type": "angle" + }, + { + "name": "name", + "type": "short_str" + }, + { + "name": "tag", + "type": "bytes" + } + ], + "id": 1, + "name": "hero" + }, + { + "fields": [ + { + "bits": 12, + "max": { + "bits": "42800000", + "f32": 64.0 + }, + "min": { + "bits": "00000000", + "f32": 0.0 + }, + "name": "x", + "type": "quant_f32" + } + ], + "id": 2, + "name": "orb" + } + ], + "server_tick": 42, + "server_time": 1000.25, + "session_id": "s1", + "tick_rate": 30, + "type": "Welcome", + "zone_id": "z1" + }, + "direction": "server_to_client", + "hex": "80027331027a31011e142a0000000000428f400272740263310201046865726f0a05616c69766500056c6576656c010268700204676f6c640302647a04057370656564050178060000c8c20000c8421003796177070a046e616d6508037461670902036f72620101780600000000000080420c010100000000000048c00000000081842e41", + "name": "welcome_origin" + }, + { + "decoded": { + "ack_seq": 0, + "creates": [], + "removes": [], + "server_tick": 43, + "type": "Delta", + "updates": [] + }, + "direction": "server_to_client", + "hex": "812b00000000", + "known_entities": [ + { + "id": 5, + "kind": 1 + }, + { + "id": 6, + "kind": 2 + } + ], + "name": "delta_empty", + "schema": [ + { + "fields": [ + { + "name": "alive", + "type": "bool" + }, + { + "name": "level", + "type": "u8" + }, + { + "name": "hp", + "type": "u16" + }, + { + "name": "gold", + "type": "u32" + }, + { + "name": "dz", + "type": "i32" + }, + { + "name": "speed", + "type": "f32" + }, + { + "bits": 16, + "max": { + "bits": "42c80000", + "f32": 100.0 + }, + "min": { + "bits": "c2c80000", + "f32": -100.0 + }, + "name": "x", + "type": "quant_f32" + }, + { + "bits": 10, + "name": "yaw", + "type": "angle" + }, + { + "name": "name", + "type": "short_str" + }, + { + "name": "tag", + "type": "bytes" + } + ], + "id": 1, + "name": "hero" + }, + { + "fields": [ + { + "bits": 12, + "max": { + "bits": "42800000", + "f32": 64.0 + }, + "min": { + "bits": "00000000", + "f32": 0.0 + }, + "name": "x", + "type": "quant_f32" + } + ], + "id": 2, + "name": "orb" + } + ] + }, + { + "decoded": { + "ack_seq": 17, + "creates": [ + { + "fields": [ + { + "bool": true + }, + { + "u": 7 + }, + { + "u": 300 + }, + { + "u": 70000 + }, + { + "i": -2 + }, + { + "bits": "3fc00000", + "f32": 1.5 + }, + { + "bits": "c2c80000", + "f32": -100.0 + }, + { + "bits": "00000000", + "f32": 0.0 + }, + { + "str": "Ana" + }, + { + "bytes": "dead" + } + ], + "id": 300, + "kind": 1 + }, + { + "fields": [ + { + "bits": "42000801", + "f32": 32.007816314697266 + } + ], + "id": 301, + "kind": 2 + } + ], + "removes": [ + 9, + 130 + ], + "server_tick": 200, + "type": "Delta", + "updates": [ + { + "fields": [ + { + "u": 299 + }, + { + "bits": "3ac800c8", + "f32": 0.0015259021893143654 + } + ], + "id": 5, + "mask": 68 + }, + { + "fields": [ + { + "bits": "42800000", + "f32": 64.0 + } + ], + "id": 6, + "mask": 1 + }, + { + "fields": [ + { + "bits": "00000000", + "f32": 0.0 + } + ], + "id": 301, + "mask": 1 + } + ] + }, + "direction": "server_to_client", + "hex": "81c801110209820102ac02010107ac02f0a204030000c03f000003416e6102deadad02028010030544ab028080020601ff1fad020100", + "known_entities": [ + { + "id": 5, + "kind": 1 + }, + { + "id": 6, + "kind": 2 + } + ], + "name": "delta", + "schema": [ + { + "fields": [ + { + "name": "alive", + "type": "bool" + }, + { + "name": "level", + "type": "u8" + }, + { + "name": "hp", + "type": "u16" + }, + { + "name": "gold", + "type": "u32" + }, + { + "name": "dz", + "type": "i32" + }, + { + "name": "speed", + "type": "f32" + }, + { + "bits": 16, + "max": { + "bits": "42c80000", + "f32": 100.0 + }, + "min": { + "bits": "c2c80000", + "f32": -100.0 + }, + "name": "x", + "type": "quant_f32" + }, + { + "bits": 10, + "name": "yaw", + "type": "angle" + }, + { + "name": "name", + "type": "short_str" + }, + { + "name": "tag", + "type": "bytes" + } + ], + "id": 1, + "name": "hero" + }, + { + "fields": [ + { + "bits": 12, + "max": { + "bits": "42800000", + "f32": 64.0 + }, + "min": { + "bits": "00000000", + "f32": 0.0 + }, + "name": "x", + "type": "quant_f32" + } + ], + "id": 2, + "name": "orb" + } + ] + }, + { + "decoded": { + "payload": "7870", + "type": "Event", + "type_id": 3 + }, + "direction": "server_to_client", + "hex": "8203027870", + "name": "event" + }, + { + "decoded": { + "client_time": 1234.5, + "server_time": 99.0, + "type": "Pong" + }, + "direction": "server_to_client", + "hex": "8300000000004a93400000000000c05840", + "name": "pong" + }, + { + "decoded": { + "notes": "brb", + "reason": "content_update", + "type": "Freeze", + "version": "c2" + }, + "direction": "server_to_client", + "hex": "840e636f6e74656e745f75706461746502633203627262", + "name": "freeze" + }, + { + "decoded": { + "notes": "", + "reason": "content_update", + "type": "Resume", + "version": "c2" + }, + "direction": "server_to_client", + "hex": "850e636f6e74656e745f75706461746502633200", + "name": "resume" + }, + { + "decoded": { + "target_zone": "z2", + "transfer_ticket": "tt", + "type": "Handoff" + }, + "direction": "server_to_client", + "hex": "86027a32027474", + "name": "handoff" + }, + { + "decoded": { + "code": 3, + "message": "bye", + "type": "Kick" + }, + "direction": "server_to_client", + "hex": "870303627965", + "name": "kick" + }, + { + "decoded": { + "code": 2, + "message": "Expired", + "type": "Error" + }, + "direction": "server_to_client", + "hex": "88020745787069726564", + "name": "error" + }, + { + "decoded": { + "code": 7, + "message": "content c2 required", + "type": "Kick" + }, + "direction": "server_to_client", + "hex": "870713636f6e74656e74206332207265717569726564", + "name": "kick_reload" + }, + { + "decoded": { + "type": "Redirect", + "url": "ws://10.0.0.2:2567/zones/realm.west", + "zone_id": "realm.west" + }, + "direction": "server_to_client", + "hex": "890a7265616c6d2e776573742377733a2f2f31302e302e302e323a323536372f7a6f6e65732f7265616c6d2e77657374", + "name": "redirect" + } + ] +} diff --git a/distributed_game/tests/fixtures/primitives.json b/distributed_game/tests/fixtures/primitives.json new file mode 100644 index 000000000..b6e5088a0 --- /dev/null +++ b/distributed_game/tests/fixtures/primitives.json @@ -0,0 +1,138 @@ +{ + "cases": [ + { + "hex": "00", + "kind": "varuint", + "value": 0 + }, + { + "hex": "01", + "kind": "varuint", + "value": 1 + }, + { + "hex": "7f", + "kind": "varuint", + "value": 127 + }, + { + "hex": "8001", + "kind": "varuint", + "value": 128 + }, + { + "hex": "ac02", + "kind": "varuint", + "value": 300 + }, + { + "hex": "808001", + "kind": "varuint", + "value": 16384 + }, + { + "hex": "ffffffff0f", + "kind": "varuint", + "value": 4294967295 + }, + { + "hex": "00", + "kind": "varint", + "value": 0 + }, + { + "hex": "01", + "kind": "varint", + "value": -1 + }, + { + "hex": "02", + "kind": "varint", + "value": 1 + }, + { + "hex": "7f", + "kind": "varint", + "value": -64 + }, + { + "hex": "8001", + "kind": "varint", + "value": 64 + }, + { + "hex": "ffffffff0f", + "kind": "varint", + "value": -2147483648 + }, + { + "hex": "feffffff0f", + "kind": "varint", + "value": 2147483647 + }, + { + "hex": "0000c03f", + "kind": "f32", + "value": { + "bits": "3fc00000", + "f32": 1.5 + } + }, + { + "hex": "00000080", + "kind": "f32", + "value": { + "bits": "80000000", + "f32": -0.0 + } + }, + { + "hex": "db0f4940", + "kind": "f32", + "value": { + "bits": "40490fdb", + "f32": 3.1415927410125732 + } + }, + { + "hex": "00000000004a9340", + "kind": "f64", + "value": 1234.5 + }, + { + "hex": "9a9999999999b93f", + "kind": "f64", + "value": 0.1 + }, + { + "hex": "00", + "kind": "string", + "value": "" + }, + { + "hex": "00", + "kind": "short_string", + "value": "" + }, + { + "hex": "026869", + "kind": "string", + "value": "hi" + }, + { + "hex": "026869", + "kind": "short_string", + "value": "hi" + }, + { + "hex": "0668c3a9726f73", + "kind": "string", + "value": "héros" + }, + { + "hex": "0668c3a9726f73", + "kind": "short_string", + "value": "héros" + } + ] +} diff --git a/distributed_game/tests/fixtures/quantization.json b/distributed_game/tests/fixtures/quantization.json new file mode 100644 index 000000000..80ca1f3cc --- /dev/null +++ b/distributed_game/tests/fixtures/quantization.json @@ -0,0 +1,574 @@ +{ + "cases": [ + { + "decoded": { + "bits": "c2c80000", + "f32": -100.0 + }, + "field": { + "bits": 16, + "max": { + "bits": "42c80000", + "f32": 100.0 + }, + "min": { + "bits": "c2c80000", + "f32": -100.0 + }, + "type": "quant_f32" + }, + "hex": "00", + "input_bits": "c2c80000", + "q": 0 + }, + { + "decoded": { + "bits": "3ac800c8", + "f32": 0.0015259021893143654 + }, + "field": { + "bits": 16, + "max": { + "bits": "42c80000", + "f32": 100.0 + }, + "min": { + "bits": "c2c80000", + "f32": -100.0 + }, + "type": "quant_f32" + }, + "hex": "808002", + "input_bits": "00000000", + "q": 32768 + }, + { + "decoded": { + "bits": "420532f5", + "f32": 33.29976272583008 + }, + "field": { + "bits": 16, + "max": { + "bits": "42c80000", + "f32": 100.0 + }, + "min": { + "bits": "c2c80000", + "f32": -100.0 + }, + "type": "quant_f32" + }, + "hex": "9fd502", + "input_bits": "42053333", + "q": 43679 + }, + { + "decoded": { + "bits": "42c80000", + "f32": 100.0 + }, + "field": { + "bits": 16, + "max": { + "bits": "42c80000", + "f32": 100.0 + }, + "min": { + "bits": "c2c80000", + "f32": -100.0 + }, + "type": "quant_f32" + }, + "hex": "ffff03", + "input_bits": "42c7ff7d", + "q": 65535 + }, + { + "decoded": { + "bits": "42c80000", + "f32": 100.0 + }, + "field": { + "bits": 16, + "max": { + "bits": "42c80000", + "f32": 100.0 + }, + "min": { + "bits": "c2c80000", + "f32": -100.0 + }, + "type": "quant_f32" + }, + "hex": "ffff03", + "input_bits": "437a0000", + "q": 65535 + }, + { + "decoded": { + "bits": "c2c80000", + "f32": -100.0 + }, + "field": { + "bits": 16, + "max": { + "bits": "42c80000", + "f32": 100.0 + }, + "min": { + "bits": "c2c80000", + "f32": -100.0 + }, + "type": "quant_f32" + }, + "hex": "00", + "input_bits": "ce6e6b28", + "q": 0 + }, + { + "decoded": { + "bits": "00000000", + "f32": 0.0 + }, + "field": { + "bits": 12, + "max": { + "bits": "42800000", + "f32": 64.0 + }, + "min": { + "bits": "00000000", + "f32": 0.0 + }, + "type": "quant_f32" + }, + "hex": "00", + "input_bits": "00000000", + "q": 0 + }, + { + "decoded": { + "bits": "3ea80a81", + "f32": 0.3282051384449005 + }, + "field": { + "bits": 12, + "max": { + "bits": "42800000", + "f32": 64.0 + }, + "min": { + "bits": "00000000", + "f32": 0.0 + }, + "type": "quant_f32" + }, + "hex": "15", + "input_bits": "3eaaaaab", + "q": 21 + }, + { + "decoded": { + "bits": "41ffefff", + "f32": 31.992185592651367 + }, + "field": { + "bits": 12, + "max": { + "bits": "42800000", + "f32": 64.0 + }, + "min": { + "bits": "00000000", + "f32": 0.0 + }, + "type": "quant_f32" + }, + "hex": "ff0f", + "input_bits": "41ffeb85", + "q": 2047 + }, + { + "decoded": { + "bits": "42800000", + "f32": 64.0 + }, + "field": { + "bits": 12, + "max": { + "bits": "42800000", + "f32": 64.0 + }, + "min": { + "bits": "00000000", + "f32": 0.0 + }, + "type": "quant_f32" + }, + "hex": "ff1f", + "input_bits": "42800000", + "q": 4095 + }, + { + "decoded": { + "bits": "bf800000", + "f32": -1.0 + }, + "field": { + "bits": 8, + "max": { + "bits": "3f800000", + "f32": 1.0 + }, + "min": { + "bits": "bf800000", + "f32": -1.0 + }, + "type": "quant_f32" + }, + "hex": "00", + "input_bits": "bf800000", + "q": 0 + }, + { + "decoded": { + "bits": "3b808081", + "f32": 0.003921568859368563 + }, + "field": { + "bits": 8, + "max": { + "bits": "3f800000", + "f32": 1.0 + }, + "min": { + "bits": "bf800000", + "f32": -1.0 + }, + "type": "quant_f32" + }, + "hex": "8001", + "input_bits": "00000000", + "q": 128 + }, + { + "decoded": { + "bits": "3efefeff", + "f32": 0.49803921580314636 + }, + "field": { + "bits": 8, + "max": { + "bits": "3f800000", + "f32": 1.0 + }, + "min": { + "bits": "bf800000", + "f32": -1.0 + }, + "type": "quant_f32" + }, + "hex": "bf01", + "input_bits": "3f000000", + "q": 191 + }, + { + "decoded": { + "bits": "bf800000", + "f32": -1.0 + }, + "field": { + "bits": 8, + "max": { + "bits": "3f800000", + "f32": 1.0 + }, + "min": { + "bits": "bf800000", + "f32": -1.0 + }, + "type": "quant_f32" + }, + "hex": "00", + "input_bits": "7fc00000", + "q": 0 + }, + { + "decoded": { + "bits": "3dfcd6ea", + "f32": 0.12345679104328156 + }, + "field": { + "bits": 32, + "max": { + "bits": "3f800000", + "f32": 1.0 + }, + "min": { + "bits": "00000000", + "f32": 0.0 + }, + "type": "quant_f32" + }, + "hex": "c0baebfc01", + "input_bits": "3dfcd6ea", + "q": 530242880 + }, + { + "decoded": { + "bits": "3f800000", + "f32": 1.0 + }, + "field": { + "bits": 32, + "max": { + "bits": "3f800000", + "f32": 1.0 + }, + "min": { + "bits": "00000000", + "f32": 0.0 + }, + "type": "quant_f32" + }, + "hex": "ffffffff0f", + "input_bits": "3f800000", + "q": 4294967295 + }, + { + "decoded": { + "bits": "00000000", + "f32": 0.0 + }, + "field": { + "bits": 8, + "type": "angle" + }, + "hex": "00", + "input_bits": "00000000", + "q": 0 + }, + { + "decoded": { + "bits": "3f80ce28", + "f32": 1.006291389465332 + }, + "field": { + "bits": 8, + "type": "angle" + }, + "hex": "29", + "input_bits": "3f800000", + "q": 41 + }, + { + "decoded": { + "bits": "40490fdb", + "f32": 3.1415927410125732 + }, + "field": { + "bits": 8, + "type": "angle" + }, + "hex": "8001", + "input_bits": "40490fdb", + "q": 128 + }, + { + "decoded": { + "bits": "4096cbe4", + "f32": 4.71238899230957 + }, + "field": { + "bits": 8, + "type": "angle" + }, + "hex": "c001", + "input_bits": "bfc90fdb", + "q": 192 + }, + { + "decoded": { + "bits": "3f36365e", + "f32": 0.7117670774459839 + }, + "field": { + "bits": 8, + "type": "angle" + }, + "hex": "1d", + "input_bits": "40e00000", + "q": 29 + }, + { + "decoded": { + "bits": "00000000", + "f32": 0.0 + }, + "field": { + "bits": 8, + "type": "angle" + }, + "hex": "00", + "input_bits": "b58637bd", + "q": 0 + }, + { + "decoded": { + "bits": "00000000", + "f32": 0.0 + }, + "field": { + "bits": 10, + "type": "angle" + }, + "hex": "00", + "input_bits": "00000000", + "q": 0 + }, + { + "decoded": { + "bits": "3f800518", + "f32": 1.0001554489135742 + }, + "field": { + "bits": 10, + "type": "angle" + }, + "hex": "a301", + "input_bits": "3f800000", + "q": 163 + }, + { + "decoded": { + "bits": "40490fdb", + "f32": 3.1415927410125732 + }, + "field": { + "bits": 10, + "type": "angle" + }, + "hex": "8004", + "input_bits": "40490fdb", + "q": 512 + }, + { + "decoded": { + "bits": "4096cbe4", + "f32": 4.71238899230957 + }, + "field": { + "bits": 10, + "type": "angle" + }, + "hex": "8006", + "input_bits": "bfc90fdb", + "q": 768 + }, + { + "decoded": { + "bits": "3f37c87e", + "f32": 0.7179030179977417 + }, + "field": { + "bits": 10, + "type": "angle" + }, + "hex": "75", + "input_bits": "40e00000", + "q": 117 + }, + { + "decoded": { + "bits": "00000000", + "f32": 0.0 + }, + "field": { + "bits": 10, + "type": "angle" + }, + "hex": "00", + "input_bits": "b58637bd", + "q": 0 + }, + { + "decoded": { + "bits": "00000000", + "f32": 0.0 + }, + "field": { + "bits": 16, + "type": "angle" + }, + "hex": "00", + "input_bits": "00000000", + "q": 0 + }, + { + "decoded": { + "bits": "3f7ffd9f", + "f32": 0.9999637007713318 + }, + "field": { + "bits": 16, + "type": "angle" + }, + "hex": "be51", + "input_bits": "3f800000", + "q": 10430 + }, + { + "decoded": { + "bits": "40490fdb", + "f32": 3.1415927410125732 + }, + "field": { + "bits": 16, + "type": "angle" + }, + "hex": "808002", + "input_bits": "40490fdb", + "q": 32768 + }, + { + "decoded": { + "bits": "4096cbe4", + "f32": 4.71238899230957 + }, + "field": { + "bits": 16, + "type": "angle" + }, + "hex": "808003", + "input_bits": "bfc90fdb", + "q": 49152 + }, + { + "decoded": { + "bits": "3f378360", + "f32": 0.7168483734130859 + }, + "field": { + "bits": 16, + "type": "angle" + }, + "hex": "b53a", + "input_bits": "40e00000", + "q": 7477 + }, + { + "decoded": { + "bits": "00000000", + "f32": 0.0 + }, + "field": { + "bits": 16, + "type": "angle" + }, + "hex": "00", + "input_bits": "b58637bd", + "q": 0 + } + ] +} diff --git a/distributed_game/tests/fixtures/sveltekit_tickets.json b/distributed_game/tests/fixtures/sveltekit_tickets.json new file mode 100644 index 000000000..3c231db41 --- /dev/null +++ b/distributed_game/tests/fixtures/sveltekit_tickets.json @@ -0,0 +1,27 @@ +{ + "secret": "sveltekit-fixture-secret-0123456789abcdef", + "zone": "z-sveltekit", + "valid": { + "ticket": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzZXNzaW9uLXVzZXItMSIsInpvbmUiOiJ6LXN2ZWx0ZWtpdCIsImV4cCI6NDAwMDAwMDAwMCwibm9uY2UiOiJmaXh0dXJlLXZhbGlkIiwicm9sZSI6InBsYXllciIsIm5hbWUiOiJBbmEifQ.6dm_sJTidsFT1CAz_YrO6v4mPRk61DGA-sfkSZ2Zi40", + "principal": "session-user-1", + "name": "Ana", + "exp": 4000000000, + "nonce": "fixture-valid" + }, + "observer": { + "ticket": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzZXNzaW9uLXVzZXItMiIsInpvbmUiOiJ6LXN2ZWx0ZWtpdCIsImV4cCI6NDAwMDAwMDAwMCwibm9uY2UiOiJmaXh0dXJlLW9ic2VydmVyIiwicm9sZSI6Im9ic2VydmVyIn0.1j2Ql0XePnslZ1kJf64VhjUeDYkdl_nAt6Vep2zQ1bs", + "principal": "session-user-2" + }, + "extended": { + "ticket": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzZXNzaW9uLXVzZXItMyIsInpvbmUiOiJ6LXN2ZWx0ZWtpdCIsImV4cCI6NDAwMDAwMDAwMCwibm9uY2UiOiJmaXh0dXJlLWV4dGVuZGVkIiwicm9sZSI6InBsYXllciIsImV4dCI6eyJtYXRjaF9pZCI6Im0tNyIsInRlYW0iOjJ9fQ.sQwdQFAEEsYZcCy2qB3szKm8bIBRWqmngIdE-FGwfwo", + "principal": "session-user-3", + "ext": { + "match_id": "m-7", + "team": 2 + } + }, + "expired": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzZXNzaW9uLXVzZXItMSIsInpvbmUiOiJ6LXN2ZWx0ZWtpdCIsImV4cCI6MzAwLCJub25jZSI6ImZpeHR1cmUtZXhwaXJlZCIsInJvbGUiOiJwbGF5ZXIifQ.pJED6dt-O-JNtFi-fqzUFNPtEWYljUs0pKR9gJrX380", + "wrongZone": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzZXNzaW9uLXVzZXItMSIsInpvbmUiOiJ6LWVsc2V3aGVyZSIsImV4cCI6NDAwMDAwMDAwMCwibm9uY2UiOiJmaXh0dXJlLXdyb25nLXpvbmUiLCJyb2xlIjoicGxheWVyIn0.s4mdpfnnVke8Ntt_LjHAgonARO5RRt_KVgKH5v96k7A", + "tampered": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZG1pbiIsInpvbmUiOiJ6LXN2ZWx0ZWtpdCIsImV4cCI6NDAwMDAwMDAwMCwibm9uY2UiOiJmaXh0dXJlLXRhbXBlcmVkIiwicm9sZSI6InBsYXllciJ9.k0UNks88hcYz9M18yZdUA2OPH-Xwgf6jBwi6snvkoJE", + "otherKey": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzZXNzaW9uLXVzZXItMSIsInpvbmUiOiJ6LXN2ZWx0ZWtpdCIsImV4cCI6NDAwMDAwMDAwMCwibm9uY2UiOiJmaXh0dXJlLW90aGVyLWtleSIsInJvbGUiOiJwbGF5ZXIifQ.qVpH3bUXNhkfwk-J-AdLw40Fnyu0k6aEFf5ItmBIlLw" +} diff --git a/distributed_game/tests/fixtures/trusted_field_denylist.json b/distributed_game/tests/fixtures/trusted_field_denylist.json new file mode 100644 index 000000000..36b210253 --- /dev/null +++ b/distributed_game/tests/fixtures/trusted_field_denylist.json @@ -0,0 +1,6 @@ +{ + "comment": "Names a zone fact (FactCommand) or a ticket extension claim (TicketExtension, createGameTicketHandler claims) must never use. Matching ignores '_', '-' and case. Checked against distributed_game_macros/src/trusted.rs and js/src/sveltekit/game/ticket.ts by their tests.", + "identity": ["principal", "user", "user_id", "owner", "owner_id", "account", "account_id", "subject", "sub"], + "reward": ["xp", "experience", "reward", "rewards"], + "economy": ["amount", "coins", "gold", "currency", "price", "cost", "balance", "grant", "payout", "credit", "debit"] +} diff --git a/distributed_game/tests/golden/main.rs b/distributed_game/tests/golden/main.rs new file mode 100644 index 000000000..1d7b78798 --- /dev/null +++ b/distributed_game/tests/golden/main.rs @@ -0,0 +1,593 @@ +//! Golden byte fixtures for independent (e.g. JavaScript) implementations. +//! +//! Writes `tests/fixtures/*.json` when missing or when `UPDATE_GOLDEN=1`; +//! otherwise asserts the encoder still produces exactly the committed bytes +//! and that every fixture decodes back to its structure. JSON conventions are +//! documented in `PROTOCOL.md` §9. + +use std::collections::BTreeMap; +use std::path::PathBuf; + +use distributed_game::protocol::{ + error, feature, kick, ClientMessage, Delta, EntityCreate, EntityKinds, EntityUpdate, Hello, + Notice, Reader, ServerMessage, Welcome, Writer, +}; +use distributed_game::{ + EntitySchema, FieldType, FieldValue, KindDef, Origin, Role, PROTOCOL_VERSION, +}; +use serde_json::{json, Value}; + +/// Schema and known ids of a fixture. +struct Kinds<'a>(&'a EntitySchema, &'a BTreeMap); + +impl EntityKinds for Kinds<'_> { + fn schema(&self) -> Option<&EntitySchema> { + Some(self.0) + } + fn kind_of(&self, id: u32) -> Option { + self.1.get(&id).copied() + } +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +fn unhex(s: &str) -> Vec { + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()) + .collect() +} + +fn f32j(v: f32) -> Value { + json!({ "f32": f64::from(v), "bits": format!("{:08x}", v.to_bits()) }) +} + +fn field_type_json(ty: &FieldType) -> Value { + match ty { + FieldType::Bool => json!({ "type": "bool" }), + FieldType::U8 => json!({ "type": "u8" }), + FieldType::U16 => json!({ "type": "u16" }), + FieldType::U32 => json!({ "type": "u32" }), + FieldType::I32 => json!({ "type": "i32" }), + FieldType::F32 => json!({ "type": "f32" }), + FieldType::QuantF32 { min, max, bits } => { + json!({ "type": "quant_f32", "min": f32j(*min), "max": f32j(*max), "bits": bits }) + } + FieldType::Angle { bits } => json!({ "type": "angle", "bits": bits }), + FieldType::ShortStr => json!({ "type": "short_str" }), + FieldType::Bytes => json!({ "type": "bytes" }), + } +} + +fn schema_json(schema: &EntitySchema) -> Value { + Value::Array( + schema + .kinds() + .iter() + .map(|k| { + json!({ + "id": k.id, + "name": k.name, + "fields": k.fields.iter().map(|f| { + let mut v = field_type_json(&f.ty); + v["name"] = json!(f.name); + v + }).collect::>(), + }) + }) + .collect(), + ) +} + +fn value_json(v: &FieldValue) -> Value { + match v { + FieldValue::Bool(b) => json!({ "bool": b }), + FieldValue::U(u) => json!({ "u": u }), + FieldValue::I(i) => json!({ "i": i }), + FieldValue::F(f) => f32j(*f), + FieldValue::Str(s) => json!({ "str": s }), + FieldValue::Bytes(b) => json!({ "bytes": hex(b) }), + } +} + +fn client_json(m: &ClientMessage) -> Value { + match m { + ClientMessage::Hello(h) => json!({ + "type": "Hello", + "protocol_version": h.protocol_version, + "content_version": h.content_version, + "capabilities": h.capabilities, + "ticket": h.ticket, + "reconnect_token": h.reconnect_token, + "near": h.near, + }), + ClientMessage::Input { + seq, + client_tick, + payload, + } => { + json!({ "type": "Input", "seq": seq, "client_tick": client_tick, "payload": hex(payload) }) + } + ClientMessage::Ping { client_time } => { + json!({ "type": "Ping", "client_time": client_time }) + } + ClientMessage::Leave => json!({ "type": "Leave" }), + ClientMessage::Content { content_version } => { + json!({ "type": "Content", "content_version": content_version }) + } + ClientMessage::Near { near } => json!({ "type": "Near", "near": near }), + ClientMessage::Focus { x, y } => json!({ "type": "Focus", "x": x, "y": y }), + } +} + +fn server_json(m: &ServerMessage) -> Value { + match m { + ServerMessage::Welcome(w) => json!({ + "type": "Welcome", + "session_id": w.session_id, + "zone_id": w.zone_id, + "role": match w.role { Role::Player => "player", Role::Observer => "observer" }, + "tick_rate": w.tick_rate, + "patch_rate": w.patch_rate, + "server_tick": w.server_tick, + "server_time": w.server_time, + "reconnect_token": w.reconnect_token, + "content_version": w.content_version, + "schema": schema_json(&w.schema), + "features": w.features, + "origin": match w.origin { + Some(o) => json!({ "x": o.x, "y": o.y }), + None => Value::Null, + }, + }), + ServerMessage::Delta(d) => json!({ + "type": "Delta", + "server_tick": d.server_tick, + "ack_seq": d.ack_seq, + "removes": d.removes, + "creates": d.creates.iter().map(|c| json!({ + "id": c.id, "kind": c.kind, + "fields": c.fields.iter().map(value_json).collect::>(), + })).collect::>(), + "updates": d.updates.iter().map(|u| json!({ + "id": u.id, "mask": u.mask, + "fields": u.fields.iter().map(value_json).collect::>(), + })).collect::>(), + }), + ServerMessage::Event { type_id, payload } => { + json!({ "type": "Event", "type_id": type_id, "payload": hex(payload) }) + } + ServerMessage::Pong { + client_time, + server_time, + } => json!({ "type": "Pong", "client_time": client_time, "server_time": server_time }), + ServerMessage::Freeze(n) | ServerMessage::Resume(n) => json!({ + "type": if matches!(m, ServerMessage::Freeze(_)) { "Freeze" } else { "Resume" }, + "reason": n.reason, "version": n.version, "notes": n.notes, + }), + ServerMessage::Handoff { + target_zone, + transfer_ticket, + } => { + json!({ "type": "Handoff", "target_zone": target_zone, "transfer_ticket": transfer_ticket }) + } + ServerMessage::Kick { code, message } => { + json!({ "type": "Kick", "code": code, "message": message }) + } + ServerMessage::Error { code, message } => { + json!({ "type": "Error", "code": code, "message": message }) + } + ServerMessage::Redirect { zone_id, url } => { + json!({ "type": "Redirect", "zone_id": zone_id, "url": url }) + } + } +} + +fn fixture_schema() -> EntitySchema { + EntitySchema::new() + .kind( + KindDef::new(1, "hero") + .field("alive", FieldType::Bool) + .field("level", FieldType::U8) + .field("hp", FieldType::U16) + .field("gold", FieldType::U32) + .field("dz", FieldType::I32) + .field("speed", FieldType::F32) + .field( + "x", + FieldType::QuantF32 { + min: -100.0, + max: 100.0, + bits: 16, + }, + ) + .field("yaw", FieldType::Angle { bits: 10 }) + .field("name", FieldType::ShortStr) + .field("tag", FieldType::Bytes), + ) + .kind(KindDef::new(2, "orb").field( + "x", + FieldType::QuantF32 { + min: 0.0, + max: 64.0, + bits: 12, + }, + )) +} + +fn fixtures_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures") +} + +fn check_or_write(name: &str, value: Value) { + let path = fixtures_dir().join(name); + let text = serde_json::to_string_pretty(&value).unwrap() + "\n"; + if std::env::var("UPDATE_GOLDEN").is_ok() || !path.exists() { + std::fs::create_dir_all(fixtures_dir()).unwrap(); + std::fs::write(&path, &text).unwrap(); + return; + } + let committed = std::fs::read_to_string(&path).unwrap(); + assert_eq!( + committed, text, + "{name} drifted; the wire format changed (UPDATE_GOLDEN=1 to accept)" + ); +} + +#[test] +fn primitives() { + let mut cases = Vec::new(); + for v in [0u32, 1, 127, 128, 300, 16_384, u32::MAX] { + let mut w = Writer::new(); + w.varuint(v); + cases.push(json!({ "kind": "varuint", "value": v, "hex": hex(w.as_bytes()) })); + } + for v in [0i32, -1, 1, -64, 64, i32::MIN, i32::MAX] { + let mut w = Writer::new(); + w.varint(v); + assert_eq!(Reader::new(w.as_bytes()).varint().unwrap(), v); + cases.push(json!({ "kind": "varint", "value": v, "hex": hex(w.as_bytes()) })); + } + for v in [1.5f32, -0.0, std::f32::consts::PI] { + let mut w = Writer::new(); + w.f32(v); + cases.push(json!({ "kind": "f32", "value": f32j(v), "hex": hex(w.as_bytes()) })); + } + for v in [1234.5f64, 0.1] { + let mut w = Writer::new(); + w.f64(v); + cases.push(json!({ "kind": "f64", "value": v, "hex": hex(w.as_bytes()) })); + } + for s in ["", "hi", "héros"] { + let mut w = Writer::new(); + w.string(s); + cases.push(json!({ "kind": "string", "value": s, "hex": hex(w.as_bytes()) })); + let mut w = Writer::new(); + w.short_string(s); + cases.push(json!({ "kind": "short_string", "value": s, "hex": hex(w.as_bytes()) })); + } + check_or_write("primitives.json", json!({ "cases": cases })); +} + +#[test] +fn quantization() { + let mut cases = Vec::new(); + let linear = [ + ( + -100.0f32, + 100.0f32, + 16u8, + vec![-100.0f32, 0.0, 33.3, 99.999, 250.0, -1e9], + ), + (0.0, 64.0, 12, vec![0.0, 1.0 / 3.0, 31.99, 64.0]), + (-1.0, 1.0, 8, vec![-1.0, 0.0, 0.5, f32::NAN]), + (0.0, 1.0, 32, vec![0.123_456_79, 1.0]), + ]; + for (min, max, bits, values) in linear { + let ty = FieldType::QuantF32 { min, max, bits }; + for v in values { + let mut w = Writer::new(); + ty.encode(&mut w, &FieldValue::F(v)); + let q = Reader::new(w.as_bytes()).varuint().unwrap(); + let FieldValue::F(back) = ty.canonicalize(&FieldValue::F(v)) else { + panic!() + }; + cases.push(json!({ + "field": field_type_json(&ty), + "input_bits": format!("{:08x}", v.to_bits()), + "q": q, + "hex": hex(w.as_bytes()), + "decoded": f32j(back), + })); + } + } + for bits in [8u8, 10, 16] { + let ty = FieldType::Angle { bits }; + for v in [ + 0.0f32, + 1.0, + std::f32::consts::PI, + -std::f32::consts::FRAC_PI_2, + 7.0, + -0.000_001, + ] { + let mut w = Writer::new(); + ty.encode(&mut w, &FieldValue::F(v)); + let q = Reader::new(w.as_bytes()).varuint().unwrap(); + let FieldValue::F(back) = ty.canonicalize(&FieldValue::F(v)) else { + panic!() + }; + cases.push(json!({ + "field": field_type_json(&ty), + "input_bits": format!("{:08x}", v.to_bits()), + "q": q, + "hex": hex(w.as_bytes()), + "decoded": f32j(back), + })); + } + } + check_or_write("quantization.json", json!({ "cases": cases })); +} + +#[test] +fn messages() { + let schema = fixture_schema(); + let mut out = Vec::new(); + + let client = vec![ + ( + "hello", + ClientMessage::Hello(Hello { + protocol_version: PROTOCOL_VERSION, + content_version: "c1".into(), + capabilities: 5, + ticket: "t.k.n".into(), + reconnect_token: String::new(), + near: false, + }), + ), + ( + "hello_reconnect", + ClientMessage::Hello(Hello { + protocol_version: PROTOCOL_VERSION, + content_version: "c1".into(), + capabilities: 0, + ticket: String::new(), + reconnect_token: "abcd".into(), + near: false, + }), + ), + ( + "input", + ClientMessage::Input { + seq: 300, + client_tick: 1_000, + payload: vec![0x01, 0xff], + }, + ), + ( + "ping", + ClientMessage::Ping { + client_time: 1234.5, + }, + ), + ("leave", ClientMessage::Leave), + ( + "content", + ClientMessage::Content { + content_version: "c2".into(), + }, + ), + ( + "hello_near", + ClientMessage::Hello(Hello { + protocol_version: PROTOCOL_VERSION, + content_version: "c1".into(), + capabilities: 0, + ticket: "t.k.n".into(), + reconnect_token: String::new(), + near: true, + }), + ), + ("near", ClientMessage::Near { near: true }), + ("passive", ClientMessage::Near { near: false }), + ("focus", ClientMessage::Focus { x: -25.5, y: 3.25 }), + ]; + for (name, msg) in client { + let bytes = msg.encode(); + assert_eq!(ClientMessage::decode(&bytes).unwrap(), msg); + out.push(json!({ + "name": name, "direction": "client_to_server", + "hex": hex(&bytes), "decoded": client_json(&msg), + })); + } + + let known: BTreeMap = [(5u32, 1u16), (6, 2)].into_iter().collect(); + let hero_fields = vec![ + FieldValue::Bool(true), + FieldValue::U(7), + FieldValue::U(300), + FieldValue::U(70_000), + FieldValue::I(-2), + FieldValue::F(1.5), + FieldValue::F(-100.0), + FieldValue::F(0.0), + FieldValue::Str("Ana".into()), + FieldValue::Bytes(vec![0xde, 0xad]), + ]; + let welcome = Welcome { + session_id: "s1".into(), + zone_id: "z1".into(), + role: Role::Player, + tick_rate: 30, + patch_rate: 20, + server_tick: 42, + server_time: 1000.25, + reconnect_token: "rt".into(), + content_version: "c1".into(), + schema: schema.clone(), + features: feature::FOCUS, + origin: None, + }; + let server = vec![ + ("welcome", ServerMessage::Welcome(welcome.clone())), + ( + "welcome_origin", + ServerMessage::Welcome(Welcome { + role: Role::Observer, + origin: Some(Origin::new(-48.0, 1e6 + 0.5)), + ..welcome + }), + ), + ( + "delta_empty", + ServerMessage::Delta(Delta { + server_tick: 43, + ack_seq: 0, + ..Delta::default() + }), + ), + ( + "delta", + ServerMessage::Delta(Delta { + server_tick: 200, + ack_seq: 17, + removes: vec![9, 130], + creates: vec![ + EntityCreate { + id: 300, + kind: 1, + fields: hero_fields, + }, + EntityCreate { + id: 301, + kind: 2, + fields: vec![FieldValue::F(32.0)], + }, + ], + updates: vec![ + EntityUpdate { + id: 5, + mask: 0b0100_0100, + fields: vec![FieldValue::U(299), FieldValue::F(0.0)], + }, + EntityUpdate { + id: 6, + mask: 0b1, + fields: vec![FieldValue::F(64.0)], + }, + EntityUpdate { + id: 301, + mask: 0b1, + fields: vec![FieldValue::F(0.0)], + }, + ], + }), + ), + ( + "event", + ServerMessage::Event { + type_id: 3, + payload: b"xp".to_vec(), + }, + ), + ( + "pong", + ServerMessage::Pong { + client_time: 1234.5, + server_time: 99.0, + }, + ), + ( + "freeze", + ServerMessage::Freeze(Notice { + reason: "content_update".into(), + version: "c2".into(), + notes: "brb".into(), + }), + ), + ( + "resume", + ServerMessage::Resume(Notice { + reason: "content_update".into(), + version: "c2".into(), + notes: String::new(), + }), + ), + ( + "handoff", + ServerMessage::Handoff { + target_zone: "z2".into(), + transfer_ticket: "tt".into(), + }, + ), + ( + "kick", + ServerMessage::Kick { + code: kick::SHUTDOWN, + message: "bye".into(), + }, + ), + ( + "error", + ServerMessage::Error { + code: error::UNAUTHORIZED, + message: "Expired".into(), + }, + ), + ( + "kick_reload", + ServerMessage::Kick { + code: kick::RELOAD, + message: "content c2 required".into(), + }, + ), + ( + "redirect", + ServerMessage::Redirect { + zone_id: "realm.west".into(), + url: "ws://10.0.0.2:2567/zones/realm.west".into(), + }, + ), + ]; + for (name, msg) in server { + let ctx = Kinds(&schema, &known); + let bytes = msg.encode(&ctx).unwrap(); + let decoded = ServerMessage::decode(&bytes, &ctx).unwrap(); + // Quantized values decode to their canonical form; compare JSON of + // the decoded message (what a client will see). + let mut entry = json!({ + "name": name, "direction": "server_to_client", + "hex": hex(&bytes), "decoded": server_json(&decoded), + }); + if matches!(msg, ServerMessage::Delta(_)) { + entry["known_entities"] = json!(known + .iter() + .map(|(id, kind)| json!({ "id": id, "kind": kind })) + .collect::>()); + entry["schema"] = schema_json(&schema); + } + // Re-encoding the decoded form is byte-identical. + assert_eq!(decoded.encode(&ctx).unwrap(), bytes, "{name}"); + out.push(entry); + } + check_or_write("messages.json", json!({ "messages": out })); + + // Fixture hex decodes back (guards hand edits). + let text = std::fs::read_to_string(fixtures_dir().join("messages.json")).unwrap(); + let parsed: Value = serde_json::from_str(&text).unwrap(); + for m in parsed["messages"].as_array().unwrap() { + let bytes = unhex(m["hex"].as_str().unwrap()); + if m["direction"] == "client_to_server" { + assert_eq!( + client_json(&ClientMessage::decode(&bytes).unwrap()), + m["decoded"] + ); + } else { + let msg = ServerMessage::decode(&bytes, &Kinds(&schema, &known)).unwrap(); + assert_eq!(server_json(&msg), m["decoded"]); + } + } +} diff --git a/distributed_game/tests/inbox/main.rs b/distributed_game/tests/inbox/main.rs new file mode 100644 index 000000000..08f62cd57 --- /dev/null +++ b/distributed_game/tests/inbox/main.rs @@ -0,0 +1,515 @@ +//! The zone inbox: typed messages and the built-in kick, delivered on the +//! zone task between ticks; `GameServer::send`, `/admin/zone-message` and +//! `ZoneInboxClient` (auth, inactive zones, wrong owner). + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use distributed_game::lifecycle::{LeftReason, Lifecycle}; +use distributed_game::net::{ + GameServer, InboxError, InternalHttpSecret, ServerConfig, TicketKey, ZoneFactory, + ZoneInboxClient, ZONE_MESSAGE_PATH, +}; +use distributed_game::protocol::kick; +use distributed_game::world::{HostAddr, StaticDirectory}; +use distributed_game::*; +use serde_json::json; + +const SECRET: &str = "inbox-secret"; +const ADMIN: &str = "inbox-test-internal-secret-0123456789"; + +/// Messages a service may send into a hall. +#[derive(Debug, Clone, PartialEq, GameEvent)] +pub enum HallMessage { + /// Change the message of the day. + #[game_event(id = 1)] + SetMotd { + /// New text. + #[long] + motd: String, + }, + /// Numbered probe (ordering / tick checks). + #[game_event(id = 2)] + Probe { + /// Sequence. + n: u32, + }, + /// Send `Probe { n }` on to the zone `to` (`Ctx::send_zone`). + #[game_event(id = 3)] + Forward { + /// Target zone. + #[long] + to: String, + /// Sequence. + n: u32, + }, +} + +#[derive(Default)] +struct Shared { + /// `(n, tick seen, delivered inside a tick?)` per probe. + probes: Vec<(u32, u64, bool)>, + /// `(receiving zone, sending zone, n)` per zone-to-zone probe. + zone_probes: Vec<(String, String, u32)>, +} + +struct Hall { + motd: String, + in_tick: bool, + ticks: u64, + left: Vec, + shared: Arc>, +} + +impl Zone for Hall { + type Config = Arc>; + type Input = u8; + type Timer = (); + type Message = HallMessage; + + fn schema() -> EntitySchema { + EntitySchema::new() + } + + fn on_create(_ctx: &mut Ctx<'_, Self>, shared: Arc>) -> Self { + Self { + motd: String::new(), + in_tick: false, + ticks: 0, + left: Vec::new(), + shared, + } + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { + payload.first().copied() + } + + fn on_tick(&mut self, _ctx: &mut Ctx<'_, Self>) { + self.in_tick = true; + self.ticks += 1; + // A little work so a concurrent delivery would have a window. + std::thread::sleep(Duration::from_micros(200)); + self.in_tick = false; + } + + fn on_message(&mut self, ctx: &mut Ctx<'_, Self>, message: HallMessage) { + match message { + HallMessage::SetMotd { motd } => self.motd = motd, + HallMessage::Probe { n } => { + self.shared + .lock() + .unwrap() + .probes + .push((n, ctx.tick(), self.in_tick)); + } + HallMessage::Forward { to, n } => ctx.send_zone(&to, &HallMessage::Probe { n }), + } + } + + fn on_zone_message(&mut self, ctx: &mut Ctx<'_, Self>, from: &ZoneSender, message: HallMessage) { + if let HallMessage::Probe { n } = message { + self.shared.lock().unwrap().zone_probes.push(( + ctx.zone_id().to_string(), + from.zone.clone(), + n, + )); + } + } + + fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, _player: PlayerId, reason: LeaveReason) { + self.left.push(reason); + } + + /// Keep ticking at the Hot rate with nobody connected. + fn has_pending_work(&self) -> bool { + true + } + + fn replicate(&self, _out: &mut WorldView) {} +} + +fn claims(principal: &str, nonce: &str) -> TicketClaims { + TicketClaims::new(principal, "hall", u64::MAX, nonce, Role::Player) +} + +#[test] +fn kick_removes_the_principal_with_a_lifecycle_fact_and_messages_reach_on_message() { + let clock = ManualClock::new(); + let (queue, feed) = fact_channel(16, RetryPolicy::default()); + let mut h = ZoneHost::::new( + "hall", + HostConfig { + lifecycle_facts: true, + ..HostConfig::default() + }, + Arc::new(clock.clone()), + Arc::default(), + ) + .with_facts(queue); + let ana = h.join(&claims("ana", "a"), 0, "").unwrap(); + h.join(&claims("bo", "b"), 0, "").unwrap(); + h.drain_outbound(); + + let delivered = h.deliver(ZoneInbound::Kick { + principal: "ana".into(), + reason: "banned".into(), + }); + assert_eq!(delivered.players_kicked, 1); + assert_eq!(h.zone().left, [LeaveReason::Kicked]); + assert_eq!(h.player_count(), 1); + let out = h.drain_outbound(); + let kicked = out.iter().any(|o| match o { + Outbound::Frame { client, frame } if *client == ana.client => matches!( + ServerMessage::decode(frame, &()), + Ok(ServerMessage::Kick { code, ref message }) if code == kick::BY_ZONE && message == "banned" + ), + _ => false, + }); + assert!(kicked, "the client is told why"); + // Kicking someone absent is a no-op. + assert_eq!( + h.deliver(ZoneInbound::Kick { + principal: "nobody".into(), + reason: String::new(), + }), + Delivered::default() + ); + h.deliver(ZoneInbound::Message(HallMessage::SetMotd { + motd: "welcome".into(), + })); + assert_eq!(h.zone().motd, "welcome"); + + drop(h); + let sink = MemoryFactSink::new(); + let waker = std::task::Waker::noop(); + let mut cx = std::task::Context::from_waker(waker); + let mut run = std::pin::pin!(feed.run(sink.clone(), |_| async {})); + while std::future::Future::poll(run.as_mut(), &mut cx).is_pending() {} + let ana: Vec<_> = sink + .committed() + .iter() + .filter(|f| f.principal() == Some("ana")) + .filter_map(Lifecycle::of) + .collect(); + assert!( + matches!(ana.last(), Some(Lifecycle::Left(l)) if l.reason == LeftReason::Kicked), + "{ana:?}" + ); +} + +#[test] +fn messages_are_in_the_surface_with_their_codec() { + let surface = GameSurface::new("hall").messages::<::Message>(); + let names: Vec<_> = surface.messages.iter().map(|m| m.name.as_str()).collect(); + assert_eq!(names, ["set_motd", "probe", "forward"]); + assert!(surface.to_json().contains("\"messages\"")); + // No messages: nothing in the JSON (older surfaces stay identical). + let quiet = GameSurface::new("quiet").messages::(); + assert!(!quiet.to_json().contains("messages")); + let message = HallMessage::Probe { n: 7 }; + let back = HallMessage::decode_event(message.event_id(), &message.to_payload()).unwrap(); + assert_eq!(back, Some(message)); +} + +async fn serve( + server: &GameServer, + listener: tokio::net::TcpListener, +) -> tokio::task::JoinHandle<()> { + let serving = server.clone(); + tokio::spawn(async move { + serving + .serve(listener, std::future::pending()) + .await + .unwrap(); + }) +} + +fn server(shared: Arc>) -> GameServer { + let mut config = ServerConfig::new(TicketKey::new(SECRET)); + config.admin_secret = Some(InternalHttpSecret::new(ADMIN).unwrap()); + config.host.tick_rate = 120; + GameServer::new( + config, + ZoneFactory::sync(move |a| a.zone_id.starts_with("hall").then(|| shared.clone())), + ) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn on_message_runs_on_the_zone_task_between_ticks() { + let shared = Arc::new(Mutex::new(Shared::default())); + let server = server(shared.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let handle = serve(&server, listener).await; + assert!(server.activate("hall").await); + let senders: Vec<_> = (0..64u32) + .map(|n| { + let server = server.clone(); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(u64::from(n % 16) * 3)).await; + server + .send("hall", ZoneInbound::Message(HallMessage::Probe { n })) + .await + }) + }) + .collect(); + for sender in senders { + sender.await.unwrap().unwrap(); + } + let probes = shared.lock().unwrap().probes.clone(); + assert_eq!(probes.len(), 64); + assert!( + probes.iter().all(|(_, _, in_tick)| !in_tick), + "never inside a tick" + ); + let ticks: std::collections::BTreeSet<_> = probes.iter().map(|(_, t, _)| *t).collect(); + assert!(ticks.len() > 1, "delivered across several ticks: {ticks:?}"); + + // A message for a zone that is not running is refused, never activates it. + assert_eq!( + server + .send( + "hall-cold", + ZoneInbound::Message(HallMessage::Probe { n: 0 }) + ) + .await, + Err(InboxError::Inactive) + ); + assert!(!server.is_active("hall-cold")); + server.shutdown(); + tokio::time::timeout(Duration::from_secs(5), handle) + .await + .unwrap() + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn admin_route_authenticates_refuses_inactive_and_redirects_to_the_owner() { + // Two hosts; the shared directory places `hall.a` on A. + let (la, lb) = ( + tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(), + tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(), + ); + let a_addr = HostAddr::new("A", la.local_addr().unwrap().to_string()); + let b_addr = HostAddr::new("B", lb.local_addr().unwrap().to_string()); + let directory = Arc::new(StaticDirectory::new()); + directory.add_host(a_addr.clone()).add_host(b_addr.clone()); + directory.assign("hall.a", "A").assign("hall.cold", "A"); + let shared = Arc::new(Mutex::new(Shared::default())); + let a = server(shared.clone()) + .with_host_id("A") + .with_directory(directory.clone()); + let b = server(shared.clone()) + .with_host_id("B") + .with_directory(directory.clone()); + let (ha, hb) = (serve(&a, la).await, serve(&b, lb).await); + assert!(a.activate("hall.a").await); + let probe = |n: u32| { + let m = HallMessage::Probe { n }; + json!({ + "zone": "hall.a", + "message": { + "type_id": m.event_id(), + "payload": base64_url(&m.to_payload()), + } + }) + }; + // Raw requests: the internal secret header as presented. + let post = |url: String, secret: &'static str, body: serde_json::Value| async move { + let response = reqwest::Client::new() + .post(format!("{url}{ZONE_MESSAGE_PATH}")) + .header("x-distributed-internal-secret", secret) + .json(&body) + .send() + .await + .unwrap(); + let status = response.status().as_u16(); + (status, response.json::().await.unwrap()) + }; + + // Unauthenticated (wrong or empty secret) is refused before anything. + for secret in ["", "wrong"] { + let (status, body) = post(a_addr.admin_url.clone(), secret, probe(1)).await; + assert_eq!( + (status, body["error"].as_str()), + (401, Some("unauthorized")) + ); + } + // The owner delivers. + let (status, _) = post(a_addr.admin_url.clone(), ADMIN, probe(2)).await; + assert_eq!(status, 200); + // The wrong host answers with the owner instead of delivering. + let (status, body) = post(b_addr.admin_url.clone(), ADMIN, probe(3)).await; + assert_eq!(status, 421, "{body}"); + assert_eq!(body["error"], "wrong_owner"); + assert_eq!(body["owner"], "A"); + assert_eq!(body["admin_url"], a_addr.admin_url); + // Inactive zones: 404, and still inactive. + let mut cold = probe(4); + cold["zone"] = json!("hall.cold"); + let (status, body) = post(a_addr.admin_url.clone(), ADMIN, cold).await; + assert_eq!((status, body["error"].as_str()), (404, Some("inactive"))); + assert!(!a.is_active("hall.cold")); + // Unknown message ids and malformed payloads: 400. + let bad = json!({"zone": "hall.a", "message": {"type_id": 99, "payload": ""}}); + let (status, _) = post(a_addr.admin_url.clone(), ADMIN, bad).await; + assert_eq!(status, 400); + let short = json!({"zone": "hall.a", "message": {"type_id": 2, "payload": ""}}); + let (status, _) = post(a_addr.admin_url.clone(), ADMIN, short).await; + assert_eq!(status, 400); + + // A service whose directory is stale (says B) follows the redirect. + let stale = Arc::new(StaticDirectory::new()); + stale.add_host(b_addr.clone()).assign("hall.a", "B"); + let client = ZoneInboxClient::new(stale, InternalHttpSecret::new(ADMIN).unwrap()); + client + .send("hall.a", &HallMessage::SetMotd { motd: "hi".into() }) + .await + .unwrap(); + assert_eq!( + a.inspect("hall.a", |h| h.zone().motd.clone()) + .await + .unwrap(), + "hi" + ); + client + .send("hall.a", &HallMessage::Probe { n: 5 }) + .await + .unwrap(); + assert_eq!( + client.kick("hall.a", "nobody", "bye").await.unwrap(), + Delivered::default() + ); + assert_eq!( + client.send("hall.cold", &HallMessage::Probe { n: 6 }).await, + Err(InboxError::Inactive) + ); + let unauthorized = ZoneInboxClient::new( + directory.clone(), + InternalHttpSecret::new("not-the-inbox-test-internal-secret").unwrap(), + ); + assert_eq!( + unauthorized + .send("hall.a", &HallMessage::Probe { n: 7 }) + .await, + Err(InboxError::Unauthorized) + ); + let ns: Vec<_> = shared.lock().unwrap().probes.iter().map(|p| p.0).collect(); + assert_eq!(ns, [2, 5], "only the authorized, owned deliveries ran"); + + a.shutdown(); + b.shutdown(); + for handle in [ha, hb] { + tokio::time::timeout(Duration::from_secs(5), handle) + .await + .unwrap() + .unwrap(); + } +} + +/// Wait (bounded) until `shared` holds `n` zone-to-zone probes. +async fn zone_probes(shared: &Arc>, n: usize) -> Vec<(String, String, u32)> { + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + loop { + let probes = shared.lock().unwrap().zone_probes.clone(); + if probes.len() >= n || tokio::time::Instant::now() >= deadline { + return probes; + } + tokio::time::sleep(Duration::from_millis(5)).await; + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn zone_messages_reach_a_zone_on_the_same_server_and_never_wake_one() { + let shared = Arc::new(Mutex::new(Shared::default())); + let server = server(shared.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let handle = serve(&server, listener).await; + assert!(server.activate("hall.a").await); + assert!(server.activate("hall.b").await); + let forward = |to: &str, n| { + ZoneInbound::Message(HallMessage::Forward { + to: to.to_string(), + n, + }) + }; + // Sent in this order from one handler: the cold zone's is dropped + // before the one for `hall.b` is delivered. + server.send("hall.a", forward("hall.cold", 1)).await.unwrap(); + server.send("hall.a", forward("hall.b", 2)).await.unwrap(); + assert_eq!( + zone_probes(&shared, 1).await, + [("hall.b".to_string(), "hall.a".to_string(), 2)] + ); + assert!(!server.is_active("hall.cold"), "a zone message never wakes a zone"); + // A zone may message itself. + server.send("hall.a", forward("hall.a", 3)).await.unwrap(); + assert_eq!(zone_probes(&shared, 2).await.len(), 2); + server.shutdown(); + tokio::time::timeout(Duration::from_secs(5), handle) + .await + .unwrap() + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn zone_messages_reach_a_zone_on_a_peer_host() { + let (la, lb) = ( + tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(), + tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(), + ); + let a_addr = HostAddr::new("A", la.local_addr().unwrap().to_string()); + let b_addr = HostAddr::new("B", lb.local_addr().unwrap().to_string()); + let directory = Arc::new(StaticDirectory::new()); + directory.add_host(a_addr).add_host(b_addr); + directory + .assign("hall.a", "A") + .assign("hall.b", "B") + .assign("hall.cold", "B"); + let shared = Arc::new(Mutex::new(Shared::default())); + let a = server(shared.clone()) + .with_host_id("A") + .with_directory(directory.clone()); + let b = server(shared.clone()) + .with_host_id("B") + .with_directory(directory.clone()); + let (ha, hb) = (serve(&a, la).await, serve(&b, lb).await); + assert!(a.activate("hall.a").await); + assert!(b.activate("hall.b").await); + for (to, n) in [("hall.cold", 1), ("hall.b", 2)] { + a.send( + "hall.a", + ZoneInbound::Message(HallMessage::Forward { to: to.into(), n }), + ) + .await + .unwrap(); + } + assert_eq!( + zone_probes(&shared, 1).await, + [("hall.b".to_string(), "hall.a".to_string(), 2)] + ); + assert!(!b.is_active("hall.cold"), "a zone message never wakes a zone"); + a.shutdown(); + b.shutdown(); + for handle in [ha, hb] { + tokio::time::timeout(Duration::from_secs(5), handle) + .await + .unwrap() + .unwrap(); + } +} + +fn base64_url(bytes: &[u8]) -> String { + const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + let mut out = String::new(); + for chunk in bytes.chunks(3) { + let n = chunk + .iter() + .enumerate() + .fold(0u32, |acc, (i, b)| acc | (u32::from(*b) << (16 - 8 * i))); + for i in 0..=chunk.len() { + out.push(ALPHABET[((n >> (18 - 6 * i)) & 63) as usize] as char); + } + } + out +} diff --git a/distributed_game/tests/lifecycle/main.rs b/distributed_game/tests/lifecycle/main.rs new file mode 100644 index 000000000..cc3a48047 --- /dev/null +++ b/distributed_game/tests/lifecycle/main.rs @@ -0,0 +1,372 @@ +//! Host-emitted player lifecycle facts (`HostConfig::lifecycle_facts`): +//! the five transitions, restart-safe keys, per-principal order under +//! concurrent commits, backpressure backlog and the connection hooks. + +#[path = "../support/arena.rs"] +mod arena; + +use std::collections::BTreeMap; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use arena::{Arena, ArenaConfig}; +use distributed_game::lifecycle::{ + JoinVia, LeftReason, Lifecycle, LostCause, CONNECTION_LOST, PLAYER_DISCONNECTED, PLAYER_JOINED, + PLAYER_RECONNECTED, +}; +use distributed_game::protocol::ServerMessage; +use distributed_game::{ + fact_channel, spawn_fact_worker, BoxFuture, ClientId, Fact, FactError, FactFeed, FactReceipt, + FactSink, HostConfig, ManualClock, MemoryFactSink, Outbound, RetryPolicy, Role, TicketClaims, + ZoneHost, +}; + +const MS: fn(u64) -> Duration = Duration::from_millis; + +fn claims(principal: &str, nonce: &str) -> TicketClaims { + TicketClaims::new(principal, "z1", u64::MAX, nonce, Role::Player) +} + +fn config(boot_epoch: u64) -> HostConfig { + HostConfig { + lifecycle_facts: true, + boot_epoch, + reconnect_grace: MS(500), + ..HostConfig::default() + } +} + +fn token(out: &[Outbound], client: ClientId) -> String { + out.iter() + .find_map(|o| match o { + Outbound::Frame { client: c, frame } if *c == client => { + match ServerMessage::decode(frame, &()).ok()? { + ServerMessage::Welcome(w) => Some(w.reconnect_token), + _ => None, + } + } + _ => None, + }) + .expect("welcome") +} + +/// Drive a whole scripted session and return the committed facts. +fn run_session(boot_epoch: u64) -> (Vec, Vec) { + let clock = ManualClock::new(); + let (queue, feed) = fact_channel(64, RetryPolicy::default()); + let mut h = ZoneHost::::new( + "z1", + config(boot_epoch), + Arc::new(clock.clone()), + ArenaConfig::default(), + ) + .with_facts(queue); + + // ana: join, drop, reconnect, reload the page (fresh ticket), drop, + // grace expires. + let ana = h.join(&claims("ana", "a1"), 0, "").unwrap(); + let ana_token = token(&h.drain_outbound(), ana.client); + h.disconnect(ana.client, false); + let back = h.reconnect(&ana_token, 0).unwrap(); + h.drain_outbound(); + let again = h.join(&claims("ana", "a2"), 0, "").unwrap(); + assert_ne!(back.client, again.client); + h.disconnect(again.client, false); + clock.advance(MS(600)); + h.advance(); + // bo: kicked. cy: leaves gracefully. dee: still here at dispose. + let bo = h.join(&claims("bo", "b1"), 0, "").unwrap(); + let Some(distributed_game::Viewer::Player(bo_id)) = h.viewer_of(bo.client) else { + panic!("bo is a player") + }; + h.kick(bo_id, "cheating"); + let cy = h.join(&claims("cy", "c1"), 0, "").unwrap(); + h.disconnect(cy.client, true); + h.join(&claims("dee", "d1"), 0, "").unwrap(); + h.dispose(); + let hooks = h.zone().connection_events.clone(); + drop(h); + let sink = MemoryFactSink::new(); + block_on(feed.run(sink.clone(), |_| async {})); + (sink.committed(), hooks) +} + +fn block_on(f: impl std::future::Future) { + let waker = std::task::Waker::noop(); + let mut cx = std::task::Context::from_waker(waker); + let mut f = std::pin::pin!(f); + while f.as_mut().poll(&mut cx).is_pending() {} +} + +fn of(facts: &[Fact], principal: &str) -> Vec { + facts + .iter() + .filter(|f| f.principal() == Some(principal)) + .map(|f| Lifecycle::of(f).expect("only lifecycle facts")) + .collect() +} + +#[test] +fn the_host_emits_every_transition_bound_to_the_verified_principal() { + let (facts, hooks) = run_session(7); + assert!(facts.iter().all(|f| f.stamp().zone_id == "z1")); + // Every stamp is strictly later than the previous one, even for + // transitions in the same tick and millisecond (emission sequence). + for pair in facts.windows(2) { + assert!( + pair[1].stamp().emitted_after(pair[0].stamp()), + "{:?} then {:?}", + pair[0].stamp(), + pair[1].stamp() + ); + } + let ana = of(&facts, "ana"); + let commands: Vec<_> = facts + .iter() + .filter(|f| f.principal() == Some("ana")) + .map(Fact::command) + .collect(); + assert_eq!( + commands, + [ + PLAYER_JOINED, + CONNECTION_LOST, + PLAYER_RECONNECTED, + PLAYER_JOINED, + CONNECTION_LOST, + PLAYER_DISCONNECTED + ] + ); + let Lifecycle::Joined(first) = &ana[0] else { + panic!() + }; + assert_eq!(first.via, JoinVia::Ticket); + let Lifecycle::ConnectionLost(lost) = &ana[1] else { + panic!() + }; + assert_eq!((lost.grace_ms, lost.cause), (500, LostCause::Dropped)); + let Lifecycle::Joined(rejoin) = &ana[3] else { + panic!() + }; + assert_eq!(rejoin.via, JoinVia::Rejoin); + assert!(ana[5].is_terminal()); + + let reasons: Vec<_> = ["bo", "cy", "dee"] + .iter() + .map(|p| match of(&facts, p).as_slice() { + [Lifecycle::Joined(_), Lifecycle::Left(left)] => left.reason, + other => panic!("{p}: {other:?}"), + }) + .collect(); + assert_eq!( + reasons, + [LeftReason::Kicked, LeftReason::Left, LeftReason::Disposed] + ); + + // Keys: command, zone, boot epoch, slot, transition counter (ana's + // slot is PlayerId(2): ids are shared with connection ids). + let keys: Vec<_> = facts + .iter() + .filter(|f| f.principal() == Some("ana")) + .map(|f| f.key().to_string()) + .collect(); + assert_eq!(keys[0], format!("{PLAYER_JOINED}:z1:7:p2:1")); + assert_eq!(keys[5], format!("{PLAYER_DISCONNECTED}:z1:7:p2:6")); + // The payload names no identity; the principal is the binding. + assert!(facts.iter().all(|f| f.input().get("principal").is_none())); + + // Connection hooks: grace start and reconnect. + assert_eq!(hooks, ["lost:2", "back:2", "lost:2"]); +} + +#[test] +fn keys_are_stable_per_run_and_distinct_after_a_restart() { + let (first, _) = run_session(100); + let (same, _) = run_session(100); + let (restarted, _) = run_session(101); + let keys = |facts: &[Fact]| { + facts + .iter() + .map(|f| f.key().to_string()) + .collect::>() + }; + assert_eq!(keys(&first), keys(&same), "deterministic per activation"); + let before: std::collections::HashSet<_> = keys(&first).into_iter().collect(); + assert_eq!(before.len(), first.len(), "unique within a run"); + assert!( + keys(&restarted).iter().all(|k| !before.contains(k)), + "a restart never reuses a key" + ); +} + +#[test] +fn off_by_default() { + let clock = ManualClock::new(); + let (queue, feed) = fact_channel(16, RetryPolicy::default()); + let mut h = ZoneHost::::new( + "z1", + HostConfig::default(), + Arc::new(clock.clone()), + ArenaConfig::default(), + ) + .with_facts(queue); + let ana = h.join(&claims("ana", "a1"), 0, "").unwrap(); + h.disconnect(ana.client, false); + let bo = h.join(&claims("bo", "b1"), 0, "").unwrap(); + h.disconnect(bo.client, true); + assert_eq!(h.zone().connection_events, ["lost:2"], "hooks still run"); + drop(h); + let sink = MemoryFactSink::new(); + block_on(feed.run(sink.clone(), |_| async {})); + assert!(sink.committed().is_empty()); +} + +/// Commits slowly for "joined" (so a later fact of the same principal would +/// overtake it if lanes were not respected) and fails the first attempt of +/// every reconnect (retries keep the key). +#[derive(Clone, Default)] +struct SlowSink { + order: Arc>>, + attempts: Arc>>, +} + +impl FactSink for SlowSink { + fn commit<'a>(&'a self, fact: &'a Fact) -> BoxFuture<'a, Result> { + Box::pin(async move { + let attempt = { + let mut attempts = self.attempts.lock().unwrap(); + let n = attempts.entry(fact.key().to_string()).or_default(); + *n += 1; + *n + }; + let delay = match fact.command() { + PLAYER_JOINED => 40, + CONNECTION_LOST => 5, + _ => 1, + }; + tokio::time::sleep(MS(delay)).await; + if fact.command() == PLAYER_RECONNECTED && attempt == 1 { + return Err(FactError::Retryable("flaky".into())); + } + self.order.lock().unwrap().push(( + fact.principal().unwrap_or_default().to_string(), + fact.command().to_string(), + fact.key().to_string(), + )); + Ok(FactReceipt { + payload: serde_json::Value::Null, + replayed: false, + }) + }) + } +} + +fn concurrent(feed: FactFeed) -> FactFeed { + feed.with_max_concurrent_commits(4) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn per_principal_order_holds_with_concurrent_commits_and_backpressure() { + let clock = ManualClock::new(); + // Capacity 2: most lifecycle facts wait in the host's backlog. + let policy = RetryPolicy { + base_backoff: MS(2), + ..RetryPolicy::default() + }; + let (queue, feed) = fact_channel(2, policy); + let sink = SlowSink::default(); + let worker = spawn_fact_worker(concurrent(feed), sink.clone()); + let mut h = ZoneHost::::new( + "z1", + config(9), + Arc::new(clock.clone()), + ArenaConfig::default(), + ) + .with_facts(queue); + + let mut emitted: BTreeMap> = BTreeMap::new(); + for principal in ["ana", "bo", "cy"] { + let joined = h.join(&claims(principal, principal), 0, "").unwrap(); + let token = token(&h.drain_outbound(), joined.client); + h.disconnect(joined.client, false); + h.reconnect(&token, 0).unwrap(); + h.drain_outbound(); + emitted.insert( + principal.into(), + vec![PLAYER_JOINED, CONNECTION_LOST, PLAYER_RECONNECTED], + ); + } + assert!(h.facts_in_flight() > 2, "backlog beyond the queue capacity"); + // The host keeps flushing its backlog as the queue drains. + for _ in 0..400 { + if h.facts_in_flight() == 0 { + break; + } + tokio::time::sleep(MS(5)).await; + clock.advance(MS(5)); + h.advance(); + } + assert_eq!(h.facts_in_flight(), 0, "every lifecycle fact settled"); + drop(h); + worker.await.unwrap(); + + let order = sink.order.lock().unwrap().clone(); + assert_eq!(order.len(), 9, "nothing dropped: {order:?}"); + for (principal, expected) in &emitted { + let committed: Vec<_> = order + .iter() + .filter(|(p, _, _)| p == principal) + .map(|(_, command, _)| command.as_str()) + .collect(); + assert_eq!(&committed, expected, "{principal}"); + } + // The flaky reconnects were retried under the same key. + let attempts = sink.attempts.lock().unwrap(); + for (_, command, key) in order.iter().filter(|(_, c, _)| c == PLAYER_RECONNECTED) { + assert_eq!(attempts[key], 2, "{command} retried once with key {key}"); + } +} + +#[test] +fn handoff_and_reload_are_lifecycle_transitions_too() { + let clock = ManualClock::new(); + let (queue, feed) = fact_channel(16, RetryPolicy::default()); + let mut h = ZoneHost::::new( + "z1", + HostConfig { + content_version: "v1".into(), + ..config(3) + }, + Arc::new(clock.clone()), + ArenaConfig::default(), + ) + .with_facts(queue); + let transfer = distributed_game::Transfer { + claims: claims("ana", "t1"), + source_zone: "z0".into(), + issuer: "h0".into(), + generation: 1, + carried: Vec::new(), + departed_at_ms: 0, + }; + let joined = h.join_transfer(&transfer, 0, "v1").unwrap(); + let Some(distributed_game::Viewer::Player(ana)) = h.viewer_of(joined.client) else { + panic!() + }; + h.reload_player(ana); + h.handoff(ana, "z2", "ticket"); + drop(h); + let sink = MemoryFactSink::new(); + block_on(feed.run(sink.clone(), |_| async {})); + match of(&sink.committed(), "ana").as_slice() { + [Lifecycle::Joined(j), Lifecycle::ConnectionLost(l), Lifecycle::Left(left)] => { + assert_eq!( + (j.via, j.from_zone.as_deref()), + (JoinVia::Handoff, Some("z0")) + ); + assert_eq!(l.cause, LostCause::Reload); + assert_eq!(left.reason, LeftReason::Handoff); + } + other => panic!("{other:?}"), + } +} diff --git a/distributed_game/tests/net_e2e/main.rs b/distributed_game/tests/net_e2e/main.rs new file mode 100644 index 000000000..d9dd57cd2 --- /dev/null +++ b/distributed_game/tests/net_e2e/main.rs @@ -0,0 +1,1365 @@ +//! End-to-end: a real WebSocket client joins through signed-ticket +//! admission, sends inputs, receives deltas, reconnects and is shut down. + +#[path = "../support/admission.rs"] +mod admission; +#[path = "../support/arena.rs"] +mod arena; + +use std::time::Duration; + +use arena::{Arena, ArenaConfig, AVATAR}; +use distributed_game::net::{GameServer, NetSim, ServerConfig, TicketKey, ZoneFactory}; +use distributed_game::protocol::{error, kick, Hello}; +use distributed_game::{ + ClientMessage, ClientMirror, FieldValue, MemoryFactSink, RetryPolicy, Role, ServerMessage, + TicketClaims, TicketExtension, TicketExtensions, PROTOCOL_VERSION, +}; +use futures_util::{SinkExt, StreamExt}; +use serde::{Deserialize, Serialize}; +use tokio::net::TcpStream; +use tokio_tungstenite::tungstenite::Message; +use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream}; + +type Ws = WebSocketStream>; + +const SECRET: &str = "dev-secret"; + +fn ticket(principal: &str, zone: &str, nonce: &str, role: Role) -> String { + TicketKey::new(SECRET).sign(&TicketClaims { + principal: principal.into(), + zone: zone.into(), + expires_at: 4_000_000_000, + nonce: nonce.into(), + role, + name: None, + extensions: Default::default(), + wake: false, + }) +} + +async fn start( + net_sim: Option, +) -> (String, GameServer, tokio::task::JoinHandle<()>) { + start_keyed(SECRET, net_sim).await +} + +async fn start_keyed( + secret: &str, + net_sim: Option, +) -> (String, GameServer, tokio::task::JoinHandle<()>) { + let mut config = ServerConfig::new(TicketKey::new(secret)); + config.host.tick_rate = 30; + config.host.patch_rate = 20; + config.net_sim = net_sim; + let server = GameServer::::new( + config, + ZoneFactory::sync(|a| a.zone_id.starts_with('z').then(ArenaConfig::default)), + ) + .with_fact_sink(MemoryFactSink::new(), 64, RetryPolicy::default()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let serving = server.clone(); + let handle = tokio::spawn(async move { + serving + .serve(listener, std::future::pending()) + .await + .unwrap(); + }); + (format!("ws://{addr}"), server, handle) +} + +async fn send(ws: &mut Ws, msg: ClientMessage) { + ws.send(Message::Binary(msg.encode().into())).await.unwrap(); +} + +async fn hello(ws: &mut Ws, ticket: String, reconnect_token: String) { + send( + ws, + ClientMessage::Hello(Hello { + protocol_version: PROTOCOL_VERSION, + content_version: String::new(), + capabilities: 0, + ticket, + reconnect_token, + near: false, + }), + ) + .await; +} + +/// Next decoded server message (skipping non-binary frames). +async fn next(ws: &mut Ws, mirror: &mut ClientMirror) -> Option { + loop { + let frame = tokio::time::timeout(Duration::from_secs(5), ws.next()) + .await + .expect("server message within 5s")?; + match frame { + Ok(Message::Binary(bytes)) => return Some(mirror.apply(&bytes).unwrap()), + Ok(Message::Close(_)) | Err(_) => return None, + Ok(_) => continue, + } + } +} + +async fn connect(url: &str, zone: &str) -> Ws { + connect_async(format!("{url}/zones/{zone}")) + .await + .unwrap() + .0 +} + +async fn expect_error(url: &str, zone: &str, ticket: String, code: u32) { + let mut ws = connect(url, zone).await; + hello(&mut ws, ticket, String::new()).await; + let mut mirror = ClientMirror::new(); + match next(&mut ws, &mut mirror).await { + Some(ServerMessage::Error { code: got, .. }) => assert_eq!(got, code), + other => panic!("expected error {code}, got {other:?}"), + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn client_joins_sends_inputs_receives_deltas_and_reconnects() { + let (url, server, handle) = start(None).await; + + let mut ws = connect(&url, "z1").await; + hello( + &mut ws, + ticket("alice", "z1", "n1", Role::Player), + String::new(), + ) + .await; + let mut mirror = ClientMirror::new(); + let Some(ServerMessage::Welcome(welcome)) = next(&mut ws, &mut mirror).await else { + panic!("expected Welcome") + }; + assert_eq!(welcome.zone_id, "z1"); + assert_eq!(welcome.role, Role::Player); + assert_eq!(welcome.tick_rate, 30); + assert_eq!(welcome.schema.kinds().len(), 2); + + // Wait for the first delta carrying our avatar. + while mirror.entities.is_empty() { + next(&mut ws, &mut mirror).await.unwrap(); + } + let (&avatar_id, avatar) = mirror.entities.iter().next().unwrap(); + assert_eq!(avatar.kind, AVATAR); + let FieldValue::F(start_x) = avatar.fields[0] else { + panic!() + }; + + for seq in 1..=10 { + send( + &mut ws, + ClientMessage::Input { + seq, + client_tick: seq, + payload: vec![1, 0], + }, + ) + .await; + } + send(&mut ws, ClientMessage::Ping { client_time: 123.5 }).await; + let mut pong = None; + while mirror.ack_seq < 10 || pong.is_none() { + match next(&mut ws, &mut mirror).await.unwrap() { + ServerMessage::Pong { + client_time, + server_time, + } => pong = Some((client_time, server_time)), + ServerMessage::Delta(_) | ServerMessage::Event { .. } => {} + other => panic!("unexpected {other:?}"), + } + } + assert_eq!(pong.unwrap().0, 123.5); + // Let the next patch carry the moved position. + for _ in 0..3 { + next(&mut ws, &mut mirror).await.unwrap(); + } + let FieldValue::F(x) = mirror.entities[&avatar_id].fields[0] else { + panic!() + }; + assert!( + x > start_x, + "server-side movement replicated ({start_x} -> {x})" + ); + + // Text frames are refused. + ws.send(Message::Text("hi".into())).await.unwrap(); + match next(&mut ws, &mut mirror).await { + Some(ServerMessage::Error { code, .. }) => assert_eq!(code, error::BAD_MESSAGE), + other => panic!("expected BAD_MESSAGE, got {other:?}"), + } + drop(ws); // abrupt drop: player stays for the grace window + + // Reconnect with the token from Welcome. + let mut ws = connect(&url, "z1").await; + hello(&mut ws, String::new(), welcome.reconnect_token.clone()).await; + let mut mirror = ClientMirror::new(); + let Some(ServerMessage::Welcome(again)) = next(&mut ws, &mut mirror).await else { + panic!("expected Welcome on reconnect") + }; + assert_eq!(again.session_id, welcome.session_id); + assert_ne!(again.reconnect_token, welcome.reconnect_token); + while !mirror.entities.contains_key(&avatar_id) { + next(&mut ws, &mut mirror).await.unwrap(); + } + + // Admission failures. + expect_error( + &url, + "z1", + ticket("bob", "z1", "n1", Role::Player), + error::UNAUTHORIZED, + ) + .await; + expect_error( + &url, + "z1", + ticket("bob", "z2", "n2", Role::Player), + error::UNAUTHORIZED, + ) + .await; + expect_error( + &url, + "nope", + ticket("bob", "nope", "n3", Role::Player), + error::NOT_FOUND, + ) + .await; + let forged = TicketKey::new("wrong").sign(&TicketClaims { + principal: "bob".into(), + zone: "z1".into(), + expires_at: 4_000_000_000, + nonce: "n4".into(), + role: Role::Player, + name: None, + extensions: Default::default(), + wake: false, + }); + expect_error(&url, "z1", forged, error::UNAUTHORIZED).await; + + // Observers see the world without a player. + let mut obs = connect(&url, "z1").await; + hello( + &mut obs, + ticket("watcher", "z1", "n5", Role::Observer), + String::new(), + ) + .await; + let mut obs_mirror = ClientMirror::new(); + let Some(ServerMessage::Welcome(w)) = next(&mut obs, &mut obs_mirror).await else { + panic!() + }; + assert_eq!(w.role, Role::Observer); + while obs_mirror.entities.is_empty() { + next(&mut obs, &mut obs_mirror).await.unwrap(); + } + + // Graceful shutdown kicks everyone. + server.shutdown(); + let mut kicked = false; + while let Some(msg) = next(&mut ws, &mut mirror).await { + if let ServerMessage::Kick { code, .. } = msg { + assert_eq!(code, kick::SHUTDOWN); + kicked = true; + } + } + assert!(kicked); + tokio::time::timeout(Duration::from_secs(5), handle) + .await + .expect("server stops") + .unwrap(); +} + +/// Tickets minted in JavaScript by `@hops-ops/distributed/sveltekit/game/server` +/// (`mintGameTicket`, reproduced byte for byte by `js/tests/sveltekit-game.test.mjs`). +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn admits_tickets_minted_by_the_sveltekit_handler() { + let fixture: serde_json::Value = + serde_json::from_str(include_str!("../fixtures/sveltekit_tickets.json")).unwrap(); + let text = |path: &str| { + fixture + .pointer(path) + .and_then(serde_json::Value::as_str) + .unwrap_or_else(|| panic!("fixture {path}")) + .to_string() + }; + let secret = text("/secret"); + let zone = text("/zone"); + + // The same key verifies the claims exactly. + let claims = TicketKey::new(secret.as_str()) + .verify(&text("/valid/ticket"), 1_700_000_000) + .unwrap(); + assert_eq!(claims.principal, text("/valid/principal")); + assert_eq!(claims.zone, zone); + assert_eq!(claims.expires_at, 4_000_000_000); + assert_eq!(claims.nonce, text("/valid/nonce")); + assert_eq!(claims.role, Role::Player); + assert_eq!(claims.name.as_deref(), Some("Ana")); + assert!(claims.extensions.is_empty()); + + // Extension claims from the handler's server-side `claims()` callback. + let extended = TicketKey::new(secret.as_str()) + .verify(&text("/extended/ticket"), 1_700_000_000) + .unwrap(); + assert_eq!(extended.principal, text("/extended/principal")); + assert_eq!( + extended.extensions.typed::().unwrap(), + MatchClaims { + match_id: "m-7".into(), + side: 2, + party: None, + } + ); + + let (url, server, handle) = start_keyed(&secret, None).await; + + // A real GameServer admits the JS-minted player ticket ... + let mut ws = connect(&url, &zone).await; + hello(&mut ws, text("/valid/ticket"), String::new()).await; + let mut mirror = ClientMirror::new(); + let Some(ServerMessage::Welcome(welcome)) = next(&mut ws, &mut mirror).await else { + panic!("expected Welcome for the JS-minted ticket") + }; + assert_eq!(welcome.zone_id, zone); + assert_eq!(welcome.role, Role::Player); + let players = server + .inspect(&zone, |host| host.players().cloned().collect::>()) + .await + .expect("zone active"); + let player = players + .iter() + .find(|p| p.principal == text("/valid/principal")) + .expect("the principal comes from the JS-minted ticket"); + assert_eq!(player.name.as_deref(), Some("Ana")); + + // ... and the observer ticket. + let mut obs = connect(&url, &zone).await; + hello(&mut obs, text("/observer/ticket"), String::new()).await; + let Some(ServerMessage::Welcome(w)) = next(&mut obs, &mut ClientMirror::new()).await else { + panic!("expected Welcome for the JS-minted observer ticket") + }; + assert_eq!(w.role, Role::Observer); + + // Single use, signature, expiry and zone binding are enforced. + for (what, ticket) in [ + ("replayed", text("/valid/ticket")), + ("tampered", text("/tampered")), + ("expired", text("/expired")), + ("wrong zone", text("/wrongZone")), + ("other key", text("/otherKey")), + ] { + let mut ws = connect(&url, &zone).await; + hello(&mut ws, ticket, String::new()).await; + match next(&mut ws, &mut ClientMirror::new()).await { + Some(ServerMessage::Error { code, .. }) => { + assert_eq!(code, error::UNAUTHORIZED, "{what}") + } + other => panic!("{what}: expected UNAUTHORIZED, got {other:?}"), + } + } + + server.shutdown(); + tokio::time::timeout(Duration::from_secs(5), handle) + .await + .expect("server stops") + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn latency_simulation_delays_but_preserves_order() { + let sim = NetSim { + latency: Duration::from_millis(40), + jitter: Duration::from_millis(20), + ..NetSim::default() + }; + let (url, server, handle) = start(Some(sim)).await; + let mut ws = connect(&url, "z9").await; + hello( + &mut ws, + ticket("carol", "z9", "m1", Role::Player), + String::new(), + ) + .await; + let mut mirror = ClientMirror::new(); + assert!(matches!( + next(&mut ws, &mut mirror).await, + Some(ServerMessage::Welcome(_)) + )); + let start = std::time::Instant::now(); + send(&mut ws, ClientMessage::Ping { client_time: 1.0 }).await; + let mut last_tick = 0; + loop { + match next(&mut ws, &mut mirror).await.unwrap() { + ServerMessage::Pong { .. } => break, + ServerMessage::Delta(d) => { + assert!(d.server_tick >= last_tick, "ordered"); + last_tick = d.server_tick; + } + _ => {} + } + } + assert!( + start.elapsed() >= Duration::from_millis(80), + "two one-way delays" + ); + server.shutdown(); + let _ = tokio::time::timeout(Duration::from_secs(5), handle).await; +} + +/// Raw HTTP/1.1 GET returning the whole response text. +async fn http_get(addr: std::net::SocketAddr, path: &str) -> String { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let mut stream = TcpStream::connect(addr).await.unwrap(); + let request = format!("GET {path} HTTP/1.1\r\nHost: test\r\nConnection: close\r\n\r\n"); + stream.write_all(request.as_bytes()).await.unwrap(); + let mut response = String::new(); + stream.read_to_string(&mut response).await.unwrap(); + response +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn serve_with_merges_extra_routes_and_shuts_down_gracefully() { + let mut config = ServerConfig::new(TicketKey::new(SECRET)); + config.host.tick_rate = 30; + let server = GameServer::::new( + config, + ZoneFactory::sync(|a| a.zone_id.starts_with('z').then(ArenaConfig::default)), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let extra = axum::Router::new().route("/hello", axum::routing::get(|| async { "hi" })); + let (stop, stopped) = tokio::sync::oneshot::channel::<()>(); + let handle = tokio::spawn(server.clone().serve_with(listener, extra, async move { + let _ = stopped.await; + })); + let hello = http_get(addr, "/hello").await; + assert!( + hello.starts_with("HTTP/1.1 200") && hello.ends_with("hi"), + "{hello}" + ); + assert!(http_get(addr, "/metrics").await.starts_with("HTTP/1.1 200")); + + // A joined player is kicked with SHUTDOWN when the signal fires. + let url = format!("ws://{addr}"); + let mut ws = connect(&url, "z1").await; + hello_join(&mut ws, "z1").await; + let mut mirror = ClientMirror::new(); + assert!(matches!( + next(&mut ws, &mut mirror).await, + Some(ServerMessage::Welcome(_)) + )); + stop.send(()).unwrap(); + let mut kicked = false; + while let Some(msg) = next(&mut ws, &mut mirror).await { + if let ServerMessage::Kick { code, .. } = msg { + assert_eq!(code, kick::SHUTDOWN); + kicked = true; + } + } + assert!(kicked, "shutdown kick delivered"); + tokio::time::timeout(Duration::from_secs(5), handle) + .await + .expect("serve_with returns after shutdown") + .unwrap() + .unwrap(); +} + +async fn hello_join(ws: &mut Ws, zone: &str) { + hello( + ws, + ticket("serve-with", zone, "n-serve-with", Role::Player), + String::new(), + ) + .await; +} + +// ---- Custom ticket verifier: a web BFF's own HS256 JWTs ---- + +const BFF_SECRET: &[u8] = b"bff-secret"; + +/// The downstream game's web-BFF ticket: HS256, `iss` +/// `dungeon-crawler-web`, `aud` `dungeon-crawler-zone`, `sub` +/// `human_`, `principal`, `name`, `jti`, `exp` at most 120 s out, +/// optional `zoneRoute`; no `zone` / `nonce` claims. +fn bff_verifier( + token: &str, + zone: &str, + now: u64, +) -> Result { + use distributed_game::net::{decode_hs256, TicketError}; + let claims = decode_hs256(token, BFF_SECRET)?; + let text = |name: &'static str| { + claims + .get(name) + .and_then(|v| v.as_str()) + .filter(|v| !v.is_empty()) + .ok_or(TicketError::MissingClaim(name)) + }; + if text("iss")? != "dungeon-crawler-web" || text("aud")? != "dungeon-crawler-zone" { + return Err(TicketError::Invalid("issuer/audience".into())); + } + let sub = text("sub")?; + let hex = sub + .strip_prefix("human_") + .filter(|h| !h.is_empty() && h.chars().all(|c| c.is_ascii_hexdigit())) + .ok_or(TicketError::Invalid("sub".into()))?; + if text("principal")? != sub { + return Err(TicketError::Invalid("principal".into())); + } + let exp = claims + .get("exp") + .and_then(|v| v.as_u64()) + .ok_or(TicketError::MissingClaim("exp"))?; + if exp > now + 120 { + return Err(TicketError::Invalid("lifetime over 120s".into())); + } + if let Some(route) = claims.get("zoneRoute").and_then(|v| v.as_str()) { + if route != zone { + return Err(TicketError::WrongZone); + } + } + let mut verified = TicketClaims::new( + format!("human_{hex}"), + zone, + exp, + text("jti")?, + Role::Player, + ); + verified.name = claims + .get("name") + .and_then(|v| v.as_str()) + .map(str::to_string); + Ok(verified) +} + +fn bff_ticket(jti: &str, exp_in: u64, zone_route: Option<&str>) -> String { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(); + let mut claims = serde_json::json!({ + "iss": "dungeon-crawler-web", "aud": "dungeon-crawler-zone", + "sub": "human_0a1b2c", "principal": "human_0a1b2c", "name": "Ana", + "jti": jti, "exp": now + exp_in, + }); + if let Some(route) = zone_route { + claims["zoneRoute"] = route.into(); + } + TicketKey::new(BFF_SECRET).sign_json(&claims) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn custom_verifier_admits_web_bff_tickets_with_replay_protection() { + let mut config = ServerConfig::new(TicketKey::new(SECRET)); + config.admission = config.admission.with_ticket_verifier(bff_verifier); + let server = GameServer::::new( + config, + ZoneFactory::sync(|a| a.zone_id.starts_with('z').then(ArenaConfig::default)), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}", listener.local_addr().unwrap()); + let serving = server.clone(); + let handle = tokio::spawn(async move { + serving + .serve(listener, std::future::pending()) + .await + .unwrap(); + }); + + let mut ws = connect(&url, "z1").await; + hello(&mut ws, bff_ticket("jti-1", 60, Some("z1")), String::new()).await; + let mut mirror = ClientMirror::new(); + let Some(ServerMessage::Welcome(welcome)) = next(&mut ws, &mut mirror).await else { + panic!("expected Welcome") + }; + assert_eq!(welcome.zone_id, "z1"); + let players = server + .inspect("z1", |host| { + host.players() + .map(|p| (p.principal.clone(), p.name.clone())) + .collect::>() + }) + .await + .unwrap(); + assert_eq!( + players, + vec![("human_0a1b2c".to_string(), Some("Ana".to_string()))] + ); + + // Replay of the same jti, wrong route, overlong lifetime, built-in + // tickets (the custom verifier replaces them) and a forged signature. + expect_error( + &url, + "z1", + bff_ticket("jti-1", 60, Some("z1")), + error::UNAUTHORIZED, + ) + .await; + expect_error( + &url, + "z2", + bff_ticket("jti-2", 60, Some("z1")), + error::UNAUTHORIZED, + ) + .await; + expect_error( + &url, + "z1", + bff_ticket("jti-3", 600, None), + error::UNAUTHORIZED, + ) + .await; + expect_error( + &url, + "z1", + ticket("bob", "z1", "n-bob", Role::Player), + error::UNAUTHORIZED, + ) + .await; + let forged = TicketKey::new("nope").sign_json(&serde_json::json!({"sub": "human_ff"})); + expect_error(&url, "z1", forged, error::UNAUTHORIZED).await; + // No zoneRoute: admitted to the zone the client asked for. + let mut ws2 = connect(&url, "z2").await; + hello(&mut ws2, bff_ticket("jti-4", 60, None), String::new()).await; + let mut mirror2 = ClientMirror::new(); + assert!(matches!( + next(&mut ws2, &mut mirror2).await, + Some(ServerMessage::Welcome(_)) + )); + + server.shutdown(); + handle.await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn host_config_hook_sets_per_zone_rates() { + let mut config = ServerConfig::new(TicketKey::new(SECRET)); + config.host.tick_rate = 30; + config.host.content_version = "c1".into(); + let server = GameServer::::new( + config, + ZoneFactory::sync(|a| a.zone_id.starts_with('z').then(ArenaConfig::default)), + ) + .with_host_config(|zone_id, host| { + if zone_id == "z-slow" { + host.tick_rate = 5; + host.patch_rate = 2; + host.content_version = "ignored".into(); + } + }); + assert!(server.activate("z-slow").await); + assert!(server.activate("z-hot").await); + let slow = server + .inspect("z-slow", |h| { + ( + h.config().tick_rate, + h.config().patch_rate, + h.config().content_version.clone(), + ) + }) + .await; + assert_eq!(slow, Some((5, 2, "c1".to_string())), "world version wins"); + let hot = server.inspect("z-hot", |h| h.config().tick_rate).await; + assert_eq!(hot, Some(30)); + server.shutdown(); +} + +/// A game's declared extension claims. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TicketExtension)] +struct MatchClaims { + match_id: String, + #[serde(rename = "team")] + side: u8, + #[serde(default)] + party: Option, +} + +fn extended_ticket(nonce: &str, ext: serde_json::Value) -> String { + TicketKey::new(SECRET).sign(&TicketClaims { + principal: "ana".into(), + zone: "z-match".into(), + expires_at: 4_000_000_000, + nonce: nonce.into(), + role: Role::Player, + name: None, + extensions: TicketExtensions::from_json(ext).unwrap(), + wake: false, + }) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn extension_claims_reach_on_auth_and_player_info() { + assert_eq!(MatchClaims::CLAIMS, ["match_id", "team", "party"]); + let mut config = ServerConfig::new(TicketKey::new(SECRET)); + config.admission = config.admission.with_ticket_extensions::(); + let server = + GameServer::::new(config, ZoneFactory::sync(|_| Some(ArenaConfig::default()))); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}", listener.local_addr().unwrap()); + let serving = server.clone(); + let handle = tokio::spawn(async move { + serving + .serve(listener, std::future::pending()) + .await + .unwrap(); + }); + + // Undeclared names and mistyped values are refused at admission. + for (nonce, ext) in [ + ( + "x-unknown", + serde_json::json!({"match_id": "m-7", "team": 2, "gold": 50}), + ), + ( + "x-typed", + serde_json::json!({"match_id": "m-7", "team": "red"}), + ), + ("x-object", serde_json::json!(["m-7"])), + ] { + let ticket = if nonce == "x-object" { + TicketKey::new(SECRET).sign_json(&serde_json::json!({ + "sub": "ana", "zone": "z-match", "exp": 4_000_000_000u64, + "nonce": nonce, "ext": ext, + })) + } else { + extended_ticket(nonce, ext) + }; + expect_error(&url, "z-match", ticket, error::UNAUTHORIZED).await; + } + + let expected = MatchClaims { + match_id: "m-7".into(), + side: 2, + party: None, + }; + let mut ws = connect(&url, "z-match").await; + hello( + &mut ws, + extended_ticket("ok", serde_json::json!({"match_id": "m-7", "team": 2})), + String::new(), + ) + .await; + let Some(ServerMessage::Welcome(_)) = next(&mut ws, &mut ClientMirror::new()).await else { + panic!("expected Welcome") + }; + let (auth, players) = server + .inspect("z-match", |host| { + ( + host.zone().auth_extensions.clone(), + host.players().cloned().collect::>(), + ) + }) + .await + .expect("zone active"); + assert_eq!( + auth.last().unwrap().typed::().unwrap(), + expected + ); + assert_eq!( + players[0].extensions.typed::().unwrap(), + expected + ); + + server.shutdown(); + tokio::time::timeout(Duration::from_secs(5), handle) + .await + .expect("server stops") + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn extension_claims_are_refused_without_a_declared_schema() { + let (url, server, handle) = start(None).await; + let ticket = TicketKey::new(SECRET).sign(&TicketClaims { + principal: "ana".into(), + zone: "z1".into(), + expires_at: 4_000_000_000, + nonce: "undeclared".into(), + role: Role::Player, + name: None, + extensions: TicketExtensions::from_json(serde_json::json!({"match_id": "m"})).unwrap(), + wake: false, + }); + expect_error(&url, "z1", ticket, error::UNAUTHORIZED).await; + server.shutdown(); + tokio::time::timeout(Duration::from_secs(5), handle) + .await + .expect("server stops") + .unwrap(); +} + +async fn serve_arena(server: &GameServer) -> (String, tokio::task::JoinHandle<()>) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}", listener.local_addr().unwrap()); + let serving = server.clone(); + let handle = tokio::spawn(async move { + serving + .serve(listener, std::future::pending()) + .await + .unwrap(); + }); + (url, handle) +} + +async fn stop(server: GameServer, handle: tokio::task::JoinHandle<()>) { + server.shutdown(); + tokio::time::timeout(Duration::from_secs(5), handle) + .await + .expect("server stops") + .unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn async_factory_reads_the_allocation_before_admitting_queued_joins() { + use distributed_game::world::{MemoryZoneAllocationStore, ZoneAllocation, ZoneAllocationStore}; + use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + use std::sync::Arc; + + let store = Arc::new(MemoryZoneAllocationStore::new()); + let roster = serde_json::json!({ "mode": "duel", "roster": ["ana", "bo"] }); + store + .put( + "z-match", + ZoneAllocation::new("game-services.match", 1, &roster).unwrap(), + ) + .await + .unwrap(); + let created = Arc::new(AtomicBool::new(false)); + let calls = Arc::new(AtomicU32::new(0)); + let (done, calls_in) = (created.clone(), calls.clone()); + let server = GameServer::::new( + ServerConfig::new(TicketKey::new(SECRET)), + ZoneFactory::new(move |activation| { + let (done, calls) = (done.clone(), calls_in.clone()); + async move { + calls.fetch_add(1, Ordering::SeqCst); + assert!(activation.activation > 0, "the fencing token"); + // Storage is slow: both joins arrive while this awaits. + tokio::time::sleep(Duration::from_millis(200)).await; + done.store(true, Ordering::SeqCst); + Ok(Some(ArenaConfig { + allocation: activation.allocation.map(|a| a.payload), + ..ArenaConfig::default() + })) + } + }), + ) + .with_allocation_store(store); + let (url, handle) = serve_arena(&server).await; + + let join = |principal: &'static str, nonce: &'static str| { + let url = url.clone(); + let created = created.clone(); + async move { + let mut ws = connect(&url, "z-match").await; + hello( + &mut ws, + ticket(principal, "z-match", nonce, Role::Player), + String::new(), + ) + .await; + let msg = next(&mut ws, &mut ClientMirror::new()).await; + assert!( + created.load(Ordering::SeqCst), + "admitted only after the factory finished" + ); + matches!(msg, Some(ServerMessage::Welcome(_))) + } + }; + let (ana, bo) = tokio::join!(join("ana", "q1"), join("bo", "q2")); + assert!(ana && bo, "both queued joins admitted"); + assert_eq!(calls.load(Ordering::SeqCst), 1, "one activation"); + let allocation = server + .inspect("z-match", |host| host.zone().cfg.allocation.clone()) + .await + .unwrap(); + assert_eq!(allocation, Some(roster), "the allocation reached on_create"); + stop(server, handle).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn factory_failures_answer_joins_with_typed_errors() { + use distributed_game::world::{ + AllocationError, BoxFuture, ZoneAllocation, ZoneAllocationStore, ZoneCreateError, + }; + use std::sync::Arc; + + struct DownStore; + impl ZoneAllocationStore for DownStore { + fn load<'a>( + &'a self, + _: &'a str, + ) -> BoxFuture<'a, Result, AllocationError>> { + Box::pin(async { Err(AllocationError("connection refused".into())) }) + } + fn put<'a>( + &'a self, + _: &'a str, + _: ZoneAllocation, + ) -> BoxFuture<'a, Result<(), AllocationError>> { + Box::pin(async { Ok(()) }) + } + fn remove<'a>(&'a self, _: &'a str) -> BoxFuture<'a, Result<(), AllocationError>> { + Box::pin(async { Ok(()) }) + } + } + + let mut config = ServerConfig::new(TicketKey::new(SECRET)); + config.activation_timeout = Duration::from_millis(300); + let server = GameServer::::new( + config, + ZoneFactory::new(|activation| async move { + match activation.zone_id.as_str() { + "z-broken" => Err(ZoneCreateError::new("roster store unavailable")), + "z-hang" => std::future::pending().await, + "z-ok" => Ok(Some(ArenaConfig::default())), + _ => Ok(None), + } + }), + ); + let (url, handle) = serve_arena(&server).await; + let started = std::time::Instant::now(); + for (zone, code, nonce) in [ + ("z-broken", error::ZONE_UNAVAILABLE, "f1"), + ("z-hang", error::ZONE_UNAVAILABLE, "f2"), + ("z-unknown", error::NOT_FOUND, "f3"), + ] { + expect_error(&url, zone, ticket("ana", zone, nonce, Role::Player), code).await; + assert!(!server.is_active(zone), "{zone} unregistered"); + } + assert!(started.elapsed() < Duration::from_secs(3), "no hang"); + assert!(!server.activate("z-broken").await); + assert!(server.activate("z-ok").await); + stop(server, handle).await; + + // An allocation store failure refuses too, without calling the factory. + let server = GameServer::::new( + ServerConfig::new(TicketKey::new(SECRET)), + ZoneFactory::new(|_| async { panic!("factory must not run without its allocation") }), + ) + .with_allocation_store(Arc::new(DownStore)); + let (url, handle) = serve_arena(&server).await; + expect_error( + &url, + "z-match", + ticket("ana", "z-match", "f4", Role::Player), + error::ZONE_UNAVAILABLE, + ) + .await; + stop(server, handle).await; +} + +/// Hello offering `version` with a fresh ticket. +async fn hello_version(ws: &mut Ws, version: u32, ticket: String) { + send( + ws, + ClientMessage::Hello(Hello { + protocol_version: version, + content_version: String::new(), + capabilities: 0, + ticket, + reconnect_token: String::new(), + near: false, + }), + ) + .await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn refuses_any_other_protocol_version() { + use distributed_game::protocol::feature; + let (url, server, handle) = start(None).await; + + let mut ws2 = connect(&url, "z1").await; + hello_version( + &mut ws2, + PROTOCOL_VERSION, + ticket("bo", "z1", "v-2", Role::Observer), + ) + .await; + let Some(ServerMessage::Welcome(w)) = next(&mut ws2, &mut ClientMirror::new()).await else { + panic!("Welcome") + }; + assert_eq!(w.features & feature::FOCUS, feature::FOCUS); + + // A version the server does not speak is refused before the ticket is + // used (message starting `protocol`): the same ticket then joins. + let mut ws3 = connect(&url, "z1").await; + let same = ticket("cy", "z1", "v-3", Role::Player); + hello_version(&mut ws3, PROTOCOL_VERSION - 1, same.clone()).await; + match next(&mut ws3, &mut ClientMirror::new()).await { + Some(ServerMessage::Error { code, message }) => { + assert_eq!(code, error::VERSION_MISMATCH); + assert!(message.starts_with("protocol"), "{message}"); + } + other => panic!("expected VERSION_MISMATCH, got {other:?}"), + } + let mut ws4 = connect(&url, "z1").await; + hello_version(&mut ws4, PROTOCOL_VERSION, same).await; + assert!(matches!( + next(&mut ws4, &mut ClientMirror::new()).await, + Some(ServerMessage::Welcome(_)) + )); + drop((ws2, ws3, ws4)); + stop(server, handle).await; +} + +/// Ownership that records every acquisition (a lease per entry). +#[derive(Default)] +struct CountingOwnership { + inner: distributed_game::world::LocalOwnership, + acquired: std::sync::Mutex>, +} + +impl distributed_game::world::ZoneOwnership for CountingOwnership { + fn acquire<'a>( + &'a self, + zone_id: &'a str, + holder: &'a str, + ttl: Duration, + ) -> distributed_game::BoxFuture< + 'a, + Result, + > { + self.acquired.lock().unwrap().push(zone_id.to_string()); + self.inner.acquire(zone_id, holder, ttl) + } + + fn renew<'a>( + &'a self, + claim: &'a distributed_game::world::ZoneClaim, + ttl: Duration, + ) -> distributed_game::BoxFuture< + 'a, + Result, + > { + self.inner.renew(claim, ttl) + } + + fn release<'a>( + &'a self, + claim: &'a distributed_game::world::ZoneClaim, + ) -> distributed_game::BoxFuture<'a, ()> { + self.inner.release(claim) + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn unauthenticated_hellos_activate_nothing() { + use std::sync::atomic::{AtomicU32, Ordering}; + use std::sync::Arc; + + let ownership = Arc::new(CountingOwnership::default()); + let created = Arc::new(AtomicU32::new(0)); + let counted = created.clone(); + let server = GameServer::::new( + ServerConfig::new(TicketKey::new(SECRET)), + ZoneFactory::sync(move |a| { + counted.fetch_add(1, Ordering::SeqCst); + a.zone_id.starts_with('z').then(ArenaConfig::default) + }), + ) + .with_fact_sink(MemoryFactSink::new(), 64, RetryPolicy::default()) + .with_ownership(ownership.clone()); + let (url, handle) = serve_arena(&server).await; + + let expired = TicketKey::new(SECRET).sign(&TicketClaims { + expires_at: 1, + ..claims_for("ana", "zg3", "g3") + }); + let forged = TicketKey::new("not-the-server-key").sign(&claims_for("ana", "zg2", "g2")); + for (zone, ticket) in [ + ("zg1", "garbage".to_string()), + ("zg2", forged), + ("zg3", expired), + ("zg4", ticket("ana", "zg9", "g4", Role::Player)), + ] { + expect_error(&url, zone, ticket, error::UNAUTHORIZED).await; + } + // A reconnect token never activates a zone either. + let mut ws = connect(&url, "zg5").await; + hello(&mut ws, String::new(), "forged-token".into()).await; + match next(&mut ws, &mut ClientMirror::new()).await { + Some(ServerMessage::Error { code, .. }) => assert_eq!(code, error::RECONNECT_FAILED), + other => panic!("expected RECONNECT_FAILED, got {other:?}"), + } + assert!(server.zone_ids().is_empty(), "{:?}", server.zone_ids()); + + // A real join afterwards: the only zone, lease and factory call. + let mut ws = connect(&url, "zok").await; + hello( + &mut ws, + ticket("ana", "zok", "ok1", Role::Player), + String::new(), + ) + .await; + assert!(matches!( + next(&mut ws, &mut ClientMirror::new()).await, + Some(ServerMessage::Welcome(_)) + )); + assert_eq!(server.zone_ids(), ["zok"]); + assert_eq!(*ownership.acquired.lock().unwrap(), ["zok"]); + assert_eq!(created.load(Ordering::SeqCst), 1); + stop(server, handle).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn max_zones_caps_activations() { + let mut config = ServerConfig::new(TicketKey::new(SECRET)); + config.max_zones = 1; + let server = GameServer::::new( + config, + ZoneFactory::sync(|a| a.zone_id.starts_with('z').then(ArenaConfig::default)), + ); + let (url, handle) = serve_arena(&server).await; + let mut ws = connect(&url, "z1").await; + hello( + &mut ws, + ticket("ana", "z1", "m1", Role::Player), + String::new(), + ) + .await; + assert!(matches!( + next(&mut ws, &mut ClientMirror::new()).await, + Some(ServerMessage::Welcome(_)) + )); + expect_error( + &url, + "z2", + ticket("bo", "z2", "m2", Role::Player), + error::ZONE_UNAVAILABLE, + ) + .await; + assert_eq!(server.zone_ids(), ["z1"]); + assert!( + !server.activate("z3").await, + "the cap applies to activate too" + ); + // The running zone still admits. + let mut ws2 = connect(&url, "z1").await; + hello( + &mut ws2, + ticket("bo", "z1", "m3", Role::Player), + String::new(), + ) + .await; + assert!(matches!( + next(&mut ws2, &mut ClientMirror::new()).await, + Some(ServerMessage::Welcome(_)) + )); + stop(server, handle).await; +} + +fn claims_for(principal: &str, zone: &str, nonce: &str) -> TicketClaims { + TicketClaims { + principal: principal.into(), + zone: zone.into(), + expires_at: 4_000_000_000, + nonce: nonce.into(), + role: Role::Player, + name: None, + extensions: Default::default(), + wake: false, + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn passes_the_admission_conformance_suite() { + let hello_timeout = Duration::from_millis(500); + let mut config = ServerConfig::new(TicketKey::new(SECRET)); + config.admission.hello_timeout = hello_timeout; + let server = GameServer::::new( + config, + ZoneFactory::sync(|a| a.zone_id.starts_with("room-").then(ArenaConfig::default)), + ); + let (url, handle) = serve_arena(&server).await; + let probe = server.clone(); + admission::run(admission::Target { + base: url, + key: TicketKey::new(SECRET), + hello_timeout, + awake: move |zone: String| { + let probe = probe.clone(); + async move { probe.is_active(&zone) } + }, + }) + .await; + stop(server, handle).await; +} + +/// Commands queued faster than the zone handles them (each handler here +/// takes 1 ms, as an expensive game hook might) never hold a due tick +/// back for more than a bounded batch. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_command_flood_never_holds_ticks_back() { + use std::sync::{Arc, Mutex}; + let mut config = ServerConfig::new(TicketKey::new(SECRET)); + config.host.idle_tick_rate = Some(30); + let server = + GameServer::::new(config, ZoneFactory::sync(|_| Some(ArenaConfig::default()))); + assert!(server.activate("zflood").await); + let seen = Arc::new(Mutex::new(Vec::new())); + let flood: Vec<_> = (0..400) + .map(|_| { + let (server, seen) = (server.clone(), seen.clone()); + tokio::spawn(async move { + server + .inspect("zflood", move |host| { + std::thread::sleep(Duration::from_millis(1)); + seen.lock().unwrap().push(host.tick()); + }) + .await + }) + }) + .collect(); + for task in flood { + task.await.unwrap().expect("handled"); + } + let seen = seen.lock().unwrap().clone(); + let longest = seen + .chunk_by(|a, b| a == b) + .map(<[u64]>::len) + .max() + .unwrap(); + // 64 handlers (64 ms) then a look at the clock: a 33 ms tick is due. + assert!(longest <= 64, "{longest} commands without a tick: {seen:?}"); + assert!(seen.last() > seen.first(), "ticks advanced: {seen:?}"); + server.shutdown(); +} + +/// A session on the native driver with recording on: two players join over +/// WebSockets, move, one drops and reconnects with its token, the other is +/// kicked through the service inbox; facts (heartbeats and lifecycle) commit +/// through the real worker. Replaying the recording reproduces every join +/// and input outcome, every per-tick hash, the final state and the facts +/// the sink committed, byte for byte. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn native_session_records_and_replays_identically() { + use distributed_game::inbox::ZoneInbound; + use distributed_game::replay::{replay_with, Recording}; + + let arena = || ArenaConfig { + fact_every_tick: true, + spawn_every: Some(Duration::from_millis(100)), + ..ArenaConfig::default() + }; + let mut config = ServerConfig::new(TicketKey::new(SECRET)); + config.host.record = true; + config.host.lifecycle_facts = true; + let sink = MemoryFactSink::new(); + let server = GameServer::::new(config, ZoneFactory::sync(move |_| Some(arena()))) + .with_fact_sink(sink.clone(), 64, RetryPolicy::default()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}", listener.local_addr().unwrap()); + let serving = server.clone(); + let handle = tokio::spawn(async move { + serving + .serve(listener, std::future::pending()) + .await + .unwrap(); + }); + + // Inputs until the server acked them all (consumed by ticks). + async fn moves(ws: &mut Ws, mirror: &mut ClientMirror, seqs: std::ops::RangeInclusive) { + let last = *seqs.end(); + for seq in seqs { + let payload = vec![(seq % 3) as u8, 1]; + let input = ClientMessage::Input { + seq, + client_tick: seq, + payload, + }; + send(ws, input).await; + } + while mirror.ack_seq < last { + next(ws, mirror).await.expect("acked"); + } + } + + let mut ana = connect(&url, "zr").await; + hello( + &mut ana, + ticket("ana", "zr", "r1", Role::Player), + String::new(), + ) + .await; + let mut ana_mirror = ClientMirror::new(); + let Some(ServerMessage::Welcome(welcome)) = next(&mut ana, &mut ana_mirror).await else { + panic!("Welcome") + }; + let mut bo = connect(&url, "zr").await; + hello( + &mut bo, + ticket("bo", "zr", "r2", Role::Player), + String::new(), + ) + .await; + let mut bo_mirror = ClientMirror::new(); + let Some(ServerMessage::Welcome(_)) = next(&mut bo, &mut bo_mirror).await else { + panic!("Welcome") + }; + moves(&mut ana, &mut ana_mirror, 1..=8).await; + moves(&mut bo, &mut bo_mirror, 1..=5).await; + drop(ana); // abrupt: reconnect grace + let mut ana = connect(&url, "zr").await; + hello(&mut ana, String::new(), welcome.reconnect_token.clone()).await; + let mut ana_mirror = ClientMirror::new(); + let Some(ServerMessage::Welcome(_)) = next(&mut ana, &mut ana_mirror).await else { + panic!("Welcome on reconnect") + }; + moves(&mut ana, &mut ana_mirror, 9..=14).await; + let kicked = server + .send( + "zr", + ZoneInbound::Kick { + principal: "bo".into(), + reason: "test".into(), + }, + ) + .await + .unwrap(); + assert_eq!(kicked.players_kicked, 1); + moves(&mut ana, &mut ana_mirror, 15..=20).await; + + // Everything applied so far is in the recording: the live state now is + // the state after its last entry. + let (recording, live_hash) = server + .inspect("zr", |h| (h.recording().cloned(), h.state_hash())) + .await + .expect("zone active"); + let recording = Recording::decode(&recording.expect("recording on").encode()).unwrap(); + let mut replayed_hash = None; + let summary = replay_with::(&recording, arena(), |h| { + replayed_hash = Some(h.state_hash()) + }) + .unwrap_or_else(|d| panic!("{d}")); + assert_eq!(replayed_hash, Some(live_hash), "final state"); + assert!(summary.ticks > 0); + + // The facts the replay emitted are exactly those the sink committed + // (it commits each one, later: wait for the last of them). + assert!(summary.facts.iter().any(|f| f.principal() == Some("ana"))); + assert!(summary.facts.iter().any(|f| f.principal().is_none())); + let mut committed = Vec::new(); + for _ in 0..500 { + committed = sink.committed(); + if summary + .facts + .iter() + .all(|f| committed.iter().any(|c| c.key() == f.key())) + { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + for fact in &summary.facts { + let live = committed.iter().find(|c| c.key() == fact.key()); + assert_eq!(live, Some(fact), "fact {}", fact.key()); + } + drop(ana); + stop(server, handle).await; +} diff --git a/distributed_game/tests/netcode/main.rs b/distributed_game/tests/netcode/main.rs new file mode 100644 index 000000000..091ef891c --- /dev/null +++ b/distributed_game/tests/netcode/main.rs @@ -0,0 +1,363 @@ +//! P8 netcode: lag compensation through `Ctx::rewind`, and deterministic +//! record/replay with divergence detection. + +#[path = "../support/arena.rs"] +mod arena; + +use std::sync::Arc; +use std::time::Duration; + +use arena::{Arena, ArenaConfig}; +use distributed_game::replay::{replay, DivergenceKind, JoinResult, Observed, Recording}; +use distributed_game::rewind::{Historic, HitQuery, RewindConfig, RewindFrame, ShotTiming}; +use distributed_game::{ + fact_channel, spawn_fact_worker, ClientMirror, ConsumePolicy, Ctx, EntitySchema, EntityState, + FieldType, FieldValue, HostConfig, KindDef, ManualClock, MemoryFactSink, Outbound, PlayerId, + RetryPolicy, Role, ServerMessage, Stimulus, TicketClaims, WorldView, Zone, ZoneHost, ZoneRng, +}; + +fn claims(principal: &str, zone: &str) -> TicketClaims { + TicketClaims { + principal: principal.into(), + zone: zone.into(), + expires_at: u64::MAX, + nonce: format!("n-{principal}"), + role: Role::Player, + name: None, + extensions: Default::default(), + wake: false, + } +} + +// ---------------------------------------------------------------- rewind + +const TARGET: u32 = 100; +const SPEED: f32 = 10.0; + +#[derive(Debug, Clone, PartialEq)] +struct ShotResult { + rewound: Option, + present: Option, + clamped: bool, + age: Duration, +} + +/// A target crosses the map along y = 10 at 10 u/s; players shoot straight +/// up (+y) from (aim_x, 0) and report their interpolation delay in the +/// payload: `aim_x: f32 LE ‖ interp_ms: u16 LE`. +struct Range { + target_x: f32, + shots: Vec, +} + +impl Zone for Range { + type Config = (); + type Input = (f32, u16); + type Timer = (); + type Message = distributed_game::NoMessages; + + fn schema() -> EntitySchema { + EntitySchema::new().kind(KindDef::new(1, "target").field("x", FieldType::F32)) + } + + fn on_create(_ctx: &mut Ctx<'_, Self>, _: ()) -> Self { + Range { + target_x: 0.0, + shots: Vec::new(), + } + } + + fn decode_input(&self, _p: PlayerId, b: &[u8]) -> Option<(f32, u16)> { + let b: &[u8; 6] = b.try_into().ok()?; + Some(( + f32::from_le_bytes([b[0], b[1], b[2], b[3]]), + u16::from_le_bytes([b[4], b[5]]), + )) + } + + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + let players: Vec<_> = ctx.players().map(|p| p.id).collect(); + for p in players { + for input in ctx.take_inputs(p, ConsumePolicy::Drain) { + let (aim_x, interp_ms) = input.input; + let timing = ShotTiming { + client_tick: input.client_tick, + interp_delay: Duration::from_millis(u64::from(interp_ms)), + }; + let ray = HitQuery::ray([aim_x, 0.0, 0.0], [0.0, 1.0, 0.0], 50.0); + let rewind = ctx.rewind(); + let resolved = rewind.resolve(timing).expect("history"); + let present = rewind.latest().unwrap().time(); + self.shots.push(ShotResult { + rewound: rewind.hit_test(resolved.time, &ray, |_| true).map(|h| h.id), + present: rewind.hit_test(present, &ray, |_| true).map(|h| h.id), + clamped: resolved.clamped, + age: resolved.age, + }); + } + } + self.target_x += SPEED * ctx.dt_secs(); + } + + fn record_rewind(&self, frame: &mut RewindFrame) { + frame.push(Historic::sphere(TARGET, [self.target_x, 10.0, 0.0], 0.5)); + } + + fn replicate(&self, out: &mut WorldView) { + out.push(EntityState::new( + TARGET, + 1, + self.target_x, + 10.0, + vec![FieldValue::F(self.target_x)], + )); + } +} + +fn shot(aim_x: f32, interp_ms: u16) -> Vec { + let mut b = aim_x.to_le_bytes().to_vec(); + b.extend_from_slice(&interp_ms.to_le_bytes()); + b +} + +#[test] +fn ctx_rewind_hits_at_view_time_and_clamps_cheats() { + let clock = ManualClock::new(); + let config = HostConfig { + rewind: RewindConfig { + max_rewind: Duration::from_millis(300), + max_frames: 128, + }, + ..HostConfig::default() + }; + let mut h = ZoneHost::::new("range", config, Arc::new(clock.clone()), ()); + let joined = h.join(&claims("sniper", "range"), 0, "").unwrap(); + let step = Duration::from_secs(1) / 30; + for _ in 0..90 { + clock.advance(step); + h.advance(); + } + let latest = h.rewind().latest().unwrap().clone(); + assert!(h.rewind().len() <= h.rewind().capacity()); + + // The client was rendering tick latest-4 with a 100 ms interpolation + // delay and aimed exactly at the target as drawn (~233 ms in the past). + let client_tick = (latest.tick() - 4) as u32; + let view = h.rewind().time_of(client_tick).unwrap() - Duration::from_millis(100); + let seen_x = h.rewind().entity_at(TARGET, view).unwrap().pos[0]; + h.push_input(joined.client, 1, client_tick, &shot(seen_x, 100)); + + // A cheater claims a 2 s interpolation delay to hit an old position. + let old_x = (latest.time() - Duration::from_secs(2)).as_secs_f32() * SPEED; + h.push_input(joined.client, 2, latest.tick() as u32, &shot(old_x, 2000)); + + clock.advance(step); + h.advance(); + let shots = &h.zone().shots; + assert_eq!(shots.len(), 2); + assert_eq!( + shots[0].rewound, + Some(TARGET), + "laggy shot hits at view time" + ); + assert_eq!(shots[0].present, None, "same shot misses at present time"); + assert!(!shots[0].clamped); + assert!(shots[0].age > Duration::from_millis(200) && shots[0].age < Duration::from_millis(300)); + assert!(shots[1].clamped, "2 s rewind is clamped"); + assert_eq!(shots[1].age, Duration::from_millis(300)); + assert_eq!( + shots[1].rewound, None, + "clamped rewind cannot reach 2 s ago" + ); +} + +// ---------------------------------------------------------------- replay + +struct Session { + recording: Recording, + /// Final `ZoneHost::state_hash` of the live run. + final_hash: u64, +} + +fn reconnect_token(out: &[Outbound], client: u32) -> Option { + out.iter().rev().find_map(|o| match o { + Outbound::Frame { client: c, frame } if c.0 == client => { + match ClientMirror::new().apply(frame) { + Ok(ServerMessage::Welcome(w)) => Some(w.reconnect_token), + _ => None, + } + } + _ => None, + }) +} + +/// Four players move randomly over uneven clock steps; one drops and +/// reconnects with its token, one leaves; heartbeat facts settle through a +/// real async worker. +async fn record_session() -> Session { + let clock = ManualClock::new(); + let config = HostConfig { + world_seed: 0xdead_beef, + record: true, + ..HostConfig::default() + }; + let cfg = ArenaConfig { + fact_every_tick: true, + spawn_every: Some(Duration::from_millis(150)), + ..ArenaConfig::default() + }; + let (queue, feed) = fact_channel(64, RetryPolicy::default()); + spawn_fact_worker(feed, MemoryFactSink::new()); + let mut rec = + ZoneHost::::new("arena-1", config, Arc::new(clock.clone()), cfg).with_facts(queue); + let mut rng = ZoneRng::from_seed(42); + let mut clients = Vec::new(); + let mut seqs = [0u32; 4]; + let mut token = None; + for step in 0..120u32 { + if step < 4 * 5 && step % 5 == 0 { + let i = (step / 5) as usize; + let joined = rec + .join(&claims(&format!("p{i}"), "arena-1"), 0, "") + .unwrap(); + clients.push(joined.client); + let out = rec.drain_outbound(); + if i == 2 { + token = reconnect_token(&out, joined.client.0); + } + } + if step == 40 { + rec.disconnect(clients[2], false); + } + if step == 55 { + let joined = rec.reconnect(token.as_deref().unwrap(), 0).unwrap(); + clients[2] = joined.client; + } + if step == 90 { + rec.disconnect(clients[3], true); + } + for (i, client) in clients.iter().enumerate() { + if (step == 90 && i == 3) || step > 90 && i == 3 || (40..55).contains(&step) && i == 2 { + continue; + } + if rng.chance(0.7) { + seqs[i] += 1; + let dx = rng.range_u32(0, 3) as i8 - 1; + let dy = rng.range_u32(0, 3) as i8 - 1; + rec.push_input(*client, seqs[i], step, &[dx as u8, dy as u8]); + } + } + clock.advance(Duration::from_millis(u64::from(rng.range_u32(10, 70)))); + rec.advance(); + rec.drain_outbound(); + if step % 7 == 0 { + tokio::time::sleep(Duration::from_millis(1)).await; + } + } + // Let outstanding facts settle, then deliver them. + tokio::time::sleep(Duration::from_millis(20)).await; + clock.advance(Duration::from_millis(40)); + rec.advance(); + Session { + recording: rec.recording().expect("recording on").clone(), + final_hash: rec.state_hash(), + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn recorded_session_replays_identically() { + let session = record_session().await; + let rec = &session.recording; + let settled: usize = rec + .entries + .iter() + .map(|e| match &e.observed { + Observed::Advance { settled, .. } => settled.len(), + _ => 0, + }) + .sum(); + assert!(settled > 0, "facts settled during the recording"); + assert!(rec.entries.iter().any(|e| matches!( + (&e.stimulus, &e.observed), + ( + Stimulus::Reconnect { .. }, + Observed::Join(JoinResult::Joined(_)) + ) + ))); + assert!(rec.tick_count() > 120, "{}", rec.tick_count()); + + // Compact file round trip. + let bytes = rec.encode(); + let path = std::env::temp_dir().join(format!("dg-replay-{}.dgr", std::process::id())); + rec.save(&path).unwrap(); + let loaded = Recording::load(&path).unwrap(); + std::fs::remove_file(&path).ok(); + assert_eq!(&loaded, rec); + let per_tick = bytes.len() as f64 / rec.tick_count() as f64; + // ~3 inputs, one heartbeat settlement and an 8-byte hash per tick. + assert!(per_tick < 96.0, "{} bytes, {per_tick:.1}/tick", bytes.len()); + + let cfg = ArenaConfig { + fact_every_tick: true, + spawn_every: Some(Duration::from_millis(150)), + ..ArenaConfig::default() + }; + let summary = replay::(&loaded, cfg).unwrap_or_else(|d| panic!("{d}")); + assert_eq!(summary.ticks as usize, rec.tick_count()); + assert_eq!(summary.final_hash, session.final_hash); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn mutated_input_diverges_at_the_consuming_tick() { + let mut rec = record_session().await.recording; + // Flip the x direction of a mid-session input from p0 (never drops). + let p0 = match &rec.entries[0].observed { + Observed::Join(JoinResult::Joined(c)) => *c, + other => panic!("{other:?}"), + }; + let (index, seq) = rec + .entries + .iter() + .enumerate() + .skip(rec.entries.len() / 2) + .find_map(|(i, e)| match &e.stimulus { + Stimulus::Input { + client, + payload, + seq, + .. + } if client.0 == p0 && payload[0] != 0 => Some((i, *seq)), + _ => None, + }) + .expect("an input to mutate"); + if let Stimulus::Input { payload, .. } = &mut rec.entries[index].stimulus { + payload[0] = (-(payload[0] as i8)) as u8; + } + let consuming_tick = rec.entries[index..] + .iter() + .find_map(|e| match &e.observed { + Observed::Advance { hashes, .. } => hashes.first().map(|(t, _)| *t), + _ => None, + }) + .unwrap(); + + let cfg = ArenaConfig { + fact_every_tick: true, + spawn_every: Some(Duration::from_millis(150)), + ..ArenaConfig::default() + }; + let divergence = replay::(&rec, cfg).expect_err("mutation must be detected"); + assert_eq!(divergence.tick, consuming_tick); + assert_eq!(divergence.last_good_tick, consuming_tick - 1); + assert!(matches!(divergence.kind, DivergenceKind::StateHash { .. })); + let report = divergence.to_string(); + println!("{report}"); + assert!( + report.contains(&format!("diverged at tick {consuming_tick}")), + "{report}" + ); + assert!( + report.contains(&format!("client {p0} seq {seq} ")), + "report names the suspect input:\n{report}" + ); +} diff --git a/distributed_game/tests/replication/main.rs b/distributed_game/tests/replication/main.rs new file mode 100644 index 000000000..350e0eb9f --- /dev/null +++ b/distributed_game/tests/replication/main.rs @@ -0,0 +1,277 @@ +//! P3 replication: interest enter/leave with hysteresis, global entities, +//! change detection, byte-budget fairness and distance-based update rates. + +use std::collections::BTreeMap; + +use distributed_game::protocol::{Delta, ServerMessage}; +use distributed_game::replication::{ClientReplica, EncodedWorld}; +use distributed_game::{ + ClientMirror, EntitySchema, EntityState, FieldType, FieldValue, InterestConfig, KindDef, + UpdateRates, View, WorldView, +}; + +fn schema() -> EntitySchema { + let pos = FieldType::QuantF32 { + min: -1000.0, + max: 1000.0, + bits: 20, + }; + EntitySchema::new() + .kind( + KindDef::new(1, "thing") + .field("x", pos) + .field("y", pos) + .field("hp", FieldType::U16), + ) + .kind( + KindDef::new(2, "beacon") + .field("x", pos) + .field("y", pos) + .field("hp", FieldType::U16) + .every_patch(), + ) +} + +fn thing(id: u32, x: f32, y: f32, hp: u32) -> EntityState { + EntityState::new( + id, + 1, + x, + y, + vec![FieldValue::F(x), FieldValue::F(y), FieldValue::U(hp)], + ) +} + +struct Client { + replica: ClientReplica, + mirror: ClientMirror, + view: View, + budget: usize, + interest: InterestConfig, + world: Option, +} + +impl Client { + fn new(view: View, budget: usize) -> Self { + Self::with_rates(view, budget, UpdateRates::every_patch()) + } + + fn with_rates(view: View, budget: usize, update_rates: UpdateRates) -> Self { + // Seed the mirror with the schema as a Welcome would. + let mut mirror = ClientMirror::new(); + mirror.welcome = Some(distributed_game::protocol::Welcome { + session_id: "s".into(), + zone_id: "z".into(), + role: distributed_game::Role::Player, + tick_rate: 30, + patch_rate: 20, + server_tick: 0, + server_time: 0.0, + reconnect_token: String::new(), + content_version: String::new(), + schema: schema(), + features: 0, + origin: None, + }); + Self { + replica: ClientReplica::new(), + mirror, + view, + budget, + interest: InterestConfig { + cell_size: 8.0, + leave_margin: 0.1, + update_rates, + }, + world: None, + } + } + + fn patch(&mut self, entities: Vec, tick: u32) -> Delta { + let mut view = WorldView::default(); + for e in entities { + view.push(e); + } + let mut world = match self.world.take() { + Some(last) => last.next(&schema(), &view, &self.interest), + None => EncodedWorld::build(&schema(), &view, &self.interest), + }; + let (frame, _) = self.replica.build_delta( + &schema(), + &mut world, + &self.interest, + &self.view, + self.budget, + tick, + 0, + ); + self.world = Some(world); + match self.mirror.apply(&frame).unwrap() { + ServerMessage::Delta(d) => d, + other => panic!("{other:?}"), + } + } +} + +#[test] +fn entities_enter_and_leave_views_with_hysteresis() { + let mut c = Client::new(View::new(0.0, 0.0, 10.0), 10_000); + let far = thing(2, 50.0, 50.0, 1); + + let d = c.patch(vec![thing(1, 5.0, 0.0, 10), far.clone()], 1); + assert_eq!(d.creates.iter().map(|e| e.id).collect::>(), vec![1]); + + // Inside the leave margin (10 * 1.1 = 11): update, not remove. + let d = c.patch(vec![thing(1, 10.5, 0.0, 10), far.clone()], 2); + assert!(d.removes.is_empty()); + assert_eq!(d.updates.len(), 1); + assert_eq!(d.updates[0].mask, 0b001, "only x changed"); + + // Beyond the margin: remove. + let d = c.patch(vec![thing(1, 12.0, 0.0, 10), far.clone()], 3); + assert_eq!(d.removes, vec![1]); + assert!(c.mirror.entities.is_empty()); + + // Back inside the enter radius: full create again. + let d = c.patch(vec![thing(1, 9.0, 0.0, 7), far.clone()], 4); + assert_eq!(d.creates.len(), 1); + assert_eq!(c.mirror.entities[&1].fields[2], FieldValue::U(7)); + + // Despawn: remove. + let d = c.patch(vec![far], 5); + assert_eq!(d.removes, vec![1]); +} + +#[test] +fn global_entities_ignore_distance_and_unchanged_state_is_free() { + let mut c = Client::new(View::new(0.0, 0.0, 10.0), 10_000); + let d = c.patch(vec![thing(9, 900.0, 900.0, 1).global()], 1); + assert_eq!(d.creates.len(), 1); + let d = c.patch(vec![thing(9, 900.0, 900.0, 1).global()], 2); + assert!(d.creates.is_empty() && d.updates.is_empty() && d.removes.is_empty()); + // Sub-quantum jitter (20-bit over 2000 units ≈ 0.0019) is not a change. + let d = c.patch(vec![thing(9, 900.000_1, 900.0, 1).global()], 3); + assert!(d.updates.is_empty()); +} + +#[test] +fn byte_budget_prioritizes_but_never_starves() { + // 60 entities all changing every patch; budget fits ~8 updates. + let mut c = Client::new(View::new(0.0, 0.0, 100.0), 64); + let n = 60u32; + let mut last_sent: BTreeMap = BTreeMap::new(); + let mut max_gap: BTreeMap = BTreeMap::new(); + let mut sends: BTreeMap = BTreeMap::new(); + for tick in 1..=200u32 { + let entities = (1..=n) + .map(|id| { + // Entity 1 is close (high priority), the rest spread out. + let d = if id == 1 { 1.0 } else { 10.0 + id as f32 }; + thing(id, d, 0.0, tick) + }) + .collect(); + let delta = c.patch(entities, tick); + let sent: Vec = delta + .creates + .iter() + .map(|e| e.id) + .chain(delta.updates.iter().map(|u| u.id)) + .collect(); + assert!(!sent.is_empty()); + for id in sent { + let gap = tick - last_sent.get(&id).copied().unwrap_or(0); + let g = max_gap.entry(id).or_insert(0); + *g = (*g).max(gap); + last_sent.insert(id, tick); + *sends.entry(id).or_insert(0) += 1; + } + } + assert_eq!(sends.len(), n as usize, "every entity was sent"); + let worst = max_gap.values().max().copied().unwrap(); + assert!(worst <= 30, "bounded staleness, worst gap {worst} patches"); + assert!( + sends[&1] > sends[&n] * 4 / 3, + "near entity sent more often ({} vs {})", + sends[&1], + sends[&n] + ); + // Mirror converges to the server state for everything sent recently. + assert_eq!(c.mirror.entities.len(), n as usize); +} + +fn hp(c: &Client, id: u32) -> u32 { + match c.mirror.entities[&id].fields[2] { + FieldValue::U(hp) => hp, + ref other => panic!("{other:?}"), + } +} + +#[test] +fn far_updates_thin_out_and_converge_within_their_interval() { + // Defaults: within 50 every patch, within 80 every 2nd, beyond every 4th. + let mut c = Client::with_rates(View::new(0.0, 0.0, 100.0), 1 << 20, UpdateRates::default()); + let world = |hp: u32| { + vec![ + thing(1, 10.0, 0.0, hp), + thing(2, 65.0, 0.0, hp), + thing(3, 95.0, 0.0, hp), + thing(4, 0.0, 95.0, hp).global(), + EntityState::new( + 5, + 2, + -95.0, + 0.0, + vec![FieldValue::F(-95.0), FieldValue::F(0.0), FieldValue::U(hp)], + ), + ] + }; + let d = c.patch(world(0), 0); + assert_eq!(d.creates.len(), 5, "creates are never held"); + + let mut updates: BTreeMap = BTreeMap::new(); + for tick in 1..=40 { + let d = c.patch(world(tick), tick); + for u in &d.updates { + *updates.entry(u.id).or_insert(0) += 1; + } + // Every entity shows a state at most its interval - 1 patches old. + for (id, every) in [(1, 1), (2, 2), (3, 4), (4, 1), (5, 1)] { + assert!(hp(&c, id) + every > tick, "entity {id} at tick {tick}"); + } + } + assert_eq!(updates[&1], 40, "near: every patch"); + assert_eq!(updates[&2], 20, "mid: every 2nd"); + assert_eq!(updates[&3], 10, "far: every 4th"); + assert_eq!(updates[&4], 40, "global: never held"); + assert_eq!(updates[&5], 40, "every_patch kind: never held"); + + // The last change arrives within 4 patches, then nothing more is sent. + for tick in 41..=44 { + c.patch(world(40), tick); + } + assert!((1..=5).all(|id| hp(&c, id) == 40)); + let d = c.patch(world(40), 45); + assert!(d.updates.is_empty()); +} + +#[test] +fn update_rates_never_hold_entering_spawning_or_leaving_entities() { + let mut c = Client::with_rates(View::new(0.0, 0.0, 100.0), 1 << 20, UpdateRates::default()); + c.patch(vec![thing(1, 95.0, 0.0, 1)], 0); + // A far spawn is created at once, whatever the patch. + for tick in 1..=4 { + let d = c.patch( + vec![thing(1, 95.0, 0.0, 1), thing(10 + tick, 0.0, 95.0, 1)], + tick, + ); + assert_eq!( + d.creates.iter().map(|e| e.id).collect::>(), + vec![10 + tick] + ); + assert_eq!(d.removes, if tick == 1 { vec![] } else { vec![9 + tick] }); + } + // Leaving the view (beyond 110) and despawning are removed at once. + let d = c.patch(vec![thing(1, 111.0, 0.0, 2)], 5); + assert_eq!(d.removes, vec![1, 14]); + assert!(c.mirror.entities.is_empty()); +} diff --git a/distributed_game/tests/support/admission.rs b/distributed_game/tests/support/admission.rs new file mode 100644 index 000000000..d5fd1f8ee --- /dev/null +++ b/distributed_game/tests/support/admission.rs @@ -0,0 +1,208 @@ +//! The admission conformance suite: one set of cases every driver (the +//! `net` server, celld zone objects) must pass over a real WebSocket. +//! Both run [`distributed_game::admission`]; this checks they wire it the +//! same way. The target declares no ticket extensions, hosts every +//! `room-*` zone and keeps the default message rate (120/s, bursts of +//! 240). + +#![allow(dead_code)] + +use std::future::Future; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use distributed_game::protocol::{error, kick, ClientMessage, Hello, ServerMessage}; +use distributed_game::ticket::TicketKey; +use distributed_game::{ClientMirror, Role, TicketClaims, TicketExtensions, PROTOCOL_VERSION}; +use futures_util::{SinkExt, StreamExt}; +use tokio_tungstenite::tungstenite::Message; + +type Ws = + tokio_tungstenite::WebSocketStream>; + +/// A driver under test. +pub struct Target { + /// `ws://host:port` (zones at `{base}/zones/{zone}`). + pub base: String, + /// Its ticket key. + pub key: TicketKey, + /// Its Hello deadline. + pub hello_timeout: Duration, + /// Whether a zone is running (activated, awake) on the target. + pub awake: A, +} + +#[derive(Debug, PartialEq)] +enum Got { + Message(ServerMessage), + Closed, +} + +fn now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs() +} + +fn claims(zone: &str, case: &str) -> TicketClaims { + let nonce = format!( + "{case}-{}", + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos() + ); + TicketClaims::new("ana", zone, now() + 120, nonce, Role::Player) +} + +async fn connect(base: &str, zone: &str) -> Ws { + tokio_tungstenite::connect_async(format!("{base}/zones/{zone}")) + .await + .expect("connect") + .0 +} + +async fn send(ws: &mut Ws, message: ClientMessage) { + let _ = ws.send(Message::Binary(message.encode().into())).await; +} + +fn hello(ticket: &str) -> ClientMessage { + ClientMessage::Hello(Hello { + protocol_version: PROTOCOL_VERSION, + ticket: ticket.into(), + ..Hello::default() + }) +} + +/// Next server message other than Delta/Event/Pong, or the close. +async fn next(ws: &mut Ws, within: Duration) -> Got { + let deadline = Instant::now() + within; + loop { + let left = deadline.saturating_duration_since(Instant::now()); + match tokio::time::timeout(left, ws.next()).await { + Err(_) => panic!("no answer within {within:?}"), + Ok(Some(Ok(Message::Binary(bytes)))) => { + match ServerMessage::decode(&bytes, &ClientMirror::new()) { + Ok(ServerMessage::Event { .. } | ServerMessage::Pong { .. }) | Err(_) => { + continue + } + Ok(message) => return Got::Message(message), + } + } + Ok(Some(Ok(Message::Close(_)))) | Ok(Some(Err(_))) | Ok(None) => return Got::Closed, + Ok(Some(Ok(_))) => continue, + } + } +} + +const ANSWER: Duration = Duration::from_secs(15); + +async fn refused(target_base: &str, zone: &str, first: ClientMessage) -> u32 { + let mut ws = connect(target_base, zone).await; + send(&mut ws, first).await; + match next(&mut ws, ANSWER).await { + Got::Message(ServerMessage::Error { code, .. }) => code, + other => panic!("{zone}: expected an Error, got {other:?}"), + } +} + +async fn joins(base: &str, zone: &str, ticket: &str) -> Ws { + let mut ws = connect(base, zone).await; + send(&mut ws, hello(ticket)).await; + match next(&mut ws, ANSWER).await { + Got::Message(ServerMessage::Welcome(_)) => ws, + other => panic!("{zone}: expected Welcome, got {other:?}"), + } +} + +/// Run every case against `target`. +pub async fn run(target: Target) +where + A: Fn(String) -> F, + F: Future, +{ + let Target { + base, + key, + hello_timeout, + awake, + } = target; + let zone = "room-admission"; + + // Refused tickets: nothing wakes. + let expired = key.sign(&TicketClaims { + expires_at: now() - 1, + ..claims("room-adm-expired", "expired") + }); + let forged = TicketKey::new("not-the-zone-key-at-all").sign(&claims("room-adm-forged", "f")); + let elsewhere = key.sign(&claims("room-adm-other", "elsewhere")); + let ext = key.sign(&TicketClaims { + extensions: TicketExtensions::from_json(serde_json::json!({"team": 1})).unwrap(), + ..claims("room-adm-ext", "ext") + }); + for (room, ticket) in [ + ("room-adm-garbage", "garbage".to_string()), + ("room-adm-expired", expired), + ("room-adm-forged", forged), + ("room-adm-wrong", elsewhere), + ("room-adm-ext", ext), + ] { + assert_eq!( + refused(&base, room, hello(&ticket)).await, + error::UNAUTHORIZED, + "{room}" + ); + assert!( + !awake(room.to_string()).await, + "{room} woke for a refused Hello" + ); + } + + // Another protocol version: refused before the ticket is used. + let ticket = key.sign(&claims(zone, "version")); + let future = ClientMessage::Hello(Hello { + protocol_version: PROTOCOL_VERSION + 1, + ticket: ticket.clone(), + ..Hello::default() + }); + assert_eq!(refused(&base, zone, future).await, error::VERSION_MISMATCH); + + // The first frame must be Hello: an unauthenticated Ping is refused. + assert_eq!( + refused(&base, zone, ClientMessage::Ping { client_time: 1.0 }).await, + error::BAD_MESSAGE + ); + assert!(!awake(zone.to_string()).await); + + // Single use: the same ticket joins once. + let mut first = joins(&base, zone, &ticket).await; + assert_eq!( + refused(&base, zone, hello(&ticket)).await, + error::UNAUTHORIZED, + "replayed ticket" + ); + + // Silence after the upgrade: closed at the Hello deadline. + let mut silent = connect(&base, zone).await; + let started = Instant::now(); + let got = next(&mut silent, hello_timeout + Duration::from_secs(10)).await; + assert!( + matches!(got, Got::Closed | Got::Message(ServerMessage::Error { .. })), + "{got:?}" + ); + assert!(started.elapsed() >= hello_timeout, "closed early"); + + // Every message after the Welcome is rate limited: a flood of Pings + // (not inputs) is kicked. + for _ in 0..2_000 { + send(&mut first, ClientMessage::Ping { client_time: 0.0 }).await; + } + let kicked = loop { + match next(&mut first, ANSWER).await { + Got::Message(ServerMessage::Kick { code, .. }) => break Some(code), + Got::Message(_) => continue, + Got::Closed => break None, + } + }; + assert_eq!(kicked, Some(kick::RATE_LIMITED)); +} diff --git a/distributed_game/tests/support/arena.rs b/distributed_game/tests/support/arena.rs new file mode 100644 index 000000000..378b3e9d9 --- /dev/null +++ b/distributed_game/tests/support/arena.rs @@ -0,0 +1,318 @@ +//! Shared test zone: avatars move by input, coins spawn on a timer, picking a +//! coin emits a durable fact credited to the verified principal. +#![allow(dead_code)] + +use std::collections::BTreeMap; +use std::time::Duration; + +use distributed_game::{ + Admission, ConsumePolicy, Ctx, EntitySchema, EntityState, Fact, FactSettlement, FieldType, + FieldValue, Fnv64, JoinRequest, KindDef, LeaveReason, ObserverId, PlayerId, Tier, TimerId, + View, WorldView, Zone, +}; +use serde_json::json; + +pub const AVATAR: u16 = 1; +pub const COIN: u16 = 2; + +#[derive(Debug, Clone, Default)] +pub struct ArenaConfig { + pub fact_every_tick: bool, + /// Every player queues a `step:{tick}:{player}` fact each tick + /// (`Ctx::queue_fact_for`: never refused for backpressure). + pub queue_facts: bool, + pub reject_principal: Option, + pub background: bool, + pub spawn_every: Option, + /// Allocation payload handed over by the zone factory. + pub allocation: Option, + /// `Zone::origin` (Welcome v2). + pub origin: Option, + /// `Zone::view_radius` (the default observer focus). + pub view_radius: Option, +} + +#[derive(Debug, Clone)] +pub struct Avatar { + pub entity: u32, + pub x: f32, + pub y: f32, + pub score: u32, +} + +#[derive(Debug, Clone)] +pub enum ArenaTimer { + SpawnCoin, +} + +pub struct Arena { + pub cfg: ArenaConfig, + pub avatars: BTreeMap, + pub coins: BTreeMap, + pub next_entity: u32, + pub log: Vec, + pub settled: Vec, + pub emit_errors: Vec, + pub ticks: u64, + pub timer_fires: u64, + pub tiers: Vec<(Tier, Tier)>, + /// Extension claims seen by `on_auth`. + pub auth_extensions: Vec, + /// `lost:{player}` / `back:{player}` from the connection hooks. + pub connection_events: Vec, + /// `Ctx::dropped_ticks` seen by each `on_tick`. + pub dropped_seen: Vec, +} + +impl Arena { + pub fn state_hash(&self) -> u64 { + let mut h = Fnv64::new(); + for (id, a) in &self.avatars { + h.write_u64(u64::from(id.0)) + .write_f32(a.x) + .write_f32(a.y) + .write_u64(u64::from(a.score)); + } + for (id, (x, y)) in &self.coins { + h.write_u64(u64::from(*id)).write_f32(*x).write_f32(*y); + } + h.write_u64(self.ticks); + h.finish() + } + + fn spawn_coin(&mut self, ctx: &mut Ctx<'_, Self>) { + let x = ctx.rng().next_f32() * 100.0; + let y = ctx.rng().next_f32() * 100.0; + self.next_entity += 1; + self.coins.insert(self.next_entity, (x, y)); + } +} + +impl Zone for Arena { + type Config = ArenaConfig; + type Input = (i8, i8); + type Timer = ArenaTimer; + type Message = distributed_game::NoMessages; + + fn schema() -> EntitySchema { + let pos = FieldType::QuantF32 { + min: 0.0, + max: 100.0, + bits: 16, + }; + EntitySchema::new() + .kind( + KindDef::new(AVATAR, "avatar") + .field("x", pos) + .field("y", pos) + .field("score", FieldType::U16), + ) + .kind( + KindDef::new(COIN, "coin") + .field("x", pos) + .field("y", pos) + .priority(0.5), + ) + } + + fn on_create(ctx: &mut Ctx<'_, Self>, cfg: ArenaConfig) -> Self { + if let Some(every) = cfg.spawn_every { + ctx.set_interval(every, ArenaTimer::SpawnCoin); + } + Self { + cfg, + avatars: BTreeMap::new(), + coins: BTreeMap::new(), + next_entity: 1000, + log: vec!["create".into()], + settled: Vec::new(), + emit_errors: Vec::new(), + ticks: 0, + timer_fires: 0, + tiers: Vec::new(), + auth_extensions: Vec::new(), + connection_events: Vec::new(), + dropped_seen: Vec::new(), + } + } + + fn on_auth(&mut self, _ctx: &mut Ctx<'_, Self>, req: &JoinRequest<'_>) -> Admission { + self.auth_extensions.push(req.claims.extensions.clone()); + if self.cfg.reject_principal.as_deref() == Some(req.claims.principal.as_str()) { + return Admission::Reject("banned".into()); + } + Admission::Admit + } + + fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + let x = 10.0 + ctx.rng().next_f32() * 80.0; + let y = 10.0 + ctx.rng().next_f32() * 80.0; + self.avatars.insert( + player, + Avatar { + entity: player.0, + x, + y, + score: 0, + }, + ); + ctx.set_view(player, View::new(x, y, 30.0)); + let principal = ctx.player(player).unwrap().principal.clone(); + self.log.push(format!("join:{principal}")); + } + + fn on_leave(&mut self, _ctx: &mut Ctx<'_, Self>, player: PlayerId, reason: LeaveReason) { + self.avatars.remove(&player); + self.log.push(format!("leave:{reason:?}")); + } + + fn on_connection_lost(&mut self, _ctx: &mut Ctx<'_, Self>, player: PlayerId) { + self.connection_events.push(format!("lost:{}", player.0)); + } + + fn on_reconnected(&mut self, _ctx: &mut Ctx<'_, Self>, player: PlayerId) { + self.connection_events.push(format!("back:{}", player.0)); + } + + fn on_observe(&mut self, ctx: &mut Ctx<'_, Self>, observer: ObserverId) { + ctx.set_view(observer, View::new(50.0, 50.0, 1000.0)); + let info = ctx + .observer(observer) + .expect("observer known in on_observe"); + let line = format!( + "observe:{}:{}", + info.principal, + info.name.as_deref().unwrap_or("-") + ); + let mine: Vec<_> = ctx.observers_of(&info.principal.clone()).collect(); + assert_eq!(mine, vec![observer]); + ctx.send_event(observer, 7, line.clone().into_bytes()); + self.log.push(line); + } + + fn on_unobserve(&mut self, ctx: &mut Ctx<'_, Self>, observer: ObserverId) { + let principal = ctx.observer(observer).map(|o| o.principal.clone()); + self.log + .push(format!("unobserve:{}", principal.as_deref().unwrap_or("?"))); + } + + fn origin(&self) -> Option { + self.cfg.origin + } + + fn view_radius(&self) -> Option { + self.cfg.view_radius + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option<(i8, i8)> { + match payload { + [dx, dy] => Some((*dx as i8, *dy as i8)), + _ => None, + } + } + + fn sanitize_input(&self, _player: PlayerId, (dx, dy): (i8, i8)) -> Option<(i8, i8)> { + if dx.unsigned_abs() > 4 || dy.unsigned_abs() > 4 { + return None; + } + Some((dx.clamp(-1, 1), dy.clamp(-1, 1))) + } + + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + self.ticks += 1; + self.dropped_seen.push(ctx.dropped_ticks()); + let dt = ctx.dt_secs(); + let players: Vec = self.avatars.keys().copied().collect(); + for player in players { + let inputs = ctx.take_inputs(player, ConsumePolicy::Drain); + let avatar = self.avatars.get_mut(&player).unwrap(); + for input in inputs { + avatar.x = (avatar.x + f32::from(input.input.0) * 10.0 * dt).clamp(0.0, 100.0); + avatar.y = (avatar.y + f32::from(input.input.1) * 10.0 * dt).clamp(0.0, 100.0); + } + let (ax, ay) = (avatar.x, avatar.y); + let picked: Vec = self + .coins + .iter() + .filter(|(_, (x, y))| (x - ax).powi(2) + (y - ay).powi(2) < 4.0) + .map(|(id, _)| *id) + .collect(); + for coin in picked { + self.coins.remove(&coin); + self.avatars.get_mut(&player).unwrap().score += 1; + let fact = Fact::new( + format!("coin:{}:{coin}", ctx.zone_id()), + "credit_xp", + json!({ "amount": 10 }), + ); + if let Err(e) = ctx.emit_fact_for(player, fact) { + self.emit_errors.push(e); + } + } + ctx.set_view(player, View::new(ax, ay, 30.0)); + } + if self.cfg.queue_facts { + let players: Vec<_> = ctx.players().map(|p| p.id).collect(); + for player in players { + let key = format!("step:{}:{}", ctx.tick(), player.0); + if let Err(e) = ctx.queue_fact_for(player, Fact::new(key, "step", json!(null))) { + self.emit_errors.push(e); + } + } + } + if self.cfg.fact_every_tick { + let fact = Fact::new(format!("tick:{}", ctx.tick()), "heartbeat", json!(null)); + if let Err(e) = ctx.emit_fact(fact) { + self.emit_errors.push(e); + } + } + } + + fn on_timer(&mut self, ctx: &mut Ctx<'_, Self>, _id: TimerId, timer: ArenaTimer) { + self.timer_fires += 1; + match timer { + ArenaTimer::SpawnCoin => self.spawn_coin(ctx), + } + } + + fn on_fact_settled(&mut self, _ctx: &mut Ctx<'_, Self>, settlement: FactSettlement) { + self.settled.push(settlement); + } + + fn on_tier_changed(&mut self, _ctx: &mut Ctx<'_, Self>, from: Tier, to: Tier) { + self.tiers.push((from, to)); + } + + fn wants_background(&self) -> bool { + self.cfg.background + } + + fn replicate(&self, out: &mut WorldView) { + for a in self.avatars.values() { + out.push(EntityState::new( + a.entity, + AVATAR, + a.x, + a.y, + vec![ + FieldValue::F(a.x), + FieldValue::F(a.y), + FieldValue::U(a.score), + ], + )); + } + for (id, (x, y)) in &self.coins { + out.push(EntityState::new( + *id, + COIN, + *x, + *y, + vec![FieldValue::F(*x), FieldValue::F(*y)], + )); + } + } + + fn on_dispose(&mut self, _ctx: &mut Ctx<'_, Self>) { + self.log.push("dispose".into()); + } +} diff --git a/distributed_game/tests/support/celld.rs b/distributed_game/tests/support/celld.rs new file mode 100644 index 000000000..03d2ce17d --- /dev/null +++ b/distributed_game/tests/support/celld.rs @@ -0,0 +1,238 @@ +//! An isolated `celld dev` serving `tests/celld/fact-worker`, owned by one +//! test: its own temp project, port and process tree (killed on drop; only +//! processes this harness started). Skips (returns `None`) when the worker +//! is not built or celld cannot start, unless `CELLD_FACTS_REQUIRED=1`. + +#![allow(dead_code)] + +use std::io::Write as _; +use std::net::TcpListener; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::time::{Duration, Instant}; + +pub const SECRET: &str = "test-only-internal-secret-change-me-2026"; + +fn worker_dir() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../tests/celld/fact-worker") +} + +pub struct Celld { + project: PathBuf, + port: u16, + child: Option, + generation: u32, +} + +impl Celld { + pub fn start_new() -> Option { + Self::start_worker(&worker_dir(), "CELLD_FACTS_REQUIRED") + } + + /// `celld dev` serving the built worker in `dir`; skips (None) when it + /// is not built or celld cannot start, unless env `required` is set. + pub fn start_worker(dir: &Path, required: &str) -> Option { + let build = dir.join("build"); + if !build.join("worker/shim.mjs").exists() { + assert!( + std::env::var_os(required).is_none(), + "{required} is set but {} is not built", + dir.display() + ); + eprintln!( + "skipping: build {} first (worker-build --release)", + dir.display() + ); + return None; + } + let project = std::env::temp_dir().join(format!( + "distributed-celld-facts-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + copy_dir(&build, &project.join("build")); + std::fs::copy(dir.join("wrangler.jsonc"), project.join("wrangler.jsonc")).unwrap(); + let port = TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + let mut celld = Self { + project, + port, + child: None, + generation: 0, + }; + if let Err(reason) = celld.start() { + assert!( + std::env::var_os(required).is_none(), + "celld dev is required but did not start: {reason}" + ); + eprintln!("skipping: {reason}"); + return None; + } + Some(celld) + } + + pub fn base(&self) -> String { + format!("http://127.0.0.1:{}", self.port) + } + + /// Start `celld dev`; `Err` when it is unavailable or exits early (no + /// celld on PATH, or no esbuild for its bundler). + pub fn start(&mut self) -> Result<(), String> { + self.generation += 1; + let binary = std::env::var("CELLD_BIN").unwrap_or_else(|_| "celld".into()); + let help = Command::new(&binary) + .args(["dev", "--help"]) + .output() + .map_err(|error| format!("cannot run `{binary}`: {error}"))?; + let mut args = vec![ + "dev".to_string(), + self.project.display().to_string(), + "--host".into(), + "127.0.0.1".into(), + "--port".into(), + self.port.to_string(), + "--logs".into(), + ]; + if String::from_utf8_lossy(&help.stdout).contains("--no-watch") { + args.push("--no-watch".into()); + } + let log_path = self.project.join(format!("celld-{}.log", self.generation)); + let log = std::fs::File::create(&log_path).unwrap(); + let child = Command::new(&binary) + .args(&args) + .env( + "RUST_LOG", + std::env::var("CELLD_RUST_LOG").unwrap_or_else(|_| "warn".into()), + ) + .stdin(Stdio::null()) + .stdout(log.try_clone().unwrap()) + .stderr(log) + .spawn() + .map_err(|error| format!("cannot start `{binary} dev`: {error}"))?; + self.child = Some(child); + let deadline = Instant::now() + Duration::from_secs(90); + while Instant::now() < deadline { + if std::net::TcpStream::connect(("127.0.0.1", self.port)).is_ok() + && blocking_get(&format!("{}/health", self.base())).is_some_and(|s| s == 200) + { + return Ok(()); + } + let exited = self + .child + .as_mut() + .and_then(|child| child.try_wait().ok().flatten()); + if let Some(status) = exited { + self.child = None; + let log = std::fs::read_to_string(&log_path).unwrap_or_default(); + return Err(format!( + "celld dev exited ({status}): {}", + log.lines().rev().take(3).collect::>().join(" | ") + )); + } + std::thread::sleep(Duration::from_millis(200)); + } + Err(format!( + "celld dev did not become ready; logs in {}", + self.project.display() + )) + } + + /// Kill the launcher this test started and every descendant. + pub fn crash(&mut self) { + let Some(mut child) = self.child.take() else { + return; + }; + let root = child.id(); + let _ = Command::new("kill") + .args(["-STOP", &root.to_string()]) + .status(); + let table = Command::new("ps") + .args(["-axo", "pid=,ppid="]) + .output() + .unwrap(); + let pairs = String::from_utf8_lossy(&table.stdout) + .lines() + .filter_map(|line| { + let mut parts = line.split_whitespace(); + Some(( + parts.next()?.parse::().ok()?, + parts.next()?.parse::().ok()?, + )) + }) + .collect::>(); + let mut doomed = vec![root]; + let mut index = 0; + while index < doomed.len() { + let parent = doomed[index]; + doomed.extend( + pairs + .iter() + .filter(|(_, ppid)| *ppid == parent) + .map(|(pid, _)| *pid), + ); + index += 1; + } + for pid in doomed.iter().rev() { + let _ = Command::new("kill") + .args(["-KILL", &pid.to_string()]) + .status(); + } + let _ = child.wait(); + // The port is released once the processes are gone. + let deadline = Instant::now() + Duration::from_secs(10); + while Instant::now() < deadline + && std::net::TcpStream::connect(("127.0.0.1", self.port)).is_ok() + { + std::thread::sleep(Duration::from_millis(100)); + } + } +} + +impl Drop for Celld { + fn drop(&mut self) { + self.crash(); + if !std::thread::panicking() { + let _ = std::fs::remove_dir_all(&self.project); + } else { + let _ = writeln!( + std::io::stderr(), + "celld artifacts kept in {}", + self.project.display() + ); + } + } +} + +pub fn copy_dir(from: &Path, to: &Path) { + std::fs::create_dir_all(to).unwrap(); + for entry in std::fs::read_dir(from).unwrap() { + let entry = entry.unwrap(); + let target = to.join(entry.file_name()); + if entry.file_type().unwrap().is_dir() { + copy_dir(&entry.path(), &target); + } else { + std::fs::copy(entry.path(), target).unwrap(); + } + } +} + +pub fn blocking_get(url: &str) -> Option { + let url = url.strip_prefix("http://")?; + let (host, path) = url.split_once('/')?; + let mut stream = std::net::TcpStream::connect(host).ok()?; + stream.set_read_timeout(Some(Duration::from_secs(2))).ok()?; + write!( + stream, + "GET /{path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n" + ) + .ok()?; + let mut response = String::new(); + std::io::Read::read_to_string(&mut stream, &mut response).ok()?; + response.split_whitespace().nth(1)?.parse().ok() +} diff --git a/distributed_game/tests/support/fleet.rs b/distributed_game/tests/support/fleet.rs new file mode 100644 index 000000000..9eb7231be --- /dev/null +++ b/distributed_game/tests/support/fleet.rs @@ -0,0 +1,308 @@ +//! A local multi-node celld fleet owned by one test: one RustFS container +//! (docker compose, its own project and port) holding the fleet bucket, the +//! worker deployed to it with `celld deploy`, and N `celld` nodes in +//! production mode. Kills only what it started; removes the container on +//! drop. Skips (None) without docker / aws / a built worker unless env +//! `required` is set. + +#![allow(dead_code)] + +use std::net::TcpListener; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::time::{Duration, Instant}; + +use super::celld_support::{blocking_get, copy_dir}; + +const ACCESS_KEY: &str = "fleettest"; +const SECRET_KEY: &str = "fleettestsecret123"; + +fn free_port() -> u16 { + TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port() +} + +pub struct Node { + pub name: String, + pub public: u16, + pub operator: u16, + child: Option, +} + +pub struct Fleet { + dir: PathBuf, + project: String, + s3_port: u16, + bucket: String, + binary: String, + pub nodes: Vec, +} + +fn skip(required: &str, reason: String) -> Option { + assert!( + std::env::var_os(required).is_none(), + "{required} is set but the fleet is unavailable: {reason}" + ); + eprintln!("skipping the celld fleet test: {reason}"); + None +} + +impl Fleet { + /// Start `nodes` nodes serving the worker in `worker` with extra + /// string `vars` (`{nodes}` in a value is replaced by the operator + /// listeners, `node-a=127.0.0.1:p,…`). + pub fn start( + worker: &Path, + nodes: usize, + vars: &[(&str, &str)], + required: &str, + ) -> Option { + if !worker.join("build/worker/shim.mjs").exists() { + return skip(required, format!("build {} first", worker.display())); + } + for tool in ["docker", "aws"] { + if Command::new(tool).arg("--version").output().is_err() { + return skip(required, format!("`{tool}` is not available")); + } + } + let binary = std::env::var("CELLD_BIN").unwrap_or_else(|_| "celld".into()); + let stamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis(); + let dir = std::env::temp_dir().join(format!( + "distributed-celld-fleet-{}-{stamp}", + std::process::id() + )); + std::fs::create_dir_all(&dir).unwrap(); + let mut fleet = Self { + project: format!("dg-fleet-{}-{}", std::process::id(), stamp % 100_000), + s3_port: free_port(), + bucket: "dg-fleet".into(), + binary, + nodes: Vec::new(), + dir, + }; + for i in 0..nodes { + fleet.nodes.push(Node { + name: format!("node-{}", (b'a' + i as u8) as char), + public: free_port(), + operator: free_port(), + child: None, + }); + } + if let Err(reason) = fleet.s3_up() { + return skip(required, reason); + } + let listeners = fleet + .nodes + .iter() + .map(|n| format!("{}=127.0.0.1:{}", n.name, n.operator)) + .collect::>() + .join(","); + let vars: Vec<(String, String)> = vars + .iter() + .map(|(k, v)| (k.to_string(), v.replace("{nodes}", &listeners))) + .collect(); + if let Err(reason) = fleet.deploy(worker, &vars) { + return skip(required, reason); + } + for i in 0..fleet.nodes.len() { + if let Err(reason) = fleet.start_node(i) { + return skip(required, reason); + } + } + Some(fleet) + } + + fn env(&self, command: &mut Command) { + command + .env("AWS_ACCESS_KEY_ID", ACCESS_KEY) + .env("AWS_SECRET_ACCESS_KEY", SECRET_KEY) + .env("AWS_REGION", "us-east-1") + .env("S3_ENDPOINT", self.endpoint()); + } + + fn endpoint(&self) -> String { + format!("http://127.0.0.1:{}", self.s3_port) + } + + fn s3_up(&self) -> Result<(), String> { + let compose = self.dir.join("s3-compose.yaml"); + std::fs::write( + &compose, + format!( + "services:\n s3:\n image: rustfs/rustfs:1.0.3\n command: [\"/data\"]\n environment:\n RUSTFS_ADDRESS: \"0.0.0.0:9000\"\n RUSTFS_ACCESS_KEY: {ACCESS_KEY}\n RUSTFS_SECRET_KEY: {SECRET_KEY}\n ports: [\"127.0.0.1:{}:9000\"]\n", + self.s3_port + ), + ) + .unwrap(); + let up = Command::new("docker") + .args(["compose", "-p", &self.project, "-f"]) + .arg(&compose) + .args(["up", "-d"]) + .output() + .map_err(|e| format!("docker compose: {e}"))?; + if !up.status.success() { + return Err(format!( + "docker compose up: {}", + String::from_utf8_lossy(&up.stderr) + )); + } + let deadline = Instant::now() + Duration::from_secs(60); + loop { + let mut mb = Command::new("aws"); + self.env(&mut mb); + let made = mb + .args(["--endpoint-url", &self.endpoint(), "s3", "mb"]) + .arg(format!("s3://{}", self.bucket)) + .output() + .map_err(|e| format!("aws: {e}"))?; + let text = String::from_utf8_lossy(&made.stderr); + if made.status.success() || text.contains("BucketAlready") { + return Ok(()); + } + if Instant::now() > deadline { + return Err(format!("bucket: {text}")); + } + std::thread::sleep(Duration::from_millis(500)); + } + } + + fn bucket_url(&self) -> String { + format!("s3://{}/fleet", self.bucket) + } + + fn deploy(&self, worker: &Path, vars: &[(String, String)]) -> Result<(), String> { + let project = self.dir.join("worker"); + copy_dir(&worker.join("build"), &project.join("build")); + let config = std::fs::read_to_string(worker.join("wrangler.jsonc")).unwrap(); + let mut config: serde_json::Value = serde_json::from_str(&strip_comments(&config)) + .map_err(|e| format!("wrangler.jsonc: {e}"))?; + for (key, value) in vars { + config["vars"][key] = serde_json::Value::String(value.clone()); + } + std::fs::write(project.join("wrangler.json"), config.to_string()).unwrap(); + let mut deploy = Command::new(&self.binary); + self.env(&mut deploy); + let out = deploy + .arg("deploy") + .arg(&project) + .args(["--bucket", &self.bucket_url()]) + .output() + .map_err(|e| format!("celld deploy: {e}"))?; + if !out.status.success() { + return Err(format!( + "celld deploy: {}{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + )); + } + Ok(()) + } + + /// (Re)start node `i`. + pub fn start_node(&mut self, i: usize) -> Result<(), String> { + let node = &self.nodes[i]; + let dir = self.dir.join(&node.name); + std::fs::create_dir_all(&dir).unwrap(); + let log = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(dir.join("celld.log")) + .unwrap(); + let mut command = Command::new(&self.binary); + self.env(&mut command); + let child = command + .args(["--bucket", &self.bucket_url()]) + .args(["--listen", &format!("127.0.0.1:{}", node.public)]) + .args(["--internal-listen", &format!("127.0.0.1:{}", node.operator)]) + .args(["--advertise", &format!("127.0.0.1:{}", node.operator)]) + .env("CELLD_NODE", &node.name) + .env("CELLD_WATCH", dir.join("watch")) + .env("CELLD_READY_FLEET_GATE_MS", "0") + .env( + "RUST_LOG", + std::env::var("CELLD_RUST_LOG").unwrap_or_else(|_| "warn".into()), + ) + .stdin(Stdio::null()) + .stdout(log.try_clone().unwrap()) + .stderr(log) + .spawn() + .map_err(|e| format!("celld: {e}"))?; + let public = node.public; + self.nodes[i].child = Some(child); + let deadline = Instant::now() + Duration::from_secs(90); + while Instant::now() < deadline { + if blocking_get(&format!("http://127.0.0.1:{public}/health")) == Some(200) { + return Ok(()); + } + let exited = self.nodes[i] + .child + .as_mut() + .and_then(|c| c.try_wait().ok().flatten()); + if let Some(status) = exited { + // A cold node sometimes fails its first start; retry once. + self.nodes[i].child = None; + return Err(format!( + "{} exited ({status}); logs in {}", + self.nodes[i].name, + dir.display() + )); + } + std::thread::sleep(Duration::from_millis(250)); + } + Err(format!( + "{} not ready; logs in {}", + self.nodes[i].name, + dir.display() + )) + } + + /// `http://127.0.0.1:{public port}` of node `i`. + pub fn base(&self, i: usize) -> String { + format!("http://127.0.0.1:{}", self.nodes[i].public) + } + + /// Index of the node named `name`. + pub fn index(&self, name: &str) -> Option { + self.nodes.iter().position(|n| n.name == name) + } + + /// SIGKILL node `i` (a crash). + pub fn kill(&mut self, i: usize) { + if let Some(mut child) = self.nodes[i].child.take() { + let _ = child.kill(); + let _ = child.wait(); + } + } +} + +impl Drop for Fleet { + fn drop(&mut self) { + for i in 0..self.nodes.len() { + self.kill(i); + } + let _ = Command::new("docker") + .args(["compose", "-p", &self.project, "-f"]) + .arg(self.dir.join("s3-compose.yaml")) + .args(["down", "-v"]) + .output(); + if std::thread::panicking() { + eprintln!("fleet logs kept in {}", self.dir.display()); + } else { + let _ = std::fs::remove_dir_all(&self.dir); + } + } +} + +/// Drop `//` line comments (wrangler.jsonc). +fn strip_comments(text: &str) -> String { + text.lines() + .filter(|line| !line.trim_start().starts_with("//")) + .collect::>() + .join("\n") +} diff --git a/distributed_game/tests/support/realm.rs b/distributed_game/tests/support/realm.rs new file mode 100644 index 000000000..e355f09a3 --- /dev/null +++ b/distributed_game/tests/support/realm.rs @@ -0,0 +1,202 @@ +//! Test zone for world-structure tests: handoff, tier-up events, +//! hibernation, gates and freeze readiness. + +#![allow(dead_code)] + +use distributed_game::*; + +/// Input commands (first payload byte). +pub const CMD_HANDOFF: u8 = 1; +pub const CMD_BOSS: u8 = 2; +pub const CMD_COUNT: u8 = 3; + +/// Event type ids sent to players. +pub const EV_JOINED: u32 = 1; +pub const EV_ARRIVED: u32 = 2; + +#[derive(Debug, Clone, Default)] +pub struct RealmConfig { + pub gate: bool, + pub freeze_ready: bool, + pub neighbour: Option, + pub reject_all: bool, + /// Emit `realm.left` / `realm.arrived` facts for handoffs. + pub move_facts: bool, +} + +impl RealmConfig { + pub fn new() -> Self { + Self { + freeze_ready: true, + ..Self::default() + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Arrival { + pub principal: String, + pub from: String, + pub carried: Vec, +} + +pub struct Realm { + pub cfg: RealmConfig, + pub counter: u32, + pub restored_from: Option, + pub arrivals: Vec, + pub child_events: Vec, + pub left: Vec<(PlayerId, LeaveReason)>, + pub versions: Vec<(String, String)>, + pub handoff_errors: Vec, +} + +impl Zone for Realm { + type Config = RealmConfig; + type Input = u8; + type Timer = (); + type Message = distributed_game::NoMessages; + + fn schema() -> EntitySchema { + EntitySchema::new().kind(KindDef::new(1, "realm").field("counter", FieldType::U32)) + } + + fn on_create(_ctx: &mut Ctx<'_, Self>, cfg: RealmConfig) -> Self { + Self { + cfg, + counter: 0, + restored_from: None, + arrivals: Vec::new(), + child_events: Vec::new(), + left: Vec::new(), + versions: Vec::new(), + handoff_errors: Vec::new(), + } + } + + fn on_auth(&mut self, _ctx: &mut Ctx<'_, Self>, _req: &JoinRequest<'_>) -> Admission { + if self.cfg.reject_all { + Admission::Reject("closed for repairs".into()) + } else { + Admission::Admit + } + } + + fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + ctx.send_event(player, EV_JOINED, self.counter.to_le_bytes().to_vec()); + } + + fn on_handoff_join( + &mut self, + ctx: &mut Ctx<'_, Self>, + player: PlayerId, + from_zone: &str, + carried: Vec, + ) { + let principal = ctx + .player(player) + .map(|p| p.principal.clone()) + .unwrap_or_default(); + if self.cfg.move_facts { + let key = format!("arrived:{}:{principal}", ctx.zone_id()); + let fact = Fact::new( + key, + "realm.arrived", + serde_json::json!({ "from": from_zone }), + ); + let _ = ctx.emit_fact_for(player, fact); + } + let carried = distributed_game::codec::from_bytes::(&carried) + .unwrap_or_default() + .into_bytes(); + let mut payload = carried.clone(); + payload.extend_from_slice(b"|"); + payload.extend_from_slice(from_zone.as_bytes()); + ctx.send_event(player, EV_ARRIVED, payload); + self.arrivals.push(Arrival { + principal, + from: from_zone.to_string(), + carried, + }); + } + + fn on_leave(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId, reason: LeaveReason) { + if self.cfg.move_facts && reason == LeaveReason::Handoff { + let key = format!("left:{}:{}", ctx.zone_id(), player.0); + let _ = ctx.emit_fact(Fact::new(key, "realm.left", serde_json::json!({}))); + } + self.left.push((player, reason)); + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { + payload.first().copied() + } + + fn on_tick(&mut self, ctx: &mut Ctx<'_, Self>) { + let players: Vec<_> = ctx.players().map(|p| (p.id, p.principal.clone())).collect(); + for (player, principal) in players { + for input in ctx.take_inputs(player, ConsumePolicy::Drain) { + match input.input { + CMD_HANDOFF => { + let Some(target) = self.cfg.neighbour.clone() else { + continue; + }; + let carried = format!("{principal}:gold={}", self.counter); + if let Err(e) = ctx.handoff(player, &target, &carried) { + self.handoff_errors.push(e); + } + } + CMD_BOSS => { + let zone = ctx.zone_id().to_string(); + ctx.emit_upward("boss_defeated", zone.into_bytes(), ChildEvent::TO_ROOT); + } + CMD_COUNT => { + self.counter += 1; + let key = format!("count:{}:{}", ctx.zone_id(), self.counter); + let _ = ctx.emit_fact_for( + player, + Fact::new(key, "realm.count", serde_json::json!({"n": self.counter})), + ); + } + _ => {} + } + } + } + } + + fn replicate(&self, out: &mut WorldView) { + out.push(EntityState::new(1, 1, 0.0, 0.0, vec![FieldValue::U(self.counter)]).global()); + } + + fn on_dispose(&mut self, ctx: &mut Ctx<'_, Self>) { + let key = format!("dispose:{}:{}", ctx.zone_id(), self.counter); + let _ = ctx.emit_fact(Fact::new(key, "realm.disposed", serde_json::json!({}))); + } + + fn hibernate(&self) -> Option> { + Some(self.counter.to_le_bytes().to_vec()) + } + + fn on_restore(&mut self, _ctx: &mut Ctx<'_, Self>, state: &[u8], saved_version: &str) { + if let Ok(bytes) = <[u8; 4]>::try_from(state) { + self.counter = u32::from_le_bytes(bytes); + self.restored_from = Some(saved_version.to_string()); + } + } + + fn on_child_event(&mut self, _ctx: &mut Ctx<'_, Self>, event: &ChildEvent) { + self.child_events.push(event.clone()); + } + + fn is_gate(&self) -> bool { + self.cfg.gate + } + + fn freeze_ready(&self) -> bool { + self.cfg.freeze_ready + } + + fn on_content_version_changed(&mut self, _ctx: &mut Ctx<'_, Self>, from: &str, to: &str) { + self.versions.push((from.to_string(), to.to_string())); + } +} diff --git a/distributed_game/tests/world/main.rs b/distributed_game/tests/world/main.rs new file mode 100644 index 000000000..600247206 --- /dev/null +++ b/distributed_game/tests/world/main.rs @@ -0,0 +1,1422 @@ +//! Two GameServers in one process on different ports: cross-host handoff +//! with a real WebSocket client, tier-up events across hosts, hibernation, +//! fenced ownership and the world content barrier. Hibernation runs on +//! celld (`CellZoneOwnership` + `CellZoneStateStore` against +//! `tests/celld/fact-worker`; skipped unless the worker is built and celld +//! starts, required with `CELLD_FACTS_REQUIRED=1`). + +#[path = "../support/celld.rs"] +mod celld_support; +#[path = "../support/realm.rs"] +mod realm; + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use distributed::lease::InMemoryLeaseStore; +use distributed_game::net::{ + AbortNotes, GameServer, InternalHttpSecret, RemoteHost, RolloutError, ServerConfig, TicketKey, + WorldCoordinator, ZoneFactory, +}; +use distributed_game::protocol::{error, kick, Hello, Notice}; +use distributed_game::world::{ + FencedLeaseOwnership, HostAddr, LocalOwnership, StaticDirectory, ZoneDirectory, ZoneOwnership, + ZoneStateStore, +}; +use distributed_game::*; +use futures_util::{SinkExt, StreamExt}; +use realm::*; +use tokio::net::TcpStream; +use tokio_tungstenite::tungstenite::Message; +use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream}; + +type Ws = WebSocketStream>; + +const SECRET: &str = "world-secret"; +const ADMIN: &str = "world-test-internal-secret-0123456789"; + +fn admin() -> InternalHttpSecret { + InternalHttpSecret::new(ADMIN).unwrap() +} + +fn ticket(principal: &str, zone: &str, nonce: &str) -> String { + TicketKey::new(SECRET).sign(&TicketClaims { + principal: principal.into(), + zone: zone.into(), + expires_at: 4_000_000_000, + nonce: nonce.into(), + role: Role::Player, + name: None, + extensions: Default::default(), + wake: false, + }) +} + +struct Node { + server: GameServer, + addr: HostAddr, + sink: MemoryFactSink, +} + +type Factory = Arc Option + Send + Sync>; + +fn base_config() -> ServerConfig { + let mut config = ServerConfig::new(TicketKey::new(SECRET)); + config.host.tick_rate = 30; + config.host.patch_rate = 10; + config.admin_secret = Some(admin()); + config +} + +async fn listen() -> (tokio::net::TcpListener, String) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap().to_string(); + (listener, addr) +} + +fn serve(server: &GameServer, listener: tokio::net::TcpListener) { + let serving = server.clone(); + tokio::spawn(async move { + serving + .serve(listener, std::future::pending()) + .await + .unwrap(); + }); +} + +/// Start two hosts "A" and "B" sharing a directory and ownership. +async fn two_hosts( + config: impl Fn() -> ServerConfig, + assign: &[(&str, &str)], + factory: Factory, + ownership: Arc, +) -> (Node, Node, Arc) { + let (la, a_addr) = listen().await; + let (lb, b_addr) = listen().await; + let a = HostAddr::new("A", &a_addr); + let b = HostAddr::new("B", &b_addr); + let dir = Arc::new(StaticDirectory::new()); + dir.add_host(a.clone()).add_host(b.clone()); + for (zone, host) in assign { + dir.assign(*zone, *host); + } + dir.fallback("A"); + let mut nodes = Vec::new(); + for (host, listener) in [(a, la), (b, lb)] { + let sink = MemoryFactSink::new(); + let f = factory.clone(); + let server = GameServer::::new(config(), ZoneFactory::sync(move |a| f(&a.zone_id))) + .with_fact_sink(sink.clone(), 64, RetryPolicy::default()) + .with_host_id(host.id.clone()) + .with_directory(dir.clone()) + .with_ownership(ownership.clone()); + serve(&server, listener); + nodes.push(Node { + server, + addr: host, + sink, + }); + } + let b = nodes.pop().unwrap(); + let a = nodes.pop().unwrap(); + (a, b, dir) +} + +async fn send(ws: &mut Ws, msg: ClientMessage) { + ws.send(Message::Binary(msg.encode().into())).await.unwrap(); +} + +async fn hello(ws: &mut Ws, ticket: &str, token: &str, version: &str) { + send( + ws, + ClientMessage::Hello(Hello { + protocol_version: PROTOCOL_VERSION, + content_version: version.into(), + capabilities: 0, + ticket: ticket.into(), + reconnect_token: token.into(), + near: false, + }), + ) + .await; +} + +async fn next(ws: &mut Ws, mirror: &mut ClientMirror) -> Option { + loop { + let frame = tokio::time::timeout(Duration::from_secs(5), ws.next()) + .await + .expect("server message within 5s")?; + match frame { + Ok(Message::Binary(bytes)) => return Some(mirror.apply(&bytes).unwrap()), + Ok(Message::Close(_)) | Err(_) => return None, + Ok(_) => continue, + } + } +} + +/// Next message that is not a Delta. +async fn next_control(ws: &mut Ws, mirror: &mut ClientMirror) -> Option { + loop { + match next(ws, mirror).await? { + ServerMessage::Delta(_) => continue, + other => return Some(other), + } + } +} + +async fn connect(url: &str) -> Ws { + connect_async(url).await.unwrap().0 +} + +struct Client { + ws: Ws, + mirror: ClientMirror, + welcome: protocol::Welcome, +} + +/// Connect to `url` (a zone URL), following Redirects, and expect Welcome. +#[allow(clippy::result_large_err)] +async fn join_url(url: &str, ticket: &str, version: &str) -> Result { + let mut url = url.to_string(); + for _ in 0..3 { + let mut ws = connect(&url).await; + hello(&mut ws, ticket, "", version).await; + let mut mirror = ClientMirror::new(); + match next_control(&mut ws, &mut mirror).await.expect("reply") { + ServerMessage::Welcome(welcome) => { + return Ok(Client { + ws, + mirror, + welcome, + }) + } + ServerMessage::Redirect { url: to, .. } => url = to, + other => return Err(other), + } + } + panic!("redirect loop") +} + +async fn control(client: &mut Client) -> Option { + next_control(&mut client.ws, &mut client.mirror).await +} + +/// Next Freeze/Resume/Kick/Error (skips Deltas and game Events). +async fn next_notice(client: &mut Client) -> Option { + loop { + match control(client).await? { + ServerMessage::Event { .. } => continue, + other => return Some(other), + } + } +} + +async fn input(client: &mut Client, seq: u32, cmd: u8) { + send( + &mut client.ws, + ClientMessage::Input { + seq, + client_tick: 0, + payload: vec![cmd], + }, + ) + .await; +} + +async fn eventually(what: &str, mut check: F) +where + F: FnMut() -> Fut, + Fut: std::future::Future, +{ + for _ in 0..200 { + if check().await { + return; + } + tokio::time::sleep(Duration::from_millis(25)).await; + } + panic!("timed out waiting for {what}"); +} + +fn realm_factory( + neighbours: &[(&'static str, &'static str)], + rejecting: &'static [&'static str], +) -> Factory { + let neighbours: Vec<(String, String)> = neighbours + .iter() + .map(|(a, b)| (a.to_string(), b.to_string())) + .collect(); + Arc::new(move |zone: &str| { + if !zone.starts_with("realm") && !zone.starts_with('z') { + return None; + } + Some(RealmConfig { + neighbour: neighbours + .iter() + .find(|(from, _)| from == zone) + .map(|(_, to)| to.clone()), + reject_all: rejecting.contains(&zone), + gate: zone.ends_with(".inn"), + freeze_ready: !zone.ends_with(".stuck"), + move_facts: false, + }) + }) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn cross_host_handoff_follows_redirect_and_ticket_is_single_use() { + let (a, b, _dir) = two_hosts( + base_config, + &[("realm.east", "A"), ("realm.west", "B")], + realm_factory(&[("realm.east", "realm.west")], &[]), + Arc::new(LocalOwnership::new()), + ) + .await; + + // Asking B for an A zone redirects without consuming the ticket. + let t = ticket("ana", "realm.east", "n1"); + let mut ana = join_url(&b.addr.zone_url("realm.east"), &t, "") + .await + .unwrap(); + assert_eq!(ana.welcome.zone_id, "realm.east"); + assert!(a.server.is_active("realm.east")); + assert!(!b.server.is_active("realm.east")); + + for seq in 1..=2 { + input(&mut ana, seq, CMD_COUNT).await; + } + input(&mut ana, 3, CMD_HANDOFF).await; + let (target, transfer) = loop { + match control(&mut ana).await { + Some(ServerMessage::Handoff { + target_zone, + transfer_ticket, + }) => break (target_zone, transfer_ticket), + Some(_) => continue, + None => panic!("closed before Handoff"), + } + }; + assert_eq!(target, "realm.west"); + // The source fenced the player out before the ticket was usable. + assert_eq!( + a.server.inspect("realm.east", |h| h.player_count()).await, + Some(0) + ); + + // Client follows: same host first (Redirect to B), then B admits. + let mut west = join_url(&a.addr.zone_url(&target), &transfer, "") + .await + .unwrap(); + assert_eq!(west.welcome.zone_id, "realm.west"); + let arrived = loop { + match control(&mut west).await.unwrap() { + ServerMessage::Event { type_id, payload } if type_id == EV_ARRIVED => break payload, + _ => continue, + } + }; + assert_eq!(arrived, b"ana:gold=2|realm.east"); + let arrivals = b + .server + .inspect("realm.west", |h| h.zone().arrivals.clone()) + .await + .unwrap(); + assert_eq!(arrivals[0].principal, "ana"); + + // Single use: neither the target nor the source accepts it again. + match join_url(&b.addr.zone_url("realm.west"), &transfer, "").await { + Err(ServerMessage::Error { code, .. }) => assert_eq!(code, error::UNAUTHORIZED), + other => panic!("replay admitted: {:?}", other.map(|c| c.welcome)), + } + match join_url(&a.addr.zone_url("realm.east"), &transfer, "").await { + Err(ServerMessage::Error { code, .. }) => assert_eq!(code, error::UNAUTHORIZED), + other => panic!( + "return after arrival admitted: {:?}", + other.map(|c| c.welcome) + ), + } + // A forged transfer (wrong key) is refused. + let forged = TicketKey::new("nope").sign(&TicketClaims { + principal: "mallory".into(), + zone: "realm.west".into(), + expires_at: 4_000_000_000, + nonce: "x".into(), + role: Role::Player, + name: None, + extensions: Default::default(), + wake: false, + }); + assert!(join_url(&b.addr.zone_url("realm.west"), &forged, "") + .await + .is_err()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn redirects_use_the_configured_public_url() { + let (_a, b, _dir) = two_hosts( + || { + base_config().with_redirect_url(|host, zone| { + format!("wss://game.example/hosts/{}/zones/{zone}", host.id) + }) + }, + &[("realm.east", "A")], + realm_factory(&[], &[]), + Arc::new(LocalOwnership::new()), + ) + .await; + let mut ws = connect(&b.addr.zone_url("realm.east")).await; + hello(&mut ws, &ticket("ana", "realm.east", "pub-1"), "", "").await; + let mut mirror = ClientMirror::new(); + match next_control(&mut ws, &mut mirror).await { + Some(ServerMessage::Redirect { zone_id, url }) => { + assert_eq!(zone_id, "realm.east"); + assert_eq!(url, "wss://game.example/hosts/A/zones/realm.east"); + } + other => panic!("expected Redirect, got {other:?}"), + } + // Per-host advertised URL in the directory (no mapping configured). + let proxied = HostAddr::new("A", "10.0.0.2:2567").with_ws_url("wss://game.example/a/"); + assert_eq!(proxied.zone_url("z"), "wss://game.example/a/zones/z"); + assert_eq!(proxied.admin_url, "http://10.0.0.2:2567"); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn refused_handoff_returns_to_source_with_carried_state() { + let (a, b, _dir) = two_hosts( + base_config, + &[("realm.east", "A"), ("realm.west", "B")], + realm_factory(&[("realm.east", "realm.west")], &["realm.west"]), + Arc::new(LocalOwnership::new()), + ) + .await; + let mut ana = join_url( + &a.addr.zone_url("realm.east"), + &ticket("ana", "realm.east", "r1"), + "", + ) + .await + .unwrap(); + input(&mut ana, 1, CMD_COUNT).await; + input(&mut ana, 2, CMD_HANDOFF).await; + let transfer = loop { + if let Some(ServerMessage::Handoff { + transfer_ticket, .. + }) = control(&mut ana).await + { + break transfer_ticket; + } + }; + // Target refuses (zone closed) -> policy: return to the source. + match join_url(&b.addr.zone_url("realm.west"), &transfer, "").await { + Err(ServerMessage::Error { code, .. }) => assert_eq!(code, error::REJECTED), + other => panic!("expected rejection: {:?}", other.map(|c| c.welcome)), + } + let mut back = join_url(&a.addr.zone_url("realm.east"), &transfer, "") + .await + .unwrap(); + let arrived = loop { + match control(&mut back).await.unwrap() { + ServerMessage::Event { type_id, payload } if type_id == EV_ARRIVED => break payload, + _ => continue, + } + }; + // Carried state comes back; `from` is the zone it never reached. + assert_eq!(arrived, b"ana:gold=1|realm.west"); + // Once returned, the ticket is dead at the target too. + assert!(join_url(&b.addr.zone_url("realm.west"), &transfer, "") + .await + .is_err()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn refused_handoff_returns_to_a_source_on_the_same_host() { + // Source and target share a host (and its nonce replay cache): the + // target saw the ticket first, the return must still be admitted once. + let (a, _b, _dir) = two_hosts( + base_config, + &[("realm.east", "A"), ("realm.west", "A")], + realm_factory(&[("realm.east", "realm.west")], &["realm.west"]), + Arc::new(LocalOwnership::new()), + ) + .await; + let mut ana = join_url( + &a.addr.zone_url("realm.east"), + &ticket("ana", "realm.east", "s1"), + "", + ) + .await + .unwrap(); + input(&mut ana, 1, CMD_HANDOFF).await; + let transfer = loop { + if let Some(ServerMessage::Handoff { + transfer_ticket, .. + }) = control(&mut ana).await + { + break transfer_ticket; + } + }; + match join_url(&a.addr.zone_url("realm.west"), &transfer, "").await { + Err(ServerMessage::Error { code, .. }) => assert_eq!(code, error::REJECTED), + other => panic!("expected rejection: {:?}", other.map(|c| c.welcome)), + } + let back = join_url(&a.addr.zone_url("realm.east"), &transfer, "").await; + assert!(back.is_ok(), "return admitted: {:?}", back.err()); + // The return is single use. + assert!(join_url(&a.addr.zone_url("realm.east"), &transfer, "") + .await + .is_err()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn boss_defeat_tiers_up_to_parent_and_grandparent_across_hosts() { + let (a, b, _dir) = two_hosts( + base_config, + &[ + ("realm", "A"), + ("realm.east", "A"), + ("realm.east.keep", "B"), + ], + realm_factory(&[], &[]), + Arc::new(LocalOwnership::new()), + ) + .await; + let mut ana = join_url( + &b.addr.zone_url("realm.east.keep"), + &ticket("ana", "realm.east.keep", "b1"), + "", + ) + .await + .unwrap(); + input(&mut ana, 1, CMD_BOSS).await; + for zone in ["realm.east", "realm"] { + let server = a.server.clone(); + eventually(zone, || { + let server = server.clone(); + async move { + server + .inspect(zone, |h| { + h.zone().child_events.iter().any(|e| { + e.kind == "boss_defeated" && e.origin_zone == "realm.east.keep" + }) + }) + .await + .unwrap_or(false) + } + }) + .await; + } + let grand = a + .server + .inspect("realm", |h| h.zone().child_events.clone()) + .await + .unwrap(); + assert_eq!(grand.len(), 1); + assert_eq!(grand[0].from_zone, "realm.east"); + assert_eq!(grand[0].payload, b"realm.east.keep"); + // Parents were activated on demand on their owning host only. + assert!(!b.server.is_active("realm.east")); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn dormant_zone_hibernates_to_celld_and_restores() { + let Some(celld) = celld_support::Celld::start_new() else { + return; + }; + let (ownership, store) = on_celld(&celld, "host-a"); + let mut config = base_config(); + config.host.idle_tick_rate = None; + config.host.dormant_after = Duration::from_millis(50); + config.hibernate_after = Some(Duration::from_millis(100)); + let sink = MemoryFactSink::new(); + let (listener, addr) = listen().await; + let factory = realm_factory(&[], &[]); + let server = GameServer::::new(config, ZoneFactory::sync(move |a| factory(&a.zone_id))) + .with_fact_sink(sink.clone(), 64, RetryPolicy::default()) + .with_ownership(ownership) + .with_state_store(store.clone()); + serve(&server, listener); + let url = format!("ws://{addr}/zones/realm.vault"); + + let mut ana = join_url(&url, &ticket("ana", "realm.vault", "h1"), "") + .await + .unwrap(); + for seq in 1..=3 { + input(&mut ana, seq, CMD_COUNT).await; + } + eventually("three counts", || { + let server = server.clone(); + async move { server.inspect("realm.vault", |h| h.zone().counter).await == Some(3) } + }) + .await; + send(&mut ana.ws, ClientMessage::Leave).await; + // The zone leaves the active set before its snapshot is written, so wait + // for the save itself. + eventually("hibernation save", || { + let server = server.clone(); + async move { !server.is_active("realm.vault") && hibernation_outcomes(&server) >= 1 } + }) + .await; + let saved = store + .load("realm.vault") + .await + .unwrap() + .expect("snapshot stored"); + assert_eq!(saved.state, 3u32.to_le_bytes()); + // Facts emitted while disposing were still committed. + eventually("dispose fact", || { + let sink = sink.clone(); + async move { + sink.committed() + .iter() + .any(|f| f.key() == "dispose:realm.vault:3") + } + }) + .await; + assert_eq!( + sink.committed() + .iter() + .filter(|f| f.command() == "realm.count") + .count(), + 3 + ); + + // Next activation restores it. + let mut again = join_url(&url, &ticket("ana", "realm.vault", "h2"), "") + .await + .unwrap(); + let counter = loop { + match control(&mut again).await.unwrap() { + ServerMessage::Event { type_id, payload } if type_id == EV_JOINED => { + break u32::from_le_bytes(payload.try_into().unwrap()) + } + _ => continue, + } + }; + assert_eq!(counter, 3); +} + +/// Zone ownership and hibernation snapshots in celld cells. +fn on_celld( + celld: &celld_support::Celld, + host: &str, +) -> ( + Arc, + Arc, +) { + let secret = || distributed::cell_host::InternalHttpSecret::new(celld_support::SECRET).unwrap(); + ( + Arc::new( + distributed_game::celld::CellZoneOwnership::new( + celld.base(), + secret(), + "world-test", + host, + ) + .unwrap(), + ), + Arc::new( + distributed_game::celld::CellZoneStateStore::new( + celld.base(), + secret(), + "world-test", + host, + ) + .unwrap(), + ), + ) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn hibernation_saves_succeed_after_a_host_restart_on_the_same_store() { + let Some(celld) = celld_support::Celld::start_new() else { + return; + }; + let url_of = |addr: &str| format!("ws://{addr}/zones/realm.keep"); + let mut epochs = Vec::new(); + let mut count = 0u32; + for run in 1..=2 { + // A fresh process: new store and ownership handles (the fencing + // tokens live in the celld lease cell, so they keep growing). + let (ownership, store) = on_celld(&celld, &format!("host-{run}")); + let mut config = base_config(); + config.host.idle_tick_rate = None; + config.host.dormant_after = Duration::from_millis(50); + config.hibernate_after = Some(Duration::from_millis(100)); + let (listener, addr) = listen().await; + let factory = realm_factory(&[], &[]); + let server = + GameServer::::new(config, ZoneFactory::sync(move |a| factory(&a.zone_id))) + .with_ownership(ownership) + .with_state_store(store.clone()); + serve(&server, listener); + // Two activations per run, so the first run's last token exceeds + // the restarted run's first token unless tokens survive restarts. + for cycle in 1..=2u64 { + let nonce = format!("r{run}-{cycle}"); + let mut ana = join_url(&url_of(&addr), &ticket("ana", "realm.keep", &nonce), "") + .await + .unwrap(); + input(&mut ana, 1, CMD_COUNT).await; + count += 1; + let expected = count; + eventually("count", || { + let server = server.clone(); + async move { + server.inspect("realm.keep", |h| h.zone().counter).await == Some(expected) + } + }) + .await; + epochs.push( + server + .inspect("realm.keep", |h| h.config().boot_epoch) + .await + .unwrap(), + ); + send(&mut ana.ws, ClientMessage::Leave).await; + // Saved, stale or error: the assertions below say which. + eventually("hibernation save", || { + let server = server.clone(); + async move { !server.is_active("realm.keep") && hibernation_outcomes(&server) >= cycle } + }) + .await; + assert_eq!(server.metrics().hibernation_saves("stale"), 0, "run {run}"); + assert_eq!( + server.metrics().hibernation_saves("saved"), + cycle, + "run {run}" + ); + let saved = store.load("realm.keep").await.unwrap().expect("snapshot"); + assert_eq!(saved.state, count.to_le_bytes(), "run {run} saved"); + } + assert!(server + .metrics() + .render() + .contains("distributed_game_hibernation_saves_total{outcome=\"saved\"} 2")); + server.shutdown(); + } + assert!( + epochs.windows(2).all(|w| w[1] > w[0]), + "epochs grow: {epochs:?}" + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn fenced_lease_keeps_zone_on_one_host_and_loss_stops_it() { + let clock = distributed::ManualClock::starting_now(); + let leases = InMemoryLeaseStore::with_clock(clock.clone()); + let ownership: Arc = Arc::new(FencedLeaseOwnership::new(leases)); + let config = || { + let mut c = base_config(); + c.ownership_ttl = Duration::from_secs(10); + c.ownership_renew_every = Duration::from_millis(50); + c.activation_timeout = Duration::from_millis(200); + c + }; + // No directory: both hosts would happily serve any zone. + let mut nodes = Vec::new(); + for id in ["A", "B"] { + let (listener, addr) = listen().await; + let f = realm_factory(&[], &[]); + let server = GameServer::::new(config(), ZoneFactory::sync(move |a| f(&a.zone_id))) + .with_host_id(id) + .with_ownership(ownership.clone()); + serve(&server, listener); + nodes.push((server, addr)); + } + let url = |i: usize| format!("ws://{}/zones/zboss", nodes[i].1); + + let mut ana = join_url(&url(0), &ticket("ana", "zboss", "l1"), "") + .await + .unwrap(); + match join_url(&url(1), &ticket("bo", "zboss", "l2"), "").await { + Err(ServerMessage::Error { code, message }) => { + assert_eq!(code, error::ZONE_UNAVAILABLE); + assert!(message.contains("owned by A#"), "{message}"); + } + other => panic!("second host ran the zone: {:?}", other.map(|c| c.welcome)), + } + + // A stalls past its TTL (e.g. paused); its next renewal fails and the + // zone stops there. + clock.advance(Duration::from_secs(11)); + let kicked = loop { + match control(&mut ana).await { + Some(ServerMessage::Kick { code, .. }) => break code, + Some(_) => continue, + None => panic!("closed without Kick"), + } + }; + assert_eq!(kicked, kick::ZONE_DISPOSED); + let a = nodes[0].0.clone(); + eventually("A stops", || { + let a = a.clone(); + async move { !a.is_active("zboss") } + }) + .await; + // Now B may own it. + let bo = join_url(&url(1), &ticket("bo", "zboss", "l3"), "") + .await + .unwrap(); + assert_eq!(bo.welcome.zone_id, "zboss"); +} + +fn versioned(version: &'static str) -> impl Fn() -> ServerConfig { + move || { + let mut c = base_config(); + c.host.content_version = version.into(); + c + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn rolling_commit_reloads_stale_clients_in_gates_and_apply_may_await() { + let safe_room = || { + let mut c = base_config(); + c.host.content_version = "v1".into(); + c.host.stale_policy = StalePolicy::SafeRoom { roam: false }; + c + }; + let (a, _b, _dir) = two_hosts( + safe_room, + &[("realm.inn", "A"), ("realm.field", "A")], + realm_factory(&[], &[]), + Arc::new(LocalOwnership::new()), + ) + .await; + let mut inn = join_url( + &a.addr.zone_url("realm.inn"), + &ticket("ina", "realm.inn", "g1"), + "v1", + ) + .await + .unwrap(); + let mut field = join_url( + &a.addr.zone_url("realm.field"), + &ticket("fey", "realm.field", "g2"), + "v1", + ) + .await + .unwrap(); + let server = a.server.clone(); + let coordinator = WorldCoordinator::new(Duration::from_secs(2)) + .participant(Arc::new(a.server.clone())) + .with_abort_notes(AbortNotes { + not_acked: "the ritual held the world".into(), + apply_failed: "CDN said: {error}".into(), + }); + + // Async apply that fails: everyone resumes on v1 with the custom note. + let failed = coordinator + .rollout_async("v2", "", BarrierMode::Rolling, |_v| async { + tokio::time::sleep(Duration::from_millis(20)).await; + Err("pack missing".to_string()) + }) + .await; + assert_eq!( + failed, + Err(RolloutError::ApplyFailed("pack missing".into())) + ); + for c in [&mut inn, &mut field] { + assert!(matches!( + next_notice(c).await, + Some(ServerMessage::Freeze(_)) + )); + let resumed = next_notice(c).await; + assert!( + matches!(&resumed, Some(ServerMessage::Resume(n)) + if n.version == "v1" && n.notes == "CDN said: pack missing"), + "{resumed:?}" + ); + } + + // Async apply observed while every zone is frozen, then a rolling commit. + let report = coordinator + .rollout_async("v2", "ice", BarrierMode::Rolling, |v| async move { + tokio::time::sleep(Duration::from_millis(100)).await; + let frozen = server.inspect("realm.inn", |h| h.is_frozen()).await; + assert_eq!(frozen, Some(true), "zones stay frozen while applying {v}"); + Ok(()) + }) + .await + .unwrap(); + assert_eq!(report.version, "v2"); + for c in [&mut inn, &mut field] { + assert!(matches!( + next_notice(c).await, + Some(ServerMessage::Freeze(_)) + )); + assert!(matches!( + next_notice(c).await, + Some(ServerMessage::Resume(n)) if n.version == "v2" + )); + } + // The stale client already inside the gate reloads there ... + match next_notice(&mut inn).await { + Some(ServerMessage::Kick { code, .. }) => assert_eq!(code, kick::RELOAD), + other => panic!("expected Kick(RELOAD), got {other:?}"), + } + // ... the one in the field keeps playing its old version. + let field_connected = a + .server + .inspect("realm.field", |h| h.players().all(|p| p.connected)) + .await; + assert_eq!(field_connected, Some(true)); + // The reloaded client reconnects with its token on v2. + let mut back = connect(&a.addr.zone_url("realm.inn")).await; + hello(&mut back, "", &inn.welcome.reconnect_token, "v2").await; + let mut mirror = ClientMirror::new(); + assert!(matches!( + next_control(&mut back, &mut mirror).await, + Some(ServerMessage::Welcome(w)) if w.content_version == "v2" + )); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn world_barrier_freezes_applies_and_resumes_across_hosts() { + let (a, b, _dir) = two_hosts( + versioned("v1"), + &[("realm.a1", "A"), ("realm.a2", "A"), ("realm.b1", "B")], + realm_factory(&[], &[]), + Arc::new(LocalOwnership::new()), + ) + .await; + let mut clients = Vec::new(); + for (i, zone) in ["realm.a1", "realm.a2", "realm.b1"].into_iter().enumerate() { + let host = if zone.ends_with("b1") { &b } else { &a }; + let c = join_url( + &host.addr.zone_url(zone), + &ticket(&format!("p{i}"), zone, &format!("w{i}")), + "v1", + ) + .await + .unwrap(); + clients.push(c); + } + + // Prepare only on A: frozen zones drop (and count) inputs. + let notice = Notice { + reason: "content_update".into(), + version: "v2".into(), + notes: String::new(), + }; + a.server + .prepare_barrier(1, notice.clone(), Duration::from_secs(2)) + .await + .unwrap(); + assert!(matches!( + next_notice(&mut clients[0]).await, + Some(ServerMessage::Freeze(n)) if n.version == "v2" + )); + input(&mut clients[0], 1, CMD_COUNT).await; + let server = a.server.clone(); + eventually("dropped input counted", || { + let server = server.clone(); + async move { + server + .inspect("realm.a1", |h| h.inputs_dropped_frozen()) + .await + .unwrap_or(0) + >= 1 + } + }) + .await; + // Per-zone metrics count frozen drops under their own outcome. + assert!(a + .server + .metrics() + .render() + .contains("distributed_game_zone_inputs_total{zone=\"realm.a1\",outcome=\"frozen\"} 1")); + // /metrics coexists with the admin routes on the same router. + let status = reqwest::Client::new() + .post(format!("{}/admin/barrier/nope", a.addr.admin_url)) + .header("x-distributed-internal-secret", ADMIN) + .json(&serde_json::json!({})) + .send() + .await + .unwrap() + .status(); + assert_eq!(status, 404); + assert!(a.server.abort_barrier(1, "test").await); + assert!(matches!( + next_notice(&mut clients[0]).await, + Some(ServerMessage::Resume(n)) if n.version == "v1" + )); + assert_eq!( + a.server.inspect("realm.a1", |h| h.zone().counter).await, + Some(0), + "input sent while frozen was not simulated" + ); + // realm.a2 (also on A) went through the same aborted barrier. + assert!(matches!( + next_notice(&mut clients[1]).await, + Some(ServerMessage::Freeze(_)) + )); + assert!( + matches!(next_notice(&mut clients[1]).await, Some(ServerMessage::Resume(n)) if n.version == "v1") + ); + + // Full rollout through the coordinator: A local, B over admin HTTP. + let applied = Arc::new(Mutex::new(Vec::new())); + let log = applied.clone(); + let coordinator = WorldCoordinator::new(Duration::from_secs(2)) + .participant(Arc::new(a.server.clone())) + .participant(Arc::new(RemoteHost::new(b.addr.clone(), admin()))); + let report = coordinator + .rollout("v2", "new loot tables", BarrierMode::Rolling, |v| { + log.lock().unwrap().push(v.to_string()); + Ok(()) + }) + .await + .unwrap(); + assert_eq!(report.version, "v2"); + assert_eq!(*applied.lock().unwrap(), vec!["v2".to_string()]); + for c in &mut clients { + assert!(matches!( + next_notice(c).await, + Some(ServerMessage::Freeze(n)) if n.version == "v2" + )); + let resumed = next_notice(c).await; + assert!( + matches!( + &resumed, + Some(ServerMessage::Resume(n)) if n.version == "v2" && n.notes == "new loot tables" + ), + "{resumed:?}" + ); + } + assert_eq!(a.server.content_version(), "v2"); + assert_eq!(b.server.content_version(), "v2"); + // Rolling: v1 clients keep playing; facts now carry v2. + input(&mut clients[2], 2, CMD_COUNT).await; + let sink = b.sink.clone(); + eventually("v2 fact", || { + let sink = sink.clone(); + async move { + sink.committed() + .iter() + .any(|f| f.command() == "realm.count" && f.stamp().content_version == "v2") + } + }) + .await; + // New zones activate on v2: a v1 fresh join is told to reload. + match join_url( + &a.addr.zone_url("realm.a3"), + &ticket("late", "realm.a3", "w9"), + "v1", + ) + .await + { + Err(ServerMessage::Error { code, .. }) => assert_eq!(code, error::VERSION_MISMATCH), + other => panic!("stale join admitted: {:?}", other.map(|c| c.welcome)), + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn barrier_aborts_and_resumes_old_version_when_a_zone_never_acks() { + let (a, b, _dir) = two_hosts( + versioned("v1"), + &[("realm.ok", "A"), ("realm.stuck", "B")], + realm_factory(&[], &[]), + Arc::new(LocalOwnership::new()), + ) + .await; + let mut ok = join_url( + &a.addr.zone_url("realm.ok"), + &ticket("p1", "realm.ok", "s1"), + "v1", + ) + .await + .unwrap(); + let mut stuck = join_url( + &b.addr.zone_url("realm.stuck"), + &ticket("p2", "realm.stuck", "s2"), + "v1", + ) + .await + .unwrap(); + let coordinator = WorldCoordinator::new(Duration::from_millis(300)) + .participant(Arc::new(a.server.clone())) + .participant(Arc::new(RemoteHost::new(b.addr.clone(), admin()))); + let mut applied = false; + let err = coordinator + .rollout("v2", "", BarrierMode::Hard, |_| { + applied = true; + Ok(()) + }) + .await + .unwrap_err(); + assert_eq!(err, RolloutError::NotAcked(vec!["B/realm.stuck".into()])); + assert!(!applied); + assert!(matches!( + next_notice(&mut ok).await, + Some(ServerMessage::Freeze(n)) if n.version == "v2" + )); + assert!(matches!( + next_notice(&mut ok).await, + Some(ServerMessage::Resume(n)) if n.version == "v1" + )); + assert_eq!(a.server.content_version(), "v1"); + assert_eq!(b.server.content_version(), "v1"); + // The stuck zone never froze, so its client saw nothing; it keeps + // simulating on v1. + input(&mut stuck, 1, CMD_COUNT).await; + let server = b.server.clone(); + eventually("stuck zone still runs", || { + let server = server.clone(); + async move { + server + .inspect("realm.stuck", |h| (h.zone().counter, h.freeze_state())) + .await + == Some((1, FreezeState::Running)) + } + }) + .await; + // A wrong admin secret is refused. + let wrong = + WorldCoordinator::new(Duration::from_millis(300)).participant(Arc::new(RemoteHost::new( + b.addr.clone(), + InternalHttpSecret::new("not-the-world-test-internal-secret").unwrap(), + ))); + assert!(matches!( + wrong + .rollout("v3", "", BarrierMode::Rolling, |_| Ok(())) + .await, + Err(RolloutError::NotAcked(_)) + )); + assert_eq!(b.server.content_version(), "v1"); +} + +#[test] +fn directory_types_are_object_safe() { + let dir: Arc = Arc::new(StaticDirectory::new()); + assert!(dir.locate("x").is_none()); +} + +/// Hibernation snapshot saves finished so far, whatever their outcome. +fn hibernation_outcomes(server: &GameServer) -> u64 { + let m = server.metrics(); + m.hibernation_saves("saved") + m.hibernation_saves("stale") + m.hibernation_saves("error") +} + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, TicketExtension)] +struct PartyClaims { + party: String, + team: u8, +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn transfer_tickets_carry_extension_claims_across_hosts() { + let (a, b, _dir) = two_hosts( + || { + let mut config = base_config(); + config.admission = config.admission.with_ticket_extensions::(); + config + }, + &[("realm.east", "A"), ("realm.west", "B")], + realm_factory(&[("realm.east", "realm.west")], &[]), + Arc::new(LocalOwnership::new()), + ) + .await; + let party = PartyClaims { + party: "p-9".into(), + team: 1, + }; + let t = TicketKey::new(SECRET).sign( + &TicketClaims::new("ana", "realm.east", 4_000_000_000, "ext-1", Role::Player) + .with_extensions(TicketExtensions::from_typed(&party).unwrap()), + ); + let mut ana = join_url(&a.addr.zone_url("realm.east"), &t, "") + .await + .unwrap(); + input(&mut ana, 1, CMD_HANDOFF).await; + let transfer = loop { + match control(&mut ana).await { + Some(ServerMessage::Handoff { + transfer_ticket, .. + }) => break transfer_ticket, + Some(_) => continue, + None => panic!("closed before Handoff"), + } + }; + // The server-minted transfer ticket signs the claims... + let distributed_game::net::VerifiedTicket::Transfer(verified) = TicketKey::new(SECRET) + .verify_ticket(&transfer, 1_700_000_000) + .unwrap() + else { + panic!("transfer ticket") + }; + assert_eq!( + verified.claims.extensions.typed::().unwrap(), + party + ); + // ...and the target zone on the other host sees them. + let _west = join_url(&a.addr.zone_url("realm.west"), &transfer, "") + .await + .unwrap(); + let players = b + .server + .inspect("realm.west", |h| h.players().cloned().collect::>()) + .await + .unwrap(); + assert_eq!(players[0].principal, "ana"); + assert_eq!(players[0].extensions.typed::().unwrap(), party); +} + +#[tokio::test] +async fn fenced_lease_ownership_passes_the_conformance_suite() { + let ownership = FencedLeaseOwnership::new(InMemoryLeaseStore::new()); + distributed_game::world::ownership_conformance(&ownership, "conformance").await; +} + +/// How a [`Severable`] ownership answers renewals. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Renewals { + /// Passed through. + Pass, + /// A partition: every renewal fails with a backend error. + Fail, + /// A partition that never answers. + Hang, + /// The claim is gone (`Lost`). + Lose, +} + +/// Ownership whose renewals can be cut (a partitioned or crashed host): +/// once cut, nothing is released either. +struct Severable { + inner: Arc, + renewals: Mutex, + /// Acquisitions answered so far. + acquired: std::sync::atomic::AtomicUsize, +} + +impl Severable { + fn new(inner: Arc) -> Arc { + Arc::new(Self { + inner, + renewals: Mutex::new(Renewals::Pass), + acquired: Default::default(), + }) + } + + fn cut(&self, renewals: Renewals) { + *self.renewals.lock().unwrap() = renewals; + } +} + +impl ZoneOwnership for Severable { + fn acquire<'a>( + &'a self, + zone_id: &'a str, + holder: &'a str, + ttl: Duration, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + let answer = self.inner.acquire(zone_id, holder, ttl).await; + self.acquired + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + answer + }) + } + + fn renew<'a>( + &'a self, + claim: &'a world::ZoneClaim, + ttl: Duration, + ) -> BoxFuture<'a, Result> { + match *self.renewals.lock().unwrap() { + Renewals::Pass => self.inner.renew(claim, ttl), + Renewals::Fail => { + Box::pin(async { Err(world::OwnershipError::Backend("partition".into())) }) + } + Renewals::Hang => Box::pin(std::future::pending()), + Renewals::Lose => Box::pin(async { Err(world::OwnershipError::Lost) }), + } + } + + fn release<'a>(&'a self, claim: &'a world::ZoneClaim) -> BoxFuture<'a, ()> { + if *self.renewals.lock().unwrap() == Renewals::Pass { + self.inner.release(claim) + } else { + Box::pin(async {}) + } + } +} + +/// A host that crashed holding a zone (its claim never released) and +/// restarted inside the TTL with the same host id: its first activation +/// must not get the dead incarnation's claim (and fencing token, which is +/// the zone's `boot_epoch`) back, or its fact keys collide with the dead +/// run's and are dropped as replays. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_restarted_host_outranks_its_previous_incarnation() { + let clock = distributed::ManualClock::starting_now(); + let store: Arc = Arc::new(FencedLeaseOwnership::new( + InMemoryLeaseStore::with_clock(clock.clone()), + )); + let start = |ownership: Arc| { + let mut config = base_config(); + config.ownership_ttl = Duration::from_secs(15); + config.activation_timeout = Duration::from_secs(10); + let f = realm_factory(&[], &[]); + GameServer::::new(config, ZoneFactory::sync(move |a| f(&a.zone_id))) + .with_host_id("H") + .with_ownership(ownership) + }; + let crashed = Severable::new(store.clone()); + let before = start(crashed.clone()); + assert!(before.activate("zr").await); + let old = before + .inspect("zr", |h| h.config().boot_epoch) + .await + .unwrap(); + // The process dies: no renewal, no release. + crashed.cut(Renewals::Fail); + + let restarted = Severable::new(store.clone()); + let after = start(restarted.clone()); + assert!(after.begin_activation("zr")); + // The restarted host asks for the claim while the dead one lives ... + eventually("an acquisition attempt", || { + let restarted = restarted.clone(); + async move { restarted.acquired.load(std::sync::atomic::Ordering::SeqCst) > 0 } + }) + .await; + // ... and gets it once the dead claim lapses at the store's TTL. + clock.advance(Duration::from_secs(16)); + let mut new = None; + for _ in 0..400 { + new = after.inspect("zr", |h| h.config().boot_epoch).await; + if new.is_some() { + break; + } + assert!(after.begin_activation("zr")); + tokio::time::sleep(Duration::from_millis(25)).await; + } + let new = new.expect("the restarted host activates the zone"); + assert!(new > old, "restarted epoch {new} <= dead epoch {old}"); + before.shutdown(); + after.shutdown(); +} + +#[tokio::test] +async fn fenced_lease_ownership_passes_the_restart_conformance_suite() { + let clock = distributed::ManualClock::starting_now(); + let ownership = FencedLeaseOwnership::new(InMemoryLeaseStore::with_clock(clock.clone())); + let ttl = Duration::from_secs(10); + distributed_game::world::restart_conformance(&ownership, "restart", ttl, async { + clock.advance(ttl + Duration::from_secs(1)); + }) + .await; +} + +#[tokio::test] +async fn sqlite_lease_ownership_passes_the_restart_conformance_suite() { + use distributed::lease::SqliteLeaseStore; + let pool = sqlx::sqlite::SqlitePoolOptions::new() + .max_connections(1) + .connect("sqlite::memory:") + .await + .unwrap(); + SqliteLeaseStore::migrate(&pool).await.unwrap(); + let ownership = FencedLeaseOwnership::new(SqliteLeaseStore::new(pool)); + distributed_game::world::ownership_conformance(&ownership, "conformance").await; + // The database clock decides expiry: wait it out. + let ttl = Duration::from_millis(200); + distributed_game::world::restart_conformance(&ownership, "restart", ttl, async { + tokio::time::sleep(ttl * 2).await; + }) + .await; +} + +/// A zone whose renewals stop succeeding stops by `ttl - renew_every` +/// after its last successful renewal began (before another host may own +/// it), and commits nothing from then on: neither queued facts nor the +/// facts its disposal emits. +#[tokio::test(start_paused = true)] +async fn a_zone_that_cannot_renew_fences_itself() { + for renewals in [Renewals::Fail, Renewals::Hang, Renewals::Lose] { + let ownership = Severable::new(Arc::new(LocalOwnership::new())); + let sink = MemoryFactSink::new(); + let mut config = base_config(); + config.ownership_ttl = Duration::from_secs(3); + config.ownership_renew_every = Duration::from_secs(1); + let f = realm_factory(&[], &[]); + let server = GameServer::::with_clock( + config, + Arc::new(distributed_game::ManualClock::new()), + ZoneFactory::sync(move |a| f(&a.zone_id)), + ) + .with_fact_sink(sink.clone(), 64, RetryPolicy::default()) + .with_ownership(ownership.clone()); + assert!(server.activate("zf").await); + // Renewals at 1 s and 2 s succeed ... + tokio::time::sleep(Duration::from_millis(2_500)).await; + assert!(server.is_active("zf"), "{renewals:?}: healthy so far"); + // ... the one at 3 s does not: the last success began at 2 s, so + // the zone fences at 2 s + (3 s - 1 s) = 4 s. + ownership.cut(renewals); + tokio::time::sleep(Duration::from_millis(1_400)).await; + if renewals != Renewals::Lose { + assert!( + server.is_active("zf"), + "{renewals:?}: still inside the TTL margin" + ); + } + tokio::time::sleep(Duration::from_millis(200)).await; + assert!(!server.is_active("zf"), "{renewals:?}: fenced at 4 s"); + tokio::time::sleep(Duration::from_secs(5)).await; + assert!( + sink.committed().is_empty(), + "{renewals:?}: committed after the fence: {:?}", + sink.committed() + ); + server.shutdown(); + } +} + +/// A commit or abort for another barrier than the current one (a delayed +/// message from an older rollout) changes nothing. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_stale_barrier_commit_or_abort_is_ignored() { + let factory = realm_factory(&[], &[]); + let server = GameServer::::new( + versioned("v1")(), + ZoneFactory::sync(move |a| factory(&a.zone_id)), + ); + assert!(server.activate("realm.s1").await); + let notice = Notice { + reason: "content_update".into(), + version: "v2".into(), + notes: String::new(), + }; + server + .prepare_barrier(2, notice, Duration::from_secs(2)) + .await + .unwrap(); + let state = |server: GameServer| async move { + server + .inspect("realm.s1", |h| { + (h.is_frozen(), h.config().content_version.clone()) + }) + .await + .unwrap() + }; + assert_eq!(state(server.clone()).await, (true, "v1".to_string())); + assert!( + !server + .commit_barrier(1, "v-old", "", BarrierMode::Rolling) + .await + ); + assert!(!server.abort_barrier(1, "old").await); + assert_eq!( + state(server.clone()).await, + (true, "v1".to_string()), + "a stale commit/abort applied" + ); + assert!( + server + .commit_barrier(2, "v2", "", BarrierMode::Rolling) + .await + ); + assert_eq!(state(server.clone()).await, (false, "v2".to_string())); + server.shutdown(); +} diff --git a/distributed_game/tests/world_host/main.rs b/distributed_game/tests/world_host/main.rs new file mode 100644 index 000000000..87dcb5b46 --- /dev/null +++ b/distributed_game/tests/world_host/main.rs @@ -0,0 +1,559 @@ +//! Host-level world features without a transport: safe-room version +//! policy, handoff issuance, freeze readiness, tier-up forwarding, +//! hibernate/restore hooks and version stamping. + +#[path = "../support/realm.rs"] +mod realm; + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use distributed_game::protocol::{error, kick, Notice}; +use distributed_game::*; +use realm::*; + +fn claims(principal: &str, zone: &str) -> TicketClaims { + TicketClaims { + principal: principal.into(), + zone: zone.into(), + expires_at: u64::MAX, + nonce: format!("n-{principal}"), + role: Role::Player, + name: None, + extensions: Default::default(), + wake: false, + } +} + +fn host(zone: &str, config: HostConfig, clock: &ManualClock, cfg: RealmConfig) -> ZoneHost { + ZoneHost::new(zone, config, Arc::new(clock.clone()), cfg) +} + +fn messages(out: &[Outbound], client: ClientId) -> Vec { + out.iter() + .filter_map(|o| match o { + Outbound::Frame { client: c, frame } if *c == client => { + ServerMessage::decode(frame, &()).ok() + } + _ => None, + }) + .collect() +} + +fn closed(out: &[Outbound], client: ClientId) -> bool { + out.iter() + .any(|o| matches!(o, Outbound::Close { client: c } if *c == client)) +} + +fn safe_room(version: &str) -> HostConfig { + HostConfig { + content_version: version.into(), + stale_policy: StalePolicy::SafeRoom { roam: false }, + ..HostConfig::default() + } +} + +fn transfer(principal: &str, from: &str, to: &str) -> Transfer { + Transfer { + claims: claims(principal, to), + source_zone: from.into(), + issuer: "h1".into(), + generation: 1, + carried: distributed_game::codec::to_bytes(&String::from("gold=7")), + departed_at_ms: 0, + } +} + +#[test] +fn safe_room_policy_admits_stale_clients_only_where_allowed() { + let clock = ManualClock::new(); + let mut field = host("realm.field", safe_room("v2"), &clock, RealmConfig::new()); + let mut gate = host( + "realm.inn", + safe_room("v2"), + &clock, + RealmConfig { + gate: true, + ..RealmConfig::new() + }, + ); + + // Fresh joins with stale content are told to reload. + let err = field + .join(&claims("ana", "realm.field"), 0, "v1") + .unwrap_err(); + assert_eq!(err.code, error::VERSION_MISMATCH); + assert!(err.message.contains("reload")); + // Stale players may not roam into non-gate zones... + let err = field + .join_transfer(&transfer("ana", "realm.inn", "realm.field"), 0, "v1") + .unwrap_err(); + assert_eq!(err.code, error::VERSION_MISMATCH); + // ...but up-to-date ones may. + field + .join_transfer(&transfer("bo", "realm.inn", "realm.field"), 0, "v2") + .unwrap(); + + // Entering a gate: admitted, then Kick(RELOAD), kept for reconnect. + let joined = gate + .join_transfer(&transfer("ana", "realm.field", "realm.inn"), 0, "v1") + .unwrap(); + let out = gate.drain_outbound(); + let msgs = messages(&out, joined.client); + let ServerMessage::Welcome(welcome) = &msgs[0] else { + panic!("welcome first: {msgs:?}") + }; + assert!(matches!( + msgs.last(), + Some(ServerMessage::Kick { code, .. }) if *code == kick::RELOAD + )); + assert!(closed(&out, joined.client)); + assert_eq!(gate.player_count(), 1, "kept in the reconnect grace window"); + assert_eq!(gate.zone().arrivals.len(), 1); + + // Reconnecting still stale at a gate -> reload again; reloaded -> in. + let again = gate + .reconnect_with_version(&welcome.reconnect_token, 0, "v1") + .unwrap(); + let out = gate.drain_outbound(); + let msgs = messages(&out, again.client); + let ServerMessage::Welcome(welcome) = &msgs[0] else { + panic!() + }; + assert!(closed(&out, again.client)); + let ok = gate + .reconnect_with_version(&welcome.reconnect_token, 0, "v2") + .unwrap(); + let out = gate.drain_outbound(); + assert!(!closed(&out, ok.client)); + let Viewer::Player(player) = ok.viewer else { + panic!() + }; + assert_eq!(gate.player_content_version(player), Some("v2")); +} + +#[test] +fn strict_policy_rejects_stale_reconnects_and_hard_mode_reloads() { + let clock = ManualClock::new(); + let config = HostConfig { + content_version: "v1".into(), + ..HostConfig::default() + }; + let mut h = host("z", config, &clock, RealmConfig::new()); + let joined = h.join(&claims("ana", "z"), 0, "v1").unwrap(); + let out = h.drain_outbound(); + let ServerMessage::Welcome(welcome) = &messages(&out, joined.client)[0] else { + panic!() + }; + h.disconnect(joined.client, false); + let err = h + .reconnect_with_version(&welcome.reconnect_token, 0, "v0") + .unwrap_err(); + assert_eq!(err.code, error::VERSION_MISMATCH); + let joined = h + .reconnect_with_version(&welcome.reconnect_token, 0, "v1") + .unwrap(); + h.drain_outbound(); + + // Barrier commit to v2 in hard mode: the v1 client is reloaded. + h.set_content_version("v2"); + assert_eq!(h.zone().versions, vec![("v1".into(), "v2".into())]); + assert_eq!(h.reload_stale_players(), 1); + let out = h.drain_outbound(); + assert!(messages(&out, joined.client) + .iter() + .any(|m| matches!(m, ServerMessage::Kick { code, .. } if *code == kick::RELOAD))); + assert_eq!(h.player_count(), 1); +} + +#[test] +fn handoff_issues_ticket_and_removes_player_first() { + let clock = ManualClock::new(); + let requests: Arc>> = Arc::default(); + let seen = requests.clone(); + let mut h = host( + "realm.east", + HostConfig::default(), + &clock, + RealmConfig { + neighbour: Some("realm.west".into()), + ..RealmConfig::new() + }, + ) + .with_transfer_issuer(move |r: &HandoffRequest| { + seen.lock().unwrap().push(r.clone()); + Some("signed-transfer".into()) + }); + let joined = h.join(&claims("ana", "realm.east"), 0, "").unwrap(); + h.drain_outbound(); + h.push_input(joined.client, 1, 0, &[CMD_HANDOFF]); + clock.advance(Duration::from_millis(40)); + h.advance(); + let out = h.drain_outbound(); + let msgs = messages(&out, joined.client); + assert!(msgs.contains(&ServerMessage::Handoff { + target_zone: "realm.west".into(), + transfer_ticket: "signed-transfer".into(), + })); + assert!(closed(&out, joined.client)); + assert_eq!(h.player_count(), 0); + assert_eq!(h.zone().left[0].1, LeaveReason::Handoff); + let r = &requests.lock().unwrap()[0]; + assert_eq!( + ( + r.principal.as_str(), + r.source_zone.as_str(), + r.target_zone.as_str() + ), + ("ana", "realm.east", "realm.west") + ); + assert_eq!( + r.carried, + distributed_game::codec::to_bytes(&String::from("ana:gold=0")) + ); + + // Without an issuer the zone gets an error and the player stays. + let mut lone = host( + "solo", + HostConfig::default(), + &clock, + RealmConfig { + neighbour: Some("x".into()), + ..RealmConfig::new() + }, + ); + let joined = lone.join(&claims("bo", "solo"), 0, "").unwrap(); + lone.push_input(joined.client, 1, 0, &[CMD_HANDOFF]); + clock.advance(Duration::from_millis(40)); + lone.advance(); + assert_eq!(lone.zone().handoff_errors, vec![HandoffError::NoIssuer]); + assert_eq!(lone.player_count(), 1); +} + +#[test] +fn freeze_waits_for_readiness_and_counts_dropped_inputs() { + let clock = ManualClock::new(); + let mut h = host( + "z", + HostConfig::default(), + &clock, + RealmConfig { + freeze_ready: false, + ..RealmConfig::new() + }, + ); + let joined = h.join(&claims("ana", "z"), 0, "").unwrap(); + let notice = Notice { + reason: "content_update".into(), + version: "v2".into(), + notes: String::new(), + }; + assert_eq!(h.request_freeze(notice.clone()), FreezeState::Freezing); + clock.advance(Duration::from_millis(100)); + assert!(h.advance().ticks > 0, "still ticking while not ready"); + h.zone_mut().cfg.freeze_ready = true; + clock.advance(Duration::from_millis(100)); + h.advance(); + assert_eq!(h.freeze_state(), FreezeState::Frozen); + let out = h.drain_outbound(); + assert!(messages(&out, joined.client).contains(&ServerMessage::Freeze(notice))); + let before = h.tick(); + h.push_input(joined.client, 1, 0, &[CMD_COUNT]); + h.push_input(joined.client, 2, 0, &[CMD_COUNT]); + clock.advance(Duration::from_millis(100)); + assert_eq!(h.advance().ticks, 0); + assert_eq!(h.tick(), before); + assert_eq!(h.inputs_dropped_frozen(), 2); + + let resume = Notice { + reason: "content_update_aborted".into(), + version: String::new(), + notes: String::new(), + }; + h.cancel_freeze(resume.clone()); + assert_eq!(h.freeze_state(), FreezeState::Running); + assert!(messages(&h.drain_outbound(), joined.client).contains(&ServerMessage::Resume(resume))); +} + +#[test] +fn child_events_are_delivered_later_and_forwarded_up() { + let clock = ManualClock::new(); + let mut h = host( + "realm.east", + HostConfig::default(), + &clock, + RealmConfig::new(), + ); + let event = ChildEvent { + origin_zone: "realm.east.keep".into(), + from_zone: "realm.east.keep".into(), + kind: "boss_defeated".into(), + payload: b"hydra".to_vec(), + origin_tick: 9, + content_version: String::new(), + levels: 3, + }; + h.deliver_child_event(event.clone()); + assert!(h.zone().child_events.is_empty(), "not synchronous"); + clock.advance(Duration::from_millis(40)); + h.advance(); + assert_eq!(h.zone().child_events, vec![event.clone()]); + let up = h.drain_upward(); + assert_eq!(up.len(), 1); + assert_eq!(up[0].from_zone, "realm.east"); + assert_eq!(up[0].origin_zone, "realm.east.keep"); + assert_eq!(up[0].levels, 2); + + // A zone's own upward event. + let joined = h.join(&claims("ana", "realm.east"), 0, "").unwrap(); + h.push_input(joined.client, 1, 0, &[CMD_BOSS]); + clock.advance(Duration::from_millis(40)); + h.advance(); + let up = h.drain_upward(); + assert_eq!(up[0].origin_zone, "realm.east"); + assert_eq!(up[0].levels, ChildEvent::TO_ROOT); +} + +#[test] +fn hibernate_restore_and_version_stamps() { + let clock = ManualClock::new(); + let (queue, _feed) = fact_channel(16, RetryPolicy::default()); + let mut h = host( + "z", + HostConfig { + content_version: "v1".into(), + ..HostConfig::default() + }, + &clock, + RealmConfig::new(), + ) + .with_facts(queue); + let joined = h.join(&claims("ana", "z"), 0, "v1").unwrap(); + h.push_input(joined.client, 1, 0, &[CMD_COUNT]); + clock.advance(Duration::from_millis(40)); + h.advance(); + let saved = h.hibernate_state().unwrap(); + + let mut restored = host("z", HostConfig::default(), &clock, RealmConfig::new()); + restored.restore(&saved, "v1"); + assert_eq!(restored.zone().counter, 1); + assert_eq!(restored.zone().restored_from.as_deref(), Some("v1")); + + // Facts emitted after a version switch carry the new version. + let (queue, feed) = fact_channel(16, RetryPolicy::default()); + let sink = MemoryFactSink::new(); + let mut h = host( + "z", + HostConfig { + content_version: "v1".into(), + ..HostConfig::default() + }, + &clock, + RealmConfig::new(), + ) + .with_facts(queue); + let joined = h.join(&claims("ana", "z"), 0, "v1").unwrap(); + h.set_content_version("v2"); + h.push_input(joined.client, 1, 0, &[CMD_COUNT]); + clock.advance(Duration::from_millis(40)); + h.advance(); + drop(h); + futures_executor(feed.run(sink.clone(), |_| async {})); + let committed = sink.committed(); + assert_eq!(committed[0].stamp().content_version, "v2"); +} + +/// Minimal executor for the fact feed (no runtime needed: the memory sink +/// never pends). +fn futures_executor(f: impl std::future::Future) { + let waker = std::task::Waker::noop(); + let mut cx = std::task::Context::from_waker(waker); + let mut f = std::pin::pin!(f); + while f.as_mut().poll(&mut cx).is_pending() {} +} + +#[test] +fn world_entry_points_record_and_replay_deterministically() { + use distributed_game::replay::{replay, Recording}; + let clock = ManualClock::new(); + let cfg = RealmConfig { + neighbour: Some("realm.west".into()), + ..RealmConfig::new() + }; + let config = HostConfig { + record: true, + ..safe_room("v1") + }; + let mut rec = + ZoneHost::::new("realm.east", config, Arc::new(clock.clone()), cfg.clone()) + .with_transfer_issuer(|_| Some("live-ticket".into())); + rec.restore(&5u32.to_le_bytes(), "v0"); + let ana = rec + .join_transfer(&transfer("ana", "realm.inn", "realm.east"), 0, "v1") + .unwrap(); + let bo = rec.join(&claims("bo", "realm.east"), 0, "v1").unwrap(); + rec.push_input(bo.client, 1, 0, &[CMD_COUNT]); + clock.advance(Duration::from_millis(40)); + rec.advance(); + rec.deliver_child_event(ChildEvent { + origin_zone: "realm.east.keep".into(), + from_zone: "realm.east.keep".into(), + kind: "boss_defeated".into(), + payload: vec![1], + origin_tick: 3, + content_version: "v1".into(), + levels: 1, + }); + let notice = Notice { + reason: "content_update".into(), + version: "v2".into(), + notes: String::new(), + }; + rec.request_freeze(notice.clone()); + rec.push_input(ana.client, 1, 0, &[CMD_COUNT]); + clock.advance(Duration::from_millis(40)); + rec.advance(); + rec.set_content_version("v2"); + rec.set_config_version("combat@2"); + rec.resume(notice); + rec.reload_stale_players(); + let out = rec.drain_outbound(); + let ServerMessage::Welcome(welcome) = &messages(&out, bo.client)[0] else { + panic!() + }; + let token = welcome.reconnect_token.clone(); + let bo = rec.reconnect_with_version(&token, 0, "v2").unwrap(); + rec.push_input(bo.client, 2, 0, &[CMD_HANDOFF]); + clock.advance(Duration::from_millis(40)); + rec.advance(); + assert_eq!(rec.zone().counter, 6); + assert_eq!(rec.config().config_version, "combat@2"); + assert_eq!(rec.zone().child_events.len(), 1); + assert_eq!(rec.player_count(), 1, "bo handed off"); + + let recording = Recording::decode(&rec.recording().unwrap().encode()).unwrap(); + let summary = replay::(&recording, cfg).unwrap(); + assert!(summary.ticks >= 2, "{summary:?}"); +} + +#[test] +fn handoff_target_stamps_after_source_departure_despite_clock_skew() { + // One virtual time, two hosts whose wall clocks disagree: the target's + // reads 9 000 s *behind* the source's. + let time = ManualClock::new(); + let source_clock = time.clone().with_unix_origin_ms(10_000_000); + let target_clock = time.clone().with_unix_origin_ms(1_000_000); + let requests = Arc::new(Mutex::new(Vec::new())); + let seen = requests.clone(); + let (source_queue, source_feed) = fact_channel(16, RetryPolicy::default()); + let mut source = ZoneHost::::new( + "realm.east", + HostConfig { + boot_epoch: 3, + config_version: "combat@12".into(), + ..HostConfig::default() + }, + Arc::new(source_clock), + RealmConfig { + neighbour: Some("realm.west".into()), + move_facts: true, + ..RealmConfig::new() + }, + ) + .with_facts(source_queue) + .with_transfer_issuer(move |r: &HandoffRequest| { + seen.lock().unwrap().push(r.clone()); + Some("signed".into()) + }); + let (target_queue, target_feed) = fact_channel(16, RetryPolicy::default()); + let mut target = ZoneHost::::new( + "realm.west", + HostConfig { + boot_epoch: 8, + ..HostConfig::default() + }, + Arc::new(target_clock), + RealmConfig { + move_facts: true, + ..RealmConfig::new() + }, + ) + .with_facts(target_queue); + + let ana = source.join(&claims("ana", "realm.east"), 0, "").unwrap(); + source.push_input(ana.client, 1, 0, &[CMD_HANDOFF]); + time.advance(Duration::from_millis(40)); + source.advance(); + let request = requests.lock().unwrap().pop().expect("handoff issued"); + // The ManualClock decides the stamp time: origin + virtual time. + assert_eq!(request.departed_at_ms, 10_000_040); + + // The source's leave runs later on its clock, still stamped with the + // departure time the ticket carries. + time.advance(Duration::from_millis(5)); + let transfer = Transfer { + claims: claims("ana", "realm.west"), + source_zone: request.source_zone.clone(), + issuer: "h1".into(), + generation: 3, + carried: request.carried.clone(), + departed_at_ms: request.departed_at_ms, + }; + target.join_transfer(&transfer, 0, "").unwrap(); + drop(source); + drop(target); + + // The target commits first. + let sink = MemoryFactSink::new(); + futures_executor(target_feed.run(sink.clone(), |_| async {})); + futures_executor(source_feed.run(sink.clone(), |_| async {})); + let committed = sink.committed(); + let commands: Vec<_> = committed.iter().map(Fact::command).collect(); + assert_eq!(commands, ["realm.arrived", "realm.left"]); + let (arrived, left) = (committed[0].stamp(), committed[1].stamp()); + + assert_eq!(left.emitted_at_ms, 10_000_040); + assert_eq!( + (left.activation, left.config_version.as_str()), + (3, "combat@12") + ); + // The target's own clock says 1 000 045; the stamp starts after the + // departure instead. + assert_eq!(arrived.emitted_at_ms, 10_000_041); + assert_eq!(arrived.activation, 8); + assert!(arrived.emitted_after(left)); + let mut ordered = committed.clone(); + ordered.sort_by(|a, b| a.stamp().emission_order(b.stamp())); + let ordered: Vec<_> = ordered.iter().map(Fact::command).collect(); + assert_eq!(ordered, ["realm.left", "realm.arrived"]); +} + +#[test] +fn stamps_follow_the_manual_clock_and_config_version() { + let clock = ManualClock::new().with_unix_origin_ms(500); + let h = host( + "z", + HostConfig { + boot_epoch: 42, + ..HostConfig::default() + }, + &clock, + RealmConfig::new(), + ); + clock.advance(Duration::from_millis(250)); + let (queue, feed) = fact_channel(16, RetryPolicy::default()); + let mut h = h.with_facts(queue); + let joined = h.join(&claims("bo", "z"), 0, "").unwrap(); + h.push_input(joined.client, 1, 0, &[CMD_COUNT]); + h.set_config_version("combat@13"); + clock.advance(Duration::from_millis(40)); + h.advance(); + drop(h); + let sink = MemoryFactSink::new(); + futures_executor(feed.run(sink.clone(), |_| async {})); + let stamp = sink.committed()[0].stamp().clone(); + assert_eq!(stamp.emitted_at_ms, 790); + assert_eq!(stamp.activation, 42); + assert_eq!(stamp.config_version, "combat@13"); + assert_eq!(stamp.zone_id, "z"); +} diff --git a/distributed_game/tests/zone_lease/main.rs b/distributed_game/tests/zone_lease/main.rs new file mode 100644 index 000000000..14dc723d3 --- /dev/null +++ b/distributed_game/tests/zone_lease/main.rs @@ -0,0 +1,295 @@ +//! `ZoneLease` cells on the in-process reference host, driven by a +//! `ManualClock`: ownership conformance, no outbox rows for renewals, +//! exactly one `zone.lease_expired`, and renewals racing the alarm. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::{Duration, SystemTime}; + +use distributed::cell_host::{ + AggregateCell, CausalDispatchError, CellCommandIdentity, CellStreamStore, +}; +use distributed::microsvc::schedule::schedule_session; +use distributed::microsvc::{Session, ROLE_KEY, USER_ID_KEY}; +use distributed::{Clock, ManualClock, StreamIdentity}; +use distributed_game::cell::command_id_for; +use distributed_game::world::zone_lease::{ + mount_zone_lease, ownership_error, ClaimPayload, ZoneLease, ACQUIRE, EXPIRE, RELEASE, RENEW, + ZONE_HOST_ROLE, +}; +use distributed_game::world::{ + ownership_conformance, restart_conformance, OwnershipError, ZoneClaim, ZoneOwnership, +}; +use distributed_game::BoxFuture; +use serde_json::{json, Value}; + +const T0: u64 = 1_700_000_000_000; + +fn clock() -> ManualClock { + ManualClock::new(SystemTime::UNIX_EPOCH + Duration::from_millis(T0)) +} + +fn lease_cell(clock: &ManualClock, zone: &str) -> AggregateCell { + let store = CellStreamStore::for_identity(StreamIdentity::new("ZoneLease", zone).unwrap()) + .with_clock(clock.clone()); + mount_zone_lease(AggregateCell::from_store(store).unwrap()) +} + +fn host_session() -> Session { + let mut session = Session::new(); + session.set(USER_ID_KEY, "zone-server-a"); + session.set(ROLE_KEY, ZONE_HOST_ROLE); + session +} + +/// `ZoneOwnership` over one in-process cell, as `CellZoneOwnership` is over +/// celld (same commands, same error mapping). +struct InProcess { + cell: AggregateCell, + calls: AtomicU64, +} + +impl InProcess { + async fn call(&self, command: &str, input: Value) -> Result { + let n = self.calls.fetch_add(1, Ordering::SeqCst); + let identity = CellCommandIdentity::new( + "zone-host", + "zone-server-a", + command_id_for("t", &n.to_string()), + ) + .unwrap(); + match self + .cell + .dispatch_idempotent(command, &identity, input, host_session()) + .await + { + Ok(result) => Ok(serde_json::from_value(result.payload().clone()).unwrap()), + Err(CausalDispatchError::Rejected { message, .. }) => Err(ownership_error(&message)), + Err(error) => Err(OwnershipError::Backend(format!("{error:?}"))), + } + } +} + +fn claim(payload: ClaimPayload) -> ZoneClaim { + ZoneClaim { + zone_id: payload.zone_id, + holder: payload.holder, + token: payload.token, + expires_at: SystemTime::UNIX_EPOCH + Duration::from_millis(payload.expires_at_ms), + } +} + +impl ZoneOwnership for InProcess { + fn acquire<'a>( + &'a self, + zone_id: &'a str, + holder: &'a str, + ttl: Duration, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + self.call( + ACQUIRE, + json!({ "zone_id": zone_id, "holder": holder, "ttl_ms": ttl.as_millis() as u64 }), + ) + .await + .map(claim) + }) + } + + fn renew<'a>( + &'a self, + current: &'a ZoneClaim, + ttl: Duration, + ) -> BoxFuture<'a, Result> { + Box::pin(async move { + self.call( + RENEW, + json!({ "zone_id": current.zone_id, "holder": current.holder, + "token": current.token, "ttl_ms": ttl.as_millis() as u64 }), + ) + .await + .map(claim) + }) + } + + fn release<'a>(&'a self, current: &'a ZoneClaim) -> BoxFuture<'a, ()> { + Box::pin(async move { + let _ = self + .call( + RELEASE, + json!({ "zone_id": current.zone_id, "holder": current.holder, + "token": current.token }), + ) + .await; + }) + } +} + +fn in_process(clock: &ManualClock, zone: &str) -> Arc { + Arc::new(InProcess { + cell: lease_cell(clock, zone), + calls: AtomicU64::new(0), + }) +} + +/// Outward event types in the cell's outbox, sorted (the reference host's +/// export is unordered; delivery order comes from `created_at`). +fn outward(cell: &AggregateCell) -> Vec { + let mut types = cell + .durable_outbox() + .unwrap() + .into_iter() + .map(|message| message.event_type) + .collect::>(); + types.sort(); + types +} + +#[tokio::test] +async fn the_lease_cell_passes_the_ownership_conformance_suite() { + let clock = clock(); + let own = in_process(&clock, "conformance"); + ownership_conformance(own.as_ref(), "conformance").await; + assert_eq!( + outward(&own.cell), + [ + "zone.activated", + "zone.activated", + "zone.activated", + "zone.released", + "zone.released", + "zone.released" + ] + ); +} + +#[tokio::test] +async fn the_lease_cell_passes_the_restart_conformance_suite() { + let clock = clock(); + let own = in_process(&clock, "restart"); + let ttl = Duration::from_secs(10); + restart_conformance(own.as_ref(), "restart", ttl, async { + clock.advance(ttl); + assert_eq!(own.cell.fire_due_schedules().await.unwrap().fired.len(), 1); + }) + .await; +} + +#[tokio::test] +async fn renewals_produce_no_outbox_rows_and_move_the_expiry_alarm() { + let clock = clock(); + let own = in_process(&clock, "z1"); + let ttl = Duration::from_secs(10); + let mut current = own.acquire("z1", "a#1", ttl).await.unwrap(); + assert_eq!(outward(&own.cell), ["zone.activated"]); + assert_eq!( + own.cell.next_schedule_due().unwrap(), + Some(SystemTime::UNIX_EPOCH + Duration::from_millis(T0 + 10_000)) + ); + for step in 1..=20u64 { + clock.advance(Duration::from_secs(3)); + current = own.renew(¤t, ttl).await.unwrap(); + assert_eq!( + own.cell.next_schedule_due().unwrap(), + Some(clock.now() + ttl), + "step {step}" + ); + assert!(own.cell.fire_due_schedules().await.unwrap().is_empty()); + } + assert_eq!( + outward(&own.cell), + ["zone.activated"], + "no heartbeat events" + ); + assert_eq!( + own.cell.load().await.unwrap().unwrap().holder(), + Some("a#1") + ); +} + +#[tokio::test] +async fn a_holder_that_stops_renewing_expires_exactly_once() { + let clock = clock(); + let own = in_process(&clock, "z2"); + let ttl = Duration::from_secs(10); + let held = own.acquire("z2", "a#1", ttl).await.unwrap(); + clock.advance(Duration::from_millis(9_999)); + assert!(own.cell.fire_due_schedules().await.unwrap().is_empty()); + clock.advance(Duration::from_millis(1)); + let report = own.cell.fire_due_schedules().await.unwrap(); + assert_eq!(report.fired.len(), 1); + assert_eq!(report.fired[0].payload["expired"], true); + assert_eq!(outward(&own.cell), ["zone.activated", "zone.lease_expired"]); + clock.advance(Duration::from_secs(60)); + assert!(own.cell.fire_due_schedules().await.unwrap().is_empty()); + assert_eq!(outward(&own.cell).len(), 2, "exactly one expiry"); + assert_eq!(own.renew(&held, ttl).await, Err(OwnershipError::Lost)); + let next = own.acquire("z2", "b#1", ttl).await.unwrap(); + assert!(next.token > held.token); +} + +#[tokio::test] +async fn a_renewal_racing_the_alarm_never_produces_a_false_expiry() { + let clock = clock(); + let own = in_process(&clock, "z3"); + let ttl = Duration::from_secs(10); + let held = own.acquire("z3", "a#1", ttl).await.unwrap(); + + // The alarm comes due, but the renewal lands before the wake. + clock.advance(ttl); + let held = own.renew(&held, ttl).await.unwrap(); + assert!(own.cell.fire_due_schedules().await.unwrap().is_empty()); + + // The wake read the due alarm, then the renewal interleaved, then the + // stale expiry command runs: the handler re-reads the lease and keeps it. + clock.advance(ttl); + let stale = own.cell.armed_schedules().unwrap().remove(0); + let _held = own.renew(&held, ttl).await.unwrap(); + let result = own + .cell + .dispatch_idempotent( + EXPIRE, + &stale.command_identity().unwrap(), + stale.input.clone(), + schedule_session(&stale), + ) + .await + .unwrap(); + assert_eq!(result.payload()["expired"], false); + assert_eq!(outward(&own.cell), ["zone.activated"]); + assert_eq!( + own.cell.load().await.unwrap().unwrap().holder(), + Some("a#1") + ); + + // Callers cannot run the expiry command themselves. + let forged = own + .cell + .dispatch_idempotent( + EXPIRE, + &CellCommandIdentity::new("zone-host", "zone-server-a", command_id_for("t", "forged")) + .unwrap(), + json!({ "zone_id": "z3" }), + host_session(), + ) + .await; + assert!(forged.is_err()); +} + +#[tokio::test] +async fn only_zone_hosts_may_acquire() { + let clock = clock(); + let cell = lease_cell(&clock, "z4"); + let mut player = Session::new(); + player.set(USER_ID_KEY, "player-1"); + let refused = cell + .dispatch_idempotent( + ACQUIRE, + &CellCommandIdentity::new("zone-host", "player-1", command_id_for("t", "p")).unwrap(), + json!({ "zone_id": "z4", "holder": "p#1", "ttl_ms": 1000 }), + player, + ) + .await; + assert!(refused.is_err()); + assert!(cell.load().await.unwrap().is_none()); +} diff --git a/distributed_game/tests/zone_message/main.rs b/distributed_game/tests/zone_message/main.rs new file mode 100644 index 000000000..2c9317dea --- /dev/null +++ b/distributed_game/tests/zone_message/main.rs @@ -0,0 +1,161 @@ +//! Zone-to-zone messages: a zone sends with `Ctx::send_zone` / +//! `send_zone_for`, the driver carries the envelope, the target runs +//! `on_zone_message` once (repeats dropped) and may emit facts as the +//! verified principal the message carried. + +use std::sync::Arc; + +use distributed_game::*; +use serde::Serialize; + +#[derive(Debug, Clone, PartialEq, GameEvent)] +pub enum Relay { + /// "Score this for whoever it is on behalf of." + #[game_event(id = 1)] + Score { + /// Points. + points: u32, + }, +} + +#[derive(Serialize, FactCommand)] +#[fact(command = "scores.record")] +struct Scored { + points: u32, +} + +#[derive(Default)] +struct Room { + /// `(from zone, principal, points)` received. + got: Vec<(String, Option, u32)>, +} + +impl Zone for Room { + type Config = (); + type Input = u8; + type Timer = (); + type Message = Relay; + + fn schema() -> EntitySchema { + EntitySchema::new() + } + + fn on_create(_ctx: &mut Ctx<'_, Self>, _: ()) -> Self { + Self::default() + } + + fn decode_input(&self, _player: PlayerId, payload: &[u8]) -> Option { + payload.first().copied() + } + + fn on_tick(&mut self, _ctx: &mut Ctx<'_, Self>) {} + + /// A player joining sends one message on its behalf and one plain. + fn on_join(&mut self, ctx: &mut Ctx<'_, Self>, player: PlayerId) { + ctx.send_zone_for(player, "east", &Relay::Score { points: 3 }); + ctx.send_zone("east", &Relay::Score { points: 1 }); + } + + fn on_zone_message(&mut self, ctx: &mut Ctx<'_, Self>, from: &ZoneSender, message: Relay) { + let Relay::Score { points } = message; + self.got.push(( + from.zone.clone(), + from.principal.as_ref().map(|p| p.as_str().to_string()), + points, + )); + if let Some(principal) = &from.principal { + let fact = ctx + .fact_with_key(&Scored { points }, &[&from.zone, &self.got.len()]) + .unwrap(); + ctx.emit_fact_as(principal, fact).unwrap(); + } + } +} + +fn host(zone: &str) -> ZoneHost { + let (queue, _feed) = fact_channel(16, RetryPolicy::default()); + ZoneHost::::new( + zone, + HostConfig::default(), + Arc::new(ManualClock::new()), + (), + ) + .with_facts(queue.with_journal()) +} + +#[test] +fn a_message_reaches_its_zone_once_with_the_verified_principal() { + let mut west = host("west"); + let mut east = host("east"); + west.join( + &TicketClaims::new("ana", "west", u64::MAX, "n1", Role::Player), + 0, + "", + ) + .unwrap(); + let sent = west.take_zone_messages(); + assert_eq!(sent.len(), 2); + assert!(sent.iter().all(|m| m.from == "west" && m.to == "east")); + assert_ne!(sent[0].id, sent[1].id, "ids are unique"); + assert_eq!(sent[0].principal.as_deref(), Some("ana")); + assert_eq!(sent[1].principal, None); + assert!(west.take_zone_messages().is_empty(), "taken once"); + + for envelope in &sent { + east.deliver_zone(envelope.clone()).unwrap(); + } + // A resend (at-least-once transport) is dropped. + assert_eq!( + east.deliver_zone(sent[0].clone()), + Err(ZoneMessageError::Duplicate) + ); + assert_eq!( + east.zone().got, + [ + ("west".to_string(), Some("ana".to_string()), 3), + ("west".to_string(), None, 1), + ] + ); + // The fact is bound to the principal the message carried. + let facts = east.take_emitted_facts(); + assert_eq!(facts.len(), 1); + assert_eq!(facts[0].principal(), Some("ana")); + + // Not for this zone, or not this zone's message type: refused. + assert_eq!( + west.deliver_zone(sent[1].clone()), + Err(ZoneMessageError::WrongZone) + ); + let mut garbled = sent[1].clone(); + garbled.id = "west/x/99".into(); + garbled.type_id = 77; + assert!(matches!( + east.deliver_zone(garbled), + Err(ZoneMessageError::Decode(_)) + )); +} + +#[test] +fn a_new_activation_numbers_its_messages_apart_from_the_last() { + let mut a = host("west"); + a.join( + &TicketClaims::new("ana", "west", u64::MAX, "n1", Role::Player), + 0, + "", + ) + .unwrap(); + std::thread::sleep(std::time::Duration::from_millis(2)); + let mut b = host("west"); + b.join( + &TicketClaims::new("ana", "west", u64::MAX, "n2", Role::Player), + 0, + "", + ) + .unwrap(); + let (first, second) = (a.take_zone_messages(), b.take_zone_messages()); + assert_ne!(first[0].id, second[0].id); + let mut east = host("east"); + east.deliver_zone(first[0].clone()).unwrap(); + east.deliver_zone(second[0].clone()).unwrap(); + assert_eq!(east.zone().got.len(), 2); +} diff --git a/distributed_game/tests/zone_runtime/main.rs b/distributed_game/tests/zone_runtime/main.rs new file mode 100644 index 000000000..76c66c7db --- /dev/null +++ b/distributed_game/tests/zone_runtime/main.rs @@ -0,0 +1,885 @@ +//! P2 zone runtime behaviour: lifecycle, cadence, tiers, inputs, +//! determinism and non-blocking facts. + +#[path = "../support/arena.rs"] +mod arena; + +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use arena::{Arena, ArenaConfig}; +use distributed_game::protocol::{error, ServerMessage}; +use distributed_game::{ + fact_channel, ClientId, ClientMirror, EmitError, Fact, FactError, FactOutcome, FactReceipt, + FactSink, HostConfig, LeaveReason, ManualClock, MemoryFactSink, Outbound, PushOutcome, + RetryPolicy, Role, SystemClock, TicketClaims, Tier, ZoneHost, +}; + +const MS: fn(u64) -> Duration = Duration::from_millis; + +fn claims(principal: &str, zone: &str) -> TicketClaims { + TicketClaims { + principal: principal.into(), + zone: zone.into(), + expires_at: u64::MAX, + nonce: format!("n-{principal}"), + role: Role::Player, + name: None, + extensions: Default::default(), + wake: false, + } +} + +fn host(config: HostConfig, clock: &ManualClock, cfg: ArenaConfig) -> ZoneHost { + ZoneHost::new("z1", config, Arc::new(clock.clone()), cfg) +} + +fn frames_for(out: &[Outbound], client: ClientId) -> Vec> { + out.iter() + .filter_map(|o| match o { + Outbound::Frame { client: c, frame } if *c == client => Some(frame.clone()), + _ => None, + }) + .collect() +} + +#[test] +fn lifecycle_hooks_capacity_and_auth() { + let clock = ManualClock::new(); + let config = HostConfig { + max_players: 2, + ..HostConfig::default() + }; + let mut h = host( + config, + &clock, + ArenaConfig { + reject_principal: Some("mallory".into()), + spawn_every: Some(MS(100)), + ..Default::default() + }, + ); + let a = h.join(&claims("alice", "z1"), 0, "").unwrap(); + let err = h.join(&claims("mallory", "z1"), 0, "").unwrap_err(); + assert_eq!(err.code, error::REJECTED); + let err = h.join(&claims("bob", "other-zone"), 0, "").unwrap_err(); + assert_eq!(err.code, error::UNAUTHORIZED); + h.join(&claims("bob", "z1"), 0, "").unwrap(); + let err = h.join(&claims("carol", "z1"), 0, "").unwrap_err(); + assert_eq!(err.code, error::ZONE_FULL); + + // Welcome is the first frame for a joined client. + let out = h.drain_outbound(); + let mut mirror = ClientMirror::new(); + let first = frames_for(&out, a.client).remove(0); + assert!(matches!( + mirror.apply(&first).unwrap(), + ServerMessage::Welcome(_) + )); + + clock.advance(MS(500)); + h.advance(); + assert!(h.zone().timer_fires > 0); + h.disconnect(a.client, true); + h.dispose(); + assert!(h.is_disposed()); + let fires = h.zone().timer_fires; + clock.advance(MS(1_000)); + assert_eq!(h.advance().ticks, 0, "disposed zones never tick"); + assert_eq!(h.zone().timer_fires, fires, "timers cleared on dispose"); + assert_eq!( + h.zone().log, + vec![ + "create", + "join:alice", + "join:bob", + "leave:Left", + "leave:Disposed", + "dispose" + ] + ); +} + +#[test] +fn fixed_timestep_caps_catch_up_and_patches_independently() { + let clock = ManualClock::new(); + let config = HostConfig { + tick_rate: 50, + patch_rate: 10, + max_catch_up: 5, + ..HostConfig::default() + }; + let mut h = host(config, &clock, ArenaConfig::default()); + h.join(&claims("alice", "z1"), 0, "").unwrap(); + h.advance(); + h.drain_outbound(); + + // A 2s stall runs at most 5 steps and drops the rest. + clock.advance(Duration::from_secs(2)); + let seen = h.zone().dropped_seen.len(); + let report = h.advance(); + assert_eq!(report.ticks, 5); + assert!(report.dropped >= Duration::from_millis(1_900)); + // The first tick after the stall sees the dropped ticks, the rest none. + assert_eq!( + h.zone().dropped_seen[seen..], + [report.dropped_ticks, 0, 0, 0, 0] + ); + assert_eq!(report.dropped_ticks, 95); + + // Steady state: 1s in 2 ms frames = 50 ticks, 10 patches. + let (mut ticks, mut patches) = (0, 0); + let start = h.tick(); + for _ in 0..500 { + clock.advance(MS(2)); + let r = h.advance(); + ticks += r.ticks; + patches += u32::from(r.patched); + } + assert_eq!(ticks, 50); + assert_eq!(h.tick() - start, 50); + assert!((9..=11).contains(&patches), "patches = {patches}"); +} + +#[test] +fn activity_tiers_hot_idle_dormant_and_wake() { + let clock = ManualClock::new(); + let config = HostConfig { + tick_rate: 20, + idle_tick_rate: Some(2), + dormant_after: Duration::from_secs(5), + ..HostConfig::default() + }; + let mut h = host(config.clone(), &clock, ArenaConfig::default()); + let a = h.join(&claims("alice", "z1"), 0, "").unwrap(); + assert_eq!(h.tier(), Tier::Hot); + let mut ticks = 0; + for _ in 0..20 { + clock.advance(MS(50)); + ticks += h.advance().ticks; + } + assert_eq!(ticks, 20); + + h.disconnect(a.client, true); + let r = h.advance(); + assert_eq!(h.tier(), Tier::Idle); + assert_eq!(r.transitions, vec![(Tier::Hot, Tier::Idle)]); + clock.advance(Duration::from_secs(2)); + assert_eq!(h.advance().ticks, 4, "idle runs the slow clock"); + + clock.advance(Duration::from_secs(4)); + let r = h.advance(); + assert_eq!(h.tier(), Tier::Dormant); + assert_eq!(r.transitions, vec![(Tier::Idle, Tier::Dormant)]); + assert_eq!(r.next_wake, None); + clock.advance(Duration::from_secs(10)); + assert_eq!(h.advance().ticks, 0, "dormant zones do not tick"); + + h.join(&claims("bob", "z1"), 0, "").unwrap(); + assert_eq!(h.tier(), Tier::Hot); + let r = h.advance(); + assert_eq!(r.transitions, vec![(Tier::Dormant, Tier::Hot)]); + assert_eq!(r.ticks, 0, "no catch-up for dormant time"); + assert_eq!( + h.zone().tiers, + vec![ + (Tier::Hot, Tier::Idle), + (Tier::Idle, Tier::Dormant), + (Tier::Dormant, Tier::Hot) + ] + ); + + // Background zones stay Idle instead of going Dormant. + let mut bg = host( + config, + &clock, + ArenaConfig { + background: true, + ..Default::default() + }, + ); + bg.advance(); + clock.advance(Duration::from_secs(60)); + bg.advance(); + assert_eq!(bg.tier(), Tier::Idle); +} + +#[test] +fn reconnect_within_grace_keeps_player_then_expires() { + let clock = ManualClock::new(); + let config = HostConfig { + reconnect_grace: Duration::from_secs(3), + ..HostConfig::default() + }; + let mut h = host(config, &clock, ArenaConfig::default()); + let a = h.join(&claims("alice", "z1"), 0, "").unwrap(); + let out = h.drain_outbound(); + let mut mirror = ClientMirror::new(); + mirror.apply(&frames_for(&out, a.client)[0]).unwrap(); + let token = mirror.welcome.as_ref().unwrap().reconnect_token.clone(); + assert!(!token.is_empty()); + + for seq in 1..=5 { + assert_eq!( + h.push_input(a.client, seq, 0, &[1, 0]), + PushOutcome::Accepted + ); + } + h.advance(); + + h.disconnect(a.client, false); + clock.advance(Duration::from_secs(1)); + h.advance(); + assert_eq!(h.player_count(), 1); + let b = h.reconnect(&token, 0).unwrap(); + assert_eq!(b.viewer, a.viewer, "same player after reconnect"); + // The resumed session restarts its input sequence at 1 (new Welcome). + assert_eq!(h.push_input(b.client, 1, 0, &[1, 0]), PushOutcome::Accepted); + assert!(h.reconnect(&token, 0).is_err(), "tokens rotate on use"); + assert_eq!(h.zone().log, vec!["create", "join:alice"]); + + h.disconnect(b.client, false); + clock.advance(Duration::from_secs(4)); + h.advance(); + assert_eq!(h.player_count(), 0); + assert_eq!(h.zone().log.last().unwrap(), "leave:Disconnected"); + let _ = LeaveReason::Disconnected; +} + +#[test] +fn inputs_are_sanitized_deduped_and_acked_in_deltas() { + let clock = ManualClock::new(); + let mut h = host(HostConfig::default(), &clock, ArenaConfig::default()); + let a = h.join(&claims("alice", "z1"), 0, "").unwrap(); + assert_eq!(h.push_input(a.client, 1, 0, &[1, 0]), PushOutcome::Accepted); + assert_eq!( + h.push_input(a.client, 1, 0, &[1, 0]), + PushOutcome::Duplicate + ); + assert_eq!(h.push_input(a.client, 2, 0, &[9, 0]), PushOutcome::Rejected); + assert_eq!(h.push_input(a.client, 3, 0, &[1]), PushOutcome::Rejected); + assert_eq!(h.push_input(a.client, 4, 0, &[0, 1]), PushOutcome::Accepted); + assert_eq!( + h.push_input(ClientId(999), 1, 0, &[0, 1]), + PushOutcome::UnknownClient + ); + + clock.advance(MS(100)); + let r = h.advance(); + assert!(r.ticks > 0 && r.patched); + assert_eq!(h.push_input(a.client, 4, 0, &[0, 1]), PushOutcome::Stale); + let mut mirror = ClientMirror::new(); + for frame in frames_for(&h.drain_outbound(), a.client) { + mirror.apply(&frame).unwrap(); + } + assert_eq!(mirror.ack_seq, 4); + assert_eq!(mirror.entities.len(), 1, "own avatar replicated"); +} + +fn run_scripted(seed: u64) -> (u64, u64) { + let clock = ManualClock::new(); + let config = HostConfig { + world_seed: seed, + ..HostConfig::default() + }; + let (queue, _feed) = fact_channel(10_000, RetryPolicy::default()); + let mut h = host( + config, + &clock, + ArenaConfig { + spawn_every: Some(MS(200)), + ..Default::default() + }, + ) + .with_facts(queue); + let a = h.join(&claims("alice", "z1"), 0, "").unwrap(); + let b = h.join(&claims("bob", "z1"), 0, "").unwrap(); + let mut seq = 0; + for step in 0..600u32 { + if step % 3 == 0 { + seq += 1; + let dx = ((step / 7) % 3) as i8 - 1; + let dy = ((step / 11) % 3) as i8 - 1; + h.push_input(a.client, seq, step, &[dx as u8, dy as u8]); + h.push_input(b.client, seq, step, &[dy as u8, dx as u8]); + } + clock.advance(MS(7)); + h.advance(); + h.drain_outbound(); + } + (h.zone().state_hash(), h.tick()) +} + +#[test] +fn same_seed_and_input_log_reproduce_state() { + let first = run_scripted(42); + let second = run_scripted(42); + assert_eq!(first, second); + assert_ne!(run_scripted(7).0, first.0, "different seed diverges"); +} + +/// A sink written the way a downstream crate would: only crate-root +/// imports (`distributed_game::{BoxFuture, Fact, FactSink, ...}`). +mod external_sink { + use distributed_game::{BoxFuture, Fact, FactError, FactReceipt, FactSink}; + + pub struct CountingSink(pub std::sync::atomic::AtomicUsize); + + impl FactSink for CountingSink { + fn commit<'a>(&'a self, fact: &'a Fact) -> BoxFuture<'a, Result> { + Box::pin(async move { + self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(FactReceipt { + payload: serde_json::json!({ "key": fact.key() }), + replayed: false, + }) + }) + } + } +} + +#[tokio::test] +async fn facts_sink_implementable_from_crate_root_exports() { + let sink = external_sink::CountingSink(Default::default()); + let fact = Fact::new("k1", "cmd", serde_json::json!({})); + let receipt = sink.commit(&fact).await.unwrap(); + assert_eq!(receipt.payload["key"], "k1"); + assert_eq!(sink.0.load(Ordering::SeqCst), 1); +} + +/// Sink that takes `delay` per commit (simulated slow storage). +struct SlowSink { + delay: Duration, + inner: MemoryFactSink, +} + +impl FactSink for SlowSink { + fn commit<'a>( + &'a self, + fact: &'a Fact, + ) -> distributed_game::BoxFuture<'a, Result> { + Box::pin(async move { + tokio::time::sleep(self.delay).await; + self.inner.commit(fact).await + }) + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn slow_sink_never_stalls_the_tick() { + let sink = MemoryFactSink::new(); + let (queue, feed) = fact_channel(10_000, RetryPolicy::default()); + tokio::spawn(feed.run( + SlowSink { + delay: MS(100), + inner: sink.clone(), + }, + tokio::time::sleep, + )); + let config = HostConfig { + tick_rate: 50, + ..HostConfig::default() + }; + let clock = Arc::new(SystemClock::new()); + let mut h = ZoneHost::::new( + "z1", + config, + clock, + ArenaConfig { + fact_every_tick: true, + ..Default::default() + }, + ) + .with_facts(queue); + h.join(&claims("alice", "z1"), 0, "").unwrap(); + + let start = Instant::now(); + let mut worst = Duration::ZERO; + let mut ticks = 0; + while start.elapsed() < MS(600) { + let t0 = Instant::now(); + let r = h.advance(); + worst = worst.max(t0.elapsed()); + ticks += r.ticks; + h.drain_outbound(); + tokio::time::sleep(MS(5)).await; + } + // 600 ms at 50 Hz = 30 ticks; storage at 10 commits/s must not slow it. + assert!(ticks >= 27, "ticks = {ticks}"); + assert!(worst < MS(25), "an advance took {worst:?}"); + assert!( + h.facts_in_flight() > 10, + "facts are still queued behind slow storage" + ); + assert!(h.zone().emit_errors.is_empty()); + let settled = h.zone().settled.len(); + assert!( + settled >= 2, + "settlements flow back on later ticks ({settled})" + ); + assert!(h + .zone() + .settled + .iter() + .all(|s| matches!(s.outcome, FactOutcome::Committed(_)))); + assert!(sink.committed().len() >= settled); +} + +struct FlakySink { + failures_left: AtomicU32, + permanent_key: String, +} + +impl FactSink for FlakySink { + fn commit<'a>( + &'a self, + fact: &'a Fact, + ) -> distributed_game::BoxFuture<'a, Result> { + Box::pin(async move { + if fact.key() == self.permanent_key { + return Err(FactError::Permanent("no such player".into())); + } + if self.failures_left.load(Ordering::SeqCst) > 0 { + self.failures_left.fetch_sub(1, Ordering::SeqCst); + return Err(FactError::Retryable("busy".into())); + } + Ok(FactReceipt { + payload: serde_json::json!({ "ok": fact.key() }), + replayed: false, + }) + }) + } +} + +#[tokio::test] +async fn retries_backoff_permanent_failure_backpressure_and_principal_binding() { + let (mut queue, feed) = fact_channel( + 2, + RetryPolicy { + max_attempts: 5, + base_backoff: MS(1), + max_backoff: MS(4), + }, + ); + let worker = tokio::spawn(feed.run( + FlakySink { + failures_left: AtomicU32::new(2), + permanent_key: "bad".into(), + }, + tokio::time::sleep, + )); + queue + .try_send(Fact::new("good", "credit_xp", serde_json::json!({}))) + .unwrap(); + assert_eq!( + queue.try_send(Fact::new("good", "credit_xp", serde_json::json!({}))), + Err(EmitError::DuplicateKey) + ); + queue + .try_send(Fact::new("bad", "credit_xp", serde_json::json!({}))) + .unwrap(); + assert_eq!( + queue.try_send(Fact::new("third", "credit_xp", serde_json::json!({}))), + Err(EmitError::Backpressure) + ); + let mut settled = Vec::new(); + while settled.len() < 2 { + settled.extend(queue.drain()); + tokio::time::sleep(MS(2)).await; + } + assert!(matches!(settled[0].outcome, FactOutcome::Committed(_))); + assert!(matches!( + settled[1].outcome, + FactOutcome::Failed { + error: FactError::Permanent(_), + attempts: 1 + } + )); + assert_eq!(queue.in_flight(), 0); + drop(queue); + worker.await.unwrap(); + + // Principal and stamp are bound by the host from the verified ticket. + let clock = ManualClock::new(); + let sink = MemoryFactSink::new(); + let (queue, feed) = fact_channel(100, RetryPolicy::default()); + let worker = tokio::spawn(feed.run(sink.clone(), tokio::time::sleep)); + let mut h = host( + HostConfig { + content_version: "c1".into(), + ..HostConfig::default() + }, + &clock, + ArenaConfig::default(), + ) + .with_facts(queue); + let a = h.join(&claims("alice", "z1"), 0, "c1").unwrap(); + let player = match a.viewer { + distributed_game::Viewer::Player(p) => p, + _ => unreachable!(), + }; + let (x, y) = { + let av = &h.zone().avatars[&player]; + (av.x, av.y) + }; + h.zone_mut().coins.insert(77, (x, y)); + clock.advance(MS(40)); + h.advance(); + let tick = h.tick(); + drop(h); + worker.await.unwrap(); + let committed = sink.committed(); + assert_eq!(committed.len(), 1); + assert_eq!(committed[0].principal(), Some("alice")); + assert_eq!(committed[0].key(), "coin:z1:77"); + assert_eq!(committed[0].stamp().zone_id, "z1"); + assert_eq!(committed[0].stamp().content_version, "c1"); + assert!(committed[0].stamp().tick >= 1 && committed[0].stamp().tick <= tick); +} + +#[test] +fn observers_receive_deltas_without_owning_a_player() { + let clock = ManualClock::new(); + let mut h = host(HostConfig::default(), &clock, ArenaConfig::default()); + h.join(&claims("alice", "z1"), 0, "").unwrap(); + let mut obs_claims = claims("watcher", "z1").with_name("Wat"); + obs_claims.role = Role::Observer; + let o = h.join(&obs_claims, 0, "").unwrap(); + assert!(h.zone().log.contains(&"observe:watcher:Wat".to_string())); + assert_eq!(h.observers().next().unwrap().principal, "watcher"); + assert_eq!(h.player_count(), 1); + assert_eq!( + h.push_input(o.client, 1, 0, &[1, 0]), + PushOutcome::UnknownClient + ); + clock.advance(MS(100)); + h.advance(); + let mut mirror = ClientMirror::new(); + let mut events = Vec::new(); + for frame in frames_for(&h.drain_outbound(), o.client) { + if let ServerMessage::Event { type_id, payload } = mirror.apply(&frame).unwrap() { + events.push((type_id, payload)); + } + } + assert_eq!(mirror.welcome.as_ref().unwrap().role, Role::Observer); + assert_eq!(mirror.entities.len(), 1); + assert!( + events + .iter() + .any(|(t, p)| *t == 7 && p == b"observe:watcher:Wat"), + "event addressed to the observer" + ); + h.disconnect(o.client, false); + assert!(h.zone().log.contains(&"unobserve:watcher".to_string())); +} + +/// An observer's mirror after a few patches (entity count). +fn observed(h: &mut ZoneHost, clock: &ManualClock, mirror: &mut ClientMirror, o: ClientId) { + for _ in 0..4 { + clock.advance(MS(100)); + h.advance(); + for frame in frames_for(&h.drain_outbound(), o) { + mirror.apply(&frame).unwrap(); + } + } +} + +#[test] +fn focus_gives_an_observer_the_zones_view_radius() { + for (view_radius, seen) in [(None, 1), (Some(5.0), 0)] { + let clock = ManualClock::new(); + let cfg = ArenaConfig { + view_radius, + ..ArenaConfig::default() + }; + let mut h = host(HostConfig::default(), &clock, cfg); + h.join(&claims("alice", "z1"), 0, "").unwrap(); + let mut obs = claims("watcher", "z1"); + obs.role = Role::Observer; + let o = h.join(&obs, 0, "").unwrap(); + let mut mirror = ClientMirror::new(); + observed(&mut h, &clock, &mut mirror, o.client); + assert_eq!(mirror.entities.len(), 1, "the whole arena before Focus"); + // Alice is 10..90 on both axes: 20 m beyond the corner is out of a + // 5 m view, inside the observer's own 1000 m one. + h.observer_focus(o.client, -20.0, -20.0); + observed(&mut h, &clock, &mut mirror, o.client); + assert_eq!(mirror.entities.len(), seen, "view radius {view_radius:?}"); + } +} + +#[test] +fn welcome_carries_features_and_origin() { + use distributed_game::protocol::feature; + use distributed_game::Origin; + let clock = ManualClock::new(); + let cfg = ArenaConfig { + origin: Some(Origin::new(120.0, -40.0)), + ..ArenaConfig::default() + }; + let mut h = host(HostConfig::default(), &clock, cfg); + let joined = h.join(&claims("ana", "z1"), 0, "").unwrap(); + let frame = frames_for(&h.drain_outbound(), joined.client).remove(0); + let Ok(ServerMessage::Welcome(w)) = ClientMirror::new().apply(&frame) else { + panic!("Welcome") + }; + assert_eq!(w.features & feature::FOCUS, feature::FOCUS); + assert_eq!(w.origin, Some(Origin::new(120.0, -40.0))); +} + +#[test] +fn same_principal_replaces_previous_connection() { + let clock = ManualClock::new(); + let mut h = host(HostConfig::default(), &clock, ArenaConfig::default()); + let a = h.join(&claims("alice", "z1"), 0, "").unwrap(); + for seq in 1..=5 { + assert_eq!( + h.push_input(a.client, seq, 0, &[1, 0]), + PushOutcome::Accepted + ); + } + clock.advance(MS(200)); + h.advance(); + h.drain_outbound(); + + // A fresh ticket (e.g. page reload) replaces the connection and is a new + // client session: its inputs number from 1 again and must not be stale, + // and the zone sees on_rejoin (default: leave(Rejoined) + join) so it can + // resend per-player state. + let b = h.join(&claims("alice", "z1"), 0, "").unwrap(); + assert_eq!(a.viewer, b.viewer); + assert_eq!(h.client_count(), 1); + let out = h.drain_outbound(); + assert!(out.contains(&Outbound::Close { client: a.client })); + assert_eq!( + h.zone().log, + vec!["create", "join:alice", "leave:Rejoined", "join:alice"] + ); + assert_eq!(h.push_input(b.client, 1, 0, &[0, 1]), PushOutcome::Accepted); + clock.advance(MS(100)); + h.advance(); + let mut mirror = ClientMirror::new(); + let later = h.drain_outbound(); + for frame in frames_for(&out, b.client) + .into_iter() + .chain(frames_for(&later, b.client)) + { + mirror.apply(&frame).unwrap(); + } + assert_eq!(mirror.ack_seq, 1, "new session acked from its own sequence"); +} + +#[test] +fn boot_epoch_defaults_to_wall_clock_and_can_be_pinned() { + let clock = ManualClock::new(); + let default = host(HostConfig::default(), &clock, ArenaConfig::default()); + assert!( + default.config().boot_epoch > 1_600_000_000_000_000, + "unix micros" + ); + let pinned = host( + HostConfig { + boot_epoch: 42, + ..HostConfig::default() + }, + &clock, + ArenaConfig::default(), + ); + assert_eq!(pinned.config().boot_epoch, 42); + assert_eq!( + distributed_game::fact_key( + "kill", + pinned.zone_id(), + pinned.config().boot_epoch, + &[&7, &"m"] + ), + "kill:z1:42:7:m" + ); +} + +/// Sink where keys starting with `slow` take `delay`; records completion order. +struct LaggySink { + delay: Duration, + done: Arc>>, +} + +impl FactSink for LaggySink { + fn commit<'a>( + &'a self, + fact: &'a Fact, + ) -> distributed_game::BoxFuture<'a, Result> { + Box::pin(async move { + if fact.key().starts_with("slow") { + tokio::time::sleep(self.delay).await; + } + self.done.lock().unwrap().push(fact.key().to_string()); + Ok(FactReceipt { + payload: serde_json::Value::Null, + replayed: false, + }) + }) + } +} + +async fn commit_order(concurrency: usize) -> Vec { + let done = Arc::new(std::sync::Mutex::new(Vec::new())); + let (mut queue, feed) = fact_channel(16, RetryPolicy::default()); + let worker = tokio::spawn(feed.with_max_concurrent_commits(concurrency).run( + LaggySink { + delay: MS(300), + done: done.clone(), + }, + tokio::time::sleep, + )); + let fact = |key: &str, principal: &str| { + Fact::trusted( + key, + "cmd", + serde_json::Value::Null, + Some(principal.into()), + Default::default(), + ) + }; + queue.try_send(fact("slow-a1", "alice")).unwrap(); + queue.try_send(fact("fast-a2", "alice")).unwrap(); + queue.try_send(fact("fast-b1", "bob")).unwrap(); + queue.try_send(fact("fast-c1", "carol")).unwrap(); + let started = Instant::now(); + while queue.in_flight() > 0 { + queue.drain(); + assert!(started.elapsed() < Duration::from_secs(5), "settles"); + tokio::time::sleep(MS(5)).await; + } + drop(queue); + worker.await.unwrap(); + let order = done.lock().unwrap().clone(); + order +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn concurrent_commits_do_not_block_other_principals_and_keep_lane_order() { + // Default: strict emission order, the slow commit blocks everyone. + assert_eq!( + commit_order(1).await, + vec!["slow-a1", "fast-a2", "fast-b1", "fast-c1"] + ); + // Concurrency: bob and carol overtake; alice's second fact waits for + // her first (same principal lane). + let order = commit_order(4).await; + assert_eq!(order.len(), 4); + let pos = |k: &str| order.iter().position(|o| o == k).unwrap(); + assert!(pos("fast-b1") < pos("slow-a1"), "{order:?}"); + assert!(pos("fast-c1") < pos("slow-a1"), "{order:?}"); + assert!(pos("slow-a1") < pos("fast-a2"), "{order:?}"); +} + +/// Consumes inputs through `InputCredits` (bank of 3). +struct Paced { + credits: distributed_game::InputCredits, + consumed: Vec, +} + +impl distributed_game::Zone for Paced { + type Config = (); + type Input = u8; + type Timer = (); + type Message = distributed_game::NoMessages; + + fn schema() -> distributed_game::EntitySchema { + distributed_game::EntitySchema::new() + } + + fn on_create(_ctx: &mut distributed_game::Ctx<'_, Self>, _config: ()) -> Self { + Self { + credits: distributed_game::InputCredits::new(3), + consumed: Vec::new(), + } + } + + fn decode_input(&self, _player: distributed_game::PlayerId, payload: &[u8]) -> Option { + payload.first().copied() + } + + fn on_tick(&mut self, ctx: &mut distributed_game::Ctx<'_, Self>) { + let players: Vec<_> = ctx.players().map(|p| p.id).collect(); + let mut n = 0; + for player in players { + n += self.credits.take(ctx, player).len(); + } + self.consumed.push(n); + } + + fn replicate(&self, _out: &mut distributed_game::WorldView) {} +} + +#[test] +fn input_credits_cap_inputs_per_tick_and_absorb_bursts() { + let clock = ManualClock::new(); + let mut h: ZoneHost = + ZoneHost::new("z1", HostConfig::default(), Arc::new(clock.clone()), ()); + let joined = h.join(&claims("ana", "z1"), 0, "").unwrap(); + for seq in 1..=10 { + h.push_input(joined.client, seq, 0, &[1]); + } + for _ in 0..5 { + clock.advance(Duration::from_secs_f64(1.0 / 30.0) + MS(1)); + h.advance(); + } + // Full bank of 3 spent on the burst, then one input per tick. + assert_eq!(h.zone().consumed[..5], [3, 1, 1, 1, 1]); +} + +/// Queued facts wait in the host's backlog behind a full queue, in order, +/// count as in flight, and go out one by one as settlements free capacity. +#[test] +fn queued_facts_wait_in_the_host_backlog_in_order() { + let clock = ManualClock::new(); + let cfg = ArenaConfig { + queue_facts: true, + ..ArenaConfig::default() + }; + let (queue, script) = distributed_game::FactQueue::scripted(1); + let mut h = host(HostConfig::default(), &clock, cfg).with_facts(queue.with_journal()); + let joined = h.join(&claims("ana", "z1"), 0, "").unwrap(); + let distributed_game::Viewer::Player(ana) = joined.viewer else { + panic!("a player") + }; + let key = |tick: u64| format!("step:{tick}:{}", ana.0); + let step = |h: &mut ZoneHost| { + clock.advance(MS(34)); + assert_eq!(h.advance().ticks, 1); + }; + for _ in 0..3 { + step(&mut h); + } + // Capacity 1: the first is sent, two wait; nothing refused. + let sent: Vec = h + .take_emitted_facts() + .iter() + .map(|f| f.key().into()) + .collect(); + assert_eq!(sent, [key(1)]); + assert_eq!(h.facts_in_flight(), 3); + assert!(h.zone().emit_errors.is_empty()); + // Each settlement frees the slot for the oldest waiting fact. + let settle = |key: &str| distributed_game::FactSettlement { + key: key.into(), + command: "step".into(), + outcome: FactOutcome::Committed(FactReceipt { + payload: serde_json::Value::Null, + replayed: false, + }), + }; + let mut order = sent; + for _ in 0..3 { + let key = order.last().unwrap().clone(); + script.push(h.tick() + 1, settle(&key)); + step(&mut h); + step(&mut h); + order.extend(h.take_emitted_facts().iter().map(|f| f.key().to_string())); + } + assert_eq!(order, [key(1), key(2), key(3), key(4)]); + assert!(h.zone().emit_errors.is_empty()); + assert_eq!(h.zone().settled.len(), 3, "settlements reach the zone"); +} diff --git a/distributed_game/tests/zone_state/main.rs b/distributed_game/tests/zone_state/main.rs new file mode 100644 index 000000000..cda9ffe9e --- /dev/null +++ b/distributed_game/tests/zone_state/main.rs @@ -0,0 +1,245 @@ +//! `ZoneState` cells on the in-process reference host: the zone-state +//! fencing contract (`state_store_conformance`) through the cell's +//! commands, for inline snapshots and for snapshots in object storage (an +//! in-memory blob map standing in for celld's R2 binding, split exactly as +//! the worker route splits them), plus the command's own guards. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Mutex; + +use base64::Engine as _; +use distributed::cell_host::{ + AggregateCell, CausalDispatchError, CellCommandIdentity, CellStreamStore, +}; +use distributed::microsvc::{Session, ROLE_KEY, USER_ID_KEY}; +use distributed::StreamIdentity; +use distributed_game::cell::command_id_for; +use distributed_game::world::zone_state::{ + blob_key, mount_zone_state, sha256_hex, stale_current, SnapshotBytes, ZoneState, DELETE, SAVE, + ZONE_HOST_ROLE, ZONE_STATE_INLINE_MAX, +}; +use distributed_game::world::{ + state_store_conformance, StateError, StoredZoneState, ZoneStateStore, +}; +use distributed_game::BoxFuture; +use serde_json::{json, Value}; + +const B64: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD; + +fn host_session() -> Session { + let mut session = Session::new(); + session.set(USER_ID_KEY, "zone-server-a"); + session.set(ROLE_KEY, ZONE_HOST_ROLE); + session +} + +/// `ZoneStateStore` over one in-process cell + a blob map, as +/// `CellZoneStateStore` + the worker route are over celld. +struct InProcess { + cell: AggregateCell, + blobs: Mutex>>, + calls: AtomicU64, +} + +impl InProcess { + fn new(zone: &str) -> Self { + let store = CellStreamStore::for_identity(StreamIdentity::new("ZoneState", zone).unwrap()); + Self { + cell: mount_zone_state(AggregateCell::from_store(store).unwrap()), + blobs: Mutex::default(), + calls: AtomicU64::new(0), + } + } + + async fn dispatch( + &self, + command: &str, + input: Value, + session: Session, + ) -> Result { + let n = self.calls.fetch_add(1, Ordering::SeqCst); + let identity = CellCommandIdentity::new( + "zone-host", + "zone-server-a", + command_id_for("t", &n.to_string()), + ) + .unwrap(); + self.cell + .dispatch_idempotent(command, &identity, input, session) + .await + .map(|result| result.payload().clone()) + } + + async fn command( + &self, + command: &str, + input: Value, + uploaded: Option, + ) -> Result<(), StateError> { + let token = input["token"].as_u64().unwrap(); + match self.dispatch(command, input, host_session()).await { + Ok(payload) => { + if let Some(key) = payload["superseded_blob"].as_str() { + self.blobs.lock().unwrap().remove(key); + } + Ok(()) + } + Err(error) => { + if let Some(key) = uploaded { + self.blobs.lock().unwrap().remove(&key); + } + match error { + CausalDispatchError::Rejected { message, .. } => { + match stale_current(&message) { + Some(current) => Err(StateError::Stale { + presented: token, + current, + }), + None => Err(StateError::Backend(message)), + } + } + other => Err(StateError::Backend(format!("{other:?}"))), + } + } + } + } +} + +impl ZoneStateStore for InProcess { + fn load<'a>( + &'a self, + _zone_id: &'a str, + ) -> BoxFuture<'a, Result, StateError>> { + Box::pin(async move { + let Some(state) = self.cell.load().await.unwrap() else { + return Ok(None); + }; + let bytes = match state.bytes() { + None => return Ok(None), + Some(SnapshotBytes::Inline(bytes)) => bytes.clone(), + Some(SnapshotBytes::Blob(blob)) => { + let bytes = self + .blobs + .lock() + .unwrap() + .get(&blob.key) + .cloned() + .expect("blob"); + assert_eq!( + (bytes.len() as u64, sha256_hex(&bytes)), + (blob.len, blob.sha256.clone()) + ); + bytes + } + }; + Ok(Some(StoredZoneState { + token: state.token(), + content_version: state.content_version().to_string(), + state: bytes, + })) + }) + } + + fn save<'a>( + &'a self, + zone_id: &'a str, + state: &'a StoredZoneState, + ) -> BoxFuture<'a, Result<(), StateError>> { + Box::pin(async move { + if state.state.len() <= ZONE_STATE_INLINE_MAX { + let input = json!({ + "zone_id": zone_id, "token": state.token, "content_version": state.content_version, + "inline_b64": B64.encode(&state.state), "blob": null, + }); + self.command(SAVE, input, None).await + } else { + let sha = sha256_hex(&state.state); + let key = blob_key(zone_id, state.token, &sha); + self.blobs + .lock() + .unwrap() + .insert(key.clone(), state.state.clone()); + let input = json!({ + "zone_id": zone_id, "token": state.token, "content_version": state.content_version, + "inline_b64": null, + "blob": { "key": key, "sha256": sha, "len": state.state.len() }, + }); + self.command(SAVE, input, Some(key)).await + } + }) + } + + fn delete<'a>(&'a self, zone_id: &'a str, token: u64) -> BoxFuture<'a, Result<(), StateError>> { + Box::pin(async move { + self.command(DELETE, json!({ "zone_id": zone_id, "token": token }), None) + .await + }) + } +} + +#[tokio::test] +async fn inline_snapshots_meet_the_zone_state_contract() { + let store = InProcess::new("grid.0.0"); + state_store_conformance(&store, "grid.0.0", vec![3; 1_000]).await; + assert!( + store.blobs.lock().unwrap().is_empty(), + "small snapshots stay in the cell" + ); +} + +#[tokio::test] +async fn large_snapshots_go_to_object_storage_and_superseded_blobs_are_dropped() { + let store = InProcess::new("grid.1.0"); + let big = (0..ZONE_STATE_INLINE_MAX + 4_096) + .map(|i| (i % 251) as u8) + .collect::>(); + state_store_conformance(&store, "grid.1.0", big.clone()).await; + // Only the live snapshot's object remains (the stale upload, the + // superseded saves and the deleted one are gone). + let blobs = store.blobs.lock().unwrap(); + assert_eq!(blobs.len(), 1, "{:?}", blobs.keys().collect::>()); + assert_eq!(blobs.values().next().unwrap(), &big); + drop(blobs); + let state = store.cell.load().await.unwrap().unwrap(); + assert!( + matches!(state.bytes(), Some(SnapshotBytes::Blob(blob)) if blob.len == big.len() as u64) + ); +} + +#[tokio::test] +async fn commands_need_the_zone_host_role_and_one_well_formed_payload() { + let store = InProcess::new("grid.2.0"); + let input = json!({ + "zone_id": "grid.2.0", "token": 1, "content_version": "c", + "inline_b64": B64.encode(b"x"), "blob": null, + }); + let mut player = Session::new(); + player.set(USER_ID_KEY, "alice"); + assert!( + store.dispatch(SAVE, input.clone(), player).await.is_err(), + "players cannot write zone state" + ); + + let both = json!({ + "zone_id": "grid.2.0", "token": 1, "content_version": "c", "inline_b64": B64.encode(b"x"), + "blob": { "key": "k", "sha256": sha256_hex(b"x"), "len": 1 }, + }); + let neither = json!({ "zone_id": "grid.2.0", "token": 1, "content_version": "c", "inline_b64": null, "blob": null }); + let oversized = json!({ + "zone_id": "grid.2.0", "token": 1, "content_version": "c", + "inline_b64": B64.encode(vec![0u8; ZONE_STATE_INLINE_MAX + 1]), "blob": null, + }); + let bad_digest = json!({ + "zone_id": "grid.2.0", "token": 1, "content_version": "c", "inline_b64": null, + "blob": { "key": "k", "sha256": "nope", "len": 1 }, + }); + for bad in [both, neither, oversized, bad_digest] { + assert!(matches!( + store.dispatch(SAVE, bad, host_session()).await, + Err(CausalDispatchError::Rejected { .. }) + )); + } + store.dispatch(SAVE, input, host_session()).await.unwrap(); + assert_eq!(store.load("grid.2.0").await.unwrap().unwrap().state, b"x"); +} diff --git a/distributed_game/tests/zone_status/main.rs b/distributed_game/tests/zone_status/main.rs new file mode 100644 index 000000000..4d8344b96 --- /dev/null +++ b/distributed_game/tests/zone_status/main.rs @@ -0,0 +1,384 @@ +//! The zone status read model end to end on the reference host: lease and +//! zone-state cells commit their outward events into their outboxes; the +//! messages go onto a SQLite bus; the `zone_status` projectors (a consumer +//! service like any other) upsert `zone_leases` / `zone_snapshots`; and +//! `ZoneStatus::of` tells active, hibernated and cold zones apart without +//! opening a cell. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::{Duration, Instant, SystemTime}; + +use distributed::bus::{Message, MessagePublisher, SqliteBus}; +use distributed::cell_host::{AggregateCell, CellCommandIdentity, CellStreamStore}; +use distributed::microsvc::{ + spawn_service_consumer_loop, CausalProjectorContext, HandlerError, ModeledProjection, Routes, + Service, Session, ROLE_KEY, USER_ID_KEY, +}; +use distributed::{Aggregate, BusPublisher, ManualClock, SqliteRepository, StreamIdentity}; +use distributed_game::cell::command_id_for; +use distributed_game::world::zone_lease::{mount_zone_lease, ZoneLease, ACQUIRE, RELEASE}; +use distributed_game::world::zone_state::{mount_zone_state, ZoneState, SAVE, ZONE_HOST_ROLE}; +use distributed_game::world::zone_status::{ + projectors, read_model_catalog, ZoneLeases, ZoneSnapshots, ZoneStatus, APPLICATION, + ZONE_LEASES, ZONE_SNAPSHOTS, +}; +use serde_json::{json, Value}; + +const T0: u64 = 1_700_000_000_000; +static CALLS: AtomicU64 = AtomicU64::new(0); + +fn host_session() -> Session { + let mut session = Session::new(); + session.set(USER_ID_KEY, "zone-server-a"); + session.set(ROLE_KEY, ZONE_HOST_ROLE); + session +} + +fn cell( + kind: &str, + zone: &str, + clock: &ManualClock, +) -> AggregateCell { + let store = CellStreamStore::for_identity(StreamIdentity::new(kind, zone).unwrap()) + .with_clock(clock.clone()); + AggregateCell::from_store(store).unwrap() +} + +async fn dispatch( + cell: &AggregateCell, + command: &str, + input: Value, +) -> Value { + let n = CALLS.fetch_add(1, Ordering::SeqCst); + let identity = CellCommandIdentity::new( + "zone-host", + "zone-server-a", + command_id_for("t", &n.to_string()), + ) + .unwrap(); + cell.dispatch_idempotent(command, &identity, input, host_session()) + .await + .unwrap_or_else(|error| panic!("{command}: {error:?}")) + .payload() + .clone() +} + +async fn project_leases( + context: CausalProjectorContext, + projection: ModeledProjection, +) -> Result<(), HandlerError> { + projection.apply(ZONE_LEASES, &context).await +} + +async fn project_snapshots( + context: CausalProjectorContext, + projection: ModeledProjection, +) -> Result<(), HandlerError> { + projection.apply(ZONE_SNAPSHOTS, &context).await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn cell_events_project_into_zone_status_rows() { + let clock = ManualClock::new(SystemTime::UNIX_EPOCH + Duration::from_millis(T0)); + // z-active: held. z-asleep: held, snapshot saved, released. + // z-cold: held and released without a snapshot. + let active = mount_zone_lease(cell::("ZoneLease", "z-active", &clock)); + let asleep = mount_zone_lease(cell::("ZoneLease", "z-asleep", &clock)); + let asleep_state = mount_zone_state(cell::("ZoneState", "z-asleep", &clock)); + let cold = mount_zone_lease(cell::("ZoneLease", "z-cold", &clock)); + let acquire = |zone: &str| json!({ "zone_id": zone, "holder": "A#1", "ttl_ms": 60_000 }); + dispatch(&active, ACQUIRE, acquire("z-active")).await; + let held = dispatch(&asleep, ACQUIRE, acquire("z-asleep")).await; + use base64::Engine as _; + dispatch( + &asleep_state, + SAVE, + json!({ "zone_id": "z-asleep", "token": held["token"], "content_version": "v1", + "inline_b64": base64::engine::general_purpose::STANDARD.encode([7u8; 42]) }), + ) + .await; + dispatch( + &asleep, + RELEASE, + json!({ "zone_id": "z-asleep", "holder": "A#1", "token": held["token"] }), + ) + .await; + let held = dispatch(&cold, ACQUIRE, acquire("z-cold")).await; + dispatch( + &cold, + RELEASE, + json!({ "zone_id": "z-cold", "holder": "A#1", "token": held["token"] }), + ) + .await; + + // Outbox → bus, in commit order per cell. + let dir = std::env::temp_dir().join(format!( + "zone-status-{}-{}", + std::process::id(), + CALLS.load(Ordering::SeqCst) + )); + std::fs::create_dir_all(&dir).unwrap(); + let bus_url = format!("sqlite:{}?mode=rwc", dir.join("bus.db").display()); + let pool = sqlx::SqlitePool::connect(&bus_url).await.unwrap(); + let bus = SqliteBus::new(pool.clone()); + bus.ensure_tables().await.unwrap(); + let publisher = BusPublisher::new(Arc::new(bus)); + let mut messages = Vec::new(); + messages.extend(active.durable_outbox().unwrap()); + messages.extend(asleep.durable_outbox().unwrap()); + messages.extend(asleep_state.durable_outbox().unwrap()); + messages.extend(cold.durable_outbox().unwrap()); + messages.sort_by_key(|m| m.created_at); + assert_eq!(messages.len(), 6, "activated ×3, released ×2, saved"); + for message in messages { + publisher.publish(Message::from(message)).await.unwrap(); + } + + // The projectors, as a consumer service. + let read_url = format!("sqlite:{}?mode=rwc", dir.join("read.db").display()); + let repo = SqliteRepository::connect_and_migrate(&read_url) + .await + .unwrap(); + repo.bootstrap_table_schema_for_dev(&read_model_catalog().table_registry().unwrap()) + .await + .unwrap(); + let read_models = repo.clone(); + spawn_service_consumer_loop(move || { + let (leases, snapshots) = projectors(); + Service::new() + .named(APPLICATION) + .routes( + Routes::new() + .with_read_model_store(read_models.clone()) + .modeled_projector(leases) + .handle(project_leases) + .modeled_projector(snapshots) + .handle(project_snapshots), + ) + .with_bus(SqliteBus::new(pool.clone())) + }); + + let status = |zone: &'static str| { + let repo = repo.clone(); + async move { + let lease: Option = sqlx::query_as::<_, (String, String, i64, String)>( + "SELECT zone_id, holder, token, status FROM zone_leases WHERE zone_id = ?", + ) + .bind(zone) + .fetch_optional(repo.pool()) + .await + .unwrap() + .map(|(zone_id, holder, token, status)| ZoneLeases { + zone_id, + holder, + token, + status, + }); + let snapshot: Option = + sqlx::query_as::<_, (String, i64, bool, String, i64)>( + "SELECT zone_id, token, stored, content_version, bytes FROM zone_snapshots WHERE zone_id = ?", + ) + .bind(zone) + .fetch_optional(repo.pool()) + .await + .unwrap() + .map(|(zone_id, token, stored, content_version, bytes)| ZoneSnapshots { + zone_id, + token, + stored, + content_version, + bytes, + }); + (lease, snapshot) + } + }; + let start = Instant::now(); + loop { + let (lease, snapshot) = status("z-asleep").await; + let done = lease.as_ref().is_some_and(|l| l.status == "released") && snapshot.is_some(); + if done + && status("z-cold") + .await + .0 + .is_some_and(|l| l.status == "released") + { + break; + } + assert!( + start.elapsed() < Duration::from_secs(20), + "projection timed out" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } + let of = |(lease, snapshot): (Option, Option)| { + ZoneStatus::of(lease.as_ref(), snapshot.as_ref()) + }; + assert_eq!( + of(status("z-active").await), + ZoneStatus::Active { + holder: "A#1".into() + } + ); + assert_eq!( + of(status("z-asleep").await), + ZoneStatus::Hibernated { bytes: 42 } + ); + let (_, snapshot) = status("z-asleep").await; + assert_eq!(snapshot.unwrap().content_version, "v1"); + assert_eq!(of(status("z-cold").await), ZoneStatus::Cold); + assert_eq!(of(status("z-never").await), ZoneStatus::Cold); + let _ = std::fs::remove_dir_all(dir); +} + +/// A celld-hosted zone's lifecycle reports (`zone_activity.record` facts) +/// project into `zone_activities`; a report emitted earlier but settled +/// later never overwrites a newer one; only the zone itself may report. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn zone_activity_reports_project_into_zone_status() { + use distributed_game::cell::trusted_session; + use distributed_game::world::zone_activity::{ + mount_zone_activity, zone_principal, RecordActivity, ZoneActivity, RECORD, + }; + use distributed_game::world::zone_status::{ + activity_projector_for, ZoneActivities, ZONE_ACTIVITIES, + }; + use distributed_game::{Fact, FactStamp}; + + let clock = ManualClock::new(SystemTime::UNIX_EPOCH + Duration::from_millis(T0)); + let cell = mount_zone_activity(cell::("ZoneActivity", "pit.0.1", &clock)); + let report = |status: &str, seq: u64, principal: &str| { + let fact = Fact::trusted( + format!("zone_activity.record:pit.0.1:9:{seq}"), + RECORD, + serde_json::to_value(RecordActivity { + status: status.into(), + activation: "act-1".into(), + restored: status == "active" && seq > 1, + players: u32::from(status == "active"), + node: "node-b".into(), + isolate: "iso".into(), + }) + .unwrap(), + Some(principal.to_string()), + FactStamp { + zone_id: "pit.0.1".into(), + activation: 9, + seq, + emitted_at_ms: T0 + seq, + ..FactStamp::default() + }, + ); + (fact.clone(), trusted_session(principal, &fact)) + }; + let send = |status: &'static str, seq: u64, principal: &'static str| { + let cell = &cell; + async move { + let (fact, session) = report(status, seq, principal); + let identity = CellCommandIdentity::new( + "celld-zone", + principal, + command_id_for("celld-zone", fact.key()), + ) + .unwrap(); + cell.dispatch_idempotent(RECORD, &identity, fact.input().clone(), session) + .await + } + }; + let me = Box::leak(zone_principal("pit.0.1").into_boxed_str()); + assert_eq!( + send("active", 1, me).await.unwrap().payload()["applied"], + true + ); + assert_eq!( + send("hibernated", 3, me).await.unwrap().payload()["applied"], + true + ); + // Emitted before `hibernated`, settled after it: ignored. + let late = send("dormant", 2, me).await.unwrap(); + assert_eq!(late.payload()["applied"], false); + assert_eq!(late.payload()["status"], "hibernated"); + assert!( + send("active", 4, "guest-x").await.is_err(), + "only the zone reports" + ); + assert_eq!(cell.load().await.unwrap().unwrap().status(), "hibernated"); + + let dir = std::env::temp_dir().join(format!( + "zone-activity-{}-{}", + std::process::id(), + SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + let bus_url = format!("sqlite:{}?mode=rwc", dir.join("bus.db").display()); + let pool = sqlx::SqlitePool::connect(&bus_url).await.unwrap(); + let bus = SqliteBus::new(pool.clone()); + bus.ensure_tables().await.unwrap(); + let publisher = BusPublisher::new(Arc::new(bus)); + let mut messages = cell.durable_outbox().unwrap(); + messages.sort_by_key(|m| m.created_at); + assert_eq!(messages.len(), 2, "one event per applied report"); + for message in messages { + publisher.publish(Message::from(message)).await.unwrap(); + } + let read_url = format!("sqlite:{}?mode=rwc", dir.join("read.db").display()); + let repo = SqliteRepository::connect_and_migrate(&read_url) + .await + .unwrap(); + repo.bootstrap_table_schema_for_dev(&read_model_catalog().table_registry().unwrap()) + .await + .unwrap(); + let read_models = repo.clone(); + async fn project( + context: CausalProjectorContext, + projection: ModeledProjection, + ) -> Result<(), HandlerError> { + projection.apply(ZONE_ACTIVITIES, &context).await + } + // A consumer of its own (a minimap service would be one too). + spawn_service_consumer_loop(move || { + Service::new() + .named("zone-minimap") + .routes( + Routes::new() + .with_read_model_store(read_models.clone()) + .modeled_projector(activity_projector_for("zone-minimap")) + .handle(project), + ) + .with_bus(SqliteBus::new(pool.clone())) + }); + let start = Instant::now(); + let row = loop { + let row = sqlx::query_as::<_, (String, String, String, i64)>( + "SELECT zone_id, status, node, activations FROM zone_activities WHERE zone_id = ?", + ) + .bind("pit.0.1") + .fetch_optional(repo.pool()) + .await + .unwrap(); + if let Some(row) = row.filter(|row| row.1 == "hibernated") { + break row; + } + assert!( + start.elapsed() < Duration::from_secs(20), + "projection timed out" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + }; + assert_eq!(row.2, "node-b"); + assert_eq!(row.3, 1); + let activity = ZoneActivities { + zone_id: row.0, + status: row.1, + node: row.2, + ..ZoneActivities::default() + }; + assert_eq!( + ZoneStatus::of_activity(Some(&activity)), + ZoneStatus::Hibernated { bytes: 0 } + ); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/distributed_game_macros/Cargo.toml b/distributed_game_macros/Cargo.toml new file mode 100644 index 000000000..e84b5dd13 --- /dev/null +++ b/distributed_game_macros/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "distributed_game_macros" +version.workspace = true +edition.workspace = true +description = "Authoring derives for distributed_game: Replicated, GameInput, GameEvent, GameRecord, FactCommand" +license.workspace = true +repository.workspace = true + +[lib] +proc-macro = true + +[dependencies] +proc-macro-crate = "3.5" +proc-macro2 = "1.0" +quote = "1.0" +syn = { version = "2.0", features = ["full"] } + +[dev-dependencies] +# Compile-fail snapshots depend on trybuild's compiler-diagnostic normalization. +trybuild = "=1.0.121" +# Dev-only cycle (as in distributed_macros): fixtures need the runtime crate. +distributed_game = { path = "../distributed_game" } +serde = { version = "1", features = ["derive"] } +serde_json = "1" diff --git a/distributed_game_macros/src/claims.rs b/distributed_game_macros/src/claims.rs new file mode 100644 index 000000000..fd489190e --- /dev/null +++ b/distributed_game_macros/src/claims.rs @@ -0,0 +1,69 @@ +//! `#[derive(TicketExtension)]`: declare the extension claims a ticket +//! issuer may vouch for (match id, team, party…). + +use proc_macro2::TokenStream; +use quote::quote; +use syn::{DeriveInput, LitStr}; + +use crate::shared::{field_name, named_fields, no_generics, runtime}; +use crate::trusted::reject_forbidden; + +pub(crate) fn expand(input: DeriveInput) -> syn::Result { + no_generics(&input, "TicketExtension")?; + let rt = runtime()?; + // Container-wide renames would change the names the schema admits + // behind the deny list's back. + for attr in input.attrs.iter().filter(|a| a.path().is_ident("serde")) { + attr.parse_nested_meta(|meta| { + if meta.path.is_ident("rename_all") || meta.path.is_ident("rename_all_fields") { + return Err(meta.error( + "#[derive(TicketExtension)] does not support `rename_all`; rename fields individually", + )); + } + if meta.input.peek(syn::Token![=]) { + let _ = meta.value()?.parse::()?; + } else if meta.input.peek(syn::token::Paren) { + meta.parse_nested_meta(|_| Ok(()))?; + } + Ok(()) + })?; + } + let fields = named_fields(&input, "TicketExtension")?; + reject_forbidden( + &fields, + "ticket claim", + "identity is only ever the verified `sub`, and rewards and economy values are decided by command handlers, never vouched for in a ticket", + )?; + let mut names = Vec::new(); + for field in &fields { + let mut name = field_name(field.ident.as_ref().expect("named")); + for attr in field.attrs.iter().filter(|a| a.path().is_ident("serde")) { + attr.parse_nested_meta(|meta| { + if meta.path.is_ident("flatten") { + return Err(meta.error( + "#[derive(TicketExtension)] does not support `flatten`; declare every claim as a field", + )); + } + if meta.path.is_ident("rename") { + if meta.input.peek(syn::Token![=]) { + name = meta.value()?.parse::()?.value(); + } else { + return Err(meta.error("use `rename = \"..\"` (one name for both directions)")); + } + } else if meta.input.peek(syn::Token![=]) { + let _ = meta.value()?.parse::()?; + } else if meta.input.peek(syn::token::Paren) { + meta.parse_nested_meta(|_| Ok(()))?; + } + Ok(()) + })?; + } + names.push(name); + } + let ident = &input.ident; + Ok(quote! { + impl #rt::TicketExtension for #ident { + const CLAIMS: &'static [&'static str] = &[#(#names),*]; + } + }) +} diff --git a/distributed_game_macros/src/event.rs b/distributed_game_macros/src/event.rs new file mode 100644 index 000000000..710f309d2 --- /dev/null +++ b/distributed_game_macros/src/event.rs @@ -0,0 +1,334 @@ +//! `#[derive(GameEvent)]` and `#[derive(GameRecord)]`: typed payloads with +//! the shared value codec. + +use proc_macro2::TokenStream; +use quote::{format_ident, quote}; +use syn::spanned::Spanned; +use syn::{Data, DeriveInput, Field, Fields, Ident, LitInt, LitStr}; + +use crate::shared::{ + check_name, field_name, find_attr, named_fields, no_generics, parse_field_attrs, payload_codec, + reject, runtime, snake_case, +}; + +/// Encode/decode/surface tokens for a list of named fields read through +/// `access(ident)` (e.g. `&self.x` or a bound pattern variable). +struct FieldsCodec { + encodes: Vec, + decodes: Vec, + surfaces: Vec, + records: Vec, +} + +fn fields_codec( + fields: &[&Field], + derive: &str, + rt: &TokenStream, + access: impl Fn(&Ident) -> TokenStream, +) -> syn::Result { + let p = quote!(#rt::__private); + let mut out = FieldsCodec { + encodes: Vec::new(), + decodes: Vec::new(), + surfaces: Vec::new(), + records: Vec::new(), + }; + for field in fields { + let fid = field.ident.as_ref().expect("named"); + let fa = parse_field_attrs(field, rt)?; + reject(fa.priority.as_ref().map(|x| x.1), "#[priority]", derive)?; + reject(fa.correct.as_ref().map(|x| x.1), "#[correct]", derive)?; + reject(fa.range.as_ref().map(|x| x.2), "#[range]", derive)?; + reject(fa.buttons.as_ref().map(|x| x.1), "#[buttons]", derive)?; + let codec = payload_codec( + &field.ty, + access(fid), + fa.special.as_ref().map(|s| &s.0), + rt, + ); + let name = field_name(fid); + out.encodes.push(codec.encode); + let decode = codec.decode; + out.decodes.push(quote!(#fid: #decode)); + let wire_type = codec.wire_type; + out.surfaces + .push(quote!(#p::PayloadField::new(#name, #wire_type))); + out.records.push(codec.records); + } + Ok(out) +} + +pub(crate) fn expand_record(input: DeriveInput) -> syn::Result { + no_generics(&input, "GameRecord")?; + let rt = runtime()?; + let p = quote!(#rt::__private); + let fields = named_fields(&input, "GameRecord")?; + let c = fields_codec(&fields, "GameRecord", &rt, |f| quote!(&self.#f))?; + let ident = &input.ident; + let name = ident.to_string(); + let (encodes, decodes, surfaces, records) = (c.encodes, c.decodes, c.surfaces, c.records); + Ok(quote! { + impl #p::Wire for #ident { + fn wire_type() -> #p::WireType { + #p::WireType::Record { name: #p::std::string::String::from(#name) } + } + + fn encode(&self, w: &mut #p::Writer) { + let _ = &w; + #(#encodes)* + } + + fn decode(r: &mut #p::Reader<'_>) -> #p::std::result::Result { + let _ = &r; + #p::std::result::Result::Ok(Self { #(#decodes),* }) + } + + fn records(records: &mut #p::std::vec::Vec<#p::RecordSurface>) { + if records.iter().any(|r| r.name == #name) { + return; + } + records.push(#p::RecordSurface { + name: #p::std::string::String::from(#name), + fields: #p::std::vec![#(#surfaces),*], + }); + #(#records)* + } + } + }) +} + +struct EventAttr { + id: u32, + id_span: proc_macro2::Span, + name: Option, +} + +fn parse_event_attr( + attrs: &[syn::Attribute], + span: proc_macro2::Span, + what: &str, +) -> syn::Result { + let Some(attr) = find_attr(attrs, "game_event") else { + return Err(syn::Error::new( + span, + format!("{what} needs #[game_event(id = N)] (a stable u32 type id)"), + )); + }; + let (mut id, mut name) = (None, None); + attr.parse_nested_meta(|meta| { + if meta.path.is_ident("id") { + let lit: LitInt = meta.value()?.parse()?; + id = Some((lit.base10_parse::()?, lit.span())); + } else if meta.path.is_ident("name") { + name = Some(check_name(&meta.value()?.parse::()?)?); + } else { + return Err(meta.error("expected `id` or `name` in #[game_event(..)]")); + } + Ok(()) + })?; + let Some((id, id_span)) = id else { + return Err(syn::Error::new( + attr.path().span(), + "#[game_event(..)] needs a literal `id = N`", + )); + }; + Ok(EventAttr { id, id_span, name }) +} + +pub(crate) fn expand_event(input: DeriveInput) -> syn::Result { + no_generics(&input, "GameEvent")?; + match &input.data { + Data::Struct(_) => expand_struct_event(&input), + Data::Enum(_) => expand_enum_event(&input), + Data::Union(_) => Err(syn::Error::new( + input.ident.span(), + "#[derive(GameEvent)] supports structs and enums", + )), + } +} + +fn expand_struct_event(input: &DeriveInput) -> syn::Result { + let rt = runtime()?; + let p = quote!(#rt::__private); + let attr = parse_event_attr(&input.attrs, input.ident.span(), "a struct event")?; + let fields = named_fields(input, "GameEvent")?; + let c = fields_codec(&fields, "GameEvent", &rt, |f| quote!(&self.#f))?; + let ident = &input.ident; + let id = attr.id; + let name = attr.name.unwrap_or_else(|| snake_case(&ident.to_string())); + let (encodes, decodes, surfaces, records) = (c.encodes, c.decodes, c.surfaces, c.records); + Ok(quote! { + impl #ident { + /// Stable event type id. + pub const EVENT_ID: u32 = #id; + } + + impl #rt::GameEvent for #ident { + fn event_id(&self) -> u32 { + #id + } + + fn encode_payload(&self, w: &mut #p::Writer) { + let _ = &w; + #(#encodes)* + } + + fn decode_event( + type_id: u32, + payload: &[u8], + ) -> #p::std::result::Result<#p::std::option::Option, #p::DecodeError> { + if type_id != #id { + return #p::std::result::Result::Ok(#p::std::option::Option::None); + } + #p::decode_whole(payload, |r| { + let _ = &r; + #p::std::result::Result::Ok(Self { #(#decodes),* }) + }) + .map(#p::std::option::Option::Some) + } + + fn event_surfaces( + records: &mut #p::std::vec::Vec<#p::RecordSurface>, + ) -> #p::std::vec::Vec<#p::EventSurface> { + #(#records)* + let _ = &records; + #p::std::vec![#p::EventSurface { + id: #id, + name: #p::std::string::String::from(#name), + payload: #p::EventPayload::Fields { fields: #p::std::vec![#(#surfaces),*] }, + }] + } + } + }) +} + +fn expand_enum_event(input: &DeriveInput) -> syn::Result { + let rt = runtime()?; + let p = quote!(#rt::__private); + let Data::Enum(data) = &input.data else { + unreachable!() + }; + if data.variants.is_empty() { + return Err(syn::Error::new( + input.ident.span(), + "an event enum needs at least one variant", + )); + } + let ident = &input.ident; + let mut seen: Vec<(u32, String)> = Vec::new(); + let (mut ids, mut encodes, mut decodes, mut surfaces, mut consts) = + (Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new()); + for variant in &data.variants { + let vid = &variant.ident; + let attr = parse_event_attr(&variant.attrs, vid.span(), "every event variant")?; + let id = attr.id; + let name = attr.name.unwrap_or_else(|| snake_case(&vid.to_string())); + if let Some((_, other)) = seen.iter().find(|(i, n)| *i == id || *n == name) { + return Err(syn::Error::new( + attr.id_span, + format!("event id {id} / name `{name}` already used by `{other}`"), + )); + } + seen.push((id, name.clone())); + let const_name = format_ident!("{}", snake_case(&vid.to_string()).to_uppercase()); + let doc = format!("Type id of [`{ident}::{vid}`]."); + consts.push(quote!(#[doc = #doc] pub const #const_name: u32 = #id;)); + match &variant.fields { + Fields::Unit => { + ids.push(quote!(Self::#vid => #id)); + encodes.push(quote!(Self::#vid => {})); + decodes.push(quote!(#id => #p::decode_whole(payload, |_| #p::std::result::Result::Ok(Self::#vid)))); + surfaces.push(quote! { + #p::EventSurface { + id: #id, + name: #p::std::string::String::from(#name), + payload: #p::EventPayload::Fields { fields: #p::std::vec::Vec::new() }, + } + }); + } + Fields::Named(named) => { + let fields: Vec<&Field> = named.named.iter().collect(); + let bind: Vec<&Ident> = fields + .iter() + .map(|f| f.ident.as_ref().expect("named")) + .collect(); + let c = fields_codec(&fields, "GameEvent", &rt, |f| quote!(#f))?; + let (enc, dec, surf, recs) = (c.encodes, c.decodes, c.surfaces, c.records); + ids.push(quote!(Self::#vid { .. } => #id)); + encodes.push(quote!(Self::#vid { #(#bind),* } => { #(#enc)* })); + decodes.push(quote!(#id => #p::decode_whole(payload, |r| { + let _ = &r; + #p::std::result::Result::Ok(Self::#vid { #(#dec),* }) + }))); + surfaces.push(quote! {{ + #(#recs)* + #p::EventSurface { + id: #id, + name: #p::std::string::String::from(#name), + payload: #p::EventPayload::Fields { fields: #p::std::vec![#(#surf),*] }, + } + }}); + } + Fields::Unnamed(unnamed) => { + if unnamed.unnamed.len() != 1 { + return Err(syn::Error::new( + variant.fields.span(), + "a tuple event variant carries exactly one value (use named fields for more)", + )); + } + let ty = &unnamed.unnamed[0].ty; + let codec = payload_codec(ty, quote!(value), None, &rt); + let (enc, dec, wt, recs) = + (codec.encode, codec.decode, codec.wire_type, codec.records); + ids.push(quote!(Self::#vid(..) => #id)); + encodes.push(quote!(Self::#vid(value) => { #enc })); + decodes.push(quote!(#id => #p::decode_whole(payload, |r| #p::std::result::Result::Ok(Self::#vid(#dec))))); + surfaces.push(quote! {{ + #recs + #p::EventSurface { + id: #id, + name: #p::std::string::String::from(#name), + payload: #p::EventPayload::Value { ty: #wt }, + } + }}); + } + } + } + Ok(quote! { + impl #ident { + #(#consts)* + } + + impl #rt::GameEvent for #ident { + fn event_id(&self) -> u32 { + match self { + #(#ids),* + } + } + + fn encode_payload(&self, w: &mut #p::Writer) { + let _ = &w; + match self { + #(#encodes)* + } + } + + fn decode_event( + type_id: u32, + payload: &[u8], + ) -> #p::std::result::Result<#p::std::option::Option, #p::DecodeError> { + match type_id { + #(#decodes.map(#p::std::option::Option::Some),)* + _ => #p::std::result::Result::Ok(#p::std::option::Option::None), + } + } + + fn event_surfaces( + records: &mut #p::std::vec::Vec<#p::RecordSurface>, + ) -> #p::std::vec::Vec<#p::EventSurface> { + let _ = &records; + #p::std::vec![#(#surfaces),*] + } + } + }) +} diff --git a/distributed_game_macros/src/fact.rs b/distributed_game_macros/src/fact.rs new file mode 100644 index 000000000..3757108d3 --- /dev/null +++ b/distributed_game_macros/src/fact.rs @@ -0,0 +1,78 @@ +//! `#[derive(FactCommand)]`: bind a cell command input type to its command +//! name so a zone can `ctx.emit(player, input)`. + +use proc_macro2::TokenStream; +use quote::quote; +use syn::spanned::Spanned; +use syn::{DeriveInput, Expr, Ident}; + +use crate::shared::{find_attr, named_fields, no_generics, runtime}; +use crate::trusted::reject_forbidden; + +pub(crate) fn expand(input: DeriveInput) -> syn::Result { + no_generics(&input, "FactCommand")?; + let rt = runtime()?; + let Some(attr) = find_attr(&input.attrs, "fact") else { + return Err(syn::Error::new( + input.ident.span(), + "#[derive(FactCommand)] needs #[fact(command = COMMAND_NAME)] (the constant the cell mounts the command under, or a string literal)", + )); + }; + let (mut command, mut key): (Option, Option>) = (None, None); + attr.parse_nested_meta(|meta| { + if meta.path.is_ident("command") { + command = Some(meta.value()?.parse()?); + } else if meta.path.is_ident("key") { + let mut parts = Vec::new(); + meta.parse_nested_meta(|part| { + let Some(ident) = part.path.get_ident() else { + return Err(part.error("key parts are field names")); + }; + parts.push(ident.clone()); + Ok(()) + })?; + key = Some(parts); + } else { + return Err(meta.error("expected `command = ..` or `key(field, ..)` in #[fact(..)]")); + } + Ok(()) + })?; + let Some(command) = command else { + return Err(syn::Error::new( + attr.path().span(), + "#[fact(..)] needs `command = ..`", + )); + }; + + let fields = named_fields(&input, "FactCommand")?; + reject_forbidden( + &fields, + "fact input", + "a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards and economy values", + )?; + + let parts = match &key { + None => quote!(::std::vec::Vec::new()), + Some(parts) => { + for part in parts { + if !fields.iter().any(|f| f.ident.as_ref() == Some(part)) { + return Err(syn::Error::new( + part.span(), + format!("no field `{part}` in this struct"), + )); + } + } + quote!(::std::vec![#(::std::string::ToString::to_string(&self.#parts)),*]) + } + }; + let ident = &input.ident; + Ok(quote! { + impl #rt::FactCommand for #ident { + const COMMAND: &'static str = #command; + + fn dedupe_parts(&self) -> ::std::vec::Vec<::std::string::String> { + #parts + } + } + }) +} diff --git a/distributed_game_macros/src/input.rs b/distributed_game_macros/src/input.rs new file mode 100644 index 000000000..f20a1d565 --- /dev/null +++ b/distributed_game_macros/src/input.rs @@ -0,0 +1,145 @@ +//! `#[derive(GameInput)]`: compact input codec + sanitize from one struct. + +use proc_macro2::TokenStream; +use quote::{format_ident, quote, quote_spanned}; +use syn::spanned::Spanned; +use syn::DeriveInput; + +use crate::shared::{ + field_name, named_fields, no_generics, parse_field_attrs, payload_codec, reject, runtime, + Special, +}; + +pub(crate) fn expand(input: DeriveInput) -> syn::Result { + no_generics(&input, "GameInput")?; + let rt = runtime()?; + let p = quote!(#rt::__private); + let fields = named_fields(&input, "GameInput")?; + let ident = &input.ident; + let type_name = ident.to_string(); + + let mut surfaces = Vec::new(); + let mut encodes = Vec::new(); + let mut decodes = Vec::new(); + let mut sanitizes = Vec::new(); + let mut consts = Vec::new(); + let mut const_names: Vec = Vec::new(); + for field in &fields { + let fid = field.ident.as_ref().expect("named"); + let name = field_name(fid); + let ty = &field.ty; + let span = ty.span(); + let fa = parse_field_attrs(field, &rt)?; + reject( + fa.priority.as_ref().map(|x| x.1), + "#[priority]", + "GameInput", + )?; + reject(fa.correct.as_ref().map(|x| x.1), "#[correct]", "GameInput")?; + if let Some((Special::Long, span)) = &fa.special { + return Err(syn::Error::new( + *span, + "inputs carry no strings; #[long] is not supported by #[derive(GameInput)]", + )); + } + let codec = payload_codec( + ty, + quote!(&self.#fid), + fa.special.as_ref().map(|s| &s.0), + &rt, + ); + encodes.push(codec.encode); + let decode = codec.decode; + decodes.push(quote!(#fid: #decode)); + + let range = match &fa.range { + Some((min, max, _)) => quote!(Some([(#min) as f64, (#max) as f64])), + None => quote!(None), + }; + let mut buttons = Vec::new(); + let sanitize = if let Some((names, bspan)) = &fa.buttons { + if fa.range.is_some() || fa.special.is_some() { + return Err(syn::Error::new( + *bspan, + "a #[buttons] field takes no #[range] / #[quant] / #[angle]", + )); + } + let mask: u64 = (1u64 << names.len()) - 1; + let mask = mask as u32; + for (bit, button) in names.iter().enumerate() { + let name = field_name(button); + buttons.push(quote!(#p::std::string::String::from(#name))); + let cname = format_ident!("{}", name.to_uppercase(), span = button.span()); + if const_names.iter().any(|c| c == &cname) { + return Err(syn::Error::new(button.span(), "duplicate button constant")); + } + const_names.push(cname.clone()); + let doc = format!("`{name}` bit of `{}`.", field_name(fid)); + let bit = bit as u32; + consts.push(quote_spanned!(span=> + #[doc = #doc] + pub const #cname: #ty = (1u32 << #bit) as #ty; + )); + } + quote_spanned!(span=> <#ty as #p::ButtonBits>::mask(self.#fid, #mask)) + } else if let Some((min, max, _)) = &fa.range { + quote_spanned!(span=> + <#ty as #p::InputField>::sanitize_range(self.#fid, (#min) as f64, (#max) as f64)? + ) + } else { + quote_spanned!(span=> <#ty as #p::InputField>::sanitize_plain(self.#fid)?) + }; + sanitizes.push(quote!(#fid: #sanitize)); + let wire_type = codec.wire_type; + let records = codec.records; + surfaces.push(quote! {{ + #records + #p::PayloadField { + name: #p::std::string::String::from(#name), + ty: #wire_type, + range: #range, + buttons: #p::std::vec![#(#buttons),*], + } + }}); + } + + let consts = if consts.is_empty() { + quote!() + } else { + quote! { + impl #ident { + #(#consts)* + } + } + }; + Ok(quote! { + #consts + + impl #rt::GameInput for #ident { + fn input_surface( + records: &mut #p::std::vec::Vec<#p::RecordSurface>, + ) -> #p::InputSurface { + let _ = &records; + #p::InputSurface { + name: #p::std::string::String::from(#type_name), + fields: #p::std::vec![#(#surfaces),*], + } + } + + fn encode_input(&self, w: &mut #p::Writer) { + let _ = &w; + #(#encodes)* + } + + fn decode_input(r: &mut #p::Reader<'_>) -> #p::std::result::Result { + let _ = &r; + #p::std::result::Result::Ok(Self { #(#decodes),* }) + } + + #[allow(clippy::unnecessary_cast)] + fn sanitize(self) -> #p::std::option::Option { + #p::std::option::Option::Some(Self { #(#sanitizes),* }) + } + } + }) +} diff --git a/distributed_game_macros/src/lib.rs b/distributed_game_macros/src/lib.rs new file mode 100644 index 000000000..ae7f2134f --- /dev/null +++ b/distributed_game_macros/src/lib.rs @@ -0,0 +1,146 @@ +//! Authoring derives for `distributed_game`. Use them through the runtime +//! crate's re-exports (`distributed_game::Replicated`, …); generated code +//! refers to `distributed_game` (renames are resolved). +//! +//! | derive | on | generates | +//! |---|---|---| +//! | [`Replicated`] | struct | `Replicated`: `KindDef` + field values from one field list | +//! | [`GameInput`] | struct | `GameInput`: compact codec, sanitize from `#[range]` / `#[buttons]` | +//! | [`GameEvent`] | struct / enum | `GameEvent`: stable ids, typed payload codec | +//! | [`GameRecord`] | struct | `Wire`: a nested payload record | +//! | [`FactCommand`] | struct | `FactCommand`: the cell command name of a fact input | +//! | [`TicketExtension`] | struct | `TicketExtension`: the extension claims a ticket may carry | +//! | [`macro@predict`] (attribute) | fn | `PredictStep` for a client-predicted step + its WebAssembly export | +//! | [`macro@game_pure`] (attribute) | fn | `GamePure` for a pure function compiled to WebAssembly + its export | +//! +//! Field attributes (where they apply): +//! +//! - `#[quant(min = A, max = B, bits = N)]` / `#[quant(centered = R, bits = N)]` +//! (zero exactly representable, `FieldType::quant_centered`) and +//! `#[angle(bits = N)]` on `f32` fields; `#[field_type(EXPR)]` uses any +//! `FieldType` expression (e.g. a shared `const POS: FieldType`). +//! - `#[long]` on a `String` payload field: varuint length instead of the +//! 255-byte short string. +//! - Replicated only: `#[priority(P)]`, `#[correct(ease = MS | ease | snap | replace)]` +//! (with `ease`, `snap_above = M`: larger errors snap — a teleport is a cut),, +//! `#[from]` / `#[from(path.to.field)]` (with `#[replicated(.., of = Entity)]`). +//! - GameInput only: `#[range(min = A, max = B)]` (clamp), `#[buttons(a, b, ..)]` +//! (bit flags, unknown bits cleared; also generates `Type::A`, `Type::B` consts). + +mod claims; +mod event; +mod fact; +mod input; +mod predict; +mod pure; +mod replicated; +mod shared; +mod trusted; + +use proc_macro::TokenStream; +use syn::{parse_macro_input, DeriveInput, ItemFn}; + +fn finish(result: syn::Result) -> TokenStream { + result.unwrap_or_else(|e| e.to_compile_error()).into() +} + +/// One replicated entity kind: `#[replicated(kind = "mob", id = 2, +/// priority = 2.0, global, every_patch, x = field, y = field, of = +/// Entity)]` on a struct with named fields (Rust type → wire type: `bool`, +/// `u8`, `u16`, `u32`, `i32`, `f32`, `String` → short_str, `Vec` → +/// bytes). The interest position is the `x`/`y` fields unless overridden; +/// a kind without a position must be `global`. `every_patch` exempts the +/// kind from distance-based update rates (`distributed_game::UpdateRates`). +/// +/// `of = Entity` makes the struct a view projected from a zone entity +/// (`distributed_game::entity`): fields marked `#[from]` (same name) or +/// `#[from(path.to.field)]` are copied from the entity, and the derive +/// generates `View::project(&entity, ViewRest { .. })`, `ViewRest` holding +/// the remaining hand-filled fields. When every field is `#[from]` it +/// generates `View::project(&entity)` and `impl Project for Entity`. +#[proc_macro_derive( + Replicated, + attributes(replicated, quant, angle, field_type, priority, correct, from) +)] +pub fn derive_replicated(input: TokenStream) -> TokenStream { + finish(replicated::expand(parse_macro_input!(input as DeriveInput))) +} + +/// A compact binary input frame. Fields are encoded in order with the +/// shared value codec; `#[range(..)]` clamps, `#[buttons(..)]` masks, +/// non-finite floats reject. +#[proc_macro_derive(GameInput, attributes(quant, angle, field_type, range, buttons))] +pub fn derive_game_input(input: TokenStream) -> TokenStream { + finish(input::expand(parse_macro_input!(input as DeriveInput))) +} + +/// Zone events with stable ids: `#[game_event(id = N, name = "..")]` on a +/// struct, or on every variant of an enum (unit, named fields, or one value +/// such as a `GameRecord`). +#[proc_macro_derive(GameEvent, attributes(game_event, quant, angle, field_type, long))] +pub fn derive_game_event(input: TokenStream) -> TokenStream { + finish(event::expand_event(parse_macro_input!( + input as DeriveInput + ))) +} + +/// A nested payload record (lists of rows, shared structs). +#[proc_macro_derive(GameRecord, attributes(quant, angle, field_type, long))] +pub fn derive_game_record(input: TokenStream) -> TokenStream { + finish(event::expand_record(parse_macro_input!( + input as DeriveInput + ))) +} + +/// Bind a cell command input to its command: +/// `#[fact(command = RECORD_KILL, key(mob, generation))]`. Requires +/// `serde::Serialize`. Identity-, reward- and economy-looking field names +/// (`principal`, `user_id`, `xp`, `reward`, `amount`, `gold`, `price`, +/// `balance`, `payout`, …; `_`/`-`/case ignored, serde renames included) +/// are rejected. +#[proc_macro_derive(FactCommand, attributes(fact))] +pub fn derive_fact_command(input: TokenStream) -> TokenStream { + finish(fact::expand(parse_macro_input!(input as DeriveInput))) +} + +/// Declare a game's ticket extension claims (match id, team, party…): +/// a struct with named fields that also derives serde `Serialize` and +/// `Deserialize`. Generates `TicketExtension::CLAIMS` (serialized names). +/// Identity-, reward- and economy-looking names are rejected with the same +/// deny list as [`FactCommand`]; `rename_all` and `flatten` are refused. +#[proc_macro_derive(TicketExtension)] +pub fn derive_ticket_extension(input: TokenStream) -> TokenStream { + finish(claims::expand(parse_macro_input!(input as DeriveInput))) +} + +/// Declare a zone's client-predicted step: +/// `#[predict(ArenaStep, kind = "player")]` on +/// `fn(state: &State, input: &Input, context: &Context, dt: f32) -> State`. +/// +/// Keeps the function and adds `struct ArenaStep` implementing +/// `distributed_game::prediction::PredictStep` (name it in +/// `GameSurface::predict::()`). On `wasm32` it also exports the +/// step as `dg_predict_` over the binary ABI described in +/// `distributed_game::prediction`. +#[proc_macro_attribute] +pub fn predict(args: TokenStream, item: TokenStream) -> TokenStream { + let args = parse_macro_input!(args as predict::Args); + let function = parse_macro_input!(item as ItemFn); + finish(predict::expand(args, function)) +} + +/// Declare a pure function the generated client calls through WebAssembly: +/// `#[game_pure(GridCellFn)]` on `fn(arg: &A) -> R` or `fn() -> R` (`A`, `R`: +/// `Wire` types, typically `#[derive(GameRecord)]` structs). +/// +/// Keeps the function and adds `struct GridCellFn` implementing +/// `distributed_game::pure::GamePure` (name it in +/// `GameSurface::pure::()`). On `wasm32` it also exports the +/// function as `dg_pure_` over the binary ABI described in +/// `distributed_game::pure`. +#[proc_macro_attribute] +pub fn game_pure(args: TokenStream, item: TokenStream) -> TokenStream { + let args = parse_macro_input!(args as pure::Args); + let function = parse_macro_input!(item as ItemFn); + finish(pure::expand(args, function)) +} diff --git a/distributed_game_macros/src/predict.rs b/distributed_game_macros/src/predict.rs new file mode 100644 index 000000000..a97937e53 --- /dev/null +++ b/distributed_game_macros/src/predict.rs @@ -0,0 +1,158 @@ +//! `#[predict(StepType, kind = "player")]` on a step function +//! `fn(state: &S, input: &I, context: &C, dt: f32) -> S`. + +use proc_macro2::TokenStream; +use quote::{format_ident, quote, quote_spanned}; +use syn::parse::{Parse, ParseStream}; +use syn::spanned::Spanned; +use syn::{FnArg, Ident, ItemFn, LitStr, Pat, ReturnType, Token, Type}; + +use crate::shared::runtime; + +pub(crate) struct Args { + step: Ident, + kind: LitStr, +} + +impl Parse for Args { + fn parse(input: ParseStream<'_>) -> syn::Result { + let step: Ident = input.parse().map_err(|e| { + syn::Error::new( + e.span(), + "expected `#[predict(StepType, kind = \"kind_name\")]`", + ) + })?; + let mut kind = None; + while !input.is_empty() { + input.parse::()?; + if input.is_empty() { + break; + } + let key: Ident = input.parse()?; + input.parse::()?; + match key.to_string().as_str() { + "kind" => kind = Some(input.parse::()?), + other => { + return Err(syn::Error::new( + key.span(), + format!("unknown `#[predict]` option `{other}` (expected `kind`)"), + )) + } + } + } + let kind = kind.ok_or_else(|| { + syn::Error::new( + step.span(), + "`#[predict]` needs the predicted kind: `kind = \"player\"`", + ) + })?; + if kind.value().is_empty() { + return Err(syn::Error::new(kind.span(), "kind must not be empty")); + } + Ok(Self { step, kind }) + } +} + +fn referenced(arg: &FnArg, what: &str) -> syn::Result { + let FnArg::Typed(typed) = arg else { + return Err(syn::Error::new( + arg.span(), + "a predicted step is a free function, not a method", + )); + }; + if !matches!(&*typed.pat, Pat::Ident(_) | Pat::Wild(_)) { + return Err(syn::Error::new( + typed.pat.span(), + "use a plain binding for step arguments", + )); + } + match &*typed.ty { + Type::Reference(reference) if reference.mutability.is_none() => { + Ok((*reference.elem).clone()) + } + other => Err(syn::Error::new( + other.span(), + format!("the {what} argument must be a shared reference (`&T`)"), + )), + } +} + +pub(crate) fn expand(args: Args, function: ItemFn) -> syn::Result { + let root = runtime()?; + let sig = &function.sig; + if !sig.generics.params.is_empty() || sig.asyncness.is_some() || sig.unsafety.is_some() { + return Err(syn::Error::new( + sig.span(), + "a predicted step must be a plain, non-generic, synchronous fn", + )); + } + let inputs: Vec<&FnArg> = sig.inputs.iter().collect(); + let [state_arg, input_arg, context_arg, dt_arg] = inputs.as_slice() else { + return Err(syn::Error::new( + sig.inputs.span(), + "a predicted step takes `(state: &State, input: &Input, context: &Context, dt: f32)`", + )); + }; + let state = referenced(state_arg, "state")?; + let input = referenced(input_arg, "input")?; + let context = referenced(context_arg, "context")?; + match dt_arg { + FnArg::Typed(typed) if matches!(&*typed.ty, Type::Path(p) if p.path.is_ident("f32")) => {} + other => { + return Err(syn::Error::new( + other.span(), + "the last argument is the frame length `dt: f32` (seconds)", + )) + } + } + let ReturnType::Type(_, output) = &sig.output else { + return Err(syn::Error::new( + sig.span(), + "a predicted step returns the next state", + )); + }; + let name = &sig.ident; + let export = name.to_string(); + let export = export.strip_prefix("r#").unwrap_or(&export).to_string(); + let symbol = format_ident!("dg_predict_{}", export); + let step = &args.step; + let kind = &args.kind; + let vis = &function.vis; + let doc = format!( + "The predicted step [`{export}`]: kind `{}`, exported to WebAssembly as `dg_predict_{export}`.", + kind.value() + ); + // Spanned at the return type: a step that does not return its state + // fails there. + let call = quote_spanned! {output.span()=> + #name(state, input, context, dt) + }; + Ok(quote! { + #function + + #[doc = #doc] + #[derive(Debug, Clone, Copy, Default)] + #vis struct #step; + + impl #root::prediction::PredictStep for #step { + const KIND: &'static str = #kind; + const PACKAGE: &'static str = ::core::env!("CARGO_PKG_NAME"); + const EXPORT: &'static str = #export; + type State = #state; + type Input = #input; + type Context = #context; + + fn step(state: &#state, input: &#input, context: &#context, dt: f32) -> #state { + #call + } + } + + #[cfg(target_arch = "wasm32")] + const _: () = { + #[unsafe(no_mangle)] + extern "C" fn #symbol(state_len: u32, input_len: u32, context_len: u32, dt: f32) -> i32 { + #root::__private::wasm_export::<#step>(state_len, input_len, context_len, dt) + } + }; + }) +} diff --git a/distributed_game_macros/src/pure.rs b/distributed_game_macros/src/pure.rs new file mode 100644 index 000000000..793ce94f2 --- /dev/null +++ b/distributed_game_macros/src/pure.rs @@ -0,0 +1,118 @@ +//! `#[game_pure(FnType)]` on a pure function `fn(arg: &A) -> R` or +//! `fn() -> R`. + +use proc_macro2::TokenStream; +use quote::{format_ident, quote, quote_spanned}; +use syn::parse::{Parse, ParseStream}; +use syn::spanned::Spanned; +use syn::{FnArg, Ident, ItemFn, Pat, ReturnType, Type}; + +use crate::shared::runtime; + +pub(crate) struct Args { + name: Ident, +} + +impl Parse for Args { + fn parse(input: ParseStream<'_>) -> syn::Result { + let name: Ident = input + .parse() + .map_err(|e| syn::Error::new(e.span(), "expected `#[game_pure(FnType)]`"))?; + if !input.is_empty() { + return Err(input.error("`#[game_pure]` takes only the generated type name")); + } + Ok(Self { name }) + } +} + +pub(crate) fn expand(args: Args, function: ItemFn) -> syn::Result { + let root = runtime()?; + let sig = &function.sig; + if !sig.generics.params.is_empty() || sig.asyncness.is_some() || sig.unsafety.is_some() { + return Err(syn::Error::new( + sig.span(), + "a game pure function must be a plain, non-generic, synchronous fn", + )); + } + let arg = match sig.inputs.iter().collect::>().as_slice() { + [] => None, + [FnArg::Typed(typed)] => { + if !matches!(&*typed.pat, Pat::Ident(_) | Pat::Wild(_)) { + return Err(syn::Error::new( + typed.pat.span(), + "use a plain binding for the argument", + )); + } + match &*typed.ty { + Type::Reference(reference) if reference.mutability.is_none() => { + Some((*reference.elem).clone()) + } + other => { + return Err(syn::Error::new( + other.span(), + "the argument must be a shared reference (`&T`, T: Wire)", + )) + } + } + } + [FnArg::Receiver(receiver)] => { + return Err(syn::Error::new( + receiver.span(), + "a game pure function is a free function, not a method", + )) + } + _ => { + return Err(syn::Error::new( + sig.inputs.span(), + "a game pure function takes nothing or one argument `&T` (bundle several values in a #[derive(GameRecord)] struct)", + )) + } + }; + let ReturnType::Type(_, output) = &sig.output else { + return Err(syn::Error::new( + sig.span(), + "a game pure function returns a value (any `Wire` type)", + )); + }; + let fn_name = &sig.ident; + let export = fn_name.to_string(); + let export = export.strip_prefix("r#").unwrap_or(&export).to_string(); + let symbol = format_ident!("dg_pure_{}", export); + let name = &args.name; + let vis = &function.vis; + let doc = + format!("The pure function [`{export}`], exported to WebAssembly as `dg_pure_{export}`."); + let (arg_ty, call) = match &arg { + Some(ty) => (quote!(#ty), quote_spanned! {output.span()=> #fn_name(arg) }), + None => ( + quote!(()), + quote_spanned! {output.span()=> { let _ = arg; #fn_name() } }, + ), + }; + Ok(quote! { + #function + + #[doc = #doc] + #[derive(Debug, Clone, Copy, Default)] + #vis struct #name; + + impl #root::pure::GamePure for #name { + const PACKAGE: &'static str = ::core::env!("CARGO_PKG_NAME"); + const EXPORT: &'static str = #export; + type Arg = #arg_ty; + type Output = #output; + + fn call(arg: &#arg_ty) -> #output { + #call + } + } + + #[cfg(target_arch = "wasm32")] + const _: () = { + #[unsafe(no_mangle)] + extern "C" fn #symbol(arg_len: u32) -> i32 { + #root::__private::pure_wasm_export::<#name>(arg_len) + } + }; + }) +} diff --git a/distributed_game_macros/src/replicated.rs b/distributed_game_macros/src/replicated.rs new file mode 100644 index 000000000..58691ba08 --- /dev/null +++ b/distributed_game_macros/src/replicated.rs @@ -0,0 +1,311 @@ +//! `#[derive(Replicated)]`: one struct = one kind's schema + field encoding. + +use proc_macro2::{Span, TokenStream}; +use quote::{quote, quote_spanned}; +use syn::punctuated::Punctuated; +use syn::spanned::Spanned; +use syn::{DeriveInput, Expr, Field, Ident, LitInt, LitStr, Member, Token, Type}; + +use crate::shared::{ + check_name, field_name, find_attr, named_fields, no_generics, parse_field_attrs, reject, + runtime, Special, +}; + +const MAX_FIELDS: usize = 32; + +struct KindAttrs { + kind: String, + id: u16, + priority: Option, + global: bool, + every_patch: bool, + x: Option, + y: Option, + of: Option, +} + +fn parse_kind_attrs(input: &DeriveInput) -> syn::Result { + let Some(attr) = find_attr(&input.attrs, "replicated") else { + return Err(syn::Error::new( + input.ident.span(), + "#[derive(Replicated)] needs #[replicated(kind = \"name\", id = N)]", + )); + }; + let (mut kind, mut id, mut priority, mut global, mut every_patch, mut x, mut y, mut of) = + (None, None, None, false, false, None, None, None); + attr.parse_nested_meta(|meta| { + let key = meta + .path + .get_ident() + .map(Ident::to_string) + .unwrap_or_default(); + match key.as_str() { + "kind" => kind = Some(check_name(&meta.value()?.parse::()?)?), + "id" => { + let lit: LitInt = meta.value()?.parse()?; + id = Some(lit.base10_parse::()?); + } + "priority" => priority = Some(meta.value()?.parse::()?), + "global" => global = true, + "every_patch" => every_patch = true, + "x" => x = Some(meta.value()?.parse::()?), + "y" => y = Some(meta.value()?.parse::()?), + "of" => of = Some(meta.value()?.parse::()?), + _ => { + return Err(meta.error( + "expected `kind`, `id`, `priority`, `global`, `every_patch`, `x`, `y` or `of` in #[replicated(..)]", + )) + } + } + Ok(()) + })?; + let span = attr.path().span(); + Ok(KindAttrs { + kind: kind + .ok_or_else(|| syn::Error::new(span, "#[replicated(..)] needs `kind = \"name\"`"))?, + id: id.ok_or_else(|| { + syn::Error::new(span, "#[replicated(..)] needs a literal `id = N` (u16)") + })?, + priority, + global, + every_patch, + x, + y, + of, + }) +} + +/// `#[from]` (same field name) or `#[from(a.b)]` (a field path on the +/// entity): the field path to copy, spanned at the attribute. +fn from_path(field: &Field) -> syn::Result, Span)>> { + let Some(attr) = find_attr(&field.attrs, "from") else { + return Ok(None); + }; + let span = attr.span(); + if matches!(attr.meta, syn::Meta::Path(_)) { + let ident = field.ident.clone().expect("named"); + return Ok(Some((vec![Member::Named(ident)], span))); + } + let path = attr.parse_args_with(Punctuated::::parse_separated_nonempty)?; + Ok(Some((path.into_iter().collect(), span))) +} + +/// With `of = T`: `View::project(&T, ViewRest)` (or, when every field is +/// `#[from]`, `View::project(&T)` plus `impl Project for T`). +fn expand_of( + input: &DeriveInput, + of: &Type, + fields: &[&Field], + rt: &TokenStream, +) -> syn::Result { + let ident = &input.ident; + let vis = &input.vis; + // Zone entities are usually private to their module while views are + // public: a crate-visible constructor never leaks the entity type. + let fn_vis = quote!(pub(crate)); + let rest_ident = Ident::new(&format!("{ident}Rest"), ident.span()); + let mut inits = Vec::new(); + let mut rest_fields = Vec::new(); + for field in fields { + let name = field.ident.as_ref().expect("named"); + match from_path(field)? { + Some((path, span)) => { + // A missing path is "no field", a different type + // "mismatched types", both at the `#[from]`. + inits.push(quote_spanned! {span=> + #name: (src #(. #path)*).clone() + }); + } + None => { + let docs = field.attrs.iter().filter(|a| a.path().is_ident("doc")); + let (fvis, ty) = (&field.vis, &field.ty); + rest_fields.push(quote! { #(#docs)* #fvis #name: #ty }); + inits.push(quote! { #name: rest.#name }); + } + } + } + if rest_fields.is_empty() { + return Ok(quote! { + impl #ident { + /// Project the entity: every field is `#[from]`. + #[allow(clippy::clone_on_copy)] + #fn_vis fn project(src: &#of) -> Self { + Self { #(#inits),* } + } + } + + impl #rt::Project<#ident> for #of { + fn view(&self) -> ::core::option::Option<#ident> { + ::core::option::Option::Some(#ident::project(self)) + } + } + }); + } + let doc = + format!("The hand-filled (non-`#[from]`) fields of [`{ident}`], for [`{ident}::project`]."); + Ok(quote! { + #[doc = #doc] + #[derive(Debug, Clone, PartialEq)] + #vis struct #rest_ident { + #(#rest_fields),* + } + + impl #ident { + /// Project the entity: `#[from]` fields are copied from `src`, + /// the others taken from `rest`. + #[allow(clippy::clone_on_copy)] + #fn_vis fn project(src: &#of, rest: #rest_ident) -> Self { + Self { #(#inits),* } + } + } + }) +} + +pub(crate) fn expand(input: DeriveInput) -> syn::Result { + no_generics(&input, "Replicated")?; + let rt = runtime()?; + let p = quote!(#rt::__private); + let attrs = parse_kind_attrs(&input)?; + let fields = named_fields(&input, "Replicated")?; + if fields.is_empty() { + return Err(syn::Error::new( + input.ident.span(), + "a replicated kind needs at least one field", + )); + } + if fields.len() > MAX_FIELDS { + return Err(syn::Error::new( + fields[MAX_FIELDS].span(), + "at most 32 fields per kind (update masks are 32-bit)", + )); + } + + let mut defs = Vec::new(); + let mut values = Vec::new(); + for field in &fields { + let ident = field.ident.as_ref().expect("named"); + let name = field_name(ident); + let ty = &field.ty; + let fa = parse_field_attrs(field, &rt)?; + reject(fa.range.as_ref().map(|r| r.2), "#[range]", "Replicated")?; + reject(fa.buttons.as_ref().map(|b| b.1), "#[buttons]", "Replicated")?; + let span = ty.span(); + let (field_type, value) = match fa.special.as_ref().map(|s| &s.0) { + None => ( + quote_spanned!(span=> <#ty as #p::EntityField>::FIELD_TYPE), + quote_spanned!(span=> <#ty as #p::EntityField>::to_field_value(&self.#ident)), + ), + Some(Special::FieldType(ft)) => ( + ft.clone(), + quote_spanned!(span=> #p::FieldValue::F(<#ty as #p::QuantizedF32>::get(&self.#ident))), + ), + Some(Special::Long) => return Err(syn::Error::new( + fa.special.as_ref().map_or(Span::call_site(), |s| s.1), + "#[long] strings cannot be replicated (entity strings are short_str, <= 255 bytes)", + )), + }; + let priority = fa + .priority + .as_ref() + .map(|(e, _)| quote!((#e) as f32)) + .unwrap_or(quote!(1.0)); + let correct = fa + .correct + .as_ref() + .map(|(c, _)| quote!(.correct(#c))) + .unwrap_or_default(); + defs.push(quote! { .field_with_priority(#name, #field_type, #priority) #correct }); + values.push(value); + } + + let has = |n: &str| { + fields + .iter() + .find(|f| f.ident.as_ref().is_some_and(|i| field_name(i) == n)) + .and_then(|f| f.ident.clone()) + }; + let check_named = |ident: &Ident| -> syn::Result<()> { + if fields.iter().any(|f| f.ident.as_ref() == Some(ident)) { + Ok(()) + } else { + Err(syn::Error::new( + ident.span(), + format!("no field `{ident}` in this struct"), + )) + } + }; + if let Some(x) = &attrs.x { + check_named(x)?; + } + if let Some(y) = &attrs.y { + check_named(y)?; + } + let pos_x = attrs.x.clone().or_else(|| has("x")); + let pos_y = attrs.y.clone().or_else(|| has("y")); + let position = match (pos_x, pos_y) { + (Some(x), Some(y)) => quote! { (self.#x as f32, self.#y as f32) }, + _ if attrs.global => quote! { (0.0, 0.0) }, + _ => { + return Err(syn::Error::new( + input.ident.span(), + "a non-global kind needs a position: name fields `x` and `y`, point at them with #[replicated(x = .., y = ..)], or mark the kind `global`", + )) + } + }; + + let ident = &input.ident; + let kind = &attrs.kind; + let id = attrs.id; + let global = attrs.global; + let projection = match &attrs.of { + Some(of) => expand_of(&input, of, &fields, &rt)?, + None => { + if let Some(field) = fields + .iter() + .find(|f| find_attr(&f.attrs, "from").is_some()) + { + let attr = find_attr(&field.attrs, "from").expect("found"); + return Err(syn::Error::new( + attr.span(), + "#[from] needs the entity type: #[replicated(.., of = Entity)]", + )); + } + TokenStream::new() + } + }; + let kind_priority = attrs + .priority + .as_ref() + .map(|e| quote!(.priority((#e) as f32))) + .unwrap_or_default(); + let every_patch = if attrs.every_patch { + quote!(.every_patch()) + } else { + TokenStream::new() + }; + Ok(quote! { + impl #rt::Replicated for #ident { + const KIND_ID: u16 = #id; + const KIND_NAME: &'static str = #kind; + const GLOBAL: bool = #global; + + fn kind_def() -> #p::KindDef { + #p::KindDef::new(#id, #kind) + #(#defs)* + #kind_priority + #every_patch + } + + #[allow(clippy::unnecessary_cast)] + fn position(&self) -> (f32, f32) { + #position + } + + fn write_fields(&self, out: &mut #p::std::vec::Vec<#p::FieldValue>) { + out.extend([#(#values),*]); + } + } + + #projection + }) +} diff --git a/distributed_game_macros/src/shared.rs b/distributed_game_macros/src/shared.rs new file mode 100644 index 000000000..0f84bc412 --- /dev/null +++ b/distributed_game_macros/src/shared.rs @@ -0,0 +1,437 @@ +//! Attribute parsing and codegen helpers shared by the derives. + +use proc_macro2::{Span, TokenStream}; +use proc_macro_crate::{crate_name, FoundCrate}; +use quote::{quote, quote_spanned}; +use syn::spanned::Spanned; +use syn::{Attribute, Data, DeriveInput, Expr, Field, Fields, Ident, LitStr, Type}; + +/// `distributed_game` as named by the consuming crate (renames and the +/// crate itself included). +pub(crate) fn runtime() -> syn::Result { + let root = match crate_name("distributed_game") { + // `::distributed_game`, not `crate`: doctests of the crate itself + // report `Itself` but compile as a separate crate. The lib declares + // `extern crate self as distributed_game` so the path also works + // inside it. + Ok(FoundCrate::Itself) => quote!(::distributed_game), + Ok(FoundCrate::Name(name)) => { + let ident = Ident::new(&name, Span::call_site()); + quote!(::#ident) + } + Err(error) => { + let message = + format!("unable to resolve `distributed_game` for generated code: {error}"); + return Err(syn::Error::new(Span::call_site(), message)); + } + }; + Ok(root) +} + +/// Rust field name without a raw prefix. +pub(crate) fn field_name(ident: &Ident) -> String { + let name = ident.to_string(); + name.strip_prefix("r#").map(str::to_string).unwrap_or(name) +} + +/// `BoardSnapshot` → `board_snapshot`. +pub(crate) fn snake_case(name: &str) -> String { + let mut out = String::new(); + for (i, c) in name.chars().enumerate() { + if c.is_uppercase() { + if i > 0 { + out.push('_'); + } + out.extend(c.to_lowercase()); + } else { + out.push(c); + } + } + out +} + +/// Named fields of a struct, or a spanned error naming the derive. +pub(crate) fn named_fields<'a>( + input: &'a DeriveInput, + derive: &str, +) -> syn::Result> { + match &input.data { + Data::Struct(data) => match &data.fields { + Fields::Named(fields) => Ok(fields.named.iter().collect()), + Fields::Unit => Ok(Vec::new()), + Fields::Unnamed(_) => Err(syn::Error::new( + input.ident.span(), + format!("#[derive({derive})] needs a struct with named fields"), + )), + }, + _ => Err(syn::Error::new( + input.ident.span(), + format!("#[derive({derive})] only supports structs"), + )), + } +} + +/// Reject generics (descriptors are per concrete type). +pub(crate) fn no_generics(input: &DeriveInput, derive: &str) -> syn::Result<()> { + if input.generics.params.is_empty() { + Ok(()) + } else { + Err(syn::Error::new( + input.generics.span(), + format!("#[derive({derive})] does not support generic types"), + )) + } +} + +/// Wire-level override of one field, from `#[quant]`, `#[angle]`, +/// `#[field_type]` or `#[long]`. +pub(crate) enum Special { + /// `#[quant(min, max, bits)]` / `#[quant(centered, bits)]` / `#[angle(bits)]` + /// / `#[field_type(EXPR)]`: an `f32` encoded as this `FieldType` expression. + FieldType(TokenStream), + /// `#[long]`: a varuint-length string. + Long, +} + +/// Every per-field attribute a derive may accept. Each derive rejects the +/// ones it does not support. +#[derive(Default)] +pub(crate) struct FieldAttrs { + pub special: Option<(Special, Span)>, + pub priority: Option<(Expr, Span)>, + pub correct: Option<(TokenStream, Span)>, + pub range: Option<(Expr, Expr, Span)>, + pub buttons: Option<(Vec, Span)>, +} + +const FIELD_ATTRS: &[&str] = &[ + "quant", + "angle", + "field_type", + "long", + "priority", + "correct", + "range", + "buttons", +]; + +fn set_special(attrs: &mut FieldAttrs, special: Special, span: Span) -> syn::Result<()> { + if attrs.special.is_some() { + return Err(syn::Error::new( + span, + "only one of #[quant], #[angle], #[field_type] or #[long] per field", + )); + } + attrs.special = Some((special, span)); + Ok(()) +} + +pub(crate) fn parse_field_attrs(field: &Field, rt: &TokenStream) -> syn::Result { + let mut out = FieldAttrs::default(); + for attr in &field.attrs { + let Some(name) = attr.path().get_ident().map(Ident::to_string) else { + continue; + }; + if !FIELD_ATTRS.contains(&name.as_str()) { + continue; + } + let span = attr.path().span(); + match name.as_str() { + "quant" => { + let (mut min, mut max, mut centered, mut bits) = (None, None, None, None); + attr.parse_nested_meta(|meta| { + let key = meta + .path + .get_ident() + .map(Ident::to_string) + .unwrap_or_default(); + let value: Expr = meta.value()?.parse()?; + match key.as_str() { + "min" => min = Some(value), + "max" => max = Some(value), + "centered" => centered = Some(value), + "bits" => bits = Some(value), + _ => { + return Err(meta.error( + "expected `min`, `max`, `bits` or `centered` in #[quant(..)]", + )) + } + } + Ok(()) + })?; + let Some(bits) = bits else { + return Err(syn::Error::new(span, "#[quant(..)] needs `bits = 1..=32`")); + }; + let ty = match (min, max, centered) { + (Some(min), Some(max), None) => quote! { + #rt::__private::FieldType::QuantF32 { + min: (#min) as f32, + max: (#max) as f32, + bits: (#bits) as u8, + } + }, + (None, None, Some(range)) => quote! { + #rt::__private::FieldType::quant_centered((#range) as f32, (#bits) as u8) + }, + _ => { + return Err(syn::Error::new( + span, + "#[quant(..)] needs either `min` and `max`, or `centered = RANGE` (zero exactly representable)", + )) + } + }; + set_special(&mut out, Special::FieldType(ty), span)?; + } + "angle" => { + let mut bits = None; + attr.parse_nested_meta(|meta| { + if meta.path.is_ident("bits") { + bits = Some(meta.value()?.parse::()?); + Ok(()) + } else { + Err(meta.error("expected `bits` in #[angle(bits = ..)]")) + } + })?; + let Some(bits) = bits else { + return Err(syn::Error::new(span, "#[angle(..)] needs `bits = 1..=32`")); + }; + let ty = quote!(#rt::__private::FieldType::Angle { bits: (#bits) as u8 }); + set_special(&mut out, Special::FieldType(ty), span)?; + } + "field_type" => { + let expr: Expr = attr.parse_args()?; + set_special(&mut out, Special::FieldType(quote!((#expr))), span)?; + } + "long" => { + attr.meta.require_path_only()?; + set_special(&mut out, Special::Long, span)?; + } + "priority" => { + if out.priority.is_some() { + return Err(syn::Error::new(span, "duplicate #[priority]")); + } + out.priority = Some((attr.parse_args()?, span)); + } + "correct" => { + if out.correct.is_some() { + return Err(syn::Error::new(span, "duplicate #[correct]")); + } + let mut policy = None; + let mut ease_ms: Option = None; + let mut snap_above: Option = None; + attr.parse_nested_meta(|meta| { + let key = meta + .path + .get_ident() + .map(Ident::to_string) + .unwrap_or_default(); + if key == "snap_above" { + if snap_above.is_some() { + return Err(meta.error("duplicate `snap_above`")); + } + snap_above = Some(meta.value()?.parse()?); + return Ok(()); + } + if policy.is_some() { + return Err(meta.error("#[correct(..)] takes one policy")); + } + policy = Some(match key.as_str() { + "ease" => { + ease_ms = Some(if meta.input.peek(syn::Token![=]) { + meta.value()?.parse()? + } else { + syn::parse_quote!(100) + }); + quote!() + } + "snap" => quote!(#rt::__private::Correction::Snap), + "replace" => quote!(#rt::__private::Correction::Replace), + _ => return Err(meta.error( + "expected `ease`, `ease = MS`, `snap` or `replace` (with `ease`: `snap_above = M`) in #[correct(..)]", + )), + }); + Ok(()) + })?; + let Some(mut policy) = policy else { + return Err(syn::Error::new(span, "#[correct(..)] needs a policy")); + }; + match (ease_ms, snap_above) { + (Some(ms), above) => { + let above = match above { + Some(m) => quote!(::core::option::Option::Some((#m) as f32)), + None => quote!(::core::option::Option::None), + }; + policy = quote!(#rt::__private::Correction::Ease { + duration_ms: (#ms) as u32, + snap_above: #above, + }); + } + (None, Some(_)) => { + return Err(syn::Error::new( + span, + "`snap_above` only applies to `ease` in #[correct(..)]", + )) + } + (None, None) => {} + } + out.correct = Some((policy, span)); + } + "range" => { + if out.range.is_some() { + return Err(syn::Error::new(span, "duplicate #[range]")); + } + let (mut min, mut max) = (None, None); + attr.parse_nested_meta(|meta| { + let value: Expr = meta.value()?.parse()?; + if meta.path.is_ident("min") { + min = Some(value); + } else if meta.path.is_ident("max") { + max = Some(value); + } else { + return Err(meta.error("expected `min` and `max` in #[range(..)]")); + } + Ok(()) + })?; + match (min, max) { + (Some(min), Some(max)) => out.range = Some((min, max, span)), + _ => { + return Err(syn::Error::new( + span, + "#[range(..)] needs both `min` and `max`", + )) + } + } + } + "buttons" => { + if out.buttons.is_some() { + return Err(syn::Error::new(span, "duplicate #[buttons]")); + } + let mut names = Vec::new(); + attr.parse_nested_meta(|meta| { + let Some(ident) = meta.path.get_ident() else { + return Err(meta.error("button names are identifiers")); + }; + if names.iter().any(|n: &Ident| n == ident) { + return Err(meta.error("duplicate button name")); + } + names.push(ident.clone()); + Ok(()) + })?; + if names.is_empty() || names.len() > 32 { + return Err(syn::Error::new(span, "#[buttons(..)] names 1..=32 bits")); + } + out.buttons = Some((names, span)); + } + _ => unreachable!(), + } + } + Ok(out) +} + +/// Error for an attribute a derive does not accept on fields. +pub(crate) fn reject(span: Option, what: &str, derive: &str) -> syn::Result<()> { + match span { + Some(span) => Err(syn::Error::new( + span, + format!("{what} is not supported by #[derive({derive})]"), + )), + None => Ok(()), + } +} + +/// One payload field's encode / decode / descriptor tokens (inputs, events, +/// records). +pub(crate) struct PayloadCodec { + pub encode: TokenStream, + pub decode: TokenStream, + pub wire_type: TokenStream, + pub records: TokenStream, +} + +/// Codec tokens for `value` (an expression of type `&ty`) of a payload field. +pub(crate) fn payload_codec( + ty: &Type, + value: TokenStream, + special: Option<&Special>, + rt: &TokenStream, +) -> PayloadCodec { + let p = quote!(#rt::__private); + let span = ty.span(); + match special { + // `Vec` encodes like any list of bytes (varuint count + bytes) — + // identical to `bytes` — but is described as `bytes` so generated + // clients get a `Uint8Array`. + None if is_byte_vec(ty) => PayloadCodec { + encode: quote_spanned!(span=> <#ty as #p::Wire>::encode(#value, w);), + decode: quote_spanned!(span=> <#ty as #p::Wire>::decode(r)?), + wire_type: quote!(#p::WireType::Bytes), + records: quote!(), + }, + None => PayloadCodec { + encode: quote_spanned!(span=> <#ty as #p::Wire>::encode(#value, w);), + decode: quote_spanned!(span=> <#ty as #p::Wire>::decode(r)?), + wire_type: quote_spanned!(span=> <#ty as #p::Wire>::wire_type()), + records: quote_spanned!(span=> <#ty as #p::Wire>::records(records);), + }, + Some(Special::FieldType(ft)) => PayloadCodec { + encode: quote_spanned!(span=> + #p::special::encode_f32(w, #ft, <#ty as #p::QuantizedF32>::get(#value)); + ), + decode: quote_spanned!(span=> + <#ty as #p::QuantizedF32>::from_f32(#p::special::decode_f32(r, #ft)?) + ), + wire_type: quote!(#p::WireType::of_field(#ft)), + records: quote!(), + }, + Some(Special::Long) => PayloadCodec { + encode: quote_spanned!(span=> + #p::special::encode_long(w, <#ty as #p::LongString>::text(#value)); + ), + decode: quote_spanned!(span=> + <#ty as #p::LongString>::from_text(#p::special::decode_long(r)?) + ), + wire_type: quote!(#p::WireType::Str), + records: quote!(), + }, + } +} + +/// `Vec` written as such (aliases are not seen). +fn is_byte_vec(ty: &Type) -> bool { + let Type::Path(path) = ty else { return false }; + let Some(last) = path.path.segments.last() else { + return false; + }; + if last.ident != "Vec" { + return false; + } + let syn::PathArguments::AngleBracketed(args) = &last.arguments else { + return false; + }; + matches!( + args.args.first(), + Some(syn::GenericArgument::Type(Type::Path(inner))) if inner.path.is_ident("u8") + ) && args.args.len() == 1 +} + +/// A `name = "..."` / `id = N` style container attribute. +pub(crate) fn find_attr<'a>(attrs: &'a [Attribute], name: &str) -> Option<&'a Attribute> { + attrs.iter().find(|a| a.path().is_ident(name)) +} + +/// Validate a wire name (non-empty, ASCII identifier-ish). +pub(crate) fn check_name(lit: &LitStr) -> syn::Result { + let value = lit.value(); + let ok = !value.is_empty() + && value + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'); + if ok { + Ok(value) + } else { + Err(syn::Error::new( + lit.span(), + "names are non-empty ASCII letters, digits, `_` or `-`", + )) + } +} diff --git a/distributed_game_macros/src/trusted.rs b/distributed_game_macros/src/trusted.rs new file mode 100644 index 000000000..a7a23df83 --- /dev/null +++ b/distributed_game_macros/src/trusted.rs @@ -0,0 +1,142 @@ +//! The deny list for fields a game must not let untrusted data carry. +//! +//! Zone facts (`FactCommand`) and ticket extension claims share it: identity +//! is bound by the host from the verified ticket, and rewards and economy +//! amounts are decided by the deterministic command handler, never by a +//! field the zone or the browser filled in. + +use proc_macro2::Span; +use syn::{Expr, Field, LitStr}; + +use crate::shared::field_name; + +/// Denied names and what they look like. Matching ignores `_`, `-` and case, +/// so `user_id`, `userId`, `USER-ID` and `UserID` all hit `user_id`. +const FORBIDDEN: &[(&str, &str)] = &[ + ("principal", "identity"), + ("user", "identity"), + ("user_id", "identity"), + ("owner", "identity"), + ("owner_id", "identity"), + ("account", "identity"), + ("account_id", "identity"), + ("subject", "identity"), + ("sub", "identity"), + ("xp", "a reward"), + ("experience", "a reward"), + ("reward", "a reward"), + ("rewards", "a reward"), + ("amount", "an economy value"), + ("coins", "an economy value"), + ("gold", "an economy value"), + ("currency", "an economy value"), + ("price", "an economy value"), + ("cost", "an economy value"), + ("balance", "an economy value"), + ("grant", "an economy value"), + ("payout", "an economy value"), + ("credit", "an economy value"), + ("debit", "an economy value"), +]; + +fn normalized(name: &str) -> String { + name.chars() + .filter(|c| *c != '_' && *c != '-') + .flat_map(char::to_lowercase) + .collect() +} + +/// What `name` looks like, if it is denied. +pub(crate) fn forbidden(name: &str) -> Option<&'static str> { + let n = normalized(name); + FORBIDDEN + .iter() + .find(|(bad, _)| normalized(bad) == n) + .map(|(_, why)| *why) +} + +/// Every name a field is seen under by a serde consumer: the Rust name plus +/// any `#[serde(rename = ..)]` / `#[serde(alias = ..)]`. +fn seen_names(field: &Field) -> Vec<(String, Span)> { + let ident = field.ident.as_ref().expect("named"); + let mut names = vec![(field_name(ident), ident.span())]; + for a in field.attrs.iter().filter(|a| a.path().is_ident("serde")) { + let _ = a.parse_nested_meta(|meta| { + if meta.path.is_ident("rename") || meta.path.is_ident("alias") { + if let Ok(value) = meta.value() { + if let Ok(lit) = value.parse::() { + names.push((lit.value(), lit.span())); + } + } + } else if meta.input.peek(syn::Token![=]) { + let _ = meta.value()?.parse::(); + } else if meta.input.peek(syn::token::Paren) { + let _ = meta.parse_nested_meta(|_| Ok(())); + } + Ok(()) + }); + } + names +} + +/// Reject every denied field name (one spanned error each, combined). +/// `what` names the declaration ("fact input", "ticket claim") and `rule` +/// ends the message with why the value must come from elsewhere. +pub(crate) fn reject_forbidden(fields: &[&Field], what: &str, rule: &str) -> syn::Result<()> { + let mut errors: Option = None; + for field in fields { + for (name, span) in seen_names(field) { + if let Some(why) = forbidden(&name) { + let error = syn::Error::new( + span, + format!("{what} field `{name}` looks like {why}: {rule}"), + ); + match &mut errors { + Some(all) => all.combine(error), + None => errors = Some(error), + } + } + } + } + errors.map_or(Ok(()), Err) +} + +#[cfg(test)] +mod tests { + use super::{forbidden, FORBIDDEN}; + + /// The JS ticket handler enforces the same list from this fixture. + #[test] + fn deny_list_matches_the_shared_fixture() { + let fixture = + include_str!("../../distributed_game/tests/fixtures/trusted_field_denylist.json"); + let mut expected = Vec::new(); + for (group, why) in [ + ("identity", "identity"), + ("reward", "a reward"), + ("economy", "an economy value"), + ] { + let start = fixture.find(&format!("\"{group}\": [")).expect(group); + let list = &fixture[start..]; + let list = &list[list.find('[').unwrap() + 1..list.find(']').unwrap()]; + for name in list.split(',') { + expected.push((name.trim().trim_matches('"').to_string(), why)); + } + } + let actual: Vec<_> = FORBIDDEN.iter().map(|(n, w)| (n.to_string(), *w)).collect(); + assert_eq!(actual, expected); + } + + #[test] + fn matches_ignore_separators_and_case() { + for name in ["userId", "USER-ID", "user_id", "UserID", "Owner_Id"] { + assert_eq!(forbidden(name), Some("identity"), "{name}"); + } + for name in ["Gold", "GOLD", "pay_out", "Pay-Out", "c_o_i_n_s", "Balance"] { + assert_eq!(forbidden(name), Some("an economy value"), "{name}"); + } + for name in ["mob", "generation", "amounts", "coin", "costs", "kills"] { + assert_eq!(forbidden(name), None, "{name}"); + } + } +} diff --git a/distributed_game_macros/tests/compile_fail.rs b/distributed_game_macros/tests/compile_fail.rs new file mode 100644 index 000000000..9d4502ad5 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail.rs @@ -0,0 +1,11 @@ +//! Compile-fail suite for `distributed_game_macros`. +//! +//! Each fixture in `tests/compile_fail/` must fail with a pointed, spanned +//! diagnostic; the `.stderr` snapshot pins it. Regenerate with +//! `TRYBUILD=overwrite cargo test -p distributed_game_macros`. + +#[test] +fn compile_fail() { + let t = trybuild::TestCases::new(); + t.compile_fail("tests/compile_fail/*.rs"); +} diff --git a/distributed_game_macros/tests/compile_fail/event_duplicate_id.rs b/distributed_game_macros/tests/compile_fail/event_duplicate_id.rs new file mode 100644 index 000000000..c19c0de16 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/event_duplicate_id.rs @@ -0,0 +1,11 @@ +use distributed_game::GameEvent; + +#[derive(GameEvent)] +enum ZoneEvent { + #[game_event(id = 1)] + Hello { entity: u32 }, + #[game_event(id = 1)] + Bye, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/event_duplicate_id.stderr b/distributed_game_macros/tests/compile_fail/event_duplicate_id.stderr new file mode 100644 index 000000000..0df9c0d7a --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/event_duplicate_id.stderr @@ -0,0 +1,5 @@ +error: event id 1 / name `bye` already used by `hello` + --> tests/compile_fail/event_duplicate_id.rs:7:23 + | +7 | #[game_event(id = 1)] + | ^ diff --git a/distributed_game_macros/tests/compile_fail/event_missing_id.rs b/distributed_game_macros/tests/compile_fail/event_missing_id.rs new file mode 100644 index 000000000..acbc006f9 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/event_missing_id.rs @@ -0,0 +1,10 @@ +use distributed_game::GameEvent; + +#[derive(GameEvent)] +enum ZoneEvent { + #[game_event(id = 1)] + Hello { entity: u32 }, + Bye, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/event_missing_id.stderr b/distributed_game_macros/tests/compile_fail/event_missing_id.stderr new file mode 100644 index 000000000..8f2b82ea7 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/event_missing_id.stderr @@ -0,0 +1,5 @@ +error: every event variant needs #[game_event(id = N)] (a stable u32 type id) + --> tests/compile_fail/event_missing_id.rs:7:5 + | +7 | Bye, + | ^^^ diff --git a/distributed_game_macros/tests/compile_fail/fact_economy_fields.rs b/distributed_game_macros/tests/compile_fail/fact_economy_fields.rs new file mode 100644 index 000000000..dcec8fe77 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/fact_economy_fields.rs @@ -0,0 +1,26 @@ +use distributed_game::FactCommand; + +// Every economy name is denied, whatever its case or separators, and under +// a serde rename or alias too. Each one gets its own error. +#[derive(serde::Serialize, FactCommand)] +#[fact(command = "crawler.loot_found")] +struct LootFound { + chest: String, + amount: u32, + Coins: u32, + GOLD: u32, + currency_: String, + price: u32, + cost: u32, + bal_ance: u64, + grant: u32, + pay_out: u32, + CREDIT: u32, + debit: u32, + #[serde(rename = "Pay-Out")] + a: u32, + #[serde(alias = "goldAmount", alias = "gold-")] + b: u32, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/fact_economy_fields.stderr b/distributed_game_macros/tests/compile_fail/fact_economy_fields.stderr new file mode 100644 index 000000000..5c1e92975 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/fact_economy_fields.stderr @@ -0,0 +1,77 @@ +error: fact input field `amount` looks like an economy value: a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards and economy values + --> tests/compile_fail/fact_economy_fields.rs:9:5 + | +9 | amount: u32, + | ^^^^^^ + +error: fact input field `Coins` looks like an economy value: a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards and economy values + --> tests/compile_fail/fact_economy_fields.rs:10:5 + | +10 | Coins: u32, + | ^^^^^ + +error: fact input field `GOLD` looks like an economy value: a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards and economy values + --> tests/compile_fail/fact_economy_fields.rs:11:5 + | +11 | GOLD: u32, + | ^^^^ + +error: fact input field `currency_` looks like an economy value: a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards and economy values + --> tests/compile_fail/fact_economy_fields.rs:12:5 + | +12 | currency_: String, + | ^^^^^^^^^ + +error: fact input field `price` looks like an economy value: a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards and economy values + --> tests/compile_fail/fact_economy_fields.rs:13:5 + | +13 | price: u32, + | ^^^^^ + +error: fact input field `cost` looks like an economy value: a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards and economy values + --> tests/compile_fail/fact_economy_fields.rs:14:5 + | +14 | cost: u32, + | ^^^^ + +error: fact input field `bal_ance` looks like an economy value: a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards and economy values + --> tests/compile_fail/fact_economy_fields.rs:15:5 + | +15 | bal_ance: u64, + | ^^^^^^^^ + +error: fact input field `grant` looks like an economy value: a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards and economy values + --> tests/compile_fail/fact_economy_fields.rs:16:5 + | +16 | grant: u32, + | ^^^^^ + +error: fact input field `pay_out` looks like an economy value: a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards and economy values + --> tests/compile_fail/fact_economy_fields.rs:17:5 + | +17 | pay_out: u32, + | ^^^^^^^ + +error: fact input field `CREDIT` looks like an economy value: a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards and economy values + --> tests/compile_fail/fact_economy_fields.rs:18:5 + | +18 | CREDIT: u32, + | ^^^^^^ + +error: fact input field `debit` looks like an economy value: a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards and economy values + --> tests/compile_fail/fact_economy_fields.rs:19:5 + | +19 | debit: u32, + | ^^^^^ + +error: fact input field `Pay-Out` looks like an economy value: a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards and economy values + --> tests/compile_fail/fact_economy_fields.rs:20:22 + | +20 | #[serde(rename = "Pay-Out")] + | ^^^^^^^^^ + +error: fact input field `gold-` looks like an economy value: a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards and economy values + --> tests/compile_fail/fact_economy_fields.rs:22:43 + | +22 | #[serde(alias = "goldAmount", alias = "gold-")] + | ^^^^^^^ diff --git a/distributed_game_macros/tests/compile_fail/fact_identity_field.rs b/distributed_game_macros/tests/compile_fail/fact_identity_field.rs new file mode 100644 index 000000000..6023b8b14 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/fact_identity_field.rs @@ -0,0 +1,10 @@ +use distributed_game::FactCommand; + +#[derive(serde::Serialize, FactCommand)] +#[fact(command = "crawler.record_kill")] +struct RecordKill { + mob: String, + principal: String, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/fact_identity_field.stderr b/distributed_game_macros/tests/compile_fail/fact_identity_field.stderr new file mode 100644 index 000000000..80a24fe32 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/fact_identity_field.stderr @@ -0,0 +1,5 @@ +error: fact input field `principal` looks like identity: a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards and economy values + --> tests/compile_fail/fact_identity_field.rs:7:5 + | +7 | principal: String, + | ^^^^^^^^^ diff --git a/distributed_game_macros/tests/compile_fail/fact_identity_variants.rs b/distributed_game_macros/tests/compile_fail/fact_identity_variants.rs new file mode 100644 index 000000000..c2c6e7f88 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/fact_identity_variants.rs @@ -0,0 +1,15 @@ +use distributed_game::FactCommand; + +#[derive(serde::Serialize, FactCommand)] +#[fact(command = "crawler.record_kill")] +struct RecordKill { + mob: String, + UserId: String, + #[serde(rename = "owner-id")] + who: String, + ACCOUNT_ID: String, + #[serde(rename = "Experience")] + gained: u32, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/fact_identity_variants.stderr b/distributed_game_macros/tests/compile_fail/fact_identity_variants.stderr new file mode 100644 index 000000000..d1c969bd5 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/fact_identity_variants.stderr @@ -0,0 +1,23 @@ +error: fact input field `UserId` looks like identity: a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards and economy values + --> tests/compile_fail/fact_identity_variants.rs:7:5 + | +7 | UserId: String, + | ^^^^^^ + +error: fact input field `owner-id` looks like identity: a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards and economy values + --> tests/compile_fail/fact_identity_variants.rs:8:22 + | +8 | #[serde(rename = "owner-id")] + | ^^^^^^^^^^ + +error: fact input field `ACCOUNT_ID` looks like identity: a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards and economy values + --> tests/compile_fail/fact_identity_variants.rs:10:5 + | +10 | ACCOUNT_ID: String, + | ^^^^^^^^^^ + +error: fact input field `Experience` looks like a reward: a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards and economy values + --> tests/compile_fail/fact_identity_variants.rs:11:22 + | +11 | #[serde(rename = "Experience")] + | ^^^^^^^^^^^^ diff --git a/distributed_game_macros/tests/compile_fail/fact_missing_command.rs b/distributed_game_macros/tests/compile_fail/fact_missing_command.rs new file mode 100644 index 000000000..21b24d8a1 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/fact_missing_command.rs @@ -0,0 +1,8 @@ +use distributed_game::FactCommand; + +#[derive(serde::Serialize, FactCommand)] +struct RecordKill { + mob: String, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/fact_missing_command.stderr b/distributed_game_macros/tests/compile_fail/fact_missing_command.stderr new file mode 100644 index 000000000..2793042a3 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/fact_missing_command.stderr @@ -0,0 +1,5 @@ +error: #[derive(FactCommand)] needs #[fact(command = COMMAND_NAME)] (the constant the cell mounts the command under, or a string literal) + --> tests/compile_fail/fact_missing_command.rs:4:8 + | +4 | struct RecordKill { + | ^^^^^^^^^^ diff --git a/distributed_game_macros/tests/compile_fail/fact_reward_field.rs b/distributed_game_macros/tests/compile_fail/fact_reward_field.rs new file mode 100644 index 000000000..33a404f30 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/fact_reward_field.rs @@ -0,0 +1,11 @@ +use distributed_game::FactCommand; + +#[derive(serde::Serialize, FactCommand)] +#[fact(command = "crawler.record_kill")] +struct RecordKill { + mob: String, + #[serde(rename = "XP")] + count: u32, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/fact_reward_field.stderr b/distributed_game_macros/tests/compile_fail/fact_reward_field.stderr new file mode 100644 index 000000000..62e0d6d0c --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/fact_reward_field.stderr @@ -0,0 +1,5 @@ +error: fact input field `XP` looks like a reward: a zone fact reports what happened; the host binds the principal from the verified ticket and the command handler decides rewards and economy values + --> tests/compile_fail/fact_reward_field.rs:7:22 + | +7 | #[serde(rename = "XP")] + | ^^^^ diff --git a/distributed_game_macros/tests/compile_fail/game_pure_by_value.rs b/distributed_game_macros/tests/compile_fail/game_pure_by_value.rs new file mode 100644 index 000000000..80e7c33e5 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/game_pure_by_value.rs @@ -0,0 +1,9 @@ +use distributed_game::game_pure; + +// The argument is borrowed. +#[game_pure(Double)] +fn double(a: u32) -> u32 { + a * 2 +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/game_pure_by_value.stderr b/distributed_game_macros/tests/compile_fail/game_pure_by_value.stderr new file mode 100644 index 000000000..d3ff31283 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/game_pure_by_value.stderr @@ -0,0 +1,5 @@ +error: the argument must be a shared reference (`&T`, T: Wire) + --> tests/compile_fail/game_pure_by_value.rs:5:14 + | +5 | fn double(a: u32) -> u32 { + | ^^^ diff --git a/distributed_game_macros/tests/compile_fail/game_pure_two_args.rs b/distributed_game_macros/tests/compile_fail/game_pure_two_args.rs new file mode 100644 index 000000000..b299e48d7 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/game_pure_two_args.rs @@ -0,0 +1,9 @@ +use distributed_game::game_pure; + +// One argument at most: bundle several values in a #[derive(GameRecord)] struct. +#[game_pure(Sum)] +fn sum(a: &u32, b: &u32) -> u32 { + a + b +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/game_pure_two_args.stderr b/distributed_game_macros/tests/compile_fail/game_pure_two_args.stderr new file mode 100644 index 000000000..3f005d058 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/game_pure_two_args.stderr @@ -0,0 +1,5 @@ +error: a game pure function takes nothing or one argument `&T` (bundle several values in a #[derive(GameRecord)] struct) + --> tests/compile_fail/game_pure_two_args.rs:5:8 + | +5 | fn sum(a: &u32, b: &u32) -> u32 { + | ^ diff --git a/distributed_game_macros/tests/compile_fail/predict_bad_signature.rs b/distributed_game_macros/tests/compile_fail/predict_bad_signature.rs new file mode 100644 index 000000000..fcc45c754 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/predict_bad_signature.rs @@ -0,0 +1,19 @@ +use distributed_game::{predict, GameInput, GameRecord}; + +#[derive(Clone, Copy, GameRecord)] +struct State { + x: f32, +} + +#[derive(Clone, Copy, GameInput)] +struct Push { + dx: i8, +} + +// The state must be borrowed, and the frame length is a trailing `dt: f32`. +#[predict(Step, kind = "dot")] +fn step(state: State, _input: &Push) -> State { + state +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/predict_bad_signature.stderr b/distributed_game_macros/tests/compile_fail/predict_bad_signature.stderr new file mode 100644 index 000000000..890e894f3 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/predict_bad_signature.stderr @@ -0,0 +1,5 @@ +error: a predicted step takes `(state: &State, input: &Input, context: &Context, dt: f32)` + --> tests/compile_fail/predict_bad_signature.rs:15:9 + | +15 | fn step(state: State, _input: &Push) -> State { + | ^^^^^ diff --git a/distributed_game_macros/tests/compile_fail/predict_needs_kind.rs b/distributed_game_macros/tests/compile_fail/predict_needs_kind.rs new file mode 100644 index 000000000..00c462c33 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/predict_needs_kind.rs @@ -0,0 +1,18 @@ +use distributed_game::{predict, GameInput, GameRecord}; + +#[derive(Clone, Copy, GameRecord)] +struct State { + x: f32, +} + +#[derive(Clone, Copy, GameInput)] +struct Push { + dx: i8, +} + +#[predict(Step)] +fn step(state: &State, _input: &Push, _context: &(), _dt: f32) -> State { + *state +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/predict_needs_kind.stderr b/distributed_game_macros/tests/compile_fail/predict_needs_kind.stderr new file mode 100644 index 000000000..b56063d06 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/predict_needs_kind.stderr @@ -0,0 +1,5 @@ +error: `#[predict]` needs the predicted kind: `kind = "player"` + --> tests/compile_fail/predict_needs_kind.rs:13:11 + | +13 | #[predict(Step)] + | ^^^^ diff --git a/distributed_game_macros/tests/compile_fail/replicated_from_missing_field.rs b/distributed_game_macros/tests/compile_fail/replicated_from_missing_field.rs new file mode 100644 index 000000000..3ae3ebf54 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/replicated_from_missing_field.rs @@ -0,0 +1,21 @@ +use distributed_game::Replicated; + +struct Mob { + x: f32, + y: f32, +} + +#[derive(Replicated)] +#[replicated(kind = "mob", id = 2, of = Mob)] +struct MobView { + #[from] + x: f32, + #[from] + y: f32, + #[from] + tier: u8, +} + +fn main() { + let _ = Mob { x: 0.0, y: 0.0 }.x; +} diff --git a/distributed_game_macros/tests/compile_fail/replicated_from_missing_field.stderr b/distributed_game_macros/tests/compile_fail/replicated_from_missing_field.stderr new file mode 100644 index 000000000..ddf110407 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/replicated_from_missing_field.stderr @@ -0,0 +1,7 @@ +error[E0609]: no field `tier` on type `&Mob` + --> tests/compile_fail/replicated_from_missing_field.rs:16:5 + | +16 | tier: u8, + | ^^^^ unknown field + | + = note: available fields are: `x`, `y` diff --git a/distributed_game_macros/tests/compile_fail/replicated_from_needs_of.rs b/distributed_game_macros/tests/compile_fail/replicated_from_needs_of.rs new file mode 100644 index 000000000..17c670358 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/replicated_from_needs_of.rs @@ -0,0 +1,11 @@ +use distributed_game::Replicated; + +#[derive(Replicated)] +#[replicated(kind = "mob", id = 2)] +struct MobView { + #[from] + x: f32, + y: f32, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/replicated_from_needs_of.stderr b/distributed_game_macros/tests/compile_fail/replicated_from_needs_of.stderr new file mode 100644 index 000000000..b17c524dd --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/replicated_from_needs_of.stderr @@ -0,0 +1,5 @@ +error: #[from] needs the entity type: #[replicated(.., of = Entity)] + --> tests/compile_fail/replicated_from_needs_of.rs:6:5 + | +6 | #[from] + | ^ diff --git a/distributed_game_macros/tests/compile_fail/replicated_from_wrong_type.rs b/distributed_game_macros/tests/compile_fail/replicated_from_wrong_type.rs new file mode 100644 index 000000000..9834d968d --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/replicated_from_wrong_type.rs @@ -0,0 +1,27 @@ +use distributed_game::Replicated; + +struct State { + x: f32, + y: f32, +} + +struct Player { + state: State, + hp: i32, +} + +#[derive(Replicated)] +#[replicated(kind = "player", id = 1, of = Player)] +struct PlayerView { + #[from(state.x)] + x: f32, + #[from(state.y)] + y: f32, + #[from] + hp: u8, +} + +fn main() { + let p = Player { state: State { x: 0.0, y: 0.0 }, hp: 1 }; + let _ = (p.state.x, p.state.y, p.hp); +} diff --git a/distributed_game_macros/tests/compile_fail/replicated_from_wrong_type.stderr b/distributed_game_macros/tests/compile_fail/replicated_from_wrong_type.stderr new file mode 100644 index 000000000..c50c90e65 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/replicated_from_wrong_type.stderr @@ -0,0 +1,5 @@ +error[E0308]: mismatched types + --> tests/compile_fail/replicated_from_wrong_type.rs:20:5 + | +20 | #[from] + | ^ expected `u8`, found `i32` diff --git a/distributed_game_macros/tests/compile_fail/replicated_needs_kind.rs b/distributed_game_macros/tests/compile_fail/replicated_needs_kind.rs new file mode 100644 index 000000000..e4319b01e --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/replicated_needs_kind.rs @@ -0,0 +1,9 @@ +use distributed_game::Replicated; + +#[derive(Replicated)] +struct OrbView { + x: f32, + y: f32, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/replicated_needs_kind.stderr b/distributed_game_macros/tests/compile_fail/replicated_needs_kind.stderr new file mode 100644 index 000000000..703985edc --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/replicated_needs_kind.stderr @@ -0,0 +1,5 @@ +error: #[derive(Replicated)] needs #[replicated(kind = "name", id = N)] + --> tests/compile_fail/replicated_needs_kind.rs:4:8 + | +4 | struct OrbView { + | ^^^^^^^ diff --git a/distributed_game_macros/tests/compile_fail/replicated_needs_position.rs b/distributed_game_macros/tests/compile_fail/replicated_needs_position.rs new file mode 100644 index 000000000..bf2f16687 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/replicated_needs_position.rs @@ -0,0 +1,9 @@ +use distributed_game::Replicated; + +#[derive(Replicated)] +#[replicated(kind = "score", id = 3)] +struct ScoreView { + points: u32, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/replicated_needs_position.stderr b/distributed_game_macros/tests/compile_fail/replicated_needs_position.stderr new file mode 100644 index 000000000..f2d61d254 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/replicated_needs_position.stderr @@ -0,0 +1,5 @@ +error: a non-global kind needs a position: name fields `x` and `y`, point at them with #[replicated(x = .., y = ..)], or mark the kind `global` + --> tests/compile_fail/replicated_needs_position.rs:5:8 + | +5 | struct ScoreView { + | ^^^^^^^^^ diff --git a/distributed_game_macros/tests/compile_fail/replicated_unknown_correction.rs b/distributed_game_macros/tests/compile_fail/replicated_unknown_correction.rs new file mode 100644 index 000000000..6bafa1254 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/replicated_unknown_correction.rs @@ -0,0 +1,11 @@ +use distributed_game::Replicated; + +#[derive(Replicated)] +#[replicated(kind = "orb", id = 1)] +struct OrbView { + #[correct(wobble)] + x: f32, + y: f32, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/replicated_unknown_correction.stderr b/distributed_game_macros/tests/compile_fail/replicated_unknown_correction.stderr new file mode 100644 index 000000000..8489371a7 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/replicated_unknown_correction.stderr @@ -0,0 +1,5 @@ +error: expected `ease`, `ease = MS`, `snap` or `replace` (with `ease`: `snap_above = M`) in #[correct(..)] + --> tests/compile_fail/replicated_unknown_correction.rs:6:15 + | +6 | #[correct(wobble)] + | ^^^^^^ diff --git a/distributed_game_macros/tests/compile_fail/ticket_extension_flatten.rs b/distributed_game_macros/tests/compile_fail/ticket_extension_flatten.rs new file mode 100644 index 000000000..ecfdfcf84 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/ticket_extension_flatten.rs @@ -0,0 +1,15 @@ +use distributed_game::TicketExtension; + +#[derive(serde::Serialize, serde::Deserialize)] +struct Extra { + team: u8, +} + +#[derive(serde::Serialize, serde::Deserialize, TicketExtension)] +struct MatchClaims { + match_id: String, + #[serde(flatten)] + extra: Extra, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/ticket_extension_flatten.stderr b/distributed_game_macros/tests/compile_fail/ticket_extension_flatten.stderr new file mode 100644 index 000000000..aa6a428c9 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/ticket_extension_flatten.stderr @@ -0,0 +1,5 @@ +error: #[derive(TicketExtension)] does not support `flatten`; declare every claim as a field + --> tests/compile_fail/ticket_extension_flatten.rs:11:13 + | +11 | #[serde(flatten)] + | ^^^^^^^ diff --git a/distributed_game_macros/tests/compile_fail/ticket_extension_identity.rs b/distributed_game_macros/tests/compile_fail/ticket_extension_identity.rs new file mode 100644 index 000000000..f0390da9e --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/ticket_extension_identity.rs @@ -0,0 +1,12 @@ +use distributed_game::TicketExtension; + +// Identity only ever comes from the verified `sub`; amounts from handlers. +#[derive(serde::Serialize, serde::Deserialize, TicketExtension)] +struct MatchClaims { + match_id: String, + userId: String, + #[serde(rename = "Gold")] + purse: u32, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/ticket_extension_identity.stderr b/distributed_game_macros/tests/compile_fail/ticket_extension_identity.stderr new file mode 100644 index 000000000..dfcc205e9 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/ticket_extension_identity.stderr @@ -0,0 +1,11 @@ +error: ticket claim field `userId` looks like identity: identity is only ever the verified `sub`, and rewards and economy values are decided by command handlers, never vouched for in a ticket + --> tests/compile_fail/ticket_extension_identity.rs:7:5 + | +7 | userId: String, + | ^^^^^^ + +error: ticket claim field `Gold` looks like an economy value: identity is only ever the verified `sub`, and rewards and economy values are decided by command handlers, never vouched for in a ticket + --> tests/compile_fail/ticket_extension_identity.rs:8:22 + | +8 | #[serde(rename = "Gold")] + | ^^^^^^ diff --git a/distributed_game_macros/tests/compile_fail/ticket_extension_rename_all.rs b/distributed_game_macros/tests/compile_fail/ticket_extension_rename_all.rs new file mode 100644 index 000000000..65f6992ab --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/ticket_extension_rename_all.rs @@ -0,0 +1,9 @@ +use distributed_game::TicketExtension; + +#[derive(serde::Serialize, serde::Deserialize, TicketExtension)] +#[serde(rename_all = "camelCase")] +struct MatchClaims { + match_id: String, +} + +fn main() {} diff --git a/distributed_game_macros/tests/compile_fail/ticket_extension_rename_all.stderr b/distributed_game_macros/tests/compile_fail/ticket_extension_rename_all.stderr new file mode 100644 index 000000000..842049fc0 --- /dev/null +++ b/distributed_game_macros/tests/compile_fail/ticket_extension_rename_all.stderr @@ -0,0 +1,5 @@ +error: #[derive(TicketExtension)] does not support `rename_all`; rename fields individually + --> tests/compile_fail/ticket_extension_rename_all.rs:4:9 + | +4 | #[serde(rename_all = "camelCase")] + | ^^^^^^^^^^ diff --git a/distributed_game_macros/tests/rustc_fail.rs b/distributed_game_macros/tests/rustc_fail.rs new file mode 100644 index 000000000..9b2fd816d --- /dev/null +++ b/distributed_game_macros/tests/rustc_fail.rs @@ -0,0 +1,43 @@ +//! Compile failures reported through a trait bound (`#[diagnostic::on_unimplemented]` +//! text or a type mismatch) rather than the macro's own error. Each must fail +//! and name its cause; rustc's notes around it are not pinned. See +//! `tests/support/rustc_fail.rs` at the workspace root. + +#[path = "../../tests/support/rustc_fail.rs"] +mod rustc_fail; + +#[test] +fn rustc_rejects_generated_code_for_the_named_cause() { + rustc_fail::assert_fail_with( + env!("CARGO_MANIFEST_DIR"), + "tests/rustc_fail", + r#"distributed_game = { path = "{workspace}/distributed_game" } +serde = { version = "1", features = ["derive"] }"#, + &[ + ( + "game_pure_unsupported_output", + &["`Opaque` has no game payload encoding"], + ), + ( + "input_buttons_on_float", + &["`#[buttons]` needs a u8, u16 or u32 field, not `f32`"], + ), + ( + "input_unsupported_field", + &["`String` cannot be a game input field"], + ), + ( + "replicated_unsupported_type", + &["`i8` cannot be a replicated entity field"], + ), + ( + "replicated_quant_on_integer", + &["`#[quant]` / `#[angle]` need an `f32` field, not `u8`"], + ), + ( + "predict_returns_state", + &["E0308", "expected `State`, found `f32`"], + ), + ], + ); +} diff --git a/distributed_game_macros/tests/rustc_fail/game_pure_unsupported_output.rs b/distributed_game_macros/tests/rustc_fail/game_pure_unsupported_output.rs new file mode 100644 index 000000000..86503879f --- /dev/null +++ b/distributed_game_macros/tests/rustc_fail/game_pure_unsupported_output.rs @@ -0,0 +1,11 @@ +use distributed_game::game_pure; + +struct Opaque; + +// The output must have a payload encoding. +#[game_pure(Make)] +fn make() -> Opaque { + Opaque +} + +fn main() {} diff --git a/distributed_game_macros/tests/rustc_fail/input_buttons_on_float.rs b/distributed_game_macros/tests/rustc_fail/input_buttons_on_float.rs new file mode 100644 index 000000000..ab9997be7 --- /dev/null +++ b/distributed_game_macros/tests/rustc_fail/input_buttons_on_float.rs @@ -0,0 +1,9 @@ +use distributed_game::GameInput; + +#[derive(GameInput)] +struct PadInput { + #[buttons(jump, duck)] + buttons: f32, +} + +fn main() {} diff --git a/distributed_game_macros/tests/rustc_fail/input_unsupported_field.rs b/distributed_game_macros/tests/rustc_fail/input_unsupported_field.rs new file mode 100644 index 000000000..6b56e28e7 --- /dev/null +++ b/distributed_game_macros/tests/rustc_fail/input_unsupported_field.rs @@ -0,0 +1,8 @@ +use distributed_game::GameInput; + +#[derive(GameInput)] +struct ChatInput { + text: String, +} + +fn main() {} diff --git a/distributed_game_macros/tests/rustc_fail/predict_returns_state.rs b/distributed_game_macros/tests/rustc_fail/predict_returns_state.rs new file mode 100644 index 000000000..0826a0fc8 --- /dev/null +++ b/distributed_game_macros/tests/rustc_fail/predict_returns_state.rs @@ -0,0 +1,18 @@ +use distributed_game::{predict, GameInput, GameRecord}; + +#[derive(Clone, Copy, GameRecord)] +struct State { + x: f32, +} + +#[derive(Clone, Copy, GameInput)] +struct Push { + dx: i8, +} + +#[predict(Step, kind = "dot")] +fn step(state: &State, _input: &Push, _context: &(), _dt: f32) -> f32 { + state.x +} + +fn main() {} diff --git a/distributed_game_macros/tests/rustc_fail/replicated_quant_on_integer.rs b/distributed_game_macros/tests/rustc_fail/replicated_quant_on_integer.rs new file mode 100644 index 000000000..6ee2b99dc --- /dev/null +++ b/distributed_game_macros/tests/rustc_fail/replicated_quant_on_integer.rs @@ -0,0 +1,11 @@ +use distributed_game::Replicated; + +#[derive(Replicated)] +#[replicated(kind = "orb", id = 1)] +struct OrbView { + #[quant(min = 0.0, max = 10.0, bits = 8)] + x: u8, + y: f32, +} + +fn main() {} diff --git a/distributed_game_macros/tests/rustc_fail/replicated_unsupported_type.rs b/distributed_game_macros/tests/rustc_fail/replicated_unsupported_type.rs new file mode 100644 index 000000000..6d58f301f --- /dev/null +++ b/distributed_game_macros/tests/rustc_fail/replicated_unsupported_type.rs @@ -0,0 +1,11 @@ +use distributed_game::Replicated; + +#[derive(Replicated)] +#[replicated(kind = "orb", id = 1)] +struct OrbView { + x: f32, + y: f32, + charge: i8, +} + +fn main() {} diff --git a/distributed_leaderboard/Cargo.toml b/distributed_leaderboard/Cargo.toml new file mode 100644 index 000000000..1cd3bf4ea --- /dev/null +++ b/distributed_leaderboard/Cargo.toml @@ -0,0 +1,38 @@ +[package] +name = "distributed_leaderboard" +description = "Sorted-set leaderboards for `distributed`: an idempotent, rebuildable projection target (in memory or Redis) served through GraphQL as an external read source." +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true + +[lib] +path = "src/lib.rs" + +[features] +default = [] +# `RedisLeaderboard`: Redis sorted sets, every idempotent write one Lua script. +redis = ["dep:redis"] +# `@live` refresh of a `GraphqlEngine`'s board roots: `change_listener` (same +# process) and `change_handlers` (board change notices over the bus). +graphql = ["distributed/graphql"] + +[dependencies] +async-trait = "0.1" +distributed = { path = "..", default-features = false } +redis = { version = "1.7.1", default-features = false, features = ["script", "tokio-comp", "connection-manager"], optional = true } +serde = { version = "1.0.210", features = ["derive"] } +serde_json = "1.0.128" +tokio = { version = "1", features = ["rt", "sync", "time"] } +tracing = "0.1" +uuid = { version = "1", features = ["v7"] } + +[dev-dependencies] +async-graphql = "7" +# The service guard (`common::env`) shared with the workspace integration tests. +common = { path = "../tests/common" } +distributed = { path = "..", features = ["graphql", "sqlite"] } +distributed_cli = { path = "../distributed_cli" } +futures-util = { version = "0.3", default-features = false, features = ["std"] } +sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", "sqlite"] } +tokio = { version = "1", features = ["full", "test-util"] } diff --git a/distributed_leaderboard/src/conformance.rs b/distributed_leaderboard/src/conformance.rs new file mode 100644 index 000000000..192f2378e --- /dev/null +++ b/distributed_leaderboard/src/conformance.rs @@ -0,0 +1,271 @@ +//! Behavioural contract every [`LeaderboardStore`] must satisfy. +//! +//! Run by the in-memory unit tests and by the Redis integration test, so both +//! implementations are held to identical ordering, policy, idempotency and +//! rebuild semantics. Panics on the first violation. + +use crate::{ + ApplyKey, ApplyOutcome, Board, LeaderboardErrorKind, LeaderboardStore, ScorePolicy, + ScoreSubmission, +}; + +fn sub(member: &str, score: f64, policy: ScorePolicy) -> ScoreSubmission { + ScoreSubmission::new(member, score, policy) +} + +fn rows(entries: &[super::LeaderboardEntry]) -> Vec<(u64, &str, f64)> { + entries + .iter() + .map(|e| (e.rank, e.member.as_str(), e.score)) + .collect() +} + +/// Run the whole contract using boards whose names start with `prefix`. +/// Boards are reset first, so a shared Redis is fine with a unique prefix. +pub async fn run_store_contract(store: &S, prefix: &str) { + policies(store, prefix).await; + ordering_and_queries(store, prefix).await; + idempotent_apply(store, prefix).await; + rebuild_and_promote(store, prefix).await; + validation(store, prefix).await; +} + +async fn fresh(store: &S, board: Board) -> Board { + store.reset(&board).await.unwrap(); + store.reset(&board.staging()).await.unwrap(); + board +} + +async fn policies(store: &S, prefix: &str) { + let board = fresh( + store, + Board::high_first(format!("{prefix}-policies")).unwrap(), + ) + .await; + use ScorePolicy::*; + assert_eq!( + store.submit(&board, &sub("max", 10.0, Max)).await.unwrap(), + 10.0 + ); + assert_eq!( + store.submit(&board, &sub("max", 5.0, Max)).await.unwrap(), + 10.0 + ); + assert_eq!( + store.submit(&board, &sub("max", 12.5, Max)).await.unwrap(), + 12.5 + ); + assert_eq!( + store.submit(&board, &sub("min", 10.0, Min)).await.unwrap(), + 10.0 + ); + assert_eq!( + store.submit(&board, &sub("min", 15.0, Min)).await.unwrap(), + 10.0 + ); + assert_eq!( + store.submit(&board, &sub("min", -3.0, Min)).await.unwrap(), + -3.0 + ); + assert_eq!( + store + .submit(&board, &sub("rep", 10.0, Replace)) + .await + .unwrap(), + 10.0 + ); + assert_eq!( + store + .submit(&board, &sub("rep", 1.0, Replace)) + .await + .unwrap(), + 1.0 + ); + assert_eq!( + store + .submit(&board, &sub("inc", 2.5, Increment)) + .await + .unwrap(), + 2.5 + ); + assert_eq!( + store + .submit(&board, &sub("inc", 4.0, Increment)) + .await + .unwrap(), + 6.5 + ); + assert_eq!( + store + .submit(&board, &sub("inc", -1.5, Increment)) + .await + .unwrap(), + 5.0 + ); + assert_eq!(store.score(&board, "max").await.unwrap(), Some(12.5)); + assert_eq!(store.score(&board, "missing").await.unwrap(), None); + assert_eq!(store.len(&board).await.unwrap(), 4); + assert!(store.remove(&board, "rep").await.unwrap()); + assert!(!store.remove(&board, "rep").await.unwrap()); + assert_eq!(store.len(&board).await.unwrap(), 3); +} + +async fn ordering_and_queries(store: &S, prefix: &str) { + let high = fresh(store, Board::high_first(format!("{prefix}-high")).unwrap()).await; + let low = fresh(store, Board::low_first(format!("{prefix}-low")).unwrap()).await; + for (member, score) in [ + ("a", 30.0), + ("b", 10.0), + ("c", 20.0), + ("d", 20.0), + ("e", 5.0), + ] { + for board in [&high, &low] { + store + .submit(board, &sub(member, score, ScorePolicy::Replace)) + .await + .unwrap(); + } + } + // Ties break by member bytes: descending on HighFirst, ascending on LowFirst. + assert_eq!( + rows(&store.top(&high, 10).await.unwrap()), + vec![ + (0, "a", 30.0), + (1, "d", 20.0), + (2, "c", 20.0), + (3, "b", 10.0), + (4, "e", 5.0) + ] + ); + assert_eq!( + rows(&store.top(&low, 2).await.unwrap()), + vec![(0, "e", 5.0), (1, "b", 10.0)] + ); + assert!(store.top(&high, 0).await.unwrap().is_empty()); + assert_eq!(store.rank(&high, "a").await.unwrap(), Some(0)); + assert_eq!(store.rank(&high, "c").await.unwrap(), Some(2)); + assert_eq!(store.rank(&low, "a").await.unwrap(), Some(4)); + assert_eq!(store.rank(&low, "zz").await.unwrap(), None); + assert_eq!( + rows(&store.around(&high, "c", 1).await.unwrap()), + vec![(1, "d", 20.0), (2, "c", 20.0), (3, "b", 10.0)] + ); + assert_eq!( + rows(&store.around(&high, "a", 2).await.unwrap()), + vec![(0, "a", 30.0), (1, "d", 20.0), (2, "c", 20.0)] + ); + assert_eq!( + rows(&store.around(&low, "a", 1).await.unwrap()), + vec![(3, "d", 20.0), (4, "a", 30.0)] + ); + assert_eq!( + rows(&store.around(&low, "b", 0).await.unwrap()), + vec![(1, "b", 10.0)] + ); + assert!(store.around(&high, "zz", 3).await.unwrap().is_empty()); +} + +async fn idempotent_apply(store: &S, prefix: &str) { + let board = fresh(store, Board::high_first(format!("{prefix}-apply")).unwrap()).await; + let inc = sub("p", 5.0, ScorePolicy::Increment); + let k1 = ApplyKey::new("evt-1#0", 1_000); + let k2 = ApplyKey::new("evt-2#0", 2_000); + assert_eq!( + store.apply(&board, &inc, &k1).await.unwrap(), + ApplyOutcome::Applied { score: 5.0 } + ); + assert_eq!( + store.apply(&board, &inc, &k1).await.unwrap(), + ApplyOutcome::Duplicate { score: Some(5.0) } + ); + assert_eq!( + store.apply(&board, &inc, &k2).await.unwrap(), + ApplyOutcome::Applied { score: 10.0 } + ); + // Duplicate detection is per board: the same key applies to another board. + let other = fresh( + store, + Board::high_first(format!("{prefix}-apply-other")).unwrap(), + ) + .await; + assert!(!store.apply(&other, &inc, &k1).await.unwrap().is_duplicate()); + // Pruning forgets old keys only. + assert_eq!(store.prune_applied(&board, 1_500).await.unwrap(), 1); + assert!(store.apply(&board, &inc, &k2).await.unwrap().is_duplicate()); + assert_eq!( + store.apply(&board, &inc, &k1).await.unwrap(), + ApplyOutcome::Applied { score: 15.0 } + ); + // A non-improving Max still records its key. + let max = sub("p", 1.0, ScorePolicy::Max); + let k3 = ApplyKey::new("evt-3#0", 3_000); + assert_eq!( + store.apply(&board, &max, &k3).await.unwrap(), + ApplyOutcome::Applied { score: 15.0 } + ); + assert!(store.apply(&board, &max, &k3).await.unwrap().is_duplicate()); + // Reset clears scores and applied keys. + store.reset(&board).await.unwrap(); + assert_eq!(store.len(&board).await.unwrap(), 0); + assert_eq!( + store.apply(&board, &inc, &k1).await.unwrap(), + ApplyOutcome::Applied { score: 5.0 } + ); +} + +async fn rebuild_and_promote(store: &S, prefix: &str) { + let board = fresh( + store, + Board::high_first(format!("{prefix}-rebuild")).unwrap(), + ) + .await; + let staging = board.staging(); + store + .submit(&board, &sub("old", 99.0, ScorePolicy::Replace)) + .await + .unwrap(); + let key = ApplyKey::new("evt-r#0", 10); + store + .apply(&staging, &sub("new", 7.0, ScorePolicy::Increment), &key) + .await + .unwrap(); + // Staging is invisible to live reads until promoted. + assert_eq!(store.score(&board, "new").await.unwrap(), None); + store.promote(&board).await.unwrap(); + assert_eq!(store.score(&board, "old").await.unwrap(), None); + assert_eq!(store.score(&board, "new").await.unwrap(), Some(7.0)); + assert_eq!(store.len(&staging).await.unwrap(), 0); + // The applied keys moved with the scores. + assert!(store + .apply(&board, &sub("new", 7.0, ScorePolicy::Increment), &key) + .await + .unwrap() + .is_duplicate()); + // Promoting an empty staging board empties live. + store.promote(&board).await.unwrap(); + assert_eq!(store.len(&board).await.unwrap(), 0); +} + +async fn validation(store: &S, prefix: &str) { + let board = fresh( + store, + Board::high_first(format!("{prefix}-invalid")).unwrap(), + ) + .await; + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let err = store + .submit(&board, &sub("p", bad, ScorePolicy::Replace)) + .await + .unwrap_err(); + assert_eq!(err.kind(), LeaderboardErrorKind::Invalid); + } + let err = store + .submit(&board, &sub("", 1.0, ScorePolicy::Replace)) + .await + .unwrap_err(); + assert_eq!(err.kind(), LeaderboardErrorKind::Invalid); + assert!(Board::high_first("").is_err()); + assert!(Board::high_first("a{b}").is_err()); + assert_eq!(store.len(&board).await.unwrap(), 0); +} diff --git a/distributed_leaderboard/src/in_memory.rs b/distributed_leaderboard/src/in_memory.rs new file mode 100644 index 000000000..5b793f5f5 --- /dev/null +++ b/distributed_leaderboard/src/in_memory.rs @@ -0,0 +1,224 @@ +//! Dependency-free [`LeaderboardStore`] for tests and demos. + +use std::collections::HashMap; +use std::sync::Mutex; + +use async_trait::async_trait; + +use crate::{ + validate_member, ApplyKey, ApplyOutcome, Board, LeaderboardEntry, LeaderboardError, + LeaderboardStore, ScoreOrder, ScorePolicy, ScoreSubmission, +}; + +#[derive(Debug, Default, Clone)] +struct BoardState { + scores: HashMap, + applied: HashMap, +} + +impl BoardState { + fn submit(&mut self, submission: &ScoreSubmission) -> Result { + let existing = self.scores.get(&submission.member).copied(); + let score = submission.score; + let next = match submission.policy { + ScorePolicy::Increment => existing.unwrap_or(0.0) + score, + ScorePolicy::Max => existing.map_or(score, |current| current.max(score)), + ScorePolicy::Min => existing.map_or(score, |current| current.min(score)), + ScorePolicy::Replace => score, + }; + if !next.is_finite() { + return Err(LeaderboardError::invalid("resulting score is not finite")); + } + self.scores.insert(submission.member.clone(), next); + Ok(next) + } + + /// Rows in rank order, matching Redis `ZRANGE`/`ZREVRANGE` tie-breaks. + fn ordered(&self, order: ScoreOrder) -> Vec<(&String, f64)> { + let mut rows: Vec<_> = self.scores.iter().map(|(m, s)| (m, *s)).collect(); + rows.sort_by(|a, b| { + a.1.total_cmp(&b.1) + .then_with(|| a.0.as_bytes().cmp(b.0.as_bytes())) + }); + if order == ScoreOrder::HighFirst { + rows.reverse(); + } + rows + } +} + +fn entries(rows: &[(&String, f64)], start: usize, end: usize) -> Vec { + rows[start..end] + .iter() + .enumerate() + .map(|(offset, (member, score))| LeaderboardEntry { + rank: (start + offset) as u64, + member: (*member).clone(), + score: *score, + }) + .collect() +} + +/// An in-process [`LeaderboardStore`] with the same semantics as the Redis +/// implementation. Queries sort on each call, so it is meant for tests, demos +/// and small boards. +#[derive(Debug, Default)] +pub struct InMemoryLeaderboard { + boards: Mutex>, +} + +impl InMemoryLeaderboard { + /// An empty store. + pub fn new() -> Self { + Self::default() + } + + fn with_board(&self, board: &Board, f: impl FnOnce(&mut BoardState) -> R) -> R { + let mut boards = self.boards.lock().unwrap_or_else(|e| e.into_inner()); + let state = boards + .entry((board.name().to_string(), board.is_staging())) + .or_default(); + f(state) + } +} + +#[async_trait] +impl LeaderboardStore for InMemoryLeaderboard { + async fn submit( + &self, + board: &Board, + submission: &ScoreSubmission, + ) -> Result { + submission.validate()?; + self.with_board(board, |state| state.submit(submission)) + } + + async fn apply( + &self, + board: &Board, + submission: &ScoreSubmission, + key: &ApplyKey, + ) -> Result { + submission.validate()?; + key.validate()?; + self.with_board(board, |state| { + if state.applied.contains_key(&key.id) { + return Ok(ApplyOutcome::Duplicate { + score: state.scores.get(&submission.member).copied(), + }); + } + let score = state.submit(submission)?; + state.applied.insert(key.id.clone(), key.at_unix_ms); + Ok(ApplyOutcome::Applied { score }) + }) + } + + async fn score(&self, board: &Board, member: &str) -> Result, LeaderboardError> { + validate_member(member)?; + Ok(self.with_board(board, |state| state.scores.get(member).copied())) + } + + async fn rank(&self, board: &Board, member: &str) -> Result, LeaderboardError> { + validate_member(member)?; + Ok(self.with_board(board, |state| { + state + .ordered(board.order()) + .iter() + .position(|(m, _)| m.as_str() == member) + .map(|rank| rank as u64) + })) + } + + async fn top( + &self, + board: &Board, + n: usize, + ) -> Result, LeaderboardError> { + Ok(self.with_board(board, |state| { + let rows = state.ordered(board.order()); + entries(&rows, 0, n.min(rows.len())) + })) + } + + async fn around( + &self, + board: &Board, + member: &str, + radius: usize, + ) -> Result, LeaderboardError> { + validate_member(member)?; + Ok(self.with_board(board, |state| { + let rows = state.ordered(board.order()); + let Some(rank) = rows.iter().position(|(m, _)| m.as_str() == member) else { + return Vec::new(); + }; + let start = rank.saturating_sub(radius); + let end = rank + .saturating_add(radius) + .saturating_add(1) + .min(rows.len()); + entries(&rows, start, end) + })) + } + + async fn len(&self, board: &Board) -> Result { + Ok(self.with_board(board, |state| state.scores.len() as u64)) + } + + async fn remove(&self, board: &Board, member: &str) -> Result { + validate_member(member)?; + Ok(self.with_board(board, |state| state.scores.remove(member).is_some())) + } + + async fn reset(&self, board: &Board) -> Result<(), LeaderboardError> { + let mut boards = self.boards.lock().unwrap_or_else(|e| e.into_inner()); + boards.remove(&(board.name().to_string(), board.is_staging())); + Ok(()) + } + + async fn promote(&self, board: &Board) -> Result<(), LeaderboardError> { + let mut boards = self.boards.lock().unwrap_or_else(|e| e.into_inner()); + let staged = boards + .remove(&(board.name().to_string(), true)) + .unwrap_or_default(); + boards.insert((board.name().to_string(), false), staged); + Ok(()) + } + + async fn prune_applied( + &self, + board: &Board, + before_unix_ms: u64, + ) -> Result { + Ok(self.with_board(board, |state| { + let before = state.applied.len(); + state.applied.retain(|_, at| *at >= before_unix_ms); + (before - state.applied.len()) as u64 + })) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn in_memory_store_satisfies_the_leaderboard_contract() { + let store = InMemoryLeaderboard::new(); + crate::conformance::run_store_contract(&store, "contract").await; + } + + #[tokio::test] + async fn boards_are_isolated_by_name_and_variant() { + let store = InMemoryLeaderboard::new(); + let a = Board::high_first("a").unwrap(); + let b = Board::high_first("b").unwrap(); + store + .submit(&a, &ScoreSubmission::new("p", 1.0, ScorePolicy::Replace)) + .await + .unwrap(); + assert_eq!(store.len(&b).await.unwrap(), 0); + assert_eq!(store.len(&a.staging()).await.unwrap(), 0); + assert_eq!(store.len(&a).await.unwrap(), 1); + } +} diff --git a/distributed_leaderboard/src/lib.rs b/distributed_leaderboard/src/lib.rs new file mode 100644 index 000000000..b43f02b59 --- /dev/null +++ b/distributed_leaderboard/src/lib.rs @@ -0,0 +1,537 @@ +//! Sorted-set leaderboards as a rebuildable projection target. +//! +//! Leaderboards are a poor fit for the relational read-model traits +//! (`ReadModelWritePlanStore` and friends): the hot queries are *rank of +//! member*, *top N* and *members around a member*, which a sorted set answers +//! in `O(log n)` while a SQL table needs a window function or a full index +//! scan per request. This crate is therefore a dedicated, typed seam rather +//! than another relational backend. +//! +//! # Pieces +//! +//! - [`LeaderboardStore`] — the typed store API: [`submit`](LeaderboardStore::submit) +//! a score under a [`ScorePolicy`], [`rank`](LeaderboardStore::rank), +//! [`score`](LeaderboardStore::score), [`top`](LeaderboardStore::top), +//! [`around`](LeaderboardStore::around), [`reset`](LeaderboardStore::reset) +//! and the rebuild primitives ([`Board::staging`] + [`promote`](LeaderboardStore::promote)). +//! - [`InMemoryLeaderboard`] — a dependency-free implementation with the same +//! ordering and tie-break semantics as Redis, for tests and demos. +//! - `RedisLeaderboard` (feature `redis`) — Redis sorted sets, with every +//! idempotent write executed by one Lua script. +//! - [`LeaderboardProjector`] — maps [`DomainEventOccurrence`](distributed::DomainEventOccurrence)s +//! (directly, or decoded from an outbox [`Message`](distributed::bus::Message)) +//! to score changes through a [`LeaderboardProjection`], applies them +//! idempotently and rebuilds boards from an event history. +//! - [`LeaderboardSurface`] + [`LeaderboardRoots`] — boards as GraphQL roots +//! through the engine's external read source extension point +//! (`GraphqlEngineBuilder::external_read_source`): top-N, around-me and +//! my-rank roots, `@live` subscriptions, the application contract and the +//! client manifest's `leaderboards` section (`leaderboards.ts`). +//! - [`LeaderboardChangePublisher`] / [`LeaderboardChanged`] — board change +//! notices on the bus, for `@live` boards served by another process; with +//! the `graphql` feature, `change_listener` and `change_handlers` feed a +//! `GraphqlEngine`. See `docs/live-query-delivery.md`. +//! +//! # How it plugs into projections +//! +//! A leaderboard is an *eventual* projection: the source of truth stays the +//! aggregate event stream, and the board can be thrown away and rebuilt at any +//! time. Feed it from the outbox / bus: publish domain events through the +//! outbox as usual and subscribe a consumer whose handler calls +//! [`LeaderboardProjector::apply_message`]. The handler returns a classified +//! [`TransportError`](distributed::bus::TransportError): a Redis outage is +//! retryable (the message is redelivered), an undecodable payload is +//! permanent. Because gameplay commands only commit to the event store and +//! outbox, a Redis blip delays the board but never blocks a command. A +//! process that already holds committed occurrences (a poller, a relay) calls +//! [`LeaderboardProjector::apply_event`] itself and retries what failed. +//! +//! # Idempotency +//! +//! At-least-once delivery and replays must not double-increment. Each change +//! applied by the projector carries an [`ApplyKey`]: the occurrence id plus the +//! change's index within that occurrence (`"#"`), and the +//! occurrence timestamp. A store records applied keys *per board* in a second +//! structure (in Redis, a sorted set of applied ids scored by event time) and +//! checks-and-records them atomically with the score change (in Redis, one Lua +//! script, so the check, the `ZADD`/`ZINCRBY` and the record cannot interleave +//! with another writer). A duplicate returns [`ApplyOutcome::Duplicate`] and +//! changes nothing. Projections must therefore be deterministic: the same +//! occurrence must always produce the same changes in the same order. +//! +//! The applied-key set grows with the number of applied changes. Two ways keep +//! it bounded: [`LeaderboardStore::prune_applied`] forgets keys older than a +//! cutoff (safe once redelivery older than the cutoff is impossible — e.g. +//! beyond the bus retention window), and a rebuild starts from an empty set. +//! +//! # Rebuild +//! +//! [`LeaderboardProjector::begin_rebuild`] writes into the *staging* variant +//! of each board ([`Board::staging`]) and [`LeaderboardRebuild::commit`] +//! atomically promotes staging over live, so readers never see a half-built +//! board. Live updates applied while a rebuild runs land on the old live board +//! and are discarded by the promote; replay the tail of the stream from the +//! rebuild's starting cursor after committing — the promoted applied-key set +//! makes overlapping replay safe. + +mod in_memory; +#[cfg(feature = "graphql")] +mod live; +mod manifest; +mod notify; +mod projector; +#[cfg(feature = "redis")] +mod redis; +mod roots; +mod surface; + +use std::fmt; + +use async_trait::async_trait; + +pub use in_memory::InMemoryLeaderboard; +#[cfg(feature = "graphql")] +pub use live::{change_handlers, change_listener}; +pub use manifest::{ + ClientLeaderboard, ClientLeaderboardArgument, ClientLeaderboardRoot, LEADERBOARDS_SECTION, +}; +pub use notify::{ + LeaderboardChangePublisher, LeaderboardChanged, ALL_BOARDS_CHANGE_KEY, + LEADERBOARD_CHANGED_EVENT, +}; +pub use projector::{ + LeaderboardChange, LeaderboardChangeListener, LeaderboardProjection, LeaderboardProjector, + LeaderboardRebuild, ProjectionReport, +}; +#[cfg(feature = "redis")] +pub use redis::{RedisLeaderboard, DEFAULT_REDIS_LEADERBOARD_PREFIX}; +pub use roots::LeaderboardRoots; +pub use surface::{ + leaderboard_change_key, LeaderboardBoards, LeaderboardGrant, LeaderboardOperation, + LeaderboardSurface, LEADERBOARD_DEFAULT_FIRST, LEADERBOARD_ENTRY_TYPE, LEADERBOARD_MAX_FIRST, + LEADERBOARD_MAX_RADIUS, MAX_LEADERBOARD_KEY_LEN, +}; + +/// Maximum board name length in bytes. +pub const MAX_BOARD_NAME_LEN: usize = 200; +/// Maximum member length in bytes. +pub const MAX_MEMBER_LEN: usize = 512; + +/// Which end of the sorted set ranks first. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ScoreOrder { + /// Highest score is rank 0 (points, kills, gold). + HighFirst, + /// Lowest score is rank 0 (speedrun times, deaths). + LowFirst, +} + +/// How a submitted score combines with a member's existing score. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ScorePolicy { + /// Keep the greater of the existing and submitted score (`ZADD GT`). + Max, + /// Keep the lesser of the existing and submitted score (`ZADD LT`). + Min, + /// Overwrite the existing score. + Replace, + /// Add the submitted score to the existing score (`ZINCRBY`); absent + /// members start at zero. + Increment, +} + +impl ScorePolicy { + #[cfg(feature = "redis")] + pub(crate) fn as_str(self) -> &'static str { + match self { + ScorePolicy::Max => "max", + ScorePolicy::Min => "min", + ScorePolicy::Replace => "replace", + ScorePolicy::Increment => "increment", + } + } +} + +/// A named leaderboard and its rank order. +/// +/// Every board has a *live* variant (what queries read) and a *staging* +/// variant (what a rebuild writes); [`LeaderboardStore::promote`] atomically +/// replaces live with staging. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct Board { + name: String, + order: ScoreOrder, + staging: bool, +} + +impl Board { + /// A live board. Names are 1..=[`MAX_BOARD_NAME_LEN`] bytes, without + /// control characters or `{`/`}` (reserved for Redis Cluster hash tags). + pub fn new(name: impl Into, order: ScoreOrder) -> Result { + let name = name.into(); + if name.is_empty() + || name.len() > MAX_BOARD_NAME_LEN + || name.chars().any(|c| c.is_control() || c == '{' || c == '}') + { + return Err(LeaderboardError::invalid(format!( + "invalid board name {name:?}" + ))); + } + Ok(Self { + name, + order, + staging: false, + }) + } + + /// A live board where the highest score ranks first. + pub fn high_first(name: impl Into) -> Result { + Self::new(name, ScoreOrder::HighFirst) + } + + /// A live board where the lowest score ranks first. + pub fn low_first(name: impl Into) -> Result { + Self::new(name, ScoreOrder::LowFirst) + } + + /// The board name. + pub fn name(&self) -> &str { + &self.name + } + + /// The board's rank order. + pub fn order(&self) -> ScoreOrder { + self.order + } + + /// Whether this is the staging (rebuild) variant. + pub fn is_staging(&self) -> bool { + self.staging + } + + /// The staging variant of this board. + pub fn staging(&self) -> Board { + Board { + staging: true, + ..self.clone() + } + } + + /// The live variant of this board. + pub fn live(&self) -> Board { + Board { + staging: false, + ..self.clone() + } + } +} + +/// One score submission for one member. +#[derive(Debug, Clone, PartialEq)] +pub struct ScoreSubmission { + /// The ranked member (player id, guild id, ...). + pub member: String, + /// The submitted score. Must be finite. + pub score: f64, + /// How the score combines with the existing one. + pub policy: ScorePolicy, +} + +impl ScoreSubmission { + /// Build a submission. + pub fn new(member: impl Into, score: f64, policy: ScorePolicy) -> Self { + Self { + member: member.into(), + score, + policy, + } + } + + pub(crate) fn validate(&self) -> Result<(), LeaderboardError> { + validate_member(&self.member)?; + if !self.score.is_finite() { + return Err(LeaderboardError::invalid("score must be finite")); + } + Ok(()) + } +} + +pub(crate) fn validate_member(member: &str) -> Result<(), LeaderboardError> { + if member.is_empty() || member.len() > MAX_MEMBER_LEN { + return Err(LeaderboardError::invalid(format!( + "member must be 1..={MAX_MEMBER_LEN} bytes" + ))); + } + Ok(()) +} + +/// The deduplication identity of one applied change. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct ApplyKey { + /// Stable id; the projector uses `"#"`. + pub id: String, + /// Event time in Unix milliseconds; [`LeaderboardStore::prune_applied`] + /// forgets keys older than a cutoff. + pub at_unix_ms: u64, +} + +impl ApplyKey { + /// Build an apply key. + pub fn new(id: impl Into, at_unix_ms: u64) -> Self { + Self { + id: id.into(), + at_unix_ms, + } + } + + pub(crate) fn validate(&self) -> Result<(), LeaderboardError> { + if self.id.is_empty() || self.id.len() > MAX_MEMBER_LEN { + return Err(LeaderboardError::invalid(format!( + "apply key must be 1..={MAX_MEMBER_LEN} bytes" + ))); + } + Ok(()) + } +} + +/// Result of an idempotent [`LeaderboardStore::apply`]. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum ApplyOutcome { + /// The change was applied (a `Max`/`Min` submission that did not beat the + /// existing score still counts as applied). Carries the resulting score. + Applied { + /// Member score after the change. + score: f64, + }, + /// The key was already applied; nothing changed. + Duplicate { + /// Current member score, if any. + score: Option, + }, +} + +impl ApplyOutcome { + /// Whether this was a duplicate. + pub fn is_duplicate(&self) -> bool { + matches!(self, ApplyOutcome::Duplicate { .. }) + } +} + +/// One ranked row. +#[derive(Debug, Clone, PartialEq)] +pub struct LeaderboardEntry { + /// Zero-based rank in the board's [`ScoreOrder`]. + pub rank: u64, + /// The member. + pub member: String, + /// The member's score. + pub score: f64, +} + +/// Leaderboard failure classification. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LeaderboardErrorKind { + /// Bad input (board name, member, non-finite score) or an undecodable + /// event. Retrying the same input will not help. + Invalid, + /// The backing store is unreachable or timed out. Retry later. + Unavailable, +} + +/// A leaderboard error. +#[derive(Debug, Clone)] +pub struct LeaderboardError { + kind: LeaderboardErrorKind, + message: String, +} + +impl LeaderboardError { + /// An invalid-input error. + pub fn invalid(message: impl Into) -> Self { + Self { + kind: LeaderboardErrorKind::Invalid, + message: message.into(), + } + } + + /// A store-unavailable error. + pub fn unavailable(message: impl Into) -> Self { + Self { + kind: LeaderboardErrorKind::Unavailable, + message: message.into(), + } + } + + /// The classification. + pub fn kind(&self) -> LeaderboardErrorKind { + self.kind + } + + /// The diagnostic message. + pub fn message(&self) -> &str { + &self.message + } + + /// Map to a transport error: unavailable is retryable, invalid permanent. + pub fn into_transport_error(self) -> distributed::bus::TransportError { + match self.kind { + LeaderboardErrorKind::Unavailable => { + distributed::bus::TransportError::retryable(self.to_string()) + } + LeaderboardErrorKind::Invalid => { + distributed::bus::TransportError::permanent(self.to_string()) + } + } + } +} + +impl fmt::Display for LeaderboardError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let kind = match self.kind { + LeaderboardErrorKind::Invalid => "invalid", + LeaderboardErrorKind::Unavailable => "unavailable", + }; + write!(f, "leaderboard error ({kind}): {}", self.message) + } +} + +impl std::error::Error for LeaderboardError {} + +impl From for distributed::bus::TransportError { + fn from(err: LeaderboardError) -> Self { + err.into_transport_error() + } +} + +/// A sorted-set leaderboard store. +/// +/// Ordering contract (shared by every implementation, matching Redis): rows +/// sort by score in the board's [`ScoreOrder`]; equal scores tie-break by the +/// member's bytes — ascending for [`ScoreOrder::LowFirst`], descending for +/// [`ScoreOrder::HighFirst`] (exactly `ZRANGE` / `ZREVRANGE`). Ranks are +/// zero-based. +#[async_trait] +pub trait LeaderboardStore: Send + Sync { + /// Submit a score without deduplication and return the resulting score. + /// + /// Use for direct, already-authoritative writes. Projections should use + /// [`apply`](LeaderboardStore::apply) so redelivery is harmless. + async fn submit( + &self, + board: &Board, + submission: &ScoreSubmission, + ) -> Result; + + /// Apply a score submission at most once per `key` and board, atomically + /// with recording the key. + async fn apply( + &self, + board: &Board, + submission: &ScoreSubmission, + key: &ApplyKey, + ) -> Result; + + /// A member's score, if ranked. + async fn score(&self, board: &Board, member: &str) -> Result, LeaderboardError>; + + /// A member's zero-based rank, if ranked. + async fn rank(&self, board: &Board, member: &str) -> Result, LeaderboardError>; + + /// The first `n` rows. + async fn top(&self, board: &Board, n: usize) + -> Result, LeaderboardError>; + + /// Up to `radius` rows either side of `member`, plus the member; empty if + /// the member is not ranked. Read atomically. + async fn around( + &self, + board: &Board, + member: &str, + radius: usize, + ) -> Result, LeaderboardError>; + + /// Number of ranked members. + async fn len(&self, board: &Board) -> Result; + + /// Remove a member; returns whether it was ranked. + async fn remove(&self, board: &Board, member: &str) -> Result; + + /// Delete every score and applied key of this board variant. + async fn reset(&self, board: &Board) -> Result<(), LeaderboardError>; + + /// Atomically replace the live board (scores and applied keys) with its + /// staging variant. An absent staging board promotes as empty. + async fn promote(&self, board: &Board) -> Result<(), LeaderboardError>; + + /// Forget applied keys recorded with `at_unix_ms < before_unix_ms`; + /// returns how many were forgotten. + async fn prune_applied( + &self, + board: &Board, + before_unix_ms: u64, + ) -> Result; +} + +#[async_trait] +impl LeaderboardStore for std::sync::Arc { + async fn submit( + &self, + board: &Board, + submission: &ScoreSubmission, + ) -> Result { + (**self).submit(board, submission).await + } + async fn apply( + &self, + board: &Board, + submission: &ScoreSubmission, + key: &ApplyKey, + ) -> Result { + (**self).apply(board, submission, key).await + } + async fn score(&self, board: &Board, member: &str) -> Result, LeaderboardError> { + (**self).score(board, member).await + } + async fn rank(&self, board: &Board, member: &str) -> Result, LeaderboardError> { + (**self).rank(board, member).await + } + async fn top( + &self, + board: &Board, + n: usize, + ) -> Result, LeaderboardError> { + (**self).top(board, n).await + } + async fn around( + &self, + board: &Board, + member: &str, + radius: usize, + ) -> Result, LeaderboardError> { + (**self).around(board, member, radius).await + } + async fn len(&self, board: &Board) -> Result { + (**self).len(board).await + } + async fn remove(&self, board: &Board, member: &str) -> Result { + (**self).remove(board, member).await + } + async fn reset(&self, board: &Board) -> Result<(), LeaderboardError> { + (**self).reset(board).await + } + async fn promote(&self, board: &Board) -> Result<(), LeaderboardError> { + (**self).promote(board).await + } + async fn prune_applied( + &self, + board: &Board, + before_unix_ms: u64, + ) -> Result { + (**self).prune_applied(board, before_unix_ms).await + } +} + +/// Shared behavioural contract run against every implementation. +#[cfg(any(test, feature = "redis"))] +#[doc(hidden)] +pub mod conformance; diff --git a/distributed_leaderboard/src/live.rs b/distributed_leaderboard/src/live.rs new file mode 100644 index 000000000..991675be9 --- /dev/null +++ b/distributed_leaderboard/src/live.rs @@ -0,0 +1,42 @@ +//! `@live` refresh of a [`GraphqlEngine`]'s leaderboard roots. + +use std::sync::Arc; + +use distributed::bus::{Handlers, Message}; +use distributed::graphql::GraphqlEngine; +use distributed::read_model::ReadModelChange; + +use crate::{leaderboard_change_key, Board, LeaderboardChangeListener, LeaderboardChanged}; + +/// A [`LeaderboardChangeListener`] that refreshes `engine`'s `@live` +/// leaderboard subscriptions: register it on the projector writing the +/// boards (`LeaderboardProjector::with_change_listener`) when that projector +/// runs in the engine's process. +pub fn change_listener(engine: &GraphqlEngine) -> LeaderboardChangeListener { + let hub = engine.change_hub().clone(); + Arc::new(move |board: &Board| { + hub.publish(ReadModelChange::new([leaderboard_change_key(board.name())])); + }) +} + +/// Bus handlers that refresh `engine`'s `@live` leaderboard subscriptions +/// from [`LEADERBOARD_CHANGED_EVENT`](crate::LEADERBOARD_CHANGED_EVENT) +/// notices, for a projector running in another process (it publishes them +/// with [`LeaderboardChangePublisher`](crate::LeaderboardChangePublisher)). +/// Run them with `bus.subscribe(Arc::new(handlers), RunOptions::default())` +/// under a consumer `group` of this process's own, so every GraphQL process +/// receives every notice. +pub fn change_handlers(engine: &GraphqlEngine, group: impl Into) -> Handlers { + let hub = engine.change_hub().clone(); + Handlers::new().named(group).on_event( + crate::LEADERBOARD_CHANGED_EVENT, + move |message: &Message| { + let notice = LeaderboardChanged::from_message(message); + let hub = hub.clone(); + async move { + hub.publish(ReadModelChange::new([notice?.change_key()])); + Ok(()) + } + }, + ) +} diff --git a/distributed_leaderboard/src/manifest.rs b/distributed_leaderboard/src/manifest.rs new file mode 100644 index 000000000..cc6e55cda --- /dev/null +++ b/distributed_leaderboard/src/manifest.rs @@ -0,0 +1,49 @@ +//! The `leaderboards` section of the client manifest +//! (`DistributedClientManifest::external`), read by the client compiler to +//! generate `leaderboards.ts`. + +use serde::{Deserialize, Serialize}; + +/// Section of the application contract and the client manifest that lists +/// leaderboard surfaces. +pub const LEADERBOARDS_SECTION: &str = "leaderboards"; + +/// One leaderboard surface on the client contract. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ClientLeaderboard { + /// GraphQL base name (`xp` → `xpLeaderboard`, …). + pub name: String, + /// Object type of each row (`LeaderboardEntry`: `rank`, `member`, `score`). + pub entry_typename: String, + /// `high_first` or `low_first`. + pub order: String, + /// `single` (no `board` argument) or `family` (`board: String!`). + pub boards: String, + pub default_first: u32, + pub max_first: u32, + pub max_radius: u32, + pub roots: Vec, +} + +/// One leaderboard root the selected roles may run. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ClientLeaderboardRoot { + pub name: String, + /// `top`, `around_me`, `my_rank` or `rank`. + pub operation: String, + /// `true`: `[LeaderboardEntry!]!`; `false`: nullable `LeaderboardEntry`. + pub list: bool, + /// Whether a same-named subscription root exists (`@live`). + pub live: bool, + pub arguments: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ClientLeaderboardArgument { + pub name: String, + pub type_name: String, + pub nullable: bool, +} diff --git a/distributed_leaderboard/src/notify.rs b/distributed_leaderboard/src/notify.rs new file mode 100644 index 000000000..116b54ccb --- /dev/null +++ b/distributed_leaderboard/src/notify.rs @@ -0,0 +1,332 @@ +//! Board change notices on the bus: `@live` boards across processes. +//! +//! A [`LeaderboardProjector`](crate::LeaderboardProjector) calls its change +//! listeners in its own process. When the GraphQL engine serving the boards +//! runs elsewhere (a zone server projects kills into Redis; a GraphQL +//! service reads the same Redis), the projector's process publishes a +//! [`LEADERBOARD_CHANGED_EVENT`] on the application's bus and the GraphQL +//! process subscribes to it: +//! +//! ```rust,ignore +//! // projector process +//! let notices = LeaderboardChangePublisher::spawn(BusPublisher::new(Arc::new(bus)), 1024); +//! let projector = LeaderboardProjector::new(store, projection) +//! .with_change_listener(notices.listener()); +//! +//! // GraphQL process (its own consumer group, so every process gets every notice) +//! let handlers = distributed_leaderboard::change_handlers(&engine, "mobpit-service-boards"); +//! tokio::spawn(async move { bus.subscribe(Arc::new(handlers), RunOptions::default()).await }); +//! ``` +//! +//! A notice names a board, or every board: the subscriber re-reads its store +//! (hash-gated, so an unchanged top-N pushes nothing). Notices are hints, so +//! duplicates and replays are harmless. + +use std::collections::BTreeSet; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; +use tokio::sync::mpsc; + +use crate::{Board, LeaderboardChangeListener}; +use distributed::bus::{Message, MessageKind, MessagePublisher, TransportError}; + +/// Event name of a board change notice. +pub const LEADERBOARD_CHANGED_EVENT: &str = "distributed.leaderboard.changed"; + +/// Change key every leaderboard read also listens on: publishing it refreshes +/// every `@live` board (a resync after notices were coalesced away). +pub const ALL_BOARDS_CHANGE_KEY: &str = "leaderboard:*"; + +/// Payload of a [`LEADERBOARD_CHANGED_EVENT`]: the board whose scores changed, +/// or `None` for "any board may have changed" (resync). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct LeaderboardChanged { + /// Board name (`Board::name`); absent for every board. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub board: Option, +} + +impl LeaderboardChanged { + /// The notice for `board`. + pub fn new(board: &Board) -> Self { + Self { + board: Some(board.name().to_string()), + } + } + + /// The notice that every board may have changed. + pub fn all() -> Self { + Self { board: None } + } + + /// The change key a GraphQL engine publishes for this notice. + pub fn change_key(&self) -> String { + match &self.board { + Some(board) => crate::leaderboard_change_key(board), + None => ALL_BOARDS_CHANGE_KEY.to_string(), + } + } + + /// The bus message of this notice (a fan-out event with a fresh id). + pub fn to_message(&self) -> Message { + let payload = serde_json::to_vec(self).expect("a board name serializes"); + Message::new(LEADERBOARD_CHANGED_EVENT, MessageKind::Event, payload) + .with_id(uuid::Uuid::now_v7().to_string()) + } + + /// Decode a delivered notice. A malformed one is a permanent failure. + pub fn from_message(message: &Message) -> Result { + let malformed = |error: String| { + TransportError::permanent(format!("malformed {LEADERBOARD_CHANGED_EVENT}: {error}")) + }; + let notice: Self = serde_json::from_slice(&message.payload) + .map_err(|error| malformed(error.to_string()))?; + if let Some(board) = ¬ice.board { + Board::high_first(board.clone()).map_err(|error| malformed(error.to_string()))?; + } + Ok(notice) + } +} + +const RETRY_FIRST: Duration = Duration::from_millis(100); +const RETRY_MAX: Duration = Duration::from_secs(5); + +/// Boards waiting to be announced, at most `capacity` distinct ones. +#[derive(Debug)] +struct Pending { + boards: BTreeSet, + /// More boards changed than fit: announce every board once instead. + all: bool, + capacity: usize, +} + +impl Pending { + fn add(&mut self, board: &str) { + if self.all || self.boards.contains(board) { + return; + } + if self.boards.len() < self.capacity { + self.boards.insert(board.to_string()); + } else { + self.boards.clear(); + self.all = true; + } + } + + fn take(&mut self) -> Vec { + if std::mem::take(&mut self.all) { + self.boards.clear(); + return vec![LeaderboardChanged::all()]; + } + std::mem::take(&mut self.boards) + .into_iter() + .map(|board| LeaderboardChanged { board: Some(board) }) + .collect() + } +} + +/// Publishes a [`LeaderboardChanged`] notice on the bus for every board a +/// projector reports (its [`listener`](Self::listener)). +/// +/// The listener never blocks the projector and memory stays bounded: changes +/// wait in a set of at most `capacity` distinct boards, so repeated changes +/// to a board coalesce into one notice. **Overflow:** a change to one more +/// board than fits clears the set and queues a single every-board notice +/// ([`LeaderboardChanged::all`]); subscribers resync every `@live` board +/// (hash-gated) instead of the publisher growing without bound. A publish +/// that fails retryably is retried with backoff (100 ms up to 5 s) while new +/// changes keep coalescing; a permanently refused notice is dropped and +/// logged. +#[derive(Clone, Debug)] +pub struct LeaderboardChangePublisher { + pending: Arc>, + /// Wakes the task; capacity 1, a full channel means it is already awake. + wake: mpsc::Sender<()>, +} + +impl LeaderboardChangePublisher { + /// Start publishing through `publisher` on the current Tokio runtime, + /// holding at most `capacity` (>= 1) distinct pending boards. The task + /// ends when every clone of this handle (and of its listeners) is + /// dropped and the pending notices are published. + pub fn spawn