diff --git a/docs/companion-development.md b/docs/companion-development.md index 9f5100d9..22aaeb25 100644 --- a/docs/companion-development.md +++ b/docs/companion-development.md @@ -31,9 +31,10 @@ bash scripts/dev-all.sh start bash scripts/dev-all.sh status ``` -`start` keeps an already healthy UKMesh fixture running. Otherwise it resumes -the prepared fixture, or creates one using the existing DEV stack command. -There is no reset or cleanup action in this launcher. +`start` runs the complete lean stack, including workers, websites and monitoring. +It resumes retained fixture storage or prepares it on first use. Builds run one +at a time. There is no reset or data deletion action in this launcher. See +[the lean runtime guide](lean-runtime.md) for resource overrides and qualification. | App | Local URL | | --- | --- | @@ -59,9 +60,11 @@ fixture, so its default map does not need a CARTO API key. The production networ and deployment Compose files are not used. -Edit any repository directly in its `third_party` checkout. Beacon Web uses -Vite with hot reload. CoreScope serves the checkout's static files; refresh the -browser after editing them. Rebuild and restart a Go service after changing it: +Edit any repository directly in its `third_party` checkout. Websites serve built +assets by default. Use `bash scripts/dev-all.sh hot beacon-web` for Vite, or +`bash scripts/dev-all.sh hot ukmesh` for the UKMesh frontend. A normal `start` +returns to built assets. CoreScope serves its checkout's static files. Restart +the service that owns a change; only its component is rebuilt: ```sh bash scripts/dev-all.sh restart corescope-ingestor @@ -70,7 +73,8 @@ bash scripts/dev-all.sh restart beacon bash scripts/dev-all.sh logs beacon ``` -`build` builds the Go binaries without starting services. The launcher discards +`build` builds application images, companion binaries and web assets without +starting services. The launcher discards inherited application settings and passes Compose an empty env file. The apps use explicit fixture configuration, and Beacon Web selects an empty Vite env directory. A deployment `.env` is not needed. @@ -80,7 +84,7 @@ bash scripts/dev-all.sh stop bash scripts/dev-all.sh start ``` -`stop` stops companions and the prepared UKMesh fixture and retains their data. +`stop` stops the complete stack and retains its data. Use `companions` instead of `start` to start only companions against an already running sample broker. diff --git a/docs/lean-runtime.md b/docs/lean-runtime.md new file mode 100644 index 00000000..8553c5b4 --- /dev/null +++ b/docs/lean-runtime.md @@ -0,0 +1,75 @@ +# Complete lean runtime + +The main Compose configuration supplies resource ceilings and connection-pool +defaults for the complete service set. Larger hosts can raise its documented +environment overrides. Feature switches, history, visibility rules, query +deadlines and public response limits retain their existing meanings. + +Local DEV starts the complete stack with built frontend assets: + +```sh +bash scripts/dev-all.sh build +bash scripts/dev-all.sh start +bash scripts/dev-all.sh status +``` + +Use `sg docker -c 'bash scripts/dev-all.sh start'` when the current shell has +not picked up membership of the Docker group. Commands use explicit local +configuration and do not read a deployment `.env`. + +| Service | Local URL | +| --- | --- | +| Public website | http://127.0.0.1:5173 | +| Dashboard | http://127.0.0.1:3003 | +| DEV website | http://127.0.0.1:3005 | +| UKMesh API | http://127.0.0.1:3100 | +| CoreScope | http://127.0.0.1:3102 | +| Beacon | http://127.0.0.1:5175 | +| Beacon API | http://127.0.0.1:3103 | +| Health Check | http://127.0.0.1:3090 | +| Grafana | http://127.0.0.1:3010 | +| Prometheus | http://127.0.0.1:9090 | +| Protected website/dashboard/health ingress | http://127.0.0.1:8923 / 8924 / 8925 | + +`hot ukmesh` or `hot beacon-web` enables Vite while editing. `start` restores +built assets. `stop` stops consumers before infrastructure and retains stores. +The migration, data initialization and historical link-backfill jobs complete +and exit; successful exit is their expected healthy state. + +Local overrides provide fixture credentials, owned storage and loopback +ingress. Tagging and alert delivery use the local test endpoint, and Health +Check uses the public `#test` channel on the local broker. The public tunnel is +off. Local Anubis derives client identity from the TCP peer; its downstream +proxies trust that overwritten identity rather than incoming Cloudflare headers. + +UKMesh runtime processes use separate API, ingest, worker, owner and monitoring +credentials. Only the bounded migration/bootstrap step receives the local +administrator credential. Explicit relation grants preserve existing business +writes and worker operations. Learning has temporary-table access; it cannot +create permanent schema objects. CoreScope's optional PostgreSQL reader uses +privacy-filtered projections and the narrow metadata needed to revoke copies. + +Qualification owns backups, fixture selection, workload generation, probes and +reports separately. Original backup receipts require actual restore checks. +Fixture switching validates cluster identity, ownership markers and source +checksums, then changes targets through brief service restarts. Original stores +and retained lookup fixtures remain available for restoration. + +```sh +bash scripts/dev-all.sh qualify backup +bash scripts/dev-all.sh qualify inventory +bash scripts/dev-all.sh qualify smoke +``` + +The executable service inventory and native work oracles must agree with the +resolved configurations. A running process or HTTP 200 alone does not establish +completed work. Missing, skipped, stale or mismatched evidence prevents a clean +qualification. Reports retain failures and resource settings under ignored +`plans/lean-runtime/`; private archive content must not enter Git. + +The VM gates remain 100/250 ms interactive p95 at 1×/10×, eight concurrent +requests, at most 3 GiB runtime working memory, at least 384 MiB host available +memory in 95% of steady samples, ten reserved PostgreSQL connections and +10 GiB free disk. Sustained qualification retains 72,000 ACKs at 30/second for +40 minutes, with explicit native expectations for additional typed traffic. +F2 and deployment to the VPS remain deferred. diff --git a/healthcheck-overrides/ukmesh-theme.css b/healthcheck-overrides/ukmesh-theme.css index 5d062c01..1aad8162 100644 --- a/healthcheck-overrides/ukmesh-theme.css +++ b/healthcheck-overrides/ukmesh-theme.css @@ -83,6 +83,11 @@ body[data-ui-theme="light"] { padding-top: 20px; } +.splash-scene { + inset-inline: 0; + width: 100%; +} + .ukmesh-topbar__brand { display: flex; align-items: center; diff --git a/scripts/companion-dev/artifacts.py b/scripts/companion-dev/artifacts.py new file mode 100644 index 00000000..a7eb3f16 --- /dev/null +++ b/scripts/companion-dev/artifacts.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Publish a complete web build and its revision, retaining crash recovery.""" +from __future__ import annotations + +import argparse +import os +from pathlib import Path +import re +import shutil + + +def paths(state: Path) -> tuple[Path, Path, Path]: + values = tuple(state / name for name in ('beacon-web', 'beacon-web.next', 'beacon-web.previous')) + if any(value.is_symlink() for value in values): + raise ValueError('Static artifact directories must not be symbolic links') + return values + + +def recover_web(state: Path) -> None: + active, _, previous = paths(state) + if previous.exists(): + if active.exists(): + shutil.rmtree(previous) + else: + os.replace(previous, active) + + +def prepare_web(state: Path) -> None: + recover_web(state) + _, staged, _ = paths(state) + if staged.exists(): + shutil.rmtree(staged) + staged.mkdir() + + +def web_revision(state: Path) -> str: + active = state / 'beacon-web' + if active.is_symlink() or not (active / 'index.html').is_file(): + return 'unknown' + marker = active / '.ukmesh-source-revision' + # Preserve the previous launcher's cache until its first complete rebuild. + if not marker.exists(): + marker = state / 'web-source' + revision = marker.read_text().strip() if marker.exists() and not marker.is_symlink() else '' + return revision if re.fullmatch('[a-f0-9]{64}', revision) else 'unknown' + + +def publish_web(state: Path, revision: str) -> None: + if not re.fullmatch('[a-f0-9]{64}', revision): + raise ValueError('A complete source revision is required') + recover_web(state) + active, staged, previous = paths(state) + if not (staged / 'index.html').is_file(): + raise ValueError('Beacon static build is incomplete') + (staged / '.ukmesh-source-revision').write_text(revision + '\n') + if active.exists(): + os.replace(active, previous) + try: + os.replace(staged, active) + except BaseException: + if previous.exists() and not active.exists(): + os.replace(previous, active) + raise + if previous.exists(): + shutil.rmtree(previous) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('action', choices=('recover-web', 'prepare-web', 'publish-web', 'web-revision')) + parser.add_argument('revision', nargs='?') + args = parser.parse_args() + state = Path(__file__).resolve().parents[2] / 'plans/companion-dev/runtime' + if args.action == 'publish-web': + publish_web(state, args.revision or '') + elif args.action == 'web-revision': + print(web_revision(state)) + else: + {'recover-web': recover_web, 'prepare-web': prepare_web}[args.action](state) + + +if __name__ == '__main__': + main() diff --git a/scripts/companion-dev/beacon-access.sh b/scripts/companion-dev/beacon-access.sh new file mode 100644 index 00000000..a85aa8e0 --- /dev/null +++ b/scripts/companion-dev/beacon-access.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +set -euo pipefail +repo=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd) +if [[ ${UKMESH_BEACON_ACCESS_CLEAN:-} != 1 ]]; then + exec env -i PATH="$PATH" HOME="$HOME" LANG=C.UTF-8 UKMESH_BEACON_ACCESS_CLEAN=1 bash "$repo/scripts/companion-dev/beacon-access.sh" "$@" +fi +[[ $# == 1 ]] || { echo 'usage: scripts/companion-dev/beacon-access.sh DATABASE' >&2; exit 2; } +database=$1 +[[ $database == beacon_dev || $database =~ ^lean_beacon_[a-z0-9_]+$ ]] || { echo 'Unowned Beacon database' >&2; exit 2; } +docker=(docker --host unix:///var/run/docker.sock) +container=ukmesh-companions-beacon-db-1 +project=$("${docker[@]}" inspect "$container" --format '{{index .Config.Labels "com.docker.compose.project"}}') +[[ $project == ukmesh-companions ]] || { echo 'Beacon database container ownership differs' >&2; exit 1; } +if [[ $database == lean_* ]]; then + marker=$("${docker[@]}" exec "$container" psql -X -U beacon_dev -d postgres -At -v ON_ERROR_STOP=1 \ + -c "SELECT shobj_description(oid,'pg_database') FROM pg_database WHERE datname='$database'") + [[ $marker == "ukmesh-owned-fixture:${database#lean_beacon_}" ]] || { echo 'Beacon fixture ownership marker differs' >&2; exit 1; } +fi +"${docker[@]}" exec -i "$container" psql -X -U beacon_dev -d "$database" -v ON_ERROR_STOP=1 -v "beacon_database=$database" \ + < "$repo/third_party/beacon-server/deploy/ukmesh-dev/access.sql" diff --git a/scripts/companion-dev/beacon.yaml b/scripts/companion-dev/beacon.yaml index 2f1f21bf..efcf2a75 100644 --- a/scripts/companion-dev/beacon.yaml +++ b/scripts/companion-dev/beacon.yaml @@ -9,7 +9,11 @@ cors: allowed_origins: ["http://127.0.0.1:5175", "http://localhost:5175"] iatas: LON: {name: London} + LHR: {name: London Heathrow} regions: - slug: dev name: DEV fixture - iatas: [LON] + iatas: [LON, LHR] +channel_keys: + hashtags: + - name: test diff --git a/scripts/companion-dev/build-beacon.sh b/scripts/companion-dev/build-beacon.sh new file mode 100644 index 00000000..22d44d50 --- /dev/null +++ b/scripts/companion-dev/build-beacon.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail +cd /src/beacon-server +go build -trimpath -o /out/beacon.next ./cmd/beacon +mv /out/beacon.next /out/beacon diff --git a/scripts/companion-dev/build-corescope.sh b/scripts/companion-dev/build-corescope.sh new file mode 100644 index 00000000..ab6669c6 --- /dev/null +++ b/scripts/companion-dev/build-corescope.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +set -euo pipefail +mkdir -p /tmp/corescope +tar -C /src/corescope --exclude=node_modules --exclude=dist --exclude=.git -cf - . | tar -C /tmp/corescope -xf - +cd /tmp/corescope +# SQLite requires the repository's native cgo build flags. +make build-server build-ingestor GIT_VERSION=ukmesh-dev GIT_COMMIT="${COMPANION_CORESCOPE_COMMIT:-unknown}" +for executable in corescope-server corescope-ingestor; do + cp "dist/$executable" "/out/$executable.next" + mv "/out/$executable.next" "/out/$executable" +done diff --git a/scripts/companion-dev/build.sh b/scripts/companion-dev/build.sh index 5c59f9f8..783bdca7 100755 --- a/scripts/companion-dev/build.sh +++ b/scripts/companion-dev/build.sh @@ -1,14 +1,9 @@ #!/usr/bin/env bash set -euo pipefail -mkdir -p /tmp/corescope -tar -C /src/corescope --exclude=node_modules --exclude=dist --exclude=.git -cf - . | tar -C /tmp/corescope -xf - -cd /tmp/corescope -# Use the repo's cgo build flags; both binaries share SQLite's native driver. -make build-server build-ingestor GIT_VERSION=ukmesh-dev GIT_COMMIT="${COMPANION_CORESCOPE_COMMIT:-unknown}" -for executable in corescope-server corescope-ingestor; do - cp "dist/$executable" "/out/$executable.next" - mv "/out/$executable.next" "/out/$executable" -done -cd /src/beacon-server -go build -trimpath -o /out/beacon.next ./cmd/beacon -mv /out/beacon.next /out/beacon +case "${1:-all}" in + corescope|beacon) exec bash "/dev-tools/build-$1.sh" ;; + all) + bash /dev-tools/build-corescope.sh + exec bash /dev-tools/build-beacon.sh ;; + *) echo 'Unknown companion build target' >&2; exit 2 ;; +esac diff --git a/scripts/companion-dev/compose.yml b/scripts/companion-dev/compose.yml index 144204bc..9883edbe 100644 --- a/scripts/companion-dev/compose.yml +++ b/scripts/companion-dev/compose.yml @@ -52,9 +52,13 @@ services: mem_limit: 128m corescope-ingestor: <<: *go + environment: + <<: *go-env + COMPANION_SOURCE_REVISION: ${COMPANION_CORESCOPE_SOURCE:-unknown} + COMPANION_CONFIG_REVISION: ${COMPANION_CORESCOPE_CONFIG:-unknown} volumes: - ../../plans/companion-dev/runtime/bin:/bin/companions:ro - - ../../plans/companion-dev/runtime/corescope:/data + - ${CORESCOPE_DATA_DIR:-../../plans/companion-dev/runtime/corescope}:/data - ./corescope.json:/config/config.json:ro # Absolute executable paths avoid PATH or inherited environment overrides. entrypoint: [/bin/companions/corescope-ingestor, -config, /config/config.json] @@ -70,12 +74,16 @@ services: stop_grace_period: 30s corescope: <<: *go + environment: + <<: *go-env + COMPANION_SOURCE_REVISION: ${COMPANION_CORESCOPE_SOURCE:-unknown} + COMPANION_CONFIG_REVISION: ${COMPANION_CORESCOPE_CONFIG:-unknown} entrypoint: [/bin/companions/corescope-server, -config-dir, /config, -public, /public] command: [] ports: ["127.0.0.1:3102:3000"] volumes: - ../../plans/companion-dev/runtime/bin:/bin/companions:ro - - ../../plans/companion-dev/runtime/corescope:/data + - ${CORESCOPE_DATA_DIR:-../../plans/companion-dev/runtime/corescope}:/data - ../../third_party/corescope/public:/public:ro - ./corescope.json:/config/config.json:ro depends_on: @@ -87,6 +95,19 @@ services: retries: 60 start_period: 5s mem_limit: 384m + beacon-migrate: + <<: *go + entrypoint: [/bin/companions/beacon, --migrate-only, --attest-migrations] + command: [] + environment: + <<: *go-env + POSTGRES_DSN: postgres://beacon_dev:local-companion-only@beacon-db:5432/${BEACON_DATABASE:-beacon_dev}?sslmode=disable + volumes: + - ../../plans/companion-dev/runtime/bin:/bin/companions:ro + depends_on: + beacon-db: {condition: service_healthy} + restart: "no" + mem_limit: 256m beacon: <<: *go entrypoint: [/bin/companions/beacon] @@ -95,7 +116,11 @@ services: environment: <<: *go-env LISTEN_ADDR: ":8080" - POSTGRES_DSN: postgres://beacon_dev:local-companion-only@beacon-db:5432/beacon_dev?sslmode=disable + COMPANION_SOURCE_REVISION: ${COMPANION_BEACON_SOURCE:-unknown} + COMPANION_CONFIG_REVISION: ${COMPANION_BEACON_CONFIG:-unknown} + POSTGRES_DSN: postgres://beacon_runtime:local-full-dev-only@beacon-db:5432/${BEACON_DATABASE:-beacon_dev}?sslmode=disable + BEACON_MAINTENANCE_DSN: postgres://beacon_maint:local-full-dev-only@beacon-db:5432/${BEACON_DATABASE:-beacon_dev}?sslmode=disable + BEACON_EXTERNAL_MIGRATIONS: "1" REDIS_ADDR: beacon-redis:6379 CONFIG_PATH: /config/beacon.yaml MQTT_BROKER_1_URL: tcp://ukmesh-sample-mqtt:1883 @@ -107,6 +132,7 @@ services: depends_on: beacon-db: {condition: service_healthy} beacon-redis: {condition: service_healthy} + beacon-migrate: {condition: service_completed_successfully} healthcheck: test: [CMD, curl, --fail, --silent, http://127.0.0.1:8080/api/v1/info] interval: 3s @@ -114,32 +140,48 @@ services: retries: 60 mem_limit: 384m stop_grace_period: 30s - beacon-web: - image: node@sha256:5df79989ed685e09f0a98019db4cebfb22fb9df1a53c0161664a011f7ff6b0f1 # 26-bookworm-slim + web-build: + image: node@sha256:5df79989ed685e09f0a98019db4cebfb22fb9df1a53c0161664a011f7ff6b0f1 + profiles: [tools] user: "${COMPANION_UID:-1000}:${COMPANION_GID:-1000}" - init: true working_dir: /work environment: HOME: /tmp VITE_API_BASE: /api/v1 BEACON_DEV_ENV_DIR: /tmp/ukmesh-empty-env - VITE_DEV_PROXY: http://beacon:8080 - ports: ["127.0.0.1:5175:5175"] volumes: - ../../third_party/beacon-web:/work:ro - ../../third_party/beacon-web/node_modules:/work/node_modules - ../../plans/companion-dev/runtime/npm-cache:/npm-cache + - ../../plans/companion-dev/runtime/beacon-web.next:/out - .:/dev-tools:ro - entrypoint: [sh, /dev-tools/web-start.sh] + entrypoint: [sh, /dev-tools/web-build.sh] + mem_limit: 1200m + beacon-web: + image: ${APP_IMAGE:-ukmesh-full-app:local} + environment: + COMPANION_SOURCE_REVISION: ${COMPANION_WEB_SOURCE:-unknown} + COMPANION_CONFIG_REVISION: ${COMPANION_WEB_CONFIG:-unknown} + ports: ["127.0.0.1:5175:8080"] + volumes: + - ../../plans/companion-dev/runtime/beacon-web:/usr/share/nginx/html:ro + - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + tmpfs: + - /tmp:rw,noexec,nosuid,size=16m,mode=1777 + - /var/cache/nginx:rw,noexec,nosuid,size=32m,uid=101,gid=101,mode=0755 + - /var/run:rw,noexec,nosuid,size=4m,uid=101,gid=101,mode=0755 depends_on: beacon: {condition: service_healthy} healthcheck: - test: [CMD, node, -e, "fetch('http://127.0.0.1:5175').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"] - interval: 3s + test: [CMD-SHELL, "wget -qO- http://127.0.0.1:8080/ >/dev/null && wget -qO- http://127.0.0.1:8080/api/v1/info >/dev/null"] + interval: 5s timeout: 3s - retries: 60 - start_period: 10s - mem_limit: 768m + retries: 30 + mem_limit: 48m + volumes: beacon-db: networks: diff --git a/scripts/companion-dev/control.sh b/scripts/companion-dev/control.sh new file mode 100644 index 00000000..e374d14d --- /dev/null +++ b/scripts/companion-dev/control.sh @@ -0,0 +1,176 @@ +#!/usr/bin/env bash +# Local fixture stack plus three independently editable companion repositories. +set -euo pipefail +repo=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd) +if [[ ${UKMESH_COMPANION_ENV_CLEAN:-} != 1 ]]; then + exec env -i PATH="$PATH" HOME="$HOME" LANG=C.UTF-8 UKMESH_COMPANION_ENV_CLEAN=1 bash "$repo/scripts/companion-dev/control.sh" "$@" +fi +cd "$repo" +action=${1:-start} +service=${2:-} +case "$action" in + help|--help) + echo 'scripts/dev-all.sh [start|companions|build|status|stop|logs [SERVICE]|restart SERVICE|init]' + echo 'start resumes or creates the UKMesh fixture, then starts companions. stop retains all data.' + echo 'restart rebuilds Go binaries before restarting the named companion. No reset or data deletion.' + exit 0 ;; + start|companions|build|status|stop|logs|restart|init|hot) ;; + *) echo "Unknown action: $action" >&2; exit 2 ;; +esac +services=(corescope corescope-ingestor beacon beacon-web beacon-db beacon-redis beacon-migrate) +if [[ -n $service ]]; then + valid=false + for candidate in "${services[@]}"; do [[ $candidate != "$service" ]] || valid=true; done + [[ $valid == true ]] || { echo "Unknown companion: $service" >&2; exit 2; } +fi +if [[ $action == restart && -z $service ]]; then echo 'restart requires a companion service name' >&2; exit 2; fi +lock_dir="$repo/plans/companion-dev" +mkdir -p "$lock_dir" +chmod 700 "$lock_dir" +if [[ $action != status && $action != logs && ${UKMESH_COMPANION_LOCKED:-} != 1 ]]; then + if flock --nonblock --close --conflict-exit-code 75 "$lock_dir/control.lock" \ + env UKMESH_COMPANION_LOCKED=1 bash "$repo/scripts/companion-dev/control.sh" "$@"; then exit 0; else + result=$? + if [[ $result == 75 ]]; then echo 'Another DEV operation is running; let it finish before starting a new one.' >&2; fi + exit "$result" + fi +fi +if [[ $action == init ]]; then + for name in corescope beacon-server beacon-web; do + path="third_party/$name" + # Preserve existing branches, edits and pending merges. + if [[ ! -e $path/.git ]]; then git submodule update --init -- "$path"; fi + if ! git -C "$path" remote get-url upstream >/dev/null 2>&1; then + case "$name" in + corescope) upstream=https://github.com/Kpa-clawbot/CoreScope.git ;; + *) upstream="https://github.com/MeshCore-Beacon/$name.git" ;; + esac + git -C "$path" remote add upstream "$upstream" + fi + if [[ -z $(git -C "$path" symbolic-ref --short -q HEAD) ]]; then git -C "$path" switch -c ukmesh-dev; fi + done + exit 0 +fi +command -v docker >/dev/null || { echo 'Docker Engine and Compose are required' >&2; exit 1; } +docker info >/dev/null +export COMPANION_UID=$(id -u) COMPANION_GID=$(id -g) +source "$repo/scripts/full-dev/environment.sh" +compose=(docker compose --project-name ukmesh-companions --env-file /dev/null -f "$repo/scripts/companion-dev/compose.yml") +state="$repo/plans/companion-dev/runtime" +mkdir -p "$state/bin" "$state/corescope" "$state/npm-cache" "$repo/plans/companion-dev/go-cache" "$repo/plans/companion-dev/go-mod" +chmod 700 "$repo/plans/companion-dev" "$state" +case "$action" in + status) + "${compose[@]}" ps + for name in corescope beacon-server beacon-web; do git -C "third_party/$name" status --short --branch; done + exit 0 ;; + logs) "${compose[@]}" logs --tail 100 ${service:+"$service"}; exit 0 ;; + stop) + "${compose[@]}" stop + exit 0 ;; +esac +case "$action:$service" in + start:*|companions:*|build:*|restart:beacon-web) + python3 "$repo/scripts/companion-dev/artifacts.py" recover-web ;; +esac +# Load the published revisions even when only another component is requested. +# A dependency must not acquire "unknown" and be recreated incidentally. +for component in corescope beacon; do + published=unknown + if [[ -f $state/$component-source ]]; then published=$(cat "$state/$component-source"); fi + [[ $published =~ ^[a-f0-9]{64}$ ]] || published=unknown + if [[ $component == corescope ]]; then + export COMPANION_CORESCOPE_SOURCE=$published + else + export COMPANION_BEACON_SOURCE=$published + fi +done +COMPANION_WEB_SOURCE=$(python3 "$repo/scripts/companion-dev/artifacts.py" web-revision) +export COMPANION_WEB_SOURCE +for setting in CORESCOPE:corescope.json BEACON:beacon.yaml WEB:nginx.conf; do + name=${setting%%:*} file=${setting#*:} + revision=$(sha256sum "$repo/scripts/companion-dev/$file") + export "COMPANION_${name}_CONFIG=${revision%% *}" +done +projects=(corescope beacon-server beacon-web) +case "$action:$service" in + restart:corescope|restart:corescope-ingestor) projects=(corescope) ;; + restart:beacon|restart:beacon-migrate) projects=(beacon-server) ;; + restart:beacon-web|hot:beacon-web) projects=(beacon-web) ;; + restart:beacon-db|restart:beacon-redis) projects=() ;; +esac +for name in "${projects[@]}"; do + [[ -e "third_party/$name/.git" ]] || { echo "Missing $name; run scripts/dev-all.sh init" >&2; exit 1; } + if [[ -n $(git -C "third_party/$name" diff --name-only --diff-filter=U) ]]; then + echo "Resolve the $name merge before starting companions" >&2; exit 1 + fi +done +if [[ $action != build ]]; then + docker network inspect ukmesh-sample_default >/dev/null 2>&1 || { echo 'Start the UKMesh fixture first with scripts/dev-all.sh start' >&2; exit 1; } +fi +components=() +case "$action:$service" in + build:*|start:*|companions:*) components=(corescope beacon) ;; + restart:corescope|restart:corescope-ingestor) components=(corescope) ;; + restart:beacon|restart:beacon-migrate) components=(beacon) ;; +esac +for component in "${components[@]}"; do + if [[ $component == corescope ]]; then + COMPANION_CORESCOPE_COMMIT=$(git -C third_party/corescope rev-parse --short HEAD) + COMPANION_CORESCOPE_SOURCE=$(python3 "$repo/scripts/companion-dev/source-hash.py" corescope) + export COMPANION_CORESCOPE_COMMIT COMPANION_CORESCOPE_SOURCE + source_hash=$COMPANION_CORESCOPE_SOURCE + binaries=(corescope-server corescope-ingestor) + else + COMPANION_BEACON_SOURCE=$(python3 "$repo/scripts/companion-dev/source-hash.py" beacon) + export COMPANION_BEACON_SOURCE + source_hash=$COMPANION_BEACON_SOURCE + binaries=(beacon) + fi + ready=true + for executable in "${binaries[@]}"; do [[ -x $state/bin/$executable ]] || ready=false; done + if [[ $action == build || $ready != true || ! -f $state/$component-source || $(cat "$state/$component-source") != "$source_hash" ]]; then + "${compose[@]}" run --rm --no-deps build "$component" + printf '%s\n' "$source_hash" > "$state/$component-source" + fi +done +if [[ $action == hot ]]; then + [[ $service == beacon-web ]] || { echo 'Only beacon-web supports companion hot reload' >&2; exit 2; } + "${compose[@]}" -f "$repo/scripts/companion-dev/hot.yml" up -d --no-deps --force-recreate beacon-web + exit +fi +if [[ $action == build || $action == start || $action == companions || ( $action == restart && $service == beacon-web ) ]]; then + web_hash=$(python3 "$repo/scripts/companion-dev/source-hash.py" web) + if [[ $action == build || ! -f $state/beacon-web/index.html || $COMPANION_WEB_SOURCE != "$web_hash" ]]; then + python3 "$repo/scripts/companion-dev/artifacts.py" prepare-web + "${compose[@]}" run --rm --no-deps web-build + python3 "$repo/scripts/companion-dev/artifacts.py" publish-web "$web_hash" + fi + export COMPANION_WEB_SOURCE=$web_hash +fi +if [[ $action == build ]]; then exit 0; fi +if [[ $action == start || $action == companions || ( $action == restart && $service == beacon* && $service != beacon-web ) ]]; then + "${compose[@]}" up -d --wait beacon-db beacon-redis + if [[ $action == restart && $service == beacon-migrate ]]; then + "${compose[@]}" up -d --no-deps --force-recreate beacon-migrate + "${compose[@]}" wait beacon-migrate + migration_container=$("${compose[@]}" ps -a -q beacon-migrate) + [[ -n $migration_container ]] || { echo 'Beacon migration container is missing' >&2; exit 1; } + migration_state=$(docker inspect --format '{{.State.Status}}:{{.State.ExitCode}}' "$migration_container") + [[ $migration_state == exited:0 ]] || { echo 'Beacon migration job failed or did not complete' >&2; exit 1; } + bash "$repo/scripts/companion-dev/beacon-access.sh" "$BEACON_DATABASE" + exit 0 + fi + "${compose[@]}" run --rm --no-deps beacon-migrate + bash "$repo/scripts/companion-dev/beacon-access.sh" "$BEACON_DATABASE" +fi +if [[ $action == restart ]]; then + targets=("$service") + # The shared Core build publishes both binaries; keep the running pair on + # that same revision after replacing either process. + if [[ $service == corescope || $service == corescope-ingestor ]]; then targets=(corescope-ingestor corescope); fi + "${compose[@]}" up -d --no-deps --force-recreate --wait --wait-timeout 180 "${targets[@]}" +else + "${compose[@]}" up -d --wait --wait-timeout 240 +fi +printf 'UKMesh http://127.0.0.1:5173\nCoreScope http://127.0.0.1:3102\nBeacon http://127.0.0.1:5175 (API http://127.0.0.1:3103)\n' diff --git a/scripts/companion-dev/corescope.json b/scripts/companion-dev/corescope.json index aa07ae74..ff58a908 100644 --- a/scripts/companion-dev/corescope.json +++ b/scripts/companion-dev/corescope.json @@ -35,5 +35,8 @@ } } } + }, + "channelKeys": { + "#test": "9cd8fcf22a47333b591d96a2b848b73f" } } diff --git a/scripts/companion-dev/hot.yml b/scripts/companion-dev/hot.yml new file mode 100644 index 00000000..27f44741 --- /dev/null +++ b/scripts/companion-dev/hot.yml @@ -0,0 +1,21 @@ +services: + beacon-web: + image: node@sha256:5df79989ed685e09f0a98019db4cebfb22fb9df1a53c0161664a011f7ff6b0f1 + user: "${COMPANION_UID:-1000}:${COMPANION_GID:-1000}" + init: true + working_dir: /work + environment: + HOME: /tmp + VITE_API_BASE: /api/v1 + BEACON_DEV_ENV_DIR: /tmp/ukmesh-empty-env + VITE_DEV_PROXY: http://beacon:8080 + ports: !override ["127.0.0.1:5175:5175"] + volumes: !override + - ../../third_party/beacon-web:/work:ro + - ../../third_party/beacon-web/node_modules:/work/node_modules + - ../../plans/companion-dev/runtime/npm-cache:/npm-cache + - .:/dev-tools:ro + entrypoint: [sh, /dev-tools/web-start.sh] + healthcheck: + test: [CMD, node, -e, "fetch('http://127.0.0.1:5175').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"] + mem_limit: 768m diff --git a/scripts/companion-dev/nginx.conf b/scripts/companion-dev/nginx.conf new file mode 100644 index 00000000..cd3b9cdc --- /dev/null +++ b/scripts/companion-dev/nginx.conf @@ -0,0 +1,29 @@ +server { + listen 8080; + root /usr/share/nginx/html; + resolver 127.0.0.11 valid=10s ipv6=off; + location /api/ { + set $api http://beacon:8080; + proxy_pass $api; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $remote_addr; + } + location /ws { + set $api http://beacon:8080; + proxy_pass $api; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $remote_addr; + proxy_read_timeout 3600s; + } + location /assets/ { + add_header Cache-Control "public, max-age=31536000, immutable"; + try_files $uri =404; + } + location / { + add_header Cache-Control "no-cache"; + try_files $uri $uri/index.html /index.html; + } +} diff --git a/scripts/companion-dev/source-hash.py b/scripts/companion-dev/source-hash.py new file mode 100644 index 00000000..f707503e --- /dev/null +++ b/scripts/companion-dev/source-hash.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Fingerprint build inputs, including new source files, without dependency caches.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess +import yaml + +PROJECTS = {'corescope': 'corescope', 'beacon': 'beacon-server', 'web': 'beacon-web'} + + +def fingerprint(root: Path, mode: str) -> str: + root = root.resolve() + digest = hashlib.sha256() + tools = root / 'scripts/companion-dev' + builder = tools / ('web-build.sh' if mode == 'web' else f'build-{mode}.sh') + digest.update(builder.read_bytes()) + if mode != 'web': + digest.update((tools / 'build.sh').read_bytes()) + configuration = yaml.safe_load((tools / 'compose.yml').read_text()) + recipe = configuration['services']['web-build' if mode == 'web' else 'build'] + # Compiler image/flags and frontend build variables are build inputs too; + # runtime-only configuration must not rebuild an unrelated component. + digest.update(json.dumps({key: recipe.get(key) for key in + ('image', 'entrypoint', 'working_dir', 'environment')}, sort_keys=True).encode()) + project = PROJECTS[mode] + checkout = root / 'third_party' / project + digest.update(subprocess.check_output(['git', '-C', str(checkout), 'rev-parse', 'HEAD'])) + paths = subprocess.check_output(['git', '-C', str(checkout), 'ls-files', '-z', '--cached', '--others', '--exclude-standard']).split(b'\0') + for raw in sorted(set(paths)): + if not raw: + continue + name = os.fsdecode(raw) + path = checkout / name + digest.update(project.encode() + b'\0' + raw + b'\0') + if path.is_symlink(): + if not path.resolve().is_relative_to(checkout): + raise ValueError('build input is outside its repository') + digest.update(b'symlink\0' + os.fsencode(os.readlink(path)) + b'\0') + if path.is_file(): + if not path.resolve().is_relative_to(checkout): + raise ValueError('build input is outside its repository') + with path.open('rb') as source: + for chunk in iter(lambda: source.read(1024 * 1024), b''): + digest.update(chunk) + else: + digest.update(b'[deleted]') + return digest.hexdigest() + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('mode', choices=PROJECTS) + arguments = parser.parse_args() + print(fingerprint(Path(__file__).resolve().parents[2], arguments.mode)) diff --git a/scripts/companion-dev/test_artifacts.py b/scripts/companion-dev/test_artifacts.py new file mode 100644 index 00000000..6bb7c549 --- /dev/null +++ b/scripts/companion-dev/test_artifacts.py @@ -0,0 +1,82 @@ +"""A failed or interrupted build must preserve the last published site.""" +import importlib.util +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + +spec = importlib.util.spec_from_file_location('artifacts', Path(__file__).with_name('artifacts.py')) +artifacts = importlib.util.module_from_spec(spec) +spec.loader.exec_module(artifacts) + + +class StaticPublication(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.state = Path(self.temporary.name) + artifacts.prepare_web(self.state) + (self.state / 'beacon-web.next/index.html').write_text('last good site') + artifacts.publish_web(self.state, 'a' * 64) + + def stage(self): + artifacts.prepare_web(self.state) + (self.state / 'beacon-web.next/index.html').write_text('complete new site') + + def test_revision_moves_with_complete_site(self): + self.stage() + artifacts.publish_web(self.state, 'b' * 64) + self.assertEqual((self.state / 'beacon-web/index.html').read_text(), 'complete new site') + self.assertEqual(artifacts.web_revision(self.state), 'b' * 64) + self.assertFalse((self.state / 'beacon-web.previous').exists()) + + def test_failed_build_does_not_replace_site_or_revision(self): + artifacts.prepare_web(self.state) + (self.state / 'beacon-web.next/partial.js').write_text('incomplete output') + with self.assertRaisesRegex(ValueError, 'incomplete'): + artifacts.publish_web(self.state, 'b' * 64) + self.assertEqual((self.state / 'beacon-web/index.html').read_text(), 'last good site') + self.assertEqual(artifacts.web_revision(self.state), 'a' * 64) + artifacts.prepare_web(self.state) + self.assertFalse((self.state / 'beacon-web.next/partial.js').exists()) + + def test_failed_publication_restores_last_good_site(self): + self.stage() + rename = artifacts.os.replace + + def fail_new_site(source, destination): + if source == self.state / 'beacon-web.next': + raise OSError('simulated interrupted publication') + return rename(source, destination) + + with patch.object(artifacts.os, 'replace', side_effect=fail_new_site): + with self.assertRaisesRegex(OSError, 'interrupted'): + artifacts.publish_web(self.state, 'b' * 64) + self.assertEqual((self.state / 'beacon-web/index.html').read_text(), 'last good site') + self.assertEqual(artifacts.web_revision(self.state), 'a' * 64) + + def test_next_invocation_recovers_process_death_between_renames(self): + self.stage() + (self.state / 'beacon-web').rename(self.state / 'beacon-web.previous') + artifacts.recover_web(self.state) + self.assertEqual((self.state / 'beacon-web/index.html').read_text(), 'last good site') + self.assertEqual(artifacts.web_revision(self.state), 'a' * 64) + + def test_committed_site_wins_if_death_prevented_backup_cleanup(self): + self.stage() + (self.state / 'beacon-web.next/.ukmesh-source-revision').write_text('b' * 64) + (self.state / 'beacon-web').rename(self.state / 'beacon-web.previous') + (self.state / 'beacon-web.next').rename(self.state / 'beacon-web') + artifacts.recover_web(self.state) + self.assertEqual((self.state / 'beacon-web/index.html').read_text(), 'complete new site') + self.assertEqual(artifacts.web_revision(self.state), 'b' * 64) + + def test_artifact_directory_cannot_escape_through_symlink(self): + (self.state / 'beacon-web.next').symlink_to(self.state / 'beacon-web', target_is_directory=True) + with self.assertRaisesRegex(ValueError, 'symbolic'): + artifacts.prepare_web(self.state) + self.assertEqual((self.state / 'beacon-web/index.html').read_text(), 'last good site') + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/companion-dev/test_control.py b/scripts/companion-dev/test_control.py new file mode 100644 index 00000000..475b70fc --- /dev/null +++ b/scripts/companion-dev/test_control.py @@ -0,0 +1,174 @@ +"""Exercise component lifecycle at the external Docker boundary without a daemon.""" +import importlib.util +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +HERE = Path(__file__).resolve().parent +spec = importlib.util.spec_from_file_location('build_inputs', HERE / 'source-hash.py') +build_inputs = importlib.util.module_from_spec(spec) +spec.loader.exec_module(build_inputs) + + +class CompanionLifecycle(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory(prefix='companion lifecycle ') + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + self.tools = self.root / 'scripts/companion-dev' + self.tools.mkdir(parents=True) + for name in ('control.sh', 'source-hash.py', 'artifacts.py', 'build.sh', + 'build-corescope.sh', 'build-beacon.sh', 'web-build.sh', 'compose.yml', + 'corescope.json', 'beacon.yaml', 'nginx.conf'): + shutil.copyfile(HERE / name, self.tools / name) + full = self.root / 'scripts/full-dev' + full.mkdir() + shutil.copyfile(HERE.parent / 'full-dev/environment.sh', full / 'environment.sh') + self.git(self.root, 'init', '-q') + (self.root / 'README').write_text('owned test checkout') + self.git(self.root, 'add', 'README') + self.git(self.root, '-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'commit', '-qm', 'fixture') + for name in ('corescope', 'beacon-server', 'beacon-web'): + checkout = self.root / 'third_party' / name + checkout.mkdir(parents=True) + self.git(checkout, 'init', '-q') + (checkout / 'source.txt').write_text(name) + self.git(checkout, 'add', 'source.txt') + self.git(checkout, '-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'commit', '-qm', 'fixture') + self.state = self.root / 'plans/companion-dev/runtime' + (self.state / 'bin').mkdir(parents=True) + for name in ('beacon', 'corescope-server', 'corescope-ingestor'): + binary = self.state / 'bin' / name + binary.write_text('last good executable') + binary.chmod(0o755) + self.revisions = {mode: build_inputs.fingerprint(self.root, mode) for mode in build_inputs.PROJECTS} + for component in ('corescope', 'beacon'): + (self.state / (component + '-source')).write_text(self.revisions[component]) + (self.state / 'beacon-web').mkdir() + (self.state / 'beacon-web/index.html').write_text('last good site') + (self.state / 'web-source').write_text(self.revisions['web']) + self.executables = self.root / 'tools' + self.executables.mkdir() + docker = self.executables / 'docker' + docker.write_text('''#!/usr/bin/python3 +import json, os +from pathlib import Path +import sys +root=Path.cwd(); args=sys.argv[1:] +with (root/'calls.jsonl').open('a') as log: + log.write(json.dumps({'args':args, 'revisions':{key:os.getenv(key) for key in + ('COMPANION_CORESCOPE_SOURCE','COMPANION_BEACON_SOURCE','COMPANION_WEB_SOURCE', + 'COMPANION_CORESCOPE_CONFIG','COMPANION_BEACON_CONFIG','COMPANION_WEB_CONFIG')}})+'\\n') +if 'run' in args and 'build' in args: + component=args[-1] + names=['beacon'] if component=='beacon' else ['corescope-server','corescope-ingestor'] + for name in names: + file=root/'plans/companion-dev/runtime/bin'/name + file.write_text('rebuilt '+component); file.chmod(0o755) +if 'run' in args and 'web-build' in args: + output=root/'plans/companion-dev/runtime/beacon-web.next' + (output/'partial.js').write_text('partial asset') + if (root/'fail-web').exists(): sys.exit(42) + (output/'index.html').write_text('complete new site') +if 'ps' in args and 'beacon-migrate' in args: print('owned-migration-container') +if args and args[0]=='inspect': print('exited:1' if (root/'fail-migration').exists() else 'exited:0') +''') + docker.chmod(0o755) + (self.tools / 'beacon-access.sh').write_text('#!/bin/sh\ntouch access-called\n') + + def git(self, checkout, *arguments): + return subprocess.check_output(['git', '-C', str(checkout), *arguments], stderr=subprocess.DEVNULL) + + def run_control(self, *arguments): + environment = {'PATH': str(self.executables) + ':' + os.environ['PATH'], + 'HOME': str(self.root), 'LANG': 'C.UTF-8'} + return subprocess.run(['bash', str(self.tools / 'control.sh'), *arguments], + cwd=self.root, env=environment, capture_output=True, text=True, timeout=30) + + def calls(self): + return [json.loads(line) for line in (self.root / 'calls.jsonl').read_text().splitlines()] + + def test_web_restart_does_not_require_or_restart_unrelated_repositories(self): + shutil.rmtree(self.root / 'third_party/corescope') + (self.root / 'third_party/beacon-web/source.txt').write_text('changed web source') + result = self.run_control('restart', 'beacon-web') + self.assertEqual(result.returncode, 0, result.stderr) + calls = self.calls() + self.assertEqual([row['args'][-1] for row in calls if 'run' in row['args']], ['web-build']) + starts = [row for row in calls if 'up' in row['args'] or 'restart' in row['args']] + self.assertEqual(len(starts), 1) + self.assertEqual(starts[0]['args'][-1], 'beacon-web') + self.assertIn('--no-deps', starts[0]['args']) + self.assertIn('--force-recreate', starts[0]['args']) + self.assertEqual(starts[0]['revisions']['COMPANION_BEACON_SOURCE'], self.revisions['beacon']) + self.assertEqual(starts[0]['revisions']['COMPANION_CORESCOPE_SOURCE'], self.revisions['corescope']) + self.assertEqual((self.state / 'beacon-web/index.html').read_text(), 'complete new site') + + def test_core_rebuild_replaces_both_processes_without_starting_beacon(self): + (self.root / 'third_party/corescope/source.txt').write_text('changed core source') + result = self.run_control('restart', 'corescope-ingestor') + self.assertEqual(result.returncode, 0, result.stderr) + calls = self.calls() + self.assertEqual([row['args'][-1] for row in calls if 'run' in row['args']], ['corescope']) + starts = [row for row in calls if 'up' in row['args'] or 'restart' in row['args']] + self.assertEqual(len(starts), 1) + self.assertEqual(starts[0]['args'][-2:], ['corescope-ingestor', 'corescope']) + + def test_failed_web_build_preserves_site_and_next_restart_recovers(self): + (self.root / 'third_party/beacon-web/source.txt').write_text('changed web source') + (self.root / 'fail-web').touch() + result = self.run_control('restart', 'beacon-web') + self.assertEqual(result.returncode, 42, result.stderr) + self.assertEqual((self.state / 'beacon-web/index.html').read_text(), 'last good site') + self.assertFalse(any('up' in row['args'] for row in self.calls())) + (self.root / 'fail-web').unlink() + result = self.run_control('restart', 'beacon-web') + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual((self.state / 'beacon-web/index.html').read_text(), 'complete new site') + + def test_fingerprint_failure_does_not_build_or_start(self): + (self.root / 'third_party/beacon-server/escaped').symlink_to(self.tools / 'build.sh') + result = self.run_control('restart', 'beacon') + self.assertNotEqual(result.returncode, 0) + self.assertIn('outside its repository', result.stderr) + self.assertFalse(any('run' in row['args'] or 'up' in row['args'] for row in self.calls())) + self.assertEqual((self.state / 'beacon-source').read_text(), self.revisions['beacon']) + + def test_migration_restart_executes_named_job_once_before_access_provisioning(self): + result = self.run_control('restart', 'beacon-migrate') + self.assertEqual(result.returncode, 0, result.stderr) + calls = self.calls() + self.assertFalse(any('run' in row['args'] for row in calls)) + self.assertEqual(len([row for row in calls if 'up' in row['args'] and row['args'][-1]=='beacon-migrate']), 1) + self.assertTrue((self.root / 'access-called').exists()) + + def test_failed_migration_never_provisions_access(self): + (self.root / 'fail-migration').touch() + result = self.run_control('restart', 'beacon-migrate') + self.assertNotEqual(result.returncode, 0) + self.assertIn('migration job failed', result.stderr) + self.assertFalse((self.root / 'access-called').exists()) + + def test_incomplete_unrelated_static_build_does_not_block_core_restart(self): + (self.state / 'beacon-web.next').symlink_to(self.root, target_is_directory=True) + result = self.run_control('restart', 'corescope') + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue((self.state / 'beacon-web.next').is_symlink()) + + def test_config_change_does_not_rebuild_companion_sources(self): + (self.tools / 'beacon.yaml').write_text('changed local settings') + result = self.run_control('start') + self.assertEqual(result.returncode, 0, result.stderr) + self.assertFalse(any('build' in row['args'] or 'web-build' in row['args'] for row in self.calls())) + final_start = [row for row in self.calls() if 'up' in row['args']][-1] + self.assertEqual(final_start['revisions']['COMPANION_BEACON_CONFIG'], + hashlib.sha256(b'changed local settings').hexdigest()) + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/companion-dev/test_source_hash.py b/scripts/companion-dev/test_source_hash.py new file mode 100644 index 00000000..d174c1d9 --- /dev/null +++ b/scripts/companion-dev/test_source_hash.py @@ -0,0 +1,99 @@ +"""Only a component's own source and build recipe should invalidate its binary.""" +import importlib.util +from pathlib import Path +import subprocess +import tempfile +import unittest +import yaml + +spec = importlib.util.spec_from_file_location('source_hash', Path(__file__).with_name('source-hash.py')) +source_hash = importlib.util.module_from_spec(spec) +spec.loader.exec_module(source_hash) + + +class BuildInputs(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + self.tools = self.root / 'scripts/companion-dev' + self.tools.mkdir(parents=True) + for name in ('build.sh', 'build-corescope.sh', 'build-beacon.sh', 'web-build.sh'): + (self.tools / name).write_text(name) + self.configuration = {'services': {'build': {'image': 'go:v1', 'environment': {'GOFLAGS': '-p=2'}}, + 'web-build': {'image': 'node:v1', 'environment': {'VITE_API_BASE': '/api/v1'}}, + 'beacon': {'ports': ['3103:8080']}}} + self.write_configuration() + for name in ('corescope', 'beacon-server', 'beacon-web'): + checkout = self.root / 'third_party' / name + checkout.mkdir(parents=True) + (checkout / '.gitignore').write_text('node_modules/\n') + (checkout / 'source.txt').write_text(name) + self.git(checkout, 'init', '-q') + self.git(checkout, 'add', '.') + self.git(checkout, '-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'commit', '-qm', 'fixture') + + def git(self, checkout, *arguments): + return subprocess.check_output(['git', '-C', str(checkout), *arguments], stderr=subprocess.DEVNULL) + + def write_configuration(self): + (self.tools / 'compose.yml').write_text(yaml.safe_dump(self.configuration)) + + def values(self): + return {mode: source_hash.fingerprint(self.root, mode) for mode in source_hash.PROJECTS} + + def test_independent_source_changes_include_new_and_deleted_files(self): + before = self.values() + checkout = self.root / 'third_party/beacon-server' + (checkout / 'new.go').write_text('package beacon') + changed = self.values() + self.assertNotEqual(changed['beacon'], before['beacon']) + self.assertEqual(changed['corescope'], before['corescope']) + self.assertEqual(changed['web'], before['web']) + (checkout / 'new.go').unlink() + (checkout / 'source.txt').unlink() + self.assertNotEqual(self.values()['beacon'], before['beacon']) + + def test_dependency_cache_and_runtime_configuration_do_not_rebuild_sources(self): + before = self.values() + cache = self.root / 'third_party/beacon-web/node_modules' + cache.mkdir() + (cache / 'downloaded.js').write_text('dependency cache') + self.configuration['services']['beacon']['ports'] = ['9999:8080'] + self.write_configuration() + self.assertEqual(self.values(), before) + + def test_compiler_and_frontend_build_settings_invalidate_only_their_consumers(self): + before = self.values() + self.configuration['services']['build']['image'] = 'go:v2' + self.write_configuration() + changed = self.values() + self.assertNotEqual(changed['beacon'], before['beacon']) + self.assertNotEqual(changed['corescope'], before['corescope']) + self.assertEqual(changed['web'], before['web']) + self.configuration['services']['web-build']['environment']['VITE_API_BASE'] = '/custom-api' + self.write_configuration() + self.assertNotEqual(self.values()['web'], before['web']) + + def test_changed_component_builder_is_an_input(self): + before = self.values() + (self.tools / 'build-corescope.sh').write_text('changed compiler flags') + changed = self.values() + self.assertNotEqual(changed['corescope'], before['corescope']) + self.assertEqual(changed['beacon'], before['beacon']) + self.assertEqual(changed['web'], before['web']) + + def test_symlinked_files_and_directories_cannot_import_untracked_external_inputs(self): + for name, target in [('outside-file', self.tools / 'build.sh'), ('outside-dir', self.tools)]: + with self.subTest(name=name): + link = self.root / 'third_party/beacon-server' / name + link.symlink_to(target) + try: + with self.assertRaisesRegex(ValueError, 'outside'): + source_hash.fingerprint(self.root, 'beacon') + finally: + link.unlink() + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/companion-dev/web-build.sh b/scripts/companion-dev/web-build.sh new file mode 100644 index 00000000..b5538dfa --- /dev/null +++ b/scripts/companion-dev/web-build.sh @@ -0,0 +1,10 @@ +#!/bin/sh +set -eu +wanted=$(sha256sum package-lock.json | cut -d ' ' -f 1) +installed=$(cat node_modules/.ukmesh-dev-lock 2>/dev/null || true) +if [ "$wanted" != "$installed" ]; then + npm ci --cache /npm-cache + printf '%s\n' "$wanted" > node_modules/.ukmesh-dev-lock +fi +node node_modules/typescript/bin/tsc -b +node node_modules/vite/bin/vite.js build --mode companion --outDir /out diff --git a/scripts/dev-all.sh b/scripts/dev-all.sh index 2432cae9..79d699b1 100755 --- a/scripts/dev-all.sh +++ b/scripts/dev-all.sh @@ -1,98 +1,43 @@ #!/usr/bin/env bash -# Local fixture stack plus three independently editable companion repositories. +# Serialized entrypoint; each subsystem owns its lifecycle and configuration. set -euo pipefail repo=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd) if [[ ${UKMESH_COMPANION_ENV_CLEAN:-} != 1 ]]; then exec env -i PATH="$PATH" HOME="$HOME" LANG=C.UTF-8 UKMESH_COMPANION_ENV_CLEAN=1 bash "$repo/scripts/dev-all.sh" "$@" fi -cd "$repo" action=${1:-start} service=${2:-} case "$action" in help|--help) - echo 'scripts/dev-all.sh [start|companions|build|status|stop|logs [SERVICE]|restart SERVICE|init]' - echo 'start resumes or creates the UKMesh fixture, then starts companions. stop retains all data.' - echo 'restart rebuilds Go binaries before restarting the named companion. No reset or data deletion.' + echo 'scripts/dev-all.sh [start|companions|build|status|stop|logs [SERVICE]|restart SERVICE|init|qualify PHASE|hot ukmesh|hot beacon-web]' + echo 'start runs the complete lean stack. stop retains stores. hot enables editing; start restores built assets.' exit 0 ;; - start|companions|build|status|stop|logs|restart|init) ;; + start|companions|build|status|stop|logs|restart|init|qualify|hot) ;; *) echo "Unknown action: $action" >&2; exit 2 ;; esac -services=(corescope corescope-ingestor beacon beacon-web beacon-db beacon-redis) -if [[ -n $service ]]; then - valid=false - for candidate in "${services[@]}"; do [[ $candidate != "$service" ]] || valid=true; done - [[ $valid == true ]] || { echo "Unknown companion: $service" >&2; exit 2; } -fi -if [[ $action == restart && -z $service ]]; then echo 'restart requires a companion service name' >&2; exit 2; fi -lock_dir="$repo/plans/companion-dev" -mkdir -p "$lock_dir" -chmod 700 "$lock_dir" +state="$repo/plans/companion-dev" +mkdir -p "$state" +chmod 700 "$state" if [[ $action != status && $action != logs && ${UKMESH_COMPANION_LOCKED:-} != 1 ]]; then - if flock --nonblock --close --conflict-exit-code 75 "$lock_dir/control.lock" \ - env UKMESH_COMPANION_LOCKED=1 bash "$repo/scripts/dev-all.sh" "$@"; then exit 0; else + if flock --nonblock --close --conflict-exit-code 75 "$state/control.lock" env UKMESH_COMPANION_LOCKED=1 bash "$repo/scripts/dev-all.sh" "$@"; then exit 0; else result=$? if [[ $result == 75 ]]; then echo 'Another DEV operation is running; let it finish before starting a new one.' >&2; fi exit "$result" fi fi -if [[ $action == init ]]; then - for name in corescope beacon-server beacon-web; do - path="third_party/$name" - # Preserve existing branches, edits and pending merges. - if [[ ! -e $path/.git ]]; then git submodule update --init -- "$path"; fi - if ! git -C "$path" remote get-url upstream >/dev/null 2>&1; then - case "$name" in - corescope) upstream=https://github.com/Kpa-clawbot/CoreScope.git ;; - *) upstream="https://github.com/MeshCore-Beacon/$name.git" ;; - esac - git -C "$path" remote add upstream "$upstream" - fi - if [[ -z $(git -C "$path" symbolic-ref --short -q HEAD) ]]; then git -C "$path" switch -c ukmesh-dev; fi - done - exit 0 -fi -command -v docker >/dev/null || { echo 'Docker Engine and Compose are required' >&2; exit 1; } -docker info >/dev/null -export COMPANION_UID=$(id -u) COMPANION_GID=$(id -g) -compose=(docker compose --env-file /dev/null -f "$repo/scripts/companion-dev/compose.yml") -state="$repo/plans/companion-dev/runtime" -mkdir -p "$state/bin" "$state/corescope" "$state/npm-cache" "$repo/plans/companion-dev/go-cache" "$repo/plans/companion-dev/go-mod" -chmod 700 "$repo/plans/companion-dev" "$state" case "$action" in - status) - "${compose[@]}" ps - for name in corescope beacon-server beacon-web; do git -C "third_party/$name" status --short --branch; done - exit 0 ;; - logs) "${compose[@]}" logs --tail 100 ${service:+"$service"}; exit 0 ;; + init|companions) exec bash "$repo/scripts/companion-dev/control.sh" "$@" ;; + qualify) shift; exec bash "$repo/scripts/qualify-full-stack.sh" "${@:-all}" ;; + build|start|status) + bash "$repo/scripts/full-dev/control.sh" "$action" + exec bash "$repo/scripts/companion-dev/control.sh" "$action" ;; stop) - "${compose[@]}" stop - if [[ -f $repo/plans/dev-stack/fixture-ready ]]; then bash "$repo/scripts/dev-stack.sh" stop; fi - exit 0 ;; + bash "$repo/scripts/companion-dev/control.sh" stop + exec bash "$repo/scripts/full-dev/control.sh" stop ;; + hot|restart|logs) + case "$service" in + corescope|corescope-ingestor|beacon|beacon-db|beacon-redis|beacon-web|beacon-migrate) + exec bash "$repo/scripts/companion-dev/control.sh" "$@" ;; + *) exec bash "$repo/scripts/full-dev/control.sh" "$@" ;; + esac ;; esac -for name in corescope beacon-server beacon-web; do - [[ -e "third_party/$name/.git" ]] || { echo "Missing $name; run scripts/dev-all.sh init" >&2; exit 1; } - if [[ -n $(git -C "third_party/$name" diff --name-only --diff-filter=U) ]]; then - echo "Resolve the $name merge before starting companions" >&2; exit 1 - fi -done -if [[ $action == start ]]; then - if ! curl --fail --silent --max-time 3 http://127.0.0.1:3100/healthz >/dev/null; then - if [[ -f $repo/plans/dev-stack/fixture-ready ]]; then bash "$repo/scripts/dev-stack.sh" start; else bash "$repo/scripts/dev-stack.sh" up; fi - fi -fi -if [[ $action != build ]]; then - docker network inspect ukmesh-sample_default >/dev/null 2>&1 || { echo 'Start the UKMesh fixture first with scripts/dev-all.sh start' >&2; exit 1; } -fi -export COMPANION_CORESCOPE_COMMIT=$(git -C third_party/corescope rev-parse --short HEAD) -if [[ $action != restart || $service == corescope || $service == corescope-ingestor || $service == beacon ]]; then - "${compose[@]}" run --rm --no-deps build -fi -if [[ $action == build ]]; then exit 0; fi -if [[ $action == restart ]]; then - "${compose[@]}" up -d --wait --wait-timeout 180 "$service" - "${compose[@]}" restart "$service" - "${compose[@]}" up -d --wait --wait-timeout 180 "$service" -else - "${compose[@]}" up -d --wait --wait-timeout 240 -fi -printf 'UKMesh http://127.0.0.1:5173\nCoreScope http://127.0.0.1:3102\nBeacon http://127.0.0.1:5175 (API http://127.0.0.1:3103)\n' diff --git a/scripts/full-dev/access.sh b/scripts/full-dev/access.sh new file mode 100644 index 00000000..b41e30e3 --- /dev/null +++ b/scripts/full-dev/access.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# Operator-only provisioning for the local sample cluster and owned databases. +set -euo pipefail +repo=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd) +if [[ ${UKMESH_LOCAL_ACCESS_CLEAN:-} != 1 ]]; then + exec env -i PATH="$PATH" HOME="$HOME" LANG=C.UTF-8 UKMESH_LOCAL_ACCESS_CLEAN=1 bash "$repo/scripts/full-dev/access.sh" "$@" +fi +[[ $# == 2 ]] || { echo 'usage: scripts/full-dev/access.sh UKMESH_DATABASE OWNER_DATABASE' >&2; exit 2; } +database=$1 owner_database=$2 +fixture_token= +if [[ $database =~ ^lean_(fixture|1x|10x|soak)_([a-z0-9_]{1,38})$ ]]; then + fixture_token=${BASH_REMATCH[2]} + [[ $owner_database == "lean_owner_$fixture_token" ]] || { echo 'Fixture database targets must share one owner' >&2; exit 2; } +else + [[ $database == meshcore && $owner_database == meshcore_owner_auth ]] || { echo 'Unowned database targets' >&2; exit 2; } +fi +[[ $database != "$owner_database" ]] || { echo 'Main and owner stores must be separate' >&2; exit 2; } +docker=(docker --host unix:///var/run/docker.sock) +project=$("${docker[@]}" inspect ukmesh-sample-db --format '{{index .Config.Labels "com.docker.compose.project"}}') +[[ $project == ukmesh-sample ]] || { echo 'Local sample database ownership not proved' >&2; exit 1; } +for target in "$database" "$owner_database"; do + if [[ $target == lean_* ]]; then + marker=$("${docker[@]}" exec ukmesh-sample-db psql -U meshcore -d postgres -At -v ON_ERROR_STOP=1 \ + -c "SELECT shobj_description(oid,'pg_database') FROM pg_database WHERE datname='$target'") + [[ $marker == "ukmesh-owned-fixture:$fixture_token" ]] || { echo 'Fixture database ownership marker differs' >&2; exit 1; } + fi +done +"${docker[@]}" exec -i ukmesh-sample-db psql -U meshcore -d "$database" \ + -v ON_ERROR_STOP=1 -v "ukmesh_database=$database" -v "owner_database=$owner_database" \ + < "$repo/scripts/full-dev/access.sql" +if [[ -n $fixture_token ]]; then + "${docker[@]}" exec -i ukmesh-sample-db psql -X -U meshcore -d "$database" -v ON_ERROR_STOP=1 \ + < "$repo/scripts/full-dev/corescope-reader.sql" +fi diff --git a/scripts/full-dev/access.sql b/scripts/full-dev/access.sql new file mode 100644 index 00000000..78b118e2 --- /dev/null +++ b/scripts/full-dev/access.sql @@ -0,0 +1,224 @@ +\set ON_ERROR_STOP on +-- Operator bootstrap for the owned local cluster, after schema migrations. +-- Existing object/function owners and their security settings stay unchanged. +BEGIN; +SET LOCAL lock_timeout = '5s'; +SET LOCAL statement_timeout = '30s'; + +DO $roles$ +DECLARE role_name text; +BEGIN + FOREACH role_name IN ARRAY ARRAY['meshcore_api','meshcore_ingest', + 'meshcore_worker','meshcore_owner','meshcore_migrate','meshcore_monitor','corescope_ro'] LOOP + IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname=role_name) THEN + EXECUTE format('CREATE ROLE %I LOGIN', role_name); + END IF; + EXECUTE format('ALTER ROLE %I LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION NOBYPASSRLS PASSWORD %L', + role_name, 'local-full-dev-only'); + END LOOP; + IF EXISTS ( + SELECT FROM pg_auth_members membership + JOIN pg_roles member ON member.oid=membership.member + JOIN pg_roles granted ON granted.oid=membership.roleid + WHERE member.rolname IN ('meshcore_api','meshcore_ingest','meshcore_worker', + 'meshcore_owner','meshcore_migrate','meshcore_monitor','corescope_ro') + AND NOT (member.rolname='meshcore_monitor' AND granted.rolname='pg_monitor') + ) THEN RAISE EXCEPTION 'Unexpected local runtime role membership'; END IF; +END +$roles$; +GRANT pg_monitor TO meshcore_monitor WITH INHERIT TRUE; + +-- Logins are cluster-wide. A target switch must withdraw access to previously +-- selected stores, including PUBLIC's default CONNECT, before granting this pair. +DO $databases$ +DECLARE database_record record; +BEGIN + FOR database_record IN SELECT oid, datname FROM pg_database LOOP + IF database_record.datname NOT IN ('meshcore','meshcore_owner_auth','postgres','template0','template1') THEN + IF database_record.datname !~ '^lean_(verify|fixture|1x|10x|soak|owner)_[a-z0-9_]{1,38}$' + OR shobj_description(database_record.oid,'pg_database') IS DISTINCT FROM + 'ukmesh-owned-fixture:' || regexp_replace(database_record.datname, + '^lean_(verify|fixture|1x|10x|soak|owner)_', '') THEN + RAISE EXCEPTION 'Unexpected or unowned database in local UKMesh cluster'; + END IF; + END IF; + EXECUTE format('REVOKE ALL ON DATABASE %I FROM PUBLIC, meshcore_api, meshcore_ingest, meshcore_worker, meshcore_owner, meshcore_migrate, meshcore_monitor, corescope_ro', + database_record.datname); + END LOOP; +END +$databases$; + +REVOKE ALL ON DATABASE :"ukmesh_database" FROM PUBLIC; +REVOKE ALL ON DATABASE :"ukmesh_database" FROM meshcore_api, meshcore_ingest, + meshcore_worker, meshcore_owner, meshcore_migrate, meshcore_monitor, corescope_ro; +GRANT CONNECT ON DATABASE :"ukmesh_database" TO meshcore_api, meshcore_ingest, + meshcore_worker, meshcore_migrate, meshcore_monitor, corescope_ro; +-- deltaPublication stages a complete learning generation in a session-local +-- table before its atomic publish. This grants no persistent schema DDL. +GRANT TEMPORARY ON DATABASE :"ukmesh_database" TO meshcore_worker; + +-- Revocation is deliberately exhaustive; grants below are named allowlists. +REVOKE ALL ON ALL TABLES IN SCHEMA core, mesh, analytics, ops, archive, public + FROM meshcore_api, meshcore_ingest, meshcore_worker, meshcore_owner, meshcore_migrate, meshcore_monitor; +REVOKE ALL ON ALL SEQUENCES IN SCHEMA core, mesh, analytics, ops, archive, public + FROM meshcore_api, meshcore_ingest, meshcore_worker, meshcore_owner, meshcore_migrate, meshcore_monitor; +REVOKE CREATE ON SCHEMA public FROM PUBLIC; +REVOKE ALL ON SCHEMA core, mesh, analytics, ops, archive, public + FROM meshcore_api, meshcore_ingest, meshcore_worker, meshcore_owner, meshcore_migrate, meshcore_monitor; +GRANT USAGE ON SCHEMA core, mesh, analytics, ops, public TO meshcore_api, meshcore_worker; +GRANT USAGE ON SCHEMA core, mesh, ops, public TO meshcore_ingest; +GRANT USAGE, CREATE ON SCHEMA core, mesh, analytics, ops, archive, public TO meshcore_migrate; +ALTER ROLE meshcore_api IN DATABASE :"ukmesh_database" SET search_path = pg_catalog, core, mesh, analytics, ops, public; +ALTER ROLE meshcore_ingest IN DATABASE :"ukmesh_database" SET search_path = pg_catalog, core, mesh, public; +ALTER ROLE meshcore_worker IN DATABASE :"ukmesh_database" SET search_path = pg_catalog, core, mesh, analytics, ops, public, pg_temp; + +-- API/repository reads and worker model/health inputs. View owners retain their +-- existing projection privileges; neither app role reads ops.node_privacy or +-- ops.channel_blocklist directly. Owner authentication lives in another DB. +GRANT SELECT ON + core.nodes, core.node_counted_adverts, core.node_coverage, + core.node_identity_aliases, core.node_identity_match_evidence, core.node_identity_refresh_state, + core.node_identity_nodes, core.node_identity_links, core.node_identity_packets, + core.node_identity_sightings, core.node_identity_status_samples, core.node_identity_link_radio_reports, + core.node_links, core.node_map_suppressions, core.node_name_history, + core.node_neighbor_samples, core.node_status_samples, core.node_network_sightings, + core.observer_region_observer_sightings, core.observer_region_packet_sightings, + core.observer_registration_requests, core.observers, core.private_node_prefixes, + core.owner_alert_rules, core.owner_alert_deliveries, core.owner_alert_delivery_attempts, + core.owner_packet_share_rules, core.owner_packet_share_deliveries, + core.owner_public_feed_nodes, core.owner_public_feed_settings, + core.planned_node_publications, core.region_scope_members, core.region_scope_run, + core.region_scope_stats, core.region_scope_unattributed, core.repeater_scope_status, + mesh.packets, mesh.packet_paths, mesh.packet_decryptions, + mesh.packet_daily_stats, mesh.packet_hourly_stats, + mesh.multibyte_path_facts, mesh.multibyte_path_fact_state, mesh.message_tags, + mesh.ingest_observation_ledger, mesh.ingest_observation_history, + mesh.ingest_observation_ledger_coverage, mesh.packet_forwarding_outbox, + analytics.analysis_runs, analytics.analysis_workload_state, analytics.ml_model_versions, + analytics.ml_model_variant_runs, analytics.ml_model_variant_packet_results, + analytics.path_corridor_priors, analytics.path_edge_priors, analytics.path_model_calibration, + analytics.path_motif_priors, analytics.path_position_prefix_priors, + analytics.path_position_transition_priors, analytics.path_prefix_priors, + analytics.path_slow_resolutions, analytics.path_transition_priors, + analytics.spam_suspects, analytics.spam_message_incidents, analytics.spam_message_members, + analytics.stats_chart_snapshots, + ops.frontend_error_events, ops.operational_check_results, ops.operator_audit_events, + ops.packet_visibility_materialization_state, ops.privacy_rematerialization_queue, + ops.public_visibility_state, ops.worker_health_current, ops.worker_health_snapshots, + ops.planned_nodes, ops.planned_coverage_jobs, ops.planned_coverage_handles, + ops.public_feed_deliveries, ops.link_job_commits, ops.link_rebuild_runs, + public.ml_learner_state +TO meshcore_api, meshcore_worker; +GRANT SELECT ON core.owner_packet_share_destinations TO meshcore_api; + +-- These business writes run through the existing HTTP executor and still rely +-- on application actor/scope checks. API never inserts packet observations. +GRANT INSERT, UPDATE, DELETE ON + core.node_map_suppressions, core.observer_registration_requests, core.observers, + core.owner_alert_rules, core.owner_alert_deliveries, core.owner_alert_delivery_attempts, + core.owner_packet_share_rules, core.owner_packet_share_deliveries, + core.owner_public_feed_nodes, core.owner_public_feed_settings, + core.planned_node_publications, + analytics.spam_suspects, analytics.spam_message_incidents, analytics.spam_message_members, + ops.planned_nodes, ops.planned_coverage_jobs, ops.planned_coverage_handles, ops.public_feed_deliveries +TO meshcore_api; +GRANT INSERT, UPDATE ON analytics.stats_chart_snapshots, analytics.path_slow_resolutions, + ops.frontend_error_events, ops.ingest_rejections, ops.operator_audit_events TO meshcore_api; +GRANT SELECT ON ops.ingest_rejections TO meshcore_api; +GRANT SELECT, UPDATE, DELETE ON mesh.packet_forwarding_outbox TO meshcore_api; +GRANT UPDATE (last_predicted_online_at, last_path_evidence_at) ON core.nodes TO meshcore_api; +-- PostgreSQL requires an UPDATE privilege for SELECT FOR SHARE/UPDATE fences. +GRANT UPDATE (updated_at) ON ops.public_visibility_state TO meshcore_api; +GRANT USAGE ON SEQUENCE + core.observer_registration_requests_id_seq, core.owner_alert_rules_id_seq, + core.owner_alert_deliveries_id_seq, core.owner_alert_delivery_attempts_id_seq, + core.owner_packet_share_deliveries_id_seq, ops.public_feed_deliveries_id_seq, + ops.frontend_error_events_id_seq, ops.operator_audit_events_id_seq +TO meshcore_api; + +-- Ingest SQL and invoker-security trigger followups: node history, privacy +-- prefixes/queues, observation tombstones and multibyte facts are real writes. +GRANT SELECT ON + core.nodes, core.node_counted_adverts, core.node_coverage, core.node_status_samples, + core.node_neighbor_samples, core.node_name_history, core.node_identity_aliases, + core.node_identity_nodes, core.private_node_prefixes, + core.node_network_sightings, core.observer_region_observer_sightings, + core.observer_region_packet_sightings, + core.owner_packet_share_rules, core.owner_public_feed_nodes, core.owner_public_feed_settings, + mesh.packets, mesh.packet_paths, mesh.packet_daily_stats, mesh.packet_hourly_stats, + mesh.ingest_observation_ledger, mesh.ingest_observation_tombstones, + mesh.ingest_observation_archive, mesh.ingest_observation_ledger_coverage, + mesh.multibyte_path_facts, mesh.packet_forwarding_outbox, + ops.public_visibility_state, ops.packet_visibility_materialization_state, + ops.privacy_rematerialization_queue +TO meshcore_ingest; +GRANT INSERT, UPDATE ON + core.nodes, core.node_counted_adverts, core.node_coverage, core.node_name_history, + core.node_status_samples, core.node_neighbor_samples, core.node_network_sightings, + core.observer_region_observer_sightings, core.observer_region_packet_sightings, + mesh.packets, mesh.packet_paths, mesh.packet_daily_stats, mesh.packet_hourly_stats, + mesh.ingest_observation_ledger, mesh.ingest_observation_tombstones, + mesh.multibyte_path_facts, mesh.packet_forwarding_outbox, + ops.public_visibility_state, ops.privacy_rematerialization_queue +TO meshcore_ingest; +GRANT DELETE ON core.node_coverage TO meshcore_ingest; +GRANT INSERT, UPDATE, DELETE ON core.private_node_prefixes TO meshcore_ingest; +GRANT USAGE ON SEQUENCE mesh.ingest_observation_ledger_seq_seq, + ops.privacy_rematerialization_queue_id_seq TO meshcore_ingest; + +-- Shared worker role is the union of active worker capabilities, not ownership. +GRANT INSERT, UPDATE, DELETE ON + core.node_identity_aliases, core.node_identity_match_evidence, core.node_identity_refresh_state, + core.node_links, core.node_coverage, core.node_map_suppressions, + core.node_network_sightings, core.observer_region_observer_sightings, + core.region_scope_members, core.region_scope_run, core.region_scope_stats, + core.region_scope_unattributed, core.repeater_scope_status, core.private_node_prefixes, + analytics.analysis_runs, analytics.analysis_workload_state, + analytics.path_corridor_priors, analytics.path_edge_priors, analytics.path_model_calibration, + analytics.path_motif_priors, analytics.path_position_prefix_priors, + analytics.path_position_transition_priors, analytics.path_prefix_priors, + analytics.path_transition_priors, analytics.spam_message_incidents, analytics.spam_message_members, + ops.public_visibility_state, ops.packet_visibility_materialization_state, + ops.privacy_rematerialization_queue, ops.worker_health_current, ops.worker_health_snapshots, + ops.tagger_state, ops.tagger_retry, ops.link_job_commits, ops.link_rebuild_runs, + core.owner_alert_rules, core.owner_alert_deliveries, core.owner_alert_delivery_attempts +TO meshcore_worker; +GRANT UPDATE, DELETE ON core.nodes TO meshcore_worker; +GRANT INSERT, UPDATE ON core.node_name_history, mesh.message_tags, + ops.operational_check_results, ops.maintenance_removed_records TO meshcore_worker; +GRANT UPDATE ON core.observer_registration_requests TO meshcore_worker; +GRANT UPDATE ON mesh.packets, mesh.packet_paths TO meshcore_worker; +GRANT DELETE ON ops.frontend_error_events, ops.operational_check_results, + core.observer_region_packet_sightings, core.owner_packet_share_deliveries, + ops.public_feed_deliveries, analytics.ml_model_variant_packet_results, + mesh.packet_decryptions, core.observer_registration_requests, ops.operator_audit_events +TO meshcore_worker; +GRANT SELECT ON ops.tagger_state, ops.tagger_retry, ops.maintenance_removed_records TO meshcore_worker; +GRANT USAGE ON SEQUENCE ops.privacy_rematerialization_queue_id_seq, + ops.maintenance_removed_records_archive_id_seq, + core.owner_alert_deliveries_id_seq, core.owner_alert_delivery_attempts_id_seq TO meshcore_worker; + +-- Runtime roles get no persistent schema CREATE, table ownership, default future-table +-- grants, security-definer rewrites, or reader permissions on raw measurements. +COMMIT; + +\connect :owner_database +BEGIN; +SET LOCAL lock_timeout = '5s'; +SET LOCAL statement_timeout = '30s'; +REVOKE ALL ON DATABASE :"owner_database" FROM PUBLIC; +REVOKE ALL ON DATABASE :"owner_database" FROM meshcore_api, meshcore_ingest, + meshcore_worker, meshcore_owner, meshcore_migrate, meshcore_monitor; +GRANT CONNECT ON DATABASE :"owner_database" TO meshcore_owner, meshcore_migrate; +REVOKE CREATE ON SCHEMA public FROM PUBLIC; +REVOKE ALL ON ALL TABLES IN SCHEMA core, public FROM meshcore_api, meshcore_ingest, + meshcore_worker, meshcore_owner, meshcore_migrate, meshcore_monitor; +REVOKE ALL ON SCHEMA core, public FROM meshcore_api, meshcore_ingest, + meshcore_worker, meshcore_owner, meshcore_migrate, meshcore_monitor; +GRANT USAGE ON SCHEMA core, public TO meshcore_owner; +GRANT USAGE, CREATE ON SCHEMA core, public TO meshcore_migrate; +GRANT SELECT, INSERT, UPDATE, DELETE ON core.owner_accounts, core.owner_account_nodes, + core.mqtt_node_logins, core.owner_grant_audit, core.owner_acl_state, + core.owner_acl_artifacts, public.owner_sessions TO meshcore_owner; +ALTER ROLE meshcore_owner IN DATABASE :"owner_database" SET search_path = pg_catalog, core, public; +COMMIT; diff --git a/scripts/full-dev/alert-bootstrap.mjs b/scripts/full-dev/alert-bootstrap.mjs new file mode 100644 index 00000000..8f17b7af --- /dev/null +++ b/scripts/full-dev/alert-bootstrap.mjs @@ -0,0 +1,15 @@ +const headers = {authorization: `Bearer ${process.env.ALERT_RECEIVER_TOKEN}`, 'content-type': 'application/json'}; +for (let attempt = 0; attempt < 120; attempt++) { + try { + const ready = await fetch('http://alert-receiver:8080/readyz', {signal: AbortSignal.timeout(3000)}); + if (ready.ok) process.exit(0); + await fetch('http://alert-receiver:8080/alerts', { + method: 'POST', headers, signal: AbortSignal.timeout(3000), + body: JSON.stringify({source: 'local-dev', status: 'resolved', check: 'local forwarding bootstrap'}), + }); + } catch (error) { + if (attempt === 119) throw error; + } + await new Promise(resolve => setTimeout(resolve, 500)); +} +throw new Error('Local alert forwarding did not become ready'); diff --git a/scripts/full-dev/alertmanager.yml b/scripts/full-dev/alertmanager.yml new file mode 100644 index 00000000..8b0371dc --- /dev/null +++ b/scripts/full-dev/alertmanager.yml @@ -0,0 +1,17 @@ +global: + resolve_timeout: 5m +route: + receiver: local-test + group_by: [alertname, severity] + group_wait: 10s + group_interval: 1m + repeat_interval: 4h +receivers: + - name: local-test + webhook_configs: + - url: http://alert-receiver:8080/alerts + send_resolved: true + http_config: + authorization: + type: Bearer + credentials: local-full-alert-token-0123456789abcdef diff --git a/scripts/full-dev/compose.yml b/scripts/full-dev/compose.yml new file mode 100644 index 00000000..b87ecd74 --- /dev/null +++ b/scripts/full-dev/compose.yml @@ -0,0 +1,201 @@ +# Merge with docker-compose.yml. Keep the main service/resource policy; replace +# only external infrastructure, fixture paths and local ingress/integrations. +services: + mosquitto-reloader: + image: ${MOSQUITTO_RELOADER_IMAGE} + build: + context: . + dockerfile: Dockerfile.mosquitto-reloader + args: {SOURCE_REVISION: "${SOURCE_REVISION}"} + restart: unless-stopped + pid: container:ukmesh-sample-mqtt + user: "1883:1883" + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + mem_limit: 64m + memswap_limit: 64m + environment: + OWNER_ACL_RELOAD_TOKEN: ${JWT_SECRET} + ports: ["127.0.0.1:3109:8080"] + volumes: [mosquitto_log:/mosquitto/log] + healthcheck: + test: [CMD, python3, -c, "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/healthz', timeout=2).read()"] + interval: 15s + timeout: 3s + retries: 6 + hopreach: + environment: + LOCAL_CONFIG_REVISION: ${FULL_DEV_HOPREACH_REVISION:-unprepared} + volumes: + - ./plans/lean-runtime/runtime/hopreach.yaml:/config/config.yaml:ro + db-migrate: + networks: [default, sample] + depends_on: !override {} + environment: + DATABASE_URL: postgresql://meshcore:meshcore@ukmesh-sample-db:5432/${UKMESH_DATABASE:-meshcore} + backend: + networks: [default, sample] + environment: + MQTT_USERNAME: !reset null + MQTT_PASSWORD: !reset null + REDIS_PASSWORD: "" + ALLOWED_ORIGINS: http://127.0.0.1:5173,http://localhost:5173,http://127.0.0.1:3003,http://localhost:3003,http://127.0.0.1:3005,http://localhost:3005,http://127.0.0.1:8923,http://localhost:8923,http://127.0.0.1:8924,http://localhost:8924 + OWNER_ACL_MODE: shadow + OWNER_ACL_UNMANAGED_USERS: "" + MOSQUITTO_ACL_PATH: /mosquitto/config/acl + DATA_LIFECYCLE_RETENTION_ENABLED: "false" + DATA_LIFECYCLE_COMPRESSION_ENABLED: "false" + MQTT_RAM_PUBLIC_READ_TOKEN: local-full-public-stream-token-0123456789abcdef + ports: !override ["127.0.0.1:3100:3000", "127.0.0.1:9091:9091"] + volumes: !override + - ./scripts/local-sample/mosquitto-acl:/mosquitto/config/acl:ro + - mosquitto_log:/mosquitto/log:ro + - timescaledb_data:/health-volumes/database:ro + - redis_data:/health-volumes/redis:ro + - srtm_data:/health-volumes/terrain:ro + - loki_data:/health-volumes/logs:ro + path-learning-worker: + networks: [default, sample] + environment: + REDIS_PASSWORD: "" + health-worker: + networks: [default, sample] + environment: + REDIS_PASSWORD: "" + DATA_LIFECYCLE_RETENTION_ENABLED: "false" + DATA_LIFECYCLE_COMPRESSION_ENABLED: "false" + volumes: !override + - timescaledb_data:/health-volumes/database:ro + - redis_data:/health-volumes/redis:ro + - srtm_data:/health-volumes/terrain:ro + - loki_data:/health-volumes/logs:ro + tagger-worker: + networks: [default, sample] + environment: + TYPESAFE_API_URL: http://external-test:8080/tag + TYPESAFE_API_KEY: local-fixture-key + region-snapshot-worker: + networks: [default, sample] + ports: ["127.0.0.1:9092:9091"] + privacy-remat-worker: + networks: [default, sample] + synthetic-monitor: + networks: [default, sample] + link-backfill-worker: + networks: [default, sample] + environment: + REDIS_PASSWORD: "" + link-worker: + networks: [default, sample] + environment: + REDIS_PASSWORD: "" + app-ukmesh: + environment: + LOCAL_CONFIG_REVISION: ${FULL_DEV_APP_PROXY_REVISION:-unprepared} + volumes: + - ./plans/lean-runtime/runtime/nginx.app.conf:/etc/nginx/conf.d/default.conf:ro + build: + args: + VITE_APP_HOSTNAME: 127.0.0.1:3003 + website-ukmesh: + environment: + LOCAL_CONFIG_REVISION: ${FULL_DEV_WEBSITE_PROXY_REVISION:-unprepared} + volumes: + - ./plans/lean-runtime/runtime/nginx.website.conf:/etc/nginx/conf.d/default.conf:ro + ports: !override ["127.0.0.1:5173:8080", "127.0.0.1:3004:8080"] + build: + args: + VITE_APP_HOSTNAME: 127.0.0.1:3003 + website-dev: + environment: + LOCAL_CONFIG_REVISION: ${FULL_DEV_WEBSITE_PROXY_REVISION:-unprepared} + volumes: + - ./plans/lean-runtime/runtime/nginx.website.conf:/etc/nginx/conf.d/default.conf:ro + profiles: !override [] + ports: !override ["127.0.0.1:3005:8080"] + build: + args: + VITE_APP_HOSTNAME: 127.0.0.1:3005 + VITE_SITE_APP_URL: http://127.0.0.1:3005 + VITE_SITE_HOME_URL: http://127.0.0.1:5173 + mesh-health-check: + networks: [default, sample] + environment: + MQTT_HOST: ukmesh-sample-mqtt + MQTT_USERNAME: "" + MQTT_PASSWORD: "" + EXTERNAL_LINK_URL: http://127.0.0.1:5173 + DASH_BROKER_HOST: 127.0.0.1:9002 + WEBSOCKET_ALLOWED_ORIGINS: http://127.0.0.1:3090,http://localhost:3090,http://127.0.0.1:8925,http://localhost:8925 + TEST_CHANNEL_NAME: test + TEST_CHANNEL_SECRET: 9cd8fcf22a47333b591d96a2b848b73f + anubis-website-ukmesh: + ports: ["127.0.0.1:8923:8923"] + environment: {COOKIE_DOMAIN: "", COOKIE_SECURE: "false", USE_REMOTE_ADDRESS: "true", CUSTOM_REAL_IP_HEADER: ""} + anubis-app-ukmesh: + ports: ["127.0.0.1:8924:8923"] + environment: {COOKIE_DOMAIN: "", COOKIE_SECURE: "false", USE_REMOTE_ADDRESS: "true", CUSTOM_REAL_IP_HEADER: ""} + anubis-health-check: + ports: ["127.0.0.1:8925:8923"] + environment: {COOKIE_DOMAIN: "", COOKIE_SECURE: "false", USE_REMOTE_ADDRESS: "true", CUSTOM_REAL_IP_HEADER: ""} + loki: + ports: ["127.0.0.1:3104:3100"] + alert-receiver: + environment: + ALERT_FORWARD_URL: http://external-test:8080/alerts + ports: ["127.0.0.1:3106:8080"] + alertmanager: + depends_on: !override + alert-bootstrap: {condition: service_completed_successfully} + ports: ["127.0.0.1:9095:9093"] + volumes: !override + - ./scripts/full-dev/alertmanager.yml:/etc/alertmanager/alertmanager.yml:ro + - alertmanager_data:/alertmanager + postgres-exporter: + networks: [default, sample] + blackbox-exporter: + networks: [default, sample] + redis-exporter: + networks: [default, sample] + environment: + REDIS_ADDR: redis://ukmesh-sample-redis:6379 + REDIS_PASSWORD: "" + prometheus: + environment: + LOCAL_CONFIG_REVISION: ${FULL_DEV_PROMETHEUS_REVISION:-unprepared} + networks: [default, sample] + volumes: + - ./plans/lean-runtime/runtime/prometheus.yml:/etc/prometheus/prometheus.yml:ro + external-test: + image: ${BACKEND_IMAGE} + command: [node, /dev-tools/external-test.mjs] + volumes: ["./scripts/full-dev/external-test.mjs:/dev-tools/external-test.mjs:ro"] + ports: ["127.0.0.1:3107:8080"] + read_only: true + cap_drop: [ALL] + mem_limit: 64m + logging: {driver: journald, options: {tag: "{{.Name}}", labels: "com.docker.compose.service,com.docker.compose.project"}} + healthcheck: + test: [CMD, node, -e, "fetch('http://127.0.0.1:8080/healthz').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"] + interval: 5s + timeout: 3s + retries: 12 + alert-bootstrap: + image: ${BACKEND_IMAGE} + restart: "no" + mem_limit: 64m + environment: + ALERT_RECEIVER_TOKEN: ${ALERT_RECEIVER_TOKEN} + command: [node, /dev-tools/alert-bootstrap.mjs] + volumes: ["./scripts/full-dev/alert-bootstrap.mjs:/dev-tools/alert-bootstrap.mjs:ro"] + depends_on: + alert-receiver: {condition: service_started} + external-test: {condition: service_healthy} +networks: + sample: + external: true + name: ukmesh-sample_default +volumes: + timescaledb_data: {external: true, name: ukmesh-sample_sample-db} + mosquitto_log: {external: true, name: ukmesh-sample_sample-mqtt-log} diff --git a/scripts/full-dev/control.sh b/scripts/full-dev/control.sh new file mode 100644 index 00000000..e8e3f90d --- /dev/null +++ b/scripts/full-dev/control.sh @@ -0,0 +1,88 @@ +#!/usr/bin/env bash +set -euo pipefail +repo=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd) +cd "$repo" +source "$repo/scripts/full-dev/runtime.sh" +source "$repo/scripts/lib/owned-processes.sh" +state="$repo/plans/lean-runtime/runtime" +mkdir -p "$state" +chmod 700 "$repo/plans/lean-runtime" "$state" +action=${1:-start} +service=${2:-} +case "$action" in + start|build|status|stop|logs|restart|hot|config) ;; + *) echo "Unknown full-stack action: $action" >&2; exit 2 ;; +esac +if [[ -n $service && $action != hot ]]; then + "${compose[@]}" config --services | rg -Fx -- "$service" > /dev/null || { echo "Unknown service: $service" >&2; exit 2; } +fi +case "$action" in + status) "${compose[@]}" ps -a; exit ;; + logs) "${compose[@]}" logs --tail 100 ${service:+"$service"}; exit ;; + config) "${compose[@]}" config --quiet; exit ;; + stop) + "${compose[@]}" stop + bash "$repo/scripts/dev-stack.sh" stop + exit ;; + restart) + [[ -n $service ]] || { echo 'restart requires a service name' >&2; exit 2; } + python3 "$repo/scripts/full-dev/wiring.py" + refresh_wiring_revisions + "${compose[@]}" up -d --no-deps --force-recreate "$service"; exit ;; +esac + +prepare_wiring() { + python3 "$repo/scripts/full-dev/wiring.py" + refresh_wiring_revisions +} + +build_images() { + prepare_wiring + for component in backend app-ukmesh website-ukmesh website-dev tagger-worker link-worker hopreach mesh-health-check mosquitto-reloader; do + echo "Building $component (one image at a time)" + "${compose[@]}" build "$component" > "$state/build-$component.log" 2>&1 || { tail -40 "$state/build-$component.log" >&2; return 1; } + done + git rev-parse HEAD > "$state/built-revision" +} + +if [[ $action == build ]]; then build_images; exit; fi +if [[ $action == hot ]]; then + [[ $service == ukmesh ]] || { echo 'hot supports ukmesh or beacon-web' >&2; exit 2; } + "${compose[@]}" -f "$repo/scripts/full-dev/hot.yml" up -d --no-deps --force-recreate website-ukmesh + exit +fi + +prepare_wiring +if ! docker network inspect ukmesh-sample_default >/dev/null 2>&1; then + if [[ -f $repo/plans/dev-stack/fixture-ready ]]; then bash "$repo/scripts/dev-stack.sh" start; else bash "$repo/scripts/dev-stack.sh" up; fi +fi +docker compose --project-name ukmesh-sample --env-file /dev/null -f "$repo/scripts/local-sample/compose.yml" up -d --wait db redis mqtt +images_ready=true +for image in "$BACKEND_IMAGE" "$APP_IMAGE" "$WEBSITE_IMAGE" "$WEBSITE_DEV_IMAGE" "$TAGGER_WORKER_IMAGE" "$RF_WORKER_IMAGE" "$HOPREACH_IMAGE" "$HEALTHCHECK_IMAGE" "$MOSQUITTO_RELOADER_IMAGE"; do + docker image inspect "$image" >/dev/null 2>&1 || images_ready=false +done +if [[ $images_ready != true ]]; then build_images; fi + +# Schema owners run only in this bounded bootstrap step. Runtime containers +# below receive their role DSNs, including on a newly selected fixture. +"${compose[@]}" run --rm --no-deps db-migrate > "$state/migrate.log" 2>&1 || { tail -30 "$state/migrate.log" >&2; exit 1; } +bash "$repo/scripts/full-dev/access.sh" "$UKMESH_DATABASE" "$OWNER_DATABASE" > "$state/access.log" 2>&1 || { tail -20 "$state/access.log" >&2; exit 1; } + +# Retire only PIDs owned by the old fixture launcher, after images exist. +for service in frontend region-snapshot backend; do + case "$service" in + frontend) entry="$repo/frontend/node_modules/vite/bin/vite.js" ;; + region-snapshot) entry="$repo/backend/dist/workers/region-snapshot.js" ;; + backend) entry="$repo/backend/dist/index.js" ;; + esac + owned_stop_process "$repo/plans/dev-stack/$service.pid" "$entry" 100 0.1 "$service" +done +mapfile -t resident_services < <("${compose[@]}" config --services | rg -v '^(db-migrate|mesh-health-check-data-init|alert-bootstrap|link-backfill-worker|cloudflared)$') +"${compose[@]}" up -d --wait --wait-timeout 240 "${resident_services[@]}" +"${compose[@]}" up -d --no-deps link-backfill-worker +"${compose[@]}" wait link-backfill-worker +backfill_container=$("${compose[@]}" ps -a -q link-backfill-worker) +[[ -n $backfill_container ]] || { echo 'Link backfill container is missing' >&2; exit 1; } +backfill_state=$(docker inspect --format '{{.State.Status}}:{{.State.ExitCode}}' "$backfill_container") +[[ $backfill_state == exited:0 ]] || { echo 'Link backfill job failed or did not complete' >&2; exit 1; } +printf 'UKMesh http://127.0.0.1:5173\nDashboard http://127.0.0.1:3003\nHealth Check http://127.0.0.1:3090\nGrafana http://127.0.0.1:3010\n' diff --git a/scripts/full-dev/corescope-reader.sql b/scripts/full-dev/corescope-reader.sql new file mode 100644 index 00000000..6fb8ef43 --- /dev/null +++ b/scripts/full-dev/corescope-reader.sql @@ -0,0 +1,162 @@ +-- Apply with the fixture migration owner through psql. A dedicated CoreScope +-- backend reads public content and the four-column policy needed to revoke +-- its SQLite copies; it receives no raw table or Redis credential. +\if :{?corescope_reader_role} +\else +\set corescope_reader_role corescope_ro +\endif + +BEGIN; +SELECT pg_catalog.set_config('ukmesh.corescope_reader_role', :'corescope_reader_role', true); +DO $guard$ +DECLARE + reader pg_catalog.pg_roles%ROWTYPE; + target regclass; + marker text; +BEGIN + IF current_database() !~ '^lean_(verify|fixture|1x|10x|soak)_[a-z0-9_]{1,38}$' THEN + RAISE EXCEPTION 'CoreScope reader provisioning requires an owned lean fixture database'; + END IF; + SELECT shobj_description(oid, 'pg_database') INTO marker + FROM pg_database WHERE datname = current_database(); + IF marker IS NULL OR marker !~ '^ukmesh-owned-fixture:[a-z0-9_]{1,38}$' + OR right(current_database(), length(split_part(marker, ':', 2)) + 1) + <> '_' || split_part(marker, ':', 2) THEN + RAISE EXCEPTION 'CoreScope reader fixture ownership marker is missing or mismatched'; + END IF; + SELECT * INTO reader FROM pg_catalog.pg_roles + WHERE rolname = current_setting('ukmesh.corescope_reader_role'); + IF NOT FOUND OR reader.rolsuper OR reader.rolcreatedb OR reader.rolcreaterole + OR reader.rolreplication OR reader.rolbypassrls OR reader.rolinherit THEN + RAISE EXCEPTION 'CoreScope reader must be an existing unprivileged NOINHERIT role'; + END IF; + IF EXISTS (SELECT 1 FROM pg_catalog.pg_auth_members WHERE member = reader.oid) THEN + RAISE EXCEPTION 'CoreScope reader must not inherit or assume other roles'; + END IF; + FOREACH target IN ARRAY ARRAY[ + to_regclass('mesh.packets'), to_regclass('core.nodes'), + to_regclass('core.private_node_prefixes'), to_regclass('mesh.ingest_observation_ledger'), + to_regclass('public.packets'), to_regclass('public.nodes'), + to_regclass('public.private_node_prefixes') + ] LOOP + IF target IS NOT NULL AND has_any_column_privilege(reader.oid, target, 'SELECT') THEN + RAISE EXCEPTION 'CoreScope reader has raw relation privileges; provision a dedicated role'; + END IF; + END LOOP; + IF EXISTS (SELECT 1 FROM pg_namespace + WHERE nspname = 'corescope_public' AND nspowner = reader.oid) THEN + RAISE EXCEPTION 'CoreScope reader cannot own its projection schema'; + END IF; +END +$guard$; + +CREATE SCHEMA IF NOT EXISTS corescope_public; +REVOKE ALL ON SCHEMA corescope_public FROM PUBLIC; + +CREATE OR REPLACE FUNCTION corescope_public.privacy_ready() +RETURNS boolean LANGUAGE sql STABLE SECURITY DEFINER +SET search_path = pg_catalog +AS $ready$ + SELECT EXISTS ( + SELECT 1 FROM ops.public_visibility_state visibility + JOIN ops.packet_visibility_materialization_state materialized + ON materialized.singleton = visibility.singleton + WHERE visibility.singleton = TRUE AND visibility.generation > 0 + AND materialized.visibility_generation = visibility.generation + ) AND EXISTS ( + SELECT 1 FROM mesh.ingest_observation_ledger_coverage + WHERE singleton = TRUE AND version = 1 + ) AND NOT EXISTS ( + SELECT 1 FROM ops.privacy_rematerialization_queue + WHERE status IN ('pending', 'processing', 'failed') + ) +$ready$; + +CREATE OR REPLACE FUNCTION corescope_public.meshcore_path_is_valid( + path_hashes text[], path_hash_size_bytes integer +) RETURNS boolean LANGUAGE sql IMMUTABLE SECURITY DEFINER +SET search_path = pg_catalog +AS $valid$ + SELECT public.meshcore_path_is_valid(path_hashes, path_hash_size_bytes) +$valid$; + +CREATE OR REPLACE FUNCTION corescope_public.meshcore_path_matches_private( + network text, rx_node_id text, src_node_id text, + path_hashes text[], path_hash_size_bytes integer +) RETURNS boolean LANGUAGE sql STABLE SECURITY DEFINER +SET search_path = pg_catalog +AS $private$ + SELECT public.meshcore_path_matches_private( + network, rx_node_id, src_node_id, path_hashes, path_hash_size_bytes + ) +$private$; + +CREATE OR REPLACE VIEW corescope_public.packets WITH (security_barrier = true) AS +SELECT p.time, p.topic, p.raw_hex, p.snr, p.rssi, + pg_catalog.jsonb_build_object('direction', p.payload->>'direction') AS payload, + p.observation_id, p.network, p.rx_node_id, p.src_node_id, + p.path_hashes, p.path_hash_size_bytes +FROM mesh.packets p +WHERE (SELECT corescope_public.privacy_ready()) + AND p.visibility_ok IS TRUE AND p.is_private IS NOT TRUE + AND corescope_public.meshcore_path_is_valid(p.path_hashes, p.path_hash_size_bytes) + AND NOT corescope_public.meshcore_path_matches_private( + p.network, p.rx_node_id, p.src_node_id, p.path_hashes, p.path_hash_size_bytes + ); + +CREATE OR REPLACE VIEW corescope_public.nodes WITH (security_barrier = true) AS +SELECT n.public_key, n.name +FROM core.nodes n +WHERE (SELECT corescope_public.privacy_ready()) + AND COALESCE(n.name, '') NOT LIKE '%🚫%' + AND NOT EXISTS ( + SELECT 1 FROM core.private_node_prefixes prefix + WHERE prefix.node_id IN (n.node_id, n.public_key) + ); + +CREATE OR REPLACE VIEW corescope_public.ingest_observation_ledger +WITH (security_barrier = true) AS +SELECT ledger.seq, ledger.observation_id, ledger.observed_at, ledger.network +FROM mesh.ingest_observation_ledger ledger +WHERE EXISTS ( + SELECT 1 FROM corescope_public.packets packet + WHERE packet.observation_id = ledger.observation_id + AND packet.time = ledger.observed_at +); + +CREATE OR REPLACE VIEW corescope_public.ingest_observation_ledger_coverage AS +SELECT singleton, version FROM mesh.ingest_observation_ledger_coverage; +CREATE OR REPLACE VIEW corescope_public.public_visibility_state AS +SELECT singleton, generation FROM ops.public_visibility_state; +CREATE OR REPLACE VIEW corescope_public.packet_visibility_materialization_state AS +SELECT singleton, visibility_generation FROM ops.packet_visibility_materialization_state; +CREATE OR REPLACE VIEW corescope_public.privacy_rematerialization_queue AS +SELECT DISTINCT status FROM ops.privacy_rematerialization_queue +WHERE status IN ('pending', 'processing', 'failed'); + +-- These exact four policy columns are required by loadCorePublicPolicy to +-- remove previously public observations from its private replay journal. +-- They are backend revocation metadata, never an HTTP/public-content export. +CREATE OR REPLACE VIEW corescope_public.private_node_prefixes AS +SELECT node_id, network, prefix_size_bytes, prefix FROM core.private_node_prefixes; + +REVOKE ALL ON FUNCTION corescope_public.privacy_ready() FROM PUBLIC; +REVOKE ALL ON FUNCTION corescope_public.meshcore_path_is_valid(text[], integer) FROM PUBLIC; +REVOKE ALL ON FUNCTION corescope_public.meshcore_path_matches_private(text, text, text, text[], integer) FROM PUBLIC; +GRANT USAGE ON SCHEMA corescope_public TO :"corescope_reader_role"; +GRANT SELECT ON corescope_public.packets, corescope_public.nodes, + corescope_public.ingest_observation_ledger, + corescope_public.ingest_observation_ledger_coverage, + corescope_public.public_visibility_state, + corescope_public.packet_visibility_materialization_state, + corescope_public.privacy_rematerialization_queue, + corescope_public.private_node_prefixes TO :"corescope_reader_role"; +GRANT EXECUTE ON FUNCTION corescope_public.privacy_ready(), + corescope_public.meshcore_path_is_valid(text[], integer), + corescope_public.meshcore_path_matches_private(text, text, text, text[], integer) + TO :"corescope_reader_role"; +SELECT pg_catalog.format( + 'ALTER ROLE %I IN DATABASE %I SET search_path = pg_catalog, corescope_public', + :'corescope_reader_role', current_database() +) \gexec +COMMIT; diff --git a/scripts/full-dev/environment.sh b/scripts/full-dev/environment.sh new file mode 100644 index 00000000..ac9940af --- /dev/null +++ b/scripts/full-dev/environment.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Local wiring only. Resource policy is inherited from the main Compose file. +unset COMPOSE_PROJECT_NAME +export POSTGRES_USER=meshcore POSTGRES_PASSWORD=meshcore POSTGRES_DB=meshcore +export REDIS_URL=redis://ukmesh-sample-redis:6379 REDIS_PASSWORD=local-unused-cache-only +export MQTT_BROKER_URL=ws://ukmesh-sample-mqtt:9001 MQTT_USERNAME= MQTT_PASSWORD= +export JWT_SECRET=local-only-development-secret-at-least-32-characters +export OWNER_COOKIE_SECRET=local-only-cookie-secret-at-least-32-characters +export OPERATOR_SITE_TOKEN=local-only-token +export ALERT_RECEIVER_TOKEN=local-full-alert-token-0123456789abcdef +export GRAFANA_ADMIN_PASSWORD=local-full-grafana-only +export ANUBIS_ED25519_PRIVATE_KEY_HEX=0101010101010101010101010101010101010101010101010101010101010101 +export HEALTHCHECK_SOURCE_REF=c93af192ec7cc0ecdfb3e9d0ea163840202ccbfc +export CLOUDFLARE_TUNNEL_TOKEN= SOURCE_REVISION="$(git -C "$repo" rev-parse HEAD)" +export BACKEND_IMAGE=ukmesh-full-backend:local APP_IMAGE=ukmesh-full-app:local +export WEBSITE_IMAGE=ukmesh-full-website:local WEBSITE_DEV_IMAGE=ukmesh-full-website-dev:local +export TAGGER_WORKER_IMAGE=ukmesh-full-tagger:local RF_WORKER_IMAGE=ukmesh-full-link:local +export HOPREACH_IMAGE=ukmesh-full-hopreach:local HEALTHCHECK_IMAGE=ukmesh-full-health-check:local +export MOSQUITTO_RELOADER_IMAGE=ukmesh-full-reloader:local +export JOURNAL_GID="$(stat -c '%g' /var/log/journal)" +export UKMESH_DATABASE=meshcore OWNER_DATABASE=meshcore_owner_auth BEACON_DATABASE=beacon_dev +export CORESCOPE_DATA_DIR="$repo/plans/companion-dev/runtime/corescope" +targets="$repo/plans/lean-runtime/runtime/targets.env" +if [[ -f $targets ]]; then + while IFS='=' read -r key value; do + [[ -n $key && $key != \#* ]] || continue + case "$key" in + UKMESH_DATABASE) [[ $value == meshcore || $value =~ ^lean_[a-z0-9_]+$ ]] ;; + OWNER_DATABASE) [[ $value == meshcore_owner_auth || $value =~ ^lean_[a-z0-9_]+$ ]] ;; + BEACON_DATABASE) [[ $value == beacon_dev || $value =~ ^lean_[a-z0-9_]+$ ]] ;; + CORESCOPE_DATA_DIR) + [[ $value == "$repo/plans/companion-dev/runtime/corescope" || $value == "$repo/plans/lean-runtime/runtime/fixtures/"* ]] && + [[ $(realpath -m -- "$value") == "$value" ]] ;; + *) echo "Unknown fixture target key: $key" >&2; return 1 ;; + esac || { echo "Invalid local fixture target: $key" >&2; return 1; } + export "$key=$value" + done < "$targets" +fi + +# Runtime containers receive only their own role; the administrator DSN is +# interpolated exclusively into the one-shot migration service. +export POSTGRES_DB="$UKMESH_DATABASE" +export MESHCORE_HTTP_DATABASE_URL="postgresql://meshcore_api:local-full-dev-only@ukmesh-sample-db:5432/$UKMESH_DATABASE" +export MESHCORE_INGEST_DATABASE_URL="postgresql://meshcore_ingest:local-full-dev-only@ukmesh-sample-db:5432/$UKMESH_DATABASE" +export MESHCORE_WORKER_DATABASE_URL="postgresql://meshcore_worker:local-full-dev-only@ukmesh-sample-db:5432/$UKMESH_DATABASE" +export OWNER_DATABASE_URL="postgresql://meshcore_owner:local-full-dev-only@ukmesh-sample-db:5432/$OWNER_DATABASE" +export MESHCORE_MIGRATE_DATABASE_URL="postgresql://meshcore:meshcore@ukmesh-sample-db:5432/$UKMESH_DATABASE" +export POSTGRES_EXPORTER_DATABASE_URL="postgresql://meshcore_monitor:local-full-dev-only@ukmesh-sample-db:5432/$UKMESH_DATABASE?sslmode=disable" +export DATABASE_ROLE_ENFORCEMENT=true diff --git a/scripts/full-dev/external-test.mjs b/scripts/full-dev/external-test.mjs new file mode 100644 index 00000000..5fb82ed9 --- /dev/null +++ b/scripts/full-dev/external-test.mjs @@ -0,0 +1,46 @@ +import http from 'node:http'; + +const counts = {tags: 0, alerts: 0, failures: 0, lastAlertProbe: ''}; +let failureStatus = 0; +const server = http.createServer((request, response) => { + handle(request, response).catch(error => { + if (!response.headersSent) response.writeHead(error instanceof SyntaxError ? 400 : 500); + response.end(); + }); +}); +async function handle(request, response) { + const url = new URL(request.url, 'http://local-test'); + if (url.pathname === '/healthz' || url.pathname === '/counts') { + response.writeHead(200, {'content-type': 'application/json'}); + response.end(JSON.stringify(counts)); + return; + } + if (request.method !== 'POST') { response.writeHead(405); response.end(); return; } + let body = ''; + for await (const chunk of request) { + body += chunk; + if (Buffer.byteLength(body) > 1_048_576) { response.writeHead(413); response.end(); return; } + } + if (url.pathname === '/failure') { + const value = JSON.parse(body).status; + if (![0, 429, 503].includes(value)) { response.writeHead(400); response.end(); return; } + failureStatus = value; response.writeHead(204); response.end(); return; + } + if (failureStatus) { counts.failures++; response.writeHead(failureStatus); response.end(); return; } + if (url.pathname === '/alerts') { + const probe = body.match(/OwnedFullStackProbe-([a-f0-9]{32})/); + if (probe) counts.lastAlertProbe = probe[1]; + counts.alerts++; response.writeHead(204); response.end(); return; + } + if (url.pathname === '/tag') { + counts.tags++; + response.writeHead(200, {'content-type': 'application/json'}); + response.end(JSON.stringify({answers: {speaker: {choice: 'human', confidence: 0.99}, kind: {choice: 'test-ping', confidence: 0.99}, directed: {noul: false, confidence: 0.99}, safety: {noul: false, confidence: 0.99}}})); + return; + } + response.writeHead(404); response.end(); +} +const port = Number(process.env.PORT ?? 8080); +if (!Number.isSafeInteger(port) || port < 0 || port > 65535) throw new Error('Invalid test endpoint port'); +server.listen(port, '0.0.0.0', () => console.log(JSON.stringify({listening: server.address().port}))); +process.on('SIGTERM', () => server.close()); diff --git a/scripts/full-dev/external-test.test.mjs b/scripts/full-dev/external-test.test.mjs new file mode 100644 index 00000000..a0bd90fd --- /dev/null +++ b/scripts/full-dev/external-test.test.mjs @@ -0,0 +1,34 @@ +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { createInterface } from 'node:readline'; +import test from 'node:test'; + +test('local providers survive malformed input and preserve explicit failure/recovery and forwarding proof', {timeout: 10000}, async () => { + const child = spawn(process.execPath, [new URL('./external-test.mjs', import.meta.url).pathname], { + env: {PORT: '0'}, stdio: ['ignore', 'pipe', 'pipe'], + }); + const output = createInterface({input: child.stdout}); + try { + const [line] = await once(output, 'line'); + const base = `http://127.0.0.1:${JSON.parse(line).listening}`; + const post = (route, body) => fetch(base + route, {method: 'POST', body: typeof body === 'string' ? body : JSON.stringify(body)}); + assert.equal((await post('/failure', '{broken')).status, 400); + assert.equal((await fetch(base + '/healthz')).status, 200); + assert.equal((await post('/failure', {status: 429})).status, 204); + assert.equal((await post('/tag', {state: 'owned fixture'})).status, 429); + assert.equal((await post('/failure', {status: 0})).status, 204); + const classification = await (await post('/tag', {state: 'owned fixture'})).json(); + assert.equal(classification.answers.kind.choice, 'test-ping'); + const probe = 'a'.repeat(32); + assert.equal((await post('/alerts', {content: 'OwnedFullStackProbe-' + probe})).status, 204); + const counts = await (await fetch(base + '/counts')).json(); + assert.equal(counts.tags, 1); + assert.equal(counts.failures, 1); + assert.equal(counts.lastAlertProbe, probe); + } finally { + output.close(); + child.kill('SIGTERM'); + await once(child, 'exit'); + } +}); diff --git a/scripts/full-dev/hot.yml b/scripts/full-dev/hot.yml new file mode 100644 index 00000000..ae533e52 --- /dev/null +++ b/scripts/full-dev/hot.yml @@ -0,0 +1,20 @@ +services: + website-ukmesh: + image: node@sha256:5df79989ed685e09f0a98019db4cebfb22fb9df1a53c0161664a011f7ff6b0f1 + user: "1000:1000" + working_dir: /work + entrypoint: [node, node_modules/vite/bin/vite.js, --host, 0.0.0.0, --port, "5173", --strictPort] + command: [] + environment: + UKMESH_DEV_API_TARGET: http://backend:3000 + VITE_BUILD_TARGET: public-website + VITE_SITE: ukmesh + VITE_APP_HOSTNAME: 127.0.0.1:3003 + volumes: !override + - ./frontend:/work:ro + - ./frontend/node_modules:/work/node_modules + ports: !override ["127.0.0.1:5173:5173", "127.0.0.1:3004:5173"] + mem_limit: 768m + memswap_limit: 768m + healthcheck: + test: [CMD, node, -e, "fetch('http://127.0.0.1:5173').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"] diff --git a/scripts/full-dev/runtime.sh b/scripts/full-dev/runtime.sh new file mode 100644 index 00000000..b988bb4c --- /dev/null +++ b/scripts/full-dev/runtime.sh @@ -0,0 +1,26 @@ +# Shared local Compose binding. Public entrypoints clean the environment first. +repo=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd) +source "$repo/scripts/full-dev/environment.sh" +export COMPOSE_PARALLEL_LIMIT=1 +compose=(docker compose --project-name ukmesh-full --env-file /dev/null \ + -f "$repo/docker-compose.yml" -f "$repo/scripts/full-dev/compose.yml") + +# Bind-mounted files keep their old inode after atomic replacement. Their +# content revisions make Compose recreate only the affected consumers. +refresh_wiring_revisions() { + local name variable revision suffix + for name in prometheus hopreach nginx.app nginx.website; do + case "$name" in + prometheus) variable=FULL_DEV_PROMETHEUS_REVISION; suffix=yml ;; + hopreach) variable=FULL_DEV_HOPREACH_REVISION; suffix=yaml ;; + nginx.app) variable=FULL_DEV_APP_PROXY_REVISION; suffix=conf ;; + nginx.website) variable=FULL_DEV_WEBSITE_PROXY_REVISION; suffix=conf ;; + esac + revision=unprepared + if [[ -f $repo/plans/lean-runtime/runtime/$name.$suffix ]]; then + read -r revision _ < <(sha256sum "$repo/plans/lean-runtime/runtime/$name.$suffix") + fi + export "$variable=$revision" + done +} +refresh_wiring_revisions diff --git a/scripts/full-dev/test_control.py b/scripts/full-dev/test_control.py new file mode 100644 index 00000000..475e850e --- /dev/null +++ b/scripts/full-dev/test_control.py @@ -0,0 +1,57 @@ +"""A finite backfill failure must fail startup even when Compose wait returns zero.""" +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + + +class FullStartupCompletion(unittest.TestCase): + def test_backfill_must_exit_successfully_before_startup_is_reported(self): + with tempfile.TemporaryDirectory(prefix='full controller ') as temporary: + root = Path(temporary) + tools = root / 'scripts/full-dev' + tools.mkdir(parents=True) + shutil.copyfile(Path(__file__).with_name('control.sh'), tools / 'control.sh') + (tools / 'wiring.py').write_text('') + (tools / 'access.sh').write_text('#!/bin/sh\nexit 0\n') + (tools / 'runtime.sh').write_text('''repo=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd) +compose=(docker compose) +UKMESH_DATABASE=lean_fixture_owned OWNER_DATABASE=lean_owner_owned +BACKEND_IMAGE=ready APP_IMAGE=ready WEBSITE_IMAGE=ready WEBSITE_DEV_IMAGE=ready +TAGGER_WORKER_IMAGE=ready RF_WORKER_IMAGE=ready HOPREACH_IMAGE=ready HEALTHCHECK_IMAGE=ready MOSQUITTO_RELOADER_IMAGE=ready +refresh_wiring_revisions() { :; } +''') + library = root / 'scripts/lib' + library.mkdir() + (library / 'owned-processes.sh').write_text('owned_stop_process() { :; }\n') + executables = root / 'tools' + executables.mkdir() + docker = executables / 'docker' + docker.write_text('''#!/usr/bin/python3 +from pathlib import Path +import sys +args=sys.argv[1:] +if 'config' in args and '--services' in args: print('backend\\nlink-backfill-worker\\ndb-migrate') +if 'ps' in args: print('owned-backfill-container') +if args and args[0]=='inspect': print((Path.cwd()/'job-result').read_text()) +''') + docker.chmod(0o755) + environment = {'PATH': str(executables) + ':' + os.environ['PATH'], 'HOME': temporary} + for state in ('exited:1', 'running:0', 'exited:0'): + with self.subTest(state=state): + (root / 'job-result').write_text(state) + result = subprocess.run(['bash', str(tools / 'control.sh'), 'start'], cwd=root, + env=environment, capture_output=True, text=True, timeout=20) + if state == 'exited:0': + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn('UKMesh http://', result.stdout) + else: + self.assertNotEqual(result.returncode, 0) + self.assertIn('Link backfill job failed or did not complete', result.stderr) + self.assertNotIn('UKMesh http://', result.stdout) + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/full-dev/test_wiring.py b/scripts/full-dev/test_wiring.py new file mode 100644 index 00000000..94543414 --- /dev/null +++ b/scripts/full-dev/test_wiring.py @@ -0,0 +1,47 @@ +"""Unchanged local wiring keeps its inode; changed wiring advances its revision.""" +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest +import yaml + + +class WiringPublication(unittest.TestCase): + def test_local_substitutions_preserve_policy_and_only_replace_changed_files(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + tool = root / 'scripts/full-dev/wiring.py' + tool.parent.mkdir(parents=True) + shutil.copyfile(Path(__file__).with_name('wiring.py'), tool) + (root / 'logging').mkdir() + (root / 'logging/prometheus.yml').write_text('targets: [mosquitto:9001, backend:9091]\n') + (root / 'rf-coverage').mkdir() + policy = {'precision': {'chunk_mib': 128, 'resolution': 30}, + 'gpu': {'mode': 'cpu', 'remote': {'broker_addr': 'configured.example:1883'}}} + (root / 'rf-coverage/config.ukmesh.yaml').write_text(yaml.safe_dump(policy)) + for name in ('app', 'website'): + (root / ('nginx.' + name + '.conf')).write_text('real_ip $http_cf_connecting_ip;\n') + subprocess.run(['python3', str(tool)], check=True) + state = root / 'plans/lean-runtime/runtime' + first = {path.name: (path.stat().st_ino, path.read_text()) for path in state.iterdir()} + subprocess.run(['python3', str(tool)], check=True) + self.assertEqual({path.name: (path.stat().st_ino, path.read_text()) for path in state.iterdir()}, first) + (root / 'nginx.website.conf').write_text('changed $http_cf_connecting_ip;\n') + subprocess.run(['python3', str(tool)], check=True) + for name, (inode, _) in first.items(): + if name == 'nginx.website.conf': + self.assertNotEqual((state / name).stat().st_ino, inode) + else: + self.assertEqual((state / name).stat().st_ino, inode) + self.assertEqual((state / 'nginx.website.conf').read_text(), 'changed $http_x_real_ip;\n') + self.assertIn('ukmesh-sample-mqtt:9001', (state / 'prometheus.yml').read_text()) + rendered = yaml.safe_load((state / 'hopreach.yaml').read_text()) + self.assertEqual(rendered['precision'], policy['precision']) + self.assertEqual(rendered['gpu']['mode'], 'cpu') + self.assertEqual(rendered['gpu']['remote']['broker_addr'], '') + self.assertEqual(yaml.safe_load((root / 'rf-coverage/config.ukmesh.yaml').read_text()), policy) + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/full-dev/wiring.py b/scripts/full-dev/wiring.py new file mode 100644 index 00000000..cc24da74 --- /dev/null +++ b/scripts/full-dev/wiring.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +"""Materialize local endpoint substitutions from the canonical configurations.""" +from pathlib import Path +import os +import yaml + +root = Path(__file__).resolve().parents[2] +state = root / 'plans/lean-runtime/runtime' +state.mkdir(parents=True, exist_ok=True, mode=0o700) + +def publish(name, text): + target = state / name + if target.exists() and target.read_text() == text: + return + temporary = state / (name + '.next') + temporary.write_text(text) + temporary.chmod(0o644) + os.replace(temporary, target) + +publish('prometheus.yml', (root / 'logging/prometheus.yml').read_text().replace( + 'mosquitto:9001', 'ukmesh-sample-mqtt:9001')) +coverage = yaml.safe_load((root / 'rf-coverage/config.ukmesh.yaml').read_text()) +# A configured broker enables remote dispatch even when local gpu.mode is cpu. +coverage['gpu']['remote']['broker_addr'] = '' +publish('hopreach.yaml', yaml.safe_dump(coverage, sort_keys=False)) + +# Local Anubis receives direct TCP clients and replaces X-Real-IP itself; +# Cloudflare's incoming header is not an authority on this fixture ingress. +for name in ('nginx.app.conf', 'nginx.website.conf'): + publish(name, (root / name).read_text().replace('$http_cf_connecting_ip', '$http_x_real_ip')) diff --git a/scripts/local-sample/compose.yml b/scripts/local-sample/compose.yml index ef83ef41..b5c5dddd 100644 --- a/scripts/local-sample/compose.yml +++ b/scripts/local-sample/compose.yml @@ -34,12 +34,29 @@ services: retries: 30 cpus: 1 mem_limit: 256m + mqtt-log-init: + image: eclipse-mosquitto@sha256:75d6662dee52c947dc9dd9c29f1d8d7ffef78ddaf38001caa09755681e8bbc98 + user: "0:0" + entrypoint: ["/bin/sh", "-ec"] + command: + - | + touch /mosquitto/log/mosquitto.log + chown -R 1883:1883 /mosquitto/log + chmod 0750 /mosquitto/log + chmod 0640 /mosquitto/log/mosquitto.log + network_mode: none + restart: "no" + mem_limit: 16m + volumes: [sample-mqtt-log:/mosquitto/log] mqtt: image: eclipse-mosquitto@sha256:75d6662dee52c947dc9dd9c29f1d8d7ffef78ddaf38001caa09755681e8bbc98 container_name: ukmesh-sample-mqtt ports: ["127.0.0.1:1884:1883", "127.0.0.1:9002:9001"] volumes: - ./mosquitto-test.conf:/mosquitto/config/mosquitto.conf:ro + - sample-mqtt-log:/mosquitto/log + depends_on: + mqtt-log-init: {condition: service_completed_successfully} healthcheck: test: ["CMD-SHELL", "mosquitto_pub -h 127.0.0.1 -t local/health -m ready -q 1"] interval: 2s @@ -49,3 +66,4 @@ services: mem_limit: 256m volumes: sample-db: + sample-mqtt-log: diff --git a/scripts/local-sample/mosquitto-test.conf b/scripts/local-sample/mosquitto-test.conf index a46ad09d..f1b30a9b 100644 --- a/scripts/local-sample/mosquitto-test.conf +++ b/scripts/local-sample/mosquitto-test.conf @@ -19,7 +19,10 @@ allow_anonymous true persistence false log_dest stdout +log_dest file /mosquitto/log/mosquitto.log log_type warning log_type error log_type notice +# The authenticated reloader confirms SIGHUP from this broker's log marker. +log_type information connection_messages true diff --git a/scripts/test-dev-all.sh b/scripts/test-dev-all.sh index cd8c901a..4dc57cc0 100755 --- a/scripts/test-dev-all.sh +++ b/scripts/test-dev-all.sh @@ -1,85 +1,64 @@ #!/usr/bin/env bash -# Check fixture preservation, environment isolation and failure handling without services. +# Exercise orchestration, environment isolation, failure propagation and locking. set -euo pipefail repo=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd) -test_root=$(mktemp -d) -trap 'rm -rf -- "$test_root"' EXIT -fixture="$test_root/fixture with spaces" -mkdir -p "$fixture/bin" "$fixture/repo/scripts" "$fixture/repo/plans/dev-stack" -cp "$repo/scripts/dev-all.sh" "$fixture/repo/scripts/" -for name in corescope beacon-server beacon-web; do mkdir -p "$fixture/repo/third_party/$name"; touch "$fixture/repo/third_party/$name/.git"; done -printf 'keep fixture\n' > "$fixture/repo/plans/dev-stack/fixture-ready" -printf 'must not be sourced $(touch dotenv-sourced)\n' > "$fixture/repo/.env" -cat > "$fixture/bin/docker" <<'MOCK' +fixture=$(mktemp -d) +trap 'rm -rf -- "$fixture"' EXIT +checkout="$fixture/repo with spaces" +mkdir -p "$checkout/scripts/companion-dev" "$checkout/scripts/full-dev" "$checkout/plans/dev-stack" +cp "$repo/scripts/dev-all.sh" "$checkout/scripts/" +printf 'retained\n' > "$checkout/plans/dev-stack/fixture-ready" +printf 'must not source $(touch dotenv-sourced)\n' > "$checkout/.env" +for subsystem in full-dev companion-dev; do + cat > "$checkout/scripts/$subsystem/control.sh" <<'MOCK' #!/usr/bin/env bash set -euo pipefail -root=$(cd -- "$(dirname -- "$0")/.." && pwd) -[[ ! ${DATABASE_URL+x} && ! ${UNTRUSTED_INHERITED_SETTING+x} ]] || exit 91 -printf 'docker %s\n' "$*" >> "$root/calls" -if [[ $1 == compose ]]; then - [[ $2 == --env-file && $3 == /dev/null ]] || exit 92 - if [[ $* == *'run --rm --no-deps build' && -f $root/build-failure ]]; then exit 42; fi - if [[ $* == *'run --rm --no-deps build' && -f $root/build-pause ]]; then - touch "$root/build-entered" - while [[ -f $root/build-pause && ! -f $root/build-resume ]]; do sleep 0.01; done - fi +repo=$(cd -- "$(dirname -- "$0")/../.." && pwd) +[[ ! ${DATABASE_URL+x} && ! ${UNTRUSTED_SETTING+x} ]] || exit 91 +name=$(basename "$(dirname "$0")") +printf '%s %s\n' "$name" "$*" >> "$repo/calls" +if [[ $name == full-dev && $1 == build ]]; then + if [[ -f $repo/fail ]]; then exit 42; fi + if [[ -f $repo/pause ]]; then + touch "$repo/entered" + while [[ ! -f $repo/resume ]]; do sleep 0.01; done + fi fi MOCK -cat > "$fixture/bin/git" <<'MOCK' + done +cat > "$checkout/scripts/qualify-full-stack.sh" <<'MOCK' #!/usr/bin/env bash -root=$(cd -- "$(dirname -- "$0")/.." && pwd) -printf 'git %s\n' "$*" >> "$root/calls" -if [[ $* == *'diff --name-only --diff-filter=U' && -f $root/merge-conflict ]]; then echo conflict.go; fi -if [[ $* == *'symbolic-ref --short -q HEAD' ]]; then echo ukmesh-dev; fi +repo=$(cd -- "$(dirname -- "$0")/.." && pwd) +printf 'qualify %s\n' "$*" >> "$repo/calls" MOCK -cat > "$fixture/bin/curl" <<'MOCK' -#!/usr/bin/env bash -root=$(cd -- "$(dirname -- "$0")/.." && pwd) -[[ ! -f $root/ukmesh-unhealthy ]] -MOCK -cat > "$fixture/repo/scripts/dev-stack.sh" <<'MOCK' -#!/usr/bin/env bash -root=$(cd -- "$(dirname -- "$0")/../.." && pwd) -printf 'ukmesh %s\n' "$*" >> "$root/calls" -MOCK -chmod +x "$fixture/bin/"* -run() { env PATH="$fixture/bin:$PATH" DATABASE_URL=postgresql://untrusted.invalid/db UNTRUSTED_INHERITED_SETTING=discard bash "$fixture/repo/scripts/dev-all.sh" "$@" > "$fixture/output" 2>&1; } -: > "$fixture/calls" +run() { env DATABASE_URL=postgres://untrusted.invalid UNTRUSTED_SETTING=discard bash "$checkout/scripts/dev-all.sh" "$@" > "$fixture/output" 2>&1; } run start -! grep -q '^ukmesh ' "$fixture/calls" -grep -q 'run --rm --no-deps build' "$fixture/calls" -grep -q 'up -d --wait --wait-timeout 240' "$fixture/calls" -[[ $(cat "$fixture/repo/plans/dev-stack/fixture-ready") == 'keep fixture' ]] -[[ ! -e "$fixture/repo/dotenv-sourced" ]] -touch "$fixture/ukmesh-unhealthy" -run start -grep -q '^ukmesh start$' "$fixture/calls" -touch "$fixture/merge-conflict" -: > "$fixture/calls" -if run companions; then echo 'Unresolved merge was accepted' >&2; exit 1; fi -! grep -q 'docker compose' "$fixture/calls" -rm "$fixture/merge-conflict" -touch "$fixture/build-failure" -if run start; then echo 'Failed build was accepted' >&2; exit 1; fi -! grep -Eq '(^ukmesh reset|docker .* (down|stop))' "$fixture/calls" -rm "$fixture/build-failure" -: > "$fixture/calls" -if run restart unowned-service; then echo 'Unowned service was accepted' >&2; exit 1; fi -[[ ! -s "$fixture/calls" ]] -run init -! grep -Eq 'submodule update|switch' "$fixture/calls" +[[ $(cat "$checkout/calls") == $'full-dev start\ncompanion-dev start' ]] +[[ $(cat "$checkout/plans/dev-stack/fixture-ready") == retained ]] +[[ ! -f $checkout/dotenv-sourced ]] +: > "$checkout/calls" run stop -grep -q '^ukmesh stop$' "$fixture/calls" -[[ -f "$fixture/repo/plans/dev-stack/fixture-ready" ]] -touch "$fixture/build-pause" -run build & -first_operation=$! -for attempt in {1..100}; do [[ ! -f $fixture/build-entered ]] || break; sleep 0.01; done -[[ -f $fixture/build-entered ]] -if run companions; then echo 'Concurrent DEV mutation was accepted' >&2; exit 1; fi -grep -q 'Another DEV operation is running' "$fixture/output" -touch "$fixture/build-resume" -wait "$first_operation" -# The lock closes before child processes start, so later operations can proceed. +[[ $(cat "$checkout/calls") == $'companion-dev stop\nfull-dev stop' ]] +: > "$checkout/calls" run init -echo 'DEV companion launcher contracts passed' +[[ $(cat "$checkout/calls") == 'companion-dev init' ]] +: > "$checkout/calls" +run qualify sample --seconds 15 --run '/tmp/evidence with spaces' +[[ $(cat "$checkout/calls") == 'qualify sample --seconds 15 --run /tmp/evidence with spaces' ]] +touch "$checkout/fail" +: > "$checkout/calls" +if run build; then echo 'Failed build accepted' >&2; exit 1; fi +[[ $(cat "$checkout/calls") == 'full-dev build' ]] +rm "$checkout/fail" +touch "$checkout/pause" +run build & +operation=$! +for attempt in {1..100}; do [[ ! -f $checkout/entered ]] || break; sleep 0.01; done +[[ -f $checkout/entered ]] +if run start; then echo 'Concurrent mutation accepted' >&2; exit 1; fi +grep -q 'Another DEV operation is running' "$fixture/output" +touch "$checkout/resume" +wait "$operation" +run init +if run erase-everything; then echo 'Unknown action accepted' >&2; exit 1; fi +echo 'Full DEV launcher contracts passed' diff --git a/third_party/beacon-server b/third_party/beacon-server index 94b33690..2aabc9d1 160000 --- a/third_party/beacon-server +++ b/third_party/beacon-server @@ -1 +1 @@ -Subproject commit 94b33690a09c739af1781041ab72022ba9d34d5c +Subproject commit 2aabc9d1a42562b2c178b27598884cfd108e00d7 diff --git a/third_party/beacon-web b/third_party/beacon-web index efc526eb..941dbb98 160000 --- a/third_party/beacon-web +++ b/third_party/beacon-web @@ -1 +1 @@ -Subproject commit efc526eb4a8b9fe8aa916dd438f85bde54fda85c +Subproject commit 941dbb9845d11511a9bf609fbd8aa169bb5c52bc diff --git a/third_party/corescope b/third_party/corescope index b71529ec..9a43b3c9 160000 --- a/third_party/corescope +++ b/third_party/corescope @@ -1 +1 @@ -Subproject commit b71529ec0ffd7a99ec0aa9557551c14925f5ac10 +Subproject commit 9a43b3c9c044144d08a2da70e152145a174edd6f