Files
loki/.github/workflows/selfhost-deploy.yml

502 lines
24 KiB
YAML

name: Self-host deploy
# Reusable CD for every app on bitbaum. Call it from an app repo with a 12-line
# shim (see docs/infrastructure/self-host-cd.md); all the logic lives here so
# there is exactly ONE deploy pipeline to fix, audit, or improve.
#
# What it does, in order:
# 1. wait for the pushed commit's own CI to go green (ci-gate.sh — a red blocks)
# 2. pull the app's runtime .env FROM THE BOX (the box stays the env SSOT;
# no prod secrets are duplicated into GitHub)
# 3. build + rsync + atomic symlink swap + health check + auto-rollback
# (scripts/hetzner/deploy.sh — the same script laptop deploys use)
# 4. verify the PUBLIC url returns 2xx/3xx before calling the deploy done
#
# The only secret an app repo needs is HETZNER_SSH_PRIVATE_KEY (ubuntu@bitbaum).
on:
workflow_call:
inputs:
app:
description: "Key in scripts/hetzner/apps.conf — SSOT for port, domain, app dir and database"
required: true
type: string
git-ref:
description: "Exact app commit to deploy (for workflow_run callers)"
required: false
type: string
default: ""
node-version:
# The FALLBACK when a repo commits no .nvmrc. It must track the box
# runtime (Node 24 since 2026-08-31) and the fleet's CI default —
# 2026-09-02: aoz-begleitung's deploy npm-ci'd with npm 10 (Node 20)
# against a lockfile written by npm 11 (Node 24 CI) and failed on
# "Missing: esbuild from lock file", stranding two merged commits.
# A stale fallback here recreates that npm-major split for every
# .nvmrc-less repo in the fleet.
description: "Node version to build with"
required: false
type: string
default: "24"
install-flags:
description: "Extra flags for the install command (e.g. --legacy-peer-deps)"
required: false
type: string
default: ""
package-manager:
description: "Override lockfile detection: npm | pnpm | yarn"
required: false
type: string
default: ""
receipt-projects:
description: "Comma-separated workspace importers included in the public package receipt"
required: false
type: string
default: ""
receipt-visibility:
description: "Whether this app's deployed release receipt is public: auto, public, or private"
required: false
type: string
default: auto
secrets:
HETZNER_SSH_PRIVATE_KEY:
required: true
jobs:
deploy:
name: ${{ inputs.app }} → bitbaum
runs-on: ubuntu-latest
timeout-minutes: 45
# Never cancel a deploy in flight: the swap is atomic but a half-finished
# rsync leaves a junk release dir. Queue instead.
concurrency:
group: selfhost-deploy-${{ inputs.app }}
cancel-in-progress: false
steps:
# A missing secret must FAIL, not skip. A deploy job that silently does
# nothing and reports green is the exact failure mode this pipeline exists
# to remove — prod would drift from main with no signal anywhere.
- name: Require deploy key
env:
SSH_KEY: ${{ secrets.HETZNER_SSH_PRIVATE_KEY }}
run: |
if [ -z "$SSH_KEY" ]; then
echo "::error::HETZNER_SSH_PRIVATE_KEY is not set on this repository — ${{ inputs.app }} cannot deploy."
exit 1
fi
echo "deploy key present"
- name: Checkout app
uses: actions/checkout@v7
with:
ref: ${{ inputs.git-ref || github.sha }}
# Cloned rather than checked out: actions/checkout can only write inside
# the workspace, and a second repo there would end up inside the app's own
# build/lint globs.
- name: Fetch fleet tooling
run: |
git clone --quiet --depth 1 https://github.com/bitbaum/loki.git "$RUNNER_TEMP/fleet-tooling"
echo "tooling at $(git -C "$RUNNER_TEMP/fleet-tooling" rev-parse --short HEAD)"
- name: Setup SSH
env:
SSH_KEY: ${{ secrets.HETZNER_SSH_PRIVATE_KEY }}
# The box address is the org-level Actions variable HETZNER_IP, not a
# literal. This workflow is REUSED by ~20 repos, so a literal here is
# twenty edits on the day the box moves — and the DNS hint below
# quoted the same number a second time, in prose nobody greps.
IP: ${{ vars.HETZNER_IP }}
run: |
set -euo pipefail
if [ -z "$IP" ]; then
echo "::error::org variable HETZNER_IP is unset — a deploy cannot guess where the box is."
echo "::error::Set it under the bitbaum org: Settings -> Secrets and variables -> Actions -> Variables."
exit 1
fi
mkdir -p ~/.ssh && chmod 700 ~/.ssh
printf '%s\n' "$SSH_KEY" > ~/.ssh/id_ed25519
chmod 600 ~/.ssh/id_ed25519
ssh-keyscan -H "$IP" >> ~/.ssh/known_hosts 2>/dev/null
ssh -o BatchMode=yes "ubuntu@$IP" 'echo "ssh to $(hostname) ok"'
- name: Resolve app from manifest
id: app
run: |
set -euo pipefail
TOOLING="$RUNNER_TEMP/fleet-tooling/scripts/hetzner"
# lib.sh sets NAME PORT DOMAINS REPO APP_DIR DB, and exits non-zero on
# an unknown app — a typo in the caller shim fails here, not in prod.
source "$TOOLING/lib.sh"
APP="${{ inputs.app }}"
[[ "$APP" =~ ^[a-z0-9][a-z0-9-]*$ ]] || exit 1
if ! app_lookup "$APP"; then
# Registration writes the durable canonical register. A new site
# must not wait for an unrelated Loki source deployment.
ssh -o BatchMode=yes "ubuntu@$HETZNER_IP" 'cat /home/ubuntu/dev/loki/scripts/hetzner/apps.conf' > "$RUNNER_TEMP/registered-apps.conf"
export MANIFEST="$RUNNER_TEMP/registered-apps.conf"
app_lookup "$APP"
# Prove the registered checkout belongs to this caller repository.
registered_repo=$(ssh -o BatchMode=yes "ubuntu@$HETZNER_IP" "git -C '$REPO' remote get-url origin")
registered_repo=$(printf '%s' "$registered_repo" | sed -E 's#^https://github.com/##; s#^git@github.com:##; s#\.git$##')
[ "$registered_repo" = "$GITHUB_REPOSITORY" ] || { echo "::error::registered repository does not match caller"; exit 1; }
echo "MANIFEST=$MANIFEST" >> "$GITHUB_ENV"
fi
{
echo "name=$NAME"
echo "port=$PORT"
echo "app_dir=$APP_DIR"
echo "domain=${DOMAINS%%,*}"
echo "ip=$HETZNER_IP"
echo "tooling=$TOOLING"
} >> "$GITHUB_OUTPUT"
echo "resolved $NAME → port $PORT, dir '$APP_DIR', domain ${DOMAINS%%,*}, db $DB"
# The box holds the authoritative runtime env (NEXT_PUBLIC_* is baked in at
# build time, so the builder needs it too). Pulling it keeps ONE copy of
# every prod secret instead of forking it into N GitHub secret stores.
- name: Pull runtime env from the box
env:
NAME: ${{ steps.app.outputs.name }}
APP_DIR: ${{ steps.app.outputs.app_dir }}
IP: ${{ steps.app.outputs.ip }}
run: |
set -euo pipefail
src=""
for cand in "/opt/$NAME/shared/.env" "/opt/$NAME/app/.env"; do
if ssh -o BatchMode=yes "ubuntu@$IP" "test -f '$cand'"; then src="$cand"; break; fi
done
if [ -z "$src" ]; then
echo "::error::no runtime .env found on the box for $NAME (looked in shared/ and app/)"
exit 1
fi
runtime_dir="$RUNNER_TEMP/selfhost-runtime"
mkdir -p "$runtime_dir"
chmod 700 "$runtime_dir"
dest="$runtime_dir/app.env"
echo "SELFHOST_ENV_FILE=$dest" >> "$GITHUB_ENV"
scp -q -o BatchMode=yes "ubuntu@$IP:$src" "$dest"
chmod 600 "$dest"
# Count, never a bare "ok": an empty file would otherwise sail through
# and produce a build with every env var silently undefined.
vars=$(grep -cE '^[A-Za-z_][A-Za-z0-9_]*=' "$dest" || true)
[ "${vars:-0}" -gt 0 ] || { echo "::error::$src has no variables"; exit 1; }
echo "pulled runtime environment outside source checkout ($vars variables)"
# The fleet's shared keys (scripts/hetzner/fleet-env.sh), for the
# build to read before the app's own env, as the runtime does.
if ssh -o BatchMode=yes "ubuntu@$IP" "test -f /opt/fleet/env"; then
scp -q -o BatchMode=yes "ubuntu@$IP:/opt/fleet/env" "$runtime_dir/shared.env"
chmod 600 "$runtime_dir/shared.env"
echo "FLEET_ENV_FILE=$runtime_dir/shared.env" >> "$GITHUB_ENV"
echo "pulled shared environment outside source checkout ($(grep -cE '^[A-Za-z_][A-Za-z0-9_]*=' "$runtime_dir/shared.env" || true) shared keys)"
fi
# The fleet is mixed: eight apps are npm, four are pnpm. Detect from the
# lockfile rather than asking every caller to declare it — the lockfile is
# already the source of truth for which manager can install this tree.
- name: Detect package manager
id: pm
env:
OVERRIDE: ${{ inputs.package-manager }}
run: |
set -euo pipefail
if [ -n "$OVERRIDE" ]; then mgr="$OVERRIDE"
elif [ -f pnpm-lock.yaml ]; then mgr=pnpm
elif [ -f yarn.lock ]; then mgr=yarn
elif [ -f package-lock.json ]; then mgr=npm
else
echo "::error::no lockfile at the repo root — cannot install reproducibly"
exit 1
fi
echo "manager=$mgr" >> "$GITHUB_OUTPUT"
echo "package manager: $mgr"
# Must precede setup-node: its pnpm/yarn cache lookup needs the binary.
- name: Enable corepack
if: steps.pm.outputs.manager != 'npm'
env:
MGR: ${{ steps.pm.outputs.manager }}
run: |
set -euo pipefail
corepack enable
# The repo's own packageManager field is the source of truth for its
# toolchain. Guessing a version from lockfileVersion does not work —
# pnpm 9, 10 and 11 all write lockfileVersion 9.0, and pinning 9
# against a pnpm-10-style pnpm-workspace.yaml breaks the install.
if node -p "require('./package.json').packageManager||''" 2>/dev/null | grep -q .; then
echo "using declared toolchain: $(node -p "require('./package.json').packageManager")"
else
echo "::warning::$GITHUB_REPOSITORY does not declare packageManager in package.json — falling back to $MGR@latest, which can change under you. Declare it."
corepack prepare "$MGR@latest" --activate
fi
# A dependency cache is an optimisation. Probing it first means a broken
# cache lookup degrades to a slower deploy instead of failing one — the
# pnpm store probe reads pnpm-workspace.yaml and errors on configs it
# does not understand, which took vitareba's first deploy down.
- name: Probe dependency cache
id: cache
env:
MGR: ${{ steps.pm.outputs.manager }}
run: |
set +e
case "$MGR" in
npm) ok=0 ;;
pnpm) pnpm store path >/dev/null 2>&1; ok=$? ;;
yarn) yarn config get cacheFolder >/dev/null 2>&1; ok=$? ;;
esac
if [ "$ok" -eq 0 ]; then
echo "use=$MGR" >> "$GITHUB_OUTPUT"
echo "dependency cache: $MGR"
else
echo "use=" >> "$GITHUB_OUTPUT"
echo "::warning::$MGR cache unavailable — deploying without it (slower, not broken)"
fi
# The build must run on the SAME Node the repo's CI verified with. npm 10
# and 11 disagree about optional platform deps, so a lockfile npm 11 wrote
# reads as "out of sync" to npm 10 — that is how hirnli's CI passed on
# Node 24 while its deploy failed `npm ci` on Node 20. A committed .nvmrc
# is the one declaration both sides read; the input is the fallback.
- name: Resolve Node version
id: node
env:
FALLBACK: ${{ inputs.node-version }}
run: |
set -euo pipefail
for f in .nvmrc .node-version; do
if [ -f "$f" ]; then
echo "file=$f" >> "$GITHUB_OUTPUT"
echo "Node version from $f: $(tr -d 'v \n' < "$f")"
exit 0
fi
done
echo "file=" >> "$GITHUB_OUTPUT"
echo "version=$FALLBACK" >> "$GITHUB_OUTPUT"
echo "::notice::no .nvmrc — building on Node $FALLBACK. If this repo's CI uses a different major, commit a .nvmrc both can read."
- uses: actions/setup-node@v7
with:
node-version: ${{ steps.node.outputs.version }}
node-version-file: ${{ steps.node.outputs.file }}
cache: ${{ steps.cache.outputs.use }}
- name: Install dependencies
env:
APP_DIR: ${{ steps.app.outputs.app_dir }}
MGR: ${{ steps.pm.outputs.manager }}
INSTALL_FLAGS: ${{ inputs.install-flags }}
# Deploys build from a lockfile CI already verified; a drifted lockfile
# should fail in CI, not be silently papered over here.
NPM_CONFIG_FUND: "false"
NPM_CONFIG_AUDIT: "false"
run: |
set -euo pipefail
case "$MGR" in
npm) install="npm ci" ;;
pnpm) install="pnpm install --frozen-lockfile" ;;
yarn) install="yarn install --immutable" ;;
esac
# Always install at the repo root (workspaces live there). Then install
# again inside the app dir only when it carries its OWN lockfile — a
# nested standalone project, as in sbb-lost-found and datacat.
echo "→ $install in ./"
$install $INSTALL_FLAGS
if [ "$APP_DIR" != "." ] && [ -f "$APP_DIR/package-lock.json" -o -f "$APP_DIR/pnpm-lock.yaml" -o -f "$APP_DIR/yarn.lock" ]; then
echo "→ $install in ./$APP_DIR (nested project with its own lockfile)"
( cd "$APP_DIR" && $install $INSTALL_FLAGS )
fi
# Prod only ever receives code CI has verified. Exit 3 = this commit was
# superseded by a newer push, whose own deploy will ship — skip quietly.
# Next keeps its compiler output in .next/cache. Deploys here run a full
# `npm run build` (deploy.sh) on the runner, and without this the build is
# COLD every single time — for every repo that calls this workflow.
#
# Measured 2026-09-07 across the fleet: nobody's deploy cached this, and
# only one repo's CI did. Deploy medians ran 2.9m (loki) to 12.7m
# (evig) against CI medians of 1.9m to 10.7m for the same commits, because
# the same compile happens twice from scratch.
#
# Scoped by app so two apps in one repo cannot evict each other, and keyed
# on the lockfile so a dependency change invalidates it. The bare
# restore-key is last on purpose: a stale cache is still far cheaper than
# no cache, and Next validates entries itself rather than trusting them.
- name: Cache Next.js build
uses: actions/cache@v6
with:
path: ${{ steps.app.outputs.app_dir }}/.next/cache
key: nextjs-${{ runner.os }}-${{ inputs.app }}-${{ hashFiles('**/package-lock.json', '**/pnpm-lock.yaml', '**/yarn.lock') }}-${{ github.sha }}
restore-keys: |
nextjs-${{ runner.os }}-${{ inputs.app }}-${{ hashFiles('**/package-lock.json', '**/pnpm-lock.yaml', '**/yarn.lock') }}-
nextjs-${{ runner.os }}-${{ inputs.app }}-
- name: Wait for CI to pass on this commit
id: gate
env:
GH_TOKEN: ${{ github.token }}
TOOLING: ${{ steps.app.outputs.tooling }}
run: |
# +e on purpose: exit 3 ("superseded") is a normal outcome to branch on,
# and the default `bash -e` shell would abort the step before we read it.
set +e
# Exclude this deploy workflow from what counts as CI — every run of
# it. It is a workflow run on the same SHA, so without this the gate
# waits on itself, and a retry after a failed deploy reads that
# earlier failure as a red CI and can never succeed.
# GITHUB_WORKFLOW_REF is owner/repo/.github/workflows/x.yml@refs/...
wf="${GITHUB_WORKFLOW_REF#*/*/}"; wf="${wf%%@*}"
echo "not counting $wf as CI"
CI_GATE_EXCLUDE_PATH="$wf" bash "$TOOLING/ci-gate.sh" "$GITHUB_REPOSITORY" "${{ inputs.git-ref || github.sha }}"
rc=$?
case "$rc" in
0) echo "proceed=true" >> "$GITHUB_OUTPUT" ;;
3) echo "proceed=false" >> "$GITHUB_OUTPUT"
echo "::notice::commit superseded — a newer push will deploy" ;;
*) echo "::error::CI is not green for ${{ inputs.git-ref || github.sha }} — deploy blocked"; exit 1 ;;
esac
# Look at the live page as a visitor on a phone does, BEFORE this deploy,
# so the step after it can say whether the change made the page worse.
# A green deploy used to prove only that the site answered 200; on
# autopilot nobody else looks. GitHub's runners ship Chrome, so this
# installs only the playwright client, never a browser. Never blocks: a
# page that cannot be read here just means there is nothing to compare.
- name: Look at the live page before the deploy
if: steps.gate.outputs.proceed == 'true' && steps.app.outputs.domain != '-'
continue-on-error: true
# A look, never a gate: a page that hangs once held the whole deploy
# for 45 minutes (farmaciadelparco, 2026-10-07). page-check.mjs has its
# own 90s deadline; this is the backstop for the install and the rest.
timeout-minutes: 4
env:
DOMAIN: ${{ steps.app.outputs.domain }}
TOOLING: ${{ steps.app.outputs.tooling }}
run: |
set -uo pipefail
dir="$RUNNER_TEMP/page-check"
mkdir -p "$dir"
cp "$TOOLING/page-check.mjs" "$TOOLING/page-check-compare.mjs" "$dir/"
cd "$dir"
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm install --no-save --silent --no-audit --no-fund playwright@1.63.0 > /dev/null 2>&1 \
|| echo "::warning::could not install the page checker; this deploy is not compared"
CHROME_PATH="$(command -v google-chrome || command -v chromium || true)" \
node page-check.mjs "https://$DOMAIN/" before.json before.png || true
- name: Prepare public artifact receipt producer
if: steps.gate.outputs.proceed == 'true'
id: receipt
env:
GH_TOKEN: ${{ github.token }}
TOOLING: ${{ steps.app.outputs.tooling }}
run: |
bash "$TOOLING/receipt-visibility.sh" "${{ inputs.receipt-visibility }}" "$GITHUB_REPOSITORY"
producer="$RUNNER_TEMP/fleet-release-receipt"
if git clone --quiet --depth 1 https://github.com/bitbaum/fleet.git "$producer" && [ -f "$producer/scripts/ci/release-receipt.mjs" ]; then
echo "root=$producer" >> "$GITHUB_OUTPUT"
else
echo "::warning::Receipt producer unavailable; promotion will have no live receipt."
fi
- name: Deploy
if: steps.gate.outputs.proceed == 'true'
env:
BUILD_PACKAGE_MANAGER: ${{ steps.pm.outputs.manager }}
FLEET_RECEIPT_PUBLIC: ${{ steps.receipt.outputs.public }}
FLEET_RECEIPT_ROOT: ${{ steps.receipt.outputs.root }}
FLEET_RECEIPT_REPO: ${{ github.repository }}
FLEET_RECEIPT_PROJECTS: ${{ inputs.receipt-projects }}
REPO_OVERRIDE: ${{ github.workspace }}
TOOLING: ${{ steps.app.outputs.tooling }}
run: bash "$TOOLING/deploy.sh" "${{ inputs.app }}"
# deploy.sh already health-checks localhost and auto-rolls-back. This
# checks what a USER actually hits — through Caddy, TLS and DNS — because
# "the service is up" and "the site works" are different claims.
- name: Verify public URL
if: steps.gate.outputs.proceed == 'true'
env:
DOMAIN: ${{ steps.app.outputs.domain }}
run: |
set -uo pipefail
if [ "$DOMAIN" = "-" ]; then
echo "::notice::${{ inputs.app }} is internal-only — no public URL to check"
exit 0
fi
# Resolve BEFORE curling. A hostname with no DNS record and an app
# that is genuinely down both make curl print 000, so reporting only
# the status code sends you to read service logs for a box that is
# perfectly healthy. solon burned this: every deploy since 2026-08-03
# failed here, the app was running the whole time, and the actual
# cause was that solon.orangecat.ch was never created at the
# registrar. Retrying an NXDOMAIN 10 times cannot help either — DNS
# is not going to appear during the sleep.
if ! getent hosts "$DOMAIN" >/dev/null 2>&1; then
echo "::error::$DOMAIN does not resolve — this is a DNS gap, NOT a broken deploy."
echo "::error::The app was deployed and Caddy is configured for it; the hostname simply does not exist."
echo "::error::Fix: create an A record $DOMAIN → $IP at the DNS provider (orangecat.ch is on Infomaniak), then re-run this workflow."
exit 1
fi
for attempt in $(seq 1 10); do
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 "https://$DOMAIN/") || true; code=${code:0:3}
if [ "$code" -ge 200 ] 2>/dev/null && [ "$code" -lt 400 ]; then
echo "https://$DOMAIN → $code (attempt $attempt)"
exit 0
fi
sleep 6
done
if [ "$code" = "000" ]; then
echo "::error::$DOMAIN resolves but nothing answered on https — check Caddy (TLS cert issuance) and the app service on the box."
else
echo "::error::https://$DOMAIN returned $code after the deploy"
fi
exit 1
# The same look AFTER the deploy. If the change made the page worse on a
# phone — it stopped loading, scrolls sideways, throws new errors, broke
# images, lost most of its text — roll back to the previous release and
# fail the deploy with the reasons. Loki's fix ledger reads that as a
# failed deploy of the fix and tells the owner the site still shows the
# old version, which is then true. Only what the change ADDED counts:
# page-check-compare.mjs, pinned by scripts/test/page-check-compare.ts.
- name: Compare the live page with before
if: steps.gate.outputs.proceed == 'true' && steps.app.outputs.domain != '-'
# Room for the look (90s deadline) and a rollback, never the job's 45m.
timeout-minutes: 8
env:
DOMAIN: ${{ steps.app.outputs.domain }}
TOOLING: ${{ steps.app.outputs.tooling }}
HETZNER_IP: ${{ steps.app.outputs.ip }}
run: |
set -uo pipefail
dir="$RUNNER_TEMP/page-check"
if [ ! -f "$dir/page-check.mjs" ] || [ ! -d "$dir/node_modules/playwright" ]; then
echo "::warning::the page checker did not install; this deploy was not compared"
exit 0
fi
cd "$dir"
CHROME_PATH="$(command -v google-chrome || command -v chromium || true)" \
node page-check.mjs "https://$DOMAIN/" after.json after.png || true
node page-check-compare.mjs before.json after.json > verdict.txt
rc=$?
cat verdict.txt
if [ "$rc" -eq 2 ]; then
echo "::error::This change made https://$DOMAIN/ worse on a phone. Rolling back to the previous version."
sed -n 's/^WORSE: /::error::/p' verdict.txt
bash "$TOOLING/rollback.sh" "${{ inputs.app }}" \
|| echo "::error::rollback FAILED — the worse version may still be live"
exit 1
fi
[ "$rc" -eq 0 ] || echo "::warning::could not compare the page (exit $rc); this deploy was not judged"
exit 0
- name: Keep what the phone saw
if: always() && steps.gate.outputs.proceed == 'true' && steps.app.outputs.domain != '-'
uses: actions/upload-artifact@v4
with:
name: page-check-${{ inputs.app }}
path: |
${{ runner.temp }}/page-check/*.png
${{ runner.temp }}/page-check/*.json
${{ runner.temp }}/page-check/verdict.txt
if-no-files-found: ignore
retention-days: 14