# VPS deploy, compose-style, split so failure recovery is cheap: # # Clippy — -D warnings on --all-targets, own runner. No Postgres. # Build and test — Postgres sidecar, the whole suite, the release # build; packs the stripped binary + migrations into the # runtime image (deploy/Containerfile.runtime) and # uploads the image tarball + compose files as the run's # artifact. # Deploy — SSH: podman load the image, point the deploy-owned # stack.env's HEZARFEN_TAG at it, install compose.yaml + # the hezarfen_backend_compose user unit + the backup script, # restart the stack, /health-gated rollback to the # previous tag, independent after-the-fact verify. # # Two test paths, the default being the full one: # DEFAULT GitHub does everything: the suite runs on the runner, then the # build, the pack and the deploy. # SPECIAL Run the full suite on your own machine first # (scripts/gate-local.sh — 565s there vs ~55min on a 4-core # runner). It prints (or, with --amend, appends) a # `Local-Gate: ( passed, s)` trailer; commit it and # GitHub only packs and deploys. The "Decide test gate" step # verifies the trailer against HEAD^{tree} before honouring it — # a stale or copy-pasted trailer silently falls back to running # the suite. # # Clippy and Build and test run in parallel. Deploy needs both green. # A new push cancels in-flight Clippy/Build on the same ref; it never # cancels an in-flight Deploy (two deploys racing would interleave the # compose stack). # # Fail-fast: Clippy is ~2 minutes, Build-and-test up to 90. A red Clippy # still leaves the suite burning runner minutes for nothing — the deploy # already gates on both, so the outcome is decided. The `clippy-guard` # job fires the moment Clippy concludes red and cancels the whole run, # killing the in-flight suite. Parallelism is untouched: the guard only # ever runs on the failure path. (GitHub has no native "sibling job # failed → cancel the rest"; the run-cancel API is the door.) # # The split is the recovery story, not ceremony: # * "Re-run failed jobs" on a run whose Deploy step failed re-runs ONLY the # ~1-minute deploy job — the built image is still in the run's artifact. # * workflow_dispatch (the manual door: Actions tab → Run workflow on main, # or `gh workflow run main.yml --ref main`) deploys WITHOUT the suite by # default: it takes the newest artifact a green Build-and-test produced — # which can lag HEAD while a push is mid-CI, and that is the point: # redeploy the known-good image, e.g. after a server-side fix (env file, # proxy, database). Its `tests` input overrides that: `force` runs the # whole build job, suite included, on the dispatched ref and deploys that # fresh artifact; `skip` (and `auto`) take the newest green one. For # env-only changes a plain # `ssh 'systemctl --user restart hezarfen_backend_compose'` needs no # workflow at all: the stack re-reads its env files on the next # `podman compose up`. # # One-time prerequisites, outside the workflow's reach: # * the repo secrets SSH_PRIVATE_KEY / SSH_HOST / SSH_USER; # * `loginctl enable-linger ` on the server unless the deploy user # already has it — user units need a running user manager; # * podman plus a compose provider on the server (the deploy checks for # both and fails with a one-line install hint); # * the operator's ~/hezarfen_backend/hezarfen_backend.env (0600), written # once by hand from deploy/hezarfen_backend.env.example — at minimum the # POSTGRES_PASSWORD and BUILDER_PASSWORD lines. The deploy never # creates or overwrites it. name: VPS deploy on: push: branches: - main # The manual redeploy door — see the header comment for how and why. workflow_dispatch: inputs: tests: description: "Run the test suite on this run? auto/skip redeploy the newest green artifact; force builds and tests the dispatched ref first." type: choice options: - auto - skip - force default: auto # Deploy serialisation lives on the deploy job, not the workflow: a new # push must be allowed to cancel stale Clippy/Build without touching an # in-flight VPS swap. env: # A gnu binary links against the toolchain's glibc, so the runner is # pinned (see runs-on below) to 24.04, and the runtime image is # debian:trixie-slim: move either side without thinking and the binary # stops loading inside the container. The pin is what forces a conscious # decision rather than a broken deploy. In exchange: no cross-toolchain, # and the linker is rustc's default bundled lld. TARGET: x86_64-unknown-linux-gnu # The systemd user unit that wraps `podman compose`. See # deploy/hezarfen_backend_compose.service. SERVICE: hezarfen_backend_compose # The deploy lives in this subdirectory of the SSH user's home. The home # itself is resolved on the server ($HOME), so switching the deploy user # moves the path with it — a baked-in absolute path once kept pointing at # the previous user's home and failed the deploy on permissions. DEPLOY_SUBDIR: hezarfen_backend # Compose interpolates its secrets from this file on the server (passed # as --env-file, and to the backend container as env_file). The deploy # never writes it, only checks it exists and carries the # POSTGRES_PASSWORD / BUILDER_PASSWORD lines prod must not run without. ENV_FILE_NAME: hezarfen_backend.env # The Postgres the test suite mints its per-test databases on. Credentials # and port match the harness default (HEZARFEN_TEST_DATABASE_URL), so the # tests need no extra environment — only the server, with the raised # connection ceiling the parallel suite exhausts (see compose.yaml). PG_USER: hezarfen PG_PASSWORD: hezarfen # sqlx's compile-time macros verify every query against the committed .sqlx # cache, so the build must never reach for a live database (same as the # Containerfile). SQLX_OFFLINE: "true" jobs: clippy: name: Clippy if: github.event_name == 'push' runs-on: ubuntu-24.04 concurrency: group: ci-${{ github.workflow }}-${{ github.ref }}-clippy cancel-in-progress: true env: CARGO_INCREMENTAL: "0" steps: - name: Checkout uses: actions/checkout@v4 - name: Set up Rust run: rustup toolchain install stable --profile minimal - name: Cache cargo uses: Swatinem/rust-cache@v2 with: cache-all-crates: true prefix-key: v1-rust-gnu # Restore the build job's cache; never save over it. Two jobs # writing the same key race, and clippy is check-mode rmeta. save-if: false - name: Clippy run: cargo clippy --all-targets --locked -- -D warnings # Fires the moment Clippy concludes red and cancels the run, killing the # in-flight Build-and-test instead of letting it burn up to 90 minutes on # a run whose outcome is already decided. Skipped on a green Clippy and on # workflow_dispatch (Clippy itself is skipped there, which is not a # failure). Needs `actions: write` to cancel the run. clippy-guard: name: Cancel run on Clippy failure needs: clippy if: failure() runs-on: ubuntu-24.04 permissions: actions: write steps: - name: Cancel the run env: GH_TOKEN: ${{ github.token }} run: gh api -X POST "/repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID/cancel" build: name: Build and test # Pushes always build (and, by default, test). A manual redeploy reuses # the newest green artifact instead of paying the suite again, unless the # dispatch asks for `tests: force`, which builds and tests this ref. if: github.event_name == 'push' || github.event.inputs.tests == 'force' concurrency: group: ci-${{ github.workflow }}-${{ github.ref }}-build cancel-in-progress: true # Pinned, not `latest`: the gnu build links the runner's glibc and the # runtime image is debian:trixie-slim — float either side carelessly # and the binary stops loading. See the TARGET comment above. runs-on: ubuntu-24.04 # GitHub's default job timeout is 360 minutes, and this job holds the # repo's serial deploy lock (every later push queues behind it), so a # stall burned six hours per run (observed: 3h38m on 35251780342 and # 35256696519, both cancelled by hand). 90 is measured, not guessed: # the *fastest* green Build-and-test was 49m13s (run 35227878489, # 13:34:06→14:23:19 — its Test step alone 41m18s), but three other # green runs took 66-68 min (35184706020 68m14s, 35103425693 66m32s, # 35184706020's Test step 60m25s), so 50-60 would kill legitimate # green runs. 90 keeps ~30% headroom over the worst green while # cutting lock-held stall time from 6h to 1.5h. timeout-minutes: 90 env: # The 41 test binaries each link the full tonic/otlp/axum/sqlx stack; # with debug info they blow past the runner's free disk and the # linker dies with SIGBUS (run 34736185339). The only cost of # dropping it is line-number backtraces. CARGO_PROFILE_TEST_DEBUG: "0" CARGO_PROFILE_DEV_DEBUG: "0" # A one-shot CI build never reuses incremental artifacts — they are # pure disk waste. CARGO_INCREMENTAL: "0" steps: # The runner's preinstalled SDKs (~20GB of Android/.NET/ghc/CodeQL) # are dead weight here, and the suite needs the room (see the env # block above for the other half of the fix). - name: Free disk space run: | df -h / sudo rm -rf /usr/local/lib/android /usr/share/dotnet /opt/ghc /opt/hostedtoolcache/CodeQL sudo docker image prune -af >/dev/null || true df -h / - name: Checkout uses: actions/checkout@v4 - name: Set up Rust run: rustup toolchain install stable --profile minimal - name: Cache cargo uses: Swatinem/rust-cache@v2 with: cache-all-crates: true # Bump when the target, the profile or any rustflags change: the # key does not otherwise see those, and a run that restores the # old key reports it up-to-date at save time — discarding the # recompiled dependencies and silently recompiling them on every # later run. prefix-key: v1-rust-gnu # ── Which test path this run takes ────────────────────────────────── # SPECIAL: a commit carrying a self-consistent `Local-Gate:` trailer was # already through the suite on the developer's machine # (scripts/gate-local.sh prints it; --amend appends it), so this run # only packs and deploys. # Verified, never trusted: the trailer's tree must equal HEAD^{tree}, so # a stale or copy-pasted trailer silently falls back to running the # suite. The log always says which branch was taken, and why. # Trailer shape: `Local-Gate: <40-hex tree> ( passed, s)`. - name: Decide test gate id: gate run: | set -euo pipefail # Only reaches here on a push, or a dispatch with tests=force (the # job-level `if` skips the other dispatch modes) — and force means # the caller explicitly asked for the suite. mode='${{ github.event.inputs.tests }}' tree=$(git rev-parse HEAD^{tree}) if [ "$mode" = force ]; then echo "workflow_dispatch tests=force ⇒ running the suite on this ref" echo "skip=false" >> "$GITHUB_OUTPUT" exit 0 fi claim=$(git log -1 --format=%B \ | sed -n 's/^Local-Gate: \([0-9a-f]\{40\}\) (\(.*\))$/\1|\2/p' \ | tail -1) if [ -z "$claim" ]; then echo "no Local-Gate trailer on $(git rev-parse --short HEAD) ⇒ running the suite (the default path)" echo "skip=false" >> "$GITHUB_OUTPUT" elif [ "${claim%%|*}" != "$tree" ]; then echo "local gate claims tree ${claim%%|*}; actual tree $tree ⇒ running tests anyway" echo "skip=false" >> "$GITHUB_OUTPUT" else echo "local gate trailer matches tree $tree ⇒ skipping the suite (${claim#*|})" echo "skip=true" >> "$GITHUB_OUTPUT" fi # The suite mints a control+school database pair per test; the default # 100-connection ceiling runs out under that, so the server gets the # same 500 the compose stack runs (see compose.yaml). - name: Start Postgres if: steps.gate.outputs.skip != 'true' run: | docker run -d --name hezarfen_backend_pg \ -e POSTGRES_USER="$PG_USER" -e POSTGRES_PASSWORD="$PG_PASSWORD" \ -p 127.0.0.1:5432:5432 \ postgres:18-alpine -c max_connections=500 for _ in $(seq 1 30); do docker exec hezarfen_backend_pg pg_isready -U "$PG_USER" && break sleep 1 done docker exec hezarfen_backend_pg pg_isready -U "$PG_USER" - name: Install cargo-nextest if: steps.gate.outputs.skip != 'true' uses: taiki-e/install-action@v2 with: tool: cargo-nextest # The runner's state and the repo's hang policy, recorded BEFORE the # suite starts: if the job is killed mid-suite, this is what the log # still holds. `show-config` is nextest's documented door onto its # resolved configuration (0.9.143: `version` and `test-groups`); it # reads the config file for real — a missing or syntactically broken # .config/nextest.toml exits 96 here (verified locally), and a key # nextest does not know is warned about by name — so a silently # ignored slow-timeout cannot hide. - name: Test environment if: steps.gate.outputs.skip != 'true' run: | df -h / free -m nproc cargo nextest --version cat .config/nextest.toml cargo nextest show-config test-groups --no-pager || true # A broken build must never reach the server: the whole suite gates # the deploy (doc_sync included, so README drift blocks it too). # --no-fail-fast: one load-luck assert must not skip the other 1000 tests. # --config-file: pin the hang policy to the repo file explicitly, so a # nextest release that moves the default lookup cannot silently drop it. # `timeout --foreground 4200` (70 min) bounds the step at the shell # level, unbuffered and unpiped: output up to the kill survives, and a # stall exits 124 naming the phase instead of running to the job's # 90-minute ceiling. 4200s because CI's Test step has run 41m18s # (green, 35227878489) and 60m25s (green, 35184706020) — local 565s is # not the yardstick — so 70 min clears the worst green by ~10 min and # still sits below the 90-minute job timeout. - name: Test if: steps.gate.outputs.skip != 'true' run: | set -euo pipefail timeout --foreground 4200 \ cargo nextest run --no-fail-fast --config-file .config/nextest.toml # Always *within the test path*, including when the step above was # killed: the discriminator. If the stall is a DB-side wait (the suite # mints and clones control+school databases per test), this names the # query and the state; if it is disk or memory, df/free show it; # docker's own log shows a crashed or refusing Postgres. Skipped when # the local gate already proved the suite — there is no container then. - name: Stall diagnostics if: always() && steps.gate.outputs.skip != 'true' run: | echo '=== df -h / ==='; df -h / || true echo '=== free -m ==='; free -m || true echo '=== docker system df ==='; docker system df || true echo '=== postgres container log (tail 80) ==='; docker logs hezarfen_backend_pg --tail 80 || true echo '=== pg_stat_activity by state ==='; docker exec hezarfen_backend_pg psql -U "$PG_USER" -c 'select count(*), state from pg_stat_activity group by state' || true echo '=== 20 longest-running queries ==='; docker exec hezarfen_backend_pg psql -U "$PG_USER" -c "select pid, now()-query_start as age, left(query,120) from pg_stat_activity where state='active' order by 2 desc limit 20" || true - name: Build the release run: | set -euo pipefail cargo build --release --locked --target "$TARGET" mkdir -p stage cp "target/$TARGET/release/hezarfen_backend" stage/hezarfen_backend # The migrators resolve `migrations/` beside the binary when the # compile-time checkout path is absent (see migrations_path), so # the schema ships inside the image, next to /app/hezarfen_backend. cp -r migrations stage/migrations strip stage/hezarfen_backend ls -l stage - name: Build the runtime image run: | set -euo pipefail # Pack the already-built, already-stripped gnu binary into the # runtime image. Never build from source here: a second rust # compile blows the runner's disk. docker build -f deploy/Containerfile.runtime -t localhost/hezarfen_backend:$GITHUB_SHA stage/ docker save localhost/hezarfen_backend:$GITHUB_SHA | gzip > stage/hezarfen_backend.tar.gz - name: Stage the compose bundle run: | set -euo pipefail cp compose.yaml deploy/hezarfen_backend_compose.service deploy/backup-postgres.sh stage/ echo -n "$GITHUB_SHA" > stage/tag # Everything the deploy installs on the server must be here; a # missing piece fails here, on the runner, not mid-deploy on the # VPS. The raw binary and migrations may linger as docker build # context — they are no longer load-bearing. test -f stage/hezarfen_backend.tar.gz test -f stage/compose.yaml test -f stage/hezarfen_backend_compose.service test -f stage/backup-postgres.sh test -f stage/tag ls -l stage # The deploy job (and, later, a manual redeploy) consumes this. 30 # days is also the dispatch door's reach-back window: an older green # build's artifact is gone, and the redeploy fails loudly instead of # silently shipping something ancient. - name: Upload the release uses: actions/upload-artifact@v4 with: name: release path: stage retention-days: 30 deploy: name: Deploy needs: [clippy, build] concurrency: group: deploy cancel-in-progress: false # Push: only behind green clippy AND a green build — both gate the server. # Dispatch: clippy/build are skipped unless tests=force, and `always()` is # what stops that skip from cascading past this gate; a skipped job is # accepted only there, and a failure anywhere still blocks. if: >- always() && (needs.clippy.result == 'success' || needs.clippy.result == 'skipped') && (needs.build.result == 'success' || needs.build.result == 'skipped') runs-on: ubuntu-24.04 steps: # The release this very run built and gated: a push always; a dispatch # with tests=force too. A dispatch that reused the newest green build # has no build job at all, hence the `skipped` branch below. - name: Fetch this run's release if: needs.build.result == 'success' uses: actions/download-artifact@v4 with: name: release path: stage # A manual redeploy takes the newest release whose BUILD job went # green — not the newest fully-green run: a run can be red because # Deploy failed at the health gate while its build is exactly the # release we want back on the server. `gh run list --status success` # would skip exactly those, hence the per-run job check. - name: Find the newest green build if: needs.build.result == 'skipped' env: GH_TOKEN: ${{ github.token }} run: | set -euo pipefail run_id="" for rid in $(gh run list --workflow main.yml --branch main --event push --limit 15 --json databaseId --jq '.[].databaseId'); do if [ "$(gh run view "$rid" --json jobs --jq '.jobs[] | select(.name=="Build and test") | .conclusion')" = "success" ]; then run_id=$rid break fi done if [ -z "$run_id" ]; then echo 'no run on main has a green Build-and-test job (or its artifact has expired)' >&2 exit 1 fi echo "redeploying the release from run $run_id" echo "run_id=$run_id" >> "$GITHUB_ENV" - name: Fetch the green release if: needs.build.result == 'skipped' uses: actions/download-artifact@v4 with: name: release path: stage run-id: ${{ env.run_id }} github-token: ${{ github.token }} # The dispatch path downloads a possibly-days-old artifact; re-check # the bundle is whole before pointing any of it at the server. - name: Check the release is complete run: | set -euo pipefail test -f stage/hezarfen_backend.tar.gz test -f stage/compose.yaml test -f stage/hezarfen_backend_compose.service test -f stage/backup-postgres.sh test -f stage/tag - name: Install SSH keys run: | mkdir -p ~/.ssh echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa && chmod 600 ~/.ssh/id_rsa ssh-keyscan -H ${{ secrets.SSH_HOST }} > ~/.ssh/known_hosts - name: Upload the release run: | set -euo pipefail ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}" # The server's login shell is not bash, and ssh would hand this # script to it; `bash -s` takes it on stdin instead, so the login # shell only ever parses one plain command. # # The deploy path is $DEPLOY_SUBDIR under the SSH user's home, # resolved on the server as $HOME: there is no path secret to go # stale, and switching the deploy user moves the deploy with it. ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR'" <<'REMOTE' set -euo pipefail case "$1" in ''|/*|*..*) echo "Refusing a broad deploy subdirectory: '$1'" >&2 exit 1 ;; esac deploy_path=$HOME/$1 # The deploy path holds the operator's hezarfen_backend.env, the # compose files and the tag files; nothing in it is deleted # wholesale, ever. mkdir -p -- "$deploy_path" REMOTE # stdin carries the bundle, so the script cannot; the extraction # still goes through bash -c because the login shell is not bash # and would not expand $HOME. Only the five deploy files ship — # the raw binary and migrations stay on the runner (they were # docker build context, nothing more). tar -C stage -czf - hezarfen_backend.tar.gz compose.yaml hezarfen_backend_compose.service backup-postgres.sh tag | ssh "$ssh_target" "bash -c 'exec tar -xzf - -C \"\$HOME/\$1\"' -- '$DEPLOY_SUBDIR'" - name: Load the image and restart the stack run: | set -euo pipefail ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}" # bash -s for the same reason as above: the login shell is not # bash and must never see this script. ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$SERVICE' '$ENV_FILE_NAME'" <<'REMOTE' set -euo pipefail deploy_path=$HOME/$1 service=$2 env_file=$deploy_path/$3 export XDG_RUNTIME_DIR=/run/user/$(id -u) # compose.yaml is resolved from the working directory: the unit's # ExecStart carries WorkingDirectory, but the rollback compose up # and a first-deploy down run from right here. cd -- "$deploy_path" # Read before anything moves: the env file is the operator's, on # the server, written once by hand (see # deploy/hezarfen_backend.env.example for the keys). The deploy # never creates or overwrites it. The password and OpenObserve lines # are load-bearing: without them compose would silently run the stack # on its laptop defaults. if [ ! -f "$env_file" ]; then echo "missing $env_file — create it (0600) from deploy/hezarfen_backend.env.example" >&2 exit 1 fi chmod 0600 -- "$env_file" for key in POSTGRES_PASSWORD BUILDER_PASSWORD ZO_ROOT_USER_EMAIL ZO_ROOT_USER_PASSWORD AI_SHARED_TOKEN AI_QUIC_ADDR; do grep -Eq "^${key}=.+" "$env_file" || { echo "no non-empty ${key}= line in $env_file — prod must not run on the compose defaults" >&2 exit 1 } done # OPERATOR ORTAMI SURECE ALINIR. podman-compose interpolasyonu ORTAM # DEGISKENLERINE bakar ve `--env-file` YALNIZ SON dosyayi cozer # (podman_compose.py:2941-2946, :2559): iki dosyali cagri operator # dosyasini tamamen dusurur ve stack SESSIZCE compose # varsayilanlariyla kosar (DATABASE_URL parolasi `hezarfen`, kopru # tokeni `change-me`) — yukaridaki "bos olamaz" kapisi bunu # yakalamaz, cunku o dosyayi denetler, compose'un onu kullanip # kullanmadigini degil (canlida yasandi, 2026-09-17). Bu yuzden # dosya satir satir okunur: kabuk genisletmesi YOK (deger icindeki # `$` oldugu gibi kalir), bicim duz KEY=value oldugu icin # tirnak/`export` aranmaz. while IFS= read -r satir || [ -n "$satir" ]; do case "$satir" in ''|'#'*) continue ;; esac anahtar=${satir%%=*} deger=${satir#*=} case "$anahtar" in ''|*[!A-Za-z0-9_]*) echo "operator env: gecersiz anahtar adi -- harf/rakam/alt cizgi beklenirdi" >&2 exit 1 ;; esac export "$anahtar=$deger" done < "$env_file" # Rootless podman plus a compose provider; fail with the fix, not # a bare command-not-found three steps in. command -v podman >/dev/null || { echo "podman not found — install podman and a compose provider (e.g. dnf install podman podman-compose)" >&2 exit 1 } podman compose version >/dev/null 2>&1 || { echo "'podman compose' unavailable — install a compose provider (podman-compose or docker-compose)" >&2 exit 1 } # Load THIS build's image and read the tag the build stamped into # it (build time and deploy time must agree on what is shipping). gunzip -c "$deploy_path/hezarfen_backend.tar.gz" | podman load tag=$(cat -- "$deploy_path/tag") # Tag rotation: previous_tag is the rollback target (absent on a # first deploy); current_tag records what should now be running. if [ -f "$deploy_path/current_tag" ]; then cp -- "$deploy_path/current_tag" "$deploy_path/previous_tag" fi printf '%s\n' "$tag" > "$deploy_path/current_tag" # stack.env is deploy-owned (unlike the secrets file): it carries # only the image tag, and it is the ONE `--env-file` compose gets — # the operator's values are in the process environment (above). A # two-file call would drop the operator file entirely # (podman_compose.py:2941-2946, :2559). printf 'HEZARFEN_TAG=%s\n' "$tag" > "$deploy_path/stack.env" # The freshly extracted bundle: compose file and unit are # world-readable, the backup script is run by hand or a timer. chmod 0644 -- "$deploy_path/compose.yaml" "$deploy_path/hezarfen_backend_compose.service" chmod 0755 -- "$deploy_path/backup-postgres.sh" # The image tarball was only a transport; the image is loaded into # podman's storage now. rm -f -- "$deploy_path/hezarfen_backend.tar.gz" compose_up() { podman compose --env-file "$deploy_path/stack.env" up -d --no-build } rollback() { if [ -f "$deploy_path/previous_tag" ]; then prev=$(cat -- "$deploy_path/previous_tag") printf 'HEZARFEN_TAG=%s\n' "$prev" > "$deploy_path/stack.env" printf '%s\n' "$prev" > "$deploy_path/current_tag" compose_up echo "rolled back to $prev" >&2 else # First deploy: nothing to roll back to, so stop the # half-brought-up stack. Plain down — the volumes hold the # operator's data and postgres's first-boot password. podman compose --env-file "$deploy_path/stack.env" down echo 'first deploy failed; stack stopped, volumes kept' >&2 fi } # The unit ships with the release: a freshly provisioned box has # no unit until the first deploy writes it, and a changed unit # lands with the compose file that needs it. mkdir -p -- "$HOME/.config/systemd/user" install -m 0644 -- "$deploy_path/hezarfen_backend_compose.service" "$HOME/.config/systemd/user/$service.service" systemctl --user daemon-reload # Retire leftover units: the binary-era hezarfen.service and the # hyphenated hezarfen-compose.service from the first compose cut. systemctl --user disable --now hezarfen.service 2>/dev/null || true; rm -f -- "$HOME/.config/systemd/user/hezarfen.service" systemctl --user disable --now hezarfen-compose.service 2>/dev/null || true; rm -f -- "$HOME/.config/systemd/user/hezarfen-compose.service" # The unit is a oneshot with RemainAfterExit, so `start` on the # active (exited) unit would be a no-op — every deploy restarts # to re-run ExecStart. A failed restart (bad interpolation, a # provider hiccup) must still reach the health gate below: it # decides between rollback and success. systemctl --user enable -- "$service" systemctl --user restart "$service" || true # The oneshot returns before the containers have bound their # ports. Wait for the health route rather than a clock: /health # answers 503 (curl -f fails) while the database is unreachable, # so a 200 whose body says "status":"ok" means the new stack is # truly serving. 90 attempts, not 30: a first deploy also pulls # the postgres and observability base images. health_ok=0 for _ in $(seq 1 90); do served=$(curl -fsS http://127.0.0.1:7656/health 2>/dev/null) || true case "$served" in *'"status":"ok"'*) health_ok=1; break ;; esac sleep 1 done if [ "$health_ok" -ne 1 ]; then echo '/health never said "status":"ok"; rolling back' >&2 rollback exit 1 fi # A stale stack from an older deploy can answer too, so the # running container must be THIS build's image, or it rolls back. image=$(podman inspect -f '{{.Config.Image}}' hezarfen_backend) case "$image" in *"$tag"*) ;; *) echo "/health answered, but the container runs '$image' — not this build ($tag); rolling back" >&2 rollback exit 1 ;; esac # ARE THE OPERATOR SECRETS IN THE CONTAINER? Without this claim the # two-file `--env-file` class can silently come back: the stack comes # up on the compose defaults and nothing turns red. The strongest # form: the VALUE in the container's environment must equal the VALUE # in the operator file byte for byte. No value is ever printed. container=hezarfen_backend container_env=$(podman inspect -f '{{range .Config.Env}}{{println .}}{{end}}' "$container") for cift in "AI_SHARED_TOKEN=$AI_SHARED_TOKEN" "POSTGRES_PASSWORD=$POSTGRES_PASSWORD" "AI_QUIC_ADDR=$AI_QUIC_ADDR" "BUILDER_USERNAME=$BUILDER_USERNAME"; do ad=${cift%%=*} case "$container_env" in *"$cift"*) ;; *) echo "container env: $ad does not carry the operator value -- the operator env never reached compose; rolling back" >&2 rollback exit 1 ;; esac done echo 'ok: the operator secrets are in the container (AI_SHARED_TOKEN / POSTGRES_PASSWORD / AI_QUIC_ADDR / BUILDER_USERNAME byte for byte)' echo 'hezarfen_backend_compose is up' REMOTE # The independent after-the-fact check: the container answering must # still be the current tag's, and the validation contract must be # served. - name: Verify the served API run: | set -euo pipefail ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}" # One remote script, im-style: mixing runner-side and server-side # variables in nested ssh quoting once shipped a check that failed # on a healthy deploy. Everything happens inside the heredoc. ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR'" <<'REMOTE' set -euo pipefail deploy_path=$HOME/$1 export XDG_RUNTIME_DIR=/run/user/$(id -u) cd -- "$deploy_path" tag=$(cat -- "$deploy_path/current_tag") image=$(podman inspect -f '{{.Config.Image}}' hezarfen_backend) case "$image" in *"$tag"*) ;; *) echo "container runs '$image', not the current tag '$tag'" >&2 exit 1 ;; esac served=$(curl -fsS http://127.0.0.1:7656/health) || { echo '/health failed' >&2; exit 1; } case "$served" in *'"status":"ok"'*) ;; *) echo '/health did not report "status":"ok"' >&2; exit 1 ;; esac curl -fsS -o /dev/null http://127.0.0.1:7656/limits echo 'health ok, limits served' REMOTE - name: Cleaning run: rm -rf ~/.ssh