forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits

main.yml487 lines, 21.5 KiBHistoryRawDownload
1# VPS deploy, compose-style, split so failure recovery is cheap:
2#
3# Typecheck — tsc --noEmit on its own runner. No browser, no build.
4# Build and test — the unit suite (vitest: node + jsdom projects), the
5# production build, then the repo Containerfile's image
6# (its ENV block is the single source of the deployment
7# defaults) and uploads the image tarball + compose files
8# as the run's 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_frontend_compose user unit, restart the
12# stack, shell-gated rollback to the previous tag,
13# independent after-the-fact verify.
14#
15# Typecheck and Build and test run in parallel. Deploy needs both green.
16# A new push cancels in-flight Typecheck/Build on the same ref; it never
17# cancels an in-flight Deploy (two deploys racing would interleave the compose
18# stack).
19#
20# The split is the recovery story, not ceremony:
21# * "Re-run failed jobs" on a run whose Deploy step failed re-runs ONLY the
22# ~1-minute deploy job — the built image is still in the run's artifact.
23# * workflow_dispatch (the manual door: Actions tab → Run workflow on main,
24# or `gh workflow run main.yml --ref main`) deploys WITHOUT the suite: it
25# takes the newest artifact a green Build-and-test produced — which can lag
26# HEAD while a push is mid-CI, and that is the point: redeploy the
27# known-good image, e.g. after a server-side fix (env file, proxy). For
28# env-only changes a plain
29# `ssh <vps> 'systemctl --user restart hezarfen_frontend_compose'` needs no
30# workflow at all: the stack re-reads its env files on the next
31# `podman compose up`.
32#
33# One-time prerequisites, outside the workflow's reach:
34# * the repo secrets SSH_PRIVATE_KEY / SSH_HOST / SSH_USER — the same three
35# names the backend's deploy uses;
36# * `loginctl enable-linger <user>` on the server unless the deploy user
37# already has it — user units need a running user manager;
38# * podman plus a compose provider on the server (the deploy checks for both
39# and fails with a one-line install hint);
40# * the operator's ~/hezarfen_frontend/hezarfen_frontend.env (0600), written
41# once by hand from deploy/hezarfen_frontend.env.example. The deploy never
42# creates or overwrites it.
43#
44# Two suites stay out of CI on purpose: Playwright e2e drives a Vite dev server
45# against a LIVE backend and logs in with the E2E_* account, and the vitest
46# contract suite (`bun run test:contract`) skips green without a real
47# CONTRACT_BASE_URL. Both are local/on-demand runs, not merge gates.
48
49name: VPS deploy
50
51on:
52 push:
53 branches:
54 - main
55 # The manual redeploy door — see the header comment for how and why.
56 workflow_dispatch:
57
58# Deploy serialisation lives on the deploy job, not the workflow: a new push
59# must be allowed to cancel stale Typecheck/Build without touching an
60# in-flight VPS swap.
61
62env:
63 # The systemd user unit that wraps `podman compose`. See
64 # deploy/hezarfen_frontend_compose.service.
65 SERVICE: hezarfen_frontend_compose
66 # The deploy lives in this subdirectory of the SSH user's home. The home
67 # itself is resolved on the server ($HOME), so switching the deploy user
68 # moves the path with it — a baked-in absolute path once kept pointing at
69 # the previous user's home and failed the deploy on permissions.
70 DEPLOY_SUBDIR: hezarfen_frontend
71 # Compose interpolates its knobs from this file on the server (passed as
72 # --env-file, and to the frontend container as env_file). The deploy never
73 # writes it, only checks it exists and carries the BACKEND_ORIGIN line prod
74 # must not run without.
75 ENV_FILE_NAME: hezarfen_frontend.env
76
77jobs:
78 typecheck:
79 name: Typecheck
80 if: github.event_name == 'push'
81 runs-on: ubuntu-24.04
82 concurrency:
83 group: ci-${{ github.workflow }}-${{ github.ref }}-typecheck
84 cancel-in-progress: true
85 steps:
86 - name: Checkout
87 uses: actions/checkout@v4
88 - name: Set up Bun
89 uses: oven-sh/setup-bun@v2
90 with:
91 # The 1.3.x line this lockfile was written with (the repo's own bun
92 # is 1.3.14). setup-bun takes a semver range; the runtime image
93 # floats on `oven/bun:1`, so the two can differ by a patch.
94 bun-version: "1.3.x"
95 - name: Cache bun
96 uses: actions/cache@v4
97 with:
98 path: ~/.bun/install/cache
99 # Keyed on the lockfile: a dependency change is a new cache, and
100 # the restore-key keeps a cold install to the added packages.
101 key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
102 restore-keys: bun-${{ runner.os }}-
103 - name: Install
104 run: bun install --frozen-lockfile
105 - name: Typecheck
106 run: bun run check
107
108 build:
109 name: Build and test
110 # Pushes only: a manual redeploy reuses the newest green artifact
111 # instead of paying the suite again.
112 if: github.event_name == 'push'
113 concurrency:
114 group: ci-${{ github.workflow }}-${{ github.ref }}-build
115 cancel-in-progress: true
116 runs-on: ubuntu-24.04
117 steps:
118 - name: Checkout
119 uses: actions/checkout@v4
120 - name: Set up Bun
121 uses: oven-sh/setup-bun@v2
122 with:
123 bun-version: "1.3.x"
124 - name: Cache bun
125 uses: actions/cache@v4
126 with:
127 path: ~/.bun/install/cache
128 key: bun-${{ runner.os }}-${{ hashFiles('bun.lock') }}
129 restore-keys: bun-${{ runner.os }}-
130 - name: Install
131 run: bun install --frozen-lockfile
132
133 # A broken build must never reach the server: the unit suite and the
134 # typecheck inside `bun run build` both gate the deploy.
135 - name: Test
136 run: bun run test
137
138 - name: Build the SPA
139 run: |
140 set -euo pipefail
141 bun run build # tsc --noEmit && vite build -> dist/
142 test -f dist/index.html
143 du -sh dist
144
145 # One Containerfile for laptop and CI, so there is no CI-only twin to
146 # drift: whatever its ENV block says is what ships.
147 - name: Build the image
148 run: |
149 set -euo pipefail
150 docker build -f Containerfile -t localhost/hezarfen_frontend:$GITHUB_SHA .
151
152 - name: Stage the release bundle
153 run: |
154 set -euo pipefail
155 mkdir -p stage
156 docker save localhost/hezarfen_frontend:$GITHUB_SHA | gzip > stage/hezarfen_frontend.tar.gz
157 cp compose.yaml deploy/hezarfen_frontend_compose.service stage/
158 echo -n "$GITHUB_SHA" > stage/tag
159 # Everything the deploy installs on the server must be here; a
160 # missing piece fails here, on the runner, not mid-deploy on the
161 # VPS.
162 test -f stage/hezarfen_frontend.tar.gz
163 test -f stage/compose.yaml
164 test -f stage/hezarfen_frontend_compose.service
165 test -f stage/tag
166 ls -l stage
167
168 # The deploy job (and, later, a manual redeploy) consumes this. 30
169 # days is also the dispatch door's reach-back window: an older green
170 # build's artifact is gone, and the redeploy fails loudly instead of
171 # silently shipping something ancient.
172 - name: Upload the release
173 uses: actions/upload-artifact@v4
174 with:
175 name: release
176 path: stage
177 retention-days: 30
178
179 deploy:
180 name: Deploy
181 needs: [typecheck, build]
182 concurrency:
183 group: deploy
184 cancel-in-progress: false
185 # Push: only behind a green typecheck AND a green build — both gate the
186 # server. Dispatch: both CI jobs are skipped on purpose (see their `if`),
187 # and `always()` is what stops that skip from cascading past this gate.
188 if: >-
189 always() &&
190 ((needs.typecheck.result == 'success' && needs.build.result == 'success') ||
191 (github.event_name == 'workflow_dispatch' &&
192 needs.typecheck.result == 'skipped' &&
193 needs.build.result == 'skipped'))
194 runs-on: ubuntu-24.04
195 steps:
196 # A push deploy takes the release this very run built and gated.
197 - name: Fetch this run's release
198 if: github.event_name == 'push'
199 uses: actions/download-artifact@v4
200 with:
201 name: release
202 path: stage
203
204 # A manual redeploy takes the newest release whose BUILD job went
205 # green — not the newest fully-green run: a run can be red because
206 # Deploy failed at the health gate while its build is exactly the
207 # release we want back on the server. `gh run list --status success`
208 # would skip exactly those, hence the per-run job check.
209 - name: Find the newest green build
210 if: github.event_name == 'workflow_dispatch'
211 env:
212 GH_TOKEN: ${{ github.token }}
213 run: |
214 set -euo pipefail
215 run_id=""
216 for rid in $(gh run list --workflow main.yml --branch main --event push --limit 15 --json databaseId --jq '.[].databaseId'); do
217 if [ "$(gh run view "$rid" --json jobs --jq '.jobs[] | select(.name=="Build and test") | .conclusion')" = "success" ]; then
218 run_id=$rid
219 break
220 fi
221 done
222 if [ -z "$run_id" ]; then
223 echo 'no run on main has a green Build-and-test job (or its artifact has expired)' >&2
224 exit 1
225 fi
226 echo "redeploying the release from run $run_id"
227 echo "run_id=$run_id" >> "$GITHUB_ENV"
228
229 - name: Fetch the green release
230 if: github.event_name == 'workflow_dispatch'
231 uses: actions/download-artifact@v4
232 with:
233 name: release
234 path: stage
235 run-id: ${{ env.run_id }}
236 github-token: ${{ github.token }}
237
238 # The dispatch path downloads a possibly-days-old artifact; re-check
239 # the bundle is whole before pointing any of it at the server.
240 - name: Check the release is complete
241 run: |
242 set -euo pipefail
243 test -f stage/hezarfen_frontend.tar.gz
244 test -f stage/compose.yaml
245 test -f stage/hezarfen_frontend_compose.service
246 test -f stage/tag
247
248 - name: Install SSH keys
249 run: |
250 mkdir -p ~/.ssh
251 echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa && chmod 600 ~/.ssh/id_rsa
252 ssh-keyscan -H ${{ secrets.SSH_HOST }} > ~/.ssh/known_hosts
253
254 - name: Upload the release
255 run: |
256 set -euo pipefail
257 ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}"
258
259 # The server's login shell is not bash, and ssh would hand this
260 # script to it; `bash -s` takes it on stdin instead, so the login
261 # shell only ever parses one plain command.
262 #
263 # The deploy path is $DEPLOY_SUBDIR under the SSH user's home,
264 # resolved on the server as $HOME: there is no path secret to go
265 # stale, and switching the deploy user moves the deploy with it.
266 ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR'" <<'REMOTE'
267 set -euo pipefail
268 case "$1" in
269 ''|/*|*..*)
270 echo "Refusing a broad deploy subdirectory: '$1'" >&2
271 exit 1
272 ;;
273 esac
274 deploy_path=$HOME/$1
275 # The deploy path holds the operator's hezarfen_frontend.env, the
276 # compose files and the tag files; nothing in it is deleted
277 # wholesale, ever.
278 mkdir -p -- "$deploy_path"
279 REMOTE
280 # stdin carries the bundle, so the script cannot; the extraction
281 # still goes through bash -c because the login shell is not bash
282 # and would not expand $HOME. Only the four deploy files are
283 # installed on the server: the staged dist/ and server.ts ride
284 # along inside the artifact (they were docker build context), but
285 # nothing ever extracts them there.
286 tar -C stage -czf - hezarfen_frontend.tar.gz compose.yaml hezarfen_frontend_compose.service tag | ssh "$ssh_target" "bash -c 'exec tar -xzf - -C \"\$HOME/\$1\"' -- '$DEPLOY_SUBDIR'"
287
288 - name: Load the image and restart the stack
289 run: |
290 set -euo pipefail
291 ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}"
292
293 # bash -s for the same reason as above: the login shell is not
294 # bash and must never see this script.
295 ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$SERVICE' '$ENV_FILE_NAME'" <<'REMOTE'
296 set -euo pipefail
297 deploy_path=$HOME/$1
298 service=$2
299 env_file=$deploy_path/$3
300 export XDG_RUNTIME_DIR=/run/user/$(id -u)
301 # compose.yaml is resolved from the working directory: the unit's
302 # ExecStart carries WorkingDirectory, but the rollback compose up
303 # and a first-deploy down run from right here.
304 cd -- "$deploy_path"
305
306 # Read before anything moves: the env file is the operator's, on
307 # the server, written once by hand (see
308 # deploy/hezarfen_frontend.env.example for the keys). The deploy
309 # never creates or overwrites it. BACKEND_ORIGIN is load-bearing:
310 # without it compose would silently fall back to its laptop default
311 # and the container would proxy /api somewhere prod did not choose.
312 if [ ! -f "$env_file" ]; then
313 echo "missing $env_file — create it (0600) from deploy/hezarfen_frontend.env.example" >&2
314 exit 1
315 fi
316 chmod 0600 -- "$env_file"
317 for key in BACKEND_ORIGIN; do
318 grep -Eq "^${key}=.+" "$env_file" || {
319 echo "no non-empty ${key}= line in $env_file — prod must not run on the compose default" >&2
320 exit 1
321 }
322 done
323
324 # The probe port is not repeated here: ask the container that gets
325 # (re)created below what it carries (image ENV, overridden by the
326 # operator's file), instead of parsing a second copy of the number.
327
328 # Rootless podman plus a compose provider; fail with the fix, not
329 # a bare command-not-found three steps in.
330 command -v podman >/dev/null || {
331 echo "podman not found — install podman and a compose provider (e.g. dnf install podman podman-compose)" >&2
332 exit 1
333 }
334 podman compose version >/dev/null 2>&1 || {
335 echo "'podman compose' unavailable — install a compose provider (podman-compose or docker-compose)" >&2
336 exit 1
337 }
338
339 # Load THIS build's image and read the tag the build stamped into
340 # it (build time and deploy time must agree on what is shipping).
341 gunzip -c "$deploy_path/hezarfen_frontend.tar.gz" | podman load
342 tag=$(cat -- "$deploy_path/tag")
343
344 # Tag rotation: previous_tag is the rollback target (absent on a
345 # first deploy); current_tag records what should now be running.
346 if [ -f "$deploy_path/current_tag" ]; then
347 cp -- "$deploy_path/current_tag" "$deploy_path/previous_tag"
348 fi
349 printf '%s\n' "$tag" > "$deploy_path/current_tag"
350
351 # stack.env is deploy-owned (unlike the knobs file): it carries
352 # only the image tag, and --env-file order makes it win over the
353 # operator's file for HEZARFEN_TAG.
354 printf 'HEZARFEN_TAG=%s\n' "$tag" > "$deploy_path/stack.env"
355
356 # The freshly extracted bundle: compose file and unit are
357 # world-readable.
358 chmod 0644 -- "$deploy_path/compose.yaml" "$deploy_path/hezarfen_frontend_compose.service"
359 # The image tarball was only a transport; the image is loaded into
360 # podman's storage now.
361 rm -f -- "$deploy_path/hezarfen_frontend.tar.gz"
362
363 compose_up() {
364 podman compose --env-file "$env_file" --env-file "$deploy_path/stack.env" up -d --no-build
365 }
366 rollback() {
367 if [ -f "$deploy_path/previous_tag" ]; then
368 prev=$(cat -- "$deploy_path/previous_tag")
369 printf 'HEZARFEN_TAG=%s\n' "$prev" > "$deploy_path/stack.env"
370 printf '%s\n' "$prev" > "$deploy_path/current_tag"
371 compose_up
372 echo "rolled back to $prev" >&2
373 else
374 # First deploy: nothing to roll back to, so stop the
375 # half-brought-up stack. Plain down — the frontend is
376 # stateless, but the shape stays identical to the backend's.
377 podman compose --env-file "$env_file" --env-file "$deploy_path/stack.env" down
378 echo 'first deploy failed; stack stopped' >&2
379 fi
380 }
381
382 # The unit ships with the release: a freshly provisioned box has
383 # no unit until the first deploy writes it, and a changed unit
384 # lands with the compose file that needs it.
385 mkdir -p -- "$HOME/.config/systemd/user"
386 install -m 0644 -- "$deploy_path/hezarfen_frontend_compose.service" "$HOME/.config/systemd/user/$service.service"
387 systemctl --user daemon-reload
388
389 # The unit is a oneshot with RemainAfterExit, so `start` on the
390 # active (exited) unit would be a no-op — every deploy restarts
391 # to re-run ExecStart. A failed restart (bad interpolation, a
392 # provider hiccup) must still reach the health gate below: it
393 # decides between rollback and success.
394 systemctl --user enable -- "$service"
395 systemctl --user restart "$service" || true
396
397 # Ask the container that was just (re)created which port to probe
398 # (image ENV, overridden by the operator's file) — the number lives in
399 # one place and this reads it, rather than keeping a second copy that
400 # can drift. No container reachable = nothing came up.
401 port=$(podman inspect -f '{{range .Config.Env}}{{println .}}{{end}}' hezarfen_frontend 2>/dev/null | sed -n 's/^PORT=//p') || true
402 if [ -z "$port" ]; then
403 echo 'the frontend container reports no PORT; rolling back' >&2
404 rollback
405 exit 1
406 fi
407
408 # The oneshot returns before the container has bound its port. Wait
409 # for the SPA shell rather than a clock: a 200 whose body carries
410 # the index.html title means the new build is really being served.
411 # 45 attempts, not the backend's 90: every image here is already
412 # loaded and there is no database to warm up behind the frontend.
413 health_ok=0
414 for _ in $(seq 1 45); do
415 served=$(curl -fsS "http://127.0.0.1:$port/" 2>/dev/null) || true
416 case "$served" in
417 *'<title>Hezarfen</title>'*) health_ok=1; break ;;
418 esac
419 sleep 1
420 done
421 if [ "$health_ok" -ne 1 ]; then
422 echo 'the SPA shell never served; rolling back' >&2
423 rollback
424 exit 1
425 fi
426
427 # A stale stack from an older deploy can answer too, so the
428 # running container must be THIS build's image, or it rolls back.
429 image=$(podman inspect -f '{{.Config.Image}}' hezarfen_frontend)
430 case "$image" in
431 *"$tag"*) ;;
432 *)
433 echo "the shell served, but the container runs '$image' — not this build ($tag); rolling back" >&2
434 rollback
435 exit 1
436 ;;
437 esac
438 echo 'hezarfen_frontend_compose is up'
439 REMOTE
440
441 # The independent after-the-fact check: the container answering must
442 # still be the current tag's, and the SPA shell must be served.
443 - name: Verify the served app
444 run: |
445 set -euo pipefail
446 ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}"
447 # One remote script, im-style: mixing runner-side and server-side
448 # variables in nested ssh quoting once shipped a check that failed
449 # on a healthy deploy. Everything happens inside the heredoc.
450 ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR'" <<'REMOTE'
451 set -euo pipefail
452 deploy_path=$HOME/$1
453 export XDG_RUNTIME_DIR=/run/user/$(id -u)
454 cd -- "$deploy_path"
455 # Same source as the deploy step: the container's own PORT, not a
456 # second copy of the number in this script.
457 port=$(podman inspect -f '{{range .Config.Env}}{{println .}}{{end}}' hezarfen_frontend | sed -n 's/^PORT=//p')
458 if [ -z "$port" ]; then
459 echo 'the frontend container reports no PORT' >&2
460 exit 1
461 fi
462 tag=$(cat -- "$deploy_path/current_tag")
463 image=$(podman inspect -f '{{.Config.Image}}' hezarfen_frontend)
464 case "$image" in
465 *"$tag"*) ;;
466 *)
467 echo "container runs '$image', not the current tag '$tag'" >&2
468 exit 1
469 ;;
470 esac
471 served=$(curl -fsS "http://127.0.0.1:$port/") || { echo 'the SPA shell did not serve' >&2; exit 1; }
472 case "$served" in
473 *'<title>Hezarfen</title>'*) ;;
474 *) echo 'the SPA shell served without its title' >&2; exit 1 ;;
475 esac
476 # NOT a gate: /api is proxied to a different deployment, so a
477 # backend outage must never fail (or roll back) a frontend deploy.
478 # Reported so a broken proxy target is visible in the deploy log.
479 if curl -fsS -o /dev/null "http://127.0.0.1:$port/api/time"; then
480 echo 'shell ok, /api reachable'
481 else
482 echo 'shell ok, but /api/time did not answer — check BACKEND_ORIGIN and the backend'
483 fi
484 REMOTE
485
486 - name: Cleaning
487 run: rm -rf ~/.ssh