forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

main.yml722 lines, 34.4 KiBHistoryRawDownload
1# VPS deploy, compose-style, split so failure recovery is cheap:
2#
3# Clippy — -D warnings on --all-targets, own runner. No Postgres.
4# Build and test — Postgres sidecar, the whole suite, the release
5# build; packs the stripped binary + migrations into the
6# runtime image (deploy/Containerfile.runtime) and
7# uploads the image tarball + compose files as the run's
8# artifact.
9# Deploy — SSH: podman load the image, point the deploy-owned
10# stack.env's HEZARFEN_TAG at it, install compose.yaml +
11# the hezarfen_backend_compose user unit + the backup script,
12# restart the stack, /health-gated rollback to the
13# previous tag, independent after-the-fact verify.
14#
15# Two test paths, the default being the full one:
16# DEFAULT GitHub does everything: the suite runs on the runner, then the
17# build, the pack and the deploy.
18# SPECIAL Run the full suite on your own machine first
19# (scripts/gate-local.sh — 565s there vs ~55min on a 4-core
20# runner). It prints (or, with --amend, appends) a
21# `Local-Gate: <tree> (<n> passed, <t>s)` trailer; commit it and
22# GitHub only packs and deploys. The "Decide test gate" step
23# verifies the trailer against HEAD^{tree} before honouring it —
24# a stale or copy-pasted trailer silently falls back to running
25# the suite.
26#
27# Clippy and Build and test run in parallel. Deploy needs both green.
28# A new push cancels in-flight Clippy/Build on the same ref; it never
29# cancels an in-flight Deploy (two deploys racing would interleave the
30# compose stack).
31#
32# Fail-fast: Clippy is ~2 minutes, Build-and-test up to 90. A red Clippy
33# still leaves the suite burning runner minutes for nothing — the deploy
34# already gates on both, so the outcome is decided. The `clippy-guard`
35# job fires the moment Clippy concludes red and cancels the whole run,
36# killing the in-flight suite. Parallelism is untouched: the guard only
37# ever runs on the failure path. (GitHub has no native "sibling job
38# failed → cancel the rest"; the run-cancel API is the door.)
39#
40# The split is the recovery story, not ceremony:
41# * "Re-run failed jobs" on a run whose Deploy step failed re-runs ONLY the
42# ~1-minute deploy job — the built image is still in the run's artifact.
43# * workflow_dispatch (the manual door: Actions tab → Run workflow on main,
44# or `gh workflow run main.yml --ref main`) deploys WITHOUT the suite by
45# default: it takes the newest artifact a green Build-and-test produced —
46# which can lag HEAD while a push is mid-CI, and that is the point:
47# redeploy the known-good image, e.g. after a server-side fix (env file,
48# proxy, database). Its `tests` input overrides that: `force` runs the
49# whole build job, suite included, on the dispatched ref and deploys that
50# fresh artifact; `skip` (and `auto`) take the newest green one. For
51# env-only changes a plain
52# `ssh <vps> 'systemctl --user restart hezarfen_backend_compose'` needs no
53# workflow at all: the stack re-reads its env files on the next
54# `podman compose up`.
55#
56# One-time prerequisites, outside the workflow's reach:
57# * the repo secrets SSH_PRIVATE_KEY / SSH_HOST / SSH_USER;
58# * `loginctl enable-linger <user>` on the server unless the deploy user
59# already has it — user units need a running user manager;
60# * podman plus a compose provider on the server (the deploy checks for
61# both and fails with a one-line install hint);
62# * the operator's ~/hezarfen_backend/hezarfen_backend.env (0600), written
63# once by hand from deploy/hezarfen_backend.env.example — at minimum the
64# POSTGRES_PASSWORD and BUILDER_PASSWORD lines. The deploy never
65# creates or overwrites it.
66
67name: VPS deploy
68
69on:
70 push:
71 branches:
72 - main
73 # The manual redeploy door — see the header comment for how and why.
74 workflow_dispatch:
75 inputs:
76 tests:
77 description: "Run the test suite on this run? auto/skip redeploy the newest green artifact; force builds and tests the dispatched ref first."
78 type: choice
79 options:
80 - auto
81 - skip
82 - force
83 default: auto
84
85# Deploy serialisation lives on the deploy job, not the workflow: a new
86# push must be allowed to cancel stale Clippy/Build without touching an
87# in-flight VPS swap.
88
89
90env:
91 # A gnu binary links against the toolchain's glibc, so the runner is
92 # pinned (see runs-on below) to 24.04, and the runtime image is
93 # debian:trixie-slim: move either side without thinking and the binary
94 # stops loading inside the container. The pin is what forces a conscious
95 # decision rather than a broken deploy. In exchange: no cross-toolchain,
96 # and the linker is rustc's default bundled lld.
97 TARGET: x86_64-unknown-linux-gnu
98 # The systemd user unit that wraps `podman compose`. See
99 # deploy/hezarfen_backend_compose.service.
100 SERVICE: hezarfen_backend_compose
101 # The deploy lives in this subdirectory of the SSH user's home. The home
102 # itself is resolved on the server ($HOME), so switching the deploy user
103 # moves the path with it — a baked-in absolute path once kept pointing at
104 # the previous user's home and failed the deploy on permissions.
105 DEPLOY_SUBDIR: hezarfen_backend
106 # Compose interpolates its secrets from this file on the server (passed
107 # as --env-file, and to the backend container as env_file). The deploy
108 # never writes it, only checks it exists and carries the
109 # POSTGRES_PASSWORD / BUILDER_PASSWORD lines prod must not run without.
110 ENV_FILE_NAME: hezarfen_backend.env
111 # The Postgres the test suite mints its per-test databases on. Credentials
112 # and port match the harness default (HEZARFEN_TEST_DATABASE_URL), so the
113 # tests need no extra environment — only the server, with the raised
114 # connection ceiling the parallel suite exhausts (see compose.yaml).
115 PG_USER: hezarfen
116 PG_PASSWORD: hezarfen
117 # sqlx's compile-time macros verify every query against the committed .sqlx
118 # cache, so the build must never reach for a live database (same as the
119 # Containerfile).
120 SQLX_OFFLINE: "true"
121
122jobs:
123 clippy:
124 name: Clippy
125 if: github.event_name == 'push'
126 runs-on: ubuntu-24.04
127 concurrency:
128 group: ci-${{ github.workflow }}-${{ github.ref }}-clippy
129 cancel-in-progress: true
130 env:
131 CARGO_INCREMENTAL: "0"
132 steps:
133 - name: Checkout
134 uses: actions/checkout@v4
135 - name: Set up Rust
136 run: rustup toolchain install stable --profile minimal
137 - name: Cache cargo
138 uses: Swatinem/rust-cache@v2
139 with:
140 cache-all-crates: true
141 prefix-key: v1-rust-gnu
142 # Restore the build job's cache; never save over it. Two jobs
143 # writing the same key race, and clippy is check-mode rmeta.
144 save-if: false
145 - name: Clippy
146 run: cargo clippy --all-targets --locked -- -D warnings
147
148 # Fires the moment Clippy concludes red and cancels the run, killing the
149 # in-flight Build-and-test instead of letting it burn up to 90 minutes on
150 # a run whose outcome is already decided. Skipped on a green Clippy and on
151 # workflow_dispatch (Clippy itself is skipped there, which is not a
152 # failure). Needs `actions: write` to cancel the run.
153 clippy-guard:
154 name: Cancel run on Clippy failure
155 needs: clippy
156 if: failure()
157 runs-on: ubuntu-24.04
158 permissions:
159 actions: write
160 steps:
161 - name: Cancel the run
162 env:
163 GH_TOKEN: ${{ github.token }}
164 run: gh api -X POST "/repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID/cancel"
165
166 build:
167 name: Build and test
168 # Pushes always build (and, by default, test). A manual redeploy reuses
169 # the newest green artifact instead of paying the suite again, unless the
170 # dispatch asks for `tests: force`, which builds and tests this ref.
171 if: github.event_name == 'push' || github.event.inputs.tests == 'force'
172 concurrency:
173 group: ci-${{ github.workflow }}-${{ github.ref }}-build
174 cancel-in-progress: true
175 # Pinned, not `latest`: the gnu build links the runner's glibc and the
176 # runtime image is debian:trixie-slim — float either side carelessly
177 # and the binary stops loading. See the TARGET comment above.
178 runs-on: ubuntu-24.04
179 # GitHub's default job timeout is 360 minutes, and this job holds the
180 # repo's serial deploy lock (every later push queues behind it), so a
181 # stall burned six hours per run (observed: 3h38m on 35251780342 and
182 # 35256696519, both cancelled by hand). 90 is measured, not guessed:
183 # the *fastest* green Build-and-test was 49m13s (run 35227878489,
184 # 13:34:06→14:23:19 — its Test step alone 41m18s), but three other
185 # green runs took 66-68 min (35184706020 68m14s, 35103425693 66m32s,
186 # 35184706020's Test step 60m25s), so 50-60 would kill legitimate
187 # green runs. 90 keeps ~30% headroom over the worst green while
188 # cutting lock-held stall time from 6h to 1.5h.
189 timeout-minutes: 90
190 env:
191 # The 41 test binaries each link the full tonic/otlp/axum/sqlx stack;
192 # with debug info they blow past the runner's free disk and the
193 # linker dies with SIGBUS (run 34736185339). The only cost of
194 # dropping it is line-number backtraces.
195 CARGO_PROFILE_TEST_DEBUG: "0"
196 CARGO_PROFILE_DEV_DEBUG: "0"
197 # A one-shot CI build never reuses incremental artifacts — they are
198 # pure disk waste.
199 CARGO_INCREMENTAL: "0"
200 steps:
201 # The runner's preinstalled SDKs (~20GB of Android/.NET/ghc/CodeQL)
202 # are dead weight here, and the suite needs the room (see the env
203 # block above for the other half of the fix).
204 - name: Free disk space
205 run: |
206 df -h /
207 sudo rm -rf /usr/local/lib/android /usr/share/dotnet /opt/ghc /opt/hostedtoolcache/CodeQL
208 sudo docker image prune -af >/dev/null || true
209 df -h /
210
211 - name: Checkout
212 uses: actions/checkout@v4
213 - name: Set up Rust
214 run: rustup toolchain install stable --profile minimal
215
216 - name: Cache cargo
217 uses: Swatinem/rust-cache@v2
218 with:
219 cache-all-crates: true
220 # Bump when the target, the profile or any rustflags change: the
221 # key does not otherwise see those, and a run that restores the
222 # old key reports it up-to-date at save time — discarding the
223 # recompiled dependencies and silently recompiling them on every
224 # later run.
225 prefix-key: v1-rust-gnu
226
227 # ── Which test path this run takes ──────────────────────────────────
228 # SPECIAL: a commit carrying a self-consistent `Local-Gate:` trailer was
229 # already through the suite on the developer's machine
230 # (scripts/gate-local.sh prints it; --amend appends it), so this run
231 # only packs and deploys.
232 # Verified, never trusted: the trailer's tree must equal HEAD^{tree}, so
233 # a stale or copy-pasted trailer silently falls back to running the
234 # suite. The log always says which branch was taken, and why.
235 # Trailer shape: `Local-Gate: <40-hex tree> (<n> passed, <t>s)`.
236 - name: Decide test gate
237 id: gate
238 run: |
239 set -euo pipefail
240 # Only reaches here on a push, or a dispatch with tests=force (the
241 # job-level `if` skips the other dispatch modes) — and force means
242 # the caller explicitly asked for the suite.
243 mode='${{ github.event.inputs.tests }}'
244 tree=$(git rev-parse HEAD^{tree})
245 if [ "$mode" = force ]; then
246 echo "workflow_dispatch tests=force ⇒ running the suite on this ref"
247 echo "skip=false" >> "$GITHUB_OUTPUT"
248 exit 0
249 fi
250 claim=$(git log -1 --format=%B \
251 | sed -n 's/^Local-Gate: \([0-9a-f]\{40\}\) (\(.*\))$/\1|\2/p' \
252 | tail -1)
253 if [ -z "$claim" ]; then
254 echo "no Local-Gate trailer on $(git rev-parse --short HEAD) ⇒ running the suite (the default path)"
255 echo "skip=false" >> "$GITHUB_OUTPUT"
256 elif [ "${claim%%|*}" != "$tree" ]; then
257 echo "local gate claims tree ${claim%%|*}; actual tree $tree ⇒ running tests anyway"
258 echo "skip=false" >> "$GITHUB_OUTPUT"
259 else
260 echo "local gate trailer matches tree $tree ⇒ skipping the suite (${claim#*|})"
261 echo "skip=true" >> "$GITHUB_OUTPUT"
262 fi
263
264 # The suite mints a control+school database pair per test; the default
265 # 100-connection ceiling runs out under that, so the server gets the
266 # same 500 the compose stack runs (see compose.yaml).
267 - name: Start Postgres
268 if: steps.gate.outputs.skip != 'true'
269 run: |
270 docker run -d --name hezarfen_backend_pg \
271 -e POSTGRES_USER="$PG_USER" -e POSTGRES_PASSWORD="$PG_PASSWORD" \
272 -p 127.0.0.1:5432:5432 \
273 postgres:18-alpine -c max_connections=500
274 for _ in $(seq 1 30); do
275 docker exec hezarfen_backend_pg pg_isready -U "$PG_USER" && break
276 sleep 1
277 done
278 docker exec hezarfen_backend_pg pg_isready -U "$PG_USER"
279
280 - name: Install cargo-nextest
281 if: steps.gate.outputs.skip != 'true'
282 uses: taiki-e/install-action@v2
283 with:
284 tool: cargo-nextest
285
286 # The runner's state and the repo's hang policy, recorded BEFORE the
287 # suite starts: if the job is killed mid-suite, this is what the log
288 # still holds. `show-config` is nextest's documented door onto its
289 # resolved configuration (0.9.143: `version` and `test-groups`); it
290 # reads the config file for real — a missing or syntactically broken
291 # .config/nextest.toml exits 96 here (verified locally), and a key
292 # nextest does not know is warned about by name — so a silently
293 # ignored slow-timeout cannot hide.
294 - name: Test environment
295 if: steps.gate.outputs.skip != 'true'
296 run: |
297 df -h /
298 free -m
299 nproc
300 cargo nextest --version
301 cat .config/nextest.toml
302 cargo nextest show-config test-groups --no-pager || true
303
304 # A broken build must never reach the server: the whole suite gates
305 # the deploy (doc_sync included, so README drift blocks it too).
306 # --no-fail-fast: one load-luck assert must not skip the other 1000 tests.
307 # --config-file: pin the hang policy to the repo file explicitly, so a
308 # nextest release that moves the default lookup cannot silently drop it.
309 # `timeout --foreground 4200` (70 min) bounds the step at the shell
310 # level, unbuffered and unpiped: output up to the kill survives, and a
311 # stall exits 124 naming the phase instead of running to the job's
312 # 90-minute ceiling. 4200s because CI's Test step has run 41m18s
313 # (green, 35227878489) and 60m25s (green, 35184706020) — local 565s is
314 # not the yardstick — so 70 min clears the worst green by ~10 min and
315 # still sits below the 90-minute job timeout.
316 - name: Test
317 if: steps.gate.outputs.skip != 'true'
318 run: |
319 set -euo pipefail
320 timeout --foreground 4200 \
321 cargo nextest run --no-fail-fast --config-file .config/nextest.toml
322
323 # Always *within the test path*, including when the step above was
324 # killed: the discriminator. If the stall is a DB-side wait (the suite
325 # mints and clones control+school databases per test), this names the
326 # query and the state; if it is disk or memory, df/free show it;
327 # docker's own log shows a crashed or refusing Postgres. Skipped when
328 # the local gate already proved the suite — there is no container then.
329 - name: Stall diagnostics
330 if: always() && steps.gate.outputs.skip != 'true'
331 run: |
332 echo '=== df -h / ==='; df -h / || true
333 echo '=== free -m ==='; free -m || true
334 echo '=== docker system df ==='; docker system df || true
335 echo '=== postgres container log (tail 80) ==='; docker logs hezarfen_backend_pg --tail 80 || true
336 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
337 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
338
339
340 - name: Build the release
341 run: |
342 set -euo pipefail
343 cargo build --release --locked --target "$TARGET"
344 mkdir -p stage
345 cp "target/$TARGET/release/hezarfen_backend" stage/hezarfen_backend
346 # The migrators resolve `migrations/` beside the binary when the
347 # compile-time checkout path is absent (see migrations_path), so
348 # the schema ships inside the image, next to /app/hezarfen_backend.
349 cp -r migrations stage/migrations
350 strip stage/hezarfen_backend
351 ls -l stage
352
353 - name: Build the runtime image
354 run: |
355 set -euo pipefail
356 # Pack the already-built, already-stripped gnu binary into the
357 # runtime image. Never build from source here: a second rust
358 # compile blows the runner's disk.
359 docker build -f deploy/Containerfile.runtime -t localhost/hezarfen_backend:$GITHUB_SHA stage/
360 docker save localhost/hezarfen_backend:$GITHUB_SHA | gzip > stage/hezarfen_backend.tar.gz
361
362 - name: Stage the compose bundle
363 run: |
364 set -euo pipefail
365 cp compose.yaml deploy/hezarfen_backend_compose.service deploy/backup-postgres.sh stage/
366 echo -n "$GITHUB_SHA" > stage/tag
367 # Everything the deploy installs on the server must be here; a
368 # missing piece fails here, on the runner, not mid-deploy on the
369 # VPS. The raw binary and migrations may linger as docker build
370 # context — they are no longer load-bearing.
371 test -f stage/hezarfen_backend.tar.gz
372 test -f stage/compose.yaml
373 test -f stage/hezarfen_backend_compose.service
374 test -f stage/backup-postgres.sh
375 test -f stage/tag
376 ls -l stage
377
378 # The deploy job (and, later, a manual redeploy) consumes this. 30
379 # days is also the dispatch door's reach-back window: an older green
380 # build's artifact is gone, and the redeploy fails loudly instead of
381 # silently shipping something ancient.
382 - name: Upload the release
383 uses: actions/upload-artifact@v4
384 with:
385 name: release
386 path: stage
387 retention-days: 30
388
389 deploy:
390 name: Deploy
391 needs: [clippy, build]
392 concurrency:
393 group: deploy
394 cancel-in-progress: false
395 # Push: only behind green clippy AND a green build — both gate the server.
396 # Dispatch: clippy/build are skipped unless tests=force, and `always()` is
397 # what stops that skip from cascading past this gate; a skipped job is
398 # accepted only there, and a failure anywhere still blocks.
399 if: >-
400 always() &&
401 (needs.clippy.result == 'success' || needs.clippy.result == 'skipped') &&
402 (needs.build.result == 'success' || needs.build.result == 'skipped')
403 runs-on: ubuntu-24.04
404 steps:
405 # The release this very run built and gated: a push always; a dispatch
406 # with tests=force too. A dispatch that reused the newest green build
407 # has no build job at all, hence the `skipped` branch below.
408 - name: Fetch this run's release
409 if: needs.build.result == 'success'
410 uses: actions/download-artifact@v4
411 with:
412 name: release
413 path: stage
414
415 # A manual redeploy takes the newest release whose BUILD job went
416 # green — not the newest fully-green run: a run can be red because
417 # Deploy failed at the health gate while its build is exactly the
418 # release we want back on the server. `gh run list --status success`
419 # would skip exactly those, hence the per-run job check.
420 - name: Find the newest green build
421 if: needs.build.result == 'skipped'
422 env:
423 GH_TOKEN: ${{ github.token }}
424 run: |
425 set -euo pipefail
426 run_id=""
427 for rid in $(gh run list --workflow main.yml --branch main --event push --limit 15 --json databaseId --jq '.[].databaseId'); do
428 if [ "$(gh run view "$rid" --json jobs --jq '.jobs[] | select(.name=="Build and test") | .conclusion')" = "success" ]; then
429 run_id=$rid
430 break
431 fi
432 done
433 if [ -z "$run_id" ]; then
434 echo 'no run on main has a green Build-and-test job (or its artifact has expired)' >&2
435 exit 1
436 fi
437 echo "redeploying the release from run $run_id"
438 echo "run_id=$run_id" >> "$GITHUB_ENV"
439
440 - name: Fetch the green release
441 if: needs.build.result == 'skipped'
442 uses: actions/download-artifact@v4
443 with:
444 name: release
445 path: stage
446 run-id: ${{ env.run_id }}
447 github-token: ${{ github.token }}
448
449 # The dispatch path downloads a possibly-days-old artifact; re-check
450 # the bundle is whole before pointing any of it at the server.
451 - name: Check the release is complete
452 run: |
453 set -euo pipefail
454 test -f stage/hezarfen_backend.tar.gz
455 test -f stage/compose.yaml
456 test -f stage/hezarfen_backend_compose.service
457 test -f stage/backup-postgres.sh
458 test -f stage/tag
459
460 - name: Install SSH keys
461 run: |
462 mkdir -p ~/.ssh
463 echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa && chmod 600 ~/.ssh/id_rsa
464 ssh-keyscan -H ${{ secrets.SSH_HOST }} > ~/.ssh/known_hosts
465
466 - name: Upload the release
467 run: |
468 set -euo pipefail
469 ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}"
470
471 # The server's login shell is not bash, and ssh would hand this
472 # script to it; `bash -s` takes it on stdin instead, so the login
473 # shell only ever parses one plain command.
474 #
475 # The deploy path is $DEPLOY_SUBDIR under the SSH user's home,
476 # resolved on the server as $HOME: there is no path secret to go
477 # stale, and switching the deploy user moves the deploy with it.
478 ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR'" <<'REMOTE'
479 set -euo pipefail
480 case "$1" in
481 ''|/*|*..*)
482 echo "Refusing a broad deploy subdirectory: '$1'" >&2
483 exit 1
484 ;;
485 esac
486 deploy_path=$HOME/$1
487 # The deploy path holds the operator's hezarfen_backend.env, the
488 # compose files and the tag files; nothing in it is deleted
489 # wholesale, ever.
490 mkdir -p -- "$deploy_path"
491 REMOTE
492 # stdin carries the bundle, so the script cannot; the extraction
493 # still goes through bash -c because the login shell is not bash
494 # and would not expand $HOME. Only the five deploy files ship —
495 # the raw binary and migrations stay on the runner (they were
496 # docker build context, nothing more).
497 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'"
498
499 - name: Load the image and restart the stack
500 run: |
501 set -euo pipefail
502 ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}"
503
504 # bash -s for the same reason as above: the login shell is not
505 # bash and must never see this script.
506 ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$SERVICE' '$ENV_FILE_NAME'" <<'REMOTE'
507 set -euo pipefail
508 deploy_path=$HOME/$1
509 service=$2
510 env_file=$deploy_path/$3
511 export XDG_RUNTIME_DIR=/run/user/$(id -u)
512 # compose.yaml is resolved from the working directory: the unit's
513 # ExecStart carries WorkingDirectory, but the rollback compose up
514 # and a first-deploy down run from right here.
515 cd -- "$deploy_path"
516
517 # Read before anything moves: the env file is the operator's, on
518 # the server, written once by hand (see
519 # deploy/hezarfen_backend.env.example for the keys). The deploy
520 # never creates or overwrites it. The password and OpenObserve lines
521 # are load-bearing: without them compose would silently run the stack
522 # on its laptop defaults.
523 if [ ! -f "$env_file" ]; then
524 echo "missing $env_file — create it (0600) from deploy/hezarfen_backend.env.example" >&2
525 exit 1
526 fi
527 chmod 0600 -- "$env_file"
528 for key in POSTGRES_PASSWORD BUILDER_PASSWORD ZO_ROOT_USER_EMAIL ZO_ROOT_USER_PASSWORD AI_SHARED_TOKEN AI_QUIC_ADDR; do
529 grep -Eq "^${key}=.+" "$env_file" || {
530 echo "no non-empty ${key}= line in $env_file — prod must not run on the compose defaults" >&2
531 exit 1
532 }
533 done
534
535 # OPERATOR ORTAMI SURECE ALINIR. podman-compose interpolasyonu ORTAM
536 # DEGISKENLERINE bakar ve `--env-file` YALNIZ SON dosyayi cozer
537 # (podman_compose.py:2941-2946, :2559): iki dosyali cagri operator
538 # dosyasini tamamen dusurur ve stack SESSIZCE compose
539 # varsayilanlariyla kosar (DATABASE_URL parolasi `hezarfen`, kopru
540 # tokeni `change-me`) — yukaridaki "bos olamaz" kapisi bunu
541 # yakalamaz, cunku o dosyayi denetler, compose'un onu kullanip
542 # kullanmadigini degil (canlida yasandi, 2026-09-17). Bu yuzden
543 # dosya satir satir okunur: kabuk genisletmesi YOK (deger icindeki
544 # `$` oldugu gibi kalir), bicim duz KEY=value oldugu icin
545 # tirnak/`export` aranmaz.
546 while IFS= read -r satir || [ -n "$satir" ]; do
547 case "$satir" in ''|'#'*) continue ;; esac
548 anahtar=${satir%%=*}
549 deger=${satir#*=}
550 case "$anahtar" in
551 ''|*[!A-Za-z0-9_]*)
552 echo "operator env: gecersiz anahtar adi -- harf/rakam/alt cizgi beklenirdi" >&2
553 exit 1
554 ;;
555 esac
556 export "$anahtar=$deger"
557 done < "$env_file"
558
559 # Rootless podman plus a compose provider; fail with the fix, not
560 # a bare command-not-found three steps in.
561 command -v podman >/dev/null || {
562 echo "podman not found — install podman and a compose provider (e.g. dnf install podman podman-compose)" >&2
563 exit 1
564 }
565 podman compose version >/dev/null 2>&1 || {
566 echo "'podman compose' unavailable — install a compose provider (podman-compose or docker-compose)" >&2
567 exit 1
568 }
569
570 # Load THIS build's image and read the tag the build stamped into
571 # it (build time and deploy time must agree on what is shipping).
572 gunzip -c "$deploy_path/hezarfen_backend.tar.gz" | podman load
573 tag=$(cat -- "$deploy_path/tag")
574
575 # Tag rotation: previous_tag is the rollback target (absent on a
576 # first deploy); current_tag records what should now be running.
577 if [ -f "$deploy_path/current_tag" ]; then
578 cp -- "$deploy_path/current_tag" "$deploy_path/previous_tag"
579 fi
580 printf '%s\n' "$tag" > "$deploy_path/current_tag"
581
582 # stack.env is deploy-owned (unlike the secrets file): it carries
583 # only the image tag, and it is the ONE `--env-file` compose gets —
584 # the operator's values are in the process environment (above). A
585 # two-file call would drop the operator file entirely
586 # (podman_compose.py:2941-2946, :2559).
587 printf 'HEZARFEN_TAG=%s\n' "$tag" > "$deploy_path/stack.env"
588
589 # The freshly extracted bundle: compose file and unit are
590 # world-readable, the backup script is run by hand or a timer.
591 chmod 0644 -- "$deploy_path/compose.yaml" "$deploy_path/hezarfen_backend_compose.service"
592 chmod 0755 -- "$deploy_path/backup-postgres.sh"
593 # The image tarball was only a transport; the image is loaded into
594 # podman's storage now.
595 rm -f -- "$deploy_path/hezarfen_backend.tar.gz"
596
597 compose_up() {
598 podman compose --env-file "$deploy_path/stack.env" up -d --no-build
599 }
600 rollback() {
601 if [ -f "$deploy_path/previous_tag" ]; then
602 prev=$(cat -- "$deploy_path/previous_tag")
603 printf 'HEZARFEN_TAG=%s\n' "$prev" > "$deploy_path/stack.env"
604 printf '%s\n' "$prev" > "$deploy_path/current_tag"
605 compose_up
606 echo "rolled back to $prev" >&2
607 else
608 # First deploy: nothing to roll back to, so stop the
609 # half-brought-up stack. Plain down — the volumes hold the
610 # operator's data and postgres's first-boot password.
611 podman compose --env-file "$deploy_path/stack.env" down
612 echo 'first deploy failed; stack stopped, volumes kept' >&2
613 fi
614 }
615
616 # The unit ships with the release: a freshly provisioned box has
617 # no unit until the first deploy writes it, and a changed unit
618 # lands with the compose file that needs it.
619 mkdir -p -- "$HOME/.config/systemd/user"
620 install -m 0644 -- "$deploy_path/hezarfen_backend_compose.service" "$HOME/.config/systemd/user/$service.service"
621 systemctl --user daemon-reload
622 # Retire leftover units: the binary-era hezarfen.service and the
623 # hyphenated hezarfen-compose.service from the first compose cut.
624 systemctl --user disable --now hezarfen.service 2>/dev/null || true; rm -f -- "$HOME/.config/systemd/user/hezarfen.service"
625 systemctl --user disable --now hezarfen-compose.service 2>/dev/null || true; rm -f -- "$HOME/.config/systemd/user/hezarfen-compose.service"
626
627 # The unit is a oneshot with RemainAfterExit, so `start` on the
628 # active (exited) unit would be a no-op — every deploy restarts
629 # to re-run ExecStart. A failed restart (bad interpolation, a
630 # provider hiccup) must still reach the health gate below: it
631 # decides between rollback and success.
632 systemctl --user enable -- "$service"
633 systemctl --user restart "$service" || true
634
635 # The oneshot returns before the containers have bound their
636 # ports. Wait for the health route rather than a clock: /health
637 # answers 503 (curl -f fails) while the database is unreachable,
638 # so a 200 whose body says "status":"ok" means the new stack is
639 # truly serving. 90 attempts, not 30: a first deploy also pulls
640 # the postgres and observability base images.
641 health_ok=0
642 for _ in $(seq 1 90); do
643 served=$(curl -fsS http://127.0.0.1:7656/health 2>/dev/null) || true
644 case "$served" in
645 *'"status":"ok"'*) health_ok=1; break ;;
646 esac
647 sleep 1
648 done
649 if [ "$health_ok" -ne 1 ]; then
650 echo '/health never said "status":"ok"; rolling back' >&2
651 rollback
652 exit 1
653 fi
654
655 # A stale stack from an older deploy can answer too, so the
656 # running container must be THIS build's image, or it rolls back.
657 image=$(podman inspect -f '{{.Config.Image}}' hezarfen_backend)
658 case "$image" in
659 *"$tag"*) ;;
660 *)
661 echo "/health answered, but the container runs '$image' — not this build ($tag); rolling back" >&2
662 rollback
663 exit 1
664 ;;
665 esac
666 # ARE THE OPERATOR SECRETS IN THE CONTAINER? Without this claim the
667 # two-file `--env-file` class can silently come back: the stack comes
668 # up on the compose defaults and nothing turns red. The strongest
669 # form: the VALUE in the container's environment must equal the VALUE
670 # in the operator file byte for byte. No value is ever printed.
671 container=hezarfen_backend
672 container_env=$(podman inspect -f '{{range .Config.Env}}{{println .}}{{end}}' "$container")
673 for cift in "AI_SHARED_TOKEN=$AI_SHARED_TOKEN" "POSTGRES_PASSWORD=$POSTGRES_PASSWORD" "AI_QUIC_ADDR=$AI_QUIC_ADDR" "BUILDER_USERNAME=$BUILDER_USERNAME"; do
674 ad=${cift%%=*}
675 case "$container_env" in
676 *"$cift"*) ;;
677 *)
678 echo "container env: $ad does not carry the operator value -- the operator env never reached compose; rolling back" >&2
679 rollback
680 exit 1
681 ;;
682 esac
683 done
684 echo 'ok: the operator secrets are in the container (AI_SHARED_TOKEN / POSTGRES_PASSWORD / AI_QUIC_ADDR / BUILDER_USERNAME byte for byte)'
685 echo 'hezarfen_backend_compose is up'
686 REMOTE
687
688 # The independent after-the-fact check: the container answering must
689 # still be the current tag's, and the validation contract must be
690 # served.
691 - name: Verify the served API
692 run: |
693 set -euo pipefail
694 ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}"
695 # One remote script, im-style: mixing runner-side and server-side
696 # variables in nested ssh quoting once shipped a check that failed
697 # on a healthy deploy. Everything happens inside the heredoc.
698 ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR'" <<'REMOTE'
699 set -euo pipefail
700 deploy_path=$HOME/$1
701 export XDG_RUNTIME_DIR=/run/user/$(id -u)
702 cd -- "$deploy_path"
703 tag=$(cat -- "$deploy_path/current_tag")
704 image=$(podman inspect -f '{{.Config.Image}}' hezarfen_backend)
705 case "$image" in
706 *"$tag"*) ;;
707 *)
708 echo "container runs '$image', not the current tag '$tag'" >&2
709 exit 1
710 ;;
711 esac
712 served=$(curl -fsS http://127.0.0.1:7656/health) || { echo '/health failed' >&2; exit 1; }
713 case "$served" in
714 *'"status":"ok"'*) ;;
715 *) echo '/health did not report "status":"ok"' >&2; exit 1 ;;
716 esac
717 curl -fsS -o /dev/null http://127.0.0.1:7656/limits
718 echo 'health ok, limits served'
719 REMOTE
720
721 - name: Cleaning
722 run: rm -rf ~/.ssh