diff --git a/.eslintrc.json b/.eslintrc.json index f6e644a5a..7207011a8 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -12,12 +12,14 @@ "CACHE_INVALIDATE_MS": "readonly", "CLIENT_CONFIG": "readonly", "CLIENT_TTL": "readonly", + "CSApi": "readonly", "CSAuth": "readonly", "ChannelColorPicker": "readonly", "ChannelColors": "readonly", "ChannelDecrypt": "readonly", "ChannelQR": "readonly", "Chart": "readonly", + "CSBeta": "readonly", "DIST_THRESHOLDS": "readonly", "DragManager": "readonly", "EXTERNAL_URLS": "readonly", @@ -298,6 +300,59 @@ "argsIgnorePattern": "^_", "varsIgnorePattern": "^_" } + ], + "no-restricted-syntax": [ + "error", + { + "selector": "CallExpression[callee.name='fetch']", + "message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md." + }, + { + "selector": "CallExpression[callee.property.name='fetch'][callee.object.name=/^(window|self|globalThis)$/]", + "message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md." + }, + { + "selector": "NewExpression[callee.name=/^(XMLHttpRequest|EventSource)$/]", + "message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md." + }, + { + "selector": "CallExpression[callee.property.name='sendBeacon']", + "message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md." + }, + { + "selector": "NewExpression[callee.name='WebSocket']:not([arguments.0.callee.property.name='wsUrl'])", + "message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md." + }, + { + "selector": "Literal[value=/(href|src|action)=[\"']\\/api(\\/|$)/]", + "message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md." + }, + { + "selector": "TemplateElement[value.raw=/(href|src|action)=[\"']\\/api(\\/|$)/]", + "message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md." + }, + { + "selector": "AssignmentExpression:matches([left.property.name=/^(href|src|action|location)$/], [left.name='location']):matches([right.value=/^\\/api(\\/|$)/], [right.left.value=/^\\/api(\\/|$)/], [right.left.left.value=/^\\/api(\\/|$)/], [right.quasis.0.value.raw=/^\\/api(\\/|$)/])", + "message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md." + }, + { + "selector": "CallExpression:matches([callee.name='open'], [callee.property.name='open'], [callee.object.name='location'][callee.property.name=/^(assign|replace)$/], [callee.object.property.name='location'][callee.property.name=/^(assign|replace)$/]):matches([arguments.0.value=/^\\/api(\\/|$)/], [arguments.0.left.value=/^\\/api(\\/|$)/], [arguments.0.left.left.value=/^\\/api(\\/|$)/], [arguments.0.quasis.0.value.raw=/^\\/api(\\/|$)/])", + "message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md." + }, + { + "selector": "CallExpression[callee.property.name='setAttribute'][arguments.0.value=/^(href|src|action|formaction)$/]:matches([arguments.1.value=/^\\/api(\\/|$)/], [arguments.1.left.value=/^\\/api(\\/|$)/], [arguments.1.left.left.value=/^\\/api(\\/|$)/], [arguments.1.quasis.0.value.raw=/^\\/api(\\/|$)/])", + "message": "Every request to the CoreScope server goes through CSApi (public/api-base.js) so the UI also works from a static host or CDN: CSApi.fetch, CSApi.postJSON, CSApi.url, CSApi.wsUrl, or api() and CSAuth.request, which use it. See \"API calls\" in AGENTS.md." + } ] - } -} \ No newline at end of file + }, + "overrides": [ + { + "files": [ + "public/api-base.js" + ], + "rules": { + "no-restricted-syntax": "off" + } + } + ] +} diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 350c28648..1f8c5d2cf 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -42,6 +42,7 @@ env: # push waits for all of them: # changes ─┬─ go-test ─────────────────────────┐ # ├─ race-test (ingestor changes only) ─┤ +# ├─ server-race-shard ×4 ── server-race (gate) ┤ # ├─ e2e-shard ×3 ── e2e-test (gate) ───┼─ build-and-publish → deploy, publish # └─ image-check (two-arch build) ──────┘ # PRs stop after build-and-publish (no GHCR push). Master continues to deploy + badges. @@ -112,8 +113,8 @@ jobs: # introduce a data race here, and paying for the check on every PR is what # gets a check switched off again. # - # The server has -race in its own step already; this closes the same gap for - # the ingestor, which carries an atomic.Pointer snapshot (the region key + # The server runs -race in the server-race-shard jobs; this closes the same + # gap for the ingestor, which carries an atomic.Pointer snapshot (the region key # set) whose safety is an argument until something checks it. race-test: name: "🏁 Race detector (ingestor)" @@ -140,6 +141,70 @@ jobs: cd cmd/ingestor go test -timeout 30m -race ./... + # ─────────────────────────────────────────────────────────────── + # 1b. Race detector (server) — four shards and a gate + # ─────────────────────────────────────────────────────────────── + # The server package has over 2,000 tests and none call t.Parallel(), so + # under -race on one runner they took about 18 minutes, the longest path of + # the pipeline. Each shard builds the race test binary once, lists the + # tests, and runs every fourth one. -race gates PR #1208's atomic.Pointer + # migration: the race detector is what makes path_inspect_atomic_race_test.go + # actually assert. Every test still runs under -race, in exactly one shard. + server-race-shard: + name: "🏁 Race detector (server) shard ${{ matrix.shard }}/4" + runs-on: ubuntu-latest + needs: [changes] + if: needs.changes.outputs.code == 'true' && !(startsWith(github.ref, 'refs/tags/v') && inputs.images_published) + strategy: + fail-fast: false + matrix: + shard: [1, 2, 3, 4] + env: + SHARD: ${{ matrix.shard }} + RACE_SHARDS: 4 + steps: + - name: Checkout code + uses: actions/checkout@v5 + + - name: Set up Go 1.27 + uses: actions/setup-go@v6 + with: + go-version: '1.27' + cache-dependency-path: "**/go.sum" + + - name: go test -race (one shard) + run: | + set -euo pipefail + cd cmd/server + bin="$RUNNER_TEMP/server.race.test" + go test -race -c -o "$bin" . + # Top-level tests, examples and fuzz seeds: everything `go test` runs + # by default. Benchmarks are not run by `go test` either. + "$bin" -test.list '.*' | grep -E '^(Test|Example|Fuzz)' > "$RUNNER_TEMP/all-tests" + awk -v n="$RACE_SHARDS" -v k="$SHARD" 'NR % n == k % n' "$RUNNER_TEMP/all-tests" > "$RUNNER_TEMP/shard-tests" + echo "shard $SHARD/$RACE_SHARDS: $(wc -l < "$RUNNER_TEMP/shard-tests") of $(wc -l < "$RUNNER_TEMP/all-tests") tests" + [ -s "$RUNNER_TEMP/shard-tests" ] || { echo "::error::shard $SHARD has no tests"; exit 1; } + "$bin" -test.count=1 -test.timeout 20m -test.paniconexit0 -test.run "^($(paste -sd'|' "$RUNNER_TEMP/shard-tests"))\$" + + # The gate also runs on a tag whose images were already published, where + # the shards skip because that :edge commit passed them on master. It then + # passes, so release-artifacts can require it on every tag run. + server-race: + name: "🏁 Race detector (server)" + needs: [server-race-shard, changes] + runs-on: ubuntu-latest + if: ${{ !cancelled() && needs.changes.outputs.code == 'true' }} + steps: + - name: Require every shard to have passed + run: | + result="${{ needs['server-race-shard'].result }}" + published="${{ startsWith(github.ref, 'refs/tags/v') && inputs.images_published }}" + echo "server-race-shard: $result (tag with published images: $published)" + if [ "$result" = success ]; then exit 0; fi + if [ "$result" = skipped ] && [ "$published" = true ]; then exit 0; fi + echo "::error::server race shards did not all pass (result: $result)" + exit 1 + # ─────────────────────────────────────────────────────────────── # 1. Go Build & Test # ─────────────────────────────────────────────────────────────── @@ -191,9 +256,10 @@ jobs: set -e -o pipefail cd cmd/server go build . - # -race gates PR #1208's atomic.Pointer migration: the race-detector - # is what makes path_inspect_atomic_race_test.go actually assert. - go test -timeout 20m -race -coverprofile=server-coverage.out ./... 2>&1 | tee server-test.log + # No -race here: the race detector runs the same tests in the + # server-race-shard jobs, side by side. On one runner -race plus + # coverage took about 18 of the job's 24 minutes. + go test -timeout 20m -coverprofile=server-coverage.out ./... 2>&1 | tee server-test.log # The e2etest build (fake mailer + /__e2e/last-mail) has its own tests. go test -tags e2etest -count=1 -run 'E2E' . echo "--- Go Server Coverage ---" @@ -553,6 +619,25 @@ jobs: sleep 1 done + - name: Start split frontend (static build + API-only server) + # The anonymous static build on :8788 against a stock server on :13591 + # that lists that origin in CORS_ALLOWED_ORIGINS, the way a static + # frontend (Cloudflare Pages) calls the containers. -public on a missing + # directory is API-only mode, so nothing is served same-origin. + if: matrix.shard == 1 + run: | + CHANNEL=dev COMMIT=e2e API_BASE=http://localhost:13591 AUTH=false CLASSIC_URL=http://localhost:13591 bash scripts/static/build.sh + fuser -k 13591/tcp 8788/tcp 2>/dev/null || true + CORS_ALLOWED_ORIGINS=http://localhost:8788 ./corescope-server -port 13591 -db test-fixtures/e2e-fixture.db -public /nonexistent & + echo $! > .server-split.pid + node scripts/dev-static.mjs --root dist/web --port 8788 & + echo $! > .static-split.pid + for i in $(seq 1 30); do + if curl -sf http://localhost:13591/api/healthz > /dev/null 2>&1 && curl -sf -o /dev/null http://localhost:8788/; then echo "split frontend ready after ${i}s"; break; fi + if [ "$i" -eq 30 ]; then echo "split frontend failed to start within 30s"; exit 1; fi + sleep 1 + done + - name: Run Playwright E2E tests (fail-fast) env: # On master pushes every suite records the frontend coverage of the @@ -587,6 +672,8 @@ jobs: # Allowlist: tests/a11y-allowlist.yaml (0 entries — hard pass policy). # Per-viewport summary printed at the end; any net>0 fails the build. suite 1 test-a11y-axe-1668.js BASE_URL=$B AXE_SCREENSHOT_DIR=/tmp/axe-1668 + # The static build on another origin than the API (scripts/static/build.sh). + suite 1 test-split-anonymous-e2e.js SPLIT_URL=http://localhost:8788 API_URL=http://localhost:13591 suite 2 test-filter-ux-e2e.js BASE_URL=$B suite 2 test-radio-setting-1869-e2e.js BASE_URL=$B suite 2 test-observer-neighbors-2270-e2e.js BASE_URL=$B @@ -602,7 +689,7 @@ jobs: suite 2 test-issue-748-node-analytics-coverage-e2e.js BASE_URL=$B suite 2 test-issue-2218-node-analytics-stale-e2e.js BASE_URL=$B suite 2 test-issue-661-airtime-e2e.js BASE_URL=$B - suite 2 test-health-status-e2e.js BASE_URL=$B + suite 1 test-health-status-e2e.js BASE_URL=$B suite 2 test-issue-1268-rf-params-e2e.js BASE_URL=$B suite 2 test-issue-1758-ng-filter-rerenders-e2e.js CHROMIUM_REQUIRE=1 BASE_URL=$B suite 2 test-nav-fluid-1055-e2e.js CHROMIUM_REQUIRE=1 BASE_URL=$B @@ -632,7 +719,7 @@ jobs: suite 3 test-issue-1150-404-state-e2e.js BASE_URL=$B suite 2 test-issue-1146-path-link-contrast-e2e.js BASE_URL=$B suite 1 test-issue-1705-subpath-contrast-e2e.js CHROMIUM_REQUIRE=1 - suite 2 test-issue-1147-section-order-e2e.js BASE_URL=$B + suite 1 test-issue-1147-section-order-e2e.js BASE_URL=$B suite 3 test-issue-1151-orphan-separators-e2e.js BASE_URL=$B suite 3 test-issue-1486-collapse-reopens-detail-e2e.js BASE_URL=$B suite 3 test-map-deeplink-path-params-e2e.js BASE_URL=$B @@ -663,7 +750,7 @@ jobs: suite 3 test-issue-1236-map-mobile-e2e.js BASE_URL=$B suite 3 test-issue-1329-map-controls-accordion-e2e.js BASE_URL=$B suite 1 test-issue-1273-qr-overlay-height-e2e.js BASE_URL=$B - suite 3 test-issue-1281-location-row-e2e.js BASE_URL=$B + suite 1 test-issue-1281-location-row-e2e.js BASE_URL=$B suite 1 test-issue-1279-legend-p2-e2e.js BASE_URL=$B suite 2 test-issue-1799-label-vocab-e2e.js BASE_URL=$B suite 2 test-home-coverage-e2e.js CHROMIUM_REQUIRE=1 BASE_URL=$B @@ -693,7 +780,7 @@ jobs: suite 2 test-issue-1630-reach-mobile-e2e.js CHROMIUM_REQUIRE=1 BASE_URL=$B suite 1 test-node-reach-coverage-e2e.js CHROMIUM_REQUIRE=1 BASE_URL=$B suite 3 test-issue-1640-compare-discovery-e2e.js CHROMIUM_REQUIRE=1 BASE_URL=$B - suite 3 test-observer-detail-ownership-e2e.js BASE_URL=$B + suite 1 test-observer-detail-ownership-e2e.js BASE_URL=$B suite 2 test-neighbor-map-btn-clip-e2e.js CHROMIUM_REQUIRE=1 suite 3 test-rx-coverage-viewport-e2e.js BASE_URL=$B suite 1 test-rx-coverage-noise-e2e.js BASE_URL=$B @@ -719,6 +806,8 @@ jobs: suite 3 test-path-inspector-e2e.js CHROMIUM_REQUIRE=1 BASE_URL=$B suite 3 test-pr-1490-live-map-gpu-animations-e2e.js CHROMIUM_REQUIRE=1 BASE_URL=$B suite 1 test-region-quick-picks.js + # The lint rule that keeps network calls on CSApi (needs eslint). + suite 1 test-lint-network-calls.js suite 3 test-table-sort.js suite 1 test-touch-targets.js CHROMIUM_REQUIRE=1 BASE_URL=$B suite 3 test-live-dedup.js BASE_URL=$B @@ -784,6 +873,9 @@ jobs: kill $(cat .server-um.pid) 2>/dev/null || true rm -f .server-um.pid fi + for f in .server-split.pid .static-split.pid; do + if [ -f "$f" ]; then kill $(cat "$f") 2>/dev/null || true; rm -f "$f"; fi + done - name: Upload shard results if: success() @@ -944,9 +1036,34 @@ jobs: - name: Validate staging compose file run: docker compose -f "$STAGING_COMPOSE_FILE" -p corescope-staging config --quiet + # Split containers: operators build the web image from their checkout and + # nothing publishes it, so without this a broken base image, package or + # Caddyfile would reach an operator first. + - name: Validate split compose file + run: CORESCOPE_IMAGE=corescope:check docker compose -f docker-compose.split.yml config --quiet + - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 + - name: Build and smoke the web image (Dockerfile.web) + env: + GIT_COMMIT: ${{ steps.meta.outputs.git_commit }} + run: | + set -euo pipefail + docker buildx build . -f Dockerfile.web --load -t corescope-web:check --build-arg GIT_COMMIT="$GIT_COMMIT" + # BACKEND is a closed port: /api must reach it (502), not the file server (404). + docker run -d --name web-check -p 8080:80 -e BACKEND=127.0.0.1:9 corescope-web:check + trap 'docker logs web-check 2>&1 | tail -20; docker rm -f web-check >/dev/null' EXIT + for i in $(seq 1 30); do curl -fs -o /dev/null http://localhost:8080/ && break; sleep 1; done + page=$(curl -fsS -D headers.txt http://localhost:8080/) + echo "$page" | grep -q "app.js?v=$GIT_COMMIT" || { echo "::error::index.html is not busted with the commit"; exit 1; } + if echo "$page" | grep -q __BUST__; then echo "::error::index.html still has __BUST__"; exit 1; fi + grep -qi '^cache-control: no-cache' headers.txt || { echo "::error::index.html may be cached"; exit 1; } + curl -fsS http://localhost:8080/deployment.js | grep -q "apiBase: ''" || { echo "::error::deployment.js is not same-origin"; exit 1; } + code=$(curl -s -o /dev/null -w '%{http_code}' http://localhost:8080/api/healthz) + [ "$code" = 502 ] || { echo "::error::/api/healthz answered $code, not 502 from the closed BACKEND"; exit 1; } + echo "web image serves the packaged UI and forwards /api ✅" + - name: Set up QEMU (arm64 runtime stage + arm64 smoke) uses: docker/setup-qemu-action@v3 @@ -1013,7 +1130,7 @@ jobs: # Go file changed, so for it skipped is accepted; a master push always runs it. build-and-publish: name: "🏗️ Build & Publish Docker Image" - needs: [go-test, race-test, e2e-test, image-check, changes] + needs: [go-test, race-test, server-race, e2e-test, image-check, changes] runs-on: ubuntu-latest if: ${{ !cancelled() && needs.changes.outputs.code == 'true' && !(startsWith(github.ref, 'refs/tags/v') && inputs.images_published) }} steps: @@ -1029,6 +1146,7 @@ jobs: } require go-test "${{ needs['go-test'].result }}" "success" require race-test "${{ needs['race-test'].result }}" "success skipped" + require server-race "${{ needs['server-race'].result }}" "success" require e2e-test "${{ needs['e2e-test'].result }}" "success" require image-check "${{ needs['image-check'].result }}" "success" exit $fail @@ -1088,7 +1206,7 @@ jobs: # ─────────────────────────────────────────────────────────────── release-artifacts: name: "📦 Release Artifacts" - needs: [go-test, changes] + needs: [go-test, server-race, changes] runs-on: ubuntu-latest permissions: contents: write @@ -1116,18 +1234,21 @@ jobs: - name: Build corescope-decrypt (static, linux/amd64) run: | cd cmd/decrypt - CGO_ENABLED=1 GOOS=linux GOARCH=amd64 CC="zig cc -target x86_64-linux-musl" go build -trimpath -tags netgo,osusergo,sqlite_omit_load_extension -ldflags="-s -w -extldflags '-static -Wl,-s' -X main.version=${{ github.ref_name }}" -o ../../corescope-decrypt-linux-amd64 . + CGO_ENABLED=1 GOOS=linux GOARCH=amd64 CC="zig cc -target x86_64-linux-musl" go build -trimpath -tags netgo,osusergo,sqlite_omit_load_extension -ldflags="-s -w -extldflags '-static -Wl,-s -Wl,-z,stack-size=8388608' -X main.version=${{ github.ref_name }}" -o ../../corescope-decrypt-linux-amd64 . - name: Build corescope-decrypt (static, linux/arm64) run: | cd cmd/decrypt - CGO_ENABLED=1 GOOS=linux GOARCH=arm64 CC="zig cc -target aarch64-linux-musl" go build -trimpath -tags netgo,osusergo,sqlite_omit_load_extension -ldflags="-s -w -extldflags '-static -Wl,-s' -X main.version=${{ github.ref_name }}" -o ../../corescope-decrypt-linux-arm64 . + CGO_ENABLED=1 GOOS=linux GOARCH=arm64 CC="zig cc -target aarch64-linux-musl" go build -trimpath -tags netgo,osusergo,sqlite_omit_load_extension -ldflags="-s -w -extldflags '-static -Wl,-s -Wl,-z,stack-size=8388608' -X main.version=${{ github.ref_name }}" -o ../../corescope-decrypt-linux-arm64 . - name: Verify release binaries are static and runnable run: | set -e for f in corescope-decrypt-linux-amd64 corescope-decrypt-linux-arm64; do file "$f" | grep -q 'statically linked' || { echo "::error::$f is not statically linked"; exit 1; } + # musl sizes thread stacks from PT_GNU_STACK; the build's + # -Wl,-z,stack-size flag must have reached the artifact. + readelf -lW "$f" | grep -Eq 'GNU_STACK .* 0x0*800000 +RW' || { echo "::error::$f: PT_GNU_STACK is not 8 MiB, musl thread stacks are not pinned"; exit 1; } done # amd64 runs natively on the runner; arm64 is only checked structurally # here (the container image job exercises arm64 under QEMU). diff --git a/AGENTS.md b/AGENTS.md index fd35106a0..0e3f1726f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,8 @@ Guide for AI agents working on this codebase. Read this before writing any code. ## Architecture -Go backend + static frontend. No build step. No framework. No bundler. +Go backend + static frontend. No build step: `public/` is what the browser runs. No framework. No bundler. +`scripts/static/build.sh` is packaging, not a build: it copies `public/` for a static host or the web container, writes `deployment.js` and fills in `__BUST__`, and never transforms code. **⚠️ The Node.js server (server.js) is DEPRECATED and has been removed. All backend code is in Go.** **⚠️ DO NOT create or modify any Node.js server files. All backend changes go in `cmd/server/` or `cmd/ingestor/`.** @@ -18,7 +19,9 @@ cmd/server/ — Go API server (REST + WebSocket broadcast + static file s decoder.go — MeshCore packet decoder cmd/ingestor/ — Go MQTT ingestor (separate binary, writes to shared SQLite DB) public/ — Frontend (vanilla JS, one file per page) — ACTIVE, NOT DEPRECATED - app.js — SPA router, shared globals, theme loading + app.js — SPA router, shared globals, theme loading, api() (cached GETs) + deployment.js — where the API is (rewritten by scripts/static/build.sh for a static host) + api-base.js — CSApi: the ONLY code that builds API URLs or opens connections (see "API calls") roles.js — ROLE_COLORS, TYPE_COLORS, health thresholds, shared helpers nodes.js — Nodes list + side pane + full detail page map.js — Leaflet map with markers, legend, filters @@ -33,9 +36,10 @@ public/ — Frontend (vanilla JS, one file per page) — ACTIVE, NOT style.css — Main styles, CSS variables for theming live.css — Live page styles home.css — Home page styles - index.html — SPA shell, script/style tags with __BUST__ placeholder (auto-replaced at server startup) + index.html — SPA shell, script/style tags with __BUST__ placeholder (filled in automatically; see rule 3) test-fixtures/ — Real data SQLite fixture from staging (used for E2E tests) -scripts/ — Tooling (coverage collector, fixture capture, frontend instrumentation) +scripts/ — Tooling (coverage collector, fixture capture, frontend instrumentation; + static/build.sh packages the UI for a static host or the web container) ``` ### Data Flow @@ -105,7 +109,7 @@ Every change must consider performance impact BEFORE implementation. This codeba No proof = no merge. ### 1. No commit without tests -Every change that touches logic MUST have tests. For Go backend: `cd cmd/server && go test ./...` and `cd cmd/ingestor && go test ./...`, or `make test` for all 14 modules. For frontend: `node tests/unit/test-packet-filter.js && node tests/unit/test-aging.js && node tests/unit/test-frontend-helpers.js`. If you add new logic, add tests. No exceptions. +Every change that touches logic MUST have tests. For Go backend: `cd cmd/server && go test ./...` and `cd cmd/ingestor && go test ./...`, or `make test` for all 14 modules. For frontend: `node tests/unit/test-packet-filter.js && node tests/unit/test-aging.js && node tests/unit/test-frontend-helpers.js`, and `npx eslint public/*.js` (CI fails on any error). If you add new logic, add tests. No exceptions. The SQLite driver (`github.com/mattn/go-sqlite3`) is cgo. **`CGO_ENABLED=0` still *builds*** — that is the trap. It links a stub, and the binary dies on the first query with `go-sqlite3 requires cgo to work. This is a stub`, so a green build proves nothing. A plain `GOOS=linux go build` likewise cannot cross-compile it. Use `make build` / `make crossbuild` — the latter needs [`zig`](https://ziglang.org/download/) as the cross C compiler and produces static musl binaries. Never re-add `CGO_ENABLED=0`. @@ -113,7 +117,7 @@ The SQLite driver (`github.com/mattn/go-sqlite3`) is cgo. **`CGO_ENABLED=0` stil After pushing, verify the change works in an actual browser. Use `browser profile=openclaw` against the running instance. Take a screenshot if the change is visual. If you can't validate it, say so — don't claim it works. ### 3. Cache busters are automatic — do NOT manually edit them -Cache busters are injected automatically by the Go server at startup. The `__BUST__` placeholder in `index.html` is replaced with a Unix timestamp when the server reads the file. No manual bumping needed — every server restart picks up new asset versions. Do NOT replace `__BUST__` with hardcoded timestamps. +Cache busters are injected automatically. The Go server replaces the `__BUST__` placeholder in every top-level page (`index.html`, `area-map.html`, `geofilter-*.html`) with a Unix timestamp at startup, so every server restart picks up new asset versions. `scripts/static/build.sh` replaces it with the commit when it packages the UI. No manual bumping needed. Do NOT replace `__BUST__` with hardcoded timestamps, and give every local script or stylesheet a new page loads `?v=__BUST__`. ### 4. Verify API response shape before building UI Before writing client code that consumes an API endpoint, check what the endpoint ACTUALLY returns. Use `curl` or check the server code. Don't assume fields exist — grouped packets (`groupByHash=true`) have different fields than raw packets. This has caused multiple breakages. @@ -196,6 +200,22 @@ If you need to know how something works — a flag, a field, a timing, a behavio ## Frontend Conventions +### API calls (api-base.js) +The UI runs embedded in the server, in the web container, and from a static host or CDN on another origin (see "Deployment modes" in `docs/deployment.md`). `public/deployment.js` says where the API is, and `public/api-base.js` (`window.CSApi`) is the only code that turns a path into a URL or opens a connection. Everything else goes through it: + +| Need | Use | +|------|-----| +| GET JSON, cached | `api('/nodes?…')` (app.js) | +| Any other request | `CSApi.fetch('/api/…', opts)` | +| JSON POST | `CSApi.postJSON('/api/…', body)`: sends `text/plain`, so a cross-origin POST has no preflight (the server decodes JSON whatever the Content-Type; `cmd/server/simple_post_test.go`) | +| Logged-in request | `CSAuth.request(method, '/api/…', body)` | +| Link, download, `src` | `CSApi.url('/api/…')` | +| WebSocket | `new WebSocket(CSApi.wsUrl('/ws'))` | + +- **Never** call `fetch`, `XMLHttpRequest`, `EventSource`, `navigator.sendBeacon` or `new WebSocket(url)` directly, or put a bare `/api/…` path in an `href`, `src` or `action` (assigned, set with `setAttribute` or written into markup) or in `window.open`, `location.assign`, `location.replace` or `location =`. It works embedded and breaks on a static host. The `no-restricted-syntax` rule in `.eslintrc.json` rejects all of these in `public/*.js` (only `api-base.js` is exempt) and CI fails on it: run `npx eslint public/*.js` before pushing. That command never sees the inline scripts and markup of `public/*.html`; `tests/e2e/test-lint-network-calls.js` applies the same rule to them, and pins what the rule reports: extend it when you extend the rule. The rule sees a path at the start of a string, a concatenation or a template; a URL assembled elsewhere and passed in a variable gets past it, so it does not replace review. Do not silence it with `eslint-disable`. The one exception is `area-map.html`, whose Server field can name another server. +- **Logins and writes:** the anonymous static build (`CSApi.anonymous`) sends no cookies. A feature that needs a login or a write shows `CSBeta.classicOnlyHtml('…')` (or links with `CSApi.classicHref(hash)`) instead, as `account.js`, `admin.js` and `perf.js` do. +- **Tests:** a test that runs a frontend file outside the browser must load `deployment.js` and `api-base.js` first, or `CSApi` is undefined and its fetches fail silently inside their `try` blocks. vm sandboxes: `tests/unit/api-base-sandbox.js`. jsdom: `w.eval` both files before the file under test (`tests/e2e/test-region-quick-picks.js`). + ### Theming All colors MUST use CSS variables. Never hardcode `#hex` values outside of `:root` definitions. The customizer controls colors via `THEME_CSS_MAP` in customize.js. If you add a new color, add it as a CSS variable and map it in the customizer. @@ -378,6 +398,7 @@ One logical change per commit. Each commit is deployable. Each commit has its te | Gave up testing locally | 2 | Basic tests work on ARM — only heavy coverage scripts crash | | Copy-pasted functions for "coverage" | 1 | Test the real code, not copies in a helper file | | Subagent timed out mid-work | 4 | Give clear scope, don't try to run slow pipelines locally | +| Frontend file tested without api-base.js | 1 | Load `deployment.js` + `api-base.js` first (see "API calls") | ## File Naming - Tests: `test-{feature}.js` in `tests/unit/` (standalone, listed in `test-all.sh`) or `tests/e2e/` (browser, listed in `scripts/non-unit-tests.json`) — never in repo root @@ -397,5 +418,6 @@ Existing patterns: `#/nodes/{pubkey}?section=node-neighbors`, `#/analytics?tab=c - Don't add framework abstractions (React, Vue, etc.) - Don't hardcode colors — use CSS variables - Don't make per-packet server API calls from the frontend +- Don't call `fetch` / `WebSocket` / XHR directly from the frontend — go through `CSApi` (see "API calls") - Don't push without running tests - Don't start implementing without plan approval diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f503ec2d..5eb94eab0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,20 @@ - Add configurable observer-region reception frequency policy and admin Frequency panel, with per-radio status tracking, bounded freshness, unknown policy and no historical deletion. +## [3.18.0] - 2026-11-17 + +See [docs/release-notes/v3.18.0.md](docs/release-notes/v3.18.0.md) for the full notes. 11 commits since v3.17.0: 5 fix, 3 feat, 1 test, 1 refactor, 1 docs. + +### Highlights +- **`users.db` migrates to schema v9 with user accounts on** (#2415) - a v3.17.x binary refuses it afterwards, so keep the pre-upgrade copy for a rollback. +- **The UI's live feed connects to `/ws` instead of `/`** (#2383) - a reverse proxy that forwards WebSocket upgrades only on `/` must forward `/ws` too. +- **Radio line of sight on packet routes and a repeater planner** (#2391) - SRTM terrain, in memory only. Opt-in (`los`, `planner`). +- **Repeater info and claims** (#2415, #2416, #2417) - height, gain, power, status and notes per repeater, edited by registered users. Needs user accounts. +- **Three ways to deploy the UI** (#2383) - all-in-one as today, a separate web container, or a static host against a server on another origin. +- **Memory after eviction** (#2327) and **map tile overrides on every page** (#2386). + +No manual migration step. + ## [3.17.0] - 2026-11-11 See [docs/release-notes/v3.17.0.md](docs/release-notes/v3.17.0.md) for the full notes. 24 commits since v3.16.0: 11 fix, 5 docs, 4 feat, 2 test, 1 ui, 1 chore. diff --git a/DEPLOY.md b/DEPLOY.md index 040cd0981..444ed5656 100644 --- a/DEPLOY.md +++ b/DEPLOY.md @@ -24,6 +24,13 @@ curl -sL https://raw.githubusercontent.com/Kpa-clawbot/CoreScope/master/docker-c docker compose up -d ``` +### Other deployment modes + +The UI can also run in a container of its own (`docker-compose.split.yml`, with +`CORESCOPE_IMAGE` set to the server image of your checkout's version) or from a +static host or CDN such as Cloudflare Pages. See +[Deployment modes](docs/deployment.md#deployment-modes). + ## Image Tags | Tag | Description | diff --git a/Dockerfile b/Dockerfile index 08857fcc5..8d979c304 100644 --- a/Dockerfile +++ b/Dockerfile @@ -18,6 +18,17 @@ FROM --platform=$BUILDPLATFORM golang:1.27-alpine AS builder ARG APP_VERSION=unknown ARG GIT_COMMIT=unknown +# musl sizes every non-main thread's stack from the ELF PT_GNU_STACK size +# (floor 128 KiB, cap 8 MiB). cgo calls into SQLite run on the calling thread's +# stack, and a deep query (multiSelect recursing ~850 B per UNION ALL term) +# overflows 128 KiB and SIGSEGVs the process. zig's linker already writes a +# 16 MiB PT_GNU_STACK, so these binaries got 8 MiB threads before this flag +# existed; GNU ld writes 0, which is where the crash was seen (a native Alpine +# gcc link). The flag pins the size so it no longer rests on a linker default, +# and the readelf check after the builds fails the image if it is ever lost. +# Reserved address space, not resident memory. Go rejects this flag in +# #cgo LDFLAGS, so it must go in -extldflags. +ARG STACK_LDFLAG="-Wl,-z,stack-size=8388608" ARG BUILD_TIME=unknown # Provided by buildx for multi-arch builds ARG TARGETOS @@ -33,7 +44,8 @@ ENV GO_BUILD_TAGS=netgo,osusergo,sqlite_omit_load_extension \ # TARGETARCH because this stage is pinned to BUILDPLATFORM — it has to work when # someone builds on an arm64 machine too. ARG ZIG_VERSION=0.16.0 -RUN apk add --no-cache curl xz && \ +# binutils: readelf, for the thread-stack check after the builds. +RUN apk add --no-cache curl xz binutils && \ case "$(uname -m)" in \ x86_64) ZA=x86_64; ZSHA=70e49664a74374b48b51e6f3fdfbf437f6395d42509050588bd49abe52ba3d00 ;; \ aarch64) ZA=aarch64; ZSHA=ea4b09bfb22ec6f6c6ceac57ab63efb6b46e17ab08d21f69f3a48b38e1534f17 ;; \ @@ -81,7 +93,7 @@ RUN --mount=type=cache,target=/root/.cache/go-build \ --mount=type=cache,target=/tmp/zig-cache \ GOOS=${TARGETOS} GOARCH=${TARGETARCH} \ go build -trimpath -tags ${GO_BUILD_TAGS} \ - -ldflags "-s -w -extldflags '-static -Wl,-s' -X main.Version=${APP_VERSION} -X main.Commit=${GIT_COMMIT} -X main.BuildTime=${BUILD_TIME}" \ + -ldflags "-s -w -extldflags '-static -Wl,-s ${STACK_LDFLAG}' -X main.Version=${APP_VERSION} -X main.Commit=${GIT_COMMIT} -X main.BuildTime=${BUILD_TIME}" \ -o /corescope-server . # Build ingestor @@ -106,7 +118,7 @@ RUN --mount=type=cache,target=/root/.cache/go-build \ --mount=type=cache,target=/tmp/zig-cache \ GOOS=${TARGETOS} GOARCH=${TARGETARCH} \ go build -trimpath -tags ${GO_BUILD_TAGS} \ - -ldflags "-s -w -extldflags '-static -Wl,-s'" \ + -ldflags "-s -w -extldflags '-static -Wl,-s ${STACK_LDFLAG}'" \ -o /corescope-ingestor . # Build decrypt CLI @@ -123,9 +135,17 @@ RUN --mount=type=cache,target=/root/.cache/go-build \ --mount=type=cache,target=/tmp/zig-cache \ GOOS=${TARGETOS} GOARCH=${TARGETARCH} \ go build -trimpath -tags ${GO_BUILD_TAGS} \ - -ldflags "-s -w -extldflags '-static -Wl,-s' -X main.version=${APP_VERSION}" \ + -ldflags "-s -w -extldflags '-static -Wl,-s ${STACK_LDFLAG}' -X main.version=${APP_VERSION}" \ -o /corescope-decrypt . +# The thread-stack size must be in every binary's PT_GNU_STACK (see +# STACK_LDFLAG). The Go test for it runs on glibc in CI, where it passes with +# or without the flag, so the artifact is checked here. +RUN for f in /corescope-server /corescope-ingestor /corescope-decrypt; do \ + readelf -lW "$f" | grep -Eq 'GNU_STACK .* 0x0*800000 +RW' || \ + { echo "$f: PT_GNU_STACK is not 8 MiB, musl thread stacks are not pinned" >&2; readelf -lW "$f" | grep GNU_STACK >&2; exit 1; }; \ + done + # Runtime image FROM alpine:3.24 diff --git a/Dockerfile.web b/Dockerfile.web new file mode 100644 index 000000000..e22799c95 --- /dev/null +++ b/Dockerfile.web @@ -0,0 +1,38 @@ +# CoreScope web container: the static UI on its own, served by Caddy, which +# forwards /api and /ws to a CoreScope server container. The UI and the API +# then share one origin, so the server needs no CORS settings. Logins work as +# on the classic UI once the server's userManagement.publicBaseUrl is this +# container's public origin. docker-compose.split.yml runs the two together; +# see "Deployment modes" in docs/deployment.md. +# +# Runtime environment: +# BACKEND host:port of the CoreScope server. Default corescope:3000. +# SITE_ADDRESS :80 (default) for plain HTTP, or a domain name for Caddy's +# automatic HTTPS (publish 80 and 443, and keep /data). + +FROM alpine:3.24 AS build +RUN apk add --no-cache bash +WORKDIR /src +COPY public/ public/ +COPY scripts/static/ scripts/static/ +COPY deploy/static/ deploy/static/ +# GIT_COMMIT is the cache buster on every asset (?v=); without one, the build +# time, as the server does at start. CHANNEL beta, next or dev shows a badge. +ARG GIT_COMMIT= +ARG CHANNEL=static +RUN COMMIT="$(printf '%.12s' "${GIT_COMMIT:-$(date +%s)}")" \ + API_BASE=same-origin AUTH=true CHANNEL="$CHANNEL" OUT=/srv \ + bash scripts/static/build.sh && \ + rm /srv/_headers + +FROM alpine:3.24 +RUN apk add --no-cache caddy +COPY --from=build /srv /srv +COPY docker/web/Caddyfile /etc/caddy/Caddyfile +ENV BACKEND=corescope:3000 \ + SITE_ADDRESS=:80 \ + XDG_DATA_HOME=/data \ + XDG_CONFIG_HOME=/config +EXPOSE 80 443 +VOLUME ["/data"] +CMD ["caddy", "run", "--config", "/etc/caddy/Caddyfile", "--adapter", "caddyfile"] diff --git a/Makefile b/Makefile index 345d628f0..dbd9c6bd7 100644 --- a/Makefile +++ b/Makefile @@ -15,6 +15,8 @@ # make crossbuild # linux/amd64 + linux/arm64, static, into dist/ # make test / vet / fmt-check # across all modules # make docker-build # multi-arch image via buildx +# make web API_BASE=… AUTH=… # the UI alone, for a static host, into dist/web +# make dev-split # UI on :8788 calling the API on :3000 cross-origin GO ?= $(shell command -v go) GIT_VERSION ?= $(shell git describe --tags --match "v*" 2>/dev/null || echo unknown) @@ -39,6 +41,24 @@ GO_BUILD_TAGS ?= netgo,osusergo,sqlite_omit_load_extension GO_BUILD_FLAGS ?= -trimpath GO_LDFLAGS_OPTIMS ?= -s -w +# musl sizes every non-main thread's stack from the ELF PT_GNU_STACK size +# (floor 128 KiB, cap 8 MiB). cgo calls into SQLite run on the calling thread's +# stack, and a deep query (multiSelect recursing ~850 B per UNION ALL term) +# overflows 128 KiB and SIGSEGVs the process. +# - Native musl links (`make build` / `make test` on Alpine: gcc + GNU ld) +# write a zero PT_GNU_STACK and get the 128 KiB floor. The flag is the fix. +# - zig links (crossbuild, the Dockerfile, the release job) already write +# 16 MiB, so those binaries had 8 MiB threads without it. There the flag +# pins the size instead of leaving it to a linker default. +# Reserved address space, not resident memory. Go rejects this flag in +# #cgo LDFLAGS, so it must go in -extldflags. Harmless on glibc; GNU ld/lld +# only, so the host build and `make test` apply it on Linux only. +STACK_LDFLAG ?= -Wl,-z,stack-size=8388608 +ifeq ($(GOOS),linux) +HOST_EXTLDFLAGS := -extldflags '$(STACK_LDFLAG)' +HOST_TEST_LDFLAGS := -ldflags=-extldflags=$(STACK_LDFLAG) +endif + CMDS := server ingestor decrypt migrate DIST := dist @@ -59,12 +79,12 @@ DOCKER_IMAGE ?= ghcr.io/kpa-clawbot/corescope DOCKER_TAG ?= $(GIT_VERSION) DOCKER_PLATFORMS ?= linux/amd64,linux/arm64 -.PHONY: all build crossbuild test vet fmt-check tidy clean docker-build docker-push help +.PHONY: all build crossbuild test vet fmt-check tidy clean web dev-split docker-build docker-push help all: build help: - @echo "targets: build crossbuild test vet fmt-check tidy clean docker-build docker-push" + @echo "targets: build crossbuild test vet fmt-check tidy clean web dev-split docker-build docker-push" @echo " build-{$(shell echo $(CMDS) | tr ' ' ',')}" # -- host builds --------------------------------------------------------------- @@ -75,7 +95,7 @@ build-%: @mkdir -p $(DIST) cd cmd/$* && GOOS=$(GOOS) GOARCH=$(GOARCH) $(GO) build \ -tags $(GO_BUILD_TAGS) $(GO_BUILD_FLAGS) \ - -ldflags "$(GO_LDFLAGS_OPTIMS) $(LDFLAGS_$*)" \ + -ldflags "$(GO_LDFLAGS_OPTIMS) $(HOST_EXTLDFLAGS) $(LDFLAGS_$*)" \ -o ../../$(DIST)/corescope-$* . # -- cross builds -------------------------------------------------------------- @@ -92,7 +112,7 @@ crossbuild-$(2)-$(3)-$(4): @command -v zig >/dev/null || { echo "zig not found: needed to cross-compile cgo. See https://ziglang.org/download/"; exit 1; } cd cmd/$(2) && CGO_ENABLED=1 GOOS=$(3) GOARCH=$(4) CC="zig cc -target $(1)" \ $$(GO) build -tags $$(GO_BUILD_TAGS) $$(GO_BUILD_FLAGS) \ - -ldflags '$$(GO_LDFLAGS_OPTIMS) -extldflags "-static -Wl,-s" $$(LDFLAGS_$(2))' \ + -ldflags '$$(GO_LDFLAGS_OPTIMS) -extldflags "-static -Wl,-s $$(STACK_LDFLAG)" $$(LDFLAGS_$(2))' \ -o ../../$$(DIST)/corescope-$(2)-$(3)-$(4) . endef @@ -103,7 +123,7 @@ $(foreach c,$(CMDS),\ # -- checks -------------------------------------------------------------------- test: - bash scripts/allmod.sh test ./... + bash scripts/allmod.sh test $(HOST_TEST_LDFLAGS) ./... vet: bash scripts/allmod.sh vet ./... @@ -119,6 +139,35 @@ tidy: clean: rm -rf $(DIST) +# -- static frontend ------------------------------------------------------------ +# +# web packages public/ into dist/web for a static host or a CDN. It reads +# API_BASE, AUTH, CHANNEL, CLASSIC_URL and COMMIT; see scripts/static/build.sh. +# The Go binaries share dist/, which is why the UI gets a folder of its own. +web: + bash scripts/static/build.sh + +# dev-split runs the UI the way a static host serves it: the anonymous +# build on :8788 calling an API-only server on :3000 cross-origin, with no +# proxy. The server change is the one env var, exactly as in production. +# DEV_SPLIT_DB=path/to.db picks the data (default: the E2E fixture); it runs on a +# migrated copy in dist/, so the original is never touched. +DEV_SPLIT_DB ?= test-fixtures/e2e-fixture.db +DEV_SPLIT_API_PORT ?= 3000 +DEV_SPLIT_STATIC_PORT ?= 8788 + +dev-split: build-server build-migrate + cp $(DEV_SPLIT_DB) $(DIST)/dev-split.db + $(DIST)/corescope-migrate -db $(DIST)/dev-split.db + CHANNEL=dev COMMIT=dev AUTH=false \ + API_BASE=http://localhost:$(DEV_SPLIT_API_PORT) CLASSIC_URL=http://localhost:$(DEV_SPLIT_API_PORT) \ + bash scripts/static/build.sh + @echo "UI: http://localhost:$(DEV_SPLIT_STATIC_PORT) API: http://localhost:$(DEV_SPLIT_API_PORT) (Ctrl-C stops both)" + @trap 'kill 0' INT TERM EXIT; \ + CORS_ALLOWED_ORIGINS=http://localhost:$(DEV_SPLIT_STATIC_PORT) \ + $(DIST)/corescope-server -port $(DEV_SPLIT_API_PORT) -db $(DIST)/dev-split.db -public /nonexistent & \ + node scripts/dev-static.mjs --root $(DIST)/web --port $(DEV_SPLIT_STATIC_PORT) + # -- docker -------------------------------------------------------------------- docker-build: diff --git a/cmd/ingestor/db.go b/cmd/ingestor/db.go index 6671d946f..228e29391 100644 --- a/cmd/ingestor/db.go +++ b/cmd/ingestor/db.go @@ -245,6 +245,22 @@ func OpenStoreWithIntervalAndSynchronous(dbPath string, sampleIntervalSec int, s log.Printf("[migration/async] scheduling tx_last_seen_backfill_v1 failed: %v", err) } + // #1856: rewrite content hashes written before #787 (full header byte) + // to the payload-type-bits formula, merging rows that then collide. Only + // rows present at boot can be stale — this process writes current hashes + // — so the range is fixed here, before ingest starts. + // PREFLIGHT: async=true reason="id-cursor scan of transmissions (86k+ rows in prod) read in 5000-row batches outside the writer lock, stale rows committed 250 per transaction; only pre-#787 rows are written" + var hashMigrateMaxID int64 + if err := db.QueryRow(`SELECT COALESCE(MAX(id), 0) FROM transmissions`).Scan(&hashMigrateMaxID); err != nil { + log.Printf("[migration/async] %s not scheduled (retried next boot): read max id: %v", contentHashMigrationName, err) + } else if err := s.RunAsyncMigration(context.Background(), contentHashMigrationName, + func(ctx context.Context, _ *sql.DB) error { + _, _, err := s.migrateContentHashes(ctx, contentHashMigrationBatch, contentHashMigrationWriteBatch, hashMigrateMaxID) + return err + }); err != nil { + log.Printf("[migration/async] scheduling %s failed: %v", contentHashMigrationName, err) + } + // A missing/failed completion lookup leaves preservation enabled. This // lifecycle state is restored on restart, independently of main's startup. var evidenceStatus string diff --git a/cmd/ingestor/hash_migrate.go b/cmd/ingestor/hash_migrate.go new file mode 100644 index 000000000..27121f74e --- /dev/null +++ b/cmd/ingestor/hash_migrate.go @@ -0,0 +1,261 @@ +package main + +import ( + "context" + "database/sql" + "errors" + "fmt" + "log" + "math" + "runtime" +) + +// Content-hash migration (#786/#787, moved here from cmd/server in #1856). +// +// Hashes written before #787 covered the full header byte, so one logical +// packet heard with different route or version bits got several hashes and +// several transmissions rows. ComputeContentHash now covers only the payload +// type bits. This pass rewrites every stale hash and folds the rows the old +// formula split apart back into one. +// +// It lives in the ingestor because it writes: the server holds a mode=ro +// handle (#1283) and its copy of this pass could never commit. The server +// reads the _async_migrations row to answer /api/stats.hashMigrationComplete. +// +// A server that loaded these rows before the pass keeps them as they were +// until it restarts: the old hashes, the merged duplicates, and survivors +// without the observations they gained. That is deliberate. tx_rewrite_feed +// cannot carry a merge (its rows cascade away with the deleted duplicate, and +// the server's tail refreshes decoded_json and scope_name only), and removing +// a transmission from every in-memory index is hot-path code this one-time +// pass over pre-#787 rows does not justify. The summary line tells the +// operator to restart instead. + +// contentHashMigrationName is the _async_migrations row the server reads. +const contentHashMigrationName = "content_hash_payload_bits_v1" + +// contentHashMigrationBatch bounds how many transmissions one read scans. The +// read runs outside the writer lock, so it can be large. +const contentHashMigrationBatch = 5000 + +// contentHashMigrationWriteBatch bounds how many stale rows one transaction +// rewrites or merges before it commits and releases the writer lock. On an +// affected install every pre-#787 row is stale, so a whole scan batch in one +// transaction held the lock for seconds (a 5000-row batch with half of it +// merging measured ~4 s of ingest wait in review). A merge moves and deletes +// an unbounded number of observations, so hold time scales like a retention +// prune batch, and this uses the same bound (pruneBatchTransmissions). +const contentHashMigrationWriteBatch = pruneBatchTransmissions + +// The deletes for a merged duplicate, with the same child list retention uses. +var hashMergeDeleteRadios, hashMergeDeleteObservations, hashMergeDeleteTransmission = transmissionDeleteStatements("?") + +// hashMergeMoveObservations moves the duplicate's observations onto the +// survivor, except those the survivor already has: idx_observations_dedup is +// (transmission_id, observer_idx, path_json with NULL read as empty), and +// moving one of those would violate it. Plain = on observer_idx is deliberate: NULLs never +// collide under the unique index, and NULL = NULL is not true here either, so +// observations without an observer always move. Args: survivor, duplicate, +// survivor. +const hashMergeMoveObservations = `UPDATE observations SET transmission_id = ? + WHERE transmission_id = ? AND NOT EXISTS ( + SELECT 1 FROM observations s + WHERE s.transmission_id = ? + AND s.observer_idx = observations.observer_idx + AND COALESCE(s.path_json, '') = COALESCE(observations.path_json, ''))` + +// hashMergeWidenSpan gives the survivor the earlier first_seen and the later +// last_seen of the pair. Args: dup first_seen x2, dup last_seen x2, survivor. +const hashMergeWidenSpan = `UPDATE transmissions SET + first_seen = CASE WHEN first_seen > ? THEN ? ELSE first_seen END, + last_seen = CASE WHEN last_seen < ? THEN ? ELSE last_seen END + WHERE id = ?` + +// staleContentHash is a transmission whose stored hash is not its content hash. +type staleContentHash struct { + id int64 + newHash string +} + +// MigrateContentHashes rewrites every stale content hash and merges the +// transmissions that collide once rewritten. It returns how many rows were +// rewritten in place and how many were merged into another row. Idempotent: +// once every hash is current it changes nothing and returns (0, 0, nil). +// +// On error, the counts cover the batches already committed. +func (s *Store) MigrateContentHashes(ctx context.Context, batchSize int) (rewritten, merged int, err error) { + return s.migrateContentHashes(ctx, batchSize, contentHashMigrationWriteBatch, math.MaxInt64) +} + +// migrateContentHashes is MigrateContentHashes over ids up to maxID, scanning +// scanBatch rows per read and committing at most writeBatch stale rows per +// transaction. The boot schedule passes the highest id at boot: this process +// writes current hashes, so a row inserted after that is never stale. +func (s *Store) migrateContentHashes(ctx context.Context, scanBatch, writeBatch int, maxID int64) (rewritten, merged int, err error) { + if scanBatch <= 0 || writeBatch <= 0 { + return 0, 0, fmt.Errorf("content-hash migration: batch sizes %d/%d must be positive", scanBatch, writeBatch) + } + var cursor int64 + for { + if err := ctx.Err(); err != nil { + return rewritten, merged, fmt.Errorf("content-hash migration stopped after id %d: %w", cursor, err) + } + stale, last, scanned, err := s.readStaleContentHashes(ctx, cursor, maxID, scanBatch) + if err != nil { + return rewritten, merged, fmt.Errorf("content-hash migration: read after id %d: %w", cursor, err) + } + for len(stale) > 0 { + if err := ctx.Err(); err != nil { + return rewritten, merged, fmt.Errorf("content-hash migration stopped before id %d: %w", stale[0].id, err) + } + chunk := stale[:min(writeBatch, len(stale))] + stale = stale[len(chunk):] + r, m, err := s.rehashChunk(chunk) + if err != nil { + return rewritten, merged, fmt.Errorf("content-hash migration: batch from id %d: %w", chunk[0].id, err) + } + rewritten += r + merged += m + // Let a queued ingest writer take the lock before the next chunk. + runtime.Gosched() + } + if msg := contentHashMigrationProgress(last, maxID, rewritten, merged); scanned > 0 && msg != "" { + log.Print(msg) + } + // A short read proves nothing is left in range. + if scanned < scanBatch { + break + } + cursor = last + } + if msg := contentHashMigrationSummary(rewritten, merged); msg != "" { + log.Print(msg) + } + return rewritten, merged, nil +} + +// rehashChunk rewrites or merges one chunk of stale rows in one transaction. +func (s *Store) rehashChunk(chunk []staleContentHash) (rewritten, merged int, err error) { + err = s.WriterTx("content_hash_migrate", func(tx *sql.Tx) error { + rewritten, merged = 0, 0 + for _, st := range chunk { + wasRewritten, wasMerged, err := rehashTransmission(tx, st) + if err != nil { + return fmt.Errorf("tx %d: %w", st.id, err) + } + if wasRewritten { + rewritten++ + } + if wasMerged { + merged++ + } + } + return nil + }) + if err != nil { + return 0, 0, err + } + return rewritten, merged, nil +} + +// contentHashMigrationProgress is the per-scan-batch log line, so a long pass +// on an affected install shows it is moving. A pass that has changed nothing +// so far stays quiet, which keeps unaffected installs silent. +func contentHashMigrationProgress(lastID, maxID int64, rewritten, merged int) string { + if rewritten == 0 && merged == 0 { + return "" + } + through := fmt.Sprintf("id %d", lastID) + if maxID != math.MaxInt64 { + through = fmt.Sprintf("id %d of %d", lastID, maxID) + } + return fmt.Sprintf("[hash-migrate] progress: scanned through %s, rewrote %d, merged %d so far", through, rewritten, merged) +} + +// contentHashMigrationSummary is the log line for a pass that changed rows, or +// "" for one that changed nothing. It tells the operator to restart servers, +// because nothing else brings a running server's memory up to date (see the +// file comment). +func contentHashMigrationSummary(rewritten, merged int) string { + if rewritten == 0 && merged == 0 { + return "" + } + return fmt.Sprintf("[hash-migrate] rewrote %d content hashes, merged %d duplicate transmissions. "+ + "A server that was already running keeps the old hashes and the merged duplicates in memory: "+ + "restart servers to pick up the change", rewritten, merged) +} + +// readStaleContentHashes scans the next batch of transmissions after cursor, +// outside the writer lock, and returns the ones whose hash is stale, the last +// id scanned and how many rows were scanned. Rows without raw_hex are not +// content-hashed (companion-relayed messages) and are skipped. +func (s *Store) readStaleContentHashes(ctx context.Context, cursor, maxID int64, batchSize int) (stale []staleContentHash, last int64, scanned int, err error) { + rows, err := s.db.QueryContext(ctx, + `SELECT id, hash, raw_hex FROM transmissions WHERE id > ? AND id <= ? ORDER BY id LIMIT ?`, + cursor, maxID, batchSize) + if err != nil { + return nil, 0, 0, err + } + defer rows.Close() + for rows.Next() { + var id int64 + var hash, rawHex string + if err := rows.Scan(&id, &hash, &rawHex); err != nil { + return nil, 0, 0, err + } + scanned++ + last = id + if rawHex == "" { + continue + } + if h := ComputeContentHash(rawHex); h != hash { + stale = append(stale, staleContentHash{id: id, newHash: h}) + } + } + return stale, last, scanned, rows.Err() +} + +// rehashTransmission gives one stale row its content hash, merging it into the +// row that already holds that hash if there is one. The row is re-read inside +// the transaction: retention may have deleted it since the batch was scanned, +// and an earlier row of the same batch may have taken the hash. +func rehashTransmission(tx *sql.Tx, st staleContentHash) (rewritten, merged bool, err error) { + var curHash, firstSeen string + var lastSeen int64 + err = tx.QueryRow(`SELECT hash, first_seen, last_seen FROM transmissions WHERE id = ?`, st.id). + Scan(&curHash, &firstSeen, &lastSeen) + if errors.Is(err, sql.ErrNoRows) { + return false, false, nil + } + if err != nil { + return false, false, fmt.Errorf("read row: %w", err) + } + if curHash == st.newHash { + return false, false, nil + } + + var survivor int64 + err = tx.QueryRow(`SELECT id FROM transmissions WHERE hash = ?`, st.newHash).Scan(&survivor) + if errors.Is(err, sql.ErrNoRows) { + if _, err := tx.Exec(`UPDATE transmissions SET hash = ? WHERE id = ?`, st.newHash, st.id); err != nil { + return false, false, fmt.Errorf("rewrite hash: %w", err) + } + return true, false, nil + } + if err != nil { + return false, false, fmt.Errorf("look up survivor: %w", err) + } + + if _, err := tx.Exec(hashMergeMoveObservations, survivor, st.id, survivor); err != nil { + return false, false, fmt.Errorf("move observations to %d: %w", survivor, err) + } + if _, err := tx.Exec(hashMergeWidenSpan, firstSeen, firstSeen, lastSeen, lastSeen, survivor); err != nil { + return false, false, fmt.Errorf("widen survivor %d: %w", survivor, err) + } + for _, q := range []string{hashMergeDeleteRadios, hashMergeDeleteObservations, hashMergeDeleteTransmission} { + if _, err := tx.Exec(q, st.id); err != nil { + return false, false, fmt.Errorf("delete duplicate: %w", err) + } + } + return false, true, nil +} diff --git a/cmd/ingestor/hash_migrate_test.go b/cmd/ingestor/hash_migrate_test.go new file mode 100644 index 000000000..3b5958f8b --- /dev/null +++ b/cmd/ingestor/hash_migrate_test.go @@ -0,0 +1,374 @@ +package main + +import ( + "context" + "errors" + "fmt" + "math" + "path/filepath" + "strings" + "testing" +) + +// Two encodings of one logical packet: the same direct-route payload, once +// with an empty path and once relayed through hop AA. The content hash skips +// the path, so both hash to the same value. +const ( + hashMigrateRawA = "0A00D69FD7A5A7475DB07337749AE61FA53A4788E976" + hashMigrateRawB = "0A01AAD69FD7A5A7475DB07337749AE61FA53A4788E976" +) + +func openHashMigrateStore(t *testing.T) *Store { + t.Helper() + store, err := OpenStore(filepath.Join(t.TempDir(), "hash-migrate.db")) + if err != nil { + t.Fatalf("OpenStore: %v", err) + } + t.Cleanup(func() { store.Close() }) + // Nothing existed when the store opened, so the scheduled migration has + // nothing in range; wait for it so it cannot overlap the test's own run. + store.WaitForAsyncMigrations() + return store +} + +func insertHashTx(t *testing.T, store *Store, rawHex, hash, firstSeen string, lastSeen int64) int64 { + t.Helper() + res, err := store.db.Exec(`INSERT INTO transmissions (raw_hex, hash, first_seen, last_seen, route_type, payload_type) + VALUES (?, ?, ?, ?, 2, 2)`, rawHex, hash, firstSeen, lastSeen) + if err != nil { + t.Fatalf("insert transmission %s: %v", hash, err) + } + id, err := res.LastInsertId() + if err != nil { + t.Fatal(err) + } + return id +} + +func insertHashObs(t *testing.T, store *Store, txID int64, observerIdx, pathJSON interface{}) int64 { + t.Helper() + res, err := store.db.Exec(`INSERT INTO observations (transmission_id, observer_idx, path_json, timestamp) + VALUES (?, ?, ?, 1700000000)`, txID, observerIdx, pathJSON) + if err != nil { + t.Fatalf("insert observation for tx %d: %v", txID, err) + } + id, err := res.LastInsertId() + if err != nil { + t.Fatal(err) + } + return id +} + +func txHash(t *testing.T, store *Store, id int64) string { + t.Helper() + var h string + if err := store.db.QueryRow(`SELECT hash FROM transmissions WHERE id = ?`, id).Scan(&h); err != nil { + t.Fatalf("hash of tx %d: %v", id, err) + } + return h +} + +func countWhere(t *testing.T, store *Store, query string, args ...interface{}) int { + t.Helper() + var n int + if err := store.db.QueryRow(query, args...).Scan(&n); err != nil { + t.Fatalf("%s: %v", query, err) + } + return n +} + +func TestMigrateContentHashesRewritesStaleHash(t *testing.T) { + store := openHashMigrateStore(t) + stale := insertHashTx(t, store, hashMigrateRawA, "deadbeef12345678", "2026-01-01T00:00:00Z", 100) + obs := insertHashObs(t, store, stale, 1, "[]") + // Companion-relayed messages carry no raw bytes; their hash is not a + // content hash and must never be touched. + noRaw := insertHashTx(t, store, "", "companionhash001", "2026-01-01T00:00:00Z", 100) + + rewritten, merged, err := store.MigrateContentHashes(context.Background(), 100) + if err != nil { + t.Fatalf("MigrateContentHashes: %v", err) + } + if rewritten != 1 || merged != 0 { + t.Fatalf("got rewritten=%d merged=%d, want 1, 0", rewritten, merged) + } + if got, want := txHash(t, store, stale), ComputeContentHash(hashMigrateRawA); got != want { + t.Errorf("stale row hash = %s, want %s", got, want) + } + if got := txHash(t, store, noRaw); got != "companionhash001" { + t.Errorf("row without raw_hex was rewritten to %s", got) + } + if n := countWhere(t, store, `SELECT COUNT(*) FROM observations WHERE id = ? AND transmission_id = ?`, obs, stale); n != 1 { + t.Errorf("a rewritten row's observation moved or vanished") + } +} + +// TestMigrateContentHashesMergesCollision covers a stale row whose correct +// hash already belongs to another row: the old formula split one logical +// packet in two, and the migration folds the duplicate into the survivor. +func TestMigrateContentHashesMergesCollision(t *testing.T) { + store := openHashMigrateStore(t) + newHash := ComputeContentHash(hashMigrateRawA) + surv := insertHashTx(t, store, hashMigrateRawA, newHash, "2026-01-02T00:00:00Z", 500) + dup := insertHashTx(t, store, hashMigrateRawB, "stalestalestale1", "2026-01-01T00:00:00Z", 900) + + insertHashObs(t, store, surv, 1, `["AA"]`) + insertHashObs(t, store, surv, nil, `["BB"]`) + // Same observer and path as one the survivor holds: moving it would + // violate idx_observations_dedup, so it is dropped with its radio row. + conflict := insertHashObs(t, store, dup, 1, `["AA"]`) + moved := insertHashObs(t, store, dup, 2, `[]`) + // NULL observer_idx never conflicts under the unique index, so these + // move even though the survivor has a NULL-observer row on the same path. + nullA := insertHashObs(t, store, dup, nil, `["BB"]`) + nullB := insertHashObs(t, store, dup, nil, nil) + for _, o := range []int64{conflict, moved} { + if _, err := store.db.Exec(`INSERT INTO observation_radios (observation_id, radio_id) VALUES (?, 'r')`, o); err != nil { + t.Fatalf("seed observation_radios: %v", err) + } + } + if _, err := store.db.Exec(`INSERT INTO advert_route_evidence (tx_id, bit) VALUES (?, 1)`, dup); err != nil { + t.Fatalf("seed advert_route_evidence: %v", err) + } + + rewritten, merged, err := store.MigrateContentHashes(context.Background(), 100) + if err != nil { + t.Fatalf("MigrateContentHashes: %v", err) + } + if rewritten != 0 || merged != 1 { + t.Fatalf("got rewritten=%d merged=%d, want 0, 1", rewritten, merged) + } + + if n := countWhere(t, store, `SELECT COUNT(*) FROM transmissions WHERE id = ?`, dup); n != 0 { + t.Error("duplicate transmission still present") + } + var firstSeen string + var lastSeen int64 + if err := store.db.QueryRow(`SELECT first_seen, last_seen FROM transmissions WHERE id = ?`, surv).Scan(&firstSeen, &lastSeen); err != nil { + t.Fatal(err) + } + if firstSeen != "2026-01-01T00:00:00Z" || lastSeen != 900 { + t.Errorf("survivor first_seen=%s last_seen=%d, want the earliest and the latest of the pair", firstSeen, lastSeen) + } + for _, o := range []int64{moved, nullA, nullB} { + if n := countWhere(t, store, `SELECT COUNT(*) FROM observations WHERE id = ? AND transmission_id = ?`, o, surv); n != 1 { + t.Errorf("observation %d was not moved onto the survivor", o) + } + } + if n := countWhere(t, store, `SELECT COUNT(*) FROM observations WHERE id = ?`, conflict); n != 0 { + t.Error("conflicting observation was kept; it duplicates one the survivor already has") + } + if n := countWhere(t, store, `SELECT COUNT(*) FROM observations WHERE transmission_id = ?`, surv); n != 5 { + t.Errorf("survivor holds %d observations, want 5 (2 own + 3 moved)", n) + } + if n := countWhere(t, store, `SELECT COUNT(*) FROM observation_radios WHERE observation_id = ?`, conflict); n != 0 { + t.Error("radio row of the dropped observation survived") + } + if n := countWhere(t, store, `SELECT COUNT(*) FROM observation_radios WHERE observation_id = ?`, moved); n != 1 { + t.Error("radio row of a moved observation was deleted") + } + if n := countWhere(t, store, `SELECT COUNT(*) FROM advert_route_evidence WHERE tx_id = ?`, dup); n != 0 { + t.Error("advert_route_evidence of the duplicate was not cascaded") + } + + // Idempotent: everything now matches the formula. + rewritten, merged, err = store.MigrateContentHashes(context.Background(), 100) + if err != nil || rewritten != 0 || merged != 0 { + t.Fatalf("second run = (%d, %d, %v), want (0, 0, nil)", rewritten, merged, err) + } +} + +// Two stale rows of one packet, neither holding the correct hash yet: the +// first is rewritten, and the second then collides with it inside the same +// batch and merges. A batch size of 1 also walks the id cursor across batches. +func TestMigrateContentHashesStalePairAcrossBatches(t *testing.T) { + for _, batch := range []int{1, 100} { + store := openHashMigrateStore(t) + a := insertHashTx(t, store, hashMigrateRawA, "staleA0000000000", "2026-01-01T00:00:00Z", 1) + b := insertHashTx(t, store, hashMigrateRawB, "staleB0000000000", "2026-01-01T00:00:00Z", 1) + insertHashObs(t, store, b, 7, `["AA"]`) + + rewritten, merged, err := store.MigrateContentHashes(context.Background(), batch) + if err != nil { + t.Fatalf("batch %d: %v", batch, err) + } + if rewritten != 1 || merged != 1 { + t.Fatalf("batch %d: got rewritten=%d merged=%d, want 1, 1", batch, rewritten, merged) + } + if got := txHash(t, store, a); got != ComputeContentHash(hashMigrateRawA) { + t.Errorf("batch %d: first row hash = %s", batch, got) + } + if n := countWhere(t, store, `SELECT COUNT(*) FROM observations WHERE transmission_id = ?`, a); n != 1 { + t.Errorf("batch %d: second row's observation did not move to the first", batch) + } + if n := countWhere(t, store, `SELECT COUNT(*) FROM transmissions`); n != 1 { + t.Errorf("batch %d: %d transmissions left, want 1", batch, n) + } + } +} + +func TestMigrateContentHashesNoOp(t *testing.T) { + store := openHashMigrateStore(t) + id := insertHashTx(t, store, hashMigrateRawA, ComputeContentHash(hashMigrateRawA), "2026-01-01T00:00:00Z", 1) + rewritten, merged, err := store.MigrateContentHashes(context.Background(), 100) + if err != nil || rewritten != 0 || merged != 0 { + t.Fatalf("got (%d, %d, %v), want (0, 0, nil)", rewritten, merged, err) + } + if got := txHash(t, store, id); got != ComputeContentHash(hashMigrateRawA) { + t.Errorf("current hash changed to %s", got) + } +} + +func TestMigrateContentHashesStopsOnCancel(t *testing.T) { + store := openHashMigrateStore(t) + id := insertHashTx(t, store, hashMigrateRawA, "deadbeef12345678", "2026-01-01T00:00:00Z", 1) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + rewritten, merged, err := store.MigrateContentHashes(ctx, 100) + if !errors.Is(err, context.Canceled) { + t.Fatalf("err = %v, want one wrapping context.Canceled (RunAsyncMigration records it as cancelled)", err) + } + if rewritten != 0 || merged != 0 { + t.Errorf("got rewritten=%d merged=%d on a cancelled context", rewritten, merged) + } + if got := txHash(t, store, id); got != "deadbeef12345678" { + t.Errorf("row rewritten despite cancellation: %s", got) + } +} + +// Ported from the deleted server test (#1856): a migration that cannot write +// must report failure, never success, so _async_migrations stays not-done. +func TestMigrateContentHashesReportsWriteFailure(t *testing.T) { + store := openHashMigrateStore(t) + insertHashTx(t, store, hashMigrateRawA, "deadbeef12345678", "2026-01-01T00:00:00Z", 1) + if err := store.db.Close(); err != nil { + t.Fatal(err) + } + if _, _, err := store.MigrateContentHashes(context.Background(), 100); err == nil { + t.Fatal("expected an error from a closed handle; a nil error would mark the migration done") + } +} + +// TestContentHashMigrationScheduledOnOpen pins the wiring: OpenStore schedules +// the migration over the rows that existed at boot, records it done, and +// leaves rows inserted after boot alone (this process writes current hashes, +// so anything newer is never stale — and the bound keeps the background pass +// from racing writes it has no business touching). +func TestContentHashMigrationScheduledOnOpen(t *testing.T) { + path := filepath.Join(t.TempDir(), "hash-migrate-boot.db") + first, err := OpenStore(path) + if err != nil { + t.Fatal(err) + } + first.WaitForAsyncMigrations() + old := insertHashTx(t, first, hashMigrateRawA, "deadbeef12345678", "2026-01-01T00:00:00Z", 1) + // The first open ran the migration over an empty table and recorded it + // done. Forget that, so the reopen behaves like the first boot of this + // build on a DB written by an older one. + if _, err := first.db.Exec(`DELETE FROM _async_migrations WHERE name = ?`, contentHashMigrationName); err != nil { + t.Fatal(err) + } + first.Close() + + store, err := OpenStore(path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { store.Close() }) + fresh := insertHashTx(t, store, "0A00AABBCCDD", "afterboot0000000", "2026-01-01T00:00:00Z", 1) + store.WaitForAsyncMigrations() + + status, err := store.AsyncMigrationStatus(contentHashMigrationName) + if err != nil || status != "done" { + t.Fatalf("status = %q, %v; want done", status, err) + } + if got := txHash(t, store, old); got != ComputeContentHash(hashMigrateRawA) { + t.Errorf("pre-boot stale row not migrated: %s", got) + } + if got := txHash(t, store, fresh); got != "afterboot0000000" { + t.Errorf("row inserted after boot was touched: %s", got) + } +} + +// A running server cannot follow this pass (no feed carries a hash change or a +// merge), so the summary must send the operator to restart it. A pass that +// changed nothing must stay silent: it runs on every boot. +func TestContentHashMigrationSummary(t *testing.T) { + if got := contentHashMigrationSummary(0, 0); got != "" { + t.Errorf("no-op pass logged %q, want nothing", got) + } + for _, c := range []struct{ rewritten, merged int }{{3, 0}, {0, 2}, {3, 2}} { + got := contentHashMigrationSummary(c.rewritten, c.merged) + for _, want := range []string{ + fmt.Sprintf("rewrote %d content hashes", c.rewritten), + fmt.Sprintf("merged %d duplicate transmissions", c.merged), + "restart servers", + } { + if !strings.Contains(got, want) { + t.Errorf("summary(%d, %d) = %q, missing %q", c.rewritten, c.merged, got, want) + } + } + } +} + +// Review on #2409: one transaction per scan batch held the writer lock for +// seconds on an affected install, where every row in the batch is stale. The +// stale rows of a scan batch must commit in chunks of at most writeBatch, so +// ingest waits for one chunk, not the whole batch. Five stale encodings of one +// packet, read in one scan batch and written two at a time, take three +// transactions and still end as one row: a chunk merges into the row an +// earlier chunk rewrote. +func TestMigrateContentHashesCommitsInWriteChunks(t *testing.T) { + store := openHashMigrateStore(t) + var first int64 + for i := 0; i < 5; i++ { + id := insertHashTx(t, store, hashMigrateRawA, fmt.Sprintf("stale%011d", i), "2026-01-01T00:00:00Z", 1) + insertHashObs(t, store, id, i, `["AA"]`) + if i == 0 { + first = id + } + } + ResetWriterStatsForTest() + t.Cleanup(ResetWriterStatsForTest) + + rewritten, merged, err := store.migrateContentHashes(context.Background(), 100, 2, math.MaxInt64) + if err != nil { + t.Fatal(err) + } + if rewritten != 1 || merged != 4 { + t.Fatalf("got rewritten=%d merged=%d, want 1, 4", rewritten, merged) + } + if got := store.WriterStatsSnapshot()["content_hash_migrate"].Count; got != 3 { + t.Errorf("%d migration transactions, want 3 (5 stale rows, 2 per commit)", got) + } + if n := countWhere(t, store, `SELECT COUNT(*) FROM transmissions`); n != 1 { + t.Errorf("%d transmissions left, want 1", n) + } + if n := countWhere(t, store, `SELECT COUNT(*) FROM observations WHERE transmission_id = ?`, first); n != 5 { + t.Errorf("survivor has %d observations, want 5", n) + } +} + +func TestMigrateContentHashesRejectsNonPositiveBatches(t *testing.T) { + store := openHashMigrateStore(t) + for _, c := range []struct{ scan, write int }{{0, 1}, {1, 0}} { + if _, _, err := store.migrateContentHashes(context.Background(), c.scan, c.write, math.MaxInt64); err == nil { + t.Errorf("scan=%d write=%d: want an error", c.scan, c.write) + } + } +} + +// The progress line shows a long pass moving, and stays quiet while nothing +// has changed so an unaffected install's boot scan logs nothing. +func TestContentHashMigrationProgress(t *testing.T) { + if got := contentHashMigrationProgress(5000, 9000, 0, 0); got != "" { + t.Errorf("unchanged pass logged %q, want nothing", got) + } + if got, want := contentHashMigrationProgress(5000, 9000, 40, 7), "scanned through id 5000 of 9000, rewrote 40, merged 7"; !strings.Contains(got, want) { + t.Errorf("progress = %q, missing %q", got, want) + } + if got := contentHashMigrationProgress(5000, math.MaxInt64, 1, 0); strings.Contains(got, " of ") { + t.Errorf("unbounded pass printed a bound: %q", got) + } +} diff --git a/cmd/ingestor/main.go b/cmd/ingestor/main.go index b4365252d..a7a6054c2 100644 --- a/cmd/ingestor/main.go +++ b/cmd/ingestor/main.go @@ -188,6 +188,7 @@ func main() { // registration across reconnects returns the same state so // counters accumulate across the process lifetime. status := RegisterSourceStatus(tag, source.Broker) + subs := &subscriptionManager{} opts.SetOnConnectHandler(func(c mqtt.Client) { log.Printf("MQTT [%s] connected to %s as client %s", tag, source.Broker, opts.ClientID) @@ -201,19 +202,15 @@ func main() { if len(topics) == 0 { topics = []string{"meshcore/#"} } - for _, t := range topics { - token := c.Subscribe(t, 0, nil) - token.Wait() - if token.Error() != nil { - log.Printf("MQTT [%s] subscribe error for %s: %v", tag, t, token.Error()) - } else { - log.Printf("MQTT [%s] subscribed to %s", tag, t) - } - } + // Checks SUBACK return codes and retries rejected + // subscriptions; supersedes retry loops from the previous + // connection (see subscribe_retry.go). + subs.start(c, tag, topics) }) opts.SetConnectionLostHandler(func(c mqtt.Client, err error) { log.Printf("MQTT [%s] disconnected from %s: %v", tag, source.Broker, err) + subs.stop() status.MarkDisconnect(time.Now(), err) }) diff --git a/cmd/ingestor/maintenance.go b/cmd/ingestor/maintenance.go index 11cd88953..7b12605ea 100644 --- a/cmd/ingestor/maintenance.go +++ b/cmd/ingestor/maintenance.go @@ -45,16 +45,28 @@ const pruneBatchTransmissions = 250 // pins the plan. const pruneAgedTransmissionIDs = `SELECT id FROM transmissions WHERE first_seen < ? ORDER BY first_seen, id LIMIT ?` -// The two statements of one prune batch. Child observations go first (no -// CASCADE in SQLite). -const ( - pruneObservationsBatch = `DELETE FROM observations WHERE transmission_id IN (` + pruneAgedTransmissionIDs + `)` - pruneTransmissionsBatch = `DELETE FROM transmissions WHERE id IN (` + pruneAgedTransmissionIDs + `)` - // Sparse rx_radio_id rows of multi-radio observers (#1869), keyed by the - // observation, so they go before the observations they point at. - pruneObservationRadiosBatch = `DELETE FROM observation_radios WHERE observation_id IN ( - SELECT id FROM observations WHERE transmission_id IN (` + pruneAgedTransmissionIDs + `))` -) +// The statements of one prune batch. +var pruneObservationRadiosBatch, pruneObservationsBatch, pruneTransmissionsBatch = transmissionDeleteStatements(pruneAgedTransmissionIDs) + +// transmissionDeleteStatements returns the statements that delete the +// transmissions selected by sel together with the rows that point at them, in +// the order they must run. sel is the body of an IN (...) list: a subquery, or +// "?" for a single id. Every path that deletes transmissions (retention prune, +// content-hash merge) uses this so the child list lives in one place. +// +// - observation_radios: sparse rx_radio_id rows of multi-radio observers +// (#1869), keyed by the observation, so they go before the observations. +// - observations: no CASCADE on transmission_id, and foreign keys are +// enforced, so they go before the transmissions. +// - advert_route_evidence and tx_rewrite_feed are ON DELETE CASCADE and +// need no statement of their own. +func transmissionDeleteStatements(sel string) (radios, observations, transmissions string) { + radios = `DELETE FROM observation_radios WHERE observation_id IN ( + SELECT id FROM observations WHERE transmission_id IN (` + sel + `))` + observations = `DELETE FROM observations WHERE transmission_id IN (` + sel + `)` + transmissions = `DELETE FROM transmissions WHERE id IN (` + sel + `)` + return radios, observations, transmissions +} // PruneOldPackets deletes transmissions (and their child observations) // older than `days`. Returns count of transmissions deleted. diff --git a/cmd/ingestor/subscribe_retry.go b/cmd/ingestor/subscribe_retry.go new file mode 100644 index 000000000..0a3122570 --- /dev/null +++ b/cmd/ingestor/subscribe_retry.go @@ -0,0 +1,163 @@ +package main + +import ( + "context" + "fmt" + "log" + "sync" + "sync/atomic" + "time" + + mqtt "github.com/eclipse/paho.mqtt.golang" +) + +// subscribeTimeout bounds a single SUBSCRIBE round-trip. +const subscribeTimeout = 10 * time.Second + +// subscribeRetryInitial / subscribeRetryMax bound the backoff between +// retries of a rejected SUBSCRIBE. Variables so tests can shorten them. +var ( + subscribeRetryInitial = 2 * time.Second + subscribeRetryMax = 60 * time.Second +) + +// subscribeClient is the subset of mqtt.Client used here, so tests can +// supply a fake. +type subscribeClient interface { + Subscribe(topic string, qos byte, callback mqtt.MessageHandler) mqtt.Token + IsConnectionOpen() bool +} + +// subackResulter is implemented by *mqtt.SubscribeToken. Matching on the +// method instead of the concrete type keeps subscribeOnce testable. +type subackResulter interface { + Result() map[string]byte +} + +// subscribeOnce sends one SUBSCRIBE and reports failure, including a +// broker-side rejection. paho does NOT surface a SUBACK failure return code +// (0x80) via token.Error(): the token completes "successfully" and the +// client stays connected with zero subscriptions. That happens e.g. when +// EMQX has just restarted and its authorization sources are not loaded yet +// (authorization.no_match = deny). Without this check the ingestor logged +// "subscribed" and then silently received nothing until restarted. +// +// Every return code in the result is checked rather than looking the topic +// up by name: paho strips "$share//" and "$queue/" before keying the +// result, so a lookup by the configured topic would miss a rejection. Each +// SUBSCRIBE carries exactly one topic, so all codes belong to it. An empty +// result means no SUBACK code was recorded and counts as failure. +func subscribeOnce(c subscribeClient, topic string) error { + tok := c.Subscribe(topic, 0, nil) + if !tok.WaitTimeout(subscribeTimeout) { + return fmt.Errorf("timeout after %s", subscribeTimeout) + } + if err := tok.Error(); err != nil { + return err + } + if st, ok := tok.(subackResulter); ok { + res := st.Result() + if len(res) == 0 { + return fmt.Errorf("SUBACK carried no return code") + } + for _, rc := range res { + if rc >= 0x80 { + return fmt.Errorf("broker rejected subscription (SUBACK 0x%02x)", rc) + } + } + } + return nil +} + +// nextSubscribeDelay doubles the backoff, capped at subscribeRetryMax. +func nextSubscribeDelay(d time.Duration) time.Duration { + d *= 2 + if d > subscribeRetryMax { + d = subscribeRetryMax + } + return d +} + +// subscriptionManager owns the subscribe attempts of one MQTT source. Each +// OnConnect calls start, which cancels any retry loops from the previous +// connection before launching new ones, so at most one loop per topic is +// ever alive. The connection-lost handler calls stop. +// +// IsConnected() cannot be used to end the loops: with AutoReconnect or +// ConnectRetry set (see buildMQTTOpts), paho reports true while it is +// reconnecting. The loops therefore watch their context (cancelled on +// connection loss and on the next OnConnect) and IsConnectionOpen(). +type subscriptionManager struct { + mu sync.Mutex + cancel context.CancelFunc + wg sync.WaitGroup + active atomic.Int32 // live retry loops, for tests +} + +// start subscribes to each topic. The first attempt per topic runs +// synchronously; failed topics are retried in the background with +// exponential backoff until they succeed or the connection ends. +func (m *subscriptionManager) start(c subscribeClient, tag string, topics []string) { + ctx, cancel := context.WithCancel(context.Background()) + m.mu.Lock() + if m.cancel != nil { + m.cancel() + } + m.cancel = cancel + m.mu.Unlock() + + for _, topic := range topics { + err := subscribeOnce(c, topic) + if err == nil { + log.Printf("MQTT [%s] subscribed to %s", tag, topic) + continue + } + log.Printf("MQTT [%s] subscribe error for %s: %v — retrying in background", tag, topic, err) + m.wg.Add(1) + go func(topic string) { + defer m.wg.Done() + m.retry(ctx, c, tag, topic) + }(topic) + } +} + +// stop cancels all retry loops of the current connection. +func (m *subscriptionManager) stop() { + m.mu.Lock() + defer m.mu.Unlock() + if m.cancel != nil { + m.cancel() + m.cancel = nil + } +} + +func (m *subscriptionManager) retry(ctx context.Context, c subscribeClient, tag, topic string) { + m.active.Add(1) + defer m.active.Add(-1) + delay := subscribeRetryInitial + for attempt := 2; ; attempt++ { + t := time.NewTimer(delay) + select { + case <-ctx.Done(): + t.Stop() + return + case <-t.C: + } + if !c.IsConnectionOpen() { + log.Printf("MQTT [%s] connection not open while retrying subscribe to %s; next OnConnect will retry", tag, topic) + return + } + if err := subscribeOnce(c, topic); err != nil { + log.Printf("MQTT [%s] subscribe attempt #%d for %s failed: %v", tag, attempt, topic, err) + delay = nextSubscribeDelay(delay) + continue + } + if ctx.Err() != nil { + // Superseded while the SUBSCRIBE was in flight; the newer + // connection's start() owns logging. + return + } + log.Printf("MQTT [%s] subscribed to %s (attempt #%d)", tag, topic, attempt) + return + } +} diff --git a/cmd/ingestor/subscribe_retry_test.go b/cmd/ingestor/subscribe_retry_test.go new file mode 100644 index 000000000..484ca3b54 --- /dev/null +++ b/cmd/ingestor/subscribe_retry_test.go @@ -0,0 +1,242 @@ +package main + +import ( + "errors" + "strings" + "sync" + "testing" + "time" + + mqtt "github.com/eclipse/paho.mqtt.golang" +) + +// fakeSubToken is a SUBSCRIBE token carrying a SUBACK result. +type fakeSubToken struct { + result map[string]byte + err error + timedOut bool +} + +func (t *fakeSubToken) Wait() bool { return !t.timedOut } +func (t *fakeSubToken) WaitTimeout(time.Duration) bool { return !t.timedOut } +func (t *fakeSubToken) Done() <-chan struct{} { + ch := make(chan struct{}) + if !t.timedOut { + close(ch) + } + return ch +} +func (t *fakeSubToken) Error() error { return t.err } +func (t *fakeSubToken) Result() map[string]byte { return t.result } + +// fakeSubClient answers SUBSCRIBE with a scripted sequence of SUBACK codes; +// the last code repeats once the script is exhausted. Like paho, it keys the +// result by the topic with any "$share//" or "$queue/" prefix +// stripped. +type fakeSubClient struct { + mu sync.Mutex + codes []byte + calls int + open bool + err error + timedOut bool + noResult bool +} + +func stripSharePrefix(topic string) string { + if strings.HasPrefix(topic, "$share/") { + return strings.Join(strings.Split(topic, "/")[2:], "/") + } + return strings.TrimPrefix(topic, "$queue/") +} + +func (c *fakeSubClient) Subscribe(topic string, _ byte, _ mqtt.MessageHandler) mqtt.Token { + c.mu.Lock() + defer c.mu.Unlock() + i := c.calls + if i >= len(c.codes) { + i = len(c.codes) - 1 + } + c.calls++ + res := map[string]byte{stripSharePrefix(topic): c.codes[i]} + if c.noResult { + res = map[string]byte{} + } + return &fakeSubToken{result: res, err: c.err, timedOut: c.timedOut} +} + +// IsConnectionOpen mirrors paho: false while reconnecting. There is +// deliberately no IsConnected here — with AutoReconnect paho reports true +// during an outage, so the retry loop must not rely on it. +func (c *fakeSubClient) IsConnectionOpen() bool { + c.mu.Lock() + defer c.mu.Unlock() + return c.open +} + +func (c *fakeSubClient) setOpen(v bool) { + c.mu.Lock() + c.open = v + c.mu.Unlock() +} + +func (c *fakeSubClient) callCount() int { + c.mu.Lock() + defer c.mu.Unlock() + return c.calls +} + +func TestSubscribeOnce_Granted(t *testing.T) { + c := &fakeSubClient{codes: []byte{0x00}, open: true} + if err := subscribeOnce(c, "meshcore/#"); err != nil { + t.Fatalf("expected success, got %v", err) + } +} + +func TestSubscribeOnce_RejectedSubackIsError(t *testing.T) { + c := &fakeSubClient{codes: []byte{0x80}, open: true} + if err := subscribeOnce(c, "meshcore/#"); err == nil { + t.Fatal("expected error for SUBACK 0x80, got nil") + } +} + +func TestSubscribeOnce_SharedTopicRejectedIsError(t *testing.T) { + for _, topic := range []string{"$share/corescope/meshcore/#", "$queue/meshcore/#"} { + c := &fakeSubClient{codes: []byte{0x80}, open: true} + if err := subscribeOnce(c, topic); err == nil { + t.Fatalf("%s: expected error for SUBACK 0x80, got nil", topic) + } + } +} + +func TestSubscribeOnce_EmptyResultIsError(t *testing.T) { + c := &fakeSubClient{codes: []byte{0x00}, open: true, noResult: true} + if err := subscribeOnce(c, "meshcore/#"); err == nil { + t.Fatal("expected error for SUBACK without return code") + } +} + +func TestSubscribeOnce_TokenError(t *testing.T) { + c := &fakeSubClient{codes: []byte{0x00}, open: true, err: errors.New("boom")} + if err := subscribeOnce(c, "meshcore/#"); err == nil { + t.Fatal("expected token error to be returned") + } +} + +func TestSubscribeOnce_Timeout(t *testing.T) { + c := &fakeSubClient{codes: []byte{0x00}, open: true, timedOut: true} + if err := subscribeOnce(c, "meshcore/#"); err == nil { + t.Fatal("expected timeout error") + } +} + +func TestNextSubscribeDelay_Capped(t *testing.T) { + d := subscribeRetryInitial + for i := 0; i < 20; i++ { + d = nextSubscribeDelay(d) + if d > subscribeRetryMax { + t.Fatalf("delay %s exceeds cap %s", d, subscribeRetryMax) + } + } + if d != subscribeRetryMax { + t.Fatalf("expected delay to settle at %s, got %s", subscribeRetryMax, d) + } +} + +func withFastRetry(t *testing.T) { + t.Helper() + oldI, oldM := subscribeRetryInitial, subscribeRetryMax + subscribeRetryInitial, subscribeRetryMax = 5*time.Millisecond, 20*time.Millisecond + t.Cleanup(func() { subscribeRetryInitial, subscribeRetryMax = oldI, oldM }) +} + +func waitForSub(t *testing.T, cond func() bool) { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + if cond() { + return + } + time.Sleep(2 * time.Millisecond) + } + t.Fatal("condition not met within 2s") +} + +func waitLoopsDone(t *testing.T, m *subscriptionManager) { + t.Helper() + done := make(chan struct{}) + go func() { m.wg.Wait(); close(done) }() + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatalf("retry loops still running (%d active)", m.active.Load()) + } +} + +func TestSubscriptionManager_RecoversAfterRejection(t *testing.T) { + withFastRetry(t) + // Broker rejects twice (authz not loaded yet), then grants. + c := &fakeSubClient{codes: []byte{0x80, 0x80, 0x00}, open: true} + m := &subscriptionManager{} + m.start(c, "test", []string{"meshcore/#"}) + waitLoopsDone(t, m) + if n := c.callCount(); n != 3 { + t.Fatalf("expected retries to stop after success at 3 calls, got %d", n) + } +} + +func TestSubscriptionManager_NoRetryOnSuccess(t *testing.T) { + withFastRetry(t) + c := &fakeSubClient{codes: []byte{0x00}, open: true} + m := &subscriptionManager{} + m.start(c, "test", []string{"meshcore/#"}) + time.Sleep(50 * time.Millisecond) + if n := c.callCount(); n != 1 { + t.Fatalf("expected exactly 1 subscribe, got %d", n) + } +} + +// With AutoReconnect, paho's IsConnected stays true while reconnecting; the +// loop must end once the connection itself is no longer open. +func TestSubscriptionManager_StopsWhenConnectionNotOpen(t *testing.T) { + withFastRetry(t) + c := &fakeSubClient{codes: []byte{0x80}, open: true} + m := &subscriptionManager{} + m.start(c, "test", []string{"meshcore/#"}) + waitForSub(t, func() bool { return c.callCount() >= 2 }) + c.setOpen(false) + waitLoopsDone(t, m) +} + +func TestSubscriptionManager_StopEndsLoop(t *testing.T) { + withFastRetry(t) + c := &fakeSubClient{codes: []byte{0x80}, open: true} + m := &subscriptionManager{} + m.start(c, "test", []string{"meshcore/#"}) + waitForSub(t, func() bool { return c.callCount() >= 2 }) + m.stop() // connection-lost handler + waitLoopsDone(t, m) + n := c.callCount() + time.Sleep(50 * time.Millisecond) + if c.callCount() != n { + t.Fatal("retry loop kept subscribing after stop") + } +} + +// A permanent ACL deny with a flapping connection must not accumulate one +// retry loop per reconnect: each OnConnect supersedes the previous loops. +func TestSubscriptionManager_ReconnectSupersedesOldLoops(t *testing.T) { + withFastRetry(t) + c := &fakeSubClient{codes: []byte{0x80}, open: true} + m := &subscriptionManager{} + for i := 0; i < 20; i++ { + m.start(c, "test", []string{"meshcore/#"}) + } + waitForSub(t, func() bool { return m.active.Load() == 1 }) + time.Sleep(50 * time.Millisecond) + if n := m.active.Load(); n != 1 { + t.Fatalf("expected 1 live retry loop after 20 reconnects, got %d", n) + } + m.stop() + waitLoopsDone(t, m) +} diff --git a/cmd/server/account_export.go b/cmd/server/account_export.go index de201e7b4..a0f78f011 100644 --- a/cmd/server/account_export.go +++ b/cmd/server/account_export.go @@ -25,6 +25,7 @@ type accountExport struct { Companions []exportCompanion `json:"companions"` ObserverLogin *exportObserverLogin `json:"observerLogin"` ObserverBindings []exportObserverBinding `json:"observerBindings"` + RepeaterClaims []repeaterClaimRefJSON `json:"repeaterClaims"` Settings *exportSettings `json:"settings"` Proposals []exportProposal `json:"proposals"` Notifications exportNotifications `json:"notifications"` @@ -134,6 +135,7 @@ func (a *authService) buildAccountExport(u *users.User, now time.Time) (*account Sessions: []exportSession{}, Companions: []exportCompanion{}, ObserverBindings: []exportObserverBinding{}, + RepeaterClaims: []repeaterClaimRefJSON{}, Proposals: []exportProposal{}, Notifications: exportNotifications{Watches: []exportWatch{}}, Audit: []exportAuditEntry{}, @@ -173,6 +175,11 @@ func (a *authService) buildAccountExport(u *users.User, now time.Time) (*account for _, b := range bindings { x.ObserverBindings = append(x.ObserverBindings, exportObserverBinding{Pubkey: b.Pubkey, BoundAt: rfc3339(b.BoundAt), BoundBy: b.BoundBy}) } + claims, err := a.st.RepeaterClaimsByUser(u.ID) + if err != nil { + return nil, fmt.Errorf("repeater claims: %w", err) + } + x.RepeaterClaims = claimRefsJSON(claims) rec, err := a.st.SettingsRecordFor(u.ID) if err != nil { return nil, fmt.Errorf("settings: %w", err) diff --git a/cmd/server/account_export_test.go b/cmd/server/account_export_test.go index 440fec438..015fc8103 100644 --- a/cmd/server/account_export_test.go +++ b/cmd/server/account_export_test.go @@ -239,3 +239,33 @@ func TestAccountExportManualActivation(t *testing.T) { t.Fatalf("activation mail = %+v", activate) } } + +func TestAccountExportRepeaterClaims(t *testing.T) { + f := repeaterFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + w := f.do("GET", "/api/account/export", nil, as(alice)) + expectStatus(t, w, 200) + if !strings.Contains(w.Body.String(), `"repeaterClaims":[]`) { + t.Fatalf("no claims should export as []: %s", w.Body.String()) + } + expectStatus(t, f.do("POST", repPath(rpkA, "claim"), nil, as(alice)), 200) + w = f.do("GET", "/api/account/export", nil, as(alice)) + expectStatus(t, w, 200) + x := decode[accountExport](t, w) + if len(x.RepeaterClaims) != 1 || x.RepeaterClaims[0].Pubkey != rpkA || x.RepeaterClaims[0].ClaimedAt == "" { + t.Fatalf("repeaterClaims = %+v", x.RepeaterClaims) + } + f2 := repeaterFixture(t, "admin@example.org") + admin := f2.registerAndActivate(t, "admin@example.org", "Admin", pw) + bob := f2.registerAndActivate(t, "bob@example.org", "Bob", pw) + expectStatus(t, f2.do("POST", repPath(rpkA, "claim"), nil, as(bob)), 200) + expectStatus(t, f2.do("POST", userPath(bob.me.ID, "/disable"), nil, as(admin)), 200) + expectStatus(t, f2.do("POST", userPath(bob.me.ID, "/enable"), nil, as(admin)), 200) + bob = f2.login(t, "bob@example.org", pw) + w = f2.do("GET", "/api/account/export", nil, as(bob)) + expectStatus(t, w, 200) + x = decode[accountExport](t, w) + if len(x.RepeaterClaims) != 1 || x.RepeaterClaims[0].Pubkey != rpkA { + t.Fatalf("claims after disable and enable = %+v", x.RepeaterClaims) + } +} diff --git a/cmd/server/admin_users_handlers.go b/cmd/server/admin_users_handlers.go index dfc80d5c0..5a23e5ec0 100644 --- a/cmd/server/admin_users_handlers.go +++ b/cmd/server/admin_users_handlers.go @@ -144,6 +144,12 @@ func (s *Server) handleAdminUserDetail(w http.ResponseWriter, r *http.Request, _ return } d.Companions = s.companionsJSON(links) + claims, err := a.st.RepeaterClaimsByUser(u.ID) + if err != nil { + adminStoreFail(w, "list repeater claims", u.ID, err) + return + } + d.RepeaterClaims = claimRefsJSON(claims) mails, err := a.st.MailForUser(u.ID, 50) if err != nil { adminStoreFail(w, "list mail", u.ID, err) diff --git a/cmd/server/auth_ratelimit.go b/cmd/server/auth_ratelimit.go index b1cd0835a..623302f34 100644 --- a/cmd/server/auth_ratelimit.go +++ b/cmd/server/auth_ratelimit.go @@ -12,12 +12,18 @@ import ( // rateLimiter is a keyed token bucket: n requests per period, refilled // continuously. In-memory, so limits reset on restart. That is acceptable // for brute-force damping, not a quota system. +// +// A capped limiter (newCappedRateLimiter) gives each key a second, slower +// bucket, charged together with the first, all or nothing: a burst that +// refills quickly under a ceiling over a longer window. type rateLimiter struct { - mu sync.Mutex - rate float64 // tokens per second - burst float64 - buckets map[string]*rlBucket - now func() time.Time + mu sync.Mutex + rate float64 // tokens per second + burst float64 + capRate float64 // the cap bucket's tokens per second; 0 without one + capBurst float64 + buckets map[string]*rlBucket + now func() time.Time maxBuckets int // cap on len(buckets); a field so tests can lower it warnFull sync.Once @@ -26,8 +32,9 @@ type rateLimiter struct { const rateLimiterMaxBuckets = 100000 type rlBucket struct { - tokens float64 - last time.Time + tokens float64 + capTokens float64 // the cap bucket's; unused without one + last time.Time } func newRateLimiter(n int, per time.Duration) *rateLimiter { @@ -35,9 +42,28 @@ func newRateLimiter(n int, per time.Duration) *rateLimiter { buckets: map[string]*rlBucket{}, now: time.Now, maxBuckets: rateLimiterMaxBuckets} } +// newCappedRateLimiter holds burst tokens per key, refilled at n per per, +// under a cap of capN tokens refilled at capN per capPer: a key never takes +// more than capN plus what capPer refills in any capPer. +func newCappedRateLimiter(burst, n int, per time.Duration, capN int, capPer time.Duration) *rateLimiter { + l := newRateLimiter(n, per) + l.burst = float64(burst) + l.capRate, l.capBurst = float64(capN)/capPer.Seconds(), float64(capN) + return l +} + // take consumes one token for key. When none is left it reports how long // until the next one. func (l *rateLimiter) take(key string) (bool, time.Duration) { + return l.takeN(key, 1) +} + +// takeN consumes n tokens for key, all or nothing: when fewer than n are left +// (in either bucket of a capped limiter) it takes none and reports how long +// until n are available (never, in effect, when n exceeds the burst or the +// cap). n < 1 takes nothing. +func (l *rateLimiter) takeN(key string, n int) (bool, time.Duration) { + need := float64(max(n, 0)) l.mu.Lock() defer l.mu.Unlock() now := l.now() @@ -52,16 +78,37 @@ func (l *rateLimiter) take(key string) (bool, time.Duration) { return false, time.Duration(1 / l.rate * float64(time.Second)) } } - b = &rlBucket{tokens: l.burst, last: now} + b = &rlBucket{tokens: l.burst, capTokens: l.capBurst, last: now} l.buckets[key] = b } - b.tokens = math.Min(l.burst, b.tokens+now.Sub(b.last).Seconds()*l.rate) + dt := now.Sub(b.last).Seconds() + b.tokens = math.Min(l.burst, b.tokens+dt*l.rate) + b.capTokens = math.Min(l.capBurst, b.capTokens+dt*l.capRate) b.last = now - if b.tokens >= 1 { - b.tokens-- + capped := l.capRate > 0 + if b.tokens >= need && (!capped || b.capTokens >= need) { + b.tokens -= need + if capped { + b.capTokens -= need + } return true, 0 } - return false, time.Duration((1 - b.tokens) / l.rate * float64(time.Second)) + wait := math.Max(0, (need-b.tokens)/l.rate) + if capped { + wait = math.Max(wait, (need-b.capTokens)/l.capRate) + } + return false, time.Duration(wait * float64(time.Second)) +} + +// refundN gives back n tokens taken from key, to both buckets of a capped +// limiter, never above either's size. A key with no bucket is a no-op. +func (l *rateLimiter) refundN(key string, n int) { + l.mu.Lock() + defer l.mu.Unlock() + if b := l.buckets[key]; b != nil && n > 0 { + b.tokens = math.Min(l.burst, b.tokens+float64(n)) + b.capTokens = math.Min(l.capBurst, b.capTokens+float64(n)) + } } // gc drops buckets that have refilled completely (they carry no state). @@ -71,10 +118,12 @@ func (l *rateLimiter) gc() { l.sweepLocked(l.now()) } -// sweepLocked deletes fully refilled buckets. The caller holds l.mu. +// sweepLocked deletes fully refilled buckets (both, when capped). The +// caller holds l.mu. func (l *rateLimiter) sweepLocked(now time.Time) { for k, b := range l.buckets { - if b.tokens+now.Sub(b.last).Seconds()*l.rate >= l.burst { + dt := now.Sub(b.last).Seconds() + if b.tokens+dt*l.rate >= l.burst && b.capTokens+dt*l.capRate >= l.capBurst { delete(l.buckets, k) } } diff --git a/cmd/server/auth_ratelimit_test.go b/cmd/server/auth_ratelimit_test.go index 6e7db12e6..8c7bc904c 100644 --- a/cmd/server/auth_ratelimit_test.go +++ b/cmd/server/auth_ratelimit_test.go @@ -66,6 +66,63 @@ func TestRateLimiterBucketCap(t *testing.T) { } } +// A capped limiter charges both buckets, all or nothing: the burst refills +// in seconds, the cap only over the hour. +func TestRateLimiterCapped(t *testing.T) { + now := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC) + l := newCappedRateLimiter(4, 10, time.Minute, 6, time.Hour) + l.now = func() time.Time { return now } + if ok, _ := l.takeN("k", 4); !ok { + t.Fatal("the burst refused") + } + if ok, wait := l.takeN("k", 1); ok || wait != 6*time.Second { + t.Fatalf("empty burst: ok=%v wait=%v, want one token in 6 s", ok, wait) + } + now = now.Add(time.Minute) // burst full again (4); cap 2 + 0.1 + // 0.9 cap tokens short at 6 an hour: 9 minutes. + if ok, wait := l.takeN("k", 3); ok || (wait-9*time.Minute).Abs() > time.Millisecond { + t.Fatalf("over the cap: ok=%v wait=%v, want 9m", ok, wait) + } + if ok, _ := l.takeN("k", 2); !ok { + t.Fatal("within both refused: the refusal took tokens") + } + l.refundN("k", 2) // 4 and 2.1 again + if ok, _ := l.takeN("k", 3); ok { + t.Fatal("refund gave the cap bucket more than was taken") + } + if ok, _ := l.takeN("k", 2); !ok { + t.Fatal("refund lost tokens") + } + l.refundN("k", 100) // never above either size: 4 and 6 + if ok, _ := l.takeN("k", 5); ok { + t.Fatal("refund raised the burst above its size") + } + if ok, _ := l.takeN("k", 4); !ok { + t.Fatal("refund did not fill the burst") + } + // A bucket is swept only once both have refilled. + now = now.Add(30 * time.Minute) + l.gc() + if l.buckets["k"] == nil { + t.Fatal("swept while the cap bucket was still refilling") + } + now = now.Add(time.Hour) + l.gc() + if len(l.buckets) != 0 { + t.Fatal("full buckets kept") + } + // An uncapped limiter is unchanged by the cap fields. + u := newRateLimiter(2, time.Minute) + u.now = l.now + u.refundN("x", 1) + if ok, _ := u.takeN("x", 2); !ok { + t.Fatal("uncapped limiter refused its burst") + } + if ok, _ := u.takeN("x", -3); !ok || u.buckets["x"].tokens != 0 { + t.Fatalf("a negative take added tokens: %v", u.buckets["x"].tokens) + } +} + func TestAllowKeysOnForwardedIP(t *testing.T) { a, _ := newTestAuthService(t) a.ipr.trustedProxies = parseCIDRList([]string{"10.0.0.0/8"}, "test") diff --git a/cmd/server/auth_routes.go b/cmd/server/auth_routes.go index e74dd3446..ce08aa785 100644 --- a/cmd/server/auth_routes.go +++ b/cmd/server/auth_routes.go @@ -43,6 +43,7 @@ func (s *Server) registerAuthRoutes(r *mux.Router) { r.HandleFunc("/api/account/companions", s.withUser(s.handleCompanionList)).Methods("GET") r.HandleFunc("/api/account/companions", s.withUser(s.handleCompanionLink)).Methods("POST") r.HandleFunc("/api/account/companions/{pubkey}", s.withUser(s.handleCompanionDelete)).Methods("DELETE") + s.registerRepeaterRoutes(r) r.HandleFunc("/api/account/export", s.withUser(s.handleAccountExport)).Methods("GET") r.HandleFunc("/api/admin/users", s.withAdmin(s.handleAdminUsers)).Methods("GET") r.HandleFunc("/api/admin/users/{id}", s.withAdmin(s.handleAdminUserDetail)).Methods("GET") diff --git a/cmd/server/auth_service.go b/cmd/server/auth_service.go index 2c79cdf79..94adc3780 100644 --- a/cmd/server/auth_service.go +++ b/cmd/server/auth_service.go @@ -25,6 +25,7 @@ type authService struct { hook *rateLimiter settingsPut *rateLimiter // PUT /api/account/settings, per user companion *rateLimiter // companion challenge + link, per IP and per user + repeater *rateLimiter // repeater edit, claim and unclaim, per user // approved is the snapshot of approved hashtag channel names, filled at // construction and reloaded from users.db after every proposal decision. @@ -62,6 +63,7 @@ func newAuthService(set *userMgmtSettings, st *users.Store, m mailer.Mailer) *au hook: newRateLimiter(600, time.Minute), settingsPut: newRateLimiter(60, time.Hour), companion: newRateLimiter(60, time.Hour), + repeater: newRateLimiter(120, time.Hour), stop: make(chan struct{}), now: time.Now, } @@ -202,6 +204,7 @@ func (a *authService) prune() { a.hook.gc() a.settingsPut.gc() a.companion.gc() + a.repeater.gc() } func (a *authService) isConfigAdmin(email string) bool { return a.set.adminEmails[email] } diff --git a/cmd/server/auth_types.go b/cmd/server/auth_types.go index 047d35a51..f5c8c98c2 100644 --- a/cmd/server/auth_types.go +++ b/cmd/server/auth_types.go @@ -179,8 +179,10 @@ type adminUserDetailJSON struct { User adminUserJSON `json:"user"` Sessions []sessionJSON `json:"sessions"` Companions []companionJSON `json:"companions"` - Mail []mailJSON `json:"mail"` - Audit []auditJSON `json:"audit"` + // RepeaterClaims lists every claim of the user, whatever the user's status. + RepeaterClaims []repeaterClaimRefJSON `json:"repeaterClaims"` + Mail []mailJSON `json:"mail"` + Audit []auditJSON `json:"audit"` } func rfc3339(t time.Time) string { return t.UTC().Format(time.RFC3339) } diff --git a/cmd/server/chunked_load.go b/cmd/server/chunked_load.go index b64e056f0..ae5345c70 100644 --- a/cmd/server/chunked_load.go +++ b/cmd/server/chunked_load.go @@ -436,12 +436,21 @@ func (s *PacketStore) LoadChunked(chunkSize int) error { // Acquire before opening the cursor: a feed waiting for the same // connection must never hold this gate while we hold its cursor. + // Held from the query to the end of the merge, it also keeps the + // poller from losing an observation committed after this chunk's + // snapshot: the poller reads its observation cursor bound before + // refreshAdvertEvidence, which waits here, so such an observation is + // either read after its transmission is merged or lies above the + // bound (see Poller.Start). s.advertEvidenceMu.Lock() rows, err := s.db.conn.Query(chunkSQL) if err != nil { s.advertEvidenceMu.Unlock() return fmt.Errorf("chunk %d: query: %w", chunkIdx, err) } + if s.chunkQueriedHook != nil { + s.chunkQueriedHook(chunkIdx + 1) + } chunkTxCount, lastID, err := s.scanAndMergeChunk(rows, relayPM, &coldLoadAmbiguousHopsSkipped) rows.Close() diff --git a/cmd/server/client_limit.go b/cmd/server/client_limit.go new file mode 100644 index 000000000..e173c6152 --- /dev/null +++ b/cmd/server/client_limit.go @@ -0,0 +1,109 @@ +package main + +// Per-client token bucket for public endpoints whose requests cost terrain +// tile downloads or heavy compute (/api/elevation/profile, /api/planner/*). +// Clients are told apart by wsLimiter.clientIPRightmost: X-Forwarded-For is +// believed only from webSocket.trustedProxies, and is read from the right, so +// the client is the last hop no trusted proxy vouches for and a forged +// leftmost entry buys nothing (these limits protect an upstream quota). +// Operators behind a CDN must list the CDN's ranges in +// webSocket.trustedProxies, or every client behind it looks like the CDN. +// When clients cannot be told apart (a local reverse proxy that is not in +// webSocket.trustedProxies, the shipped default), the per-client limit is +// skipped, as /ws and the login limiter skip theirs: one bucket for the whole +// site would refuse real visitors. The global budgets still apply (terrain +// downloads: srtmBudgetFor; planner jobs: plannerGlobalJobsPerMin), and a +// one-time warning tells the operator what to configure. + +import ( + "log" + "math" + "net/http" + "strconv" + "sync" + "time" +) + +// clientLimiter charges tokens to the caller's bucket. A nil limiter, ipr or +// rl disables the limit (tests). +type clientLimiter struct { + ipr *wsLimiter + rl *rateLimiter + warn sync.Once + // tag is the log prefix ("los"); what names the limit in the warning + // ("terrain tile"). + tag, what string +} + +// clientSharedKey names, in logs, the clients that cannot be told apart. It +// is never a bucket: those clients are not charged. +const clientSharedKey = "shared" + +// clientKey is r's bucket, the client IP, and whether it identifies a +// client. When it does not, the key is clientSharedKey, nothing is charged +// to it and the one-time warning is logged. +func (c *clientLimiter) clientKey(r *http.Request) (key string, distinct bool) { + if c.ipr == nil { + return clientSharedKey, false + } + ip, distinct := c.ipr.clientIPRightmost(r) + if distinct && ip != nil { + return ip.String(), true + } + c.warn.Do(func() { + log.Printf("[%s] WARNING: clients cannot be told apart (requests arrive from %v), "+ + "so the per-client %s rate limit is off and only the global budget applies. "+ + "Set webSocket.trustedProxies to your reverse proxy's address for per-client limits.", c.tag, ip, c.what) + }) + return clientSharedKey, false +} + +// take consumes one token from r's bucket. When none is left it reports how +// long until the next one. It writes nothing and takes no lock but the +// bucket map's, so callers may hold their own locks around it. +func (c *clientLimiter) take(r *http.Request) (bool, time.Duration) { + return c.takeN(r, 1) +} + +// takeN consumes n tokens from r's bucket, all or nothing; on refusal it +// reports how long until n are available and takes none. n < 1 always +// succeeds, and leaves no bucket behind, as does a client that cannot be +// told apart from the others (clientKey). +func (c *clientLimiter) takeN(r *http.Request, n int) (bool, time.Duration) { + if c.off() || n < 1 { + return true, 0 + } + key, distinct := c.clientKey(r) + if !distinct { + return true, 0 + } + return c.rl.takeN(key, n) +} + +// refundN gives back n tokens takeN just took from r's bucket. +func (c *clientLimiter) refundN(r *http.Request, n int) { + if c.off() || n < 1 { + return + } + if key, distinct := c.clientKey(r); distinct { + c.rl.refundN(key, n) + } +} + +func (c *clientLimiter) off() bool { return c == nil || c.ipr == nil || c.rl == nil } + +// retryAfterSecs rounds wait up to whole seconds, at least 1. +func retryAfterSecs(wait time.Duration) int { + secs := int(math.Ceil(wait.Seconds())) + if secs < 1 { + secs = 1 + } + return secs +} + +// writeRateLimited answers 429 "rate limited" with a Retry-After of at least +// 1 s. +func writeRateLimited(w http.ResponseWriter, wait time.Duration) { + w.Header().Set("Retry-After", strconv.Itoa(retryAfterSecs(wait))) + writeError(w, http.StatusTooManyRequests, "rate limited") +} diff --git a/cmd/server/client_limit_test.go b/cmd/server/client_limit_test.go new file mode 100644 index 000000000..afa9b102a --- /dev/null +++ b/cmd/server/client_limit_test.go @@ -0,0 +1,131 @@ +package main + +import ( + "fmt" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func xffReq(peer string, xff ...string) *http.Request { + r := httptest.NewRequest("GET", "/api/planner/x", nil) + r.RemoteAddr = peer + for _, v := range xff { + r.Header.Add("X-Forwarded-For", v) + } + return r +} + +func TestClientIPRightmost(t *testing.T) { + trusted := []string{"10.0.0.0/8", "2001:db8:ffff::/48"} + cases := []struct { + name string + trusted []string + peer string + xff []string + want string + wantDistinct bool + wantLeftmost string // what /ws resolves for the same request + }{ + {"single proxy", trusted, "10.0.0.2:1", []string{"203.0.113.20"}, "203.0.113.20", true, "203.0.113.20"}, + {"chain of two trusted proxies", trusted, "10.0.0.2:1", []string{"203.0.113.20, 10.0.0.9"}, "203.0.113.20", true, "203.0.113.20"}, + {"spoofed leftmost", trusted, "10.0.0.2:1", []string{"1.2.3.4, 203.0.113.20"}, "203.0.113.20", true, "1.2.3.4"}, + {"spoofed leftmost across header lines", trusted, "10.0.0.2:1", []string{"1.2.3.4", "203.0.113.20"}, "203.0.113.20", true, "1.2.3.4"}, + {"spoofed leftmost behind two proxies", trusted, "10.0.0.2:1", []string{"1.2.3.4, 203.0.113.20, 10.0.0.9"}, "203.0.113.20", true, "1.2.3.4"}, + {"all entries trusted: leftmost", trusted, "10.0.0.2:1", []string{"10.0.0.5, 10.0.0.9"}, "10.0.0.5", true, "10.0.0.5"}, + {"no header", trusted, "10.0.0.2:1", nil, "10.0.0.2", true, "10.0.0.2"}, + {"garbage only", trusted, "10.0.0.2:1", []string{"not-an-ip"}, "10.0.0.2", true, "10.0.0.2"}, + {"garbage rightmost", trusted, "10.0.0.2:1", []string{"203.0.113.20, junk"}, "10.0.0.2", true, "203.0.113.20"}, + {"garbage leftmost is never reached", trusted, "10.0.0.2:1", []string{"junk, 203.0.113.20"}, "203.0.113.20", true, "10.0.0.2"}, + {"ipv6 client", trusted, "10.0.0.2:1", []string{"2001:db8::7"}, "2001:db8::", true, "2001:db8::7"}, + {"ipv6 same /64, other host", trusted, "10.0.0.2:1", []string{"2001:db8:0:0:aaaa::9"}, "2001:db8::", true, "2001:db8::aaaa:0:0:9"}, + {"ipv6 different /64", trusted, "10.0.0.2:1", []string{"2001:db8:0:1::7"}, "2001:db8:0:1::", true, "2001:db8:0:1::7"}, + {"ipv4 with port", trusted, "10.0.0.2:1", []string{"1.2.3.4:5678"}, "1.2.3.4", true, "10.0.0.2"}, + {"ipv6 with port", trusted, "10.0.0.2:1", []string{"[2001:db8::1]:443"}, "2001:db8::", true, "10.0.0.2"}, + {"bracketed bare ipv6", trusted, "10.0.0.2:1", []string{"[2001:db8::1]"}, "2001:db8::", true, "10.0.0.2"}, + {"port on trusted hop still skipped", trusted, "10.0.0.2:1", []string{"203.0.113.20, 10.0.0.9:4000"}, "203.0.113.20", true, "203.0.113.20"}, + {"spoofed leftmost beside ported hop", trusted, "10.0.0.2:1", []string{"1.2.3.4, 203.0.113.20:99"}, "203.0.113.20", true, "1.2.3.4"}, + {"ipv6 proxy chain", trusted, "[2001:db8:ffff::1]:1", []string{"198.51.100.4, 2001:db8:ffff::2"}, "198.51.100.4", true, "198.51.100.4"}, + {"untrusted peer ignores header", trusted, "203.0.113.30:1", []string{"198.51.100.1"}, "203.0.113.30", true, "203.0.113.30"}, + {"private peer, no trusted proxies: not distinct", nil, "10.0.0.2:1", []string{"203.0.113.20"}, "10.0.0.2", false, "10.0.0.2"}, + {"loopback peer, no trusted proxies: not distinct", nil, "127.0.0.1:1", []string{"203.0.113.20"}, "127.0.0.1", false, "127.0.0.1"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + l := &wsLimiter{trustedProxies: parseCIDRList(tc.trusted, "test")} + ip, distinct := l.clientIPRightmost(xffReq(tc.peer, tc.xff...)) + if ip == nil || ip.String() != tc.want || distinct != tc.wantDistinct { + t.Errorf("rightmost = %v distinct=%v, want %s distinct=%v", ip, distinct, tc.want, tc.wantDistinct) + } + // /ws keeps resolving the leftmost entry. + ws, _ := l.clientIP(xffReq(tc.peer, tc.xff...)) + if ws == nil || ws.String() != tc.wantLeftmost { + t.Errorf("/ws clientIP = %v, want %s", ws, tc.wantLeftmost) + } + }) + } +} + +func TestClientKeyMasksIPv6To64(t *testing.T) { + c := &clientLimiter{ipr: &wsLimiter{trustedProxies: parseCIDRList([]string{"10.0.0.0/8"}, "test")}, tag: "t", what: "w"} + a, _ := c.clientKey(xffReq("10.0.0.2:1", "2001:db8:1:2::1")) + b, _ := c.clientKey(xffReq("10.0.0.2:1", "2001:db8:1:2:ffff:ffff:ffff:ffff")) + d, _ := c.clientKey(xffReq("10.0.0.2:1", "2001:db8:1:3::1")) + if a != b { + t.Errorf("same /64 gave different keys %q, %q", a, b) + } + if a == d { + t.Errorf("different /64 shared key %q", a) + } + // Untrusted IPv6 peer is masked too; IPv4-mapped stays an IPv4 key. + if k, _ := c.clientKey(xffReq("[2001:db8:9:9::5]:1")); k != "2001:db8:9:9::" { + t.Errorf("peer key = %q", k) + } + if k, _ := c.clientKey(xffReq("10.0.0.2:1", "::ffff:1.2.3.4")); k != "1.2.3.4" { + t.Errorf("mapped key = %q", k) + } +} + +func TestClientLimiterKeysOnRightmostUntrusted(t *testing.T) { + c := &clientLimiter{ipr: &wsLimiter{trustedProxies: parseCIDRList([]string{"10.0.0.0/8"}, "test")}, tag: "t", what: "w"} + // A client rotating its own leftmost entry must stay in one bucket. + a, _ := c.clientKey(xffReq("10.0.0.2:1", "1.1.1.1, 203.0.113.20")) + b, _ := c.clientKey(xffReq("10.0.0.2:1", "2.2.2.2, 203.0.113.20")) + if a != "203.0.113.20" || a != b { + t.Errorf("keys %q, %q: want both 203.0.113.20", a, b) + } +} + +// Without webSocket.trustedProxies a local reverse proxy hides every client +// behind one address (the bundled Caddyfile on a default install). One bucket +// for the whole site would refuse real visitors, so nothing is charged; the +// global budgets still apply (review #2391). +func TestClientLimiterSkipsClientsItCannotTellApart(t *testing.T) { + c := &clientLimiter{ipr: &wsLimiter{}, rl: newRateLimiter(2, time.Hour), tag: "t", what: "w"} + for i := 0; i < 10; i++ { + r := xffReq("127.0.0.1:1", fmt.Sprintf("198.51.100.%d", i)) + if key, distinct := c.clientKey(r); distinct || key != clientSharedKey { + t.Fatalf("clientKey = %q, %v: a loopback peer without trustedProxies is not a client", key, distinct) + } + if ok, _ := c.takeN(r, 2); !ok { + t.Fatalf("request %d limited: every visitor shares one bucket", i) + } + c.refundN(r, 2) + } + if n := len(c.rl.buckets); n != 0 { + t.Fatalf("%d buckets for clients that cannot be told apart", n) + } + // Listing the proxy turns the per-client limit on. + c.ipr.trustedProxies = parseCIDRList([]string{"127.0.0.1"}, "test") + r := xffReq("127.0.0.1:1", "198.51.100.1") + if ok, _ := c.takeN(r, 2); !ok { + t.Fatal("first request of a distinct client limited") + } + if ok, _ := c.takeN(r, 1); ok { + t.Fatal("a distinct client over its limit was not limited") + } + if ok, _ := c.takeN(xffReq("127.0.0.1:1", "198.51.100.2"), 2); !ok { + t.Fatal("another client was charged for the first one") + } +} diff --git a/cmd/server/client_log_id.go b/cmd/server/client_log_id.go new file mode 100644 index 000000000..fe4b6405e --- /dev/null +++ b/cmd/server/client_log_id.go @@ -0,0 +1,31 @@ +package main + +import ( + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "encoding/hex" +) + +// clientLogKey keys clientLogID. It is random per process, so a client's ID is +// stable within a run (an operator can correlate its requests) but cannot be +// reversed or linked across restarts. +var clientLogKey = func() []byte { + k := make([]byte, 32) + if _, err := rand.Read(k); err != nil { + panic("client log key: " + err.Error()) + } + return k +}() + +// clientLogID names a client in logs without recording its IP: the first 12 +// hex chars of HMAC-SHA256(clientLogKey, ip). clientSharedKey has no IP to +// hide and logs as itself. +func clientLogID(ip string) string { + if ip == clientSharedKey { + return clientSharedKey + } + m := hmac.New(sha256.New, clientLogKey) + m.Write([]byte(ip)) + return hex.EncodeToString(m.Sum(nil)[:6]) +} diff --git a/cmd/server/client_log_id_test.go b/cmd/server/client_log_id_test.go new file mode 100644 index 000000000..9658d9c5a --- /dev/null +++ b/cmd/server/client_log_id_test.go @@ -0,0 +1,84 @@ +package main + +import ( + "bytes" + "log" + "net/http" + "strings" + "sync" + "testing" + "time" +) + +func TestClientLogID(t *testing.T) { + a, b := "198.51.100.20", "198.51.100.21" + ida, idb := clientLogID(a), clientLogID(b) + if ida != clientLogID(a) { + t.Error("ID must be stable within a process") + } + if ida == idb { + t.Error("different IPs must get different IDs") + } + if len(ida) != 12 { + t.Errorf("len = %d, want 12 hex chars", len(ida)) + } + for ip, id := range map[string]string{a: ida, b: idb, "2001:db8::7": clientLogID("2001:db8::7")} { + if strings.Contains(id, ip) || strings.Trim(id, "0123456789abcdef") != "" { + t.Errorf("ID %q for %s must be bare hex with no IP in it", id, ip) + } + } + if clientLogID(clientSharedKey) != "shared" { + t.Error("clients that cannot be told apart must log as shared") + } +} + +type lockedBuf struct { + mu sync.Mutex + b bytes.Buffer +} + +func (l *lockedBuf) Write(p []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.b.Write(p) +} + +func (l *lockedBuf) String() string { + l.mu.Lock() + defer l.mu.Unlock() + return l.b.String() +} + +func TestPlannerJobLogHasNoClientIP(t *testing.T) { + h := newPlannerHarness(t) + h.p.fastWait = plannerFastWait + var buf lockedBuf + prev := log.Writer() + log.SetOutput(&buf) + defer log.SetOutput(prev) + + ip := "198.51.100.77" + if w := h.get("/api/planner/profile?pts=30.1,-97.1,30.2,-97.0", ip); w.Code != http.StatusOK { + t.Fatalf("job: %d %s", w.Code, w.Body.String()) + } + var line string + for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(10 * time.Millisecond) { + for _, l := range strings.Split(buf.String(), "\n") { + if strings.Contains(l, "[planner]") && strings.Contains(l, "client=") && strings.Contains(l, "outcome=") { + line = l + } + } + if line != "" { + break + } + } + if line == "" { + t.Fatalf("no planner job log line; log: %q", buf.String()) + } + if strings.Contains(buf.String(), ip) { + t.Errorf("log contains the client IP: %q", buf.String()) + } + if !strings.Contains(line, "client="+clientLogID(ip)) { + t.Errorf("line %q lacks client=%s", line, clientLogID(ip)) + } +} diff --git a/cmd/server/config.go b/cmd/server/config.go index 2cb02687f..9fa6b0b9c 100644 --- a/cmd/server/config.go +++ b/cmd/server/config.go @@ -236,6 +236,18 @@ type Config struct { // LoRa RF parameters per node from the MeshCore map (issue #1268). // OPT-IN: nil or an empty nodesUrl starts no fetch. RfParams *RfParamsConfig `json:"rfParams,omitempty"` + + // Radio line-of-sight on the map's packet route view (los_config.go). + // OPT-IN: nil or enabled=false fetches no elevation data. + LOS *LOSConfig `json:"los,omitempty"` + + // Repeater planner (#/tools/planner, planner_types.go). OPT-IN: nil or + // enabled=false fetches no terrain tiles and /api/planner/* answers 404. + Planner *PlannerConfig `json:"planner,omitempty"` + + // SRTM terrain tiles shared by route LOS and the planner + // (terrain_config.go). Read only while one of them is enabled. + Terrain *TerrainConfig `json:"terrain,omitempty"` } // CustomizerConfig holds operator-side knobs for the in-app customizer modal. @@ -601,6 +613,12 @@ type WebSocketConfig struct { // X-Forwarded-For may be believed. REQUIRED for the limits to do anything // behind nginx/Caddy/Traefik/ingress: without it every visitor shares the // proxy's address, so the limits are skipped and a warning is logged. + // /ws takes the leftmost X-Forwarded-For entry; the terrain-backed + // /api/elevation/profile and /api/planner/* limits take the rightmost + // entry that is not a trusted proxy, so behind a CDN list the CDN's + // ranges here too, or every client looks like the CDN. + // A listed proxy MUST append to X-Forwarded-For (nginx $proxy_add_x_forwarded_for); + // behind a CDN, anyone sending from inside its ranges can choose the hop used. // Never list an address you do not control; anyone reaching the server // from a trusted address can name any client IP they like. TrustedProxies []string `json:"trustedProxies,omitempty"` diff --git a/cmd/server/db.go b/cmd/server/db.go index ae296da29..d05022037 100644 --- a/cmd/server/db.go +++ b/cmd/server/db.go @@ -36,12 +36,18 @@ const routeTypeTransportSQL = "route_type IN (0, 3)" // per MeshCore protocol (#1838). const routeTypeNonTransportSQL = "route_type IN (1, 2)" +// contentHashMigrationName is the ingestor's async migration that rewrites +// pre-#787 content hashes (cmd/ingestor/hash_migrate.go). The server only reads +// its status: the migration writes, so it cannot run here (#1856). +const contentHashMigrationName = "content_hash_payload_bits_v1" + // DB wraps a read-only connection to the MeshCore SQLite database. type DB struct { advertEvidenceTable atomic.Bool txRewriteFeedTable atomic.Bool // tx_rewrite_feed present (#2107); re-probed while absent clientNodeNamesTable atomic.Bool // client_node_names present; re-probed while absent (clientNodeNamesPresent) inactiveNodesTable atomic.Bool // inactive_nodes present; re-probed while absent (clientNameHeard) + hashMigrationDone atomic.Bool // ingestor's content-hash migration seen done; latched (hashMigrationComplete) advertEvidenceReadHook func() // test-only: immediately before a bulk mask query conn *sql.DB path string // filesystem path to the database file @@ -203,6 +209,26 @@ func (db *DB) stmtQueryRow(stmt *sql.Stmt, fallbackSQL string, args ...interface // prepareStatements creates prepared statements for frequently-called queries. // SQLite compiles and caches the query plan once, avoiding re-parsing per request. +// hashMigrationComplete reports whether the ingestor has finished the +// content-hash migration, for /api/stats.hashMigrationComplete. A missing +// _async_migrations table or row, or any status other than done, is false: +// the migration is not proven finished. done is final (the ingestor never +// re-runs a done migration), so it is latched and the query stops. +func (db *DB) hashMigrationComplete() bool { + if db.hashMigrationDone.Load() { + return true + } + var status string + if err := db.conn.QueryRow(`SELECT status FROM _async_migrations WHERE name = ?`, contentHashMigrationName).Scan(&status); err != nil { + return false + } + if status != "done" { + return false + } + db.hashMigrationDone.Store(true) + return true +} + func (db *DB) prepareStatements() error { var err error prepare := func(query string) *sql.Stmt { @@ -2509,6 +2535,24 @@ func (db *DB) GetMaxTransmissionID() int { return maxID } +// highWaterMarks reads MAX(id) of transmissions and observations. Unlike +// GetMaxTransmissionID it reports failure: a 0 from a failed query would +// otherwise replay the whole table. ok is false without a connection. +func (db *DB) highWaterMarks() (txMax, obsMax int, ok bool) { + if db == nil || db.conn == nil { + return 0, 0, false + } + if err := db.conn.QueryRow("SELECT COALESCE(MAX(id), 0) FROM transmissions").Scan(&txMax); err != nil { + log.Printf("[store] startup high-water mark (transmissions): %v", err) + return 0, 0, false + } + if err := db.conn.QueryRow("SELECT COALESCE(MAX(id), 0) FROM observations").Scan(&obsMax); err != nil { + log.Printf("[store] startup high-water mark (observations): %v", err) + return 0, 0, false + } + return txMax, obsMax, true +} + // GetMaxObservationID returns the current max observation ID for polling. func (db *DB) GetMaxObservationID() int { var maxID int @@ -3333,7 +3377,7 @@ func (db *DB) GetScopeStats(window string) (*ScopeStatsResponse, error) { if err := row.Scan( &resp.Summary.TransportTotal, &resp.Summary.Scoped, - &resp.Summary.Unscoped, + &resp.Summary.UnscopedTransport, &resp.Summary.UnknownScope, ); err != nil { return nil, fmt.Errorf("scope summary query: %w", err) @@ -3343,14 +3387,19 @@ func (db *DB) GetScopeStats(window string) (*ScopeStatsResponse, error) { // transport_code_1 per MeshCore protocol, so they are inherently unscoped. // Fold their count into Summary.Unscoped so the analytics denominator // reflects total-observed-transmissions rather than only transport-eligible. - var nonTransportUnscoped int + // #2364: keep the per-route split and report Total so the summary adds up. + // Same single scan as before; the CASE split costs nothing extra. if err := db.conn.QueryRow(` - SELECT COUNT(*) FROM transmissions + SELECT + COALESCE(SUM(CASE WHEN route_type = 1 THEN 1 ELSE 0 END), 0), + COALESCE(SUM(CASE WHEN route_type = 2 THEN 1 ELSE 0 END), 0) + FROM transmissions WHERE `+routeTypeNonTransportSQL+` AND first_seen >= ? - `, since).Scan(&nonTransportUnscoped); err != nil { + `, since).Scan(&resp.Summary.UnscopedFlood, &resp.Summary.UnscopedDirect); err != nil { return nil, fmt.Errorf("scope non-transport count query: %w", err) } - resp.Summary.Unscoped += nonTransportUnscoped + resp.Summary.Unscoped = resp.Summary.UnscopedTransport + resp.Summary.UnscopedFlood + resp.Summary.UnscopedDirect + resp.Summary.Total = resp.Summary.Scoped + resp.Summary.Unscoped // Per-region counts (named regions only) rows, err := db.conn.Query(scopeStatsByRegionQuery, since) diff --git a/cmd/server/db_test.go b/cmd/server/db_test.go index 65fe6a822..0a3f68d62 100644 --- a/cmd/server/db_test.go +++ b/cmd/server/db_test.go @@ -2310,6 +2310,24 @@ func TestGetScopeStats(t *testing.T) { if stats.Summary.UnknownScope != 1 { t.Errorf("UnknownScope = %d, want 1", stats.Summary.UnknownScope) } + // #2364: per-route split of Unscoped, and a Total the summary adds up to. + s := stats.Summary + if s.UnscopedTransport != 1 || s.UnscopedFlood != 1 || s.UnscopedDirect != 1 { + t.Errorf("unscoped split = transport %d / flood %d / direct %d, want 1/1/1", + s.UnscopedTransport, s.UnscopedFlood, s.UnscopedDirect) + } + if s.Total != 5 { + t.Errorf("Total = %d, want 5 (all routes)", s.Total) + } + if s.TransportTotal != s.Scoped+s.UnscopedTransport { + t.Errorf("transportTotal %d != scoped %d + unscopedTransport %d", s.TransportTotal, s.Scoped, s.UnscopedTransport) + } + if s.Unscoped != s.UnscopedTransport+s.UnscopedFlood+s.UnscopedDirect { + t.Errorf("unscoped %d != sum of its route split", s.Unscoped) + } + if s.Total != s.Scoped+s.Unscoped { + t.Errorf("total %d != scoped %d + unscoped %d", s.Total, s.Scoped, s.Unscoped) + } if len(stats.ByRegion) != 1 || stats.ByRegion[0].Name != "#belgium" || stats.ByRegion[0].Count != 1 { t.Errorf("ByRegion = %+v, want [{#belgium 1}]", stats.ByRegion) } diff --git a/cmd/server/distance_ownership_bench_test.go b/cmd/server/distance_ownership_bench_test.go new file mode 100644 index 000000000..bd309f72c --- /dev/null +++ b/cmd/server/distance_ownership_bench_test.go @@ -0,0 +1,54 @@ +package main + +import ( + "fmt" + "testing" + "time" +) + +// Exercise the real reader and batch path-update entry points with 10,000 +// transmissions, 30,000 hop records and 10,000 path records. Setup is excluded. +func BenchmarkDistanceOwnership(b *testing.B) { + for _, operation := range []string{"analytics-read", "path-update"} { + b.Run(operation, func(b *testing.B) { + s := NewPacketStore(nil, nil) + nodes := []nodeInfo{ + {PublicKey: "aa", Name: "A", Role: "repeater", HasGPS: true, Lat: 1, Lon: 1}, + {PublicKey: "bb", Name: "B", Role: "repeater", HasGPS: true, Lat: 1, Lon: 1.01}, + {PublicKey: "cc", Name: "C", Role: "repeater", HasGPS: true, Lat: 1, Lon: 1.02}, + {PublicKey: "dd", Name: "D", Role: "repeater", HasGPS: true, Lat: 1, Lon: 1.03}, + } + s.nodeCache, s.nodePM, s.nodeCacheTime = nodes, buildPrefixMap(nodes), time.Now() + const count = 10000 + s.distHops = make([]distHopRecord, 0, count*3) + s.distPaths = make([]distPathRecord, 0, count) + stamp := time.Now().UTC().Format(time.RFC3339) + for i := 0; i < count; i++ { + tx := &StoreTx{ID: i + 1, Hash: fmt.Sprintf("synthetic-%d", i), FirstSeen: stamp, + PathJSON: `["aa","bb","cc","dd"]`, parsedPath: []string{"aa", "bb", "cc", "dd"}, pathParsed: true} + s.packets = append(s.packets, tx) + details := make([]distHopDetail, 3) + for j := range details { + a, z := nodes[j], nodes[j+1] + s.distHops = append(s.distHops, distHopRecord{FromName: a.Name, FromPk: a.PublicKey, + ToName: z.Name, ToPk: z.PublicKey, Dist: 1, Type: "R↔R", Hash: tx.Hash, Timestamp: stamp, tx: tx}) + details[j] = distHopDetail{FromName: a.Name, FromPk: a.PublicKey, ToName: z.Name, ToPk: z.PublicKey, Dist: 1} + } + s.distPaths = append(s.distPaths, distPathRecord{Hash: tx.Hash, TotalDist: 3, HopCount: 3, + Timestamp: stamp, Hops: details, tx: tx}) + } + changed := s.packets[:1] + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + if operation == "analytics-read" { + s.computeAnalyticsDistance("", "") + } else { + s.mu.Lock() + s.updateDistanceIndexForTxs(changed) + s.mu.Unlock() + } + } + }) + } +} diff --git a/cmd/server/elevation.go b/cmd/server/elevation.go new file mode 100644 index 000000000..2ce548b1a --- /dev/null +++ b/cmd/server/elevation.go @@ -0,0 +1,394 @@ +package main + +// GET /api/elevation/profile — terrain elevation along consecutive legs of a +// route, for the map's line-of-sight view (los_config.go). The terrain is +// the planner's: the same SRTM source (terrain_config.go) and the same +// sampling (sampleLegProfile), so a leg gets the same verdict in both views. +// +// CONTRACT (public/route-los.js depends on it): +// +// GET /api/elevation/profile?pts=lat1,lon1,lat2,lon2[,lat3,lon3...] +// +// pts flat comma list of 2..losMaxPoints points (even count of +// numbers), lat in [-90,90], lon in [-180,180]. +// 200 ElevationProfileResponse; legs[i] is pts[i] → pts[i+1]. +// 202 PlannerJobStatus{"loading_terrain", progress, retry_after_s} +// + Retry-After, no-store: some of the request's tiles are still +// downloading after losTileWait. The downloads carry on; the +// client re-polls the same URL. +// 400 writeError: bad/missing pts, odd count, out of range, too many, +// query over 2048 bytes. +// 404 writeError "los disabled" when los.enabled is false. +// 429 writeError "rate limited" + Retry-After (seconds): the request +// would start more tile downloads than this client has tokens +// left in the terrain budget it shares with the planner +// (newTerrainClientLimiter). A request that starts none is never +// limited. +// +// Points rule: every point must be the position of a known node (GPS set, +// not 0,0) that /api/nodes shows (node_visibility.go), matched at 5 +// decimals. This bounds the tiles a client can make the server download to +// those under real node pairs. +// +// Per-leg failures never fail the request: the leg carries an error code +// and no elev_m. Codes, checked in this order: "too_long" (leg > +// losMaxLegKm), "unknown_point" (an endpoint is not a known node), +// "too_many_tiles" (the leg's tiles would take the request past +// losMaxTiles), "upstream" (a tile could not be loaded: downloads paused, +// over budget or failed), "no_terrain" (a sample lies in a tile without +// data). Cache-Control is public, max-age=86400 when every leg is OK or +// too_long, else no-store. + +import ( + "fmt" + "maps" + "math" + "net/http" + "strconv" + "strings" + "sync" + "time" +) + +// ElevationProfileResponse is the /api/elevation/profile body. +type ElevationProfileResponse struct { + // Source attributes the terrain: "SRTM (AWS Open Data)" for the default + // tiles, else "SRTM ()" (terrainSourceName). The planner + // reports the same string. + Source string `json:"source"` + Legs []ElevationLeg `json:"legs"` +} + +// ElevationLeg is one leg of the requested route. +type ElevationLeg struct { + // Great-circle (haversine, R=6371 km) length of the leg. + DistanceKm float64 `json:"distance_km"` + // ElevM holds terrain heights in metres (0.1 m steps), from the leg's + // first point to its second, at evenly spaced great-circle fractions + // t = i/(len-1). The count grows with the leg: planProfileSamples, about + // one sample per 90 m, 64 to 600. Omitted when Error is set. + ElevM []float64 `json:"elev_m,omitempty"` + // Error codes: see the file comment. + Error string `json:"error,omitempty"` +} + +// Leg error codes. The ones the planner profile shares mean the same there. +const ( + elevErrTooLong = plannerErrTooLong + elevErrUnknownPoint = "unknown_point" + elevErrTooManyTiles = plannerErrTooManyTiles + elevErrUpstream = "upstream" + elevErrNoTerrain = plannerErrNoTerrain +) + +const ( + elevMaxRawQuery = 2048 + elevNodeSetTTL = 60 * time.Second + elevCacheControl = "public, max-age=86400" +) + +func (s *Server) handleElevationProfile(w http.ResponseWriter, r *http.Request) { + if !s.cfg.LOS.enabled() || s.elevation == nil { + writeError(w, http.StatusNotFound, "los disabled") + return + } + if len(r.URL.RawQuery) > elevMaxRawQuery { + writeError(w, http.StatusBadRequest, "pts too long") + return + } + pts, msg := parseElevationPts(r.URL.Query().Get("pts")) + if msg != "" { + writeError(w, http.StatusBadRequest, msg) + return + } + s.elevation.serve(w, r, pts) +} + +// serve answers a validated request. It waits up to e.wait for the tiles it +// needs, then answers 200, or 202 while some are still downloading. The +// client is charged one token per download the request starts, all or +// nothing, in the step that starts them (srtmSource.tiles), so requests that +// arrive together pay for a tile once; resident tiles, tiles already downloading +// (another request's, or the planner's) and tiles the download budget has no +// room for cost nothing, so a poll that only waits is free. The legs on +// refused tiles answer upstream; the rest are answered. +func (e *elevationService) serve(w http.ResponseWriter, r *http.Request, pts []geoPoint) { + legs, keys := e.plan(pts) + var retry time.Duration + ts, ok := e.src.tiles(keys, func(starts int) bool { + var ok bool + ok, retry = e.downloads.takeN(r, starts) + return ok + }) + if !ok { + writeRateLimited(w, retry) + return + } + failed := make(map[srtmKey]bool, len(ts.refused)) + for _, k := range ts.refused { + failed[k] = true + } + if len(ts.need) > 0 { + got, bad := e.src.await(r.Context(), ts.need, e.wait) + maps.Copy(ts.grids, got) + maps.Copy(failed, bad) + if len(ts.grids)+len(failed) < len(keys) { + writePlannerStatus(w, PlannerJobStatus{ + State: plannerStateNames[plannerStateTerrain], + Progress: math.Round(float64(len(ts.grids))/float64(len(keys))*100) / 100, + RetryAfterS: losPollAfterS, + }) + return + } + } + view := srtmTileView(ts.grids) + out := ElevationProfileResponse{Source: e.src.source, Legs: make([]ElevationLeg, len(legs))} + cc := elevCacheControl + for i, l := range legs { + out.Legs[i] = l.res + res := &out.Legs[i] + if res.Error == "" { + if anyTileIn(l.tiles, failed) { + res.Error = elevErrUpstream + } else if elev, ok := sampleLegProfile(view, l.a, l.b); ok { + res.ElevM = elev + } else { + res.Error = elevErrNoTerrain + } + } + if res.Error != "" && res.Error != elevErrTooLong { + cc = "no-store" + } + } + w.Header().Set("Cache-Control", cc) + writeJSON(w, out) +} + +// anyTileIn reports whether any of keys is in set. +func anyTileIn(keys []srtmKey, set map[srtmKey]bool) bool { + for _, k := range keys { + if set[k] { + return true + } + } + return false +} + +// parseElevationPts validates the flat "lat,lon,lat,lon..." list. The second +// return value is a 400 message, empty when valid. +func parseElevationPts(raw string) ([]geoPoint, string) { + if raw == "" { + return nil, "pts required" + } + tooMany := fmt.Sprintf("pts must hold 2 to %d points", losMaxPoints) + if strings.Count(raw, ",") > 2*losMaxPoints-1 { + return nil, tooMany + } + parts := strings.SplitN(raw, ",", 2*losMaxPoints+1) + if len(parts)%2 != 0 { + return nil, "pts must hold lat,lon pairs" + } + n := len(parts) / 2 + if n < 2 || n > losMaxPoints { + return nil, tooMany + } + pts := make([]geoPoint, n) + for i := 0; i < n; i++ { + lat, err1 := strconv.ParseFloat(strings.TrimSpace(parts[2*i]), 64) + lon, err2 := strconv.ParseFloat(strings.TrimSpace(parts[2*i+1]), 64) + if err1 != nil || err2 != nil || math.IsNaN(lat) || math.IsInf(lat, 0) || math.IsNaN(lon) || math.IsInf(lon, 0) { + return nil, "pts contains an invalid number" + } + if lat < -90 || lat > 90 || lon < -180 || lon > 180 { + return nil, "pts out of range" + } + pts[i] = geoPoint{lat, lon} + } + return pts, "" +} + +// legTiles lists, first seen first, the tiles sampleLegProfile reads for +// leg a→b: the one each of legSamplePoints falls in, as srtmTileView looks +// it up (srtmKeyOf). Only these load, not the leg's bounding box: a 300 km +// diagonal's box holds dozens of tiles, its samples about 10. +func legTiles(a, b geoPoint) []srtmKey { + var out []srtmKey + seen := map[srtmKey]bool{} + for _, p := range legSamplePoints(a, b) { + if k := srtmKeyOf(p.Lat, p.Lon); !seen[k] { + seen[k] = true + out = append(out, k) + } + } + return out +} + +// elevVisibility is the node-hiding rule /api/nodes applies; *Server +// implements it (node_visibility.go). +type elevVisibility interface { + // nodeVisibilityGen changes whenever the rule does. + nodeVisibilityGen() string + // visibleNodeInfo returns the current rule; called once per set rebuild. + visibleNodeInfo() func(n *nodeInfo) bool +} + +// elevationService serves route LOS profiles from the shared terrain source. +// It keeps no terrain of its own: tiles live in the source's cache, in +// memory only (the server never writes the DB). +type elevationService struct { + src *srtmSource + now func() time.Time + // wait is the longest a request waits for its tiles before 202. + wait time.Duration + // nodes lists the known nodes; only their positions are valid leg + // endpoints. Nil means none (every leg is unknown_point). + nodes func() []nodeInfo + // visibility narrows nodes to those /api/nodes shows + // (node_visibility.go). Nil (unit tests) hides nothing. + visibility elevVisibility + // downloads is the per-client terrain download budget, shared with the + // planner (newTerrainClientLimiter): one token per download a request + // starts. Nil disables it. + downloads *clientLimiter + + refreshMu sync.Mutex // serialises node-set rebuilds + + mu sync.Mutex + nodeSet map[string]struct{} + nodeSetAt time.Time + nodeSetGen string // visibility generation nodeSet was built under +} + +// newElevationService builds the service over src, the SRTM source it +// shares with the planner (newTerrainServices); nil builds a private default +// one sized for route LOS (tests). +func newElevationService(src *srtmSource) *elevationService { + if src == nil { + src = newSRTMSource(TerrainConfig{}, losMaxTiles) + } + return &elevationService{ + src: src, + now: time.Now, + wait: losTileWait, + } +} + +func elevKey(p geoPoint) string { return fmt.Sprintf("%.5f,%.5f", p.Lat, p.Lon) } + +// known reports whether key is the position of a known node that /api/nodes +// shows. The set is rebuilt outside e.mu every elevNodeSetTTL, and at once +// when the hiding rules change, so a node the operator hides stops being a +// valid endpoint on the next request. +func (e *elevationService) known(key string) bool { + if e.nodes == nil { + return false + } + gen := e.visibilityGen() + e.mu.Lock() + due := e.nodeSetDue(gen) + e.mu.Unlock() + if due { + e.refreshMu.Lock() + // Read the generation before the rule and the nodes: a rule change + // during the build then leaves a stale generation behind, which the + // next call rebuilds. + gen = e.visibilityGen() + e.mu.Lock() + due = e.nodeSetDue(gen) + e.mu.Unlock() + if due { + set := e.buildNodeSet() + e.mu.Lock() + e.nodeSet, e.nodeSetAt, e.nodeSetGen = set, e.now(), gen + e.mu.Unlock() + } + e.refreshMu.Unlock() + } + e.mu.Lock() + _, ok := e.nodeSet[key] + e.mu.Unlock() + return ok +} + +func (e *elevationService) visibilityGen() string { + if e.visibility == nil { + return "" + } + return e.visibility.nodeVisibilityGen() +} + +// nodeSetDue reports whether the set must be rebuilt. Caller holds e.mu. +func (e *elevationService) nodeSetDue(gen string) bool { + return e.nodeSet == nil || e.nodeSetGen != gen || e.now().Sub(e.nodeSetAt) >= elevNodeSetTTL +} + +// buildNodeSet keys the positions of the visible nodes with GPS (not 0,0). +func (e *elevationService) buildNodeSet() map[string]struct{} { + var visible func(n *nodeInfo) bool + if e.visibility != nil { + visible = e.visibility.visibleNodeInfo() + } + ns := e.nodes() + set := make(map[string]struct{}, len(ns)) + for i := range ns { + n := &ns[i] + if !n.HasGPS || (n.Lat == 0 && n.Lon == 0) { + continue + } + if visible != nil && !visible(n) { + continue + } + set[elevKey(geoPoint{n.Lat, n.Lon})] = struct{}{} + } + return set +} + +// elevLeg is one requested leg after the checks that need no terrain. +type elevLeg struct { + res ElevationLeg // the distance, and the error once decided + a, b geoPoint + tiles []srtmKey // legTiles; nil once res.Error is set +} + +// plan runs the checks that need no terrain, in order: too_long, +// unknown_point, too_many_tiles. It returns the legs and the request's +// distinct tiles, first seen first. A leg whose new tiles would take the +// request past losMaxTiles is too_many_tiles and adds none; a later leg may +// still fit. +func (e *elevationService) plan(pts []geoPoint) ([]elevLeg, []srtmKey) { + legs := make([]elevLeg, len(pts)-1) + seen := map[srtmKey]bool{} + var keys []srtmKey + for i := range legs { + l := &legs[i] + l.a, l.b = pts[i], pts[i+1] + l.res.DistanceKm = losRound(geoDistKm(l.a, l.b), 1000) + if l.res.DistanceKm > losMaxLegKm { + l.res.Error = elevErrTooLong + continue + } + if !e.known(elevKey(l.a)) || !e.known(elevKey(l.b)) { + l.res.Error = elevErrUnknownPoint + continue + } + tiles := legTiles(l.a, l.b) + fresh := 0 + for _, k := range tiles { + if !seen[k] { + fresh++ + } + } + if len(keys)+fresh > losMaxTiles { + l.res.Error = elevErrTooManyTiles + continue + } + for _, k := range tiles { + if !seen[k] { + seen[k] = true + keys = append(keys, k) + } + } + l.tiles = tiles + } + return legs, keys +} diff --git a/cmd/server/elevation_test.go b/cmd/server/elevation_test.go new file mode 100644 index 000000000..46fb266e7 --- /dev/null +++ b/cmd/server/elevation_test.go @@ -0,0 +1,980 @@ +package main + +import ( + "compress/gzip" + "encoding/json" + "fmt" + "math" + "net/http" + "net/http/httptest" + "net/url" + "slices" + "strconv" + "strings" + "sync" + "testing" + "time" +) + +type elevClock struct { + mu sync.Mutex + t time.Time +} + +func (c *elevClock) now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.t } +func (c *elevClock) add(d time.Duration) { + c.mu.Lock() + c.t = c.t.Add(d) + c.mu.Unlock() +} + +// elevNodes is the injected node list. Tests register the points they use +// with register (or implicitly through elevTest.get). +type elevNodes struct { + mu sync.Mutex + svc *elevationService + ns []nodeInfo +} + +func (n *elevNodes) get() []nodeInfo { + n.mu.Lock() + defer n.mu.Unlock() + return append([]nodeInfo(nil), n.ns...) +} + +// register adds nodes at the points and forces a node-set rebuild. +func (n *elevNodes) register(pts ...geoPoint) { + n.mu.Lock() + for _, p := range pts { + n.ns = append(n.ns, nodeInfo{Lat: p.Lat, Lon: p.Lon, HasGPS: true}) + } + n.mu.Unlock() + n.svc.mu.Lock() + n.svc.nodeSet = nil + n.svc.mu.Unlock() +} + +func (n *elevNodes) set(ns []nodeInfo) { + n.mu.Lock() + n.ns = ns + n.mu.Unlock() +} + +// elevTest is route LOS over a test SRTM source (newSRTMTest): tiles are +// preloaded with src.put, as a finished download leaves them, or served by +// the test upstream h (nil: every tile 404s). +type elevTest struct { + srv *Server + svc *elevationService + src *srtmSource + up *srtmUpstream + clk *elevClock + nodes *elevNodes +} + +func newElevTest(t testing.TB, h http.HandlerFunc) *elevTest { + t.Helper() + if h == nil { + h = srtmServe(nil) + } + src, up, clk := newSRTMTest(t, 0, h) + svc := newElevationService(src) + svc.now = clk.now + svc.wait = 10 * time.Second // downloads from the local upstream finish well within it + nl := &elevNodes{svc: svc} + svc.nodes = nl.get + srv := &Server{cfg: &Config{LOS: &LOSConfig{Enabled: true}}, elevation: svc} + return &elevTest{srv: srv, svc: svc, src: src, up: up, clk: clk, nodes: nl} +} + +const elevTestClient = "192.0.2.1:5000" + +func elevParsePts(pts string) []geoPoint { + parts := strings.Split(pts, ",") + var ps []geoPoint + for i := 0; i+1 < len(parts); i += 2 { + la, e1 := strconv.ParseFloat(parts[i], 64) + lo, e2 := strconv.ParseFloat(parts[i+1], 64) + if e1 == nil && e2 == nil { + ps = append(ps, geoPoint{la, lo}) + } + } + return ps +} + +// get registers the request's points as known nodes, then requests them. +func (et *elevTest) get(pts string) *httptest.ResponseRecorder { + return et.getFrom(pts, elevTestClient, nil) +} + +func (et *elevTest) getFrom(pts, remote string, hdr map[string]string) *httptest.ResponseRecorder { + et.nodes.register(elevParsePts(pts)...) + return et.raw(pts, remote, hdr) +} + +// raw requests pts as they are, registering nothing. +func (et *elevTest) raw(pts, remote string, hdr map[string]string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodGet, "/api/elevation/profile?pts="+url.QueryEscape(pts), nil) + req.RemoteAddr = remote + for k, v := range hdr { + req.Header.Set(k, v) + } + w := httptest.NewRecorder() + et.srv.handleElevationProfile(w, req) + return w +} + +// legs decodes a 200 body. +func elevLegs(t testing.TB, w *httptest.ResponseRecorder) ElevationProfileResponse { + t.Helper() + if w.Code != http.StatusOK { + t.Fatalf("code=%d body=%s", w.Code, w.Body.String()) + } + var resp ElevationProfileResponse + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("body %q: %v", w.Body.String(), err) + } + return resp +} + +func elevLegErrors(resp ElevationProfileResponse) []string { + out := make([]string, len(resp.Legs)) + for i, l := range resp.Legs { + out[i] = l.Error + if (l.Error == "") != (len(l.ElevM) > 0) { + out[i] += "!elev_m" + } + } + return out +} + +// withElevLimit gives the service a download limit of n tiles a minute. +func withElevLimit(svc *elevationService, clk *elevClock, n int) { + svc.downloads = &clientLimiter{ipr: &wsLimiter{state: map[string]*wsIPState{}}, rl: newRateLimiter(n, time.Minute)} + svc.downloads.rl.now = clk.now +} + +func elevBucketTokens(svc *elevationService, ip string) float64 { + return rlTokens(svc.downloads.rl, ip) +} + +// rlTokens is key's tokens in l (its burst when it has no bucket yet). +func rlTokens(l *rateLimiter, key string) float64 { + l.mu.Lock() + defer l.mu.Unlock() + if b := l.buckets[key]; b != nil { + return b.tokens + } + return l.burst +} + +// elevFieldGrid is tile k with each sample set to f at its position, so +// tiles built from one f agree on their shared edges, as real SRTM tiles do. +func elevFieldGrid(k srtmKey, f func(lat, lon float64) float64) []int16 { + g := make([]int16, srtmSide*srtmSide) + for r := 0; r < srtmSide; r++ { + lat := float64(k.lat+1) - float64(r)/srtmCells + for c := 0; c < srtmSide; c++ { + g[r*srtmSide+c] = int16(math.Round(f(lat, float64(k.lon)+float64(c)/srtmCells))) + } + } + return g +} + +func elevFlatGrid(v int16) []int16 { + g := make([]int16, srtmSide*srtmSide) + for i := range g { + g[i] = v + } + return g +} + +// elevLinear is linear in lat and lon and whole at every 3-arc-second grid +// point near 29-33 N, 99-95 W, so bilinear interpolation reproduces it +// exactly there. +func elevLinear(lat, lon float64) float64 { return 1200*(lat-29) + 1200*(lon+99) } + +// elevWavy is rough terrain: ridges every few km in both directions. +func elevWavy(lat, lon float64) float64 { + return 600 + 250*math.Sin(lat*9) + 180*math.Cos(lon*7) + 40*math.Sin((lat+lon)*310) +} + +// ─── Request handling ────────────────────────────────────────────────────── + +func TestElevationDisabled(t *testing.T) { + for _, srv := range []*Server{ + {cfg: &Config{LOS: &LOSConfig{Enabled: false}}, elevation: newElevationService(nil)}, + {cfg: &Config{LOS: &LOSConfig{Enabled: true}}}, + {cfg: &Config{}}, + } { + w := httptest.NewRecorder() + srv.handleElevationProfile(w, httptest.NewRequest(http.MethodGet, "/api/elevation/profile?pts=1,1,2,2", nil)) + if w.Code != http.StatusNotFound || !strings.Contains(w.Body.String(), "los disabled") { + t.Fatalf("code=%d body=%s want 404", w.Code, w.Body.String()) + } + } +} + +func TestElevationValidation(t *testing.T) { + et := newElevTest(t, nil) + many := make([]string, 0) + for i := 0; i < (losMaxPoints+1)*2; i++ { + many = append(many, "1") + } + cases := map[string]string{ + "missing": "", + "odd": "1,2,3", + "one point": "1,2", + "17 points": strings.Join(many, ","), + "lat range": "91,0,1,1", + "lon range": "0,181,1,1", + "nan": "NaN,0,1,1", + "inf": "Inf,0,1,1", + "garbage": "a,b,c,d", + "empty val": "1,,2,3", + } + for name, pts := range cases { + if w := et.get(pts); w.Code != http.StatusBadRequest { + t.Errorf("%s: code=%d want 400", name, w.Code) + } + } + if n := et.up.total(); n != 0 { + t.Fatalf("validation failures fetched %d tiles", n) + } +} + +func TestElevationQueryBounds(t *testing.T) { + et := newElevTest(t, nil) + req := httptest.NewRequest(http.MethodGet, "/api/elevation/profile?pts=1,1,2,2&x="+strings.Repeat("a", 2100), nil) + w := httptest.NewRecorder() + et.srv.handleElevationProfile(w, req) + if w.Code != 400 || !strings.Contains(w.Body.String(), "pts too long") { + t.Fatalf("raw query: %d %s", w.Code, w.Body.String()) + } + if _, msg := parseElevationPts(strings.Repeat("1,", 500) + "1"); !strings.Contains(msg, "2 to 16") { + t.Fatalf("comma count: %q", msg) + } + // 16 points (31 commas) is the maximum and still parses. + if pts, msg := parseElevationPts(strings.TrimSuffix(strings.Repeat("1,1,", 16), ",")); msg != "" || len(pts) != 16 { + t.Fatalf("16 points: %d %q", len(pts), msg) + } + if _, msg := parseElevationPts(strings.TrimSuffix(strings.Repeat("1,1,", 17), ",")); msg == "" { + t.Fatal("17 points accepted") + } +} + +// Review #2391 point 9: route LOS and the planner read the same tiles and +// sample a leg the same way, so the same leg gets the same terrain, and so +// the same verdict, in both views. Both requests go through their real +// handlers over one shared source. +func TestElevationMatchesPlannerProfile(t *testing.T) { + et := newElevTest(t, nil) + for _, k := range []srtmKey{{30, -98}, {30, -97}, {31, -98}, {31, -97}} { + et.src.put(k, elevFieldGrid(k, elevWavy)) + } + // Points at 0.001° so the planner's quantisation keeps them as they are. + const pts = "30.2,-97.8,30.85,-97.15,31.3,-96.6" + cfg := &Config{LOS: &LOSConfig{Enabled: true}, Planner: &PlannerConfig{Enabled: true}} + et.srv.cfg = cfg + p := newPlannerService(*cfg.Planner, et.srv, et.src) + t.Cleanup(p.Close) + var ns []nodeInfo + for i, pt := range elevParsePts(pts) { + ns = append(ns, nodeInfo{PublicKey: fmt.Sprintf("ee%02d", i), Name: "N", Role: "repeater", + Lat: pt.Lat, Lon: pt.Lon, HasGPS: true, LastSeen: time.Now()}) + } + p.data = &fakePlannerData{serverPlannerData: serverPlannerData{et.srv}, ns: ns} + p.fastWait = 10 * time.Second + et.srv.planner = p + + los := elevLegs(t, et.get(pts)) + req := httptest.NewRequest(http.MethodGet, "/api/planner/profile?pts="+pts, nil) + req.RemoteAddr = elevTestClient + pw := httptest.NewRecorder() + et.srv.handlePlannerProfile(pw, req) + if pw.Code != http.StatusOK { + t.Fatalf("planner: %d %s", pw.Code, pw.Body.String()) + } + var plan PlannerProfileResponse + if err := json.Unmarshal(pw.Body.Bytes(), &plan); err != nil { + t.Fatal(err) + } + + if los.Source != et.src.source || plan.Source != los.Source || los.Source != "SRTM (127.0.0.1)" { + t.Fatalf("sources: LOS %q, planner %q, source %q", los.Source, plan.Source, et.src.source) + } + if len(los.Legs) != 2 || len(plan.Legs) != 2 { + t.Fatalf("legs: LOS %d, planner %d", len(los.Legs), len(plan.Legs)) + } + gp := elevParsePts(pts) + for i := range los.Legs { + l, pl := los.Legs[i], plan.Legs[i] + if l.Error != "" || pl.Error != "" { + t.Fatalf("leg %d errors: LOS %q, planner %q", i, l.Error, pl.Error) + } + a, b := gp[i], gp[i+1] + if n := planProfileSamples(geoDistKm(a, b)); len(l.ElevM) != n { + t.Fatalf("leg %d: %d samples, want %d", i, len(l.ElevM), n) + } + if l.DistanceKm != pl.DistanceKm || !slices.Equal(l.ElevM, pl.ElevM) { + t.Fatalf("leg %d differs: LOS %v km, planner %v km, first elev %v vs %v", + i, l.DistanceKm, pl.DistanceKm, l.ElevM[:3], pl.ElevM[:3]) + } + // Not flat: the comparison means something. + if slices.Min(l.ElevM) == slices.Max(l.ElevM) { + t.Fatalf("leg %d is flat", i) + } + } + if n := et.up.total(); n != 0 { + t.Fatalf("resident tiles fetched again: %d", n) + } +} + +// Only the tiles a leg's samples fall in are loaded, not its bounding box. +func TestElevationLoadsOnlyLegTiles(t *testing.T) { + a, b := geoPoint{30.5, -97.5}, geoPoint{32.5, -95.5} + if d := geoDistKm(a, b); d > losMaxLegKm { + t.Fatalf("test leg is %.0f km", d) + } + want := legTiles(a, b) + box, _ := srtmSpanOf(geoBBox{S: a.Lat, W: a.Lon, N: b.Lat, E: b.Lon}) + if len(want) >= box.count() { + t.Fatalf("the leg's samples touch %d tiles, its box %d: the test needs fewer", len(want), box.count()) + } + for _, p := range legSamplePoints(a, b) { + if !slices.Contains(want, srtmKeyOf(p.Lat, p.Lon)) { + t.Fatalf("sample (%v, %v) is in no listed tile", p.Lat, p.Lon) + } + } + tile := srtmConstTile(t, 250, srtmRawBytes, gzip.BestSpeed) + tiles := map[string][]byte{} + for i := 0; i < box.count(); i++ { + tiles[srtmPath(box.key(i))] = tile + } + et := newElevTest(t, srtmServe(tiles)) + resp := elevLegs(t, et.get("30.5,-97.5,32.5,-95.5")) + l := resp.Legs[0] + if l.Error != "" || len(l.ElevM) != planProfileSamples(geoDistKm(a, b)) || slices.Min(l.ElevM) != 250 || slices.Max(l.ElevM) != 250 { + t.Fatalf("leg %+v", l.Error) + } + for i := 0; i < box.count(); i++ { + k := box.key(i) + wantHits := 0 + if slices.Contains(want, k) { + wantHits = 1 + } + if got := et.up.hitsFor(srtmPath(k)); got != wantHits { + t.Errorf("tile %s fetched %d times, want %d", k.name(), got, wantHits) + } + } +} + +// Points on degree lines (a tile corner, a parallel, a meridian) read the +// tile north or east of the line, which shares its edge with the other +// side, and agree with the planner's rectangular view. +func TestElevationDegreeLinePoints(t *testing.T) { + et := newElevTest(t, nil) + for lat := 29; lat <= 31; lat++ { + for lon := -98; lon <= -96; lon++ { + k := srtmKey{lat, lon} + et.src.put(k, elevFieldGrid(k, elevLinear)) + } + } + // Along the -97 meridian, to the 31,-97 corner, then along the 31st + // parallel (the great circle bulges north of it). + const pts = "30.2,-97,30.8,-97,31,-97,31,-96.5,31,-96" + geo := elevParsePts(pts) + if !slices.Contains(legTiles(geoPoint{31, -97}, geoPoint{31, -96.5}), srtmKey{31, -97}) { + t.Fatal("the corner point does not load the tile north-east of it") + } + resp := elevLegs(t, et.get(pts)) + tmpl := make([]PlannerProfileLeg, len(geo)-1) + for i := range tmpl { + tmpl[i].DistanceKm = losRound(geoDistKm(geo[i], geo[i+1]), 1000) + } + v := srtmMustView(t, et.src, plannerProfileView(geoBBox{S: 30.2, W: -97, N: 31, E: -96}, plannerProfilePad(defaultPlannerMaxLegKm))) + plan, err := planProfileLegs(t.Context(), v, geo, tmpl, func(float64) {}) + if err != nil { + t.Fatal(err) + } + for i, l := range resp.Legs { + if l.Error != "" { + t.Fatalf("leg %d: %q", i, l.Error) + } + samples := legSamplePoints(geo[i], geo[i+1]) + for j, e := range l.ElevM { + if want := elevLinear(samples[j].Lat, samples[j].Lon); math.Abs(e-want) > 0.05+1e-6 { + t.Fatalf("leg %d sample %d at (%v, %v): %v, want %v", i, j, samples[j].Lat, samples[j].Lon, e, want) + } + } + if !slices.Equal(l.ElevM, plan.Legs[i].ElevM) { + t.Fatalf("leg %d differs from the planner view", i) + } + } + if n := et.up.total(); n != 0 { + t.Fatalf("fetched %d tiles", n) + } +} + +// Tiles that are not resident: the request waits, then answers 202 while +// the download goes on; polls are free and start nothing; once the tile is +// in, the same URL answers 200. +func TestElevationLoadingThenReady(t *testing.T) { + gate := newSRTMGate() + slow, ready := srtmKey{40, 10}, srtmKey{40, 11} + tile := srtmConstTile(t, 300, srtmRawBytes, gzip.BestSpeed) + serve := srtmServe(map[string][]byte{srtmPath(slow): tile}) + et := newElevTest(t, func(w http.ResponseWriter, r *http.Request) { + if gate.wait(r) { + serve(w, r) + } + }) + t.Cleanup(gate.open) + et.svc.wait = 20 * time.Millisecond + withElevLimit(et.svc, et.clk, 10) + et.src.put(ready, elevFlatGrid(50)) + const ip = "192.0.2.30" + const pts = "40.5,10.5,40.5,11.5" + + check202 := func(w *httptest.ResponseRecorder) { + t.Helper() + if w.Code != http.StatusAccepted || w.Header().Get("Retry-After") != "2" || w.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("code=%d Retry-After=%q Cache-Control=%q body=%s", w.Code, w.Header().Get("Retry-After"), + w.Header().Get("Cache-Control"), w.Body.String()) + } + var st PlannerJobStatus + if err := json.Unmarshal(w.Body.Bytes(), &st); err != nil || + st != (PlannerJobStatus{State: "loading_terrain", Progress: 0.5, RetryAfterS: 2}) { + t.Fatalf("status %s (%v)", w.Body.String(), err) + } + } + check202(et.getFrom(pts, ip+":5000", nil)) + if got := elevBucketTokens(et.svc, ip); got != 9 { + t.Fatalf("tokens=%v want 9 (one download started)", got) + } + srtmEventually(t, "the download to start", func() bool { return et.up.hitsFor(srtmPath(slow)) == 1 }) + // A poll while it downloads costs nothing and starts nothing. + check202(et.raw(pts, ip+":5000", nil)) + if got := elevBucketTokens(et.svc, ip); got != 9 || et.up.total() != 1 { + t.Fatalf("poll: tokens=%v, fetches=%d", got, et.up.total()) + } + + gate.open() + srtmEventually(t, "the tile to load", func() bool { return et.src.Resident(srtmBox(slow)) }) + w := et.raw(pts, ip+":5000", nil) + resp := elevLegs(t, w) + l := resp.Legs[0] + if l.Error != "" || l.ElevM[0] != 300 || l.ElevM[len(l.ElevM)-1] != 50 || w.Header().Get("Cache-Control") != elevCacheControl { + t.Fatalf("after load: %q, ends %v..%v, Cache-Control %q", l.Error, l.ElevM[0], l.ElevM[len(l.ElevM)-1], + w.Header().Get("Cache-Control")) + } + if got := elevBucketTokens(et.svc, ip); got != 9 || et.up.total() != 1 { + t.Fatalf("after load: tokens=%v, fetches=%d", got, et.up.total()) + } +} + +func TestElevationMissingTileIsNoTerrain(t *testing.T) { + et := newElevTest(t, nil) // every download 404s: no such tile + et.src.put(srtmKey{40, 10}, elevFlatGrid(70)) + const pts = "40.2,10.2,40.8,10.8,41.2,10.5" + for round := 0; round < 2; round++ { + w := et.get(pts) + resp := elevLegs(t, w) + if got := elevLegErrors(resp); !slices.Equal(got, []string{"", elevErrNoTerrain}) { + t.Fatalf("round %d: errors %q", round, got) + } + if cc := w.Header().Get("Cache-Control"); cc != "no-store" { + t.Fatalf("round %d: Cache-Control %q", round, cc) + } + } + // Known missing after the first: not asked again. + if n := et.up.hitsFor(srtmPath(srtmKey{41, 10})); n != 1 || et.up.total() != 1 { + t.Fatalf("missing tile fetched %d times (total %d)", n, et.up.total()) + } +} + +// A request loads at most losMaxTiles distinct tiles. A leg whose new tiles +// would go past the cap is too_many_tiles and loads nothing; a later leg +// over tiles already in the request still fits. +func TestElevationTooManyTiles(t *testing.T) { + et := newElevTest(t, nil) + // About 280 km legs east along 30.5° N, then back west over the fifth. + lons := []float64{-100, -97.1, -94.2, -91.3, -88.4, -85.5, -82.6, -85.5, -88.4} + var parts []string + var geo []geoPoint + for _, lon := range lons { + parts = append(parts, fmt.Sprintf("30.5,%g", lon)) + geo = append(geo, geoPoint{30.5, lon}) + } + pts := strings.Join(parts, ",") + seen := map[srtmKey]bool{} + var cum []int + for i := 0; i+1 < len(geo); i++ { + if d := geoDistKm(geo[i], geo[i+1]); d > losMaxLegKm { + t.Fatalf("leg %d is %.0f km", i, d) + } + for _, k := range legTiles(geo[i], geo[i+1]) { + seen[k] = true + } + cum = append(cum, len(seen)) + } + if cum[4] > losMaxTiles || cum[5] <= losMaxTiles { + t.Fatalf("cumulative tiles %v: the test needs the 6th leg to cross the cap", cum) + } + // Preload what the request may load, so nothing is downloaded. + et.nodes.register(elevParsePts(pts)...) + _, keys := et.svc.plan(elevParsePts(pts)) + if len(keys) != cum[4] { + t.Fatalf("request tiles %d, want %d", len(keys), cum[4]) + } + flat := elevFlatGrid(10) + for _, k := range keys { + et.src.put(k, flat) + } + w := et.raw(pts, elevTestClient, nil) + resp := elevLegs(t, w) + tm := elevErrTooManyTiles + if got, want := elevLegErrors(resp), []string{"", "", "", "", "", tm, tm, ""}; !slices.Equal(got, want) { + t.Fatalf("errors %q, want %q", got, want) + } + if cc := w.Header().Get("Cache-Control"); cc != "no-store" || et.up.total() != 0 { + t.Fatalf("Cache-Control %q, fetches %d", cc, et.up.total()) + } +} + +// Terrain that cannot load makes its legs "upstream" (retryable); the +// other legs are still answered. +func TestElevationTerrainUnavailable(t *testing.T) { + near, far := srtmKey{40, 10}, srtmKey{40, 11} + const pts = "40.2,10.2,40.8,10.8,40.5,11.5" + tile := srtmConstTile(t, 300, srtmRawBytes, gzip.BestSpeed) + + // Downloads paused (cooldown): nothing is fetched or charged. + et := newElevTest(t, srtmServe(map[string][]byte{srtmPath(far): tile})) + withElevLimit(et.svc, et.clk, 10) + et.src.put(near, elevFlatGrid(70)) + et.src.mu.Lock() + et.src.coolTo = et.clk.now().Add(time.Minute) + et.src.mu.Unlock() + w := et.getFrom(pts, "192.0.2.40:5000", nil) + resp := elevLegs(t, w) + if got := elevLegErrors(resp); !slices.Equal(got, []string{"", elevErrUpstream}) || w.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("cooldown: errors %q, Cache-Control %q", got, w.Header().Get("Cache-Control")) + } + if et.up.total() != 0 || elevBucketTokens(et.svc, "192.0.2.40") != 10 { + t.Fatalf("cooldown: fetches %d, tokens %v", et.up.total(), elevBucketTokens(et.svc, "192.0.2.40")) + } + + // Download budget used up. + et.clk.add(time.Minute) + et.src.mu.Lock() + for i := 0; i < et.src.budget.perMinute; i++ { + et.src.budget.starts = append(et.src.budget.starts, et.clk.now()) + } + et.src.mu.Unlock() + if got := elevLegErrors(elevLegs(t, et.raw(pts, elevTestClient, nil))); !slices.Equal(got, []string{"", elevErrUpstream}) { + t.Fatalf("budget: errors %q", got) + } + + // The tile server failing opens a cooldown. + et2 := newElevTest(t, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusBadGateway) }) + if got := elevLegErrors(elevLegs(t, et2.get("40.5,11.2,40.5,11.8"))); !slices.Equal(got, []string{elevErrUpstream}) { + t.Fatalf("502: errors %q", got) + } + if !et2.src.cooling() { + t.Fatal("a failed download did not pause downloads") + } +} + +// ─── Per-client limit ────────────────────────────────────────────────────── + +// A request is charged one token per tile download it starts, all or +// nothing; resident tiles cost nothing, so such a request is never limited. +func TestElevationChargedPerDownload(t *testing.T) { + tile := srtmConstTile(t, 120, srtmRawBytes, gzip.BestSpeed) + tiles := map[string][]byte{} + for lon := 10; lon <= 18; lon++ { + tiles[srtmPath(srtmKey{40, lon})] = tile + } + et := newElevTest(t, srtmServe(tiles)) + withElevLimit(et.svc, et.clk, 4) + const a, b = "192.0.2.20", "192.0.2.21" + ok := func(pts, ip string) { + t.Helper() + if w := et.getFrom(pts, ip+":5000", nil); w.Code != http.StatusOK { + t.Fatalf("%s from %s: %d %s", pts, ip, w.Code, w.Body.String()) + } + } + tokens := func(ip string, want float64) { + t.Helper() + if got := elevBucketTokens(et.svc, ip); math.Abs(got-want) > 1e-6 { + t.Fatalf("%s tokens=%v want %v", ip, got, want) + } + } + + ok("40.5,10.5,40.5,11.5", a) // 2 downloads + tokens(a, 2) + ok("40.5,10.5,40.5,11.5", a) // resident: free + tokens(a, 2) + + // 3 downloads, 2 tokens: refused, nothing taken, nothing fetched. + const three = "40.5,11.5,40.5,12.5,40.5,13.5,40.5,14.5" + before := et.up.total() + w := et.getFrom(three, a+":5000", nil) + if w.Code != http.StatusTooManyRequests || !strings.Contains(w.Body.String(), "rate limited") { + t.Fatalf("code=%d body=%s want 429", w.Code, w.Body.String()) + } + if ra, _ := strconv.Atoi(w.Header().Get("Retry-After")); ra < 1 || ra > 60 { + t.Fatalf("Retry-After=%q", w.Header().Get("Retry-After")) + } + tokens(a, 2) + if et.up.total() != before { + t.Fatal("a refused request fetched tiles") + } + + ok(three, b) // another client has its own bucket + tokens(b, 1) + ok("40.5,14.5,40.5,16.5", a) // 2 downloads: a is out of tokens + tokens(a, 0) + ok(three, a) // resident now: never limited + tokens(a, 0) + const more = "40.5,16.5,40.5,18.5" // 2 downloads + if w := et.getFrom(more, a+":5000", nil); w.Code != http.StatusTooManyRequests { + t.Fatalf("out of tokens: %d", w.Code) + } + et.clk.add(31 * time.Second) // 4 a minute: 2.07 tokens back + ok(more, a) + tokens(a, 31.0/60*4-2) +} + +// Code review #1 (#2391): a request whose tiles the download budget only +// partly admits answered 202 while the admitted one loaded, and every poll +// counted the refused tile as a new start and charged for it again, until +// the client got 429 on a poll. The budget is now peeked first: a tile it +// has no room for is upstream and costs nothing, so polls stay free. +func TestElevationPollAfterRefusedIsFree(t *testing.T) { + gate := newSRTMGate() + slow, refused := srtmKey{40, 10}, srtmKey{40, 11} + tile := srtmConstTile(t, 300, srtmRawBytes, gzip.BestSpeed) + serve := srtmServe(map[string][]byte{srtmPath(slow): tile, srtmPath(refused): tile}) + et := newElevTest(t, func(w http.ResponseWriter, r *http.Request) { + if gate.wait(r) { + serve(w, r) + } + }) + t.Cleanup(gate.open) + et.svc.wait = 20 * time.Millisecond + withElevLimit(et.svc, et.clk, 10) + // The download budget has room for one more start this minute. + et.src.mu.Lock() + for i := 0; i < et.src.budget.perMinute-1; i++ { + et.src.budget.starts = append(et.src.budget.starts, et.clk.now()) + } + et.src.mu.Unlock() + const ip = "192.0.2.31" + // One leg in each tile, and one across both. + const pts = "40.2,10.2,40.8,10.8,40.2,11.2,40.8,11.8" + + w := et.getFrom(pts, ip+":5000", nil) + if w.Code != http.StatusAccepted { + t.Fatalf("first request: %d %s", w.Code, w.Body.String()) + } + if got := elevBucketTokens(et.svc, ip); got != 9 { + t.Fatalf("tokens=%v want 9 (one download admitted, one refused)", got) + } + srtmEventually(t, "the admitted download", func() bool { return et.up.hitsFor(srtmPath(slow)) == 1 }) + // Spend the rest: a poll that charged anything would now be limited. + if ok, _ := et.svc.downloads.rl.takeN(ip, 9); !ok { + t.Fatal("could not drain the bucket") + } + for i := 0; i < 5; i++ { + if w := et.raw(pts, ip+":5000", nil); w.Code != http.StatusAccepted { + t.Fatalf("poll %d: %d %s", i, w.Code, w.Body.String()) + } + } + if got := elevBucketTokens(et.svc, ip); got != 0 { + t.Fatalf("polls took tokens: %v left", got) + } + gate.open() + srtmEventually(t, "the tile to load", func() bool { return et.src.Resident(srtmBox(slow)) }) + w = et.raw(pts, ip+":5000", nil) + if got := elevLegErrors(elevLegs(t, w)); !slices.Equal(got, []string{"", elevErrUpstream, elevErrUpstream}) { + t.Fatalf("after load: errors %q", got) + } + if w.Header().Get("Cache-Control") != "no-store" || et.up.hitsFor(srtmPath(refused)) != 0 || elevBucketTokens(et.svc, ip) != 0 { + t.Fatalf("Cache-Control %q, refused tile fetched %d times, tokens %v", w.Header().Get("Cache-Control"), + et.up.hitsFor(srtmPath(refused)), elevBucketTokens(et.svc, ip)) + } + // Once the budget has room again the refused tile downloads, charged + // once: the bucket refilled to 10, less 1. + et.clk.add(time.Minute) + et.svc.wait = 10 * time.Second // the download finishes well within it + if got := elevLegErrors(elevLegs(t, et.raw(pts, ip+":5000", nil))); !slices.Equal(got, []string{"", "", ""}) { + t.Fatalf("budget back: errors %q", got) + } + if got := elevBucketTokens(et.svc, ip); got != 9 || et.up.hitsFor(srtmPath(refused)) != 1 { + t.Fatalf("budget back: tokens %v, refused tile fetched %d times", got, et.up.hitsFor(srtmPath(refused))) + } +} + +// Without trustedProxies every visitor behind the local proxy looks like one +// client, so the per-client budget is skipped (review #2391); with the proxy +// listed, each client has its own. +func TestElevationRateLimitSkipsIndistinctClients(t *testing.T) { + tile := srtmConstTile(t, 120, srtmRawBytes, gzip.BestSpeed) + tiles := map[string][]byte{} + for lon := 20; lon <= 25; lon++ { + tiles[srtmPath(srtmKey{40, lon})] = tile + } + et := newElevTest(t, srtmServe(tiles)) + withElevLimit(et.svc, et.clk, 2) + // Loopback peer, no trusted proxy: X-Forwarded-For is not believed. + for i, xff := range []string{"198.51.100.1", "198.51.100.2"} { + pts := fmt.Sprintf("40.2,%d.2,40.8,%d.8", 20+i, 20+i) + if w := et.getFrom(pts, "127.0.0.1:1", map[string]string{"X-Forwarded-For": xff}); w.Code != http.StatusOK { + t.Fatalf("request %d: %d", i, w.Code) + } + } + if w := et.getFrom("40.2,22.2,40.8,22.8", "127.0.0.1:1", map[string]string{"X-Forwarded-For": "198.51.100.3"}); w.Code != http.StatusOK { + t.Fatalf("visitors behind an unlisted proxy share one bucket: %d", w.Code) + } + if n := len(et.svc.downloads.rl.buckets); n != 0 { + t.Fatalf("%d buckets for clients that cannot be told apart", n) + } + // The proxy listed: X-Forwarded-For is believed and the client is charged. + et.svc.downloads.ipr.trustedProxies = parseCIDRList([]string{"127.0.0.1"}, "test") + xff := map[string]string{"X-Forwarded-For": "198.51.100.4"} + for lon := 23; lon <= 24; lon++ { + if w := et.getFrom(fmt.Sprintf("40.2,%d.2,40.8,%d.8", lon, lon), "127.0.0.1:1", xff); w.Code != http.StatusOK { + t.Fatalf("tile %d: %d", lon, w.Code) + } + } + if w := et.getFrom("40.2,25.2,40.8,25.8", "127.0.0.1:1", xff); w.Code != http.StatusTooManyRequests { + t.Fatalf("a distinct client over its budget: %d", w.Code) + } +} + +// ─── Known-node rule ─────────────────────────────────────────────────────── + +func TestElevationUnknownPoint(t *testing.T) { + et := newElevTest(t, nil) + et.src.put(srtmKey{1, 1}, elevFlatGrid(5)) + et.nodes.set([]nodeInfo{ + {Lat: 1, Lon: 1, HasGPS: true}, + {Lat: 1.2, Lon: 1.2, HasGPS: true}, + {Lat: 0, Lon: 0, HasGPS: true}, // null island: excluded + {Lat: 0.5, Lon: 0.5, HasGPS: false}, // no GPS: excluded + }) + leg := func(pts string) ElevationLeg { + t.Helper() + return elevLegs(t, et.raw(pts, elevTestClient, nil)).Legs[0] + } + for name, pts := range map[string]string{ + "unknown": "1.5,1.5,1,1", + "unknown b": "1,1,1.5,1.5", + "null island": "0,0,1,1", + "no gps": "0.5,0.5,1,1", + } { + if l := leg(pts); l.Error != elevErrUnknownPoint || len(l.ElevM) != 0 { + t.Errorf("%s: %+v", name, l) + } + } + if n := et.up.total(); n != 0 { + t.Fatalf("unknown points fetched %d tiles", n) + } + if l := leg("1,1,1.2,1.2"); l.Error != "" { + t.Fatalf("known pair: %+v", l) + } + // too_long wins over unknown_point. + if l := leg("10,10,10,20"); l.Error != elevErrTooLong { + t.Fatalf("order: %+v", l) + } + // The set is rebuilt only after 60 s. + et.nodes.set(append(et.nodes.get(), nodeInfo{Lat: 1.4, Lon: 1.4, HasGPS: true})) + if l := leg("1,1,1.4,1.4"); l.Error != elevErrUnknownPoint { + t.Fatalf("set refreshed early: %+v", l) + } + et.clk.add(elevNodeSetTTL + time.Second) + if l := leg("1,1,1.4,1.4"); l.Error != "" { + t.Fatalf("set not refreshed after TTL: %+v", l) + } +} + +// Review #2391 point 4: a node /api/nodes hides (blacklist, hidden name, +// outside the geo_filter) is no valid endpoint, and a rule change applies to +// the next request, not after elevNodeSetTTL. +func TestElevationHiddenNodesAreUnknown(t *testing.T) { + et := newElevTest(t, nil) + et.src.put(srtmKey{1, 1}, elevFlatGrid(5)) + srv, svc := et.srv, et.svc + srv.cfg.SetNodeBlacklist([]string{"bad1"}) + srv.cfg.SetHiddenNamePrefixes([]string{"zz-"}) + inside := &GeoFilterConfig{Polygon: [][2]float64{{0.5, 0.5}, {0.5, 1.35}, {1.35, 1.35}, {1.35, 0.5}}} + srv.setGeoFilter(inside) + svc.visibility = srv + et.nodes.set([]nodeInfo{ + {PublicKey: "ok1", Name: "A", Lat: 1, Lon: 1, HasGPS: true}, + {PublicKey: "ok2", Name: "B", Lat: 1.2, Lon: 1.2, HasGPS: true}, + {PublicKey: "BAD1", Name: "C", Lat: 1.1, Lon: 1.1, HasGPS: true}, + {PublicKey: "hid1", Name: "zz-x", Lat: 1.3, Lon: 1.3, HasGPS: true}, + {PublicKey: "far1", Name: "D", Lat: 1.4, Lon: 1.4, HasGPS: true}, + }) + leg := func(pts string) ElevationLeg { + t.Helper() + resp := elevLegs(t, et.raw(pts, elevTestClient, nil)) + if len(resp.Legs) != 1 { + t.Fatalf("%s: %+v", pts, resp) + } + return resp.Legs[0] + } + for name, pts := range map[string]string{ + "blacklisted": "1,1,1.1,1.1", + "hidden name": "1,1,1.3,1.3", + "outside geo_filter": "1,1,1.4,1.4", + "hidden first": "1.1,1.1,1,1", + } { + if l := leg(pts); l.Error != elevErrUnknownPoint || len(l.ElevM) != 0 { + t.Errorf("%s: %+v", name, l) + } + } + if l := leg("1,1,1.2,1.2"); l.Error != "" { + t.Fatalf("visible pair: %+v", l) + } + + // Each rule change applies at once (the clock never moves), and terrain + // is not served for an endpoint that is now hidden. + steps := []struct { + name string + change func() + pts string + want string + }{ + {"blacklist ok2", func() { srv.cfg.SetNodeBlacklist([]string{"bad1", "OK2"}) }, "1,1,1.2,1.2", elevErrUnknownPoint}, + {"unblacklist ok2", func() { srv.cfg.SetNodeBlacklist([]string{"bad1"}) }, "1,1,1.2,1.2", ""}, + {"hide B", func() { srv.cfg.SetHiddenNamePrefixes([]string{"zz-", "B"}) }, "1,1,1.2,1.2", elevErrUnknownPoint}, + {"unhide B", func() { srv.cfg.SetHiddenNamePrefixes([]string{"zz-"}) }, "1,1,1.2,1.2", ""}, + {"shrink geo_filter", func() { + srv.setGeoFilter(&GeoFilterConfig{Polygon: [][2]float64{{0.5, 0.5}, {0.5, 1.1}, {1.1, 1.1}, {1.1, 0.5}}}) + }, "1,1,1.2,1.2", elevErrUnknownPoint}, + {"drop geo_filter", func() { srv.setGeoFilter(nil) }, "1,1,1.4,1.4", ""}, + } + for _, st := range steps { + st.change() + if l := leg(st.pts); l.Error != st.want { + t.Fatalf("after %s: %s → %+v, want error %q", st.name, st.pts, l, st.want) + } + } + if n := et.up.total(); n != 0 { + t.Fatalf("fetched %d tiles", n) + } +} + +func TestElevationUnknownPointFailClosed(t *testing.T) { + et := newElevTest(t, nil) + et.svc.nodes = nil + if l := elevLegs(t, et.raw("1,1,1.2,1.2", elevTestClient, nil)).Legs[0]; l.Error != elevErrUnknownPoint { + t.Fatalf("nil nodes: %+v", l) + } + et.svc.nodes = func() []nodeInfo { return nil } + if l := elevLegs(t, et.raw("1,1,1.2,1.2", elevTestClient, nil)).Legs[0]; l.Error != elevErrUnknownPoint || et.up.total() != 0 { + t.Fatalf("empty nodes: %+v fetches=%d", l, et.up.total()) + } +} + +func TestElevationCacheControl(t *testing.T) { + et := newElevTest(t, nil) + et.src.put(srtmKey{1, 1}, elevFlatGrid(5)) + cc := func(pts string, register bool, want string, wantErrs ...string) { + t.Helper() + var w *httptest.ResponseRecorder + if register { + w = et.get(pts) + } else { + w = et.raw(pts, elevTestClient, nil) + } + if got := elevLegErrors(elevLegs(t, w)); !slices.Equal(got, wantErrs) || w.Header().Get("Cache-Control") != want { + t.Fatalf("%s: errors %q, Cache-Control %q; want %q, %q", pts, got, w.Header().Get("Cache-Control"), wantErrs, want) + } + } + cc("1,1,1.2,1.2", true, elevCacheControl, "") + cc("1,1,1.2,1.2,1,5", true, elevCacheControl, "", elevErrTooLong) // too_long only: still cacheable + cc("60,60,60.1,60.1", false, "no-store", elevErrUnknownPoint) + cc("1,1,1.2,1.2,1.5,2.5", true, "no-store", "", elevErrNoTerrain) // N01E002 404s +} + +func TestRateLimiterTakeN(t *testing.T) { + l := newRateLimiter(5, time.Minute) + if ok, _ := l.takeN("k", 3); !ok { + t.Fatal("3 of 5 refused") + } + if ok, wait := l.takeN("k", 3); ok || wait <= 0 { + t.Fatalf("ok=%v wait=%v", ok, wait) + } + if ok, _ := l.takeN("k", 2); !ok { + t.Fatal("refusal took tokens") + } +} + +// BenchmarkElevationServeResident: a full request (16 points, 15 legs of +// about 190 km, so 600 samples a leg) whose tiles are all resident: tile +// planning, sampling and encoding, no download. +func BenchmarkElevationServeResident(b *testing.B) { + et := newElevTest(b, nil) + flat := elevFlatGrid(100) + for lat := 30; lat <= 31; lat++ { + for lon := -98; lon <= -96; lon++ { + et.src.put(srtmKey{lat, lon}, flat) + } + } + var parts []string + for i := 0; i < losMaxPoints; i++ { + lat := 30.1 + 1.7*float64(i%2) + parts = append(parts, fmt.Sprintf("%.3f,%.3f", lat, -97.9+0.18*float64(i))) + } + pts := strings.Join(parts, ",") + et.nodes.register(elevParsePts(pts)...) + if resp := elevLegs(b, et.raw(pts, elevTestClient, nil)); !slices.Equal(elevLegErrors(resp), make([]string, losMaxPoints-1)) { + b.Fatalf("benchmark route: %q", elevLegErrors(resp)) + } + b.ResetTimer() + for i := 0; i < b.N; i++ { + if w := et.raw(pts, elevTestClient, nil); w.Code != http.StatusOK { + b.Fatal(w.Code) + } + } +} + +// Requests that arrive together for the same cold tile start one download, +// and exactly one of them pays for it: the charge and the start happen in one +// step, so no second request can be charged in between (review #2391). +func TestElevationConcurrentRequestsChargeOneDownload(t *testing.T) { + et := newElevTest(t, nil) // every tile answers 404: known missing, quickly + const clients, rounds = 8, 60 + for round := 0; round < rounds; round++ { + withElevLimit(et.svc, et.clk, 10) + pts := fmt.Sprintf("%d.2,10.2,%d.8,10.8", round, round) + et.nodes.register(elevParsePts(pts)...) + start := make(chan struct{}) + var wg sync.WaitGroup + for c := 0; c < clients; c++ { + wg.Add(1) + go func(c int) { + defer wg.Done() + <-start + if w := et.raw(pts, fmt.Sprintf("192.0.2.%d:5000", 100+c), nil); w.Code != http.StatusOK && w.Code != http.StatusAccepted { + t.Errorf("round %d client %d: %d %s", round, c, w.Code, w.Body.String()) + } + }(c) + } + close(start) + wg.Wait() + charged := 0.0 + for c := 0; c < clients; c++ { + charged += 10 - elevBucketTokens(et.svc, fmt.Sprintf("192.0.2.%d", 100+c)) + } + if charged != 1 { + t.Fatalf("round %d: %v tokens charged for one download", round, charged) + } + et.clk.add(time.Minute) // room in the global download budget again + } +} diff --git a/cmd/server/eviction_churn_bench_test.go b/cmd/server/eviction_churn_bench_test.go new file mode 100644 index 000000000..f1514fba2 --- /dev/null +++ b/cmd/server/eviction_churn_bench_test.go @@ -0,0 +1,154 @@ +package main + +import ( + "fmt" + "runtime" + "strings" + "testing" + "time" +) + +// Synthetic live-ingest bookkeeping uses the real membership, observation and byte +// accounting helpers. No fixture keeps packet pointers outside the store. +func appendEvictionChurnBatch(s *PacketStore, firstID, count, fanout int, now time.Time) { + const hops = 8 + relays := make([]string, 512) + for i := range relays { + relays[i] = fmt.Sprintf("%02x%062x", i%256, i) + } + origin := strings.Repeat("f", 64) // distinct from every resolved relay + stamp := now.UTC().Format(time.RFC3339) + hopsSeen := make(map[string]bool) + for id := firstID; id < firstID+count; id++ { + pt := 5 + tx := &StoreTx{ + ID: id, Hash: fmt.Sprintf("%064x", id), RawHex: strings.Repeat("ab", 64), + FirstSeen: stamp, LatestSeen: stamp, PayloadType: &pt, + DecodedJSON: fmt.Sprintf(`{"pubKey":%q,"text":"synthetic churn packet %d"}`, origin, id), + } + s.packets = append(s.packets, tx) + s.byHash[tx.Hash], s.byTxID[id] = tx, tx + s.byPayloadType[pt] = append(s.byPayloadType[pt], tx) + s.indexByNode(tx) + for j := 0; j < fanout; j++ { + pks, rawHops := make([]string, hops), make([]string, hops) + for k := range pks { + pks[k] = relays[(id*17+j*19+k*13)%len(relays)] + rawHops[k] = fmt.Sprintf("%q", pks[k][:2]) + } + path := "[" + strings.Join(rawHops, ",") + "]" + observer := fmt.Sprintf("observer-%03d", (id+j)%225) + snr := float64(j%12) - 4 + obs := &StoreObs{ID: id*fanout + j, TransmissionID: id, + ObserverID: observer, ObserverName: "Synthetic " + observer, + PathJSON: path, Timestamp: stamp, Direction: "rx", SNR: &snr} + tx.addObservation(obs) + s.byObsID[obs.ID] = obs + s.byObserver[observer] = append(s.byObserver[observer], obs) + s.totalObs++ + s.trackedBytes += estimateStoreObsBytes(obs) + s.indexResolvedPathHops(tx, pks, hopsSeen, nil, obs) + } + pickBestObservation(tx) + s.trackedBytes += rechargeTx(tx) + addTxToPathHopIndex(s.byPathHop, tx) + } +} + +func newEvictionChurnStore(now time.Time) *PacketStore { + s := makeTestStore(0, now, 0) + s.retentionHours = 1 + s.byPathHop = make(map[string][]*StoreTx) + s.useResolvedPathIndex = true + s.initResolvedPathIndex() + return s +} + +func evictedNodePacketCount(s *PacketStore) int { + seen := make(map[int]bool) + for _, list := range s.byNode { + for _, tx := range list { + if s.byTxID[tx.ID] != tx { + seen[tx.ID] = true + } + } + } + return len(seen) +} + +func TestEvictionChurnOwnsOnlyLivePackets(t *testing.T) { + now := time.Now().UTC() + s := newEvictionChurnStore(now) + const batch = 8 + for cycle := 0; cycle < 5; cycle++ { + for _, tx := range s.packets { + tx.FirstSeen = now.Add(-2 * time.Hour).Format(time.RFC3339) + } + appendEvictionChurnBatch(s, cycle*batch+1, batch, 4, now) + s.RunEviction() + if len(s.packets) != batch || s.totalObs != batch*4 { + t.Fatalf("cycle %d retained %d packets/%d observations", cycle, len(s.packets), s.totalObs) + } + if got := evictedNodePacketCount(s); got != 0 { + t.Fatalf("cycle %d retains %d evicted packets through the node index", cycle, got) + } + var charged int64 + for _, tx := range s.packets { + charged += tx.accountedBytes + for _, obs := range tx.Observations { + charged += estimateStoreObsBytes(obs) + } + } + if s.trackedBytes != charged { + t.Fatalf("cycle %d charged %d bytes, want live-packet sum %d", cycle, s.trackedBytes, charged) + } + } +} + +// One operation is eight complete 1,000-transmission generations, each with +// sixteen observations and distinct resolved eight-hop paths. It leaves the +// final generation live. GC samples run outside the timer, and only the store +// retains packet pointers. This measures in-memory churn, not SQL or HTTP. +func BenchmarkEvictionOwnershipChurn(b *testing.B) { + const batch, fanout, cycles = 1000, 16, 8 + b.ReportAllocs() + var retained, tracked, orphans, livePackets, liveObservations float64 + for i := 0; i < b.N; i++ { + b.StopTimer() + runtime.GC() + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + now := time.Now().UTC() + s := newEvictionChurnStore(now) + b.StartTimer() + for cycle := 0; cycle < cycles; cycle++ { + for _, tx := range s.packets { + tx.FirstSeen = now.Add(-2 * time.Hour).Format(time.RFC3339) + } + appendEvictionChurnBatch(s, cycle*batch+1, batch, fanout, now) + s.RunEviction() + } + b.StopTimer() + runtime.GC() + runtime.ReadMemStats(&after) + packetCount, observationCount := len(s.packets), 0 + for _, tx := range s.packets { + observationCount += len(tx.Observations) + } + if packetCount != batch || observationCount != batch*fanout { + b.Fatalf("retained %d packets/%d observations, want %d/%d", packetCount, observationCount, batch, batch*fanout) + } + retained += float64(int64(after.HeapAlloc) - int64(before.HeapAlloc)) + tracked += float64(s.trackedBytes) + orphans += float64(evictedNodePacketCount(s)) + livePackets += float64(packetCount) + liveObservations += float64(observationCount) + runtime.KeepAlive(s) + b.StartTimer() + } + b.ReportMetric(retained/float64(b.N), "retained-B/op") + b.ReportMetric(tracked/float64(b.N), "tracked-B/op") + b.ReportMetric(orphans/float64(b.N), "orphan-tx/op") + b.ReportMetric(livePackets/float64(b.N), "live-tx/op") + b.ReportMetric(liveObservations/float64(b.N), "live-obs/op") +} diff --git a/cmd/server/eviction_ownership_test.go b/cmd/server/eviction_ownership_test.go new file mode 100644 index 000000000..8b508e42e --- /dev/null +++ b/cmd/server/eviction_ownership_test.go @@ -0,0 +1,374 @@ +package main + +import ( + "context" + "database/sql" + "fmt" + "reflect" + "slices" + "strings" + "sync/atomic" + "testing" + "time" +) + +func assertEvictedNodeMemberships(t *testing.T, s *PacketStore, removed map[int]bool) { + t.Helper() + for key, list := range s.byNode { + for _, tx := range list[:cap(list)] { + if tx != nil && removed[tx.ID] { + t.Errorf("node index %q retains evicted transmission %d", key, tx.ID) + } + } + for id := range s.nodeHashes[key] { + if s.byTxID[id] == nil { + t.Errorf("node hash index %q retains evicted transmission %d", key, id) + } + } + } + for key, hashes := range s.nodeHashes { + if len(hashes) == 0 || len(s.byNode[key]) == 0 { + t.Errorf("node hash index %q has no live memberships", key) + } + } +} + +func TestEvictionOwnsResolvedNodeMemberships(t *testing.T) { + for _, mode := range []string{"missing", "different", "expanded", "matching", "index-disabled"} { + t.Run(mode, func(t *testing.T) { + now := time.Now().UTC() + s := makeTestStore(4, now.Add(-30*time.Minute), 0) + s.retentionHours = 1 + s.useResolvedPathIndex = mode != "index-disabled" + s.initResolvedPathIndex() + s.byPathHop = make(map[string][]*StoreTx) + relay, other := strings.Repeat("a", 64), strings.Repeat("b", 64) + for _, tx := range s.packets { + s.indexResolvedPathHops(tx, []string{relay}, make(map[string]bool), nil, nil) + } + s.packets[0].FirstSeen = now.Add(-2 * time.Hour).Format(time.RFC3339) + batch := map[int][]string{} + switch mode { + case "different": + batch[1] = []string{other} + case "expanded", "matching": + batch[1] = []string{relay} + } + removed := map[int]bool{1: true} + if mode == "expanded" { + // The SQL batch was selected while only ID 1 was eligible. + // Expiration can advance before the actual eviction lock is acquired. + s.packets[1].FirstSeen = now.Add(-90 * time.Minute).Format(time.RFC3339) + removed[2] = true + } + // Even a duplicate index entry must not keep an evicted packet alive. + s.byNode[relay] = append(s.byNode[relay], s.packets[0]) + s.mu.Lock() + got := s.EvictStaleWithRP(batch) + s.mu.Unlock() + if got != len(removed) { + t.Fatalf("evicted %d packets, want %d", got, len(removed)) + } + assertEvictedNodeMemberships(t, s, removed) + if len(s.byNode[relay]) != 4-len(removed) { + t.Errorf("resolved relay has %d memberships, want %d live packets", len(s.byNode[relay]), 4-len(removed)) + } + for _, tx := range s.packets { + if !s.nodeHasTx(relay, tx) { + t.Errorf("lost surviving hash %q", tx.Hash) + } + s.addToByNode(tx, relay) + } + if len(s.byNode[relay]) != 4-len(removed) { + t.Error("surviving memberships lost their deduplication markers") + } + }) + } +} + +func TestEvictionAfterLocalPathResolution(t *testing.T) { + for _, producer := range []string{"cold-missing", "ingest-different", "late-missing"} { + t.Run(producer, func(t *testing.T) { + relay := strings.Repeat("a", 64) + other := strings.Repeat("b", 64) + dsn := createTestDBWithResolvedPath(t, 2, nil) + w, err := sql.Open("sqlite3", dsn+"?_journal_mode=WAL") + if err != nil { + t.Fatal(err) + } + defer w.Close() + if _, err = w.Exec("INSERT INTO nodes(public_key,name,role) VALUES(?,'Synthetic relay','repeater')", relay); err != nil { + t.Fatal(err) + } + var persisted any + if producer == "ingest-different" { + persisted = fmt.Sprintf(`[%q]`, other) + } + path := `["aa"]` + if producer == "late-missing" { + path = `[]` + } + if _, err = w.Exec("UPDATE observations SET path_json=?, resolved_path=?", path, persisted); err != nil { + t.Fatal(err) + } + db, err := OpenDB(dsn) + if err != nil { + t.Fatal(err) + } + defer db.Close() + s := NewPacketStore(db, &PacketStoreConfig{RetentionHours: 24}) + now := time.Now().UTC() + if producer == "cold-missing" { + if err := s.loadChunk(now.Add(-72*time.Hour), now); err != nil { + t.Fatal(err) + } + } else { + s.IngestNewFromDB(0, 10) + if producer == "late-missing" { + for id := 1; id <= 2; id++ { + if _, err = w.Exec(`INSERT INTO observations(id,transmission_id,observer_id,path_json,timestamp) + VALUES(?,?,'late-observer','["aa"]',?)`, id+2, id, now.Add(-48*time.Hour).Format(time.RFC3339)); err != nil { + t.Fatal(err) + } + } + s.IngestNewObservations(2, 10) + } + } + if len(s.byNode[relay]) != 2 { + t.Fatalf("producer did not locally resolve both packets: %d memberships", len(s.byNode[relay])) + } + if got := s.RunEviction(); got != 2 { + t.Fatalf("evicted %d packets, want 2", got) + } + assertEvictedNodeMemberships(t, s, map[int]bool{1: true, 2: true}) + var count int + if err := w.QueryRow("SELECT COUNT(*) FROM transmissions").Scan(&count); err != nil || count != 2 { + t.Fatalf("cache eviction changed SQL history: count=%d, err=%v", count, err) + } + }) + } +} + +func TestEvictionDoesNotWaitForSQL(t *testing.T) { + db := setupTestDB(t) + defer db.Close() + db.conn.SetMaxOpenConns(1) + conn, err := db.conn.Conn(context.Background()) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + s := makeTestStore(2, time.Now().Add(-2*time.Hour), 0) + s.retentionHours, s.db = 1, db + done := make(chan int, 1) + go func() { done <- s.RunEviction() }() + select { + case got := <-done: + if got != 2 { + t.Fatalf("evicted %d packets, want 2", got) + } + case <-time.After(time.Second): + // Release the only SQL connection and drain eviction before failing. + conn.Close() + <-done + t.Fatal("cache eviction waited for a SQL connection") + } +} + +func TestEvictionReleasesPrivateSliceTails(t *testing.T) { + now := time.Now().UTC() + s := makeTestStore(4, now.Add(-30*time.Minute), 0) + s.retentionHours = 1 + for _, tx := range s.packets[:2] { + tx.FirstSeen = now.Add(-2 * time.Hour).Format(time.RFC3339) + } + // Cold load can append newest-first buckets. Removing their oldest tail + // must clear it, not just shorten the visible slice. + slices.Reverse(s.byPayloadType[4]) + for _, list := range s.byObserver { + slices.Reverse(list) + } + if got := s.RunEviction(); got != 2 { + t.Fatalf("evicted %d packets, want 2", got) + } + check := func(owner string, list []*StoreTx) { + t.Helper() + for _, tx := range list[:cap(list)] { + if tx != nil && tx.ID <= 2 { + t.Errorf("%s backing array retains evicted transmission %d", owner, tx.ID) + } + } + } + check("payload", s.byPayloadType[4]) + for key, list := range s.byObserver { + for _, obs := range list[:cap(list)] { + if obs != nil && obs.TransmissionID <= 2 { + t.Errorf("observer %q backing array retains evicted observation %d", key, obs.ID) + } + } + } + // An empty primary slice must not keep its former contents alive. + for _, tx := range s.packets { + tx.FirstSeen = now.Add(-2 * time.Hour).Format(time.RFC3339) + } + if got := s.RunEviction(); got != 2 { + t.Fatalf("final eviction removed %d packets, want 2", got) + } + for _, tx := range s.packets[:cap(s.packets)] { + if tx != nil { + t.Error("empty packet store retains a transmission in its backing array") + break + } + } +} + +func TestPathHopRemovalReleasesTail(t *testing.T) { + old, live := &StoreTx{ID: 1}, &StoreTx{ID: 2} + idx := map[string][]*StoreTx{"aa": {live, old}} + removeTxFromSlice(idx, "aa", old) + if !reflect.DeepEqual(idx["aa"], []*StoreTx{live}) { + t.Fatal("path-hop removal lost its survivor") + } + for _, tx := range idx["aa"][:cap(idx["aa"])] { + if tx == old { + t.Fatal("removed path-hop transmission remains in the backing array") + } + } +} + +func TestEvictionCopiesOnlyAffectedDistanceArrays(t *testing.T) { + for _, tc := range []struct { + name string + hopsAffected bool + pathsAffected bool + }{ + {name: "neither"}, + {name: "hops-only", hopsAffected: true}, + {name: "paths-only", pathsAffected: true}, + } { + t.Run(tc.name, func(t *testing.T) { + now := time.Now().UTC() + s := makeTestStore(4, now.Add(-30*time.Minute), 0) + s.retentionHours = 1 + s.packets[0].FirstSeen = now.Add(-2 * time.Hour).Format(time.RFC3339) + wantHops := slices.Clone(s.distHops[1:]) + wantPaths := slices.Clone(s.distPaths[1:]) + if tc.hopsAffected { + // Removals may follow a live prefix and occur more than once. + s.distHops = []distHopRecord{s.distHops[1], s.distHops[0], s.distHops[2], s.distHops[0], s.distHops[3]} + } else { + s.distHops = slices.Clone(wantHops) + } + if tc.pathsAffected { + s.distPaths = []distPathRecord{s.distPaths[1], s.distPaths[2], s.distPaths[3], s.distPaths[0]} + } else { + s.distPaths = slices.Clone(wantPaths) + } + + s.mu.RLock() + hops, paths := s.snapshotDistanceIndexLocked() + s.mu.RUnlock() + beforeHops, beforePaths := slices.Clone(hops), slices.Clone(paths) + if got := s.RunEviction(); got != 1 { + t.Fatalf("evicted %d packets, want 1", got) + } + if !reflect.DeepEqual(s.distHops, wantHops) || !reflect.DeepEqual(s.distPaths, wantPaths) { + t.Fatal("eviction did not preserve the surviving distance records") + } + if !reflect.DeepEqual(hops, beforeHops) || !reflect.DeepEqual(paths, beforePaths) { + t.Error("eviction modified a distance snapshot borrowed by an unlocked reader") + } + // Equal contents alone would miss an unnecessary full-array allocation. + if !tc.hopsAffected && &s.distHops[0] != &hops[0] { + t.Error("eviction copied the unaffected distance hop array") + } + if !tc.pathsAffected && &s.distPaths[0] != &paths[0] { + t.Error("eviction copied the unaffected distance path array") + } + }) + } +} + +func TestEvictionPreservesDistanceSnapshots(t *testing.T) { + for _, operation := range []string{"eviction", "path-update"} { + t.Run(operation, func(t *testing.T) { + now := time.Now().UTC() + s := makeTestStore(4, now.Add(-30*time.Minute), 0) + s.retentionHours = 1 + s.packets[0].FirstSeen = now.Add(-2 * time.Hour).Format(time.RFC3339) + // Use the same snapshot boundary as computeAnalyticsDistance. The + // arrays it owns must survive later eviction and live path updates. + s.mu.RLock() + hops, paths := s.snapshotDistanceIndexLocked() + s.mu.RUnlock() + wantHops, wantPaths := slices.Clone(hops), slices.Clone(paths) + if operation == "eviction" { + s.RunEviction() + } else { + s.nodeCacheTime = now + s.nodePM = &prefixMap{m: map[string][]nodeInfo{}} + s.mu.Lock() + s.updateDistanceIndexForTxs(s.packets[:1]) + s.mu.Unlock() + } + if !reflect.DeepEqual(hops, wantHops) || !reflect.DeepEqual(paths, wantPaths) { + t.Error("writer modified a distance snapshot borrowed by an unlocked reader") + } + for _, hop := range s.distHops[:cap(s.distHops)] { + if hop.tx != nil && hop.tx.ID == 1 { + t.Error("distance hop backing array retains a removed record") + } + } + for _, path := range s.distPaths[:cap(s.distPaths)] { + if path.tx != nil && path.tx.ID == 1 { + t.Error("distance path backing array retains a removed record") + } + } + }) + } +} + +func TestEvictionReleasesGroupedCache(t *testing.T) { + now := time.Now().UTC() + s := makeTestStore(4, now.Add(-30*time.Minute), 0) + s.retentionHours = 1 + if got := s.QueryGroupedPackets(PacketQuery{}).Total; got != 4 { + t.Fatalf("warm grouped total=%d, want 4", got) + } + // A returned snapshot is allowed to finish after eviction. Invalidating the + // cache must release its root without clearing an active reader's array. + reader := s.groupedCacheTxs + s.groupedCacheExp = now.Add(-time.Second) + s.packets[0].FirstSeen = now.Add(-2 * time.Hour).Format(time.RFC3339) + s.RunEviction() + if s.groupedCacheTxs != nil { + t.Error("eviction retained the expired grouped packet cache") + } + if len(reader) != 4 || reader[0].tx == nil { + t.Error("cache invalidation corrupted a borrowed grouped snapshot") + } + if got := s.QueryGroupedPackets(PacketQuery{}).Total; got != 3 { + t.Errorf("grouped total after eviction=%d, want 3", got) + } +} + +func TestGroupedCacheRejectsPreEvictionSnapshot(t *testing.T) { + now := time.Now().UTC() + s := makeTestStore(4, now.Add(-30*time.Minute), 0) + s.retentionHours = 1 + s.QueryGroupedPackets(PacketQuery{}) + oldSnapshot := s.groupedCacheTxs + oldGeneration := atomic.LoadInt64(&s.evicted) + s.packets[0].FirstSeen = now.Add(-2 * time.Hour).Format(time.RFC3339) + s.RunEviction() + // A query that captured its pointers before eviction can finish sorting + // afterwards. Exercise its real publication step in that exact order. + s.cacheGroupedPackets(oldSnapshot, "retired", oldGeneration) + if s.groupedCacheTxs != nil { + t.Fatal("late grouped-cache publication retained a pre-eviction snapshot") + } + s.cacheGroupedPackets([]groupedEntry{{tx: s.packets[0]}, {tx: s.packets[1]}, {tx: s.packets[2]}}, "live", atomic.LoadInt64(&s.evicted)) + if len(s.groupedCacheTxs) != 3 || s.groupedCacheKey != "live" { + t.Fatal("current grouped snapshot was not published") + } +} diff --git a/cmd/server/eviction_reachability_test.go b/cmd/server/eviction_reachability_test.go index bf6377e33..d5b685aea 100644 --- a/cmd/server/eviction_reachability_test.go +++ b/cmd/server/eviction_reachability_test.go @@ -7,7 +7,6 @@ import ( "runtime/pprof" "slices" "strings" - "sync/atomic" "testing" "time" ) @@ -350,48 +349,3 @@ func BenchmarkEvictionNodeSweep(b *testing.B) { }) } } - -func TestEvictionReleasesGroupedCache(t *testing.T) { - now := time.Now().UTC() - s := makeTestStore(4, now.Add(-30*time.Minute), 0) - s.retentionHours = 1 - if got := s.QueryGroupedPackets(PacketQuery{}).Total; got != 4 { - t.Fatalf("warm grouped total=%d, want 4", got) - } - // A returned snapshot is allowed to finish after eviction. Invalidating the - // cache must release its root without clearing an active reader's array. - reader := s.groupedCacheTxs - s.groupedCacheExp = now.Add(-time.Second) - s.packets[0].FirstSeen = now.Add(-2 * time.Hour).Format(time.RFC3339) - s.RunEviction() - if s.groupedCacheTxs != nil { - t.Error("eviction retained the expired grouped packet cache") - } - if len(reader) != 4 || reader[0].tx == nil { - t.Error("cache invalidation corrupted a borrowed grouped snapshot") - } - if got := s.QueryGroupedPackets(PacketQuery{}).Total; got != 3 { - t.Errorf("grouped total after eviction=%d, want 3", got) - } -} - -func TestGroupedCacheRejectsPreEvictionSnapshot(t *testing.T) { - now := time.Now().UTC() - s := makeTestStore(4, now.Add(-30*time.Minute), 0) - s.retentionHours = 1 - s.QueryGroupedPackets(PacketQuery{}) - oldSnapshot := s.groupedCacheTxs - oldGeneration := atomic.LoadInt64(&s.evicted) - s.packets[0].FirstSeen = now.Add(-2 * time.Hour).Format(time.RFC3339) - s.RunEviction() - // A query that captured its pointers before eviction can finish sorting - // afterwards. Exercise its real publication step in that exact order. - s.cacheGroupedPackets(oldSnapshot, "retired", oldGeneration) - if s.groupedCacheTxs != nil { - t.Fatal("late grouped-cache publication retained a pre-eviction snapshot") - } - s.cacheGroupedPackets([]groupedEntry{{tx: s.packets[0]}, {tx: s.packets[1]}, {tx: s.packets[2]}}, "live", atomic.LoadInt64(&s.evicted)) - if len(s.groupedCacheTxs) != 3 || s.groupedCacheKey != "live" { - t.Fatal("current grouped snapshot was not published") - } -} diff --git a/cmd/server/eviction_resolved_pubkeys_test.go b/cmd/server/eviction_resolved_pubkeys_test.go deleted file mode 100644 index 078ca351f..000000000 --- a/cmd/server/eviction_resolved_pubkeys_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package main - -import ( - "fmt" - "runtime" - "testing" -) - -func evictionResolvedStore(t testing.TB, n int) (*PacketStore, []int) { - t.Helper() - db := setupTestDB(t) - t.Cleanup(func() { db.Close() }) - pk := func(i int) string { return fmt.Sprintf("%064x", i) } - ids := make([]int, 0, n) - for i := 1; i <= n; i++ { - if _, err := db.conn.Exec(`INSERT INTO transmissions (id, raw_hex, hash, first_seen) VALUES (?, '00', ?, '2026-01-01T00:00:00Z')`, i, fmt.Sprintf("h%015d", i)); err != nil { - t.Fatal(err) - } - for o := 0; o < 3; o++ { - rp := `["` + pk(i%9) + `",null,"` + pk(o+20) + `","` + pk(i%9) + `"]` - if _, err := db.conn.Exec(`INSERT INTO observations (transmission_id, observer_idx, path_json, timestamp, resolved_path) VALUES (?, 1, '["aa","bb","cc","dd"]', 0, ?)`, i, rp); err != nil { - t.Fatal(err) - } - } - ids = append(ids, i) - } - return &PacketStore{db: db}, ids -} - -// Eviction looks up the resolved pubkeys of every packet it drops, once a -// minute in steady state. It decoded each resolved_path into a pointer per -// hop and built a de-dup map per packet: about 130MB of allocations per -// five minutes on a busy week. -func TestResolvedPubkeysForEvictionBatch(t *testing.T) { - s, ids := evictionResolvedStore(t, 300) - got := s.resolvedPubkeysForEvictionBatch(ids) - want := []string{fmt.Sprintf("%064x", 1), fmt.Sprintf("%064x", 20), fmt.Sprintf("%064x", 21), fmt.Sprintf("%064x", 22)} - if fmt.Sprint(got[1]) != fmt.Sprint(want) { - t.Fatalf("tx 1: %v, want %v (first-seen order, de-duplicated)", got[1], want) - } - if len(got) != 300 { - t.Fatalf("%d packets resolved, want 300", len(got)) - } - var a, b runtime.MemStats - runtime.GC() - runtime.ReadMemStats(&a) - _ = s.resolvedPubkeysForEvictionBatch(ids) - runtime.ReadMemStats(&b) - per := float64(b.Mallocs-a.Mallocs) / float64(len(ids)) - t.Logf("%.1f allocations per evicted packet (3 observations, 4 hops each)", per) - if per > 20 { - t.Fatalf("%.1f allocations per evicted packet, limit 20", per) - } -} diff --git a/cmd/server/hash_migrate.go b/cmd/server/hash_migrate.go deleted file mode 100644 index cb4cd4a32..000000000 --- a/cmd/server/hash_migrate.go +++ /dev/null @@ -1,167 +0,0 @@ -package main - -import ( - "log" - "sync/atomic" - "time" -) - -// migrateContentHashesAsync recomputes content hashes in batches after the -// server is already serving HTTP. Packets whose hash changes are updated in -// both the DB and the in-memory byHash index. The migration is idempotent: -// once all hashes match the current formula it completes instantly. -func migrateContentHashesAsync(store *PacketStore, batchSize int, yieldDuration time.Duration) { - // Eviction compacts the slice, and background loads may prepend packets. - // Keep one boundary pointer, not a snapshot that pins all data. - store.mu.RLock() - total := len(store.packets) - evicted := atomic.LoadInt64(&store.evicted) - var last *StoreTx - if total > 0 { - last = store.packets[total-1] - } - store.mu.RUnlock() - // Caller holds store.mu. Appends leave the original range intact; merges - // before its end move the boundary and invalidate offset-based traversal. - sameRange := func() bool { - return len(store.packets) >= total && atomic.LoadInt64(&store.evicted) == evicted && - (total == 0 || store.packets[total-1] == last) - } - inputChanged := false - - // #1856: every DB failure below continues to the next batch, so the loop - // always reaches the deferred completion. Setting the flag unconditionally - // therefore reported success after migrating nothing, which is exactly what - // happens on the read-only handle the server holds since #1283: begin, - // prepare and commit all fail, every batch is skipped, and /api/stats then - // answers hashMigrationComplete: true. - failedBatches := 0 - defer func() { - if r := recover(); r != nil { - log.Printf("[hash-migrate] panic recovered: %v", r) - failedBatches++ - } - if failedBatches > 0 { - log.Printf("[hash-migrate] INCOMPLETE: %d batch(es) could not be written; "+ - "hashMigrationComplete stays false. On a read-only DB handle this is expected "+ - "and the migration belongs in the ingestor (#1856).", failedBatches) - return - } - store.mu.RLock() - defer store.mu.RUnlock() - if inputChanged || !sameRange() { - log.Printf("[hash-migrate] INCOMPLETE: packet set changed during migration") - return - } - store.hashMigrationComplete.Store(true) - }() - - migrated := 0 - for offset := 0; offset < total; offset += batchSize { - // Collect stale hashes in this batch under RLock. - type hashUpdate struct { - tx *StoreTx - oldHash string - newHash string - } - var updates []hashUpdate - - func() { - store.mu.RLock() - defer store.mu.RUnlock() - if !sameRange() { - inputChanged = true - return - } - end := min(offset+batchSize, min(total, len(store.packets))) - for _, tx := range store.packets[offset:end] { - if tx.RawHex == "" { - continue - } - newHash := ComputeContentHash(tx.RawHex) - if newHash != tx.Hash { - updates = append(updates, hashUpdate{tx: tx, oldHash: tx.Hash, newHash: newHash}) - } - } - }() - if inputChanged { - return - } - - if len(updates) == 0 { - continue - } - - // Write batch to DB in a single transaction. - dbTx, err := store.db.conn.Begin() - if err != nil { - log.Printf("[hash-migrate] begin tx: %v", err) - failedBatches++ - continue - } - stmt, err := dbTx.Prepare("UPDATE transmissions SET hash = ? WHERE id = ?") - if err != nil { - log.Printf("[hash-migrate] prepare: %v", err) - dbTx.Rollback() - failedBatches++ - continue - } - - for _, u := range updates { - if _, err := stmt.Exec(u.newHash, u.tx.ID); err != nil { - // UNIQUE constraint = two old hashes map to the same new hash (duplicate). - // Merge observations to the surviving tx, delete the duplicate. - log.Printf("[hash-migrate] tx %d collides — merging duplicate", u.tx.ID) - var survID int - if err2 := dbTx.QueryRow("SELECT id FROM transmissions WHERE hash = ?", u.newHash).Scan(&survID); err2 == nil { - dbTx.Exec("UPDATE observations SET transmission_id = ? WHERE transmission_id = ?", survID, u.tx.ID) - dbTx.Exec("DELETE FROM transmissions WHERE id = ?", u.tx.ID) - u.newHash = "" // mark for in-memory removal only - } - } - } - stmt.Close() - - if err := dbTx.Commit(); err != nil { - log.Printf("[hash-migrate] commit: %v", err) - failedBatches++ - continue - } - - // Update in-memory index under write lock. - func() { - store.mu.Lock() - defer store.mu.Unlock() - for _, u := range updates { - // SQL can wait while eviction removes or replaces this object. - if store.byTxID[u.tx.ID] != u.tx { - inputChanged = true - continue - } - delete(store.byHash, u.oldHash) - if u.newHash == "" { - // Merged duplicate — remove from packets slice and indexes. - delete(store.byTxID, u.tx.ID) - // Move observations to survivor if present. - if surv := store.byHash[ComputeContentHash(u.tx.RawHex)]; surv != nil { - for _, obs := range u.tx.Observations { - surv.Observations = append(surv.Observations, obs) - surv.ObservationCount++ - } - } - } else { - u.tx.Hash = u.newHash - store.byHash[u.newHash] = u.tx - } - migrated++ - } - }() - - // Yield to let HTTP handlers run. - time.Sleep(yieldDuration) - } - - if migrated > 0 { - log.Printf("[hash-migrate] Migrated %d content hashes to new formula", migrated) - } -} diff --git a/cmd/server/hash_migrate_eviction_test.go b/cmd/server/hash_migrate_eviction_test.go deleted file mode 100644 index 293d9918e..000000000 --- a/cmd/server/hash_migrate_eviction_test.go +++ /dev/null @@ -1,210 +0,0 @@ -package main - -import ( - "context" - "database/sql" - "runtime" - "testing" - "time" -) - -func TestMigrateContentHashesAsyncSurvivesEviction(t *testing.T) { - for _, tc := range []struct { - name string - batchSize int - replace bool - }{ - {name: "later_batch", batchSize: 1}, - {name: "pending_batch", batchSize: 4}, - {name: "replacement_with_same_ID", batchSize: 4, replace: true}, - } { - t.Run(tc.name, func(t *testing.T) { - dbPath := createTestDBWithResolvedPath(t, 4, nil) - // Reuse the valid raw packet from the existing migration regression. - // The fixture's legacy hashes intentionally need migration. - writer, err := sql.Open("sqlite3", dbPath) - if err != nil { - t.Fatal(err) - } - _, err = writer.Exec("UPDATE transmissions SET raw_hex = ?", "0A00D69FD7A5A7475DB07337749AE61FA53A4788E976") - writer.Close() - if err != nil { - t.Fatal(err) - } - db, err := OpenDB(dbPath) - if err != nil { - t.Fatal(err) - } - defer db.Close() - store := NewPacketStore(db, &PacketStoreConfig{RetentionHours: 24}) - now := time.Now().UTC() - if err := store.loadChunk(now.Add(-72*time.Hour), now); err != nil { - t.Fatal(err) - } - if len(store.packets) != 4 { - t.Fatalf("fixture loaded %d packets, want 4", len(store.packets)) - } - original := append([]*StoreTx(nil), store.packets...) - - finish := pauseHashMigrationAtSQL(t, store, tc.batchSize) - defer finish() - if got := store.RunEviction(); got != 4 { - t.Fatalf("evicted %d packets, want 4", got) - } - - var replacements []*StoreTx - if tc.replace { - // A reloaded transmission has the same ID but a new pointer. - // Refill to the original length so a length-only check is insufficient. - store.mu.Lock() - for _, tx := range original { - replacement := &StoreTx{ID: tx.ID, Hash: tx.Hash, RawHex: tx.RawHex, FirstSeen: now.Format(time.RFC3339)} - replacements = append(replacements, replacement) - store.packets = append(store.packets, replacement) - store.byTxID[replacement.ID] = replacement - store.byHash[replacement.Hash] = replacement - } - store.mu.Unlock() - } - finish() - - if !store.mu.TryLock() { - // The migration has returned and no other readers exist. Release - // its leaked RLock so the assertion failure does not strand the test. - store.mu.RUnlock() - t.Error("migration returned while retaining the store read lock") - } else { - store.mu.Unlock() - } - if !store.mu.TryRLock() { - t.Fatal("store read lock is unusable after migration") - } - defer store.mu.RUnlock() - if got := len(store.packets); got != len(replacements) { - t.Errorf("primary packet count = %d, want %d", got, len(replacements)) - } - if got := len(store.byTxID); got != len(replacements) { - t.Errorf("byTxID count = %d, want %d", got, len(replacements)) - } - if got := len(store.byHash); got != len(replacements) { - t.Errorf("byHash count = %d, want %d; pending migration republished evicted packets", got, len(replacements)) - } - for _, tx := range original { - for hash, cached := range store.byHash { - if cached == tx { - t.Errorf("byHash[%q] retained evicted transmission %d", hash, tx.ID) - } - } - } - for _, tx := range replacements { - if store.byTxID[tx.ID] != tx || store.byHash[tx.Hash] != tx { - t.Errorf("migration changed ownership of replacement transmission %d", tx.ID) - } - } - if store.hashMigrationComplete.Load() { - t.Error("migration must not claim completion after its input changed") - } - var unchanged int - if err := db.conn.QueryRow("SELECT COUNT(*) FROM transmissions WHERE hash LIKE 'hash1558_%'").Scan(&unchanged); err != nil { - t.Fatal(err) - } - if unchanged != 4 { - t.Errorf("read-only fixture retained %d original hashes, want 4", unchanged) - } - }) - } -} - -func TestMigrateContentHashesAsyncKeepsInitialRange(t *testing.T) { - for _, prepend := range []bool{false, true} { - name := "append" - if prepend { - name = "prepend" - } - t.Run(name, func(t *testing.T) { - db := setupTestDBv2(t) - defer db.Close() - store := NewPacketStore(db, nil) - rawHex := "0A00D69FD7A5A7475DB07337749AE61FA53A4788E976" - for _, suffix := range []string{"76", "77", "78"} { - raw := rawHex[:len(rawHex)-2] + suffix - if _, err := db.conn.Exec(`INSERT INTO transmissions (raw_hex, hash, first_seen, route_type, payload_type) - VALUES (?, ?, datetime('now'), 0, 2)`, raw, "old-"+raw); err != nil { - t.Fatal(err) - } - } - if err := store.Load(); err != nil { - t.Fatal(err) - } - if len(store.packets) != 3 { - t.Fatalf("fixture loaded %d packets, want 3", len(store.packets)) - } - original := append([]*StoreTx(nil), store.packets...) - finish := pauseHashMigrationAtSQL(t, store, 2) - defer finish() - - added := &StoreTx{ID: 4, RawHex: rawHex, Hash: "added-hash"} - store.mu.Lock() - if prepend { - store.packets = mergeChunkIntoPackets([]*StoreTx{added}, store.packets) - } else { - store.packets = append(store.packets, added) - } - store.byTxID[added.ID] = added - store.byHash[added.Hash] = added - store.mu.Unlock() - finish() - - for i, tx := range original { - wantHash := ComputeContentHash(tx.RawHex) - if prepend && i >= 2 { - wantHash = "old-" + tx.RawHex - } - if store.byHash[wantHash] != tx || tx.Hash != wantHash { - t.Errorf("original transmission %d hash = %q, want %q and retained ownership", tx.ID, tx.Hash, wantHash) - } - } - if added.Hash != "added-hash" || store.byHash["added-hash"] != added { - t.Error("bounded migration changed a transmission outside its initial range") - } - if got := store.hashMigrationComplete.Load(); got != !prepend { - t.Errorf("hashMigrationComplete = %v, want %v", got, !prepend) - } - }) - } -} - -// Occupy the SQL pool until the real migration captures its first batch and -// releases the store's read lock. The caller must release and drain it. -func pauseHashMigrationAtSQL(t *testing.T, store *PacketStore, batchSize int) func() { - t.Helper() - store.db.conn.SetMaxOpenConns(1) - conn, err := store.db.conn.Conn(context.Background()) - if err != nil { - t.Fatal(err) - } - before := store.db.conn.Stats().WaitCount - done := make(chan struct{}) - go func() { - defer close(done) - migrateContentHashesAsync(store, batchSize, 0) - }() - finish := func() { - t.Helper() - conn.Close() - select { - case <-done: - case <-time.After(5 * time.Second): - t.Fatal("migration did not return after releasing the SQL connection") - } - } - deadline := time.Now().Add(5 * time.Second) - for store.db.conn.Stats().WaitCount == before && time.Now().Before(deadline) { - runtime.Gosched() - } - if store.db.conn.Stats().WaitCount == before { - finish() - t.Fatal("migration did not reach its first SQL batch") - } - return finish -} diff --git a/cmd/server/hash_migrate_test.go b/cmd/server/hash_migrate_test.go deleted file mode 100644 index 0cc7f21e6..000000000 --- a/cmd/server/hash_migrate_test.go +++ /dev/null @@ -1,122 +0,0 @@ -package main - -import ( - "testing" - "time" -) - -func TestMigrateContentHashesAsync(t *testing.T) { - db := setupTestDBv2(t) - store := NewPacketStore(db, nil) - - // Insert a packet with a manually wrong hash (simulating old formula). - rawHex := "0A00D69FD7A5A7475DB07337749AE61FA53A4788E976" - correctHash := ComputeContentHash(rawHex) - wrongHash := "deadbeef12345678" - - _, err := db.conn.Exec(`INSERT INTO transmissions (raw_hex, hash, first_seen, route_type, payload_type) - VALUES (?, ?, datetime('now'), 0, 2)`, rawHex, wrongHash) - if err != nil { - t.Fatal(err) - } - - if err := store.Load(); err != nil { - t.Fatal(err) - } - - if store.byHash[wrongHash] == nil { - t.Fatal("expected packet under wrong hash before migration") - } - - migrateContentHashesAsync(store, 100, time.Millisecond) - - if !store.hashMigrationComplete.Load() { - t.Error("expected hashMigrationComplete to be true") - } - if store.byHash[wrongHash] != nil { - t.Error("old hash should be removed from index") - } - if store.byHash[correctHash] == nil { - t.Error("new hash should be in index") - } - - var dbHash string - err = db.conn.QueryRow("SELECT hash FROM transmissions WHERE raw_hex = ?", rawHex).Scan(&dbHash) - if err != nil { - t.Fatal(err) - } - if dbHash != correctHash { - t.Errorf("DB hash = %s, want %s", dbHash, correctHash) - } -} - -func TestMigrateContentHashesAsync_NoOp(t *testing.T) { - db := setupTestDBv2(t) - store := NewPacketStore(db, nil) - - rawHex := "0A00D69FD7A5A7475DB07337749AE61FA53A4788E976" - correctHash := ComputeContentHash(rawHex) - - _, err := db.conn.Exec(`INSERT INTO transmissions (raw_hex, hash, first_seen, route_type, payload_type) - VALUES (?, ?, datetime('now'), 0, 2)`, rawHex, correctHash) - if err != nil { - t.Fatal(err) - } - - if err := store.Load(); err != nil { - t.Fatal(err) - } - - migrateContentHashesAsync(store, 100, time.Millisecond) - - if !store.hashMigrationComplete.Load() { - t.Error("expected hashMigrationComplete to be true") - } - if store.byHash[correctHash] == nil { - t.Error("hash should remain in index") - } -} - -// #1856: a migration that could not write anything must not report completion. -// -// In production the server holds a mode=ro handle (#1283), so Begin, Prepare and -// Commit all fail, every batch takes a `continue`, and the loop reaches the -// deferred completion having migrated nothing. Before this fix the flag was set -// unconditionally there, so /api/stats answered hashMigrationComplete: true -// after doing no work at all. -// -// Closing the handle stands in for the read-only one: it is deterministic and it -// exercises the identical failure path (Begin returns an error, batch skipped). -func TestMigrateContentHashesAsyncDoesNotClaimCompletionWhenWritesFail(t *testing.T) { - db := setupTestDBv2(t) - store := NewPacketStore(db, nil) - - rawHex := "0A00D69FD7A5A7475DB07337749AE61FA53A4788E976" - wrongHash := "deadbeef12345678" - if _, err := db.conn.Exec(`INSERT INTO transmissions (raw_hex, hash, first_seen, route_type, payload_type) - VALUES (?, ?, datetime('now'), 0, 2)`, rawHex, wrongHash); err != nil { - t.Fatal(err) - } - if err := store.Load(); err != nil { - t.Fatal(err) - } - if store.byHash[wrongHash] == nil { - t.Fatal("expected packet under the wrong hash before migration") - } - - // Make every write fail, the way a read-only handle does in production. - if err := db.conn.Close(); err != nil { - t.Fatal(err) - } - - migrateContentHashesAsync(store, 100, time.Millisecond) - - if store.hashMigrationComplete.Load() { - t.Error("hashMigrationComplete must stay false when no batch could be written; " + - "reporting true here is what #1856 called self-reported success") - } - if store.byHash[wrongHash] == nil { - t.Error("the in-memory index must be left alone when the DB write failed, " + - "otherwise memory and disk disagree") - } -} diff --git a/cmd/server/hash_migration_status_test.go b/cmd/server/hash_migration_status_test.go new file mode 100644 index 000000000..185d810b0 --- /dev/null +++ b/cmd/server/hash_migration_status_test.go @@ -0,0 +1,47 @@ +package main + +import "testing" + +// TestHashMigrationCompleteReadsIngestorStatus pins /api/stats +// hashMigrationComplete to the ingestor's _async_migrations row (#1856): +// false until the row says done, then latched true. +func TestHashMigrationCompleteReadsIngestorStatus(t *testing.T) { + db := setupTestDBv2(t) + + if db.hashMigrationComplete() { + t.Fatal("missing _async_migrations table must read as not complete") + } + + // The ingestor's bookkeeping table (cmd/ingestor/async_migration.go). + if _, err := db.conn.Exec(`CREATE TABLE _async_migrations ( + name TEXT PRIMARY KEY, status TEXT NOT NULL, started_at TEXT, ended_at TEXT, error TEXT)`); err != nil { + t.Fatal(err) + } + if db.hashMigrationComplete() { + t.Fatal("missing row must read as not complete") + } + for _, status := range []string{"pending_async", "failed", "cancelled"} { + if _, err := db.conn.Exec(`INSERT OR REPLACE INTO _async_migrations (name, status) VALUES (?, ?)`, + contentHashMigrationName, status); err != nil { + t.Fatal(err) + } + if db.hashMigrationComplete() { + t.Fatalf("status %q must read as not complete", status) + } + } + + if _, err := db.conn.Exec(`UPDATE _async_migrations SET status = 'done' WHERE name = ?`, contentHashMigrationName); err != nil { + t.Fatal(err) + } + if !db.hashMigrationComplete() { + t.Fatal("done must read as complete") + } + + // done is final, so the answer is latched and the table is not read again. + if _, err := db.conn.Exec(`DROP TABLE _async_migrations`); err != nil { + t.Fatal(err) + } + if !db.hashMigrationComplete() { + t.Fatal("complete must stay latched once seen") + } +} diff --git a/cmd/server/helpers_test.go b/cmd/server/helpers_test.go index b2bff47a6..f146ffc53 100644 --- a/cmd/server/helpers_test.go +++ b/cmd/server/helpers_test.go @@ -8,6 +8,7 @@ import ( "net/http/httptest" "os" "path/filepath" + "regexp" "strings" "testing" ) @@ -447,6 +448,37 @@ func TestSpaHandlerCacheBust(t *testing.T) { }) } +// Every top-level page gets the same cache buster as index.html, so a tool +// page (area-map.html, geofilter-builder.html) served fresh never runs a +// script cached from before the server started. +func TestSpaHandlerBustsEveryTopLevelPage(t *testing.T) { + dir := t.TempDir() + os.WriteFile(filepath.Join(dir, "index.html"), []byte(``), 0644) + os.WriteFile(filepath.Join(dir, "tool.html"), []byte(``), 0644) + handler := spaHandler(dir, http.FileServer(http.Dir(dir))) + + get := func(p string) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + handler.ServeHTTP(w, httptest.NewRequest("GET", p, nil)) + return w + } + bust := regexp.MustCompile(`v=(\d+)`) + index, tool := get("/"), get("/tool.html") + if strings.Contains(tool.Body.String(), "__BUST__") { + t.Fatalf("tool.html kept its placeholder: %s", tool.Body.String()) + } + im, tm := bust.FindStringSubmatch(index.Body.String()), bust.FindStringSubmatch(tool.Body.String()) + if im == nil || tm == nil || im[1] != tm[1] { + t.Errorf("tool.html buster %v, index.html buster %v: want the same timestamp", tm, im) + } + if got := tool.Header().Get("Cache-Control"); got != "no-cache, no-store, must-revalidate" { + t.Errorf("tool.html Cache-Control = %q", got) + } + if got := tool.Header().Get("Content-Type"); !strings.HasPrefix(got, "text/html") { + t.Errorf("tool.html Content-Type = %q", got) + } +} + func TestWriteJSON(t *testing.T) { w := httptest.NewRecorder() writeJSON(w, map[string]interface{}{"key": "value"}) diff --git a/cmd/server/los_config.go b/cmd/server/los_config.go new file mode 100644 index 000000000..1c3884025 --- /dev/null +++ b/cmd/server/los_config.go @@ -0,0 +1,124 @@ +package main + +// Radio line-of-sight (LOS) for packet routes on the map. OPT-IN, like +// rfParams (#1268): without los.enabled the server fetches nothing, +// /api/elevation/profile answers 404 and /api/config/client omits "los", so +// the frontend shows no LOS UI at all. +// +// The server only supplies terrain elevation along each leg (elevation.go), +// read from the SRTM tiles the planner uses (terrain_config.go: one shared +// source, in memory, never written to disk or the DB). Earth curvature, the +// Fresnel zone and the verdict are computed in the browser (public/los.js) so +// the antenna-height and frequency inputs re-render instantly. + +import ( + "log" + "time" +) + +const ( + defaultLOSFrequencyMHz = 910.525 + defaultLOSAntennaM = 5.0 + defaultLOSKFactor = 4.0 / 3.0 + + // losMaxPoints caps the route points in one profile request (so at most + // losMaxPoints-1 legs). + losMaxPoints = 16 + // losMaxLegKm: longer legs are not real LoRa links worth a profile; they + // come back with error "too_long" and load no terrain. + losMaxLegKm = 300.0 + // losMaxTiles caps the distinct 1° SRTM tiles one profile request may + // load; a leg that would take the request past it is "too_many_tiles". + // A 300 km leg's samples fall in about 10 tiles within the SRTM band. The + // shared source keeps at least this many resident (terrainViewTiles). + losMaxTiles = 16 + // losTileWait is how long a request waits for its tiles before it + // answers 202; the downloads carry on without it. + losTileWait = 1500 * time.Millisecond + // losPollAfterS is the 202's retry_after_s. + losPollAfterS = 2 +) + +// LOSConfig is the "los" block in config.json. Terrain tiles come from the +// "terrain" block (TerrainConfig). +type LOSConfig struct { + Enabled bool `json:"enabled"` + FrequencyMHz float64 `json:"frequencyMhz"` + AntennaHeightM float64 `json:"antennaHeightM"` + KFactor float64 `json:"kFactor"` +} + +func (c *LOSConfig) enabled() bool { return c != nil && c.Enabled } + +// resolved returns the config with defaults applied and out-of-range values +// replaced by their default (logged once at startup by the caller). +func (c *LOSConfig) resolved() (LOSConfig, []string) { + out := LOSConfig{ + FrequencyMHz: defaultLOSFrequencyMHz, + AntennaHeightM: defaultLOSAntennaM, + KFactor: defaultLOSKFactor, + } + var warns []string + if c == nil { + return out, nil + } + out.Enabled = c.Enabled + if c.FrequencyMHz != 0 { + if c.FrequencyMHz >= 100 && c.FrequencyMHz <= 6000 { + out.FrequencyMHz = c.FrequencyMHz + } else { + warns = append(warns, "los.frequencyMhz must be within 100-6000; using the default") + } + } + if c.AntennaHeightM != 0 { + if c.AntennaHeightM > 0 && c.AntennaHeightM <= 300 { + out.AntennaHeightM = c.AntennaHeightM + } else { + warns = append(warns, "los.antennaHeightM must be within 0-300; using the default") + } + } + if c.KFactor != 0 { + if c.KFactor >= 0.5 && c.KFactor <= 10 { + out.KFactor = c.KFactor + } else { + warns = append(warns, "los.kFactor must be within 0.5-10; using the default") + } + } + return out, warns +} + +// LOSClientConfig is /api/config/client "los"; present only when enabled. +type LOSClientConfig struct { + FrequencyMHz float64 `json:"frequencyMhz"` + AntennaHeightM float64 `json:"antennaHeightM"` + KFactor float64 `json:"kFactor"` + MaxPoints int `json:"maxPoints"` + MaxLegKm float64 `json:"maxLegKm"` +} + +func (c *LOSConfig) clientConfig() *LOSClientConfig { + if !c.enabled() { + return nil + } + r, _ := c.resolved() + return &LOSClientConfig{ + FrequencyMHz: r.FrequencyMHz, + AntennaHeightM: r.AntennaHeightM, + KFactor: r.KFactor, + MaxPoints: losMaxPoints, + MaxLegKm: losMaxLegKm, + } +} + +// logLOSConfig reports the effective config once at startup. +func logLOSConfig(c *LOSConfig) { + if !c.enabled() { + return + } + r, warns := c.resolved() + for _, w := range warns { + log.Printf("[los] %s", w) + } + log.Printf("[los] enabled (%.3f MHz, antenna=%.1f m, k=%.3f, up to %d terrain tiles a request)", + r.FrequencyMHz, r.AntennaHeightM, r.KFactor, losMaxTiles) +} diff --git a/cmd/server/los_config_test.go b/cmd/server/los_config_test.go new file mode 100644 index 000000000..1b19b3b67 --- /dev/null +++ b/cmd/server/los_config_test.go @@ -0,0 +1,77 @@ +package main + +import ( + "bytes" + "encoding/json" + "log" + "strings" + "testing" +) + +func TestLOSConfigDisabledByDefault(t *testing.T) { + var c *LOSConfig + if c.enabled() { + t.Fatal("nil los config must be disabled") + } + if c.clientConfig() != nil { + t.Fatal("disabled los must not appear in /api/config/client") + } + if (&LOSConfig{}).clientConfig() != nil { + t.Fatal("enabled=false must not appear in /api/config/client") + } +} + +func TestLOSConfigDefaults(t *testing.T) { + cc := (&LOSConfig{Enabled: true}).clientConfig() + if cc == nil { + t.Fatal("enabled los must appear in /api/config/client") + } + if cc.FrequencyMHz != defaultLOSFrequencyMHz || cc.AntennaHeightM != defaultLOSAntennaM || + cc.KFactor != defaultLOSKFactor || cc.MaxPoints != losMaxPoints || cc.MaxLegKm != losMaxLegKm { + t.Fatalf("unexpected defaults: %+v", *cc) + } + // The sample count varies per leg now; the client config no longer names one. + b, _ := json.Marshal(cc) + if strings.Contains(string(b), "samples") { + t.Fatalf("client config %s still carries samples", b) + } + if _, warns := (&LOSConfig{Enabled: true}).resolved(); len(warns) != 0 { + t.Fatalf("default warns: %v", warns) + } +} + +func TestLOSConfigOverridesAndValidation(t *testing.T) { + r, warns := (&LOSConfig{Enabled: true, FrequencyMHz: 869.618, AntennaHeightM: 12, KFactor: 1}).resolved() + if r.FrequencyMHz != 869.618 || r.AntennaHeightM != 12 || r.KFactor != 1 || len(warns) != 0 { + t.Fatalf("valid overrides not kept: %+v %v", r, warns) + } + r, warns = (&LOSConfig{Enabled: true, FrequencyMHz: 50, AntennaHeightM: -3, KFactor: 99}).resolved() + if r.FrequencyMHz != defaultLOSFrequencyMHz || r.AntennaHeightM != defaultLOSAntennaM || r.KFactor != defaultLOSKFactor { + t.Fatalf("invalid values must fall back to defaults: %+v", r) + } + if len(warns) != 3 { + t.Fatalf("want 3 warnings, got %v", warns) + } +} + +func TestLOSConfigLog(t *testing.T) { + var buf bytes.Buffer + prev, flags := log.Writer(), log.Flags() + log.SetOutput(&buf) + t.Cleanup(func() { log.SetOutput(prev); log.SetFlags(flags) }) + logLOSConfig(&LOSConfig{Enabled: true, FrequencyMHz: 50}) + out := buf.String() + for _, want := range []string{ + "los.frequencyMhz must be within 100-6000; using the default", + "[los] enabled (910.525 MHz, antenna=5.0 m, k=1.333, up to 16 terrain tiles a request)", + } { + if !strings.Contains(out, want) { + t.Errorf("log lacks %q:\n%s", want, out) + } + } + buf.Reset() + logLOSConfig(&LOSConfig{}) + if buf.Len() != 0 { + t.Fatalf("disabled los logged %q", buf.String()) + } +} diff --git a/cmd/server/lru.go b/cmd/server/lru.go new file mode 100644 index 000000000..4628b18f0 --- /dev/null +++ b/cmd/server/lru.go @@ -0,0 +1,97 @@ +package main + +// lru is the in-memory least-recently-used map behind the planner's result +// caches (plannerLRU) and the SRTM tile cache (srtmSource). + +import "container/list" + +// lru maps keys to values, bounded by an item count and, when sizeOf is +// set, a byte budget. A Put past either bound evicts least recently used +// entries until the cache is within both. Expiry, if any, is the caller's. +// It is not safe for concurrent use: each caller guards it with its own +// mutex. +type lru[K comparable, V any] struct { + maxItems int + maxBytes int // ignored when sizeOf is nil + sizeOf func(K, V) int // an entry's share of maxBytes; nil: no byte budget + size int // sum of the entries' sizeOf + ll *list.List // *lruEntry[K, V], most recently used first + items map[K]*list.Element +} + +type lruEntry[K comparable, V any] struct { + key K + val V + size int // sizeOf(key, val) when stored +} + +// newLRU holds at most maxItems entries (at least one) and, when sizeOf is +// not nil, at most maxBytes of sizeOf in total. +func newLRU[K comparable, V any](maxItems, maxBytes int, sizeOf func(K, V) int) *lru[K, V] { + return &lru[K, V]{maxItems: max(maxItems, 1), maxBytes: maxBytes, sizeOf: sizeOf, + ll: list.New(), items: make(map[K]*list.Element)} +} + +// Get returns k's value and marks it most recently used. +func (c *lru[K, V]) Get(k K) (V, bool) { + el, ok := c.items[k] + if !ok { + var zero V + return zero, false + } + c.ll.MoveToFront(el) + return el.Value.(*lruEntry[K, V]).val, true +} + +// Peek returns k's value without changing the eviction order. +func (c *lru[K, V]) Peek(k K) (V, bool) { + el, ok := c.items[k] + if !ok { + var zero V + return zero, false + } + return el.Value.(*lruEntry[K, V]).val, true +} + +// Put stores v under k, replacing any value k had, as the most recently +// used entry, then evicts from the least recently used end until the cache +// is within its bounds. A value over the whole byte budget on its own is +// not stored, and drops any value k had, so it cannot flush the rest. +func (c *lru[K, V]) Put(k K, v V) { + sz := 0 + if c.sizeOf != nil { + if sz = c.sizeOf(k, v); sz > c.maxBytes { + c.Remove(k) + return + } + } + if el, ok := c.items[k]; ok { + e := el.Value.(*lruEntry[K, V]) + c.size += sz - e.size + e.val, e.size = v, sz + c.ll.MoveToFront(el) + } else { + c.items[k] = c.ll.PushFront(&lruEntry[K, V]{key: k, val: v, size: sz}) + c.size += sz + } + // k is at the front and fits on its own, so it is never evicted here. + for c.ll.Len() > c.maxItems || (c.sizeOf != nil && c.size > c.maxBytes) { + c.removeElement(c.ll.Back()) + } +} + +// Remove drops k, if present. +func (c *lru[K, V]) Remove(k K) { + if el, ok := c.items[k]; ok { + c.removeElement(el) + } +} + +// Len is the number of entries. +func (c *lru[K, V]) Len() int { return c.ll.Len() } + +func (c *lru[K, V]) removeElement(el *list.Element) { + e := c.ll.Remove(el).(*lruEntry[K, V]) + delete(c.items, e.key) + c.size -= e.size +} diff --git a/cmd/server/lru_test.go b/cmd/server/lru_test.go new file mode 100644 index 000000000..89078caa6 --- /dev/null +++ b/cmd/server/lru_test.go @@ -0,0 +1,112 @@ +package main + +import ( + "slices" + "testing" +) + +// lruKeys lists c's keys, most recently used first. +func lruKeys[K comparable, V any](c *lru[K, V]) []K { + var out []K + for el := c.ll.Front(); el != nil; el = el.Next() { + out = append(out, el.Value.(*lruEntry[K, V]).key) + } + return out +} + +func lruWant[K comparable, V any](t *testing.T, c *lru[K, V], want ...K) { + t.Helper() + if got := lruKeys(c); !slices.Equal(got, want) || c.Len() != len(want) || len(c.items) != len(want) { + t.Fatalf("keys %v (len %d, map %d), want %v", got, c.Len(), len(c.items), want) + } +} + +func TestLRUEvictsLeastRecentlyUsed(t *testing.T) { + c := newLRU[string, int](3, 0, nil) + c.Put("a", 1) + c.Put("b", 2) + c.Put("c", 3) + lruWant(t, c, "c", "b", "a") + if v, ok := c.Get("a"); !ok || v != 1 { + t.Fatalf("get a = %v, %v", v, ok) + } + lruWant(t, c, "a", "c", "b") + c.Put("d", 4) // b is least recently used + lruWant(t, c, "d", "a", "c") + if v, ok := c.Get("b"); ok || v != 0 { + t.Fatalf("evicted b = %v, %v", v, ok) + } + c.Put("e", 5) + c.Put("f", 6) + lruWant(t, c, "f", "e", "d") + c.Remove("e") + c.Remove("missing") + lruWant(t, c, "f", "d") +} + +func TestLRUPeekDoesNotTouch(t *testing.T) { + c := newLRU[int, string](2, 0, nil) + c.Put(1, "one") + c.Put(2, "two") + if v, ok := c.Peek(1); !ok || v != "one" { + t.Fatalf("peek 1 = %q, %v", v, ok) + } + if _, ok := c.Peek(3); ok { + t.Fatal("peek of a missing key hit") + } + lruWant(t, c, 2, 1) + c.Put(3, "three") // 1 is still the least recently used + lruWant(t, c, 3, 2) +} + +func TestLRUUpdateInPlace(t *testing.T) { + c := newLRU[string, []byte](3, 100, func(k string, v []byte) int { return len(k) + len(v) }) + c.Put("a", make([]byte, 10)) + c.Put("b", make([]byte, 10)) + c.Put("c", make([]byte, 10)) + c.Put("a", make([]byte, 30)) // replaces, moves to the front, resizes + lruWant(t, c, "a", "c", "b") + if v, _ := c.Peek("a"); len(v) != 30 || c.size != 31+11+11 { + t.Fatalf("a holds %d bytes, size %d", len(v), c.size) + } + c.Put("b", make([]byte, 1)) // shrinking evicts nothing + lruWant(t, c, "b", "a", "c") + if c.size != 2+31+11 { + t.Fatalf("size %d", c.size) + } +} + +func TestLRUByteBudget(t *testing.T) { + c := newLRU[string, []byte](100, 100, func(k string, v []byte) int { return len(k) + len(v) }) + for _, k := range []string{"a", "b", "c", "d"} { + c.Put(k, make([]byte, 24)) // 25 bytes each: exactly the budget + } + lruWant(t, c, "d", "c", "b", "a") + c.Get("a") + c.Put("e", make([]byte, 49)) // 50 bytes: b and c go, oldest first + lruWant(t, c, "e", "a", "d") + if c.size != 50+25+25 { + t.Fatalf("size %d", c.size) + } + // A value over the whole budget is not stored, flushes nothing, and + // drops the value its key had. + c.Put("d", make([]byte, 100)) + lruWant(t, c, "e", "a") + if c.size != 75 { + t.Fatalf("size %d after an oversized put", c.size) + } + // One that fits exactly evicts everything else. + c.Put("f", make([]byte, 99)) + lruWant(t, c, "f") + c.Remove("f") + if c.size != 0 || c.Len() != 0 { + t.Fatalf("empty cache: size %d, len %d", c.size, c.Len()) + } +} + +func TestLRUHoldsAtLeastOne(t *testing.T) { + c := newLRU[int, int](0, 0, nil) + c.Put(1, 1) + c.Put(2, 2) + lruWant(t, c, 2) +} diff --git a/cmd/server/main.go b/cmd/server/main.go index 7f34cf732..6f30975fb 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -510,6 +510,12 @@ func main() { cfg.RfParams.NodesURL, cfg.RfParams.PresetsURL, cfg.RfParams.refresh(), cfg.RfParams.maxAge()) } + // Radio line-of-sight profiles and the repeater planner, over one shared + // SRTM terrain source. OPT-IN: without los.enabled /api/elevation/profile + // answers 404, without planner.enabled /api/planner/* does, and with + // neither no terrain tile is ever fetched. + srv.elevation, srv.planner = newTerrainServices(cfg, srv) + // Steady-state repeater-enrichment recomputer (issue #1262). // Prewarms the bulk caches feeding handleNodes so the very first // /api/nodes?limit=2000 from live.js's SPA bootstrap hits a @@ -626,6 +632,12 @@ func main() { // 3b. Close users.db (user management, opt-in; no-op when off). srv.closeUserManagement() + // 3c. Cancel planner jobs and wait for them: they read the store, + // so before dbClose. + if srv.planner != nil { + srv.planner.Close() + } + // 4. Close database (release SQLite WAL lock) if err := dbClose(); err != nil { log.Printf("[server] DB close error: %v", err) @@ -640,9 +652,6 @@ func main() { // process. The server reads the results via the periodic // recompNeighborGraph / fetchResolvedPathForObs paths. - // Migrate old content hashes in background (one-time, idempotent). - go migrateContentHashesAsync(store, 5000, 100*time.Millisecond) - if err := httpServer.ListenAndServe(); err != http.ErrServerClosed { log.Fatalf("[server] %v", err) } @@ -652,16 +661,22 @@ func main() { // It reads index.html once at creation time and replaces the __BUST__ placeholder // with a Unix timestamp so browsers fetch fresh JS/CSS after each server restart. func spaHandler(root string, fs http.Handler) http.Handler { - // Pre-process index.html: replace __BUST__ with a cache-bust timestamp - indexPath := filepath.Join(root, "index.html") - rawHTML, err := os.ReadFile(indexPath) - if err != nil { - log.Printf("[static] warning: could not read index.html for cache-bust: %v", err) - rawHTML = []byte("

CoreScope

index.html not found

") - } + // Pre-process every top-level page, index.html and the tool pages + // (area-map.html, geofilter-builder.html): replace __BUST__ with a + // cache-bust timestamp, so each loads the scripts of this start. bustValue := fmt.Sprintf("%d", time.Now().Unix()) - indexHTML := []byte(strings.ReplaceAll(string(rawHTML), "__BUST__", bustValue)) - log.Printf("[static] cache-bust value: %s", bustValue) + pages := bustPages(root, bustValue) + indexHTML, ok := pages["/index.html"] + if !ok { + log.Printf("[static] warning: could not read index.html for cache-bust") + indexHTML = []byte("

CoreScope

index.html not found

") + } + log.Printf("[static] cache-bust value: %s (%d pages)", bustValue, len(pages)) + servePage := func(w http.ResponseWriter, body []byte) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") + w.Write(body) + } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Defense-in-depth: explicitly reject path-traversal attempts before @@ -674,20 +689,21 @@ func spaHandler(root string, fs http.Handler) http.Handler { http.Error(w, "bad request", http.StatusBadRequest) return } - // Serve pre-processed index.html for root and /index.html - if r.URL.Path == "/" || r.URL.Path == "/index.html" { - w.Header().Set("Content-Type", "text/html; charset=utf-8") - w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") - w.Write(indexHTML) + // Serve the pre-processed index.html for the root, and each + // pre-processed page (/index.html included) at its own path + if r.URL.Path == "/" { + servePage(w, indexHTML) + return + } + if page, ok := pages[r.URL.Path]; ok { + servePage(w, page) return } path := filepath.Join(root, r.URL.Path) if _, err := os.Stat(path); os.IsNotExist(err) { // SPA fallback — serve pre-processed index.html - w.Header().Set("Content-Type", "text/html; charset=utf-8") - w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") - w.Write(indexHTML) + servePage(w, indexHTML) return } // Disable caching for JS/CSS/HTML @@ -698,6 +714,29 @@ func spaHandler(root string, fs http.Handler) http.Handler { }) } +// bustPages reads each .html file at the top of root, keyed by its URL path +// ("/index.html"), with every __BUST__ replaced by bust. +func bustPages(root, bust string) map[string][]byte { + pages := map[string][]byte{} + entries, err := os.ReadDir(root) + if err != nil { + log.Printf("[static] warning: could not list %s for cache-bust: %v", root, err) + return pages + } + for _, e := range entries { + if e.IsDir() || !strings.EqualFold(filepath.Ext(e.Name()), ".html") { + continue + } + raw, err := os.ReadFile(filepath.Join(root, e.Name())) + if err != nil { + log.Printf("[static] warning: could not read %s for cache-bust: %v", e.Name(), err) + continue + } + pages["/"+e.Name()] = []byte(strings.ReplaceAll(string(raw), "__BUST__", bust)) + } + return pages +} + // isSafeStaticPath rejects request paths that contain traversal sequences // or backslashes — defense-in-depth for the SPA static handler so a future // router with SkipClean(true) cannot expose the filesystem. Empty input is diff --git a/cmd/server/musl_thread_stack_linux_test.go b/cmd/server/musl_thread_stack_linux_test.go new file mode 100644 index 000000000..2720259a7 --- /dev/null +++ b/cmd/server/musl_thread_stack_linux_test.go @@ -0,0 +1,91 @@ +package main + +import ( + "fmt" + "os" + "runtime" + "strings" + "syscall" + "testing" +) + +// Regression for musl thread stacks. musl sizes every non-main thread's stack +// from the ELF PT_GNU_STACK size (floor 128 KiB), and cgo calls into SQLite +// run on the calling thread's stack. SQLite's multiSelect recurses ~850 B per +// UNION ALL term, so the wide chunked queries below overflow 128 KiB off the +// main thread and SIGSEGV the process. +// +// Which links are exposed: a native musl link with gcc and GNU ld (`go test` +// or `make build` on Alpine) writes a zero PT_GNU_STACK and crashes here +// without -Wl,-z,stack-size=8388608. zig's linker writes 16 MiB by default, so +// the zig-linked release binaries pass with or without the flag, and so does +// any glibc link. That makes this a test for Alpine hosts (`make test` passes +// the flag); the shipped artifacts are guarded by the readelf checks in the +// Dockerfile and the release job instead. +// +// Linux only: it needs the thread id to stay off the main thread. + +// offMainThread runs fn on an OS thread that is not the process's main thread. +// The main thread has the kernel-sized stack, so it would hide the bug. A +// goroutine locked to the main thread cannot be moved off it, so it runs fn in +// a fresh goroutine instead; a fresh goroutine is never on the main thread +// while the locking goroutine still holds it. +func offMainThread(fn func()) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + if syscall.Gettid() != os.Getpid() { + fn() + return + } + done := make(chan struct{}) + go func() { + defer close(done) + runtime.LockOSThread() + fn() + }() + <-done +} + +func TestMuslThreadStackWideUnionQueries(t *testing.T) { + srv := seedClientNames(t) + + // 249 keys nothing matches and one that resolves, in the second chunk. + keys := make([]string, 0, 250) + for i := 0; i < 249; i++ { + keys = append(keys, fmt.Sprintf("%08x", 0x30000000+i)) + } + keys = append(keys, "c0cd") + // 160 targets nothing shares a prefix with, and one whose 8-byte prefix is + // also the seeded node cnnAdvertPK's. + targets := make([]string, 0, 161) + for i := 0; i < 160; i++ { + targets = append(targets, fmt.Sprintf("%016x", 0x4000000000000000+uint64(i))+strings.Repeat("0", 48)) + } + sharedTarget := cnnAdvertPK[:16] + strings.Repeat("f", 48) + targets = append(targets, sharedTarget) + + var hits map[string]prefixHit + var shared map[string]bool + offMainThread(func() { + hits = srv.lookupPrefixes(keys) + shared = srv.sharedEightBytePrefixes(targets) + }) + + // A failed lookupPrefixes chunk drops its keys, and a failed + // sharedEightBytePrefixes chunk marks every prefix in it shared. Both + // results are checked exactly, so neither failure passes as "no match". + if len(hits) != len(keys) { + t.Fatalf("lookupPrefixes returned %d keys, want %d (a chunk failed)", len(hits), len(keys)) + } + if h := hits["c0cd"]; h.pubkey != cnnOnlyPK || h.name != "Self Named" { + t.Fatalf("c0cd = %+v, want %s / Self Named", h, cnnOnlyPK) + } + for _, k := range keys[:249] { + if h := hits[k]; h.matches != 0 { + t.Fatalf("key %s: unexpected match %+v", k, h) + } + } + if len(shared) != 1 || !shared[sharedTarget[:16]] { + t.Fatalf("sharedEightBytePrefixes = %v, want only %s (a chunk failed?)", shared, sharedTarget[:16]) + } +} diff --git a/cmd/server/neighbor_graph_snapshot.go b/cmd/server/neighbor_graph_snapshot.go new file mode 100644 index 000000000..ff112f478 --- /dev/null +++ b/cmd/server/neighbor_graph_snapshot.go @@ -0,0 +1,64 @@ +package main + +import ( + "maps" + "slices" + "strings" +) + +// SnapshotEdges returns a deep copy of every edge, in no particular order. +// AllEdges hands out the graph's own pointers, which ingest keeps mutating +// under g.mu; the copies here (Observers, CountsByMode and Candidates +// included) share nothing with the graph, so callers may read or change +// them without any lock. +func (g *NeighborGraph) SnapshotEdges() []NeighborEdge { + return g.snapshotEdges(nil) +} + +// snapshotEdgesAmong is SnapshotEdges restricted to resolved edges whose two +// endpoints are both in pubkeys (case-insensitive). Filtering happens before +// the copy, so the read lock is held for one cheap pass over the edges plus +// copies of the few that match, not a clone of the whole graph. +func (g *NeighborGraph) snapshotEdgesAmong(pubkeys []string) []NeighborEdge { + keep := make(map[string]struct{}, len(pubkeys)) + for _, pk := range pubkeys { + keep[strings.ToLower(pk)] = struct{}{} + } + return g.snapshotEdges(keep) +} + +// snapshotEdges copies the edges under the read lock; a nil keep copies all. +func (g *NeighborGraph) snapshotEdges(keep map[string]struct{}) []NeighborEdge { + if g == nil { + return nil + } + g.mu.RLock() + defer g.mu.RUnlock() + n := len(g.edges) + if keep != nil { + n = 0 + } + out := make([]NeighborEdge, 0, n) + for _, e := range g.edges { + if keep != nil && !edgeAmong(e, keep) { + continue + } + c := *e + c.Observers = maps.Clone(e.Observers) + c.CountsByMode = maps.Clone(e.CountsByMode) + c.Candidates = slices.Clone(e.Candidates) + out = append(out, c) + } + return out +} + +func edgeAmong(e *NeighborEdge, keep map[string]struct{}) bool { + if e.NodeB == "" { + return false + } + if _, ok := keep[strings.ToLower(e.NodeA)]; !ok { + return false + } + _, ok := keep[strings.ToLower(e.NodeB)] + return ok +} diff --git a/cmd/server/node_visibility.go b/cmd/server/node_visibility.go new file mode 100644 index 000000000..4203e0f09 --- /dev/null +++ b/cmd/server/node_visibility.go @@ -0,0 +1,110 @@ +package main + +import ( + "fmt" + "log" + + "github.com/meshcore-analyzer/geofilter" +) + +// nodeVisibility is the operator's node-hiding rules exactly as /api/nodes +// applies them: nodeBlacklist, hiddenNamePrefixes (#1181) and the geo_filter, +// which spares foreign-flagged nodes (#730). /api/nodes, the repeater planner +// and the route-LOS elevation proxy all decide with Visible, so a node one of +// them hides cannot surface through another (review #2391 point 4). +type nodeVisibility struct { + cfg *Config // nodeBlacklist and hiddenNamePrefixes; nil hides nothing + geo *GeoFilterConfig // nil: no geo_filter +} + +// nodeVisibility snapshots the current rules. The geo_filter is read under +// cfgMu (getGeoFilter); the blacklist and hidden prefixes are atomic reads in +// Config. +func (s *Server) nodeVisibility() nodeVisibility { + if s == nil || s.cfg == nil { + return nodeVisibility{} + } + return nodeVisibility{cfg: s.cfg, geo: s.getGeoFilter()} +} + +// Visible reports whether /api/nodes lists the node: not blacklisted, name +// not hidden, and inside the geo_filter unless foreign. lat, lon = 0, 0 is +// "no position fix", which the geo_filter always passes +// (geofilter.PassesFilter). +func (v nodeVisibility) Visible(pubkey, name string, lat, lon float64, foreign bool) bool { + if v.cfg.IsBlacklisted(pubkey) || v.cfg.IsNameHidden(name) { + return false + } + return foreign || geofilter.PassesFilter(lat, lon, v.geo) +} + +// filters reports whether any rule is configured. /api/nodes rewrites its +// total to the filtered page length only then. +func (v nodeVisibility) filters() bool { + return v.geo != nil || (v.cfg != nil && (len(v.cfg.NodeBlacklist) > 0 || len(v.cfg.HiddenNamePrefixes) > 0)) +} + +// infoRule is Visible for rows of the node cache (nodeInfo), which carry no +// foreign flag: foreign holds the pubkeys flagged foreign_advert (nil: none). +func (v nodeVisibility) infoRule(foreign map[string]struct{}) func(n *nodeInfo) bool { + return func(n *nodeInfo) bool { + lat, lon := n.Lat, n.Lon + if !n.HasGPS { + lat, lon = 0, 0 // no fix, as getAllNodes stores a NULL or 0,0 position + } + _, f := foreign[n.PublicKey] + return v.Visible(n.PublicKey, n.Name, lat, lon, f) + } +} + +// visibleNodeInfo returns the current rule for node-cache rows. It reads the +// foreign set from the DB when a geo_filter is set (the flag matters only +// then), so call it once per pass over the nodes, not per node. If that read +// fails no node is spared: the rule then hides more, never less. +func (s *Server) visibleNodeInfo() func(n *nodeInfo) bool { + v := s.nodeVisibility() + var foreign map[string]struct{} + if v.geo != nil && s.db != nil && s.db.conn != nil { + f, err := s.db.foreignNodeKeys() + if err != nil { + log.Printf("[visibility] foreign_advert read failed, foreign nodes outside the geo_filter stay hidden: %v", err) + } + foreign = f + } + return v.infoRule(foreign) +} + +// nodeVisibilityGen changes whenever a rule changes: the blacklist and +// hidden-prefix generations, and the geo_filter, which setGeoFilter swaps as +// a whole pointer so its address identifies the version. The foreign flag is +// not part of it: the ingestor only ever sets it, so a stale rule can only +// hide a newly foreign node until its next rebuild, never show a hidden one. +func (s *Server) nodeVisibilityGen() string { + if s == nil || s.cfg == nil { + return "" + } + return fmt.Sprintf("%d.%d.%p", s.cfg.BlacklistGeneration(), s.cfg.HiddenNamePrefixesGeneration(), s.getGeoFilter()) +} + +// foreignNodeKeys returns the pubkeys (as stored) of the nodes the ingestor +// flagged foreign_advert = 1 (#730; it writes only 0 or 1), through the +// partial index idx_nodes_foreign_advert. Read-only. +func (db *DB) foreignNodeKeys() (map[string]struct{}, error) { + rows, err := db.conn.Query(`SELECT public_key FROM nodes WHERE foreign_advert = 1 AND public_key IS NOT NULL`) + if err != nil { + return nil, err + } + defer rows.Close() + out := make(map[string]struct{}) + for rows.Next() { + var pk string + if err := rows.Scan(&pk); err != nil { + return nil, err + } + out[pk] = struct{}{} + } + if err := rows.Err(); err != nil { + return nil, err + } + return out, nil +} diff --git a/cmd/server/node_visibility_test.go b/cmd/server/node_visibility_test.go new file mode 100644 index 000000000..0b6bd28c2 --- /dev/null +++ b/cmd/server/node_visibility_test.go @@ -0,0 +1,325 @@ +package main + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "slices" + "testing" + "time" + + "github.com/gorilla/mux" +) + +// visTestPolygon is a geo_filter around lat 30..31, lon -98..-97. +func visTestPolygon() *GeoFilterConfig { + return &GeoFilterConfig{Polygon: [][2]float64{{30, -98}, {30, -97}, {31, -97}, {31, -98}}} +} + +func TestNodeVisibilityVisible(t *testing.T) { + cfg := &Config{NodeBlacklist: []string{"BAD1"}, HiddenNamePrefixes: []string{"zz-"}} + v := nodeVisibility{cfg: cfg, geo: visTestPolygon()} + cases := []struct { + name string + pubkey string + nodeName string + lat, lon float64 + foreign bool + want bool + }{ + {"visible inside the geo_filter", "aa01", "Hill", 30.5, -97.5, false, true}, + {"blacklisted, any case", "bad1", "Hill", 30.5, -97.5, false, false}, + {"hidden name prefix", "aa02", "zz-secret", 30.5, -97.5, false, false}, + {"outside the geo_filter", "aa03", "Far", 40, -80, false, false}, + {"outside the geo_filter but foreign (#730)", "aa04", "Bridged", 40, -80, true, true}, + {"foreign does not spare the blacklist", "bad1", "Bridged", 40, -80, true, false}, + {"foreign does not spare a hidden name", "aa05", "zz-bridged", 40, -80, true, false}, + {"no position fix passes the geo_filter", "aa06", "Nowhere", 0, 0, false, true}, + {"empty pubkey is never blacklisted", "", "Anon", 30.5, -97.5, false, true}, + } + for _, tc := range cases { + if got := v.Visible(tc.pubkey, tc.nodeName, tc.lat, tc.lon, tc.foreign); got != tc.want { + t.Errorf("%s: Visible=%v want %v", tc.name, got, tc.want) + } + } + if !v.filters() { + t.Error("configured rules: filters() = false") + } + + // No rules (and the zero value): everything is visible and nothing filters. + for _, none := range []nodeVisibility{{}, {cfg: &Config{}}} { + if !none.Visible("bad1", "zz-x", 40, -80, false) || none.filters() { + t.Errorf("no rules %+v hid a node or reports filtering", none) + } + } + // Each rule alone turns filtering on. + for name, one := range map[string]nodeVisibility{ + "blacklist": {cfg: &Config{NodeBlacklist: []string{"x"}}}, + "hidden": {cfg: &Config{HiddenNamePrefixes: []string{"x"}}}, + "geo": {geo: visTestPolygon()}, + } { + if !one.filters() { + t.Errorf("%s alone: filters() = false", name) + } + } +} + +func TestNodeVisibilityInfoRule(t *testing.T) { + v := nodeVisibility{cfg: &Config{NodeBlacklist: []string{"bad1"}}, geo: visTestPolygon()} + rule := v.infoRule(map[string]struct{}{"for1": {}, "bad1": {}}) + cases := []struct { + n nodeInfo + want bool + }{ + {nodeInfo{PublicKey: "in1", Lat: 30.5, Lon: -97.5, HasGPS: true}, true}, + {nodeInfo{PublicKey: "out1", Lat: 40, Lon: -80, HasGPS: true}, false}, + {nodeInfo{PublicKey: "for1", Lat: 40, Lon: -80, HasGPS: true}, true}, + {nodeInfo{PublicKey: "bad1", Lat: 40, Lon: -80, HasGPS: true}, false}, + // No fix: the position is ignored, as /api/nodes ignores a NULL one. + {nodeInfo{PublicKey: "nofix", Lat: 40, Lon: -80}, true}, + } + for _, tc := range cases { + if got := rule(&tc.n); got != tc.want { + t.Errorf("%s: %v want %v", tc.n.PublicKey, got, tc.want) + } + } + // A nil foreign set spares nobody. + if v.infoRule(nil)(&nodeInfo{PublicKey: "for1", Lat: 40, Lon: -80, HasGPS: true}) { + t.Error("nil foreign set spared a node outside the geo_filter") + } +} + +func TestNodeVisibilityGen(t *testing.T) { + cfg := &Config{} + srv := &Server{cfg: cfg} + g := srv.nodeVisibilityGen() + if srv.nodeVisibilityGen() != g { + t.Fatal("generation changed with no rule change") + } + // In order: removing the geo filter is only a change once one is set. + for _, c := range []struct { + name string + change func() + }{ + {"blacklist", func() { cfg.SetNodeBlacklist([]string{"x"}) }}, + {"hidden", func() { cfg.SetHiddenNamePrefixes([]string{"x"}) }}, + {"geo filter", func() { srv.setGeoFilter(visTestPolygon()) }}, + {"geo filter removed", func() { srv.setGeoFilter(nil) }}, + } { + before := srv.nodeVisibilityGen() + c.change() + if srv.nodeVisibilityGen() == before { + t.Errorf("%s change kept the generation", c.name) + } + } + var nilSrv *Server + if nilSrv.nodeVisibilityGen() != "" || (&Server{}).nodeVisibilityGen() != "" { + t.Fatal("configless server has a generation") + } + if v := nilSrv.nodeVisibility(); v.filters() { + t.Fatal("nil server filters") + } +} + +// visNode is one node of the mixed fixture and whether /api/nodes shows it. +type visNode struct { + pubkey, name string + lat, lon float64 // 0,0: stored as NULL + foreign bool + visible bool +} + +// visFixtureNodes covers every rule alone and foreign against each rule. +// Positions are distinct at elevKey's 5 decimals. +var visFixtureNodes = []visNode{ + {"vis00001", "Visible", 30.40001, -97.50001, false, true}, + {"bad00001", "Banned", 30.40002, -97.50002, false, false}, + {"hid00001", "zz-secret", 30.40003, -97.50003, false, false}, + {"out00001", "Outside", 32.50001, -97.50001, false, false}, + {"for00001", "Bridged", 32.50002, -97.50002, true, true}, + {"fbl00001", "Bridged banned", 32.50003, -97.50003, true, false}, + {"fhd00001", "zz-bridged", 32.50004, -97.50004, true, false}, + {"vis00002", "Visible room", 30.40004, -97.50004, false, true}, + {"nofix001", "No fix", 0, 0, false, true}, +} + +// visibilityFixture is a server whose DB holds visFixtureNodes (all +// repeaters, newest first in fixture order) and whose rules hide the +// bad*/zz-*/out* ones; rules=false leaves the rules unset. +func visibilityFixture(t *testing.T, rules bool) (*Server, *mux.Router) { + t.Helper() + srv, router := setupTestServer(t) + base := time.Now().UTC().Add(-time.Minute) + for i, n := range visFixtureNodes { + var lat, lon interface{} + if n.lat != 0 || n.lon != 0 { + lat, lon = n.lat, n.lon + } + foreign := 0 + if n.foreign { + foreign = 1 + } + seen := base.Add(-time.Duration(i) * time.Second).Format(time.RFC3339) + if _, err := srv.db.conn.Exec(`INSERT INTO nodes + (public_key, name, role, lat, lon, last_seen, first_seen, advert_count, foreign_advert) + VALUES (?, ?, 'repeater', ?, ?, ?, ?, 1, ?)`, n.pubkey, n.name, lat, lon, seen, seen, foreign); err != nil { + t.Fatal(err) + } + } + srv.store.InvalidateNodeCache() + if rules { + setVisibilityRules(srv) + } + return srv, router +} + +func setVisibilityRules(srv *Server) { + srv.cfg.SetNodeBlacklist([]string{"BAD00001", "fbl00001"}) + srv.cfg.SetHiddenNamePrefixes([]string{"zz-"}) + srv.setGeoFilter(visTestPolygon()) +} + +// fixtureKeys keeps, in order, the pubkeys from pks of fixture nodes that +// keep accepts. +func fixtureKeys(pks []string, keep func(visNode) bool) []string { + var out []string + for _, pk := range pks { + for _, n := range visFixtureNodes { + if n.pubkey == pk && keep(n) { + out = append(out, pk) + } + } + } + return out +} + +func anyVisNode(visNode) bool { return true } +func visNodeHasFix(n visNode) bool { return n.lat != 0 || n.lon != 0 } +func visNodeVisible(n visNode) bool { return n.visible } + +type visNodesPage struct { + Nodes []struct { + PublicKey string `json:"public_key"` + } `json:"nodes"` + Total int `json:"total"` +} + +func apiNodeKeys(t *testing.T, router http.Handler) ([]string, visNodesPage) { + t.Helper() + req := httptest.NewRequest("GET", "/api/nodes?limit=500", nil) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("/api/nodes: %d %s", w.Code, w.Body.String()) + } + var page visNodesPage + if err := json.Unmarshal(w.Body.Bytes(), &page); err != nil { + t.Fatal(err) + } + var pks []string + for _, n := range page.Nodes { + pks = append(pks, n.PublicKey) + } + return pks, page +} + +// /api/nodes applies all three rules (and the foreign exemption) in one +// pass: same rows, same order as the unfiltered page, total = rows kept. +func TestHandleNodesAppliesAllVisibilityRules(t *testing.T) { + srv, router := visibilityFixture(t, false) + all, page := apiNodeKeys(t, router) + if page.Total != len(all) { + t.Fatalf("unfiltered total %d, %d rows", page.Total, len(all)) + } + if len(fixtureKeys(all, anyVisNode)) != len(visFixtureNodes) { + t.Fatalf("unfiltered page misses fixture nodes: %v", all) + } + want := fixtureKeys(all, visNodeVisible) + + setVisibilityRules(srv) + got, page := apiNodeKeys(t, router) + if kept := fixtureKeys(got, anyVisNode); !slices.Equal(kept, want) { + t.Fatalf("visible fixture nodes %v, want %v", kept, want) + } + if page.Total != len(got) { + t.Fatalf("total %d, want the %d rows kept", page.Total, len(got)) + } +} + +// The planner honours the foreign exemption /api/nodes applies (#730): a +// foreign node outside the geo_filter is usable, one that is not foreign is +// not. +func TestPlannerHonoursForeignExemption(t *testing.T) { + srv, _ := visibilityFixture(t, true) + all, _ := srv.store.getCachedNodesAndPM() + d := serverPlannerData{srv} + area := geoBBox{S: 32.4, W: -97.6, N: 32.6, E: -97.4} + sel, _ := selectPlannerNodes(all, nil, area, 0, d.filter(), time.Now()) + var got []string + for _, n := range sel { + got = append(got, n.PubKey) + } + if !slices.Equal(got, []string{"for00001"}) { + t.Fatalf("planner nodes outside the geo_filter: %v, want only the foreign one", got) + } +} + +// Regression for review #2391 point 4: /api/nodes, the planner and the +// route-LOS elevation proxy agree on which nodes exist. +func TestNodeVisibilityAgreesAcrossSurfaces(t *testing.T) { + srv, router := visibilityFixture(t, true) + all, _ := srv.store.getCachedNodesAndPM() + + // Only nodes with a position can reach the planner or the proxy. + sorted := func(pks []string) []string { + out := fixtureKeys(pks, visNodeHasFix) + slices.Sort(out) + return out + } + var want []string + for _, n := range visFixtureNodes { + if n.visible && visNodeHasFix(n) { + want = append(want, n.pubkey) + } + } + slices.Sort(want) + + // /api/nodes + apiKeys, _ := apiNodeKeys(t, router) + if got := sorted(apiKeys); !slices.Equal(got, want) { + t.Fatalf("/api/nodes %v, want %v", got, want) + } + + // Planner: the node selection and the known set behind its point checks. + d := serverPlannerData{srv} + now := time.Now() + sel, _ := selectPlannerNodes(all, nil, geoBBox{S: 29, W: -99, N: 34, E: -96}, 0, d.filter(), now) + var selKeys []string + for _, n := range sel { + selKeys = append(selKeys, n.PubKey) + } + if got := sorted(selKeys); !slices.Equal(got, want) { + t.Fatalf("planner nodes %v, want %v", got, want) + } + var knownKeys []string + for _, k := range buildPlannerKnown(all, d.filter(), d.filterGen(), now).infra { + knownKeys = append(knownKeys, k.key) + } + if got := sorted(knownKeys); !slices.Equal(got, want) { + t.Fatalf("planner known set %v, want %v", got, want) + } + + // Elevation proxy: only visible nodes' positions are valid endpoints. + svc := newElevationService(nil) + svc.nodes = func() []nodeInfo { ns, _ := srv.store.getCachedNodesAndPM(); return ns } + svc.visibility = srv + var elevKeys []string + for _, n := range visFixtureNodes { + if visNodeHasFix(n) && svc.known(elevKey(geoPoint{n.lat, n.lon})) { + elevKeys = append(elevKeys, n.pubkey) + } + } + if got := sorted(elevKeys); !slices.Equal(got, want) { + t.Fatalf("elevation endpoints %v, want %v", got, want) + } +} diff --git a/cmd/server/openapi.go b/cmd/server/openapi.go index 1298bf8b9..61c893e37 100644 --- a/cmd/server/openapi.go +++ b/cmd/server/openapi.go @@ -63,6 +63,8 @@ func routeDescriptions() map[string]routeMeta { "GET /api/config/geo-filter": {Summary: "Get geo-filter configuration", Tag: "config"}, "GET /api/config/observer-frequency": {Summary: "Get saved observer frequency policy", Description: "Returns rules keyed by three-letter region, writeEnabled, and restartRequired. Saved configuration is not proof of current ingestor state.", Tag: "config"}, "PUT /api/config/observer-frequency": {Summary: "Save observer frequency policy", Description: "Accepts {rules:{SMF:{mhz:909.875,toleranceKHz:0.5,maxStatusAgeSec:1800,dropUnknown:false}}}. Replaces the frequency rules only. An ingestor restart is required. Does not delete historical observations.", Tag: "config", Auth: true, Session: true}, + "GET /api/config/areas": {Summary: "List configured areas", Description: "Returns an array of configured area keys and labels with a non-empty label. Labels are not trimmed and keys are not filtered by prefix. Returns an empty array when no entries qualify. Result order is unspecified. Public endpoint with no query parameters.", Tag: "config", Response: schemaRef("ConfigAreasResponse")}, + "GET /api/config/areas/polygons": {Summary: "Get configured area geometry", Description: "Returns an array of all configured areas, including unlabeled entries, with their raw polygon and bounding-box fields. Empty polygons and unset bounds are omitted; zero bounds are included. Each bound is independently optional, and polygons may coexist with bounds. Returns an empty array when no areas are configured. Result order is unspecified. Public endpoint with no query parameters.", Tag: "config", Response: schemaRef("ConfigAreaPolygonsResponse")}, // Admin / system "GET /api/health": {Summary: "Health check", Description: "Returns server health, uptime, and memory stats.", Tag: "admin"}, @@ -80,58 +82,64 @@ func routeDescriptions() map[string]routeMeta { "GET /api/backup": {Summary: "Download SQLite backup", Description: "Streams a consistent SQLite snapshot of the analyzer DB (VACUUM INTO). Response is application/octet-stream with attachment filename corescope-backup-.db.", Tag: "admin", Auth: true, Session: true}, // User management (optional; routes exist only when userManagement.enabled) - "POST /api/auth/register": {Summary: "Register an account", Description: "Creates a pending account and mails an activation link. The response is identical whether or not the address is already registered.", Tag: "users"}, - "POST /api/auth/activate": {Summary: "Activate an account", Description: "Request body {token, password}: the mailed activation token and the account password chosen at (the newest) registration. A wrong password answers 401 and leaves the token usable; attempts are rate-limited per account. On success consumes the token, activates the account and starts a session.", Tag: "users"}, - "POST /api/auth/login": {Summary: "Log in", Description: "Email + password. Sets the cs_session cookie. Rate-limited per IP and per address.", Tag: "users"}, - "POST /api/auth/device-token": {Summary: "Issue a device token (CoreDrive RX)", Description: "Body {email, password, deviceName}. 200 {token, expiresAt, user: {id, displayName}}. The token is a bearer credential (Authorization: Bearer ), valid 90 days and extended on use, limited to /api/auth/me, /api/auth/logout, /api/account/settings and /api/account/companions*; other account routes answer 403 to it. deviceName is cleaned (control characters removed, trimmed, at most 64 characters) and shown under Devices. Same 401 answer, rate limits (shared with /api/auth/login) and user.login audit row (detail via=device) as /api/auth/login. No Origin check: nothing is stored in the browser.", Tag: "users"}, - "POST /api/auth/logout": {Summary: "Log out", Description: "With the cs_session cookie (Origin must be publicBaseUrl): ends that browser session and clears the cookie. With Authorization: Bearer : revokes that device token.", Tag: "users"}, - "GET /api/auth/me": {Summary: "Current user", Description: "Returns the logged-in user and the CSRF token, or 401. Also accepts a device token (Authorization: Bearer); csrfToken is then empty.", Tag: "users", Session: true}, - "POST /api/auth/forgot": {Summary: "Request a password reset", Tag: "users"}, - "POST /api/auth/reset": {Summary: "Reset the password", Description: "Consumes the mailed reset token and ends all sessions of the user.", Tag: "users"}, - "PATCH /api/account": {Summary: "Update profile", Tag: "users", Session: true}, - "DELETE /api/account": {Summary: "Delete own account", Tag: "users", Session: true}, - "POST /api/account/password": {Summary: "Change password", Tag: "users", Session: true}, - "POST /api/account/email": {Summary: "Request an address change", Tag: "users", Session: true}, - "POST /api/account/confirm-email": {Summary: "Confirm an address change", Tag: "users"}, - "GET /api/account/sessions": {Summary: "List own sessions", Description: "[{id, kind, label, createdAt, lastSeenAt, expiresAt, userAgent, current}]. kind is web (a browser) or device (a CoreDrive RX device token); label is the device name, empty for web sessions. DELETE /api/account/sessions/{id} revokes either kind.", Tag: "users", Session: true}, - "DELETE /api/account/sessions/{id}": {Summary: "Revoke one own session", Tag: "users", Session: true}, - "GET /api/account/settings": {Summary: "Get own synced settings", Description: "Returns {revision, generation, doc, allowlist}. doc is {v: 1, keys: {: }} or null at revision 0. generation is a random id of the stored document (empty at revision 0); revisions restart at 1 after a DELETE, the generation does not repeat. allowlist lists the keys the server accepts: {key, kind: set|scalar, id?}, where id names the field that identifies an item of a set (absent: the item itself).", Tag: "users", Session: true}, - "PUT /api/account/settings": {Summary: "Replace own synced settings", Description: "Body {baseRevision, baseGeneration, doc}. 200 {revision, generation}. 409 {revision, generation, doc} when baseRevision is not the stored revision or, with a stored document, baseGeneration is not its generation. baseRevision 0 without a stored document starts a new generation. 400 when doc is not {v: 1, keys} or holds a key that is never synced or not allowlisted. 413 above 256 KiB. 429 above 60 PUT requests per hour per user.", Tag: "users", Session: true}, - "DELETE /api/account/settings": {Summary: "Delete own synced settings", Description: "Removes the stored document; the next PUT (baseRevision 0) starts a new one in a new generation.", Tag: "users", Session: true}, - "POST /api/account/companions/challenge": {Summary: "Start linking a companion", Description: "Body {pubkey} (64 hex). 200 {challenge, expiresAt, host}: host is what to sign (the host of userManagement.publicBaseUrl); challenge is 32 random bytes as hex, single use, valid 5 minutes, bound to the caller and the pubkey. 400 malformed pubkey; 429 above 60 challenge + link requests per hour per user and per IP. Accepts a device token (Authorization: Bearer).", Tag: "users", Session: true}, - "POST /api/account/companions": {Summary: "Link a companion", Description: "Body {pubkey, challenge, signature, name}. signature is the companion's Ed25519 signature (64 bytes, hex) over the UTF-8 string \"corescope-link:\" + host of userManagement.publicBaseUrl + \":\" + challenge. The challenge is consumed in every case. 200 {pubkey, name, linkedAt}. The synced settings (meshcore-my-nodes) are not touched: a companion is not a node to monitor. A companion linked to another account moves to the caller (the newest proof wins); both get a companion.transfer audit row and the previous owner a mail (a security notice, sent whatever the node notification settings are). 400 malformed pubkey or signature, or a signature that does not verify; 410 challenge missing, expired, used, or bound to another user or pubkey; 429 rate limited. Accepts a device token.", Tag: "users", Session: true}, - "GET /api/account/companions": {Summary: "List own linked companions", Description: "[{pubkey, name, linkedAt, lastSeenAt}], newest link first. lastSeenAt is the newest client reception of that companion (rx_at as stored) or null. Accepts a device token.", Tag: "users", Session: true}, - "DELETE /api/account/companions/{pubkey}": {Summary: "Unlink an own companion", Description: "204. Stored coverage stays. 400 malformed pubkey, 404 not linked to the caller. Accepts a device token.", Tag: "users", Session: true}, - "GET /api/account/observer-login": {Summary: "Own observer MQTT login", Description: "{login: null} or {login: {username, createdAt, revoked}, observers: [{pubkey, name, lastSeenAt}]}. observers are the pubkeys bound to the caller (the first time an observer publishes with the login); name and lastSeenAt come from the analyzer observers (empty name and null lastSeenAt when unknown). Never contains the password, its hash or its ciphertext. Routes exist only when userManagement.observerLogins is enabled. Not available to device tokens.", Tag: "users", Session: true}, - "POST /api/account/observer-login": {Summary: "Request an observer MQTT login", Description: "Generates a username and password, stores the password hashed and sealed, and mails the credentials to the account address in five formats (meshcoretomqtt, Gessaman or Dutch-MeshCore observer firmware, Home Assistant meshcore-ha, OpenHop, plain). 201 {sent: true}: the response never carries the credentials. 409 when the caller already has a login, 403 when it was revoked, 503 when the mail could not be sent (the login exists; use resend) or the feature failed to load.", Tag: "users", Session: true}, - "POST /api/account/observer-login/resend": {Summary: "Mail the observer MQTT credentials again", Description: "Mails the same credentials again. 200 {sent: true}. 404 without a login, 403 when revoked, 429 after 3 credential mails in 24 hours (the first mail counts; Retry-After in seconds), 503 when the mail fails.", Tag: "users", Session: true}, - "GET /api/account/export": {Summary: "Download own account data", Description: "One JSON file (Content-Disposition attachment corescope-account-.json): {formatVersion: 1, exportedAt, instance, profile, sessions (with kind web|device and the device label), companions (linked companions: pubkey, name, linkedAt), settings, proposals, notifications: {prefs, watches}, audit, mail, observerLogin: {username, createdAt, revoked} or null, observerBindings: [{pubkey, boundAt, boundBy}]}. Every row, no caps. Leaves out the password hash, every session, link and unsubscribe token, and companion link challenges. Audit rows name other accounts by id only. Includes activatedAt, activatedBy (id) and each mail row's to-address. Records a user.export audit row after the file is built.", Tag: "users", Session: true}, - "GET /api/admin/users": {Summary: "List users (admin)", Tag: "users", Session: true, QueryParams: []paramMeta{{Name: "status", Description: "pending | active | disabled", Type: "string"}, {Name: "role", Description: "user | admin", Type: "string"}, {Name: "q", Description: "Substring of email or display name", Type: "string"}, {Name: "bouncing", Description: "1 = only addresses whose mail bounces", Type: "string"}}}, - "GET /api/admin/users/{id}": {Summary: "User detail with sessions, companions, mail log and audit (admin)", Description: "{user, sessions, companions, mail, audit}. companions is [{pubkey, name, linkedAt, lastSeenAt}] like GET /api/account/companions.", Tag: "users", Session: true}, - "DELETE /api/admin/users/{id}": {Summary: "Delete a user (admin)", Tag: "users", Session: true}, - "POST /api/admin/users/{id}/disable": {Summary: "Disable a user (admin)", Tag: "users", Session: true}, - "POST /api/admin/users/{id}/enable": {Summary: "Enable a user (admin)", Tag: "users", Session: true}, - "POST /api/admin/users/{id}/role": {Summary: "Change a user's role (admin)", Tag: "users", Session: true}, - "POST /api/admin/users/{id}/resend-activation": {Summary: "Resend the activation mail (admin)", Tag: "users", Session: true}, - "POST /api/admin/users/{id}/activate": {Summary: "Activate a pending user manually (admin)", Description: "For when mail keeps failing. The address stays unverified; recorded as activatedBy + audit row.", Tag: "users", Session: true}, - "POST /api/admin/users/{id}/mail/{mailId}/refresh": {Summary: "Pull delivery events for one mail from the provider (admin)", Tag: "users", Session: true}, - "GET /api/admin/audit": {Summary: "Global audit log (admin)", Description: "Newest first, keyset-paginated: {entries, next}. Pass next as before for the following page; next is null on the last page. Entry: {id, at, action, actor, target, detail}; actor and target are {id, displayName, email}, {id, deleted: true} for a removed account, or null for the system. Login rows (user.login, user.login.failed) are kept 90 days. 400 on an invalid parameter.", Tag: "users", Session: true, QueryParams: []paramMeta{{Name: "action", Description: "One action, or a group ending in .* (user.login.* matches user.login and user.login.failed)", Type: "string"}, {Name: "user", Description: "User id, as actor or target", Type: "integer"}, {Name: "from", Description: "RFC 3339 time, inclusive", Type: "string"}, {Name: "to", Description: "RFC 3339 time, inclusive", Type: "string"}, {Name: "before", Description: "Only entries with a smaller id (next of the previous page)", Type: "integer"}, {Name: "limit", Description: "Page size, default 100, capped at 500", Type: "integer"}}}, - "GET /api/admin/stats": {Summary: "User figures for the admin overview (admin)", Description: "Accounts by status, active admins, pending accounts older than 24 hours (stuckPending), bouncing addresses, registrations in 7 and 30 days and per UTC day for 30 days (newPerDay, oldest first), users active in 7 and 30 days, logins and failed logins in 24 hours, mail sent in 7 days by latest delivery status (mail7d), and accounts with 5 or more failed logins in 24 hours (guessing: [{userId, displayName, failed}]).", Tag: "users", Session: true}, - "GET /api/admin/observer-logins": {Summary: "List observer MQTT logins and bindings (admin)", Description: "{logins: [{userId, email, displayName, username, createdAt, revoked, lastAuthAt, observers: [pubkey]}], bindings: [{pubkey, userId|null, boundAt, boundBy, confirmedAt|null}]}. confirmedAt is when the owner's own login first published under the pubkey. Never contains passwords, hashes or ciphertext. Routes exist only when userManagement.observerLogins is enabled.", Tag: "users", Session: true}, - "POST /api/admin/observer-logins/{id}/revoke": {Summary: "Revoke a user's observer MQTT login (admin)", Description: "Takes effect at once for the broker hooks. 404 when the user has no login. Records an observer.login.revoke audit row.", Tag: "users", Session: true}, - "POST /api/admin/observer-logins/{id}/reissue": {Summary: "Issue new observer MQTT credentials (admin)", Description: "New username and password, revocation cleared, credentials mailed to the account address. 200 {sent: true}; 404 without a login; 503 when the mail fails (the new login is already active). Records an observer.login.reissue audit row without the password.", Tag: "users", Session: true}, - "PUT /api/admin/observer-bindings/{pubkey}": {Summary: "Reassign or unbind an observer (admin)", Description: "Body {userId: n} binds the pubkey to that user (bound_by admin, no per-user cap); {userId: null} removes the binding so the next publisher can claim it. Records an observer.binding.set audit row.", Tag: "users", Session: true}, - "GET /api/admin/users-backup": {Summary: "Download a users.db snapshot (admin)", Description: "A fresh, consistent copy of users.db (VACUUM INTO) as application/octet-stream, attachment corescope-users-.db (UTC). It holds every password hash and address: store it encrypted. Records a user.backup audit row. The analyzer database has its own route, GET /api/backup.", Tag: "users", Session: true}, - "POST /api/proposals": {Summary: "Propose a hashtag channel", Description: "Body {kind: \"hashtag_channel\", subject}. subject is trimmed and gets a leading # when missing; at most 31 UTF-8 bytes including the #, no control or invisible characters (ZWJ allowed), not Public. 201 with the proposal {id, kind, subject, status, note, createdAt, decidedAt}. 400 invalid kind or name, 409 already pending, already approved or rejected, or already decrypted on this instance (a name in config.json hashChannels or channelKeys, case-sensitive), 429 when the caller created userManagement.channelProposals.perUserPerDay proposals in 24 hours or maxPending proposals wait for review. Registered only when userManagement.channelProposals.enabled.", Tag: "users", Session: true}, - "GET /api/account/proposals": {Summary: "List own proposals", Description: "The caller's proposals, newest first: [{id, kind, subject, status, note, createdAt, decidedAt}]. note is the reviewer's reason.", Tag: "users", Session: true}, - "GET /api/admin/proposals": {Summary: "List proposals (admin)", Description: "Newest first, at most 500: the proposal fields plus proposer and reviewer ({id, displayName, email}, or null once the account is deleted). 400 on an invalid filter.", Tag: "users", Session: true, QueryParams: []paramMeta{{Name: "status", Description: "pending | approved | rejected | revoked", Type: "string"}, {Name: "kind", Description: "hashtag_channel", Type: "string"}}}, - "POST /api/admin/proposals/{id}/approve": {Summary: "Approve a proposal (admin)", Description: "Body {note} (at most 500 characters). Pending only (409 otherwise). The ingestor decrypts the channel from its next refresh (at most a minute) and /api/channels lists it in approvedChannels. 409 when userManagement.channelProposals.maxApproved channels are approved.", Tag: "users", Session: true}, - "POST /api/admin/proposals/{id}/reject": {Summary: "Reject a proposal (admin)", Description: "Body {note}. Pending only (409 otherwise). The name cannot be proposed again until the row is pruned, 90 days after the decision.", Tag: "users", Session: true}, - "POST /api/admin/proposals/{id}/revoke": {Summary: "Revoke an approved proposal (admin)", Description: "Body {note}. Approved only (409 otherwise). The ingestor stops decrypting the channel from its next refresh unless the channel is configured; stored messages stay. The name can be proposed again.", Tag: "users", Session: true}, - "POST /api/mail/brevo/webhook": {Summary: "Brevo delivery-event webhook", Description: "Authenticated with Authorization: Bearer . Registered only when mail.provider is brevo and the secret is set.", Tag: "users"}, - "POST /api/mqtt-hook/emqx/authn": {Summary: "EMQX authentication hook", Description: "Body {username, password, clientid}; answers {result: allow|deny|ignore}. ignore for usernames that are not a managed observer login, so the broker falls through to its own users. Authenticated with the X-CoreScope-Hook-Secret header (401 otherwise). Registered only when userManagement.observerLogins.enabled.", Tag: "users"}, - "POST /api/mqtt-hook/emqx/authz": {Summary: "EMQX authorization hook", Description: "Body {username, topic, action}, action publish or subscribe; answers {result: allow|deny|ignore}. A managed login may publish only to meshcore/// for a pubkey it owns; an unbound pubkey is bound to the login on first publish. Everything else is denied for managed logins and ignored for other usernames. Authenticated with the X-CoreScope-Hook-Secret header (401 otherwise). Registered only when userManagement.observerLogins.enabled.", Tag: "users"}, - "POST /api/mail/postal/webhook": {Summary: "Postal message-event webhook", Description: "Authenticated with HTTP Basic auth whose password is userManagement.mail.webhookSecret (put it in the webhook URL: https://postal:@host/api/mail/postal/webhook). Registered only when mail.provider is postal and the secret is set.", Tag: "users"}, + "POST /api/auth/register": {Summary: "Register an account", Description: "Creates a pending account and mails an activation link. The response is identical whether or not the address is already registered.", Tag: "users"}, + "POST /api/auth/activate": {Summary: "Activate an account", Description: "Request body {token, password}: the mailed activation token and the account password chosen at (the newest) registration. A wrong password answers 401 and leaves the token usable; attempts are rate-limited per account. On success consumes the token, activates the account and starts a session.", Tag: "users"}, + "POST /api/auth/login": {Summary: "Log in", Description: "Email + password. Sets the cs_session cookie. Rate-limited per IP and per address.", Tag: "users"}, + "POST /api/auth/device-token": {Summary: "Issue a device token (CoreDrive RX)", Description: "Body {email, password, deviceName}. 200 {token, expiresAt, user: {id, displayName}}. The token is a bearer credential (Authorization: Bearer ), valid 90 days and extended on use, limited to /api/auth/me, /api/auth/logout, /api/account/settings and /api/account/companions*; other account routes answer 403 to it. deviceName is cleaned (control characters removed, trimmed, at most 64 characters) and shown under Devices. Same 401 answer, rate limits (shared with /api/auth/login) and user.login audit row (detail via=device) as /api/auth/login. No Origin check: nothing is stored in the browser.", Tag: "users"}, + "POST /api/auth/logout": {Summary: "Log out", Description: "With the cs_session cookie (Origin must be publicBaseUrl): ends that browser session and clears the cookie. With Authorization: Bearer : revokes that device token.", Tag: "users"}, + "GET /api/auth/me": {Summary: "Current user", Description: "Returns the logged-in user and the CSRF token, or 401. Also accepts a device token (Authorization: Bearer); csrfToken is then empty.", Tag: "users", Session: true}, + "POST /api/auth/forgot": {Summary: "Request a password reset", Tag: "users"}, + "POST /api/auth/reset": {Summary: "Reset the password", Description: "Consumes the mailed reset token and ends all sessions of the user.", Tag: "users"}, + "PATCH /api/account": {Summary: "Update profile", Tag: "users", Session: true}, + "DELETE /api/account": {Summary: "Delete own account", Tag: "users", Session: true}, + "POST /api/account/password": {Summary: "Change password", Tag: "users", Session: true}, + "POST /api/account/email": {Summary: "Request an address change", Tag: "users", Session: true}, + "POST /api/account/confirm-email": {Summary: "Confirm an address change", Tag: "users"}, + "GET /api/account/sessions": {Summary: "List own sessions", Description: "[{id, kind, label, createdAt, lastSeenAt, expiresAt, userAgent, current}]. kind is web (a browser) or device (a CoreDrive RX device token); label is the device name, empty for web sessions. DELETE /api/account/sessions/{id} revokes either kind.", Tag: "users", Session: true}, + "DELETE /api/account/sessions/{id}": {Summary: "Revoke one own session", Tag: "users", Session: true}, + "GET /api/account/settings": {Summary: "Get own synced settings", Description: "Returns {revision, generation, doc, allowlist}. doc is {v: 1, keys: {: }} or null at revision 0. generation is a random id of the stored document (empty at revision 0); revisions restart at 1 after a DELETE, the generation does not repeat. allowlist lists the keys the server accepts: {key, kind: set|scalar, id?}, where id names the field that identifies an item of a set (absent: the item itself).", Tag: "users", Session: true}, + "PUT /api/account/settings": {Summary: "Replace own synced settings", Description: "Body {baseRevision, baseGeneration, doc}. 200 {revision, generation}. 409 {revision, generation, doc} when baseRevision is not the stored revision or, with a stored document, baseGeneration is not its generation. baseRevision 0 without a stored document starts a new generation. 400 when doc is not {v: 1, keys} or holds a key that is never synced or not allowlisted. 413 above 256 KiB. 429 above 60 PUT requests per hour per user.", Tag: "users", Session: true}, + "DELETE /api/account/settings": {Summary: "Delete own synced settings", Description: "Removes the stored document; the next PUT (baseRevision 0) starts a new one in a new generation.", Tag: "users", Session: true}, + "POST /api/account/companions/challenge": {Summary: "Start linking a companion", Description: "Body {pubkey} (64 hex). 200 {challenge, expiresAt, host}: host is what to sign (the host of userManagement.publicBaseUrl); challenge is 32 random bytes as hex, single use, valid 5 minutes, bound to the caller and the pubkey. 400 malformed pubkey; 429 above 60 challenge + link requests per hour per user and per IP. Accepts a device token (Authorization: Bearer).", Tag: "users", Session: true}, + "POST /api/account/companions": {Summary: "Link a companion", Description: "Body {pubkey, challenge, signature, name}. signature is the companion's Ed25519 signature (64 bytes, hex) over the UTF-8 string \"corescope-link:\" + host of userManagement.publicBaseUrl + \":\" + challenge. The challenge is consumed in every case. 200 {pubkey, name, linkedAt}. The synced settings (meshcore-my-nodes) are not touched: a companion is not a node to monitor. A companion linked to another account moves to the caller (the newest proof wins); both get a companion.transfer audit row and the previous owner a mail (a security notice, sent whatever the node notification settings are). 400 malformed pubkey or signature, or a signature that does not verify; 410 challenge missing, expired, used, or bound to another user or pubkey; 429 rate limited. Accepts a device token.", Tag: "users", Session: true}, + "GET /api/account/companions": {Summary: "List own linked companions", Description: "[{pubkey, name, linkedAt, lastSeenAt}], newest link first. lastSeenAt is the newest client reception of that companion (rx_at as stored) or null. Accepts a device token.", Tag: "users", Session: true}, + "DELETE /api/account/companions/{pubkey}": {Summary: "Unlink an own companion", Description: "204. Stored coverage stays. 400 malformed pubkey, 404 not linked to the caller. Accepts a device token.", Tag: "users", Session: true}, + "GET /api/account/observer-login": {Summary: "Own observer MQTT login", Description: "{login: null} or {login: {username, createdAt, revoked}, observers: [{pubkey, name, lastSeenAt}]}. observers are the pubkeys bound to the caller (the first time an observer publishes with the login); name and lastSeenAt come from the analyzer observers (empty name and null lastSeenAt when unknown). Never contains the password, its hash or its ciphertext. Routes exist only when userManagement.observerLogins is enabled. Not available to device tokens.", Tag: "users", Session: true}, + "POST /api/account/observer-login": {Summary: "Request an observer MQTT login", Description: "Generates a username and password, stores the password hashed and sealed, and mails the credentials to the account address in five formats (meshcoretomqtt, Gessaman or Dutch-MeshCore observer firmware, Home Assistant meshcore-ha, OpenHop, plain). 201 {sent: true}: the response never carries the credentials. 409 when the caller already has a login, 403 when it was revoked, 503 when the mail could not be sent (the login exists; use resend) or the feature failed to load.", Tag: "users", Session: true}, + "POST /api/account/observer-login/resend": {Summary: "Mail the observer MQTT credentials again", Description: "Mails the same credentials again. 200 {sent: true}. 404 without a login, 403 when revoked, 429 after 3 credential mails in 24 hours (the first mail counts; Retry-After in seconds), 503 when the mail fails.", Tag: "users", Session: true}, + "PUT /api/repeaters/{pubkey}/info": {Summary: "Edit a repeater's community details", Description: "Body is a full replace, omitted fields are cleared, and an unchanged body is a no-op: {heightM (null = unknown, 0 to 300), gainDbi (omitted = 0, -10 to 30), status (active|maintenance|decommissioned|empty), power (mains|battery|solar|empty), notes (at most 500 characters)}. 200 the repeater info with canEdit and claimedByMe. Allowed for an admin, for any active user when the repeater has no active claimer, otherwise only for its claimers. Writes a repeater.edit audit row with the changed fields (none when nothing changed). 400 malformed pubkey, invalid value, or a node that is not a repeater; 401 not logged in; 403 not a maintainer or CSRF failure; 404 unknown node; 429 above 120 repeater requests per hour per user and per IP.", Tag: "users", Session: true}, + "POST /api/repeaters/{pubkey}/claim": {Summary: "Claim a repeater", Description: "No body. 200 the repeater info with canEdit and claimedByMe. Idempotent: a repeat answers 200 and writes no second repeater.claim audit row. 400 malformed pubkey or not a repeater; 401 not logged in; 403 CSRF failure; 404 unknown node; 429 rate limited.", Tag: "users", Session: true}, + "DELETE /api/repeaters/{pubkey}/claim": {Summary: "Remove own claim on a repeater", Description: "200 the repeater info with canEdit and claimedByMe. Writes a repeater.unclaim audit row. 400 malformed pubkey; 401 not logged in; 403 CSRF failure; 404 the caller has no claim on it; 429 rate limited.", Tag: "users", Session: true}, + "GET /api/repeaters/info": {Summary: "Community details of all repeaters with details or claimers", Description: "{repeaters: [...]} ordered by pubkey; each entry has the shape of GET /api/repeaters/{pubkey}/info without canEdit and claimedByMe. Contains every pubkey with a saved info row or at least one active claimer. Only display names are public, never email. 404 when user management is off.", Tag: "users", Session: false}, + "GET /api/repeaters/{pubkey}/info": {Summary: "Community details of one repeater", Description: "{pubkey, heightM, gainDbi, status, power, notes, claimers: [{displayName, claimedAt}], updatedAt, updatedBy}. A repeater without a saved row answers 200 with defaults: heightM null, gainDbi 0, status null, power null, notes \"\", claimers [], updatedAt null, updatedBy null. heightM 0 is a real value, null is unknown. canEdit and claimedByMe appear only with a browser session (a bearer token is treated as anonymous). The pubkey is case-insensitive; 400 when it is not 64 hex characters. No analyzer lookup: any well-formed pubkey answers. 404 when user management is off.", Tag: "users", Session: false}, + "GET /api/account/export": {Summary: "Download own account data", Description: "One JSON file (Content-Disposition attachment corescope-account-.json): {formatVersion: 1, exportedAt, instance, profile, sessions (with kind web|device and the device label), companions (linked companions: pubkey, name, linkedAt), settings, proposals, notifications: {prefs, watches}, audit, mail, observerLogin: {username, createdAt, revoked} or null, observerBindings: [{pubkey, boundAt, boundBy}], repeaterClaims: [{pubkey, claimedAt}], newest first, all own claims}. Every row, no caps. Leaves out the password hash, every session, link and unsubscribe token, and companion link challenges. Audit rows name other accounts by id only. Includes activatedAt, activatedBy (id) and each mail row's to-address. Records a user.export audit row after the file is built.", Tag: "users", Session: true}, + "GET /api/admin/users": {Summary: "List users (admin)", Tag: "users", Session: true, QueryParams: []paramMeta{{Name: "status", Description: "pending | active | disabled", Type: "string"}, {Name: "role", Description: "user | admin", Type: "string"}, {Name: "q", Description: "Substring of email or display name", Type: "string"}, {Name: "bouncing", Description: "1 = only addresses whose mail bounces", Type: "string"}}}, + "DELETE /api/admin/repeaters/{pubkey}/claims/{userId}": {Summary: "Remove a user's claim on a repeater (admin)", Description: "204. Writes a repeater.unclaim audit row with actor = the admin, target = the user and detail {pubkey, by: admin}. 400 malformed pubkey or user id; 401 not logged in; 403 not an admin or CSRF failure; 404 no such claim.", Tag: "users", Session: true}, + "GET /api/admin/users/{id}": {Summary: "User detail with sessions, companions, repeater claims, mail log and audit (admin)", Description: "{user, sessions, companions, repeaterClaims, mail, audit}. companions is [{pubkey, name, linkedAt, lastSeenAt}] like GET /api/account/companions. repeaterClaims is [{pubkey, claimedAt}], newest first, every claim of the user whatever the user's status.", Tag: "users", Session: true}, + "DELETE /api/admin/users/{id}": {Summary: "Delete a user (admin)", Tag: "users", Session: true}, + "POST /api/admin/users/{id}/disable": {Summary: "Disable a user (admin)", Tag: "users", Session: true}, + "POST /api/admin/users/{id}/enable": {Summary: "Enable a user (admin)", Tag: "users", Session: true}, + "POST /api/admin/users/{id}/role": {Summary: "Change a user's role (admin)", Tag: "users", Session: true}, + "POST /api/admin/users/{id}/resend-activation": {Summary: "Resend the activation mail (admin)", Tag: "users", Session: true}, + "POST /api/admin/users/{id}/activate": {Summary: "Activate a pending user manually (admin)", Description: "For when mail keeps failing. The address stays unverified; recorded as activatedBy + audit row.", Tag: "users", Session: true}, + "POST /api/admin/users/{id}/mail/{mailId}/refresh": {Summary: "Pull delivery events for one mail from the provider (admin)", Tag: "users", Session: true}, + "GET /api/admin/audit": {Summary: "Global audit log (admin)", Description: "Newest first, keyset-paginated: {entries, next}. Pass next as before for the following page; next is null on the last page. Entry: {id, at, action, actor, target, detail}; actor and target are {id, displayName, email}, {id, deleted: true} for a removed account, or null for the system. Login rows (user.login, user.login.failed) are kept 90 days. 400 on an invalid parameter.", Tag: "users", Session: true, QueryParams: []paramMeta{{Name: "action", Description: "One action, or a group ending in .* (user.login.* matches user.login and user.login.failed)", Type: "string"}, {Name: "user", Description: "User id, as actor or target", Type: "integer"}, {Name: "from", Description: "RFC 3339 time, inclusive", Type: "string"}, {Name: "to", Description: "RFC 3339 time, inclusive", Type: "string"}, {Name: "before", Description: "Only entries with a smaller id (next of the previous page)", Type: "integer"}, {Name: "limit", Description: "Page size, default 100, capped at 500", Type: "integer"}}}, + "GET /api/admin/stats": {Summary: "User figures for the admin overview (admin)", Description: "Accounts by status, active admins, pending accounts older than 24 hours (stuckPending), bouncing addresses, registrations in 7 and 30 days and per UTC day for 30 days (newPerDay, oldest first), users active in 7 and 30 days, logins and failed logins in 24 hours, mail sent in 7 days by latest delivery status (mail7d), and accounts with 5 or more failed logins in 24 hours (guessing: [{userId, displayName, failed}]).", Tag: "users", Session: true}, + "GET /api/admin/observer-logins": {Summary: "List observer MQTT logins and bindings (admin)", Description: "{logins: [{userId, email, displayName, username, createdAt, revoked, lastAuthAt, observers: [pubkey]}], bindings: [{pubkey, userId|null, boundAt, boundBy, confirmedAt|null}]}. confirmedAt is when the owner's own login first published under the pubkey. Never contains passwords, hashes or ciphertext. Routes exist only when userManagement.observerLogins is enabled.", Tag: "users", Session: true}, + "POST /api/admin/observer-logins/{id}/revoke": {Summary: "Revoke a user's observer MQTT login (admin)", Description: "Takes effect at once for the broker hooks. 404 when the user has no login. Records an observer.login.revoke audit row.", Tag: "users", Session: true}, + "POST /api/admin/observer-logins/{id}/reissue": {Summary: "Issue new observer MQTT credentials (admin)", Description: "New username and password, revocation cleared, credentials mailed to the account address. 200 {sent: true}; 404 without a login; 503 when the mail fails (the new login is already active). Records an observer.login.reissue audit row without the password.", Tag: "users", Session: true}, + "PUT /api/admin/observer-bindings/{pubkey}": {Summary: "Reassign or unbind an observer (admin)", Description: "Body {userId: n} binds the pubkey to that user (bound_by admin, no per-user cap); {userId: null} removes the binding so the next publisher can claim it. Records an observer.binding.set audit row.", Tag: "users", Session: true}, + "GET /api/admin/users-backup": {Summary: "Download a users.db snapshot (admin)", Description: "A fresh, consistent copy of users.db (VACUUM INTO) as application/octet-stream, attachment corescope-users-.db (UTC). It holds every password hash and address: store it encrypted. Records a user.backup audit row. The analyzer database has its own route, GET /api/backup.", Tag: "users", Session: true}, + "POST /api/proposals": {Summary: "Propose a hashtag channel", Description: "Body {kind: \"hashtag_channel\", subject}. subject is trimmed and gets a leading # when missing; at most 31 UTF-8 bytes including the #, no control or invisible characters (ZWJ allowed), not Public. 201 with the proposal {id, kind, subject, status, note, createdAt, decidedAt}. 400 invalid kind or name, 409 already pending, already approved or rejected, or already decrypted on this instance (a name in config.json hashChannels or channelKeys, case-sensitive), 429 when the caller created userManagement.channelProposals.perUserPerDay proposals in 24 hours or maxPending proposals wait for review. Registered only when userManagement.channelProposals.enabled.", Tag: "users", Session: true}, + "GET /api/account/proposals": {Summary: "List own proposals", Description: "The caller's proposals, newest first: [{id, kind, subject, status, note, createdAt, decidedAt}]. note is the reviewer's reason.", Tag: "users", Session: true}, + "GET /api/admin/proposals": {Summary: "List proposals (admin)", Description: "Newest first, at most 500: the proposal fields plus proposer and reviewer ({id, displayName, email}, or null once the account is deleted). 400 on an invalid filter.", Tag: "users", Session: true, QueryParams: []paramMeta{{Name: "status", Description: "pending | approved | rejected | revoked", Type: "string"}, {Name: "kind", Description: "hashtag_channel", Type: "string"}}}, + "POST /api/admin/proposals/{id}/approve": {Summary: "Approve a proposal (admin)", Description: "Body {note} (at most 500 characters). Pending only (409 otherwise). The ingestor decrypts the channel from its next refresh (at most a minute) and /api/channels lists it in approvedChannels. 409 when userManagement.channelProposals.maxApproved channels are approved.", Tag: "users", Session: true}, + "POST /api/admin/proposals/{id}/reject": {Summary: "Reject a proposal (admin)", Description: "Body {note}. Pending only (409 otherwise). The name cannot be proposed again until the row is pruned, 90 days after the decision.", Tag: "users", Session: true}, + "POST /api/admin/proposals/{id}/revoke": {Summary: "Revoke an approved proposal (admin)", Description: "Body {note}. Approved only (409 otherwise). The ingestor stops decrypting the channel from its next refresh unless the channel is configured; stored messages stay. The name can be proposed again.", Tag: "users", Session: true}, + "POST /api/mail/brevo/webhook": {Summary: "Brevo delivery-event webhook", Description: "Authenticated with Authorization: Bearer . Registered only when mail.provider is brevo and the secret is set.", Tag: "users"}, + "POST /api/mqtt-hook/emqx/authn": {Summary: "EMQX authentication hook", Description: "Body {username, password, clientid}; answers {result: allow|deny|ignore}. ignore for usernames that are not a managed observer login, so the broker falls through to its own users. Authenticated with the X-CoreScope-Hook-Secret header (401 otherwise). Registered only when userManagement.observerLogins.enabled.", Tag: "users"}, + "POST /api/mqtt-hook/emqx/authz": {Summary: "EMQX authorization hook", Description: "Body {username, topic, action}, action publish or subscribe; answers {result: allow|deny|ignore}. A managed login may publish only to meshcore/// for a pubkey it owns; an unbound pubkey is bound to the login on first publish. Everything else is denied for managed logins and ignored for other usernames. Authenticated with the X-CoreScope-Hook-Secret header (401 otherwise). Registered only when userManagement.observerLogins.enabled.", Tag: "users"}, + "POST /api/mail/postal/webhook": {Summary: "Postal message-event webhook", Description: "Authenticated with HTTP Basic auth whose password is userManagement.mail.webhookSecret (put it in the webhook URL: https://postal:@host/api/mail/postal/webhook). Registered only when mail.provider is postal and the secret is set.", Tag: "users"}, // Node notifications (user management, part E) "GET /api/account/notifications": {Summary: "Get own notification settings", Description: "Returns {enabled, events, availableEvents, externalLabel, watches: [{pubkey, name, known, createdAt}], limits: {maxWatches, perUserPerDay, mailsLast24h}}. node.external and externalLabel appear only when notifications.externalAlerts is configured. Creates the default settings (on, node.offline and node.battery) on first use. known is false once the node left the analyzer database. Registered only when userManagement.notifications.enabled.", Tag: "users", Session: true}, @@ -254,6 +262,11 @@ func routeDescriptions() map[string]routeMeta { // Channels "GET /api/channels": {Summary: "List channels", Description: "Returns known mesh channels with message counts. With userManagement.channelProposals.enabled the response also carries approvedChannels: the approved hashtag channel names, oldest approval first, at most maxApproved, listed also before they have traffic.", Tag: "channels"}, "GET /api/channels/{hash}/messages": {Summary: "Get channel messages", Description: "Returns messages for a specific channel.", Tag: "channels"}, + "GET /api/known-channels": { + Summary: "Get the community channel catalogue", Tag: "channels", Response: schemaRef("KnownChannelsResponse"), + Description: "Returns the cached community channel catalogue without waiting for an upstream fetch. Catalogue entries do not establish observed traffic or successful decryption. An unavailable cache (including disabled fetching) returns 200 with empty entries, an empty source and the zero fetchedAt timestamp. Failed refreshes retain the last successful snapshot. Result order is unspecified. Cache-Control: public, max-age=30 without a snapshot; public, max-age=300 with a snapshot, including an empty catalogue.", + QueryParams: []paramMeta{{Name: "region", Type: "string", Description: "Single catalogue region label (not the IATA observer filter), matched by a case-insensitive comparison after trimming whitespace. Omitted or blank returns all entries. Unknown values return an empty entries array; comma-separated values are not expanded."}}, + }, // Observers "GET /api/observers": {Summary: "List observers", Description: "Returns all known packet observers/gateways. neighbors_report_at (when the latest /neighbors report arrived) and neighbors_count (how many neighbors it named) are present for observers that ever sent one (#2270).", Tag: "observers"}, @@ -267,6 +280,11 @@ func routeDescriptions() map[string]routeMeta { // Misc "GET /api/resolve-hops": {Summary: "Resolve hop path", Description: "Resolves hash prefixes in a hop path to node names. Returns affinity scores and best candidates.", Tag: "nodes", QueryParams: []paramMeta{{Name: "hops", Description: "Comma-separated hop hash prefixes", Type: "string", Required: true}}}, "GET /api/traces/{hash}": {Summary: "Get packet traces", Description: "Returns all observer sightings for a packet hash.", Tag: "packets"}, + "GET /api/planner/profile": {Summary: "Terrain profiles for a multi-point LOS chain", Description: "Opt-in (config planner.enabled). pts is a flat comma list of 2-16 points near the mesh; legs[i] is pts[i] to pts[i+1] with distance_km and elev_m (SRTM terrain, ~90 m spacing) or error too_long|out_of_area|no_terrain. 202 + {state,progress,retry_after_s} while terrain loads: re-poll the same URL.", Tag: "map"}, + "GET /api/planner/relay": {Summary: "Best relay site between two points", Description: "Opt-in (config planner.enabled). Direct A-B link plus ranked relay options among known repeaters and open terrain in the corridor, each with both legs' clearance and profiles. 202 while computing: re-poll the same URL.", Tag: "map"}, + "GET /api/planner/viewshed": {Summary: "Theoretical reach of one candidate repeater site", Description: "Opt-in (config planner.enabled). For site=lat,lon (near a known node) at h metres (default planner.newAntennaM) within range km (one of the planner's ranges, default planner.defaultRangeKm): a grid of cells over bbox [s,w,n,e], row 0 north, row-major, base64 in cells, one byte per cell: low nibble the Users class 1-5 (handheld reach curve planner.userReach, lowered in deep terrain shadow), high nibble the Repeaters class 1-3 (blocked below -20% first-Fresnel clearance, slightly blocked -20% to 0%, line of sight 0% or more, for a receiver at rx metres, default planner.existingAntennaM), 0 for no data. links lists the known repeaters within range (rooms, stale repeaters and repeaters within 100 m of the site excluded), nearest first, with the site-to-repeater link at h and rx (no elev_m profile). truncated is true only when the 300-node cap may have dropped a repeater within range. 202 while computing: re-poll the same URL.", Tag: "map"}, + "GET /api/planner/coverage": {Summary: "Repeater backbone plan for an area", Description: "Opt-in (config planner.enabled). For bbox s,w,n,e (each side at most config planner.maxAreaKm, 100 km by default, settable from 20 to 250; must contain known repeaters) suggests up to sites=N new repeater sites, greedily minimising backbone components, then single points of failure, then maximising repeaters reached. 202 while computing: re-poll the same URL.", Tag: "map"}, + "GET /api/elevation/profile": {Summary: "Terrain elevation along route legs", Description: "Opt-in (config los.enabled). Query pts is a flat comma list lat1,lon1,lat2,lon2,... of 2-16 points; legs[i] is pts[i] to pts[i+1] with distance_km (great-circle) and elev_m, terrain heights in metres evenly spaced along the great circle (about one per 90 m, 64-600, as /api/planner/profile samples a leg), or error too_long (leg over 300 km), unknown_point (endpoint is not a known node), too_many_tiles (the request would load more than 16 terrain tiles), upstream (a terrain tile could not be loaded; retry later) or no_terrain (no terrain data there). Terrain is the planner's SRTM tiles (config terrain block), held in memory; source names it for attribution. Every point must be a known node position. 202 with {state, progress, retry_after_s} while tiles download: re-poll the same URL. 404 when disabled, 400 on bad pts, 429 with Retry-After when the request would start more tile downloads than the client's per-IP allowance.", Tag: "map"}, "GET /api/rf-params": {Summary: "LoRa RF parameters per node", Description: "Opt-in (config rfParams.nodesUrl, issue #1268). Frequency, SF, bandwidth and coding rate the MeshCore map holds for the nodes this instance knows, keyed by lower-case pubkey, limited to adverts within rfParams.maxAgeDays (default 7). Also returns the named presets and fetched_at, the time of the last successful map fetch (null before the first one), and deviations: the nodes whose frequency, SF or bandwidth differs from a setting that more than half of the nodes within rfParams.compareRadiusKm (default 50) on the same band share, the node itself counted, with that majority and the counts. Frequencies within a quarter of the bandwidth count as the same channel. enabled is false when the feature is off.", Tag: "nodes"}, "GET /api/iata-coords": {Summary: "Get IATA airport coordinates", Description: "Returns lat/lon for known airport codes (used for observer positioning).", Tag: "config"}, "GET /api/audio-lab/buckets": {Summary: "Audio lab frequency buckets", Description: "Returns frequency bucket data for audio analysis.", Tag: "analytics"}, @@ -281,6 +299,8 @@ type openAPISchema struct { Nullable bool `json:"nullable,omitempty"` Enum []string `json:"enum,omitempty"` Items *openAPISchema `json:"items,omitempty"` + MinItems int `json:"minItems,omitempty"` + MaxItems int `json:"maxItems,omitempty"` Properties map[string]openAPISchema `json:"properties,omitempty"` Required []string `json:"required,omitempty"` AdditionalProperties *openAPISchema `json:"additionalProperties,omitempty"` @@ -313,6 +333,35 @@ func componentSchemas() map[string]interface{} { return m } return map[string]interface{}{ + "ConfigAreasResponse": openAPISchema{ + Type: "array", Items: &openAPISchema{ + Type: "object", Required: []string{"key", "label"}, + Properties: map[string]openAPISchema{ + "key": {Type: "string", Description: "Area configuration map key, preserved verbatim."}, + "label": {Type: "string", Description: "Non-empty configured display label, preserved verbatim."}, + }, + }, + }, + "ConfigAreaPolygonsResponse": openAPISchema{ + Type: "array", Items: &openAPISchema{ + Type: "object", Required: []string{"key", "label"}, + Properties: map[string]openAPISchema{ + "key": {Type: "string", Description: "Area configuration map key, preserved verbatim."}, + "label": {Type: "string", Description: "Configured display label; may be empty."}, + "polygon": { + Type: "array", MinItems: 1, Description: "Configured coordinates, unchanged; omitted when empty. The endpoint does not validate polygon geometry.", + Items: &openAPISchema{ + Type: "array", MinItems: 2, MaxItems: 2, Description: "[latitude, longitude] in degrees.", + Items: &openAPISchema{Type: "number"}, + }, + }, + "latMin": {Type: "number", Description: "Configured minimum latitude in degrees. Omitted when unset; included when set to zero."}, + "latMax": {Type: "number", Description: "Configured maximum latitude in degrees. Omitted when unset; included when set to zero."}, + "lonMin": {Type: "number", Description: "Configured minimum longitude in degrees. Omitted when unset; included when set to zero."}, + "lonMax": {Type: "number", Description: "Configured maximum longitude in degrees. Omitted when unset; included when set to zero."}, + }, + }, + }, "ReadinessResponse": openAPISchema{ Type: "object", Required: []string{"ready", "loadedTx", "loadedObs", "from_pubkey_backfill"}, Properties: map[string]openAPISchema{ @@ -499,6 +548,25 @@ func componentSchemas() map[string]interface{} { "total_observations": map[string]interface{}{"type": "integer"}, }, }, + "KnownChannelsResponse": openAPISchema{ + Type: "object", Required: []string{"fetchedAt", "source", "entries"}, + Properties: map[string]openAPISchema{ + "fetchedAt": {Type: "string", Description: "Server fetch timestamp in RFC3339 form; 0001-01-01T00:00:00Z when no snapshot is available."}, + "source": {Type: "string", Description: "Catalogue source URL; empty when no snapshot is available."}, + "generatedAt": {Type: "string", Description: "Upstream generation value, copied verbatim without timestamp validation; omitted when empty."}, + "license": {Type: "string", Description: "Upstream license text, copied verbatim; omitted when empty."}, + "entries": {Type: "array", Description: "Catalogue entries for the selected region, or all entries without a filter. An empty catalogue, unavailable cache or unmatched region yields an empty array.", Items: &openAPISchema{ + Type: "object", Required: []string{"channel", "region"}, + Properties: map[string]openAPISchema{ + "channel": {Type: "string", Description: "Upstream channel name with surrounding whitespace trimmed. Empty names are skipped; a # prefix is preserved when supplied."}, + "region": {Type: "string", Description: "Upstream region label, trimmed and lowercased. May be empty or an arbitrary label; no country-code validation is applied."}, + "description": {Type: "string", Description: "Upstream description, copied verbatim; omitted when empty."}, + "key": {Type: "string", Description: "Upstream channel key, copied verbatim without format validation; omitted when empty."}, + "regionName": {Type: "string", Description: "Upstream display name for the region, copied verbatim; omitted when empty."}, + }, + }}, + }, + }, } } diff --git a/cmd/server/openapi_areas_test.go b/cmd/server/openapi_areas_test.go new file mode 100644 index 000000000..32d009916 --- /dev/null +++ b/cmd/server/openapi_areas_test.go @@ -0,0 +1,184 @@ +package main + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "reflect" + "slices" + "strings" + "testing" +) + +// Inspect JSON served by /api/spec, independently of the production schema type. +func TestOpenAPIConfigAreasDocumentation(t *testing.T) { + spec := fetchSpec(t) + paths := asMap(t, spec["paths"], "paths") + schemas := asMap(t, asMap(t, spec["components"], "components")["schemas"], "schemas") + if spec["security"] != nil { + t.Fatal("area routes must not inherit a global authentication requirement") + } + for _, tc := range []struct { + path, schema string + geometry bool + terms []string + }{ + {"/api/config/areas", "ConfigAreasResponse", false, []string{"non-empty", "label"}}, + {"/api/config/areas/polygons", "ConfigAreaPolygonsResponse", true, []string{"unlabeled", "omitted", "zero"}}, + } { + t.Run(tc.path, func(t *testing.T) { + path := asMap(t, paths[tc.path], tc.path) + op := asMap(t, path["get"], "get") + if len(path) != 1 || op["summary"] == "" || op["summary"] == tc.path { + t.Errorf("expected a documented GET operation: %v", path) + } + if op["security"] != nil || !reflect.DeepEqual(op["tags"], []interface{}{"config"}) { + t.Errorf("expected a public config operation: %v", op) + } + if params, ok := op["parameters"]; ok && !reflect.DeepEqual(params, []interface{}{}) { + t.Errorf("area configuration endpoints have no parameters: %v", params) + } + description, _ := op["description"].(string) + for _, term := range append(tc.terms, "empty array", "order", "query parameters") { + if !strings.Contains(description, term) { + t.Errorf("description must explain %q: %q", term, description) + } + } + response := asMap(t, asMap(t, op["responses"], "responses")["200"], "200") + media := asMap(t, asMap(t, response["content"], "content")["application/json"], "JSON") + if asMap(t, media["schema"], "response schema")["$ref"] != "#/components/schemas/"+tc.schema { + t.Errorf("expected concrete %s response schema", tc.schema) + } + schema := asMap(t, schemas[tc.schema], tc.schema) + if schema["type"] != "array" || schema["nullable"] == true { + t.Errorf("expected a non-null array response: %v", schema) + } + item := asMap(t, schema["items"], "area entry") + props := asMap(t, item["properties"], "area properties") + required, _ := item["required"].([]interface{}) + if item["type"] != "object" || len(required) != 2 || !slices.Contains(required, interface{}("key")) || !slices.Contains(required, interface{}("label")) { + t.Errorf("area entry must require key and label: %v", item) + } + fields := map[string]string{"key": "string", "label": "string"} + if tc.geometry { + fields["polygon"] = "array" + for _, name := range []string{"latMin", "latMax", "lonMin", "lonMax"} { + fields[name] = "number" + } + } + if len(props) != len(fields) { + t.Errorf("unexpected area properties: %v", props) + } + for name, kind := range fields { + property := asMap(t, props[name], name) + if property["type"] != kind || property["nullable"] == true { + t.Errorf("wrong type or nullability for %s: %v", name, property) + } + } + if tc.geometry { + polygon := asMap(t, props["polygon"], "polygon") + if minimum, _ := polygon["minItems"].(float64); minimum > 1 { + t.Error("the geometry endpoint returns short configured polygons without validation") + } + pair := asMap(t, polygon["items"], "coordinate pair") + if pair["type"] != "array" || pair["minItems"] != float64(2) || pair["maxItems"] != float64(2) || asMap(t, pair["items"], "coordinate")["type"] != "number" { + t.Errorf("polygon coordinates must be pairs of exactly two numbers: %v", pair) + } + if desc, _ := pair["description"].(string); !strings.Contains(desc, "[latitude, longitude]") { + t.Errorf("coordinate order must be explicit: %q", desc) + } + } + if loadKnownGaps(t)[tc.path] { + t.Error("documented area route must leave the known-gap list") + } + }) + } +} + +func TestConfigAreasDocumentedResponses(t *testing.T) { + srv, router := setupTestServerWithAPIKey(t, "test-secret-key-strong-enough") + for _, tc := range []struct { + name, config, areas, polygons string + }{ + {"absent", `{}`, `{}`, `{}`}, + {"empty", `{"areas":{}}`, `{}`, `{}`}, + { + "configured", + `{"areas":{ + "polygon":{"label":"Polygon fixture","polygon":[[10,20],[11,20],[10,21]]}, + "box":{"label":"Box fixture","latMin":0,"latMax":2,"lonMin":0,"lonMax":3}, + "partial":{"label":"Partial fixture","latMax":0}, + "both":{"label":"Both fixture","polygon":[[10,20]],"lonMin":0}, + "unlabeled":{"label":"","polygon":[[1,2],[3,4]]}, + "_named":{"label":"Underscore fixture"}, + "_comment":{}, + "empty-polygon":{"label":"Empty polygon fixture","polygon":[]}, + "whitespace":{"label":" "} + }}`, + `{ + "polygon":{"key":"polygon","label":"Polygon fixture"}, + "box":{"key":"box","label":"Box fixture"}, + "partial":{"key":"partial","label":"Partial fixture"}, + "both":{"key":"both","label":"Both fixture"}, + "_named":{"key":"_named","label":"Underscore fixture"}, + "empty-polygon":{"key":"empty-polygon","label":"Empty polygon fixture"}, + "whitespace":{"key":"whitespace","label":" "} + }`, + `{ + "polygon":{"key":"polygon","label":"Polygon fixture","polygon":[[10,20],[11,20],[10,21]]}, + "box":{"key":"box","label":"Box fixture","latMin":0,"latMax":2,"lonMin":0,"lonMax":3}, + "partial":{"key":"partial","label":"Partial fixture","latMax":0}, + "both":{"key":"both","label":"Both fixture","polygon":[[10,20]],"lonMin":0}, + "unlabeled":{"key":"unlabeled","label":"","polygon":[[1,2],[3,4]]}, + "_named":{"key":"_named","label":"Underscore fixture"}, + "_comment":{"key":"_comment","label":""}, + "empty-polygon":{"key":"empty-polygon","label":"Empty polygon fixture"}, + "whitespace":{"key":"whitespace","label":" "} + }`, + }, + } { + t.Run(tc.name, func(t *testing.T) { + var cfg Config + if err := json.Unmarshal([]byte(tc.config), &cfg); err != nil { + t.Fatal(err) + } + srv.cfg.Areas = cfg.Areas + for _, endpoint := range []struct{ path, want string }{ + {"/api/config/areas", tc.areas}, + {"/api/config/areas/polygons", tc.polygons}, + } { + t.Run(endpoint.path, func(t *testing.T) { + // No credentials; unrelated query parameters must not filter config. + w := httptest.NewRecorder() + router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, endpoint.path+"?area=unknown", nil)) + if w.Code != http.StatusOK || w.Header().Get("Content-Type") != "application/json" { + t.Fatalf("expected public JSON response, got %d %s: %s", w.Code, w.Header().Get("Content-Type"), w.Body.String()) + } + var rows []map[string]interface{} + if err := json.Unmarshal(w.Body.Bytes(), &rows); err != nil { + t.Fatal(err) + } + if rows == nil { + t.Fatal("expected an array, not null") + } + // Map iteration order is not part of either endpoint's contract. + got := make(map[string]map[string]interface{}, len(rows)) + for _, row := range rows { + key, ok := row["key"].(string) + if !ok || got[key] != nil { + t.Fatalf("missing or duplicate key: %v", row) + } + got[key] = row + } + var want map[string]map[string]interface{} + if err := json.Unmarshal([]byte(endpoint.want), &want); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, want) { + t.Errorf("response differs from the documented fields and omission rules:\ngot %v\nwant %v", got, want) + } + }) + } + }) + } +} diff --git a/cmd/server/openapi_known_channels_test.go b/cmd/server/openapi_known_channels_test.go new file mode 100644 index 000000000..19d8d87bf --- /dev/null +++ b/cmd/server/openapi_known_channels_test.go @@ -0,0 +1,206 @@ +package main + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "reflect" + "slices" + "strings" + "testing" + "time" +) + +func TestOpenAPIKnownChannelsDocumentation(t *testing.T) { + spec := fetchSpec(t) + path := asMap(t, asMap(t, spec["paths"], "paths")["/api/known-channels"], "known channels") + op := asMap(t, path["get"], "get") + if len(path) != 1 || op["summary"] == "" || op["summary"] == "/api/known-channels" { + t.Errorf("expected a documented GET operation: %v", path) + } + if spec["security"] != nil || op["security"] != nil || !reflect.DeepEqual(op["tags"], []interface{}{"channels"}) { + t.Errorf("expected a public channels operation: %v", op) + } + description, _ := op["description"].(string) + for _, term := range []string{"catalogue", "cache", "empty", "order", "max-age=30", "max-age=300"} { + if !strings.Contains(description, term) { + t.Errorf("description must explain %q: %q", term, description) + } + } + params, _ := op["parameters"].([]interface{}) + if len(params) != 1 { + t.Errorf("expected only the region query parameter: %v", params) + } + for _, raw := range params { + p := asMap(t, raw, "parameter") + if p["name"] != "region" || p["in"] != "query" || p["required"] != false || !reflect.DeepEqual(p["schema"], map[string]interface{}{"type": "string"}) { + t.Errorf("expected an optional string region parameter: %v", p) + } + desc, _ := p["description"].(string) + for _, term := range []string{"catalogue", "case-insensitive", "trim", "blank", "all", "Unknown", "empty", "IATA"} { + if !strings.Contains(desc, term) { + t.Errorf("region description must explain %q: %q", term, desc) + } + } + } + if loadKnownGaps(t)["/api/known-channels"] { + t.Error("documented known-channels route must leave the known-gap list") + } + response := asMap(t, asMap(t, op["responses"], "responses")["200"], "200") + media := asMap(t, asMap(t, response["content"], "content")["application/json"], "JSON") + if asMap(t, media["schema"], "response schema")["$ref"] != "#/components/schemas/KnownChannelsResponse" { + t.Error("known channels must use its concrete response schema") + } + schemas := asMap(t, asMap(t, spec["components"], "components")["schemas"], "schemas") + snapshot := asMap(t, schemas["KnownChannelsResponse"], "known-channels response schema") + props := asMap(t, snapshot["properties"], "snapshot properties") + entries := asMap(t, props["entries"], "entries") + if entries["type"] != "array" || entries["nullable"] == true { + t.Errorf("entries must be a non-null array: %v", entries) + } + item := asMap(t, entries["items"], "catalogue entry") + for _, tc := range []struct { + name string + schema map[string]interface{} + fields map[string]string + required []string + }{ + {"snapshot", snapshot, map[string]string{"fetchedAt": "string", "source": "string", "entries": "array", "generatedAt": "string", "license": "string"}, []string{"fetchedAt", "source", "entries"}}, + {"entry", item, map[string]string{"channel": "string", "region": "string", "description": "string", "key": "string", "regionName": "string"}, []string{"channel", "region"}}, + } { + t.Run(tc.name, func(t *testing.T) { + properties := asMap(t, tc.schema["properties"], tc.name+" properties") + required, _ := tc.schema["required"].([]interface{}) + if tc.schema["type"] != "object" || tc.schema["nullable"] == true || len(properties) != len(tc.fields) || len(required) != len(tc.required) { + t.Errorf("unexpected %s shape: %v", tc.name, tc.schema) + } + for name, kind := range tc.fields { + property := asMap(t, properties[name], name) + if property["type"] != kind || property["nullable"] == true || slices.Contains(required, interface{}(name)) != slices.Contains(tc.required, name) { + t.Errorf("wrong type, nullability or optionality for %s: %v", name, property) + } + desc, _ := property["description"].(string) + if desc == "" || (!slices.Contains(tc.required, name) && !strings.Contains(desc, "omitted")) { + t.Errorf("%s must describe its value and omission rule: %q", name, desc) + } + // Metadata is unvalidated, and region labels may be arbitrary or empty. + if name == "generatedAt" || name == "key" || name == "region" { + for _, constraint := range []string{"format", "pattern", "enum", "minLength", "maxLength"} { + if _, ok := property[constraint]; ok { + t.Errorf("%s must not invent a %s constraint: %v", name, constraint, property) + } + } + } + } + }) + } + if desc, _ := asMap(t, props["fetchedAt"], "fetchedAt")["description"].(string); !strings.Contains(desc, "0001-01-01T00:00:00Z") { + t.Errorf("fetchedAt must document the unavailable-cache sentinel: %q", desc) + } + if desc, _ := asMap(t, props["source"], "source")["description"].(string); !strings.Contains(desc, "empty") { + t.Errorf("source must document the empty unavailable-cache value: %q", desc) + } +} + +func TestKnownChannelsDocumentedResponses(t *testing.T) { + srv, router := setupTestServerWithAPIKey(t, "test-secret-key-strong-enough") + fetchedAt := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + const fixture = `{ + "generated_at":"upstream-generation-label", + "license":"CC0-1.0", + "countryNames":{" ZZ ":"Fixture region"}, + "countries":{ + " ZZ ":[ + {"channel":" #fixture-one ","description":" Fixture description ","key":"not-base64"}, + {"channel":"plain-fixture"}, + {"channel":" "} + ], + "custom-region":[{"channel":"#fixture-two"}], + " ":[{"channel":"#fixture-blank"}], + "empty":[] + } + }` + snap, err := parseKnownChannelsJSON([]byte(fixture), "fixture://catalogue", fetchedAt) + if err != nil { + t.Fatal(err) + } + empty, err := parseKnownChannelsJSON([]byte(`{}`), "fixture://catalogue", fetchedAt) + if err != nil { + t.Fatal(err) + } + // Index only these distinct fixture names; catalogue order is unspecified. + allEntries := map[string]interface{}{ + "#fixture-one": map[string]interface{}{"channel": "#fixture-one", "region": "zz", "regionName": "Fixture region", "description": " Fixture description ", "key": "not-base64"}, + "plain-fixture": map[string]interface{}{"channel": "plain-fixture", "region": "zz", "regionName": "Fixture region"}, + "#fixture-two": map[string]interface{}{"channel": "#fixture-two", "region": "custom-region"}, + "#fixture-blank": map[string]interface{}{"channel": "#fixture-blank", "region": ""}, + } + for _, tc := range []struct { + name, query string + cache bool + snapshot *KnownChannelsSnapshot + channels []string + }{ + {name: "nil cache"}, + {name: "unpopulated cache", cache: true}, + {name: "populated empty", cache: true, snapshot: empty}, + {name: "all", cache: true, snapshot: snap, channels: []string{"#fixture-one", "plain-fixture", "#fixture-two", "#fixture-blank"}}, + {name: "empty filter", query: "?region=", cache: true, snapshot: snap, channels: []string{"#fixture-one", "plain-fixture", "#fixture-two", "#fixture-blank"}}, + {name: "blank filter", query: "?region=%20%09%20", cache: true, snapshot: snap, channels: []string{"#fixture-one", "plain-fixture", "#fixture-two", "#fixture-blank"}}, + {name: "case and whitespace", query: "?region=%20zZ%20", cache: true, snapshot: snap, channels: []string{"#fixture-one", "plain-fixture"}}, + {name: "catalogue region", query: "?region=CUSTOM-REGION", cache: true, snapshot: snap, channels: []string{"#fixture-two"}}, + {name: "unknown", query: "?region=unknown", cache: true, snapshot: snap}, + {name: "not a region list", query: "?region=zz,custom-region", cache: true, snapshot: snap}, + } { + t.Run(tc.name, func(t *testing.T) { + srv.knownChannels = nil + wantCacheControl := "public, max-age=30" + want := map[string]interface{}{"fetchedAt": "0001-01-01T00:00:00Z", "source": ""} + if tc.cache { + srv.knownChannels = &knownChannelsCache{} + srv.knownChannels.ptr.Store(tc.snapshot) + } + if tc.snapshot != nil { + wantCacheControl = "public, max-age=300" + want["fetchedAt"] = "2026-01-02T03:04:05Z" + want["source"] = "fixture://catalogue" + if tc.snapshot == snap { + want["generatedAt"] = "upstream-generation-label" + want["license"] = "CC0-1.0" + } + } + // Exercise the registered route and middleware without credentials. + w := httptest.NewRecorder() + router.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/known-channels"+tc.query, nil)) + if w.Code != http.StatusOK || w.Header().Get("Content-Type") != "application/json" || w.Header().Get("Cache-Control") != wantCacheControl { + t.Fatalf("unexpected public response: status=%d headers=%v body=%s", w.Code, w.Header(), w.Body.String()) + } + var got map[string]interface{} + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + entries, ok := got["entries"].([]interface{}) + if !ok || len(entries) != len(tc.channels) { + t.Fatalf("expected %d entries in a non-null array, got %v", len(tc.channels), got["entries"]) + } + indexed := make(map[string]interface{}, len(entries)) + for _, raw := range entries { + entry := asMap(t, raw, "entry") + channel, ok := entry["channel"].(string) + if !ok || indexed[channel] != nil { + t.Fatalf("missing or duplicate fixture channel: %v", entry) + } + indexed[channel] = entry + } + got["entries"] = indexed + wantEntries := make(map[string]interface{}, len(tc.channels)) + for _, name := range tc.channels { + wantEntries[name] = allEntries[name] + } + want["entries"] = wantEntries + if !reflect.DeepEqual(got, want) { + t.Errorf("response differs from documented fields and omission rules:\ngot %v\nwant %v", got, want) + } + }) + } +} diff --git a/cmd/server/openapi_known_gaps.json b/cmd/server/openapi_known_gaps.json index 347f093b7..ed7b616c8 100644 --- a/cmd/server/openapi_known_gaps.json +++ b/cmd/server/openapi_known_gaps.json @@ -6,11 +6,8 @@ "/api/admin/prune-geo-filter/status", "/api/analytics/relay-airtime-share", "/api/analytics/roles", - "/api/config/areas", - "/api/config/areas/polygons", "/api/docs", "/api/dropped-packets", - "/api/known-channels", "/api/nodes/{pubkey}/reach", "/api/nodes/{pubkey}/rx-coverage", "/api/paths/inspect", diff --git a/cmd/server/planner_api.go b/cmd/server/planner_api.go new file mode 100644 index 000000000..a5157d601 --- /dev/null +++ b/cmd/server/planner_api.go @@ -0,0 +1,1735 @@ +package main + +// /api/planner/* — the repeater planner's public endpoints. Wire types, +// constants and the 200/202 job protocol are in planner_types.go. +// +// Abuse model. Every request is quantised before anything else happens +// (points to 0.001°, coverage boxes outward to a 0.05° grid, antenna heights +// to 1 m, ranges to a fixed set), so the cache-key space is small and compute +// only ever sees quantised values. Work runs as background jobs, one per +// key: a request waits at most plannerFastWait for its job and otherwise gets +// 202 + PlannerJobStatus to re-poll. Starting a job costs the client a per-IP +// token, plus one token per tile download its terrain view would start from +// the terrain budget it shares with route LOS, and the server a global +// token; cache hits and polls of a live job are free. Compute is kept away +// from the live app by slot semaphores (coverage + viewshed 1, relay + profile 2), caps +// on live and queued jobs, per-stage timeouts, and cancellation of any job +// nobody has polled for plannerAbandonAfter. +// +// Invariants: +// - At most one live job per key. A successful job caches its result before +// it leaves p.jobs (both under p.mu), so no request can see neither and +// start a duplicate. +// - Every job, however it ends (result, error, panic, cancel), gives back +// its slot, leaves p.jobs and the queue count, and closes done once. +// - A job loads its terrain before it takes a compute slot, so a download +// never holds up jobs whose terrain is already here. It counts as queued +// from creation until it holds the slot. +// - A key whose job failed (anything but being abandoned or shut down) is +// answered 503 for plannerFailedFor without a new job or a token, so a +// query that times out or crashes cannot be replayed into the compute +// slot. +// - Node data is read outside the store's long-held locks: the node list +// is the store's shared cache (read only), LastHeardMap holds the read +// lock for one map lookup per pubkey, edges are copied under the graph's +// read lock. Nothing /api/nodes hides (blacklist, hidden names) reaches +// a response, a geo check or a cache key. + +import ( + "cmp" + "context" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "log" + "math" + "net/http" + "net/url" + "runtime/debug" + "slices" + "sort" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" +) + +const ( + plannerCacheControl = "public, max-age=300" + + plannerMaxRawQuery = 512 + plannerCoordScale = 1000.0 // points quantised to 0.001° + plannerGridPerDeg = 20 // coverage boxes snapped to 0.05° + plannerGridEps = 1e-9 // in grid cells: a value on a grid line stays there + plannerCoverageMinLat = -56.0 // SRTM coverage + plannerCoverageMaxLat = 60.0 + plannerMinAntennaM = 1.0 + plannerMaxAntennaM = 100.0 + plannerDefaultSites = 3 + + plannerProfilePadDeg = 0.01 // covers the great-circle bulge of a 100 km leg (plannerProfilePad) + plannerRelayPadFrac = 0.3 // relay corridor: A,B ± max(0.3·D, 2 km) + plannerRelayPadMinKm = 2.0 + plannerMinLegTiles = 6 // profile/relay tile caps never go below this + plannerAreaNodeKm = 10.0 // coverage needs a repeater/room within bbox + this + // plannerObservedMinScore is the Score×Confidence an observed neighbor + // edge needs to count as a backbone link (same floor as the neighbor + // graph view's default minScore). + plannerObservedMinScore = 0.1 + + plannerKnownTTL = 60 * time.Second + plannerResultTTL = 10 * time.Minute + plannerCovCacheItems = 128 + plannerCovCacheBytes = 32 << 20 + plannerCheapCacheItems = 1024 + plannerCheapCacheBytes = 32 << 20 + + plannerCovSlots = 1 + plannerCheapSlots = 2 + plannerMaxQueuedCoverage = 4 + plannerMaxLiveJobs = 8 + plannerIPJobsPerMin = 6 + plannerGlobalJobsPerMin = 30 + plannerFullRetryS = 5 + + plannerFastWait = 1500 * time.Millisecond + plannerTerrainTimeout = 60 * time.Second + plannerComputeTimeout = 20 * time.Second + plannerAbandonAfter = 15 * time.Second + plannerBusyFor = 30 * time.Second + plannerFailedFor = 5 * time.Minute + plannerWatchEvery = time.Second +) + +// Endpoints, as they appear in cache keys and log lines. +const ( + plannerProfile = "profile" + plannerRelay = "relay" + plannerCoverage = "coverage" + plannerViewshed = "viewshed" +) + +// 400 codes the UI matches on (leg errors use the first three too). +// area_too_large: a coverage box side is over the size limit. +// too_many_tiles: the request's terrain view spans more 1° tiles than its +// endpoint's cap (plannerTileLimits). +const ( + plannerErrTooLong = "too_long" + plannerErrOutOfArea = "out_of_area" + plannerErrNoTerrain = "no_terrain" + plannerErrAreaTooLarge = "area_too_large" + plannerErrTooManyTiles = "too_many_tiles" + plannerErrNoNodes = "no_nodes_in_area" +) + +var ( + errPlannerAbandoned = errors.New("planner: job not polled") + errPlannerClosed = errors.New("planner: shutting down") + errPlannerPanic = errors.New("planner: job panicked") +) + +// Answers for a key that failed recently. +const ( + plannerMsgTerrainBusy = "terrain busy" + plannerMsgFailedRecent = "planner job failed recently" +) + +// ─── Data the planner reads ───────────────────────────────────────────────── + +// plannerData is everything the planner reads from the rest of the server. +// serverPlannerData is the real one; tests inject fixed data. +type plannerData interface { + // nodes is the node list. It is shared with other readers: never modify it. + nodes() []nodeInfo + // lastHeard is the certain last-heard time of each pubkey that has one. + lastHeard(pubkeys []string) map[string]time.Time + // edges is a private copy of the neighbor edges between pubkeys. + edges(pubkeys []string) []NeighborEdge + // filter is what /api/nodes hides, plus each role's silent window. + filter() plannerNodeFilter + // filterGen changes whenever the hiding rules change. + filterGen() string +} + +type serverPlannerData struct{ s *Server } + +func (d serverPlannerData) nodes() []nodeInfo { + if d.s == nil || d.s.store == nil { + return nil + } + ns, _ := d.s.store.getCachedNodesAndPM() + return ns +} + +func (d serverPlannerData) lastHeard(pubkeys []string) map[string]time.Time { + if d.s == nil || d.s.store == nil || len(pubkeys) == 0 { + return nil + } + m, _ := d.s.store.LastHeardMap(pubkeys) + return m +} + +func (d serverPlannerData) edges(pubkeys []string) []NeighborEdge { + if d.s == nil || len(pubkeys) == 0 { + return nil + } + return d.s.getNeighborGraph().snapshotEdgesAmong(pubkeys) +} + +func (d serverPlannerData) filter() plannerNodeFilter { + var cfg *Config + if d.s != nil { + cfg = d.s.cfg + } + if cfg == nil { + return plannerNodeFilter{} + } + h := cfg.GetHealthThresholds() + return plannerNodeFilter{ + // Exactly what /api/nodes hides (node_visibility.go): a node the + // operator filtered out of the API must not surface through the + // planner, and a foreign one it shows is usable. + Visible: d.s.visibleNodeInfo(), + SilentAfter: func(role string) time.Duration { + _, silentMs := h.GetHealthMs(role) + return time.Duration(silentMs) * time.Millisecond + }, + } +} + +func (d serverPlannerData) filterGen() string { return d.s.nodeVisibilityGen() } + +// ─── Service ──────────────────────────────────────────────────────────────── + +// plannerService holds terrain, caches, limiters and the job runner. +type plannerService struct { + cfg PlannerConfig // resolved + freqMHz float64 // radio defaults from the los block, like the LOS tool + kFactor float64 + tiles plannerTileLimits + source string // terrain attribution in every response (terrainSourceName) + + src terrainSource + data plannerData + coverage func(ctx context.Context, v terrainView, in planInputs, progress func(float64)) (PlannerPlanResponse, error) + relay func(ctx context.Context, v terrainView, nodes []plannerNode, p PlannerRelayParams, progress func(float64)) (PlannerRelayResponse, error) + now func() time.Time + + // limit charges the client for each job it starts; global caps new jobs + // for everyone. downloads charges the client per tile download a job's + // view starts: the budget route LOS shares (newTerrainServices), else + // this planner's own. + limit clientLimiter + downloads *clientLimiter + global *rateLimiter + + // Timings (fields so tests can shorten them). + fastWait, terrainTimeout, computeTimeout time.Duration + abandonAfter, busyFor, failedFor time.Duration + watchEvery time.Duration + + knownMu sync.Mutex // one rebuild at a time + known atomic.Pointer[plannerKnown] + + covCache, cheapCache *plannerLRU + covSlots, cheapSlots chan struct{} + + epoch time.Time // origin of plannerJob.polledAt + ctx context.Context // parent of every job; Close cancels it + cancel context.CancelCauseFunc + wg sync.WaitGroup + + mu sync.Mutex + closed bool + jobs map[string]*plannerJob + covQueued int // coverage jobs not yet holding a slot + recent map[string]plannerRecent // keys answered 503 without a new job +} + +// plannerRecent is a key's recent failure: requests for it get msg until +// the entry lapses. +type plannerRecent struct { + until time.Time + msg string +} + +// newPlannerService builds the service from the resolved config over terrain, +// the SRTM source it shares with route LOS (newTerrainServices); nil builds a +// private default one sized for this planner (tests). It starts no +// goroutine; each job brings its own and Close stops them. +func newPlannerService(cfg PlannerConfig, s *Server, terrain *srtmSource) *plannerService { + rc, _ := cfg.resolved() + if terrain == nil { + terrain = newSRTMSource(TerrainConfig{}, rc.tileLimits().max()) + } + var los *LOSConfig + var trusted []string + if s != nil && s.cfg != nil { + los = s.cfg.LOS + trusted = s.cfg.WSTrustedProxies() + } + radio, _ := los.resolved() + ctx, cancel := context.WithCancelCause(context.Background()) + return &plannerService{ + cfg: rc, + freqMHz: radio.FrequencyMHz, + kFactor: radio.KFactor, + tiles: rc.tileLimits(), + source: terrain.source, + src: terrain, + data: serverPlannerData{s}, + coverage: runCoveragePlan, + relay: runRelaySearch, + now: time.Now, + limit: clientLimiter{ + ipr: &wsLimiter{state: map[string]*wsIPState{}, + trustedProxies: parseCIDRList(trusted, "webSocket.trustedProxies")}, + rl: newRateLimiter(plannerIPJobsPerMin, time.Minute), + tag: "planner", what: "planner", + }, + downloads: newTerrainClientLimiter(trusted, terrain.maxTiles), + global: newRateLimiter(plannerGlobalJobsPerMin, time.Minute), + fastWait: plannerFastWait, + terrainTimeout: plannerTerrainTimeout, + computeTimeout: plannerComputeTimeout, + abandonAfter: plannerAbandonAfter, + busyFor: plannerBusyFor, + failedFor: plannerFailedFor, + watchEvery: plannerWatchEvery, + covCache: newPlannerLRU(plannerCovCacheItems, plannerCovCacheBytes, plannerResultTTL), + cheapCache: newPlannerLRU(plannerCheapCacheItems, plannerCheapCacheBytes, plannerResultTTL), + covSlots: make(chan struct{}, plannerCovSlots), + cheapSlots: make(chan struct{}, plannerCheapSlots), + epoch: time.Now(), + ctx: ctx, + cancel: cancel, + jobs: map[string]*plannerJob{}, + recent: map[string]plannerRecent{}, + } +} + +// Close cancels every job, refuses new ones and waits for the job +// goroutines to return. +func (p *plannerService) Close() { + p.mu.Lock() + p.closed = true + p.mu.Unlock() + p.cancel(errPlannerClosed) + p.wg.Wait() +} + +func (s *Server) plannerDisabled(w http.ResponseWriter) bool { + if !s.cfg.Planner.enabled() || s.planner == nil { + writeError(w, http.StatusNotFound, "planner disabled") + return true + } + return false +} + +func (s *Server) handlePlannerProfile(w http.ResponseWriter, r *http.Request) { + if s.plannerDisabled(w) { + return + } + s.planner.handleProfile(w, r) +} + +func (s *Server) handlePlannerRelay(w http.ResponseWriter, r *http.Request) { + if s.plannerDisabled(w) { + return + } + s.planner.handleRelay(w, r) +} + +func (s *Server) handlePlannerCoverage(w http.ResponseWriter, r *http.Request) { + if s.plannerDisabled(w) { + return + } + s.planner.handleCoverage(w, r) +} + +func (s *Server) handlePlannerViewshed(w http.ResponseWriter, r *http.Request) { + if s.plannerDisabled(w) { + return + } + s.planner.handleViewshed(w, r) +} + +// ─── /api/planner/profile ─────────────────────────────────────────────────── + +func (p *plannerService) handleProfile(w http.ResponseWriter, r *http.Request) { + q, rej := plannerParseQuery(r.URL.RawQuery, "pts") + if rej != nil { + rej.write(w) + return + } + raw, ok := q["pts"] + if !ok { + plannerBadRequest(w, "pts required") + return + } + pts, msg := plannerParsePts(raw) + if msg != "" { + plannerBadRequest(w, msg) + return + } + known := p.knownSet() + far := make([]bool, len(pts)) + for i, pt := range pts { + far[i] = !known.near(pt) + } + legs := make([]PlannerProfileLeg, len(pts)-1) + var key strings.Builder + key.WriteString(plannerProfile) + for _, pt := range pts { + fmt.Fprintf(&key, "|%d,%d", plannerMilli(pt.Lat), plannerMilli(pt.Lon)) + } + key.WriteByte('|') + var bb geoBBox + valid := 0 + for i := range legs { + d := geoDistKm(pts[i], pts[i+1]) + legs[i].DistanceKm = losRound(d, 1000) + switch { + case d > p.cfg.MaxLegKm: + legs[i].Error = plannerErrTooLong + key.WriteByte('L') + case far[i] || far[i+1]: + legs[i].Error = plannerErrOutOfArea + key.WriteByte('A') + default: + key.WriteByte('-') + if valid == 0 { + bb = geoBBox{S: pts[i].Lat, W: pts[i].Lon, N: pts[i].Lat, E: pts[i].Lon} + } + bb = plannerBBoxAdd(plannerBBoxAdd(bb, pts[i]), pts[i+1]) + valid++ + } + } + if valid == 0 { + // Nothing to sample: the answer is fully decided here, no job. + body, err := plannerEncode(PlannerProfileResponse{Source: p.source, Legs: legs}) + if err != nil { + writeError(w, http.StatusInternalServerError, "planner failed") + return + } + writePlannerResult(w, body) + return + } + bb = plannerProfileView(bb, plannerProfilePad(p.cfg.MaxLegKm)) + if p.src.TileCount(bb) > p.tiles.Profile { + plannerBadRequest(w, plannerErrTooManyTiles) + return + } + p.serve(w, r, plannerJobSpec{ + endpoint: plannerProfile, + key: key.String(), + view: bb, + compute: func(ctx context.Context, v terrainView, progress func(float64)) (any, error) { + res, err := planProfileLegs(ctx, v, pts, legs, progress) + res.Source = p.source + return res, err + }, + }) +} + +// plannerProfilePad is the profile view's margin in degrees for legs up to +// maxLegKm. A great circle bulges poleward of its endpoints by about +// tan(lat)·(d/R)²/8, so the 0.01° that covers a 100 km leg (0.003° at 60°, +// 0.01° at 80°) scales with the square of the leg. +func plannerProfilePad(maxLegKm float64) float64 { + scale := maxLegKm / defaultPlannerMaxLegKm + return plannerProfilePadDeg * math.Max(1, scale*scale) +} + +// plannerProfileView is the terrain a profile over legs (the bbox of its +// valid legs' endpoints) reads: grown by padDeg on every side for the +// great-circle bulge. +func plannerProfileView(legs geoBBox, padDeg float64) geoBBox { + return geoBBox{S: legs.S - padDeg, W: legs.W - padDeg, N: legs.N + padDeg, E: legs.E + padDeg} +} + +// planProfileLegs samples every leg without an error (sampleLegProfile, as +// route LOS does); legs is the request's pre-checked template and is not +// modified. A leg with any sample on a tile without data is no_terrain +// (terrain has no elevation there, never a 0 m valley), and the response +// carries the terrain warning. The caller sets Source. +func planProfileLegs(ctx context.Context, v terrainView, pts []geoPoint, legs []PlannerProfileLeg, + progress func(float64)) (PlannerProfileResponse, error) { + out := PlannerProfileResponse{Legs: slices.Clone(legs)} + if w := plannerTerrainWarning(v); w != "" { + out.Warnings = []string{w} + } + for i := range out.Legs { + if err := ctx.Err(); err != nil { + return PlannerProfileResponse{}, err + } + if leg := &out.Legs[i]; leg.Error == "" { + if elev, ok := sampleLegProfile(v, pts[i], pts[i+1]); ok { + leg.ElevM = elev + } else { + leg.Error = plannerErrNoTerrain + } + } + progress(float64(i+1) / float64(len(out.Legs))) + } + return out, nil +} + +// plannerTerrainWarning is the warning to show when some of v's tiles have +// no data, which every endpoint skips; "" when it has none or cannot tell. +func plannerTerrainWarning(v terrainView) string { + tc, ok := v.(terrainCoverage) + if !ok { + return "" + } + missing, total := tc.MissingTiles() + if missing == 0 { + return "" + } + return fmt.Sprintf("Terrain missing for %d of %d tiles (open sea or unavailable): sites and links there were skipped", + missing, total) +} + +// ─── /api/planner/relay ───────────────────────────────────────────────────── + +func (p *plannerService) handleRelay(w http.ResponseWriter, r *http.Request) { + q, rej := plannerParseQuery(r.URL.RawQuery, "a", "b", "ha", "hb", "hr", "range") + if rej != nil { + rej.write(w) + return + } + var ends [2]geoPoint + for i, k := range [2]string{"a", "b"} { + raw, ok := q[k] + if !ok { + plannerBadRequest(w, k+" required") + return + } + pt, ok := plannerParsePoint(raw) + if !ok { + plannerBadRequest(w, k+" must be lat,lon within range") + return + } + ends[i] = pt + } + a, b := ends[0], ends[1] + var heights [3]float64 + for i, k := range [3]string{"ha", "hb", "hr"} { + h, ok := plannerOptHeight(q, k, p.cfg.NewAntennaM) + if !ok { + plannerBadRequest(w, k+" must be a number of metres") + return + } + heights[i] = h + } + rangeKm, ok := plannerOptRange(q, p.cfg.DefaultRangeKm, p.cfg.rangesKm()) + if !ok { + plannerBadRequest(w, plannerRangeMsg(p.cfg.rangesKm())) + return + } + d := geoDistKm(a, b) + if d > p.cfg.MaxLegKm { + plannerBadRequest(w, plannerErrTooLong) + return + } + known := p.knownSet() + if !known.near(a) || !known.near(b) { + plannerBadRequest(w, plannerErrOutOfArea) + return + } + view := plannerRelayView(a, b) + if p.src.TileCount(view) > p.tiles.Relay { + plannerBadRequest(w, plannerErrTooManyTiles) + return + } + params := PlannerRelayParams{ + A: geoPointJSON{Lat: a.Lat, Lon: a.Lon}, + B: geoPointJSON{Lat: b.Lat, Lon: b.Lon}, + AntennaAM: heights[0], + AntennaBM: heights[1], + RelayAntennaM: heights[2], + ExistingAntennaM: p.cfg.ExistingAntennaM, + RangeKm: rangeKm, + FrequencyMHz: p.freqMHz, + KFactor: p.kFactor, + } + _, fp := known.scan(view, 0, 0) + key := fmt.Sprintf("%s|%d,%d|%d,%d|%g,%g,%g|%g|%s|%s", plannerRelay, + plannerMilli(a.Lat), plannerMilli(a.Lon), plannerMilli(b.Lat), plannerMilli(b.Lon), + heights[0], heights[1], heights[2], rangeKm, fp, known.gen) + p.serve(w, r, plannerJobSpec{ + endpoint: plannerRelay, + key: key, + view: view, + compute: func(ctx context.Context, v terrainView, progress func(float64)) (any, error) { + nodes, _ := p.snapshotNodes(view, 0, p.now()) + res, err := p.relay(ctx, v, nodes, params, progress) + if err != nil { + return nil, err + } + res.Source = p.source + if res.Params == (PlannerRelayParams{}) { + res.Params = params + } + res.Existing = plannerNonNil(res.Existing) + res.Open = plannerNonNil(res.Open) + if w := plannerTerrainWarning(v); w != "" { + res.Warnings = append(res.Warnings, w) + } + res.Warnings = plannerNonNil(res.Warnings) + return res, nil + }, + }) +} + +// plannerRelayPad is the corridor margin around a leg of dKm. +func plannerRelayPad(dKm float64) float64 { + return math.Max(plannerRelayPadFrac*dKm, plannerRelayPadMinKm) +} + +// plannerRelayView is the terrain a relay search for a→b reads: the +// endpoints' bbox grown by plannerRelayPad on every side. +func plannerRelayView(a, b geoPoint) geoBBox { + ends := plannerBBoxAdd(geoBBox{S: a.Lat, W: a.Lon, N: a.Lat, E: a.Lon}, b) + return plannerExpandBBox(ends, plannerRelayPad(geoDistKm(a, b))) +} + +// ─── /api/planner/viewshed ────────────────────────────────────────────────── + +func (p *plannerService) handleViewshed(w http.ResponseWriter, r *http.Request) { + q, rej := plannerParseQuery(r.URL.RawQuery, "site", "h", "rx", "range") + if rej != nil { + rej.write(w) + return + } + raw, ok := q["site"] + if !ok { + plannerBadRequest(w, "site required") + return + } + site, ok := plannerParsePoint(raw) + if !ok { + plannerBadRequest(w, "site must be lat,lon within range") + return + } + h, ok := plannerOptHeight(q, "h", p.cfg.NewAntennaM) + if !ok { + plannerBadRequest(w, "h must be a number of metres") + return + } + rx, ok := plannerOptHeight(q, "rx", p.cfg.ExistingAntennaM) + if !ok { + plannerBadRequest(w, "rx must be a number of metres") + return + } + rangeKm, ok := plannerOptRange(q, p.cfg.DefaultRangeKm, p.cfg.rangesKm()) + if !ok { + plannerBadRequest(w, plannerRangeMsg(p.cfg.rangesKm())) + return + } + known := p.knownSet() + if !known.near(site) { + plannerBadRequest(w, plannerErrOutOfArea) + return + } + view := viewshedBBox(site, rangeKm) + if p.src.TileCount(view) > p.tiles.Viewshed { + plannerBadRequest(w, plannerErrTooManyTiles) + return + } + reach := *p.cfg.UserReach + params := PlannerViewshedParams{ + Site: geoPointJSON{Lat: site.Lat, Lon: site.Lon}, + AntennaM: h, + RxAntennaM: rx, + RangeKm: rangeKm, + FrequencyMHz: p.freqMHz, + KFactor: p.kFactor, + UserReach: PlannerViewshedUserReach{D50Km: reach.D50Km, Slope: reach.Slope}, + } + _, fp := known.scan(view, 0, 0) + key := fmt.Sprintf("%s|%d,%d|%g,%g|%g|%g,%g|%s|%s", plannerViewshed, + plannerMilli(site.Lat), plannerMilli(site.Lon), h, rx, rangeKm, reach.D50Km, reach.Slope, fp, known.gen) + p.serve(w, r, plannerJobSpec{ + endpoint: plannerViewshed, + key: key, + view: view, + compute: func(ctx context.Context, v terrainView, progress func(float64)) (any, error) { + g, err := computeViewshed(ctx, v, viewshedParams{ + Site: site, SiteM: h, RxM: rx, RangeKm: rangeKm, + FreqMHz: p.freqMHz, KFactor: p.kFactor, Reach: reach, + }, progress) + if err != nil { + return nil, err + } + nodes, truncated := p.snapshotNodes(view, 0, p.now()) + res := PlannerViewshedResponse{ + Source: p.source, + Params: params, + BBox: [4]float64{g.BBox.S, g.BBox.W, g.BBox.N, g.BBox.E}, + Rows: g.Rows, + Cols: g.Cols, + CellKm: g.CellKm, + Cells: base64.StdEncoding.EncodeToString(g.Cells), + Links: viewshedLinks(v, site, nodes, rangeKm, losParams{FreqMHz: p.freqMHz, KFactor: p.kFactor}, h, rx), + Warnings: []string{}, + Truncated: viewshedTruncated(site, nodes, rangeKm, truncated), + } + if w := plannerTerrainWarning(v); w != "" { + res.Warnings = append(res.Warnings, w) + } + return res, nil + }, + }) +} + +// viewshedTruncated reports a node-cap cut that may have cost a link. The cap +// keeps the nodes nearest the site, so everything dropped lies at least as far +// as the farthest kept one: when that is already beyond rangeKm (the square +// view's corners), no in-range repeater was lost. +func viewshedTruncated(site geoPoint, kept []plannerNode, rangeKm float64, capped bool) bool { + if !capped { + return false + } + var farthest float64 + for i := range kept { + farthest = max(farthest, geoDistKm(site, geoPoint{Lat: kept[i].Lat, Lon: kept[i].Lon})) + } + return farthest <= rangeKm +} + +// viewshedSelfKm: a repeater this close to the site is the site itself (a +// candidate placed on an existing repeater), not a link to list. +const viewshedSelfKm = 0.1 + +// viewshedLinks is the site's link to every repeater within rangeKm that +// Relay would offer (not stale, valid position), nearest first (then by +// pubkey), the site at h and the repeater at rx. +func viewshedLinks(v terrainView, site geoPoint, nodes []plannerNode, rangeKm float64, lp losParams, h, rx float64) []PlannerViewshedLink { + type near struct { + n *plannerNode + d float64 + } + var in []near + for i := range nodes { + n := &nodes[i] + if n.Role != "repeater" || n.Stale || !planCoordOK(n.Lat, n.Lon) { + continue + } + if d := geoDistKm(site, geoPoint{Lat: n.Lat, Lon: n.Lon}); d >= viewshedSelfKm && d <= rangeKm { + in = append(in, near{n, d}) + } + } + slices.SortFunc(in, func(a, b near) int { + if c := cmp.Compare(a.d, b.d); c != 0 { + return c + } + return strings.Compare(a.n.PubKey, b.n.PubKey) + }) + out := make([]PlannerViewshedLink, len(in)) + for i, e := range in { + pt := geoPoint{Lat: e.n.Lat, Lon: e.n.Lon} + out[i] = PlannerViewshedLink{ + PubKey: e.n.PubKey, Name: e.n.Name, Lat: e.n.Lat, Lon: e.n.Lon, + Link: relayLink(v, site, pt, e.d, lp, h, rx, false), + } + } + return out +} + +// ─── /api/planner/coverage ────────────────────────────────────────────────── + +func (p *plannerService) handleCoverage(w http.ResponseWriter, r *http.Request) { + q, rej := plannerParseQuery(r.URL.RawQuery, "bbox", "sites", "range", "hr", "he", "baseline", "stale") + if rej != nil { + rej.write(w) + return + } + raw, ok := q["bbox"] + if !ok { + plannerBadRequest(w, "bbox required") + return + } + grid, msg := plannerParseGridBox(raw, p.cfg.MaxAreaKm) + if msg != "" { + plannerBadRequest(w, msg) + return + } + sites := plannerDefaultSites + if s, ok := q["sites"]; ok { + n, err := strconv.Atoi(s) + if err != nil || n < 1 || n > plannerMaxSites { + plannerBadRequest(w, fmt.Sprintf("sites must be an integer 1-%d", plannerMaxSites)) + return + } + sites = n + } + rangeKm, ok := plannerOptRange(q, p.cfg.DefaultRangeKm, p.cfg.rangesKm()) + if !ok { + plannerBadRequest(w, plannerRangeMsg(p.cfg.rangesKm())) + return + } + hr, ok1 := plannerOptHeight(q, "hr", p.cfg.NewAntennaM) + he, ok2 := plannerOptHeight(q, "he", p.cfg.ExistingAntennaM) + if !ok1 || !ok2 { + plannerBadRequest(w, "hr and he must be numbers of metres") + return + } + baseline := "predicted" + if s, ok := q["baseline"]; ok { + if s != "predicted" && s != "observed" { + plannerBadRequest(w, "baseline must be predicted or observed") + return + } + baseline = s + } + stale := false + if s, ok := q["stale"]; ok { + if s != "0" && s != "1" { + plannerBadRequest(w, "stale must be 0 or 1") + return + } + stale = s == "1" + } + area := grid.bbox() + known := p.knownSet() + margin := p.cfg.NodeMarginKm + hasNodes, fp := known.scan(area, plannerAreaNodeKm, margin) + if !hasNodes { + plannerBadRequest(w, plannerErrNoNodes) + return + } + view := plannerExpandBBox(area, margin) + if p.src.TileCount(view) > p.tiles.Coverage { + plannerBadRequest(w, plannerErrTooManyTiles) + return + } + params := PlannerPlanParams{ + Sites: sites, + RangeKm: rangeKm, + NewAntennaM: hr, + ExistingAntennaM: he, + Baseline: baseline, + IncludeStale: stale, + FrequencyMHz: p.freqMHz, + KFactor: p.kFactor, + MinClearance: plannerMinClearance, + } + key := fmt.Sprintf("%s|%d,%d,%d,%d|%d|%g|%g,%g|%s|%t|%s|%s", plannerCoverage, + grid.s, grid.w, grid.n, grid.e, sites, rangeKm, hr, he, baseline, stale, fp, known.gen) + p.serve(w, r, plannerJobSpec{ + endpoint: plannerCoverage, + key: key, + view: view, + compute: func(ctx context.Context, v terrainView, progress func(float64)) (any, error) { + now := p.now() + nodes, truncated := p.snapshotNodes(area, margin, now) + pubkeys := make([]string, len(nodes)) + for i := range nodes { + pubkeys[i] = nodes[i].PubKey + } + observed := observedPlannerEdges(nodes, p.data.edges(pubkeys), now, plannerObservedMinScore) + res, err := p.coverage(ctx, v, planInputs{ + Area: area, Nodes: nodes, Observed: observed, Truncated: truncated, Params: params, + }, progress) + if err != nil { + return nil, err + } + if res.Area == (geoBBoxJSON{}) { + res.Area = geoBBoxJSON{S: area.S, W: area.W, N: area.N, E: area.E} + } + if res.Params == (PlannerPlanParams{}) { + res.Params = params + } + res.Source = p.source + if res.ComputedAt.IsZero() { + res.ComputedAt = now.UTC() + } + res.Truncated = res.Truncated || truncated + res.Nodes = plannerNonNil(res.Nodes) + res.Edges = plannerNonNil(res.Edges) + res.Sites = plannerNonNil(res.Sites) + if w := plannerTerrainWarning(v); w != "" { + res.Warnings = append(res.Warnings, w) + } + res.Warnings = plannerNonNil(res.Warnings) + return res, nil + }, + }) +} + +// snapshotNodes selects a job's repeaters/rooms from one read of the node +// cache. Only candidates' pubkeys go to LastHeardMap, keeping its store +// read lock short. +func (p *plannerService) snapshotNodes(area geoBBox, marginKm float64, now time.Time) ([]plannerNode, bool) { + all := p.data.nodes() + outer := plannerExpandBBox(area, marginKm) + var pubkeys []string + for i := range all { + n := &all[i] + if (n.Role == "repeater" || n.Role == "room") && n.HasGPS && plannerBBoxContains(outer, n.Lat, n.Lon) { + pubkeys = append(pubkeys, n.PublicKey) + } + } + return selectPlannerNodes(all, p.data.lastHeard(pubkeys), area, marginKm, p.data.filter(), now) +} + +// ─── Parsing ──────────────────────────────────────────────────────────────── + +// plannerParseQuery applies the checks common to every endpoint: a bounded +// query, only the allowed keys, none repeated. +func plannerParseQuery(raw string, allowed ...string) (map[string]string, *plannerReject) { + if len(raw) > plannerMaxRawQuery { + return nil, &plannerReject{code: http.StatusBadRequest, msg: "query too long"} + } + vals, err := url.ParseQuery(raw) + if err != nil { + return nil, &plannerReject{code: http.StatusBadRequest, msg: "malformed query"} + } + out := make(map[string]string, len(vals)) + for k, v := range vals { + if !slices.Contains(allowed, k) { + return nil, &plannerReject{code: http.StatusBadRequest, msg: fmt.Sprintf("unknown parameter %q", k)} + } + if len(v) != 1 { + return nil, &plannerReject{code: http.StatusBadRequest, msg: fmt.Sprintf("duplicate parameter %q", k)} + } + out[k] = v[0] + } + return out, nil +} + +// plannerFloat parses a finite float. +func plannerFloat(s string) (float64, bool) { + f, err := strconv.ParseFloat(s, 64) + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0, false + } + return f, true +} + +// plannerMilli is v in thousandths of a degree, the planner's point quantum. +func plannerMilli(v float64) int64 { return int64(math.Round(v * plannerCoordScale)) } + +// plannerLatLon range-checks and quantises one point. +func plannerLatLon(latS, lonS string) (geoPoint, bool) { + lat, ok1 := plannerFloat(latS) + lon, ok2 := plannerFloat(lonS) + if !ok1 || !ok2 || lat < -90 || lat > 90 || lon < -180 || lon > 180 { + return geoPoint{}, false + } + return geoPoint{ + Lat: float64(plannerMilli(lat)) / plannerCoordScale, + Lon: float64(plannerMilli(lon)) / plannerCoordScale, + }, true +} + +// plannerParsePoint parses "lat,lon". +func plannerParsePoint(raw string) (geoPoint, bool) { + if strings.Count(raw, ",") != 1 { + return geoPoint{}, false + } + la, lo, _ := strings.Cut(raw, ",") + return plannerLatLon(la, lo) +} + +// plannerParsePts parses the flat "lat,lon,lat,lon..." list; the second +// return value is a 400 message, empty when valid. Separators are counted +// before splitting, so an oversized list costs no allocation. +func plannerParsePts(raw string) ([]geoPoint, string) { + c := strings.Count(raw, ",") + if c%2 == 0 || c < 3 || c > 2*plannerMaxPoints-1 { + return nil, fmt.Sprintf("pts must hold 2 to %d lat,lon points", plannerMaxPoints) + } + parts := strings.Split(raw, ",") + pts := make([]geoPoint, len(parts)/2) + for i := range pts { + pt, ok := plannerLatLon(parts[2*i], parts[2*i+1]) + if !ok { + return nil, "pts contains an invalid or out-of-range number" + } + pts[i] = pt + } + return pts, "" +} + +// plannerHeight rounds an antenna height to 1 m and clamps it to 1..100. +func plannerHeight(v float64) float64 { + v = math.Round(v) + if v < plannerMinAntennaM { + return plannerMinAntennaM + } + if v > plannerMaxAntennaM { + return plannerMaxAntennaM + } + return v +} + +func plannerOptHeight(q map[string]string, key string, def float64) (float64, bool) { + s, ok := q[key] + if !ok { + return plannerHeight(def), true + } + v, ok := plannerFloat(s) + if !ok { + return 0, false + } + return plannerHeight(v), true +} + +// plannerOptRange is the "range" parameter, def when absent; it must be +// one of allowed. +func plannerOptRange(q map[string]string, def float64, allowed []float64) (float64, bool) { + s, ok := q["range"] + if !ok { + return def, true + } + v, ok := plannerFloat(s) + if !ok || !slices.Contains(allowed, v) { + return 0, false + } + return v, true +} + +func plannerRangeMsg(allowed []float64) string { + s := make([]string, len(allowed)) + for i, r := range allowed { + s[i] = strconv.FormatFloat(r, 'f', -1, 64) + } + return "range must be one of " + strings.Join(s, ",") +} + +// plannerGridBox is a coverage area in 0.05° grid cells. +type plannerGridBox struct{ s, w, n, e int } + +func (g plannerGridBox) bbox() geoBBox { + return geoBBox{ + S: float64(g.s) / plannerGridPerDeg, W: float64(g.w) / plannerGridPerDeg, + N: float64(g.n) / plannerGridPerDeg, E: float64(g.e) / plannerGridPerDeg, + } +} + +// plannerParseGridBox parses "s,w,n,e" and snaps it outward to the grid; +// neither side of the snapped box may exceed maxAreaKm. The second return +// value is a 400 message, empty when valid. +func plannerParseGridBox(raw string, maxAreaKm float64) (plannerGridBox, string) { + const bad = "bbox must be s,w,n,e in degrees" + if strings.Count(raw, ",") != 3 { + return plannerGridBox{}, bad + } + parts := strings.Split(raw, ",") + var v [4]float64 + for i, s := range parts { + f, ok := plannerFloat(s) + if !ok { + return plannerGridBox{}, bad + } + v[i] = f + } + s, w, n, e := v[0], v[1], v[2], v[3] + if s < -90 || n > 90 || w < -180 || e > 180 { + return plannerGridBox{}, bad + } + if !(s < n) || !(w < e) { + return plannerGridBox{}, "bbox needs south below north and west below east (no antimeridian crossing)" + } + g := plannerGridBox{ + s: int(math.Floor(s*plannerGridPerDeg + plannerGridEps)), + w: int(math.Floor(w*plannerGridPerDeg + plannerGridEps)), + n: int(math.Ceil(n*plannerGridPerDeg - plannerGridEps)), + e: int(math.Ceil(e*plannerGridPerDeg - plannerGridEps)), + } + if g.n <= g.s { + g.n = g.s + 1 + } + if g.e <= g.w { + g.e = g.w + 1 + } + bb := g.bbox() + if bb.S < plannerCoverageMinLat || bb.N > plannerCoverageMaxLat { + return plannerGridBox{}, "bbox must lie within latitudes -56 to 60 (terrain coverage)" + } + hKm := (bb.N - bb.S) * plannerKmPerDeg + wKm := (bb.E - bb.W) * plannerKmPerDeg * math.Cos((bb.S+bb.N)/2*math.Pi/180) + if hKm > maxAreaKm || wKm > maxAreaKm { + return plannerGridBox{}, plannerErrAreaTooLarge + } + return g, "" +} + +// plannerBBoxAdd grows bb to include pt. +func plannerBBoxAdd(bb geoBBox, pt geoPoint) geoBBox { + bb.S, bb.N = math.Min(bb.S, pt.Lat), math.Max(bb.N, pt.Lat) + bb.W, bb.E = math.Min(bb.W, pt.Lon), math.Max(bb.E, pt.Lon) + return bb +} + +// plannerNonNil turns a nil slice into an empty one so it encodes as []. +func plannerNonNil[T any](s []T) []T { + if s == nil { + return []T{} + } + return s +} + +// ─── Terrain tile caps ────────────────────────────────────────────────────── + +// plannerTileLimits is the most 1° terrain tiles one request's view may span, +// per endpoint. Each is the worst case of the largest request the size +// limits accept anywhere in the SRTM latitude band, so such a request is +// never refused for its tiles. A view over its cap (a profile chain of many +// long legs, a leg beyond the band) is too_many_tiles. +type plannerTileLimits struct{ Profile, Relay, Coverage, Viewshed int } + +// max is the most tiles one view may need: what the terrain source accepts +// in one View. +func (l plannerTileLimits) max() int { return max(l.Profile, l.Relay, l.Coverage, l.Viewshed) } + +// plannerTileCaps derives the caps from the size limits. +// +// - Coverage: the parser checks the snapped box, so its sides are at most +// maxAreaKm (the width at the box's middle latitude) and its edges within +// the band; the view adds nodeMarginKm on every side. Every point of the +// view lies within the band's edge plus the margin (plus one grid cell, +// to spare), and its extent is at most maxAreaKm + 2·nodeMarginKm. +// - Relay: A and B are at most maxLegKm apart and the corridor adds +// plannerRelayPad of that on every side, so its extent is at most +// maxLegKm + 2·plannerRelayPad(maxLegKm), with A and B in the band. +// - Profile: one leg's view (its pad is far below the relay corridor's) +// fits the relay's; longer chains may not. +// - Viewshed: the site ± its range, the site in the band. The cap uses +// the largest range a request can ask for, the largest of +// plannerRangesKm within maxLegKm (60 km at most), not maxLegKm itself: +// 2·maxLegKm would raise max(), and so every view's memory and the +// download budgets, for views no request can make. +// +// Profile and relay never go below plannerMinLegTiles. +func plannerTileCaps(maxAreaKm, nodeMarginKm, maxLegKm float64) plannerTileLimits { + band := math.Max(plannerCoverageMaxLat, -plannerCoverageMinLat) + cov := plannerWorstCaseTiles(maxAreaKm+2*nodeMarginKm, + band+nodeMarginKm/plannerKmPerDeg+1.0/plannerGridPerDeg) + pad := plannerRelayPad(maxLegKm) + leg := max(plannerWorstCaseTiles(maxLegKm+2*pad, band+pad/plannerKmPerDeg), plannerMinLegTiles) + ranges := PlannerConfig{MaxLegKm: maxLegKm}.rangesKm() + rv := ranges[len(ranges)-1] + vs := plannerWorstCaseTiles(2*rv, band+rv/plannerKmPerDeg) + return plannerTileLimits{Profile: leg, Relay: leg, Coverage: cov, Viewshed: vs} +} + +// plannerWorstCaseTiles is the most 1° SRTM tiles a view can span when it +// extends at most sideKm north-south and east-west and no point of it lies +// beyond maxAbsLat. A span of x degrees touches at most ceil(x)+1 tiles, +// when it starts just short of a degree line; the 1e-9° keeps a span that +// rounding nudged past a whole number from being counted one short. +func plannerWorstCaseTiles(sideKm, maxAbsLat float64) int { + lat := math.Ceil(sideKm/plannerKmPerDeg+1e-9) + 1 + lon := math.Ceil(plannerLonSpanDeg(sideKm, maxAbsLat)+1e-9) + 1 + return int(math.Min(lat, 180) * math.Min(lon, 360)) +} + +// plannerLonSpanDeg bounds the degrees of longitude km can span at +// |lat| ≤ maxAbsLat: the longitude between two points on that parallel km +// apart (haversine). It is at least km/(plannerKmPerDeg·cos maxAbsLat), the +// linear conversion plannerExpandBBox and the width check use, and it grows +// at least that fast, so it also covers a leg's endpoints (no further apart +// in longitude than two points on the parallel) plus linear padding. +func plannerLonSpanDeg(km, maxAbsLat float64) float64 { + c := math.Cos(math.Min(math.Abs(maxAbsLat), 90) * math.Pi / 180) + q := math.Sin(km/(2*earthRadiusKm)) / c + if !(q < 1) { + return 360 + } + return 2 * math.Asin(q) * 180 / math.Pi +} + +// ─── Known positions ──────────────────────────────────────────────────────── + +// plannerKnown is the visible nodes with GPS, rebuilt at most every +// plannerKnownTTL (and at once when the hiding rules change). The geo checks +// and cache-key fingerprints read it; it is immutable once published. +type plannerKnown struct { + builtAt time.Time + gen string + byLat []geoPoint // every visible node with GPS, any role, by latitude + infra []plannerKnownInfra // visible repeaters/rooms, by pubkey then position +} + +type plannerKnownInfra struct { + key string // lower-case pubkey + lat, lon float64 + qlat, qlon int64 // plannerMilli +} + +// knownSet returns the current set. A set that is only too old keeps +// serving while one caller rebuilds it; a missing one, or one built under +// other hiding rules, is rebuilt before anyone uses it. +func (p *plannerService) knownSet() *plannerKnown { + gen := p.data.filterGen() + now := p.now() + fresh := func(k *plannerKnown) bool { + return k != nil && k.gen == gen && now.Sub(k.builtAt) < plannerKnownTTL + } + k := p.known.Load() + if fresh(k) { + return k + } + if k != nil && k.gen == gen { + if !p.knownMu.TryLock() { + return k + } + } else { + p.knownMu.Lock() + } + defer p.knownMu.Unlock() + if k := p.known.Load(); fresh(k) { + return k + } + k = buildPlannerKnown(p.data.nodes(), p.data.filter(), gen, now) + p.known.Store(k) + return k +} + +func buildPlannerKnown(nodes []nodeInfo, f plannerNodeFilter, gen string, now time.Time) *plannerKnown { + k := &plannerKnown{builtAt: now, gen: gen} + for i := range nodes { + n := &nodes[i] + if !n.HasGPS || !plannerFiniteCoord(n.Lat, n.Lon) || (n.Lat == 0 && n.Lon == 0) { + continue + } + if f.Visible != nil && !f.Visible(n) { + continue + } + k.byLat = append(k.byLat, geoPoint{Lat: n.Lat, Lon: n.Lon}) + if (n.Role == "repeater" || n.Role == "room") && n.PublicKey != "" { + k.infra = append(k.infra, plannerKnownInfra{ + key: strings.ToLower(n.PublicKey), lat: n.Lat, lon: n.Lon, + qlat: plannerMilli(n.Lat), qlon: plannerMilli(n.Lon), + }) + } + } + sort.Slice(k.byLat, func(i, j int) bool { return k.byLat[i].Lat < k.byLat[j].Lat }) + slices.SortFunc(k.infra, func(a, b plannerKnownInfra) int { + if c := strings.Compare(a.key, b.key); c != 0 { + return c + } + if a.qlat != b.qlat { + return compareInt64(a.qlat, b.qlat) + } + return compareInt64(a.qlon, b.qlon) + }) + return k +} + +func compareInt64(a, b int64) int { + switch { + case a < b: + return -1 + case a > b: + return 1 + } + return 0 +} + +// near reports whether pt is within plannerGeoRadiusKm of a visible node. +// Only the latitude band that can hold such a node is scanned. +func (k *plannerKnown) near(pt geoPoint) bool { + band := plannerGeoRadiusKm/plannerKmPerDeg + 1e-9 + i := sort.Search(len(k.byLat), func(i int) bool { return k.byLat[i].Lat >= pt.Lat-band }) + for ; i < len(k.byLat) && k.byLat[i].Lat <= pt.Lat+band; i++ { + if geoDistKm(pt, k.byLat[i]) <= plannerGeoRadiusKm { + return true + } + } + return false +} + +// scan reports whether a visible repeater/room lies within area + nearKm, +// and fingerprints (pubkey + quantised position, in sorted order) those +// within area + fpKm: the nodes a job on area would select. +func (k *plannerKnown) scan(area geoBBox, nearKm, fpKm float64) (bool, string) { + nb, fb := plannerExpandBBox(area, nearKm), plannerExpandBBox(area, fpKm) + h := sha256.New() + var buf []byte + found := false + for i := range k.infra { + n := &k.infra[i] + if !found && plannerBBoxContains(nb, n.lat, n.lon) { + found = true + } + if plannerBBoxContains(fb, n.lat, n.lon) { + buf = append(buf[:0], n.key...) + buf = append(buf, '@') + buf = strconv.AppendInt(buf, n.qlat, 10) + buf = append(buf, ',') + buf = strconv.AppendInt(buf, n.qlon, 10) + buf = append(buf, ';') + h.Write(buf) + } + } + return found, hex.EncodeToString(h.Sum(nil)[:8]) +} + +// ─── Job runner ───────────────────────────────────────────────────────────── + +const ( + plannerStateQueued int32 = iota + plannerStateTerrain + plannerStateComputing +) + +var plannerStateNames = [...]string{"queued", "loading_terrain", "computing"} + +// plannerJobSpec is one endpoint's job: its key, the terrain it needs and +// the compute to run over that terrain. +type plannerJobSpec struct { + endpoint string + key string + view geoBBox + compute func(ctx context.Context, v terrainView, progress func(float64)) (any, error) +} + +type plannerJob struct { + key string + endpoint string + heavy bool // coverage, viewshed: their own slot and queue limit + client string // clientLogID, for the log line only; never the IP + ctx context.Context + cancel context.CancelCauseFunc + done chan struct{} + + state atomic.Int32 + progress atomic.Uint64 // math.Float64bits + polledAt atomic.Int64 // p.since(now) of the last request for key + + queued bool // waiting for a slot; guarded by p.mu + + // Set before done is closed; read only after. + body []byte + err error +} + +// since is now as a duration from p.epoch. With the real clock both carry a +// monotonic reading, so a wall-clock jump cannot abandon every job at once. +func (p *plannerService) since(now time.Time) int64 { return int64(now.Sub(p.epoch)) } + +func (j *plannerJob) setProgress(f float64) { + if math.IsNaN(f) { + return + } + if f < 0 { + f = 0 + } else if f > 1 { + f = 1 + } + j.progress.Store(math.Float64bits(f)) +} + +func (j *plannerJob) status() PlannerJobStatus { + st := j.state.Load() + retry := 2 + if st == plannerStateComputing { + retry = 1 + } + return PlannerJobStatus{ + State: plannerStateNames[st], + Progress: math.Round(math.Float64frombits(j.progress.Load())*100) / 100, + RetryAfterS: retry, + } +} + +// plannerReject is a request answered without a result: 4xx/5xx + message +// and, when set, Retry-After. +type plannerReject struct { + code int + msg string + retryAfter int +} + +func (rj *plannerReject) write(w http.ResponseWriter) { + w.Header().Set("Cache-Control", "no-store") + if rj.retryAfter > 0 { + w.Header().Set("Retry-After", strconv.Itoa(rj.retryAfter)) + } + writeError(w, rj.code, rj.msg) +} + +func plannerBadRequest(w http.ResponseWriter, msg string) { + (&plannerReject{code: http.StatusBadRequest, msg: msg}).write(w) +} + +func (p *plannerService) cacheFor(heavy bool) *plannerLRU { + if heavy { + return p.covCache + } + return p.cheapCache +} + +// serve answers a validated request: the cached result, or the status of +// the key's job (starting one if needed). It waits at most p.fastWait, and +// only when the terrain is already resident. +func (p *plannerService) serve(w http.ResponseWriter, r *http.Request, spec plannerJobSpec) { + heavy := spec.endpoint == plannerCoverage || spec.endpoint == plannerViewshed + now := p.now() + if body, ok := p.cacheFor(heavy).get(spec.key, now); ok { + writePlannerResult(w, body) + return + } + j, body, rej := p.attach(r, spec, heavy, now) + switch { + case rej != nil: + rej.write(w) + return + case body != nil: + writePlannerResult(w, body) + return + } + if p.fastWait > 0 && p.src.Resident(spec.view) { + t := time.NewTimer(p.fastWait) + select { + case <-j.done: + case <-t.C: + case <-r.Context().Done(): + } + t.Stop() + } + select { + case <-j.done: + if j.err != nil { + p.failure(j.err).write(w) + return + } + writePlannerResult(w, j.body) + default: + writePlannerStatus(w, j.status()) + } +} + +// attach returns the live job for spec.key, or the result that landed since +// the caller's cache miss, or starts a job. Starting one checks capacity +// first (free), then charges the client a job, the global budget a job, and +// the client the downloads its view starts (p.src.Begin, all or nothing, in +// the step that starts them, so a tile two jobs or route LOS ask for at once +// is charged once). A refusal gives back what was charged before it, all +// under p.mu: a client over its own limit never spends everyone else's. +func (p *plannerService) attach(r *http.Request, spec plannerJobSpec, heavy bool, now time.Time) (*plannerJob, []byte, *plannerReject) { + p.mu.Lock() + defer p.mu.Unlock() + if j := p.jobs[spec.key]; j != nil { + j.polledAt.Store(p.since(now)) + return j, nil, nil + } + if body, ok := p.cacheFor(heavy).get(spec.key, now); ok { + return nil, body, nil + } + if rec, ok := p.recent[spec.key]; ok { + if now.Before(rec.until) { + return nil, nil, &plannerReject{http.StatusServiceUnavailable, rec.msg, retryAfterSecs(rec.until.Sub(now))} + } + delete(p.recent, spec.key) + } + if p.closed { + return nil, nil, &plannerReject{http.StatusServiceUnavailable, "planner unavailable", plannerFullRetryS} + } + if len(p.jobs) >= plannerMaxLiveJobs || (heavy && p.covQueued >= plannerMaxQueuedCoverage) { + return nil, nil, &plannerReject{http.StatusServiceUnavailable, "planner busy", plannerFullRetryS} + } + client, _ := p.limit.clientKey(r) + if ok, wait := p.limit.take(r); !ok { + return nil, nil, &plannerReject{http.StatusTooManyRequests, "rate limited", retryAfterSecs(wait)} + } + if ok, wait := p.global.take("all"); !ok { + p.limit.refundN(r, 1) + return nil, nil, &plannerReject{http.StatusServiceUnavailable, "planner busy", retryAfterSecs(wait)} + } + // Last, so nothing can refuse the job once its downloads have started. + var retry time.Duration + if !p.src.Begin(spec.view, func(starts int) bool { + var ok bool + ok, retry = p.downloads.takeN(r, starts) + return ok + }) { + p.limit.refundN(r, 1) + p.global.refundN("all", 1) + return nil, nil, &plannerReject{http.StatusTooManyRequests, "rate limited", retryAfterSecs(retry)} + } + ctx, cancel := context.WithCancelCause(p.ctx) + j := &plannerJob{ + key: spec.key, endpoint: spec.endpoint, heavy: heavy, client: clientLogID(client), + ctx: ctx, cancel: cancel, done: make(chan struct{}), queued: true, + } + j.polledAt.Store(p.since(now)) + p.jobs[spec.key] = j + if heavy { + p.covQueued++ + } + p.wg.Add(1) + go p.run(j, spec) + return j, nil, nil +} + +func (p *plannerService) run(j *plannerJob, spec plannerJobSpec) { + defer p.wg.Done() + start := time.Now() + stop := make(chan struct{}) + p.wg.Add(1) + go p.watch(j, stop) + body, err := p.execute(j, spec) + close(stop) + p.finish(j, body, err) + log.Printf("[planner] %s client=%s key=%s took=%s outcome=%s", j.endpoint, j.client, + plannerKeyHash(j.key), time.Since(start).Round(time.Millisecond), plannerOutcome(err)) +} + +// execute runs one job: load terrain, wait for a slot, compute, encode. +// Terrain comes first, outside the slot, so a slow download only delays its +// own job. A panic anywhere in it fails the job, not the server; the slot is +// released on every path. +func (p *plannerService) execute(j *plannerJob, spec plannerJobSpec) (body []byte, err error) { + defer func() { + if rec := recover(); rec != nil { + log.Printf("[planner] %s job %s panicked: %v\n%s", j.endpoint, plannerKeyHash(j.key), rec, debug.Stack()) + body, err = nil, errPlannerPanic + } + }() + if !p.src.Resident(spec.view) { + j.state.Store(plannerStateTerrain) + } + tctx, cancel := context.WithTimeout(j.ctx, p.terrainTimeout) + v, err := p.src.View(tctx, spec.view) + cancel() + if err != nil { + return nil, j.failure(err) + } + j.state.Store(plannerStateQueued) + + slots := p.cheapSlots + if j.heavy { + slots = p.covSlots + } + select { + case slots <- struct{}{}: + case <-j.ctx.Done(): + return nil, context.Cause(j.ctx) + } + defer func() { <-slots }() + p.mu.Lock() + p.dequeueLocked(j) + p.mu.Unlock() + + j.state.Store(plannerStateComputing) + cctx, cancel := context.WithTimeout(j.ctx, p.computeTimeout) + defer cancel() + res, err := spec.compute(cctx, v, j.setProgress) + if err == nil && cctx.Err() != nil { + // A search that ignored its deadline does not get to finish late. + err = cctx.Err() + } + if err != nil { + return nil, j.failure(err) + } + return plannerEncode(res) +} + +// failure reports why the job's own context ended, when it did, rather than +// the bare context.Canceled the compute saw. +func (j *plannerJob) failure(err error) error { + if j.ctx.Err() != nil { + return context.Cause(j.ctx) + } + return err +} + +// watch cancels j once no request has asked for its key for abandonAfter. +func (p *plannerService) watch(j *plannerJob, stop <-chan struct{}) { + defer p.wg.Done() + t := time.NewTicker(p.watchEvery) + defer t.Stop() + for { + select { + case <-stop: + return + case <-t.C: + if time.Duration(p.since(p.now())-j.polledAt.Load()) > p.abandonAfter { + j.cancel(errPlannerAbandoned) + return + } + } + } +} + +func (p *plannerService) dequeueLocked(j *plannerJob) { + if !j.queued { + return + } + j.queued = false + if j.heavy { + p.covQueued-- + } +} + +// finish publishes the outcome: a result goes to the cache, a failure to +// p.recent (terrain busy for busyFor, anything else for failedFor) unless +// nobody wanted the job any more, so the next poll starts afresh. The job +// leaves p.jobs in the same critical section. +func (p *plannerService) finish(j *plannerJob, body []byte, err error) { + j.body, j.err = body, err + now := p.now() + p.mu.Lock() + switch { + case err == nil: + p.cacheFor(j.heavy).put(j.key, body, now) + case errors.Is(err, errTerrainBusy): + p.rememberLocked(j.key, now, p.busyFor, plannerMsgTerrainBusy) + case !errors.Is(err, errPlannerAbandoned) && !errors.Is(err, errPlannerClosed): + p.rememberLocked(j.key, now, p.failedFor, plannerMsgFailedRecent) + } + if p.jobs[j.key] == j { + delete(p.jobs, j.key) + } + p.dequeueLocked(j) + p.mu.Unlock() + j.cancel(nil) + close(j.done) +} + +// rememberLocked answers key with msg for d, sweeping lapsed entries first +// (the map holds at most the jobs started in the last failedFor). The caller +// holds p.mu. +func (p *plannerService) rememberLocked(key string, now time.Time, d time.Duration, msg string) { + for k, rec := range p.recent { + if !now.Before(rec.until) { + delete(p.recent, k) + } + } + p.recent[key] = plannerRecent{until: now.Add(d), msg: msg} +} + +// failure maps a failed job to the answer its waiting request gets; its +// Retry-After matches how long finish remembers the failure. +func (p *plannerService) failure(err error) *plannerReject { + unavailable := http.StatusServiceUnavailable + busyS, failedS := retryAfterSecs(p.busyFor), retryAfterSecs(p.failedFor) + switch { + case errors.Is(err, errTerrainBusy): + return &plannerReject{unavailable, plannerMsgTerrainBusy, busyS} + case errors.Is(err, errPlannerAbandoned), errors.Is(err, errPlannerClosed): + return &plannerReject{unavailable, "planner job cancelled", 1} + case errors.Is(err, errTerrainUnavailable): + return &plannerReject{unavailable, "terrain unavailable", failedS} + case errors.Is(err, errTerrainTooManyTiles): + return &plannerReject{code: http.StatusBadRequest, msg: plannerErrTooManyTiles} + case errors.Is(err, context.DeadlineExceeded): + return &plannerReject{unavailable, "planner timed out", failedS} + } + return &plannerReject{http.StatusInternalServerError, "planner failed", failedS} +} + +// plannerOutcome is the log line's outcome. +func plannerOutcome(err error) string { + switch { + case err == nil: + return "ok" + case errors.Is(err, errTerrainBusy): + return "terrain_busy" + case errors.Is(err, errTerrainUnavailable): + return "terrain_unavailable" + case errors.Is(err, errTerrainTooManyTiles): + return "too_many_tiles" + case errors.Is(err, context.DeadlineExceeded): + return "timeout" + case errors.Is(err, errPlannerAbandoned): + return "abandoned" + case errors.Is(err, errPlannerClosed): + return "closed" + case errors.Is(err, context.Canceled): + return "cancelled" + case errors.Is(err, errPlannerPanic): + return "panic" + } + return "error: " + err.Error() +} + +// plannerKeyHash names a key in logs without revealing the coordinates in it. +func plannerKeyHash(key string) string { + sum := sha256.Sum256([]byte(key)) + return hex.EncodeToString(sum[:6]) +} + +func plannerEncode(v any) ([]byte, error) { + b, err := json.Marshal(v) + if err != nil { + return nil, err + } + return append(b, '\n'), nil // byte-identical to json.Encoder output +} + +func writePlannerResult(w http.ResponseWriter, body []byte) { + w.Header().Set("Cache-Control", plannerCacheControl) + writeJSONBytes(w, body) +} + +func writePlannerStatus(w http.ResponseWriter, st PlannerJobStatus) { + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Retry-After", strconv.Itoa(st.RetryAfterS)) + writeJSONStatus(w, http.StatusAccepted, st) +} + +// ─── Result cache ─────────────────────────────────────────────────────────── + +// plannerLRU holds encoded results, bounded by entry count and total bytes; +// entries expire ttl after they were stored. Bodies are never modified after +// put, so get hands out the stored slice. +type plannerLRU struct { + mu sync.Mutex + ttl time.Duration + maxEntry int // bytes; put skips a bigger entry + cache *lru[string, plannerLRUEntry] +} + +type plannerLRUEntry struct { + body []byte + exp time.Time +} + +func newPlannerLRU(maxItems, maxBytes int, ttl time.Duration) *plannerLRU { + return &plannerLRU{ttl: ttl, maxEntry: maxBytes / 4, + cache: newLRU(maxItems, maxBytes, plannerEntrySize)} +} + +func plannerEntrySize(key string, e plannerLRUEntry) int { return len(key) + len(e.body) } + +func (c *plannerLRU) get(key string, now time.Time) ([]byte, bool) { + c.mu.Lock() + defer c.mu.Unlock() + e, ok := c.cache.Get(key) + if !ok { + return nil, false + } + if !now.Before(e.exp) { + c.cache.Remove(key) + return nil, false + } + return e.body, true +} + +// put stores body; one entry over a quarter of the byte budget is not +// cached, so it cannot flush everything else. +func (c *plannerLRU) put(key string, body []byte, now time.Time) { + e := plannerLRUEntry{body: body, exp: now.Add(c.ttl)} + if plannerEntrySize(key, e) > c.maxEntry { + return + } + c.mu.Lock() + defer c.mu.Unlock() + c.cache.Put(key, e) +} + +func (c *plannerLRU) len() int { + c.mu.Lock() + defer c.mu.Unlock() + return c.cache.Len() +} diff --git a/cmd/server/planner_api_test.go b/cmd/server/planner_api_test.go new file mode 100644 index 000000000..678f91d26 --- /dev/null +++ b/cmd/server/planner_api_test.go @@ -0,0 +1,2031 @@ +package main + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "math" + "math/rand" + "net/http" + "net/http/httptest" + "slices" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +// ─── Fakes ────────────────────────────────────────────────────────────────── + +type plannerTestClock struct { + mu sync.Mutex + t time.Time +} + +func (c *plannerTestClock) now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.t } +func (c *plannerTestClock) add(d time.Duration) { + c.mu.Lock() + c.t = c.t.Add(d) + c.mu.Unlock() +} + +var plannerTestStart = time.Unix(1_700_000_000, 0) + +// fakeTerrain is an in-memory terrainSource: flat-ish terrain over whatever +// box is asked for, with a switchable resident flag, error and gate. +type fakeTerrain struct { + mu sync.Mutex + resident bool + err error + gate chan struct{} // non-nil: View blocks until it is closed (or ctx ends) + gates map[geoBBox]chan struct{} // per view: blocks, and is not resident, until released + missing map[[2]int]bool // 1° tiles (south-west corner) without data + tiles func(geoBBox) int // nil: real 1° tile count + starts func(geoBBox) int // nil: no view downloads anything + views int + lastView geoBBox +} + +func (f *fakeTerrain) View(ctx context.Context, bb geoBBox) (terrainView, error) { + f.mu.Lock() + f.views++ + f.lastView = bb + gate, err := f.gate, f.err + if g, ok := f.gates[bb]; ok { + gate = g + } + missing := f.missing + f.mu.Unlock() + if gate != nil { + select { + case <-gate: + case <-ctx.Done(): + return nil, ctx.Err() + } + } + if err != nil { + return nil, err + } + return fakeTerrainView{bb: bb, missing: missing}, nil +} + +func (f *fakeTerrain) Resident(bb geoBBox) bool { + f.mu.Lock() + defer f.mu.Unlock() + if _, held := f.gates[bb]; held { + return false + } + return f.resident +} + +// hold makes View(bb) block, and bb not resident, until release(bb). +func (f *fakeTerrain) hold(bb geoBBox) { + f.mu.Lock() + defer f.mu.Unlock() + if f.gates == nil { + f.gates = map[geoBBox]chan struct{}{} + } + f.gates[bb] = make(chan struct{}) +} + +func (f *fakeTerrain) release(bb geoBBox) { + f.mu.Lock() + defer f.mu.Unlock() + if g, ok := f.gates[bb]; ok { + close(g) + delete(f.gates, bb) + } +} + +func (f *fakeTerrain) releaseAll() { + f.mu.Lock() + defer f.mu.Unlock() + for bb, g := range f.gates { + close(g) + delete(f.gates, bb) + } +} + +// fakeTiles lists the 1° tiles covering bb, as srtmSpanOf counts them. +func fakeTiles(bb geoBBox) [][2]int { + lat0, lon0 := int(math.Floor(bb.S)), int(math.Floor(bb.W)) + lat1, lon1 := int(math.Ceil(bb.N))-1, int(math.Ceil(bb.E))-1 + if lat1 < lat0 { + lat1 = lat0 + } + if lon1 < lon0 { + lon1 = lon0 + } + var out [][2]int + for la := lat0; la <= lat1; la++ { + for lo := lon0; lo <= lon1; lo++ { + out = append(out, [2]int{la, lo}) + } + } + return out +} + +func (f *fakeTerrain) TileCount(bb geoBBox) int { + if f.tiles != nil { + return f.tiles(bb) + } + return len(fakeTiles(bb)) +} + +// Begin charges for f.starts(bb) downloads, or none: the fake does not track +// which tiles are downloading, so the tests that charge downloads use a real +// srtmSource (planner_tiles_test.go). +func (f *fakeTerrain) Begin(bb geoBBox, charge func(starts int) bool) bool { + f.mu.Lock() + fn := f.starts + f.mu.Unlock() + if fn == nil { + return true + } + n := fn(bb) + return n < 1 || charge(n) +} + +func (f *fakeTerrain) set(fn func(f *fakeTerrain)) { f.mu.Lock(); fn(f); f.mu.Unlock() } +func (f *fakeTerrain) viewCount() int { f.mu.Lock(); defer f.mu.Unlock(); return f.views } +func (f *fakeTerrain) lastBBox() geoBBox { f.mu.Lock(); defer f.mu.Unlock(); return f.lastView } + +// fakeTerrainView is terrain over bb; tiles in missing have no elevation +// and are reported through terrainCoverage, like srtmView's. +type fakeTerrainView struct { + bb geoBBox + missing map[[2]int]bool +} + +func (v fakeTerrainView) inside(lat, lon float64) bool { + const tol = 1e-9 + return lat >= v.bb.S-tol && lat <= v.bb.N+tol && lon >= v.bb.W-tol && lon <= v.bb.E+tol +} + +func (v fakeTerrainView) ElevationAt(lat, lon float64) (float64, bool) { + if v.MissingAt(lat, lon) { + return 0, false + } + return 100 + 3*lat, true +} + +func (v fakeTerrainView) MissingTiles() (missing, total int) { + tiles := fakeTiles(v.bb) + for _, t := range tiles { + if v.missing[t] { + missing++ + } + } + return missing, len(tiles) +} + +func (v fakeTerrainView) MissingAt(lat, lon float64) bool { + return !v.inside(lat, lon) || v.missing[[2]int{int(math.Floor(lat)), int(math.Floor(lon))}] +} + +// fakePlannerData serves fixed nodes and edges; the hiding rules are the +// real serverPlannerData ones, read from the test Server's config. +type fakePlannerData struct { + serverPlannerData + mu sync.Mutex + ns []nodeInfo + heard map[string]time.Time + es []NeighborEdge +} + +func (d *fakePlannerData) nodes() []nodeInfo { d.mu.Lock(); defer d.mu.Unlock(); return d.ns } +func (d *fakePlannerData) lastHeard(pks []string) map[string]time.Time { + d.mu.Lock() + defer d.mu.Unlock() + out := map[string]time.Time{} + for _, pk := range pks { + if t, ok := d.heard[pk]; ok { + out[pk] = t + } + } + return out +} +func (d *fakePlannerData) edges([]string) []NeighborEdge { + d.mu.Lock() + defer d.mu.Unlock() + return slices.Clone(d.es) +} +func (d *fakePlannerData) setNodes(ns []nodeInfo) { d.mu.Lock(); d.ns = ns; d.mu.Unlock() } + +// plannerTestNodes: a visible cluster near 30.15,-97.05, nodes /api/nodes +// hides (bad*, zz-*) both inside it and alone far away, and nodes the +// planner must skip for other reasons (companion role, no GPS). +func plannerTestNodes() []nodeInfo { + return []nodeInfo{ + {PublicKey: "aa01", Name: "Hill", Role: "repeater", Lat: 30.10, Lon: -97.10, HasGPS: true, LastSeen: plannerTestStart}, + {PublicKey: "aa02", Name: "Mesa", Role: "repeater", Lat: 30.20, Lon: -97.00, HasGPS: true, LastSeen: plannerTestStart}, + {PublicKey: "aa03", Name: "Hall", Role: "room", Lat: 30.15, Lon: -96.95, HasGPS: true}, + {PublicKey: "cc01", Name: "Phone", Role: "companion", Lat: 30.30, Lon: -97.30, HasGPS: true}, + {PublicKey: "cc02", Name: "North phone", Role: "companion", Lat: 31.50, Lon: -97.10, HasGPS: true}, + {PublicKey: "bad1", Name: "Banned", Role: "repeater", Lat: 30.12, Lon: -97.05, HasGPS: true}, + {PublicKey: "hid1", Name: "zz-secret", Role: "repeater", Lat: 30.18, Lon: -97.08, HasGPS: true}, + {PublicKey: "bad2", Name: "Banned far", Role: "repeater", Lat: 40.00, Lon: -80.00, HasGPS: true}, + {PublicKey: "hid2", Name: "zz-far", Role: "repeater", Lat: 41.00, Lon: -81.00, HasGPS: true}, + {PublicKey: "nogps", Name: "Nowhere", Role: "repeater"}, + } +} + +// plannerStubs stands in for the planner_search functions. +type plannerStubs struct { + mu sync.Mutex + gate chan struct{} // non-nil: searches block until closed (or ctx ends) + entered chan struct{} + panicMsg string + progress float64 + covCalls int + relayCalls int + lastPlan planInputs + lastRelay PlannerRelayParams + relayNodes []plannerNode + cause error // context.Cause a cancelled search saw +} + +func (st *plannerStubs) hold() { + st.mu.Lock() + st.gate = make(chan struct{}) + st.mu.Unlock() +} + +func (st *plannerStubs) release() { + st.mu.Lock() + if st.gate != nil { + close(st.gate) + st.gate = nil + } + st.mu.Unlock() +} + +func (st *plannerStubs) set(fn func(st *plannerStubs)) { st.mu.Lock(); fn(st); st.mu.Unlock() } + +func (st *plannerStubs) calls() (cov, relay int) { + st.mu.Lock() + defer st.mu.Unlock() + return st.covCalls, st.relayCalls +} + +// block runs the common part of both stubs after their bookkeeping. +func (st *plannerStubs) block(ctx context.Context, progress func(float64)) error { + st.mu.Lock() + gate, pm, pr := st.gate, st.panicMsg, st.progress + st.mu.Unlock() + if pm != "" { + panic(pm) + } + if pr > 0 { + progress(pr) + } + select { + case st.entered <- struct{}{}: + default: + } + if gate == nil { + return nil + } + select { + case <-gate: + return nil + case <-ctx.Done(): + st.mu.Lock() + st.cause = context.Cause(ctx) + st.mu.Unlock() + return ctx.Err() + } +} + +func (st *plannerStubs) coverage(ctx context.Context, v terrainView, in planInputs, progress func(float64)) (PlannerPlanResponse, error) { + st.mu.Lock() + st.covCalls++ + st.lastPlan = in + st.mu.Unlock() + if err := st.block(ctx, progress); err != nil { + return PlannerPlanResponse{}, err + } + out := PlannerPlanResponse{Status: "connected"} + for _, n := range in.Nodes { + out.Nodes = append(out.Nodes, PlannerNodeOut{PubKey: n.PubKey, Name: n.Name, Role: n.Role, + Lat: n.Lat, Lon: n.Lon, Stale: n.Stale, InArea: n.InArea}) + } + return out, nil +} + +func (st *plannerStubs) relay(ctx context.Context, v terrainView, nodes []plannerNode, p PlannerRelayParams, progress func(float64)) (PlannerRelayResponse, error) { + st.mu.Lock() + st.relayCalls++ + st.lastRelay = p + st.relayNodes = nodes + st.mu.Unlock() + if err := st.block(ctx, progress); err != nil { + return PlannerRelayResponse{}, err + } + out := PlannerRelayResponse{} + for _, n := range nodes { + out.Existing = append(out.Existing, PlannerRelayOption{Kind: "existing", PubKey: n.PubKey, Name: n.Name, Lat: n.Lat, Lon: n.Lon}) + } + return out, nil +} + +// ─── Harness ──────────────────────────────────────────────────────────────── + +type plannerHarness struct { + srv *Server + p *plannerService + src *fakeTerrain + data *fakePlannerData + clk *plannerTestClock + stubs *plannerStubs +} + +const ( + plannerCovPath = "/api/planner/coverage?bbox=30.0,-97.2,30.35,-96.85" + plannerRelayPath = "/api/planner/relay?a=30.1,-97.1&b=30.2,-97.0" + plannerProfPath = "/api/planner/profile?pts=30.1,-97.1,30.2,-97.0" +) + +func newPlannerHarness(t *testing.T) *plannerHarness { + t.Helper() + return newPlannerHarnessWith(t, PlannerConfig{Enabled: true}) +} + +// newPlannerHarnessWith is newPlannerHarness with its own planner block. +func newPlannerHarnessWith(t *testing.T, pc PlannerConfig) *plannerHarness { + t.Helper() + cfg := &Config{ + Planner: &pc, + NodeBlacklist: []string{"bad1", "bad2"}, + HiddenNamePrefixes: []string{"zz-"}, + } + srv := &Server{cfg: cfg} + p := newPlannerService(pc, srv, nil) + h := &plannerHarness{ + srv: srv, + p: p, + src: &fakeTerrain{resident: true}, + clk: &plannerTestClock{t: plannerTestStart}, + stubs: &plannerStubs{entered: make(chan struct{}, 64)}, + } + h.data = &fakePlannerData{serverPlannerData: serverPlannerData{srv}, ns: plannerTestNodes()} + p.src = h.src + p.data = h.data + p.coverage = h.stubs.coverage + p.relay = h.stubs.relay + p.now = h.clk.now + p.limit.rl.now = h.clk.now + p.downloads.rl.now = h.clk.now + p.global.now = h.clk.now + p.fastWait = 0 + p.watchEvery = 2 * time.Millisecond + srv.planner = p + t.Cleanup(func() { + h.stubs.release() + h.src.releaseAll() + p.Close() + }) + return h +} + +func (h *plannerHarness) get(path, ip string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodGet, path, nil) + req.RemoteAddr = ip + ":40000" + w := httptest.NewRecorder() + switch { + case strings.HasPrefix(path, "/api/planner/profile"): + h.srv.handlePlannerProfile(w, req) + case strings.HasPrefix(path, "/api/planner/relay"): + h.srv.handlePlannerRelay(w, req) + case strings.HasPrefix(path, "/api/planner/viewshed"): + h.srv.handlePlannerViewshed(w, req) + default: + h.srv.handlePlannerCoverage(w, req) + } + return w +} + +// pollUntil re-polls path until its status is want, failing after 5 s. +func (h *plannerHarness) pollUntil(t *testing.T, path, ip string, want int) *httptest.ResponseRecorder { + t.Helper() + // Past plannerComputeTimeout, so a slow runner ends in the job's own + // timeout rather than in a poll that gave up early. + deadline := time.Now().Add(30 * time.Second) + for { + w := h.get(path, ip) + if w.Code == want { + return w + } + if w.Code != http.StatusAccepted || time.Now().After(deadline) { + t.Fatalf("%s: code=%d body=%s, want %d", path, w.Code, w.Body.String(), want) + } + time.Sleep(time.Millisecond) + } +} + +func (h *plannerHarness) waitEntered(t *testing.T) { + t.Helper() + select { + case <-h.stubs.entered: + case <-time.After(5 * time.Second): + t.Fatal("search never started") + } +} + +func (h *plannerHarness) liveJobs() int { + h.p.mu.Lock() + defer h.p.mu.Unlock() + return len(h.p.jobs) +} + +func (h *plannerHarness) tokens(ip string) float64 { + rl := h.p.limit.rl + rl.mu.Lock() + defer rl.mu.Unlock() + if b := rl.buckets[ip]; b != nil { + return b.tokens + } + return float64(plannerIPJobsPerMin) +} + +func plannerWaitFor(t *testing.T, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for !cond() { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for %s", what) + } + time.Sleep(time.Millisecond) + } +} + +func decodeStatus(t *testing.T, w *httptest.ResponseRecorder) PlannerJobStatus { + t.Helper() + var st PlannerJobStatus + if err := json.Unmarshal(w.Body.Bytes(), &st); err != nil { + t.Fatalf("status body %q: %v", w.Body.String(), err) + } + return st +} + +// ─── Tests ────────────────────────────────────────────────────────────────── + +func TestPlannerAPIDisabled(t *testing.T) { + off := newPlannerService(PlannerConfig{}, nil, nil) + t.Cleanup(off.Close) + for _, srv := range []*Server{ + {cfg: &Config{}}, + {cfg: &Config{Planner: &PlannerConfig{Enabled: false}}, planner: off}, + {cfg: &Config{Planner: &PlannerConfig{Enabled: true}}}, + } { + h := &plannerHarness{srv: srv} + for _, path := range []string{plannerProfPath, plannerRelayPath, plannerCovPath} { + w := h.get(path, "198.51.100.1") + if w.Code != http.StatusNotFound || !strings.Contains(w.Body.String(), "planner disabled") { + t.Fatalf("%s: %d %s", path, w.Code, w.Body.String()) + } + } + } +} + +func TestPlannerAPIValidation(t *testing.T) { + seventeen := strings.TrimSuffix(strings.Repeat("30.1,-97.1,", 17), ",") + long := plannerProfPath + "&pad=" + strings.Repeat("x", 520) + manyTiles := func(n int) func(h *plannerHarness) { + return func(h *plannerHarness) { h.src.set(func(f *fakeTerrain) { f.tiles = func(geoBBox) int { return n } }) } + } + cases := []struct { + name, path, want string + setup func(h *plannerHarness) + }{ + // common query rules + {name: "long query", path: long, want: "query too long"}, + {name: "unknown key", path: plannerProfPath + "&x=1", want: "unknown parameter"}, + {name: "duplicate key", path: plannerProfPath + "&pts=30.1,-97.1,30.2,-97.0", want: "duplicate parameter"}, + {name: "semicolon", path: "/api/planner/profile?pts=30.1,-97.1;x=1", want: "malformed query"}, + {name: "relay unknown key", path: plannerRelayPath + "&he=5", want: "unknown parameter"}, + {name: "relay duplicate", path: plannerRelayPath + "&a=30.1,-97.1", want: "duplicate parameter"}, + {name: "coverage unknown", path: plannerCovPath + "&_=1", want: "unknown parameter"}, + {name: "coverage duplicate", path: plannerCovPath + "&sites=2&sites=3", want: "duplicate parameter"}, + {name: "coverage long", path: plannerCovPath + "&baseline=" + strings.Repeat("o", 520), want: "query too long"}, + + // profile + {name: "pts missing", path: "/api/planner/profile", want: "pts required"}, + {name: "pts NaN", path: "/api/planner/profile?pts=NaN,-97.1,30.2,-97.0", want: "invalid"}, + {name: "pts Inf", path: "/api/planner/profile?pts=30.1,Inf,30.2,-97.0", want: "invalid"}, + {name: "pts -Inf", path: "/api/planner/profile?pts=30.1,-97.1,-Inf,-97.0", want: "invalid"}, + {name: "pts lat range", path: "/api/planner/profile?pts=91,-97.1,30.2,-97.0", want: "out-of-range"}, + {name: "pts lon range", path: "/api/planner/profile?pts=30.1,-181,30.2,-97.0", want: "out-of-range"}, + {name: "pts empty number", path: "/api/planner/profile?pts=30.1,,30.2,-97.0", want: "invalid"}, + {name: "one point", path: "/api/planner/profile?pts=30.1,-97.1", want: "2 to 16"}, + {name: "odd count", path: "/api/planner/profile?pts=30.1,-97.1,30.2", want: "2 to 16"}, + {name: "17 points", path: "/api/planner/profile?pts=" + seventeen, want: "2 to 16"}, + {name: "profile tiles", path: plannerProfPath, want: plannerErrTooManyTiles, setup: manyTiles(13)}, + + // relay + {name: "a missing", path: "/api/planner/relay?b=30.2,-97.0", want: "a required"}, + {name: "b missing", path: "/api/planner/relay?a=30.2,-97.0", want: "b required"}, + {name: "a one number", path: "/api/planner/relay?a=30.1&b=30.2,-97.0", want: "a must be"}, + {name: "a three numbers", path: "/api/planner/relay?a=30.1,-97.1,4&b=30.2,-97.0", want: "a must be"}, + {name: "a NaN", path: "/api/planner/relay?a=NaN,-97.1&b=30.2,-97.0", want: "a must be"}, + {name: "b Inf", path: "/api/planner/relay?a=30.1,-97.1&b=30.2,+Inf", want: "b must be"}, + {name: "b range", path: "/api/planner/relay?a=30.1,-97.1&b=-90.5,-97.0", want: "b must be"}, + {name: "ha NaN", path: plannerRelayPath + "&ha=NaN", want: "ha must be"}, + {name: "hr Inf", path: plannerRelayPath + "&hr=Inf", want: "hr must be"}, + {name: "hb empty", path: plannerRelayPath + "&hb=", want: "hb must be"}, + {name: "relay range not in set", path: plannerRelayPath + "&range=25", want: "range must be one of"}, + {name: "relay range NaN", path: plannerRelayPath + "&range=NaN", want: "range must be one of"}, + {name: "relay too long", path: "/api/planner/relay?a=30.1,-97.1&b=31.5,-97.1", want: plannerErrTooLong}, + {name: "relay out of area", path: "/api/planner/relay?a=30.1,-97.1&b=30.9,-97.0", want: plannerErrOutOfArea}, + {name: "relay near hidden only", path: "/api/planner/relay?a=40.0,-80.05&b=40.05,-80.0", want: plannerErrOutOfArea}, + {name: "relay tiles", path: plannerRelayPath, want: plannerErrTooManyTiles, setup: manyTiles(13)}, + + // coverage + {name: "bbox missing", path: "/api/planner/coverage?sites=2", want: "bbox required"}, + {name: "bbox three", path: "/api/planner/coverage?bbox=30,-97.2,30.3", want: "bbox must be"}, + {name: "bbox NaN", path: "/api/planner/coverage?bbox=NaN,-97.2,30.3,-96.9", want: "bbox must be"}, + {name: "bbox Inf", path: "/api/planner/coverage?bbox=30,-97.2,Inf,-96.9", want: "bbox must be"}, + {name: "bbox lon range", path: "/api/planner/coverage?bbox=30,-181,30.3,-96.9", want: "bbox must be"}, + {name: "bbox inverted", path: "/api/planner/coverage?bbox=30.3,-97.2,30.0,-96.9", want: "south below north"}, + {name: "bbox empty", path: "/api/planner/coverage?bbox=30.3,-97.2,30.3,-96.9", want: "south below north"}, + {name: "bbox antimeridian", path: "/api/planner/coverage?bbox=50,179.8,50.3,-179.8", want: "antimeridian"}, + {name: "bbox north of srtm", path: "/api/planner/coverage?bbox=60.01,10,60.3,10.4", want: "latitudes"}, + {name: "bbox snaps north of srtm", path: "/api/planner/coverage?bbox=59.8,10,60.01,10.4", want: "latitudes"}, + {name: "bbox south of srtm", path: "/api/planner/coverage?bbox=-56.3,10,-56.01,10.4", want: "latitudes"}, + {name: "bbox too tall", path: "/api/planner/coverage?bbox=30.0,-97.2,31.0,-96.85", want: plannerErrAreaTooLarge}, + {name: "bbox too wide", path: "/api/planner/coverage?bbox=30.0,-97.6,30.35,-96.5", want: plannerErrAreaTooLarge}, + {name: "sites 0", path: plannerCovPath + "&sites=0", want: "sites must be"}, + {name: "sites 11", path: plannerCovPath + "&sites=11", want: "sites must be"}, + {name: "sites fraction", path: plannerCovPath + "&sites=2.5", want: "sites must be"}, + {name: "sites text", path: plannerCovPath + "&sites=x", want: "sites must be"}, + {name: "coverage range", path: plannerCovPath + "&range=25", want: "range must be one of"}, + {name: "coverage range Inf", path: plannerCovPath + "&range=Inf", want: "range must be one of"}, + {name: "hr NaN", path: plannerCovPath + "&hr=NaN", want: "hr and he"}, + {name: "he Inf", path: plannerCovPath + "&he=-Inf", want: "hr and he"}, + {name: "baseline", path: plannerCovPath + "&baseline=both", want: "baseline must be"}, + {name: "stale 2", path: plannerCovPath + "&stale=2", want: "stale must be"}, + {name: "stale true", path: plannerCovPath + "&stale=true", want: "stale must be"}, + {name: "no nodes", path: "/api/planner/coverage?bbox=10,10,10.3,10.3", want: plannerErrNoNodes}, + {name: "only hidden nodes", path: "/api/planner/coverage?bbox=39.9,-80.1,40.1,-79.9", want: plannerErrNoNodes}, + {name: "only blacklisted node", path: "/api/planner/coverage?bbox=40.9,-81.1,41.1,-80.9", want: plannerErrNoNodes}, + {name: "only companions", path: "/api/planner/coverage?bbox=31.4,-97.2,31.6,-97.0", want: plannerErrNoNodes}, + {name: "coverage tiles", path: plannerCovPath, want: plannerErrTooManyTiles, setup: manyTiles(13)}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + h := newPlannerHarness(t) + if tc.setup != nil { + tc.setup(h) + } + w := h.get(tc.path, "198.51.100.1") + if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), tc.want) { + t.Fatalf("code=%d body=%s, want 400 containing %q", w.Code, w.Body.String(), tc.want) + } + if cc := w.Header().Get("Cache-Control"); cc != "no-store" { + t.Fatalf("Cache-Control=%q", cc) + } + if n := h.liveJobs(); n != 0 || h.tokens("198.51.100.1") != plannerIPJobsPerMin { + t.Fatalf("a rejected request started a job (%d) or took a token", n) + } + }) + } + // The exact tile limits are inclusive. + for _, tc := range []struct { + path string + max int + }{{plannerProfPath, 12}, {plannerRelayPath, 12}, {plannerCovPath, 12}} { + h := newPlannerHarness(t) + h.src.set(func(f *fakeTerrain) { f.tiles = func(geoBBox) int { return tc.max } }) + if w := h.get(tc.path, "198.51.100.1"); w.Code != http.StatusAccepted && w.Code != http.StatusOK { + t.Fatalf("%s at %d tiles: %d %s", tc.path, tc.max, w.Code, w.Body.String()) + } + } +} + +func TestPlannerAPIQuantisationOneJob(t *testing.T) { + h := newPlannerHarness(t) + h.stubs.hold() + rng := rand.New(rand.NewSource(1)) + jitter := func(lo float64) float64 { return lo + 0.001 + rng.Float64()*0.048 } + for i := 0; i < 100; i++ { + path := fmt.Sprintf("/api/planner/coverage?bbox=%.6f,%.6f,%.6f,%.6f", + jitter(30.0), jitter(-97.2), jitter(30.30), jitter(-96.90)) + if w := h.get(path, "198.51.100.1"); w.Code != http.StatusAccepted { + t.Fatalf("request %d (%s): %d %s", i, path, w.Code, w.Body.String()) + } + } + if n := h.liveJobs(); n != 1 { + t.Fatalf("100 jittered boxes made %d jobs, want 1", n) + } + if tok := h.tokens("198.51.100.1"); tok != plannerIPJobsPerMin-1 { + t.Fatalf("tokens=%v: the client was charged more than once", tok) + } + h.waitEntered(t) + h.stubs.mu.Lock() + area := h.stubs.lastPlan.Area + h.stubs.mu.Unlock() + if area != (geoBBox{S: 30.0, W: -97.2, N: 30.35, E: -96.85}) { + t.Fatalf("snapped area %+v", area) + } + // One cell further south is another key. + if w := h.get("/api/planner/coverage?bbox=29.99,-97.19,30.31,-96.89", "198.51.100.1"); w.Code != http.StatusAccepted { + t.Fatalf("neighbouring cell: %d", w.Code) + } + if n := h.liveJobs(); n != 2 { + t.Fatalf("jobs=%d want 2", n) + } + // A value exactly on a grid line stays on it. + if g, msg := plannerParseGridBox("30,-97.2,30.35,-96.85", defaultPlannerMaxAreaKm); msg != "" || g != (plannerGridBox{600, -1944, 607, -1937}) { + t.Fatalf("on-grid box: %+v %q", g, msg) + } +} + +func TestPlannerAPIProtocol(t *testing.T) { + h := newPlannerHarness(t) + h.stubs.hold() + h.stubs.set(func(st *plannerStubs) { st.progress = 0.5 }) + path := plannerCovPath + "&sites=2" + ip := "198.51.100.7" + + w := h.get(path, ip) + if w.Code != http.StatusAccepted { + t.Fatalf("first: %d %s", w.Code, w.Body.String()) + } + if cc := w.Header().Get("Cache-Control"); cc != "no-store" { + t.Fatalf("202 Cache-Control=%q", cc) + } + st := decodeStatus(t, w) + if ra := w.Header().Get("Retry-After"); ra != strconv.Itoa(st.RetryAfterS) || st.RetryAfterS < 1 { + t.Fatalf("Retry-After=%q body=%+v", ra, st) + } + if !slices.Contains([]string{"queued", "loading_terrain", "computing"}, st.State) { + t.Fatalf("state %q", st.State) + } + + h.waitEntered(t) + w = h.get(path, ip) + st = decodeStatus(t, w) + if w.Code != http.StatusAccepted || st.State != "computing" || st.Progress != 0.5 || st.RetryAfterS != 1 || + w.Header().Get("Retry-After") != "1" { + t.Fatalf("second: %d %+v RA=%q", w.Code, st, w.Header().Get("Retry-After")) + } + + h.stubs.release() + w = h.pollUntil(t, path, ip, http.StatusOK) + if cc := w.Header().Get("Cache-Control"); cc != plannerCacheControl { + t.Fatalf("200 Cache-Control=%q", cc) + } + var plan PlannerPlanResponse + if err := json.Unmarshal(w.Body.Bytes(), &plan); err != nil { + t.Fatal(err) + } + if plan.Source != terrainDefaultSource || plan.Params.Sites != 2 || plan.ComputedAt.IsZero() || + plan.Area != (geoBBoxJSON{S: 30.0, W: -97.2, N: 30.35, E: -96.85}) { + t.Fatalf("plan %+v", plan) + } + if !strings.Contains(w.Body.String(), `"warnings":[]`) || !strings.Contains(w.Body.String(), `"sites":[]`) { + t.Fatalf("nil lists not normalised: %s", w.Body.String()) + } + + // Cache hits: same body, no new job, no token. + before := w.Body.String() + for i := 0; i < 10; i++ { + w := h.get(path, ip) + if w.Code != http.StatusOK || w.Body.String() != before { + t.Fatalf("hit %d: %d", i, w.Code) + } + } + if cov, _ := h.stubs.calls(); cov != 1 { + t.Fatalf("searches=%d want 1", cov) + } + if tok := h.tokens(ip); tok != plannerIPJobsPerMin-1 { + t.Fatalf("tokens=%v want %d", tok, plannerIPJobsPerMin-1) + } + // Results expire after the TTL; the next request is a new job. + h.clk.add(plannerResultTTL) + if w := h.get(path, ip); w.Code != http.StatusAccepted && w.Code != http.StatusOK { + t.Fatalf("after TTL: %d", w.Code) + } + plannerWaitFor(t, "second search", func() bool { cov, _ := h.stubs.calls(); return cov == 2 }) +} + +func TestPlannerAPIFastPath(t *testing.T) { + h := newPlannerHarness(t) + h.p.fastWait = plannerFastWait + ip := "198.51.100.8" + + w := h.get(plannerProfPath, ip) + if w.Code != http.StatusOK || w.Header().Get("Cache-Control") != plannerCacheControl { + t.Fatalf("profile: %d %s", w.Code, w.Body.String()) + } + var prof PlannerProfileResponse + if err := json.Unmarshal(w.Body.Bytes(), &prof); err != nil { + t.Fatal(err) + } + d := geoDistKm(geoPoint{30.1, -97.1}, geoPoint{30.2, -97.0}) + if prof.Source != terrainDefaultSource || len(prof.Legs) != 1 || prof.Legs[0].Error != "" || + len(prof.Legs[0].ElevM) != planProfileSamples(d) || prof.Legs[0].DistanceKm != losRound(d, 1000) { + t.Fatalf("profile %+v", prof) + } + if e0 := prof.Legs[0].ElevM[0]; e0 != losRound(100+3*30.1, 10) { + t.Fatalf("first sample %v", e0) + } + + if w := h.get(plannerRelayPath, ip); w.Code != http.StatusOK { + t.Fatalf("relay: %d %s", w.Code, w.Body.String()) + } + if w := h.get(plannerCovPath, ip); w.Code != http.StatusOK { + t.Fatalf("coverage: %d %s", w.Code, w.Body.String()) + } + + // Terrain still to download: no point waiting, answer 202 at once. + gate := make(chan struct{}) + h.src.set(func(f *fakeTerrain) { f.resident = false; f.gate = gate }) + path := "/api/planner/profile?pts=30.15,-97.1,30.2,-97.0" + start := time.Now() + w = h.get(path, ip) + if w.Code != http.StatusAccepted || time.Since(start) > time.Second { + t.Fatalf("non-resident: %d after %v", w.Code, time.Since(start)) + } + plannerWaitFor(t, "loading_terrain", func() bool { + w := h.get(path, ip) + return decodeStatus(t, w).State == "loading_terrain" && w.Header().Get("Retry-After") == "2" + }) + close(gate) + h.pollUntil(t, path, ip, http.StatusOK) +} + +func TestPlannerAPIProfileLegs(t *testing.T) { + h := newPlannerHarness(t) + h.p.fastWait = plannerFastWait + // ok, out_of_area (30.9,-97.0 is >50 km from every visible node), + // out_of_area, too_long. + path := "/api/planner/profile?pts=30.1,-97.1,30.2,-97.0,30.9,-97.0,30.15,-96.95,31.5,-97.1" + w := h.get(path, "198.51.100.9") + if w.Code != http.StatusOK { + t.Fatalf("%d %s", w.Code, w.Body.String()) + } + var prof PlannerProfileResponse + json.Unmarshal(w.Body.Bytes(), &prof) + var codes []string + for _, l := range prof.Legs { + codes = append(codes, l.Error) + if (l.Error == "") != (len(l.ElevM) > 0) { + t.Fatalf("leg %+v", l) + } + } + if want := []string{"", plannerErrOutOfArea, plannerErrOutOfArea, plannerErrTooLong}; !slices.Equal(codes, want) { + t.Fatalf("codes %q want %q", codes, want) + } + // One view over the valid legs only, padded by 0.01°. + bb := h.src.lastBBox() + want := geoBBox{S: 30.09, W: -97.11, N: 30.21, E: -96.99} + if math.Abs(bb.S-want.S) > 1e-9 || math.Abs(bb.W-want.W) > 1e-9 || math.Abs(bb.N-want.N) > 1e-9 || math.Abs(bb.E-want.E) > 1e-9 { + t.Fatalf("view %+v want %+v", bb, want) + } + // No valid leg: answered in the request, no job, no terrain, no token. + views := h.src.viewCount() + w = h.get("/api/planner/profile?pts=30.1,-97.1,31.5,-97.1,40.0,-80.0,40.1,-80.0", "198.51.100.10") + json.Unmarshal(w.Body.Bytes(), &prof) + if w.Code != http.StatusOK || len(prof.Legs) != 3 || prof.Legs[0].Error != plannerErrTooLong || + prof.Legs[2].Error != plannerErrOutOfArea || h.src.viewCount() != views || h.tokens("198.51.100.10") != plannerIPJobsPerMin { + t.Fatalf("all-error profile: %d %s", w.Code, w.Body.String()) + } + // A leg the terrain cannot cover is no_terrain, not a failure. + legs, err := planProfileLegs(context.Background(), fakeTerrainView{bb: geoBBox{S: 0, W: 0, N: 1, E: 1}}, + []geoPoint{{30.1, -97.1}, {30.2, -97.0}}, []PlannerProfileLeg{{DistanceKm: 1}}, func(float64) {}) + if err != nil || legs.Legs[0].Error != plannerErrNoTerrain { + t.Fatalf("no_terrain: %+v %v", legs, err) + } +} + +func TestPlannerAPIRelayParams(t *testing.T) { + h := newPlannerHarness(t) + h.p.fastWait = plannerFastWait + w := h.get(plannerRelayPath+"&ha=2.6&hb=150&hr=-3&range=20", "198.51.100.11") + if w.Code != http.StatusOK { + t.Fatalf("%d %s", w.Code, w.Body.String()) + } + h.stubs.mu.Lock() + got, nodes := h.stubs.lastRelay, h.stubs.relayNodes + h.stubs.mu.Unlock() + radio, _ := (*LOSConfig)(nil).resolved() + want := PlannerRelayParams{ + A: geoPointJSON{30.1, -97.1}, B: geoPointJSON{30.2, -97.0}, + AntennaAM: 3, AntennaBM: 100, RelayAntennaM: 1, + ExistingAntennaM: defaultPlannerExistAntenna, RangeKm: 20, + FrequencyMHz: radio.FrequencyMHz, KFactor: radio.KFactor, + } + if got != want { + t.Fatalf("params %+v\nwant %+v", got, want) + } + var resp PlannerRelayResponse + json.Unmarshal(w.Body.Bytes(), &resp) + if resp.Params != want || resp.Source != terrainDefaultSource || resp.Open == nil || resp.Warnings == nil { + t.Fatalf("response %+v", resp) + } + // Nodes: in the corridor, visible, repeaters/rooms only. + var keys []string + for _, n := range nodes { + keys = append(keys, n.PubKey) + } + if !slices.Contains(keys, "aa01") || !slices.Contains(keys, "aa02") { + t.Fatalf("relay nodes %v", keys) + } + for _, bad := range []string{"bad1", "hid1", "cc01", "nogps"} { + if slices.Contains(keys, bad) || strings.Contains(w.Body.String(), bad) { + t.Fatalf("relay exposed %s: %v", bad, keys) + } + } + // Corridor: A,B ± max(0.3·D, 2 km). + d := geoDistKm(geoPoint{30.1, -97.1}, geoPoint{30.2, -97.0}) + wantView := plannerExpandBBox(geoBBox{S: 30.1, W: -97.1, N: 30.2, E: -97.0}, 0.3*d) + if h.src.lastBBox() != wantView { + t.Fatalf("view %+v want %+v", h.src.lastBBox(), wantView) + } + // Defaults, and the 2 km floor on a short hop. + w = h.get("/api/planner/relay?a=30.1,-97.1&b=30.101,-97.1", "198.51.100.11") + if w.Code != http.StatusOK { + t.Fatalf("%d %s", w.Code, w.Body.String()) + } + h.stubs.mu.Lock() + got = h.stubs.lastRelay + h.stubs.mu.Unlock() + if got.AntennaAM != defaultPlannerNewAntennaM || got.AntennaBM != defaultPlannerNewAntennaM || + got.RelayAntennaM != defaultPlannerNewAntennaM || got.RangeKm != defaultPlannerRangeKm { + t.Fatalf("defaults %+v", got) + } + if v := h.src.lastBBox(); v != plannerExpandBBox(geoBBox{S: 30.1, W: -97.1, N: 30.101, E: -97.1}, plannerRelayPadMinKm) { + t.Fatalf("short-hop view %+v", v) + } +} + +func TestPlannerAPICoverageInputs(t *testing.T) { + h := newPlannerHarness(t) + h.p.fastWait = plannerFastWait + h.data.mu.Lock() + h.data.es = []NeighborEdge{ + {NodeA: "aa01", NodeB: "aa02", Count: 100, LastSeen: plannerTestStart, + Observers: map[string]bool{"o1": true, "o2": true, "o3": true}, CountsByMode: map[int]int{2: 100}}, + {NodeA: "aa01", NodeB: "bad1", Count: 100, LastSeen: plannerTestStart, + Observers: map[string]bool{"o1": true, "o2": true, "o3": true}, CountsByMode: map[int]int{2: 100}}, + } + h.data.mu.Unlock() + w := h.get(plannerCovPath+"&sites=4&range=20&hr=12.4&he=7&baseline=observed&stale=1", "198.51.100.12") + if w.Code != http.StatusOK { + t.Fatalf("%d %s", w.Code, w.Body.String()) + } + h.stubs.mu.Lock() + in := h.stubs.lastPlan + h.stubs.mu.Unlock() + radio, _ := (*LOSConfig)(nil).resolved() + wantParams := PlannerPlanParams{Sites: 4, RangeKm: 20, NewAntennaM: 12, ExistingAntennaM: 7, + Baseline: "observed", IncludeStale: true, FrequencyMHz: radio.FrequencyMHz, KFactor: radio.KFactor, + MinClearance: plannerMinClearance} + if in.Params != wantParams { + t.Fatalf("params %+v\nwant %+v", in.Params, wantParams) + } + area := geoBBox{S: 30.0, W: -97.2, N: 30.35, E: -96.85} + if in.Area != area || in.Truncated { + t.Fatalf("area %+v truncated %v", in.Area, in.Truncated) + } + var keys []string + for _, n := range in.Nodes { + keys = append(keys, n.PubKey) + } + if !slices.Equal(keys, []string{"aa01", "aa02", "aa03"}) { + t.Fatalf("nodes %v", keys) + } + if len(in.Observed) != 1 || in.Observed[0].Class != "observed" { + t.Fatalf("observed %+v", in.Observed) + } + if v := h.src.lastBBox(); v != plannerExpandBBox(area, defaultPlannerNodeMarginKm) { + t.Fatalf("view %+v", v) + } + // Defaults. + w = h.get(plannerCovPath, "198.51.100.12") + if w.Code != http.StatusOK { + t.Fatalf("%d", w.Code) + } + h.stubs.mu.Lock() + in = h.stubs.lastPlan + h.stubs.mu.Unlock() + if p := in.Params; p.Sites != plannerDefaultSites || p.RangeKm != defaultPlannerRangeKm || p.Baseline != "predicted" || + p.IncludeStale || p.NewAntennaM != defaultPlannerNewAntennaM || p.ExistingAntennaM != defaultPlannerExistAntenna { + t.Fatalf("defaults %+v", p) + } +} + +func TestPlannerAPIPerIPLimit(t *testing.T) { + h := newPlannerHarness(t) + h.p.fastWait = plannerFastWait + ip := "198.51.100.20" + path := func(i int) string { + return fmt.Sprintf("/api/planner/profile?pts=%.3f,-97.1,30.2,-97.0", 30.1+float64(i)/1000) + } + for i := 0; i < plannerIPJobsPerMin; i++ { + if w := h.get(path(i), ip); w.Code != http.StatusOK { + t.Fatalf("job %d: %d %s", i, w.Code, w.Body.String()) + } + } + w := h.get(path(99), ip) + if w.Code != http.StatusTooManyRequests || !strings.Contains(w.Body.String(), "rate limited") { + t.Fatalf("7th: %d %s", w.Code, w.Body.String()) + } + if ra, _ := strconv.Atoi(w.Header().Get("Retry-After")); ra != 10 { + t.Fatalf("Retry-After=%q want 10", w.Header().Get("Retry-After")) + } + if h.liveJobs() != 0 { + t.Fatal("a limited request started a job") + } + // Cached results stay free; other clients have their own budget. + if w := h.get(path(0), ip); w.Code != http.StatusOK { + t.Fatalf("cache hit limited: %d", w.Code) + } + if w := h.get(path(99), "198.51.100.21"); w.Code != http.StatusOK { + t.Fatalf("other client: %d", w.Code) + } + h.clk.add(10 * time.Second) + if w := h.get(path(98), ip); w.Code != http.StatusOK { + t.Fatalf("after refill: %d", w.Code) + } +} + +func TestPlannerAPIGlobalCap(t *testing.T) { + h := newPlannerHarness(t) + h.p.fastWait = plannerFastWait + n := 0 + for c := 0; n < plannerGlobalJobsPerMin; c++ { + ip := fmt.Sprintf("198.51.100.%d", 30+c) + for i := 0; i < plannerIPJobsPerMin && n < plannerGlobalJobsPerMin; i++ { + path := fmt.Sprintf("/api/planner/profile?pts=%.3f,-97.1,30.2,-97.0", 30.1+float64(n)/1000) + if w := h.get(path, ip); w.Code != http.StatusOK { + t.Fatalf("job %d: %d %s", n, w.Code, w.Body.String()) + } + n++ + } + } + w := h.get("/api/planner/profile?pts=30.15,-97.15,30.2,-97.0", "198.51.100.99") + if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "planner busy") { + t.Fatalf("31st: %d %s", w.Code, w.Body.String()) + } + if ra, _ := strconv.Atoi(w.Header().Get("Retry-After")); ra < 1 || ra > 60 { + t.Fatalf("Retry-After=%q", w.Header().Get("Retry-After")) + } + // The server being busy is not the client's fault: its token comes back. + if tok := h.tokens("198.51.100.99"); tok != plannerIPJobsPerMin { + t.Fatalf("refused client was charged: tokens %v", tok) + } +} + +func TestPlannerAPICoverageQueueFull(t *testing.T) { + h := newPlannerHarness(t) + h.stubs.hold() + ip := "198.51.100.40" + cov := func(sites int) string { return fmt.Sprintf("%s&sites=%d", plannerCovPath, sites) } + if w := h.get(cov(1), ip); w.Code != http.StatusAccepted { + t.Fatalf("running job: %d", w.Code) + } + h.waitEntered(t) + for s := 2; s <= 1+plannerMaxQueuedCoverage; s++ { + w := h.get(cov(s), ip) + if w.Code != http.StatusAccepted || decodeStatus(t, w).State != "queued" { + t.Fatalf("queued job %d: %d %s", s, w.Code, w.Body.String()) + } + } + other := "198.51.100.41" + w := h.get(cov(9), other) + if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") != "5" { + t.Fatalf("overflow: %d RA=%q %s", w.Code, w.Header().Get("Retry-After"), w.Body.String()) + } + if h.tokens(other) != plannerIPJobsPerMin { + t.Fatal("a refused job charged the client") + } + // Polling a queued job is still fine. + if w := h.get(cov(3), ip); w.Code != http.StatusAccepted { + t.Fatalf("poll of queued job: %d", w.Code) + } + // Cheap jobs are not stuck behind coverage. + h.p.fastWait = plannerFastWait + if w := h.get(plannerProfPath, other); w.Code != http.StatusOK { + t.Fatalf("profile behind coverage: %d", w.Code) + } + // Draining the queue runs every job once. + h.stubs.release() + plannerWaitFor(t, "queue to drain", func() bool { return h.liveJobs() == 0 }) + if c, _ := h.stubs.calls(); c != 1+plannerMaxQueuedCoverage { + t.Fatalf("searches=%d", c) + } + h.p.mu.Lock() + q := h.p.covQueued + h.p.mu.Unlock() + if q != 0 { + t.Fatalf("covQueued=%d after drain", q) + } +} + +func TestPlannerAPILiveJobCap(t *testing.T) { + h := newPlannerHarness(t) + h.stubs.hold() + covIP, relayIP := "198.51.100.50", "198.51.100.51" + if w := h.get(plannerCovPath+"&sites=1", covIP); w.Code != http.StatusAccepted { + t.Fatalf("coverage: %d", w.Code) + } + h.waitEntered(t) + for s := 2; s <= 5; s++ { + if w := h.get(fmt.Sprintf("%s&sites=%d", plannerCovPath, s), covIP); w.Code != http.StatusAccepted { + t.Fatalf("coverage %d: %d", s, w.Code) + } + } + for hr := 1; hr <= plannerMaxLiveJobs-5; hr++ { + if w := h.get(fmt.Sprintf("%s&hr=%d", plannerRelayPath, hr), relayIP); w.Code != http.StatusAccepted { + t.Fatalf("relay %d: %d", hr, w.Code) + } + } + if n := h.liveJobs(); n != plannerMaxLiveJobs { + t.Fatalf("live=%d", n) + } + w := h.get(plannerRelayPath+"&hr=50", relayIP) + if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") != "5" { + t.Fatalf("9th job: %d RA=%q", w.Code, w.Header().Get("Retry-After")) + } +} + +func TestPlannerAPIAbandonedJobCancelled(t *testing.T) { + h := newPlannerHarness(t) + h.stubs.hold() + // Two jobs an hour, so the clock moving below refills nothing useful. + h.p.limit.rl = newRateLimiter(2, time.Hour) + h.p.limit.rl.now = h.clk.now + ip := "198.51.100.60" + if w := h.get(plannerCovPath, ip); w.Code != http.StatusAccepted { + t.Fatalf("%d", w.Code) + } + h.waitEntered(t) + // Polls keep it alive. + h.clk.add(10 * time.Second) + if w := h.get(plannerCovPath, ip); w.Code != http.StatusAccepted { + t.Fatalf("poll: %d", w.Code) + } + h.clk.add(10 * time.Second) + time.Sleep(20 * time.Millisecond) // several watch ticks + if h.liveJobs() != 1 { + t.Fatal("a polled job was cancelled") + } + // 16 s without a poll: cancelled and removed. + h.clk.add(6 * time.Second) + plannerWaitFor(t, "abandoned job to go", func() bool { return h.liveJobs() == 0 }) + h.stubs.mu.Lock() + cause := h.stubs.cause + h.stubs.mu.Unlock() + if !errors.Is(cause, errPlannerAbandoned) { + t.Fatalf("search saw cause %v", cause) + } + if len(h.p.covSlots) != 0 { + t.Fatal("slot not released") + } + // The next poll starts afresh, and pays for it. + if w := h.get(plannerCovPath, ip); w.Code != http.StatusAccepted { + t.Fatalf("restart: %d", w.Code) + } + plannerWaitFor(t, "second search", func() bool { c, _ := h.stubs.calls(); return c == 2 }) + if tok := h.tokens(ip); tok >= 1 { + t.Fatalf("restart was free (tokens %v)", tok) + } +} + +func TestPlannerAPIPanicRecovered(t *testing.T) { + h := newPlannerHarness(t) + h.p.fastWait = plannerFastWait + h.stubs.set(func(st *plannerStubs) { st.panicMsg = "boom" }) + for _, path := range []string{plannerCovPath, plannerRelayPath} { + w := h.get(path, "198.51.100.70") + if w.Code != http.StatusInternalServerError || !strings.Contains(w.Body.String(), "planner failed") || + strings.Contains(w.Body.String(), "boom") { + t.Fatalf("%s: %d %s", path, w.Code, w.Body.String()) + } + } + if h.liveJobs() != 0 || len(h.p.covSlots) != 0 || len(h.p.cheapSlots) != 0 { + t.Fatal("panicked job left state behind") + } + // The crashing query is not replayed for plannerFailedFor... + h.stubs.set(func(st *plannerStubs) { st.panicMsg = "" }) + for _, path := range []string{plannerCovPath, plannerRelayPath} { + w := h.get(path, "198.51.100.70") + if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), plannerMsgFailedRecent) { + t.Fatalf("right after panic %s: %d %s", path, w.Code, w.Body.String()) + } + } + if cov, relay := h.stubs.calls(); cov != 1 || relay != 1 { + t.Fatalf("searches re-ran: %d %d", cov, relay) + } + // ...the server still serves everything else... + if w := h.get(plannerCovPath+"&sites=2", "198.51.100.70"); w.Code != http.StatusOK { + t.Fatalf("other key after panic: %d %s", w.Code, w.Body.String()) + } + // ...and the key itself once the window has passed. + h.clk.add(plannerFailedFor) + for _, path := range []string{plannerCovPath, plannerRelayPath} { + if w := h.get(path, "198.51.100.71"); w.Code != http.StatusOK { + t.Fatalf("after the window %s: %d %s", path, w.Code, w.Body.String()) + } + } +} + +func TestPlannerAPITerrainBusy(t *testing.T) { + h := newPlannerHarness(t) + h.src.set(func(f *fakeTerrain) { f.resident = false; f.err = errTerrainBusy }) + ip := "198.51.100.80" + h.get(plannerCovPath, ip) + w := h.pollUntil(t, plannerCovPath, ip, http.StatusServiceUnavailable) + if w.Header().Get("Retry-After") != "30" || !strings.Contains(w.Body.String(), "terrain busy") { + t.Fatalf("busy: RA=%q %s", w.Header().Get("Retry-After"), w.Body.String()) + } + if v := h.src.viewCount(); v != 1 { + t.Fatalf("views=%d", v) + } + // Within 30 s: the same answer without a new job or token. + h.clk.add(20 * time.Second) + w = h.get(plannerCovPath, ip) + if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") != "10" || h.src.viewCount() != 1 || + h.liveJobs() != 0 { + t.Fatalf("busy window: %d RA=%q views=%d", w.Code, w.Header().Get("Retry-After"), h.src.viewCount()) + } + // After it, the next poll restarts. + h.clk.add(11 * time.Second) + h.src.set(func(f *fakeTerrain) { f.err = nil }) + h.pollUntil(t, plannerCovPath, ip, http.StatusOK) + if v := h.src.viewCount(); v != 2 { + t.Fatalf("views=%d want 2", v) + } + // Other terrain failures are remembered for plannerFailedFor instead. + h.p.fastWait = plannerFastWait + h.src.set(func(f *fakeTerrain) { f.resident = true; f.err = errTerrainUnavailable }) + path := plannerCovPath + "&sites=5" + w = h.get(path, ip) + if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "terrain unavailable") || + w.Header().Get("Retry-After") != "300" { + t.Fatalf("unavailable: %d RA=%q %s", w.Code, w.Header().Get("Retry-After"), w.Body.String()) + } + h.src.set(func(f *fakeTerrain) { f.err = nil }) + views := h.src.viewCount() + if w := h.get(path, ip); w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), plannerMsgFailedRecent) || + h.src.viewCount() != views { + t.Fatalf("retry inside the window: %d %s", w.Code, w.Body.String()) + } + h.clk.add(plannerFailedFor) + if w := h.get(path, ip); w.Code != http.StatusOK { + t.Fatalf("retry after the window: %d", w.Code) + } +} + +func TestPlannerAPIExposure(t *testing.T) { + h := newPlannerHarness(t) + h.p.fastWait = plannerFastWait + ip := "198.51.100.90" + w := h.get(plannerCovPath, ip) + if w.Code != http.StatusOK { + t.Fatalf("%d %s", w.Code, w.Body.String()) + } + var plan PlannerPlanResponse + json.Unmarshal(w.Body.Bytes(), &plan) + var keys []string + for _, n := range plan.Nodes { + keys = append(keys, n.PubKey) + } + if !slices.Equal(keys, []string{"aa01", "aa02", "aa03"}) { + t.Fatalf("nodes %v", keys) + } + for _, hidden := range []string{"bad1", "hid1", "Banned", "zz-secret"} { + if strings.Contains(w.Body.String(), hidden) { + t.Fatalf("response exposes %q", hidden) + } + } + // A profile point near only hidden nodes is out of area. + w = h.get("/api/planner/profile?pts=40.0,-80.05,40.05,-80.0", ip) + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), plannerErrOutOfArea) { + t.Fatalf("profile near hidden node: %d %s", w.Code, w.Body.String()) + } + // Blacklisting at runtime: the cached plan is not served again. + h.srv.cfg.SetNodeBlacklist([]string{"bad1", "bad2", "aa01"}) + w = h.get(plannerCovPath, ip) + if w.Code != http.StatusOK || strings.Contains(w.Body.String(), "aa01") { + t.Fatalf("after blacklisting aa01: %d %s", w.Code, w.Body.String()) + } + if c, _ := h.stubs.calls(); c != 2 { + t.Fatalf("searches=%d want 2", c) + } +} + +func TestPlannerAPIFingerprint(t *testing.T) { + area := geoBBox{S: 30.0, W: -97.2, N: 30.35, E: -96.85} + f := plannerNodeFilter{} + fp := func(ns []nodeInfo) string { + _, s := buildPlannerKnown(ns, f, "", plannerTestStart).scan(area, plannerAreaNodeKm, defaultPlannerNodeMarginKm) + return s + } + base := plannerTestNodes() + ref := fp(base) + moved := plannerTestNodes() + moved[0].Lat += 0.01 + if fp(moved) == ref { + t.Fatal("moving an in-area repeater kept the fingerprint") + } + jitter := plannerTestNodes() + jitter[0].Lat += 0.0001 + if fp(jitter) != ref { + t.Fatal("sub-quantum jitter changed the fingerprint") + } + shuffled := plannerTestNodes() + slices.Reverse(shuffled) + if fp(shuffled) != ref { + t.Fatal("node order changed the fingerprint") + } + far := append(plannerTestNodes(), nodeInfo{PublicKey: "far1", Role: "repeater", Lat: 35, Lon: -90, HasGPS: true}) + if fp(far) != ref { + t.Fatal("a repeater far outside the area changed the fingerprint") + } + phone := append(plannerTestNodes(), nodeInfo{PublicKey: "cc09", Role: "companion", Lat: 30.1, Lon: -97.0, HasGPS: true}) + if fp(phone) != ref { + t.Fatal("a companion changed the fingerprint") + } + + // End to end: the known set refreshes after 60 s and the moved node + // makes a new key. + h := newPlannerHarness(t) + h.p.fastWait = plannerFastWait + ip := "198.51.100.95" + if w := h.get(plannerCovPath, ip); w.Code != http.StatusOK { + t.Fatalf("%d", w.Code) + } + h.data.setNodes(moved) + if w := h.get(plannerCovPath, ip); w.Code != http.StatusOK { + t.Fatalf("%d", w.Code) + } + if c, _ := h.stubs.calls(); c != 1 { + t.Fatalf("known set rebuilt early (searches=%d)", c) + } + h.clk.add(plannerKnownTTL + time.Second) + if w := h.get(plannerCovPath, ip); w.Code != http.StatusOK { + t.Fatalf("%d", w.Code) + } + if c, _ := h.stubs.calls(); c != 2 { + t.Fatalf("moved node did not change the key (searches=%d)", c) + } +} + +func TestPlannerAPIDefaultDataSource(t *testing.T) { + cfg := &Config{Planner: &PlannerConfig{Enabled: true}, LOS: &LOSConfig{FrequencyMHz: 915, KFactor: 1.2}} + srv := &Server{cfg: cfg} + p := newPlannerService(PlannerConfig{Enabled: true}, srv, nil) + t.Cleanup(p.Close) + srv.planner = p + if p.freqMHz != 915 || p.kFactor != 1.2 { + t.Fatalf("radio %v %v", p.freqMHz, p.kFactor) + } + if _, ok := p.src.(*srtmSource); !ok { + t.Fatalf("terrain source %T", p.src) + } + if p.cfg.DefaultRangeKm != defaultPlannerRangeKm || p.cfg.NewAntennaM != defaultPlannerNewAntennaM { + t.Fatalf("config not resolved: %+v", p.cfg) + } + h := &plannerHarness{srv: srv} + // No store: no known nodes, so nothing reaches terrain or compute. + if w := h.get(plannerCovPath, "198.51.100.96"); w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), plannerErrNoNodes) { + t.Fatalf("coverage: %d %s", w.Code, w.Body.String()) + } + if w := h.get(plannerRelayPath, "198.51.100.96"); w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), plannerErrOutOfArea) { + t.Fatalf("relay: %d %s", w.Code, w.Body.String()) + } + if w := h.get(plannerProfPath, "198.51.100.96"); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), plannerErrOutOfArea) { + t.Fatalf("profile: %d %s", w.Code, w.Body.String()) + } + d := serverPlannerData{srv} + if d.nodes() != nil || d.lastHeard([]string{"x"}) != nil || len(d.edges([]string{"x"})) != 0 { + t.Fatal("storeless data source returned data") + } + fl := d.filter() + if fl.SilentAfter("repeater") != 72*time.Hour || fl.SilentAfter("companion") != 24*time.Hour { + t.Fatalf("silent windows %v %v", fl.SilentAfter("repeater"), fl.SilentAfter("companion")) + } + gen := d.filterGen() + cfg.SetHiddenNamePrefixes([]string{"x-"}) + if d.filterGen() == gen { + t.Fatal("filterGen ignores hidden-prefix changes") + } +} + +func TestPlannerAPIResultCacheBounds(t *testing.T) { + now := plannerTestStart + body := func(n int) []byte { return make([]byte, n) } + + c := newPlannerLRU(3, 1<<20, time.Minute) + for _, k := range []string{"a", "b", "c"} { + c.put(k, body(10), now) + } + c.get("a", now) // a is now most recent; b is the eviction candidate + c.put("d", body(10), now) + if _, ok := c.get("b", now); ok || c.len() != 3 { + t.Fatalf("item cap: len=%d", c.len()) + } + if _, ok := c.get("a", now); !ok { + t.Fatal("recently used entry evicted") + } + if _, ok := c.get("a", now.Add(time.Minute)); ok || c.len() != 2 { + t.Fatal("expired entry served") + } + + c = newPlannerLRU(100, 1000, time.Minute) + for i := 0; i < 4; i++ { + c.put(strconv.Itoa(i), body(240), now) // 241 bytes each + } + c.put("4", body(240), now) + if _, ok := c.get("0", now); ok || c.len() != 4 || c.cache.size > 1000 { + t.Fatalf("byte cap: len=%d size=%d", c.len(), c.cache.size) + } + c.put("big", body(300), now) // over a quarter of the budget + if _, ok := c.get("big", now); ok { + t.Fatal("oversized entry cached") + } + c.put("1", body(10), now) // replacing an entry adjusts the size + if c.cache.size != 241*3+11 { + t.Fatalf("size=%d", c.cache.size) + } +} + +func TestPlannerAPICloseStopsJobs(t *testing.T) { + h := newPlannerHarness(t) + h.stubs.hold() + h.get(plannerCovPath, "198.51.100.97") + h.waitEntered(t) + done := make(chan struct{}) + go func() { h.p.Close(); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("Close did not stop the running job") + } + if w := h.get(plannerCovPath+"&sites=2", "198.51.100.97"); w.Code != http.StatusServiceUnavailable { + t.Fatalf("after Close: %d", w.Code) + } +} + +// ─── Shared limiter ───────────────────────────────────────────────────────── + +func TestClientLimitPerClientAndShared(t *testing.T) { + req := func(remote, xff string) *http.Request { + r := httptest.NewRequest(http.MethodGet, "/", nil) + r.RemoteAddr = remote + if xff != "" { + r.Header.Set("X-Forwarded-For", xff) + } + return r + } + off := &clientLimiter{} + for i := 0; i < 50; i++ { + if ok, _ := off.take(req("203.0.113.1:1", "")); !ok { + t.Fatal("limiter without buckets limited") + } + } + + clk := &plannerTestClock{t: plannerTestStart} + c := &clientLimiter{ipr: &wsLimiter{state: map[string]*wsIPState{}}, rl: newRateLimiter(2, time.Minute), tag: "test", what: "test"} + c.rl.now = clk.now + allow := func(w http.ResponseWriter, r *http.Request) bool { + ok, wait := c.take(r) + if !ok { + writeRateLimited(w, wait) + } + return ok + } + for i := 0; i < 2; i++ { + if !allow(httptest.NewRecorder(), req("203.0.113.1:1", "")) { + t.Fatalf("request %d limited", i) + } + } + w := httptest.NewRecorder() + if allow(w, req("203.0.113.1:2", "")) || w.Code != http.StatusTooManyRequests || + w.Header().Get("Retry-After") != "30" || !strings.Contains(w.Body.String(), "rate limited") { + t.Fatalf("3rd: %d RA=%q %s", w.Code, w.Header().Get("Retry-After"), w.Body.String()) + } + if !allow(httptest.NewRecorder(), req("203.0.113.2:1", "")) { + t.Fatal("another client shares the bucket") + } + // Behind an untrusted local proxy, X-Forwarded-For is ignored and the + // clients cannot be told apart: none is charged. + if k, distinct := c.clientKey(req("127.0.0.1:1", "198.51.100.1")); k != clientSharedKey || distinct { + t.Fatalf("indistinct key %q, distinct %v", k, distinct) + } + for i := 0; i < 5; i++ { + if !allow(httptest.NewRecorder(), req("127.0.0.1:1", "198.51.100.1")) { + t.Fatalf("indistinct request %d limited", i) + } + } + c.ipr.trustedProxies = parseCIDRList([]string{"127.0.0.1"}, "test") + if k, distinct := c.clientKey(req("127.0.0.1:1", "198.51.100.1")); k != "198.51.100.1" || !distinct { + t.Fatalf("trusted proxy key %q, distinct %v", k, distinct) + } + if retryAfterSecs(0) != 1 || retryAfterSecs(1500*time.Millisecond) != 2 { + t.Fatal("retryAfterSecs") + } +} + +// ─── Edge snapshots ───────────────────────────────────────────────────────── + +func TestSnapshotEdgesDeepCopy(t *testing.T) { + g := NewNeighborGraph() + snr := 5.0 + g.upsertEdge("aa", "bb", "aabb", "obs1", &snr, plannerTestStart) + amb := &NeighborEdge{NodeA: "cc", Prefix: "dd", Ambiguous: true, Candidates: []string{"d1", "d2"}, + Observers: map[string]bool{"o": true}, CountsByMode: map[int]int{1: 2}} + g.mu.Lock() + g.edges[makeEdgeKey("cc", "dd?")] = amb + g.mu.Unlock() + + snap := g.SnapshotEdges() + if len(snap) != 2 { + t.Fatalf("len=%d", len(snap)) + } + var ab, cc *NeighborEdge + for i := range snap { + if snap[i].NodeA == "aa" { + ab = &snap[i] + } else { + cc = &snap[i] + } + } + // The graph moving on does not reach the copy. + g.upsertEdge("aa", "bb", "aabb", "obs2", &snr, plannerTestStart.Add(time.Minute)) + if ab.Count != 1 || len(ab.Observers) != 1 || ab.CountsByMode[2] != 1 || !ab.LastSeen.Equal(plannerTestStart) { + t.Fatalf("copy changed with the graph: %+v", ab) + } + // Changing the copy does not reach the graph. + cc.Candidates[0] = "x" + cc.Observers["evil"] = true + cc.CountsByMode[9] = 9 + if amb.Candidates[0] != "d1" || len(amb.Observers) != 1 || len(amb.CountsByMode) != 1 { + t.Fatalf("graph changed with the copy: %+v", amb) + } + // Among: resolved edges with both ends in the set, case-insensitively. + among := g.snapshotEdgesAmong([]string{"AA", "bb", "cc"}) + if len(among) != 1 || among[0].NodeA != "aa" || among[0].Count != 2 { + t.Fatalf("among %+v", among) + } + if len(g.snapshotEdgesAmong([]string{"aa"})) != 0 { + t.Fatal("edge with one end outside the set") + } + var nilGraph *NeighborGraph + if nilGraph.SnapshotEdges() != nil { + t.Fatal("nil graph") + } +} + +func TestSnapshotEdgesConcurrentUpserts(t *testing.T) { + g := NewNeighborGraph() + var running atomic.Int32 + var wg sync.WaitGroup + for w := 0; w < 4; w++ { + running.Add(1) + wg.Add(1) + go func(w int) { + defer wg.Done() + defer running.Add(-1) + snr := float64(w) + for i := 0; i < 3000; i++ { + g.upsertEdge(fmt.Sprintf("n%02d", i%13), fmt.Sprintf("m%02d", (i+w)%11), "aabb", + fmt.Sprintf("obs%d", i%7), &snr, plannerTestStart.Add(time.Duration(i)*time.Second)) + } + }(w) + } + reads := 0 + for running.Load() > 0 || reads == 0 { + for _, list := range [][]NeighborEdge{g.SnapshotEdges(), g.snapshotEdgesAmong([]string{"n01", "m02", "n03", "m04"})} { + for _, e := range list { + for o := range e.Observers { + _ = o + } + for m, c := range e.CountsByMode { + _ = m + c + } + // Writing the copy must not race with ingest writing the graph. + e.Observers["reader"] = true + e.CountsByMode[0]++ + _ = e.Count + e.SNRCount + } + } + reads++ + } + wg.Wait() + for _, e := range g.AllEdges() { + if e.Observers["reader"] { + t.Fatal("a snapshot write reached the graph") + } + } +} + +// ─── Failure memory, terrain order, missing terrain ───────────────────────── + +func TestPlannerAPIFailedJobRemembered(t *testing.T) { + h := newPlannerHarness(t) + h.p.computeTimeout = 30 * time.Millisecond + var sleep atomic.Int64 + sleep.Store(int64(150 * time.Millisecond)) + var calls atomic.Int32 + // Ignores its context: sleeps past the deadline, then "succeeds". + h.p.coverage = func(ctx context.Context, v terrainView, in planInputs, progress func(float64)) (PlannerPlanResponse, error) { + calls.Add(1) + time.Sleep(time.Duration(sleep.Load())) + return PlannerPlanResponse{Status: "connected"}, nil + } + ip := "198.51.100.110" + if w := h.get(plannerCovPath, ip); w.Code != http.StatusAccepted { + t.Fatalf("first: %d", w.Code) + } + w := h.pollUntil(t, plannerCovPath, ip, http.StatusServiceUnavailable) + if w.Header().Get("Retry-After") != "300" { + t.Fatalf("late result: RA=%q %s", w.Header().Get("Retry-After"), w.Body.String()) + } + // Every later request in the window: 503, no job, no token. + for i := 0; i < 3; i++ { + w := h.get(plannerCovPath, ip) + if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), plannerMsgFailedRecent) || + w.Header().Get("Retry-After") != "300" { + t.Fatalf("in the window: %d RA=%q %s", w.Code, w.Header().Get("Retry-After"), w.Body.String()) + } + } + if n := calls.Load(); n != 1 || h.liveJobs() != 0 || h.tokens(ip) != plannerIPJobsPerMin-1 { + t.Fatalf("searches=%d live=%d tokens=%v", n, h.liveJobs(), h.tokens(ip)) + } + h.clk.add(plannerFailedFor - time.Minute) + if w := h.get(plannerCovPath, ip); w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") != "60" { + t.Fatalf("a minute left: %d RA=%q", w.Code, w.Header().Get("Retry-After")) + } + h.clk.add(time.Minute) + sleep.Store(0) + h.pollUntil(t, plannerCovPath, ip, http.StatusOK) + if n := calls.Load(); n != 2 { + t.Fatalf("searches=%d want 2", n) + } + + // A search that honours its deadline fails the same way; the request + // waiting on it is told why. + h.p.fastWait = plannerFastWait + h.p.relay = func(ctx context.Context, v terrainView, nodes []plannerNode, p PlannerRelayParams, progress func(float64)) (PlannerRelayResponse, error) { + <-ctx.Done() + return PlannerRelayResponse{}, ctx.Err() + } + w = h.get(plannerRelayPath, ip) + if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "planner timed out") { + t.Fatalf("relay timeout: %d %s", w.Code, w.Body.String()) + } + if w := h.get(plannerRelayPath, ip); !strings.Contains(w.Body.String(), plannerMsgFailedRecent) { + t.Fatalf("relay retry: %d %s", w.Code, w.Body.String()) + } +} + +// Jobs nobody polls are dropped, not held against the key. +func TestPlannerAPIAbandonedJobNotRemembered(t *testing.T) { + h := newPlannerHarness(t) + h.stubs.hold() + ip := "198.51.100.111" + h.get(plannerCovPath, ip) + h.waitEntered(t) + h.clk.add(plannerAbandonAfter + time.Second) + plannerWaitFor(t, "abandoned job to go", func() bool { return h.liveJobs() == 0 }) + h.p.mu.Lock() + n := len(h.p.recent) + h.p.mu.Unlock() + if n != 0 { + t.Fatalf("abandoned job remembered (%d entries)", n) + } + if w := h.get(plannerCovPath, ip); w.Code != http.StatusAccepted { + t.Fatalf("after abandonment: %d %s", w.Code, w.Body.String()) + } +} + +func TestPlannerAPITerrainBeforeSlot(t *testing.T) { + h := newPlannerHarness(t) + view1 := plannerExpandBBox(geoBBox{S: 30.0, W: -97.2, N: 30.35, E: -96.85}, defaultPlannerNodeMarginKm) + h.src.hold(view1) // the first job's terrain takes as long as we like + ip := "198.51.100.112" + if w := h.get(plannerCovPath, ip); w.Code != http.StatusAccepted { + t.Fatalf("slow job: %d", w.Code) + } + plannerWaitFor(t, "loading_terrain", func() bool { + return decodeStatus(t, h.get(plannerCovPath, ip)).State == "loading_terrain" + }) + // A second area whose terrain is resident runs to completion meanwhile. + h.p.fastWait = plannerFastWait + other := "/api/planner/coverage?bbox=30.05,-97.15,30.3,-96.9" + if w := h.get(other, ip); w.Code != http.StatusOK { + t.Fatalf("resident job behind a download: %d %s", w.Code, w.Body.String()) + } + if st := decodeStatus(t, h.get(plannerCovPath, ip)); st.State != "loading_terrain" { + t.Fatalf("first job state %q", st.State) + } + h.p.mu.Lock() + q := h.p.covQueued + h.p.mu.Unlock() + if q != 1 { + t.Fatalf("covQueued=%d: a loading job must count as queued", q) + } + h.src.release(view1) + h.pollUntil(t, plannerCovPath, ip, http.StatusOK) +} + +func TestPlannerAPILoadingJobsCountAsQueued(t *testing.T) { + h := newPlannerHarness(t) + view := plannerExpandBBox(geoBBox{S: 30.0, W: -97.2, N: 30.35, E: -96.85}, defaultPlannerNodeMarginKm) + h.src.hold(view) + ip := "198.51.100.113" + for s := 1; s <= plannerMaxQueuedCoverage; s++ { + if w := h.get(fmt.Sprintf("%s&sites=%d", plannerCovPath, s), ip); w.Code != http.StatusAccepted { + t.Fatalf("job %d: %d", s, w.Code) + } + } + w := h.get(plannerCovPath+"&sites=9", ip) + if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") != "5" { + t.Fatalf("5th loading coverage job: %d RA=%q", w.Code, w.Header().Get("Retry-After")) + } + if len(h.p.covSlots) != 0 { + t.Fatal("a job took the compute slot before its terrain loaded") + } + h.src.release(view) + plannerWaitFor(t, "jobs to finish", func() bool { return h.liveJobs() == 0 }) + if c, _ := h.stubs.calls(); c != plannerMaxQueuedCoverage { + t.Fatalf("searches=%d", c) + } +} + +func TestPlannerAPIMissingTerrainWarnings(t *testing.T) { + h := newPlannerHarness(t) + h.p.fastWait = plannerFastWait + ip := "198.51.100.114" + warning := func(view geoBBox) string { + return fmt.Sprintf("Terrain missing for 1 of %d tiles (open sea or unavailable): sites and links there were skipped", + len(fakeTiles(view))) + } + setMissing := func(tiles ...[2]int) { + h.src.set(func(f *fakeTerrain) { + f.missing = map[[2]int]bool{} + for _, t := range tiles { + f.missing[t] = true + } + }) + } + + // Coverage: its view spans 29..30 N, 98..97 W; one corner has no data. + setMissing([2]int{29, -98}) + w := h.get(plannerCovPath, ip) + var plan PlannerPlanResponse + json.Unmarshal(w.Body.Bytes(), &plan) + if want := warning(h.src.lastBBox()); w.Code != http.StatusOK || !slices.Contains(plan.Warnings, want) { + t.Fatalf("coverage: %d warnings %q, want %q", w.Code, plan.Warnings, want) + } + + setMissing([2]int{30, -98}) + w = h.get(plannerRelayPath, ip) + var relay PlannerRelayResponse + json.Unmarshal(w.Body.Bytes(), &relay) + if want := warning(h.src.lastBBox()); w.Code != http.StatusOK || !slices.Contains(relay.Warnings, want) { + t.Fatalf("relay: %d warnings %q, want %q", w.Code, relay.Warnings, want) + } + + // Profile: the first leg stays in 30N 98W; the second crosses into + // 30N 97W, which has no data. + setMissing([2]int{30, -97}) + w = h.get("/api/planner/profile?pts=30.1,-97.3,30.2,-97.2,30.15,-96.95", ip) + var prof PlannerProfileResponse + json.Unmarshal(w.Body.Bytes(), &prof) + if w.Code != http.StatusOK || len(prof.Legs) != 2 { + t.Fatalf("profile: %d %s", w.Code, w.Body.String()) + } + if prof.Legs[0].Error != "" || len(prof.Legs[0].ElevM) == 0 { + t.Fatalf("leg over good terrain: %+v", prof.Legs[0]) + } + if prof.Legs[1].Error != plannerErrNoTerrain || prof.Legs[1].ElevM != nil { + t.Fatalf("leg over missing terrain: %+v", prof.Legs[1]) + } + if want := warning(h.src.lastBBox()); !slices.Equal(prof.Warnings, []string{want}) { + t.Fatalf("profile warnings %q, want %q", prof.Warnings, want) + } + + // Full terrain: no warning anywhere. + setMissing() + w = h.get("/api/planner/profile?pts=30.1,-97.3,30.2,-97.2,30.15,-96.94", ip) + if w.Code != http.StatusOK || strings.Contains(w.Body.String(), "warnings") || strings.Contains(w.Body.String(), plannerErrNoTerrain) { + t.Fatalf("complete terrain: %d %s", w.Code, w.Body.String()) + } + w = h.get(plannerCovPath+"&sites=2", ip) + json.Unmarshal(w.Body.Bytes(), &plan) + if len(plan.Warnings) != 0 { + t.Fatalf("complete terrain coverage warnings %q", plan.Warnings) + } +} + +// ─── /api/planner/viewshed ────────────────────────────────────────────────── + +// plannerViewshedPath: a site 1.4 km from Hill (aa01) and 13 km from Mesa +// (aa02), both repeaters of plannerTestNodes. +const plannerViewshedPath = "/api/planner/viewshed?site=30.11,-97.09" + +// plannerViewshedResultPath computes a full grid at 15 km, which still holds +// Hill and Mesa: a 30 km grid has 4 times the cells and passed the 20 s job +// timeout on a CI runner with coverage on. +const plannerViewshedResultPath = plannerViewshedPath + "&range=15" + +const plannerViewshedResultKm = 15 + +func TestPlannerViewshedDisabled404(t *testing.T) { + off := newPlannerService(PlannerConfig{}, nil, nil) + t.Cleanup(off.Close) + for _, srv := range []*Server{ + {cfg: &Config{}}, + {cfg: &Config{Planner: &PlannerConfig{Enabled: false}}, planner: off}, + {cfg: &Config{Planner: &PlannerConfig{Enabled: true}}}, + } { + h := &plannerHarness{srv: srv} + w := h.get(plannerViewshedPath, "198.51.100.1") + if w.Code != http.StatusNotFound || !strings.Contains(w.Body.String(), "planner disabled") { + t.Fatalf("%d %s", w.Code, w.Body.String()) + } + } +} + +func TestPlannerViewshedBadRequests(t *testing.T) { + cases := []struct{ name, path, want string }{ + {"site missing", "/api/planner/viewshed?h=10", "site required"}, + {"site lat range", "/api/planner/viewshed?site=91,0", "site must be lat,lon within range"}, + {"site one number", "/api/planner/viewshed?site=30.1", "site must be lat,lon within range"}, + {"unknown key", plannerViewshedPath + "&foo=1", "unknown parameter"}, + {"duplicate key", plannerViewshedPath + "&h=5&h=6", "duplicate parameter"}, + {"h NaN", plannerViewshedPath + "&h=NaN", "h must be a number of metres"}, + {"rx Inf", plannerViewshedPath + "&rx=Inf", "rx must be a number of metres"}, + {"range not offered", plannerViewshedPath + "&range=7", "range must be one of"}, + {"no node near", "/api/planner/viewshed?site=10,10", plannerErrOutOfArea}, + {"near hidden only", "/api/planner/viewshed?site=40.0,-80.05", plannerErrOutOfArea}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + h := newPlannerHarness(t) + w := h.get(tc.path, "198.51.100.1") + if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), tc.want) { + t.Fatalf("code=%d body=%s, want 400 containing %q", w.Code, w.Body.String(), tc.want) + } + if n := h.liveJobs(); n != 0 || h.tokens("198.51.100.1") != plannerIPJobsPerMin || h.src.viewCount() != 0 { + t.Fatalf("a rejected request started a job (%d), took a token or read terrain", n) + } + }) + } +} + +func TestPlannerViewshedTooManyTiles(t *testing.T) { + h := newPlannerHarness(t) + h.src.set(func(f *fakeTerrain) { f.tiles = func(geoBBox) int { return h.p.tiles.Viewshed + 1 } }) + w := h.get(plannerViewshedPath, "198.51.100.1") + if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), plannerErrTooManyTiles) { + t.Fatalf("%d %s", w.Code, w.Body.String()) + } + if h.src.viewCount() != 0 || h.liveJobs() != 0 { + t.Fatalf("views %d, jobs %d", h.src.viewCount(), h.liveJobs()) + } + // The cap itself is accepted. + h.src.set(func(f *fakeTerrain) { f.tiles = func(geoBBox) int { return h.p.tiles.Viewshed } }) + if w := h.get(plannerViewshedPath, "198.51.100.1"); w.Code != http.StatusAccepted && w.Code != http.StatusOK { + t.Fatalf("at the cap: %d %s", w.Code, w.Body.String()) + } +} + +func decodeViewshed(t *testing.T, w *httptest.ResponseRecorder) (PlannerViewshedResponse, []byte) { + t.Helper() + var resp PlannerViewshedResponse + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("body %q: %v", w.Body.String(), err) + } + cells, err := base64.StdEncoding.DecodeString(resp.Cells) + if err != nil { + t.Fatalf("cells: %v", err) + } + return resp, cells +} + +func TestPlannerViewshedResult(t *testing.T) { + h := newPlannerHarness(t) + ip := "198.51.100.120" + w := h.pollUntil(t, plannerViewshedResultPath, ip, http.StatusOK) + resp, cells := decodeViewshed(t, w) + radio, _ := (*LOSConfig)(nil).resolved() + site := geoPoint{30.11, -97.09} + want := PlannerViewshedParams{ + Site: geoPointJSON{Lat: site.Lat, Lon: site.Lon}, + AntennaM: defaultPlannerNewAntennaM, RxAntennaM: defaultPlannerExistAntenna, + RangeKm: plannerViewshedResultKm, FrequencyMHz: radio.FrequencyMHz, KFactor: radio.KFactor, + UserReach: PlannerViewshedUserReach{D50Km: defaultPlannerUserD50Km, Slope: defaultPlannerUserSlope}, + } + if resp.Params != want { + t.Fatalf("params %+v\nwant %+v", resp.Params, want) + } + // snake_case like the rest of the response, not the config's d50Km. + if wantJSON := `"user_reach":{"d50_km":2.7,"slope":0.3}`; !strings.Contains(w.Body.String(), wantJSON) { + t.Fatalf("body lacks %s", wantJSON) + } + if resp.Source != terrainDefaultSource || resp.Rows < 1 || resp.Cols < 1 || resp.Rows*resp.Cols != len(cells) { + t.Fatalf("source %q, %dx%d grid, %d cells", resp.Source, resp.Rows, resp.Cols, len(cells)) + } + bb := viewshedBBox(site, plannerViewshedResultKm) + if resp.BBox != [4]float64{bb.S, bb.W, bb.N, bb.E} || resp.CellKm != viewshedCellKm(plannerViewshedResultKm) { + t.Fatalf("bbox %v cell %g, want %+v", resp.BBox, resp.CellKm, bb) + } + if h.src.lastBBox() != bb { + t.Fatalf("view %+v, want %+v", h.src.lastBBox(), bb) + } + if !slices.ContainsFunc(cells, func(c byte) bool { return c != 0 }) { + t.Fatal("every cell is no data over full terrain") + } + // Repeaters only (no room, no hidden or blacklisted node), nearest first, + // each link at h → rx. + var keys []string + for _, l := range resp.Links { + keys = append(keys, l.PubKey) + } + if !slices.Equal(keys, []string{"aa01", "aa02"}) { + t.Fatalf("links %v, want [aa01 aa02]", keys) + } + lp := losParams{FreqMHz: radio.FrequencyMHz, KFactor: radio.KFactor} + hill := geoPoint{30.10, -97.10} + v := fakeTerrainView{bb: bb} + wantLink := relayLink(v, site, hill, geoDistKm(site, hill), lp, defaultPlannerNewAntennaM, defaultPlannerExistAntenna, false) + got := resp.Links[0] + if got.Name != "Hill" || got.Lat != hill.Lat || got.Lon != hill.Lon || got.Link.Verdict != wantLink.Verdict || + got.Link.DistanceKm != wantLink.DistanceKm || got.Link.ClearancePct != wantLink.ClearancePct { + t.Fatalf("link %+v\nwant %+v", got, wantLink) + } + if resp.Links[0].Link.DistanceKm >= resp.Links[1].Link.DistanceKm { + t.Fatalf("links not nearest first: %+v", resp.Links) + } + if !strings.Contains(w.Body.String(), `"warnings":[]`) { + t.Fatalf("warnings not []: %s", w.Body.String()[:200]) + } + if resp.Truncated { + t.Fatal("truncated with a handful of nodes") + } + + // range=10 drops Mesa (13 km); with no repeater in range links is []. + w = h.pollUntil(t, plannerViewshedPath+"&range=10&h=-1&rx=150", ip, http.StatusOK) + resp, _ = decodeViewshed(t, w) + if len(resp.Links) != 1 || resp.Links[0].PubKey != "aa01" || resp.Params.RangeKm != 10 || + resp.Params.AntennaM != plannerMinAntennaM || resp.Params.RxAntennaM != plannerMaxAntennaM { + t.Fatalf("range 10: params %+v links %+v", resp.Params, resp.Links) + } + h.data.setNodes(append(plannerTestNodes()[2:], nodeInfo{PublicKey: "cc09", Name: "Far phone", Role: "companion", + Lat: 30.11, Lon: -97.09, HasGPS: true})) + h.p.known.Store(nil) + w = h.pollUntil(t, plannerViewshedPath+"&range=10", ip, http.StatusOK) + if !strings.Contains(w.Body.String(), `"links":[]`) { + t.Fatalf("links not []: %s", w.Body.String()[:200]) + } +} + +func TestPlannerViewshedUsesHeavyCache(t *testing.T) { + h := newPlannerHarness(t) + ip := "198.51.100.121" + first := h.pollUntil(t, plannerViewshedPath+"&range=10", ip, http.StatusOK) + views := h.src.viewCount() + if h.p.covCache.len() != 1 || h.p.cheapCache.len() != 0 { + t.Fatalf("cov cache %d, cheap cache %d", h.p.covCache.len(), h.p.cheapCache.len()) + } + w := h.get(plannerViewshedPath+"&range=10", ip) + if w.Code != http.StatusOK || w.Body.String() != first.Body.String() || h.src.viewCount() != views { + t.Fatalf("second request: %d, views %d -> %d", w.Code, views, h.src.viewCount()) + } +} + +// A stale repeater in range gets no link, as Relay offers none. +func TestPlannerViewshedSkipsStale(t *testing.T) { + h := newPlannerHarness(t) + h.data.setNodes(append(plannerTestNodes(), nodeInfo{PublicKey: "aa09", Name: "Silent", Role: "repeater", + Lat: 30.115, Lon: -97.085, HasGPS: true})) + site := geoPoint{30.11, -97.09} + nodes, _ := h.p.snapshotNodes(viewshedBBox(site, 10), 0, h.clk.now()) + if i := slices.IndexFunc(nodes, func(n plannerNode) bool { return n.PubKey == "aa09" }); i < 0 || !nodes[i].Stale { + t.Fatalf("fixture: aa09 not selected as stale: %+v", nodes) + } + w := h.pollUntil(t, plannerViewshedPath+"&range=10", "198.51.100.122", http.StatusOK) + resp, _ := decodeViewshed(t, w) + if len(resp.Links) != 1 || resp.Links[0].PubKey != "aa01" { + t.Fatalf("links %+v, want only aa01", resp.Links) + } +} + +// More repeaters in the view than plannerMaxNodes: the farthest from the +// site are dropped and the response says so. +// The 300-node cap only drops nodes beyond the farthest kept one. When that +// one is already farther than range, nothing in range was lost: not truncated. +func TestPlannerViewshedTruncatedOnlyWhenInRangeLost(t *testing.T) { + h := newPlannerHarness(t) + ns := plannerTestNodes() + // Inside the square view of range=10 (north edge 30.1999) but ~12.8 km from + // the site, beyond the radius: 301 repeaters there overflow the cap. + for i := 0; i <= plannerMaxNodes; i++ { + ns = append(ns, nodeInfo{PublicKey: fmt.Sprintf("ee%04d", i), Name: "Corner", Role: "repeater", + Lat: 30.195 + float64(i)*0.00001, Lon: -97.0, HasGPS: true, LastSeen: plannerTestStart}) + } + h.data.setNodes(ns) + w := h.pollUntil(t, plannerViewshedPath+"&range=10", "198.51.100.123", http.StatusOK) + resp, _ := decodeViewshed(t, w) + if len(resp.Links) != 1 || resp.Links[0].PubKey != "aa01" { + t.Fatalf("links %+v, want only aa01", resp.Links) + } + if resp.Truncated { + t.Fatal("truncated set although only nodes beyond range were dropped") + } +} + +func TestViewshedTruncatedRule(t *testing.T) { + site := geoPoint{Lat: 30.11, Lon: -97.09} + near := plannerNode{PubKey: "n", Lat: 30.12, Lon: -97.09} + far := plannerNode{PubKey: "f", Lat: 30.30, Lon: -97.09} // ~21 km + cases := []struct { + name string + nodes []plannerNode + truncated bool + want bool + }{ + {"not capped", []plannerNode{near}, false, false}, + {"capped, farthest kept inside range", []plannerNode{near}, true, true}, + {"capped, farthest kept beyond range", []plannerNode{near, far}, true, false}, + } + for _, c := range cases { + if got := viewshedTruncated(site, c.nodes, 10, c.truncated); got != c.want { + t.Errorf("%s: got %v want %v", c.name, got, c.want) + } + } +} + +func TestPlannerViewshedLinksCarryNoElevProfile(t *testing.T) { + h := newPlannerHarness(t) + h.data.setNodes(plannerTestNodes()) + w := h.pollUntil(t, plannerViewshedResultPath, "198.51.100.123", http.StatusOK) + resp, _ := decodeViewshed(t, w) + if len(resp.Links) == 0 { + t.Fatal("no links") + } + for _, l := range resp.Links { + if l.Link.ElevM != nil { + t.Errorf("link %s carries a %d-sample elevation profile", l.PubKey, len(l.Link.ElevM)) + } + } + if strings.Contains(w.Body.String(), `"elev_m"`) { + t.Error("body contains elev_m") + } +} + +// A repeater at the site itself (within viewshedSelfKm) is the site, not a +// link: it is left out of the list. +func TestPlannerViewshedLinksSkipRepeaterAtSite(t *testing.T) { + h := newPlannerHarness(t) + ns := append(plannerTestNodes(), + nodeInfo{PublicKey: "ee0001", Name: "AtSite", Role: "repeater", Lat: 30.11, Lon: -97.09, HasGPS: true, LastSeen: plannerTestStart}, + nodeInfo{PublicKey: "ee0002", Name: "Near90m", Role: "repeater", Lat: 30.1108, Lon: -97.09, HasGPS: true, LastSeen: plannerTestStart}, + nodeInfo{PublicKey: "ee0003", Name: "At200m", Role: "repeater", Lat: 30.1118, Lon: -97.09, HasGPS: true, LastSeen: plannerTestStart}) + h.data.setNodes(ns) + w := h.pollUntil(t, plannerViewshedResultPath, "198.51.100.123", http.StatusOK) + resp, _ := decodeViewshed(t, w) + got := map[string]bool{} + for _, l := range resp.Links { + got[l.PubKey] = true + } + if got["ee0001"] || got["ee0002"] { + t.Errorf("repeater within %.1f km of the site listed as a link: %v", viewshedSelfKm, got) + } + if !got["ee0003"] { + t.Error("repeater 200 m from the site missing from links") + } +} + +func TestPlannerViewshedTruncated(t *testing.T) { + h := newPlannerHarness(t) + ns := plannerTestNodes() + for i := 0; i <= plannerMaxNodes; i++ { + ns = append(ns, nodeInfo{PublicKey: fmt.Sprintf("dd%04d", i), Name: "Row", Role: "repeater", + Lat: 30.112 + float64(i)*0.0001, Lon: -97.09, HasGPS: true, LastSeen: plannerTestStart}) + } + h.data.setNodes(ns) + w := h.pollUntil(t, plannerViewshedPath+"&range=10", "198.51.100.123", http.StatusOK) + resp, _ := decodeViewshed(t, w) + keys := make([]string, len(resp.Links)) + for i, l := range resp.Links { + keys[i] = l.PubKey + } + if !resp.Truncated || len(keys) == 0 || len(keys) > plannerMaxNodes { + t.Fatalf("truncated %v, %d links", resp.Truncated, len(keys)) + } + far := fmt.Sprintf("dd%04d", plannerMaxNodes) + if slices.Contains(keys, far) || !slices.Contains(keys, "dd0000") || !slices.Contains(keys, "aa01") { + t.Fatalf("kept the farthest (%s) or dropped a near one: %v", far, keys[:5]) + } +} diff --git a/cmd/server/planner_config.go b/cmd/server/planner_config.go new file mode 100644 index 000000000..7fb8510a2 --- /dev/null +++ b/cmd/server/planner_config.go @@ -0,0 +1,155 @@ +package main + +import ( + "fmt" + "log" +) + +func (c *PlannerConfig) enabled() bool { return c != nil && c.Enabled } + +// resolved applies defaults; invalid values fall back with a warning. +func (c *PlannerConfig) resolved() (PlannerConfig, []string) { + out := PlannerConfig{ + DefaultRangeKm: defaultPlannerRangeKm, + NewAntennaM: defaultPlannerNewAntennaM, + ExistingAntennaM: defaultPlannerExistAntenna, + MaxAreaKm: defaultPlannerMaxAreaKm, + NodeMarginKm: defaultPlannerNodeMarginKm, + MaxLegKm: defaultPlannerMaxLegKm, + UserReach: &PlannerUserReach{D50Km: defaultPlannerUserD50Km, Slope: defaultPlannerUserSlope}, + } + if c == nil { + return out, nil + } + var warns []string + out.Enabled = c.Enabled + if c.DefaultRangeKm != 0 { + if plannerRangeAllowed(c.DefaultRangeKm) { + out.DefaultRangeKm = c.DefaultRangeKm + } else { + warns = append(warns, "planner.defaultRangeKm must be one of 10,15,20,30,40,50,60; using the default") + } + } + if c.NewAntennaM != 0 { + if c.NewAntennaM > 0 && c.NewAntennaM <= 100 { + out.NewAntennaM = c.NewAntennaM + } else { + warns = append(warns, "planner.newAntennaM must be within 0-100; using the default") + } + } + if c.ExistingAntennaM != 0 { + if c.ExistingAntennaM > 0 && c.ExistingAntennaM <= 100 { + out.ExistingAntennaM = c.ExistingAntennaM + } else { + warns = append(warns, "planner.existingAntennaM must be within 0-100; using the default") + } + } + out.MaxAreaKm = plannerSizeKm("maxAreaKm", c.MaxAreaKm, defaultPlannerMaxAreaKm, plannerAreaKmMin, plannerAreaKmMax, &warns) + out.NodeMarginKm = plannerSizeKm("nodeMarginKm", c.NodeMarginKm, defaultPlannerNodeMarginKm, + plannerMarginKmMin, plannerMarginKmMax, &warns) + out.MaxLegKm = plannerSizeKm("maxLegKm", c.MaxLegKm, defaultPlannerMaxLegKm, plannerLegKmMin, plannerLegKmMax, &warns) + if u := c.UserReach; u != nil { + out.UserReach.D50Km = plannerSizeKm("userReach.d50Km", u.D50Km, defaultPlannerUserD50Km, + plannerUserD50KmMin, plannerUserD50KmMax, &warns) + out.UserReach.Slope = plannerSizeKm("userReach.slope", u.Slope, defaultPlannerUserSlope, + plannerUserSlopeMin, plannerUserSlopeMax, &warns) + } + // No range above the leg limit is offered, so the default cannot be one. + if out.DefaultRangeKm > out.MaxLegKm { + r := out.rangesKm() + warns = append(warns, fmt.Sprintf("planner.defaultRangeKm %g is over planner.maxLegKm %g; using %g", + out.DefaultRangeKm, out.MaxLegKm, r[len(r)-1])) + out.DefaultRangeKm = r[len(r)-1] + } + return out, warns +} + +// plannerSizeKm resolves one size limit: v when it lies within lo-hi, def +// when it is unset (0), and def with a warning otherwise (NaN included). +func plannerSizeKm(name string, v, def, lo, hi float64, warns *[]string) float64 { + switch { + case v == 0: + return def + case v >= lo && v <= hi: + return v + } + *warns = append(*warns, fmt.Sprintf("planner.%s must be within %g-%g; using the default", name, lo, hi)) + return def +} + +// rangesKm is the range values resolved c accepts and offers: those of +// plannerRangesKm up to MaxLegKm, since a relay leg is never longer than the +// A→B leg. The smallest range equals the smallest MaxLegKm, so it is never +// empty. +func (c PlannerConfig) rangesKm() []float64 { + n := 0 + for n < len(plannerRangesKm) && plannerRangesKm[n] <= c.MaxLegKm { + n++ + } + return plannerRangesKm[:n:n] +} + +// tileLimits is the per-endpoint terrain tile caps for c's size limits. A +// size that is 0 counts as its default, as in resolved(). +func (c PlannerConfig) tileLimits() plannerTileLimits { + or := func(v, def float64) float64 { + if v == 0 { + return def + } + return v + } + return plannerTileCaps(or(c.MaxAreaKm, defaultPlannerMaxAreaKm), or(c.NodeMarginKm, defaultPlannerNodeMarginKm), + or(c.MaxLegKm, defaultPlannerMaxLegKm)) +} + +func plannerRangeAllowed(km float64) bool { + for _, r := range plannerRangesKm { + if r == km { + return true + } + } + return false +} + +// clientConfig is /api/config/client "planner"; nil when disabled. Radio +// defaults come from the los block (frequency, k) so both tools agree. +func (c *PlannerConfig) clientConfig(los *LOSConfig) *PlannerClientConfig { + if !c.enabled() { + return nil + } + r, _ := c.resolved() + l, _ := los.resolved() + return &PlannerClientConfig{ + DefaultRangeKm: r.DefaultRangeKm, + RangesKm: r.rangesKm(), + NewAntennaM: r.NewAntennaM, + ExistingAntennaM: r.ExistingAntennaM, + FrequencyMHz: l.FrequencyMHz, + KFactor: l.KFactor, + MaxPoints: plannerMaxPoints, + MaxLegKm: r.MaxLegKm, + MaxAreaKm: r.MaxAreaKm, + NodeMarginKm: r.NodeMarginKm, + MaxSites: plannerMaxSites, + MinClearance: plannerMinClearance, + UserReach: *r.UserReach, + } +} + +func logPlannerConfig(c *PlannerConfig) { + if !c.enabled() { + return + } + r, warns := c.resolved() + for _, w := range warns { + log.Printf("[planner] %s", w) + } + lim := r.tileLimits() + log.Printf("[planner] enabled (range=%.0f km, new=%.0f m, existing=%.0f m, "+ + "maxArea=%g km, nodeMargin=%g km, maxLeg=%g km, userReach d50=%g km slope=%g)", + r.DefaultRangeKm, r.NewAntennaM, r.ExistingAntennaM, r.MaxAreaKm, r.NodeMarginKm, r.MaxLegKm, + r.UserReach.D50Km, r.UserReach.Slope) + log.Printf("[planner] terrain tiles per request: coverage %d, relay %d, profile %d, viewshed %d; "+ + "one view takes up to %.0f MB (%.1f MB a tile)", + lim.Coverage, lim.Relay, lim.Profile, lim.Viewshed, float64(lim.max())*srtmTileBytes/1e6, float64(srtmTileBytes)/1e6) +} diff --git a/cmd/server/planner_config_test.go b/cmd/server/planner_config_test.go new file mode 100644 index 000000000..053e9f877 --- /dev/null +++ b/cmd/server/planner_config_test.go @@ -0,0 +1,262 @@ +package main + +import ( + "bytes" + "encoding/json" + "log" + "math" + "net/http" + "slices" + "strings" + "testing" +) + +func TestPlannerConfigSizes(t *testing.T) { + // Unset: the defaults, no warning. + for _, c := range []*PlannerConfig{nil, {}, {Enabled: true}} { + r, warns := c.resolved() + if r.MaxAreaKm != 100 || r.NodeMarginKm != 30 || r.MaxLegKm != 100 || len(warns) != 0 { + t.Fatalf("%+v: resolved %+v, warnings %q", c, r, warns) + } + } + // Each end of each range is kept. + for _, c := range []PlannerConfig{ + {MaxAreaKm: 20, NodeMarginKm: 10, MaxLegKm: 10, DefaultRangeKm: 10}, + {MaxAreaKm: 250, NodeMarginKm: 60, MaxLegKm: 200}, + {MaxAreaKm: 137.5, NodeMarginKm: 12.5, MaxLegKm: 64}, + } { + r, warns := c.resolved() + if r.MaxAreaKm != c.MaxAreaKm || r.NodeMarginKm != c.NodeMarginKm || r.MaxLegKm != c.MaxLegKm || len(warns) != 0 { + t.Fatalf("%+v: resolved %+v, warnings %q", c, r, warns) + } + } + // Out of range (NaN included): the default and one warning each. + for _, c := range []struct { + cfg PlannerConfig + warn string + }{ + {PlannerConfig{MaxAreaKm: 19.9}, "planner.maxAreaKm must be within 20-250; using the default"}, + {PlannerConfig{MaxAreaKm: 251}, "planner.maxAreaKm must be within 20-250; using the default"}, + {PlannerConfig{MaxAreaKm: -100}, "planner.maxAreaKm must be within 20-250; using the default"}, + {PlannerConfig{MaxAreaKm: math.NaN()}, "planner.maxAreaKm must be within 20-250; using the default"}, + {PlannerConfig{NodeMarginKm: 9.5}, "planner.nodeMarginKm must be within 10-60; using the default"}, + {PlannerConfig{NodeMarginKm: 61}, "planner.nodeMarginKm must be within 10-60; using the default"}, + {PlannerConfig{MaxLegKm: 9}, "planner.maxLegKm must be within 10-200; using the default"}, + {PlannerConfig{MaxLegKm: 200.5}, "planner.maxLegKm must be within 10-200; using the default"}, + {PlannerConfig{MaxLegKm: math.Inf(1)}, "planner.maxLegKm must be within 10-200; using the default"}, + } { + r, warns := c.cfg.resolved() + if r.MaxAreaKm != 100 || r.NodeMarginKm != 30 || r.MaxLegKm != 100 || !slices.Equal(warns, []string{c.warn}) { + t.Errorf("%+v: resolved %+v, warnings %q", c.cfg, r, warns) + } + } +} + +func TestPlannerConfigRangesFollowMaxLeg(t *testing.T) { + for _, c := range []struct { + maxLeg float64 + want []float64 + }{ + {100, []float64{10, 15, 20, 30, 40, 50, 60}}, + {60, []float64{10, 15, 20, 30, 40, 50, 60}}, + {45, []float64{10, 15, 20, 30, 40}}, + {10, []float64{10}}, + } { + r, _ := (&PlannerConfig{MaxLegKm: c.maxLeg}).resolved() + if got := r.rangesKm(); !slices.Equal(got, c.want) { + t.Errorf("maxLegKm %v: ranges %v, want %v", c.maxLeg, got, c.want) + } + } + // The returned slice cannot grow into the shared list. + r, _ := (&PlannerConfig{MaxLegKm: 25}).resolved() + _ = append(r.rangesKm(), 999) + if plannerRangesKm[3] != 30 { + t.Fatal("append through rangesKm overwrote plannerRangesKm") + } + + // A default range over maxLegKm becomes the largest allowed one. + for _, c := range []struct { + cfg PlannerConfig + wantRange float64 + warn string + }{ + {PlannerConfig{MaxLegKm: 25}, 20, "planner.defaultRangeKm 30 is over planner.maxLegKm 25; using 20"}, + {PlannerConfig{MaxLegKm: 10, DefaultRangeKm: 60}, 10, "planner.defaultRangeKm 60 is over planner.maxLegKm 10; using 10"}, + } { + r, warns := c.cfg.resolved() + if r.DefaultRangeKm != c.wantRange || !slices.Equal(warns, []string{c.warn}) { + t.Errorf("%+v: range %v, warnings %q", c.cfg, r.DefaultRangeKm, warns) + } + // Resolving again is stable and quiet. + r2, warns := r.resolved() + same := *r2.UserReach == *r.UserReach // pointers differ, values must not + r2.UserReach, r.UserReach = nil, nil + if r2 != r || !same || len(warns) != 0 { + t.Errorf("%+v: re-resolved %+v, warnings %q", c.cfg, r2, warns) + } + } + if r, warns := (&PlannerConfig{MaxLegKm: 40, DefaultRangeKm: 40}).resolved(); r.DefaultRangeKm != 40 || len(warns) != 0 { + t.Errorf("range equal to maxLegKm: %v, %q", r.DefaultRangeKm, warns) + } +} + +func TestPlannerConfigJSONAndClient(t *testing.T) { + var cfg Config + raw := `{"planner":{"enabled":true,"maxAreaKm":180,"nodeMarginKm":45,"maxLegKm":35}}` + if err := json.Unmarshal([]byte(raw), &cfg); err != nil { + t.Fatal(err) + } + if p := cfg.Planner; p.MaxAreaKm != 180 || p.NodeMarginKm != 45 || p.MaxLegKm != 35 { + t.Fatalf("decoded %+v", p) + } + cc := cfg.Planner.clientConfig(nil) + if cc.MaxAreaKm != 180 || cc.NodeMarginKm != 45 || cc.MaxLegKm != 35 || cc.DefaultRangeKm != 30 || + !slices.Equal(cc.RangesKm, []float64{10, 15, 20, 30}) { + t.Fatalf("client config %+v", cc) + } + b, _ := json.Marshal(cc) + for _, k := range []string{`"maxAreaKm":180`, `"nodeMarginKm":45`, `"maxLegKm":35`, `"rangesKm":[10,15,20,30]`} { + if !strings.Contains(string(b), k) { + t.Fatalf("client JSON %s lacks %s", b, k) + } + } + // Defaults. + cc = (&PlannerConfig{Enabled: true}).clientConfig(nil) + if cc.MaxAreaKm != 100 || cc.NodeMarginKm != 30 || cc.MaxLegKm != 100 || len(cc.RangesKm) != len(plannerRangesKm) { + t.Fatalf("default client config %+v", cc) + } +} + +func TestPlannerConfigLogSizes(t *testing.T) { + var buf bytes.Buffer + prev, flags := log.Writer(), log.Flags() + log.SetOutput(&buf) + t.Cleanup(func() { log.SetOutput(prev); log.SetFlags(flags) }) + logPlannerConfig(&PlannerConfig{Enabled: true, MaxAreaKm: 200, NodeMarginKm: 50, MaxLegKm: 150}) + out := buf.String() + for _, want := range []string{ + "maxArea=200 km, nodeMargin=50 km, maxLeg=150 km", + "terrain tiles per request: coverage 28, relay 24, profile 24", + "one view takes up to 81 MB (2.9 MB a tile)", + } { + if !strings.Contains(out, want) { + t.Errorf("log lacks %q:\n%s", want, out) + } + } +} + +// The handlers apply the operator's sizes: the box limit, the node margin +// (view, fingerprint and node selection), the leg limit and its ranges. +func TestPlannerAPIConfiguredSizes(t *testing.T) { + const ip = "198.51.100.210" + // About 145 × 144 km around the test cluster. + const big = "/api/planner/coverage?bbox=29.5,-97.8,30.8,-96.3" + h := newPlannerHarness(t) + if w := h.get(big, ip); w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), plannerErrAreaTooLarge) { + t.Fatalf("default size: %d %s", w.Code, w.Body.String()) + } + + h = newPlannerHarnessWith(t, PlannerConfig{Enabled: true, MaxAreaKm: 200, NodeMarginKm: 50}) + // A repeater 40 km north of the box: inside a 50 km margin, not a 30 km one. + h.data.setNodes(append(plannerTestNodes(), nodeInfo{PublicKey: "aa09", Name: "Ridge", Role: "repeater", + Lat: 30.8 + 40/plannerKmPerDeg, Lon: -97.0, HasGPS: true, LastSeen: plannerTestStart})) + if w := h.get(big, ip); w.Code != http.StatusAccepted && w.Code != http.StatusOK { + t.Fatalf("maxAreaKm 200: %d %s", w.Code, w.Body.String()) + } + h.waitEntered(t) + area := geoBBox{S: 29.5, W: -97.8, N: 30.8, E: -96.3} + if v := h.src.lastBBox(); v != plannerExpandBBox(area, 50) { + t.Fatalf("view %+v, want the box plus 50 km", v) + } + h.stubs.mu.Lock() + plan := h.stubs.lastPlan + h.stubs.mu.Unlock() + if !slices.ContainsFunc(plan.Nodes, func(n plannerNode) bool { return n.PubKey == "aa09" && !n.InArea }) { + t.Fatalf("plan nodes %+v lack the margin repeater", plan.Nodes) + } + + // maxLegKm: a 120 km leg is too long by default and allowed at 150. + const relay120 = "/api/planner/relay?a=30.1,-97.1&b=31.18,-97.1" + const prof120 = "/api/planner/profile?pts=30.1,-97.1,31.18,-97.1" + h = newPlannerHarness(t) + if w := h.get(relay120, ip); w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), plannerErrTooLong) { + t.Fatalf("default relay 120 km: %d %s", w.Code, w.Body.String()) + } + if w := h.get(prof120, ip); w.Code != http.StatusOK || !strings.Contains(w.Body.String(), plannerErrTooLong) { + t.Fatalf("default profile 120 km: %d %s", w.Code, w.Body.String()) + } + h = newPlannerHarnessWith(t, PlannerConfig{Enabled: true, MaxLegKm: 150}) + h.p.fastWait = plannerFastWait + if w := h.get(relay120, ip); w.Code != http.StatusOK { + t.Fatalf("maxLegKm 150 relay: %d %s", w.Code, w.Body.String()) + } + w := h.get(prof120, ip) + var prof PlannerProfileResponse + if err := json.Unmarshal(w.Body.Bytes(), &prof); err != nil || w.Code != http.StatusOK || + len(prof.Legs) != 1 || prof.Legs[0].Error != "" || len(prof.Legs[0].ElevM) == 0 { + t.Fatalf("maxLegKm 150 profile: %d %s", w.Code, w.Body.String()) + } + if v, want := h.src.lastBBox(), plannerProfileView(geoBBox{30.1, -97.1, 31.18, -97.1}, plannerProfilePad(150)); v != want { + t.Fatalf("profile view %+v, want %+v", v, want) + } + + // Ranges above maxLegKm are refused, and the default follows them. + h = newPlannerHarnessWith(t, PlannerConfig{Enabled: true, MaxLegKm: 25}) + h.p.fastWait = plannerFastWait + for _, path := range []string{plannerRelayPath + "&range=30", plannerCovPath + "&range=30"} { + if w := h.get(path, ip); w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), "range must be one of 10,15,20\"") { + t.Fatalf("%s: %d %s", path, w.Code, w.Body.String()) + } + } + if w := h.get(plannerRelayPath+"&range=20", ip); w.Code != http.StatusOK { + t.Fatalf("range 20: %d %s", w.Code, w.Body.String()) + } + if w := h.get(plannerRelayPath, ip); w.Code != http.StatusOK { + t.Fatalf("default range: %d %s", w.Code, w.Body.String()) + } + h.stubs.mu.Lock() + rangeKm := h.stubs.lastRelay.RangeKm + h.stubs.mu.Unlock() + if rangeKm != 20 { + t.Fatalf("default range %v, want 20", rangeKm) + } +} + +func TestPlannerUserReachDefaults(t *testing.T) { + for _, c := range []*PlannerConfig{nil, {}, {Enabled: true}} { + r, warns := c.resolved() + if r.UserReach == nil || *r.UserReach != (PlannerUserReach{D50Km: 2.7, Slope: 0.30}) || len(warns) != 0 { + t.Fatalf("%+v: resolved %+v, warnings %q", c, r.UserReach, warns) + } + } + r, warns := (&PlannerConfig{Enabled: true, UserReach: &PlannerUserReach{D50Km: 0.2, Slope: 2}}).resolved() + if *r.UserReach != (PlannerUserReach{D50Km: 0.2, Slope: 2}) || len(warns) != 0 { + t.Fatalf("range ends: resolved %+v, warnings %q", r.UserReach, warns) + } +} + +func TestPlannerUserReachOutOfRange(t *testing.T) { + for _, c := range []struct { + in PlannerUserReach + want PlannerUserReach + warn string + }{ + {PlannerUserReach{D50Km: 0.1, Slope: 0.4}, PlannerUserReach{D50Km: 2.7, Slope: 0.4}, "planner.userReach.d50Km"}, + {PlannerUserReach{D50Km: 3, Slope: 5}, PlannerUserReach{D50Km: 3, Slope: 0.30}, "planner.userReach.slope"}, + } { + r, warns := (&PlannerConfig{Enabled: true, UserReach: &c.in}).resolved() + if *r.UserReach != c.want || len(warns) != 1 || !strings.Contains(warns[0], c.warn) { + t.Errorf("%+v: resolved %+v, warnings %q", c.in, r.UserReach, warns) + } + } +} + +func TestPlannerClientConfigUserReach(t *testing.T) { + cc := (&PlannerConfig{Enabled: true, UserReach: &PlannerUserReach{D50Km: 4, Slope: 0.5}}).clientConfig(nil) + if cc.UserReach != (PlannerUserReach{D50Km: 4, Slope: 0.5}) { + t.Fatalf("client config %+v", cc.UserReach) + } + if cc := (&PlannerConfig{Enabled: true}).clientConfig(nil); cc.UserReach != (PlannerUserReach{D50Km: 2.7, Slope: 0.30}) { + t.Fatalf("default client config %+v", cc.UserReach) + } +} diff --git a/cmd/server/planner_graph.go b/cmd/server/planner_graph.go new file mode 100644 index 000000000..622012be6 --- /dev/null +++ b/cmd/server/planner_graph.go @@ -0,0 +1,495 @@ +package main + +// Backbone graph for the planner: which repeaters count, which observed RF +// links are trustworthy, and the connectivity objective the greedy site +// search optimises (components, articulation points, fragility). + +import ( + "cmp" + "math" + "slices" + "strings" + "time" +) + +// plannerNode is a repeater/room with GPS considered by a plan. +type plannerNode struct { + PubKey, Name, Role string + Lat, Lon float64 + Stale bool // no certain activity within the role's silent window + InArea bool // inside the (snapped) bbox, not just the margin +} + +// plannerEdge: A/B index the plannerNode slice. Class: observed | solid | marginal. +type plannerEdge struct { + A, B int + Class string + DistanceKm float64 + ClearancePct float64 +} + +// plannerNodeFilter carries the same filters /api/nodes applies. +type plannerNodeFilter struct { + // Visible is /api/nodes' hiding rule for one node (node_visibility.go); + // nil hides nothing. + Visible func(n *nodeInfo) bool + SilentAfter func(role string) time.Duration +} + +// plannerKmPerDeg is one degree of latitude on haversineKm's sphere. +const plannerKmPerDeg = earthRadiusKm * math.Pi / 180 + +// selectPlannerNodes picks repeaters/rooms with GPS (not 0,0) that f.Visible +// keeps, inside area expanded by marginKm, capped at +// plannerMaxNodes (in-area first, then nearest the centre). Stale is set from +// max(LastSeen, lastHeard[pk]) vs SilentAfter(role). A nil Visible hides +// nothing; a nil SilentAfter marks nothing stale. A pubkey listed twice +// (case-insensitively) is kept once, so pubkeys identify nodes downstream. +// Output: in-area first, then by pubkey. +func selectPlannerNodes(all []nodeInfo, lastHeard map[string]time.Time, area geoBBox, marginKm float64, + f plannerNodeFilter, now time.Time) (nodes []plannerNode, truncated bool) { + outer := plannerExpandBBox(area, marginKm) + type candidate struct { + node plannerNode + distKm float64 // to the area centre; filled only when capping + } + var cands []candidate + seen := make(map[string]struct{}) + for i := range all { + ni := &all[i] + if ni.Role != "repeater" && ni.Role != "room" { + continue + } + if !ni.HasGPS || !plannerFiniteCoord(ni.Lat, ni.Lon) || (ni.Lat == 0 && ni.Lon == 0) { + continue + } + if f.Visible != nil && !f.Visible(ni) { + continue + } + if !plannerBBoxContains(outer, ni.Lat, ni.Lon) { + continue + } + key := strings.ToLower(ni.PublicKey) + if key == "" { + continue + } + if _, dup := seen[key]; dup { + continue + } + seen[key] = struct{}{} + cands = append(cands, candidate{node: plannerNode{ + PubKey: ni.PublicKey, Name: ni.Name, Role: ni.Role, + Lat: ni.Lat, Lon: ni.Lon, + Stale: plannerNodeStale(ni, lastHeard[ni.PublicKey], f.SilentAfter, now), + InArea: plannerBBoxContains(area, ni.Lat, ni.Lon), + }}) + } + if len(cands) > plannerMaxNodes { + cLat, cLon := (area.S+area.N)/2, (area.W+area.E)/2 + for i := range cands { + cands[i].distKm = haversineKm(cLat, cLon, cands[i].node.Lat, cands[i].node.Lon) + } + slices.SortFunc(cands, func(a, b candidate) int { + if a.node.InArea != b.node.InArea { + if a.node.InArea { + return -1 + } + return 1 + } + if c := cmp.Compare(a.distKm, b.distKm); c != 0 { + return c + } + return strings.Compare(a.node.PubKey, b.node.PubKey) + }) + cands = cands[:plannerMaxNodes] + truncated = true + } + nodes = make([]plannerNode, len(cands)) + for i := range cands { + nodes[i] = cands[i].node + } + slices.SortFunc(nodes, func(a, b plannerNode) int { + if a.InArea != b.InArea { + if a.InArea { + return -1 + } + return 1 + } + return strings.Compare(a.PubKey, b.PubKey) + }) + return nodes, truncated +} + +func plannerFiniteCoord(lat, lon float64) bool { + return !math.IsNaN(lat) && !math.IsInf(lat, 0) && !math.IsNaN(lon) && !math.IsInf(lon, 0) +} + +// plannerNodeStale: liveness is the newer of the DB last_seen and the +// certain last heard (AGENTS.md "last_heard vs last_seen"). Never seen at all +// means stale: now.Sub(zero time) saturates at the maximum Duration. +func plannerNodeStale(ni *nodeInfo, heard time.Time, silentAfter func(role string) time.Duration, now time.Time) bool { + if silentAfter == nil { + return false + } + last := ni.LastSeen + if heard.After(last) { + last = heard + } + return now.Sub(last) > silentAfter(ni.Role) +} + +// plannerExpandBBox grows b by km on every side. Longitude degrees shrink +// with cos(lat); the expanded box's highest |lat| is used so the east/west +// margin is at least km at every latitude in the box (slightly more nearer +// the equator). A box reaching a pole spans every longitude. +func plannerExpandBBox(b geoBBox, km float64) geoBBox { + if !(km > 0) { + return b + } + dLat := km / plannerKmPerDeg + s, n := math.Max(b.S-dLat, -90), math.Min(b.N+dLat, 90) + cosLat := math.Cos(math.Max(math.Abs(s), math.Abs(n)) * math.Pi / 180) + if cosLat < 1e-9 { + return geoBBox{S: s, W: -180, N: n, E: 180} + } + dLon := km / (plannerKmPerDeg * cosLat) + if dLon >= 180 { + return geoBBox{S: s, W: -180, N: n, E: 180} + } + return geoBBox{S: s, W: b.W - dLon, N: n, E: b.E + dLon} +} + +// plannerBBoxContains is inclusive on every edge. lon is also tried ±360 so +// an expanded box that runs past ±180 still catches nodes on the far side +// of the antimeridian. +func plannerBBoxContains(b geoBBox, lat, lon float64) bool { + if lat < b.S || lat > b.N { + return false + } + for _, l := range [3]float64{lon, lon + 360, lon - 360} { + if l >= b.W && l <= b.E { + return true + } + } + return false +} + +// observedPlannerEdges turns observed neighbor edges into Class "observed" +// edges between nodes (rules: non-ambiguous, not 1-byte-only evidence, +// Score*Confidence ≥ minScore). Endpoints match nodes by full pubkey +// (case-insensitive; the neighbor graph lower-cases its keys). (A,B) and +// (B,A) collapse into one edge. Output has A < B, sorted by (A, B). +// DistanceKm is the great-circle distance; ClearancePct is 0 because observed +// edges are not terrain-checked. +func observedPlannerEdges(nodes []plannerNode, edges []NeighborEdge, now time.Time, minScore float64) []plannerEdge { + index := make(map[string]int, len(nodes)) + for i := range nodes { + k := strings.ToLower(nodes[i].PubKey) + if _, dup := index[k]; !dup { + index[k] = i + } + } + seen := make(map[[2]int]struct{}) + var out []plannerEdge + for i := range edges { + e := &edges[i] + if e.Ambiguous || e.NodeB == "" || !plannerEdgeEvidenceOK(e) { + continue + } + a, okA := index[strings.ToLower(e.NodeA)] + b, okB := index[strings.ToLower(e.NodeB)] + if !okA || !okB || a == b { + continue + } + if !(e.Score(now)*e.Confidence() >= minScore) { + continue + } + if a > b { + a, b = b, a + } + if _, dup := seen[[2]int{a, b}]; dup { + continue + } + seen[[2]int{a, b}] = struct{}{} + out = append(out, plannerEdge{ + A: a, B: b, Class: "observed", + DistanceKm: haversineKm(nodes[a].Lat, nodes[a].Lon, nodes[b].Lat, nodes[b].Lon), + }) + } + slices.SortFunc(out, func(x, y plannerEdge) int { + if c := cmp.Compare(x.A, y.A); c != 0 { + return c + } + return cmp.Compare(x.B, y.B) + }) + return out +} + +// plannerEdgeEvidenceOK rejects edges whose only per-mode evidence is 1-byte +// hop prefixes, which collide ~8-way across a mesh (CountsByMode doc in +// neighbor_graph.go). 2- and 3-byte sightings are evidence. An edge with no +// per-mode tally or only the legacy bucket 0 (persisted snapshot counts) +// is accepted when it is resolved or was never ambiguous. Legacy counts +// mixed with 1-byte sightings and nothing longer are not "legacy-only", so +// that edge is rejected. +func plannerEdgeEvidenceOK(e *NeighborEdge) bool { + if e.CountsByMode[2]+e.CountsByMode[3] > 0 { + return true + } + return e.CountsByMode[1] <= 0 && (e.Resolved || !e.Ambiguous) +} + +// backboneGraph is an undirected graph over the active plannerNode indices +// plus any extra (site) vertices appended after them. Invariants: len(active) +// == len(adj) == n; adj holds only active vertices, never v itself, and no +// neighbour twice. Stats and Clone only read g, so they may run concurrently; +// AddVertex must not. +type backboneGraph struct { + n int + active []bool + adj [][]int +} + +// newBackboneGraph: vertices 0..n-1; active[i]=false removes vertex i +// (e.g. stale nodes when stale=0). active == nil means all active; indices +// past len(active) are active too. Edges touching an inactive or +// out-of-range vertex, self-loops and parallel edges are dropped. +func newBackboneGraph(n int, active []bool, edges []plannerEdge) *backboneGraph { + n = max(n, 0) + act := make([]bool, n, n+1) + for i := range act { + act[i] = i >= len(active) || active[i] + } + pairs := make([]uint64, 0, len(edges)) + for _, e := range edges { + a, b := e.A, e.B + if a == b || a < 0 || b < 0 || a >= n || b >= n || !act[a] || !act[b] { + continue + } + if a > b { + a, b = b, a + } + pairs = append(pairs, uint64(a)<<32|uint64(b)) + } + slices.Sort(pairs) + pairs = slices.Compact(pairs) + deg := make([]int, n) + for _, p := range pairs { + deg[p>>32]++ + deg[uint32(p)]++ + } + // One backing array; each list is capped at its degree so a later + // AddVertex append reallocates instead of overwriting the next list. + flat := make([]int, 2*len(pairs)) + adj := make([][]int, n, n+1) + off := 0 + for v := range adj { + adj[v] = flat[off : off : off+deg[v]] + off += deg[v] + } + for _, p := range pairs { + a, b := int(p>>32), int(uint32(p)) + adj[a] = append(adj[a], b) + adj[b] = append(adj[b], a) + } + return &backboneGraph{n: n, active: act, adj: adj} +} + +// AddVertex appends a vertex (a candidate site) linked to peers; returns its index. +// Peers that are inactive, out of range or repeated are ignored. +func (g *backboneGraph) AddVertex(peers []int) int { + v := g.n + nb := make([]int, 0, len(peers)) + for _, p := range peers { + if p >= 0 && p < v && g.active[p] { + nb = append(nb, p) + } + } + slices.Sort(nb) + nb = slices.Compact(nb) + for _, p := range nb { + g.adj[p] = append(g.adj[p], v) + } + g.adj = append(g.adj, nb) + g.active = append(g.active, true) + g.n++ + return v +} + +// Clone returns an independent copy (greedy evaluates candidates on copies). +func (g *backboneGraph) Clone() *backboneGraph { + total := 0 + for _, nb := range g.adj { + total += len(nb) + } + flat := make([]int, total) + adj := make([][]int, len(g.adj), len(g.adj)+1) + off := 0 + for v, nb := range g.adj { + copy(flat[off:], nb) + adj[v] = flat[off : off+len(nb) : off+len(nb)] + off += len(nb) + } + act := make([]bool, len(g.active), len(g.active)+1) + copy(act, g.active) + return &backboneGraph{n: g.n, active: act, adj: adj} +} + +// backboneStats is the objective state of a graph. +// - Components: components containing ≥ 1 counted vertex (isolated counted +// vertices are components); Largest = counted vertices in the largest. +// - CutVertices: articulation points that are counted vertices. +// - Fragility: Σ over articulation points v of (|C(v)| − 1 − size of the +// largest part left when v is removed): nodes cut off from the main part +// if v fails. +// - ComponentOf: component id per vertex (−1 inactive); ids ordered by +// counted size descending, so 0 is the largest. +type backboneStats struct { + Components, Largest, Isolated, CutVertices, Fragility int + ComponentOf []int +} + +// Stats computes backboneStats; counted(i) says whether vertex i counts +// (in-area nodes; margin nodes carry connectivity but are not counted). +// counted is asked only about active vertices; nil counts every vertex. +// +// Sizes are counted sizes throughout: Fragility sums, over every +// articulation point v (counted or not), counted(C(v)) − counted(v) − the +// largest counted part left when v is removed. Ties in ComponentOf order go +// to the component with the smallest vertex index; components with no +// counted vertex get the ids after Components. +// +// One iterative Tarjan pass, O(V+E), no recursion. The parts of v come from +// the same pass: a DFS child c with low[c] ≥ disc[v] is cut off with its +// subtree; for the root every child is, and a non-root keeps one more part, +// the rest of the component (its ancestors plus the child subtrees with a +// back edge above v). +func (g *backboneGraph) Stats(counted func(i int) bool) backboneStats { + n := g.n + st := backboneStats{ComponentOf: make([]int, n)} + if n == 0 { + return st + } + slab := make([]int32, 11*n) + disc := slab[0*n : 1*n] // DFS discovery time; 0 = unvisited + low := slab[1*n : 2*n] + parent := slab[2*n : 3*n] // −1 for a DFS root + next := slab[3*n : 4*n] // next adjacency index to scan + sub := slab[4*n : 5*n] // counted vertices in the DFS subtree + sepN := slab[5*n : 6*n] // children cut off when v is removed + sepSum := slab[6*n : 7*n] // their counted subtree sizes, summed + sepMax := slab[7*n : 8*n] // and the largest + cnt := slab[8*n : 9*n] // 1 if counted + stack := slab[9*n : 10*n] + compCnt := slab[10*n : 11*n] // counted size per discovery-order component + comp := st.ComponentOf // discovery-order id, remapped at the end + + for v := 0; v < n; v++ { + comp[v] = -1 + if g.active[v] && (counted == nil || counted(v)) { + cnt[v] = 1 + } + } + + var clock int32 + nComp := 0 + for r := 0; r < n; r++ { + if !g.active[r] || disc[r] != 0 { + continue + } + id := nComp + nComp++ + clock++ + disc[r], low[r], parent[r], sub[r] = clock, clock, -1, cnt[r] + comp[r] = id + stack[0] = int32(r) + sp := 1 + for sp > 0 { + v := stack[sp-1] + if nb := g.adj[v]; int(next[v]) < len(nb) { + w := nb[next[v]] + next[v]++ + if disc[w] == 0 { + clock++ + disc[w], low[w], parent[w], sub[w] = clock, clock, v, cnt[w] + comp[w] = id + stack[sp] = int32(w) + sp++ + } else if int32(w) != parent[v] && disc[w] < low[v] { + // The usual tree-edge skip. The articulation test below + // (low ≥ disc) holds either way; only bridges need it. + low[v] = disc[w] + } + continue + } + sp-- + if p := parent[v]; p >= 0 { + // Not the min builtin: routes_test.go declares a package + // min(int, int) that shadows it in test builds. + if low[v] < low[p] { + low[p] = low[v] + } + sub[p] += sub[v] + if low[v] >= disc[p] { + sepN[p]++ + sepSum[p] += sub[v] + sepMax[p] = max(sepMax[p], sub[v]) + } + } + } + compCnt[id] = sub[r] + } + + for v := 0; v < n; v++ { + if comp[v] < 0 { + continue + } + if cnt[v] == 1 && len(g.adj[v]) == 0 { + st.Isolated++ + } + isRoot := parent[v] < 0 + if sepN[v] < 1 || (isRoot && sepN[v] < 2) { + continue // not an articulation point + } + if cnt[v] == 1 { + st.CutVertices++ + } + total := compCnt[comp[v]] + rest := total - cnt[v] - sepSum[v] // 0 for a root + st.Fragility += int(total - cnt[v] - max(sepMax[v], rest)) + } + + // Rank components by counted size, descending, with a stable counting + // sort (discovery order = smallest vertex index first). The DFS arrays + // are dead now, so the sort reuses the slab: maxC+1 ≤ n+1 ≤ 2n. + var maxC int32 + for id := 0; id < nComp; id++ { + if compCnt[id] > 0 { + st.Components++ + } + maxC = max(maxC, compCnt[id]) + } + st.Largest = int(maxC) + firstRank := slab[0 : maxC+1] // per counted size + clear(firstRank) + for id := 0; id < nComp; id++ { + firstRank[compCnt[id]]++ + } + var acc int32 + for s := maxC; s >= 0; s-- { + c := firstRank[s] + firstRank[s] = acc + acc += c + } + rank := slab[2*n : 2*n+nComp] + for id := 0; id < nComp; id++ { + rank[id] = firstRank[compCnt[id]] + firstRank[compCnt[id]]++ + } + for v := range comp { + if comp[v] >= 0 { + comp[v] = int(rank[comp[v]]) + } + } + return st +} diff --git a/cmd/server/planner_graph_test.go b/cmd/server/planner_graph_test.go new file mode 100644 index 000000000..9946fadf2 --- /dev/null +++ b/cmd/server/planner_graph_test.go @@ -0,0 +1,842 @@ +package main + +import ( + "fmt" + "math" + "math/rand/v2" + "slices" + "testing" + "time" +) + +// ─── backboneGraph.Stats: hand-computed cases ────────────────────────────── + +func gEdges(pairs ...[2]int) []plannerEdge { + out := make([]plannerEdge, len(pairs)) + for i, p := range pairs { + out[i] = plannerEdge{A: p[0], B: p[1], Class: "solid"} + } + return out +} + +func countedSet(idx ...int) func(int) bool { + set := map[int]bool{} + for _, i := range idx { + set[i] = true + } + return func(i int) bool { return set[i] } +} + +func assertStats(t *testing.T, got, want backboneStats) { + t.Helper() + if got.Components != want.Components || got.Largest != want.Largest || got.Isolated != want.Isolated || + got.CutVertices != want.CutVertices || got.Fragility != want.Fragility || + !slices.Equal(got.ComponentOf, want.ComponentOf) { + t.Fatalf("stats mismatch\n got %+v\n want %+v", got, want) + } +} + +func TestBackboneStatsTable(t *testing.T) { + cases := []struct { + name string + n int + active []bool + edges []plannerEdge + counted func(int) bool // nil = all + want backboneStats + }{ + { + // a-b-c, b is a cut vertex: removing it leaves {a},{c}: 3-1-1 = 1. + name: "path a-b-c", n: 3, edges: gEdges([2]int{0, 1}, [2]int{1, 2}), + want: backboneStats{Components: 1, Largest: 3, CutVertices: 1, Fragility: 1, ComponentOf: []int{0, 0, 0}}, + }, + { + // Same path with b at index 0, so the cut vertex is the DFS root. + name: "path with cut vertex as DFS root", n: 3, edges: gEdges([2]int{0, 1}, [2]int{0, 2}), + want: backboneStats{Components: 1, Largest: 3, CutVertices: 1, Fragility: 1, ComponentOf: []int{0, 0, 0}}, + }, + { + // Star, 4 leaves: centre fragility = 5-1-1 = 3 = leaves-1. + name: "star centre root", n: 5, + edges: gEdges([2]int{0, 1}, [2]int{0, 2}, [2]int{0, 3}, [2]int{0, 4}), + want: backboneStats{Components: 1, Largest: 5, CutVertices: 1, Fragility: 3, ComponentOf: []int{0, 0, 0, 0, 0}}, + }, + { + // Star with the centre at the last index (non-root in the DFS). + name: "star centre non-root", n: 6, + edges: gEdges([2]int{5, 0}, [2]int{5, 1}, [2]int{5, 2}, [2]int{5, 3}, [2]int{5, 4}), + want: backboneStats{Components: 1, Largest: 6, CutVertices: 1, Fragility: 4, ComponentOf: []int{0, 0, 0, 0, 0, 0}}, + }, + { + name: "cycle", n: 4, edges: gEdges([2]int{0, 1}, [2]int{1, 2}, [2]int{2, 3}, [2]int{3, 0}), + want: backboneStats{Components: 1, Largest: 4, ComponentOf: []int{0, 0, 0, 0}}, + }, + { + // Triangles {0,1,2} and {4,5,6} joined through bridge vertex 3. + // v=2: parts {0,1}=2, {3,4,5,6}=4 → 7-1-4 = 2 + // v=3: parts {0,1,2}=3, {4,5,6}=3 → 7-1-3 = 3 + // v=4: parts {5,6}=2, {0,1,2,3}=4 → 7-1-4 = 2 + name: "two triangles joined by a bridge vertex", n: 7, + edges: gEdges([2]int{0, 1}, [2]int{1, 2}, [2]int{0, 2}, [2]int{2, 3}, [2]int{3, 4}, + [2]int{4, 5}, [2]int{5, 6}, [2]int{4, 6}), + want: backboneStats{Components: 1, Largest: 7, CutVertices: 3, Fragility: 7, ComponentOf: []int{0, 0, 0, 0, 0, 0, 0}}, + }, + { + // Bow-tie: triangles share vertex 2. parts {0,1},{3,4} → 5-1-2 = 2. + name: "bow-tie sharing one vertex", n: 5, + edges: gEdges([2]int{0, 1}, [2]int{1, 2}, [2]int{0, 2}, [2]int{2, 3}, [2]int{3, 4}, [2]int{2, 4}), + want: backboneStats{Components: 1, Largest: 5, CutVertices: 1, Fragility: 2, ComponentOf: []int{0, 0, 0, 0, 0}}, + }, + { + // 0 and 1 isolated, pair 2-3: the pair is the largest (id 0), the + // isolated vertices follow in index order. + name: "disconnected pair plus isolated vertices", n: 4, edges: gEdges([2]int{2, 3}), + want: backboneStats{Components: 3, Largest: 2, Isolated: 2, ComponentOf: []int{1, 2, 0, 0}}, + }, + { + // Equal counted sizes: the component with the smaller vertex wins. + name: "tie broken by smallest vertex index", n: 4, edges: gEdges([2]int{1, 3}, [2]int{0, 2}), + want: backboneStats{Components: 2, Largest: 2, ComponentOf: []int{0, 1, 0, 1}}, + }, + { + // Counted {0,1,2}; margin vertices 3 and 5 uncounted; 4 is an + // uncounted isolated vertex. Graph 0-3-1-2-5. + // v=3 (uncounted AP): parts {0}=1, {1,2,5}=2 → 3-0-2 = 1 + // v=1: parts {0,3}=1, {2,5}=1 → 3-1-1 = 1 + // v=2: parts {0,3,1}=2, {5}=0 → 3-1-2 = 0 + // CutVertices counts 1 and 2 only; {4} is not a component. + name: "counted/uncounted mix", n: 6, + edges: gEdges([2]int{0, 3}, [2]int{3, 1}, [2]int{1, 2}, [2]int{2, 5}), + counted: countedSet(0, 1, 2), + want: backboneStats{Components: 1, Largest: 3, CutVertices: 2, Fragility: 2, ComponentOf: []int{0, 0, 0, 0, 1, 0}}, + }, + { + // Uncounted-only component bigger than the counted one still + // ranks after it. + name: "uncounted component ranks last", n: 5, + edges: gEdges([2]int{0, 1}, [2]int{1, 2}, [2]int{3, 4}), + counted: countedSet(3), + want: backboneStats{Components: 1, Largest: 1, CutVertices: 0, Fragility: 0, ComponentOf: []int{1, 1, 1, 0, 0}}, + }, + { + // Path 0-1-2 with 1 inactive: its edges vanish, 0 and 2 isolated. + name: "inactive vertex", n: 3, active: []bool{true, false, true}, + edges: gEdges([2]int{0, 1}, [2]int{1, 2}), + want: backboneStats{Components: 2, Largest: 1, Isolated: 2, ComponentOf: []int{0, -1, 1}}, + }, + { + // Parallel edges, reversed duplicates, self-loops and out-of-range + // endpoints collapse to the single edge 0-1; 0-1 is no cycle. + name: "parallel edges and junk are deduped", n: 3, + edges: gEdges([2]int{0, 1}, [2]int{1, 0}, [2]int{0, 1}, [2]int{1, 1}, [2]int{2, 2}, [2]int{0, 7}, [2]int{-1, 2}), + want: backboneStats{Components: 2, Largest: 2, Isolated: 1, ComponentOf: []int{0, 0, 1}}, + }, + { + name: "empty graph", n: 0, + want: backboneStats{ComponentOf: []int{}}, + }, + { + name: "nothing counted", n: 3, edges: gEdges([2]int{0, 1}, [2]int{1, 2}), + counted: func(int) bool { return false }, + want: backboneStats{ComponentOf: []int{0, 0, 0}}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + g := newBackboneGraph(tc.n, tc.active, tc.edges) + assertStats(t, g.Stats(tc.counted), tc.want) + }) + } +} + +func TestBackboneAddVertexBridgesComponents(t *testing.T) { + g := newBackboneGraph(5, []bool{true, true, true, true, false}, gEdges([2]int{0, 1}, [2]int{2, 3})) + counted := func(i int) bool { return i < 4 } // the site itself is not counted + assertStats(t, g.Stats(counted), backboneStats{Components: 2, Largest: 2, ComponentOf: []int{0, 0, 1, 1, -1}}) + + // Duplicates, out-of-range, negative and inactive peers are ignored. + v := g.AddVertex([]int{1, 2, 1, 99, -1, 4}) + if v != 5 || g.n != 6 || len(g.adj[5]) != 2 || len(g.adj[4]) != 0 { + t.Fatalf("AddVertex = %d, n=%d, adj[5]=%v adj[4]=%v", v, g.n, g.adj[5], g.adj[4]) + } + // 0-1-5-2-3, counted {0..3}: + // v=1: parts {0}=1, {5,2,3}=2 → 4-1-2 = 1 + // v=5: parts {0,1}=2, {2,3}=2 → 4-0-2 = 2 (not counted: no CutVertices) + // v=2: parts {3}=1, {0,1,5}=2 → 4-1-2 = 1 + assertStats(t, g.Stats(counted), backboneStats{ + Components: 1, Largest: 4, CutVertices: 2, Fragility: 4, ComponentOf: []int{0, 0, 0, 0, -1, 0}, + }) + + // A second site linked to 3 and 0 closes the cycle 0-1-5-2-3-6: a + // redundancy pick leaves no articulation point at all. + w := g.AddVertex([]int{3, 0}) + if w != 6 { + t.Fatalf("second AddVertex = %d", w) + } + assertStats(t, g.Stats(counted), backboneStats{ + Components: 1, Largest: 4, ComponentOf: []int{0, 0, 0, 0, -1, 0, 0}, + }) +} + +func TestBackboneAddVertexNoPeers(t *testing.T) { + g := newBackboneGraph(2, nil, gEdges([2]int{0, 1})) + g.AddVertex(nil) + assertStats(t, g.Stats(nil), backboneStats{Components: 2, Largest: 2, Isolated: 1, ComponentOf: []int{0, 0, 1}}) +} + +func TestBackboneCloneIndependence(t *testing.T) { + g := newBackboneGraph(4, nil, gEdges([2]int{0, 1}, [2]int{2, 3})) + before := g.Stats(nil) + + c := g.Clone() + c.AddVertex([]int{1, 2}) + c.AddVertex([]int{0, 3}) + if g.n != 4 || len(g.adj) != 4 || len(g.active) != 4 { + t.Fatalf("clone mutation leaked: n=%d len(adj)=%d", g.n, len(g.adj)) + } + for v, want := range []int{1, 1, 1, 1} { + if len(g.adj[v]) != want { + t.Fatalf("original adj[%d]=%v after clone AddVertex", v, g.adj[v]) + } + } + assertStats(t, g.Stats(nil), before) + assertStats(t, c.Stats(nil), backboneStats{Components: 1, Largest: 6, ComponentOf: []int{0, 0, 0, 0, 0, 0}}) + + // And the other way: growing the original leaves the clone alone. + cBefore := c.Stats(nil) + g.AddVertex([]int{0, 1, 2, 3}) + assertStats(t, c.Stats(nil), cBefore) + if len(c.adj[0]) != 2 { + t.Fatalf("clone adj[0]=%v after original AddVertex", c.adj[0]) + } + + // A clone of a clone appends without overwriting its neighbour's list + // in the shared flat backing array. + cc := c.Clone() + cc.AddVertex([]int{0}) + if !slices.Equal(cc.adj[1], c.adj[1]) || len(cc.adj[0]) != len(c.adj[0])+1 { + t.Fatalf("flat backing overwrite: cc.adj[0]=%v cc.adj[1]=%v c.adj[1]=%v", cc.adj[0], cc.adj[1], c.adj[1]) + } +} + +// Parallel edges cannot change vertex connectivity, so Stats alone cannot +// see a missed dedup; check the adjacency invariant directly. +func TestBackboneNewGraphDedupsAdjacency(t *testing.T) { + g := newBackboneGraph(3, nil, gEdges([2]int{0, 1}, [2]int{1, 0}, [2]int{0, 1}, [2]int{1, 1}, [2]int{1, 2})) + if !slices.Equal(g.adj[0], []int{1}) || !slices.Equal(g.adj[1], []int{0, 2}) || !slices.Equal(g.adj[2], []int{1}) { + t.Fatalf("adj = %v", g.adj) + } +} + +func TestBackboneNewGraphKeepsCallerSlices(t *testing.T) { + active := []bool{true, true} + g := newBackboneGraph(2, active, gEdges([2]int{0, 1})) + active[1] = false + g.AddVertex([]int{1}) + if !g.active[1] || len(active) != 2 { + t.Fatalf("graph aliases the caller's active slice") + } + // A short active slice: indices past it are active. + h := newBackboneGraph(3, []bool{false}, gEdges([2]int{1, 2}, [2]int{0, 1})) + assertStats(t, h.Stats(nil), backboneStats{Components: 1, Largest: 2, ComponentOf: []int{-1, 0, 0}}) +} + +// A long path proves the DFS is iterative and the fragility sum exact: +// internal vertex i leaves parts i and m-i (m = n-1), so it contributes +// min(i, m-i); for m = 2k the total is k². +func TestBackboneStatsDeepPath(t *testing.T) { + const n = 200001 + edges := make([]plannerEdge, 0, n-1) + for i := 0; i+1 < n; i++ { + edges = append(edges, plannerEdge{A: i, B: i + 1}) + } + st := newBackboneGraph(n, nil, edges).Stats(nil) + k := (n - 1) / 2 + if st.Components != 1 || st.Largest != n || st.CutVertices != n-2 || st.Fragility != k*k { + t.Fatalf("deep path: %+v (want cut %d frag %d)", backboneStats{ + Components: st.Components, Largest: st.Largest, CutVertices: st.CutVertices, Fragility: st.Fragility, + }, n-2, k*k) + } +} + +// ─── backboneGraph.Stats: property test against brute force ──────────────── + +// bruteStats recomputes backboneStats from the raw edge list (not g.adj): +// components by BFS, and for each vertex, the parts left after deleting it. +func bruteStats(n int, active []bool, edges [][2]int, counted func(int) bool) backboneStats { + isAct := func(i int) bool { return active == nil || i >= len(active) || active[i] } + adj := make([]map[int]bool, n) + for i := range adj { + adj[i] = map[int]bool{} + } + for _, e := range edges { + a, b := e[0], e[1] + if a == b || a < 0 || b < 0 || a >= n || b >= n || !isAct(a) || !isAct(b) { + continue + } + adj[a][b], adj[b][a] = true, true + } + cnt := func(i int) int { + if isAct(i) && (counted == nil || counted(i)) { + return 1 + } + return 0 + } + // components ignoring vertex skip (−1 = none); returns per-vertex label + // and per-label counted size, labels in smallest-vertex order. + label := func(skip int) ([]int, []int) { + lab := make([]int, n) + for i := range lab { + lab[i] = -1 + } + var sizes []int + for r := 0; r < n; r++ { + if r == skip || !isAct(r) || lab[r] >= 0 { + continue + } + id := len(sizes) + sizes = append(sizes, 0) + queue := []int{r} + lab[r] = id + for len(queue) > 0 { + v := queue[0] + queue = queue[1:] + sizes[id] += cnt(v) + for w := range adj[v] { + if w != skip && lab[w] < 0 { + lab[w] = id + queue = append(queue, w) + } + } + } + } + return lab, sizes + } + lab, sizes := label(-1) + var st backboneStats + for _, s := range sizes { + if s > 0 { + st.Components++ + } + st.Largest = max(st.Largest, s) + } + order := make([]int, len(sizes)) + for i := range order { + order[i] = i + } + slices.SortStableFunc(order, func(a, b int) int { return sizes[b] - sizes[a] }) + rank := make([]int, len(sizes)) + for r, id := range order { + rank[id] = r + } + st.ComponentOf = make([]int, n) + for v := 0; v < n; v++ { + st.ComponentOf[v] = -1 + if lab[v] < 0 { + continue + } + st.ComponentOf[v] = rank[lab[v]] + if cnt(v) == 1 && len(adj[v]) == 0 { + st.Isolated++ + } + // Parts of C(v) after removing v. + lab2, sizes2 := label(v) + parts := map[int]int{} + for u := 0; u < n; u++ { + if u != v && lab[u] == lab[v] { + parts[lab2[u]] = sizes2[lab2[u]] + } + } + if len(parts) < 2 { + continue + } + if cnt(v) == 1 { + st.CutVertices++ + } + largest := 0 + for _, s := range parts { + largest = max(largest, s) + } + st.Fragility += sizes[lab[v]] - cnt(v) - largest + } + return st +} + +func TestBackboneStatsMatchesBruteForce(t *testing.T) { + rng := rand.New(rand.NewPCG(2026, 11)) + for iter := 0; iter < 300; iter++ { + n := 1 + rng.IntN(14) + var active []bool + if rng.IntN(3) > 0 { + active = make([]bool, n) + for i := range active { + active[i] = rng.IntN(6) > 0 + } + } + p := 0.05 + 0.4*rng.Float64() + var edges [][2]int + for a := 0; a < n; a++ { + for b := 0; b < n; b++ { + if a != b && rng.Float64() < p/2 { + edges = append(edges, [2]int{a, b}) // both directions possible: duplicates + } + } + } + if rng.IntN(4) == 0 && n > 0 { + edges = append(edges, [2]int{0, 0}, [2]int{n - 1, n + 3}) // junk + } + cMask := make([]bool, n+3) + for i := range cMask { + cMask[i] = rng.IntN(4) > 0 + } + counted := func(i int) bool { return cMask[i] } + + g := newBackboneGraph(n, active, gEdges(edges...)) + // Sometimes grow the graph with sites, mirroring the edges in the + // brute force's list. + bn, bActive := n, active + if rng.IntN(2) == 0 { + if bActive == nil { + bActive = make([]bool, n) + for i := range bActive { + bActive[i] = true + } + } else { + bActive = slices.Clone(bActive) + } + for s := 0; s < 1+rng.IntN(3); s++ { + var peers []int + for q := 0; q < rng.IntN(4); q++ { + peers = append(peers, rng.IntN(bn+1)-1) + } + if rng.IntN(2) == 0 { + g = g.Clone() + } + v := g.AddVertex(peers) + for _, p := range peers { + if p >= 0 && p < bn && bActive[p] { + edges = append(edges, [2]int{v, p}) + } + } + bActive = append(bActive, true) + bn++ + } + } + got := g.Stats(counted) + want := bruteStats(bn, bActive, edges, counted) + if got.Components != want.Components || got.Largest != want.Largest || got.Isolated != want.Isolated || + got.CutVertices != want.CutVertices || got.Fragility != want.Fragility || + !slices.Equal(got.ComponentOf, want.ComponentOf) { + t.Fatalf("iter %d n=%d active=%v edges=%v counted=%v\n got %+v\n want %+v", + iter, bn, bActive, edges, cMask[:bn], got, want) + } + } +} + +// BenchmarkBackboneStats: the greedy search calls Stats ~500×10 times per +// plan on graphs of up to ~800 vertices (300 nodes + 500 candidates). +func BenchmarkBackboneStats(b *testing.B) { + const n, m = 800, 4000 + rng := rand.New(rand.NewPCG(1, 2)) + seen := map[[2]int]bool{} + var edges []plannerEdge + for len(edges) < m { + a, c := rng.IntN(n), rng.IntN(n) + if a == c || seen[[2]int{min(a, c), max(a, c)}] { + continue + } + seen[[2]int{min(a, c), max(a, c)}] = true + edges = append(edges, plannerEdge{A: a, B: c}) + } + // A pendant chain gives the pass real articulation points to score. + for i := 0; i < 50; i++ { + edges = append(edges, plannerEdge{A: 700 + i, B: 701 + i}) + } + g := newBackboneGraph(n, nil, edges) + counted := func(i int) bool { return i < 300 || i >= 700 } + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + _ = g.Stats(counted) + } +} + +// ─── selectPlannerNodes ──────────────────────────────────────────────────── + +// testArea is ~55 km N-S by ~39 km E-W around lat 45.25. +var testArea = geoBBox{S: 45.0, W: -122.0, N: 45.5, E: -121.5} + +// lonOffsetKm returns lon moved km east at lat. +func lonOffsetKm(lat, lon, km float64) float64 { + return lon + km/(plannerKmPerDeg*math.Cos(lat*math.Pi/180)) +} + +func latOffsetKm(lat, km float64) float64 { return lat + km/plannerKmPerDeg } + +func rptr(pk string, lat, lon float64) nodeInfo { + return nodeInfo{PublicKey: pk, Name: "node-" + pk, Role: "repeater", Lat: lat, Lon: lon, HasGPS: true} +} + +func pubkeys(nodes []plannerNode) []string { + out := make([]string, len(nodes)) + for i, n := range nodes { + out[i] = n.PubKey + } + return out +} + +func TestSelectPlannerNodesFilters(t *testing.T) { + now := time.Date(2026, 11, 11, 12, 0, 0, 0, time.UTC) + cLat, cLon := 45.25, -121.75 + all := []nodeInfo{ + rptr("aa01", cLat, cLon), + {PublicKey: "aa02", Name: "room", Role: "room", Lat: cLat, Lon: cLon, HasGPS: true}, + {PublicKey: "aa03", Name: "comp", Role: "companion", Lat: cLat, Lon: cLon, HasGPS: true}, + {PublicKey: "aa04", Name: "sens", Role: "sensor", Lat: cLat, Lon: cLon, HasGPS: true}, + {PublicKey: "aa05", Name: "room-server", Role: "room_server", Lat: cLat, Lon: cLon, HasGPS: true}, + {PublicKey: "aa06", Name: "nogps", Role: "repeater", Lat: cLat, Lon: cLon, HasGPS: false}, + rptr("aa07", 0, 0), + rptr("aa08", math.NaN(), cLon), + rptr("aa09", cLat, math.Inf(1)), + rptr("aa10", cLat, cLon), // blacklisted + {PublicKey: "aa11", Name: "Hidden-x", Role: "repeater", Lat: cLat, Lon: cLon, HasGPS: true}, + rptr("AA01", cLat, cLon), // same pubkey as aa01, different case + rptr("", cLat, cLon), + } + f := plannerNodeFilter{ + Visible: nodeVisibility{cfg: &Config{NodeBlacklist: []string{"aa10"}, HiddenNamePrefixes: []string{"Hidden"}}}.infoRule(nil), + } + got, trunc := selectPlannerNodes(all, nil, testArea, 30, f, now) + if trunc { + t.Fatal("unexpected truncation") + } + if want := []string{"aa01", "aa02"}; !slices.Equal(pubkeys(got), want) { + t.Fatalf("got %v want %v", pubkeys(got), want) + } + if got[1].Role != "room" || got[1].Name != "room" || !got[0].InArea || got[0].Stale { + t.Fatalf("fields: %+v", got) + } + + // A nil Visible hides nothing. + got, _ = selectPlannerNodes(all, nil, testArea, 30, plannerNodeFilter{}, now) + if want := []string{"aa01", "aa02", "aa10", "aa11"}; !slices.Equal(pubkeys(got), want) { + t.Fatalf("nil filters: got %v want %v", pubkeys(got), want) + } + + // (0,0) is the "no fix" placeholder: dropped even when the area holds it. + gulf := geoBBox{S: -0.5, W: -0.5, N: 0.5, E: 0.5} + got, _ = selectPlannerNodes([]nodeInfo{rptr("null-island", 0, 0), rptr("near", 0.1, 0)}, nil, gulf, 0, plannerNodeFilter{}, now) + if want := []string{"near"}; !slices.Equal(pubkeys(got), want) { + t.Fatalf("(0,0): got %v want %v", pubkeys(got), want) + } +} + +func TestSelectPlannerNodesMarginAndInArea(t *testing.T) { + now := time.Date(2026, 11, 11, 12, 0, 0, 0, time.UTC) + midLat := 45.25 + all := []nodeInfo{ + rptr("b01-centre", midLat, -121.75), + rptr("b02-on-north-edge", testArea.N, -121.75), + rptr("b03-on-west-edge", midLat, testArea.W), + rptr("b04-east-20km", midLat, lonOffsetKm(midLat, testArea.E, 20)), + rptr("b05-east-40km", midLat, lonOffsetKm(midLat, testArea.E, 40)), + rptr("b06-north-20km", latOffsetKm(testArea.N, 20), -121.75), + rptr("b07-north-40km", latOffsetKm(testArea.N, 40), -121.75), + rptr("b08-south-25km", latOffsetKm(testArea.S, -25), -121.75), + rptr("b09-west-28km-at-north", testArea.N, lonOffsetKm(testArea.N, testArea.W, -28)), + rptr("b10-west-33km", midLat, lonOffsetKm(midLat, testArea.W, -33)), + } + got, _ := selectPlannerNodes(all, nil, testArea, 30, plannerNodeFilter{}, now) + in := map[string]bool{} + for _, n := range got { + in[n.PubKey] = n.InArea + } + want := map[string]bool{ + "b01-centre": true, "b02-on-north-edge": true, "b03-on-west-edge": true, + "b04-east-20km": false, "b06-north-20km": false, "b08-south-25km": false, "b09-west-28km-at-north": false, + } + if len(in) != len(want) { + t.Fatalf("selected %v, want %v", in, want) + } + for pk, w := range want { + if g, ok := in[pk]; !ok || g != w { + t.Fatalf("%s: selected=%v InArea=%v, want InArea=%v (all: %v)", pk, ok, g, w, in) + } + } + // In-area first, then by pubkey. + if wantOrder := []string{"b01-centre", "b02-on-north-edge", "b03-on-west-edge", + "b04-east-20km", "b06-north-20km", "b08-south-25km", "b09-west-28km-at-north"}; !slices.Equal(pubkeys(got), wantOrder) { + t.Fatalf("order %v want %v", pubkeys(got), wantOrder) + } + + // marginKm 0: only the area itself. + got, _ = selectPlannerNodes(all, nil, testArea, 0, plannerNodeFilter{}, now) + if wantOrder := []string{"b01-centre", "b02-on-north-edge", "b03-on-west-edge"}; !slices.Equal(pubkeys(got), wantOrder) { + t.Fatalf("margin 0: %v", pubkeys(got)) + } +} + +func TestPlannerGraphExpandBBox(t *testing.T) { + e := plannerExpandBBox(testArea, 30) + // The east margin, measured along the parallels of the expanded box, + // is ≥ 30 km everywhere and ≈ 30 km at its highest latitude. + for _, lat := range []float64{e.S, testArea.S, 45.25, testArea.N, e.N} { + if d := haversineKm(lat, testArea.E, lat, e.E); d < 30-1e-3 { + t.Fatalf("east margin at lat %.3f = %.3f km < 30", lat, d) + } + } + if d := haversineKm(e.N, testArea.E, e.N, e.E); math.Abs(d-30) > 0.05 { + t.Fatalf("east margin at top = %.3f km, want ≈30", d) + } + if d := haversineKm(testArea.N, 0, e.N, 0); math.Abs(d-30) > 1e-6 { + t.Fatalf("north margin = %.6f km", d) + } + // Antimeridian: a node just past 180 is inside a box expanded past it. + area := geoBBox{S: -17.5, W: 179.5, N: -17.0, E: 179.9} + if !plannerBBoxContains(plannerExpandBBox(area, 30), -17.2, -179.95) { + t.Fatal("margin across the antimeridian missed a node") + } + // A pole-reaching box spans every longitude. + if p := plannerExpandBBox(geoBBox{S: 89.9, W: 0, N: 89.95, E: 1}, 30); p.W != -180 || p.E != 180 || p.N != 90 { + t.Fatalf("polar expansion %+v", p) + } + // NaN or negative margins expand nothing. + if plannerExpandBBox(testArea, math.NaN()) != testArea || plannerExpandBBox(testArea, -5) != testArea { + t.Fatal("bad margin changed the box") + } +} + +func TestSelectPlannerNodesStale(t *testing.T) { + now := time.Date(2026, 11, 11, 12, 0, 0, 0, time.UTC) + c := func(pk, role string, lastSeen time.Time) nodeInfo { + n := rptr(pk, 45.25, -121.75) + n.Role, n.LastSeen = role, lastSeen + return n + } + all := []nodeInfo{ + c("c1-old-seen-recent-heard", "repeater", now.Add(-100*time.Hour)), + c("c2-old-seen-no-heard", "repeater", now.Add(-100*time.Hour)), + c("c3-recent-seen-old-heard", "repeater", now.Add(-time.Hour)), + c("c4-never-seen", "repeater", time.Time{}), + c("c5-room-50h", "room", now.Add(-50*time.Hour)), + c("c6-repeater-50h", "repeater", now.Add(-50*time.Hour)), + c("c7-exactly-silent", "repeater", now.Add(-72*time.Hour)), + c("c8-future", "repeater", now.Add(time.Hour)), + } + heard := map[string]time.Time{ + "c1-old-seen-recent-heard": now.Add(-time.Hour), + "c3-recent-seen-old-heard": now.Add(-200 * time.Hour), + "c4-never-seen": {}, + } + f := plannerNodeFilter{SilentAfter: func(role string) time.Duration { + if role == "room" { + return 24 * time.Hour + } + return 72 * time.Hour + }} + got, _ := selectPlannerNodes(all, heard, testArea, 30, f, now) + stale := map[string]bool{} + for _, n := range got { + stale[n.PubKey] = n.Stale + } + want := map[string]bool{ + "c1-old-seen-recent-heard": false, // lastHeard overrides an old LastSeen + "c2-old-seen-no-heard": true, + "c3-recent-seen-old-heard": false, // the newer of the two wins + "c4-never-seen": true, + "c5-room-50h": true, // room window is 24h + "c6-repeater-50h": false, + "c7-exactly-silent": false, // strictly greater than the window + "c8-future": false, + } + for pk, w := range want { + if g, ok := stale[pk]; !ok || g != w { + t.Fatalf("%s: stale=%v present=%v, want %v", pk, g, ok, w) + } + } + + // Nil SilentAfter: nothing is stale. + got, _ = selectPlannerNodes(all, heard, testArea, 30, plannerNodeFilter{}, now) + for _, n := range got { + if n.Stale { + t.Fatalf("%s stale with nil SilentAfter", n.PubKey) + } + } +} + +func TestSelectPlannerNodesCapAndTruncation(t *testing.T) { + now := time.Date(2026, 11, 11, 12, 0, 0, 0, time.UTC) + cLat, cLon := 45.25, -121.75 + var all []nodeInfo + // 10 in-area nodes in the SW corner, ~34 km from the centre, and 300 + // margin nodes just east of the area, 20-30 km from it: every margin + // node is nearer the centre than every in-area node, so only the + // in-area-first rule keeps the corner nodes. + for i := 0; i < 10; i++ { + all = append(all, rptr(fmt.Sprintf("in-%02d", i), testArea.S+0.001*float64(i), testArea.W+0.001)) + } + for i := 0; i < 300; i++ { + lon := lonOffsetKm(cLat, testArea.E, 0.5+0.03*float64(i)) + all = append(all, rptr(fmt.Sprintf("m-%03d", i), cLat, lon)) + } + rng := rand.New(rand.NewPCG(3, 4)) + rng.Shuffle(len(all), func(i, j int) { all[i], all[j] = all[j], all[i] }) + + if far, near := haversineKm(cLat, cLon, testArea.S, testArea.W+0.001), + haversineKm(cLat, cLon, cLat, lonOffsetKm(cLat, testArea.E, 0.5+0.03*299)); far <= near { + t.Fatalf("fixture: corner %.1f km not beyond farthest margin node %.1f km", far, near) + } + got, trunc := selectPlannerNodes(all, nil, testArea, 30, plannerNodeFilter{}, now) + if !trunc || len(got) != plannerMaxNodes { + t.Fatalf("trunc=%v len=%d", trunc, len(got)) + } + for i := 0; i < 10; i++ { + if want := fmt.Sprintf("in-%02d", i); got[i].PubKey != want || !got[i].InArea { + t.Fatalf("got[%d]=%s InArea=%v, want %s in area", i, got[i].PubKey, got[i].InArea, want) + } + } + for i := 10; i < plannerMaxNodes; i++ { + // The 290 nearest margin nodes, ordered by pubkey. + if want := fmt.Sprintf("m-%03d", i-10); got[i].PubKey != want || got[i].InArea { + t.Fatalf("got[%d]=%s, want %s", i, got[i].PubKey, want) + } + } + + // Exactly at the cap: nothing dropped, no truncation. + got, trunc = selectPlannerNodes(all[:plannerMaxNodes], nil, testArea, 30, plannerNodeFilter{}, now) + if trunc || len(got) != plannerMaxNodes { + t.Fatalf("at cap: trunc=%v len=%d", trunc, len(got)) + } + + // More in-area nodes than the cap: the ones nearest the centre stay. + all = all[:0] + for i := 0; i < plannerMaxNodes+5; i++ { + all = append(all, rptr(fmt.Sprintf("z-%03d", i), cLat, cLon+0.0005*float64(i))) + } + got, trunc = selectPlannerNodes(all, nil, testArea, 30, plannerNodeFilter{}, now) + if !trunc || len(got) != plannerMaxNodes || got[len(got)-1].PubKey != fmt.Sprintf("z-%03d", plannerMaxNodes-1) { + t.Fatalf("in-area cap: trunc=%v len=%d last=%s", trunc, len(got), got[len(got)-1].PubKey) + } +} + +// ─── observedPlannerEdges ────────────────────────────────────────────────── + +func TestObservedPlannerEdges(t *testing.T) { + now := time.Date(2026, 11, 11, 12, 0, 0, 0, time.UTC) + nodes := []plannerNode{ + {PubKey: "aaaa", Lat: 45.0, Lon: -122.0}, + {PubKey: "bbbb", Lat: 45.1, Lon: -122.0}, + {PubKey: "cccc", Lat: 45.2, Lon: -122.0}, + {PubKey: "dddd", Lat: 45.3, Lon: -122.0}, + {PubKey: "EEEE", Lat: 45.4, Lon: -122.0}, + {PubKey: "ffff", Lat: 45.5, Lon: -122.0}, + {PubKey: "gggg", Lat: 45.6, Lon: -122.0}, + } + three := map[string]bool{"o1": true, "o2": true, "o3": true} + strong := func(a, b string, modes map[int]int) NeighborEdge { + return NeighborEdge{NodeA: a, NodeB: b, Count: 100, LastSeen: now, Observers: three, CountsByMode: modes} + } + ambiguous := strong("aaaa", "gggg", map[int]int{2: 100}) + ambiguous.Ambiguous = true + unresolved := strong("aaaa", "", map[int]int{2: 100}) + weak := strong("cccc", "gggg", map[int]int{2: 100}) + weak.Count = 4 // score 0.04 < 0.05 + oneObserver := strong("dddd", "gggg", map[int]int{2: 100}) + oneObserver.Observers = map[string]bool{"o1": true} // 1.0 × 1/3 < 0.5 + decayed := strong("ffff", "gggg", map[int]int{3: 100}) + decayed.LastSeen = now.Add(-30 * 24 * time.Hour) // ~0.05 after 4+ half-lives + edges := []NeighborEdge{ + ambiguous, + unresolved, + strong("aaaa", "bbbb", map[int]int{1: 100}), // 1-byte only: dropped + strong("bbbb", "cccc", map[int]int{2: 100}), // 2-byte: kept + strong("cccc", "bbbb", map[int]int{2: 50, 1: 50}), // duplicate of the above, reversed + strong("CCCC", "dddd", map[int]int{0: 100}), // legacy: kept + strong("dddd", "eeee", nil), // no tally: kept (and case-insensitive) + strong("aaaa", "cccc", map[int]int{1: 99, 3: 1}), // any 3-byte evidence: kept + strong("aaaa", "dddd", map[int]int{0: 50, 1: 50}), // legacy + 1-byte, not legacy-only: dropped + strong("aaaa", "zzzz", map[int]int{3: 100}), // endpoint not in nodes + strong("bbbb", "bbbb", map[int]int{3: 100}), // self + strong("eeee", "ffff", map[int]int{0: 0, 1: 0, 2: 7}), // zero buckets ignored + weak, + oneObserver, + decayed, + } + got := observedPlannerEdges(nodes, edges, now, 0.5) + type pair struct{ a, b int } + var gotPairs []pair + for _, e := range got { + if e.Class != "observed" || e.ClearancePct != 0 || e.A >= e.B { + t.Fatalf("bad edge %+v", e) + } + if want := haversineKm(nodes[e.A].Lat, nodes[e.A].Lon, nodes[e.B].Lat, nodes[e.B].Lon); e.DistanceKm != want { + t.Fatalf("distance %v want %v", e.DistanceKm, want) + } + gotPairs = append(gotPairs, pair{e.A, e.B}) + } + want := []pair{{0, 2}, {1, 2}, {2, 3}, {3, 4}, {4, 5}} + if !slices.Equal(gotPairs, want) { + t.Fatalf("pairs %v want %v", gotPairs, want) + } + if math.Abs(got[0].DistanceKm-22.24) > 0.01 { + t.Fatalf("0.2° of latitude = %.3f km", got[0].DistanceKm) + } + + // minScore gates on Score×Confidence: a low threshold admits the weak, + // single-observer and decayed edges too. + got = observedPlannerEdges(nodes, edges, now, 0.01) + if len(got) != 8 { + t.Fatalf("minScore 0.01: %d edges %+v", len(got), got) + } + + // The threshold is inclusive: the strong edges score exactly 1.0. + if got = observedPlannerEdges(nodes, edges, now, 1.0); len(got) != 5 { + t.Fatalf("minScore 1.0: %d edges %+v", len(got), got) + } + + if out := observedPlannerEdges(nil, edges, now, 0); len(out) != 0 { + t.Fatalf("no nodes: %+v", out) + } +} + +func TestPlannerGraphEdgeEvidence(t *testing.T) { + cases := []struct { + modes map[int]int + ambiguous bool + resolved bool + want bool + }{ + {nil, false, false, true}, + {map[int]int{}, false, false, true}, + {map[int]int{0: 5}, false, false, true}, + {map[int]int{0: 5}, true, true, true}, // Jaccard-resolved legacy + {map[int]int{0: 5}, true, false, false}, + {map[int]int{1: 5}, false, true, false}, + {map[int]int{0: 5, 1: 1}, false, false, false}, + {map[int]int{2: 1}, true, false, true}, // evidence only; ambiguity is the caller's rule + {map[int]int{1: 9, 3: 1}, false, false, true}, + } + for i, tc := range cases { + e := &NeighborEdge{CountsByMode: tc.modes, Ambiguous: tc.ambiguous, Resolved: tc.resolved} + if got := plannerEdgeEvidenceOK(e); got != tc.want { + t.Fatalf("case %d %+v: got %v", i, tc, got) + } + } +} + +// The operator geo_filter /api/nodes applies must also hide nodes from the +// planner: no node the API hides may surface here. +func TestSelectPlannerNodesHonoursGeoFilter(t *testing.T) { + now := time.Now() + all := []nodeInfo{ + {PublicKey: "aa01", Name: "Inside", Role: "repeater", Lat: 30.30, Lon: -97.80, HasGPS: true, LastSeen: now}, + {PublicKey: "bb02", Name: "Filtered", Role: "repeater", Lat: 30.32, Lon: -97.70, HasGPS: true, LastSeen: now}, + } + area := geoBBox{S: 30.2, W: -97.9, N: 30.4, E: -97.6} + gf := &GeoFilterConfig{Polygon: [][2]float64{{30.2, -97.9}, {30.2, -97.75}, {30.4, -97.75}, {30.4, -97.9}}} + f := plannerNodeFilter{Visible: nodeVisibility{geo: gf}.infoRule(nil)} + nodes, _ := selectPlannerNodes(all, nil, area, 0, f, now) + if len(nodes) != 1 || nodes[0].PubKey != "aa01" { + t.Fatalf("geo-filtered node leaked into planner nodes: %+v", nodes) + } +} diff --git a/cmd/server/planner_los.go b/cmd/server/planner_los.go new file mode 100644 index 000000000..da1068117 --- /dev/null +++ b/cmd/server/planner_los.go @@ -0,0 +1,269 @@ +package main + +// LOS maths for the planner: a Go port of public/los.js analyze(). +// The server and browser must reach identical verdicts on identical terrain; +// tests/fixtures/planner-los-vectors.json is the shared proof (generated from +// the real los.js, checked by both Go and Node). + +import "math" + +// geoSamePointRadians: a leg shorter than this is one point to the samplers. +const geoSamePointRadians = 1e-9 + +// losParams: antenna heights are metres above ground at each end. +// KFactor 0 means the default 4/3; negative is invalid. +type losParams struct { + FreqMHz, KFactor, AntennaAM, AntennaBM float64 +} + +// losResult mirrors MeshLOS.analyze: Clearance is the min over interior +// samples of (LOS − terrain)/F1 (+Inf when fewer than 3 samples), Verdict is +// clear | clear60 | marginal | blocked. With no interior sample WorstIdx is +// -1, WorstT/WorstKm are 0 and ObstructionM is -Inf. +type losResult struct { + DistanceKm float64 + Clearance float64 + WorstIdx int + WorstT float64 + WorstKm float64 + ObstructionM float64 + Verdict string +} + +func losFinite(x float64) bool { return !math.IsNaN(x) && !math.IsInf(x, 0) } + +func losVerdict(c float64) string { + switch { + case c >= 1: + return "clear" + case c >= 0.6: + return "clear60" + case c >= 0: + return "marginal" + } + return "blocked" +} + +// analyzeLOS: ok=false on invalid input (fewer than 2 samples, NaN/Inf, +// freq ≤ 0, k < 0). +func analyzeLOS(elevM []float64, distKm float64, p losParams) (losResult, bool) { + n := len(elevM) + if n < 2 { + return losResult{}, false + } + for _, v := range elevM { + if !losFinite(v) { + return losResult{}, false + } + } + if !(p.FreqMHz > 0) || !losFinite(p.FreqMHz) { + return losResult{}, false + } + k := p.KFactor + if k == 0 { + k = 4.0 / 3.0 + } + if !(k > 0) || !losFinite(k) { + return losResult{}, false + } + D := distKm + if !losFinite(D) || D < 0.001 { + D = 0.001 + } + aA, aB := p.AntennaAM, p.AntennaBM + if !losFinite(aA) { + aA = 0 + } + if !losFinite(aB) { + aB = 0 + } + + last := float64(n - 1) + terrain := func(i int) float64 { + d := float64(i) / last * D + return elevM[i] + d*(D-d)/(2*k*earthRadiusKm)*1000 + } + yA, yB := terrain(0)+aA, terrain(n-1)+aB + res := losResult{DistanceKm: D, Clearance: math.Inf(1), WorstIdx: -1, ObstructionM: math.Inf(-1)} + for i := 1; i <= n-2; i++ { + t := float64(i) / last + los := yA + (yB-yA)*t + d := t * D + f1 := 17.32 * math.Sqrt(math.Max(d*(D-d), 1e-9)/(D*p.FreqMHz/1000)) + tm := terrain(i) + if c := (los - tm) / f1; c < res.Clearance { + res.Clearance, res.WorstIdx = c, i + } + if ob := tm - los; ob > res.ObstructionM { + res.ObstructionM = ob + } + } + if res.WorstIdx >= 0 { + res.WorstT = float64(res.WorstIdx) / last + res.WorstKm = res.WorstT * D + } + res.Verdict = losVerdict(res.Clearance) + return res, true +} + +// planProfileSamples: samples for a leg, ~90 m spacing, clamped to [64, 600]. +// Above ~54 km the cap widens the spacing past the grid's 90 m, so a ridge +// narrower than the spacing can fall between samples and the verdict leans +// towards clear; the UI footers and docs/api-spec.md say so. +func planProfileSamples(distKm float64) int { + if !losFinite(distKm) || distKm < 0 { + return 64 + } + n := math.Ceil(distKm*1000/90) + 1 + if n < 64 { + return 64 + } + if n > 600 { + return 600 + } + return int(n) +} + +// sampleTerrainProfile returns n elevations from a to b along the great +// circle (t = i/(n-1)); ok=false if any sample has no terrain (outside the +// view, or on a tile without data). +func sampleTerrainProfile(v terrainView, a, b geoPoint, n int) ([]float64, bool) { + if n < 2 { + return nil, false + } + return sampleTerrainAt(v, greatCircleSamples(a, b, n)) +} + +// sampleTerrainAt returns the elevation at each point; ok=false if any has +// no terrain. +func sampleTerrainAt(v terrainView, pts []geoPoint) ([]float64, bool) { + if v == nil { + return nil, false + } + out := make([]float64, len(pts)) + for i, p := range pts { + e, ok := v.ElevationAt(p.Lat, p.Lon) + if !ok { + return nil, false + } + out[i] = e + } + return out, true +} + +// legSamplePoints is where a profile reads the terrain of leg a→b: +// planProfileSamples(km) points along the great circle, both ends included. +func legSamplePoints(a, b geoPoint) []geoPoint { + return greatCircleSamples(a, b, planProfileSamples(geoDistKm(a, b))) +} + +// sampleLegProfile is leg a→b's terrain as both profile endpoints serve it +// (/api/planner/profile and /api/elevation/profile): the elevation at each +// of legSamplePoints, rounded to 0.1 m. One helper, so the same leg over the +// same tiles gets the same heights, and so the same verdict, in both views. +// ok=false if any sample has no terrain. +func sampleLegProfile(v terrainView, a, b geoPoint) ([]float64, bool) { + elev, ok := sampleTerrainAt(v, legSamplePoints(a, b)) + if !ok { + return nil, false + } + for i := range elev { + elev[i] = losRound(elev[i], 10) + } + return elev, true +} + +func geoDistKm(a, b geoPoint) float64 { return haversineKm(a.Lat, a.Lon, b.Lat, b.Lon) } + +// greatCircleSamples returns n points from a to b (inclusive) along the great +// circle, at fractions t = i/(n-1), using the spherical intermediate-point +// formula. It is the one sampler of point slices; planArc is its one-point +// form for the search's hot loop. +func greatCircleSamples(a, b geoPoint, n int) []geoPoint { + out := make([]geoPoint, n) + p1, l1 := a.Lat*math.Pi/180, a.Lon*math.Pi/180 + p2, l2 := b.Lat*math.Pi/180, b.Lon*math.Pi/180 + d := geoDistKm(a, b) / earthRadiusKm + if d < geoSamePointRadians { + for i := range out { + out[i] = a + } + return out + } + sd := math.Sin(d) + for i := range out { + f := float64(i) / float64(n-1) + A := math.Sin((1-f)*d) / sd + B := math.Sin(f*d) / sd + x := A*math.Cos(p1)*math.Cos(l1) + B*math.Cos(p2)*math.Cos(l2) + y := A*math.Cos(p1)*math.Sin(l1) + B*math.Cos(p2)*math.Sin(l2) + z := A*math.Sin(p1) + B*math.Sin(p2) + out[i] = geoPoint{ + Lat: math.Atan2(z, math.Hypot(x, y)) * 180 / math.Pi, + Lon: math.Atan2(y, x) * 180 / math.Pi, + } + } + // Endpoints are exact, not trig round-trips. + out[0], out[n-1] = a, b + return out +} + +func losRound(x float64, scale float64) float64 { return math.Round(x*scale) / scale } + +// linkFromProfile summarises a profile as a PlannerLink; withElev attaches +// the profile decimated to ≤ 200 samples. Invalid input yields a zero link +// with a "blocked" verdict so it can never read as a usable path. +func linkFromProfile(elev []float64, distKm float64, p losParams, withElev bool) PlannerLink { + r, ok := analyzeLOS(elev, distKm, p) + if !ok { + return PlannerLink{DistanceKm: losRound(math.Max(distKm, 0), 1000), Verdict: "blocked"} + } + pct := 999.0 + if !math.IsInf(r.Clearance, 1) { + pct = losRound(r.Clearance*100, 10) + } + obs := r.ObstructionM + if math.IsInf(obs, -1) { + obs = 0 // no interior samples; -Inf is not JSON-encodable + } + l := PlannerLink{ + DistanceKm: losRound(r.DistanceKm, 1000), + ClearancePct: pct, + Verdict: r.Verdict, + WorstKm: losRound(r.WorstKm, 10), + ObstructionM: losRound(obs, 10), + } + if withElev { + d := decimateProfile(elev, 200) + l.ElevM = make([]float64, len(d)) + for i, v := range d { + l.ElevM[i] = losRound(v, 10) + } + } + return l +} + +// decimateProfile keeps both ends and at most max samples, preserving the +// per-bucket maximum so ridges survive. The result has exactly max samples +// when len(elev) > max (max < 3 returns the input unchanged). +func decimateProfile(elev []float64, max int) []float64 { + n := len(elev) + if n <= max || max < 3 { + return elev + } + interior, buckets := n-2, max-2 + out := make([]float64, 0, max) + out = append(out, elev[0]) + for j := 0; j < buckets; j++ { + lo := 1 + j*interior/buckets + hi := 1 + (j+1)*interior/buckets + m := elev[lo] + for _, v := range elev[lo+1 : hi] { + if v > m { + m = v + } + } + out = append(out, m) + } + return append(out, elev[n-1]) +} diff --git a/cmd/server/planner_los_test.go b/cmd/server/planner_los_test.go new file mode 100644 index 000000000..23d13cbb8 --- /dev/null +++ b/cmd/server/planner_los_test.go @@ -0,0 +1,248 @@ +package main + +import ( + "encoding/json" + "math" + "os" + "testing" +) + +type losVectorFile struct { + Name string `json:"name"` + Input struct { + ElevM []float64 `json:"elevM"` + DistanceKm float64 `json:"distanceKm"` + FreqMHz float64 `json:"freqMHz"` + KFactor float64 `json:"kFactor"` + AntennaAM float64 `json:"antennaAM"` + AntennaBM float64 `json:"antennaBM"` + } `json:"input"` + Expect struct { + Clearance *float64 `json:"clearance"` // null = +Inf + WorstIdx int `json:"worstIdx"` + ObstructionM *float64 `json:"obstructionM"` // null = -Inf + WorstKm *float64 `json:"worstKm"` + DistanceKm float64 `json:"distanceKm"` + Verdict string `json:"verdict"` + } `json:"expect"` +} + +func loadLOSVectors(t *testing.T) []losVectorFile { + t.Helper() + raw, err := os.ReadFile("../../tests/fixtures/planner-los-vectors.json") + if err != nil { + t.Fatal(err) + } + var vs []losVectorFile + if err := json.Unmarshal(raw, &vs); err != nil { + t.Fatal(err) + } + if len(vs) < 6 { + t.Fatalf("want >= 6 vectors, got %d", len(vs)) + } + return vs +} + +func near(a, b float64) bool { return math.Abs(a-b) <= 1e-9 } + +func TestPlannerLOSVectorsMatchJS(t *testing.T) { + for _, v := range loadLOSVectors(t) { + t.Run(v.Name, func(t *testing.T) { + p := losParams{v.Input.FreqMHz, v.Input.KFactor, v.Input.AntennaAM, v.Input.AntennaBM} + r, ok := analyzeLOS(v.Input.ElevM, v.Input.DistanceKm, p) + if !ok { + t.Fatal("ok=false") + } + e := v.Expect + if e.Clearance == nil { + if !math.IsInf(r.Clearance, 1) { + t.Errorf("clearance %v, want +Inf", r.Clearance) + } + } else if !near(r.Clearance, *e.Clearance) { + t.Errorf("clearance %v, want %v", r.Clearance, *e.Clearance) + } + if e.ObstructionM == nil { + if !math.IsInf(r.ObstructionM, -1) { + t.Errorf("obstruction %v, want -Inf", r.ObstructionM) + } + } else if !near(r.ObstructionM, *e.ObstructionM) { + t.Errorf("obstruction %v, want %v", r.ObstructionM, *e.ObstructionM) + } + if e.WorstKm != nil && !near(r.WorstKm, *e.WorstKm) { + t.Errorf("worstKm %v, want %v", r.WorstKm, *e.WorstKm) + } + if r.WorstIdx != e.WorstIdx { + t.Errorf("worstIdx %d, want %d", r.WorstIdx, e.WorstIdx) + } + if r.Verdict != e.Verdict { + t.Errorf("verdict %s, want %s", r.Verdict, e.Verdict) + } + if !near(r.DistanceKm, e.DistanceKm) { + t.Errorf("distanceKm %v, want %v", r.DistanceKm, e.DistanceKm) + } + }) + } +} + +func TestPlannerLOSVectorsCoverAllVerdicts(t *testing.T) { + seen := map[string]bool{} + for _, v := range loadLOSVectors(t) { + seen[v.Expect.Verdict] = true + } + for _, w := range []string{"clear", "clear60", "marginal", "blocked"} { + if !seen[w] { + t.Errorf("no vector with verdict %s", w) + } + } +} + +func TestPlannerLOSInvalidInput(t *testing.T) { + ok := losParams{FreqMHz: 869.6} + cases := map[string]struct { + e []float64 + d float64 + p losParams + }{ + "one sample": {[]float64{1}, 1, ok}, + "nan elev": {[]float64{1, math.NaN(), 2}, 1, ok}, + "inf elev": {[]float64{1, math.Inf(1), 2}, 1, ok}, + "freq zero": {[]float64{1, 2, 3}, 1, losParams{}}, + "freq nan": {[]float64{1, 2, 3}, 1, losParams{FreqMHz: math.NaN()}}, + "k negative": {[]float64{1, 2, 3}, 1, losParams{FreqMHz: 869.6, KFactor: -1}}, + } + for name, c := range cases { + if _, got := analyzeLOS(c.e, c.d, c.p); got { + t.Errorf("%s: ok=true", name) + } + } + // k=0 defaults to 4/3. + a, _ := analyzeLOS([]float64{0, 0, 0}, 10, losParams{FreqMHz: 869.6}) + b, _ := analyzeLOS([]float64{0, 0, 0}, 10, losParams{FreqMHz: 869.6, KFactor: 4.0 / 3.0}) + if a.Clearance != b.Clearance { + t.Errorf("k default mismatch %v vs %v", a.Clearance, b.Clearance) + } +} + +func TestPlannerLOSLinkFromProfile(t *testing.T) { + p := losParams{FreqMHz: 869.618, KFactor: 4.0 / 3.0} + l := linkFromProfile([]float64{120, 340}, 5.00049, p, true) + if l.ClearancePct != 999 || l.Verdict != "clear" || l.ObstructionM != 0 || l.DistanceKm != 5.000 { + t.Errorf("n=2 link: %+v", l) + } + if _, err := json.Marshal(l); err != nil { + t.Errorf("link not JSON-encodable: %v", err) + } + elev := make([]float64, 41) + for i := range elev { + elev[i] = 100.04 + } + l = linkFromProfile(elev, 3, losParams{FreqMHz: 869.618, KFactor: 4.0 / 3.0, AntennaAM: 25, AntennaBM: 25}, true) + if l.Verdict != "clear" || l.ClearancePct != 154.6 || l.WorstKm != 1.5 || len(l.ElevM) != 41 || l.ElevM[0] != 100 { + t.Errorf("flat link: %+v", l) + } + if l = linkFromProfile(elev, 3, p, false); l.ElevM != nil { + t.Error("ElevM set without withElev") + } + if l = linkFromProfile(nil, 3, p, true); l.Verdict != "blocked" { + t.Errorf("invalid input verdict %q", l.Verdict) + } +} + +func TestPlannerLOSProfileSamples(t *testing.T) { + cases := []struct { + d float64 + want int + }{{0, 64}, {1, 64}, {5.67, 64}, {5.76, 65}, {5.8, 66}, {9, 101}, {53.8, 599}, {54, 600}, {200, 600}, {math.NaN(), 64}} + for _, c := range cases { + if got := planProfileSamples(c.d); got != c.want { + t.Errorf("planProfileSamples(%v) = %d, want %d", c.d, got, c.want) + } + } +} + +func TestPlannerLOSDecimate(t *testing.T) { + in := make([]float64, 1000) + for i := range in { + in[i] = float64(i % 37) + } + in[500] = 9999 // lone ridge + in[999] = 7 + out := decimateProfile(in, 200) + if len(out) != 200 || out[0] != in[0] || out[199] != 7 { + t.Fatalf("len=%d first=%v last=%v", len(out), out[0], out[len(out)-1]) + } + mx := 0.0 + for _, v := range out { + mx = math.Max(mx, v) + } + if mx != 9999 { + t.Errorf("ridge lost: max %v", mx) + } + short := []float64{1, 2, 3} + if got := decimateProfile(short, 3); len(got) != 3 { + t.Error("short input changed") + } + if got := decimateProfile(in[:201], 200); len(got) != 200 { + t.Errorf("201->200 len %d", len(got)) + } + if got := decimateProfile(in, 3); len(got) != 3 { + t.Errorf("max=3 len %d", len(got)) + } +} + +type rampView struct{ minLon float64 } + +func (r rampView) ElevationAt(lat, lon float64) (float64, bool) { + if lon < r.minLon { + return 0, false + } + return lon * 10, true // metres per degree of longitude +} + +func TestPlannerLOSTerrainProfile(t *testing.T) { + a, b := geoPoint{0, 0}, geoPoint{0, 1} + prof, ok := sampleTerrainProfile(rampView{-1}, a, b, 11) + if !ok || len(prof) != 11 { + t.Fatalf("ok=%v len=%d", ok, len(prof)) + } + for i, v := range prof { + if want := float64(i); math.Abs(v-want) > 1e-6 { // 10 m/deg over 1 deg, 0.1 steps + t.Errorf("prof[%d]=%v want %v", i, v, want) + } + } + if _, ok := sampleTerrainProfile(rampView{0.5}, a, b, 11); ok { + t.Error("out-of-view returned ok") + } + if _, ok := sampleTerrainProfile(rampView{-1}, a, b, 1); ok { + t.Error("n=1 returned ok") + } +} + +func TestPlannerLOSGeoHelpers(t *testing.T) { + near := func(p, q geoPoint) bool { return math.Abs(p.Lat-q.Lat) <= 1e-9 && math.Abs(p.Lon-q.Lon) <= 1e-9 } + // Along the equator, evenly spaced in t. + for i, p := range greatCircleSamples(geoPoint{0, 0}, geoPoint{0, 90}, 5) { + if want := (geoPoint{0, 22.5 * float64(i)}); !near(p, want) { + t.Errorf("equator sample %d %+v, want %+v", i, p, want) + } + } + // Between two points on the 45th parallel the great circle bulges + // poleward: its midpoint is at atan(√2), not 45. + mid := greatCircleSamples(geoPoint{45, 0}, geoPoint{45, 90}, 3)[1] + if want := (geoPoint{math.Atan(math.Sqrt2) * 180 / math.Pi, 45}); !near(mid, want) { + t.Errorf("midpoint %+v, want %+v", mid, want) + } + // The ends are the inputs exactly, not trig round-trips. + a, b := geoPoint{37.123456789, -122.987654321}, geoPoint{36.5, -121.25} + if pts := greatCircleSamples(a, b, 64); len(pts) != 64 || pts[0] != a || pts[63] != b { + t.Errorf("ends %+v %+v of %d", pts[0], pts[len(pts)-1], len(pts)) + } + for _, p := range greatCircleSamples(geoPoint{3, 4}, geoPoint{3, 4}, 3) { + if p != (geoPoint{3, 4}) { + t.Errorf("same point %+v", p) + } + } + if d := geoDistKm(geoPoint{0, 0}, geoPoint{0, 90}); math.Abs(d-earthRadiusKm*math.Pi/2) > 1e-6 { + t.Errorf("dist %v", d) + } +} diff --git a/cmd/server/planner_search.go b/cmd/server/planner_search.go new file mode 100644 index 000000000..d90934c15 --- /dev/null +++ b/cmd/server/planner_search.go @@ -0,0 +1,1303 @@ +package main + +// Planner search: the repeater backbone plan (runCoveragePlan) and the +// single-relay search (runRelaySearch). +// +// Both are deterministic: single-threaded, no map iteration, and every sort +// is a total order (ties fall to an index). Every terrain link goes through +// planLinkEval, which samples the points sampleTerrainProfile samples and +// applies analyzeLOS's formulas in the same operand order, so a link the plan +// calls solid reads the same on /api/planner/profile. (Equal up to rounding: +// the compiler may fuse a multiply-add differently in the two copies, moving +// a sample by an ulp, ~1 nm.) + +import ( + "cmp" + "context" + "errors" + "fmt" + "math" + "slices" + "time" +) + +// planInputs is everything a coverage plan needs, snapshotted by the API +// layer outside any store lock. +type planInputs struct { + Area geoBBox // snapped + Nodes []plannerNode + Observed []plannerEdge + Truncated bool + Params PlannerPlanParams +} + +const ( + planGridKm = 1.0 // coverage candidate grid spacing + planPeakRadius = 2 // candidate = local maximum over a 5×5 window + planSiteSpacingKm = 2.0 // candidates keep this far from active nodes and chosen sites + planEdgesEnd = 0.4 // progress when the baseline edges are done + planCandsEnd = 0.75 // progress when the candidates are done + planSiteLinksOut = 12 // PlannerSite.Links cap + + relayGridKm = 0.5 + relayPeakRadius = 1 // 3×3 window + relayMaxOpen = 400 // open cells evaluated, highest first + relayMaxOptions = 5 // per list + relayDetour = 1.3 // d(A,R)+d(R,B) ≤ 1.3·max(D, relayMinBaseKm) + relayMinBaseKm = 1.0 + relayExpand = 0.3 // open grid: bbox(A,B) grown by 0.3·D ... + relayMinExpandKm = 2.0 // ... but at least 2 km + relaySpacingKm = 1.0 // open options keep this far from a better one + relayMinLegKm = 0.1 // a relay this close to A or B is the endpoint itself + relayGridEnd = 0.1 // progress when the open grid is sampled + + // relayWarnDirectNoTerrain: a sample of the direct path has no terrain, + // so Direct is not measured (Error no_terrain). + relayWarnDirectNoTerrain = "Direct link crosses missing terrain: not measured" + + // planGridMaxSide caps grid rows/cols. A 250 km coverage area (the + // largest maxAreaKm) at 1 km fits, and so does a 200 km relay leg's + // corridor (the largest maxLegKm: 320 km at 500 m is 641 cells, a little + // more east-west at high latitude). + planGridMaxSide = 720 + planCtxEvery = 16 // profiles between ctx checks (≤ ~1 ms of work) + planStride0 = 16 // first stride of the coarse-to-fine profile walk +) + +// ─── Backbone plan ───────────────────────────────────────────────────────── + +// runCoveragePlan computes the backbone plan. progress(frac) is called +// with 0..1 as stages complete. Must check ctx in its hot loops. +// +// Stages: baseline edges (observed, plus predicted pairs within range when +// Baseline is "predicted") → baseline graph and stats → candidate sites +// (1 km grid local maxima, plateaus thinned to one per 3 km, with ≥ 1 +// solid link) → greedy picks → response. +// Terrain without data (ElevationAt ok=false) is skipped, never read as 0 m: +// no candidate stands on it and no predicted edge or candidate link crosses +// it. An observed edge is radio evidence and stays, its clearance unknown (0). +// A cancelled ctx returns ctx.Err() within one ctx-check interval; invalid +// inputs return an error before any work. +func runCoveragePlan(ctx context.Context, v terrainView, in planInputs, progress func(frac float64)) (PlannerPlanResponse, error) { + return planCoverage(ctx, v, in, progress, nil) +} + +// planStageStats is what planCoverage spent per stage (benchmarks). +type planStageStats struct { + EdgesTime, CandsTime, GreedyTime, OutputTime time.Duration + Profiles, Peaks, Candidates, Sites int +} + +func planCoverage(ctx context.Context, v terrainView, in planInputs, progress func(float64), stats *planStageStats) (PlannerPlanResponse, error) { + if err := checkPlanInputs(v, in); err != nil { + return PlannerPlanResponse{}, err + } + if err := ctx.Err(); err != nil { + return PlannerPlanResponse{}, err + } + if progress == nil { + progress = func(float64) {} + } + s := newCoverageSearch(ctx, v, in, progress) + var st planStageStats + t := time.Now() + if err := s.baselineEdges(); err != nil { + return PlannerPlanResponse{}, err + } + s.baselineGraph() + st.EdgesTime = time.Since(t) + t = time.Now() + peaks, err := s.findCandidates() + if err != nil { + return PlannerPlanResponse{}, err + } + st.CandsTime = time.Since(t) + t = time.Now() + if err := s.greedy(); err != nil { + return PlannerPlanResponse{}, err + } + st.GreedyTime = time.Since(t) + t = time.Now() + resp, err := s.response() + if err != nil { + return PlannerPlanResponse{}, err + } + st.OutputTime = time.Since(t) + st.Profiles, st.Peaks, st.Candidates, st.Sites = s.ev.profiles, peaks, len(s.cands), len(s.picks) + if stats != nil { + *stats = st + } + progress(1) + return resp, nil +} + +// checkPlanInputs rejects what the API layer should never pass; the error +// names the field, never a value. Ranges are checked against the largest +// planner.maxLegKm an operator can set: the API layer enforces the one set. +func checkPlanInputs(v terrainView, in planInputs) error { + if v == nil { + return errors.New("planner: no terrain view") + } + a := in.Area + if !planCoordOK(a.S, a.W) || !planCoordOK(a.N, a.E) || a.S > a.N || a.W > a.E { + return errors.New("planner: invalid area") + } + if len(in.Nodes) > plannerMaxNodes { + return errors.New("planner: too many nodes") + } + for i := range in.Nodes { + if !planCoordOK(in.Nodes[i].Lat, in.Nodes[i].Lon) { + return errors.New("planner: invalid node position") + } + } + p := in.Params + switch { + case p.Sites < 0 || p.Sites > plannerMaxSites: + return errors.New("planner: invalid sites") + case !(p.RangeKm > 0 && p.RangeKm <= plannerLegKmMax): + return errors.New("planner: invalid range") + case !planHeightOK(p.NewAntennaM) || !planHeightOK(p.ExistingAntennaM): + return errors.New("planner: invalid antenna height") + case !planRadioOK(p.FrequencyMHz, p.KFactor): + return errors.New("planner: invalid radio parameters") + case !losFinite(p.MinClearance): + return errors.New("planner: invalid min clearance") + case p.Baseline != "predicted" && p.Baseline != "observed": + return errors.New("planner: invalid baseline") + } + return nil +} + +func planCoordOK(lat, lon float64) bool { + return plannerFiniteCoord(lat, lon) && lat >= -90 && lat <= 90 && lon >= -180 && lon <= 180 +} + +func planHeightOK(h float64) bool { return h >= 0 && !math.IsInf(h, 1) } + +// planRadioOK: the inputs analyzeLOS accepts (k = 0 means 4/3). +func planRadioOK(freqMHz, k float64) bool { + return freqMHz > 0 && losFinite(freqMHz) && k >= 0 && losFinite(k) +} + +// coverageSearch is one plan computation. Node vertices are 0..n-1 in the +// backbone graph; the site picked at step s is vertex n+s-1. +type coverageSearch struct { + ctx context.Context + in planInputs + p PlannerPlanParams + progress func(float64) + ev *planLinkEval + pts []geoPoint + active []bool // !Stale || IncludeStale + counted []bool // active && InArea + countFn func(int) bool + inRange planNear // RangeKm prefilter + spacing planNear // planSiteSpacingKm prefilter + + repeaters, staleExcluded int + + observed, solid, marginal []plannerEdge + g *backboneGraph // baseline, then + each pick + s0, cur backboneStats + // linked: the node has an edge in g (observed, solid or to a site). A + // counted node without one is what a pick can newly "reach". + linked []bool + cands []planCand + picks []planPick +} + +// planCand is a candidate site. links are its solid links to active nodes +// (peer = node index), siteLinks its solid links to chosen sites +// (peer = step); minClear is the lowest clearance over both. +type planCand struct { + idx int // grid index: stable identity and the last tie-break + pt geoPoint + elev float64 + links []planCandLink + siteLinks []planCandLink + minClear float64 + gone bool // picked, or within planSiteSpacingKm of a pick +} + +type planCandLink struct { + peer int + dist, clear float64 +} + +type planPick struct { + cand int // index into cands + gain planGain + reason string + before backboneStats + after backboneStats +} + +// planGain is a pick's lexicographic objective: components joined, then +// largest-component growth, then fragility removed, then repeaters reached. +type planGain struct{ comps, largest, frag, reach int } + +func (a planGain) compare(b planGain) int { + if c := cmp.Compare(a.comps, b.comps); c != 0 { + return c + } + if c := cmp.Compare(a.largest, b.largest); c != 0 { + return c + } + if c := cmp.Compare(a.frag, b.frag); c != 0 { + return c + } + return cmp.Compare(a.reach, b.reach) +} + +func newCoverageSearch(ctx context.Context, v terrainView, in planInputs, progress func(float64)) *coverageSearch { + n := len(in.Nodes) + p := in.Params + s := &coverageSearch{ + ctx: ctx, in: in, p: p, progress: progress, + ev: newPlanLinkEval(ctx, v, p.FrequencyMHz, p.KFactor), + pts: make([]geoPoint, n), + active: make([]bool, n), + counted: make([]bool, n), + linked: make([]bool, n), + } + maxAbsLat := math.Max(math.Abs(in.Area.S), math.Abs(in.Area.N)) + for i, nd := range in.Nodes { + s.pts[i] = geoPoint{nd.Lat, nd.Lon} + s.active[i] = !nd.Stale || p.IncludeStale + s.counted[i] = s.active[i] && nd.InArea + if s.counted[i] { + s.repeaters++ + } + if nd.InArea && !s.active[i] { + s.staleExcluded++ + } + maxAbsLat = math.Max(maxAbsLat, math.Abs(nd.Lat)) + } + s.countFn = func(i int) bool { return i < n && s.counted[i] } + s.inRange = newPlanNear(p.RangeKm, maxAbsLat) + s.spacing = newPlanNear(planSiteSpacingKm, maxAbsLat) + return s +} + +// baselineEdges: observed edges between active nodes (with their terrain +// clearance), then, for Baseline "predicted", every other active pair +// within range as solid or marginal. Pairs are canonical i b { + a, b = b, a + } + if a < 0 || b >= n || a == b || !s.active[a] || !s.active[b] || isObserved[a*n+b] { + continue + } + isObserved[a*n+b] = true + d := geoDistKm(s.pts[a], s.pts[b]) + pct := 0.0 // terrain unknown: a sample has no terrain + if c, ok := s.ev.clearance(s.pts[a], s.pts[b], d, he, he, math.Inf(-1)); ok { + pct = planPct(c) + } + if s.ev.err != nil { + return s.ev.err + } + s.observed = append(s.observed, plannerEdge{A: a, B: b, Class: "observed", DistanceKm: d, ClearancePct: pct}) + } + if !predicted { + return nil + } + for i := 0; i < n; i++ { + for j := i + 1; j < n; j++ { + if err := tick(); err != nil { + return err + } + if !s.active[i] || !s.active[j] || isObserved[i*n+j] || !s.inRange.maybe(s.pts[i], s.pts[j]) { + continue + } + d := geoDistKm(s.pts[i], s.pts[j]) + if d > s.p.RangeKm { + continue + } + c, ok := s.ev.clearance(s.pts[i], s.pts[j], d, he, he, 0) + if s.ev.err != nil { + return s.ev.err + } + switch { + case !ok: + case c >= s.p.MinClearance: + s.solid = append(s.solid, plannerEdge{A: i, B: j, Class: "solid", DistanceKm: d, ClearancePct: planPct(c)}) + default: + s.marginal = append(s.marginal, plannerEdge{A: i, B: j, Class: "marginal", DistanceKm: d, ClearancePct: planPct(c)}) + } + } + } + return nil +} + +// baselineGraph: only observed and solid edges connect the backbone. +func (s *coverageSearch) baselineGraph() { + edges := make([]plannerEdge, 0, len(s.observed)+len(s.solid)) + edges = append(append(edges, s.observed...), s.solid...) + for _, e := range edges { + s.linked[e.A], s.linked[e.B] = true, true + } + s.g = newBackboneGraph(len(s.pts), s.active, edges) + s.s0 = s.g.Stats(s.countFn) + s.cur = s.s0 +} + +// findCandidates fills s.cands (grid order) and returns the number of grid +// cells profiled: local maxima more than planSiteSpacingKm from every active +// node, plateaus thinned. +func (s *coverageSearch) findCandidates() (int, error) { + grid, err := newPlanGrid(s.ctx, s.ev.v, s.in.Area, planGridKm) + if err != nil { + return 0, err + } + peaks := grid.peaks(planPeakRadius) + eligible := peaks[:0] + for k, gi := range peaks { + if k%256 == 0 { + if err := s.ctx.Err(); err != nil { + return 0, err + } + } + if !s.nearActiveNode(grid.point(gi)) { + eligible = append(eligible, gi) + } + } + peaks = grid.thin(eligible, planPeakRadius) + hr, he := s.p.NewAntennaM, s.p.ExistingAntennaM + for k, gi := range peaks { + if err := s.ctx.Err(); err != nil { + return 0, err + } + s.progress(planEdgesEnd + (planCandsEnd-planEdgesEnd)*float64(k)/float64(len(peaks))) + pt := grid.point(gi) + var links []planCandLink + for j, q := range s.pts { + if !s.active[j] || !s.inRange.maybe(pt, q) { + continue + } + d := geoDistKm(pt, q) + if d > s.p.RangeKm { + continue + } + c, ok := s.ev.clearance(pt, q, d, hr, he, s.p.MinClearance) + if s.ev.err != nil { + return 0, s.ev.err + } + if ok { + links = append(links, planCandLink{peer: j, dist: d, clear: c}) + } + } + if len(links) == 0 { + continue + } + minC := math.Inf(1) + for _, l := range links { + minC = math.Min(minC, l.clear) + } + s.cands = append(s.cands, planCand{idx: gi, pt: pt, elev: grid.elev[gi], links: links, minClear: minC}) + } + s.capCandidates() + return len(peaks), nil +} + +func (s *coverageSearch) nearActiveNode(pt geoPoint) bool { + for j, q := range s.pts { + if s.active[j] && s.spacing.maybe(pt, q) && geoDistKm(pt, q) <= planSiteSpacingKm { + return true + } + } + return false +} + +// capCandidates keeps the plannerMaxCands best by (distinct baseline +// components linked, solid links, elevation), then restores grid order. +func (s *coverageSearch) capCandidates() { + if len(s.cands) <= plannerMaxCands { + return + } + comps := make([]int, len(s.cands)) + seen := make([]int, len(s.pts)) // ComponentOf ids are < n; stamp = k+1 + for k := range s.cands { + for _, l := range s.cands[k].links { + if c := s.s0.ComponentOf[l.peer]; c >= 0 && seen[c] != k+1 { + seen[c] = k + 1 + comps[k]++ + } + } + } + order := make([]int, len(s.cands)) + for k := range order { + order[k] = k + } + slices.SortFunc(order, func(x, y int) int { + a, b := &s.cands[x], &s.cands[y] + if c := cmp.Compare(comps[y], comps[x]); c != 0 { + return c + } + if c := cmp.Compare(len(b.links), len(a.links)); c != 0 { + return c + } + if c := cmp.Compare(b.elev, a.elev); c != 0 { + return c + } + return cmp.Compare(a.idx, b.idx) + }) + order = order[:plannerMaxCands] + slices.Sort(order) // grid order again + kept := make([]planCand, len(order)) + for k, o := range order { + kept[k] = s.cands[o] + } + s.cands = kept +} + +// greedy picks up to Params.Sites sites, each the candidate with the best +// planGain against the current graph (ties: higher min clearance, higher +// elevation, lower grid index), stopping when the best gain is not positive. +func (s *coverageSearch) greedy() error { + var peers []int + for step := 1; step <= s.p.Sites; step++ { + best := -1 + var bestGain planGain + var bestStats backboneStats + for k := range s.cands { + if k%32 == 0 { + if err := s.ctx.Err(); err != nil { + return err + } + frac := (float64(step-1) + float64(k)/float64(len(s.cands))) / float64(s.p.Sites) + s.progress(planCandsEnd + (1-planCandsEnd)*frac) + } + c := &s.cands[k] + if c.gone { + continue + } + peers = s.candPeers(c, peers[:0]) + gc := s.g.Clone() + gc.AddVertex(peers) + st := gc.Stats(s.countFn) + gain := planGain{ + comps: s.cur.Components - st.Components, + largest: st.Largest - s.cur.Largest, + frag: s.cur.Fragility - st.Fragility, + reach: s.reach(c), + } + if best < 0 || planCandBetter(gain, c, bestGain, &s.cands[best]) { + best, bestGain, bestStats = k, gain, st + } + } + if best < 0 || bestGain.compare(planGain{}) <= 0 { + break + } + if err := s.pick(best, step, bestGain, bestStats); err != nil { + return err + } + } + return nil +} + +func (s *coverageSearch) candPeers(c *planCand, peers []int) []int { + for _, l := range c.links { + peers = append(peers, l.peer) + } + for _, l := range c.siteLinks { + peers = append(peers, len(s.pts)+l.peer-1) + } + return peers +} + +// reach: counted nodes c links solidly that have no edge in the current +// graph. Nodes already on the backbone are not "reached" again, so a +// connected, redundant backbone yields no reach-only picks. +func (s *coverageSearch) reach(c *planCand) int { + r := 0 + for _, l := range c.links { + if s.counted[l.peer] && !s.linked[l.peer] { + r++ + } + } + return r +} + +func planCandBetter(g planGain, c *planCand, bg planGain, b *planCand) bool { + if x := g.compare(bg); x != 0 { + return x > 0 + } + if c.minClear != b.minClear { + return c.minClear > b.minClear + } + if c.elev != b.elev { + return c.elev > b.elev + } + return c.idx < b.idx +} + +// pick commits candidate k as site step: adds it to g, removes it and every +// candidate within planSiteSpacingKm, and links it to the rest in range. +func (s *coverageSearch) pick(k, step int, gain planGain, after backboneStats) error { + c := &s.cands[k] + s.g.AddVertex(s.candPeers(c, nil)) + reason := "reach" + switch { + case gain.comps > 0: + reason = "joins" + case gain.frag > 0 || after.CutVertices < s.cur.CutVertices: + reason = "redundancy" + } + s.picks = append(s.picks, planPick{cand: k, gain: gain, reason: reason, before: s.cur, after: after}) + s.cur = after + for _, l := range c.links { + s.linked[l.peer] = true + } + hr := s.p.NewAntennaM + for k2 := range s.cands { + o := &s.cands[k2] + if o.gone || k2 == k { + continue + } + if s.spacing.maybe(c.pt, o.pt) && geoDistKm(c.pt, o.pt) <= planSiteSpacingKm { + o.gone = true + continue + } + if !s.inRange.maybe(c.pt, o.pt) { + continue + } + d := geoDistKm(c.pt, o.pt) + if d > s.p.RangeKm { + continue + } + cl, ok := s.ev.clearance(c.pt, o.pt, d, hr, hr, s.p.MinClearance) + if s.ev.err != nil { + return s.ev.err + } + if ok { + o.siteLinks = append(o.siteLinks, planCandLink{peer: step, dist: d, clear: cl}) + o.minClear = math.Min(o.minClear, cl) + } + } + c.gone = true + return nil +} + +func (s *coverageSearch) summary(st backboneStats) PlannerSummary { + return PlannerSummary{ + Repeaters: s.repeaters, + Components: st.Components, + LargestComponent: st.Largest, + Isolated: st.Isolated, + CutVertices: st.CutVertices, + StaleExcluded: s.staleExcluded, + } +} + +func (s *coverageSearch) response() (PlannerPlanResponse, error) { + in := s.in + resp := PlannerPlanResponse{ + Area: geoBBoxJSON{S: in.Area.S, W: in.Area.W, N: in.Area.N, E: in.Area.E}, + Params: s.p, + Baseline: s.summary(s.s0), + Final: s.summary(s.cur), + Nodes: make([]PlannerNodeOut, len(in.Nodes)), + Sites: make([]PlannerSite, 0, len(s.picks)), + Warnings: []string{}, + Truncated: in.Truncated, + ComputedAt: time.Now().UTC(), + } + switch { + case s.s0.Components <= 1: + resp.Status = "connected" + case len(s.picks) > 0: + resp.Status = "improved" + default: + resp.Status = "no_gain" + } + for i, nd := range in.Nodes { + resp.Nodes[i] = PlannerNodeOut{ + PubKey: nd.PubKey, Name: nd.Name, Role: nd.Role, Lat: nd.Lat, Lon: nd.Lon, + Stale: nd.Stale, InArea: nd.InArea, Component: s.s0.ComponentOf[i], + } + } + var cut bool + resp.Edges, cut = planEdgesOut(s.observed, s.solid, s.marginal) + resp.Truncated = resp.Truncated || cut + for step, pk := range s.picks { + site, err := s.siteOut(step+1, pk) + if err != nil { + return PlannerPlanResponse{}, err + } + resp.Sites = append(resp.Sites, site) + } + if s.staleExcluded > 0 { + resp.Warnings = append(resp.Warnings, plannerCount(s.staleExcluded, "stale repeater", "stale repeaters")+" excluded") + } + if len(s.cands) == 0 { + resp.Warnings = append(resp.Warnings, "Area has no candidate high ground with a usable link") + } + return resp, nil +} + +// planEdgesOut: observed, then solid, then marginal, each by distance +// (ties by A, B), capped at plannerMaxEdgesOut. +func planEdgesOut(classes ...[]plannerEdge) ([]PlannerEdgeOut, bool) { + total := 0 + for _, es := range classes { + total += len(es) + } + out := make([]PlannerEdgeOut, 0, int(math.Min(float64(total), plannerMaxEdgesOut))) + for _, es := range classes { + es = slices.Clone(es) + slices.SortFunc(es, func(x, y plannerEdge) int { + if c := cmp.Compare(x.DistanceKm, y.DistanceKm); c != 0 { + return c + } + if c := cmp.Compare(x.A, y.A); c != 0 { + return c + } + return cmp.Compare(x.B, y.B) + }) + for _, e := range es { + if len(out) == plannerMaxEdgesOut { + return out, true + } + out = append(out, PlannerEdgeOut{ + A: e.A, B: e.B, Class: e.Class, + DistanceKm: losRound(e.DistanceKm, 1000), ClearancePct: e.ClearancePct, + }) + } + } + return out, false +} + +// siteOut renders a pick. Links: its solid node and earlier-site links plus +// marginal node links (profiled again here, ≤ n per site), best first. +func (s *coverageSearch) siteOut(step int, pk planPick) (PlannerSite, error) { + c := &s.cands[pk.cand] + type ranked struct { + link PlannerSiteLink + clear float64 + } + var links []ranked + isSolid := make([]bool, len(s.pts)) + var comps []int + for _, l := range c.links { + isSolid[l.peer] = true + comps = append(comps, s.s0.ComponentOf[l.peer]) + links = append(links, ranked{PlannerSiteLink{Node: l.peer, DistanceKm: losRound(l.dist, 1000), + ClearancePct: planPct(l.clear), Class: "solid"}, l.clear}) + } + for _, l := range c.siteLinks { + links = append(links, ranked{PlannerSiteLink{Node: -1, PeerStep: l.peer, DistanceKm: losRound(l.dist, 1000), + ClearancePct: planPct(l.clear), Class: "solid"}, l.clear}) + } + hr, he := s.p.NewAntennaM, s.p.ExistingAntennaM + for j, q := range s.pts { + if !s.active[j] || isSolid[j] || !s.inRange.maybe(c.pt, q) { + continue + } + d := geoDistKm(c.pt, q) + if d > s.p.RangeKm { + continue + } + cl, ok := s.ev.clearance(c.pt, q, d, hr, he, 0) + if s.ev.err != nil { + return PlannerSite{}, s.ev.err + } + if ok && cl < s.p.MinClearance { + links = append(links, ranked{PlannerSiteLink{Node: j, DistanceKm: losRound(d, 1000), + ClearancePct: planPct(cl), Class: "marginal"}, cl}) + } + } + slices.SortFunc(links, func(x, y ranked) int { + if c := cmp.Compare(y.clear, x.clear); c != 0 { + return c + } + if c := cmp.Compare(x.link.DistanceKm, y.link.DistanceKm); c != 0 { + return c + } + if c := cmp.Compare(x.link.Node, y.link.Node); c != 0 { + return c + } + return cmp.Compare(x.link.PeerStep, y.link.PeerStep) + }) + if len(links) > planSiteLinksOut { + links = links[:planSiteLinksOut] + } + out := make([]PlannerSiteLink, len(links)) + for i, l := range links { + out[i] = l.link + } + slices.Sort(comps) + comps = slices.Compact(comps) + if comps == nil { + comps = []int{} + } + return PlannerSite{ + Step: step, Lat: c.pt.Lat, Lon: c.pt.Lon, ElevM: losRound(c.elev, 10), AntennaM: hr, + Reason: pk.reason, + Gain: PlannerGain{ + ComponentsJoined: pk.before.Components - pk.after.Components, + CutVerticesRemoved: pk.before.CutVertices - pk.after.CutVertices, + RepeatersReached: pk.gain.reach, + }, + After: s.summary(pk.after), + Links: out, + JoinsComponents: comps, + }, nil +} + +// ─── Relay search ────────────────────────────────────────────────────────── + +// runRelaySearch finds the best single relay for A→B among known nodes and +// open terrain in the corridor. +// +// A relay R qualifies when both legs are within range, the detour +// d(A,R)+d(R,B) is at most 1.3·max(D, 1 km), and R is not within 100 m of +// A or B. Options rank by bottleneck clearance (the worse leg, as reported), +// then total distance, then node/grid index; up to 5 per list. Open cells +// are 500 m grid local maxima (3×3), the 400 highest evaluated, and none +// within 1 km of a better one. Options with a negative bottleneck are listed +// only when no option in either list reaches 0. +// +// Terrain without data is skipped, never read as 0 m: no relay stands on it +// and no option has a leg across it. A direct path across it is not +// measured (Error no_terrain, no verdict or profile) and gets +// relayWarnDirectNoTerrain. +func runRelaySearch(ctx context.Context, v terrainView, nodes []plannerNode, p PlannerRelayParams, progress func(frac float64)) (PlannerRelayResponse, error) { + if err := checkRelayParams(v, p); err != nil { + return PlannerRelayResponse{}, err + } + if err := ctx.Err(); err != nil { + return PlannerRelayResponse{}, err + } + if progress == nil { + progress = func(float64) {} + } + a, b := geoPoint{p.A.Lat, p.A.Lon}, geoPoint{p.B.Lat, p.B.Lon} + D := geoDistKm(a, b) + corridor := relayDetour * math.Max(D, relayMinBaseKm) + box := plannerExpandBBox(geoBBox{ + S: math.Min(a.Lat, b.Lat), W: math.Min(a.Lon, b.Lon), + N: math.Max(a.Lat, b.Lat), E: math.Max(a.Lon, b.Lon), + }, math.Max(relayExpand*D, relayMinExpandKm)) + grid, err := newPlanGrid(ctx, v, box, relayGridKm) + if err != nil { + return PlannerRelayResponse{}, err + } + progress(relayGridEnd) + + maxAbsLat := math.Max(math.Abs(box.S), math.Abs(box.N)) + for i := range nodes { + maxAbsLat = math.Max(maxAbsLat, math.Abs(nodes[i].Lat)) + } + near := newPlanNear(p.RangeKm, maxAbsLat) + fits := func(pt geoPoint) (dA, dB float64, ok bool) { + if !near.maybe(a, pt) || !near.maybe(pt, b) { + return 0, 0, false + } + dA, dB = geoDistKm(a, pt), geoDistKm(pt, b) + ok = dA <= p.RangeKm && dB <= p.RangeKm && dA+dB <= corridor && dA >= relayMinLegKm && dB >= relayMinLegKm + return dA, dB, ok + } + + var existing, open []relayCand + for i := range nodes { + nd := &nodes[i] + if nd.Stale || !planCoordOK(nd.Lat, nd.Lon) { + continue + } + pt := geoPoint{nd.Lat, nd.Lon} + dA, dB, ok := fits(pt) + if !ok { + continue + } + if e, okE := v.ElevationAt(pt.Lat, pt.Lon); okE && losFinite(e) { + existing = append(existing, relayCand{order: i, node: i, pt: pt, elev: e, dA: dA, dB: dB}) + } + } + for _, gi := range grid.peaks(relayPeakRadius) { + pt := grid.point(gi) + if dA, dB, ok := fits(pt); ok { + open = append(open, relayCand{order: gi, node: -1, pt: pt, elev: grid.elev[gi], dA: dA, dB: dB}) + } + } + // Highest first; on a plateau, the shortest detour. + slices.SortFunc(open, func(x, y relayCand) int { + if c := cmp.Compare(y.elev, x.elev); c != 0 { + return c + } + if c := cmp.Compare(x.dA+x.dB, y.dA+y.dB); c != 0 { + return c + } + return cmp.Compare(x.order, y.order) + }) + if len(open) > relayMaxOpen { + open = open[:relayMaxOpen] + } + + ev := newPlanLinkEval(ctx, v, p.FrequencyMHz, p.KFactor) + total, done := 2*(len(existing)+len(open)), 0 + rank := func(list []relayCand, hR float64) ([]relayCand, error) { + kept := list[:0] + for _, c := range list { + ca, okA := ev.clearance(a, c.pt, c.dA, p.AntennaAM, hR, math.Inf(-1)) + cb, okB := ev.clearance(c.pt, b, c.dB, hR, p.AntennaBM, math.Inf(-1)) + if ev.err != nil { + return nil, ev.err + } + if done += 2; done%64 == 0 { + progress(relayGridEnd + (1-relayGridEnd)*float64(done)/float64(total)) + } + if okA && okB { // a leg over missing terrain says nothing + c.pct = math.Min(planPct(ca), planPct(cb)) + kept = append(kept, c) + } + } + slices.SortFunc(kept, relayCandCompare) + return kept, nil + } + if existing, err = rank(existing, p.ExistingAntennaM); err != nil { + return PlannerRelayResponse{}, err + } + if open, err = rank(open, p.RelayAntennaM); err != nil { + return PlannerRelayResponse{}, err + } + if len(existing) > relayMaxOptions { + existing = existing[:relayMaxOptions] + } + open = relaySpread(open) + // Lists are sorted, so a list has a usable option iff its head does. + if (len(existing) > 0 && existing[0].pct >= 0) || (len(open) > 0 && open[0].pct >= 0) { + existing, open = relayUsable(existing), relayUsable(open) + } + + lp := losParams{FreqMHz: p.FrequencyMHz, KFactor: p.KFactor} + resp := PlannerRelayResponse{ + Direct: relayLink(v, a, b, D, lp, p.AntennaAM, p.AntennaBM, true), + Existing: relayOptions(v, nodes, existing, a, b, lp, p, "existing", p.ExistingAntennaM), + Open: relayOptions(v, nodes, open, a, b, lp, p, "open", p.RelayAntennaM), + Params: p, + Warnings: []string{}, + } + if resp.Direct.Error != "" { + resp.Warnings = append(resp.Warnings, relayWarnDirectNoTerrain) + } + best := math.Inf(-1) + for _, list := range [][]PlannerRelayOption{resp.Existing, resp.Open} { + if len(list) > 0 { + best = math.Max(best, list[0].BottleneckPct) + } + } + if best < plannerMinClearance*100 { + resp.Warnings = append(resp.Warnings, "No relay gives a clear first Fresnel zone") + } + progress(1) + return resp, nil +} + +// checkRelayParams rejects what the API layer should never pass. The leg and +// range are checked against the largest planner.maxLegKm an operator can +// set (planGridMaxSide fits its corridor): the API layer enforces the one +// set. +func checkRelayParams(v terrainView, p PlannerRelayParams) error { + if v == nil { + return errors.New("planner: no terrain view") + } + switch { + case !planCoordOK(p.A.Lat, p.A.Lon) || !planCoordOK(p.B.Lat, p.B.Lon): + return errors.New("planner: invalid endpoint") + case !(haversineKm(p.A.Lat, p.A.Lon, p.B.Lat, p.B.Lon) <= plannerLegKmMax): + return errors.New("planner: leg too long") + case !(p.RangeKm > 0 && p.RangeKm <= plannerLegKmMax): + return errors.New("planner: invalid range") + case !planHeightOK(p.AntennaAM) || !planHeightOK(p.AntennaBM) || + !planHeightOK(p.RelayAntennaM) || !planHeightOK(p.ExistingAntennaM): + return errors.New("planner: invalid antenna height") + case !planRadioOK(p.FrequencyMHz, p.KFactor): + return errors.New("planner: invalid radio parameters") + } + return nil +} + +// relayCand: order is the node index (existing) or grid index (open); +// pct is the bottleneck as PlannerRelayOption.BottleneckPct reports it. +type relayCand struct { + order, node int // node −1 for open terrain + pt geoPoint + elev float64 + dA, dB float64 + pct float64 +} + +func relayCandCompare(x, y relayCand) int { + if c := cmp.Compare(y.pct, x.pct); c != 0 { + return c + } + if c := cmp.Compare(x.dA+x.dB, y.dA+y.dB); c != 0 { + return c + } + return cmp.Compare(x.order, y.order) +} + +// relaySpread walks ranked open cells and keeps those more than +// relaySpacingKm from every option already kept, up to relayMaxOptions. +func relaySpread(ranked []relayCand) []relayCand { + var out []relayCand + for _, c := range ranked { + clash := false + for _, k := range out { + if geoDistKm(c.pt, k.pt) <= relaySpacingKm { + clash = true + break + } + } + if !clash { + if out = append(out, c); len(out) == relayMaxOptions { + break + } + } + } + return out +} + +func relayUsable(list []relayCand) []relayCand { + return slices.DeleteFunc(list, func(c relayCand) bool { return c.pct < 0 }) +} + +// relayLink is a reported leg: the shared LOS summary, with its profile when +// withElev. A leg with a sample that has no terrain is not measured: Error +// no_terrain, no verdict and no profile, never a verdict read from 0 m. +func relayLink(v terrainView, a, b geoPoint, d float64, lp losParams, ha, hb float64, withElev bool) PlannerLink { + lp.AntennaAM, lp.AntennaBM = ha, hb + elev, ok := sampleTerrainProfile(v, a, b, planProfileSamples(d)) + if !ok { + return PlannerLink{DistanceKm: losRound(math.Max(d, 0), 1000), Error: plannerErrNoTerrain} + } + return linkFromProfile(elev, d, lp, withElev) +} + +func relayOptions(v terrainView, nodes []plannerNode, list []relayCand, a, b geoPoint, lp losParams, + p PlannerRelayParams, kind string, hR float64) []PlannerRelayOption { + out := make([]PlannerRelayOption, 0, len(list)) + for _, c := range list { + legA := relayLink(v, a, c.pt, c.dA, lp, p.AntennaAM, hR, true) + legB := relayLink(v, c.pt, b, c.dB, lp, hR, p.AntennaBM, true) + if legA.Error != "" || legB.Error != "" { + // The search measured both legs, so only an interior sample an + // ulp across the edge of a tile without data gets here (planArc + // vs greatCircleSamples). An unmeasured leg is never offered. + continue + } + o := PlannerRelayOption{ + Kind: kind, Lat: c.pt.Lat, Lon: c.pt.Lon, ElevM: losRound(c.elev, 10), AntennaM: hR, + LegA: legA, LegB: legB, + } + o.BottleneckPct = math.Min(o.LegA.ClearancePct, o.LegB.ClearancePct) + if c.node >= 0 { + o.PubKey, o.Name = nodes[c.node].PubKey, nodes[c.node].Name + } + out = append(out, o) + } + // The legs are recomputed from the same samples, so this is a no-op + // unless rounding disagrees; it keeps the list ordered as reported. + slices.SortStableFunc(out, func(x, y PlannerRelayOption) int { return cmp.Compare(y.BottleneckPct, x.BottleneckPct) }) + return out +} + +// ─── Shared terrain machinery ────────────────────────────────────────────── + +// planPct is PlannerLink.ClearancePct for clearance c (linkFromProfile's +// rounding; +Inf, no interior sample, reads 999). +func planPct(c float64) float64 { + if math.IsInf(c, 1) { + return 999 + } + return losRound(c*100, 10) +} + +// planLinkEval profiles links without allocating. Not safe for concurrent +// use; each search owns one. +type planLinkEval struct { + ctx context.Context + v terrainView + freq float64 + bulgeDen float64 // 2·k·R with k defaulted as analyzeLOS does + profiles int + err error // ctx.Err() once seen; every later call fails fast +} + +func newPlanLinkEval(ctx context.Context, v terrainView, freqMHz, kFactor float64) *planLinkEval { + k := kFactor + if k == 0 { + k = 4.0 / 3.0 + } + return &planLinkEval{ctx: ctx, v: v, freq: freqMHz, bulgeDen: 2 * k * earthRadiusKm} +} + +// clearance returns the worst first-Fresnel clearance of a→b with antennas +// ha, hb metres above ground: analyzeLOS(sampleTerrainProfile(v, a, b, +// planProfileSamples(distKm)), distKm, …).Clearance, with distKm = +// geoDistKm(a, b). Interior samples are visited coarse-to-fine (stride 16, +// then the midpoints between) so an obstruction is usually met early, and +// the walk stops at the first sample below floor: ok=false. floor = −Inf +// evaluates every sample. ok=false also means a sample has no terrain +// (outside the view, or a tile without data: never read as 0 m) or ctx was +// cancelled (e.err is then set). +func (e *planLinkEval) clearance(a, b geoPoint, distKm, ha, hb, floor float64) (float64, bool) { + worst, _, ok := e.clearanceWalk(a, b, distKm, ha, hb, floor, 0, false) + return worst, ok +} + +// clearanceWalk is the walk behind clearance. With two it also returns +// worst2, the worst clearance of the same path with the receiver hb2 metres +// above ground, from the same samples: the elevation lookups and the +// great-circle trigonometry, which dominate, are paid once. floor applies to +// hb only, so a caller that wants worst2 over every sample passes −Inf. +func (e *planLinkEval) clearanceWalk(a, b geoPoint, distKm, ha, hb, floor, hb2 float64, two bool) (worst, worst2 float64, ok bool) { + if e.err != nil { + return 0, 0, false + } + if e.profiles%planCtxEvery == 0 { + if err := e.ctx.Err(); err != nil { + e.err = err + return 0, 0, false + } + } + e.profiles++ + eA, okA := e.v.ElevationAt(a.Lat, a.Lon) + eB, okB := e.v.ElevationAt(b.Lat, b.Lon) + if !okA || !okB || !losFinite(eA) || !losFinite(eB) { + return 0, 0, false + } + n := planProfileSamples(distKm) + arc := newPlanArc(a, b, distKm) + D := distKm + if !losFinite(D) || D < 0.001 { + D = 0.001 + } + // Below, every expression keeps analyzeLOS's operand order; only loop + // invariants are hoisted. + last := float64(n - 1) + fDen := D * e.freq / 1000 + yA, yB, yB2 := eA+ha, eB+hb, eB+hb2 + worst, worst2 = math.Inf(1), math.Inf(1) + for s := planStride0; s >= 1; s /= 2 { + i, step := s, 2*s // odd multiples of s: the points the coarser passes skipped + if s == planStride0 { + step = s + } + for ; i <= n-2; i += step { + t := float64(i) / last + lat, lon := arc.at(t) + el, ok := e.v.ElevationAt(lat, lon) + if !ok || !losFinite(el) { + return 0, 0, false + } + d := t * D + tm := el + d*(D-d)/e.bulgeDen*1000 + f1 := 17.32 * math.Sqrt(math.Max(d*(D-d), 1e-9)/fDen) + if two { + if c := (yA + (yB2-yA)*t - tm) / f1; c < worst2 { + worst2 = c + } + } + los := yA + (yB-yA)*t + if c := (los - tm) / f1; c < worst { + if worst = c; worst < floor { + return worst, worst2, false + } + } + } + } + return worst, worst2, true +} + +// planArc is greatCircleSamples for one point at a time: the same formula +// and operand order, with the per-leg trigonometry hoisted (equal to an ulp). +type planArc struct { + a geoPoint + same bool + d, sd float64 + cp1, sp1, cl1, sl1, cp2, sp2, cl2, sl2 float64 +} + +func newPlanArc(a, b geoPoint, distKm float64) planArc { + p1, l1 := a.Lat*math.Pi/180, a.Lon*math.Pi/180 + p2, l2 := b.Lat*math.Pi/180, b.Lon*math.Pi/180 + d := distKm / earthRadiusKm + if d < geoSamePointRadians { + return planArc{a: a, same: true} + } + return planArc{ + a: a, d: d, sd: math.Sin(d), + cp1: math.Cos(p1), sp1: math.Sin(p1), cl1: math.Cos(l1), sl1: math.Sin(l1), + cp2: math.Cos(p2), sp2: math.Sin(p2), cl2: math.Cos(l2), sl2: math.Sin(l2), + } +} + +// at is the point at fraction t (0 < t < 1; the ends are exact elsewhere). +func (r *planArc) at(t float64) (lat, lon float64) { + if r.same { + return r.a.Lat, r.a.Lon + } + A := math.Sin((1-t)*r.d) / r.sd + B := math.Sin(t*r.d) / r.sd + x := A*r.cp1*r.cl1 + B*r.cp2*r.cl2 + y := A*r.cp1*r.sl1 + B*r.cp2*r.sl2 + z := A*r.sp1 + B*r.sp2 + return math.Atan2(z, math.Hypot(x, y)) * 180 / math.Pi, math.Atan2(y, x) * 180 / math.Pi +} + +// planNear is a conservative degree-box prefilter for "within km": it +// never rejects a pair whose haversine distance is ≤ km when neither point +// is further from the equator than maxAbsLat. From the haversine formula, +// hav(d) ≥ hav(Δφ) and hav(d) ≥ cos²(maxAbsLat)·hav(Δλ). +type planNear struct{ latLim, lonLim float64 } + +func newPlanNear(km, maxAbsLat float64) planNear { + const slack = 1 + 1e-9 + r := km / earthRadiusKm // radians; haversineKm uses the same radius + p := planNear{latLim: r * 180 / math.Pi * slack, lonLim: 360} + if c := math.Cos(maxAbsLat * math.Pi / 180); c > 0 { + if q := math.Sin(r/2) / c; q < 1 { + p.lonLim = 2 * math.Asin(q) * 180 / math.Pi * slack + } + } + return p +} + +func (p planNear) maybe(a, b geoPoint) bool { + if math.Abs(a.Lat-b.Lat) > p.latLim { + return false + } + dl := math.Abs(a.Lon - b.Lon) + if dl > 180 { + dl = 360 - dl + } + return dl <= p.lonLim +} + +// planGrid samples terrain on a regular grid over a bbox: stepKm apart +// north–south and, at the box's middle latitude, east–west; centred in the +// box. Points are rounded to 5 decimals (what the API reports) and sampled +// there, so a reported site reproduces exactly. +type planGrid struct { + rows, cols int + lat, lon []float64 // per row, per column + elev []float64 // row-major + ok []bool // the view had terrain there +} + +func newPlanGrid(ctx context.Context, v terrainView, b geoBBox, stepKm float64) (*planGrid, error) { + dLat := stepKm / plannerKmPerDeg + dLon := dLat / math.Max(math.Cos((b.S+b.N)/2*math.Pi/180), 0.01) + rows := int(math.Floor((b.N-b.S)/dLat+1e-9)) + 1 + cols := int(math.Floor((b.E-b.W)/dLon+1e-9)) + 1 + if rows < 1 || cols < 1 || rows > planGridMaxSide || cols > planGridMaxSide { + return nil, errors.New("planner: search area too large") + } + g := &planGrid{ + rows: rows, cols: cols, + lat: make([]float64, rows), lon: make([]float64, cols), + elev: make([]float64, rows*cols), ok: make([]bool, rows*cols), + } + lat0 := b.S + ((b.N-b.S)-float64(rows-1)*dLat)/2 + lon0 := b.W + ((b.E-b.W)-float64(cols-1)*dLon)/2 + for r := range g.lat { + g.lat[r] = losRound(lat0+float64(r)*dLat, 1e5) + } + for c := range g.lon { + g.lon[c] = losRound(lon0+float64(c)*dLon, 1e5) + } + for r := 0; r < rows; r++ { + if err := ctx.Err(); err != nil { + return nil, err + } + for c := 0; c < cols; c++ { + if e, ok := v.ElevationAt(g.lat[r], g.lon[c]); ok && losFinite(e) { + g.elev[r*cols+c], g.ok[r*cols+c] = e, true + } + } + } + return g, nil +} + +func (g *planGrid) point(i int) geoPoint { return geoPoint{g.lat[i/g.cols], g.lon[i%g.cols]} } + +// peaks returns, in grid order, the valid cells at least as high as every +// valid cell within radius (a (2·radius+1)² window, clipped at the edges). +// Every cell of a plateau qualifies. +func (g *planGrid) peaks(radius int) []int { + var out []int + for r := 0; r < g.rows; r++ { + for c := 0; c < g.cols; c++ { + i := r*g.cols + c + if g.ok[i] && !g.window(r, c, radius, func(j int) bool { return g.ok[j] && g.elev[j] > g.elev[i] }) { + out = append(out, i) + } + } + } + return out +} + +// thin walks peaks (grid order) and drops each one that has an already kept +// peak in its window. Two peaks in each other's window are necessarily equal, +// so this thins plateaus only, to one cell per (radius+1)² (every 3 km for +// the plan), and never drops an isolated peak. It bounds the plan on flat +// ground or sea, where every 1 km cell would otherwise be profiled to every +// node in range (14.9 s → 1.9 s with 100 m masts, BenchmarkCoveragePlanMax). +func (g *planGrid) thin(peaks []int, radius int) []int { + kept := make([]bool, len(g.elev)) + out := peaks[:0:0] + for _, i := range peaks { + if !g.window(i/g.cols, i%g.cols, radius, func(j int) bool { return kept[j] }) { + kept[i] = true + out = append(out, i) + } + } + return out +} + +// window reports whether hit holds for any cell within radius of (r, c). +func (g *planGrid) window(r, c, radius int, hit func(j int) bool) bool { + for rr := r - radius; rr <= r+radius; rr++ { + if rr < 0 || rr >= g.rows { + continue + } + for cc := c - radius; cc <= c+radius; cc++ { + if cc >= 0 && cc < g.cols && hit(rr*g.cols+cc) { + return true + } + } + } + return false +} + +// plannerCount renders "1 stale repeater" / "3 stale repeaters". +func plannerCount(n int, one, many string) string { + if n == 1 { + return "1 " + one + } + return fmt.Sprintf("%d %s", n, many) +} diff --git a/cmd/server/planner_search_test.go b/cmd/server/planner_search_test.go new file mode 100644 index 000000000..daf623d03 --- /dev/null +++ b/cmd/server/planner_search_test.go @@ -0,0 +1,1382 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "math" + "math/rand/v2" + "slices" + "strings" + "sync" + "testing" + "time" +) + +// ─── Synthetic terrain ───────────────────────────────────────────────────── + +// Test geometry is in km east (x) / north (y) of a fixed origin. +const ( + ptLat0 = 37.0 + ptLon0 = -100.0 +) + +var ptCos0 = math.Cos(ptLat0 * math.Pi / 180) + +func ptGeo(x, y float64) geoPoint { + return geoPoint{Lat: ptLat0 + y/plannerKmPerDeg, Lon: ptLon0 + x/(plannerKmPerDeg*ptCos0)} +} + +func ptXY(p geoPoint) (x, y float64) { + return (p.Lon - ptLon0) * plannerKmPerDeg * ptCos0, (p.Lat - ptLat0) * plannerKmPerDeg +} + +// ptBumps is a flat base plus Gaussian bumps (h may be negative: a +// pit). sy = 1e6 makes a ridge running north–south. +type ptBumps struct { + base float64 + bumps []ptBump +} + +type ptBump struct{ x, y, h, sx, sy float64 } + +func (t *ptBumps) ElevationAt(lat, lon float64) (float64, bool) { + x, y := ptXY(geoPoint{lat, lon}) + e := t.base + for _, b := range t.bumps { + dx, dy := (x-b.x)/b.sx, (y-b.y)/b.sy + e += b.h * math.Exp(-(dx*dx+dy*dy)/2) + } + return e, true +} + +// ptWaves: cheap, hilly, many local maxima. +type ptWaves struct{} + +func (ptWaves) ElevationAt(lat, lon float64) (float64, bool) { + x, y := ptXY(geoPoint{lat, lon}) + return 300 + 140*math.Sin(x/3.1)*math.Cos(y/2.3) + 60*math.Sin(x/1.3+y/0.9) + 20*math.Cos(x/0.45-y/0.6), true +} + +func ptNode(name string, x, y float64) plannerNode { + p := ptGeo(x, y) + return plannerNode{PubKey: "pk-" + name, Name: name, Role: "repeater", Lat: p.Lat, Lon: p.Lon, InArea: true} +} + +func ptArea(x0, y0, x1, y1 float64) geoBBox { + sw, ne := ptGeo(x0, y0), ptGeo(x1, y1) + return geoBBox{S: sw.Lat, W: sw.Lon, N: ne.Lat, E: ne.Lon} +} + +func ptParams() PlannerPlanParams { + return PlannerPlanParams{ + Sites: 3, RangeKm: 30, NewAntennaM: 10, ExistingAntennaM: 30, Baseline: "predicted", + FrequencyMHz: 869.525, KFactor: 4.0 / 3.0, MinClearance: plannerMinClearance, + } +} + +func ptPlan(t *testing.T, v terrainView, in planInputs) PlannerPlanResponse { + t.Helper() + resp, err := runCoveragePlan(context.Background(), v, in, nil) + if err != nil { + t.Fatalf("runCoveragePlan: %v", err) + } + return resp +} + +// ─── Scenarios ───────────────────────────────────────────────────────────── + +// ptTwoClusterCase: two 3-node clusters 30+ km apart behind two parallel +// north–south ridges (x = ±4 km, 500 m). Only the summit between them +// (0, 0, 800 m) sees over both ridges. +func ptTwoClusterCase() (terrainView, planInputs) { + v := &ptBumps{base: 100, bumps: []ptBump{ + {x: -4, h: 400, sx: 0.8, sy: 1e6}, + {x: 4, h: 400, sx: 0.8, sy: 1e6}, + {x: 0, y: 0, h: 700, sx: 1.2, sy: 1.2}, + }} + nodes := []plannerNode{ + ptNode("w1", -16, -3), ptNode("w2", -15, 3), ptNode("w3", -19, 0), + ptNode("e1", 16, -3), ptNode("e2", 15, 3), ptNode("e3", 19, 0), + } + p := ptParams() + p.RangeKm = 40 + return v, planInputs{Area: ptArea(-22, -8, 22, 8), Nodes: nodes, Params: p} +} + +func TestCoveragePlanJoinsClustersAtSummit(t *testing.T) { + v, in := ptTwoClusterCase() + resp := ptPlan(t, v, in) + if resp.Baseline.Components != 2 || resp.Baseline.Repeaters != 6 { + t.Fatalf("baseline %+v, want 2 components of 6 repeaters", resp.Baseline) + } + if resp.Status != "improved" { + t.Errorf("status %q, want improved", resp.Status) + } + if len(resp.Sites) == 0 { + t.Fatal("no sites") + } + s := resp.Sites[0] + if d := geoDistKm(geoPoint{s.Lat, s.Lon}, ptGeo(0, 0)); d > 1 { + t.Errorf("first site %.2f km from the summit (%v,%v)", d, s.Lat, s.Lon) + } + if s.Step != 1 || s.Reason != "joins" || s.Gain.ComponentsJoined != 1 || s.After.Components != 1 { + t.Errorf("site 1 = step %d reason %q gain %+v after %+v", s.Step, s.Reason, s.Gain, s.After) + } + if !slices.Equal(s.JoinsComponents, []int{0, 1}) { + t.Errorf("joins_components %v, want [0 1]", s.JoinsComponents) + } + if s.AntennaM != in.Params.NewAntennaM || s.ElevM < 700 { + t.Errorf("antenna %v elev %v", s.AntennaM, s.ElevM) + } + if len(s.Links) == 0 || len(s.Links) > planSiteLinksOut { + t.Fatalf("links %d", len(s.Links)) + } + sides := map[byte]bool{} + for i, l := range s.Links { + if l.Class == "solid" && l.Node >= 0 { + sides[resp.Nodes[l.Node].Name[0]] = true + } + if i > 0 && l.ClearancePct > s.Links[i-1].ClearancePct { + t.Errorf("links not sorted by clearance: %+v", s.Links) + } + } + if !sides['w'] || !sides['e'] { + t.Errorf("summit links do not reach both clusters: %+v", s.Links) + } + // The summit is the only joining site; nothing else adds anything. + if len(resp.Sites) != 1 || resp.Final.Components != 1 { + t.Errorf("sites %d final %+v, want exactly the summit", len(resp.Sites), resp.Final) + } + // Baseline components: west (indices 0-2) is id 0, east id 1. + for i, n := range resp.Nodes { + if want := i / 3; n.Component != want { + t.Errorf("node %s component %d, want %d", n.Name, n.Component, want) + } + } + for _, e := range resp.Edges { + if e.Class == "solid" && resp.Nodes[e.A].Name[0] != resp.Nodes[e.B].Name[0] { + t.Errorf("solid edge across the ridges: %+v", e) + } + } +} + +// ptChainCase: a-b-c with a hill between a and c, so a–c is blocked and b is +// a cut vertex; the hilltop sees all three. +func ptChainCase() (terrainView, planInputs) { + v := &ptBumps{base: 100, bumps: []ptBump{{x: 0, y: 0, h: 250, sx: 1, sy: 1}}} + nodes := []plannerNode{ptNode("a", -6, 0), ptNode("b", 0, 6), ptNode("c", 6, 0)} + p := ptParams() + p.ExistingAntennaM, p.RangeKm = 25, 20 + return v, planInputs{Area: ptArea(-10, -10, 10, 10), Nodes: nodes, Params: p} +} + +func TestCoveragePlanConnectedChainGetsRedundancy(t *testing.T) { + v, in := ptChainCase() + resp := ptPlan(t, v, in) + if resp.Status != "connected" || resp.Baseline.Components != 1 || resp.Baseline.CutVertices != 1 { + t.Fatalf("status %q baseline %+v, want connected with 1 cut vertex", resp.Status, resp.Baseline) + } + if len(resp.Sites) == 0 { + t.Fatal("no redundancy pick") + } + s := resp.Sites[0] + if s.Reason != "redundancy" || s.Gain.CutVerticesRemoved != 1 || s.After.CutVertices != 0 || s.Gain.ComponentsJoined != 0 { + t.Errorf("site 1 reason %q gain %+v after %+v", s.Reason, s.Gain, s.After) + } + // Fragility is not in the summary; recompute it from the graph. + g := newBackboneGraph(3, nil, gEdges([2]int{0, 1}, [2]int{1, 2})) + before := g.Stats(nil).Fragility + var peers []int + for _, l := range s.Links { + if l.Class == "solid" && l.Node >= 0 { + peers = append(peers, l.Node) + } + } + g.AddVertex(peers) + if after := g.Stats(func(i int) bool { return i < 3 }).Fragility; after >= before { + t.Errorf("fragility %d -> %d, want a decrease", before, after) + } + if len(resp.Sites) != 1 { + t.Errorf("%d sites; after the cycle closes nothing should gain", len(resp.Sites)) + } +} + +func ptFlatClusterCase() (terrainView, planInputs) { + nodes := []plannerNode{ + ptNode("a", 0, 0), ptNode("b", 3, 0), ptNode("c", 0, 3), ptNode("d", 3, 3), ptNode("e", 1.5, 1.5), + } + p := ptParams() + p.RangeKm = 20 + return &ptBumps{base: 200}, planInputs{Area: ptArea(-10, -10, 13, 13), Nodes: nodes, Params: p} +} + +func TestCoveragePlanFullMeshNeedsNothing(t *testing.T) { + v, in := ptFlatClusterCase() + resp := ptPlan(t, v, in) + if resp.Status != "connected" || resp.Baseline.Components != 1 || resp.Baseline.CutVertices != 0 { + t.Fatalf("status %q baseline %+v", resp.Status, resp.Baseline) + } + if n := len(resp.Edges); n != 10 { + t.Errorf("%d edges, want all 10 pairs solid", n) + } + if len(resp.Sites) != 0 { + t.Errorf("sites %+v, want none", resp.Sites) + } + // Candidates did exist; they just add nothing. + for _, w := range resp.Warnings { + if strings.Contains(w, "candidate") { + t.Errorf("unexpected warning %q", w) + } + } + if resp.Final != resp.Baseline { + t.Errorf("final %+v != baseline %+v", resp.Final, resp.Baseline) + } +} + +func TestCoveragePlanBaselineObservedVsPredicted(t *testing.T) { + v := &ptBumps{base: 200} + nodes := []plannerNode{ptNode("a", 0, 0), ptNode("b", 3, 0), ptNode("c", 6, 0)} + in := planInputs{Area: ptArea(-1, -1, 7, 1), Nodes: nodes, Params: ptParams(), + Observed: []plannerEdge{{A: 1, B: 0, Class: "observed"}}} + in.Params.Sites = 0 + + pred := ptPlan(t, v, in) + in.Params.Baseline = "observed" + obs := ptPlan(t, v, in) + + if pred.Baseline.Components != 1 || obs.Baseline.Components != 2 { + t.Errorf("components predicted %d observed %d, want 1 and 2", pred.Baseline.Components, obs.Baseline.Components) + } + if len(obs.Edges) != 1 || obs.Edges[0].Class != "observed" || obs.Edges[0].A != 0 || obs.Edges[0].B != 1 { + t.Errorf("observed-mode edges %+v", obs.Edges) + } + if obs.Edges[0].ClearancePct < 60 { + t.Errorf("observed edge terrain clearance %v not recorded", obs.Edges[0].ClearancePct) + } + var classes []string + for _, e := range pred.Edges { + classes = append(classes, e.Class) + } + if !slices.Equal(classes, []string{"observed", "solid", "solid"}) { + t.Errorf("predicted-mode classes %v", classes) + } + if pred.Edges[1].DistanceKm > pred.Edges[2].DistanceKm { + t.Errorf("solid edges not by distance: %+v", pred.Edges) + } + if obs.Nodes[2].Component != 1 || pred.Nodes[2].Component != 0 { + t.Errorf("node c component observed %d predicted %d", obs.Nodes[2].Component, pred.Nodes[2].Component) + } +} + +func TestCoveragePlanStaleExclusion(t *testing.T) { + v := &ptBumps{base: 200} + stale, margin := ptNode("s", 0, 3), ptNode("m", 9, 0) + stale.Stale, margin.Stale, margin.InArea = true, true, false + in := planInputs{ + Area: ptArea(-5, -5, 5, 5), + Nodes: []plannerNode{ptNode("a", 0, 0), ptNode("b", 3, 0), stale, margin}, + Observed: []plannerEdge{{A: 0, B: 2, Class: "observed"}}, + Params: ptParams(), + } + in.Params.Sites = 0 + + resp := ptPlan(t, v, in) + if resp.Baseline.Repeaters != 2 || resp.Baseline.StaleExcluded != 1 || resp.Final.StaleExcluded != 1 { + t.Errorf("baseline %+v, want 2 repeaters and 1 stale excluded", resp.Baseline) + } + if !slices.Contains(resp.Warnings, "1 stale repeater excluded") { + t.Errorf("warnings %q", resp.Warnings) + } + if resp.Nodes[2].Component != -1 || resp.Nodes[3].Component != -1 || !resp.Nodes[2].Stale { + t.Errorf("stale nodes %+v %+v", resp.Nodes[2], resp.Nodes[3]) + } + for _, e := range resp.Edges { + if e.A >= 2 || e.B >= 2 { + t.Errorf("edge touches an excluded node: %+v", e) + } + } + + in.Params.IncludeStale = true + resp = ptPlan(t, v, in) + if resp.Baseline.Repeaters != 3 || resp.Baseline.StaleExcluded != 0 || resp.Baseline.Components != 1 { + t.Errorf("with stale: baseline %+v", resp.Baseline) + } + for _, w := range resp.Warnings { + if strings.Contains(w, "stale") { + t.Errorf("unexpected warning %q", w) + } + } + if resp.Nodes[2].Component != 0 || resp.Nodes[3].Component < 0 { + t.Errorf("components %d %d", resp.Nodes[2].Component, resp.Nodes[3].Component) + } +} + +func TestCoveragePlanEdgesCapAndTruncation(t *testing.T) { + var nodes []plannerNode + for r := 0; r < 10; r++ { + for c := 0; c < 7; c++ { + nodes = append(nodes, ptNode("n", float64(c)*0.5, float64(r)*0.5)) + } + } + in := planInputs{Area: ptArea(-1, -1, 4, 5.5), Nodes: nodes, Params: ptParams()} + in.Params.Sites, in.Params.ExistingAntennaM, in.Params.RangeKm = 1, 40, 10 + for i := 0; i < 5; i++ { + in.Observed = append(in.Observed, plannerEdge{A: 2 * i, B: 60 + i, Class: "observed"}) + } + resp := ptPlan(t, &ptBumps{base: 200}, in) + if len(resp.Edges) != plannerMaxEdgesOut || !resp.Truncated { + t.Fatalf("edges %d truncated %v, want %d and true", len(resp.Edges), resp.Truncated, plannerMaxEdgesOut) + } + for i, e := range resp.Edges { + want := "solid" + if i < 5 { + want = "observed" + } + if e.Class != want { + t.Fatalf("edge %d class %q, want %q", i, e.Class, want) + } + if i > 0 && e.Class == resp.Edges[i-1].Class && e.DistanceKm < resp.Edges[i-1].DistanceKm { + t.Fatalf("edge %d out of distance order", i) + } + } + if !slices.Contains(resp.Warnings, "Area has no candidate high ground with a usable link") { + t.Errorf("warnings %q", resp.Warnings) + } + if resp.Status != "connected" || len(resp.Sites) != 0 { + t.Errorf("status %q sites %d", resp.Status, len(resp.Sites)) + } + + // A small plan is not cut, but the caller's node cap still shows. + v, small := ptFlatClusterCase() + small.Truncated = true + if resp := ptPlan(t, v, small); !resp.Truncated || len(resp.Edges) != 10 { + t.Errorf("caller truncation lost: truncated %v edges %d", resp.Truncated, len(resp.Edges)) + } +} + +func ptJSON(t *testing.T, resp PlannerPlanResponse) string { + t.Helper() + resp.ComputedAt = time.Time{} + b, err := json.Marshal(resp) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +func TestCoveragePlanDeterministic(t *testing.T) { + for name, mk := range map[string]func() (terrainView, planInputs){ + "two clusters": ptTwoClusterCase, "chain": ptChainCase, "hilly": func() (terrainView, planInputs) { return ptHillyCase(40, 20) }, + } { + t.Run(name, func(t *testing.T) { + v, in := mk() + first := ptJSON(t, ptPlan(t, v, in)) + if again := ptJSON(t, ptPlan(t, v, in)); again != first { + t.Errorf("runs differ:\n%s\n%s", first, again) + } + if !strings.Contains(first, `"warnings":[`) || !strings.Contains(first, `"sites":[`) { + t.Errorf("slices must encode as arrays: %s", first) + } + }) + } +} + +// ptHillyCase: n seeded random nodes over a side×side km area (plus a 10 km +// margin) on ptWaves, 10 sites asked. +func ptHillyCase(n int, side float64) (terrainView, planInputs) { + rng := rand.New(rand.NewPCG(7, 11)) + var nodes []plannerNode + for i := 0; i < n; i++ { + x, y := rng.Float64()*(side+20)-10, rng.Float64()*(side+20)-10 + nd := ptNode(string(rune('a'+i%26))+string(rune('a'+i/26)), x, y) + nd.InArea = x >= 0 && x <= side && y >= 0 && y <= side + nd.Stale = i%10 == 9 + nodes = append(nodes, nd) + } + p := ptParams() + p.Sites, p.ExistingAntennaM, p.NewAntennaM, p.RangeKm = 10, 10, 15, 30 + return ptWaves{}, planInputs{Area: ptArea(0, 0, side, side), Nodes: nodes, Params: p} +} + +// ptHeavyCase: 300 random nodes (220 in a 100×100 km area) on flat ground +// with 40 m / 20 m masts and a 60 km range, so every stage has real work +// (~0.1 s each without -race): long predicted links stay solid and need +// full profiles. With the observed baseline (150 links) the backbone is in +// pieces and the greedy runs. +func ptHeavyCase(baseline string) (terrainView, planInputs) { + rng := rand.New(rand.NewPCG(5, 6)) + var nodes []plannerNode + for i := 0; i < plannerMaxNodes; i++ { + x, y := rng.Float64()*100, rng.Float64()*100 + if i >= 220 { // the 30 km margin + x, y = rng.Float64()*160-30, rng.Float64()*160-30 + for x >= 0 && x <= 100 && y >= 0 && y <= 100 { + x, y = rng.Float64()*160-30, rng.Float64()*160-30 + } + } + nd := ptNode("h", x, y) + nd.InArea = i < 220 + nodes = append(nodes, nd) + } + var observed []plannerEdge + for len(observed) < 150 { + a, b := rng.IntN(len(nodes)), rng.IntN(len(nodes)) + if a != b { + observed = append(observed, plannerEdge{A: a, B: b, Class: "observed"}) + } + } + p := ptParams() + p.Sites, p.RangeKm, p.NewAntennaM, p.ExistingAntennaM, p.Baseline = 10, 60, 40, 20, baseline + return &ptBumps{base: 0}, planInputs{Area: ptArea(0, 0, 100, 100), Nodes: nodes, Observed: observed, Params: p} +} + +// Cancelling from inside each stage (baseline edges, candidates, greedy) +// returns ctx.Err() within 50 ms, though each stage has far more work left. +func TestCoveragePlanCancelPromptly(t *testing.T) { + for _, tc := range []struct { + baseline string + at float64 + }{{"predicted", 0.05}, {"predicted", 0.45}, {"observed", 0.8}} { + v, in := ptHeavyCase(tc.baseline) + ctx, cancel := context.WithCancel(context.Background()) + var cancelled time.Time + _, err := runCoveragePlan(ctx, v, in, func(f float64) { + if f >= tc.at && cancelled.IsZero() { + cancel() + cancelled = time.Now() + } + }) + took := time.Since(cancelled) + cancel() + if cancelled.IsZero() { + t.Fatalf("%s: progress never reached %.2f (err %v)", tc.baseline, tc.at, err) + } + if !errors.Is(err, context.Canceled) { + t.Errorf("cancel at %.2f: err %v, want context.Canceled", tc.at, err) + } + if took > 50*time.Millisecond { + t.Errorf("cancel at %.2f: returned %v after cancel", tc.at, took) + } + t.Logf("%s, cancel at %.2f: returned %v later", tc.baseline, tc.at, took) + } + v, in := ptHillyCase(40, 20) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := runCoveragePlan(ctx, v, in, nil); !errors.Is(err, context.Canceled) { + t.Errorf("pre-cancelled: %v", err) + } +} + +func TestCoveragePlanProgressMonotonic(t *testing.T) { + v, in := ptHillyCase(40, 20) + last := -1.0 + resp, err := runCoveragePlan(context.Background(), v, in, func(f float64) { + if f < last || f < 0 || f > 1 { + t.Errorf("progress %v after %v", f, last) + } + last = f + }) + if err != nil || last != 1 { + t.Fatalf("err %v last progress %v", err, last) + } + if len(resp.Sites) == 0 { + t.Errorf("hilly case picked nothing: %+v", resp.Baseline) + } + for i, s := range resp.Sites { + if s.Step != i+1 || s.Lat != losRound(s.Lat, 1e5) || s.ElevM != losRound(s.ElevM, 10) { + t.Errorf("site %+v", s) + } + for _, l := range s.Links { + if (l.Node < 0) != (l.PeerStep > 0) || (l.PeerStep > 0 && l.PeerStep >= s.Step) { + t.Errorf("site %d link %+v", s.Step, l) + } + } + for _, o := range resp.Sites[:i] { + if d := geoDistKm(geoPoint{s.Lat, s.Lon}, geoPoint{o.Lat, o.Lon}); d <= planSiteSpacingKm { + t.Errorf("sites %d and %d only %.2f km apart", o.Step, s.Step, d) + } + } + } +} + +func TestCoveragePlanRejectsBadInput(t *testing.T) { + v, good := ptFlatClusterCase() + cases := map[string]func(*planInputs){ + "sites": func(in *planInputs) { in.Params.Sites = plannerMaxSites + 1 }, + "range": func(in *planInputs) { in.Params.RangeKm = math.NaN() }, + "antenna": func(in *planInputs) { in.Params.NewAntennaM = -1 }, + "frequency": func(in *planInputs) { in.Params.FrequencyMHz = 0 }, + "k": func(in *planInputs) { in.Params.KFactor = -1 }, + "baseline": func(in *planInputs) { in.Params.Baseline = "guess" }, + "area": func(in *planInputs) { in.Area.S, in.Area.N = in.Area.N, in.Area.S }, + "node": func(in *planInputs) { in.Nodes[0].Lat = math.Inf(1) }, + "nodes": func(in *planInputs) { in.Nodes = make([]plannerNode, plannerMaxNodes+1) }, + } + for name, mutate := range cases { + in := good + in.Nodes = slices.Clone(good.Nodes) + mutate(&in) + if _, err := runCoveragePlan(context.Background(), v, in, nil); err == nil { + t.Errorf("%s: no error", name) + } + } + if _, err := runCoveragePlan(context.Background(), nil, good, nil); err == nil { + t.Error("nil view: no error") + } + // Out-of-range observed indices are ignored, not trusted. + good.Observed = []plannerEdge{{A: -1, B: 2}, {A: 0, B: 99}, {A: 3, B: 3}} + if _, err := runCoveragePlan(context.Background(), v, good, nil); err != nil { + t.Errorf("bad observed edges: %v", err) + } +} + +// ─── Shared machinery ────────────────────────────────────────────────────── + +// planLinkEval must reproduce sampleTerrainProfile + analyzeLOS exactly, +// and its early exit must agree with the full value. +func TestPlannerSearchLinkEvalMatchesAnalyzeLOS(t *testing.T) { + rng := rand.New(rand.NewPCG(1, 2)) + views := map[string]terrainView{"bumps": ptTwoClusterView(), "waves": ptWaves{}, "grid": ptBenchTerrain()} + for name, v := range views { + var origin geoPoint + if name == "grid" { + origin = geoPoint{45, -120.5} + } else { + origin = ptGeo(0, 0) + } + ev := newPlanLinkEval(context.Background(), v, 869.525, 0) + for i := 0; i < 300; i++ { + a := geoPoint{origin.Lat + rng.Float64()*0.6 - 0.3, origin.Lon + rng.Float64()*0.8 - 0.4} + b := geoPoint{origin.Lat + rng.Float64()*0.6 - 0.3, origin.Lon + rng.Float64()*0.8 - 0.4} + if i%50 == 0 { + b = a // zero-length leg + } + d := geoDistKm(a, b) + ha, hb := rng.Float64()*30, rng.Float64()*30 + prof, ok := sampleTerrainProfile(v, a, b, planProfileSamples(d)) + if !ok { + t.Fatalf("%s: profile not ok", name) + } + want, ok := analyzeLOS(prof, d, losParams{FreqMHz: 869.525, AntennaAM: ha, AntennaBM: hb}) + if !ok { + t.Fatalf("%s: analyzeLOS not ok", name) + } + // Equal up to rounding: a sample may sit an ulp (~1 nm) away + // where a multiply-add fuses differently. + tol := 1e-9 * math.Max(1, math.Abs(want.Clearance)) + got, ok := ev.clearance(a, b, d, ha, hb, math.Inf(-1)) + if !ok || math.Abs(got-want.Clearance) > tol { + t.Fatalf("%s pair %d: eval %v (ok %v), analyzeLOS %v", name, i, got, ok, want.Clearance) + } + for _, floor := range []float64{0, plannerMinClearance, want.Clearance - 1e-6, want.Clearance + 1e-6} { + c, ok := ev.clearance(a, b, d, ha, hb, floor) + if ok != (want.Clearance >= floor) || (ok && math.Abs(c-want.Clearance) > tol) { + t.Fatalf("%s pair %d floor %v: got %v ok %v, full %v", name, i, floor, c, ok, want.Clearance) + } + } + } + } + // A profile that leaves the view is no link, like analyzeLOS's reject. + ev := newPlanLinkEval(context.Background(), rampView{0.5}, 869.525, 0) + if _, ok := ev.clearance(geoPoint{0, 0}, geoPoint{0, 1}, geoDistKm(geoPoint{0, 0}, geoPoint{0, 1}), 5, 5, math.Inf(-1)); ok { + t.Error("out-of-view profile ok") + } +} + +func ptTwoClusterView() terrainView { v, _ := ptTwoClusterCase(); return v } + +// planArc is greatCircleSamples one point at a time: planLinkEval must read +// the terrain at the points the profile endpoints read. +func TestPlannerSearchArcMatchesGreatCircleSamples(t *testing.T) { + legs := [][2]geoPoint{ + {{30.2, -97.8}, {30.85, -97.15}}, + {{45.1, -120.7}, {44.8, -120.2}}, + {{-33.9, 151.2}, {-34.4, 150.6}}, + {{45, 0}, {45, 90}}, // long: 600 samples, bulging poleward + {{10, 179.3}, {10.4, -179.6}}, // across the antimeridian + {{3, 4}, {3, 4}}, // one point + } + for _, l := range legs { + a, b := l[0], l[1] + d := geoDistKm(a, b) + n := planProfileSamples(d) + want := greatCircleSamples(a, b, n) + arc := newPlanArc(a, b, d) + for _, i := range []int{1, n / 4, n / 2, 3 * n / 4, n - 2} { + lat, lon := arc.at(float64(i) / float64(n-1)) + if math.Abs(lat-want[i].Lat) > 1e-9 || math.Abs(lon-want[i].Lon) > 1e-9 { + t.Errorf("%v→%v sample %d/%d: planArc (%v, %v), greatCircleSamples %+v", a, b, i, n, lat, lon, want[i]) + } + } + } +} + +// planNear must never reject a pair within range. +func TestPlannerSearchNearIsConservative(t *testing.T) { + rng := rand.New(rand.NewPCG(3, 4)) + for _, lat := range []float64{0, 37, 60, 75, -55} { + for _, km := range []float64{2, 10, 60, 100} { + p := newPlanNear(km, math.Abs(lat)+1) + for i := 0; i < 2000; i++ { + a := geoPoint{lat + rng.Float64()*2 - 1, rng.Float64()*360 - 180} + brg, dist := rng.Float64()*2*math.Pi, km*(0.98+rng.Float64()*0.04) + dLat := dist * math.Cos(brg) / plannerKmPerDeg + dLon := dist * math.Sin(brg) / (plannerKmPerDeg * math.Cos(a.Lat*math.Pi/180)) + b := geoPoint{a.Lat + dLat, math.Remainder(a.Lon+dLon, 360)} + if math.Abs(b.Lat) > math.Abs(lat)+1 { + continue + } + if geoDistKm(a, b) <= km && !p.maybe(a, b) { + t.Fatalf("lat %v km %v: rejected %v-%v at %.6f km", lat, km, a, b, geoDistKm(a, b)) + } + } + } + } + if p := newPlanNear(10, 45); p.maybe(geoPoint{45, 0}, geoPoint{45.2, 0}) { + t.Error("22 km north accepted for 10 km") + } +} + +// Plateau cells are all local maxima; thinning keeps one per 3×3 block +// (radius 2) and never touches an isolated peak. +func TestPlannerSearchGridPeaksThinPlateaus(t *testing.T) { + ctx := context.Background() + // Half a step of slack: the grid's cos(latitude) is the box middle's, + // not ptGeo's origin's. + box := ptArea(0, 0, 20.5, 11.5) + flat, err := newPlanGrid(ctx, &ptBumps{base: 10}, box, 1) + if err != nil { + t.Fatal(err) + } + if flat.rows != 12 || flat.cols != 21 { + t.Fatalf("grid %dx%d, want 12x21", flat.rows, flat.cols) + } + if n := len(flat.peaks(2)); n != 12*21 { + t.Errorf("plateau peaks %d, want every cell", n) + } + thin := flat.thin(flat.peaks(2), 2) + if len(thin) != 4*7 { + t.Errorf("thinned plateau peaks %d, want a 3-cell lattice of 28", len(thin)) + } + for _, i := range thin { + if r, c := i/flat.cols, i%flat.cols; r%3 != 0 || c%3 != 0 { + t.Errorf("thinned peak at %d,%d off the lattice", r, c) + } + } + hills := &ptBumps{base: 10, bumps: []ptBump{{x: 5, y: 5, h: 100, sx: 1, sy: 1}, {x: 15, y: 5, h: 50, sx: 1, sy: 1}}} + g, err := newPlanGrid(ctx, hills, box, 1) + if err != nil { + t.Fatal(err) + } + for _, thin := range []bool{false, true} { + peaks := g.peaks(2) + if thin { + peaks = g.thin(peaks, 2) + } + var tops []geoPoint + for _, i := range peaks { + if g.elev[i] > 20 { + tops = append(tops, g.point(i)) + } + } + if len(tops) != 2 || geoDistKm(tops[0], ptGeo(5, 5)) > 0.8 || geoDistKm(tops[1], ptGeo(15, 5)) > 0.8 { + t.Errorf("thin=%v: hilltops %v", thin, tops) + } + } + // Cells outside the view are skipped, not peaks. + if g, err := newPlanGrid(ctx, rampView{ptLon0 + 0.1}, box, 1); err != nil { + t.Fatal(err) + } else { + for _, i := range g.peaks(1) { + if !g.ok[i] || g.point(i).Lon < ptLon0+0.1 { + t.Fatalf("peak %v outside the view", g.point(i)) + } + } + } + if _, err := newPlanGrid(ctx, &ptBumps{}, geoBBox{S: 0, W: 0, N: 10, E: 10}, 1); err == nil { + t.Error("1100 km grid accepted") + } +} + +// ─── Relay ───────────────────────────────────────────────────────────────── + +// ptRelayCase: A and B 20 km apart across a ridge (350 m); a sharp hill +// (~725 m) 5 km beside the line sees both more steeply. Existing nodes: one +// on the hill, six on the ridge, and four that break a rule. Existing masts +// are 20 m: a short mast on a rounded crown is shadowed by the crown itself +// when looking 3° down. +func ptRelayCase() (terrainView, []plannerNode, PlannerRelayParams) { + v := &ptBumps{base: 50, bumps: []ptBump{ + {x: 0, y: 0, h: 300, sx: 0.7, sy: 3}, + {x: 0, y: 5, h: 600, sx: 0.8, sy: 0.8}, + }} + stale := ptNode("stale-hill", 0.3, 5) + stale.Stale = true + nodes := []plannerNode{ + ptNode("crest-3", 0, -3), ptNode("crest-2", 0, -2), ptNode("crest-1", 0, -1), + ptNode("crest0", 0, 0), ptNode("crest1", 0, 1), ptNode("crest2", 0, 2), + ptNode("detour", 0, 8.5), // legs 13.1 km ≤ range, detour 26.2 > 1.3·20 + ptNode("out-of-range", -6, 0), // detour 20, but 16 km from B + ptNode("at-a", -10, 0), // A itself + stale, + ptNode("hill", 0, 5), + } + a, b := ptGeo(-10, 0), ptGeo(10, 0) + return v, nodes, PlannerRelayParams{ + A: geoPointJSON{a.Lat, a.Lon}, B: geoPointJSON{b.Lat, b.Lon}, + AntennaAM: 2, AntennaBM: 2, RelayAntennaM: 10, ExistingAntennaM: 20, RangeKm: 15, + FrequencyMHz: 869.525, KFactor: 4.0 / 3.0, + } +} + +func TestRelaySearchRidgeAndHill(t *testing.T) { + v, nodes, p := ptRelayCase() + resp, err := runRelaySearch(context.Background(), v, nodes, p, nil) + if err != nil { + t.Fatal(err) + } + a, b := geoPoint{p.A.Lat, p.A.Lon}, geoPoint{p.B.Lat, p.B.Lon} + if resp.Direct.Verdict != "blocked" || len(resp.Direct.ElevM) == 0 { + t.Errorf("direct %+v, want blocked with a profile", resp.Direct) + } + if len(resp.Existing) != relayMaxOptions || len(resp.Open) == 0 || len(resp.Open) > relayMaxOptions { + t.Fatalf("existing %d open %d", len(resp.Existing), len(resp.Open)) + } + if resp.Existing[0].Name != "hill" || resp.Existing[0].PubKey != "pk-hill" { + t.Errorf("existing[0] = %q, want the hill", resp.Existing[0].Name) + } + if d := geoDistKm(geoPoint{resp.Open[0].Lat, resp.Open[0].Lon}, ptGeo(0, 5)); d > 1 { + t.Errorf("best open option %.2f km from the hilltop", d) + } + for _, list := range [][]PlannerRelayOption{resp.Existing, resp.Open} { + for i, o := range list { + r := geoPoint{o.Lat, o.Lon} + dA, dB := geoDistKm(a, r), geoDistKm(r, b) + if dA > p.RangeKm || dB > p.RangeKm || dA+dB > 1.3*geoDistKm(a, b) { + t.Errorf("%s %q breaks the corridor/range rule: %.2f + %.2f", o.Kind, o.Name, dA, dB) + } + if len(o.LegA.ElevM) == 0 || len(o.LegB.ElevM) == 0 || len(o.LegA.ElevM) > 200 { + t.Errorf("%s %q legs lack profiles", o.Kind, o.Name) + } + if o.BottleneckPct != math.Min(o.LegA.ClearancePct, o.LegB.ClearancePct) || o.BottleneckPct < 0 { + t.Errorf("%s %q bottleneck %v legs %v/%v", o.Kind, o.Name, o.BottleneckPct, o.LegA.ClearancePct, o.LegB.ClearancePct) + } + if i > 0 && o.BottleneckPct > list[i-1].BottleneckPct { + t.Errorf("%s list not ranked: %v after %v", o.Kind, o.BottleneckPct, list[i-1].BottleneckPct) + } + if o.ElevM <= 50 { + t.Errorf("%s %q elev %v", o.Kind, o.Name, o.ElevM) + } + } + } + for _, o := range resp.Existing { + if o.Kind != "existing" || o.AntennaM != p.ExistingAntennaM { + t.Errorf("existing option %+v", o) + } + switch o.Name { + case "detour", "out-of-range", "at-a", "stale-hill": + t.Errorf("%q should be excluded", o.Name) + } + } + for i, o := range resp.Open { + if o.Kind != "open" || o.AntennaM != p.RelayAntennaM || o.PubKey != "" { + t.Errorf("open option %+v", o) + } + for _, q := range resp.Open[:i] { + if geoDistKm(geoPoint{o.Lat, o.Lon}, geoPoint{q.Lat, q.Lon}) <= relaySpacingKm { + t.Errorf("open options within %v km", relaySpacingKm) + } + } + } + if len(resp.Warnings) != 0 { + t.Errorf("warnings %q", resp.Warnings) + } + if resp.Source != "" || resp.Params != p { // the API layer names the source + t.Errorf("source %q params %+v", resp.Source, resp.Params) + } + + // Each rule-breaker alone is still excluded (not just ranked out). + for _, i := range []int{6, 7, 8, 9} { + resp2, err := runRelaySearch(context.Background(), v, nodes[i:i+1], p, nil) + if err != nil || len(resp2.Existing) != 0 { + t.Errorf("%q listed alone: %+v (err %v)", nodes[i].Name, resp2.Existing, err) + } + } +} + +func TestRelaySearchBlockedOptionsOnlyWhenNothingClears(t *testing.T) { + v, nodes, p := ptRelayCase() + pit := ptNode("pit", 2, -4) + terr := v.(*ptBumps) + terr.bumps = append(terr.bumps, ptBump{x: 2, y: -4, h: -300, sx: 0.4, sy: 0.4}) + resp, err := runRelaySearch(context.Background(), terr, []plannerNode{pit, nodes[10]}, p, nil) + if err != nil { + t.Fatal(err) + } + if len(resp.Existing) != 1 || resp.Existing[0].Name != "hill" { + t.Errorf("existing %+v, want only the hill (the pit is blocked)", resp.Existing) + } + + // A sits in a pit: no relay clears, so blocked options are still listed. + a := ptGeo(-10, 0) + pitA := &ptBumps{base: 50, bumps: []ptBump{{x: -10, y: 0, h: -45, sx: 0.4, sy: 0.4}}} + resp, err = runRelaySearch(context.Background(), pitA, []plannerNode{ptNode("mid", 0, 1)}, p, nil) + if err != nil { + t.Fatal(err) + } + if len(resp.Existing) != 1 || len(resp.Open) == 0 { + t.Fatalf("existing %d open %d, want blocked options kept", len(resp.Existing), len(resp.Open)) + } + for _, o := range append(resp.Existing, resp.Open...) { + if o.BottleneckPct >= 0 { + t.Errorf("option at %v,%v clears from inside the pit at %v", o.Lat, o.Lon, a) + } + } + if !slices.Contains(resp.Warnings, "No relay gives a clear first Fresnel zone") { + t.Errorf("warnings %q", resp.Warnings) + } +} + +func TestRelaySearchDeterministicAndCancellable(t *testing.T) { + v, nodes, p := ptRelayCase() + r1, err1 := runRelaySearch(context.Background(), v, nodes, p, nil) + r2, err2 := runRelaySearch(context.Background(), v, nodes, p, nil) + j1, _ := json.Marshal(r1) + j2, _ := json.Marshal(r2) + if err1 != nil || err2 != nil || string(j1) != string(j2) { + t.Errorf("relay runs differ (%v, %v)", err1, err2) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := runRelaySearch(ctx, v, nodes, p, nil); !errors.Is(err, context.Canceled) { + t.Errorf("pre-cancelled: %v", err) + } + ctx, cancel = context.WithCancel(context.Background()) + var at time.Time + _, err := runRelaySearch(ctx, v, nodes, p, func(f float64) { + if f >= relayGridEnd && at.IsZero() { // before the first profile + cancel() + at = time.Now() + } + }) + cancel() + if at.IsZero() || !errors.Is(err, context.Canceled) || time.Since(at) > 50*time.Millisecond { + t.Errorf("mid-run cancel: err %v after %v", err, time.Since(at)) + } + bad := p + bad.B = geoPointJSON{p.A.Lat + 2, p.A.Lon} // 222 km: over the largest maxLegKm + if _, err := runRelaySearch(context.Background(), v, nodes, bad, nil); err == nil { + t.Error("over-long leg accepted") + } + bad = p + bad.RangeKm = 0 + if _, err := runRelaySearch(context.Background(), v, nodes, bad, nil); err == nil { + t.Error("zero range accepted") + } +} + +// The longest leg an operator can allow (planner.maxLegKm 200) fits the +// relay grid, north-south and east-west, up to the edge of the SRTM band. +func TestRelaySearchLongestLegFitsGrid(t *testing.T) { + for _, c := range []struct{ a, b geoPoint }{ + {geoPoint{58.2, 10}, geoPoint{59.99, 10}}, // north-south, 199 km + {geoPoint{60, 10}, geoPoint{60, 10 + 199/(plannerKmPerDeg*math.Cos(math.Pi/3))}}, // east-west at 60° + {geoPoint{-56, -70}, geoPoint{-56, -70 + 199/(plannerKmPerDeg*math.Cos(56*math.Pi/180))}}, + } { + d := geoDistKm(c.a, c.b) + if d > plannerLegKmMax || d < plannerLegKmMax-2 { + t.Fatalf("%+v → %+v is %.1f km", c.a, c.b, d) + } + p := PlannerRelayParams{ + A: geoPointJSON{c.a.Lat, c.a.Lon}, B: geoPointJSON{c.b.Lat, c.b.Lon}, + AntennaAM: 10, AntennaBM: 10, RelayAntennaM: 10, ExistingAntennaM: 5, RangeKm: 60, + FrequencyMHz: 869.525, KFactor: 4.0 / 3.0, + } + resp, err := runRelaySearch(context.Background(), ptWaves{}, nil, p, nil) + if err != nil { + t.Fatalf("%.0f km leg from %+v: %v", d, c.a, err) + } + if math.Abs(resp.Direct.DistanceKm-d) > 0.01 { + t.Fatalf("direct %.3f km, want %.3f", resp.Direct.DistanceKm, d) + } + } +} + +// ─── Missing terrain ─────────────────────────────────────────────────────── + +// ptNE is the SRTM tile north-east of the test origin (x ≥ 0, y ≥ 0). +var ptNE = srtmKey{int(ptLat0), int(ptLon0)} + +// ptSRTMView renders t onto the four real SRTM tiles that meet at the test +// origin (36–38 N, 101–99 W), so the search reads terrain through srtmView. +func ptSRTMView(t terrainView) *srtmView { + sp := srtmSpan{lat0: int(ptLat0) - 1, lon0: int(ptLon0) - 1, nLat: 2, nLon: 2} + v := &srtmView{span: sp, grids: make([][]int16, sp.count())} + for i := range v.grids { + k := sp.key(i) + g := make([]int16, srtmSide*srtmSide) + for r := 0; r < srtmSide; r++ { + lat := float64(k.lat+1) - float64(r)/srtmCells + for c := 0; c < srtmSide; c++ { + e, _ := t.ElevationAt(lat, float64(k.lon)+float64(c)/srtmCells) + g[r*srtmSide+c] = int16(math.Round(e)) + } + } + v.grids[i] = g + } + return v +} + +// ptWithout is v with tile k gone, as a 404 leaves it (grids are shared). +func ptWithout(v *srtmView, k srtmKey) *srtmView { + out := &srtmView{span: v.span, grids: slices.Clone(v.grids)} + for i := range out.grids { + if v.span.key(i) == k { + out.grids[i] = nil + } + } + return out +} + +// ptTouchesMissing reports whether a sample of the a→b profile (the points +// sampleTerrainProfile reads) has no terrain in v. +func ptTouchesMissing(v terrainCoverage, a, b geoPoint) bool { + n := planProfileSamples(geoDistKm(a, b)) + for _, p := range greatCircleSamples(a, b, n) { + if v.MissingAt(p.Lat, p.Lon) { + return true + } + } + return false +} + +// A tile without data (404: open sea, or unavailable) is skipped, never read +// as 0 m: no relay stands on it, no reported leg crosses it, and a direct +// link across it is not measured: error no_terrain, no verdict. +func TestRelaySearchSkipsMissingTerrain(t *testing.T) { + // Flat 0 m with two 300 m hills, one each side of the origin. A (north- + // west) to B (south-east) crosses the north-east tile. + full := ptSRTMView(&ptBumps{bumps: []ptBump{ + {x: -1, y: -1, h: 300, sx: 0.6, sy: 0.6}, + {x: 2.5, y: 2.5, h: 300, sx: 0.6, sy: 0.6}, + }}) + nodes := []plannerNode{ptNode("kept", -1, -1), ptNode("lost", 2.5, 2.5)} + a, b := ptGeo(-3, 6), ptGeo(6, -3) + p := PlannerRelayParams{ + A: geoPointJSON{a.Lat, a.Lon}, B: geoPointJSON{b.Lat, b.Lon}, + AntennaAM: 2, AntennaBM: 2, RelayAntennaM: 10, ExistingAntennaM: 20, RangeKm: 15, + FrequencyMHz: 869.525, KFactor: 4.0 / 3.0, + } + run := func(v terrainView) PlannerRelayResponse { + t.Helper() + resp, err := runRelaySearch(context.Background(), v, nodes, p, nil) + if err != nil { + t.Fatal(err) + } + return resp + } + isLost := func(o PlannerRelayOption) bool { return o.Name == "lost" } + + directJSON := func(l PlannerLink) string { + t.Helper() + b, err := json.Marshal(l) + if err != nil { + t.Fatal(err) + } + return string(b) + } + + // Control: with every tile present the north-east hill is offered and + // the direct link is measured. + resp := run(full) + if !slices.ContainsFunc(resp.Existing, isLost) || len(resp.Direct.ElevM) == 0 || resp.Direct.Verdict == "" || + resp.Direct.Error != "" || strings.Contains(directJSON(resp.Direct), `"error"`) || + slices.Contains(resp.Warnings, relayWarnDirectNoTerrain) { + t.Fatalf("full terrain: existing %+v direct %+v warnings %q", resp.Existing, resp.Direct, resp.Warnings) + } + + v := ptWithout(full, ptNE) + if !ptTouchesMissing(v, a, b) || !v.MissingAt(ptGeo(2.5, 2.5).Lat, ptGeo(2.5, 2.5).Lon) { + t.Fatal("test geometry: the direct path and the lost hill should be in the missing tile") + } + resp = run(v) + d := resp.Direct + if d.Error != plannerErrNoTerrain || d.Verdict != "" || d.ElevM != nil || d.ClearancePct != 0 || d.WorstKm != 0 || + d.ObstructionM != 0 || d.DistanceKm != losRound(geoDistKm(a, b), 1000) { + t.Errorf("direct %+v, want it unmeasured (error no_terrain, no verdict, no profile)", d) + } + if got := directJSON(d); !strings.Contains(got, `"error":"no_terrain"`) || !strings.Contains(got, `"verdict":""`) || + strings.Contains(got, "elev_m") { + t.Errorf("direct JSON %s", got) + } + if !slices.Contains(resp.Warnings, relayWarnDirectNoTerrain) { + t.Errorf("warnings %q lack %q", resp.Warnings, relayWarnDirectNoTerrain) + } + if len(resp.Existing) != 1 || resp.Existing[0].Name != "kept" { + t.Errorf("existing %+v, want only the hill with terrain", resp.Existing) + } + if len(resp.Open) == 0 || geoDistKm(geoPoint{resp.Open[0].Lat, resp.Open[0].Lon}, ptGeo(-1, -1)) > 1 { + t.Fatalf("open %+v, want the south-west hilltop first", resp.Open) + } + for _, list := range [][]PlannerRelayOption{resp.Existing, resp.Open} { + for _, o := range list { + r := geoPoint{o.Lat, o.Lon} + if v.MissingAt(r.Lat, r.Lon) { + t.Errorf("%s option %q at %+v stands on missing terrain", o.Kind, o.Name, r) + } + if ptTouchesMissing(v, a, r) || ptTouchesMissing(v, r, b) || len(o.LegA.ElevM) == 0 || len(o.LegB.ElevM) == 0 { + t.Errorf("%s option %q at %+v has a leg over missing terrain", o.Kind, o.Name, r) + } + } + } + + // An endpoint on missing terrain: nothing can be measured, nothing offered. + p.B = geoPointJSON{ptGeo(4, 4).Lat, ptGeo(4, 4).Lon} + resp = run(v) + if len(resp.Existing)+len(resp.Open) != 0 || resp.Direct.Error != plannerErrNoTerrain || resp.Direct.Verdict != "" || + !slices.Contains(resp.Warnings, relayWarnDirectNoTerrain) { + t.Errorf("B on missing terrain: existing %d open %d direct %+v warnings %q", + len(resp.Existing), len(resp.Open), resp.Direct, resp.Warnings) + } +} + +// The coverage plan skips missing terrain the same way: no candidate site on +// it, no candidate link, site link or predicted edge across it. An observed +// edge is radio evidence, so it stays in the backbone, with its clearance +// unknown (0). +func TestCoveragePlanSkipsMissingTerrain(t *testing.T) { + // ptTwoClusterCase with its summit 3 km south, out of the north-east + // tile, where e2 stands. + full := ptSRTMView(&ptBumps{base: 100, bumps: []ptBump{ + {x: -4, h: 400, sx: 0.8, sy: 1e6}, + {x: 4, h: 400, sx: 0.8, sy: 1e6}, + {x: 0, y: -3, h: 700, sx: 1.2, sy: 1.2}, + }}) + nodes := []plannerNode{ + ptNode("w1", -16, -3), ptNode("w2", -15, 3), ptNode("w3", -19, -0.5), + ptNode("e1", 16, -3), ptNode("e2", 15, 3), ptNode("e3", 19, -1), + } + const e1, e2 = 3, 4 + p := ptParams() + p.RangeKm = 40 + in := planInputs{ + Area: ptArea(-22, -8, 22, 8), Nodes: nodes, Params: p, + Observed: []plannerEdge{{A: e1, B: e2, Class: "observed"}}, + } + pt := func(i int) geoPoint { return geoPoint{nodes[i].Lat, nodes[i].Lon} } + candidates := func(v terrainView) []planCand { + t.Helper() + s := newCoverageSearch(context.Background(), v, in, func(float64) {}) + if err := s.baselineEdges(); err != nil { + t.Fatal(err) + } + s.baselineGraph() + if _, err := s.findCandidates(); err != nil { + t.Fatal(err) + } + return s.cands + } + inNE := func(c planCand) bool { return srtmKeyOf(c.pt.Lat, c.pt.Lon) == ptNE } + predictedTouching := func(holed terrainCoverage, resp PlannerPlanResponse) (n int) { + for _, e := range resp.Edges { + if e.Class != "observed" && ptTouchesMissing(holed, pt(e.A), pt(e.B)) { + n++ + } + } + return n + } + + // Control: with every tile present the north-east has candidates and + // e2 has predicted links. + v := ptWithout(full, ptNE) + if !slices.ContainsFunc(candidates(full), inNE) { + t.Fatal("full terrain: no candidate in the north-east tile") + } + if n := predictedTouching(v, ptPlan(t, full, in)); n == 0 { + t.Fatal("full terrain: no predicted edge through the north-east tile") + } + + if !v.MissingAt(nodes[e2].Lat, nodes[e2].Lon) { + t.Fatal("test geometry: e2 should stand in the missing tile") + } + cands := candidates(v) + if len(cands) == 0 { + t.Fatal("no candidates at all") + } + for _, c := range cands { + if v.MissingAt(c.pt.Lat, c.pt.Lon) { + t.Errorf("candidate %+v stands on missing terrain", c.pt) + } + for _, l := range c.links { + if ptTouchesMissing(v, c.pt, pt(l.peer)) { + t.Errorf("candidate %+v links %s across missing terrain", c.pt, nodes[l.peer].Name) + } + } + } + + resp := ptPlan(t, v, in) + if len(resp.Sites) == 0 || resp.Sites[0].Reason != "joins" { + t.Fatalf("sites %+v, want the summit to join the clusters", resp.Sites) + } + for _, s := range resp.Sites { + sp := geoPoint{s.Lat, s.Lon} + if v.MissingAt(s.Lat, s.Lon) { + t.Errorf("site %d at %+v stands on missing terrain", s.Step, sp) + } + for _, l := range s.Links { + var q geoPoint + if l.Node >= 0 { + q = pt(l.Node) + } else { + q = geoPoint{resp.Sites[l.PeerStep-1].Lat, resp.Sites[l.PeerStep-1].Lon} + } + if ptTouchesMissing(v, sp, q) { + t.Errorf("site %d link %+v crosses missing terrain", s.Step, l) + } + } + } + if n := predictedTouching(v, resp); n != 0 { + t.Errorf("%d predicted edges cross missing terrain", n) + } + i := slices.IndexFunc(resp.Edges, func(e PlannerEdgeOut) bool { return e.Class == "observed" }) + if i < 0 || resp.Edges[i].A != e1 || resp.Edges[i].B != e2 || resp.Edges[i].ClearancePct != 0 { + t.Errorf("edges %+v, want the observed e1–e2 kept with unknown (0) clearance", resp.Edges) + } + if resp.Nodes[e2].Component != resp.Nodes[e1].Component { + t.Errorf("observed e1–e2 no longer joins them: components %d, %d", resp.Nodes[e1].Component, resp.Nodes[e2].Component) + } +} + +// ─── Benchmarks (AGENTS.md rule 0) ───────────────────────────────────────── + +// ptGridTerrain is SRTM-like: int16 metres every 3 arc-seconds (1200 per +// degree), bilinear like srtmView, row 0 = south. +type ptGridTerrain struct { + lat0, lon0 float64 + rows, cols int + g []int16 +} + +func (t *ptGridTerrain) ElevationAt(lat, lon float64) (float64, bool) { + fy, fx := (lat-t.lat0)*1200, (lon-t.lon0)*1200 + if !(fy >= 0 && fx >= 0 && fy <= float64(t.rows-1) && fx <= float64(t.cols-1)) { + return 0, false + } + r, c := int(fy), int(fx) + if r > t.rows-2 { + r = t.rows - 2 + } + if c > t.cols-2 { + c = t.cols - 2 + } + dy, dx := fy-float64(r), fx-float64(c) + i := r*t.cols + c + s := float64(t.g[i])*(1-dx) + float64(t.g[i+1])*dx + n := float64(t.g[i+t.cols])*(1-dx) + float64(t.g[i+t.cols+1])*dx + return s*(1-dy) + n*dy, true +} + +var ( + ptBenchOnce sync.Once + ptBenchView *ptGridTerrain +) + +// ptBenchTerrain: 2°×3° (44–46 N, 122–119 W, fictional hills) of value noise, +// 20/6/1.6/0.6 km octaves, 0–~1250 m: rough enough that the 1 km grid has +// more than plannerMaxCands candidates. Built once, ~17 MB. +func ptBenchTerrain() *ptGridTerrain { + ptBenchOnce.Do(func() { + t := &ptGridTerrain{lat0: 44, lon0: -122, rows: 2*1200 + 1, cols: 3*1200 + 1} + t.g = make([]int16, t.rows*t.cols) + rng := rand.New(rand.NewPCG(42, 42)) + type octave struct { + cellKm, amp float64 + w int + lat []float64 + } + kmPerPx := plannerKmPerDeg / 1200 + octs := []octave{{cellKm: 20, amp: 500}, {cellKm: 6, amp: 300}, {cellKm: 1.6, amp: 300}, {cellKm: 0.6, amp: 150}} + for k := range octs { + o := &octs[k] + o.w = int(float64(t.cols)*kmPerPx/o.cellKm) + 3 + h := int(float64(t.rows)*kmPerPx/o.cellKm) + 3 + o.lat = make([]float64, o.w*h) + for i := range o.lat { + o.lat[i] = rng.Float64() + } + } + smooth := func(f float64) float64 { return f * f * (3 - 2*f) } + for r := 0; r < t.rows; r++ { + for c := 0; c < t.cols; c++ { + e := 0.0 + for k := range octs { + o := &octs[k] + y, x := float64(r)*kmPerPx/o.cellKm, float64(c)*kmPerPx*0.7/o.cellKm + iy, ix := int(y), int(x) + fy, fx := smooth(y-float64(iy)), smooth(x-float64(ix)) + l := o.lat[iy*o.w+ix:] + top := l[0]*(1-fx) + l[1]*fx + bot := l[o.w]*(1-fx) + l[o.w+1]*fx + e += o.amp * (top*(1-fy) + bot*fy) + } + t.g[r*t.cols+c] = int16(e) + } + } + ptBenchView = t + }) + return ptBenchView +} + +// ptBenchPlanInputs: the largest plan the API allows. 100×100 km area at +// 45 N, 300 nodes (220 in area, 80 in the 30 km margin) each on the highest +// of 8 random spots within 1.5 km, 10 % stale, 150 observed links. +func ptBenchPlanInputs() planInputs { + v := ptBenchTerrain() + rng := rand.New(rand.NewPCG(9, 9)) + area := geoBBox{S: 44.55, W: -121.136, N: 45.45, E: -119.864} + outer := plannerExpandBBox(area, defaultPlannerNodeMarginKm) + var nodes []plannerNode + for len(nodes) < plannerMaxNodes { + in := len(nodes) < 220 + b := outer + if in { + b = area + } + p := geoPoint{b.S + rng.Float64()*(b.N-b.S), b.W + rng.Float64()*(b.E-b.W)} + if !in && plannerBBoxContains(area, p.Lat, p.Lon) { + continue + } + best, bestE := p, -1e9 + for k := 0; k < 8; k++ { + q := geoPoint{p.Lat + (rng.Float64()-0.5)*0.027, p.Lon + (rng.Float64()-0.5)*0.038} + if e, ok := v.ElevationAt(q.Lat, q.Lon); ok && e > bestE { + best, bestE = q, e + } + } + i := len(nodes) + nodes = append(nodes, plannerNode{ + PubKey: string(rune('A'+i%26)) + string(rune('A'+i/26%26)) + string(rune('0'+i/676)), + Role: "repeater", Lat: best.Lat, Lon: best.Lon, InArea: in, Stale: i%10 == 7, + }) + } + var observed []plannerEdge + for len(observed) < 150 { + a, b := rng.IntN(len(nodes)), rng.IntN(len(nodes)) + if a != b && geoDistKm(geoPoint{nodes[a].Lat, nodes[a].Lon}, geoPoint{nodes[b].Lat, nodes[b].Lon}) < 40 { + observed = append(observed, plannerEdge{A: a, B: b, Class: "observed"}) + } + } + return planInputs{Area: area, Nodes: nodes, Observed: observed, Params: PlannerPlanParams{ + Sites: plannerMaxSites, RangeKm: 60, NewAntennaM: 10, ExistingAntennaM: 5, Baseline: "predicted", + FrequencyMHz: 869.525, KFactor: 4.0 / 3.0, MinClearance: plannerMinClearance, + }} +} + +// ptBenchFlat: the same grid, all 0 m (the sea in a coastal tile). Every cell +// of a plateau is a local maximum, so this is the candidate-count worst case. +func ptBenchFlat() *ptGridTerrain { + t := ptBenchTerrain() + return &ptGridTerrain{lat0: t.lat0, lon0: t.lon0, rows: t.rows, cols: t.cols, g: make([]int16, len(t.g))} +} + +// BenchmarkCoveragePlanMax: the largest plan the API allows (100×100 km, +// 300 nodes, 60 km range, 10 sites), single-threaded, with the time split +// per stage. "hilly" is the realistic case; "flat" maximises grid peaks +// (every plateau cell is one, before thinning); "flat-tall" (40 m / 20 m +// masts, observed baseline of 150 links) also gives the peaks solid links +// and leaves components to join, so the greedy runs 10 rounds on +// plannerMaxCands; "flat-100m" (100 m masts, the config maximum) makes every +// link in range solid, so no profile exits early. +func BenchmarkCoveragePlanMax(b *testing.B) { + base := ptBenchPlanInputs() + tall, tallest := base, base + tall.Params.NewAntennaM, tall.Params.ExistingAntennaM, tall.Params.Baseline = 40, 20, "observed" + tallest.Params.NewAntennaM, tallest.Params.ExistingAntennaM = 100, 100 + for _, tc := range []struct { + name string + v terrainView + in planInputs + }{ + {"hilly", ptBenchTerrain(), base}, {"flat", ptBenchFlat(), base}, + {"flat-tall", ptBenchFlat(), tall}, {"flat-100m", ptBenchFlat(), tallest}, + } { + b.Run(tc.name, func(b *testing.B) { + var st planStageStats + var resp PlannerPlanResponse + for i := 0; i < b.N; i++ { + var err error + if resp, err = planCoverage(context.Background(), tc.v, tc.in, nil, &st); err != nil { + b.Fatal(err) + } + } + ms := func(d time.Duration) float64 { return float64(d.Microseconds()) / 1000 } + b.ReportMetric(ms(st.EdgesTime), "edges-ms") + b.ReportMetric(ms(st.CandsTime), "cands-ms") + b.ReportMetric(ms(st.GreedyTime), "greedy-ms") + b.ReportMetric(ms(st.OutputTime), "output-ms") + b.ReportMetric(float64(st.Profiles), "profiles") + b.ReportMetric(float64(st.Peaks), "peaks") + b.ReportMetric(float64(st.Candidates), "cands") + b.ReportMetric(float64(st.Sites), "sites") + b.Logf("edges %d baseline %+v final %+v status %s", len(resp.Edges), resp.Baseline, resp.Final, resp.Status) + }) + } +} + +// BenchmarkRelayMax: a 99 km A–B, 60 km range, 300 nodes. "flat" makes +// every 500 m cell a 3×3 peak (~100k cells to filter and sort). +func BenchmarkRelayMax(b *testing.B) { + in := ptBenchPlanInputs() + a, c := geoPoint{45.0, -121.13}, geoPoint{45.0, -119.87} + p := PlannerRelayParams{ + A: geoPointJSON{a.Lat, a.Lon}, B: geoPointJSON{c.Lat, c.Lon}, + AntennaAM: 5, AntennaBM: 5, RelayAntennaM: 10, ExistingAntennaM: 5, RangeKm: 60, + FrequencyMHz: 869.525, KFactor: 4.0 / 3.0, + } + for _, tc := range []struct { + name string + v terrainView + }{{"hilly", ptBenchTerrain()}, {"flat", ptBenchFlat()}} { + b.Run(tc.name, func(b *testing.B) { + var resp PlannerRelayResponse + for i := 0; i < b.N; i++ { + var err error + if resp, err = runRelaySearch(context.Background(), tc.v, in.Nodes, p, nil); err != nil { + b.Fatal(err) + } + } + b.ReportMetric(geoDistKm(a, c), "km") + b.ReportMetric(float64(len(resp.Existing)), "existing") + b.ReportMetric(float64(len(resp.Open)), "open") + }) + } +} + +// BenchmarkPlannerSearchProfile: one 40 km leg, shared path +// (sampleTerrainProfile + analyzeLOS) vs planLinkEval, full and with the +// solid-only early exit. +func BenchmarkPlannerSearchProfile(b *testing.B) { + v := ptBenchTerrain() + a, c := geoPoint{44.8, -121.0}, geoPoint{45.1, -120.65} + d := geoDistKm(a, c) + lp := losParams{FreqMHz: 869.525, AntennaAM: 10, AntennaBM: 5} + b.Run("shared", func(b *testing.B) { + for i := 0; i < b.N; i++ { + prof, _ := sampleTerrainProfile(v, a, c, planProfileSamples(d)) + analyzeLOS(prof, d, lp) + } + }) + ev := newPlanLinkEval(context.Background(), v, 869.525, 0) + b.Run("eval", func(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + ev.clearance(a, c, d, 10, 5, math.Inf(-1)) + } + }) + b.Run("eval-solid", func(b *testing.B) { + for i := 0; i < b.N; i++ { + ev.clearance(a, c, d, 10, 5, plannerMinClearance) + } + }) +} diff --git a/cmd/server/planner_tiles_test.go b/cmd/server/planner_tiles_test.go new file mode 100644 index 000000000..b014c1f2b --- /dev/null +++ b/cmd/server/planner_tiles_test.go @@ -0,0 +1,601 @@ +package main + +import ( + "context" + "fmt" + "math" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + "time" +) + +// plannerTestDest is the point km from a on the initial bearing (degrees +// clockwise from north), on haversineKm's sphere. +func plannerTestDest(a geoPoint, bearingDeg, km float64) geoPoint { + const rad = math.Pi / 180 + d := km / earthRadiusKm + p1, l1, th := a.Lat*rad, a.Lon*rad, bearingDeg*rad + p2 := math.Asin(math.Sin(p1)*math.Cos(d) + math.Cos(p1)*math.Sin(d)*math.Cos(th)) + l2 := l1 + math.Atan2(math.Sin(th)*math.Sin(d)*math.Cos(p1), math.Cos(d)-math.Sin(p1)*math.Sin(p2)) + return geoPoint{p2 / rad, l2 / rad} +} + +// plannerTestTiles is the real source's tile count. +func plannerTestTiles(bb geoBBox) int { + sp, ok := srtmSpanOf(bb) + if !ok { + return 0 + } + return sp.count() +} + +func TestPlannerWorstCaseTiles(t *testing.T) { + cases := []struct { + name string + sideKm, maxLat float64 + want int + }{ + // 50 km is 0.45° of latitude and, at the equator, of longitude. + {"small at the equator", 50, 0, 2 * 2}, + // At 60° a degree of longitude is half as long: 0.9° → still 2. + {"small at 60", 50, 60, 2 * 2}, + // 160 km: 1.44° of latitude (3 tiles), 2.9° of longitude at 60.3° (4). + {"default view at the band edge", 160, 60.3, 3 * 4}, + // 160 km at 30°: 1.66° of longitude → 3 tiles. + {"default view at 30", 160, 30, 3 * 3}, + } + for _, c := range cases { + if got := plannerWorstCaseTiles(c.sideKm, c.maxLat); got != c.want { + t.Errorf("%s: plannerWorstCaseTiles(%v, %v) = %d, want %d", c.name, c.sideKm, c.maxLat, got, c.want) + } + } + // Longitude never shrinks with latitude, and a span never needs fewer + // tiles than a smaller one. + for lat := 0.0; lat <= 85; lat += 5 { + if a, b := plannerWorstCaseTiles(160, lat), plannerWorstCaseTiles(160, lat+5); a > b { + t.Errorf("tiles at %v° (%d) > at %v° (%d)", lat, a, lat+5, b) + } + } + if got := plannerWorstCaseTiles(100, 89.99); got < 180 { + t.Errorf("near the pole: %d tiles, want the whole circle of longitude counted", got) + } +} + +// plannerTestSizes are the size limits the property tests run at: the +// defaults, the smallest and largest an operator can set, and one between. +var plannerTestSizes = []struct{ area, margin, leg float64 }{ + {defaultPlannerMaxAreaKm, defaultPlannerNodeMarginKm, defaultPlannerMaxLegKm}, + {200, 50, 150}, + {plannerAreaKmMax, plannerMarginKmMax, plannerLegKmMax}, + {plannerAreaKmMin, plannerMarginKmMin, plannerLegKmMin}, +} + +func TestPlannerTileCapsDefaults(t *testing.T) { + got := plannerTileCaps(defaultPlannerMaxAreaKm, defaultPlannerNodeMarginKm, defaultPlannerMaxLegKm) + // 100 km box + 30 km margin = 160 km; 100 km leg + 2×30 km pad = 160 km: + // 3 × 4 tiles at the north edge of the SRTM band; a viewshed at the + // largest range (60 km) spans 120 km: 3 × 4 too. + if want := (plannerTileLimits{Profile: 12, Relay: 12, Coverage: 12, Viewshed: 12}); got != want { + t.Fatalf("caps %+v, want %+v", got, want) + } + if got.max() != 12 { + t.Fatalf("max %d", got.max()) + } + // Short legs keep the old floor of 6. + if c := plannerTileCaps(defaultPlannerMaxAreaKm, defaultPlannerNodeMarginKm, 10); c.Relay != 6 || c.Profile != 6 { + t.Fatalf("10 km legs: %+v, want relay/profile 6", c) + } + if n := terrainViewTiles(nil, &PlannerConfig{Enabled: true}); n != got.max() { + t.Fatalf("a planner-only source accepts %d tiles per view, want %d", n, got.max()) + } + p := newPlannerService(PlannerConfig{Enabled: true}, nil, nil) + t.Cleanup(p.Close) + if p.tiles != got { + t.Fatalf("service caps %+v, want %+v", p.tiles, got) + } +} + +// The caps, the source's per-view cap and the cache floor follow the +// operator's sizes. +func TestPlannerTileCapsFromConfig(t *testing.T) { + cfg := PlannerConfig{Enabled: true, MaxAreaKm: 200, NodeMarginKm: 50, MaxLegKm: 150} + r, warns := cfg.resolved() + if len(warns) != 0 { + t.Fatalf("warnings %q", warns) + } + // 300 km: 2.7° (4 tiles) by 6.1° at 60.5° (8 tiles); 150 + 2×45 km: + // 2.2° (4) by 4.4° (6); the viewshed stays at its 60 km range's 12. + want := plannerTileLimits{Profile: 24, Relay: 24, Coverage: 28, Viewshed: 12} + if got := r.tileLimits(); got != want { + t.Fatalf("caps %+v, want %+v", got, want) + } + p := newPlannerService(cfg, nil, nil) + t.Cleanup(p.Close) + src := p.src.(*srtmSource) + if p.tiles != want || src.maxTiles != 28 || src.cache.maxItems != 28 { + t.Fatalf("service caps %+v, source max %d, cache %d", p.tiles, src.maxTiles, src.cache.maxItems) + } + if n := terrainViewTiles(nil, &cfg); n != 28 { + t.Fatalf("shared source view cap %d, want 28", n) + } + if c := (TerrainConfig{TileCacheTiles: 100}).cacheTiles(28); c != 100 { + t.Fatalf("a larger configured cache: %d", c) + } +} + +// Review #2391 point 1: an 89 × 84 km box at 51° N needs 3 × 4 = 12 tiles +// once the 30 km node margin is added, and was refused at a cap of 9. +func TestPlannerCoverageReviewBoxAccepted(t *testing.T) { + const bbox = "50.2,3.4,51.0,4.6" + g, msg := plannerParseGridBox(bbox, defaultPlannerMaxAreaKm) + if msg != "" { + t.Fatalf("parse: %s", msg) + } + view := plannerExpandBBox(g.bbox(), defaultPlannerNodeMarginKm) + caps := PlannerConfig{}.tileLimits() + src := newSRTMSource(TerrainConfig{}, caps.max()) + if n := src.TileCount(view); n != 12 || n > caps.Coverage || n > src.maxTiles { + t.Fatalf("view %+v: %d tiles, coverage cap %d, source cap %d", view, n, caps.Coverage, src.maxTiles) + } + + h := newPlannerHarness(t) + h.data.setNodes(append(plannerTestNodes(), nodeInfo{PublicKey: "be01", Name: "Brussels", Role: "repeater", + Lat: 50.6, Lon: 4.0, HasGPS: true, LastSeen: plannerTestStart})) + w := h.get("/api/planner/coverage?bbox="+bbox, "198.51.100.200") + if w.Code != http.StatusAccepted && w.Code != http.StatusOK { + t.Fatalf("review box: %d %s", w.Code, w.Body.String()) + } + plannerWaitFor(t, "the job's terrain request", func() bool { return h.src.viewCount() == 1 }) + if v := h.src.lastBBox(); v != view { + t.Fatalf("job view %+v, want %+v", v, view) + } +} + +// plannerTestCoverageBoxes calls fn with the coverage boxes at the size +// limit that plannerParseGridBox accepts: south edges on the 0.05° grid +// within the band, every sStride-th (a stride prime to 20 still meets every +// alignment to the degree lines), each height, the widest box the width +// check allows at that height, and every 0.05° west-edge alignment within a +// degree. A smaller box at the same corner lies inside one of these, so they +// are the worst case for the tile count. +func plannerTestCoverageBoxes(t *testing.T, maxAreaKm float64, sStride int, fn func(area geoBBox)) { + t.Helper() + parse := func(s, w, n, e int) bool { + raw := fmt.Sprintf("%g,%g,%g,%g", float64(s)/plannerGridPerDeg, float64(w)/plannerGridPerDeg, + float64(n)/plannerGridPerDeg, float64(e)/plannerGridPerDeg) + g, msg := plannerParseGridBox(raw, maxAreaKm) + if msg == "" && g != (plannerGridBox{s, w, n, e}) { + t.Fatalf("%s snapped to %+v", raw, g) + } + return msg == "" + } + sMin := int(plannerCoverageMinLat * plannerGridPerDeg) + nMax := int(plannerCoverageMaxLat * plannerGridPerDeg) + hMax := int(maxAreaKm / plannerKmPerDeg * plannerGridPerDeg) + boxes := 0 + for s := sMin; s < nMax; s += sStride { + for h := 1; h <= hMax && s+h <= nMax; h++ { + n := s + h + mid := (float64(s) + float64(n)) / 2 / plannerGridPerDeg + w0 := 20 // 1° E: any meridian will do, only the alignment matters + wd := int(maxAreaKm/(plannerKmPerDeg*math.Cos(mid*math.Pi/180))*plannerGridPerDeg) + 1 + for wd > 0 && !parse(s, w0, n, w0+wd) { + wd-- + } + if wd == 0 || parse(s, w0, n, w0+wd+1) { + t.Fatalf("no widest box at s=%d h=%d (width %d)", s, h, wd) + } + for off := 0; off < plannerGridPerDeg; off++ { + if !parse(s, w0+off, n, w0+off+wd) { + t.Fatalf("box s=%d h=%d w=%d at offset %d refused", s, h, wd, off) + } + fn(plannerGridBox{s, w0 + off, n, w0 + off + wd}.bbox()) + boxes++ + } + } + } + if boxes == 0 { + t.Fatal("no boxes") + } +} + +// Every coverage box the parser accepts fits the coverage cap, at every +// tested size, and the cap is reached: it is the worst case, not a guess. +func TestPlannerCoverageTileCapHoldsEverywhere(t *testing.T) { + for i, sz := range plannerTestSizes { + caps := plannerTileCaps(sz.area, sz.margin, sz.leg) + stride := 1 + if i > 0 { + stride = 3 + } + worst := 0 + plannerTestCoverageBoxes(t, sz.area, stride, func(area geoBBox) { + n := plannerTestTiles(plannerExpandBBox(area, sz.margin)) + if n > caps.Coverage { + t.Fatalf("%+v: box %+v: view needs %d tiles, cap %d", sz, area, n, caps.Coverage) + } + worst = max(worst, n) + }) + if worst != caps.Coverage { + t.Errorf("%+v: largest view needs %d tiles, cap %d: the cap is not the worst case", sz, worst, caps.Coverage) + } + } +} + +// Every relay corridor and single profile leg of at most the maximum length, +// with both ends in the band, fits its cap, at every tested size. +func TestPlannerRelayProfileTileCapsHoldEverywhere(t *testing.T) { + for i, sz := range plannerTestSizes { + caps := plannerTileCaps(sz.area, sz.margin, sz.leg) + pad := plannerProfilePad(sz.leg) + step := 0.25 + if i > 0 { + step = 0.65 + } + legs := 0 + for lat := plannerCoverageMinLat; lat <= plannerCoverageMaxLat; lat += step { + for off := 0.0; off < 1; off += 0.05 { + a := geoPoint{lat, 20 + off} + for bearing := 0.0; bearing < 360; bearing += 15 { + for _, km := range []float64{sz.leg, sz.leg / 2} { + b := plannerTestDest(a, bearing, km) + qa, ok1 := plannerLatLon(fmt.Sprint(a.Lat), fmt.Sprint(a.Lon)) + qb, ok2 := plannerLatLon(fmt.Sprint(b.Lat), fmt.Sprint(b.Lon)) + if !ok1 || !ok2 || qb.Lat < plannerCoverageMinLat || qb.Lat > plannerCoverageMaxLat { + continue + } + if d := geoDistKm(qa, qb); d > sz.leg { + // Rounding to 0.001° lengthened it: the handler says too_long. + continue + } + legs++ + if n := plannerTestTiles(plannerRelayView(qa, qb)); n > caps.Relay { + t.Fatalf("%+v: relay %+v → %+v: %d tiles, cap %d", sz, qa, qb, n, caps.Relay) + } + pv := plannerProfileView(plannerBBoxAdd(geoBBox{qa.Lat, qa.Lon, qa.Lat, qa.Lon}, qb), pad) + if n := plannerTestTiles(pv); n > caps.Profile { + t.Fatalf("%+v: profile %+v → %+v: %d tiles, cap %d", sz, qa, qb, n, caps.Profile) + } + } + } + } + } + if legs < 30000 { + t.Fatalf("%+v: only %d legs checked", sz, legs) + } + } +} + +// The profile pad covers the great-circle bulge of the longest leg: every +// point the profile samples lies inside its view. +func TestPlannerProfilePadCoversBulge(t *testing.T) { + for _, c := range []struct{ leg, want float64 }{{10, 0.01}, {100, 0.01}, {150, 0.0225}, {200, 0.04}} { + if got := plannerProfilePad(c.leg); math.Abs(got-c.want) > 1e-12 { + t.Errorf("plannerProfilePad(%v) = %v, want %v", c.leg, got, c.want) + } + } + for _, sz := range plannerTestSizes { + pad := plannerProfilePad(sz.leg) + for lat := plannerCoverageMinLat; lat <= plannerCoverageMaxLat; lat += 1 { + for bearing := 0.0; bearing < 180; bearing += 15 { + a := geoPoint{lat, 20.5} + b := plannerTestDest(a, bearing, sz.leg) + view := plannerProfileView(plannerBBoxAdd(geoBBox{a.Lat, a.Lon, a.Lat, a.Lon}, b), pad) + for _, pt := range greatCircleSamples(a, b, planProfileSamples(sz.leg)) { + if !plannerBBoxContains(view, pt.Lat, pt.Lon) { + t.Fatalf("leg %v km from %+v on %v°: sample %+v outside %+v", sz.leg, a, bearing, pt, view) + } + } + } + } + } +} + +// A view over its endpoint's cap is too_many_tiles, not area_too_large, and +// refused before any job or token; area_too_large stays for a box side over +// the size limit. +func TestPlannerTooManyTiles(t *testing.T) { + for _, tc := range []struct { + name, path string + set func(l *plannerTileLimits, n int) + }{ + {"profile", plannerProfPath, func(l *plannerTileLimits, n int) { l.Profile = n }}, + {"relay", plannerRelayPath, func(l *plannerTileLimits, n int) { l.Relay = n }}, + {"coverage", plannerCovPath, func(l *plannerTileLimits, n int) { l.Coverage = n }}, + } { + t.Run(tc.name, func(t *testing.T) { + h := newPlannerHarness(t) + // The test views are 2×2 tiles (29-30 N × 98-97 W) or smaller. + need := 0 + h.src.set(func(f *fakeTerrain) { + f.tiles = func(bb geoBBox) int { need = len(fakeTiles(bb)); return need } + }) + tc.set(&h.p.tiles, 0) + w := h.get(tc.path, "198.51.100.201") + if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), plannerErrTooManyTiles) || + strings.Contains(w.Body.String(), plannerErrAreaTooLarge) { + t.Fatalf("over the cap: %d %s", w.Code, w.Body.String()) + } + if h.liveJobs() != 0 || h.tokens("198.51.100.201") != plannerIPJobsPerMin { + t.Fatal("a refused request started a job or took a token") + } + // At exactly the cap it runs. + tc.set(&h.p.tiles, need) + if w := h.get(tc.path, "198.51.100.201"); w.Code != http.StatusAccepted && w.Code != http.StatusOK { + t.Fatalf("at the cap (%d): %d %s", need, w.Code, w.Body.String()) + } + }) + } + + // A terrain source that refuses the view fails the job the same way. + h := newPlannerHarness(t) + h.p.fastWait = plannerFastWait + h.src.set(func(f *fakeTerrain) { f.err = errTerrainTooManyTiles }) + w := h.get(plannerCovPath, "198.51.100.202") + if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), plannerErrTooManyTiles) { + t.Fatalf("source refusal: %d %s", w.Code, w.Body.String()) + } + if got := plannerOutcome(fmt.Errorf("wrapped: %w", errTerrainTooManyTiles)); got != "too_many_tiles" { + t.Fatalf("outcome %q", got) + } + + // The size limit keeps its own code. + h = newPlannerHarness(t) + w = h.get("/api/planner/coverage?bbox=30.0,-97.2,31.0,-96.85", "198.51.100.203") + if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), plannerErrAreaTooLarge) { + t.Fatalf("oversized box: %d %s", w.Code, w.Body.String()) + } +} + +// The source enforces its own per-view cap: one tile more is refused +// without a request, and is never resident. +func TestSRTMSourceMaxTiles(t *testing.T) { + s, u, _ := newSRTMTest(t, 0, srtmServe(nil)) + strip := func(n int) geoBBox { return geoBBox{S: 30.2, W: -99.5, N: 30.8, E: -100 + float64(n)} } + if got := s.TileCount(strip(s.maxTiles + 1)); got != s.maxTiles+1 { + t.Fatalf("strip of %d: %d tiles", s.maxTiles+1, got) + } + if _, err := s.View(context.Background(), strip(s.maxTiles+1)); err != errTerrainTooManyTiles { + t.Fatalf("View over the cap: %v", err) + } + if s.Resident(strip(s.maxTiles + 1)) { + t.Fatal("a view over the cap is resident") + } + if n := u.total(); n != 0 { + t.Fatalf("refused view made %d requests", n) + } +} + +// terrainBoth is route LOS and the planner over one test source and one +// per-client download budget, wired as newTerrainServices wires them, on the +// source's clock. +type terrainBoth struct { + *elevTest + p *plannerService + data *fakePlannerData +} + +func newTerrainBoth(t *testing.T, h http.HandlerFunc) *terrainBoth { + t.Helper() + et := newElevTest(t, h) + cfg := &Config{LOS: &LOSConfig{Enabled: true}, Planner: &PlannerConfig{Enabled: true}} + et.srv.cfg = cfg + p := newPlannerService(*cfg.Planner, et.srv, et.src) + t.Cleanup(p.Close) + data := &fakePlannerData{serverPlannerData: serverPlannerData{et.srv}} + p.data = data + p.now = et.clk.now + p.limit.rl.now = et.clk.now + p.global.now = et.clk.now + et.svc.downloads = newTerrainClientLimiter(nil, terrainViewTiles(cfg.LOS, cfg.Planner)) + et.svc.downloads.rl.now = et.clk.now + p.downloads = et.svc.downloads + et.srv.planner = p + return &terrainBoth{elevTest: et, p: p, data: data} +} + +// known makes the points of each pts list repeaters the planner knows. Call +// it before the first planner request: the planner rebuilds its node set +// only every plannerKnownTTL. +func (tb *terrainBoth) known(ptsLists ...string) { + var ns []nodeInfo + for _, pts := range ptsLists { + for _, pt := range elevParsePts(pts) { + ns = append(ns, nodeInfo{PublicKey: fmt.Sprintf("kn%04d", len(ns)), Name: "N", Role: "repeater", + Lat: pt.Lat, Lon: pt.Lon, HasGPS: true, LastSeen: tb.clk.now()}) + } + } + tb.data.setNodes(append(tb.data.nodes(), ns...)) +} + +// profile asks the planner for a profile of pts from ip, once. +func (tb *terrainBoth) profile(pts, ip string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodGet, "/api/planner/profile?pts="+url.QueryEscape(pts), nil) + req.RemoteAddr = ip + ":5000" + w := httptest.NewRecorder() + tb.srv.handlePlannerProfile(w, req) + return w +} + +// profileDone polls the planner profile until it answers 200. +func (tb *terrainBoth) profileDone(t *testing.T, pts, ip string) { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + for { + w := tb.profile(pts, ip) + if w.Code == http.StatusOK { + return + } + if w.Code != http.StatusAccepted || time.Now().After(deadline) { + t.Fatalf("planner %s from %s: %d %s", pts, ip, w.Code, w.Body.String()) + } + time.Sleep(2 * time.Millisecond) + } +} + +func (tb *terrainBoth) tokens(ip string) float64 { return rlTokens(tb.p.downloads.rl, ip) } + +// Security review (#2391): a planner job cost one token however many tiles +// its view downloaded. It now also takes one token per download its view +// starts, from the budget route LOS charges, all or nothing; tiles already +// in memory or already downloading cost nothing. +func TestPlannerChargesTileDownloads(t *testing.T) { + gate := newSRTMGate() + tb := newTerrainBoth(t, func(w http.ResponseWriter, r *http.Request) { + if gate.wait(r) { + http.NotFound(w, r) + } + }) + t.Cleanup(gate.open) + const ( + cold = "30.8,-97.2,31.2,-96.8" // N30-N31 × W098-W097: 4 tiles + overlap = "30.85,-97.15,31.15,-96.85" // the same 4 tiles, another key + here = "40.3,10.3,40.6,10.6" // N40E010 only + refused = "50.8,5.8,51.2,6.2" // N50-N51 × E005-E006: 4 tiles + busy = "52.8,5.8,53.2,6.2" // N52-N53 × E005-E006: 4 tiles + ) + tb.known(cold, overlap, here, refused, busy) + tb.src.put(srtmKey{31, -97}, elevFlatGrid(80)) + tb.src.put(srtmKey{40, 10}, elevFlatGrid(80)) + const ip = "198.51.100.150" + burst := tb.p.downloads.rl.burst + + // 3 of the 4 tiles are not here: 3 tokens, and one job token. + if w := tb.profile(cold, ip); w.Code != http.StatusAccepted { + t.Fatalf("cold view: %d %s", w.Code, w.Body.String()) + } + if got := tb.tokens(ip); got != burst-3 { + t.Fatalf("cold view: %v download tokens left, want %v", got, burst-3) + } + srtmEventually(t, "the 3 downloads to start", func() bool { + tb.src.mu.Lock() + defer tb.src.mu.Unlock() + return len(tb.src.loading) == 3 + }) + jobs := rlTokens(tb.p.limit.rl, ip) + + // Polling the job, a view over the same tiles while they download, and a + // view in memory cost no download token. + if w := tb.profile(cold, ip); w.Code != http.StatusAccepted { + t.Fatalf("poll: %d", w.Code) + } + if w := tb.profile(overlap, ip); w.Code != http.StatusAccepted { + t.Fatalf("overlapping view: %d %s", w.Code, w.Body.String()) + } + tb.p.fastWait = 10 * time.Second + if w := tb.profile(here, ip); w.Code != http.StatusOK { + t.Fatalf("resident view: %d %s", w.Code, w.Body.String()) + } + if got := tb.tokens(ip); got != burst-3 || rlTokens(tb.p.limit.rl, ip) != jobs-2 { + t.Fatalf("free requests: %v download tokens, %v job tokens (want %v, %v)", got, rlTokens(tb.p.limit.rl, ip), burst-3, jobs-2) + } + + // Too few download tokens: 429, the job token back, nothing started. + tb.p.downloads.rl.takeN(ip, int(burst)-3-2) // 2 left, the view needs 4 + jobs = rlTokens(tb.p.limit.rl, ip) + w := tb.profile(refused, ip) + if w.Code != http.StatusTooManyRequests || !strings.Contains(w.Body.String(), "rate limited") || w.Header().Get("Retry-After") == "" { + t.Fatalf("over the download budget: %d %s", w.Code, w.Body.String()) + } + if rlTokens(tb.p.limit.rl, ip) != jobs || tb.tokens(ip) != 2 || terrainStarts(tb.p.src, plannerProfileView(geoBBox{S: 50.8, W: 5.8, N: 51.2, E: 6.2}, + plannerProfilePad(defaultPlannerMaxLegKm))) != 4 { + t.Fatalf("refused job: %v job tokens (want %v), %v download tokens", rlTokens(tb.p.limit.rl, ip), jobs, tb.tokens(ip)) + } + + // The global job budget refusing gives both tokens back. + tb.clk.add(time.Minute) // 2 + 10 download tokens + tb.p.global = newRateLimiter(1, time.Hour) + tb.p.global.now = tb.clk.now + tb.p.global.take("all") + if w := tb.profile(busy, ip); w.Code != http.StatusServiceUnavailable { + t.Fatalf("global budget out: %d %s", w.Code, w.Body.String()) + } + if ok, _ := tb.p.downloads.rl.takeN(ip, 12); !ok || rlTokens(tb.p.limit.rl, ip) != plannerIPJobsPerMin { + t.Fatalf("not refunded: %v download tokens, %v job tokens", tb.tokens(ip), rlTokens(tb.p.limit.rl, ip)) + } + if tb.liveJobs() != 2 { + t.Fatalf("%d live jobs, want the 2 loading ones", tb.liveJobs()) + } +} + +func (tb *terrainBoth) liveJobs() int { + tb.p.mu.Lock() + defer tb.p.mu.Unlock() + return len(tb.p.jobs) +} + +// Code review #2 (#2391): at the largest sizes an operator may set, one cold +// coverage view spans 40 tiles, twice the old 20-a-minute download budget, +// so its first request always failed busy and the key was refused for 30 s. +// The budget now fits the largest view, and such a view loads in one go. +func TestPlannerLargestViewLoadsCold(t *testing.T) { + terrainQuietLog(t) + cfg := &PlannerConfig{Enabled: true, MaxAreaKm: plannerAreaKmMax, NodeMarginKm: plannerMarginKmMax, MaxLegKm: plannerLegKmMax} + r, warns := cfg.resolved() + if len(warns) != 0 { + t.Fatalf("warnings %q", warns) + } + g, msg := plannerParseGridBox("55.3,1.95,57.5,6", r.MaxAreaKm) + if msg != "" { + t.Fatal(msg) + } + view := plannerExpandBBox(g.bbox(), r.NodeMarginKm) + caps := r.tileLimits() + if n := plannerTestTiles(view); n != 40 || n != caps.Coverage || n <= srtmPerMinute { + t.Fatalf("view %+v: %d tiles, coverage cap %d", view, n, caps.Coverage) + } + // The shared source, as newTerrainServices builds it, budgets for it. + both := &Config{LOS: &LOSConfig{Enabled: true}, Planner: cfg} + _, p := newTerrainServices(both, &Server{cfg: both}) + t.Cleanup(p.Close) + if b := p.src.(*srtmSource).budget; b.perMinute != 40 || b.perHour != 200 { + t.Fatalf("budget %d/min, %d/hour for 40-tile views", b.perMinute, b.perHour) + } + + s, u, _ := newSRTMTestViews(t, 0, terrainViewTiles(both.LOS, cfg), srtmServe(nil)) // every tile 404s + if n := terrainStarts(s, view); n != 40 { + t.Fatalf("Starts = %d, want all 40", n) + } + if _, err := s.View(context.Background(), view); err != nil { + t.Fatalf("cold 40-tile view: %v", err) + } + if u.total() != 40 || !s.Resident(view) { + t.Fatalf("%d downloads, resident %v", u.total(), s.Resident(view)) + } +} + +// The viewshed view is the site ± its range; the largest range offered is +// the largest of plannerRangesKm within maxLegKm, so that sets the cap. +func TestPlannerTileCapsViewshed(t *testing.T) { + band := math.Max(plannerCoverageMaxLat, -plannerCoverageMinLat) + worst := func(rangeKm float64) int { + return plannerWorstCaseTiles(2*rangeKm, band+rangeKm/plannerKmPerDeg) + } + if got, want := plannerTileCaps(100, 30, 100).Viewshed, worst(60); got != want { + t.Fatalf("maxLeg 100: viewshed cap %d, want %d (60 km range)", got, want) + } + if got, want := plannerTileCaps(100, 30, 10).Viewshed, worst(10); got != want { + t.Fatalf("maxLeg 10: viewshed cap %d, want %d", got, want) + } + if small, big := plannerTileCaps(100, 30, 10).Viewshed, plannerTileCaps(100, 30, 60).Viewshed; small >= big { + t.Fatalf("cap does not grow with maxLegKm: %d at 10 km, %d at 60 km", small, big) + } + // Every viewshed view at the largest range, with the site in the band, + // fits the cap. + for _, sz := range plannerTestSizes { + caps := plannerTileCaps(sz.area, sz.margin, sz.leg) + r := PlannerConfig{MaxLegKm: sz.leg}.rangesKm() + rangeKm := r[len(r)-1] + for lat := plannerCoverageMinLat; lat <= plannerCoverageMaxLat; lat += 0.5 { + for off := 0.0; off < 1; off += 0.1 { + view := viewshedBBox(geoPoint{lat, 20 + off}, rangeKm) + if n := plannerTestTiles(view); n > caps.Viewshed { + t.Fatalf("%+v: site %g,%g: %d tiles, cap %d", sz, lat, 20+off, n, caps.Viewshed) + } + } + } + } +} diff --git a/cmd/server/planner_types.go b/cmd/server/planner_types.go new file mode 100644 index 000000000..196b4fee9 --- /dev/null +++ b/cmd/server/planner_types.go @@ -0,0 +1,348 @@ +package main + +// Repeater planner — shared types. The JSON tags here are the wire contract +// public/planner.js and public/planner-area.js depend on: change them together. +// +// Three GET endpoints under /api/planner/ (planner_api.go), OPT-IN via the +// "planner" config block. All terrain comes from SRTM 1° tiles (the "terrain" +// block, shared with route LOS: terrain_config.go) kept in memory +// (terrain_srtm.go): no DB, no disk — the server stays read-only. +// +// /api/planner/profile ?pts=lat,lon,lat,lon[,...] multi-point LOS chain +// /api/planner/relay ?a=lat,lon&b=lat,lon&ha=&hb=&hr=&range= best relay for A→B +// /api/planner/coverage ?bbox=s,w,n,e&sites=&range=&hr=&he=&baseline=&stale= +// +// Job protocol (all three): the server quantises the query to a cache key. +// 200 = finished result (cached ~10 min). 202 = PlannerJobStatus while the job +// runs (terrain download or compute); the client re-polls the SAME URL after +// retry_after_s. 400 bad input, 404 planner disabled, 429 per-IP limit, 503 +// busy/terrain unavailable (Retry-After). A job nobody polls for 15 s is +// cancelled. + +import "time" + +// geoPoint / geoBBox are the internal coordinate types shared by every +// planner file. Degrees, WGS84. +type geoPoint struct{ Lat, Lon float64 } + +type geoBBox struct{ S, W, N, E float64 } + +// ─── Config ──────────────────────────────────────────────────────────────── + +// PlannerConfig is the "planner" block in config.json. OPT-IN: nil or +// enabled=false → endpoints 404, /api/config/client omits "planner". Terrain +// tiles come from the "terrain" block (TerrainConfig). +type PlannerConfig struct { + Enabled bool `json:"enabled"` + DefaultRangeKm float64 `json:"defaultRangeKm"` + NewAntennaM float64 `json:"newAntennaM"` + ExistingAntennaM float64 `json:"existingAntennaM"` + // Size limits. They set how many terrain tiles one request may load + // (plannerTileCaps), and so the memory a view and the cache take. + // MaxAreaKm: coverage bbox side after snapping, 20-250. + MaxAreaKm float64 `json:"maxAreaKm"` + // NodeMarginKm: repeaters/rooms this far outside the bbox still count, 10-60. + NodeMarginKm float64 `json:"nodeMarginKm"` + // MaxLegKm: profile/relay A→B leg, 10-200. Ranges above it are not offered. + MaxLegKm float64 `json:"maxLegKm"` + // UserReach: the Users layer of the Coverage tab. Non-nil after resolved(). + UserReach *PlannerUserReach `json:"userReach,omitempty"` +} + +// PlannerUserReach is the handheld reach curve +// P(heard) = 1/(1+exp((ln d - ln D50Km)/Slope)). +type PlannerUserReach struct { + D50Km float64 `json:"d50Km"` // distance with P = 0.5, 0.2-50 + Slope float64 `json:"slope"` // 0.05-2 +} + +const ( + defaultPlannerRangeKm = 30.0 + defaultPlannerNewAntennaM = 10.0 + defaultPlannerExistAntenna = 5.0 + defaultPlannerMaxAreaKm = 100.0 + defaultPlannerNodeMarginKm = 30.0 + defaultPlannerMaxLegKm = 100.0 + defaultPlannerUserD50Km = 2.7 + defaultPlannerUserSlope = 0.30 + + // Valid ranges of the size limits; outside them resolved() uses the default. + plannerAreaKmMin, plannerAreaKmMax = 20.0, 250.0 + // The margin minimum is plannerAreaNodeKm: the "a repeater is near the box" + // check reaches that far, so a smaller margin could start a plan with no + // nodes in it. + plannerMarginKmMin, plannerMarginKmMax = 10.0, 60.0 + plannerLegKmMin, plannerLegKmMax = 10.0, 200.0 + plannerUserD50KmMin, plannerUserD50KmMax = 0.2, 50.0 + plannerUserSlopeMin, plannerUserSlopeMax = 0.05, 2.0 + + plannerMaxPoints = 16 // profile: points per request + plannerMaxSites = 10 // coverage: max suggested sites + plannerMaxNodes = 300 // coverage: max repeaters/rooms considered + plannerMaxCands = 500 // coverage: max candidate sites + plannerMaxEdgesOut = 2000 // coverage: max edges in the response + plannerMinClearance = 0.6 // "solid" link: ≥ 60 % first-Fresnel clearance + plannerGeoRadiusKm = 50.0 // profile/relay points must be this close to a known node +) + +// plannerRangesKm is the fixed set of allowed range values: a small fixed +// set keeps the result-cache key space small, so arbitrary ranges cannot +// flood the cache or force a recompute per request. The UI offers those up +// to maxLegKm (PlannerConfig.rangesKm). +var plannerRangesKm = []float64{10, 15, 20, 30, 40, 50, 60} + +// PlannerClientConfig is /api/config/client "planner"; present only when enabled. +type PlannerClientConfig struct { + DefaultRangeKm float64 `json:"defaultRangeKm"` + RangesKm []float64 `json:"rangesKm"` + NewAntennaM float64 `json:"newAntennaM"` + ExistingAntennaM float64 `json:"existingAntennaM"` + FrequencyMHz float64 `json:"frequencyMhz"` + KFactor float64 `json:"kFactor"` + MaxPoints int `json:"maxPoints"` + MaxLegKm float64 `json:"maxLegKm"` + MaxAreaKm float64 `json:"maxAreaKm"` + NodeMarginKm float64 `json:"nodeMarginKm"` + MaxSites int `json:"maxSites"` + MinClearance float64 `json:"minClearance"` + UserReach PlannerUserReach `json:"userReach"` +} + +// ─── Wire types ──────────────────────────────────────────────────────────── + +// PlannerJobStatus is the 202 body while a job runs. +type PlannerJobStatus struct { + State string `json:"state"` // queued | loading_terrain | computing + Progress float64 `json:"progress"` // 0..1 + RetryAfterS int `json:"retry_after_s"` +} + +// PlannerProfileResponse — /api/planner/profile. legs[i] is pts[i]→pts[i+1]. +type PlannerProfileResponse struct { + Source string `json:"source"` // terrainSourceName, e.g. "SRTM (AWS Open Data)" + Legs []PlannerProfileLeg `json:"legs"` + // Warnings, e.g. terrain missing for some tiles (legs there no_terrain). + Warnings []string `json:"warnings,omitempty"` +} + +// PlannerProfileLeg: ElevM holds terrain metres at evenly spaced +// great-circle fractions t=i/(len-1), both ends included; the length varies +// with leg distance (planProfileSamples). Error codes: too_long, +// out_of_area (point not near the mesh), no_terrain. +type PlannerProfileLeg struct { + DistanceKm float64 `json:"distance_km"` + ElevM []float64 `json:"elev_m,omitempty"` + Error string `json:"error,omitempty"` +} + +// PlannerLink summarises one predicted link. ClearancePct = 100 × worst +// first-Fresnel clearance (negative = terrain crosses the line). Verdict is +// one of clear | clear60 | marginal | blocked (public/los.js VERDICTS). +// ElevM (optional) is the terrain profile decimated to ≤ 200 samples. +// Error no_terrain: the link was not measured (a sample has no terrain); +// Verdict is then empty, the numbers 0 and ElevM absent. +type PlannerLink struct { + DistanceKm float64 `json:"distance_km"` + ClearancePct float64 `json:"clearance_pct"` + Verdict string `json:"verdict"` + WorstKm float64 `json:"worst_km"` + ObstructionM float64 `json:"obstruction_m"` + ElevM []float64 `json:"elev_m,omitempty"` + Error string `json:"error,omitempty"` +} + +// PlannerRelayResponse — /api/planner/relay. +type PlannerRelayResponse struct { + Source string `json:"source"` + Direct PlannerLink `json:"direct"` + Existing []PlannerRelayOption `json:"existing"` // known repeaters/rooms, ranked + Open []PlannerRelayOption `json:"open"` // terrain sites, ranked + Params PlannerRelayParams `json:"params"` + Warnings []string `json:"warnings"` +} + +type PlannerRelayParams struct { + A geoPointJSON `json:"a"` + B geoPointJSON `json:"b"` + AntennaAM float64 `json:"ha"` + AntennaBM float64 `json:"hb"` + RelayAntennaM float64 `json:"hr"` + // ExistingAntennaM: assumed mast height of existing relay nodes (config). + ExistingAntennaM float64 `json:"he"` + RangeKm float64 `json:"range_km"` + FrequencyMHz float64 `json:"frequency_mhz"` + KFactor float64 `json:"k_factor"` +} + +// PlannerViewshedResponse — /api/planner/viewshed. Cells is the base64 of +// Rows×Cols bytes over BBox (s, w, n, e), row 0 north, row-major; each byte +// is users | repeaters<<4, a nibble of 0 meaning no data (viewshedGrid). +type PlannerViewshedResponse struct { + Source string `json:"source"` + Params PlannerViewshedParams `json:"params"` + BBox [4]float64 `json:"bbox"` + Rows int `json:"rows"` + Cols int `json:"cols"` + CellKm float64 `json:"cell_km"` + Cells string `json:"cells"` + Links []PlannerViewshedLink `json:"links"` // live repeaters within range, nearest first + Warnings []string `json:"warnings"` + // Truncated: more repeaters/rooms in the view than plannerMaxNodes; the + // farthest from the site were left out of links. + Truncated bool `json:"truncated"` +} + +type PlannerViewshedParams struct { + Site geoPointJSON `json:"site"` + AntennaM float64 `json:"antenna_m"` + RxAntennaM float64 `json:"rx_antenna_m"` + RangeKm float64 `json:"range_km"` + FrequencyMHz float64 `json:"frequency_mhz"` + KFactor float64 `json:"k_factor"` + UserReach PlannerViewshedUserReach `json:"user_reach"` +} + +// PlannerViewshedUserReach is PlannerUserReach as the viewshed response +// reports it, in the response's snake_case. +type PlannerViewshedUserReach struct { + D50Km float64 `json:"d50_km"` + Slope float64 `json:"slope"` +} + +// PlannerViewshedLink: the site → repeater link, site at AntennaM and the +// repeater at RxAntennaM. +type PlannerViewshedLink struct { + PubKey string `json:"pubkey"` + Name string `json:"name"` + Lat float64 `json:"lat"` + Lon float64 `json:"lon"` + Link PlannerLink `json:"link"` +} + +// PlannerRelayOption: BottleneckPct = min(LegA, LegB).ClearancePct. Options +// are ranked by bottleneck, then total distance. Up to 5 per list; LegA/LegB +// carry ElevM so the UI can draw both profiles without another request. +type PlannerRelayOption struct { + Kind string `json:"kind"` // existing | open + PubKey string `json:"pubkey,omitempty"` + Name string `json:"name,omitempty"` + Lat float64 `json:"lat"` + Lon float64 `json:"lon"` + ElevM float64 `json:"elev_m"` + AntennaM float64 `json:"antenna_m"` + LegA PlannerLink `json:"leg_a"` + LegB PlannerLink `json:"leg_b"` + BottleneckPct float64 `json:"bottleneck_pct"` +} + +type geoPointJSON struct { + Lat float64 `json:"lat"` + Lon float64 `json:"lon"` +} + +type geoBBoxJSON struct { + S float64 `json:"s"` + W float64 `json:"w"` + N float64 `json:"n"` + E float64 `json:"e"` +} + +// PlannerPlanResponse — /api/planner/coverage (repeater backbone plan). +// +// Objective (lexicographic, greedy, "suggested, not optimal"): +// 1. fewer backbone components (isolated repeaters count as components), +// ties → larger largest component; +// 2. fewer cut vertices (single points of failure), weighted by the size of +// the smaller side they separate; +// 3. more in-area repeaters reached at solid quality. +// +// Status: improved | connected (backbone was already one component; sites are +// redundancy picks) | no_gain (no candidate improves anything). +type PlannerPlanResponse struct { + Area geoBBoxJSON `json:"area"` + Params PlannerPlanParams `json:"params"` + Source string `json:"source"` + Status string `json:"status"` + Baseline PlannerSummary `json:"baseline"` + Final PlannerSummary `json:"final"` + Nodes []PlannerNodeOut `json:"nodes"` + Edges []PlannerEdgeOut `json:"edges"` + Sites []PlannerSite `json:"sites"` + Warnings []string `json:"warnings"` + Truncated bool `json:"truncated"` + ComputedAt time.Time `json:"computed_at"` +} + +type PlannerPlanParams struct { + Sites int `json:"sites"` + RangeKm float64 `json:"range_km"` + NewAntennaM float64 `json:"hr"` + ExistingAntennaM float64 `json:"he"` + Baseline string `json:"baseline"` // predicted | observed + IncludeStale bool `json:"stale"` + FrequencyMHz float64 `json:"frequency_mhz"` + KFactor float64 `json:"k_factor"` + MinClearance float64 `json:"min_clearance"` +} + +type PlannerSummary struct { + Repeaters int `json:"repeaters"` // in-area repeaters/rooms counted + Components int `json:"components"` + LargestComponent int `json:"largest_component"` + Isolated int `json:"isolated"` + CutVertices int `json:"cut_vertices"` + StaleExcluded int `json:"stale_excluded"` +} + +// PlannerNodeOut — only fields /api/nodes already exposes, so the planner +// reveals nothing about a node that the nodes list does not. +type PlannerNodeOut struct { + PubKey string `json:"pubkey"` + Name string `json:"name"` + Role string `json:"role"` + Lat float64 `json:"lat"` + Lon float64 `json:"lon"` + Stale bool `json:"stale"` + InArea bool `json:"in_area"` + Component int `json:"component"` // baseline component id (0 = largest) +} + +// PlannerEdgeOut: A/B index Nodes. Class: observed | solid | marginal. +type PlannerEdgeOut struct { + A int `json:"a"` + B int `json:"b"` + Class string `json:"class"` + DistanceKm float64 `json:"distance_km"` + ClearancePct float64 `json:"clearance_pct"` +} + +// PlannerSite is one greedy pick. Reason: joins | redundancy | reach. +type PlannerSite struct { + Step int `json:"step"` // 1-based greedy order + Lat float64 `json:"lat"` + Lon float64 `json:"lon"` + ElevM float64 `json:"elev_m"` + AntennaM float64 `json:"antenna_m"` + Reason string `json:"reason"` + Gain PlannerGain `json:"gain"` + After PlannerSummary `json:"after"` // backbone summary after this pick + Links []PlannerSiteLink `json:"links"` + // JoinsComponents lists the baseline component ids this site connects. + JoinsComponents []int `json:"joins_components"` +} + +type PlannerGain struct { + ComponentsJoined int `json:"components_joined"` + CutVerticesRemoved int `json:"cut_vertices_removed"` + RepeatersReached int `json:"repeaters_reached"` +} + +// PlannerSiteLink: Node indexes Nodes, or -1 when the peer is an earlier +// site (PeerStep = its step). Class: solid | marginal. +type PlannerSiteLink struct { + Node int `json:"node"` + PeerStep int `json:"peer_step,omitempty"` + DistanceKm float64 `json:"distance_km"` + ClearancePct float64 `json:"clearance_pct"` + Class string `json:"class"` +} diff --git a/cmd/server/planner_viewshed.go b/cmd/server/planner_viewshed.go new file mode 100644 index 000000000..379597350 --- /dev/null +++ b/cmd/server/planner_viewshed.go @@ -0,0 +1,239 @@ +package main + +// Viewshed raster for the planner's Coverage tab: for one candidate site, +// each cell of a grid around it gets a Users class (handheld reach curve, +// lowered in deep terrain shadow) and a Repeaters class (the same LOS +// verdict a Chain leg site→cell would get). + +import ( + "context" + "math" + "runtime" + "sync" + "sync/atomic" +) + +const ( + // viewshedUserRxM: handheld height above ground for the shadow test. + viewshedUserRxM = 1.5 + // viewshedShadowClearance: a ground path whose worst first-Fresnel + // clearance is below this (the LOS this many F1 radii under terrain) + // counts as deep shadow. + viewshedShadowClearance = -1.0 + // viewshedShadowDrop: Users classes dropped in deep shadow (floor 1). + viewshedShadowDrop = 2 +) + +type viewshedParams struct { + Site geoPoint + SiteM, RxM, RangeKm, FreqMHz, KFactor float64 + Reach PlannerUserReach +} + +// viewshedGrid: Rows×Cols cells over BBox, row 0 north, row-major; cell +// (r, c) is centred at the middle of the r-th of Rows equal latitude bands +// (from N) and the c-th of Cols equal longitude bands (from W). Each byte +// is users | repeaters<<4; a nibble of 0 means no data (outside RangeKm, or +// no terrain at the cell, the site or on the path between). +type viewshedGrid struct { + BBox geoBBox + Rows, Cols int + CellKm float64 + Cells []byte +} + +func viewshedBBox(site geoPoint, rangeKm float64) geoBBox { + return plannerExpandBBox(geoBBox{S: site.Lat, W: site.Lon, N: site.Lat, E: site.Lon}, rangeKm) +} + +// viewshedCellKm: 200 m, coarser above 30 km so a grid stays near 300×300. +func viewshedCellKm(rangeKm float64) float64 { return math.Max(0.2, rangeKm/150) } + +// userReachP is the handheld reach curve P = 1/(1+exp((ln d − ln d50)/s)). +func userReachP(dKm float64, r PlannerUserReach) float64 { + return 1 / (1 + math.Exp((math.Log(dKm)-math.Log(r.D50Km))/r.Slope)) +} + +func userReachClass(p float64) byte { + switch { + case p < 0.10: + return 1 + case p < 0.25: + return 2 + case p < 0.50: + return 3 + case p < 0.75: + return 4 + } + return 5 +} + +// viewshedNearClearance is the lower bound of the Repeaters "slightly +// blocked" class: the line of sight at most this fraction of the first +// Fresnel radius under terrain. Calibrated loosely on one repeater +// (2026-11-16, 17 heard links): every link heard within 16 km had a clearance +// of 2% to 54%, so the textbook 60%/100% classes never mark working links on +// SRTM; within 20 km, 12 of 15 links with clearance >= 0 were heard against 1 +// of 8 below 0; one link was heard at -20%. +const viewshedNearClearance = -0.2 + +// repeaterClass maps a first-Fresnel clearance (1 = fully clear) to the +// Repeaters class: 3 line of sight (>= 0), 2 slightly blocked (down to +// viewshedNearClearance), 1 blocked. +func repeaterClass(c float64) byte { + switch { + case c >= 0: + return 3 + case c >= viewshedNearClearance: + return 2 + } + return 1 +} + +// viewshedWorkers is how many goroutines computeViewshed spreads rows over. +// The planner runs one Coverage/Viewshed job at a time (plannerCovSlots), so +// this is also the most CPUs a viewshed takes from the live app. +func viewshedWorkers() int { return max(1, min(4, runtime.GOMAXPROCS(0)/2)) } + +// clearancePair is two e.clearance walks of the same path a→b in one pass: +// the worst first-Fresnel clearance with the receiver hbR above ground +// (floor −Inf, every sample: crOK=false means no terrain on the path, or ctx +// cancelled with e.err set), and whether the worst clearance with the +// receiver hbU is below shadowFloor. Each result equals that of its own +// e.clearance call. +func (e *planLinkEval) clearancePair(a, b geoPoint, distKm, ha, hbR, hbU, shadowFloor float64) (cr float64, crOK, shadow bool) { + cr, cu, ok := e.clearanceWalk(a, b, distKm, ha, hbR, math.Inf(-1), hbU, true) + if !ok { + return 0, false, false + } + return cr, true, cu < shadowFloor +} + +// computeViewshed profiles site→cell for every cell in range: two +// clearance walks per cell (receiver at RxM for Repeaters, at +// viewshedUserRxM for the Users shadow test). progress gets the fraction of +// rows done. Errors: ctx.Err() only. +func computeViewshed(ctx context.Context, v terrainView, p viewshedParams, progress func(float64)) (viewshedGrid, error) { + return computeViewshedN(ctx, v, p, viewshedWorkers(), progress) +} + +// computeViewshedN is computeViewshed over up to workers goroutines. Cells are +// independent and each row's bytes are written by one worker only, so the +// grid is identical for any workers. progress is called serially with a +// non-decreasing fraction that ends at exactly 1. +func computeViewshedN(ctx context.Context, v terrainView, p viewshedParams, workers int, progress func(float64)) (viewshedGrid, error) { + cellKm := viewshedCellKm(p.RangeKm) + bb := viewshedBBox(p.Site, p.RangeKm) + cosLat := math.Cos(p.Site.Lat * math.Pi / 180) + rows := max(1, int(math.Ceil((bb.N-bb.S)*plannerKmPerDeg/cellKm))) + cols := max(1, int(math.Ceil((bb.E-bb.W)*plannerKmPerDeg*cosLat/cellKm))) + g := viewshedGrid{BBox: bb, Rows: rows, Cols: cols, CellKm: cellKm, Cells: make([]byte, rows*cols)} + if err := ctx.Err(); err != nil { + return viewshedGrid{}, err + } + if _, ok := v.ElevationAt(p.Site.Lat, p.Site.Lon); !ok { + return g, nil // no terrain at the site: every cell is no data + } + dLat := (bb.N - bb.S) / float64(rows) + dLon := (bb.E - bb.W) / float64(cols) + // row fills row r with e; it reports e.err (ctx cancelled). + row := func(e *planLinkEval, r int) error { + lat := bb.N - (float64(r)+0.5)*dLat + for c := 0; c < cols; c++ { + cell := geoPoint{Lat: lat, Lon: bb.W + (float64(c)+0.5)*dLon} + d := geoDistKm(p.Site, cell) + if d > p.RangeKm { + continue + } + cr, ok, shadow := e.clearancePair(p.Site, cell, d, p.SiteM, p.RxM, viewshedUserRxM, viewshedShadowClearance) + if !ok { + continue // no terrain on the path (or ctx cancelled: checked below) + } + users := userReachClass(userReachP(d, p.Reach)) + if shadow { + if users > viewshedShadowDrop { + users -= viewshedShadowDrop + } else { + users = 1 + } + } + g.Cells[r*cols+c] = users | repeaterClass(cr)<<4 + } + return e.err + } + workers = max(1, min(workers, rows)) + if workers == 1 { + e := newPlanLinkEval(ctx, v, p.FreqMHz, p.KFactor) + for r := 0; r < rows; r++ { + if err := row(e, r); err != nil { + return viewshedGrid{}, err + } + if progress != nil { + progress(float64(r+1) / float64(rows)) + } + } + } else { + // Rows are handed out one at a time (they differ in length), each + // worker with its own planLinkEval, which is not safe to share. + var ( + next, stop atomic.Int64 + mu sync.Mutex // serialises progress and the first error + done int + firstErr error + panicked any + wg sync.WaitGroup + ) + for w := 0; w < workers; w++ { + wg.Add(1) + go func() { + defer wg.Done() + defer func() { + // Re-raised below on the caller's goroutine, where the + // job runner recovers it; here it would kill the process. + if r := recover(); r != nil { + mu.Lock() + if panicked == nil { + panicked = r + } + mu.Unlock() + stop.Store(1) + } + }() + e := newPlanLinkEval(ctx, v, p.FreqMHz, p.KFactor) + for stop.Load() == 0 { + r := int(next.Add(1) - 1) + if r >= rows { + return + } + err := row(e, r) + mu.Lock() + if err != nil && firstErr == nil { + firstErr = err + } + if err == nil { + done++ + if progress != nil { + progress(float64(done) / float64(rows)) + } + } + mu.Unlock() + if err != nil { + stop.Store(1) + return + } + } + }() + } + wg.Wait() + if panicked != nil { + panic(panicked) + } + if firstErr != nil { + return viewshedGrid{}, firstErr + } + } + if err := ctx.Err(); err != nil { + return viewshedGrid{}, err + } + return g, nil +} diff --git a/cmd/server/planner_viewshed_test.go b/cmd/server/planner_viewshed_test.go new file mode 100644 index 000000000..d9989ac1b --- /dev/null +++ b/cmd/server/planner_viewshed_test.go @@ -0,0 +1,832 @@ +package main + +import ( + "bytes" + "context" + "errors" + "fmt" + "math" + "math/rand" + "sort" + "sync/atomic" + "testing" +) + +// flatTerrainView is level ground everywhere. +type flatTerrainView struct{ elevM float64 } + +func (v flatTerrainView) ElevationAt(lat, lon float64) (float64, bool) { return v.elevM, true } + +// ridgeTerrainView is level ground with a north-south ridge between two +// longitudes. +type ridgeTerrainView struct { + baseM, ridgeM float64 + west, east float64 +} + +func (v ridgeTerrainView) ElevationAt(lat, lon float64) (float64, bool) { + if lon >= v.west && lon <= v.east { + return v.baseM + v.ridgeM, true + } + return v.baseM, true +} + +var viewshedTestSite = geoPoint{Lat: 30.5, Lon: -97.5} + +func viewshedTestParams(rangeKm float64) viewshedParams { + return viewshedParams{ + Site: viewshedTestSite, SiteM: 10, RxM: 5, RangeKm: rangeKm, + FreqMHz: 869.525, KFactor: 4.0 / 3.0, + Reach: PlannerUserReach{D50Km: defaultPlannerUserD50Km, Slope: defaultPlannerUserSlope}, + } +} + +// viewshedCellCenter mirrors the documented grid layout: row 0 north, +// row-major, cell centres at the middle of equal bbox divisions. +func viewshedCellCenter(g viewshedGrid, r, c int) geoPoint { + return geoPoint{ + Lat: g.BBox.N - (float64(r)+0.5)*(g.BBox.N-g.BBox.S)/float64(g.Rows), + Lon: g.BBox.W + (float64(c)+0.5)*(g.BBox.E-g.BBox.W)/float64(g.Cols), + } +} + +func mustViewshed(t testing.TB, v terrainView, p viewshedParams) viewshedGrid { + t.Helper() + g, err := computeViewshed(context.Background(), v, p, nil) + checkViewshedGrid(t, g, err) + return g +} + +func checkViewshedGrid(t testing.TB, g viewshedGrid, err error) { + t.Helper() + if err != nil { + t.Fatalf("computeViewshed: %v", err) + } + if len(g.Cells) != g.Rows*g.Cols || g.Rows == 0 || g.Cols == 0 { + t.Fatalf("grid %dx%d with %d cells", g.Rows, g.Cols, len(g.Cells)) + } +} + +func TestUserReachP(t *testing.T) { + r := PlannerUserReach{D50Km: 2.7, Slope: 0.30} + if p := userReachP(2.7, r); math.Abs(p-0.5) > 1e-9 { + t.Errorf("P(2.7) = %v, want 0.5", p) + } + if p := userReachP(1.0, r); !(p > 0.95) { + t.Errorf("P(1) = %v, want > 0.95", p) + } + if p := userReachP(10, r); !(p < 0.02) { + t.Errorf("P(10) = %v, want < 0.02", p) + } +} + +func TestUserReachClassBounds(t *testing.T) { + for _, tc := range []struct { + p float64 + want byte + }{{0.0999, 1}, {0.10, 2}, {0.2499, 2}, {0.25, 3}, {0.50, 4}, {0.75, 5}} { + if got := userReachClass(tc.p); got != tc.want { + t.Errorf("userReachClass(%v) = %d, want %d", tc.p, got, tc.want) + } + } +} + +func TestRepeaterClass(t *testing.T) { + for _, tc := range []struct { + c float64 + want byte + }{ + {1.5, 3}, {1, 3}, {0.6, 3}, {0, 3}, + {-0.0001, 2}, {-0.2, 2}, + {-0.2001, 1}, {-1, 1}, {-6, 1}, + } { + if got := repeaterClass(tc.c); got != tc.want { + t.Errorf("repeaterClass(%v) = %d, want %d", tc.c, got, tc.want) + } + } +} + +func TestViewshedCellKm(t *testing.T) { + if got := viewshedCellKm(10); got != 0.2 { + t.Errorf("viewshedCellKm(10) = %v, want 0.2", got) + } + if got := viewshedCellKm(100); math.Abs(got-100.0/150) > 1e-12 { + t.Errorf("viewshedCellKm(100) = %v, want %v", got, 100.0/150) + } +} + +// On flat ground the Repeaters verdict depends on distance only. With the +// planner's default heights (10 m site, 5 m receiver) the first Fresnel zone +// already grazes the ground well inside 3 km, so the "clear within 3 km" +// check runs with masts high enough for it (30 m / 15 m); both cases check +// the analyzeLOS equality, the plain Users curve and monotonic classes. +func TestViewshedFlatTerrainIsPlainCurve(t *testing.T) { + for _, tc := range []struct { + name string + siteM, rxM float64 + clearWithinKm float64 // 0: not asserted + }{ + {"masts 30m/15m", 30, 15, 3}, + {"defaults 10m/5m", 10, 5, 0}, + } { + t.Run(tc.name, func(t *testing.T) { + p := viewshedTestParams(30) + p.SiteM, p.RxM = tc.siteM, tc.rxM + checkFlatViewshed(t, p, tc.clearWithinKm) + }) + } +} + +func checkFlatViewshed(t *testing.T, p viewshedParams, clearWithinKm float64) { + const elev = 50.0 + v := flatTerrainView{elevM: elev} + g := mustViewshed(t, v, p) + if g.Rows > 305 || g.Cols > 305 { + t.Errorf("grid %dx%d exceeds ~300x300", g.Rows, g.Cols) + } + lp := losParams{FreqMHz: p.FreqMHz, KFactor: p.KFactor, AntennaAM: p.SiteM, AntennaBM: p.RxM} + type cell struct { + d float64 + rep byte + } + var cells []cell + for r := 0; r < g.Rows; r++ { + for c := 0; c < g.Cols; c++ { + pt := viewshedCellCenter(g, r, c) + d := geoDistKm(p.Site, pt) + b := g.Cells[r*g.Cols+c] + if d > p.RangeKm { + continue + } + users, rep := b&0x0f, b>>4 + if want := userReachClass(userReachP(d, p.Reach)); users != want { + t.Fatalf("cell (%d,%d) at %.2f km: users %d, want plain curve %d", r, c, d, users, want) + } + profile := make([]float64, planProfileSamples(d)) + for i := range profile { + profile[i] = elev + } + res, ok := analyzeLOS(profile, d, lp) + if !ok { + t.Fatalf("analyzeLOS failed at %.2f km", d) + } + if want := repeaterClass(res.Clearance); rep != want { + t.Fatalf("cell (%d,%d) at %.2f km: repeaters %d, want %d (%s)", r, c, d, rep, want, res.Verdict) + } + if d <= clearWithinKm && rep != 3 { + t.Fatalf("cell (%d,%d) at %.2f km: repeaters %d, want 3 within %.0f km", r, c, d, rep, clearWithinKm) + } + cells = append(cells, cell{d, rep}) + } + } + if len(cells) == 0 { + t.Fatal("no cell in range") + } + // Flat terrain: the class depends on distance only, so along every ray + // (and across all of them) it never increases with distance. + sort.Slice(cells, func(i, j int) bool { return cells[i].d < cells[j].d }) + for i := 1; i < len(cells); i++ { + if cells[i].rep > cells[i-1].rep { + t.Fatalf("repeaters class rises from %d at %.3f km to %d at %.3f km", + cells[i-1].rep, cells[i-1].d, cells[i].rep, cells[i].d) + } + } + // First distance at which each class appears, for the report. + first := map[byte]float64{} + for _, c := range cells { + if _, seen := first[c.rep]; !seen { + first[c.rep] = c.d + } + } + t.Logf("site %.0f m / rx %.0f m: repeaters class first seen at km %v (4 clear, 3 clear60, 2 marginal, 1 blocked)", + p.SiteM, p.RxM, first) + + // R2: where earth curvature alone puts the handheld path into deep + // shadow on flat terrain, up to the largest range the planner offers. + e := newPlanLinkEval(context.Background(), v, p.FreqMHz, p.KFactor) + for d := 0.1; d <= defaultPlannerMaxLegKm; d += 0.1 { + pt := geoPoint{Lat: p.Site.Lat, Lon: p.Site.Lon + d/(plannerKmPerDeg*math.Cos(p.Site.Lat*math.Pi/180))} + dd := geoDistKm(p.Site, pt) + if c, _ := e.clearance(p.Site, pt, dd, p.SiteM, viewshedUserRxM, math.Inf(-1)); c < viewshedShadowClearance { + t.Logf("site %.0f m: users-layer curvature shadow starts at %.1f km (plain curve class there %d)", + p.SiteM, dd, userReachClass(userReachP(dd, p.Reach))) + return + } + } + t.Logf("site %.0f m: no users-layer curvature shadow within %.0f km", p.SiteM, defaultPlannerMaxLegKm) +} + +func TestViewshedRidgeShadow(t *testing.T) { + p := viewshedTestParams(30) + // A wider handheld reach so the curve is still high 10 km out and the + // shadow drop is visible above the class-1 floor. + p.Reach = PlannerUserReach{D50Km: 20, Slope: 0.30} + cosLat := math.Cos(p.Site.Lat * math.Pi / 180) + kmToLon := func(km float64) float64 { return km / (plannerKmPerDeg * cosLat) } + ridge := ridgeTerrainView{ + baseM: 50, ridgeM: 300, + west: p.Site.Lon + kmToLon(4.8), east: p.Site.Lon + kmToLon(5.2), + } + flat := mustViewshed(t, flatTerrainView{elevM: 50}, p) + g := mustViewshed(t, ridge, p) + if flat.Rows != g.Rows || flat.Cols != g.Cols { + t.Fatalf("grid shape differs: %dx%d vs %dx%d", flat.Rows, flat.Cols, g.Rows, g.Cols) + } + east, west := 0, 0 + for r := 0; r < g.Rows; r++ { + for c := 0; c < g.Cols; c++ { + pt := viewshedCellCenter(g, r, c) + if math.Abs(pt.Lat-p.Site.Lat)*plannerKmPerDeg > 1 { + continue + } + dx := (pt.Lon - p.Site.Lon) * plannerKmPerDeg * cosLat + i := r*g.Cols + c + fu, gu, gr := flat.Cells[i]&0x0f, g.Cells[i]&0x0f, g.Cells[i]>>4 + switch { + case math.Abs(dx-10) <= 0.5: + east++ + if gr != 1 { + t.Errorf("east cell (%d,%d): repeaters %d, want 1 (blocked)", r, c, gr) + } + if fu < 1+viewshedShadowDrop { + t.Fatalf("east cell (%d,%d): flat users %d leaves no room for the drop", r, c, fu) + } + if gu > fu-viewshedShadowDrop { + t.Errorf("east cell (%d,%d): users %d, want at most %d (flat %d)", r, c, gu, fu-viewshedShadowDrop, fu) + } + case math.Abs(dx+10) <= 0.5: + west++ + if g.Cells[i] != flat.Cells[i] { + t.Errorf("west cell (%d,%d): %#x, want flat %#x", r, c, g.Cells[i], flat.Cells[i]) + } + } + } + } + if east == 0 || west == 0 { + t.Fatalf("checked %d east and %d west cells", east, west) + } +} + +// Runs at the default heights and at mast heights so every verdict class +// is in the sample: 200 cells each. +func TestViewshedAgreesWithAnalyzeLOS(t *testing.T) { + verdicts := map[string]int{} + for _, h := range [][2]float64{{10, 5}, {30, 15}} { + p := viewshedTestParams(30) + p.SiteM, p.RxM = h[0], h[1] + checkViewshedAgainstLOS(t, p, verdicts) + } + if len(verdicts) < 4 { + t.Errorf("sample covers only verdicts %v; want all four", verdicts) + } + t.Logf("verdicts sampled: %v", verdicts) +} + +func checkViewshedAgainstLOS(t *testing.T, p viewshedParams, verdicts map[string]int) { + v := fakeTerrainView{bb: plannerExpandBBox(viewshedBBox(p.Site, p.RangeKm), 1)} + g := mustViewshed(t, v, p) + lp := losParams{FreqMHz: p.FreqMHz, KFactor: p.KFactor, AntennaAM: p.SiteM, AntennaBM: p.RxM} + rng := rand.New(rand.NewSource(2391)) + for checked := 0; checked < 200; { + r, c := rng.Intn(g.Rows), rng.Intn(g.Cols) + pt := viewshedCellCenter(g, r, c) + d := geoDistKm(p.Site, pt) + if d > p.RangeKm { + continue + } + checked++ + prof, ok := sampleTerrainProfile(v, p.Site, pt, planProfileSamples(d)) + if !ok { + t.Fatalf("no profile to cell (%d,%d)", r, c) + } + res, ok := analyzeLOS(prof, d, lp) + if !ok { + t.Fatalf("analyzeLOS failed for cell (%d,%d)", r, c) + } + verdicts[res.Verdict]++ + if got, want := g.Cells[r*g.Cols+c]>>4, repeaterClass(res.Clearance); got != want { + t.Errorf("cell (%d,%d) at %.2f km: repeaters %d, analyzeLOS %d (%s, clearance %.4f)", + r, c, d, got, want, res.Verdict, res.Clearance) + } + } +} + +func TestViewshedMissingTerrainIsNoData(t *testing.T) { + p := viewshedTestParams(30) + p.Site = geoPoint{Lat: 30.9, Lon: -97.5} + bb := plannerExpandBBox(viewshedBBox(p.Site, p.RangeKm), 1) + v := fakeTerrainView{bb: bb, missing: map[[2]int]bool{{31, -98}: true}} + g := mustViewshed(t, v, p) + missing, classed := 0, 0 + for r := 0; r < g.Rows; r++ { + for c := 0; c < g.Cols; c++ { + pt := viewshedCellCenter(g, r, c) + b := g.Cells[r*g.Cols+c] + if v.MissingAt(pt.Lat, pt.Lon) { + missing++ + if b != 0 { + t.Fatalf("cell (%d,%d) on missing terrain has %#x, want 0", r, c, b) + } + } else if b != 0 { + classed++ + } + } + } + if missing == 0 || classed == 0 { + t.Fatalf("%d cells on missing terrain, %d classed elsewhere", missing, classed) + } +} + +func TestViewshedMissingSiteIsAllNoData(t *testing.T) { + // A missing site still allocates the largest offered grid. + p := viewshedTestParams(60) + v := fakeTerrainView{bb: plannerExpandBBox(viewshedBBox(p.Site, p.RangeKm), 1), + missing: map[[2]int]bool{{30, -98}: true}} + g := mustViewshed(t, v, p) + if g.Rows > 305 || g.Cols > 305 { + t.Fatalf("60 km grid %dx%d exceeds ~300x300", g.Rows, g.Cols) + } + for i, b := range g.Cells { + if b != 0 { + t.Fatalf("cell %d = %#x with the site on missing terrain", i, b) + } + } +} + +func TestViewshedOutsideRangeIsNoData(t *testing.T) { + p := viewshedTestParams(20) + g := mustViewshed(t, flatTerrainView{elevM: 50}, p) + for _, rc := range [][2]int{{0, 0}, {0, g.Cols - 1}, {g.Rows - 1, 0}, {g.Rows - 1, g.Cols - 1}} { + if b := g.Cells[rc[0]*g.Cols+rc[1]]; b != 0 { + t.Errorf("corner cell %v = %#x, want 0", rc, b) + } + } + mid := g.Cells[(g.Rows/2)*g.Cols+g.Cols/2] + if mid&0x0f == 0 || mid>>4 == 0 { + t.Errorf("centre cell = %#x, want both layers classed", mid) + } +} + +func TestViewshedHonoursContext(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + _, err := computeViewshed(ctx, flatTerrainView{elevM: 50}, viewshedTestParams(30), nil) + if !errors.Is(err, context.Canceled) { + t.Fatalf("err = %v, want context.Canceled", err) + } +} + +func TestViewshedReportsProgress(t *testing.T) { + var last float64 + calls := 0 + _, err := computeViewshed(context.Background(), flatTerrainView{elevM: 50}, viewshedTestParams(10), + func(f float64) { + if f < last { + t.Errorf("progress went back from %v to %v", last, f) + } + last = f + calls++ + }) + if err != nil { + t.Fatal(err) + } + if calls == 0 || last != 1 { + t.Errorf("progress: %d calls, last %v; want calls ending at 1", calls, last) + } +} + +// computeViewshedRef is the original single-goroutine, two-walk +// computeViewshed, kept as the oracle the optimised one must match byte for +// byte. computeViewshed profiles site→cell for every cell in range: two +// clearance walks per cell (receiver at RxM for Repeaters, at +// viewshedUserRxM for the Users shadow test). progress gets the fraction of +// rows done. Errors: ctx.Err() only. +func computeViewshedRef(ctx context.Context, v terrainView, p viewshedParams, progress func(float64)) (viewshedGrid, error) { + cellKm := viewshedCellKm(p.RangeKm) + bb := viewshedBBox(p.Site, p.RangeKm) + cosLat := math.Cos(p.Site.Lat * math.Pi / 180) + rows := max(1, int(math.Ceil((bb.N-bb.S)*plannerKmPerDeg/cellKm))) + cols := max(1, int(math.Ceil((bb.E-bb.W)*plannerKmPerDeg*cosLat/cellKm))) + g := viewshedGrid{BBox: bb, Rows: rows, Cols: cols, CellKm: cellKm, Cells: make([]byte, rows*cols)} + if err := ctx.Err(); err != nil { + return viewshedGrid{}, err + } + if _, ok := v.ElevationAt(p.Site.Lat, p.Site.Lon); !ok { + return g, nil // no terrain at the site: every cell is no data + } + e := newPlanLinkEval(ctx, v, p.FreqMHz, p.KFactor) + dLat := (bb.N - bb.S) / float64(rows) + dLon := (bb.E - bb.W) / float64(cols) + for r := 0; r < rows; r++ { + lat := bb.N - (float64(r)+0.5)*dLat + for c := 0; c < cols; c++ { + cell := geoPoint{Lat: lat, Lon: bb.W + (float64(c)+0.5)*dLon} + d := geoDistKm(p.Site, cell) + if d > p.RangeKm { + continue + } + cr, ok := e.clearance(p.Site, cell, d, p.SiteM, p.RxM, math.Inf(-1)) + if !ok { + continue // no terrain on the path (or ctx cancelled: checked below) + } + users := userReachClass(userReachP(d, p.Reach)) + // Same path as above, so terrain is present; the walk stops at + // the first sample below the shadow threshold. + if cu, ok := e.clearance(p.Site, cell, d, p.SiteM, viewshedUserRxM, viewshedShadowClearance); !ok && cu < viewshedShadowClearance { + if users > viewshedShadowDrop { + users -= viewshedShadowDrop + } else { + users = 1 + } + } + g.Cells[r*cols+c] = users | repeaterClass(cr)<<4 + } + if e.err != nil { + return viewshedGrid{}, e.err + } + if progress != nil { + progress(float64(r+1) / float64(rows)) + } + } + if err := ctx.Err(); err != nil { + return viewshedGrid{}, err + } + return g, nil +} + +// roughSRTMView is a real srtmView (bilinear lookups over int16 tiles) over +// bb (relief scaled by scale: 1 rough, 0.1 gentle), with deterministic hills and a few sharp ridges, so the paths see +// shadow, partial blockage and clear ground. +func roughSRTMView(bb geoBBox, scale float64) *srtmView { + sp, _ := srtmSpanOf(bb) + v := &srtmView{span: sp, grids: make([][]int16, sp.count())} + for i := range v.grids { + k := sp.key(i) + g := make([]int16, srtmSide*srtmSide) + for r := 0; r < srtmSide; r++ { + lat := float64(k.lat+1) - float64(r)/srtmCells + for c := 0; c < srtmSide; c++ { + lon := float64(k.lon) + float64(c)/srtmCells + e := 300 + scale*(120*math.Sin(lat*37)*math.Cos(lon*29)+60*math.Sin(lat*151+lon*113)) + if math.Mod(lon*40, 1) < 0.08 { // N-S ridges ~2 km wide every ~2.5 km + e += 90 * scale + } + g[r*srtmSide+c] = int16(e) + } + } + v.grids[i] = g + } + return v +} + +// viewshedEquivalenceCases are the terrains and parameters the optimised +// code is compared with computeViewshedRef on. +func viewshedEquivalenceCases() []struct { + name string + v terrainView + p viewshedParams +} { + var cs []struct { + name string + v terrainView + p viewshedParams + } + sites := []geoPoint{viewshedTestSite, {Lat: 45.2, Lon: 7.1}, {Lat: -33.9, Lon: 151.2}} + for _, site := range sites { + for _, rng := range []float64{3, 12, 30} { + if rng == 30 && site != viewshedTestSite { + continue // the slow case once is enough + } + p := viewshedTestParams(rng) + p.Site = site + bb := plannerExpandBBox(viewshedBBox(site, rng), 1) + ridge := ridgeTerrainView{baseM: 100, ridgeM: 80, west: site.Lon + 0.05, east: site.Lon + 0.07} + // The full-size 30 km grid costs about 3 s per terrain. Its cell + // size is the same 0.2 km floor as 12 km; what it adds is longer + // rays with more samples per profile. The ridge terrain covers + // those, with level ground west of the ridge and shadow east of it. + if rng != 30 { + cs = append(cs, + struct { + name string + v terrainView + p viewshedParams + }{fmt.Sprintf("fake/%.1f,%.1f/%gkm", site.Lat, site.Lon, rng), fakeTerrainView{bb: bb}, p}, + struct { + name string + v terrainView + p viewshedParams + }{fmt.Sprintf("flat/%.1f,%.1f/%gkm", site.Lat, site.Lon, rng), flatTerrainView{elevM: 50}, p}, + ) + } + cs = append(cs, struct { + name string + v terrainView + p viewshedParams + }{fmt.Sprintf("ridge/%.1f,%.1f/%gkm", site.Lat, site.Lon, rng), ridgeTerrainView{ridge.baseM, ridge.ridgeM, ridge.west, ridge.east}, p}) + } + } + return cs +} + +func TestViewshedMatchesReference(t *testing.T) { + check := func(name string, v terrainView, p viewshedParams) { + want, err := computeViewshedRef(context.Background(), v, p, nil) + if err != nil { + t.Fatalf("%s: ref: %v", name, err) + } + for _, workers := range []int{1, 3, 7} { + got, err := computeViewshedN(context.Background(), v, p, workers, nil) + if err != nil { + t.Fatalf("%s: workers=%d: %v", name, workers, err) + } + if got.Rows != want.Rows || got.Cols != want.Cols || got.BBox != want.BBox || got.CellKm != want.CellKm || + !bytes.Equal(got.Cells, want.Cells) { + diff := 0 + for i := range want.Cells { + if got.Cells[i] != want.Cells[i] { + diff++ + } + } + t.Fatalf("%s: workers=%d: %d of %d cells differ from the reference", name, workers, diff, len(want.Cells)) + } + } + } + for _, c := range viewshedEquivalenceCases() { + check(c.name, c.v, c.p) + } + // Real tile lookups with ridges and shadow, and a tile without data. + for _, rng := range []float64{8, 20} { + p := viewshedTestParams(rng) + bb := viewshedBBox(p.Site, rng) + v := roughSRTMView(bb, 1) + check(fmt.Sprintf("srtm/%gkm", rng), v, p) + holed := &srtmView{span: v.span, grids: append([][]int16(nil), v.grids...)} + holed.grids[0] = nil + check(fmt.Sprintf("srtm-hole/%gkm", rng), holed, p) + } + mv, mp := viewshedMissingTileCase() + check("missing-tile", mv, mp) +} + +// viewshedMissingTileCase puts the site 0.05 degrees (about 5.6 km) south of a +// missing SRTM tile, so the 12 km range reaches into it. +func viewshedMissingTileCase() (fakeTerrainView, viewshedParams) { + p := viewshedTestParams(12) + p.Site = geoPoint{Lat: 30.95, Lon: -97.5} + return fakeTerrainView{bb: plannerExpandBBox(viewshedBBox(p.Site, p.RangeKm), 1), + missing: map[[2]int]bool{{31, -98}: true}}, p +} + +// TestViewshedMissingTileCaseReachesTheTile guards the missing-tile case of +// the equivalence test: it only checks missing terrain if cells in range +// have their endpoint on the missing tile and are NoData, while cells south +// of it are not. +func TestViewshedMissingTileCaseReachesTheTile(t *testing.T) { + v, p := viewshedMissingTileCase() + if missing, total := v.MissingTiles(); missing != 1 || total < 2 { + t.Fatalf("MissingTiles() = %d of %d, want 1 of at least 2", missing, total) + } + g := mustViewshed(t, v, p) + var northNoData, northData, southData int + for r := 0; r < g.Rows; r++ { + for c := 0; c < g.Cols; c++ { + pt := viewshedCellCenter(g, r, c) + if geoDistKm(p.Site, pt) > p.RangeKm*0.9 { + continue + } + b := g.Cells[r*g.Cols+c] + switch { + case pt.Lat > 31.001 && b == 0: + northNoData++ + case pt.Lat > 31.001: + northData++ + case pt.Lat < 30.999 && b != 0: + southData++ + } + } + } + if northNoData == 0 || northData != 0 || southData == 0 { + t.Fatalf("north of the tile edge %d NoData / %d with data, south %d with data; want >0 / 0 / >0", + northNoData, northData, southData) + } +} + +// TestViewshedRoughTerrainHasEveryClass guards the equivalence test above: +// it is only worth something if the terrain exercises shadow and every +// Repeaters class. +func TestViewshedRoughTerrainHasEveryClass(t *testing.T) { + p := viewshedTestParams(25) + g := mustViewshed(t, roughSRTMView(viewshedBBox(p.Site, p.RangeKm), 1), p) + var rep [4]int + for _, b := range g.Cells { + rep[b>>4]++ + } + if rep[1] == 0 || rep[2] == 0 || rep[3] == 0 { + t.Fatalf("repeater class counts %v: terrain too tame", rep) + } +} + +// TestClearancePairMatchesClearance pins clearancePair to the two +// e.clearance calls it replaces, sample for sample, on rough terrain. +func TestClearancePairMatchesClearance(t *testing.T) { + p := viewshedTestParams(40) + v := roughSRTMView(viewshedBBox(p.Site, p.RangeKm), 1) + rng := rand.New(rand.NewSource(1)) + e := newPlanLinkEval(context.Background(), v, p.FreqMHz, p.KFactor) + ref := newPlanLinkEval(context.Background(), v, p.FreqMHz, p.KFactor) + for i := 0; i < 400; i++ { + b := geoPoint{Lat: p.Site.Lat + (rng.Float64()-0.5)*0.6, Lon: p.Site.Lon + (rng.Float64()-0.5)*0.6} + d := geoDistKm(p.Site, b) + cr, ok, shadow := e.clearancePair(p.Site, b, d, p.SiteM, p.RxM, viewshedUserRxM, viewshedShadowClearance) + wantCr, wantOK := ref.clearance(p.Site, b, d, p.SiteM, p.RxM, math.Inf(-1)) + cu, uok := ref.clearance(p.Site, b, d, p.SiteM, viewshedUserRxM, viewshedShadowClearance) + wantShadow := !uok && cu < viewshedShadowClearance + if ok != wantOK || (ok && math.Float64bits(cr) != math.Float64bits(wantCr)) || shadow != wantShadow { + t.Fatalf("b=%v d=%.2f: pair (%v,%v,%v) want (%v,%v,%v)", b, d, cr, ok, shadow, wantCr, wantOK, wantShadow) + } + } +} + +func TestViewshedParallelProgress(t *testing.T) { + for _, workers := range []int{2, 4} { + var last float64 + calls := 0 + _, err := computeViewshedN(context.Background(), flatTerrainView{elevM: 50}, viewshedTestParams(10), workers, + func(f float64) { // would race under -race if not serialised + if f < last { + t.Errorf("workers=%d: progress went back from %v to %v", workers, last, f) + } + last = f + calls++ + }) + if err != nil { + t.Fatal(err) + } + if calls == 0 || last != 1 { + t.Errorf("workers=%d: %d calls, last %v; want calls ending at exactly 1", workers, calls, last) + } + } +} + +// cancelAfterView cancels its context after n lookups. +type cancelAfterView struct { + terrainView + n int64 + seen atomic.Int64 + cancel context.CancelFunc +} + +func (v *cancelAfterView) ElevationAt(lat, lon float64) (float64, bool) { + if v.seen.Add(1) == v.n { + v.cancel() + } + return v.terrainView.ElevationAt(lat, lon) +} + +func TestViewshedParallelCancelsPromptly(t *testing.T) { + p := viewshedTestParams(12) + total := countingElevations(t, p) + for _, workers := range []int{1, 4} { + ctx, cancel := context.WithCancel(context.Background()) + v := &cancelAfterView{terrainView: flatTerrainView{elevM: 50}, n: 1000, cancel: cancel} + _, err := computeViewshedN(ctx, v, p, workers, nil) + cancel() + if !errors.Is(err, context.Canceled) { + t.Fatalf("workers=%d: err = %v, want context.Canceled", workers, err) + } + // Each worker may finish its current 16-cell ctx window plus its row. + if got := v.seen.Load(); got > total/20 { + t.Errorf("workers=%d: %d lookups after cancel at 1000 (full run %d): not prompt", workers, got, total) + } + } +} + +// A panic in a worker must surface on the caller's goroutine, where the job +// runner recovers it, not kill the process. +func TestViewshedWorkerPanicReachesCaller(t *testing.T) { + // The site lookup in computeViewshedN is on the caller; let it pass. + v := &panicAfterView{terrainView: flatTerrainView{elevM: 50}, after: 1} + defer func() { + if r := recover(); r != "boom" { + t.Fatalf("recovered %v, want boom", r) + } + }() + _, _ = computeViewshedN(context.Background(), v, viewshedTestParams(10), 4, nil) + t.Fatal("no panic") +} + +type panicAfterView struct { + terrainView + after int64 + seen atomic.Int64 +} + +func (v *panicAfterView) ElevationAt(lat, lon float64) (float64, bool) { + if v.seen.Add(1) > v.after { + panic("boom") + } + return v.terrainView.ElevationAt(lat, lon) +} + +// countView counts ElevationAt calls. +type countView struct { + terrainView + n atomic.Int64 +} + +func (v *countView) ElevationAt(lat, lon float64) (float64, bool) { + v.n.Add(1) + return v.terrainView.ElevationAt(lat, lon) +} + +func countingElevations(t testing.TB, p viewshedParams) int64 { + v := &countView{terrainView: flatTerrainView{elevM: 50}} + if _, err := computeViewshedRef(context.Background(), v, p, nil); err != nil { + t.Fatal(err) + } + return v.n.Load() +} + +func measureViewshedWork(t testing.TB, rangeKm float64) (reference, singlePass int64) { + t.Helper() + p := viewshedTestParams(rangeKm) + v := &countView{terrainView: flatTerrainView{elevM: 50}} + g, err := computeViewshedN(context.Background(), v, p, 1, nil) + checkViewshedGrid(t, g, err) + cells := 0 + for _, b := range g.Cells { + if b != 0 { + cells++ + } + } + if cells == 0 { + t.Fatal("flat terrain produced no cells in range") + } + reference, singlePass = countingElevations(t, p), v.n.Load() + t.Logf("%gkm: grid %dx%d, cell %.3f km, %d cells in range; ElevationAt calls: reference %d, single pass %d", + rangeKm, g.Rows, g.Cols, g.CellKm, cells, reference, singlePass) + return reference, singlePass +} + +func TestViewshedWorkCount(t *testing.T) { + reference, singlePass := measureViewshedWork(t, 5) + // Both implementations look up the site once before walking the cells. + if singlePass <= 1 || singlePass-1 > (reference-1)/2 { + t.Fatalf("elevation lookups: reference %d, single pass %d; want at most half the path lookups", reference, singlePass) + } +} + +// Run the full diagnostic with go test -run '^$' -bench '^BenchmarkViewshedWorkCount$' -benchtime=1x. +func BenchmarkViewshedWorkCount(b *testing.B) { + for _, rangeKm := range []float64{30, 60} { + b.Run(fmt.Sprintf("%gkm", rangeKm), func(b *testing.B) { + for i := 0; i < b.N; i++ { + reference, singlePass := measureViewshedWork(b, rangeKm) + b.ReportMetric(float64(reference), "reference-lookups/op") + b.ReportMetric(float64(singlePass), "single-pass-lookups/op") + } + }) + } +} + +func benchmarkViewshed(b *testing.B, rangeKm float64, relief float64, workers int) { + p := viewshedTestParams(rangeKm) + var v terrainView = fakeTerrainView{bb: plannerExpandBBox(viewshedBBox(p.Site, p.RangeKm), 1)} + if relief > 0 { + v = roughSRTMView(viewshedBBox(p.Site, p.RangeKm), relief) + } + b.ResetTimer() + for i := 0; i < b.N; i++ { + var err error + if workers == 0 { + _, err = computeViewshedRef(context.Background(), v, p, nil) + } else { + _, err = computeViewshedN(context.Background(), v, p, workers, nil) + } + if err != nil { + b.Fatal(err) + } + } +} + +func BenchmarkViewshed30km(b *testing.B) { benchmarkViewshed(b, 30, 0, viewshedWorkers()) } + +// BenchmarkViewshedMaxLeg: the largest range the planner offers (60 km). +func BenchmarkViewshedMaxLeg(b *testing.B) { benchmarkViewshed(b, 60, 0, viewshedWorkers()) } + +// BenchmarkViewshedVariants: workers=0 is the reference implementation. +// fake is the plane fakeTerrainView; srtm and srtm-gentle are real tile +// lookups over rough and gentle relief. +func BenchmarkViewshedVariants(b *testing.B) { + for _, rangeKm := range []float64{30, 60} { + for _, terrain := range []struct { + name string + relief float64 + }{{"fake", 0}, {"srtm", 1}, {"srtm-gentle", 0.1}} { + for _, w := range []int{0, 1, 2, 4, 6} { + b.Run(fmt.Sprintf("%gkm/%s/w%d", rangeKm, terrain.name, w), func(b *testing.B) { benchmarkViewshed(b, rangeKm, terrain.relief, w) }) + } + } + } +} diff --git a/cmd/server/ratelimit_refund_test.go b/cmd/server/ratelimit_refund_test.go new file mode 100644 index 000000000..5eee4d1d0 --- /dev/null +++ b/cmd/server/ratelimit_refund_test.go @@ -0,0 +1,27 @@ +package main + +import ( + "testing" + "time" +) + +func TestRateLimiterRefundReturnsOneToken(t *testing.T) { + l := newRateLimiter(1, time.Hour) + if ok, _ := l.take("ip"); !ok { + t.Fatal("first take must succeed") + } + if ok, _ := l.take("ip"); ok { + t.Fatal("bucket of 1 must be empty after one take") + } + l.refundN("ip", 1) + if ok, _ := l.take("ip"); !ok { + t.Fatal("refund must give the token back") + } + l.refundN("ip", 1) + l.refundN("ip", 1) // never above burst + l.take("ip") + if ok, _ := l.take("ip"); ok { + t.Fatal("refund must not raise the bucket above its burst") + } + l.refundN("unknown", 1) // no bucket: no-op, no panic +} diff --git a/cmd/server/readonly_invariant_test.go b/cmd/server/readonly_invariant_test.go index 3e265655e..2c5f56066 100644 --- a/cmd/server/readonly_invariant_test.go +++ b/cmd/server/readonly_invariant_test.go @@ -3,10 +3,15 @@ package main import ( "database/sql" "fmt" + "go/ast" + "go/parser" + "go/token" "os" "path/filepath" "reflect" "regexp" + "sort" + "strconv" "strings" "testing" @@ -277,3 +282,252 @@ func TestUsersOpenIsTheOnlyServerWritePath(t *testing.T) { t.Fatalf("users.Open calls in cmd/server: %d total, %d with the measurement DB forbidden; want exactly 1 and 1", calls, good) } } + +// analyzerReadTxAllowed lists the functions allowed to open a transaction on +// the analyzer connection, as "file:func". Each is a read snapshot: several +// SELECTs that must see one consistent state. A transaction is never needed +// to read one statement, and the server has no business holding one to write. +// An entry that no longer begins a transaction fails the test, so the list +// cannot go stale and silently cover a later write. +var analyzerReadTxAllowed = map[string]bool{ + "scope_audit.go:ScopeAuditForwardingHeardIn": true, +} + +// analyzerSQLCallArgs maps database/sql methods that take SQL to the index of +// the SQL argument. +var analyzerSQLCallArgs = map[string]int{ + "Exec": 0, "ExecContext": 1, + "Query": 0, "QueryContext": 1, + "QueryRow": 0, "QueryRowContext": 1, + "Prepare": 0, "PrepareContext": 1, +} + +var analyzerWriteSQL = regexp.MustCompile(`(?i)^(INSERT|UPDATE|DELETE|REPLACE)\b`) + +// analyzerWriteViolations parses Go sources and reports, as "file:line: what", +// every place that +// +// - calls Begin / BeginTx on the analyzer connection (the conn field of *DB, +// or a *sql.DB passed around as conn) outside analyzerReadTxAllowed, or +// - passes SQL starting with INSERT, UPDATE, DELETE or REPLACE to Exec, +// Query*, or Prepare* on any receiver. In cmd/server every such receiver +// is the analyzer handle or a Tx/Stmt made from it (users.db is written +// only inside internal/users), so the receiver is not narrowed. +// +// The SQL is resolved from a string literal, a package-level string constant +// or variable, or the leading operand of a + concatenation, after leading +// whitespace and -- comments. Residual gap: SQL built at runtime +// (fmt.Sprintf, strings.Builder) cannot be resolved; TestServerDBConnIsReadOnly +// is the structural backstop for that. +func analyzerWriteViolations(t *testing.T, fset *token.FileSet, files map[string]*ast.File) []string { + t.Helper() + consts := map[string]string{} + var resolve func(e ast.Expr) (string, bool) + resolve = func(e ast.Expr) (string, bool) { + switch v := e.(type) { + case *ast.BasicLit: + if v.Kind != token.STRING { + return "", false + } + s, err := strconv.Unquote(v.Value) + return s, err == nil + case *ast.Ident: + s, ok := consts[v.Name] + return s, ok + case *ast.ParenExpr: + return resolve(v.X) + case *ast.BinaryExpr: + if v.Op == token.ADD { + return resolve(v.X) + } + } + return "", false + } + // Package-level string constants and variables, in two passes so a + // value built from another (const a = b + "...") resolves either way. + for pass := 0; pass < 2; pass++ { + for _, f := range files { + for _, d := range f.Decls { + gd, ok := d.(*ast.GenDecl) + if !ok || (gd.Tok != token.CONST && gd.Tok != token.VAR) { + continue + } + for _, spec := range gd.Specs { + vs := spec.(*ast.ValueSpec) + if len(vs.Values) != len(vs.Names) { + continue + } + for i, n := range vs.Names { + if s, ok := resolve(vs.Values[i]); ok { + consts[n.Name] = s + } + } + } + } + } + } + + isAnalyzerConn := func(e ast.Expr) bool { + switch v := e.(type) { + case *ast.Ident: + return v.Name == "conn" + case *ast.SelectorExpr: + return v.Sel.Name == "conn" + } + return false + } + leadingSQL := func(s string) string { + for { + s = strings.TrimSpace(s) + if !strings.HasPrefix(s, "--") { + return s + } + nl := strings.IndexByte(s, '\n') + if nl < 0 { + return "" + } + s = s[nl+1:] + } + } + + names := make([]string, 0, len(files)) + for name := range files { + names = append(names, name) + } + sort.Strings(names) + var out []string + seenAllowed := map[string]bool{} + for _, name := range names { + for _, d := range files[name].Decls { + fd, ok := d.(*ast.FuncDecl) + if !ok || fd.Body == nil { + continue + } + fn := name + ":" + fd.Name.Name + ast.Inspect(fd.Body, func(n ast.Node) bool { + call, ok := n.(*ast.CallExpr) + if !ok { + return true + } + sel, ok := call.Fun.(*ast.SelectorExpr) + if !ok { + return true + } + pos := fset.Position(call.Pos()) + where := fmt.Sprintf("%s:%d", name, pos.Line) + method := sel.Sel.Name + if (method == "Begin" || method == "BeginTx") && isAnalyzerConn(sel.X) { + if analyzerReadTxAllowed[fn] { + seenAllowed[fn] = true + } else { + out = append(out, where+": "+method+" on the analyzer connection in "+fd.Name.Name) + } + } + if idx, ok := analyzerSQLCallArgs[method]; ok && idx < len(call.Args) { + if q, ok := resolve(call.Args[idx]); ok { + if m := analyzerWriteSQL.FindString(leadingSQL(q)); m != "" { + out = append(out, where+": "+strings.ToUpper(m)+" passed to "+method+" in "+fd.Name.Name) + } + } + } + return true + }) + } + } + return append(out, analyzerAllowlistStale(files, seenAllowed)...) +} + +// analyzerAllowlistStale reports allowlisted read snapshots that no longer +// open a transaction, but only for files present in this parse (the self-test +// below parses fixtures, not the package). +func analyzerAllowlistStale(files map[string]*ast.File, seen map[string]bool) []string { + var out []string + for fn := range analyzerReadTxAllowed { + file := fn[:strings.IndexByte(fn, ':')] + if _, ok := files[file]; ok && !seen[fn] { + out = append(out, fn+": allowlisted read transaction no longer found; remove it from analyzerReadTxAllowed") + } + } + sort.Strings(out) + return out +} + +func parseServerSources(t *testing.T) (*token.FileSet, map[string]*ast.File) { + t.Helper() + entries, err := os.ReadDir(".") + if err != nil { + t.Fatal(err) + } + fset := token.NewFileSet() + files := map[string]*ast.File{} + for _, e := range entries { + name := e.Name() + if e.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { + continue + } + f, err := parser.ParseFile(fset, name, nil, 0) + if err != nil { + t.Fatalf("parse %s: %v", name, err) + } + files[name] = f + } + return fset, files +} + +// TestServerSourceHasNoAnalyzerWrites enforces #1856: cmd/server never opens a +// write transaction on, or sends write SQL to, the analyzer DB. The server's +// content-hash migration did both on the mode=ro handle (#1283), so it could +// never commit; it now lives in cmd/ingestor/hash_migrate.go. +func TestServerSourceHasNoAnalyzerWrites(t *testing.T) { + fset, files := parseServerSources(t) + if v := analyzerWriteViolations(t, fset, files); len(v) > 0 { + t.Errorf("cmd/server writes the analyzer DB (#1856); writes belong in cmd/ingestor:\n %s", + strings.Join(v, "\n ")) + } +} + +// TestAnalyzerWriteViolationsDetects proves the checker bites on the shapes +// the removed server hash migration used, and leaves reads alone. +func TestAnalyzerWriteViolationsDetects(t *testing.T) { + const src = `package main + +const updateHash = "UPDATE transmissions SET hash = ? WHERE id = ?" +const pruneSQL = ` + "`" + ` + -- leading comment + DELETE FROM observations WHERE id IN (` + "`" + ` + sel + ` + "`" + `)` + "`" + ` + +func migrate(store *PacketStore) { + dbTx, _ := store.db.conn.Begin() + stmt, _ := dbTx.Prepare(updateHash) + dbTx.Exec("UPDATE observations SET transmission_id = ? WHERE transmission_id = ?", 1, 2) + dbTx.ExecContext(ctx, "delete from transmissions where id = ?", 1) + dbTx.Exec(pruneSQL) + conn.BeginTx(ctx, nil) + _ = stmt +} + +func read(db *DB) { + db.conn.Query("SELECT hash FROM transmissions WHERE note = 'UPDATE'") + db.conn.QueryRow(` + "`" + ` + SELECT status FROM _async_migrations` + "`" + `) + ws.conn.Close() +} +` + fset := token.NewFileSet() + f, err := parser.ParseFile(fset, "fixture.go", src, 0) + if err != nil { + t.Fatal(err) + } + got := analyzerWriteViolations(t, fset, map[string]*ast.File{"fixture.go": f}) + want := []string{ + "fixture.go:9: Begin on the analyzer connection in migrate", + "fixture.go:10: UPDATE passed to Prepare in migrate", + "fixture.go:11: UPDATE passed to Exec in migrate", + "fixture.go:12: DELETE passed to ExecContext in migrate", + "fixture.go:13: DELETE passed to Exec in migrate", + "fixture.go:14: BeginTx on the analyzer connection in migrate", + } + if strings.Join(got, "\n") != strings.Join(want, "\n") { + t.Errorf("violations:\n %s\nwant:\n %s", strings.Join(got, "\n "), strings.Join(want, "\n ")) + } +} diff --git a/cmd/server/repeater_handlers.go b/cmd/server/repeater_handlers.go new file mode 100644 index 000000000..ad7f68896 --- /dev/null +++ b/cmd/server/repeater_handlers.go @@ -0,0 +1,368 @@ +package main + +import ( + "errors" + "log" + "net/http" + "sort" + "strconv" + + "github.com/gorilla/mux" + "github.com/meshcore-analyzer/users" +) + +type repeaterClaimerJSON struct { + DisplayName string `json:"displayName"` + ClaimedAt string `json:"claimedAt"` +} + +// repeaterClaimRefJSON is one claim as seen from the claiming user (admin +// detail, account export). +type repeaterClaimRefJSON struct { + Pubkey string `json:"pubkey"` + ClaimedAt string `json:"claimedAt"` +} + +func claimRefsJSON(claims []users.RepeaterClaim) []repeaterClaimRefJSON { + out := make([]repeaterClaimRefJSON, 0, len(claims)) + for _, c := range claims { + out = append(out, repeaterClaimRefJSON{Pubkey: c.Pubkey, ClaimedAt: rfc3339(c.ClaimedAt)}) + } + return out +} + +type repeaterInfoJSON struct { + Pubkey string `json:"pubkey"` + HeightM *float64 `json:"heightM"` + GainDBi float64 `json:"gainDbi"` + Status *string `json:"status"` + Power *string `json:"power"` + Notes string `json:"notes"` + Claimers []repeaterClaimerJSON `json:"claimers"` + UpdatedAt *string `json:"updatedAt"` + UpdatedBy *string `json:"updatedBy"` + CanEdit *bool `json:"canEdit,omitempty"` + ClaimedByMe *bool `json:"claimedByMe,omitempty"` +} + +type repeaterInfoListJSON struct { + Repeaters []repeaterInfoJSON `json:"repeaters"` +} + +func (s *Server) registerRepeaterRoutes(r *mux.Router) { + r.HandleFunc("/api/repeaters/info", s.handleRepeaterInfoList).Methods("GET") + r.HandleFunc("/api/repeaters/{pubkey}/info", s.handleRepeaterInfoGet).Methods("GET") + r.HandleFunc("/api/repeaters/{pubkey}/info", s.withUser(s.handleRepeaterInfoPut)).Methods("PUT") + r.HandleFunc("/api/repeaters/{pubkey}/claim", s.withUser(s.handleRepeaterClaim)).Methods("POST") + r.HandleFunc("/api/repeaters/{pubkey}/claim", s.withUser(s.handleRepeaterUnclaim)).Methods("DELETE") + r.HandleFunc("/api/admin/repeaters/{pubkey}/claims/{userId}", s.withAdmin(s.handleAdminRepeaterUnclaim)).Methods("DELETE") +} + +func stringPtrOrNil(s string) *string { + if s == "" { + return nil + } + return &s +} + +func claimersJSON(claims []users.RepeaterClaim) []repeaterClaimerJSON { + out := make([]repeaterClaimerJSON, 0, len(claims)) + for _, c := range claims { + out = append(out, repeaterClaimerJSON{DisplayName: c.DisplayName, ClaimedAt: rfc3339(c.ClaimedAt)}) + } + return out +} + +// repeaterInfoBase fills the stored fields; info may be nil (no row). +func repeaterInfoBase(pk string, info *users.RepeaterInfo, claims []users.RepeaterClaim) repeaterInfoJSON { + out := repeaterInfoJSON{Pubkey: pk, Claimers: claimersJSON(claims)} + if info == nil { + return out + } + out.HeightM = info.HeightM + out.GainDBi = info.GainDBi + out.Status = stringPtrOrNil(info.Status) + out.Power = stringPtrOrNil(info.Power) + out.Notes = info.Notes + t := rfc3339(info.UpdatedAt) + out.UpdatedAt = &t + if info.UpdatedBy != nil { + out.UpdatedBy = stringPtrOrNil(info.UpdatedByName) + } + return out +} + +// repeaterInfoFor builds one entry. CanEdit and ClaimedByMe are set only when +// u is non-nil. +func (s *Server) repeaterInfoFor(pk string, u *users.User) (repeaterInfoJSON, error) { + info, err := s.auth.st.GetRepeaterInfo(pk) + if errors.Is(err, users.ErrNotFound) { + info = nil + } else if err != nil { + return repeaterInfoJSON{}, err + } + claims, err := s.auth.st.RepeaterClaims(pk) + if err != nil { + return repeaterInfoJSON{}, err + } + out := repeaterInfoBase(pk, info, claims) + if u != nil { + can, err := s.auth.st.CanEditRepeater(u, pk) + if err != nil { + return repeaterInfoJSON{}, err + } + mine := false + for _, c := range claims { + if c.UserID == u.ID { + mine = true + break + } + } + out.CanEdit, out.ClaimedByMe = &can, &mine + } + return out, nil +} + +func (s *Server) handleRepeaterInfoGet(w http.ResponseWriter, r *http.Request) { + pk, err := users.NormalizePubkey(mux.Vars(r)["pubkey"]) + if err != nil { + writeError(w, http.StatusBadRequest, "pubkey must be 64 hex characters") + return + } + u, _ := s.auth.currentUser(w, r) + out, err := s.repeaterInfoFor(pk, u) + if err != nil { + log.Printf("[users] repeater info %s: %v", pk, err) + writeError(w, http.StatusInternalServerError, "internal error") + return + } + writeJSON(w, out) +} + +func (s *Server) handleRepeaterInfoList(w http.ResponseWriter, r *http.Request) { + rows, err := s.auth.st.ListRepeaterInfo() + if err != nil { + log.Printf("[users] list repeater info: %v", err) + writeError(w, http.StatusInternalServerError, "internal error") + return + } + claims, err := s.auth.st.AllRepeaterClaims() + if err != nil { + log.Printf("[users] list repeater claims: %v", err) + writeError(w, http.StatusInternalServerError, "internal error") + return + } + out := make([]repeaterInfoJSON, 0, len(rows)+len(claims)) + seen := make(map[string]bool, len(rows)) + for i := range rows { + seen[rows[i].Pubkey] = true + out = append(out, repeaterInfoBase(rows[i].Pubkey, &rows[i], claims[rows[i].Pubkey])) + } + for pk, c := range claims { + if !seen[pk] { + out = append(out, repeaterInfoBase(pk, nil, c)) + } + } + sort.Slice(out, func(i, j int) bool { return out[i].Pubkey < out[j].Pubkey }) + writeJSON(w, repeaterInfoListJSON{Repeaters: out}) +} + +type repeaterEditRequest struct { + HeightM *float64 `json:"heightM"` + GainDBi *float64 `json:"gainDbi"` // nil = 0 + Status string `json:"status"` + Power string `json:"power"` + Notes string `json:"notes"` +} + +func fmtFloat(v float64) string { return strconv.FormatFloat(v, 'f', -1, 64) } + +func fmtHeight(h *float64) string { + if h == nil { + return "" + } + return fmtFloat(*h) +} + +// repeaterEditDiff lists the changed fields as .old / .new +// audit details. prev nil means no row before: the zero values. +func repeaterEditDiff(prev *users.RepeaterInfo, next users.RepeaterEdit) map[string]string { + var old users.RepeaterInfo + if prev != nil { + old = *prev + } + out := map[string]string{} + add := func(field, o, n string) { + if o != n { + out[field+".old"], out[field+".new"] = o, n + } + } + add("height_m", fmtHeight(old.HeightM), fmtHeight(next.HeightM)) + add("gain_dbi", fmtFloat(old.GainDBi), fmtFloat(next.GainDBi)) + add("status", old.Status, next.Status) + add("power", old.Power, next.Power) + add("notes", old.Notes, next.Notes) + return out +} + +// repeaterTarget applies the per-user rate limit and normalises the pubkey; +// with needKnown it also requires a known repeater in the analyzer DB. ok +// false means the error answer is already written. +func (s *Server) repeaterTarget(w http.ResponseWriter, r *http.Request, u *users.User, needKnown bool) (string, bool) { + if !s.auth.allow(w, r, s.auth.repeater, "user:"+strconv.FormatInt(u.ID, 10)) { + return "", false + } + pk, err := users.NormalizePubkey(mux.Vars(r)["pubkey"]) + if err != nil { + writeError(w, http.StatusBadRequest, "pubkey must be 64 hex characters") + return "", false + } + if !needKnown { + return pk, true + } + found, isRep, err := s.db.RepeaterKnown(pk) + switch { + case err != nil: + log.Printf("[users] repeater lookup %s: %v", pk, err) + writeError(w, http.StatusInternalServerError, "internal error") + case !found: + writeError(w, http.StatusNotFound, "unknown node") + case !isRep: + writeError(w, http.StatusBadRequest, "not a repeater") + default: + return pk, true + } + return "", false +} + +func (s *Server) writeRepeaterInfo(w http.ResponseWriter, pk string, u *users.User) { + out, err := s.repeaterInfoFor(pk, u) + if err != nil { + log.Printf("[users] repeater info %s: %v", pk, err) + writeError(w, http.StatusInternalServerError, "internal error") + return + } + writeJSON(w, out) +} + +func (s *Server) handleRepeaterInfoPut(w http.ResponseWriter, r *http.Request, u *users.User, _ *users.Session) { + pk, ok := s.repeaterTarget(w, r, u, true) + if !ok { + return + } + var req repeaterEditRequest + if !decodeJSON(w, r, &req) { + return + } + can, err := s.auth.st.CanEditRepeater(u, pk) + if err != nil { + log.Printf("[users] repeater permission %s: %v", pk, err) + writeError(w, http.StatusInternalServerError, "internal error") + return + } + if !can { + writeError(w, http.StatusForbidden, "only this repeater's maintainers can edit it") + return + } + edit := users.RepeaterEdit{HeightM: req.HeightM, Status: req.Status, Power: req.Power, Notes: req.Notes} + if req.GainDBi != nil { + edit.GainDBi = *req.GainDBi + } + edit, err = users.ValidateRepeaterEdit(edit) + if writeValidation(w, err) { + return + } + if err != nil { + log.Printf("[users] validate repeater edit %s: %v", pk, err) + writeError(w, http.StatusInternalServerError, "internal error") + return + } + cur, err := s.auth.st.GetRepeaterInfo(pk) + if errors.Is(err, users.ErrNotFound) { + cur, err = nil, nil + } + if err != nil { + log.Printf("[users] read repeater info %s: %v", pk, err) + writeError(w, http.StatusInternalServerError, "internal error") + return + } + // An unchanged body writes nothing: updated_at and updated_by stay. The + // early read only decides that; the audit diff comes from the row the + // save replaced. + if len(repeaterEditDiff(cur, edit)) > 0 { + prev, err := s.auth.st.SaveRepeaterInfo(u.ID, pk, edit) + if err != nil { + if writeValidation(w, err) { + return + } + log.Printf("[users] save repeater info %s: %v", pk, err) + writeError(w, http.StatusInternalServerError, "internal error") + return + } + diff := repeaterEditDiff(prev, edit) + diff["pubkey"] = pk + s.auth.auditAsync(idPtr(u.ID), "repeater.edit", nil, diff) + } + s.writeRepeaterInfo(w, pk, u) +} + +func (s *Server) handleRepeaterClaim(w http.ResponseWriter, r *http.Request, u *users.User, _ *users.Session) { + pk, ok := s.repeaterTarget(w, r, u, true) + if !ok { + return + } + added, err := s.auth.st.ClaimRepeater(u.ID, pk) + if err != nil { + log.Printf("[users] claim repeater %s: %v", pk, err) + writeError(w, http.StatusInternalServerError, "internal error") + return + } + if added { + s.auth.auditAsync(idPtr(u.ID), "repeater.claim", idPtr(u.ID), map[string]string{"pubkey": pk}) + } + s.writeRepeaterInfo(w, pk, u) +} + +func (s *Server) handleRepeaterUnclaim(w http.ResponseWriter, r *http.Request, u *users.User, _ *users.Session) { + pk, ok := s.repeaterTarget(w, r, u, false) + if !ok { + return + } + err := s.auth.st.UnclaimRepeater(u.ID, pk) + if errors.Is(err, users.ErrNotFound) { + writeError(w, http.StatusNotFound, "you have not claimed this repeater") + return + } + if err != nil { + log.Printf("[users] unclaim repeater %s: %v", pk, err) + writeError(w, http.StatusInternalServerError, "internal error") + return + } + s.auth.auditAsync(idPtr(u.ID), "repeater.unclaim", idPtr(u.ID), map[string]string{"pubkey": pk}) + s.writeRepeaterInfo(w, pk, u) +} + +func (s *Server) handleAdminRepeaterUnclaim(w http.ResponseWriter, r *http.Request, admin *users.User, _ *users.Session) { + pk, err := users.NormalizePubkey(mux.Vars(r)["pubkey"]) + if err != nil { + writeError(w, http.StatusBadRequest, "pubkey must be 64 hex characters") + return + } + uid, err := strconv.ParseInt(mux.Vars(r)["userId"], 10, 64) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid user id") + return + } + err = s.auth.st.UnclaimRepeater(uid, pk) + if errors.Is(err, users.ErrNotFound) { + writeError(w, http.StatusNotFound, "no such claim") + return + } + if err != nil { + log.Printf("[users] admin unclaim repeater %s for user #%d: %v", pk, uid, err) + writeError(w, http.StatusInternalServerError, "internal error") + return + } + s.auth.auditAsync(idPtr(admin.ID), "repeater.unclaim", idPtr(uid), map[string]string{"pubkey": pk, "by": "admin"}) + w.WriteHeader(http.StatusNoContent) +} diff --git a/cmd/server/repeater_handlers_test.go b/cmd/server/repeater_handlers_test.go new file mode 100644 index 000000000..d2889e3dd --- /dev/null +++ b/cmd/server/repeater_handlers_test.go @@ -0,0 +1,414 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + + "github.com/meshcore-analyzer/users" +) + +const ( + rpkA = "aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11aa11" + rpkB = "bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22bb22" +) + +func TestRepeaterInfoGetDefaults(t *testing.T) { + f := newAuthFixture(t) + w := f.do("GET", "/api/repeaters/"+rpkA+"/info", nil) + expectStatus(t, w, 200) + body := w.Body.String() + for _, want := range []string{`"heightM":null`, `"gainDbi":0`, `"status":null`, `"power":null`, + `"notes":""`, `"claimers":[]`, `"updatedAt":null`, `"updatedBy":null`} { + if !strings.Contains(body, want) { + t.Errorf("body missing %s: %s", want, body) + } + } + if strings.Contains(body, "canEdit") || strings.Contains(body, "claimedByMe") { + t.Errorf("anonymous body has caller fields: %s", body) + } +} + +func seedAliceRepeater(t *testing.T, f *authFixture) *client { + t.Helper() + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + h := 12.5 + if _, err := f.st.SaveRepeaterInfo(alice.me.ID, rpkA, users.RepeaterEdit{HeightM: &h, GainDBi: 3, Status: users.RepeaterStatusMaintenance}); err != nil { + t.Fatal(err) + } + if _, err := f.st.ClaimRepeater(alice.me.ID, rpkA); err != nil { + t.Fatal(err) + } + return alice +} + +func TestRepeaterInfoGetSaved(t *testing.T) { + f := newAuthFixture(t) + seedAliceRepeater(t, f) + w := f.do("GET", "/api/repeaters/"+rpkA+"/info", nil) + expectStatus(t, w, 200) + got := decode[repeaterInfoJSON](t, w) + if got.HeightM == nil || *got.HeightM != 12.5 || got.Status == nil || *got.Status != "maintenance" || got.GainDBi != 3 { + t.Errorf("saved fields wrong: %+v", got) + } + if len(got.Claimers) != 1 || got.Claimers[0].DisplayName != "Alice" || got.Claimers[0].ClaimedAt == "" { + t.Errorf("claimers = %+v", got.Claimers) + } + if got.UpdatedBy == nil || *got.UpdatedBy != "Alice" || got.UpdatedAt == nil { + t.Errorf("updatedBy/At = %v %v", got.UpdatedBy, got.UpdatedAt) + } + if strings.Contains(w.Body.String(), "@") { + t.Errorf("body leaks an email: %s", w.Body.String()) + } +} + +func TestRepeaterInfoGetCallerFields(t *testing.T) { + f := newAuthFixture(t) + alice := seedAliceRepeater(t, f) + bob := f.registerAndActivate(t, "bob@example.org", "Bob", pw) + for _, c := range []struct { + name string + cl *client + want bool + }{{"bob", bob, false}, {"alice", alice, true}} { + got := decode[repeaterInfoJSON](t, f.do("GET", "/api/repeaters/"+rpkA+"/info", nil, as(c.cl))) + if got.CanEdit == nil || *got.CanEdit != c.want || got.ClaimedByMe == nil || *got.ClaimedByMe != c.want { + t.Errorf("%s: canEdit=%v claimedByMe=%v, want %v", c.name, got.CanEdit, got.ClaimedByMe, c.want) + } + } +} + +func TestRepeaterInfoGetUpperCase(t *testing.T) { + f := newAuthFixture(t) + seedAliceRepeater(t, f) + w := f.do("GET", "/api/repeaters/"+strings.ToUpper(rpkA)+"/info", nil) + expectStatus(t, w, 200) + got := decode[repeaterInfoJSON](t, w) + if got.Pubkey != rpkA || got.HeightM == nil || *got.HeightM != 12.5 { + t.Errorf("uppercase did not hit the lowercase row: %+v", got) + } +} + +func TestRepeaterInfoGetBadPubkey(t *testing.T) { + f := newAuthFixture(t) + w := f.do("GET", "/api/repeaters/xyz/info", nil) + expectStatus(t, w, 400) + if !strings.Contains(w.Body.String(), "pubkey must be 64 hex characters") { + t.Errorf("body = %s", w.Body.String()) + } +} + +func TestRepeaterInfoList(t *testing.T) { + f := newAuthFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + if _, err := f.st.SaveRepeaterInfo(alice.me.ID, rpkA, users.RepeaterEdit{Status: users.RepeaterStatusActive}); err != nil { + t.Fatal(err) + } + if _, err := f.st.ClaimRepeater(alice.me.ID, rpkB); err != nil { + t.Fatal(err) + } + w := f.do("GET", "/api/repeaters/info", nil) + expectStatus(t, w, 200) + if !strings.Contains(w.Body.String(), `"claimers":[]`) { + t.Errorf("first entry claimers not []: %s", w.Body.String()) + } + got := decode[repeaterInfoListJSON](t, w) + if len(got.Repeaters) != 2 || got.Repeaters[0].Pubkey != rpkA || got.Repeaters[1].Pubkey != rpkB { + t.Fatalf("list = %+v", got.Repeaters) + } + if len(got.Repeaters[1].Claimers) != 1 || got.Repeaters[1].Claimers[0].DisplayName != "Alice" { + t.Errorf("claim-only entry = %+v", got.Repeaters[1]) + } +} + +func TestRepeaterInfoListEmpty(t *testing.T) { + f := newAuthFixture(t) + w := f.do("GET", "/api/repeaters/info", nil) + expectStatus(t, w, 200) + if !strings.Contains(w.Body.String(), `"repeaters":[]`) { + t.Errorf("body = %s", w.Body.String()) + } +} + +func TestRepeaterRoutesOffWithoutUserManagement(t *testing.T) { + _, router := setupTestServer(t) + for _, p := range []string{"/api/repeaters/info", "/api/repeaters/" + rpkA + "/info"} { + w := httptest.NewRecorder() + router.ServeHTTP(w, httptest.NewRequest("GET", p, nil)) + if w.Code != 404 { + t.Errorf("GET %s = %d with user management off, want 404", p, w.Code) + } + } +} + +func seedNode(t *testing.T, db *DB, pk, role string) { + t.Helper() + if _, err := db.conn.Exec(`INSERT INTO nodes (public_key, role) VALUES (?, ?)`, pk, role); err != nil { + t.Fatal(err) + } +} + +const rpkComp = "cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33cc33" + +func repeaterFixture(t *testing.T, adminEmails ...string) *authFixture { + t.Helper() + f := newAuthFixture(t, adminEmails...) + f.srv.db = setupTestDB(t) + seedNode(t, f.srv.db, rpkA, "repeater") + seedNode(t, f.srv.db, rpkComp, "companion") + return f +} + +func auditOf(t *testing.T, f *authFixture, uid int64, action string) []users.AuditEntry { + t.Helper() + entries, err := f.st.AuditFor(uid, 100) + if err != nil { + t.Fatal(err) + } + var out []users.AuditEntry + for _, e := range entries { + if e.Action == action { + out = append(out, e) + } + } + return out +} + +func repPath(pk, what string) string { return "/api/repeaters/" + pk + "/" + what } + +func TestRepeaterEditUnclaimedByAnyUser(t *testing.T) { + f := repeaterFixture(t) + bob := f.registerAndActivate(t, "bob@example.org", "Bob", pw) + w := f.do("PUT", repPath(rpkA, "info"), map[string]any{"heightM": 20}, as(bob)) + expectStatus(t, w, 200) + got := decode[repeaterInfoJSON](t, w) + if got.HeightM == nil || *got.HeightM != 20 || got.UpdatedBy == nil || *got.UpdatedBy != "Bob" { + t.Errorf("response = %+v", got) + } + if got.CanEdit == nil || !*got.CanEdit { + t.Errorf("caller fields missing: %+v", got) + } + rows := auditOf(t, f, bob.me.ID, "repeater.edit") + if len(rows) != 1 || rows[0].Detail["height_m.old"] != "" || rows[0].Detail["height_m.new"] != "20" || rows[0].Detail["pubkey"] != rpkA { + t.Fatalf("audit = %+v", rows) + } +} + +func TestRepeaterEditClaimedOnlyByClaimers(t *testing.T) { + f := repeaterFixture(t, "boss@example.org") + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + bob := f.registerAndActivate(t, "bob@example.org", "Bob", pw) + boss := f.registerAndActivate(t, "boss@example.org", "Boss", pw) + expectStatus(t, f.do("POST", repPath(rpkA, "claim"), nil, as(alice)), 200) + body := map[string]any{"heightM": 5} + w := f.do("PUT", repPath(rpkA, "info"), body, as(bob)) + expectStatus(t, w, 403) + if !strings.Contains(w.Body.String(), "only this repeater's maintainers can edit it") { + t.Errorf("body = %s", w.Body.String()) + } + expectStatus(t, f.do("PUT", repPath(rpkA, "info"), body, as(alice)), 200) + expectStatus(t, f.do("PUT", repPath(rpkA, "info"), map[string]any{"heightM": 6}, as(boss)), 200) +} + +func TestRepeaterEditValidation(t *testing.T) { + f := repeaterFixture(t) + bob := f.registerAndActivate(t, "bob@example.org", "Bob", pw) + w := f.do("PUT", repPath(rpkA, "info"), map[string]any{"gainDbi": 31}, as(bob)) + expectStatus(t, w, 400) + if !strings.Contains(w.Body.String(), "gain") { + t.Errorf("body = %s", w.Body.String()) + } + expectStatus(t, f.do("PUT", repPath(rpkA, "info"), map[string]any{"status": "planned"}, as(bob)), 400) +} + +func TestRepeaterEditUnknownAndNonRepeater(t *testing.T) { + f := repeaterFixture(t) + bob := f.registerAndActivate(t, "bob@example.org", "Bob", pw) + expectStatus(t, f.do("PUT", repPath(rpkB, "info"), map[string]any{"heightM": 1}, as(bob)), 404) + w := f.do("PUT", repPath(rpkComp, "info"), map[string]any{"heightM": 1}, as(bob)) + expectStatus(t, w, 400) + if !strings.Contains(w.Body.String(), "not a repeater") { + t.Errorf("body = %s", w.Body.String()) + } + expectStatus(t, f.do("POST", repPath(rpkComp, "claim"), nil, as(bob)), 400) + expectStatus(t, f.do("POST", repPath(rpkB, "claim"), nil, as(bob)), 404) + if rows, _ := f.st.ListRepeaterInfo(); len(rows) != 0 { + t.Errorf("stored rows = %+v", rows) + } + if claims, _ := f.st.AllRepeaterClaims(); len(claims) != 0 { + t.Errorf("stored claims = %+v", claims) + } +} + +func TestRepeaterEditAnonymous(t *testing.T) { + f := repeaterFixture(t) + bob := f.registerAndActivate(t, "bob@example.org", "Bob", pw) + body := map[string]any{"heightM": 1} + expectStatus(t, f.do("PUT", repPath(rpkA, "info"), body), 401) + expectStatus(t, f.do("PUT", repPath(rpkA, "info"), body, func(r *http.Request) { r.AddCookie(bob.cookie) }), 403) +} + +func TestRepeaterClaimIdempotent(t *testing.T) { + f := repeaterFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + for i := 0; i < 2; i++ { + w := f.do("POST", repPath(rpkA, "claim"), nil, as(alice)) + expectStatus(t, w, 200) + got := decode[repeaterInfoJSON](t, w) + if len(got.Claimers) != 1 || got.ClaimedByMe == nil || !*got.ClaimedByMe { + t.Fatalf("claim %d: %+v", i, got) + } + } + rows := auditOf(t, f, alice.me.ID, "repeater.claim") + if len(rows) != 1 || rows[0].Detail["pubkey"] != rpkA || rows[0].TargetUserID == nil || *rows[0].TargetUserID != alice.me.ID { + t.Fatalf("audit = %+v", rows) + } +} + +func TestRepeaterUnclaim(t *testing.T) { + f := repeaterFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + expectStatus(t, f.do("POST", repPath(rpkA, "claim"), nil, as(alice)), 200) + w := f.do("DELETE", repPath(rpkA, "claim"), nil, as(alice)) + expectStatus(t, w, 200) + if !strings.Contains(w.Body.String(), `"claimers":[]`) { + t.Errorf("body = %s", w.Body.String()) + } + if rows := auditOf(t, f, alice.me.ID, "repeater.unclaim"); len(rows) != 1 || rows[0].Detail["pubkey"] != rpkA { + t.Fatalf("audit = %+v", rows) + } + expectStatus(t, f.do("DELETE", repPath(rpkA, "claim"), nil, as(alice)), 404) +} + +func TestRepeaterEditNoChangeNoAudit(t *testing.T) { + f := repeaterFixture(t) + bob := f.registerAndActivate(t, "bob@example.org", "Bob", pw) + body := map[string]any{"heightM": 20, "gainDbi": 3, "status": "active", "notes": "roof"} + expectStatus(t, f.do("PUT", repPath(rpkA, "info"), body, as(bob)), 200) + expectStatus(t, f.do("PUT", repPath(rpkA, "info"), body, as(bob)), 200) + if rows := auditOf(t, f, bob.me.ID, "repeater.edit"); len(rows) != 1 { + t.Fatalf("audit rows = %d, want 1", len(rows)) + } +} + +func TestRepeaterInfoGetPaddedPubkey(t *testing.T) { + f := newAuthFixture(t) + seedAliceRepeater(t, f) + w := f.do("GET", "/api/repeaters/%20"+rpkA+"%20/info", nil) + expectStatus(t, w, 200) + got := decode[repeaterInfoJSON](t, w) + if got.Pubkey != rpkA || got.HeightM == nil || *got.HeightM != 12.5 { + t.Errorf("padded pubkey did not hit the lowercase row: %+v", got) + } +} + +func TestRepeaterEditIdenticalIsNoOp(t *testing.T) { + f := repeaterFixture(t) + bob := f.registerAndActivate(t, "bob@example.org", "Bob", pw) + cy := f.registerAndActivate(t, "cy@example.org", "Cy", pw) + body := map[string]any{"heightM": 20, "notes": "roof"} + first := decode[repeaterInfoJSON](t, f.do("PUT", repPath(rpkA, "info"), body, as(bob))) + second := decode[repeaterInfoJSON](t, f.do("PUT", repPath(rpkA, "info"), body, as(cy))) + if second.UpdatedBy == nil || *second.UpdatedBy != "Bob" || second.UpdatedAt == nil || *second.UpdatedAt != *first.UpdatedAt { + t.Errorf("no-op PUT changed updatedBy/At: %+v vs %+v", second, first) + } + if rows := auditOf(t, f, cy.me.ID, "repeater.edit"); len(rows) != 0 { + t.Errorf("no-op PUT wrote audit: %+v", rows) + } +} + +func TestRepeaterEditPaddedNotesNoSecondAudit(t *testing.T) { + f := repeaterFixture(t) + bob := f.registerAndActivate(t, "bob@example.org", "Bob", pw) + expectStatus(t, f.do("PUT", repPath(rpkA, "info"), map[string]any{"notes": "roof"}, as(bob)), 200) + expectStatus(t, f.do("PUT", repPath(rpkA, "info"), map[string]any{"notes": " roof "}, as(bob)), 200) + if rows := auditOf(t, f, bob.me.ID, "repeater.edit"); len(rows) != 1 { + t.Fatalf("audit rows = %d, want 1", len(rows)) + } +} + +func TestRepeaterEditDeviceTokenForbidden(t *testing.T) { + f := repeaterFixture(t) + f.registerAndActivate(t, "alice@example.org", "Alice", pw) + tok := f.deviceToken(t, "alice@example.org", pw, "Pixel").Token + expectStatus(t, f.do("PUT", repPath(rpkA, "info"), map[string]any{"heightM": 1}, bearer(tok)), 403) + if rows, _ := f.st.ListRepeaterInfo(); len(rows) != 0 { + t.Errorf("stored rows = %+v", rows) + } +} + +func TestRepeaterEditForbiddenLeavesRowUnchanged(t *testing.T) { + f := repeaterFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + bob := f.registerAndActivate(t, "bob@example.org", "Bob", pw) + expectStatus(t, f.do("POST", repPath(rpkA, "claim"), nil, as(alice)), 200) + expectStatus(t, f.do("PUT", repPath(rpkA, "info"), map[string]any{"heightM": 7}, as(alice)), 200) + expectStatus(t, f.do("PUT", repPath(rpkA, "info"), map[string]any{"heightM": 99}, as(bob)), 403) + got, err := f.st.GetRepeaterInfo(rpkA) + if err != nil || got.HeightM == nil || *got.HeightM != 7 { + t.Errorf("row after 403 = %+v, %v", got, err) + } +} + +func TestRepeaterUnclaimBadPubkey(t *testing.T) { + f := repeaterFixture(t) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + expectStatus(t, f.do("DELETE", "/api/repeaters/xyz/claim", nil, as(alice)), 400) +} + +func adminClaimPath(pk string, uid int64) string { + return "/api/admin/repeaters/" + pk + "/claims/" + strconv.FormatInt(uid, 10) +} + +func TestAdminRemoveRepeaterClaim(t *testing.T) { + f := repeaterFixture(t, "admin@example.org") + admin := f.registerAndActivate(t, "admin@example.org", "Admin", pw) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + bob := f.registerAndActivate(t, "bob@example.org", "Bob", pw) + expectStatus(t, f.do("POST", repPath(rpkA, "claim"), nil, as(alice)), 200) + + expectStatus(t, f.do("DELETE", adminClaimPath(rpkA, alice.me.ID), nil, as(bob)), 403) + if cs, _ := f.st.RepeaterClaimsByUser(alice.me.ID); len(cs) != 1 { + t.Fatalf("claim removed by a non-admin: %+v", cs) + } + expectStatus(t, f.do("DELETE", adminClaimPath(rpkA, alice.me.ID), nil, as(admin)), 204) + if cs, _ := f.st.RepeaterClaimsByUser(alice.me.ID); len(cs) != 0 { + t.Fatalf("claim still there: %+v", cs) + } + rows := auditOf(t, f, alice.me.ID, "repeater.unclaim") + if len(rows) != 1 || rows[0].Detail["pubkey"] != rpkA || rows[0].Detail["by"] != "admin" || + rows[0].ActorUserID == nil || *rows[0].ActorUserID != admin.me.ID { + t.Fatalf("audit = %+v", rows) + } + expectStatus(t, f.do("DELETE", adminClaimPath(rpkA, alice.me.ID), nil, as(admin)), 404) + expectStatus(t, f.do("DELETE", adminClaimPath("zz", alice.me.ID), nil, as(admin)), 400) + expectStatus(t, f.do("DELETE", "/api/admin/repeaters/"+rpkA+"/claims/abc", nil, as(admin)), 400) +} + +func TestAdminUserDetailRepeaterClaims(t *testing.T) { + f := repeaterFixture(t, "admin@example.org") + admin := f.registerAndActivate(t, "admin@example.org", "Admin", pw) + alice := f.registerAndActivate(t, "alice@example.org", "Alice", pw) + expectStatus(t, f.do("POST", repPath(rpkA, "claim"), nil, as(alice)), 200) + + w := f.do("GET", "/api/admin/users/"+strconv.FormatInt(alice.me.ID, 10), nil, as(admin)) + expectStatus(t, w, 200) + d := decode[adminUserDetailJSON](t, w) + if len(d.RepeaterClaims) != 1 || d.RepeaterClaims[0].Pubkey != rpkA || d.RepeaterClaims[0].ClaimedAt == "" { + t.Fatalf("repeaterClaims = %+v", d.RepeaterClaims) + } + w = f.do("GET", "/api/admin/users/"+strconv.FormatInt(admin.me.ID, 10), nil, as(admin)) + expectStatus(t, w, 200) + if !strings.Contains(w.Body.String(), `"repeaterClaims":[]`) { + t.Fatalf("no claims should be []: %s", w.Body.String()) + } + expectStatus(t, f.do("POST", userPath(alice.me.ID, "/disable"), nil, as(admin)), 200) + w = f.do("GET", "/api/admin/users/"+strconv.FormatInt(alice.me.ID, 10), nil, as(admin)) + expectStatus(t, w, 200) + d = decode[adminUserDetailJSON](t, w) + if len(d.RepeaterClaims) != 1 || d.RepeaterClaims[0].Pubkey != rpkA { + t.Fatalf("claims of a disabled user = %+v", d.RepeaterClaims) + } +} diff --git a/cmd/server/repeater_lookup.go b/cmd/server/repeater_lookup.go new file mode 100644 index 000000000..fb850dff2 --- /dev/null +++ b/cmd/server/repeater_lookup.go @@ -0,0 +1,33 @@ +package main + +import ( + "database/sql" + "errors" +) + +// RepeaterKnown reports whether pubkey (lowercase) is a known node, and +// whether its role is repeater. It looks in nodes first, then in +// inactive_nodes when that table exists. Read-only. +func (db *DB) RepeaterKnown(pubkey string) (found bool, isRepeater bool, err error) { + if db == nil || db.conn == nil { + return false, false, errors.New("repeater lookup: no database") + } + tables := []string{"nodes"} + if db.inactiveNodesPresent() { + tables = append(tables, "inactive_nodes") + } + for _, tbl := range tables { + var isRep bool + err := db.conn.QueryRow( + `SELECT lower(COALESCE(role, '')) = 'repeater' FROM `+tbl+` WHERE public_key = ? LIMIT 1`, + pubkey).Scan(&isRep) + if err == sql.ErrNoRows { + continue + } + if err != nil { + return false, false, err + } + return true, isRep, nil + } + return false, false, nil +} diff --git a/cmd/server/repeater_lookup_test.go b/cmd/server/repeater_lookup_test.go new file mode 100644 index 000000000..f524e9925 --- /dev/null +++ b/cmd/server/repeater_lookup_test.go @@ -0,0 +1,53 @@ +package main + +import "testing" + +func TestRepeaterKnown(t *testing.T) { + const ( + rep = "aa11000000000000000000000000000000000000000000000000000000000001" + comp = "bb22000000000000000000000000000000000000000000000000000000000002" + old = "cc33000000000000000000000000000000000000000000000000000000000003" + none = "dd44000000000000000000000000000000000000000000000000000000000004" + ) + db := setupTestDB(t) + for _, q := range []string{ + `INSERT INTO nodes (public_key, name, role) VALUES ('` + rep + `', 'r', 'Repeater')`, + `INSERT INTO nodes (public_key, name, role) VALUES ('` + comp + `', 'c', 'companion')`, + `CREATE TABLE inactive_nodes (public_key TEXT PRIMARY KEY, name TEXT, role TEXT)`, + `INSERT INTO inactive_nodes (public_key, name, role) VALUES ('` + old + `', 'o', 'repeater')`, + } { + if _, err := db.conn.Exec(q); err != nil { + t.Fatal(err) + } + } + cases := []struct { + name string + pk string + found, isRep bool + }{ + {"repeater", rep, true, true}, + {"companion", comp, true, false}, + {"retired repeater", old, true, true}, + {"unknown", none, false, false}, + } + for _, c := range cases { + f, r, err := db.RepeaterKnown(c.pk) + if err != nil || f != c.found || r != c.isRep { + t.Errorf("%s: got (%v,%v,%v); want (%v,%v,nil)", c.name, f, r, err, c.found, c.isRep) + } + } + + plain := setupTestDB(t) + f, r, err := plain.RepeaterKnown(none) + if err != nil || f || r { + t.Errorf("no inactive_nodes: got (%v,%v,%v); want (false,false,nil)", f, r, err) + } + + var nilDB *DB + if _, _, err := nilDB.RepeaterKnown(rep); err == nil { + t.Error("nil db: want error") + } + if _, _, err := (&DB{}).RepeaterKnown(rep); err == nil { + t.Error("nil conn: want error") + } +} diff --git a/cmd/server/resolved_index.go b/cmd/server/resolved_index.go index 11ab7498a..f1bd2159a 100644 --- a/cmd/server/resolved_index.go +++ b/cmd/server/resolved_index.go @@ -536,75 +536,6 @@ func (s *PacketStore) lruDelete(obsID int) { // Don't scan lruOrder — eviction handles stale entries naturally. } -// resolvedPubkeysForEvictionBatch fetches resolved pubkeys for multiple txIDs -// from SQL in a single batched query. Returns a map from txID to unique pubkeys. -// MUST be called WITHOUT holding s.mu — this is the whole point of the batch approach. -// Chunks queries to stay under SQLite's 500-parameter limit. -func (s *PacketStore) resolvedPubkeysForEvictionBatch(txIDs []int) map[int][]string { - result := make(map[int][]string, len(txIDs)) - if len(txIDs) == 0 || s.db == nil || s.db.conn == nil { - return result - } - - const chunkSize = 499 // SQLite SQLITE_MAX_VARIABLE_NUMBER default is 999; stay well under - for start := 0; start < len(txIDs); start += chunkSize { - end := start + chunkSize - if end > len(txIDs) { - end = len(txIDs) - } - chunk := txIDs[start:end] - - // Build query with placeholders - placeholders := make([]byte, 0, len(chunk)*2) - args := make([]interface{}, len(chunk)) - for i, id := range chunk { - if i > 0 { - placeholders = append(placeholders, ',') - } - placeholders = append(placeholders, '?') - args[i] = id - } - - query := "SELECT transmission_id, resolved_path FROM observations WHERE transmission_id IN (" + - string(placeholders) + ") AND resolved_path IS NOT NULL" - - rows, err := s.db.conn.Query(query, args...) - if err != nil { - continue - } - - var txID int - var rpJSON sql.NullString - for rows.Next() { - if err := rows.Scan(&txID, &rpJSON); err != nil { - continue - } - if !rpJSON.Valid || rpJSON.String == "" { - continue - } - // De-duplicate as we go: a packet has a handful of keys, so a - // scan of its list is cheaper than a map per packet. - pks := result[txID] - for _, pk := range resolvedPubkeysFromJSON(rpJSON.String) { - dup := false - for _, have := range pks { - if have == pk { - dup = true - break - } - } - if !dup { - pks = append(pks, pk) - } - } - result[txID] = pks - } - rows.Close() - } - - return result -} - // initResolvedPathIndex initializes the resolved path index data structures. func (s *PacketStore) initResolvedPathIndex() { s.resolvedPubkeyIndex = make(map[uint64][]int, 4096) diff --git a/cmd/server/resolved_pubkeys_bench_test.go b/cmd/server/resolved_pubkeys_bench_test.go index 70adcb8bd..ad55f73db 100644 --- a/cmd/server/resolved_pubkeys_bench_test.go +++ b/cmd/server/resolved_pubkeys_bench_test.go @@ -25,13 +25,3 @@ func BenchmarkResolvedPubkeysFromJSON(b *testing.B) { _ = resolvedPubkeysFromJSON(paths[i%len(paths)]) } } - -// An eviction batch of 1,000 packets with 3 observations each. -func BenchmarkResolvedPubkeysForEvictionBatch(b *testing.B) { - s, ids := evictionResolvedStore(b, 1000) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - _ = s.resolvedPubkeysForEvictionBatch(ids) - } -} diff --git a/cmd/server/routes.go b/cmd/server/routes.go index 1a9a5dfac..11544e334 100644 --- a/cmd/server/routes.go +++ b/cmd/server/routes.go @@ -156,6 +156,10 @@ type Server struct { // LoRa RF parameters from the MeshCore map (issue #1268). Nil unless // rfParams.nodesUrl is configured. rfParams *rfParamsCache + // elevation serves /api/elevation/profile; nil unless los.enabled. + elevation *elevationService + // planner serves /api/planner/*; nil unless planner.enabled. + planner *plannerService // Optional user management (docs/specs/2026-10-06-user-management-design.md). // Nil unless userManagement.enabled; see initUserManagement. @@ -392,6 +396,11 @@ func (s *Server) RegisterRoutes(r *mux.Router) { r.HandleFunc("/api/channels", s.handleChannels).Methods("GET") r.HandleFunc("/api/known-channels", s.handleKnownChannels).Methods("GET") r.HandleFunc("/api/rf-params", s.handleRfParams).Methods("GET") + r.HandleFunc("/api/elevation/profile", s.handleElevationProfile).Methods("GET") + r.HandleFunc("/api/planner/profile", s.handlePlannerProfile).Methods("GET") + r.HandleFunc("/api/planner/relay", s.handlePlannerRelay).Methods("GET") + r.HandleFunc("/api/planner/viewshed", s.handlePlannerViewshed).Methods("GET") + r.HandleFunc("/api/planner/coverage", s.handlePlannerCoverage).Methods("GET") r.HandleFunc("/api/observers/metrics/summary", s.handleMetricsSummary).Methods("GET") r.HandleFunc("/api/observers/{id}/metrics", s.handleObserverMetrics).Methods("GET") r.HandleFunc("/api/observers/{id}/analytics", s.handleObserverAnalytics).Methods("GET") @@ -572,6 +581,8 @@ func (s *Server) handleConfigClient(w http.ResponseWriter, r *http.Request) { ClientRxAppURL: s.cfg.ClientRxAppURL(), PathTrust: &pathTrust, UserManagement: s.clientUserManagement(), + LOS: s.cfg.LOS.clientConfig(), + Planner: s.cfg.Planner.clientConfig(s.cfg.LOS), }) } @@ -972,7 +983,7 @@ func (s *Server) handleStats(w http.ResponseWriter, r *http.Request) { Sensors: counts["sensors"], }, SignatureDrops: s.db.GetSignatureDropCount(), - HashMigrationComplete: s.store != nil && s.store.hashMigrationComplete.Load(), + HashMigrationComplete: s.db.hashMigrationComplete(), TrackedMB: mem.StoreDataMB, // deprecated alias StoreDataMB: mem.StoreDataMB, @@ -1711,45 +1722,24 @@ func (s *Server) buildNodesResponse(r *http.Request) (NodeListResponse, error) { } } } - if s.cfg.GeoFilter != nil { - filtered := nodes[:0] - for _, node := range nodes { - // Foreign-flagged nodes (#730) are kept even when their GPS lies - // outside the geofilter polygon — that's the whole point of the - // flag: operators need to SEE bridged/leaked nodes, not have them - // filtered away. The ingestor sets foreign_advert=1 when its - // configured geo_filter rejected the advert; the server must - // surface those. - if isForeign, _ := node["foreign"].(bool); isForeign { - filtered = append(filtered, node) - continue - } - if NodePassesGeoFilter(node["lat"], node["lon"], s.cfg.GeoFilter) { - filtered = append(filtered, node) - } - } - total = len(filtered) - nodes = filtered - } - // Filter blacklisted nodes - if len(s.cfg.NodeBlacklist) > 0 { - filtered := nodes[:0] - for _, node := range nodes { - if pk, ok := node["public_key"].(string); !ok || !s.cfg.IsBlacklisted(pk) { - filtered = append(filtered, node) - } - } - total = len(filtered) - nodes = filtered - } - // Filter nodes whose name starts with a hidden prefix (#1181). DB rows - // are preserved — this only drops them from the API surface so observer - // history (paths, hops, distances) remains intact for analytics. - if len(s.cfg.HiddenNamePrefixes) > 0 { + // The operator's hiding rules — blacklist, hidden name prefixes (#1181) + // and the geo_filter, which keeps foreign-flagged nodes (#730) — in one + // pass of the predicate the planner and the elevation proxy share + // (node_visibility.go). DB rows are preserved: this only drops them from + // the API surface, so observer history (paths, hops, distances) remains + // intact for analytics. + if vis := s.nodeVisibility(); vis.filters() { filtered := nodes[:0] for _, node := range nodes { + pk, _ := node["public_key"].(string) name, _ := node["name"].(string) - if !s.cfg.IsNameHidden(name) { + foreign, _ := node["foreign"].(bool) + lat, okLat := toFloat64(node["lat"]) + lon, okLon := toFloat64(node["lon"]) + if !okLat || !okLon { + lat, lon = 0, 0 // no fix: the geo_filter keeps it + } + if vis.Visible(pk, name, lat, lon, foreign) { filtered = append(filtered, node) } } diff --git a/cmd/server/routes_test.go b/cmd/server/routes_test.go index b33b92224..970041050 100644 --- a/cmd/server/routes_test.go +++ b/cmd/server/routes_test.go @@ -4358,6 +4358,14 @@ func TestHandleScopeStats(t *testing.T) { if resp.Summary.UnknownScope != 1 { t.Errorf("unknownScope = %d, want 1", resp.Summary.UnknownScope) } + // #2364: the summary adds up again. + if resp.Summary.Total != 6 { + t.Errorf("total = %d, want 6", resp.Summary.Total) + } + if resp.Summary.UnscopedTransport != 1 || resp.Summary.UnscopedFlood != 1 || resp.Summary.UnscopedDirect != 1 { + t.Errorf("unscoped split = %d/%d/%d, want 1/1/1", + resp.Summary.UnscopedTransport, resp.Summary.UnscopedFlood, resp.Summary.UnscopedDirect) + } if len(resp.ByRegion) != 1 || resp.ByRegion[0].Name != "#belgium" || resp.ByRegion[0].Count != 2 { t.Errorf("byRegion = %v, want [{#belgium 2}]", resp.ByRegion) } diff --git a/cmd/server/startup_poll_gap_test.go b/cmd/server/startup_poll_gap_test.go new file mode 100644 index 000000000..e5cef89c5 --- /dev/null +++ b/cmd/server/startup_poll_gap_test.go @@ -0,0 +1,664 @@ +package main + +import ( + "database/sql" + "encoding/json" + "fmt" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + _ "github.com/mattn/go-sqlite3" + "github.com/meshcore-analyzer/dbschema" +) + +// A transmission or observation the ingestor commits after the startup load's +// last chunk has read its snapshot, but before the poller initialises its +// cursor, must still reach the in-memory store. The poller seeds its cursor +// from a fresh MAX(id) taken when it starts (websocket.go Poller.Start), so a +// row committed in that window is above everything loaded yet not above the +// cursor: neither the load nor the poll ever reads it. +// +// The window is opened deterministically with OnChunkLoaded, which fires +// after a chunk's rows have been read and closed. With one chunk that is the +// last snapshot the load takes. + +func TestStartupLoadPollerGap_SQLite(t *testing.T) { + db, rw := openGapSQLite(t) + runStartupLoadPollerGap(t, db, rw) +} + +func runStartupLoadPollerGap(t *testing.T, db *DB, rw *sql.DB) { + t.Helper() + base := time.Now().UTC().Add(-10 * time.Minute).Truncate(time.Second) + iso := func(d time.Duration) string { return base.Add(d).Format("2006-01-02T15:04:05.000Z") } + mustExec := func(q string, args ...any) { + t.Helper() + if _, err := rw.Exec(q, args...); err != nil { + t.Fatalf("seed: %v\n%s", err, q) + } + } + addTx := func(id int) { + mustExec(`INSERT INTO transmissions (id, raw_hex, hash, first_seen, route_type, payload_type, payload_version, decoded_json, last_seen) + VALUES (?, ?, ?, ?, 1, 5, 1, '{"type":"GRP_TXT"}', ?)`, + id, fmt.Sprintf("11%02dAABBCCDD", id), gapHash(id), iso(time.Duration(id)*time.Second), base.Add(time.Duration(id)*time.Second).Unix()) + } + addObs := func(id, tx, observer int) { + mustExec(`INSERT INTO observations (id, transmission_id, observer_idx, direction, snr, rssi, score, path_json, timestamp) + VALUES (?, ?, ?, 'rx', 5.5, -90, 1, ?, ?)`, + id, tx, observer, fmt.Sprintf(`["%02X"]`, id), base.Add(time.Duration(id)*time.Second).Unix()) + } + for idx := 1; idx <= 3; idx++ { + mustExec(`INSERT INTO observers (rowid, id, name, iata, last_seen, first_seen) VALUES (?, ?, ?, 'SJC', ?, ?)`, + idx, fmt.Sprintf("%064X", idx), fmt.Sprintf("Obs-%d", idx), iso(0), iso(-time.Hour)) + } + // Committed before the load. + addTx(1) + addObs(1, 1, 1) + addTx(2) + addObs(2, 2, 1) + + store := NewPacketStore(db, &PacketStoreConfig{}) + fired := false + store.OnChunkLoaded(func(int, int) { + if fired { + return + } + fired = true + // Committed after the (only) chunk read its snapshot, before the + // poller starts: a new transmission with one observation, and a + // second observation of an already loaded transmission. + addTx(3) + addObs(3, 3, 1) + addObs(4, 1, 2) + }) + if err := store.RunStartupLoad(100); err != nil { + t.Fatalf("RunStartupLoad: %v", err) + } + if !fired { + t.Fatal("OnChunkLoaded never fired") + } + + loaded := loadedObsPaths(store) + pr := startGapPoller(t, db, store) + + time.Sleep(80 * time.Millisecond) + // Committed after the poller started: a later observation of tx 3 (the + // 12 observations of the lost transmission in the field), and a control + // transmission proving the poller itself works. + addObs(5, 3, 3) + addTx(4) + addObs(6, 4, 1) + + has := func() (tx3, tx4 bool, obs3, obs4, obs5 bool) { + store.mu.RLock() + defer store.mu.RUnlock() + _, tx3 = store.byHash[gapHash(3)] + _, tx4 = store.byHash[gapHash(4)] + _, obs3 = store.byObsID[3] + _, obs4 = store.byObsID[4] + _, obs5 = store.byObsID[5] + return + } + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + if _, tx4, _, _, _ := has(); tx4 { + break + } + time.Sleep(20 * time.Millisecond) + } + time.Sleep(100 * time.Millisecond) // a few more ticks for stragglers + tx3, tx4, obs3, obs4, obs5 := has() + if !tx4 { + t.Fatal("control: tx 4, committed after the poller started, never reached the store; the poller is not running") + } + if !tx3 { + t.Errorf("tx 3, committed between the load's snapshot and the poller's cursor init, is missing from the store (lost forever)") + } + if !obs3 || !obs5 { + t.Errorf("observations of tx 3 missing: obs3=%v obs5=%v", obs3, obs5) + } + if !obs4 { + t.Errorf("obs 4 (new observation of already-loaded tx 1, committed in the same window) is missing from the store") + } + pr.stop() + assertStoreMatchesDB(t, store, rw) + assertNoDuplicateBroadcasts(t, pr.drain(), loaded) + assertReplayIdempotent(t, store, rw) +} + +func gapHash(id int) string { return fmt.Sprintf("feed%012x", id) } + +// A chunk-1 transmission can gain an observation after chunk 1 has read its +// snapshot whose id is BELOW an observation a later chunk loads (that one +// belongs to a chunk-2 transmission and was committed just after it). Using +// the store's highest loaded observation id as the poller's floor would then +// skip it. Three chunks of two: {1,2} {3,4} {5}; the last is short, so its +// callback runs after the load's final snapshot. + +func TestStartupLoadPollerGapMultiChunk_SQLite(t *testing.T) { + db, rw := openGapSQLite(t) + runStartupLoadPollerGapMultiChunk(t, db, rw) +} + +func openGapSQLite(t *testing.T) (*DB, *sql.DB) { + t.Helper() + path := filepath.Join(t.TempDir(), "gap.db") + rw, err := sql.Open("sqlite3", path+"?_journal_mode=WAL&_foreign_keys=on") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { rw.Close() }) + rw.SetMaxOpenConns(1) + // The tables the load and the poller read, as the ingestor creates them + // (cmd/ingestor/db.go), then the server-side migrations it applies on top. + if _, err := rw.Exec(gapBaseSchema); err != nil { + t.Fatalf("create base schema: %v", err) + } + if err := dbschema.Apply(rw, nil); err != nil { + t.Fatalf("dbschema.Apply: %v", err) + } + db, err := OpenDB(path) + if err != nil { + t.Fatalf("OpenDB: %v", err) + } + t.Cleanup(func() { db.conn.Close() }) + return db, rw +} + +// gapBaseSchema is the ingestor's DDL for the tables these tests seed. Observers +// are inserted by rowid: observations.observer_idx refers to it. +const gapBaseSchema = ` + CREATE TABLE nodes ( + public_key TEXT PRIMARY KEY, name TEXT, role TEXT, lat REAL, lon REAL, + last_seen TEXT, first_seen TEXT, advert_count INTEGER DEFAULT 0, + battery_mv INTEGER, temperature_c REAL, foreign_advert INTEGER DEFAULT 0 + ); + CREATE TABLE observers ( + id TEXT PRIMARY KEY, name TEXT, iata TEXT, last_seen TEXT, first_seen TEXT, + packet_count INTEGER DEFAULT 0, model TEXT, firmware TEXT, client_version TEXT, + radio TEXT, battery_mv INTEGER, uptime_secs INTEGER, noise_floor REAL, + inactive INTEGER DEFAULT 0, last_packet_at TEXT DEFAULT NULL, + clock_skew_seconds INTEGER DEFAULT NULL, clock_skew_count_24h INTEGER DEFAULT 0, + clock_last_naive_at TEXT DEFAULT NULL, can_relay INTEGER DEFAULT 1, + can_relay_seen INTEGER DEFAULT 0 + ); + CREATE TABLE transmissions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, raw_hex TEXT NOT NULL, + hash TEXT NOT NULL UNIQUE, first_seen TEXT NOT NULL, route_type INTEGER, + payload_type INTEGER, payload_version INTEGER, decoded_json TEXT, + from_pubkey TEXT, last_seen INTEGER NOT NULL DEFAULT 0, + created_at TEXT DEFAULT (datetime('now')), code1 TEXT, code2 TEXT + ); + CREATE TABLE observations ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + transmission_id INTEGER NOT NULL REFERENCES transmissions(id), + observer_idx INTEGER, direction TEXT, snr REAL, rssi REAL, score INTEGER, + path_json TEXT, timestamp INTEGER NOT NULL + ); + CREATE INDEX idx_observations_transmission_id ON observations(transmission_id); + CREATE INDEX idx_observations_observer_idx ON observations(observer_idx); + CREATE INDEX idx_observations_timestamp ON observations(timestamp); + CREATE TABLE schema_version (version INTEGER); +` + +func runStartupLoadPollerGapMultiChunk(t *testing.T, db *DB, rw *sql.DB) { + t.Helper() + base := time.Now().UTC().Add(-10 * time.Minute).Truncate(time.Second) + iso := func(d time.Duration) string { return base.Add(d).Format("2006-01-02T15:04:05.000Z") } + mustExec := func(q string, args ...any) { + t.Helper() + if _, err := rw.Exec(q, args...); err != nil { + t.Fatalf("seed: %v\n%s", err, q) + } + } + addTx := func(id int) { + mustExec(`INSERT INTO transmissions (id, raw_hex, hash, first_seen, route_type, payload_type, payload_version, decoded_json, last_seen) + VALUES (?, ?, ?, ?, 1, 5, 1, '{"type":"GRP_TXT"}', ?)`, + id, fmt.Sprintf("11%02dAABBCCDD", id), gapHash(id), iso(time.Duration(id)*time.Second), base.Add(time.Duration(id)*time.Second).Unix()) + } + // path_json is unique per observation, so none merges with another + // (dedup is by observer+path) and DB and store counts must agree. + addObs := func(id, tx, observer int) { + mustExec(`INSERT INTO observations (id, transmission_id, observer_idx, direction, snr, rssi, score, path_json, timestamp) + VALUES (?, ?, ?, 'rx', 5.5, -90, 1, ?, ?)`, + id, tx, observer, fmt.Sprintf(`["%02X"]`, id), base.Add(time.Duration(id)*time.Second).Unix()) + } + for idx := 1; idx <= 3; idx++ { + mustExec(`INSERT INTO observers (rowid, id, name, iata, last_seen, first_seen) VALUES (?, ?, ?, 'SJC', ?, ?)`, + idx, fmt.Sprintf("%064X", idx), fmt.Sprintf("Obs-%d", idx), iso(0), iso(-time.Hour)) + } + for id := 1; id <= 5; id++ { + addTx(id) + addObs(id, id, 1) + } + + store := NewPacketStore(db, &PacketStoreConfig{}) + chunk := 0 + store.OnChunkLoaded(func(int, int) { + chunk++ + switch chunk { + case 1: + // Between chunks 1 and 2: obs 10 of chunk-1 tx 1, then obs 11 + // of tx 3, which chunk 2 loads. The store's max obs id becomes + // 11 although 10 was never loaded. + addObs(10, 1, 2) + addObs(11, 3, 2) + case 3: + // After the final snapshot: a new transmission with one + // observation, and a new observation of loaded tx 2. + addTx(6) + addObs(12, 6, 1) + addObs(13, 2, 3) + } + }) + if err := store.RunStartupLoad(2); err != nil { + t.Fatalf("RunStartupLoad: %v", err) + } + if chunk != 3 { + t.Fatalf("expected 3 chunks, got %d", chunk) + } + loaded := loadedObsPaths(store) + if _, ok := loaded[11]; !ok { + t.Fatal("setup: obs 11 should have been loaded by chunk 2") + } + if _, ok := loaded[10]; ok { + t.Fatal("setup: obs 10 should not have been loaded (committed after chunk 1)") + } + + pr := startGapPoller(t, db, store) + time.Sleep(80 * time.Millisecond) + // After the poller started: a later observation of tx 6 and a control. + addObs(14, 6, 2) + addTx(7) + addObs(15, 7, 1) + + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + store.mu.RLock() + _, ok := store.byObsID[15] + store.mu.RUnlock() + if ok { + break + } + time.Sleep(20 * time.Millisecond) + } + time.Sleep(100 * time.Millisecond) // a few more ticks for stragglers + pr.stop() + + store.mu.RLock() + _, tx6 := store.byHash[gapHash(6)] + _, tx7 := store.byHash[gapHash(7)] + var missing []int + for _, id := range []int{10, 12, 13, 14, 15} { + if _, ok := store.byObsID[id]; !ok { + missing = append(missing, id) + } + } + store.mu.RUnlock() + if !tx7 { + t.Fatal("control: tx 7, committed after the poller started, never reached the store; the poller is not running") + } + if !tx6 { + t.Errorf("tx 6, committed after the load's final snapshot, is missing from the store") + } + if len(missing) > 0 { + t.Errorf("observations missing from the store: %v (10 is below the max loaded obs id 11)", missing) + } + assertStoreMatchesDB(t, store, rw) + assertNoDuplicateBroadcasts(t, pr.drain(), loaded) + assertReplayIdempotent(t, store, rw) +} + +type gapPoller struct { + client *Client + stop func() +} + +// startGapPoller runs a poller over store with one capturing hub client. +// stop waits for Start to return, so no tick races the assertions after it. +func startGapPoller(t *testing.T, db *DB, store *PacketStore) *gapPoller { + t.Helper() + hub := NewHub() + c := &Client{send: make(chan []byte, 1024), release: func() {}} + hub.mu.Lock() + hub.clients[c] = true + hub.mu.Unlock() + poller := NewPoller(db, hub, 20*time.Millisecond) + poller.store = store + done := make(chan struct{}) + go func() { + poller.Start() + close(done) + }() + var once sync.Once + stop := func() { + once.Do(func() { + poller.Stop() + <-done + }) + } + t.Cleanup(stop) + return &gapPoller{client: c, stop: stop} +} + +// drain returns every message broadcast so far. +func (p *gapPoller) drain() [][]byte { + var out [][]byte + for { + select { + case m := <-p.client.send: + out = append(out, m) + default: + return out + } + } +} + +// loadedObsPaths maps each observation id the store holds to its path_json. +func loadedObsPaths(store *PacketStore) map[int]string { + store.mu.RLock() + defer store.mu.RUnlock() + out := make(map[int]string, len(store.byObsID)) + for id, o := range store.byObsID { + out[id] = o.PathJSON + } + return out +} + +// assertStoreMatchesDB checks the store holds exactly the DB's transmissions +// and observations: nothing lost, nothing counted twice. +// notLoaded names transmissions outside the loaded window; they and their +// observations are left out of the DB side. +func assertStoreMatchesDB(t *testing.T, store *PacketStore, rw *sql.DB, notLoaded ...int) { + t.Helper() + txWhere, obsWhere := "", "" + if len(notLoaded) > 0 { + ids := strings.Trim(strings.Join(strings.Fields(fmt.Sprint(notLoaded)), ","), "[]") + txWhere = " WHERE id NOT IN (" + ids + ")" + obsWhere = " WHERE transmission_id NOT IN (" + ids + ")" + } + var dbTx, dbObs int + if err := rw.QueryRow(`SELECT COUNT(*) FROM transmissions` + txWhere).Scan(&dbTx); err != nil { + t.Fatal(err) + } + if err := rw.QueryRow(`SELECT COUNT(*) FROM observations` + obsWhere).Scan(&dbObs); err != nil { + t.Fatal(err) + } + store.mu.RLock() + defer store.mu.RUnlock() + sumObs, sumCount := 0, 0 + for _, tx := range store.packets { + sumObs += len(tx.Observations) + sumCount += tx.ObservationCount + } + if len(store.packets) != dbTx || len(store.byHash) != dbTx { + t.Errorf("store transmissions: packets=%d byHash=%d, DB has %d", len(store.packets), len(store.byHash), dbTx) + } + if store.totalObs != dbObs || len(store.byObsID) != dbObs || sumObs != dbObs || sumCount != dbObs { + t.Errorf("store observations: totalObs=%d byObsID=%d attached=%d ObservationCount=%d, DB has %d", + store.totalObs, len(store.byObsID), sumObs, sumCount, dbObs) + } +} + +// assertNoDuplicateBroadcasts checks the poller's catch-up over rows it +// re-read did not re-announce one the load already held, nor any row twice. +func assertNoDuplicateBroadcasts(t *testing.T, msgs [][]byte, loaded map[int]string) { + t.Helper() + loadedPaths := make(map[string]int, len(loaded)) + for id, p := range loaded { + loadedPaths[p] = id + } + seen := make(map[string]bool) + for _, raw := range msgs { + var m struct { + Type string `json:"type"` + Data struct { + Hash string `json:"hash"` + PathJSON string `json:"path_json"` + } `json:"data"` + } + if err := json.Unmarshal(raw, &m); err != nil { + t.Fatalf("broadcast: %v", err) + } + key := m.Data.Hash + " " + m.Data.PathJSON + if seen[key] { + t.Errorf("broadcast twice: %s", key) + } + seen[key] = true + if id, ok := loadedPaths[m.Data.PathJSON]; ok { + t.Errorf("broadcast obs %d, which the startup load already held", id) + } + } + if len(msgs) == 0 { + t.Error("no broadcasts captured; the capturing client is not wired") + } +} + +// assertReplayIdempotent re-reads every row from id 0. A store that already +// holds them all must ingest nothing and announce nothing. notLoaded is as +// for assertStoreMatchesDB. +func assertReplayIdempotent(t *testing.T, store *PacketStore, rw *sql.DB, notLoaded ...int) { + t.Helper() + // IngestNewFromDB applies no retention window, so with transmissions + // outside it a replay would rightly load them; replay observations only. + if len(notLoaded) == 0 { + if txs, _ := store.IngestNewFromDB(0, 1000); len(txs) != 0 { + t.Errorf("replaying transmissions from 0 broadcast %d already-held packets", len(txs)) + } + } + if obs := store.IngestNewObservations(0, 1000); len(obs) != 0 { + t.Errorf("replaying observations from 0 broadcast %d already-held observations", len(obs)) + } + assertStoreMatchesDB(t, store, rw, notLoaded...) +} + +// gapSeeder writes rows the way the ingestor does, with explicit ids (one +// writer: ids commit in order). +type gapSeeder struct { + t *testing.T + rw *sql.DB + base time.Time +} + +func newGapSeeder(t *testing.T, rw *sql.DB) *gapSeeder { + g := &gapSeeder{t: t, rw: rw, base: time.Now().UTC().Add(-10 * time.Minute).Truncate(time.Second)} + for idx := 1; idx <= 3; idx++ { + g.exec(`INSERT INTO observers (rowid, id, name, iata, last_seen, first_seen) VALUES (?, ?, ?, 'SJC', ?, ?)`, + idx, fmt.Sprintf("%064X", idx), fmt.Sprintf("Obs-%d", idx), g.iso(g.base), g.iso(g.base.Add(-time.Hour))) + } + return g +} + +func (g *gapSeeder) iso(ts time.Time) string { return ts.Format("2006-01-02T15:04:05.000Z") } + +// exec may run on a load or poller goroutine, so it reports with Errorf. +func (g *gapSeeder) exec(q string, args ...any) { + if _, err := g.rw.Exec(q, args...); err != nil { + g.t.Errorf("seed: %v\n%s", err, q) + } +} + +// tx inserts a transmission seen at base+id seconds, or two hours ago when +// old, which puts it outside a one-hour retention window. +func (g *gapSeeder) tx(id int, old bool) { + seen := g.base.Add(time.Duration(id) * time.Second) + if old { + seen = g.base.Add(-2 * time.Hour) + } + g.exec(`INSERT INTO transmissions (id, raw_hex, hash, first_seen, route_type, payload_type, payload_version, decoded_json, last_seen) + VALUES (?, ?, ?, ?, 1, 5, 1, '{"type":"GRP_TXT"}', ?)`, + id, fmt.Sprintf("11%02dAABBCCDD", id), gapHash(id), g.iso(seen), seen.Unix()) +} + +// obs inserts an observation with a unique path, so none dedupes. +func (g *gapSeeder) obs(id, tx, observer int) { + g.exec(`INSERT INTO observations (id, transmission_id, observer_idx, direction, snr, rssi, score, path_json, timestamp) + VALUES (?, ?, ?, 'rx', 5.5, -90, 1, ?, ?)`, + id, tx, observer, fmt.Sprintf(`["%02X"]`, id), g.base.Add(time.Duration(id)*time.Second).Unix()) +} + +func gapWait(t *testing.T, ch <-chan struct{}, what string) bool { + select { + case <-ch: + return true + case <-time.After(5 * time.Second): + t.Errorf("timed out waiting for %s", what) + return false + } +} + +func storeHasObs(store *PacketStore, id int) bool { + store.mu.RLock() + defer store.mu.RUnlock() + _, ok := store.byObsID[id] + return ok +} + +func waitStoreObs(store *PacketStore, id int, within time.Duration) bool { + deadline := time.Now().Add(within) + for time.Now().Before(deadline) { + if storeHasObs(store, id) { + return true + } + time.Sleep(10 * time.Millisecond) + } + return storeHasObs(store, id) +} + +// The poller runs from the first chunk on, while later chunks still load. +// Obs 10 of chunk-2 tx 3 is committed after chunk 2's query and polled before +// chunk 2 merges, when tx 3 is not in the store yet. It must end up in the +// store exactly once. This pins an ordering, not a mechanism of its own: the +// poller reads its observation cursor bound before ingestNewObservations polls +// the advert feed, which waits on advertEvidenceMu that each chunk holds from +// its query to its merge. So obs 10 lies above the bound of the poll that +// skips it, and is read again once tx 3 is merged (or the chunk already saw +// it). Obs 11 belongs to a transmission outside retention; it is skipped and +// must not hold back the live observation committed after the load. + +func TestStartupObsDuringChunkMerge_SQLite(t *testing.T) { + db, rw := openGapSQLite(t) + runStartupObsDuringChunkMerge(t, db, rw) +} + +func runStartupObsDuringChunkMerge(t *testing.T, db *DB, rw *sql.DB) { + g := newGapSeeder(t, rw) + for id := 1; id <= 4; id++ { + g.tx(id, false) + g.obs(id, id, 1) + } + g.tx(5, true) // outside retention: never loaded + g.obs(5, 5, 1) + + store := NewPacketStore(db, &PacketStoreConfig{RetentionHours: 1}) + pollerAtFeeds := make(chan struct{}) + releasePoller := make(chan struct{}) + pollerMerged := make(chan struct{}) + var stage atomic.Int32 // 0 idle, 1 poller paused, 2 merge done + store.obsPollHook = func(st obsPollStage) { + switch { + case st == obsPollAfterFeeds && stage.CompareAndSwap(0, 1): + close(pollerAtFeeds) + gapWait(t, releasePoller, "chunk 2's query") + case st == obsPollDone && stage.CompareAndSwap(1, 2): + close(pollerMerged) + } + } + store.OnChunkLoaded(func(int, int) { + if store.loadProgressRows.Load() == 2 { // after chunk 1 + gapWait(t, pollerAtFeeds, "the poller's first tick") + } + }) + store.chunkQueriedHook = func(chunk int) { + if chunk != 2 { + return + } + g.obs(10, 3, 2) // of tx 3, which this chunk is about to merge + g.obs(11, 5, 2) // orphan: tx 5 is outside retention + close(releasePoller) + gapWait(t, pollerMerged, "the poller's merge") + } + + loadErr := make(chan error, 1) + go func() { loadErr <- store.RunStartupLoad(2) }() + <-store.FirstChunkReady() + pr := startGapPoller(t, db, store) + if err := <-loadErr; err != nil { + t.Fatalf("RunStartupLoad: %v", err) + } + if stage.Load() != 2 { + t.Fatal("setup: the poller never polled between chunk 2's query and its merge") + } + + // After the load: a live observation must not wait behind orphan 11. + g.obs(12, 1, 3) + if !waitStoreObs(store, 12, 3*time.Second) { + t.Fatal("live obs 12, committed after the load completed, never reached the store: the feed is blocked") + } + pr.stop() + if !storeHasObs(store, 10) { + t.Error("obs 10 (chunk-2 tx, committed after chunk 2's query, polled before its merge) is missing from the store") + } + if storeHasObs(store, 11) { + t.Error("obs 11 of a transmission outside retention is in the store") + } + assertStoreMatchesDB(t, store, rw, 5) + assertNoDuplicateBroadcasts(t, pr.drain(), nil) + assertReplayIdempotent(t, store, rw, 5) +} + +// A failed transmission or observation read must leave the poller's cursor +// where it was, so the same rows are read once the database recovers. The +// observation cursor's bound comes from its own query, which used to advance +// the cursor past rows the failed read never saw. Renaming observers fails +// both ingest reads (they join it) while the bound query still succeeds. + +func TestPollerRetriesFailedRead_SQLite(t *testing.T) { + db, rw := openGapSQLite(t) + runPollerRetriesFailedRead(t, db, rw) +} + +func runPollerRetriesFailedRead(t *testing.T, db *DB, rw *sql.DB) { + g := newGapSeeder(t, rw) + g.tx(1, false) + g.obs(1, 1, 1) + store := NewPacketStore(db, &PacketStoreConfig{}) + if err := store.RunStartupLoad(100); err != nil { + t.Fatalf("RunStartupLoad: %v", err) + } + loaded := loadedObsPaths(store) + pr := startGapPoller(t, db, store) + + g.exec(`ALTER TABLE observers RENAME TO observers_away`) + renamed := true + defer func() { + if renamed { + g.exec(`ALTER TABLE observers_away RENAME TO observers`) + } + }() + g.tx(2, false) + g.obs(2, 2, 1) // arrives with tx 2 + g.obs(3, 1, 2) // a new observation of loaded tx 1 + + time.Sleep(150 * time.Millisecond) // several failing ticks + if storeHasObs(store, 2) || storeHasObs(store, 3) { + t.Fatal("setup: the ingest reads did not fail while observers was renamed") + } + g.exec(`ALTER TABLE observers_away RENAME TO observers`) + renamed = false + + if !waitStoreObs(store, 3, 3*time.Second) { + t.Error("obs 3, committed while the observation read failed, never reached the store: the cursor passed it") + } + if !waitStoreObs(store, 2, time.Second) { + t.Error("tx 2 and its obs 2, committed while the transmission read failed, never reached the store") + } + pr.stop() + assertStoreMatchesDB(t, store, rw) + assertNoDuplicateBroadcasts(t, pr.drain(), loaded) + assertReplayIdempotent(t, store, rw) +} diff --git a/cmd/server/store.go b/cmd/server/store.go index 71a3b1d44..cab3fee9e 100644 --- a/cmd/server/store.go +++ b/cmd/server/store.go @@ -250,6 +250,14 @@ type PacketStore struct { txRewriteMu sync.Mutex txRewriteCursor int64 + // Poller start cursors: MAX(id) of transmissions / observations, read in + // NewPacketStore before any load query. A row above a mark may have been + // committed after the load's snapshot, so the poller re-reads from there. + // Written once before the store is shared; read-only afterwards. + startupTxMark int + startupObsMark int + startupMarksOK bool // false: no conn, or a MAX query failed + mu sync.RWMutex db *DB packets []*StoreTx // sorted by first_seen ASC (oldest first; newest at tail) @@ -544,9 +552,6 @@ type PacketStore struct { // Hot startup atomic gates — see contract below. // // Contract / ordering invariant (PR #1187): - // * hashMigrationComplete (set by migrateContentHashesAsync) gates - // content-hash–dependent code paths (e.g. dedup correctness on the - // write side). Set true ONLY after the migration loop finishes. // * backgroundLoadDone is set true exactly once, after // loadBackgroundChunks finishes its loop AND its post-load index // rebuild. It gates "hot startup has finished filling @@ -595,9 +600,6 @@ type PacketStore struct { // perf payload for prod observability. loadCoverageRatio float64 - // Async hash migration state: set after migrateContentHashesAsync completes. - hashMigrationComplete atomic.Bool - // Chunked startup load state (#1009). LoadChunked closes // firstChunkReady after the first chunk is merged so the HTTP // listener can bind. loadComplete flips true after all chunks have @@ -649,8 +651,22 @@ type PacketStore struct { // ordering tests to capture the bg-loader entry timestamp/signal // without polling. See runstartup_load_test.go. bgLoaderEntryHook func() + // Test-only hooks for the poller/load interleaving tests. Nil in + // production. chunkQueriedHook fires in LoadChunked after a chunk's + // query returns, before its rows are merged (chunk counts from 1). + // obsPollHook fires in ingestNewObservations after the feeds are + // polled and again when it returns. + chunkQueriedHook func(chunk int) + obsPollHook func(stage obsPollStage) } +type obsPollStage int + +const ( + obsPollAfterFeeds obsPollStage = iota + obsPollDone +) + // Precomputed distance records for fast analytics aggregation. type distHopRecord struct { FromName string @@ -857,6 +873,11 @@ func NewPacketStore(db *DB, cfg *PacketStoreConfig, cacheTTLs ...map[string]inte ps.invCooldown = v } } + // Capture BEFORE loading any packets: the load reads each chunk in its own + // snapshot, so a row committed while it runs is only safe if the poller + // starts at or below it. One writer commits ids in order, so everything + // the load can miss lies above these marks (see Poller.startCursors). + ps.startupTxMark, ps.startupObsMark, ps.startupMarksOK = db.highWaterMarks() // Capture BEFORE loading any packets. Evidence arriving during startup // remains above this watermark; each loaded tx also reads its full mask. if db.advertEvidencePresent() { @@ -3038,9 +3059,23 @@ func (s *PacketStore) queryMultiNodePacketsLocked(resolved []string, limit, offs return &PacketResult{Packets: packets, Total: total}, jobs } +// wsPacketMaps is a batch of broadcast-ready packet maps from the ingest paths. +type wsPacketMaps []map[string]interface{} + // IngestNewFromDB loads new transmissions from SQLite into memory and returns // broadcast-ready maps plus the new max transmission ID. -func (s *PacketStore) IngestNewFromDB(sinceID, limit int) ([]map[string]interface{}, int) { +func (s *PacketStore) IngestNewFromDB(sinceID, limit int) (wsPacketMaps, int) { + out, newMax, err := s.ingestNewFromDB(sinceID, limit) + if err != nil { + log.Printf("[store] %v", err) + } + return out, newMax +} + +// ingestNewFromDB is IngestNewFromDB reporting a failed read. On error the +// returned max is sinceID, so the caller's cursor stays put and the poll is +// retried. +func (s *PacketStore) ingestNewFromDB(sinceID, limit int) (wsPacketMaps, int, error) { if limit <= 0 { limit = 100 } @@ -3082,8 +3117,7 @@ func (s *PacketStore) IngestNewFromDB(sinceID, limit int) ([]map[string]interfac rows, err := s.db.conn.Query(querySQL, sinceID) if err != nil { - log.Printf("[store] ingest query error: %v", err) - return nil, sinceID + return nil, sinceID, fmt.Errorf("ingest query error: %w", err) } defer rows.Close() @@ -3164,11 +3198,11 @@ func (s *PacketStore) IngestNewFromDB(sinceID, limit int) ([]map[string]interfac tempRows = append(tempRows, tr) } - if len(tempRows) == 0 { - return nil, sinceID - } if err := rows.Err(); err != nil { - return nil, sinceID + return nil, sinceID, fmt.Errorf("ingest read error: %w", err) + } + if len(tempRows) == 0 { + return nil, sinceID, nil } rows.Close() s.advertEvidenceMu.Lock() @@ -3181,8 +3215,7 @@ func (s *PacketStore) IngestNewFromDB(sinceID, limit int) ([]map[string]interfac } masks, err := s.db.advertEvidenceForIDs(ids) if err != nil { - log.Printf("[store] load advert evidence: %v", err) - return nil, sinceID + return nil, sinceID, fmt.Errorf("load advert evidence: %w", err) } // Now lock and merge into store @@ -3445,16 +3478,31 @@ func (s *PacketStore) IngestNewFromDB(sinceID, limit int) ([]map[string]interfac if evidenceChanged { s.invalidateAdvertEvidence() } - return result, newMaxID + return result, newMaxID, nil } // IngestNewObservations loads new observations for transmissions already in the // store. This catches observations that arrive after IngestNewFromDB has already // advanced past the transmission's ID (fixes #174). -func (s *PacketStore) IngestNewObservations(sinceObsID, limit int) []map[string]interface{} { +func (s *PacketStore) IngestNewObservations(sinceObsID, limit int) wsPacketMaps { + out, err := s.ingestNewObservations(sinceObsID, limit) + if err != nil { + log.Printf("[store] %v", err) + } + return out +} + +// ingestNewObservations is IngestNewObservations reporting a failed read, so +// the poller can keep its cursor and retry instead of passing rows it never +// saw. A row that fails to scan is still skipped. +func (s *PacketStore) ingestNewObservations(sinceObsID, limit int) (wsPacketMaps, error) { // Must run even when observation IDs/timestamps have not changed. s.refreshAdvertEvidence() s.refreshTxRewrites() // #2107: rewrites never move IDs, so poll them here too + if s.obsPollHook != nil { + s.obsPollHook(obsPollAfterFeeds) + defer s.obsPollHook(obsPollDone) + } if limit <= 0 { limit = 500 } @@ -3484,8 +3532,7 @@ func (s *PacketStore) IngestNewObservations(sinceObsID, limit int) []map[string] rows, err := s.db.conn.Query(querySQL, sinceObsID, limit) if err != nil { - log.Printf("[store] ingest observations query error: %v", err) - return nil + return nil, fmt.Errorf("ingest observations query error: %w", err) } defer rows.Close() @@ -3536,8 +3583,11 @@ func (s *PacketStore) IngestNewObservations(sinceObsID, limit int) []map[string] }) } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("ingest observations read error: %w", err) + } if len(obsRows) == 0 { - return nil + return nil, nil } s.mu.Lock() @@ -3740,7 +3790,7 @@ func (s *PacketStore) IngestNewObservations(sinceObsID, limit int) []map[string] _ = pm _ = graphRef - return broadcastMaps + return broadcastMaps, nil } // MaxTransmissionID returns the highest transmission ID in the store. @@ -3750,6 +3800,12 @@ func (s *PacketStore) MaxTransmissionID() int { return s.maxTxID } +// StartupMarks returns the transmission and observation high-water marks taken +// before the startup load, and whether both queries succeeded. +func (s *PacketStore) StartupMarks() (txMark, obsMark int, ok bool) { + return s.startupTxMark, s.startupObsMark, s.startupMarksOK +} + // MaxObservationID returns the highest observation ID in the store. func (s *PacketStore) MaxObservationID() int { s.mu.RLock() @@ -4943,12 +4999,10 @@ func (s *PacketStore) updateDistanceIndexForTxs(txs []*StoreTx) { for _, tx := range txs { removeSet[tx] = true } - s.distHops = slices.DeleteFunc(slices.Clone(s.distHops), func(r distHopRecord) bool { - return removeSet[r.tx] - }) - s.distPaths = slices.DeleteFunc(slices.Clone(s.distPaths), func(r distPathRecord) bool { - return removeSet[r.tx] - }) + // Distance readers borrow these arrays after releasing s.mu. Copy here, + // once per changed-path batch, so their O(1) snapshots remain immutable. + s.distHops = slices.DeleteFunc(slices.Clone(s.distHops), func(r distHopRecord) bool { return removeSet[r.tx] }) + s.distPaths = slices.DeleteFunc(slices.Clone(s.distPaths), func(r distPathRecord) bool { return removeSet[r.tx] }) // Build lookup maps once. allNodes, pm := s.getCachedNodesAndPM() @@ -5211,15 +5265,15 @@ func (s *PacketStore) trackedMemoryMB() float64 { return float64(s.trackedBytes) / 1048576.0 } -// EvictStaleWithRP retains the existing entry point for callers with a SQL -// batch. Eviction now walks the actual in-memory indexes, so it does not need -// (or trust) persisted resolved paths to discover references. Must hold s.mu. +// EvictStaleWithRP retains the old entry point for callers with a prefetched +// batch. Cleanup uses actual in-memory membership; SQL paths may differ from it. +// Must be called under s.mu.Lock. func (s *PacketStore) EvictStaleWithRP(_ map[int][]string) int { return s.evictStaleInternal() } -// EvictStale removes packets older than the retention window and/or exceeding -// the memory cap. Must hold s.mu for writing. Returns packets evicted. +// EvictStale removes expired packets and their in-memory memberships without SQL. +// Must be called under s.mu.Lock. func (s *PacketStore) EvictStale() int { return s.evictStaleInternal() } @@ -5384,7 +5438,8 @@ func (s *PacketStore) evictStaleInternal() int { // DeleteFunc clears discarded pointer slots as well as shortening the // slice. The GC scans the whole backing array, including beyond len. for obsID := range affectedObservers { - filtered := slices.DeleteFunc(s.byObserver[obsID], func(o *StoreObs) bool { + obsList := s.byObserver[obsID] + filtered := slices.DeleteFunc(obsList, func(o *StoreObs) bool { _, evicted := evictedObsIDs[o.ID] return evicted }) @@ -5395,8 +5450,9 @@ func (s *PacketStore) evictStaleInternal() int { } } for pt := range affectedPayloadTypes { - filtered := slices.DeleteFunc(s.byPayloadType[pt], func(tx *StoreTx) bool { - _, evicted := evictedTxIDs[tx.ID] + ptList := s.byPayloadType[pt] + filtered := slices.DeleteFunc(ptList, func(t *StoreTx) bool { + _, evicted := evictedTxIDs[t.ID] return evicted }) if len(filtered) == 0 { @@ -5406,17 +5462,15 @@ func (s *PacketStore) evictStaleInternal() int { } } - // Sweep the actual node index once per batch, like byPathHop above. - // Cold-load and live path resolution can add node keys that never reach - // observations.resolved_path (the server is read-only). A SQL-derived - // affected-node list misses those keys and pins evicted txs and all their - // observations forever. This is O(total node memberships), not one scan - // per evicted packet, and needs no new reverse index or DB query. - for nodeKey, list := range s.byNode { - filtered := slices.DeleteFunc(list, func(tx *StoreTx) bool { - _, evicted := evictedTxIDs[tx.ID] + // Sweep actual memberships once per batch, as for byPathHop. Server-side + // resolution can differ from persisted paths or have no persisted path at + // all. Reconstructing keys from SQL leaves uncharged packet graphs alive. + // Readers either hold s.mu or copy these buckets before releasing it. + for nodeKey, nodeList := range s.byNode { + filtered := slices.DeleteFunc(nodeList, func(t *StoreTx) bool { + _, evicted := evictedTxIDs[t.ID] if evicted { - delete(s.nodeHashes[nodeKey], tx.ID) + delete(s.nodeHashes[nodeKey], t.ID) } return evicted }) @@ -5430,25 +5484,30 @@ func (s *PacketStore) evictStaleInternal() int { } } - // Distance analytics readers retain slice snapshots after unlocking. - // Replace these arrays instead of mutating them; readers can finish on - // the old immutable arrays, which are then collected. DeleteFunc clears - // the replacement tails so the store retains only surviving records. - s.distHops = slices.DeleteFunc(slices.Clone(s.distHops), func(h distHopRecord) bool { - if h.tx == nil { - return false - } - _, evicted := evictedTxIDs[h.tx.ID] - return evicted - }) - s.distPaths = slices.DeleteFunc(slices.Clone(s.distPaths), func(p distPathRecord) bool { - if p.tx == nil { - return false - } - _, evicted := evictedTxIDs[p.tx.ID] - return evicted - }) - s.packets = slices.Delete(s.packets, 0, cutoffIdx) + // Remove from distance indexes — filter out records referencing evicted txs + evictedTxSet := make(map[*StoreTx]bool, cutoffIdx) + for _, tx := range evicting { + evictedTxSet[tx] = true + } + // Only copy arrays with evicted records. Preserve arrays borrowed by + // unlocked readers; deleting from the copied suffix clears retired pointers. + isEvictedHop := func(r distHopRecord) bool { return evictedTxSet[r.tx] } + if first := slices.IndexFunc(s.distHops, isEvictedHop); first >= 0 { + hops := slices.Clone(s.distHops) + filtered := slices.DeleteFunc(hops[first:], isEvictedHop) + s.distHops = hops[:first+len(filtered)] + } + isEvictedPath := func(r distPathRecord) bool { return evictedTxSet[r.tx] } + if first := slices.IndexFunc(s.distPaths, isEvictedPath); first >= 0 { + paths := slices.Clone(s.distPaths) + filtered := slices.DeleteFunc(paths[first:], isEvictedPath) + s.distPaths = paths[:first+len(filtered)] + } + + // Trim packets slice + n := copy(s.packets, s.packets[cutoffIdx:]) + clear(s.packets[n:]) + s.packets = s.packets[:n] s.totalObs -= evictedObs evictCount := cutoffIdx @@ -5475,8 +5534,8 @@ func (s *PacketStore) evictStaleInternal() int { return evictCount } -// RunEviction acquires the write lock and runs eviction. Cleanup uses the -// in-memory indexes, so no SQL prefetch or second candidate pass is needed. +// RunEviction acquires the write lock and runs eviction. Safe to call from +// a goroutine. Returns evicted count. func (s *PacketStore) RunEviction() int { s.mu.Lock() defer s.mu.Unlock() @@ -8271,8 +8330,12 @@ func (s *PacketStore) computeAnalyticsTopology(region, area string, window TimeW // --- Distance Analytics --- +// earthRadiusKm is the sphere of every great-circle distance, sample and +// earth bulge on the server (haversineKm, greatCircleSamples, analyzeLOS). +const earthRadiusKm = 6371.0 + func haversineKm(lat1, lon1, lat2, lon2 float64) float64 { - const R = 6371.0 + const R = earthRadiusKm dLat := (lat2 - lat1) * math.Pi / 180 dLon := (lon2 - lon1) * math.Pi / 180 a := math.Sin(dLat/2)*math.Sin(dLat/2) + @@ -8320,11 +8383,24 @@ func (s *PacketStore) GetAnalyticsDistance(region, area string) map[string]inter return result } +// snapshotDistanceIndexLocked borrows immutable record arrays for an unlocked +// reader. Path updates and eviction filter copies; appends stay beyond the +// captured length. Hop-detail slices are immutable too. Caller holds s.mu. +func (s *PacketStore) snapshotDistanceIndexLocked() ([]distHopRecord, []distPathRecord) { + return s.distHops, s.distPaths +} + func (s *PacketStore) computeAnalyticsDistance(region, area string) map[string]interface{} { - // Snapshot slice headers under RLock, then aggregate outside it (#1239). - // Writers append or replace these arrays: eviction and live-path updates - // copy before filtering, so published record values remain immutable. - // Readers can safely finish using old arrays, then release them to GC. + // #1239: hold s.mu.RLock() only long enough to (a) snapshot the + // distHops/distPaths slice headers and (b) build the region match + // set (which reads tx.Observations, a field mutated by ingest under + // s.mu.Lock). All filtering, sorting, deduping, histogram building + // and category stats run on locally-captured slices OUTSIDE the + // lock so concurrent ingest writers are not blocked by readers. + // + // Safety: snapshot slice headers are O(1). Ingest appends beyond the + // captured length; path updates and eviction filter copies, never mutate + // these borrowed backing arrays. Hop-detail slices are immutable too. var regionObs map[string]bool if region != "" { // resolveRegionObservers uses its own mutex (regionObsMu) @@ -8337,8 +8413,7 @@ func (s *PacketStore) computeAnalyticsDistance(region, area string) map[string]i } s.mu.RLock() - hopsSnap := s.distHops - pathsSnap := s.distPaths + hopsSnap, pathsSnap := s.snapshotDistanceIndexLocked() // Build region match set INSIDE the lock — touches tx.Observations // (slice header mutated by ingest). For non-region calls (the common diff --git a/cmd/server/store_read_race_2237_test.go b/cmd/server/store_read_race_2237_test.go index 6334ddf28..03b71cc0b 100644 --- a/cmd/server/store_read_race_2237_test.go +++ b/cmd/server/store_read_race_2237_test.go @@ -218,8 +218,9 @@ func TestStatsTrackedBytesRace2237(t *testing.T) { }) } -// The content-hash migration (hash_migrate.go) rewrites tx.Hash under -// s.mu.Lock while the observer analytics handler builds its response. +// A writer rewriting tx.Hash under s.mu.Lock (the server-side content-hash +// migration did this until #1856 moved it to the ingestor) must not race the +// observer analytics handler building its response. func TestObserverAnalyticsHashMigrationRace2237(t *testing.T) { s := makeRaceStore2237(20) srv := &Server{store: s} diff --git a/cmd/server/terrain_config.go b/cmd/server/terrain_config.go new file mode 100644 index 000000000..b5d5a5e5f --- /dev/null +++ b/cmd/server/terrain_config.go @@ -0,0 +1,209 @@ +package main + +// Terrain for route line-of-sight (elevation.go) and the repeater planner +// (planner_api.go). Both read ONE SRTM tile source (terrain_srtm.go), so a +// leg's terrain, and with it its verdict, is the same in both views. The +// source exists only while los or planner is enabled; the "terrain" block has +// no switch of its own. + +import ( + "log" + "net/url" + "strings" + "time" +) + +// TerrainConfig is the "terrain" block in config.json. +type TerrainConfig struct { + // TileURL is the base of an SRTM "skadi" tile tree: + // /N30/N30W098.hgt.gz, https without a query. Default AWS Open + // Data elevation-tiles-prod. + TileURL string `json:"tileUrl"` + // TileCacheTiles caps resident downsampled tiles (~2.9 MB each), 4-200. + // The effective cache never goes below one full view (cacheTiles). + TileCacheTiles int `json:"tileCacheTiles"` +} + +const ( + defaultTerrainTileURL = "https://s3.amazonaws.com/elevation-tiles-prod/skadi" + defaultTerrainTileCache = 24 + // terrainDefaultSource attributes the default tiles in responses. + terrainDefaultSource = "SRTM (AWS Open Data)" + + // terrainClientTilesPerMin refills a client's tile download budget + // (terrainClientBudget), half the global srtmPerMinute: one client + // cannot hold the shared budget on its own. + terrainClientTilesPerMin = 10 + // terrainClientHourFloor is the least a client may download in an hour. + terrainClientHourFloor = 40 +) + +// terrainClientBudget is one client's tile download budget, shared by route +// LOS and the planner, for a source whose largest view is viewTiles +// (terrainViewTiles): burst tokens, so any single request can load in one +// go, refilled at terrainClientTilesPerMin, under an hourly cap of hourly +// tokens refilled at hourly an hour. Even twice hourly (a full cap plus an +// hour of refill) stays below the global hourly budget (srtmBudgetFor) at +// every size the planner allows: 160 of 200 at 40 tiles a view. +func terrainClientBudget(viewTiles int) (burst, hourly int) { + return viewTiles, max(terrainClientHourFloor, 2*viewTiles) +} + +// newTerrainClientLimiter builds the per-client terrain download limiter +// route LOS and the planner share (newTerrainServices): one token per tile +// download a request or job starts, keyed like every other per-client limit +// (clientKey). +func newTerrainClientLimiter(trustedProxies []string, viewTiles int) *clientLimiter { + burst, hourly := terrainClientBudget(viewTiles) + return &clientLimiter{ + ipr: &wsLimiter{state: map[string]*wsIPState{}, + trustedProxies: parseCIDRList(trustedProxies, "webSocket.trustedProxies")}, + rl: newCappedRateLimiter(burst, terrainClientTilesPerMin, time.Minute, hourly, time.Hour), + tag: "terrain", what: "terrain download", + } +} + +// resolved applies defaults; invalid values fall back with a warning. +func (c *TerrainConfig) resolved() (TerrainConfig, []string) { + out := TerrainConfig{TileURL: defaultTerrainTileURL, TileCacheTiles: defaultTerrainTileCache} + if c == nil { + return out, nil + } + var warns []string + if c.TileURL != "" { + if u, err := url.Parse(c.TileURL); err == nil && u.Scheme == "https" && u.Host != "" && u.RawQuery == "" { + out.TileURL = c.TileURL + } else { + warns = append(warns, "terrain.tileUrl must be an https URL without a query; using the default") + } + } + if c.TileCacheTiles != 0 { + if c.TileCacheTiles >= 4 && c.TileCacheTiles <= 200 { + out.TileCacheTiles = c.TileCacheTiles + } else { + warns = append(warns, "terrain.tileCacheTiles must be within 4-200; using the default") + } + } + return out, warns +} + +// cacheTiles is the cache size in tiles: TileCacheTiles (0 = the default), +// raised to viewTiles when it is smaller. A smaller cache would evict a +// request's own tiles while loading them, so the next request downloads them +// again. +func (c TerrainConfig) cacheTiles(viewTiles int) int { + n := c.TileCacheTiles + if n <= 0 { + n = defaultTerrainTileCache + } + return max(n, viewTiles) +} + +// terrainSourceName is the attribution every terrain response carries: +// terrainDefaultSource for the default tiles, else "SRTM ()". +func terrainSourceName(tileURL string) string { + if tileURL == "" || strings.TrimRight(tileURL, "/") == defaultTerrainTileURL { + return terrainDefaultSource + } + u, err := url.Parse(tileURL) + if err != nil || u.Hostname() == "" { + return "SRTM" + } + return "SRTM (" + u.Hostname() + ")" +} + +// terrainViewTiles is the most tiles one load of the shared source may span: +// the largest planner cap (planner on) and losMaxTiles (los on); 0 when both +// are off. It is the source's per-view cap and its cache floor. +func terrainViewTiles(los *LOSConfig, planner *PlannerConfig) int { + n := 0 + if los.enabled() { + n = losMaxTiles + } + if planner.enabled() { + r, _ := planner.resolved() + n = max(n, r.tileLimits().max()) + } + return n +} + +// terrainUsers names the features reading the source, for the startup log. +func terrainUsers(los *LOSConfig, planner *PlannerConfig) string { + switch { + case los.enabled() && planner.enabled(): + return "route LOS and the planner" + case los.enabled(): + return "route LOS" + } + return "the planner" +} + +// logTerrainConfig reports the effective source once at startup. +func logTerrainConfig(c *TerrainConfig, los *LOSConfig, planner *PlannerConfig) { + r, warns := c.resolved() + for _, w := range warns { + log.Printf("[terrain] %s", w) + } + views := terrainViewTiles(los, planner) + cache := r.cacheTiles(views) + if cache > r.TileCacheTiles { + log.Printf("[terrain] tileCacheTiles=%d is below one full view; keeping %d tiles resident", + r.TileCacheTiles, cache) + } + // A view keeps its own references, so tiles evicted while it is in use + // stay in memory until it is done. Every eviction is a download, so the + // extra is about one minute of the download budget. + budget := srtmBudgetFor(views) + log.Printf("[terrain] SRTM tiles from %s for %s: up to %d tiles per view, cache %d tiles (%.0f MB, %.1f MB a tile); "+ + "views in use can briefly keep about %d evicted tiles more (%.0f MB, a minute of downloads)", + terrainTileHost(r.TileURL), terrainUsers(los, planner), views, cache, + float64(cache)*srtmTileBytes/1e6, float64(srtmTileBytes)/1e6, + budget.perMinute, float64(budget.perMinute)*srtmTileBytes/1e6) + burst, hourly := terrainClientBudget(views) + log.Printf("[terrain] tile downloads: %d/min and %d/hour for everyone; per client, %d at once, "+ + "then %d/min, at most %d/hour", + budget.perMinute, budget.perHour, burst, terrainClientTilesPerMin, hourly) +} + +// terrainTileHost is the tile URL reduced to scheme and host for logs: a +// self-hosted tile server's path or userinfo may carry a token. +func terrainTileHost(raw string) string { + u, err := url.Parse(raw) + if err != nil || u.Host == "" { + return "(invalid)" + } + return u.Scheme + "://" + u.Host +} + +// newTerrainServices builds the services los and planner enable over one +// shared SRTM source, and logs the effective config of each once. A service +// whose feature is off is nil; with both off no source is built. +func newTerrainServices(cfg *Config, s *Server) (*elevationService, *plannerService) { + if !cfg.LOS.enabled() && !cfg.Planner.enabled() { + return nil, nil + } + logTerrainConfig(cfg.Terrain, cfg.LOS, cfg.Planner) + tc, _ := cfg.Terrain.resolved() + views := terrainViewTiles(cfg.LOS, cfg.Planner) + src := newSRTMSource(tc, views) + // One budget per client across both features: a client cannot get twice + // the downloads by using both. + downloads := newTerrainClientLimiter(cfg.WSTrustedProxies(), views) + + var elev *elevationService + if cfg.LOS.enabled() { + logLOSConfig(cfg.LOS) + elev = newElevationService(src) + elev.nodes = serverPlannerData{s}.nodes + elev.visibility = s + elev.downloads = downloads + } + var planner *plannerService + if cfg.Planner.enabled() { + logPlannerConfig(cfg.Planner) + pc, _ := cfg.Planner.resolved() + planner = newPlannerService(pc, s, src) + planner.downloads = downloads + } + return elev, planner +} diff --git a/cmd/server/terrain_config_test.go b/cmd/server/terrain_config_test.go new file mode 100644 index 000000000..86a2d1d71 --- /dev/null +++ b/cmd/server/terrain_config_test.go @@ -0,0 +1,381 @@ +package main + +import ( + "bytes" + "compress/gzip" + "encoding/json" + "fmt" + "log" + "math" + "net/http" + "slices" + "strings" + "testing" + "time" +) + +func TestTerrainConfigResolve(t *testing.T) { + // Unset: the defaults, no warning. + for _, c := range []*TerrainConfig{nil, {}} { + r, warns := c.resolved() + if r.TileURL != defaultTerrainTileURL || r.TileCacheTiles != defaultTerrainTileCache || len(warns) != 0 { + t.Fatalf("%+v: resolved %+v, warnings %q", c, r, warns) + } + } + // Valid values are kept, each end of the cache range included. + for _, c := range []TerrainConfig{ + {TileURL: "https://tiles.example.com/skadi", TileCacheTiles: 4}, + {TileURL: "https://user:pw@tiles.example.com:8443/tok/skadi/", TileCacheTiles: 200}, + } { + r, warns := c.resolved() + if r != c || len(warns) != 0 { + t.Fatalf("%+v: resolved %+v, warnings %q", c, r, warns) + } + } + // Invalid values fall back, one warning each. + const badURL = "terrain.tileUrl must be an https URL without a query; using the default" + const badCache = "terrain.tileCacheTiles must be within 4-200; using the default" + for _, c := range []struct { + cfg TerrainConfig + warn []string + }{ + {TerrainConfig{TileURL: "http://tiles.example.com/skadi"}, []string{badURL}}, + {TerrainConfig{TileURL: "https://tiles.example.com/skadi?key=x"}, []string{badURL}}, + {TerrainConfig{TileURL: "https:///skadi"}, []string{badURL}}, + {TerrainConfig{TileURL: "file:///etc"}, []string{badURL}}, + {TerrainConfig{TileURL: "::"}, []string{badURL}}, + {TerrainConfig{TileCacheTiles: 3}, []string{badCache}}, + {TerrainConfig{TileCacheTiles: 201}, []string{badCache}}, + {TerrainConfig{TileURL: "ftp://x", TileCacheTiles: -1}, []string{badURL, badCache}}, + } { + r, warns := c.cfg.resolved() + if r.TileURL != defaultTerrainTileURL || r.TileCacheTiles != defaultTerrainTileCache || !slices.Equal(warns, c.warn) { + t.Errorf("%+v: resolved %+v, warnings %q", c.cfg, r, warns) + } + } + // The block decodes from config.json, and los/planner lost their tile keys. + var cfg Config + raw := `{"terrain":{"tileUrl":"https://tiles.example.com/skadi","tileCacheTiles":50}}` + if err := json.Unmarshal([]byte(raw), &cfg); err != nil { + t.Fatal(err) + } + if cfg.Terrain == nil || cfg.Terrain.TileURL != "https://tiles.example.com/skadi" || cfg.Terrain.TileCacheTiles != 50 { + t.Fatalf("decoded %+v", cfg.Terrain) + } + if b, _ := json.Marshal(LOSConfig{}); string(b) != `{"enabled":false,"frequencyMhz":0,"antennaHeightM":0,"kFactor":0}` { + t.Errorf("los keys %s", b) + } + if b, _ := json.Marshal(PlannerConfig{}); strings.Contains(string(b), "tileUrl") || strings.Contains(string(b), "tileCacheTiles") { + t.Errorf("planner keys %s", b) + } +} + +// Responses name the terrain they read: the default tiles as AWS Open Data, +// any other tile server by its host (never its path or credentials). +func TestTerrainSourceName(t *testing.T) { + for _, c := range []struct{ url, want string }{ + {"", terrainDefaultSource}, + {defaultTerrainTileURL, "SRTM (AWS Open Data)"}, + {defaultTerrainTileURL + "/", "SRTM (AWS Open Data)"}, + {"https://user:pw@tiles.example.com:8443/tok-1/skadi", "SRTM (tiles.example.com)"}, + {"https://s3.amazonaws.com/my-bucket/skadi", "SRTM (s3.amazonaws.com)"}, + } { + if got := terrainSourceName(c.url); got != c.want { + t.Errorf("terrainSourceName(%q) = %q, want %q", c.url, got, c.want) + } + } + if got := newSRTMSource(TerrainConfig{}, 0).source; got != terrainDefaultSource { + t.Errorf("default source %q", got) + } + if got := newSRTMSource(TerrainConfig{TileURL: "https://dem.example.org/skadi/"}, 0).source; got != "SRTM (dem.example.org)" { + t.Errorf("custom source %q", got) + } +} + +func TestTerrainViewTiles(t *testing.T) { + on := true + los := &LOSConfig{Enabled: on} + small := &PlannerConfig{Enabled: on} + big := &PlannerConfig{Enabled: on, MaxAreaKm: 200, NodeMarginKm: 50, MaxLegKm: 150} + if small.tileLimits().max() >= losMaxTiles || func() int { r, _ := big.resolved(); return r.tileLimits().max() }() <= losMaxTiles { + t.Fatal("the test needs one planner below losMaxTiles and one above") + } + for _, c := range []struct { + name string + los *LOSConfig + planner *PlannerConfig + want int + }{ + {"neither", nil, nil, 0}, + {"both disabled", &LOSConfig{}, &PlannerConfig{}, 0}, + {"los only", los, nil, losMaxTiles}, + {"planner only", nil, small, small.tileLimits().max()}, + {"both, los larger", los, small, losMaxTiles}, + {"both, planner larger", los, big, 28}, + } { + if got := terrainViewTiles(c.los, c.planner); got != c.want { + t.Errorf("%s: %d tiles, want %d", c.name, got, c.want) + } + } +} + +// Review #2391 point 9: route LOS and the planner read one SRTM source, so +// a leg's terrain cannot differ between them. Its per-view cap and cache +// cover whichever of them needs more. +func TestTerrainServicesShareOneSource(t *testing.T) { + terrainQuietLog(t) + newSrv := func(cfg *Config) (*elevationService, *plannerService) { + t.Helper() + e, p := newTerrainServices(cfg, &Server{cfg: cfg}) + if p != nil { + t.Cleanup(p.Close) + } + return e, p + } + + // Both on: one source, sized for the larger of the two. + tc := &TerrainConfig{TileURL: "https://dem.example.org/skadi", TileCacheTiles: 4} + cfg := &Config{LOS: &LOSConfig{Enabled: true}, Planner: &PlannerConfig{Enabled: true}, Terrain: tc} + e, p := newSrv(cfg) + if e == nil || p == nil { + t.Fatalf("services %v %v", e, p) + } + if ps, ok := p.src.(*srtmSource); !ok || ps != e.src { + t.Fatalf("planner source %p, LOS source %p: not shared", p.src, e.src) + } + if e.src.maxTiles != losMaxTiles || e.src.cache.maxItems != losMaxTiles || e.src.baseURL != tc.TileURL { + t.Fatalf("shared source: max %d, cache %d, base %s", e.src.maxTiles, e.src.cache.maxItems, e.src.baseURL) + } + if e.src.source != "SRTM (dem.example.org)" || p.source != e.src.source { + t.Fatalf("attribution: LOS %q, planner %q", e.src.source, p.source) + } + if e.nodes == nil || e.visibility == nil || e.downloads == nil || e.downloads.ipr == nil { + t.Fatalf("LOS service not wired: %+v", e) + } + // One download budget per client across both features, sized for one + // full view of the shared source. + if p.downloads != e.downloads || e.downloads.rl.burst != float64(e.src.maxTiles) { + t.Fatalf("download budgets: LOS %p, planner %p, burst %v", e.downloads, p.downloads, e.downloads.rl.burst) + } + + // A larger planner raises the shared cap and cache floor. + big := &PlannerConfig{Enabled: true, MaxAreaKm: 200, NodeMarginKm: 50, MaxLegKm: 150} + e, p = newSrv(&Config{LOS: &LOSConfig{Enabled: true}, Planner: big}) + if e.src != p.src.(*srtmSource) || e.src.maxTiles != 28 || e.src.cache.maxItems != 28 { + t.Fatalf("big planner: max %d, cache %d", e.src.maxTiles, e.src.cache.maxItems) + } + if e.src.source != terrainDefaultSource { + t.Fatalf("default attribution %q", e.src.source) + } + + // One feature: the other service is nil. + if e, p := newSrv(&Config{LOS: &LOSConfig{Enabled: true}}); e == nil || p != nil || e.src.maxTiles != losMaxTiles { + t.Fatalf("los only: %v %v", e, p) + } + if e, p := newSrv(&Config{Planner: &PlannerConfig{Enabled: true}}); e != nil || p == nil || + p.src.(*srtmSource).maxTiles != (PlannerConfig{}).tileLimits().max() { + t.Fatalf("planner only: %v %v", e, p) + } + if e, p := newSrv(&Config{Terrain: tc}); e != nil || p != nil { + t.Fatalf("neither: %v %v", e, p) + } +} + +// Review #2391: a terrain cache smaller than one view evicted the view's +// own tiles while it loaded, so the next request on the same area downloaded +// them again. The configured size is still validated as 4-200, but the +// cache in use never holds fewer tiles than one full view. +func TestTerrainCacheHoldsOneView(t *testing.T) { + view := PlannerConfig{}.tileLimits().max() + if view <= 4 { + t.Fatalf("one view is %d tiles: the test needs it above the configurable minimum", view) + } + for _, tc := range []struct{ configured, want int }{ + {0, defaultTerrainTileCache}, {4, view}, {view - 1, view}, {view, view}, + {defaultTerrainTileCache, defaultTerrainTileCache}, {200, 200}, + } { + c := TerrainConfig{TileCacheTiles: tc.configured} + if got := c.cacheTiles(view); got != tc.want { + t.Errorf("tileCacheTiles=%d: cache %d, want %d", tc.configured, got, tc.want) + } + if got := newSRTMSource(c, view).cache.maxItems; got != tc.want { + t.Errorf("tileCacheTiles=%d: source capacity %d, want %d", tc.configured, got, tc.want) + } + } + + // The raise is logged at startup, once; a large enough cache is not. + var buf bytes.Buffer + prev, flags := log.Writer(), log.Flags() + log.SetOutput(&buf) + t.Cleanup(func() { log.SetOutput(prev); log.SetFlags(flags) }) + planner := &PlannerConfig{Enabled: true} + logTerrainConfig(&TerrainConfig{TileCacheTiles: 4}, nil, planner) + raised := fmt.Sprintf("tileCacheTiles=4 is below one full view; keeping %d tiles resident", view) + if out := buf.String(); strings.Count(out, raised) != 1 || !strings.Contains(out, fmt.Sprintf("cache %d tiles", view)) { + t.Fatalf("log %q", out) + } + buf.Reset() + logTerrainConfig(nil, nil, planner) + if out := buf.String(); strings.Contains(out, "below one full view") { + t.Fatalf("log %q", out) + } + + // End to end: with tileCacheTiles 4, a 3×4-tile view stays resident + // after it loads, and loading it again downloads nothing. + box := geoBBox{S: 49.5, W: 2.5, N: 51.5, E: 5.5} + sp, _ := srtmSpanOf(box) + if sp.count() != 12 || sp.count() > view { + t.Fatalf("test box spans %d tiles, one view %d", sp.count(), view) + } + tile := srtmConstTile(t, 100, srtmRawBytes, gzip.BestSpeed) + tiles := map[string][]byte{} + for i := 0; i < sp.count(); i++ { + tiles[srtmPath(sp.key(i))] = tile + } + s, u, _ := newSRTMTest(t, 4, srtmServe(tiles)) + srtmMustView(t, s, box) + if !s.Resident(box) || srtmCacheLen(s) != sp.count() { + t.Fatalf("after one view: resident %v, %d tiles cached", s.Resident(box), srtmCacheLen(s)) + } + srtmMustView(t, s, box) + if n := u.total(); n != sp.count() { + t.Fatalf("two views of %d tiles made %d requests", sp.count(), n) + } +} + +func TestTerrainConfigLog(t *testing.T) { + var buf bytes.Buffer + prev, flags := log.Writer(), log.Flags() + log.SetOutput(&buf) + t.Cleanup(func() { log.SetOutput(prev); log.SetFlags(flags) }) + logTerrainConfig(&TerrainConfig{TileURL: "https://user:s3cret@tiles.example.com/tok-123/skadi", TileCacheTiles: 3}, + &LOSConfig{Enabled: true}, &PlannerConfig{Enabled: true}) + out := buf.String() + for _, want := range []string{ + "terrain.tileCacheTiles must be within 4-200; using the default", + "[terrain] SRTM tiles from https://tiles.example.com for route LOS and the planner: up to 16 tiles per view, cache 24 tiles (69 MB, 2.9 MB a tile); " + + "views in use can briefly keep about 20 evicted tiles more (58 MB, a minute of downloads)", + "[terrain] tile downloads: 20/min and 200/hour for everyone; per client, 16 at once, then 10/min, at most 40/hour", + } { + if !strings.Contains(out, want) { + t.Errorf("log lacks %q:\n%s", want, out) + } + } + // The path or userinfo of a self-hosted tile server may carry a token. + for _, leak := range []string{"user", "s3cret", "tok-123", "skadi"} { + if strings.Contains(out, leak) { + t.Fatalf("log leaks %q: %q", leak, out) + } + } + if got := terrainTileHost("not a url"); got != "(invalid)" { + t.Fatalf("terrainTileHost = %q", got) + } + buf.Reset() + logTerrainConfig(nil, &LOSConfig{Enabled: true}, nil) + if out := buf.String(); !strings.Contains(out, "for route LOS: up to 16 tiles per view") { + t.Fatalf("los-only log %q", out) + } +} + +// Security review (#2391): the per-client budget is one full view of the +// shared source, so any single request can load at once, refills at half the +// global rate, and is capped per hour well below the global hourly budget. +func TestTerrainClientBudget(t *testing.T) { + terrainQuietLog(t) + for _, los := range []*LOSConfig{nil, {Enabled: true}} { + for _, sz := range plannerTestSizes { + planner := &PlannerConfig{Enabled: true, MaxAreaKm: sz.area, NodeMarginKm: sz.margin, MaxLegKm: sz.leg} + view := planner.tileLimits().max() + if los.enabled() { + view = max(view, losMaxTiles) + } + burst, hourly := terrainClientBudget(terrainViewTiles(los, planner)) + if burst != view || hourly != max(terrainClientHourFloor, 2*view) { + t.Fatalf("los %v, %+v: burst %d, hourly %d; largest view %d", los.enabled(), sz, burst, hourly, view) + } + // A token bucket lets a client take its cap and one refill in any + // hour: that still leaves part of the global hour to others. + if global := srtmBudgetFor(view).perHour; 2*hourly >= global { + t.Fatalf("%+v: a client may take %d of the %d downloads an hour", sz, 2*hourly, global) + } + cfg := &Config{LOS: los, Planner: planner} + e, p := newTerrainServices(cfg, &Server{cfg: cfg}) + t.Cleanup(p.Close) + rl := p.downloads.rl + if (e != nil && e.downloads != p.downloads) || rl.burst != float64(view) || rl.capBurst != float64(hourly) || + math.Abs(rl.rate*60-terrainClientTilesPerMin) > 1e-9 || math.Abs(rl.capRate*3600-float64(hourly)) > 1e-9 { + t.Fatalf("los %v, %+v: limiter %+v", los.enabled(), sz, rl) + } + if ok, _ := p.downloads.rl.takeN("198.51.100.1", view); !ok { + t.Fatalf("%+v: the largest view does not fit a fresh client's budget", sz) + } + } + } +} + +// Security review (#2391): route LOS and the planner draw on one budget per +// client, so using both buys no more downloads, and the hourly cap holds +// while the per-minute bucket refills. +func TestTerrainClientHourlyCapAcrossFeatures(t *testing.T) { + terrainQuietLog(t) + tb := newTerrainBoth(t, srtmServe(nil)) // every tile 404s: cheap, one request each + _, hourly := terrainClientBudget(losMaxTiles) + if hourly != 40 || tb.p.downloads.rl.burst != losMaxTiles { + t.Fatalf("budget: hourly %d, burst %v", hourly, tb.p.downloads.rl.burst) + } + // route is one leg per tile along latitude lat+0.5: n+1 tiles. + route := func(lat, n int) string { + parts := make([]string, n+1) + for i := range parts { + parts[i] = fmt.Sprintf("%d.5,%d.5", lat, i) + } + return strings.Join(parts, ",") + } + // area is a 2×2-tile planner profile view at lat, lat+1 × 5, 6. + area := func(lat int) string { return fmt.Sprintf("%d.8,5.8,%d.2,6.2", lat, lat+1) } + tb.known(area(50), area(52), area(54), area(56)) + const ip, other = "198.51.100.160", "198.51.100.161" + los := func(pts, from string, want int) { + t.Helper() + if w := tb.getFrom(pts, from+":5000", nil); w.Code != want { + t.Fatalf("route LOS %s: %d, want %d: %s", pts, w.Code, want, w.Body.String()) + } + } + minute := func() { // refills 10 per-minute tokens, 0.67 hourly ones + tb.clk.add(time.Minute) + tb.p.downloads.rl.takeN(ip, 0) + } + + los(route(40, 15), ip, http.StatusOK) // 16: the burst + for i, lat := range []int{50, 52} { + minute() + tb.profileDone(t, area(lat), ip) // 4 + los(route(45+i, 5), ip, http.StatusOK) // 6 + } + minute() + tb.profileDone(t, area(54), ip) // 4: 40 in all, the hourly cap + if got := tb.up.total(); got != hourly { + t.Fatalf("%d downloads, want %d", got, hourly) + } + // The minute bucket has room for 6 more; the hourly cap has 2. + if got := tb.tokens(ip); got < 6 { + t.Fatalf("per-minute tokens %v: the test needs room in them", got) + } + los(route(47, 5), ip, http.StatusTooManyRequests) + minute() + if w := tb.profile(area(56), ip); w.Code != http.StatusTooManyRequests { + t.Fatalf("planner past the hourly cap: %d %s", w.Code, w.Body.String()) + } + // Downloads are capped per client, not for everyone. + los(route(47, 5), other, http.StatusOK) + if got := tb.up.total(); got != hourly+6 { + t.Fatalf("%d downloads, want %d", got, hourly+6) + } +} + +// terrainQuietLog discards the log for the rest of t. +func terrainQuietLog(t *testing.T) { + prev := log.Writer() + log.SetOutput(&bytes.Buffer{}) + t.Cleanup(func() { log.SetOutput(prev) }) +} diff --git a/cmd/server/terrain_srtm.go b/cmd/server/terrain_srtm.go new file mode 100644 index 000000000..aaaf3b782 --- /dev/null +++ b/cmd/server/terrain_srtm.go @@ -0,0 +1,1049 @@ +package main + +// SRTM terrain for route line-of-sight and the repeater planner: ONE source +// serves both (terrain_config.go), so they read the same tiles. +// +// CONTRACT (planner_search.go / planner_api.go / elevation.go depend on it; +// keep signatures): +// - Tiles: //.hgt.gz, gzipped raw big-endian int16, +// 3601×3601, row 0 = north edge, 1 arc-second. Downsampled in memory to +// 3 arc-seconds (1201×1201) by keeping every third sample, not each +// cell's highest: a ridge under ~90 m wide can be missed (documented in +// the UI footers and docs/api-spec.md). Missing (404/ocean) tiles have no elevation: +// never 0 m, which would read as sea level. +// - terrainView is immutable and safe for concurrent use without locks. +// - The planner loads a rectangle of tiles (View); route LOS loads only the +// tiles its legs' samples fall in (tiles + await, read through an +// srtmTileView). Both share the cache, the downloads and the budget, and +// both charge their client for the downloads they start (Begin, tiles) +// in the same step that starts them, so one download is charged once. +// +// Safety model (this runs inside a public web server; nothing touches disk): +// - Tile names and URLs are built only from clamped integer indices. +// - A fetch reads at most srtmMaxGzipBytes of compressed body and exactly +// srtmRawBytes of tile data: one byte more, one byte less or a bad gzip +// CRC fails the tile. Decoding streams row by row, so no 26 MB raw buffer +// is ever held; a decompression bomb costs one 2.9 MB grid and stops. +// - At most srtmMaxConcurrent fetches run process-wide; at most +// srtmPerMinute / srtmPerHour start per rolling window, raised to fit the +// largest view (srtmBudgetFor). An upstream failure (429, 5xx, transport +// error) opens the srtmBackoff cooldown ladder, which pauses every +// download. +// - Failed or partial tiles are never cached as data. A tile the server +// does not have (404 for srtmNegTTL, 403 for srtmForbiddenTTL), a tile +// whose body is unusable (corrupt, oversized, truncated, wrong length, +// unexpected status; srtmBadTTL, and no cooldown: one bad tile must not +// stop the others) and a tile that is all void are negative-cached and +// have no elevation, so callers skip what touches them. Views count them +// through terrainCoverage, so callers can warn that terrain is missing. + +import ( + "compress/gzip" + "context" + "encoding/binary" + "errors" + "fmt" + "io" + "log" + "math" + "net" + "net/http" + "net/url" + "strings" + "sync" + "time" +) + +// terrainView answers elevation queries over the tiles it was built for. +type terrainView interface { + // ElevationAt returns bilinear-interpolated metres above sea level. + // ok=false when (lat, lon) has no terrain: it is outside the view's + // tiles or in a tile without data (terrainCoverage). Callers skip such + // a point, and anything that samples it; they never read it as 0 m. + ElevationAt(lat, lon float64) (float64, bool) +} + +// terrainSource loads the tiles that cover a bbox. +type terrainSource interface { + // View returns a view covering bb, fetching missing tiles within the + // fetch budget. Errors: errTerrainTooManyTiles, errTerrainBusy, + // errTerrainUnavailable, or ctx.Err(). + View(ctx context.Context, bb geoBBox) (terrainView, error) + // Resident reports whether every tile covering bb is already loaded + // (or known missing), i.e. View would not download anything. + Resident(bb geoBBox) bool + // TileCount is the number of 1° tiles covering bb. + TileCount(bb geoBBox) int + // Begin charges for, then starts, the downloads View(bb) would start + // now: tiles neither loaded, known missing nor already downloading, as + // many as the download budget admits (none while downloads are paused). + // With at least one, charge is called once with their number while the + // source's lock is held, so no other caller is charged for the same + // download; it must not block or call back into the source. When it + // refuses, nothing starts and Begin reports false. A box View refuses + // starts nothing and is not charged. + Begin(bb geoBBox, charge func(starts int) bool) bool +} + +// terrainCoverage is implemented by views that know which of their tiles +// have no data: known missing, unusable, or all void, and so without +// elevation. Optional; callers type-assert. +type terrainCoverage interface { + // MissingTiles counts the view's tiles without data, of total. + MissingTiles() (missing, total int) + // MissingAt reports whether (lat, lon) has no data: it lies in such a + // tile, or outside the view. Exactly where ElevationAt says ok=false. + MissingAt(lat, lon float64) bool +} + +var ( + errTerrainTooManyTiles = errors.New("terrain: area spans too many tiles") + errTerrainBusy = errors.New("terrain: fetch budget exhausted") + errTerrainUnavailable = errors.New("terrain: tiles unavailable") +) + +var ( + _ terrainSource = (*srtmSource)(nil) + _ terrainView = (*srtmView)(nil) + _ terrainCoverage = (*srtmView)(nil) + _ terrainView = srtmTileView(nil) +) + +const ( + srtmRawSide = 3601 // samples per tile side at 1 arc-second + srtmRawRowBytes = srtmRawSide * 2 // one big-endian int16 row + srtmRawBytes = srtmRawSide * srtmRawRowBytes // 25,934,402: the whole decompressed tile + srtmStep = 3 // keep every 3rd row and column + srtmSide = (srtmRawSide-1)/srtmStep + 1 // 1201 samples per side at 3 arc-seconds + srtmCells = srtmSide - 1 // 1200 grid intervals per degree + srtmTileBytes = srtmSide * srtmSide * 2 // one resident tile: ~2.9 MB + srtmVoid = -32768 // SRTM no-data value + + srtmMaxGzipBytes = 24 << 20 // real tiles reach ~17 MB (Sierra, Alps); raw is 25.9 MB + srtmFetchTimeout = 30 * time.Second + srtmDialTimeout = 5 * time.Second + srtmSlotWait = 2 * time.Minute // longest wait for a fetch slot once admitted + srtmMaxConcurrent = 2 + srtmPerMinute = 20 // the download budget's floors (srtmBudgetFor) + srtmPerHour = 200 // the download budget's floors (srtmBudgetFor) + srtmNegTTL = 24 * time.Hour // 404: the tile does not exist (ocean) + srtmForbiddenTTL = time.Hour // 403: S3's answer for absent keys, but also for a misconfigured bucket + srtmBadTTL = 10 * time.Minute // unusable body: retry this tile soon, the others at once + srtmNegMax = 1024 + srtmVoidWarnFrac = 0.20 + srtmErrBodyDrain = 4096 +) + +// srtmFetchSlots bounds concurrent tile fetches (and so decode memory) for +// the whole process, however many sources exist. +var srtmFetchSlots = make(chan struct{}, srtmMaxConcurrent) + +// srtmBackoff is the download pause after the 1st, 2nd, 3rd... consecutive +// upstream failure; the last step repeats. +var srtmBackoff = []time.Duration{60 * time.Second, 5 * time.Minute, 30 * time.Minute, time.Hour} + +// srtmHTTPDoer is the slice of *http.Client the source needs (test seam). +type srtmHTTPDoer interface { + Do(*http.Request) (*http.Response, error) +} + +// srtmKey is a 1° tile by its south-west corner: lat -90..89, lon -180..179. +type srtmKey struct{ lat, lon int } + +// name is the skadi tile name, e.g. N30W098 or S01E000. +func (k srtmKey) name() string { + ns, la := 'N', k.lat + if la < 0 { + ns, la = 'S', -la + } + ew, lo := 'E', k.lon + if lo < 0 { + ew, lo = 'W', -lo + } + return fmt.Sprintf("%c%02d%c%03d", ns, la, ew, lo) +} + +// srtmIndex turns an already floored degree value into a tile index clamped +// to [lo, hi]. Comparing as floats first keeps huge values from overflowing +// the int conversion; NaN maps to lo. +func srtmIndex(f float64, lo, hi int) int { + switch { + case !(f > float64(lo)): + return lo + case f >= float64(hi): + return hi + } + return int(f) +} + +// srtmKeyOf is the tile holding (lat, lon); a point on a degree line belongs +// to the tile north/east of it, as math.Floor says. +func srtmKeyOf(lat, lon float64) srtmKey { + return srtmKey{srtmIndex(math.Floor(lat), -90, 89), srtmIndex(math.Floor(lon), -180, 179)} +} + +// srtmSpan is the rectangle of tiles covering a bbox. +type srtmSpan struct{ lat0, lon0, nLat, nLon int } + +func (sp srtmSpan) count() int { return sp.nLat * sp.nLon } + +// key is the i-th tile, row-major from the south-west corner. +func (sp srtmSpan) key(i int) srtmKey { + return srtmKey{sp.lat0 + i/sp.nLon, sp.lon0 + i%sp.nLon} +} + +// srtmSpanOf returns the tiles covering bb; ok=false for a NaN/Inf or +// inverted box (S>N, or W>E as an antimeridian box would be). A north or east +// edge lying exactly on a degree line does not pull in the next tile: N=31.0 +// ends in tile N30. +func srtmSpanOf(bb geoBBox) (srtmSpan, bool) { + for _, v := range [...]float64{bb.S, bb.W, bb.N, bb.E} { + if math.IsNaN(v) || math.IsInf(v, 0) { + return srtmSpan{}, false + } + } + if bb.S > bb.N || bb.W > bb.E { + return srtmSpan{}, false + } + lat0 := srtmIndex(math.Floor(bb.S), -90, 89) + lat1 := srtmIndex(math.Ceil(bb.N)-1, -90, 89) + lon0 := srtmIndex(math.Floor(bb.W), -180, 179) + lon1 := srtmIndex(math.Ceil(bb.E)-1, -180, 179) + // max: a box that is a single point on a degree line still needs a tile. + return srtmSpan{lat0, lon0, max(lat1-lat0, 0) + 1, max(lon1-lon0, 0) + 1}, true +} + +// srtmCell splits a grid coordinate into the cell's first index, in +// [0, srtmCells-1], and the fraction, in [0, 1]. Out-of-range values (and +// NaN) clamp to the edge. +func srtmCell(v float64) (int, float64) { + switch { + case !(v > 0): + return 0, 0 + case v >= srtmCells: + return srtmCells - 1, 1 + } + i := int(v) + return i, v - float64(i) +} + +// srtmPixel locates (lat, lon) on tile k's 1201² grid (row 0 = north edge): +// the north-west corner of its interpolation cell and the offsets into it. +// Positions outside the tile clamp to its edge. +func srtmPixel(lat, lon float64, k srtmKey) (row, col int, fy, fx float64) { + // The explicit float64() rounds the product. Without it the compiler may + // fuse it with srtmCell's subtraction into an FMA (arm64 does), and a + // product that rounds up to an integer then yields a fraction just below 0. + row, fy = srtmCell(float64((float64(k.lat+1) - lat) * srtmCells)) + col, fx = srtmCell(float64((lon - float64(k.lon)) * srtmCells)) + return row, col, fy, fx +} + +// srtmBilinear interpolates grid g inside the cell at (row, col). +func srtmBilinear(g []int16, row, col int, fy, fx float64) float64 { + c := g[row*srtmSide+col:] + c = c[:srtmSide+2] // the cell's four corners: [0], [1], [srtmSide], [srtmSide+1] + n := float64(c[0])*(1-fx) + float64(c[1])*fx + s := float64(c[srtmSide])*(1-fx) + float64(c[srtmSide+1])*fx + return n*(1-fy) + s*fy +} + +// srtmView is an immutable set of tiles. The grids are never written after +// decode, and the view holds its own references, so reads take no lock and a +// cache eviction never invalidates a view. +type srtmView struct { + span srtmSpan + grids [][]int16 // span.key(i) order; nil = tile without data (no elevation) +} + +// tile is the grid holding (lat, lon) (nil: no data) and its key; +// ok=false outside the view. NaN fails too. +func (v *srtmView) tile(lat, lon float64) (g []int16, k srtmKey, ok bool) { + sp := v.span + if !(lat >= float64(sp.lat0) && lat <= float64(sp.lat0+sp.nLat) && + lon >= float64(sp.lon0) && lon <= float64(sp.lon0+sp.nLon)) { + return nil, srtmKey{}, false + } + // SRTM tiles share their edge rows and columns, so every point's four + // interpolation corners lie in the tile floor() picks. Only a point on + // the view's own north/east edge needs clamping back onto the last tile. + ti := min(int(math.Floor(lat))-sp.lat0, sp.nLat-1) + tj := min(int(math.Floor(lon))-sp.lon0, sp.nLon-1) + return v.grids[ti*sp.nLon+tj], srtmKey{sp.lat0 + ti, sp.lon0 + tj}, true +} + +func (v *srtmView) MissingTiles() (missing, total int) { + for _, g := range v.grids { + if g == nil { + missing++ + } + } + return missing, len(v.grids) +} + +func (v *srtmView) MissingAt(lat, lon float64) bool { + g, _, ok := v.tile(lat, lon) + return !ok || g == nil +} + +// ElevationAt repeats tile's lookup inline: tile is over the inlining +// budget, and this is the planner's innermost loop. +func (v *srtmView) ElevationAt(lat, lon float64) (float64, bool) { + sp := v.span + // Written so that NaN fails too. + if !(lat >= float64(sp.lat0) && lat <= float64(sp.lat0+sp.nLat) && + lon >= float64(sp.lon0) && lon <= float64(sp.lon0+sp.nLon)) { + return 0, false + } + ti := min(int(math.Floor(lat))-sp.lat0, sp.nLat-1) + tj := min(int(math.Floor(lon))-sp.lon0, sp.nLon-1) + g := v.grids[ti*sp.nLon+tj] + if g == nil { + return 0, false + } + row, col, fy, fx := srtmPixel(lat, lon, srtmKey{sp.lat0 + ti, sp.lon0 + tj}) + return srtmBilinear(g, row, col, fy, fx), true +} + +// srtmTileView is an immutable set of tiles that need not form a rectangle: +// the tiles a route's leg samples fall in (elevation.go). A point is looked +// up in the tile srtmKeyOf names, the one legTiles loads for it, so a point +// on a degree line reads the edge row or column of the tile north or east of +// it, which SRTM tiles share with their neighbour. Like srtmView it takes no +// lock and holds its own grid references. +type srtmTileView map[srtmKey][]int16 // nil grid: tile without data + +func (v srtmTileView) ElevationAt(lat, lon float64) (float64, bool) { + // Written so that NaN fails too. + if !(lat >= -90 && lat <= 90 && lon >= -180 && lon <= 180) { + return 0, false + } + k := srtmKeyOf(lat, lon) + g := v[k] + if g == nil { + return 0, false + } + row, col, fy, fx := srtmPixel(lat, lon, k) + return srtmBilinear(g, row, col, fy, fx), true +} + +// srtmBudget is a sliding log of download starts: at most perMinute in any +// rolling minute and perHour in any rolling hour. +type srtmBudget struct { + perMinute, perHour int + starts []time.Time // oldest first, all within the last hour +} + +// srtmBudgetFor is the budget of a source whose largest view is viewTiles: +// srtmPerMinute, or one full view when that is more, so a cold request at +// the largest size the limits allow loads in one go; and srtmPerHour, or +// five minutes of that when more. +func srtmBudgetFor(viewTiles int) srtmBudget { + m := max(srtmPerMinute, viewTiles) + return srtmBudget{perMinute: m, perHour: max(srtmPerHour, 5*m)} +} + +// take records a start at now when both windows allow it. +func (b *srtmBudget) take(now time.Time) bool { + drop := 0 + for drop < len(b.starts) && now.Sub(b.starts[drop]) >= time.Hour { + drop++ + } + b.starts = b.starts[:copy(b.starts, b.starts[drop:])] + if b.room(now) == 0 { + return false + } + b.starts = append(b.starts, now) + return true +} + +// room is how many starts take would accept at now, recording none. +func (b *srtmBudget) room(now time.Time) int { + inHour, inMinute := 0, 0 + for i := len(b.starts) - 1; i >= 0; i-- { + d := now.Sub(b.starts[i]) + if d >= time.Hour { + break // oldest first: the rest are older still + } + inHour++ + if d < time.Minute { + inMinute++ + } + } + return max(0, min(b.perHour-inHour, b.perMinute-inMinute)) +} + +// srtmSource is the production terrainSource: an LRU of downsampled tiles in +// memory, filled from the tile server on demand. +type srtmSource struct { + baseURL string + source string // attribution for responses (terrainSourceName) + userAgent string + client srtmHTTPDoer + now func() time.Time + maxTiles int // max tiles in one load (terrainViewTiles) + sem chan struct{} // fetch slots; srtmFetchSlots outside tests + + mu sync.Mutex + cache *lru[srtmKey, []int16] // decoded tiles; its cap is never below maxTiles + neg map[srtmKey]time.Time // known-missing tile → expiry + loading map[srtmKey]*srtmLoad // the one running load of each tile (startLocked) + fails int // consecutive upstream failures + coolTo time.Time // no downloads before then + budget srtmBudget +} + +// newSRTMSource builds the source from the resolved terrain config. +// viewTiles is the most tiles one load may span (terrainViewTiles): the +// per-view cap, the floor of the cache and of the per-minute download +// budget. +func newSRTMSource(cfg TerrainConfig, viewTiles int) *srtmSource { + base := strings.TrimRight(cfg.TileURL, "/") + if base == "" { + base = defaultTerrainTileURL + } + ua := "CoreScope" + if Version != "" { + ua += "/" + Version + } + return &srtmSource{ + baseURL: base, + source: terrainSourceName(base), + userAgent: ua, + client: newSRTMHTTPClient(), + now: time.Now, + maxTiles: viewTiles, + sem: srtmFetchSlots, + cache: newLRU[srtmKey, []int16](cfg.cacheTiles(viewTiles), 0, nil), + neg: make(map[srtmKey]time.Time), + loading: make(map[srtmKey]*srtmLoad), + budget: srtmBudgetFor(viewTiles), + } +} + +// newSRTMHTTPClient is the dedicated tile client: no proxy, no redirects, +// bounded dial/handshake/total time, and the body exactly as sent. +func newSRTMHTTPClient() *http.Client { + d := &net.Dialer{Timeout: srtmDialTimeout, KeepAlive: 30 * time.Second} + return &http.Client{ + Timeout: srtmFetchTimeout, + Transport: &http.Transport{ + Proxy: nil, + DialContext: d.DialContext, + TLSHandshakeTimeout: srtmDialTimeout, + ResponseHeaderTimeout: srtmFetchTimeout, + MaxIdleConnsPerHost: srtmMaxConcurrent, + IdleConnTimeout: 90 * time.Second, + ForceAttemptHTTP2: true, + // Tiles are .gz files: never gunzip behind our back, so the size + // cap applies to the compressed bytes and srtmDecode sees them. + DisableCompression: true, + }, + // A tile host has no business redirecting us elsewhere. + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + } +} + +// tileURL is built from the configured base and integer indices only. +func (s *srtmSource) tileURL(k srtmKey) string { + n := k.name() + return fmt.Sprintf("%s/%s/%s.hgt.gz", s.baseURL, n[:3], n) +} + +func (s *srtmSource) TileCount(bb geoBBox) int { + sp, ok := srtmSpanOf(bb) + if !ok { + return 0 + } + return sp.count() +} + +// Resident is false for boxes View would refuse (invalid or too many tiles). +// It does not touch LRU order. +func (s *srtmSource) Resident(bb geoBBox) bool { + sp, ok := srtmSpanOf(bb) + if !ok || sp.count() > s.maxTiles { + return false + } + s.mu.Lock() + defer s.mu.Unlock() + now := s.now() + for i := 0; i < sp.count(); i++ { + if _, ok := s.lookupLocked(sp.key(i), now, false); !ok { + return false + } + } + return true +} + +func (s *srtmSource) View(ctx context.Context, bb geoBBox) (terrainView, error) { + sp, ok := srtmSpanOf(bb) + if !ok { + return nil, errTerrainUnavailable + } + if sp.count() > s.maxTiles { + return nil, errTerrainTooManyTiles + } + v := &srtmView{span: sp, grids: make([][]int16, sp.count())} + var missing []int + var loads []*srtmLoad + s.mu.Lock() + now := s.now() + for i := range v.grids { + g, ok := s.lookupLocked(sp.key(i), now, true) + if !ok { + missing = append(missing, i) + continue + } + v.grids[i] = g + } + cooling := now.Before(s.coolTo) + if len(missing) > 0 && !cooling { + // Start every load before waiting on any. + loads = make([]*srtmLoad, len(missing)) + for j, i := range missing { + loads[j] = s.startLocked(sp.key(i)) + } + } + s.mu.Unlock() + if len(missing) == 0 { + return v, nil + } + if cooling { + return nil, errTerrainBusy + } + for j, i := range missing { + ld := loads[j] + select { + case <-ld.done: + if ld.err != nil { + return nil, ld.err + } + v.grids[i] = ld.grid + case <-ctx.Done(): + return nil, ctx.Err() + } + } + return v, nil +} + +// Begin is tiles for View's rectangle, without touching LRU order. +func (s *srtmSource) Begin(bb geoBBox, charge func(starts int) bool) bool { + sp, ok := srtmSpanOf(bb) + if !ok || sp.count() > s.maxTiles { + return true + } + keys := make([]srtmKey, sp.count()) + for i := range keys { + keys[i] = sp.key(i) + } + s.mu.Lock() + defer s.mu.Unlock() + ts := s.tilesLocked(keys, false) + return s.beginLocked(&ts, charge) +} + +// roomLocked is how many downloads admit would accept now: none while they +// are paused. Caller holds s.mu. +func (s *srtmSource) roomLocked(now time.Time) int { + if now.Before(s.coolTo) { + return 0 + } + return s.budget.room(now) +} + +// srtmTileSet is a set of tiles as tiles found them. +type srtmTileSet struct { + grids map[srtmKey][]int16 // resident: the grid, or nil for a tile without data + need []srtmKey // to load: already downloading, or a download the budget admits; keys order + starts int // of need, those no load is running for: the downloads loading need would start + refused []srtmKey // not downloading, and over what the budget admits now (all of them while downloads are paused) +} + +// tiles looks keys up in one pass, marking the cached ones used, then +// charges for and starts the downloads the keys need. It counts as starts +// only the downloads the budget would admit now: the rest are refused, so no +// caller is charged for a download that would fail at once, and tiles already +// downloading cost no start. charge is called as Begin calls it; a nil +// charge is free. When charge refuses, nothing starts and tiles reports +// false. +func (s *srtmSource) tiles(keys []srtmKey, charge func(starts int) bool) (srtmTileSet, bool) { + s.mu.Lock() + defer s.mu.Unlock() + ts := s.tilesLocked(keys, true) + return ts, s.beginLocked(&ts, charge) +} + +// tilesLocked sorts keys into resident, to load and refused, starting +// nothing. touch marks the cached ones used. Caller holds s.mu. +func (s *srtmSource) tilesLocked(keys []srtmKey, touch bool) srtmTileSet { + ts := srtmTileSet{grids: make(map[srtmKey][]int16, len(keys))} + now := s.now() + room := -1 // looked up at the first tile that needs a download + for _, k := range keys { + if g, ok := s.lookupLocked(k, now, touch); ok { + ts.grids[k] = g + continue + } + if _, running := s.loading[k]; !running { + if room < 0 { + room = s.roomLocked(now) + } + if ts.starts == room { + ts.refused = append(ts.refused, k) + continue + } + ts.starts++ + } + ts.need = append(ts.need, k) + } + return ts +} + +// beginLocked charges for ts.starts, then starts every load ts.need lacks. +// Charging and starting under one hold of s.mu is what makes a download +// cost one caller: the next one finds it in s.loading. Caller holds s.mu. +func (s *srtmSource) beginLocked(ts *srtmTileSet, charge func(starts int) bool) bool { + if ts.starts > 0 && charge != nil && !charge(ts.starts) { + return false + } + for _, k := range ts.need { + s.startLocked(k) + } + return true +} + +// await starts (or joins) the load of each key and waits until all are done, +// ctx ends or wait passes. A finished key lands in got (its grid, or nil for +// a tile without data) or, when its load failed (busy, unavailable), in +// failed; a key in neither is still loading, and goes on loading. Waiting +// registers nothing with the load: a caller that leaves, by ctx or by wait, +// leaves nothing behind, so free polls hold no memory. +func (s *srtmSource) await(ctx context.Context, keys []srtmKey, wait time.Duration) (got map[srtmKey][]int16, failed map[srtmKey]bool) { + got, failed = make(map[srtmKey][]int16, len(keys)), make(map[srtmKey]bool) + loads := make([]*srtmLoad, len(keys)) + s.mu.Lock() + now := s.now() + for i, k := range keys { + if g, ok := s.lookupLocked(k, now, true); ok { + got[k] = g // landed since the caller looked + continue + } + loads[i] = s.startLocked(k) + } + s.mu.Unlock() + timer := time.NewTimer(wait) + defer timer.Stop() + waiting := true + for i, k := range keys { + ld := loads[i] + if ld == nil { + continue + } + select { + case <-ld.done: + default: + if !waiting { + continue // collect only what has already finished + } + select { + case <-ld.done: + case <-timer.C: + waiting = false + continue + case <-ctx.Done(): + waiting = false + continue + } + } + if ld.err != nil { + failed[k] = true + continue + } + got[k] = ld.grid + } + return got, failed +} + +// srtmLoad is one tile's running load. done is closed once, when the load +// ends; grid and err are set before that and read only after. Waiters +// select on done and register nothing, so a record's size is fixed however +// many requests wait on it. +type srtmLoad struct { + done chan struct{} + grid []int16 // nil with a nil err: a tile without data + err error +} + +// startLocked returns tile k's running load, starting one when none runs: +// one load per tile, however many callers ask. Callers start one only after +// lookupLocked missed under the same hold of s.mu, so no tile already cached +// or known missing is loaded again. The load runs detached from every +// caller, so one that gives up still leaves the tile cached for its retry. +// While it runs, k is in s.loading (tiles counts no start for it). Caller +// holds s.mu. +func (s *srtmSource) startLocked(k srtmKey) *srtmLoad { + if ld := s.loading[k]; ld != nil { + return ld + } + ld := &srtmLoad{done: make(chan struct{})} + s.loading[k] = ld + go s.run(k, ld) + return ld +} + +// run performs ld, then retires it. A tile it loaded is cached before k +// leaves s.loading, so no caller in between starts it again. +func (s *srtmSource) run(k srtmKey, ld *srtmLoad) { + ld.grid, ld.err = s.load(k) + s.mu.Lock() + delete(s.loading, k) + s.mu.Unlock() + close(ld.done) +} + +// lookupLocked finds k in the cache (grid) or the negative cache (nil grid). +// touch marks a cached tile most recently used. Caller holds s.mu. +func (s *srtmSource) lookupLocked(k srtmKey, now time.Time, touch bool) ([]int16, bool) { + var g []int16 + var ok bool + if touch { + g, ok = s.cache.Get(k) + } else { + g, ok = s.cache.Peek(k) + } + if ok { + return g, true + } + if exp, ok := s.neg[k]; ok { + if now.Before(exp) { + return nil, true + } + delete(s.neg, k) + } + return nil, false +} + +// load fetches one tile. It runs on the goroutine startLocked starts, so it +// must never panic out. A nil grid with a nil error is a known-missing tile. +func (s *srtmSource) load(k srtmKey) (grid []int16, err error) { + defer func() { + if r := recover(); r != nil { + log.Printf("[terrain] tile %s: panic: %v", k.name(), r) + grid, err = nil, errTerrainUnavailable + } + }() + // Admission comes before the slot wait, so the number of queued + // fetches is bounded by the budget. + if !s.admit() { + return nil, errTerrainBusy + } + wait := time.NewTimer(srtmSlotWait) + defer wait.Stop() + select { + case s.sem <- struct{}{}: + case <-wait.C: + return nil, errTerrainBusy + } + defer func() { <-s.sem }() + // A fetch that failed while this one queued has opened a cooldown. + if s.cooling() { + return nil, errTerrainBusy + } + return s.fetchAndStore(k) +} + +// admit applies the cooldown and the rolling budgets, recording one start. +func (s *srtmSource) admit() bool { + s.mu.Lock() + defer s.mu.Unlock() + now := s.now() + if now.Before(s.coolTo) { + return false + } + return s.budget.take(now) +} + +func (s *srtmSource) cooling() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.now().Before(s.coolTo) +} + +// openCooldown records an upstream failure and blocks downloads for the next +// step of the srtmBackoff ladder, returning how long they stay blocked. +// Failures landing inside a running cooldown do not escalate it. +func (s *srtmSource) openCooldown() time.Duration { + s.mu.Lock() + defer s.mu.Unlock() + now := s.now() + if now.Before(s.coolTo) { + return s.coolTo.Sub(now) + } + d := srtmBackoff[min(s.fails, len(srtmBackoff)-1)] + s.fails++ + s.coolTo = now.Add(d) + return d +} + +// put caches a decoded tile and resets the failure ladder. +func (s *srtmSource) put(k srtmKey, grid []int16) { + s.mu.Lock() + defer s.mu.Unlock() + s.fails = 0 + delete(s.neg, k) + s.cache.Put(k, grid) +} + +// putMissing remembers for ttl a tile without data. When the negative +// cache is full it drops expired entries, then the one closest to expiry. +func (s *srtmSource) putMissing(k srtmKey, ttl time.Duration) { + s.mu.Lock() + defer s.mu.Unlock() + now := s.now() + if _, ok := s.neg[k]; !ok && len(s.neg) >= srtmNegMax { + var oldest srtmKey + var oldestAt time.Time + for nk, exp := range s.neg { + if !now.Before(exp) { + delete(s.neg, nk) + } else if oldestAt.IsZero() || exp.Before(oldestAt) { + oldest, oldestAt = nk, exp + } + } + if len(s.neg) >= srtmNegMax { + delete(s.neg, oldest) + } + } + s.neg[k] = now.Add(ttl) +} + +// fetchAndStore downloads one tile under a fetch slot and records the outcome. +func (s *srtmSource) fetchAndStore(k srtmKey) ([]int16, error) { + // Detached from every caller: the tile is worth having even if the + // request that asked for it has gone. + ctx, cancel := context.WithTimeout(context.Background(), srtmFetchTimeout) + defer cancel() + start := time.Now() + grid, voids, status, err := s.fetch(ctx, k) + switch { + case status == http.StatusNotFound: + return s.missing(k, srtmNegTTL, "HTTP 404") + case status == http.StatusForbidden: + return s.missing(k, srtmForbiddenTTL, "HTTP 403") + case err == nil && grid == nil: + return s.missing(k, srtmNegTTL, "all void") + case err == nil: + case srtmUpstreamFailed(status, err): + d := s.openCooldown() + log.Printf("[terrain] tile %s: %v; tile downloads paused for %s", k.name(), err, d) + return nil, errTerrainUnavailable + default: + // The server answered, but not with a usable tile. Only this tile + // is set aside; the others keep downloading. + return s.missing(k, srtmBadTTL, err.Error()) + } + if frac := float64(voids) / (srtmSide * srtmSide); frac > srtmVoidWarnFrac { + log.Printf("[terrain] tile %s is %.0f%% void (filled from the nearest valid samples)", k.name(), frac*100) + } + s.put(k, grid) + log.Printf("[terrain] tile %s loaded in %s", k.name(), time.Since(start).Round(time.Millisecond)) + return grid, nil +} + +// missing negative-caches k for ttl, so views report it missing and give no +// elevation there, and logs why. +func (s *srtmSource) missing(k srtmKey, ttl time.Duration, why string) ([]int16, error) { + s.putMissing(k, ttl) + log.Printf("[terrain] tile %s: %s; no terrain there for %s", k.name(), why, ttl) + return nil, nil +} + +// srtmUpstreamError is a fetch failure that is the network's fault, not the +// tile's: no response, or a body that stopped with a read error. +type srtmUpstreamError struct{ err error } + +func (e *srtmUpstreamError) Error() string { return e.err.Error() } +func (e *srtmUpstreamError) Unwrap() error { return e.err } + +// srtmUpstreamFailed reports whether a failed fetch says the tile server or +// the path to it is unwell (429, 5xx, transport): the cases that pause every +// download. Anything else is about this one tile. +func srtmUpstreamFailed(status int, err error) bool { + var ue *srtmUpstreamError + return errors.As(err, &ue) || status == http.StatusTooManyRequests || status >= 500 +} + +// srtmBody records the first read error that is not the body ending, early +// or not: a timeout or reset mid-download is the network's fault, while a +// short body is the tile's. +type srtmBody struct { + r io.Reader + err error +} + +func (b *srtmBody) Read(p []byte) (int, error) { + n, err := b.r.Read(p) + if err != nil && b.err == nil && err != io.EOF && !errors.Is(err, io.ErrUnexpectedEOF) { + b.err = err + } + return n, err +} + +// fetch downloads and decodes one tile. status is the HTTP status, 0 when no +// response arrived; err is nil only for a complete, valid tile, and is an +// *srtmUpstreamError when the network, not the tile, failed. +func (s *srtmSource) fetch(ctx context.Context, k srtmKey) (grid []int16, voids, status int, err error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.tileURL(k), nil) + if err != nil { + return nil, 0, 0, &srtmUpstreamError{errors.New("bad tile URL")} + } + req.Header.Set("User-Agent", s.userAgent) + resp, err := s.client.Do(req) + if err != nil { + // Unwrap: url.Error text embeds the URL, which may carry credentials. + var ue *url.Error + if errors.As(err, &ue) { + err = ue.Err + } + return nil, 0, 0, &srtmUpstreamError{fmt.Errorf("request failed: %w", err)} + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + io.Copy(io.Discard, io.LimitReader(resp.Body, srtmErrBodyDrain)) + return nil, 0, resp.StatusCode, fmt.Errorf("HTTP %d", resp.StatusCode) + } + if resp.ContentLength > srtmMaxGzipBytes { + return nil, 0, resp.StatusCode, fmt.Errorf("body of %d bytes is over the %d-byte cap", resp.ContentLength, srtmMaxGzipBytes) + } + body := &srtmBody{r: io.LimitReader(resp.Body, srtmMaxGzipBytes)} + grid, voids, err = srtmDecode(body) + if err != nil && body.err != nil { + err = &srtmUpstreamError{fmt.Errorf("reading the body: %w", body.err)} + } + return grid, voids, resp.StatusCode, err +} + +// srtmDecode gunzips one 1-arc-second tile and returns it downsampled to the +// 1201² grid, with voids filled, plus the number of void samples found. A +// void is filled from the nearest valid sample in its row, and a row without +// any from the nearest rows that have some, so no void ever reads as 0 m; a +// tile without one valid sample has no terrain and decodes to a nil grid. It +// reads the 3601 rows with io.ReadFull (exactly srtmRawBytes in all), keeping +// every srtmStep-th row and column, then requires EOF on one more read, which +// is also when gzip checks the CRC and length trailer. Anything short, long +// or corrupt is an error. +func srtmDecode(r io.Reader) (grid []int16, voids int, err error) { + zr, err := gzip.NewReader(r) + if err != nil { + return nil, 0, fmt.Errorf("not a gzip tile: %w", err) + } + defer zr.Close() + grid = make([]int16, srtmSide*srtmSide) + buf := make([]byte, srtmRawRowBytes) + var raw []int16 // full-resolution row, only for rows with voids + var voidRows []int // kept rows without one valid sample, ascending + for y := 0; y < srtmRawSide; y++ { + if _, err := io.ReadFull(zr, buf); err != nil { + return nil, 0, fmt.Errorf("tile shorter than %d bytes: %w", srtmRawBytes, err) + } + if y%srtmStep != 0 { + continue + } + out := grid[(y/srtmStep)*srtmSide:][:srtmSide] + rowVoids := 0 + for c := range out { + v := int16(binary.BigEndian.Uint16(buf[2*srtmStep*c:])) + if v == srtmVoid { + rowVoids++ + } + out[c] = v + } + if rowVoids == 0 { + continue + } + // Fill from the nearest valid sample at full resolution. + voids += rowVoids + if raw == nil { + raw = make([]int16, srtmRawSide) + } + for c := range raw { + raw[c] = int16(binary.BigEndian.Uint16(buf[2*c:])) + } + if !srtmFillVoids(raw) { + voidRows = append(voidRows, y/srtmStep) // out is all void: filled below + continue + } + for c := range out { + out[c] = raw[c*srtmStep] + } + } + var extra [1]byte + switch _, err := io.ReadFull(zr, extra[:]); { + case err == nil: + return nil, 0, fmt.Errorf("tile longer than %d bytes", srtmRawBytes) + case err != io.EOF: + return nil, 0, fmt.Errorf("tile trailer: %w", err) + } + if len(voidRows) == srtmSide { + return nil, voids, nil + } + srtmFillVoidRows(grid, srtmSide, voidRows) + return grid, voids, nil +} + +// srtmFillVoids replaces each void in row with the nearest valid sample in +// the same row (ties go west). A row without a valid sample is left as it is +// and reported false: it has nothing to fill from, and 0 would read as sea +// level. +func srtmFillVoids(row []int16) bool { + for i := 0; i < len(row); { + if row[i] != srtmVoid { + i++ + continue + } + j := i + for j < len(row) && row[j] == srtmVoid { + j++ + } + if i == 0 && j == len(row) { + return false + } + // row[i:j] is a run of voids; row[i-1] and row[j] are valid if present. + for p := i; p < j; p++ { + row[p] = row[srtmNearest(p, i, j, len(row))] + } + i = j + } + return true +} + +// srtmNearest is the index nearest to p just outside the run [i, j) of an +// n-long line: i-1 or j, whichever exists and is closer (ties go to i-1). +// One of them must exist. +func srtmNearest(p, i, j, n int) int { + if i == 0 || (j < n && j-p < p-(i-1)) { + return j + } + return i - 1 +} + +// srtmFillVoidRows copies into each of the side-long rows of grid listed in +// void (ascending) the nearest row not listed (ties go north). At least one +// row must not be listed. +func srtmFillVoidRows(grid []int16, side int, void []int) { + rows := len(grid) / side + for a := 0; a < len(void); { + b := a + for b+1 < len(void) && void[b+1] == void[b]+1 { + b++ + } + // void[a..b] is a run of rows i..j-1; rows i-1 and j are valid if present. + i, j := void[a], void[b]+1 + for p := i; p < j; p++ { + src := srtmNearest(p, i, j, rows) + copy(grid[p*side:][:side], grid[src*side:][:side]) + } + a = b + 1 + } +} diff --git a/cmd/server/terrain_srtm_test.go b/cmd/server/terrain_srtm_test.go new file mode 100644 index 000000000..113717bb1 --- /dev/null +++ b/cmd/server/terrain_srtm_test.go @@ -0,0 +1,1815 @@ +package main + +import ( + "bytes" + "compress/gzip" + "context" + "encoding/binary" + "errors" + "fmt" + "io" + "log" + "math" + "math/rand/v2" + "net/http" + "net/http/httptest" + "os" + "regexp" + "runtime" + "slices" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +// ─── Synthetic tiles ─────────────────────────────────────────────────────── + +// srtmTestTiles caches generated gzip bodies by id: each costs one build. +var srtmTestTiles struct { + sync.Mutex + m map[string][]byte +} + +// srtmTestGzip gzips whatever write produces, cached under id. +func srtmTestGzip(t testing.TB, id string, level int, write func(w io.Writer) error) []byte { + t.Helper() + srtmTestTiles.Lock() + defer srtmTestTiles.Unlock() + if b, ok := srtmTestTiles.m[id]; ok { + return b + } + var buf bytes.Buffer + zw, err := gzip.NewWriterLevel(&buf, level) + if err != nil { + t.Fatal(err) + } + if err := write(zw); err != nil { + t.Fatal(err) + } + if err := zw.Close(); err != nil { + t.Fatal(err) + } + if srtmTestTiles.m == nil { + srtmTestTiles.m = make(map[string][]byte) + } + srtmTestTiles.m[id] = buf.Bytes() + return buf.Bytes() +} + +// srtmTileFunc gzips a full 3601² tile whose raw sample (row, col) is f(row, col). +func srtmTileFunc(t testing.TB, id string, f func(r, c int) int16) []byte { + return srtmTestGzip(t, id, gzip.BestSpeed, func(w io.Writer) error { + row := make([]byte, srtmRawRowBytes) + for r := 0; r < srtmRawSide; r++ { + for c := 0; c < srtmRawSide; c++ { + binary.BigEndian.PutUint16(row[2*c:], uint16(f(r, c))) + } + if _, err := w.Write(row); err != nil { + return err + } + } + return nil + }) +} + +// srtmConstTile gzips a tile of n raw bytes holding v in every sample (n = +// srtmRawBytes for a valid tile; the last sample may be cut short). +func srtmConstTile(t testing.TB, v int16, n, level int) []byte { + return srtmTestGzip(t, fmt.Sprintf("const:%d:%d:%d", v, n, level), level, func(w io.Writer) error { + row := make([]byte, srtmRawRowBytes) + for c := 0; c < srtmRawSide; c++ { + binary.BigEndian.PutUint16(row[2*c:], uint16(v)) + } + for n > 0 { + k := min(n, len(row)) + if _, err := w.Write(row[:k]); err != nil { + return err + } + n -= k + } + return nil + }) +} + +// srtmPatternAt is the known 10×10 block at the north-west corner of the +// "grid" tile, at 3-arc-second positions. Negative values check signed +// decoding; distinct (R,C)/(C,R) values check orientation. +func srtmPatternAt(R, C int) int16 { return int16((R*37+C*101+R*C*13)%251 - 120) } + +// srtmGridTile: raw sample = row+col (downsampled: 3R+3C), except the 10×10 +// pattern block. +func srtmGridTile(t testing.TB) []byte { + return srtmTileFunc(t, "grid", func(r, c int) int16 { + if r%srtmStep == 0 && c%srtmStep == 0 && r/srtmStep < 10 && c/srtmStep < 10 { + return srtmPatternAt(r/srtmStep, c/srtmStep) + } + return int16(r + c) + }) +} + +// srtmLinearTile is tile (lat, lon) of a field that is linear across tiles: +// elevation = 3600·(32−lat) + 3600·(lon+98) on N30..N31 × W098..W097, so the +// shared tile edges agree exactly as real SRTM edges do. +func srtmLinearTile(t testing.TB, k srtmKey) []byte { + return srtmTileFunc(t, "linear:"+k.name(), func(r, c int) int16 { + return int16((31-k.lat)*(srtmRawSide-1) + r + (k.lon+98)*(srtmRawSide-1) + c) + }) +} + +func srtmLinearWant(lat, lon float64) float64 { return 3600*(32-lat) + 3600*(lon+98) } + +// ─── Test upstream ───────────────────────────────────────────────────────── + +type srtmUpstream struct { + ts *httptest.Server + mu sync.Mutex + hits map[string]int + uas []string + h http.HandlerFunc +} + +func (u *srtmUpstream) ServeHTTP(w http.ResponseWriter, r *http.Request) { + u.mu.Lock() + u.hits[r.URL.Path]++ + u.uas = append(u.uas, r.Header.Get("User-Agent")) + h := u.h + u.mu.Unlock() + h(w, r) +} + +func (u *srtmUpstream) hitsFor(path string) int { + u.mu.Lock() + defer u.mu.Unlock() + return u.hits[path] +} + +func (u *srtmUpstream) total() int { + u.mu.Lock() + defer u.mu.Unlock() + n := 0 + for _, v := range u.hits { + n += v + } + return n +} + +// srtmTestViewTiles is a test source's per-view cap: the planner's at its +// default sizes, as when only the planner is enabled. +var srtmTestViewTiles = PlannerConfig{}.tileLimits().max() + +// newSRTMTest builds a source against a local upstream with a fake clock and +// its own fetch slots. cacheTiles 0 means the default. +func newSRTMTest(t testing.TB, cacheTiles int, h http.HandlerFunc) (*srtmSource, *srtmUpstream, *elevClock) { + t.Helper() + return newSRTMTestViews(t, cacheTiles, srtmTestViewTiles, h) +} + +// newSRTMTestViews is newSRTMTest for views of up to viewTiles tiles. +func newSRTMTestViews(t testing.TB, cacheTiles, viewTiles int, h http.HandlerFunc) (*srtmSource, *srtmUpstream, *elevClock) { + t.Helper() + u := &srtmUpstream{hits: make(map[string]int), h: h} + u.ts = httptest.NewServer(u) + s := newSRTMSource(TerrainConfig{TileURL: u.ts.URL, TileCacheTiles: cacheTiles}, viewTiles) + s.sem = make(chan struct{}, srtmMaxConcurrent) + clk := &elevClock{t: time.Unix(1_700_000_000, 0)} + s.now = clk.now + t.Cleanup(func() { + if c, ok := s.client.(*http.Client); ok { + c.CloseIdleConnections() + } + u.ts.Close() + }) + return s, u, clk +} + +func srtmPath(k srtmKey) string { + n := k.name() + return "/" + n[:3] + "/" + n + ".hgt.gz" +} + +// srtmBox is a bbox well inside tile k. +func srtmBox(k srtmKey) geoBBox { + la, lo := float64(k.lat), float64(k.lon) + return geoBBox{S: la + 0.25, W: lo + 0.25, N: la + 0.75, E: lo + 0.75} +} + +// terrainStarts is how many downloads src.Begin(bb) would charge for and +// start now. Its charge refuses, so it starts none. +func terrainStarts(src terrainSource, bb geoBBox) int { + n := 0 + src.Begin(bb, func(starts int) bool { n = starts; return false }) + return n +} + +// srtmLook is s.tiles(keys) with a charge that refuses: it starts nothing. +func srtmLook(s *srtmSource, keys []srtmKey) srtmTileSet { + ts, _ := s.tiles(keys, func(int) bool { return false }) + return ts +} + +// srtmServe serves body for path and 404 for everything else. +func srtmServe(tiles map[string][]byte) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + b, ok := tiles[r.URL.Path] + if !ok { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Length", strconv.Itoa(len(b))) + w.Write(b) + } +} + +func srtmCacheLen(s *srtmSource) int { + s.mu.Lock() + defer s.mu.Unlock() + return s.cache.Len() +} + +func srtmNegLen(s *srtmSource) int { + s.mu.Lock() + defer s.mu.Unlock() + return len(s.neg) +} + +// srtmGate holds handlers until opened. Register t.Cleanup(gate.open) after +// newSRTMTest: cleanups run last-first, so a failed test opens the gate +// before the server waits for its handlers. +type srtmGate struct { + ch chan struct{} + once sync.Once +} + +func newSRTMGate() *srtmGate { return &srtmGate{ch: make(chan struct{})} } + +func (g *srtmGate) open() { g.once.Do(func() { close(g.ch) }) } + +// wait reports false when the client went away first. +func (g *srtmGate) wait(r *http.Request) bool { + select { + case <-g.ch: + return true + case <-r.Context().Done(): + return false + } +} + +func srtmEventually(t *testing.T, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + for !cond() { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for %s", what) + } + time.Sleep(5 * time.Millisecond) + } +} + +func srtmMustView(t *testing.T, s *srtmSource, bb geoBBox) terrainView { + t.Helper() + v, err := s.View(context.Background(), bb) + if err != nil { + t.Fatalf("View(%+v): %v", bb, err) + } + return v +} + +func srtmWantElev(t *testing.T, v terrainView, lat, lon, want float64) { + t.Helper() + got, ok := v.ElevationAt(lat, lon) + if !ok { + t.Fatalf("ElevationAt(%v, %v): ok=false, want %v", lat, lon, want) + } + if math.Abs(got-want) > 1e-6 { + t.Fatalf("ElevationAt(%v, %v) = %v, want %v", lat, lon, got, want) + } +} + +// srtmWantNoElev: (lat, lon) has no terrain, so callers skip it. +func srtmWantNoElev(t *testing.T, v terrainView, lat, lon float64) { + t.Helper() + if got, ok := v.ElevationAt(lat, lon); ok { + t.Fatalf("ElevationAt(%v, %v) = %v, ok=true; want no elevation", lat, lon, got) + } +} + +type srtmLogBuf struct { + mu sync.Mutex + b bytes.Buffer +} + +func (l *srtmLogBuf) Write(p []byte) (int, error) { + l.mu.Lock() + defer l.mu.Unlock() + return l.b.Write(p) +} + +func (l *srtmLogBuf) String() string { + l.mu.Lock() + defer l.mu.Unlock() + return l.b.String() +} + +// ─── Tile selection ──────────────────────────────────────────────────────── + +var srtmNameRE = regexp.MustCompile(`^[NS]\d{2}[EW]\d{3}$`) + +func TestSRTMTileNaming(t *testing.T) { + cases := []struct { + lat, lon float64 + want string + }{ + {30.2672, -97.7431, "N30W098"}, + {0, 0, "N00E000"}, + {0.0001, 0.0001, "N00E000"}, + {-0.0001, -0.0001, "S01W001"}, + {-0.0001, 0.0001, "S01E000"}, + {0.0001, -0.0001, "N00W001"}, + {-0.5, -49.5, "S01W050"}, + {31.0, -98.0, "N31W098"}, // on a degree line: the tile north/east of it + {30.9999, -97.0001, "N30W098"}, + {-1.0, 1.0, "S01E001"}, + {-89.9999, 0.5, "S90E000"}, + {-90, -180, "S90W180"}, + {89.9999, 0.5, "N89E000"}, + {90, 0.5, "N89E000"}, // clamped + {45, -180, "N45W180"}, + {45, -179.9999, "N45W180"}, + {45, 179.9999, "N45E179"}, + {45, 180, "N45E179"}, // clamped + {1e300, -1e300, "N89W180"}, + } + for _, c := range cases { + k := srtmKeyOf(c.lat, c.lon) + if got := k.name(); got != c.want { + t.Errorf("srtmKeyOf(%v, %v).name() = %s, want %s", c.lat, c.lon, got, c.want) + } + } + + s := newSRTMSource(TerrainConfig{TileURL: "https://tiles.example/skadi/"}, srtmTestViewTiles) + if got, want := s.tileURL(srtmKey{30, -98}), "https://tiles.example/skadi/N30/N30W098.hgt.gz"; got != want { + t.Errorf("tileURL = %s, want %s", got, want) + } + if got, want := s.tileURL(srtmKey{-1, -50}), "https://tiles.example/skadi/S01/S01W050.hgt.gz"; got != want { + t.Errorf("tileURL = %s, want %s", got, want) + } + if got := newSRTMSource(TerrainConfig{}, srtmTestViewTiles).baseURL; got != defaultTerrainTileURL { + t.Errorf("default base = %s", got) + } +} + +func TestSRTMTileCount(t *testing.T) { + cases := []struct { + name string + bb geoBBox + want int + }{ + {"inside one tile", geoBBox{30.2, -97.9, 30.8, -97.1}, 1}, + {"exactly one tile on degree lines", geoBBox{30, -98, 31, -97}, 1}, + {"N edge on a degree line", geoBBox{30.5, -97.9, 31.0, -97.1}, 1}, + {"E edge on a degree line", geoBBox{30.2, -97.5, 30.8, -97.0}, 1}, + {"crosses one latitude line", geoBBox{29.9, -98, 31, -97}, 2}, + {"crosses one longitude line", geoBBox{30.5, -98.5, 30.6, -97.5}, 2}, + {"crosses one line each way", geoBBox{29.5, -98.5, 30.5, -97.5}, 4}, + {"crosses two lines each way", geoBBox{29.5, -99.5, 31.5, -97.5}, 9}, + {"equator and prime meridian", geoBBox{-0.5, -0.5, 0.5, 0.5}, 4}, + {"point on a degree line", geoBBox{31, -97.5, 31, -97.5}, 1}, + {"point on a tile corner", geoBBox{31, -97, 31, -97}, 1}, + {"beyond the north pole clamps", geoBBox{89.5, 0.5, 95, 0.6}, 1}, + {"beyond the south pole clamps", geoBBox{-95, 0.5, -89.5, 0.6}, 1}, + {"beyond +180 clamps", geoBBox{45.2, 179.5, 45.5, 200}, 1}, + {"beyond -180 clamps", geoBBox{45.2, -200, 45.5, -179.5}, 1}, + {"whole world", geoBBox{-90, -180, 90, 180}, 180 * 360}, + {"NaN", geoBBox{math.NaN(), 0, 1, 1}, 0}, + {"Inf", geoBBox{0, 0, math.Inf(1), 1}, 0}, + {"-Inf", geoBBox{0, math.Inf(-1), 1, 1}, 0}, + {"inverted lat", geoBBox{31, -98, 30, -97}, 0}, + {"antimeridian", geoBBox{10, 179.5, 11, -179.5}, 0}, + } + s, u, _ := newSRTMTest(t, 0, srtmServe(nil)) + for _, c := range cases { + if got := s.TileCount(c.bb); got != c.want { + t.Errorf("%s: TileCount = %d, want %d", c.name, got, c.want) + } + if c.want != 0 && c.want <= s.maxTiles { + continue + } + // Boxes View refuses: never a request, never resident. + v, err := s.View(context.Background(), c.bb) + want := errTerrainUnavailable + if c.want > s.maxTiles { + want = errTerrainTooManyTiles + } + if !errors.Is(err, want) || v != nil { + t.Errorf("%s: View = %v, %v; want %v", c.name, v, err, want) + } + if s.Resident(c.bb) { + t.Errorf("%s: Resident = true for a box View refuses", c.name) + } + } + tooMany := geoBBox{29.5, -99.5, 32.5, -96.5} // 4×4 + if got := s.TileCount(tooMany); got != 16 || got <= s.maxTiles { + t.Fatalf("TileCount = %d, want 16 (over the cap of %d)", got, s.maxTiles) + } + if _, err := s.View(context.Background(), tooMany); !errors.Is(err, errTerrainTooManyTiles) { + t.Fatalf("View(16 tiles) err = %v, want errTerrainTooManyTiles", err) + } + if n := u.total(); n != 0 { + t.Fatalf("refused boxes made %d requests", n) + } +} + +// ─── Interpolation ───────────────────────────────────────────────────────── + +func TestSRTMBilinear(t *testing.T) { + k := srtmKey{30, -98} + s, _, _ := newSRTMTest(t, 0, srtmServe(map[string][]byte{srtmPath(k): srtmGridTile(t)})) + v := srtmMustView(t, s, srtmBox(k)) + at := func(y, x float64) (float64, float64) { return 31 - y/srtmCells, -98 + x/srtmCells } + + // Outside the pattern the field is 3y+3x and bilinear is exact. + for _, p := range [][2]float64{{600, 600}, {879.36, 308.28}, {12.5, 1100.25}, {1199.9, 0.1}, {1200, 1200}, {1200, 0}, {0, 1200}, {1200, 600}, {360, 1200}} { + lat, lon := at(p[0], p[1]) + srtmWantElev(t, v, lat, lon, 3*p[0]+3*p[1]) + } + srtmWantElev(t, v, 30.2672, -97.7431, 3*((31-30.2672)*1200+(-97.7431+98)*1200)) + + // Pattern: exact at grid points (row 0 = north edge, col 0 = west edge)… + for R := 0; R < 10; R++ { + for C := 0; C < 10; C++ { + lat, lon := at(float64(R), float64(C)) + srtmWantElev(t, v, lat, lon, float64(srtmPatternAt(R, C))) + } + } + // …the mean of the four corners at cell centres… + for R := 0; R < 9; R++ { + for C := 0; C < 9; C++ { + lat, lon := at(float64(R)+0.5, float64(C)+0.5) + want := float64(int(srtmPatternAt(R, C))+int(srtmPatternAt(R, C+1))+int(srtmPatternAt(R+1, C))+int(srtmPatternAt(R+1, C+1))) / 4 + srtmWantElev(t, v, lat, lon, want) + } + } + // …and weighted off-centre. + lat, lon := at(2.25, 7.75) + n := 0.25*float64(srtmPatternAt(2, 7)) + 0.75*float64(srtmPatternAt(2, 8)) + sth := 0.25*float64(srtmPatternAt(3, 7)) + 0.75*float64(srtmPatternAt(3, 8)) + srtmWantElev(t, v, lat, lon, 0.75*n+0.25*sth) + + // Outside the view's tiles. + for _, p := range [][2]float64{{31.0001, -97.5}, {29.9999, -97.5}, {30.5, -98.0001}, {30.5, -96.9999}, + {math.NaN(), -97.5}, {30.5, math.NaN()}, {math.Inf(1), -97.5}, {30.5, math.Inf(-1)}} { + if e, ok := v.ElevationAt(p[0], p[1]); ok { + t.Errorf("ElevationAt(%v, %v) = %v, ok=true outside the view", p[0], p[1], e) + } + } +} + +func TestSRTMTileBoundaryInterpolation(t *testing.T) { + tiles := map[string][]byte{} + for _, k := range []srtmKey{{30, -98}, {30, -97}, {31, -98}, {31, -97}} { + tiles[srtmPath(k)] = srtmLinearTile(t, k) + } + s, u, _ := newSRTMTest(t, 0, srtmServe(tiles)) + v := srtmMustView(t, s, geoBBox{S: 30.5, W: -97.5, N: 31.5, E: -96.5}) + if u.total() != 4 { + t.Fatalf("requests = %d, want 4", u.total()) + } + // Across the latitude line, the longitude line and the four-tile corner + // the field stays exact: each side reads its own tile, the edges agree. + for _, d := range []float64{-0.01, -1.0 / 1200, -1e-4, -1e-9, 0, 1e-9, 1e-4, 1.0 / 1200, 0.01} { + srtmWantElev(t, v, 31+d, -97.3, srtmLinearWant(31+d, -97.3)) + srtmWantElev(t, v, 30.6, -97+d, srtmLinearWant(30.6, -97+d)) + srtmWantElev(t, v, 31+d, -97+d, srtmLinearWant(31+d, -97+d)) + srtmWantElev(t, v, 31+d, -97-d, srtmLinearWant(31+d, -97-d)) + } + // The view's own outer edges clamp onto its last tiles. + srtmWantElev(t, v, 32, -97.5, srtmLinearWant(32, -97.5)) + srtmWantElev(t, v, 30.5, -96, srtmLinearWant(30.5, -96)) + srtmWantElev(t, v, 30, -98, srtmLinearWant(30, -98)) +} + +// With edges that disagree, a point exactly on a shared edge reads the +// neighbouring tile when the view has it, and clamps to its own tile's edge +// when it does not. +func TestSRTMBoundaryOwnership(t *testing.T) { + a, north, east := srtmKey{30, -98}, srtmKey{31, -98}, srtmKey{30, -97} + s, _, _ := newSRTMTest(t, 0, srtmServe(map[string][]byte{ + srtmPath(a): srtmConstTile(t, 100, srtmRawBytes, gzip.BestSpeed), + srtmPath(north): srtmConstTile(t, 200, srtmRawBytes, gzip.BestSpeed), + srtmPath(east): srtmConstTile(t, 300, srtmRawBytes, gzip.BestSpeed), + })) + both := srtmMustView(t, s, geoBBox{S: 30.5, W: -97.5, N: 31.5, E: -97.5}) + srtmWantElev(t, both, 31, -97.5, 200) + srtmWantElev(t, both, 30.9999, -97.5, 100) + alone := srtmMustView(t, s, geoBBox{S: 30.5, W: -97.5, N: 31, E: -97.5}) + srtmWantElev(t, alone, 31, -97.5, 100) + if _, ok := alone.ElevationAt(31.0001, -97.5); ok { + t.Fatal("point north of a one-tile view reported ok") + } + both = srtmMustView(t, s, geoBBox{S: 30.5, W: -97.5, N: 30.5, E: -96.5}) + srtmWantElev(t, both, 30.5, -97, 300) + alone = srtmMustView(t, s, geoBBox{S: 30.5, W: -97.5, N: 30.5, E: -97}) + srtmWantElev(t, alone, 30.5, -97, 100) +} + +// ─── Decode ──────────────────────────────────────────────────────────────── + +func TestSRTMFillVoids(t *testing.T) { + const V = srtmVoid + cases := []struct{ in, want []int16 }{ + {[]int16{1, 2, 3}, []int16{1, 2, 3}}, + {[]int16{V, V, V}, nil}, // nothing to fill from: left void, never 0 m + {[]int16{V, V, 7, 8}, []int16{7, 7, 7, 8}}, + {[]int16{7, 8, V, V}, []int16{7, 8, 8, 8}}, + {[]int16{1, V, 3}, []int16{1, 1, 3}}, // tie goes west + {[]int16{1, V, V, 4}, []int16{1, 1, 4, 4}}, // each to its nearest + {[]int16{1, V, V, V, 5}, []int16{1, 1, 1, 5, 5}}, // middle tie goes west + {[]int16{-5, V, V, V, V, 9}, []int16{-5, -5, -5, 9, 9, 9}}, + {[]int16{V}, nil}, + {[]int16{}, []int16{}}, + } + for _, c := range cases { + got := append([]int16(nil), c.in...) + ok := srtmFillVoids(got) + want := c.want + if want == nil { + want = c.in + } + if ok != (c.want != nil) || fmt.Sprint(got) != fmt.Sprint(want) { + t.Errorf("srtmFillVoids(%v) = %v, %v; want %v, %v", c.in, got, ok, want, c.want != nil) + } + } +} + +// Rows without a valid sample take the nearest row that has some (ties go +// north), whatever the run's length or position. +func TestSRTMFillVoidRows(t *testing.T) { + const V = srtmVoid + // One value per row; the rows listed in void hold V. + cases := []struct { + rows []int16 + void []int + want []int16 + }{ + {[]int16{1, 2, 3}, nil, []int16{1, 2, 3}}, + {[]int16{V, 2, 3}, []int{0}, []int16{2, 2, 3}}, + {[]int16{V, V, 3}, []int{0, 1}, []int16{3, 3, 3}}, + {[]int16{1, V, V}, []int{1, 2}, []int16{1, 1, 1}}, + {[]int16{1, V, 3}, []int{1}, []int16{1, 1, 3}}, // tie goes north + {[]int16{1, V, V, 4}, []int{1, 2}, []int16{1, 1, 4, 4}}, // each to its nearest + {[]int16{1, V, V, V, 5}, []int{1, 2, 3}, []int16{1, 1, 1, 5, 5}}, + {[]int16{V, 2, V, 4, V, V, 7, V}, []int{0, 2, 4, 5, 7}, []int16{2, 2, 2, 4, 4, 7, 7, 7}}, + } + for _, c := range cases { + const side = 3 + grid := make([]int16, 0, side*len(c.rows)) + for _, v := range c.rows { + grid = append(grid, v, v, v) + } + srtmFillVoidRows(grid, side, c.void) + for r, want := range c.want { + for col := 0; col < side; col++ { + if got := grid[r*side+col]; got != want { + t.Errorf("rows %v: row %d col %d = %d, want %d", c.rows, r, col, got, want) + } + } + } + } +} + +func srtmVoidTileValue(r, c int) int16 { + const V = srtmVoid + switch { + case r == 0: // kept row: value = col, voids at kept cols 3, 6, 30, 33 + if c == 3 || c == 6 || (c >= 30 && c <= 35) { + return V + } + return int16(c) + case r == 1, r == 3, r >= 1800: // row 1 is dropped; 3 and ≥1800 are kept, without a valid sample + return V + case r == 6: // leading and trailing void runs + switch { + case c <= 8 || c >= 3590: + return V + case c == 9: + return 777 + case c == 3589: + return 888 + } + } + return 500 +} + +func TestSRTMDecodeVoids(t *testing.T) { + body := srtmTileFunc(t, "voids", srtmVoidTileValue) + grid, voids, err := srtmDecode(bytes.NewReader(body)) + if err != nil { + t.Fatal(err) + } + at := func(R, C int) int16 { return grid[R*srtmSide+C] } + checks := []struct { + R, C int + want int16 + }{ + {0, 0, 0}, {0, 1, 2}, {0, 2, 5}, {0, 10, 29}, {0, 11, 36}, {0, 12, 36}, {0, 1200, 3600}, + // Kept row 1 has no valid sample: it takes row 0 (the tie goes north). + {1, 0, 0}, {1, 1, 2}, {1, 600, 1800}, {1, 1200, 3600}, + {2, 0, 777}, {2, 1, 777}, {2, 2, 777}, {2, 3, 777}, {2, 4, 500}, + {2, 1196, 500}, {2, 1197, 888}, {2, 1200, 888}, + // Kept rows 600 to 1200 have none either: they take row 599, never 0 m. + {5, 5, 500}, {599, 1200, 500}, {600, 0, 500}, {900, 600, 500}, {1200, 1200, 500}, + } + for _, c := range checks { + if got := at(c.R, c.C); got != c.want { + t.Errorf("grid[%d][%d] = %d, want %d", c.R, c.C, got, c.want) + } + } + if want := 4 + srtmSide + 7 + 601*srtmSide; voids != want { + t.Errorf("voids = %d, want %d", voids, want) + } + + // Through the source: the >20 % void tile is logged, not rejected. + var logs srtmLogBuf + prev := log.Writer() + log.SetOutput(&logs) + defer log.SetOutput(prev) + k := srtmKey{30, -98} + s, _, _ := newSRTMTest(t, 0, srtmServe(map[string][]byte{srtmPath(k): body})) + v := srtmMustView(t, s, srtmBox(k)) + srtmWantElev(t, v, 31, -98+1.0/srtmCells, 2) + srtmWantElev(t, v, 30, -97.5, 500) + if !strings.Contains(logs.String(), "N30W098 is 50% void") { + t.Errorf("void warning missing from log: %q", logs.String()) + } +} + +func TestSRTMDecompressionBomb(t *testing.T) { + var streamed atomic.Int64 + s, u, _ := newSRTMTest(t, 0, func(w http.ResponseWriter, r *http.Request) { + zw, _ := gzip.NewWriterLevel(w, gzip.BestCompression) + zeros := make([]byte, 1<<20) + for i := 0; i < 1024; i++ { // 1 GiB of zeros, compressed on the fly + if r.Context().Err() != nil { + return + } + if _, err := zw.Write(zeros); err != nil { + return + } + streamed.Add(int64(len(zeros))) + } + zw.Close() + }) + k := srtmKey{30, -98} + + runtime.GC() + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + var peak atomic.Uint64 + stop, sampled := make(chan struct{}), make(chan struct{}) + go func() { + defer close(sampled) + tick := time.NewTicker(2 * time.Millisecond) + defer tick.Stop() + for { + select { + case <-stop: + return + case <-tick.C: + var m runtime.MemStats + runtime.ReadMemStats(&m) + if m.HeapAlloc > peak.Load() { + peak.Store(m.HeapAlloc) + } + } + } + }() + start := time.Now() + v, err := s.View(context.Background(), srtmBox(k)) + elapsed := time.Since(start) + close(stop) + <-sampled + runtime.ReadMemStats(&after) + + if err != nil { + t.Fatalf("View err = %v, want the bomb read as a missing tile", err) + } + alloc := after.TotalAlloc - before.TotalAlloc + growth := int64(peak.Load()) - int64(before.HeapAlloc) + t.Logf("bomb aborted in %s: total allocated %.1f MiB, peak heap growth %.1f MiB (server had produced %d MiB of the 1024 MiB stream)", + elapsed.Round(time.Millisecond), float64(alloc)/(1<<20), float64(growth)/(1<<20), streamed.Load()>>20) + // Everything allocated in the process (source and test server) during + // the fetch is below even one raw tile, let alone 1 GiB. + if alloc > 24<<20 { + t.Errorf("allocated %d bytes during the bomb fetch", alloc) + } + if srtmCacheLen(s) != 0 || srtmNegLen(s) != 1 || s.cooling() { + t.Error("the bomb was cached as data, or not set aside, or paused every download") + } + if m, n := v.(terrainCoverage).MissingTiles(); m != 1 || n != 1 { + t.Errorf("MissingTiles = %d of %d, want 1 of 1", m, n) + } + if n := u.total(); n != 1 { + t.Errorf("requests = %d, want 1", n) + } +} + +// An unusable body is about that one tile: it has no elevation for +// srtmBadTTL, is never cached as data, and does not pause other downloads. +func TestSRTMBadBodiesReadAsMissing(t *testing.T) { + valid := srtmConstTile(t, 0, srtmRawBytes, gzip.BestSpeed) + badCRC := append([]byte(nil), valid...) + badCRC[len(badCRC)-8] ^= 0xff + stored := srtmConstTile(t, 0, srtmRawBytes, gzip.NoCompression) // valid, but over the cap + cases := []struct { + name string + body []byte + contentLength bool + ok bool + }{ + {"valid control", valid, true, true}, + {"valid control chunked", valid, false, true}, + {"truncated", valid[:len(valid)/2], true, false}, + {"truncated trailer", valid[:len(valid)-4], true, false}, + {"two bytes short", srtmConstTile(t, 0, srtmRawBytes-2, gzip.BestSpeed), true, false}, + {"two bytes long", srtmConstTile(t, 0, srtmRawBytes+2, gzip.BestSpeed), true, false}, + {"bad CRC", badCRC, true, false}, + {"trailing garbage", append(append([]byte(nil), valid...), "garbage!"...), true, false}, + {"HTML", []byte("Not here"), true, false}, + {"empty", nil, true, false}, + {"over the cap, chunked", stored, false, false}, + {"over the cap, Content-Length", stored, true, false}, + } + if len(stored) <= srtmMaxGzipBytes { + t.Fatalf("stored tile is only %d bytes", len(stored)) + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + s, u, clk := newSRTMTest(t, 0, func(w http.ResponseWriter, r *http.Request) { + if c.contentLength { + w.Header().Set("Content-Length", strconv.Itoa(len(c.body))) + } + w.Header().Set("Content-Type", "application/x-gzip") + w.WriteHeader(http.StatusOK) + for b := c.body; len(b) > 0; { // in pieces, so chunked bodies stream + n := min(len(b), 64<<10) + if _, err := w.Write(b[:n]); err != nil { + return + } + b = b[n:] + } + }) + k := srtmKey{30, -98} + v, err := s.View(context.Background(), srtmBox(k)) + if err != nil { + t.Fatalf("View err = %v", err) + } + missing, _ := v.(terrainCoverage).MissingTiles() + if c.ok { + if missing != 0 || srtmCacheLen(s) != 1 { + t.Fatal("valid tile not cached") + } + return + } + if missing != 1 || !v.(terrainCoverage).MissingAt(30.5, -97.5) { + t.Fatalf("bad tile not reported missing (%d)", missing) + } + srtmWantNoElev(t, v, 30.5, -97.5) + if srtmCacheLen(s) != 0 || srtmNegLen(s) != 1 { + t.Fatal("a bad tile was cached as data, or not set aside") + } + if s.cooling() { + t.Fatal("one bad tile paused every download") + } + clk.add(srtmBadTTL - time.Second) + srtmMustView(t, s, srtmBox(k)) + if n := u.total(); n != 1 { + t.Fatalf("requests = %d within %s, want 1", n, srtmBadTTL) + } + clk.add(time.Second) + if s.Resident(srtmBox(k)) { + t.Fatalf("bad tile still set aside after %s", srtmBadTTL) + } + s.View(context.Background(), srtmBox(k)) + if n := u.total(); n != 2 { + t.Fatalf("requests = %d, want a retry after %s", n, srtmBadTTL) + } + }) + } +} + +type srtmFakeDoer func(*http.Request) (*http.Response, error) + +func (f srtmFakeDoer) Do(r *http.Request) (*http.Response, error) { return f(r) } + +type srtmCountingBody struct { + reads atomic.Int64 + closed atomic.Bool +} + +func (b *srtmCountingBody) Read(p []byte) (int, error) { + b.reads.Add(1) + clear(p) + return len(p), nil // an endless body +} + +func (b *srtmCountingBody) Close() error { b.closed.Store(true); return nil } + +// A declared length over the cap is refused before a single body byte is read. +func TestSRTMContentLengthOverCapNotRead(t *testing.T) { + s, _, _ := newSRTMTest(t, 0, srtmServe(nil)) + body := &srtmCountingBody{} + s.client = srtmFakeDoer(func(r *http.Request) (*http.Response, error) { + return &http.Response{StatusCode: http.StatusOK, ContentLength: srtmMaxGzipBytes + 1, Body: body, Request: r}, nil + }) + bb := srtmBox(srtmKey{30, -98}) + v, err := s.View(context.Background(), bb) + if err != nil { + t.Fatalf("View err = %v", err) + } + if n := body.reads.Load(); n != 0 || !body.closed.Load() { + t.Fatalf("body read %d times, closed=%v; want unread and closed", n, body.closed.Load()) + } + if m, _ := v.(terrainCoverage).MissingTiles(); m != 1 || srtmCacheLen(s) != 0 || s.cooling() { + t.Fatal("oversized tile cached as data, not reported missing, or paused downloads") + } +} + +// ─── Negative cache, cooldown, budget ────────────────────────────────────── + +func TestSRTMNegativeCache(t *testing.T) { + a, b := srtmKey{30, -98}, srtmKey{31, -98} + s, u, clk := newSRTMTest(t, 0, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == srtmPath(b) { + w.WriteHeader(http.StatusForbidden) // S3 says 403 for absent keys + return + } + http.NotFound(w, r) + }) + bb := geoBBox{S: 30.5, W: -97.5, N: 31.5, E: -97.5} + v := srtmMustView(t, s, bb) + srtmWantNoElev(t, v, 30.5, -97.5) + srtmWantNoElev(t, v, 31.5, -97.5) + if !s.Resident(bb) { + t.Fatal("404/403 tiles not resident") + } + if m, n := v.(terrainCoverage).MissingTiles(); m != 2 || n != 2 { + t.Fatalf("MissingTiles = %d of %d, want 2 of 2", m, n) + } + srtmMustView(t, s, bb) + // 403 (also what a misconfigured bucket says) is believed for an hour, + // 404 for a day. + clk.add(srtmForbiddenTTL - time.Second) + srtmMustView(t, s, bb) + if ha, hb := u.hitsFor(srtmPath(a)), u.hitsFor(srtmPath(b)); ha != 1 || hb != 1 { + t.Fatalf("hits = %d, %d; want one request per tile within an hour", ha, hb) + } + clk.add(time.Second) + srtmMustView(t, s, bb) + if ha, hb := u.hitsFor(srtmPath(a)), u.hitsFor(srtmPath(b)); ha != 1 || hb != 2 { + t.Fatalf("hits = %d, %d; want only the 403 tile refetched after an hour", ha, hb) + } + clk.add(srtmNegTTL - srtmForbiddenTTL - time.Second) + if !s.Resident(srtmBox(a)) { + t.Fatal("404 entry expired early") + } + clk.add(time.Second) + if s.Resident(srtmBox(a)) { + t.Fatal("404 entry outlived 24 h") + } + srtmMustView(t, s, bb) + if ha := u.hitsFor(srtmPath(a)); ha != 2 { + t.Fatalf("404 hits = %d; want a refetch after 24 h", ha) + } +} + +func TestSRTMNegativeCacheBounded(t *testing.T) { + s, _, clk := newSRTMTest(t, 0, srtmServe(nil)) + for i := 0; i < srtmNegMax+100; i++ { + s.putMissing(srtmKey{-60 + i/300, -150 + i%300}, srtmNegTTL) + clk.add(time.Second) + } + if n := srtmNegLen(s); n != srtmNegMax { + t.Fatalf("negative cache holds %d, want %d", n, srtmNegMax) + } + s.mu.Lock() + _, first := s.neg[srtmKey{-60, -150}] + _, last := s.neg[srtmKey{-60 + (srtmNegMax+99)/300, -150 + (srtmNegMax+99)%300}] + s.mu.Unlock() + if first || !last { + t.Fatalf("eviction kept the oldest (%v) or dropped the newest (%v)", first, last) + } + clk.add(srtmNegTTL) + s.putMissing(srtmKey{80, 80}, srtmNegTTL) + if n := srtmNegLen(s); n != 1 { + t.Fatalf("expired entries not purged when full: %d left", n) + } +} + +func TestSRTMUpstreamFailuresNotNegativeCached(t *testing.T) { + for _, status := range []int{http.StatusInternalServerError, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusTooManyRequests, 0} { + name := "timeout" + if status != 0 { + name = strconv.Itoa(status) + } + t.Run(name, func(t *testing.T) { + s, u, clk := newSRTMTest(t, 0, func(w http.ResponseWriter, r *http.Request) { + if status == 0 { + select { + case <-r.Context().Done(): + case <-time.After(10 * time.Second): + } + return + } + w.WriteHeader(status) + }) + if status == 0 { + c := newSRTMHTTPClient() + c.Timeout = 200 * time.Millisecond + s.client = c + } + bb := srtmBox(srtmKey{30, -98}) + if _, err := s.View(context.Background(), bb); !errors.Is(err, errTerrainUnavailable) { + t.Fatalf("first View err = %v, want errTerrainUnavailable", err) + } + if _, err := s.View(context.Background(), bb); !errors.Is(err, errTerrainBusy) { + t.Fatalf("View in cooldown err = %v, want errTerrainBusy", err) + } + if s.Resident(bb) || srtmNegLen(s) != 0 { + t.Fatal("failure was negatively cached") + } + clk.add(time.Minute) + s.View(context.Background(), bb) + if n := u.total(); n != 2 { + t.Fatalf("requests = %d, want 2", n) + } + }) + } +} + +func TestSRTMCooldownLadder(t *testing.T) { + good := srtmKey{40, 10} + goodTile := srtmConstTile(t, 42, srtmRawBytes, gzip.BestSpeed) + s, u, clk := newSRTMTest(t, 0, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == srtmPath(good) { + w.Write(goodTile) + return + } + w.WriteHeader(http.StatusInternalServerError) + }) + bad, bad2 := srtmBox(srtmKey{30, -98}), srtmBox(srtmKey{31, -98}) + view := func(bb geoBBox) error { _, err := s.View(context.Background(), bb); return err } + + if err := view(bad); !errors.Is(err, errTerrainUnavailable) { + t.Fatalf("err = %v", err) + } + ladder := []time.Duration{time.Minute, 5 * time.Minute, 30 * time.Minute, time.Hour, time.Hour} + for i, d := range ladder { + hits := u.total() + clk.add(d - time.Second) + if err := view(bad); !errors.Is(err, errTerrainBusy) { + t.Fatalf("step %d: %s into a %s cooldown err = %v, want errTerrainBusy", i, d-time.Second, d, err) + } + if err := view(bad2); !errors.Is(err, errTerrainBusy) { + t.Fatalf("step %d: other tile err = %v, want errTerrainBusy", i, err) + } + if u.total() != hits { + t.Fatalf("step %d: request made during cooldown", i) + } + clk.add(time.Second) + if err := view(bad); !errors.Is(err, errTerrainUnavailable) { + t.Fatalf("step %d: err = %v after the cooldown", i, err) + } + if u.total() != hits+1 { + t.Fatalf("step %d: requests = %d, want %d", i, u.total(), hits+1) + } + } + // Success resets the ladder; cached tiles keep working in a cooldown. + clk.add(time.Hour) + v := srtmMustView(t, s, srtmBox(good)) + srtmWantElev(t, v, 40.5, 10.5, 42) + if err := view(bad2); !errors.Is(err, errTerrainUnavailable) { + t.Fatalf("err = %v", err) + } + srtmMustView(t, s, srtmBox(good)) + clk.add(time.Minute - time.Second) + if err := view(bad2); !errors.Is(err, errTerrainBusy) { + t.Fatalf("err = %v, want errTerrainBusy", err) + } + clk.add(time.Second) + hits := u.total() + if err := view(bad2); !errors.Is(err, errTerrainUnavailable) || u.total() != hits+1 { + t.Fatalf("ladder did not reset to 60 s: err = %v", err) + } +} + +func TestSRTMBudget(t *testing.T) { + s, u, clk := newSRTMTest(t, 0, srtmServe(nil)) // every tile 404s: cheap, no cooldown + key := func(i int) geoBBox { return srtmBox(srtmKey{-60 + i/300, -150 + i%300}) } + view := func(i int) error { _, err := s.View(context.Background(), key(i)); return err } + perMin, perHour := s.budget.perMinute, s.budget.perHour + if perMin != srtmPerMinute || perHour != srtmPerHour { + t.Fatalf("a source for %d-tile views has budget %d/%d, want the floors", s.maxTiles, perMin, perHour) + } + + next := 0 + for m := 0; m < perHour/perMin; m++ { + for i := 0; i < perMin; i++ { + if err := view(next); err != nil { + t.Fatalf("minute %d, download %d: %v", m, i, err) + } + next++ + } + if err := view(next); !errors.Is(err, errTerrainBusy) { + t.Fatalf("minute %d: download %d err = %v, want errTerrainBusy", m, perMin+1, err) + } + if m == 0 { + clk.add(59 * time.Second) + if err := view(next); !errors.Is(err, errTerrainBusy) { + t.Fatalf("59 s later err = %v, want errTerrainBusy", err) + } + clk.add(time.Second) + continue + } + clk.add(time.Minute) + } + if u.total() != perHour { + t.Fatalf("requests = %d, want %d", u.total(), perHour) + } + // 10 minutes in: the minute window is empty but the hour is spent. + if err := view(next); !errors.Is(err, errTerrainBusy) { + t.Fatalf("hour budget err = %v, want errTerrainBusy", err) + } + clk.add(50*time.Minute - time.Second) // 59:59 after the first downloads + if err := view(next); !errors.Is(err, errTerrainBusy) { + t.Fatalf("at 59:59 err = %v, want errTerrainBusy", err) + } + clk.add(time.Second) + if err := view(next); err != nil { + t.Fatalf("at 60:00 err = %v", err) + } + if u.total() != perHour+1 { + t.Fatalf("requests = %d, want %d", u.total(), perHour+1) + } +} + +// The download budget never starts below its floors, and grows to hold the +// largest view in one minute (code review #2, #2391). +func TestSRTMBudgetFor(t *testing.T) { + for _, c := range []struct{ view, perMin, perHour int }{ + {0, 20, 200}, {12, 20, 200}, {16, 20, 200}, {20, 20, 200}, + {28, 28, 200}, {40, 40, 200}, {41, 41, 205}, + } { + if b := srtmBudgetFor(c.view); b.perMinute != c.perMin || b.perHour != c.perHour || b.starts != nil { + t.Errorf("srtmBudgetFor(%d) = %d/min, %d/hour; want %d, %d", c.view, b.perMinute, b.perHour, c.perMin, c.perHour) + } + } + if b := newSRTMSource(TerrainConfig{}, 40).budget; b.perMinute != 40 || b.perHour != 200 { + t.Fatalf("source budget %d/%d", b.perMinute, b.perHour) + } +} + +// room peeks at what take would admit; tiles and Begin count only the +// downloads it admits (code review #1, #2391), the first ones first. +func TestSRTMBudgetRoomAndStarts(t *testing.T) { + s, u, clk := newSRTMTest(t, 0, srtmServe(nil)) + b := srtmBudgetFor(s.maxTiles) + now := clk.now() + if r := b.room(now); r != b.perMinute { + t.Fatalf("empty budget: room %d", r) + } + for i := 0; i < 5; i++ { + b.take(now) + } + if r := b.room(now); r != b.perMinute-5 || len(b.starts) != 5 { + t.Fatalf("after 5: room %d, %d starts (room must not record)", r, len(b.starts)) + } + for i := 0; i < b.perHour-6; i++ { // spread over the hour: only the hour binds + b.starts = append(b.starts, now.Add(time.Duration(i)*time.Second-time.Hour+time.Minute)) + } + slices.SortFunc(b.starts, func(x, y time.Time) int { return x.Compare(y) }) + if r := b.room(now); r != 1 { + t.Fatalf("one start left in the hour: room %d", r) + } + if !b.take(now) || b.take(now) || b.room(now) != 0 { + t.Fatal("take disagrees with room") + } + + box := geoBBox{S: 40.5, W: 10.5, N: 41.5, E: 11.5} // 4 tiles + keys := []srtmKey{{40, 10}, {40, 11}, {41, 10}, {41, 11}} + s.put(keys[3], elevFlatGrid(1)) + if n := terrainStarts(s, box); n != 3 { + t.Fatalf("Starts = %d, want the 3 tiles not in memory", n) + } + s.mu.Lock() + for i := 0; i < s.budget.perMinute-2; i++ { + s.budget.starts = append(s.budget.starts, clk.now()) + } + s.mu.Unlock() + if n := terrainStarts(s, box); n != 2 { + t.Fatalf("Starts = %d with room for 2", n) + } + ts := srtmLook(s, keys) + if ts.starts != 2 || !slices.Equal(ts.need, keys[:2]) || !slices.Equal(ts.refused, keys[2:3]) { + t.Fatalf("tiles: starts %d, need %v, refused %v", ts.starts, ts.need, ts.refused) + } + s.mu.Lock() + s.coolTo = clk.now().Add(time.Minute) + s.mu.Unlock() + if n := terrainStarts(s, box); n != 0 { + t.Fatalf("Starts = %d while downloads are paused", n) + } + for _, bad := range []geoBBox{{S: 40.5, W: 10.5, N: 41.5, E: 30.5}, {S: math.NaN()}} { + if n := terrainStarts(s, bad); n != 0 { + t.Fatalf("Starts(%+v) = %d for a box View refuses", bad, n) + } + } + if u.total() != 0 { + t.Fatalf("peeking downloaded %d tiles", u.total()) + } +} + +// ─── Concurrency ─────────────────────────────────────────────────────────── + +func TestSRTMSingleflight(t *testing.T) { + k := srtmKey{30, -98} + tile := srtmGridTile(t) + gate := newSRTMGate() + s, u, _ := newSRTMTest(t, 0, func(w http.ResponseWriter, r *http.Request) { + if gate.wait(r) { + w.Write(tile) + } + }) + t.Cleanup(gate.open) + var wg sync.WaitGroup + errs := make(chan error, 10) + for i := 0; i < 10; i++ { + wg.Add(1) + go func() { + defer wg.Done() + v, err := s.View(context.Background(), srtmBox(k)) + if err != nil { + errs <- err + return + } + if e, ok := v.ElevationAt(30.5, -97.5); !ok || e != 3600 { + errs <- fmt.Errorf("elevation %v %v", e, ok) + } + }() + } + srtmEventually(t, "the first request", func() bool { return u.total() >= 1 }) + time.Sleep(100 * time.Millisecond) // let the other nine join the flight + gate.open() + wg.Wait() + close(errs) + for err := range errs { + t.Error(err) + } + if n := u.total(); n != 1 { + t.Fatalf("requests = %d, want 1", n) + } +} + +// srtmHeapObjects is the live heap object count after a full GC. +func srtmHeapObjects() uint64 { + runtime.GC() + var m runtime.MemStats + runtime.ReadMemStats(&m) + return m.HeapObjects +} + +// Security review #3 (#2391): every free 202 poll joined the tile's +// singleflight call, which kept a result channel per call until the +// download ended (up to minutes). A load is now one record whose done +// channel waiters select on: pollers, cancelled or timed out, leave nothing +// behind, and everyone waiting sees the one result. +func TestSRTMWaitersHoldNothing(t *testing.T) { + k := srtmKey{30, -98} + gate := newSRTMGate() + tile := srtmGridTile(t) + s, u, _ := newSRTMTest(t, 0, func(w http.ResponseWriter, r *http.Request) { + if gate.wait(r) { + w.Write(tile) + } + }) + t.Cleanup(gate.open) + keys := []srtmKey{k} + if got, failed := s.await(context.Background(), keys, time.Millisecond); len(got)+len(failed) != 0 { + t.Fatalf("gated tile finished: got %d, failed %d", len(got), len(failed)) + } + srtmEventually(t, "the download", func() bool { return u.hitsFor(srtmPath(k)) == 1 }) + s.mu.Lock() + ld := s.loading[k] + s.mu.Unlock() + if ld == nil { + t.Fatal("no running load") + } + + // 50 pollers at once, 4000 polls in all, half cancelled before they + // wait, half timing out: none leaves an object behind. The first round + // only warms up the runtime's caches of goroutines and channel waiters, + // which a fixed number of pollers keeps the same size. + const workers, polls = 50, 4000 + cancelled, cancel := context.WithCancel(context.Background()) + cancel() + var wg sync.WaitGroup + poll := func() { + for w := 0; w < workers; w++ { + wg.Add(1) + go func(w int) { + defer wg.Done() + for i := w; i < polls; i += workers { + ctx := context.Background() + if i%2 == 0 { + ctx = cancelled + } + if got, failed := s.await(ctx, keys, time.Millisecond); len(got)+len(failed) != 0 { + t.Errorf("poll %d: got %d, failed %d", i, len(got), len(failed)) + } + vctx, vcancel := context.WithTimeout(ctx, time.Millisecond) + if _, err := s.View(vctx, srtmBox(k)); err == nil { + t.Errorf("poll %d: View of a loading tile returned", i) + } + vcancel() + } + }(w) + } + wg.Wait() + } + poll() + before := srtmHeapObjects() + poll() + // Measuring leaves about 100 objects whatever the number of polls (500 + // to 20000 alike, with or without -race); singleflight kept a channel + // per call, 2 a poll: 8000 here. + if grew := int64(srtmHeapObjects()) - int64(before); grew > 500 { + t.Fatalf("%d polls left %d heap objects behind", polls, grew) + } + s.mu.Lock() + same, n := s.loading[k] == ld, len(s.loading) + s.mu.Unlock() + if !same || n != 1 || u.total() != 1 { + t.Fatalf("loads: same record %v, %d running, %d downloads", same, n, u.total()) + } + + // Waiters through both paths share the one download and its grid. + const waiters = 50 + grids := make([][]int16, 2*waiters) + for i := 0; i < waiters; i++ { + wg.Add(2) + go func(i int) { + defer wg.Done() + got, _ := s.await(context.Background(), keys, time.Minute) + grids[i] = got[k] + }(i) + go func(i int) { + defer wg.Done() + if v, err := s.View(context.Background(), srtmBox(k)); err == nil { + grids[waiters+i] = v.(*srtmView).grids[0] + } + }(i) + } + time.Sleep(50 * time.Millisecond) // let them reach the wait + gate.open() + wg.Wait() + <-ld.done + if ld.err != nil || len(ld.grid) != srtmSide*srtmSide { + t.Fatalf("load: err %v, %d samples", ld.err, len(ld.grid)) + } + for i, g := range grids { + if len(g) == 0 || &g[0] != &ld.grid[0] { + t.Fatalf("waiter %d did not get the load's grid", i) + } + } + s.mu.Lock() + n = len(s.loading) + s.mu.Unlock() + if n != 0 || u.total() != 1 || !s.Resident(srtmBox(k)) { + t.Fatalf("after: %d running, %d downloads, resident %v", n, u.total(), s.Resident(srtmBox(k))) + } +} + +func TestSRTMViewContextDetached(t *testing.T) { + k := srtmKey{30, -98} + tile := srtmGridTile(t) + gate := newSRTMGate() + s, u, _ := newSRTMTest(t, 0, func(w http.ResponseWriter, r *http.Request) { + if gate.wait(r) { + w.Write(tile) + } + }) + t.Cleanup(gate.open) + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + if _, err := s.View(ctx, srtmBox(k)); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("View err = %v, want the caller's deadline", err) + } + gate.open() + srtmEventually(t, "the abandoned fetch to be cached", func() bool { return s.Resident(srtmBox(k)) }) + v := srtmMustView(t, s, srtmBox(k)) + srtmWantElev(t, v, 30.5, -97.5, 3600) + if n := u.total(); n != 1 { + t.Fatalf("requests = %d, want 1", n) + } +} + +func TestSRTMConcurrencyCap(t *testing.T) { + tile := srtmConstTile(t, 7, srtmRawBytes, gzip.BestSpeed) + var inflight, peak atomic.Int32 + gate := newSRTMGate() + s, u, _ := newSRTMTest(t, 0, func(w http.ResponseWriter, r *http.Request) { + n := inflight.Add(1) + defer inflight.Add(-1) + for p := peak.Load(); n > p && !peak.CompareAndSwap(p, n); p = peak.Load() { + } + if gate.wait(r) { + w.Write(tile) + } + }) + t.Cleanup(gate.open) + done := make(chan error, 1) + go func() { + _, err := s.View(context.Background(), geoBBox{S: 30.5, W: -97.5, N: 31.5, E: -96.5}) // 4 tiles + done <- err + }() + srtmEventually(t, "two fetches in flight", func() bool { return inflight.Load() == 2 }) + time.Sleep(200 * time.Millisecond) + if n := inflight.Load(); n != 2 { + t.Fatalf("%d fetches in flight, want %d", n, srtmMaxConcurrent) + } + gate.open() + if err := <-done; err != nil { + t.Fatal(err) + } + if u.total() != 4 || peak.Load() != srtmMaxConcurrent { + t.Fatalf("requests = %d, peak concurrency = %d", u.total(), peak.Load()) + } +} + +func TestSRTMLRUEviction(t *testing.T) { + tiles := map[string][]byte{} + key := func(i int) srtmKey { return srtmKey{40, i} } + for i := 0; i < 7; i++ { + tiles[srtmPath(key(i))] = srtmConstTile(t, int16(1000+i), srtmRawBytes, gzip.BestSpeed) + } + s, u, _ := newSRTMTest(t, 4, srtmServe(tiles)) + // LRU mechanics at a small size, below the one-view floor newSRTMSource + // applies to a configured cache (TestPlannerTileCacheHoldsOneView). + s.cache = newLRU[srtmKey, []int16](4, 0, nil) + views := make([]terrainView, 7) + for i := 0; i < 4; i++ { + views[i] = srtmMustView(t, s, srtmBox(key(i))) + } + srtmMustView(t, s, srtmBox(key(0))) // touch: 1 is now least recently used + views[4] = srtmMustView(t, s, srtmBox(key(4))) + if s.Resident(srtmBox(key(1))) || !s.Resident(srtmBox(key(0))) { + t.Fatal("eviction did not drop the least recently used tile") + } + for i := 5; i < 7; i++ { + views[i] = srtmMustView(t, s, srtmBox(key(i))) + if n := srtmCacheLen(s); n != 4 { + t.Fatalf("cache holds %d tiles, want 4", n) + } + } + // Views keep reading their own tiles after eviction. + for i, v := range views { + if v != nil { + srtmWantElev(t, v, 40.5, float64(i)+0.5, float64(1000+i)) + } + } + if n := u.total(); n != 7 { + t.Fatalf("requests = %d, want 7", n) + } +} + +// ─── HTTP client ─────────────────────────────────────────────────────────── + +func TestSRTMNoRedirect(t *testing.T) { + k := srtmKey{30, -98} + tile := srtmGridTile(t) + s, u, _ := newSRTMTest(t, 0, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == srtmPath(k) { + http.Redirect(w, r, "/elsewhere/N30W098.hgt.gz", http.StatusFound) + return + } + w.Write(tile) + }) + v := srtmMustView(t, s, srtmBox(k)) + if n := u.hitsFor("/elsewhere/N30W098.hgt.gz"); n != 0 { + t.Fatalf("redirect followed (%d requests)", n) + } + if m, _ := v.(terrainCoverage).MissingTiles(); m != 1 || srtmCacheLen(s) != 0 || s.cooling() { + t.Fatal("redirect cached as data, not reported missing, or paused downloads") + } +} + +// ─── Missing terrain ─────────────────────────────────────────────────────── + +func TestSRTMViewMissingTiles(t *testing.T) { + good := srtmKey{30, -98} // its northern neighbour 404s + s, _, _ := newSRTMTest(t, 0, srtmServe(map[string][]byte{ + srtmPath(good): srtmConstTile(t, 250, srtmRawBytes, gzip.BestSpeed), + })) + v := srtmMustView(t, s, geoBBox{S: 30.5, W: -97.5, N: 31.5, E: -97.5}) + tc, ok := v.(terrainCoverage) + if !ok { + t.Fatalf("%T does not implement terrainCoverage", v) + } + if m, n := tc.MissingTiles(); m != 1 || n != 2 { + t.Fatalf("MissingTiles = %d of %d, want 1 of 2", m, n) + } + for _, c := range []struct { + lat, lon float64 + want bool + }{ + {30.5, -97.5, false}, // good tile + {31.5, -97.5, true}, // 404 tile + {30.999, -97.5, false}, // just south of the boundary + {31.0, -97.5, true}, // a boundary point belongs to the tile north of it + {32.0, -97.5, true}, // the view's north edge clamps onto the 404 tile + {29.9, -97.5, true}, // outside the view: no data either + {math.NaN(), -97.5, true}, // nonsense + } { + if got := tc.MissingAt(c.lat, c.lon); got != c.want { + t.Errorf("MissingAt(%v, %v) = %v, want %v", c.lat, c.lon, got, c.want) + } + // No data is no elevation: never 0 m, which would read as sea level. + if e, ok := v.ElevationAt(c.lat, c.lon); ok == c.want { + t.Errorf("ElevationAt(%v, %v) = %v, ok=%v; want ok=%v", c.lat, c.lon, e, ok, !c.want) + } + } + srtmWantElev(t, v, 30.5, -97.5, 250) + srtmWantElev(t, v, 30.999, -97.5, 250) + srtmWantNoElev(t, v, 31.5, -97.5) +} + +// A tile with no valid sample decodes to no grid: it is reported missing, has +// no elevation, and never reads as 0 m. +func TestSRTMAllVoidTileIsMissing(t *testing.T) { + k := srtmKey{30, -98} + s, u, clk := newSRTMTest(t, 0, srtmServe(map[string][]byte{ + srtmPath(k): srtmConstTile(t, srtmVoid, srtmRawBytes, gzip.BestSpeed), + })) + v := srtmMustView(t, s, srtmBox(k)) + if m, _ := v.(terrainCoverage).MissingTiles(); m != 1 || srtmCacheLen(s) != 0 || srtmNegLen(s) != 1 { + t.Fatalf("all-void tile: missing=%d cached=%d negative=%d", m, srtmCacheLen(s), srtmNegLen(s)) + } + srtmWantNoElev(t, v, 30.5, -97.5) + clk.add(srtmNegTTL - time.Second) + srtmMustView(t, s, srtmBox(k)) + if n := u.total(); n != 1 { + t.Fatalf("requests = %d, want 1 within %s", n, srtmNegTTL) + } +} + +// A body that stalls mid-download is the network's fault, not the tile's: +// it pauses downloads like any transport error and sets nothing aside. +func TestSRTMBodyTimeoutIsUpstreamFailure(t *testing.T) { + tile := srtmConstTile(t, 7, srtmRawBytes, gzip.BestSpeed) + s, _, _ := newSRTMTest(t, 0, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", strconv.Itoa(len(tile))) + w.WriteHeader(http.StatusOK) + w.Write(tile[:len(tile)/4]) + w.(http.Flusher).Flush() + select { + case <-r.Context().Done(): + case <-time.After(10 * time.Second): + } + }) + c := newSRTMHTTPClient() + c.Timeout = 300 * time.Millisecond + s.client = c + bb := srtmBox(srtmKey{30, -98}) + if _, err := s.View(context.Background(), bb); !errors.Is(err, errTerrainUnavailable) { + t.Fatalf("View err = %v, want errTerrainUnavailable", err) + } + if !s.cooling() || srtmNegLen(s) != 0 || s.Resident(bb) { + t.Fatalf("stalled body: cooling=%v negative=%d", s.cooling(), srtmNegLen(s)) + } +} + +func TestSRTMUpstreamFailedClassification(t *testing.T) { + for _, c := range []struct { + status int + err error + want bool + }{ + {http.StatusTooManyRequests, errors.New("HTTP 429"), true}, + {http.StatusInternalServerError, errors.New("HTTP 500"), true}, + {http.StatusGatewayTimeout, errors.New("HTTP 504"), true}, + {0, &srtmUpstreamError{errors.New("request failed")}, true}, + {http.StatusOK, fmt.Errorf("wrapped: %w", &srtmUpstreamError{io.ErrClosedPipe}), true}, + {http.StatusOK, errors.New("tile shorter than expected"), false}, + {http.StatusFound, errors.New("HTTP 302"), false}, + {http.StatusUnauthorized, errors.New("HTTP 401"), false}, + } { + if got := srtmUpstreamFailed(c.status, c.err); got != c.want { + t.Errorf("srtmUpstreamFailed(%d, %v) = %v, want %v", c.status, c.err, got, c.want) + } + } +} + +func TestSRTMUserAgent(t *testing.T) { + prev := Version + Version = "9.9.9-test" + defer func() { Version = prev }() + s, u, _ := newSRTMTest(t, 0, srtmServe(nil)) + srtmMustView(t, s, srtmBox(srtmKey{30, -98})) + u.mu.Lock() + defer u.mu.Unlock() + if len(u.uas) != 1 || u.uas[0] != "CoreScope/9.9.9-test" { + t.Fatalf("User-Agent = %q", u.uas) + } +} + +func TestSRTMClientConfig(t *testing.T) { + c := newSRTMHTTPClient() + tr, ok := c.Transport.(*http.Transport) + if !ok { + t.Fatalf("transport is %T", c.Transport) + } + if c.Timeout != 30*time.Second || tr.TLSHandshakeTimeout != 5*time.Second { + t.Errorf("timeouts: total %s, TLS %s", c.Timeout, tr.TLSHandshakeTimeout) + } + if tr.Proxy != nil { + t.Error("tile client honours proxy settings") + } + if !tr.DisableCompression { + t.Error("transport may gunzip bodies behind the size cap") + } + if c.CheckRedirect == nil || c.CheckRedirect(nil, nil) != http.ErrUseLastResponse { + t.Error("redirects are followed") + } + if s := newSRTMSource(TerrainConfig{}, srtmTestViewTiles); s.sem != srtmFetchSlots || cap(s.sem) != 2 || s.cache.maxItems != defaultTerrainTileCache { + t.Errorf("source: %d slots (shared %v), %d tiles", cap(s.sem), s.sem == srtmFetchSlots, s.cache.maxItems) + } +} + +// BenchmarkSRTMElevationAt: one lookup on a 3×3-tile view (the planner's +// hot loop samples millions of these per coverage job). +func BenchmarkSRTMElevationAt(b *testing.B) { + grid := make([]int16, srtmSide*srtmSide) + for i := range grid { + grid[i] = int16(i % 3000) + } + v := &srtmView{span: srtmSpan{29, -99, 3, 3}, grids: make([][]int16, 9)} + for i := range v.grids { + v.grids[i] = grid + } + var sink float64 + b.ResetTimer() + for i := 0; i < b.N; i++ { + f := float64(i%100000) / 100000 + e, _ := v.ElevationAt(29+3*f, -99+3*(1-f)) + sink += e + } + if sink < 0 { + b.Fatal(sink) + } +} + +// ─── Fuzz ────────────────────────────────────────────────────────────────── + +func FuzzSRTMPixel(f *testing.F) { + for _, p := range [][2]float64{ + {30.2672, -97.7431}, {0, 0}, {-0.0001, 0.0001}, {31, -98}, {90, 180}, {-90, -180}, + {89.99999999999, 179.99999999999}, {-89.99999999999, -179.99999999999}, + {math.NaN(), 0}, {0, math.NaN()}, {math.Inf(1), math.Inf(-1)}, {1e308, -1e308}, + {5e-324, -5e-324}, {math.Nextafter(31, 30), math.Nextafter(-97, -98)}, + {-0.16666666666666666, 682}, // found by the fuzzer: FMA gave fy = -1.1e-14 + } { + f.Add(p[0], p[1]) + } + grid := make([]int16, srtmSide*srtmSide) + for R := 0; R < srtmSide; R++ { + for C := 0; C < srtmSide; C++ { + grid[R*srtmSide+C] = int16(R + C) + } + } + viewOf := func(sp srtmSpan) *srtmView { + v := &srtmView{span: sp, grids: make([][]int16, sp.count())} + for i := range v.grids { + v.grids[i] = grid + } + return v + } + f.Fuzz(func(t *testing.T, lat, lon float64) { + finite := !math.IsNaN(lat) && !math.IsInf(lat, 0) && !math.IsNaN(lon) && !math.IsInf(lon, 0) + k := srtmKeyOf(lat, lon) + if k.lat < -90 || k.lat > 89 || k.lon < -180 || k.lon > 179 || !srtmNameRE.MatchString(k.name()) { + t.Fatalf("srtmKeyOf(%v, %v) = %+v %q", lat, lon, k, k.name()) + } + row, col, fy, fx := srtmPixel(lat, lon, k) + if row < 0 || row > srtmCells-1 || col < 0 || col > srtmCells-1 || !(fy >= 0 && fy <= 1) || !(fx >= 0 && fx <= 1) { + t.Fatalf("srtmPixel(%v, %v) = %d, %d, %v, %v", lat, lon, row, col, fy, fx) + } + views := []*srtmView{viewOf(srtmSpan{k.lat, k.lon, 1, 1})} + sp, ok := srtmSpanOf(geoBBox{S: lat - 1, W: lon - 1, N: lat + 1, E: lon + 1}) + if ok != finite { + t.Fatalf("srtmSpanOf ok=%v for finite=%v", ok, finite) + } + if ok { + if sp.count() < 1 || sp.count() > 9 || sp.lat0 < -90 || sp.lat0+sp.nLat > 90 || sp.lon0 < -180 || sp.lon0+sp.nLon > 180 { + t.Fatalf("srtmSpanOf around (%v, %v) = %+v", lat, lon, sp) + } + views = append(views, viewOf(sp)) + } + for _, v := range views { + e, ok := v.ElevationAt(lat, lon) + sp := v.span + inside := finite && lat >= float64(sp.lat0) && lat <= float64(sp.lat0+sp.nLat) && + lon >= float64(sp.lon0) && lon <= float64(sp.lon0+sp.nLon) + if ok != inside { + t.Fatalf("ElevationAt(%v, %v) ok=%v on %+v, want %v", lat, lon, ok, sp, inside) + } + if ok && !(e >= 0 && e <= 2*srtmCells) { + t.Fatalf("ElevationAt(%v, %v) = %v outside the grid's range", lat, lon, e) + } + } + }) +} + +// ─── Tile sets (route LOS) ───────────────────────────────────────────────── + +// srtmTileView reads each point from the tile srtmKeyOf names: a point on a +// degree line from the tile north or east of it, which shares that edge. +func TestSRTMTileView(t *testing.T) { + sw, nw, se := srtmKey{30, -98}, srtmKey{31, -98}, srtmKey{30, -97} + v := srtmTileView{ + sw: elevFieldGrid(sw, elevLinear), + nw: elevFieldGrid(nw, elevLinear), + se: nil, // known missing + } + for _, p := range [][2]float64{ + {30.5, -97.5}, {30.123, -97.987}, // inside + {31, -97.5}, // on the 31st parallel: the north tile's south edge + {31.999, -98}, // on the 98th meridian + {30, -98}, // the south-west corner of the set + {31.5, -97.001}, // just inside the north-west tile's east edge + } { + got, ok := v.ElevationAt(p[0], p[1]) + if !ok || math.Abs(got-elevLinear(p[0], p[1])) > 1e-6 { + t.Errorf("ElevationAt(%v, %v) = %v, %v; want %v", p[0], p[1], got, ok, elevLinear(p[0], p[1])) + } + } + for _, p := range [][2]float64{ + {30.5, -96.5}, // tile without data + {30.5, -97}, // its west edge belongs to it, not to the tile west of it + {32.5, -97.5}, // tile not in the set + {29.9, -97.5}, + {math.NaN(), -97.5}, {30.5, math.NaN()}, {91, 0}, {0, -181}, + } { + if got, ok := v.ElevationAt(p[0], p[1]); ok { + t.Errorf("ElevationAt(%v, %v) = %v, want no terrain", p[0], p[1], got) + } + } + // The poles and the antimeridian clamp onto the last tile. + edge := srtmTileView{{89, 179}: elevFlatGrid(7)} + if got, ok := edge.ElevationAt(90, 180); !ok || got != 7 { + t.Errorf("ElevationAt(90, 180) = %v, %v", got, ok) + } +} + +// tiles reports what is resident and how many downloads loading the rest +// would start; await loads them detached and waits a bounded time. +func TestSRTMTilesAndAwait(t *testing.T) { + gated, gone, here, broken := srtmKey{40, 10}, srtmKey{40, 11}, srtmKey{40, 12}, srtmKey{40, 13} + gate := newSRTMGate() + tile := srtmConstTile(t, 77, srtmRawBytes, gzip.BestSpeed) + s, u, clk := newSRTMTest(t, 0, func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case srtmPath(gated): + if gate.wait(r) { + w.Write(tile) + } + case srtmPath(broken): + w.WriteHeader(http.StatusServiceUnavailable) + default: + http.NotFound(w, r) + } + }) + t.Cleanup(gate.open) + s.put(here, elevFlatGrid(5)) + + keys := []srtmKey{gated, gone, here} + charged := 0 + ts, ok := s.tiles(keys, func(starts int) bool { charged += starts; return true }) + if !ok || charged != 2 { + t.Fatalf("first look: ok %v, charged %d for 2 downloads", ok, charged) + } + if len(ts.grids) != 1 || ts.grids[here] == nil || !slices.Equal(ts.need, []srtmKey{gated, gone}) || ts.starts != 2 || len(ts.refused) != 0 { + t.Fatalf("first look: %d resident, need %v, starts %d, refused %v", len(ts.grids), ts.need, ts.starts, ts.refused) + } + got, failed := s.await(context.Background(), ts.need, 200*time.Millisecond) + if g, ok := got[gone]; !ok || g != nil || len(failed) != 0 { + t.Fatalf("404 tile: got %v (%v), failed %v", g, ok, failed) + } + if _, ok := got[gated]; ok { + t.Fatal("a gated tile finished") + } + + // Still downloading: known missing counts as resident, and loading the + // gated tile again would start nothing. + srtmEventually(t, "the gated download", func() bool { return u.hitsFor(srtmPath(gated)) == 1 }) + ts, ok = s.tiles(keys, func(int) bool { t.Error("charged for a tile already downloading"); return true }) + if !ok || len(ts.grids) != 2 || !slices.Equal(ts.need, []srtmKey{gated}) || ts.starts != 0 { + t.Fatalf("second look: %d resident, need %v, starts %d", len(ts.grids), ts.need, ts.starts) + } + // A caller that went away returns at once, and the download goes on. + ctx, cancel := context.WithCancel(context.Background()) + cancel() + start := time.Now() + if got, failed := s.await(ctx, []srtmKey{gated}, time.Minute); len(got) != 0 || len(failed) != 0 || time.Since(start) > 5*time.Second { + t.Fatalf("cancelled: got %d, failed %d after %s", len(got), len(failed), time.Since(start)) + } + gate.open() + got, _ = s.await(context.Background(), []srtmKey{gated}, 10*time.Second) + if g := got[gated]; len(g) != srtmSide*srtmSide || g[0] != 77 || u.hitsFor(srtmPath(gated)) != 1 { + t.Fatalf("gated tile: %d samples, fetched %d times", len(g), u.hitsFor(srtmPath(gated))) + } + if ts = srtmLook(s, keys); len(ts.need) != 0 || ts.starts != 0 { + t.Fatalf("all resident: need %v", ts.need) + } + + // A failed download is reported as failed and pauses every download. + if _, failed := s.await(context.Background(), []srtmKey{broken}, 10*time.Second); !failed[broken] { + t.Fatalf("503 tile not failed: %v", failed) + } + // Paused: nothing would start, so every download is refused and none is + // counted, or charged. + paused := []srtmKey{broken, {41, 10}} + if ts = srtmLook(s, paused); len(ts.need) != 0 || ts.starts != 0 || !slices.Equal(ts.refused, paused) { + t.Fatalf("after a 503: need %v, starts %d, refused %v", ts.need, ts.starts, ts.refused) + } + clk.add(srtmBackoff[0]) + if ts = srtmLook(s, paused); ts.starts != 2 || len(ts.refused) != 0 { + t.Fatalf("cooldown did not lapse: starts %d, refused %v", ts.starts, ts.refused) + } + // A refused charge starts nothing: the tiles are still to start. + hits := u.total() + if ts, ok := s.tiles(paused, func(int) bool { return false }); ok || terrainStarts(s, srtmBox(paused[1])) != 1 || u.total() != hits { + t.Fatalf("refused charge: ok %v, need %v, %d downloads", ok, ts.need, u.total()-hits) + } +} + +// ─── Real tile server (opt-in) ───────────────────────────────────────────── + +func TestSRTMRealBucketAustin(t *testing.T) { + if os.Getenv("CORESCOPE_NET_TESTS") != "1" { + t.Skip("set CORESCOPE_NET_TESTS=1 to fetch a real SRTM tile") + } + s := newSRTMSource(TerrainConfig{}, srtmTestViewTiles) + s.sem = make(chan struct{}, srtmMaxConcurrent) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + v, err := s.View(ctx, geoBBox{S: 30.2, W: -97.8, N: 30.4, E: -97.7}) + if err != nil { + t.Fatal(err) + } + for _, p := range []struct{ lat, lon, want float64 }{{30.2672, -97.7431, 149}, {30.3207, -97.7735, 213}} { + got, ok := v.ElevationAt(p.lat, p.lon) + t.Logf("(%v, %v) = %.1f m", p.lat, p.lon, got) + if !ok || math.Abs(got-p.want) > 15 { + t.Errorf("ElevationAt(%v, %v) = %.1f, %v; want %.0f ± 15", p.lat, p.lon, got, ok, p.want) + } + } +} + +// Real rugged tiles (Sierra Nevada, Alps) gzip to 14-17 MB. A 12 MiB cap +// refused them and, worse, paused every download for a minute. A tile in +// that range must load. +func TestSRTMRuggedTileOverOldCapLoads(t *testing.T) { + rugged := srtmTestGzip(t, "rugged-15mb", gzip.BestSpeed, func(w io.Writer) error { + rng := rand.New(rand.NewPCG(5, 5)) + row := make([]byte, srtmRawRowBytes) + for r := 0; r < srtmRawSide; r++ { + if r%4 != 3 { // 3 rows in 4 incompressible: ~15 MB of gzip + for c := 0; c < srtmRawSide; c++ { + binary.BigEndian.PutUint16(row[2*c:], uint16(rng.IntN(2000))) + } + } else { + clear(row) + } + if _, err := w.Write(row); err != nil { + return err + } + } + return nil + }) + if len(rugged) <= 12<<20 || len(rugged) >= srtmMaxGzipBytes { + t.Fatalf("test tile is %d bytes, want between 12 MiB and the cap", len(rugged)) + } + s, _, _ := newSRTMTest(t, 0, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", strconv.Itoa(len(rugged))) + w.Write(rugged) + }) + k := srtmKey{36, -119} + if _, err := s.View(context.Background(), srtmBox(k)); err != nil { + t.Fatalf("View err = %v", err) + } + if !s.Resident(srtmBox(k)) { + t.Fatal("rugged tile not cached") + } +} diff --git a/cmd/server/types.go b/cmd/server/types.go index 7ea74919d..29724e1d4 100644 --- a/cmd/server/types.go +++ b/cmd/server/types.go @@ -98,11 +98,25 @@ type StatsResponse struct { // ─── Scope Stats ─────────────────────────────────────────────────────────────── +// ScopeStatsSummary invariants (#2364): +// +// transportTotal = scoped + unscopedTransport (routes 0, 3) +// unscoped = unscopedTransport + unscopedFlood + unscopedDirect +// total = scoped + unscoped (routes 0-3) +// +// Unscoped has folded in the non-transport routes since #1838, so it is +// compared against Total, not TransportTotal. The three Unscoped* fields +// split it by route so a client can, for example, look at unscoped floods +// only (DIRECT traffic is not subject to flood-region filtering). type ScopeStatsSummary struct { - TransportTotal int `json:"transportTotal"` - Scoped int `json:"scoped"` - Unscoped int `json:"unscoped"` - UnknownScope int `json:"unknownScope"` + Total int `json:"total"` + TransportTotal int `json:"transportTotal"` + Scoped int `json:"scoped"` + Unscoped int `json:"unscoped"` + UnscopedTransport int `json:"unscopedTransport"` + UnscopedFlood int `json:"unscopedFlood"` + UnscopedDirect int `json:"unscopedDirect"` + UnknownScope int `json:"unknownScope"` } type ScopeRegionCount struct { @@ -1120,6 +1134,11 @@ type ClientConfigResponse struct { // Present only when user management is on, so the payload is unchanged // for every instance that leaves it off. UserManagement *ClientUserManagement `json:"userManagement,omitempty"` + // Present only when los.enabled: the map route view's line-of-sight + // defaults (los_config.go). + LOS *LOSClientConfig `json:"los,omitempty"` + // Present only when planner.enabled (planner_config.go). + Planner *PlannerClientConfig `json:"planner,omitempty"` } // ClientUserManagement tells the frontend that accounts exist, and whether diff --git a/cmd/server/websocket.go b/cmd/server/websocket.go index fe28afdd8..2e643cc79 100644 --- a/cmd/server/websocket.go +++ b/cmd/server/websocket.go @@ -380,22 +380,30 @@ func NewPoller(db *DB, hub *Hub, interval time.Duration) *Poller { return &Poller{db: db, hub: hub, interval: interval, stop: make(chan struct{})} } -func (p *Poller) Start() { - lastID := p.db.GetMaxTransmissionID() - lastObsID := p.db.GetMaxObservationID() - // If the store already loaded data, use its max IDs as a floor. - // This prevents replaying the entire DB when the DB query fails - // (e.g., corrupted DB returns 0 from COALESCE). - if p.store != nil { - if storeMax := p.store.MaxTransmissionID(); storeMax > lastID { - lastID = storeMax - } - if storeMaxObs := p.store.MaxObservationID(); storeMaxObs > lastObsID { - lastObsID = storeMaxObs - } +// pollFailure logs a failing poll once per streak of failures, and once when +// it recovers. Owned by the Start goroutine. +type pollFailure struct { + what string + failing bool +} + +func (f *pollFailure) note(err error, cursor int) { + switch { + case err != nil && !f.failing: + f.failing = true + log.Printf("[poller] %s poll failed, retrying from id %d each tick: %v", f.what, cursor, err) + case err == nil && f.failing: + f.failing = false + log.Printf("[poller] %s poll recovered at id %d", f.what, cursor) } +} + +func (p *Poller) Start() { + lastID, lastObsID := p.startCursors() log.Printf("[poller] starting from transmission ID %d, obs ID %d, interval %v", lastID, lastObsID, p.interval) + txFail := pollFailure{what: "transmission"} + obsFail := pollFailure{what: "observation"} ticker := time.NewTicker(p.interval) defer ticker.Stop() @@ -407,11 +415,18 @@ func (p *Poller) Start() { // new observation must be known before it is broadcast. refreshRadioHistory(p.db.conn, false) // Ingest new transmissions into in-memory store and broadcast - newTxs, newMax := p.store.IngestNewFromDB(lastID, 100) + // On error newMax is lastID: the same rows are read next tick. + newTxs, newMax, err := p.store.ingestNewFromDB(lastID, 100) + txFail.note(err, lastID) if newMax > lastID { lastID = newMax } - // Ingest new observations for existing transmissions (fixes #174) + // Ingest new observations for existing transmissions (fixes #174). + // The bound below is read BEFORE ingestNewObservations polls the + // advert feed, which waits on advertEvidenceMu while a startup + // chunk sits between its query and its merge. So an observation + // of a transmission that chunk has not merged yet is either read + // after the merge or lies above the bound, never skipped below it. nextObsID := lastObsID if err := p.db.conn.QueryRow(` SELECT COALESCE(MAX(id), ?) FROM ( @@ -422,8 +437,10 @@ func (p *Poller) Start() { )`, lastObsID, lastObsID).Scan(&nextObsID); err != nil { nextObsID = lastObsID } - newObs := p.store.IngestNewObservations(lastObsID, 500) - if nextObsID > lastObsID { + newObs, err := p.store.ingestNewObservations(lastObsID, 500) + obsFail.note(err, lastObsID) + // A failed read saw none of these rows: keep the cursor. + if err == nil && nextObsID > lastObsID { lastObsID = nextObsID } if len(newTxs) > 0 { @@ -471,6 +488,37 @@ func (p *Poller) Start() { } } +// startCursors picks the ids polling starts above. A fresh MAX(id) here would +// skip every row committed between the load's last snapshot and now: it is in +// neither the store nor any later poll. So with a store, polling starts at the +// high-water marks taken before the load. Rows between a mark and the end of +// the load are read again and dedupe: transmissions by hash, observations by +// byObsID or observer+path, and only rows new to the store are broadcast. +func (p *Poller) startCursors() (lastID, lastObsID int) { + if p.store == nil { + return p.db.GetMaxTransmissionID(), p.db.GetMaxObservationID() + } + txMark, obsMark, ok := p.store.StartupMarks() + if ok { + lastID, lastObsID = txMark, obsMark + } else { + // No marks: keep the old fresh-MAX start, floored by the store so a + // failed query (COALESCE 0) cannot replay the whole DB. + lastID, lastObsID = p.db.GetMaxTransmissionID(), p.db.GetMaxObservationID() + if storeMaxObs := p.store.MaxObservationID(); storeMaxObs > lastObsID { + lastObsID = storeMaxObs + } + } + // The loaded max transmission id is a safe floor: one writer commits ids + // in order, so every lower id was visible to the chunk that loaded it. + // The loaded max observation id is not: a chunk-1 transmission can gain + // an observation after chunk 1 whose id is below one loaded in chunk 2. + if storeMax := p.store.MaxTransmissionID(); storeMax > lastID { + lastID = storeMax + } + return lastID, lastObsID +} + func (p *Poller) Stop() { close(p.stop) } diff --git a/cmd/server/websocket_test.go b/cmd/server/websocket_test.go index fbdd62106..17bf337d6 100644 --- a/cmd/server/websocket_test.go +++ b/cmd/server/websocket_test.go @@ -454,3 +454,31 @@ func TestHubDefaultPingInterval(t *testing.T) { t.Fatalf("pingInterval = %v, want 30s (public/app.js WS_STALE_MS depends on it)", got) } } + +// UIs cached from before the UI moved its WebSocket to /ws still connect on +// "/": wsOrStatic upgrades any path the static handler serves. Keep that +// until those clients are gone; this pins it. +func TestWebSocketUpgradeOnRootStillWorks(t *testing.T) { + hub := NewHub() + static := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte("static")) + }) + srv := httptest.NewServer(wsOrStatic(hub, static)) + defer srv.Close() + + conn, resp, err := websocket.DefaultDialer.Dial("ws"+srv.URL[4:]+"/", nil) + if err != nil { + t.Fatalf("dial /: %v", err) + } + defer conn.Close() + if resp.StatusCode != http.StatusSwitchingProtocols { + t.Fatalf("dial /: status %d, want 101", resp.StatusCode) + } + deadline := time.Now().Add(2 * time.Second) + for hub.ClientCount() != 1 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + if hub.ClientCount() != 1 { + t.Errorf("expected the root connection to register with the hub, got %d clients", hub.ClientCount()) + } +} diff --git a/cmd/server/ws_limits.go b/cmd/server/ws_limits.go index 9638b9e33..cad3dc81a 100644 --- a/cmd/server/ws_limits.go +++ b/cmd/server/ws_limits.go @@ -146,6 +146,37 @@ func ipInAny(ip net.IP, nets []*net.IPNet) bool { // reverse proxy whose X-Forwarded-For we are not allowed to believe, so every // visitor looks identical and per-IP limits would punish the wrong people. func (l *wsLimiter) clientIP(r *http.Request) (ip net.IP, distinct bool) { + return l.resolveClientIP(r, false) +} + +// clientIPRightmost is clientIP for limits that protect an upstream quota. It +// walks X-Forwarded-For from the right, skipping hops inside trustedProxies; +// the first untrusted hop is the client. A client can prepend any value it +// likes to the header, but it cannot make a trusted proxy append anything but +// the address that connected, so the rightmost untrusted entry cannot be +// forged. An unparseable entry ends the walk at the peer, since it cannot be +// attributed to any proxy. distinct has the same meaning as for clientIP. +// +// The result is key-ready: an IPv6 address is masked to its /64, because a +// single subscriber is routinely delegated a whole /64 and keying on the full +// address would hand it 2^64 buckets. IPv4 is unchanged. +func (l *wsLimiter) clientIPRightmost(r *http.Request) (ip net.IP, distinct bool) { + ip, distinct = l.resolveClientIP(r, true) + return maskIPv6To64(ip), distinct +} + +var ipv6Mask64 = net.CIDRMask(64, 128) + +// maskIPv6To64 truncates a native IPv6 address to its /64 network. IPv4 and +// IPv4-mapped addresses (To4 != nil) are returned as they are. +func maskIPv6To64(ip net.IP) net.IP { + if ip == nil || ip.To4() != nil { + return ip + } + return ip.Mask(ipv6Mask64) +} + +func (l *wsLimiter) resolveClientIP(r *http.Request, rightmost bool) (ip net.IP, distinct bool) { host, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { host = r.RemoteAddr @@ -155,15 +186,19 @@ func (l *wsLimiter) clientIP(r *http.Request) (ip net.IP, distinct bool) { return nil, false } if ipInAny(peer, l.trustedProxies) { - // First hop is the client; later hops were appended by intermediaries - // we have no reason to trust individually. - if xff := r.Header.Get("X-Forwarded-For"); xff != "" { + if rightmost { + if fwd := rightmostUntrusted(r.Header.Values("X-Forwarded-For"), l.trustedProxies); fwd != nil { + return fwd, true + } + } else if xff := r.Header.Get("X-Forwarded-For"); xff != "" { + // First hop is the client; later hops were appended by + // intermediaries we have no reason to trust individually. first := strings.TrimSpace(strings.Split(xff, ",")[0]) if fwd := net.ParseIP(first); fwd != nil { return fwd, true } } - // A trusted proxy that forwarded no XFF still identifies itself. + // A trusted proxy that forwarded no usable XFF still identifies itself. return peer, true } if peer.IsLoopback() || peer.IsPrivate() || peer.IsLinkLocalUnicast() { @@ -172,6 +207,47 @@ func (l *wsLimiter) clientIP(r *http.Request) (ip net.IP, distinct bool) { return peer, true } +// parseXFFHop parses one X-Forwarded-For entry. Some proxies write "ip:port" +// or "[v6]:port", and a bare IPv6 may be wrapped in brackets; all of those are +// accepted. Returns nil when the entry is not an address. +func parseXFFHop(raw string) net.IP { + e := strings.TrimSpace(raw) + if ip := net.ParseIP(e); ip != nil { + return ip + } + if host, _, err := net.SplitHostPort(e); err == nil { + e = host + } + if len(e) > 2 && e[0] == '[' && e[len(e)-1] == ']' { + e = e[1 : len(e)-1] + } + return net.ParseIP(e) +} + +// rightmostUntrusted returns the last X-Forwarded-For entry (across all +// header lines) that is not a trusted proxy. When every entry is trusted it +// returns the leftmost one (nginx real_ip_recursive), so clients inside a +// trusted range are still told apart. It returns nil when the header is +// empty or an entry reached by the walk is unparseable. +func rightmostUntrusted(values []string, trusted []*net.IPNet) net.IP { + if len(values) == 0 { + return nil + } + hops := strings.Split(strings.Join(values, ","), ",") + var leftmost net.IP + for i := len(hops) - 1; i >= 0; i-- { + ip := parseXFFHop(hops[i]) + if ip == nil { + return nil + } + if !ipInAny(ip, trusted) { + return ip + } + leftmost = ip + } + return leftmost +} + // allow decides whether an upgrade may proceed. On rejection it returns the // reason. On success it returns a release func the caller MUST invoke when // the connection ends, so the concurrent-connection count comes back down. diff --git a/config.example.json b/config.example.json index 079c1d78c..85a9e8488 100644 --- a/config.example.json +++ b/config.example.json @@ -47,7 +47,7 @@ "upgradesPerMinPerIP": 30, "_comment_upgradesPerMinPerIP": "#1794 - handshakes per minute from one client address. On by default. Safe under CGNAT: a real client upgrades a handful of times per minute even while reconnecting, so 30 leaves ordinary traffic alone while flattening a scraper reconnect loop. Set 0 to disable.", "trustedProxies": [], - "_comment_trustedProxies": "#1794 - addresses or CIDRs of YOUR reverse proxy. REQUIRED for the per-IP limits to do anything behind nginx/Caddy/Traefik/ingress: without it every visitor shares the proxy's address, so the limits are skipped and one warning is logged at startup. X-Forwarded-For is believed only from these addresses, because anyone else can forge it. Never list an address you do not control.", + "_comment_trustedProxies": "#1794 - addresses or CIDRs of YOUR reverse proxy. REQUIRED for the per-IP limits to do anything behind nginx/Caddy/Traefik/ingress: without it every visitor shares the proxy's address, so the limits are skipped and one warning is logged at startup. X-Forwarded-For is believed only from these addresses, because anyone else can forge it. Never list an address you do not control. A listed proxy MUST append to X-Forwarded-For (nginx: proxy_add_x_forwarded_for); if you list a CDN, anyone who can send from inside its ranges can choose the hop used.", "deny": [], "_comment_deny": "#1794 - addresses or CIDRs refused at the /ws upgrade, before the handshake. Accepts both \"1.2.3.4\" and \"1.2.3.0/24\". Applies even behind an unconfigured proxy, since it is your explicit instruction. Rejections are counted in /api/stats under websocket.rejectedDeny." }, @@ -378,6 +378,29 @@ "_comment_compareRadiusKm": "A node whose frequency, SF or bandwidth differs from a clear majority (at least half, no tie, at least 3 nodes) of the nodes within compareRadiusKm on the same band (within 30 MHz) gets a LoRa badge in the Nodes list and the 'LoRa: differs from nearby' filter. The coding rate is not compared: the explicit LoRa header carries it, so a CR mismatch still decodes. A separate band next door (433 vs 868 MHz) is never flagged.", "_comment": "Issue #1268. OPT-IN LoRa radio settings (frequency, SF, bandwidth, coding rate) per node, which never travel in packets. Empty nodesUrl (default) = DISABLED: nothing is fetched and /api/rf-params reports enabled=false. To enable set nodesUrl to \"https://map.meshcore.io/api/v1/nodes\" and presetsUrl to \"https://api.meshcore.nz/api/v1/config\" (named presets; optional). The map payload is about 50 MB of JSON (17 MB gzipped); it is fetched after a random 0-60 s startup delay and then every refreshHours, stream-decoded with a 128 MB cap, validated per field, and kept in memory only for adverts younger than maxAgeDays. A failed fetch keeps the previous data; until the first fetch succeeds it is retried after 1, 2, 4, 8 and 16 min, then every 30 min. Adverts dated more than 10 min in the future are dropped. Shown in the node detail panel and on the full node page." }, + "los": { + "_comment": "Radio line-of-sight on the map packet-route view. OPT-IN. Terrain comes from the terrain block (SRTM tiles shared with the planner); one profile request loads at most 16 tiles. Route LOS and the planner share one per-client tile-download budget (a burst of one full view, then 10 a minute, capped per hour); the startup log prints the exact numbers. frequencyMhz/antennaHeightM/kFactor are the default inputs viewers can change in the profile panel. frequencyMhz: 910.525 is the US default; use 869.618 for EU/UK meshes (set it to your mesh's frequency). The planner reads frequencyMhz and kFactor from this block even when los.enabled is false.", + "enabled": false, + "frequencyMhz": 910.525, + "antennaHeightM": 5, + "kFactor": 1.333 + }, + "planner": { + "_comment": "Repeater planner at #/tools/planner (line of sight between points, best relay site, backbone site suggestions for an area). OPT-IN. Terrain comes from the terrain block (SRTM tiles shared with route LOS). Size limits: maxAreaKm is the largest coverage box side (20-250), nodeMarginKm how far outside the box repeaters still count (10-60), maxLegKm the longest profile/relay leg (10-200). Raise them for sparse regions; the terrain one request may load grows with them (the startup log prints the tile counts and memory). defaultRangeKm must be one of 10,15,20,30,40,50,60 and at most maxLegKm. Antenna heights are the defaults viewers can change. Frequency and k-factor come from the los block (set los.frequencyMhz even if route LOS stays off). userReach: the Users layer of the Coverage tab, P(heard) = 1/(1+exp((ln d - ln d50Km)/slope)) for a handheld at 1.5 m; defaults fitted on 41 Belgian repeaters against drive-test receptions (2026-10); set your own if you have measurements.", + "enabled": false, + "defaultRangeKm": 30, + "newAntennaM": 10, + "existingAntennaM": 5, + "maxAreaKm": 100, + "nodeMarginKm": 30, + "maxLegKm": 100, + "userReach": { "d50Km": 2.7, "slope": 0.30 } + }, + "terrain": { + "_comment": "SRTM terrain shared by route line-of-sight (los) and the repeater planner, so both read the same tiles and give a leg the same verdict. Used only while los.enabled or planner.enabled is true. 1° tiles (~5.6 MB each) are fetched on demand into server memory only (no disk, no DB); downloads are budgeted at 20 tiles/min, 200/h for both features together. tileUrl: base of an SRTM skadi tile tree (/N30/N30W098.hgt.gz), https without a query; the default is AWS Open Data. tileCacheTiles caps resident tiles (~2.9 MB each), 4-200; the cache never holds fewer than the largest single load of an enabled feature (16 tiles for route LOS, 12 for the planner at its default sizes), so a smaller value is raised at startup.", + "tileUrl": "https://s3.amazonaws.com/elevation-tiles-prod/skadi", + "tileCacheTiles": 24 + }, "_comment_knownChannels": "Issue #1323. OPT-IN community-maintained hashtag-channels catalogue. Empty string (default) = DISABLED: no background HTTP fetch is started and GET /api/known-channels returns an empty snapshot. To enable, set knownChannelsUrl to a pinned-SHA URL such as \"https://raw.githubusercontent.com/marcelverdult/meshcore-channels/072bc25b6fc983aa2aa7e9d399a97a5f4899ea71/channels-by-country.json\". The URL should point at the channels-by-country.json shape: {generated_at, license, countries:{cc:[{channel,description,key?}]}}. Always pin to a specific commit SHA (not the moving 'main' branch) so a hostile or compromised future upstream commit cannot be silently fetched by your deployment; periodically bump the pin after reviewing upstream diffs. Fetched in the background every knownChannelsRefreshMs (default 86400000 = 24h). Stored in-memory only — no DB, no disk cache. Surfaced over GET /api/known-channels?region=XX. Cache is fail-soft: a failed refresh keeps the last-known snapshot in place. No credentials are sent.", "batteryThresholds": { "lowMv": 3300, diff --git a/deploy/static/README.md b/deploy/static/README.md new file mode 100644 index 000000000..a7d53f002 --- /dev/null +++ b/deploy/static/README.md @@ -0,0 +1,174 @@ +# Frontend on a static host or CDN + +The CoreScope UI is static files. This directory and `scripts/static/build.sh` +let it be served from Cloudflare Pages or any other static host, while the +existing container keeps serving the API and the classic, embedded UI. This is +the third of the deployment modes in +[docs/deployment.md](../../docs/deployment.md#deployment-modes); the other two +run the UI in a container. + +This is the **anonymous** build (`AUTH=false`): it reads everything a logged-out +visitor can read, live updates included, and links to the classic site for +logging in and admin work. On the server it needs one setting, +`CORS_ALLOWED_ORIGINS` (see [Server](#server)), on a version that includes #2362: +`edge` now, and releases cut from `master` after it. Older servers accept the +origin too, but they hide the `Retry-After` and `X-CoreScope-Load-Status` +headers from it, so the warm-up banner never shows, and they refuse wildcard +preview origins. + +## How it works + +- `public/deployment.js` says where the API is. The embedded UI ships it with + `apiBase: ''` (same origin, as today). `build.sh` rewrites it for the + static build. +- `public/api-base.js` (`window.CSApi`) is the only place that builds API and + WebSocket URLs. A lint rule keeps raw `fetch('/api…')` out of every other file. +- The anonymous build sends no cookies, sends its three JSON `POST`s as + `text/plain` (so the browser sends no preflight), and hides login, account and + admin controls in favour of an "available on classic" link. + +## Building + +```bash +make web API_BASE=https://analyzer.example.org AUTH=false +``` + +writes `dist/web`: `public/` byte for byte, except that every top-level page +(`index.html` and the tool pages) gets the cache buster and `deployment.js` says +where the API is. Serve that folder at the root of a hostname; the UI uses +absolute paths such as `/icons/…`. `_headers` holds the cache rules: the pages +and `deployment.js` always revalidate, while everything they load carries +`?v=`. Cloudflare Pages and Netlify read it; other hosts need the same +rules in their own config. The variables are in step 6 below and at the top of +`scripts/static/build.sh`. + +## Deploying from a fork + +This repository is the software, not any one CoreScope instance: it has no +Pages project and deploys nothing. Each instance (a region, the flagship) +deploys from its own fork. Pages needs that anyway: its GitHub App is installed +on a repository you administer. + +The fork carries **no code changes**. Every setting lives in the Pages project +variables, and deploying means moving a branch to a commit that already exists +upstream. + +### One-time setup + +1. Fork this repository into an account or org your maintainers administer. +2. In the fork, turn GitHub Actions off (Settings → Actions). Otherwise syncing + `master` runs this repository's CI and deploy workflows there, which fail + without its secrets. Pages builds do not use Actions. +3. Create the deploy branches `stage` and `prod`, and protect `prod` so only + maintainers can move it. +4. Install the Cloudflare Pages GitHub App on the fork only. +5. Create one Pages project per deploy branch, on the Free plan: + + | Project | Production branch | Serves | API | + |---|---|---|---| + | e.g. `corescope-web-stage` | `stage` | your staging frontend | your staging server | + | e.g. `corescope-web-prod` | `prod` | your production frontend | your production server | + + For both: + - build command: `bash scripts/static/build.sh`; + - build output directory: `dist/web`; root directory: blank (the + repository root holds files over Pages' 25 MiB limit); + - preview branches: None, or All to get a preview of every other branch + pushed to the fork (see Previews below). + + One project on `prod` is enough if you have no staging server. +6. Environment variables (Production environment, and Preview too if previews + are on) for each project: + + | Name | Example | Notes | + |---|---|---| + | `API_BASE` | `https://analyzer.example.org` | The CoreScope server. https, lowercase, no path | + | `AUTH` | `false` | Required, no default. Must be `false`: the server allows no credentialed CORS, so `build.sh` refuses `true` with a cross-origin `API_BASE` | + | `CHANNEL` | `beta` | `beta`, `next` or `dev` show a badge; `static` shows none | + | `CLASSIC_URL` | `https://analyzer.example.org` | Optional. Target of the "Open in classic" links | + | `SKIP_DEPENDENCY_INSTALL` | `1` | `build.sh` needs no npm packages | + + `COMMIT` defaults to the first 7 characters of `CF_PAGES_COMMIT_SHA`. +7. Add a custom domain to each project (for example `beta.example.org`). The + UI uses absolute paths such as `/icons/…`, so it must be served at the root + of a hostname. + +### Deploying + +Keep each frontend on the version its server runs: `prod` on the release tag +your production containers run, `stage` on upstream `master` if staging runs +the master image. Upgrade the server first, then move the branch. Move branches +by fast-forward, so they stay identical to upstream commits (`upstream` is this +repository, `region` is your fork, and `vX.Y.Z` is the release your production +server runs): + +```bash +git fetch upstream --tags +git push region vX.Y.Z:refs/heads/prod +git push region upstream/master:refs/heads/stage +``` + +Releases up to v3.16.0 predate `scripts/static/build.sh` and have nothing to +build, so `prod` can only follow releases cut after it. + +Only move `stage` to a `master` commit whose CI passed. A pull request into +`prod` also works if you want a review step, but its merge commits make the +branch drift from upstream. Each project builds only when its branch moves. + +### Previews + +With preview branches on, every other branch pushed to the fork, and every pull +request between branches of the fork, gets its own deployment at +`..pages.dev` plus a branch alias such as +`my-branch..pages.dev`. Set `CHANNEL=dev` in the Preview environment +so previews show the Dev badge. Pull requests to this repository come from +forks and get no preview. + +A preview is code from a branch, so keep previews anonymous (`AUTH=false`), +pointed at a staging server if you have one. + +## Server + +Append the static origin to the embed CORS list and restart: + +```bash +# Keep every origin already listed; add the static one exactly. Never "*". +CORS_ALLOWED_ORIGINS=https://existing-embed.example.org,https://beta.example.org +``` + +- The env var replaces `corsAllowedOrigins` from `config.json`, so it must list + every origin, old and new. +- An entry is an exact origin: lowercase, scheme included, no trailing slash. +- For previews, also list `https://.pages.dev` and + `https://*..pages.dev` (wildcard labels need a server with #2362; see + `config.example.json`). The wildcard matches one label only, and the server + refuses `https://*.pages.dev`. +- The same list admits the origin to `/ws`. A `*` entry does not work for `/ws`. + +Check it: + +```bash +curl -sI -H "Origin: https://beta.example.org" https://analyzer.example.org/api/stats | grep -i access-control-allow-origin +``` + +It must print the origin, and no `Access-Control-Allow-Credentials` line. + +## Local and CI + +```bash +make dev-split +``` + +The UI on `http://localhost:8788` calls an API-only server on +`http://localhost:3000` cross-origin, with no proxy. CI runs +`tests/e2e/test-split-anonymous-e2e.js` the same way on E2E shard 1. Pull requests +to this repository get no preview deployment; this is how to try one. + +## Roll back + +- **The UI:** in the Pages dashboard, roll back to the previous deployment, or + move the deploy branch back to the previous release tag + (`git push --force-with-lease region vX.Y.Z:refs/heads/prod`). +- **Access from the static origin:** remove it from `CORS_ALLOWED_ORIGINS` and + restart. The static UI then shows "Can't reach the CoreScope API"; the classic + UI and embeds are unaffected. diff --git a/deploy/static/_headers b/deploy/static/_headers new file mode 100644 index 000000000..56aa174bd --- /dev/null +++ b/deploy/static/_headers @@ -0,0 +1,19 @@ +# Copied into the static build by scripts/static/build.sh. Cloudflare Pages +# and Netlify read it; other hosts ignore it and need the same rules in their +# own config (the web container's are in docker/web/Caddyfile). The pages and +# deployment.js change on every deploy without a ?v= buster, so a browser must +# always revalidate them. Every local script and stylesheet a page loads +# carries ?v= (vendor/ files carry their version in the path), so +# those may use the host's default caching. +/ + Cache-Control: no-cache, no-store, must-revalidate +/index.html + Cache-Control: no-cache, no-store, must-revalidate +/area-map.html + Cache-Control: no-cache, no-store, must-revalidate +/geofilter-builder.html + Cache-Control: no-cache, no-store, must-revalidate +/geofilter-docs.html + Cache-Control: no-cache, no-store, must-revalidate +/deployment.js + Cache-Control: no-cache, no-store, must-revalidate diff --git a/docker-compose.split.yml b/docker-compose.split.yml new file mode 100644 index 000000000..bdf90546d --- /dev/null +++ b/docker-compose.split.yml @@ -0,0 +1,99 @@ +# CoreScope — split containers: the UI in its own web container and the +# server in the usual image. +# +# The web container (Dockerfile.web, Caddy) serves the static UI and forwards +# /api and /ws to the server, so both share one origin: no CORS settings. With +# user management on, set the server's userManagement.publicBaseUrl to the web +# container's public origin (scheme and port included): logins and other +# writes are checked against it. The server container is unchanged and still +# serves everything, the classic UI included, on port 3000 inside the compose +# network; publish it too if you want to reach that directly. For per-IP +# limits, the server trusts the web container's fixed address: see networks. +# +# Usage: CORESCOPE_IMAGE=ghcr.io/kpa-clawbot/corescope:edge \ +# docker compose -f docker-compose.split.yml up -d --build +# Docs: docs/deployment.md, "Deployment modes" +# +# Variables (shell or .env): +# CORESCOPE_IMAGE required: the server image of the same version as this +# checkout, which the web image is built from. :edge on +# master, :vX.Y.Z on a release tag. There is no default, so +# a release server is never paired with a newer UI unasked. +# DATA_DIR the server's data directory. Default ./data +# HTTP_PORT default 80; HTTPS_PORT default 443 (TCP and UDP) +# SITE_ADDRESS :80 (default), or a domain name for automatic HTTPS, which +# needs the default ports: certificate issuance and the +# HTTP/3 advertisement both assume 80 and 443 +# GIT_COMMIT the UI's cache buster; default the build time +# CHANNEL static (default), or beta, next, dev for a badge +# MQTT_BIND where the server's built-in broker is published. Default +# 127.0.0.1: it accepts anonymous clients, so set 0.0.0.0 +# only to let gateways on a network you trust publish to it. +# MQTT_PORT default 1883 +# SPLIT_NET the compose network's /24, as its first three octets. +# Default 172.30.83, which puts the web container at +# 172.30.83.200. Change it only if Docker reports that the +# pool overlaps another network, and update the server's +# trustedProxies to match. + +services: + corescope: + image: ${CORESCOPE_IMAGE:?set CORESCOPE_IMAGE to the server image of this checkout's version, e.g. ghcr.io/kpa-clawbot/corescope:edge on master or :vX.Y.Z on a release tag} + ports: + - "${MQTT_BIND:-127.0.0.1}:${MQTT_PORT:-1883}:1883" + volumes: + - ${DATA_DIR:-./data}:/app/data + environment: + - DISABLE_CADDY=true + - DISABLE_MOSQUITTO=${DISABLE_MOSQUITTO:-false} + restart: unless-stopped + healthcheck: + test: ["CMD", "wget", "-qO-", "http://localhost:3000/api/healthz"] + interval: 30s + timeout: 5s + retries: 3 + + web: + build: + context: . + dockerfile: Dockerfile.web + args: + GIT_COMMIT: ${GIT_COMMIT:-} + CHANNEL: ${CHANNEL:-static} + image: corescope-web:latest + ports: + - "${HTTP_PORT:-80}:80" + - "${HTTPS_PORT:-443}:443" + # HTTP/3: Caddy advertises it on 443 when SITE_ADDRESS is a domain. + - "${HTTPS_PORT:-443}:443/udp" + volumes: + - web-caddy-data:/data + environment: + - BACKEND=corescope:3000 + - SITE_ADDRESS=${SITE_ADDRESS:-:80} + networks: + default: + # The one address the server's trustedProxies lists; see networks. + ipv4_address: "${SPLIT_NET:-172.30.83}.200" + depends_on: + - corescope + restart: unless-stopped + +networks: + # A fixed subnet gives the web container a fixed address, so the server's + # webSocket.trustedProxies and userManagement.trustedProxies can list it + # alone (172.30.83.200 by default) and still match after a recreate. Never + # list the whole subnet: it holds the gateway address too, and a client + # that reaches a published port 3000 through Docker's proxy arrives from + # there, so its own X-Forwarded-For would be believed. + default: + ipam: + config: + - subnet: "${SPLIT_NET:-172.30.83}.0/24" + # Automatic addresses come from the lower half, so no container + # can take the web container's. + ip_range: "${SPLIT_NET:-172.30.83}.0/25" + +volumes: + # Caddy's TLS certificates when SITE_ADDRESS is a domain name. + web-caddy-data: diff --git a/docker/web/Caddyfile b/docker/web/Caddyfile new file mode 100644 index 000000000..7e259cc8f --- /dev/null +++ b/docker/web/Caddyfile @@ -0,0 +1,23 @@ +# The web container (Dockerfile.web): the static UI from /srv, with the API +# and the WebSocket forwarded to the CoreScope server, so both share this +# origin. BACKEND is the server's host:port; SITE_ADDRESS is ":80" for plain +# HTTP, or a domain name for automatic HTTPS. +# +# Caddy adds X-Forwarded-For. To keep the server's per-IP limits behind this +# proxy, list its address in webSocket.trustedProxies (and +# userManagement.trustedProxies) in the server's config.json. + +{$SITE_ADDRESS::80} { + encode zstd gzip + + @backend path /api/* /ws + reverse_proxy @backend {$BACKEND} + + # The same rules as deploy/static/_headers: these change on every deploy + # without a ?v= buster, so a browser must always revalidate them. + @nocache path / /index.html /area-map.html /geofilter-builder.html /geofilter-docs.html /deployment.js + header @nocache Cache-Control "no-cache, no-store, must-revalidate" + + root * /srv + file_server +} diff --git a/docs/api-spec.md b/docs/api-spec.md index 3d09e13c6..08026a71e 100644 --- a/docs/api-spec.md +++ b/docs/api-spec.md @@ -36,6 +36,11 @@ - [GET /api/channels](#get-apichannels) - [GET /api/channels/:hash/messages](#get-apichannelshashmessages) - [GET /api/rf-noise](#get-apirf-noise) +- [GET /api/elevation/profile](#get-apielevationprofile) +- [GET /api/planner/profile](#get-apiplannerprofile) +- [GET /api/planner/relay](#get-apiplannerrelay) +- [GET /api/planner/viewshed](#get-apiplannerviewshed) +- [GET /api/planner/coverage](#get-apiplannercoverage) - [GET /api/analytics/rf](#get-apianalyticsrf) - [GET /api/analytics/topology](#get-apianalyticstopology) - [GET /api/analytics/retransmissions](#get-apianalyticsretransmissions) @@ -1433,6 +1438,579 @@ Returned when `bbox` is missing or malformed. --- +## GET /api/elevation/profile + +Terrain elevation along consecutive legs of a route, for the map's line-of-sight +view. Only available when `los.enabled` is `true` in `config.json`; otherwise the +endpoint returns `404`. + +The terrain is the repeater planner's: the same SRTM tiles (the shared [`terrain`](#terrain-tiles) block) sampled the same way as [`/api/planner/profile`](#get-apiplannerprofile), so a leg gets the same heights, and the same verdict, in both views. + +### Query Parameters + +| Param | Type | Default | Description | +|-------|--------|---------|--------------------------------------------------------------------------| +| `pts` | string | - | **Required.** Flat comma list `lat1,lon1,lat2,lon2,...`. 2 to 16 points. Lat in `[-90,90]`, lon in `[-180,180]` | + +### Response `200` + +```json +{"source":"SRTM (AWS Open Data)","legs":[{"distance_km":12.345,"elev_m":[201.4,203.0,207.8,"... N values ..."]},{"distance_km":412.1,"error":"too_long"}]} +``` + +| Field | Description | +|---------------|----------------------------------------------------------------------------------------------| +| `source` | Terrain attribution: `"SRTM (AWS Open Data)"` for the default tiles, otherwise `"SRTM ()"`. The planner reports the same string | +| `legs[i]` | The leg from `pts[i]` to `pts[i+1]` | +| `distance_km` | Great-circle distance of the leg | +| `elev_m` | Terrain height in metres (0.1 m steps), evenly spaced along the great circle from the first point to the second, both ends included. The count varies with the leg: about one sample per 90 m, at least 64 and at most 600. Omitted on error | +| `error` | See below | + +Per-leg failures do not fail the request: a leg with an `error` has no `elev_m`. The codes, checked in this order: + +| Code | Meaning | +|------|---------| +| `too_long` | The leg is longer than 300 km. No terrain is loaded for it | +| `unknown_point` | An endpoint is not a known node (see below). No terrain is loaded for it | +| `too_many_tiles` | The leg's tiles would take the request past 16 distinct 1° terrain tiles. It loads nothing; later legs over tiles already in the request still fit. Split the route to check it | +| `upstream` | A tile the leg needs could not be loaded: tile downloads are paused after a tile-server failure, over their budget, or the download failed. Worth retrying later | +| `no_terrain` | A sample lies in a tile without data (open sea, or a tile the server lacks) | + +### Response `202` + +Some tiles the request needs are still downloading after the server waited about 1.5 s for them. The downloads carry on; re-poll the same URL after `retry_after_s`. Sent with `Retry-After` and `Cache-Control: no-store`. + +```json +{"state":"loading_terrain","progress":0.5,"retry_after_s":2} +``` + +`progress` is the share of the request's tiles already in memory, from `0` to `1`. + +### Known-node rule + +Every point must be the position of a known node that `/api/nodes` shows (GPS set, not 0,0), matched at 5 decimals. A leg with any other endpoint answers `unknown_point` and loads no terrain. This bounds the tiles a client can make the server download to those under real node pairs. The node set is refreshed at most every 60 s, and at once when the node-hiding rules change. + +### Terrain tiles + +Route line of sight and the [repeater planner](#get-apiplannerprofile) read one shared terrain source, configured by the top-level `terrain` block in `config.json`. It is built only while `los.enabled` or `planner.enabled` is `true`. + +| Key | Default | Valid | Meaning | +|-----|---------|-------|---------| +| `terrain.tileUrl` | `https://s3.amazonaws.com/elevation-tiles-prod/skadi` (AWS Open Data) | `https` URL without a query | Base of an SRTM `skadi` tile tree: `/N30/N30W098.hgt.gz` | +| `terrain.tileCacheTiles` | 24 | 4 to 200 | Tiles kept in memory, about 2.9 MB each | + +A value of 0 or a missing key means the default; an invalid value falls back to the default and logs a warning at startup. The cache never holds fewer tiles than the largest single load of an enabled feature (16 for route line of sight, 12 for the planner at its default sizes), so a request never evicts its own tiles; a smaller `tileCacheTiles` is raised at startup and the log says so. + +Tiles are 1 arc-second SRTM, downsampled to 3 arc-seconds (about 90 m) and held in server memory only. Downsampling keeps every third sample, not the highest of each cell, and a leg is sampled at most 600 times, so the spacing grows past 90 m on legs over about 54 km. Both can step over a ridge narrower than the spacing, which leans a verdict towards clear. Nothing is written to disk or the database. Downloads are shared by both features: at most 2 at a time, 20 per minute and 200 per hour. When the planner's size limits let one load span more than 20 tiles (up to 40 at the largest sizes), the per-minute limit is that many and the hourly one five times that, if more than 200, so the largest load can still download in one go. After a `429`, `5xx` or transport error from the tile server, every download pauses for 60 s, then 5 min, 30 min and 1 h for each further consecutive failure; a successful download resets this. A tile the server does not have (`404`, `403`), or one whose body is unusable or all void, has no terrain for a while instead. + +Each client IP also has one download budget for both features, so using both buys no more downloads. A route line-of-sight request, or a new planner job, takes one token for each tile download it starts, all or nothing, before any starts. Tiles already in memory or already downloading (for any client, or for either feature) cost nothing, and neither do downloads the server-wide limits above would refuse. The budget holds the largest single load of an enabled feature (16 tiles for route line of sight, 12 to 40 for the planner depending on its size limits), so any one request fits it, and refills at 10 tokens a minute. A second bucket caps it at 40 tokens an hour, or twice the largest load when that is more, refilled at the same number an hour. The startup log prints the numbers in effect. + +The per-client budgets (this one and the planner's jobs per minute) need clients the server can tell apart. Behind a reverse proxy on a loopback or private address that is not in `webSocket.trustedProxies`, every visitor arrives from the proxy's address, so no client is charged and only the server-wide limits apply; one warning is logged. + +### Caching & limits + +- Terrain comes from SRTM 1° tiles held in server memory (see [Terrain tiles](#terrain-tiles)). Only the tiles the legs' samples fall in are loaded, not each leg's bounding box. A request loads at most 16 distinct tiles. +- `Cache-Control: public, max-age=86400` when every leg is OK or `too_long`; otherwise `no-store`. +- Per client IP, a request takes one token from the client's [download budget](#terrain-tiles), shared with the planner, for each tile download it starts, all or nothing, before any starts. A request that would start more downloads than its tokens allow answers `429` with `Retry-After` and starts none. Tiles already in memory or already downloading (for any client, or for the planner) cost nothing. So do tiles the server-wide download limits have no room for: they are not downloaded, and their legs answer `upstream`. A request whose tiles are all in memory is never limited, and a poll after `202` costs nothing unless the server-wide limits have since made room for a tile they refused. +- The request query may not exceed 2048 bytes. +- Data: SRTM terrain only; trees and buildings are not modelled. The grid is about 90 m and a leg has at most 600 samples, so a narrow ridge can be missed (see [Terrain tiles](#terrain-tiles)): read `clear` as a best case. + +### Response `400` + +Returned when `pts` is missing, has an odd number of values, holds fewer than 2 or more than 16 points, contains a non-numeric value, or has a lat or lon out of range. + +### Response `404` + +Returned when `los.enabled` is not `true` in `config.json`. + +```json +{ "error": "los disabled" } +``` + +### Response `429` + +Returned when the request would start more tile downloads than the client's [download budget](#terrain-tiles) allows. The budget is shared with the planner. The `Retry-After` header gives whole seconds to wait. + +```json +{ "error": "rate limited" } +``` + +--- + +## GET /api/planner/profile + +Line-of-sight profile along a chain of points, for the repeater planner at `#/tools/planner`. The server returns the terrain height along each consecutive leg. Only available when `planner.enabled` is `true` in `config.json`; otherwise the endpoint returns `404`. + +### Common rules + +These rules apply to all planner endpoints: this one, [`/api/planner/relay`](#get-apiplannerrelay), [`/api/planner/viewshed`](#get-apiplannerviewshed) and [`/api/planner/coverage`](#get-apiplannercoverage). + +- **Opt-in.** Only available when `planner.enabled` is `true`. Otherwise the endpoints return `404`, and `/api/config/client` omits the `planner` block. +- **Quantised input.** Points are rounded to 0.001°, antenna heights to 1 m, and `range` must be one of a fixed set. Coverage boxes are snapped outward to a 0.05° grid. Requests that round to the same values share one cache entry and one job. +- **Unknown or repeated parameters.** A parameter the endpoint does not take, a repeated parameter, or a query longer than 512 bytes returns `400`. +- **Terrain.** SRTM 1° tiles, shared with route line of sight (see [Terrain tiles](#terrain-tiles)). A tile that is missing upstream (open sea or no data), unusable or all void has no terrain: relay and area searches skip every site and link that touches it, a profile leg across it is `no_terrain`, and a relay `direct` link across it carries `error: "no_terrain"` with no verdict. +- **Size limits.** Three `config.json` keys set how large a request may be. A value of 0 or a missing key means the default. A value outside the valid range falls back to the default and logs a warning at startup. + + | Key | Default | Valid | Limits | + |-----|---------|-------|--------| + | `planner.maxAreaKm` | 100 | 20 to 250 | Each side of a snapped coverage box | + | `planner.nodeMarginKm` | 30 | 10 to 60 | How far outside the coverage box repeaters and rooms are still read | + | `planner.maxLegKm` | 100 | 10 to 200 | The A to B leg of a profile or relay. Only `range` values up to it are accepted | + + The server derives from these how many 1° terrain tiles one request may load, as the worst case anywhere within latitudes -56 to 60. At the defaults that is 12 tiles for each endpoint. Each resident tile takes about 2.9 MB, so larger limits cost memory, and the terrain cache never holds fewer tiles than one full view. The startup log prints the tile counts, the memory one view and the cache take, and how many tiles the cache has dropped that views still in use may briefly keep in memory (about a minute of downloads). `/api/config/client` reports the sizes in effect. +- **Caveat.** Results are line of sight against bare terrain on a grid of about 90 m, which can miss a narrow ridge (see [Terrain tiles](#terrain-tiles)). Trees, buildings and other clutter are not modelled. The output is not a link budget: it has no transmit power, gain or receiver sensitivity. + +### Job protocol + +The planner runs each request as a background job, one per cache key. A request waits up to about 1.5 s for its job. If the job is still running, the response is `202` and the client re-polls the same URL. + +| Status | Body | Meaning | +|--------|------|---------| +| `200` | The endpoint's result | Finished. Cached on the server for about 10 minutes. Sent with `Cache-Control: public, max-age=300`. | +| `202` | `{"state":"computing","progress":0.42,"retry_after_s":1}` | Job still running. The `Retry-After` header carries the same wait. Re-poll the same URL after `retry_after_s` seconds. | +| `400` | `{"error":"..."}` | Bad input. See the endpoint's error codes. | +| `404` | `{"error":"planner disabled"}` | `planner.enabled` is not `true`. | +| `429` | `{"error":"rate limited"}` | Per-IP limit of 6 new jobs per minute. A new job also takes one token from the client's [download budget](#terrain-tiles), shared with route line of sight, for each tile download its terrain view starts, all or nothing; tiles in memory or already downloading cost nothing. The `Retry-After` header gives whole seconds to wait. Cache hits and polls of a live job are never limited. | +| `503` | `{"error":"planner busy"}` | Too many jobs are live or queued (`planner busy`). The server is shutting down (`planner unavailable`). The terrain fetch for this key failed and is cooling down (`terrain busy`). The `Retry-After` header gives whole seconds to wait. | + +`state` is one of `queued`, `loading_terrain` or `computing`. `progress` runs from `0` to `1`. A job that no client has polled for 15 s is cancelled. + +### Query Parameters + +| Param | Type | Default | Description | +|-------|--------|---------|-------------| +| `pts` | string | - | **Required.** Flat comma list `lat1,lon1,lat2,lon2,...`. 2 to 16 points. Lat in `[-90,90]`, lon in `[-180,180]`. | + +### Response `200` + +```json +{"source":"SRTM (AWS Open Data)","legs":[{"distance_km":12.345,"elev_m":[201.4,203.0,207.8,"... N values ..."]},{"distance_km":118.9,"error":"too_long"}]} +``` + +| Field | Description | +|---------------|-------------| +| `source` | Terrain attribution: `"SRTM (AWS Open Data)"` for the default tiles, otherwise `"SRTM ()"`. Route line of sight reports the same string | +| `legs[i]` | The leg from `pts[i]` to `pts[i+1]`. One entry per leg, in order | +| `distance_km` | Great-circle distance of the leg, rounded to 3 decimals | +| `elev_m` | Terrain height in metres at evenly spaced points along the great circle, both endpoints included, rounded to 0.1 m. The count depends on the leg length (about one sample per 90 m, between 64 and 600). Omitted on error | +| `error` | Omitted on success. Per-leg code, see below | + +Per-leg failures do not fail the request. A leg with an `error` has no `elev_m`. + +### Error codes + +Whole-request `400` messages: + +| Message | Cause | +|---------|-------| +| `pts required` | `pts` is missing | +| `pts must hold 2 to 16 lat,lon points` | Odd number of values, fewer than 2 points or more than 16 | +| `pts contains an invalid or out-of-range number` | A value is not a number, or lat or lon is out of range | +| `too_many_tiles` | The chain needs more 1° terrain tiles than the server loads for one request. Any single leg up to the maximum length within latitudes -56 to 60 fits. Long multi-leg chains may not | + +Per-leg `error` codes (the request still returns `200`): + +| Code | Cause | +|------|-------| +| `too_long` | The leg is longer than `planner.maxLegKm` (100 km by default). No terrain is loaded for it | +| `out_of_area` | An endpoint is not within 50 km of a known node. Legs touching that point are marked | +| `no_terrain` | Terrain for the leg could not be read | + +### Response `400` + +```json +{ "error": "pts must hold 2 to 16 lat,lon points" } +``` + +### Response `404` + +```json +{ "error": "planner disabled" } +``` + +--- + +## GET /api/planner/relay + +Best relay for a link from point A to point B. The server analyses the direct path, then ranks candidate relay sites in two lists: + +- `existing`: known repeaters and rooms from the node store, with an assumed mast height (`planner.existingAntennaM`). +- `open`: sites picked from the terrain, with the new-relay height `hr`. + +Each candidate is checked as two legs, A to relay and relay to B. Common rules and the job protocol are described under [`/api/planner/profile`](#get-apiplannerprofile). + +### Query Parameters + +| Param | Type | Default | Description | +|---------|--------|-------------------------------|-------------| +| `a` | string | - | **Required.** Point A as `lat,lon`. Must be within 50 km of a known node | +| `b` | string | - | **Required.** Point B as `lat,lon`. Same rule as `a` | +| `ha` | number | `planner.newAntennaM` (10) | Antenna height at A, metres. Rounded to 1 m and clamped to 1 to 100 | +| `hb` | number | `planner.newAntennaM` (10) | Antenna height at B, metres. Same limits as `ha` | +| `hr` | number | `planner.newAntennaM` (10) | Height of a new relay at an open site, metres. Same limits as `ha` | +| `range` | number | `planner.defaultRangeKm` (30) | Largest distance in km from the relay to each end. One of `10,15,20,30,40,50,60`, up to `planner.maxLegKm` (the client config's `rangesKm`) | + +The A to B distance is limited to `planner.maxLegKm` (100 km by default). The existing-relay height comes from `planner.existingAntennaM` and is echoed in `params.he`. It is not a query parameter. + +### Response `200` + +```json +{ + "source": "SRTM (AWS Open Data)", + "direct": { + "distance_km": 24.812, + "clearance_pct": -35.2, + "verdict": "blocked", + "worst_km": 9.4, + "obstruction_m": 38.6, + "elev_m": [212.0, 240.5, "... up to 200 values ..."] + }, + "existing": [ + { + "kind": "existing", + "pubkey": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + "name": "Example Hilltop", + "lat": 30.1, + "lon": -97.7, + "elev_m": 312, + "antenna_m": 5, + "leg_a": {"distance_km": 12.1, "clearance_pct": 74.0, "verdict": "clear60", "worst_km": 6.0, "obstruction_m": -8.2}, + "leg_b": {"distance_km": 12.7, "clearance_pct": 61.5, "verdict": "clear60", "worst_km": 5.1, "obstruction_m": -4.0}, + "bottleneck_pct": 61.5 + } + ], + "open": [ + { + "kind": "open", + "lat": 30.2, + "lon": -97.6, + "elev_m": 298, + "antenna_m": 10, + "leg_a": {"distance_km": 11.8, "clearance_pct": 88.0, "verdict": "clear", "worst_km": 4.2, "obstruction_m": -20.1}, + "leg_b": {"distance_km": 12.9, "clearance_pct": 66.3, "verdict": "clear60", "worst_km": 6.7, "obstruction_m": -6.5}, + "bottleneck_pct": 66.3 + } + ], + "params": { + "a": {"lat": 30.1, "lon": -97.7}, + "b": {"lat": 30.2, "lon": -97.5}, + "ha": 10, + "hb": 10, + "hr": 10, + "he": 5, + "range_km": 30, + "frequency_mhz": 910.525, + "k_factor": 1.333 + }, + "warnings": [] +} +``` + +Abbreviated: the `elev_m` arrays in `direct`, `leg_a` and `leg_b` are truncated for readability. A real response includes them in full, and `leg_a`/`leg_b` carry an `elev_m` array as well. + +| Field | Description | +|-------|-------------| +| `source` | Terrain attribution | +| `direct` | The A to B link, see *Link object* below | +| `existing` | Up to 5 known repeaters and rooms, ranked by `bottleneck_pct`, then by total distance | +| `open` | Up to 5 terrain sites, ranked the same way | +| `params` | The quantised inputs the result was computed with, and the mast heights used | +| `warnings` | Human-readable notes, for example `No relay gives a clear first Fresnel zone`. Always an array | + +**Option object** (`existing[]` and `open[]`): + +| Field | Description | +|-------|-------------| +| `kind` | `existing` or `open` | +| `pubkey` | Node public key. Present only for `existing` | +| `name` | Node name. Present only for `existing`, when the node has one | +| `lat`, `lon` | Site position | +| `elev_m` | Terrain height at the site, metres | +| `antenna_m` | Mast height used at the site: `he` for existing, `hr` for open | +| `leg_a`, `leg_b` | Link objects for A to site and site to B. Each carries its own `elev_m` profile | +| `bottleneck_pct` | The weaker of `leg_a.clearance_pct` and `leg_b.clearance_pct` | + +**Link object** (`direct`, `leg_a`, `leg_b`): + +| Field | Description | +|-------|-------------| +| `distance_km` | Great-circle distance of the link | +| `clearance_pct` | 100 × the worst first-Fresnel clearance along the path. Negative means terrain crosses the line | +| `verdict` | `clear` (100% or more), `clear60` (60% or more), `marginal` (0% or more) or `blocked` (below 0%). Empty when `error` is set | +| `worst_km` | Distance along the link to the point with the worst clearance | +| `obstruction_m` | Height of the highest terrain point above the line of sight, metres. Negative means it clears the line | +| `elev_m` | Terrain profile, decimated to at most 200 samples. Present on `direct` and on the option legs, absent when `error` is set | +| `error` | Present only when the link could not be measured: `no_terrain` (part of it has no terrain data). `verdict` is then empty, `clearance_pct`, `worst_km` and `obstruction_m` are 0, and `warnings` says so. Only `direct` can carry it: an option whose leg would is not offered | + +### Error codes + +| Message or code | Cause | +|-----------------|-------| +| `a required`, `b required` | Point missing | +| `a must be lat,lon within range`, `b must be lat,lon within range` | Point malformed or out of range | +| `ha must be a number of metres`, `hb ...`, `hr ...` | Height is not a number | +| `range must be one of 10,15,20,30,40,50,60` | Range not in the allowed set. The message lists the values allowed up to `planner.maxLegKm` | +| `too_long` | A to B is longer than `planner.maxLegKm` (100 km by default) | +| `out_of_area` | A or B is not within 50 km of a known node | +| `too_many_tiles` | The corridor around A and B needs more 1° terrain tiles than the server loads for one request. Any leg up to the maximum length with both ends within latitudes -56 to 60 fits | + +### Response `400` + +```json +{ "error": "too_long" } +``` + +### Response `404` + +```json +{ "error": "planner disabled" } +``` + +--- + +## GET /api/planner/viewshed + +Theoretical reach of one candidate repeater site, for the planner's Coverage tab. The server profiles the site to every cell of a grid around it and returns two classes per cell, plus the site's link to each known repeater within range. Common rules and the job protocol are described under [`/api/planner/profile`](#get-apiplannerprofile). A viewshed job shares the coverage endpoint's compute slot, queue limit and result cache. + +### Query Parameters + +| Param | Type | Default | Description | +|---------|--------|---------------------------------|-------------| +| `site` | string | - | **Required.** The site as `lat,lon`. Must be within 50 km of a known node | +| `h` | number | `planner.newAntennaM` (10) | Antenna height at the site, metres. Rounded to 1 m and clamped to 1 to 100 | +| `rx` | number | `planner.existingAntennaM` (5) | Antenna height of the other repeater, for the Repeaters class and the links. Same limits as `h` | +| `range` | number | `planner.defaultRangeKm` (30) | Radius in km of the grid and of the link list. One of `10,15,20,30,40,50,60`, up to `planner.maxLegKm` | + +### Response `200` + +```json +{ + "source": "SRTM (AWS Open Data)", + "params": { + "site": {"lat": 30.11, "lon": -97.09}, + "antenna_m": 10, + "rx_antenna_m": 5, + "range_km": 30, + "frequency_mhz": 910.525, + "k_factor": 1.333, + "user_reach": {"d50_km": 2.7, "slope": 0.3} + }, + "bbox": [29.8402, -97.4027, 30.3798, -96.7773], + "rows": 301, + "cols": 301, + "cell_km": 0.2, + "cells": "AAAAQkJDQ0RE...", + "links": [ + { + "pubkey": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + "name": "Example Hilltop", + "lat": 30.1, + "lon": -97.1, + "link": {"distance_km": 1.43, "clearance_pct": 212.4, "verdict": "clear", "worst_km": 0.7, "obstruction_m": -14.2} + } + ], + "warnings": [], + "truncated": false +} +``` + +Abbreviated: `cells` is truncated for readability. + +| Field | Description | +|-------|-------------| +| `source` | Terrain attribution | +| `params` | The quantised inputs the result was computed with, the radio settings and the users reach curve (`planner.userReach`) | +| `bbox` | `[s, w, n, e]` of the grid in degrees: the site ± `range_km` | +| `rows`, `cols` | Grid size. Cell (r, c) is centred in the r-th of `rows` equal latitude bands from the north and the c-th of `cols` equal longitude bands from the west | +| `cell_km` | Nominal cell size: 0.2 km, or `range_km / 150` above 30 km | +| `cells` | Base64 of `rows × cols` bytes, row 0 north, row-major. Low nibble: Users class 1 to 5 from the handheld reach curve `P(d) = 1 / (1 + exp((ln d - ln d50) / slope))` (1: P below 0.10, 2: below 0.25, 3: below 0.50, 4: below 0.75, 5: 0.75 or more), two classes lower (at least 1) where a 1.5 m receiver is in deep terrain shadow. High nibble: Repeaters class for a receiver at `rx`, from the first-Fresnel clearance of the site-to-cell path: 1 blocked (below -20%), 2 slightly blocked (-20% to 0%), 3 line of sight (0% or more). These bounds differ from the link `verdict` on purpose: checked against one repeater's heard links, every link heard within 16 km had a clearance between 2% and 54%. A nibble of 0 means no data: outside `range_km`, or no terrain at the cell, the site or the path between | +| `links` | Known repeaters within `range_km` (rooms and stale repeaters excluded, as in `/api/planner/relay`, and repeaters within 100 m of the site, which are the site itself), nearest first. Each carries `pubkey`, `name`, `lat`, `lon` and a `link` object (see [`/api/planner/relay`](#get-apiplannerrelay)) for the site at `h` to the repeater at `rx`. The `link` has no `elev_m` profile. Always an array | +| `warnings` | Human-readable notes, for example missing terrain tiles. Always an array | +| `truncated` | `true` when the grid holds more repeaters and rooms than the planner reads for one job (300) and the farthest one kept is still within `range_km`, so a repeater in range may be missing from `links`. `false` when the cut only dropped nodes beyond `range_km` (the corners of the square grid) | + +### Error codes + +| Message or code | Cause | +|-----------------|-------| +| `site required` | Site missing | +| `site must be lat,lon within range` | Site malformed or out of range | +| `h must be a number of metres`, `rx ...` | Height is not a number | +| `range must be one of 10,15,20,30,40,50,60` | Range not in the allowed set. The message lists the values allowed up to `planner.maxLegKm` | +| `out_of_area` | The site is not within 50 km of a known node | +| `too_many_tiles` | The grid needs more 1° terrain tiles than the server loads for one request. Any site within latitudes -56 to 60 at any offered range fits | + +### Response `404` + +```json +{ "error": "planner disabled" } +``` + +--- + +## GET /api/planner/coverage + +Repeater backbone plan for an area. The server reads the repeaters and rooms in a bounding box, builds the backbone graph between them, and suggests up to `sites` new sites that would strengthen it. The result is a suggestion, not an optimum. Common rules and the job protocol are described under [`/api/planner/profile`](#get-apiplannerprofile). + +### Objective + +Sites are picked greedily, one at a time, against a fixed order of goals: + +1. **Fewer separate clusters.** Reduce the number of backbone components. An isolated repeater counts as a component of its own. Ties go to a larger largest component. +2. **Fewer single points of failure.** Reduce cut vertices, the repeaters whose loss would split the backbone. Each is weighted by the size of the smaller side it separates. +3. **Reach.** Add repeaters that have no solid link to the rest, so more of the area is covered at solid quality. + +Each pick is the candidate that gives the best gain under this order, comparing the goals in turn. Candidates are local high points on a 1 km grid, and no two picks sit closer than 2 km. Each pick links to nearby repeaters and earlier picks within `range`. + +### Query Parameters + +| Param | Type | Default | Description | +|------------|--------|--------------------------------|-------------| +| `bbox` | string | - | **Required.** `s,w,n,e` in degrees. Snapped outward to a 0.05° grid. South below north, west below west-east (no antimeridian crossing). Latitude must be within -56 to 60 (SRTM coverage). The snapped box may be at most `planner.maxAreaKm` (100 km by default) on either side | +| `sites` | int | 3 | Number of suggested sites, 1 to 10 | +| `range` | number | `planner.defaultRangeKm` (30) | Largest link distance in km considered. One of `10,15,20,30,40,50,60`, up to `planner.maxLegKm` | +| `hr` | number | `planner.newAntennaM` (10) | Height of a new site, metres. Rounded to 1 m and clamped to 1 to 100 | +| `he` | number | `planner.existingAntennaM` (5) | Assumed mast height of existing repeaters and rooms, metres. Same limits as `hr` | +| `baseline` | string | `predicted` | `predicted`: the backbone is every pair in range that terrain says is clear enough, plus observed links. `observed`: only links seen in real neighbour data (score × confidence of at least 0.1) | +| `stale` | string | `0` | `1` includes repeaters the node store marks as stale. `0` leaves them out and counts them in `stale_excluded` | + +The area must hold at least one repeater or room within 10 km of the box. Nodes are read from up to `planner.nodeMarginKm` (30 km by default) outside the box, at most 300 of them. + +### Response `200` + +```json +{ + "area": {"s": 30.10, "w": -97.80, "n": 30.35, "e": -97.55}, + "params": { + "sites": 3, + "range_km": 30, + "hr": 10, + "he": 5, + "baseline": "predicted", + "stale": false, + "frequency_mhz": 910.525, + "k_factor": 1.333, + "min_clearance": 0.6 + }, + "source": "SRTM (AWS Open Data)", + "status": "improved", + "baseline": {"repeaters": 9, "components": 3, "largest_component": 5, "isolated": 1, "cut_vertices": 2, "stale_excluded": 0}, + "final": {"repeaters": 9, "components": 1, "largest_component": 9, "isolated": 0, "cut_vertices": 0, "stale_excluded": 0}, + "nodes": [ + {"pubkey": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", "name": "Example Hilltop", "role": "repeater", "lat": 30.12, "lon": -97.74, "stale": false, "in_area": true, "component": 0} + ], + "edges": [ + {"a": 0, "b": 1, "class": "observed", "distance_km": 8.4, "clearance_pct": 112.0} + ], + "sites": [ + { + "step": 1, + "lat": 30.24, + "lon": -97.66, + "elev_m": 301, + "antenna_m": 10, + "reason": "joins", + "gain": {"components_joined": 2, "cut_vertices_removed": 0, "repeaters_reached": 1}, + "after": {"repeaters": 9, "components": 2, "largest_component": 6, "isolated": 0, "cut_vertices": 2, "stale_excluded": 0}, + "links": [ + {"node": 4, "distance_km": 9.7, "clearance_pct": 64.2, "class": "solid"}, + {"node": -1, "peer_step": 0, "distance_km": 6.1, "clearance_pct": 71.0, "class": "solid"} + ], + "joins_components": [1, 2] + } + ], + "warnings": [], + "truncated": false, + "computed_at": "2026-11-11T12:00:00Z" +} +``` + +| Field | Description | +|-------|-------------| +| `area` | The snapped bounding box actually analysed | +| `params` | The quantised inputs. `hr`, `he`, `baseline` and `stale` are echoed here | +| `source` | Terrain attribution | +| `status` | `improved`: at least one site was picked and the backbone changed. `connected`: the baseline backbone was already a single component, so the sites added redundancy. `no_gain`: no candidate improved anything | +| `baseline` | Backbone summary before any site is added | +| `final` | Backbone summary after the last site | +| `nodes[]` | Repeaters and rooms considered. Fields come from the same data `/api/nodes` shows. `component` is the baseline component id, `0` being the largest | +| `edges[]` | Backbone links. `a` and `b` are indexes into `nodes`. Capped at 2000 edges | +| `sites[]` | Greedy picks in order. See the site object below | +| `warnings` | Human-readable notes, for example `Area has no candidate high ground with a usable link`. Always an array | +| `truncated` | `true` when the node or candidate set was capped (300 nodes, 500 candidates) | +| `computed_at` | When the plan was computed (UTC) | + +**Summary object** (`baseline`, `final`, `sites[].after`): + +| Field | Description | +|-------|-------------| +| `repeaters` | In-area repeaters and rooms counted | +| `components` | Number of backbone components. An isolated repeater counts as one | +| `largest_component` | Size of the largest component | +| `isolated` | Repeaters with no backbone link | +| `cut_vertices` | Single points of failure | +| `stale_excluded` | Stale repeaters left out of the plan | + +**Edge class** (`edges[].class`): + +| Class | Meaning | +|-------|---------| +| `observed` | A link seen in real neighbour data, with a score × confidence of at least 0.1 | +| `solid` | A terrain-predicted link with at least 60% first-Fresnel clearance (`min_clearance`) | +| `marginal` | A terrain-predicted link with clearance from 0% up to 60%. The line clears the terrain but not by much | + +**Site object** (`sites[]`): + +| Field | Description | +|-------|-------------| +| `step` | 1-based greedy order | +| `lat`, `lon` | Suggested position | +| `elev_m` | Terrain height at the site, metres | +| `antenna_m` | Mast height used, `hr` | +| `reason` | Why this site was picked (see below) | +| `gain` | What the pick improved: `components_joined`, `cut_vertices_removed`, `repeaters_reached` | +| `after` | Backbone summary after this pick | +| `links[]` | Links from the site. `node` is an index into `nodes`, or `-1` when the peer is an earlier site, in which case `peer_step` gives its step. `class` is `solid` or `marginal` | +| `joins_components` | Baseline component ids this site connects | + +**Site reason** (`sites[].reason`): + +| Reason | Meaning | +|--------|---------| +| `joins` | The site connects two or more separate backbone components | +| `redundancy` | No components joined, but the site removes a single point of failure or otherwise reduces fragility | +| `reach` | Neither of the above. The site brings in repeaters that had no solid link | + +### Error codes + +| Message or code | Cause | +|-----------------|-------| +| `bbox required` | `bbox` missing | +| `bbox must be s,w,n,e in degrees` | Wrong number of values, not a number, or out of range | +| `bbox needs south below north and west below east (no antimeridian crossing)` | Degenerate or reversed box | +| `bbox must lie within latitudes -56 to 60 (terrain coverage)` | Outside SRTM coverage | +| `area_too_large` | The snapped box is over `planner.maxAreaKm` (100 km by default) on a side | +| `too_many_tiles` | The box plus the node margin needs more 1° terrain tiles than the server loads for one request. Never returned for a box the size check accepts; kept as a safeguard | +| `no_nodes_in_area` | No repeater or room within 10 km of the box | +| `sites must be an integer 1-10` | `sites` not an integer in range | +| `range must be one of 10,15,20,30,40,50,60` | `range` not in the allowed set. The message lists the values allowed up to `planner.maxLegKm` | +| `hr and he must be numbers of metres` | A height is not a number | +| `baseline must be predicted or observed` | Unknown `baseline` value | +| `stale must be 0 or 1` | Unknown `stale` value | + +### Response `400` + +```json +{ "error": "no_nodes_in_area" } +``` + +### Response `404` + +```json +{ "error": "planner disabled" } +``` + +--- + ## GET /api/analytics/topology Network topology analytics. @@ -2144,10 +2722,14 @@ Scope-based packet statistics over a time window. Requires ingestor `scope_name_ { "window": string, // echoed window ("1h", "24h", or "7d") "summary": { - "transportTotal": number, // scoped + unscoped transport-route packets - "scoped": number, // Code1 ≠ 0000 (named + unknown regions) - "unscoped": number, // transport-route with Code1 = 0000 - "unknownScope": number // scoped but no configured region matched (subset of scoped) + "total": number, // all observed transmissions, routes 0-3 (= scoped + unscoped) + "transportTotal": number, // transport routes 0 and 3 (= scoped + unscopedTransport) + "scoped": number, // Code1 ≠ 0000 (named + unknown regions) + "unscoped": number, // all unscoped traffic (= unscopedTransport + unscopedFlood + unscopedDirect) + "unscopedTransport": number, // transport route (0, 3) with Code1 = 0000 + "unscopedFlood": number, // FLOOD (route 1): no transport code, unscoped by protocol + "unscopedDirect": number, // DIRECT (route 2): no transport code, never floods + "unknownScope": number // scoped but no configured region matched (subset of scoped) }, "byRegion": [ { "name": string, "count": number } // region name and packet count @@ -2167,9 +2749,16 @@ Scope-based packet statistics over a time window. Requires ingestor `scope_name_ ``` **Notes:** -- `transportTotal` = `scoped` + `unscoped` (only route_type 0 or 3 packets) +- Route types per MeshCore `docs/packet_format.md`: 0 = TRANSPORT_FLOOD, 1 = FLOOD, 2 = DIRECT, + 3 = TRANSPORT_DIRECT. Only routes 0 and 3 carry a transport code (Code1). +- `total` = `scoped` + `unscoped` (all route types) +- `transportTotal` = `scoped` + `unscopedTransport` (only route_type 0 or 3 packets) - `scoped` = packets with Code1 ≠ 0000 -- `unscoped` = transport-route packets with Code1 = 0000 +- `unscoped` = `unscopedTransport` + `unscopedFlood` + `unscopedDirect`. Since #1838 it includes the + non-transport routes 1 and 2, so it can exceed `transportTotal`; compute shares against `total` (#2364). +- `unscopedFlood` is the figure to watch for region rollout: DIRECT traffic (`unscopedDirect`) is not + subject to flood-region filtering, which repeaters apply to flood routes only. +- `timeSeries` counts transport routes (0, 3) only; its `unscoped` corresponds to `unscopedTransport`. - `unknownScope` = scoped packets that did not match any configured region name - Time-series bucket size depends on window: - `1h` window → 5-minute buckets @@ -2431,6 +3020,8 @@ Client-side configuration values. "externalUrls": object | null, "propagationBufferMs": number, // default: 5000 "clientRfSamples": boolean, // opt-in flag; gates /api/rf-noise + "los": object, // omitted unless los.enabled is true: frequencyMhz, antennaHeightM, kFactor, maxPoints, maxLegKm. frequencyMhz 910.525 is the US default; use 869.618 for EU/UK meshes (set los.frequencyMhz to your mesh's frequency). The planner reads frequencyMhz and kFactor from the los block even when los.enabled is false. + "planner": object, // omitted unless planner.enabled is true: defaultRangeKm, rangesKm (only those up to maxLegKm), newAntennaM, existingAntennaM, frequencyMhz, kFactor, maxPoints, maxLegKm, maxAreaKm, nodeMarginKm, maxSites, minClearance "clientRxAppUrl": string // omitted unless clientRxCoverage is on and clientRxCoverage.appUrl is an https URL } ``` diff --git a/docs/superpowers/specs/2026-04-15-repeater-liveness-design.md b/docs/archive/2026-04-15-repeater-liveness-design.md similarity index 94% rename from docs/superpowers/specs/2026-04-15-repeater-liveness-design.md rename to docs/archive/2026-04-15-repeater-liveness-design.md index d9cde1d22..420502cd7 100644 --- a/docs/superpowers/specs/2026-04-15-repeater-liveness-design.md +++ b/docs/archive/2026-04-15-repeater-liveness-design.md @@ -1,5 +1,11 @@ # Repeater Liveness — Design Spec +> **Archived plan.** Historical planning material; proposals, status claims, and +> instructions below may be outdated or unimplemented. The proposed `relaying` +> status and helper signature are not current. For current liveness guidance, +> see [AGENTS.md](../../AGENTS.md#last_heard-vs-last_seen) and the +> [status helpers](../../public/roles.js). + **Issue:** Kpa-clawbot/CoreScope#662 **Date:** 2026-04-15 **Status:** Approved diff --git a/docs/superpowers/plans/2026-04-15-repeater-liveness.md b/docs/archive/2026-04-15-repeater-liveness.md similarity index 99% rename from docs/superpowers/plans/2026-04-15-repeater-liveness.md rename to docs/archive/2026-04-15-repeater-liveness.md index 53badc61e..5b761a4d2 100644 --- a/docs/superpowers/plans/2026-04-15-repeater-liveness.md +++ b/docs/archive/2026-04-15-repeater-liveness.md @@ -1,5 +1,11 @@ # Repeater Liveness Implementation Plan +> **Archived plan.** Historical planning material; proposals, status claims, and +> instructions below may be outdated or unimplemented. The proposed `relaying` +> status and helper signature are not current. For current liveness guidance, +> see [AGENTS.md](../../AGENTS.md#last_heard-vs-last_seen) and the +> [status helpers](../../public/roles.js). + > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. **Goal:** Distinguish repeaters that are actively relaying traffic from those that are alive but idle, using a precomputed O(log n) sorted-timestamp index. diff --git a/docs/deployment.md b/docs/deployment.md index 4c4d5c6e9..a2fb5071d 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -5,6 +5,7 @@ Comprehensive guide to deploying and operating CoreScope. For a quick start, see ## Table of Contents - [System Requirements](#system-requirements) +- [Deployment modes](#deployment-modes) - [Docker Deployment](#docker-deployment) - [Configuration Reference](#configuration-reference) - [MQTT Setup](#mqtt-setup) @@ -33,6 +34,85 @@ CoreScope runs well on Raspberry Pi 4/5 (ARM64). The Go server uses ~300 MB RAM --- +## Deployment modes + +The UI is static files (`public/`) that call the server's API. The three modes +differ only in what serves those files. The server container is the same image +in all three, and it still serves the classic UI itself. + +| Mode | The UI is served by | API | Server CORS setting | Logins | +|---|---|---|---|---| +| [All-in-one container](#all-in-one-container) | the server container | same origin | none | yes | +| [Split containers](#split-containers) | a web container (`Dockerfile.web`) that forwards the API | same origin | none | yes | +| [Static host or CDN](#static-host-or-cdn) | Cloudflare Pages, a CDN or any web server | another origin | `CORS_ALLOWED_ORIGINS` | no, links to the classic UI | + +### All-in-one container + +The default, and what the rest of this guide describes: one image runs the +server, the ingestor and, optionally, Mosquitto and Caddy. The server serves the +UI from `/app/public` and the API on one origin. See +[Docker Deployment](#docker-deployment). + +### Split containers + +`docker-compose.split.yml` runs the server image unchanged next to a web +container built from `Dockerfile.web`. The web container is Caddy: it serves the +UI, packaged by `scripts/static/build.sh` when the image is built, and forwards +`/api/*` and `/ws` to the server. The browser sees one origin, so the server +needs no CORS setting. Logins work as on the classic UI when account +configuration uses the public web origin, as described below. + +```bash +CORESCOPE_IMAGE=ghcr.io/kpa-clawbot/corescope:edge \ + docker compose -f docker-compose.split.yml up -d --build +``` + +| Variable | Default | | +|---|---|---| +| `HTTP_PORT`, `HTTPS_PORT` | `80`, `443` | Published by the web container; 443 over TCP and UDP (HTTP/3) | +| `SITE_ADDRESS` | `:80` | A domain name turns on Caddy's automatic HTTPS and HTTP/3. Keep the default ports then: certificate issuance and the HTTP/3 advertisement both assume 80 and 443 | +| `CORESCOPE_IMAGE` | none, required | The server image of the same version as the checkout the web image is built from: `:edge` on `master`, `:vX.Y.Z` on a release tag | +| `DATA_DIR` | `./data` | The server's data directory | +| `GIT_COMMIT` | the build time | The UI's cache buster | +| `CHANNEL` | `static` | `beta`, `next` or `dev` shows a badge | +| `MQTT_BIND`, `MQTT_PORT` | `127.0.0.1`, `1883` | Where the server's built-in broker is published. It accepts anonymous clients, so set `MQTT_BIND=0.0.0.0` only to let gateways on a network you trust publish to it | +| `SPLIT_NET` | `172.30.83` | The compose network's /24, as its first three octets; the web container is `.200` in it. Change it only if Docker reports that the pool overlaps another network, and update `trustedProxies` to match | + +- When `userManagement.enabled` is true, set `userManagement.publicBaseUrl` in + the server's config to the public web origin, including its scheme and port + (for example, `http://localhost:8080` for a web container published on port + 8080). Login and other state-changing requests compare the browser's `Origin` + or `Referer` with this configured origin; forwarding the public `Host` header + alone is not enough. This value also determines mail links. See + [account configuration](user-guide/accounts.md#2-configure). +- The web container finds the server through `BACKEND` (`corescope:3000` in the + compose file). Port 3000 stays inside the compose network, and the server + still serves everything there, the classic UI included; publish it if you want + to reach that directly. +- The web image is built from your checkout, so keep the checkout and + `CORESCOPE_IMAGE` on the same version: a newer UI may call endpoints an older + server lacks. To update only the UI, rebuild the web container: + `docker compose -f docker-compose.split.yml up -d --build web`. +- Behind the web container, as behind the all-in-one image's Caddy, every + request reaches the server from the proxy's address, so per-IP limits are off + until `webSocket.trustedProxies` and `userManagement.trustedProxies` list it. + The compose file fixes that address at `172.30.83.200`: list it alone. Never + list the compose subnet. It also holds the gateway address, and a client that + reaches a published port 3000 through Docker's proxy (from the host itself or + over IPv6, for example) arrives from there, so its own `X-Forwarded-For` + would be believed. + +### Static host or CDN + +`make web` (or `scripts/static/build.sh`) writes the anonymous build to +`dist/web` for Cloudflare Pages or any static host. It calls the server +cross-origin, so the server lists the UI's origin in `CORS_ALLOWED_ORIGINS`. +It sends no cookies; logins and admin pages link to the classic UI on the +server. Setup, previews, server settings and rollback: +[deploy/static/README.md](../deploy/static/README.md). + +--- + ## Docker Deployment ### Quick Start (one command) @@ -419,12 +499,33 @@ server { proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } ``` The `Upgrade` and `Connection` headers are required for WebSocket support. +The `X-Forwarded-For` line matters for the per-client limits on +`/api/elevation/profile` and `/api/planner/*`. Without it stock nginx passes +the visitor's own header through untouched, and the entry CoreScope trusts is +chosen by the visitor. `$proxy_add_x_forwarded_for` appends the real peer +address. + +Those limits apply only when CoreScope can tell clients apart. A reverse proxy +on a loopback or private address that is not listed in +`webSocket.trustedProxies` (the shipped default) makes every visitor look like +one client, so the per-client limits are skipped and one warning is logged; +the server-wide terrain download and planner job budgets still apply. List the +proxy's address to turn them on. + +A proxy listed in `webSocket.trustedProxies` MUST append to `X-Forwarded-For` +(never replace it with a client-supplied value). If you list a CDN's ranges, +anyone who can send requests from inside those ranges (for example CDN +workers) can choose the hop CoreScope uses. Traefik appends to +`X-Forwarded-For` by default for trusted entrypoints; check yours. + ### Option 2: Built-in Caddy (auto-TLS) The container includes Caddy for automatic Let's Encrypt certificates: @@ -446,7 +547,10 @@ The container includes Caddy for automatic Let's Encrypt certificates: ghcr.io/kpa-clawbot/corescope:latest ``` -Caddy handles certificate issuance and renewal automatically. +Caddy handles certificate issuance and renewal automatically. `reverse_proxy` +appends the connecting address to `X-Forwarded-For` by default, so no extra +header configuration is needed; list the Caddy address in +`webSocket.trustedProxies`. --- diff --git a/docs/fork-maintenance.md b/docs/fork-maintenance.md index 945165ee1..6b54e6af1 100644 --- a/docs/fork-maintenance.md +++ b/docs/fork-maintenance.md @@ -1,6 +1,6 @@ # Fork maintenance -This fork retains upstream CoreScope history. Release `v3.17.0+sacmesh.1` integrates the unified SacMesh changes with the upstream `v3.17.0` tag. The previously deployed `v3.15.0+sacmesh.1` remains a separate tested release, not a second fork. It keeps upstream licensing and attribution. It is not an upstream release. +This fork retains upstream CoreScope history. Release `v3.18.0+sacmesh.1` merges upstream `master` after `v3.18.0` (through `6c78a1d2`) into the SacMesh changes; `v3.17.0+sacmesh.1` and `.2` were built on the upstream `v3.17.0` tag. The previously deployed `v3.15.0+sacmesh.1` remains a separate tested release, not a second fork. It keeps upstream licensing and attribution. It is not an upstream release. ## Included changes @@ -24,6 +24,8 @@ A release must not replace site-specific broker subscriptions, region filters, b The web server keeps the analyzer database read-only. The ingestor remains the only writer of measurements and schema changes. The only analyzer schema change of the SacMesh fork is the additive `hop_aliases` table (created empty on start; older binaries ignore it). The newer upstream base adds observer radio history and neighbor-report tables. With accounts enabled, it also upgrades the separate users database from schema v6 to v8; older binaries cannot open that upgraded users database. Back up both databases before deployment and test rollback on copies. There is no further upstream database migration from v3.16 to v3.17. Merging source does not upgrade a running instance. +From v3.17 to v3.18 upstream adds two migrations. The ingestor runs the content-hash migration `content_hash_payload_bits_v1` once (#2409): it scans every packet by id. It rewrites stale hashes and merges any duplicates the rewrite creates; the fork's server-side copy of this migration is gone. Its status is a row in `_async_migrations`, which older binaries ignore; a merge is not undone by a rollback. With user accounts on, `users.db` moves to schema v9 (#2415), which v3.17 binaries refuse; neither SacMesh instance enables accounts. The UI's live feed now connects to `/ws` (#2383), so a proxy must forward WebSocket upgrades on `/ws` as well as `/`. + ## Release checks Run `make test`, `make vet` and `sh test-all.sh`. Run focused race tests for changed concurrent code. Validate the frontend in a browser before deployment. @@ -42,7 +44,7 @@ Keep separate container names, ports, configuration, data directories and databa ## Map tile provider follow-up -The fork includes upstream change `a0b4e6cf` (after the v3.17.0 release) for consistent light/dark tile selection, late configuration and node-map refresh. Map and Live also refresh the existing layer's maximum zoom and attribution when switching providers, including label overlays. Re-registering the layer lets Leaflet recalculate its zoom limits; it does not add packet-processing work. +The fork includes upstream change `a0b4e6cf` (part of v3.18.0) for consistent light/dark tile selection, late configuration and node-map refresh. Map and Live also refresh the existing layer's maximum zoom and attribution when switching providers, including label overlays. Re-registering the layer lets Leaflet recalculate its zoom limits; it does not add packet-processing work. Explicit operator tile URL overrides now take precedence consistently on these maps. Without an override, the existing customizer provider selection and server defaults apply. No configuration keys or defaults are added by this follow-up. Test fresh loads, provider/theme changes and zoom limits before deploying to an instance with custom tile URLs. This source change alone does not update running instances. diff --git a/docs/release-notes/v3.18.0.md b/docs/release-notes/v3.18.0.md new file mode 100644 index 000000000..0667f624e --- /dev/null +++ b/docs/release-notes/v3.18.0.md @@ -0,0 +1,100 @@ +# v3.18.0 + +11 commits since v3.17.0: 5 fix, 3 feat, 1 test, 1 refactor, 1 docs. Three feats, so +minor not patch. + +A short release with three larger features. Two are optional tools: radio line of sight +on packet routes plus a repeater planner, and repeater details that registered users can +fill in. The third is a new way to deploy the UI: from its own web container or from a +static host such as Cloudflare Pages. An instance that keeps running the one container +it runs today needs no configuration change. + +## Read this before upgrading + +### With user accounts on, `users.db` moves to schema v9 + +With `userManagement.enabled`, the first start creates the tables for repeater claims and +details (#2415). A v3.17.x binary refuses the database afterwards ("database schema +version 9 is newer than this binary supports"), so keep a copy of `users.db` from before +the upgrade if you may want to roll back. The analyzer database is not touched. Without +user accounts nothing changes. + +### The live feed connects to `/ws` + +The UI's WebSocket now goes to `/ws` instead of `/` (#2383). The server has answered on +`/ws` for a long time and still accepts `/`, so open browsers keep working. A reverse +proxy that forwards WebSocket upgrades only for an exact `/` must forward `/ws` too. The +nginx example in `docs/deployment.md` (`location /`) already covers it. + +### Map tile URLs you set in the config now win on every page + +If your config sets a tile URL (`tiles.dark`, `tiles.light`, `map.tiles.darkUrl` or +`map.tiles.lightUrl`), the Map and Live pages now use it too (#2386). Before, a visitor's +tile pick in the customizer overrode it on those two pages, while the node pages, reach +map and analytics already followed your setting. Without those keys nothing changes. + +## Features + +- **Radio line of sight on packet routes** (#2391). With `los.enabled`, every leg of a + packet route on the map gets a clear, marginal or blocked chip (first Fresnel zone, + k=4/3), obstructions are marked on the map, and a terrain profile panel lets viewers + change antenna height and frequency. Set `los.frequencyMhz` to your mesh's frequency: + the default 910.525 is the US one, use 869.618 for EU/UK. +- **Repeater planner** (#2391). With `planner.enabled`, `#/tools/planner` checks line of + sight along a chain of points, finds the best single relay between two points, and + suggests new repeater sites that join the existing backbone in an area of up to + 100 by 100 km. Both features use SRTM terrain (about 90 m) fetched on demand from AWS + Open Data and kept in memory only; the server still writes nothing. Both are off by + default, and with them off nothing is fetched. +- **Repeater info and claims** (#2415, #2416, #2417). With user accounts on, registered + users can claim a repeater and record what the radio cannot advertise: antenna height + and gain, power source, whether it is active, in maintenance or decommissioned, and + notes. Everyone sees the details on the node page. A claimed repeater can be edited by + its claimers and by admins only; edits and claims show in the audit log, and admins can + remove a claim. +- **Three ways to deploy the UI** (#2383). Next to the all-in-one container you run + today, the UI can now come from a separate web container (Caddy, `Dockerfile.web` and + `docker-compose.split.yml`) that forwards the API, or from a static host or CDN against + your server on another origin. The static build has no logins; its account pages link + to the classic UI. `docs/deployment.md` has a "Deployment modes" section, and + `deploy/static/README.md` covers Cloudflare Pages and rollback. + +## Fixes + +- **Memory after eviction** (#2327). Packets removed from memory were still held by some + secondary indexes, so memory use stayed higher than the data in it. In a synthetic test + with the same live data the retained heap went from 98 to 27 MiB. +- **Scope statistics** (#2368, closes #2364). `/api/scope-stats` counted flood and direct + traffic as unscoped but left them out of `transportTotal`, so an unscoped share could + pass 100%. The summary now has a `total` and splits unscoped into transport, flood and + direct; existing fields keep their values. The Scopes tab shows the split. +- **Light-mode maps on node pages** (#2386). The node page map ignored the light tile + provider picked in the customizer, could show Carto's "API key required" watermark when + the config arrived late, and did not follow a theme switch. It now uses the same tile + choice as the main map and follows changes while open. + +## Tests, refactoring and docs + +The tile-resolver unit test loads `CSApi` before `roles.js` (#2402), and the Live page +reuses the shared timestamp renderer (#2395). Superseded repeater liveness plans were +moved to the archive (#2392). + +## Issues closed + +- #2364 `/api/scope-stats`: `unscoped` can exceed `transportTotal` since #1838 + +## Contributors + +Pull requests: efiten (3, maintainer), n30nex (3), zfouts (2), ppicazo, SaarMesh-Bot and +trixmoe (1 each). efiten co-authored #2391. + +Issues: Nursedude for the scope statistics report in #2364. + +## Upgrade notes + +- Created automatically: the repeater claim and detail tables in `users.db` (schema v9), + only with user accounts on. +- Opt-in: `los.enabled`, `planner.enabled` (with the shared `terrain` block), the web + container and the static build. +- Action needed: a reverse proxy that forwards WebSocket upgrades only on `/` must also + forward `/ws`. Keep a pre-upgrade copy of `users.db` if you run user accounts. diff --git a/docs/user-guide/accounts.md b/docs/user-guide/accounts.md index b9ed11d65..fe0460bfd 100644 --- a/docs/user-guide/accounts.md +++ b/docs/user-guide/accounts.md @@ -328,6 +328,24 @@ coverage counts as the owner's (*My coverage* on the coverage page). Links are p everything from RX builds without account support: upgrade the RX clients first. See [Client RX Coverage, Linked companions only](../client-rx-coverage.md#linked-companions-only-optional). +### Repeater info + +With user management on, a repeater's node page has a *Repeater info* section: antenna height, +antenna gain, status (active, maintenance, decommissioned), power (mains, battery, solar) and +free notes (500 characters). There is no separate switch: it is on whenever `userManagement` is +enabled. + +- **Who may edit:** a repeater nobody claimed can be edited by any logged-in active user. Once + it has claimers, only its active claimers can. Admins can always edit. An unchanged save + writes nothing. +- **Public names:** the display names of the claimers, and of the user who made the last edit, + are shown to every visitor. Email addresses never are. Claims of a disabled user are kept + but hidden and do not count, so a repeater whose only claimer is disabled is open again. +- **Audit log:** edits are recorded as `repeater.edit` (with the old and new value of each + changed field), claims as `repeater.claim` and `repeater.unclaim`. +- **Removing a claim:** *Admin, Users*, open the user, *Remove* next to the claim. Admins use + this when a claimer left or claimed a repeater that is not theirs. + ### Observer MQTT logins (optional) `userManagement.observerLogins` lets every user request a personal MQTT login for their observers, @@ -464,6 +482,11 @@ version N is newer than this binary supports"): run that version or newer. Delet not a node to monitor. The app shows under *Devices* as "CoreDrive RX – "; *Log out* there signs the app out. *Unlink* removes the link; the coverage it already collected stays on the map. On the coverage page, *My coverage* shows only what your linked companions heard. +- **Repeater info:** on a repeater's page, *Repeater info* shows what the community knows + about it. *Claim this repeater* says you operate it; after that only you (and the other + claimers and admins) can edit it. An unclaimed repeater can be edited by any logged-in + user. Your display name is public next to your claims and edits, your email address is + not. *Unclaim* removes your claim. - **Never synced:** channel keys and decrypted messages, the API key, panel and column sizes, collapsed panels and map positions. They stay in the browser where you set them. - **Logging out** asks whether to keep your settings on this device (the default) or diff --git a/internal/users/confirm_observer_test.go b/internal/users/confirm_observer_test.go index 0c92e7532..5eba90e99 100644 --- a/internal/users/confirm_observer_test.go +++ b/internal/users/confirm_observer_test.go @@ -50,8 +50,8 @@ func TestMigrationV8ConfirmsAutoBindings(t *testing.T) { t.Fatalf("Open v7 db: %v", err) } defer st.Close() - if v, err := st.SchemaVersion(); err != nil || v != 8 || v != len(migrations) { - t.Fatalf("SchemaVersion = %d, %v; want 8", v, err) + if v, err := st.SchemaVersion(); err != nil || v != len(migrations) { + t.Fatalf("SchemaVersion = %d, %v; want %d", v, err, len(migrations)) } auto, admin := mustBinding(t, st, "AUTOKEY"), mustBinding(t, st, "ADMINKEY") if auto.ConfirmedAt == nil || !auto.ConfirmedAt.Equal(auto.BoundAt) { diff --git a/internal/users/repeaters.go b/internal/users/repeaters.go new file mode 100644 index 000000000..a7e1aee5b --- /dev/null +++ b/internal/users/repeaters.go @@ -0,0 +1,326 @@ +package users + +import ( + "database/sql" + "errors" + "fmt" + "math" + "strings" + "time" + "unicode" + "unicode/utf8" +) + +const ( + RepeaterStatusActive = "active" + RepeaterStatusMaintenance = "maintenance" + RepeaterStatusDecommissioned = "decommissioned" + + RepeaterPowerMains = "mains" + RepeaterPowerBattery = "battery" + RepeaterPowerSolar = "solar" + + MaxRepeaterNotes = 500 + MaxRepeaterHeightM = 300 + MinRepeaterGainDBi = -10 + MaxRepeaterGainDBi = 30 +) + +// RepeaterEdit is one community edit of a repeater's details. HeightM nil is +// unknown (distinct from 0); an empty Status or Power is unset. +type RepeaterEdit struct { + HeightM *float64 + GainDBi float64 + Status string + Power string + Notes string +} + +// ValidateRepeaterEdit returns the cleaned edit or a *ValidationError. +func ValidateRepeaterEdit(e RepeaterEdit) (RepeaterEdit, error) { + if e.HeightM != nil { + h := *e.HeightM + if math.IsNaN(h) || math.IsInf(h, 0) || h < 0 || h > MaxRepeaterHeightM { + return RepeaterEdit{}, &ValidationError{Msg: fmt.Sprintf("height must be between 0 and %d m", MaxRepeaterHeightM)} + } + hc := h + e.HeightM = &hc + } + if math.IsNaN(e.GainDBi) || math.IsInf(e.GainDBi, 0) || e.GainDBi < MinRepeaterGainDBi || e.GainDBi > MaxRepeaterGainDBi { + return RepeaterEdit{}, &ValidationError{Msg: fmt.Sprintf("antenna gain must be between %d and %d dBi", MinRepeaterGainDBi, MaxRepeaterGainDBi)} + } + switch e.Status { + case "", RepeaterStatusActive, RepeaterStatusMaintenance, RepeaterStatusDecommissioned: + default: + return RepeaterEdit{}, &ValidationError{Msg: "status must be active, maintenance or decommissioned"} + } + switch e.Power { + case "", RepeaterPowerMains, RepeaterPowerBattery, RepeaterPowerSolar: + default: + return RepeaterEdit{}, &ValidationError{Msg: "power must be mains, battery or solar"} + } + n := strings.ToValidUTF8(e.Notes, "") + n = strings.ReplaceAll(n, "\r\n", "\n") + n = strings.Map(func(r rune) rune { + switch { + case r == '\t' || r == '\r': + return ' ' + case r != '\n' && unicode.IsControl(r): + return -1 + case (r >= 0x202A && r <= 0x202E) || (r >= 0x2066 && r <= 0x2069): + return -1 + } + return r + }, n) + lines := strings.Split(n, "\n") + for i, l := range lines { + lines[i] = strings.TrimRight(l, " ") + } + n = strings.TrimSpace(strings.Join(lines, "\n")) + for strings.Contains(n, "\n\n\n") { + n = strings.ReplaceAll(n, "\n\n\n", "\n\n") + } + if utf8.RuneCountInString(n) > MaxRepeaterNotes { + return RepeaterEdit{}, &ValidationError{Msg: fmt.Sprintf("notes must be at most %d characters", MaxRepeaterNotes)} + } + e.Notes = n + return e, nil +} + +// RepeaterInfo is the community-maintained detail row of one repeater. +// UpdatedBy and UpdatedByName are empty when the editor was deleted or is not +// an active user. +type RepeaterInfo struct { + Pubkey string + HeightM *float64 + GainDBi float64 + Status string + Power string + Notes string + UpdatedAt time.Time + UpdatedBy *int64 + UpdatedByName string +} + +// RepeaterClaim says a user operates a repeater. +type RepeaterClaim struct { + Pubkey string + UserID int64 + DisplayName string + ClaimedAt time.Time +} + +const repeaterInfoSelect = `SELECT i.pubkey, i.height_m, i.gain_dbi, i.status, i.power, i.notes, i.updated_at, u.id, u.display_name + FROM repeater_info i LEFT JOIN users u ON u.id = i.updated_by AND u.status = 'active'` + +func scanRepeaterInfo(r rowScanner) (*RepeaterInfo, error) { + var ( + ri RepeaterInfo + h sql.NullFloat64 + st, pw, name sql.NullString + ub sql.NullInt64 + updatedAtUnix int64 + ) + if err := r.Scan(&ri.Pubkey, &h, &ri.GainDBi, &st, &pw, &ri.Notes, &updatedAtUnix, &ub, &name); err != nil { + return nil, err + } + if h.Valid { + v := h.Float64 + ri.HeightM = &v + } + ri.Status, ri.Power = st.String, pw.String + ri.UpdatedAt = fromUnix(updatedAtUnix) + if ub.Valid { + v := ub.Int64 + ri.UpdatedBy = &v + ri.UpdatedByName = name.String + } + return &ri, nil +} + +func (s *Store) GetRepeaterInfo(pubkey string) (*RepeaterInfo, error) { + pk, err := NormalizePubkey(pubkey) + if err != nil { + return nil, err + } + ri, err := scanRepeaterInfo(s.db.QueryRow(repeaterInfoSelect+` WHERE i.pubkey = ?`, pk)) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + return ri, err +} + +// ListRepeaterInfo returns every info row ordered by pubkey. +func (s *Store) ListRepeaterInfo() ([]RepeaterInfo, error) { + rows, err := s.db.Query(repeaterInfoSelect + ` ORDER BY i.pubkey`) + if err != nil { + return nil, err + } + defer rows.Close() + var out []RepeaterInfo + for rows.Next() { + ri, err := scanRepeaterInfo(rows) + if err != nil { + return nil, err + } + out = append(out, *ri) + } + return out, rows.Err() +} + +// SaveRepeaterInfo validates and upserts the row. It returns the row the write +// replaced (nil if there was none), read in the same transaction, for the +// audit diff. +func (s *Store) SaveRepeaterInfo(userID int64, pubkey string, e RepeaterEdit) (*RepeaterInfo, error) { + pk, err := NormalizePubkey(pubkey) + if err != nil { + return nil, err + } + e, err = ValidateRepeaterEdit(e) + if err != nil { + return nil, err + } + tx, err := s.db.Begin() + if err != nil { + return nil, err + } + defer tx.Rollback() + prev, err := scanRepeaterInfo(tx.QueryRow(repeaterInfoSelect+` WHERE i.pubkey = ?`, pk)) + if errors.Is(err, sql.ErrNoRows) { + prev = nil + } else if err != nil { + return nil, err + } + var h any + if e.HeightM != nil { + h = *e.HeightM + } + var st, pw any + if e.Status != "" { + st = e.Status + } + if e.Power != "" { + pw = e.Power + } + if _, err := tx.Exec(`INSERT INTO repeater_info (pubkey, height_m, gain_dbi, status, power, notes, updated_at, updated_by) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(pubkey) DO UPDATE SET height_m = excluded.height_m, gain_dbi = excluded.gain_dbi, + status = excluded.status, power = excluded.power, notes = excluded.notes, + updated_at = excluded.updated_at, updated_by = excluded.updated_by`, + pk, h, e.GainDBi, st, pw, e.Notes, unix(s.now()), userID); err != nil { + return nil, err + } + if err := tx.Commit(); err != nil { + return nil, err + } + return prev, nil +} + +// ClaimRepeater is idempotent: added is false when the user already claimed it. +func (s *Store) ClaimRepeater(userID int64, pubkey string) (bool, error) { + pk, err := NormalizePubkey(pubkey) + if err != nil { + return false, err + } + res, err := s.db.Exec(`INSERT OR IGNORE INTO repeater_claims (pubkey, user_id, claimed_at) VALUES (?, ?, ?)`, pk, userID, unix(s.now())) + if err != nil { + return false, err + } + n, err := res.RowsAffected() + return n == 1, err +} + +// UnclaimRepeater returns ErrNotFound when the user has no claim on it. +func (s *Store) UnclaimRepeater(userID int64, pubkey string) error { + pk, err := NormalizePubkey(pubkey) + if err != nil { + return err + } + return expectOne(s.db.Exec(`DELETE FROM repeater_claims WHERE pubkey = ? AND user_id = ?`, pk, userID)) +} + +func scanRepeaterClaims(rows *sql.Rows) ([]RepeaterClaim, error) { + defer rows.Close() + var out []RepeaterClaim + for rows.Next() { + var c RepeaterClaim + var at int64 + if err := rows.Scan(&c.Pubkey, &c.UserID, &c.DisplayName, &at); err != nil { + return nil, err + } + c.ClaimedAt = fromUnix(at) + out = append(out, c) + } + return out, rows.Err() +} + +const repeaterClaimsSelect = `SELECT c.pubkey, c.user_id, u.display_name, c.claimed_at + FROM repeater_claims c JOIN users u ON u.id = c.user_id` + +// RepeaterClaims lists the active claimers of one repeater. +func (s *Store) RepeaterClaims(pubkey string) ([]RepeaterClaim, error) { + pk, err := NormalizePubkey(pubkey) + if err != nil { + return nil, err + } + rows, err := s.db.Query(repeaterClaimsSelect+` WHERE c.pubkey = ? AND u.status = 'active' ORDER BY c.claimed_at, c.user_id`, pk) + if err != nil { + return nil, err + } + return scanRepeaterClaims(rows) +} + +// AllRepeaterClaims returns the active claimers of every repeater, by pubkey. +func (s *Store) AllRepeaterClaims() (map[string][]RepeaterClaim, error) { + rows, err := s.db.Query(repeaterClaimsSelect + ` WHERE u.status = 'active' ORDER BY c.pubkey, c.claimed_at, c.user_id`) + if err != nil { + return nil, err + } + list, err := scanRepeaterClaims(rows) + if err != nil { + return nil, err + } + out := make(map[string][]RepeaterClaim) + for _, c := range list { + out[c.Pubkey] = append(out[c.Pubkey], c) + } + return out, nil +} + +// RepeaterClaimsByUser lists every claim of a user regardless of their +// status, newest first. +func (s *Store) RepeaterClaimsByUser(userID int64) ([]RepeaterClaim, error) { + rows, err := s.db.Query(repeaterClaimsSelect+` WHERE c.user_id = ? ORDER BY c.claimed_at DESC, c.pubkey`, userID) + if err != nil { + return nil, err + } + return scanRepeaterClaims(rows) +} + +// CanEditRepeater: admin always; a non-active user never; with no active +// claimers any active user; otherwise only the active claimers. +func (s *Store) CanEditRepeater(u *User, pubkey string) (bool, error) { + pk, err := NormalizePubkey(pubkey) + if err != nil { + return false, err + } + if u == nil || u.Status != StatusActive { + return false, nil + } + if u.Role == RoleAdmin { + return true, nil + } + claims, err := s.RepeaterClaims(pk) + if err != nil { + return false, err + } + if len(claims) == 0 { + return true, nil + } + for _, c := range claims { + if c.UserID == u.ID { + return true, nil + } + } + return false, nil +} diff --git a/internal/users/repeaters_test.go b/internal/users/repeaters_test.go new file mode 100644 index 000000000..b60461fbf --- /dev/null +++ b/internal/users/repeaters_test.go @@ -0,0 +1,321 @@ +package users + +import ( + "errors" + "math" + "strings" + "testing" + "time" +) + +func fp(f float64) *float64 { return &f } + +func TestValidateRepeaterEdit(t *testing.T) { + tests := []struct { + name string + in RepeaterEdit + wantErr bool + check func(t *testing.T, got RepeaterEdit) + }{ + {"height negative", RepeaterEdit{HeightM: fp(-0.1)}, true, nil}, + {"height zero", RepeaterEdit{HeightM: fp(0)}, false, func(t *testing.T, g RepeaterEdit) { + if g.HeightM == nil || *g.HeightM != 0 { + t.Fatalf("height = %v, want pointer to 0", g.HeightM) + } + }}, + {"height 300", RepeaterEdit{HeightM: fp(300)}, false, nil}, + {"height 300.1", RepeaterEdit{HeightM: fp(300.1)}, true, nil}, + {"height nil", RepeaterEdit{}, false, func(t *testing.T, g RepeaterEdit) { + if g.HeightM != nil { + t.Fatal("nil height became non-nil") + } + }}, + {"height NaN", RepeaterEdit{HeightM: fp(math.NaN())}, true, nil}, + {"height Inf", RepeaterEdit{HeightM: fp(math.Inf(1))}, true, nil}, + {"gain -10", RepeaterEdit{GainDBi: -10}, false, nil}, + {"gain -10.1", RepeaterEdit{GainDBi: -10.1}, true, nil}, + {"gain 30", RepeaterEdit{GainDBi: 30}, false, nil}, + {"gain 30.1", RepeaterEdit{GainDBi: 30.1}, true, nil}, + {"gain NaN", RepeaterEdit{GainDBi: math.NaN()}, true, nil}, + {"gain Inf", RepeaterEdit{GainDBi: math.Inf(-1)}, true, nil}, + {"status planned", RepeaterEdit{Status: "planned"}, true, nil}, + {"status padded", RepeaterEdit{Status: " Active "}, true, nil}, + {"status empty", RepeaterEdit{Status: ""}, false, nil}, + {"status ok", RepeaterEdit{Status: RepeaterStatusMaintenance}, false, nil}, + {"power wind", RepeaterEdit{Power: "wind"}, true, nil}, + {"power ok", RepeaterEdit{Power: RepeaterPowerSolar}, false, nil}, + {"notes cleaned", RepeaterEdit{Notes: " line1\r\nline2\t\x00 "}, false, func(t *testing.T, g RepeaterEdit) { + if g.Notes != "line1\nline2" { + t.Fatalf("notes = %q", g.Notes) + } + }}, + {"notes blank-line run", RepeaterEdit{Notes: "a\n\n\n\n\nb\n\nc"}, false, func(t *testing.T, g RepeaterEdit) { + if g.Notes != "a\n\nb\n\nc" { + t.Fatalf("notes = %q", g.Notes) + } + }}, + {"notes CRLF blank-line run", RepeaterEdit{Notes: "a\r\n\r\n\r\nb"}, false, func(t *testing.T, g RepeaterEdit) { + if g.Notes != "a\n\nb" { + t.Fatalf("notes = %q", g.Notes) + } + }}, + {"notes whitespace-only lines count as blank", RepeaterEdit{Notes: "a\n \n\t\n \nb"}, false, func(t *testing.T, g RepeaterEdit) { + if g.Notes != "a\n\nb" { + t.Fatalf("notes = %q", g.Notes) + } + }}, + {"notes trailing spaces dropped per line", RepeaterEdit{Notes: "a \n b"}, false, func(t *testing.T, g RepeaterEdit) { + if g.Notes != "a\n b" { + t.Fatalf("notes = %q", g.Notes) + } + }}, + {"notes single newline kept", RepeaterEdit{Notes: "a\nb"}, false, func(t *testing.T, g RepeaterEdit) { + if g.Notes != "a\nb" { + t.Fatalf("notes = %q", g.Notes) + } + }}, + {"notes tab", RepeaterEdit{Notes: "a\tb"}, false, func(t *testing.T, g RepeaterEdit) { + if g.Notes != "a b" { + t.Fatalf("notes = %q", g.Notes) + } + }}, + {"notes lone CR", RepeaterEdit{Notes: "a\rb"}, false, func(t *testing.T, g RepeaterEdit) { + if g.Notes != "a b" { + t.Fatalf("notes = %q", g.Notes) + } + }}, + {"notes bidi", RepeaterEdit{Notes: "x" + string(rune(0x202e)) + "y" + string(rune(0x2067))}, false, func(t *testing.T, g RepeaterEdit) { + if g.Notes != "xy" { + t.Fatalf("notes = %q", g.Notes) + } + }}, + {"notes invalid utf8", RepeaterEdit{Notes: "a" + string([]byte{0xff}) + "b"}, false, func(t *testing.T, g RepeaterEdit) { + if g.Notes != "ab" { + t.Fatalf("notes = %q", g.Notes) + } + }}, + {"notes 500 padded", RepeaterEdit{Notes: " " + strings.Repeat("é", 500) + " "}, false, nil}, + {"notes 500", RepeaterEdit{Notes: strings.Repeat("é", 500)}, false, nil}, + {"notes 501", RepeaterEdit{Notes: strings.Repeat("é", 501)}, true, nil}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + got, err := ValidateRepeaterEdit(tc.in) + if tc.wantErr { + var ve *ValidationError + if !errors.As(err, &ve) || ve.Msg == "" { + t.Fatalf("err = %v, want *ValidationError with Msg", err) + } + return + } + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if tc.check != nil { + tc.check(t, got) + } + }) + } +} + +const rpk = "ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12ab12" +const rpk2 = "cd34cd34cd34cd34cd34cd34cd34cd34cd34cd34cd34cd34cd34cd34cd34cd34" + +func activeUser(t *testing.T, st *Store, email, name string) *User { + t.Helper() + u := mustCreate(t, st, email, name) + if err := st.Activate(u.ID, RoleUser, nil); err != nil { + t.Fatalf("Activate: %v", err) + } + got, err := st.GetByID(u.ID) + if err != nil { + t.Fatalf("GetByID: %v", err) + } + return got +} + +func TestRepeaterInfoSaveAndGet(t *testing.T) { + st, clk := newTestStore(t) + a := activeUser(t, st, "a@example.org", "Alice") + if _, err := st.GetRepeaterInfo(rpk); !errors.Is(err, ErrNotFound) { + t.Fatalf("Get before save = %v, want ErrNotFound", err) + } + prev, err := st.SaveRepeaterInfo(a.ID, rpk, RepeaterEdit{HeightM: fp(0), GainDBi: 2.5, Status: RepeaterStatusActive, Power: RepeaterPowerSolar, Notes: "first"}) + if err != nil || prev != nil { + t.Fatalf("first save prev=%v err=%v", prev, err) + } + got, err := st.GetRepeaterInfo(rpk) + if err != nil { + t.Fatal(err) + } + if got.HeightM == nil || *got.HeightM != 0 || got.GainDBi != 2.5 || got.Notes != "first" || + got.UpdatedBy == nil || *got.UpdatedBy != a.ID || got.UpdatedByName != "Alice" || !got.UpdatedAt.Equal(clk.Now()) { + t.Fatalf("got %+v", got) + } + clk.Advance(time.Hour) + prev, err = st.SaveRepeaterInfo(a.ID, rpk, RepeaterEdit{}) + if err != nil || prev == nil || prev.Notes != "first" || prev.HeightM == nil || prev.Status != RepeaterStatusActive { + t.Fatalf("second save prev=%+v err=%v", prev, err) + } + got, _ = st.GetRepeaterInfo(rpk) + if got.HeightM != nil || got.Status != "" || got.Power != "" { + t.Fatalf("after nil save: %+v", got) + } +} + +func TestRepeaterInfoSaveRejectsInvalid(t *testing.T) { + st, _ := newTestStore(t) + a := activeUser(t, st, "a@example.org", "Alice") + _, err := st.SaveRepeaterInfo(a.ID, rpk, RepeaterEdit{GainDBi: 31}) + var ve *ValidationError + if !errors.As(err, &ve) { + t.Fatalf("err = %v, want *ValidationError", err) + } + if _, err := st.GetRepeaterInfo(rpk); !errors.Is(err, ErrNotFound) { + t.Fatalf("row stored: %v", err) + } + if _, err := st.SaveRepeaterInfo(a.ID, "nope", RepeaterEdit{}); !errors.Is(err, ErrBadPubkey) { + t.Fatalf("bad pubkey err = %v", err) + } +} + +func TestRepeaterInfoUpperCasePubkey(t *testing.T) { + st, _ := newTestStore(t) + a := activeUser(t, st, "a@example.org", "Alice") + if _, err := st.SaveRepeaterInfo(a.ID, strings.ToUpper(rpk), RepeaterEdit{Notes: "x"}); err != nil { + t.Fatal(err) + } + got, err := st.GetRepeaterInfo(" " + rpk + " ") + if err != nil || got.Pubkey != rpk || got.Notes != "x" { + t.Fatalf("got %+v err %v", got, err) + } +} + +func TestRepeaterInfoEditorDeleted(t *testing.T) { + st, _ := newTestStore(t) + a := activeUser(t, st, "a@example.org", "Alice") + if _, err := st.SaveRepeaterInfo(a.ID, rpk, RepeaterEdit{Notes: "x"}); err != nil { + t.Fatal(err) + } + if err := st.Delete(a.ID); err != nil { + t.Fatal(err) + } + got, err := st.GetRepeaterInfo(rpk) + if err != nil || got.UpdatedBy != nil || got.UpdatedByName != "" || got.Notes != "x" { + t.Fatalf("got %+v err %v", got, err) + } +} + +func TestRepeaterClaimsMany(t *testing.T) { + st, clk := newTestStore(t) + a := activeUser(t, st, "a@example.org", "Alice") + b := activeUser(t, st, "b@example.org", "Bob") + if added, err := st.ClaimRepeater(a.ID, rpk); err != nil || !added { + t.Fatalf("A claim added=%v err=%v", added, err) + } + clk.Advance(time.Minute) + if added, err := st.ClaimRepeater(b.ID, strings.ToUpper(rpk)); err != nil || !added { + t.Fatalf("B claim added=%v err=%v", added, err) + } + if added, err := st.ClaimRepeater(a.ID, rpk); err != nil || added { + t.Fatalf("A re-claim added=%v err=%v", added, err) + } + cl, err := st.RepeaterClaims(rpk) + if err != nil || len(cl) != 2 || cl[0].UserID != a.ID || cl[0].DisplayName != "Alice" || cl[1].UserID != b.ID || cl[1].DisplayName != "Bob" { + t.Fatalf("claims %+v err %v", cl, err) + } + if by, _ := st.RepeaterClaimsByUser(a.ID); len(by) != 1 { + t.Fatalf("by user = %+v", by) + } + if err := st.UnclaimRepeater(a.ID, rpk); err != nil { + t.Fatal(err) + } + cl, _ = st.RepeaterClaims(rpk) + if len(cl) != 1 || cl[0].UserID != b.ID { + t.Fatalf("after unclaim %+v", cl) + } + if err := st.UnclaimRepeater(a.ID, rpk); !errors.Is(err, ErrNotFound) { + t.Fatalf("second unclaim = %v", err) + } +} + +func TestRepeaterClaimsCascadeOnDelete(t *testing.T) { + st, _ := newTestStore(t) + b := activeUser(t, st, "b@example.org", "Bob") + if _, err := st.ClaimRepeater(b.ID, rpk); err != nil { + t.Fatal(err) + } + if err := st.Delete(b.ID); err != nil { + t.Fatal(err) + } + if cl, err := st.RepeaterClaims(rpk); err != nil || len(cl) != 0 { + t.Fatalf("claims %+v err %v", cl, err) + } +} + +func TestCanEditRepeater(t *testing.T) { + st, _ := newTestStore(t) + a := activeUser(t, st, "a@example.org", "Alice") + b := activeUser(t, st, "b@example.org", "Bob") + c := activeUser(t, st, "c@example.org", "Carol") + if err := st.SetRole(c.ID, RoleAdmin); err != nil { + t.Fatal(err) + } + c, _ = st.GetByID(c.ID) + can := func(u *User, want bool, msg string) { + t.Helper() + got, err := st.CanEditRepeater(u, rpk) + if err != nil || got != want { + t.Fatalf("%s: got %v err %v, want %v", msg, got, err, want) + } + } + can(a, true, "unclaimed A") + if _, err := st.ClaimRepeater(b.ID, rpk); err != nil { + t.Fatal(err) + } + can(a, false, "claimed by B, A") + can(b, true, "claimed by B, B") + can(c, true, "admin") + if err := st.SetStatus(b.ID, StatusDisabled); err != nil { + t.Fatal(err) + } + can(a, true, "B disabled, A") + if cl, _ := st.RepeaterClaims(rpk); len(cl) != 0 { + t.Fatalf("claims visible for disabled: %+v", cl) + } + if by, _ := st.RepeaterClaimsByUser(b.ID); len(by) != 1 { + t.Fatalf("by user B = %+v", by) + } + b, _ = st.GetByID(b.ID) + can(b, false, "disabled B") +} + +func TestAllRepeaterClaimsAndList(t *testing.T) { + st, _ := newTestStore(t) + a := activeUser(t, st, "a@example.org", "Alice") + b := activeUser(t, st, "b@example.org", "Bob") + for _, pk := range []string{rpk, rpk2} { + for _, u := range []*User{a, b} { + if _, err := st.ClaimRepeater(u.ID, pk); err != nil { + t.Fatal(err) + } + } + } + if err := st.SetStatus(b.ID, StatusDisabled); err != nil { + t.Fatal(err) + } + m, err := st.AllRepeaterClaims() + if err != nil || len(m) != 2 || len(m[rpk]) != 1 || m[rpk][0].UserID != a.ID || len(m[rpk2]) != 1 { + t.Fatalf("map %+v err %v", m, err) + } + if _, err := st.SaveRepeaterInfo(a.ID, rpk2, RepeaterEdit{}); err != nil { + t.Fatal(err) + } + if _, err := st.SaveRepeaterInfo(a.ID, rpk, RepeaterEdit{}); err != nil { + t.Fatal(err) + } + l, err := st.ListRepeaterInfo() + if err != nil || len(l) != 2 || l[0].Pubkey != rpk || l[1].Pubkey != rpk2 { + t.Fatalf("list %+v err %v", l, err) + } +} diff --git a/internal/users/schema.go b/internal/users/schema.go index 670911584..c30d601fd 100644 --- a/internal/users/schema.go +++ b/internal/users/schema.go @@ -170,6 +170,26 @@ var migrations = [][]string{ `ALTER TABLE observer_bindings ADD COLUMN confirmed_at INTEGER`, `UPDATE observer_bindings SET confirmed_at = bound_at WHERE bound_by = 'auto'`, }, + // v9: repeater claims and community-maintained repeater details. + { + `CREATE TABLE repeater_claims ( + pubkey TEXT NOT NULL, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + claimed_at INTEGER NOT NULL, + PRIMARY KEY (pubkey, user_id) + )`, + `CREATE INDEX repeater_claims_user ON repeater_claims(user_id)`, + `CREATE TABLE repeater_info ( + pubkey TEXT PRIMARY KEY, + height_m REAL, + gain_dbi REAL NOT NULL DEFAULT 0, + status TEXT CHECK (status IN ('active','maintenance','decommissioned')), + power TEXT CHECK (power IN ('mains','battery','solar')), + notes TEXT NOT NULL DEFAULT '', + updated_at INTEGER NOT NULL, + updated_by INTEGER REFERENCES users(id) ON DELETE SET NULL + )`, + }, } func (s *Store) migrate() error { diff --git a/internal/users/schema_v9_test.go b/internal/users/schema_v9_test.go new file mode 100644 index 000000000..64d2e5592 --- /dev/null +++ b/internal/users/schema_v9_test.go @@ -0,0 +1,29 @@ +package users + +import "testing" + +func TestMigrateToV9CreatesRepeaterTables(t *testing.T) { + st, _ := newTestStore(t) + if v, err := st.SchemaVersion(); err != nil || v < 9 || v != len(migrations) { + t.Fatalf("SchemaVersion = %d, %v; want >= 9 and %d", v, err, len(migrations)) + } + pk := "aa" + if _, err := st.db.Exec(`INSERT INTO repeater_info (pubkey, status, updated_at) VALUES (?, 'planned', 1)`, pk); err == nil { + t.Fatal("status 'planned' accepted, want CHECK violation") + } + if _, err := st.db.Exec(`INSERT INTO repeater_info (pubkey, power, updated_at) VALUES (?, 'wind', 1)`, pk); err == nil { + t.Fatal("power 'wind' accepted, want CHECK violation") + } + if _, err := st.db.Exec(`INSERT INTO repeater_info (pubkey, status, power, updated_at) VALUES (?, 'active', 'solar', 1)`, pk); err != nil { + t.Fatalf("valid repeater_info row rejected: %v", err) + } + if _, err := st.db.Exec(`INSERT INTO users (email, display_name, password_hash, created_at) VALUES ('a@example.org', 'Aa', 'x', 1)`); err != nil { + t.Fatal(err) + } + if _, err := st.db.Exec(`INSERT INTO repeater_claims (pubkey, user_id, claimed_at) VALUES (?, 1, 1)`, pk); err != nil { + t.Fatalf("first claim: %v", err) + } + if _, err := st.db.Exec(`INSERT INTO repeater_claims (pubkey, user_id, claimed_at) VALUES (?, 1, 2)`, pk); err == nil { + t.Fatal("duplicate claim accepted, want unique violation") + } +} diff --git a/public/account.js b/public/account.js index 9345dbf3c..e8ed60634 100644 --- a/public/account.js +++ b/public/account.js @@ -119,7 +119,7 @@ (window.CSSettingsSync ? '

Settings sync

' : '') + '

My data

' + '' + - '' + + '' + '

Delete account