Skip to content

chore: #134 run Playwright E2E in CI, expand tests, and harden CI/CD deploy #275

chore: #134 run Playwright E2E in CI, expand tests, and harden CI/CD deploy

chore: #134 run Playwright E2E in CI, expand tests, and harden CI/CD deploy #275

Workflow file for this run

name: CI/CD
# `contents: read` limits the GitHub Actions GITHUB_TOKEN to read-only access
# on GitHub. Note that on the self-hosted VM (`it2810-19`), PR jobs currently
# run under the same OS user that deploys (with access to `~/T19-Project-2/.env`,
# `/var/www/html/project2`, and `sudo systemctl restart crate-api`), so only
# trusted group members should open PRs. Running PR checks on a separate
# unprivileged runner user without sudo or `.env` access would isolate this further.
permissions:
contents: read
on:
# No branch filter here on purpose. We stack PRs (a branch PR based on
# another branch), and a `branches: [main]` filter silently skips CI for
# every stacked PR. That is how this was found: #34 targets
# feat/1-repo-tooling and got no run at all.
pull_request:
push:
branches: [main]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
# Cancel superseded PR runs, but never cancel an in-progress push/deploy on main.
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
quality:
name: Format, lint, typecheck, test, build
# Deliberately unpinned beyond the platform: quality is a pure function of
# the checked-out tree, so it can run on any self-hosted runner we add
# later without changing this file. Only `deploy` is machine-specific.
runs-on: [self-hosted, linux, x64]
steps:
- name: Checkout
uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0
- name: Install pnpm
uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4.3.0
with:
version: 10.33.0
- name: Set up Node.js
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 24
cache: pnpm
- name: Install dependencies
run: pnpm install --frozen-lockfile
# Generated operation types are committed, so a checkout builds without
# running the generator. That only holds if the committed output matches
# the schema and the operations, so regenerate and fail on any diff. This
# runs before typecheck on purpose: a stale tree should fail with "run
# pnpm codegen", not with a type error in generated code.
- name: Check generated GraphQL types are up to date
run: |
set -euo pipefail
pnpm codegen
if [ -n "$(git status --porcelain -- client/src/generated)" ]; then
echo "::error::client/src/generated is stale. Run 'pnpm codegen' and commit the result."
git --no-pager diff -- client/src/generated | head -60
exit 1
fi
- name: Check formatting
run: pnpm format:check
- name: Lint
run: pnpm lint
- name: Typecheck
run: pnpm typecheck
- name: Test
run: pnpm test
- name: Build
run: pnpm build
# Bundle budget, one of our bærekraft measures. The budget is deliberately
# loose today and tightens as the app grows; the point is that CI fails
# before a dependency quietly doubles our payload.
- name: Enforce client bundle budget
run: |
set -euo pipefail
MAX_BYTES=512000
shopt -s nullglob
found=0
for f in client/dist/assets/*.js; do
found=1
size=$(stat -c%s "$f")
echo "$f = ${size} bytes (budget ${MAX_BYTES})"
if [ "$size" -gt "$MAX_BYTES" ]; then
echo "::error::Bundle budget exceeded: $f is ${size} bytes (max ${MAX_BYTES})."
exit 1
fi
done
if [ "$found" -eq 0 ]; then
echo "::error::No client JS bundle found in client/dist/assets/."
exit 1
fi
# The database-backed suites are skipped when TEST_DATABASE_URL is unset, so
# until this job existed CI reported them as "27 skipped" and stayed green.
# The tests guard the things unit tests cannot see: SQL that only fails once
# PostgreSQL parses it, keyset paging across ties and NULLs, facet counts
# against the filters, and the MusicBrainz import preserving reviews.
#
# The cluster is created here and thrown away at the end. Deliberately not the
# application database and not a shared test database: no secret to hand out,
# no state to drift, and running the destructive seed is impossible by
# construction. It listens on a unix socket only, so it cannot accept a TCP
# connection even while it exists.
integration:
name: PostgreSQL integration tests
runs-on: [self-hosted, linux, x64]
steps:
- name: Checkout
uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0
- name: Install pnpm
uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4.3.0
with:
version: 10.33.0
- name: Set up Node.js
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 24
cache: pnpm
- name: Install dependencies
run: pnpm install --frozen-lockfile
# Resolved once, up front, and exported through the job environment. The
# cleanup step runs with `if: always()` even when the cluster was never
# created, so it must not depend on variables set by the step that starts
# it: a failed initdb would otherwise leave PGDATA unset or empty.
- name: Locate PostgreSQL
run: |
set -euo pipefail
# Debian installs the server binaries under /usr/lib/postgresql/<major>/bin
# and only puts the client on PATH, so `initdb` is not found even with
# PostgreSQL 18 installed. Use PATH when it works, otherwise the newest
# installed major version.
if ! command -v initdb >/dev/null 2>&1; then
pg_bindir=''
for dir in /usr/lib/postgresql/*/bin; do
if [ -x "${dir}/initdb" ]; then
pg_bindir="${dir}"
fi
done
if [ -z "${pg_bindir}" ]; then
echo "::error::initdb was not found. Install a PostgreSQL server package on the runner."
exit 1
fi
echo "${pg_bindir}" >> "${GITHUB_PATH}"
fi
echo "PGDATA=${RUNNER_TEMP}/pgdata" >> "${GITHUB_ENV}"
- name: Start a throwaway PostgreSQL cluster
run: |
set -euo pipefail
initdb --version
rm -rf "${PGDATA}"
initdb -D "${PGDATA}" --auth=trust --no-sync
# -k puts the socket in the data directory and `listen_addresses=''`
# keeps it off the network entirely.
pg_ctl -D "${PGDATA}" -l "${PGDATA}/server.log" \
-o "-c listen_addresses='' -k ${PGDATA}" start
createdb -h "${PGDATA}" crate_test
echo "TEST_DATABASE_URL=postgres:///crate_test?host=${PGDATA}" >> "${GITHUB_ENV}"
psql -h "${PGDATA}" -d crate_test -tAc 'select version()'
- name: Apply migrations
run: DATABASE_URL="$TEST_DATABASE_URL" pnpm --filter @t19/server db:migrate
- name: Run the server test suite
# The JSON report is only there for the next step; the default reporter
# still prints the normal output a reader expects.
run: |
pnpm --filter @t19/server exec vitest run \
--reporter=default \
--reporter=json \
--outputFile="${RUNNER_TEMP}/vitest.json"
# A green run is not evidence on its own: without a database every
# PostgreSQL suite skips and vitest still exits 0. See the script header.
- name: Fail if the PostgreSQL tests were skipped
run: node server/scripts/assert-postgres-tests.mjs "${RUNNER_TEMP}/vitest.json"
- name: Remove the cluster
if: always()
run: |
set -uo pipefail
# PGDATA and PATH come from "Locate PostgreSQL", so they are set even
# when initdb or createdb aborted the job before a cluster existed.
if [ -z "${PGDATA:-}" ]; then
echo "PGDATA was never set, so there is no cluster to remove."
exit 0
fi
if [ -f "${PGDATA}/postmaster.pid" ]; then
# Refuse to delete a data directory under a live server: that would
# leave the postmaster running against an unlinked directory.
if ! command -v pg_ctl >/dev/null 2>&1; then
echo "::error::pg_ctl is not on PATH; refusing to delete ${PGDATA} while PostgreSQL may be running."
exit 1
fi
pg_ctl -D "${PGDATA}" -m immediate stop
for _ in $(seq 1 20); do
[ -f "${PGDATA}/postmaster.pid" ] || break
sleep 0.5
done
if [ -f "${PGDATA}/postmaster.pid" ]; then
echo "::error::PostgreSQL did not stop; refusing to delete ${PGDATA}."
exit 1
fi
fi
rm -rf "${PGDATA}"
# Real-browser E2E + axe-core checks against a throwaway seeded PostgreSQL
# cluster, the built API on an ephemeral localhost port (so it never collides
# with the live crate-api service on port 3001), and the built client via
# `vite preview`. Chromium headless shell is reused in a single shared cache
# directory on the runner to keep disk usage minimal on the VM.
e2e:
name: Playwright E2E tests
runs-on: [self-hosted, linux, x64]
steps:
- name: Checkout
uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0
- name: Install pnpm
uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4.3.0
with:
version: 10.33.0
- name: Set up Node.js
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 24
cache: pnpm
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Locate PostgreSQL and configure browser cache
run: |
set -euo pipefail
if ! command -v initdb >/dev/null 2>&1; then
pg_bindir=''
for dir in /usr/lib/postgresql/*/bin; do
if [ -x "${dir}/initdb" ]; then
pg_bindir="${dir}"
fi
done
if [ -z "${pg_bindir}" ]; then
echo "::error::initdb was not found. Install a PostgreSQL server package on the runner."
exit 1
fi
echo "${pg_bindir}" >> "${GITHUB_PATH}"
fi
echo "PGDATA=${RUNNER_TEMP}/pgdata-e2e" >> "${GITHUB_ENV}"
echo "PLAYWRIGHT_BROWSERS_PATH=${HOME}/.cache/ms-playwright" >> "${GITHUB_ENV}"
- name: Start and seed throwaway PostgreSQL cluster
run: |
set -euo pipefail
rm -rf "${PGDATA}"
initdb -D "${PGDATA}" --auth=trust --no-sync
pg_ctl -D "${PGDATA}" -l "${PGDATA}/server.log" \
-o "-c listen_addresses='' -k ${PGDATA}" start
createdb -h "${PGDATA}" crate_e2e
db_url="postgres:///crate_e2e?host=${PGDATA}"
echo "E2E_DATABASE_URL=${db_url}" >> "${GITHUB_ENV}"
DATABASE_URL="${db_url}" pnpm --filter @t19/server db:migrate
DATABASE_URL="${db_url}" pnpm --filter @t19/server db:seed
- name: Build server and client
run: pnpm build
- name: Ensure Playwright Chromium is installed
run: |
set -euo pipefail
# Install only the Chromium headless shell into the single shared
# cache directory. Re-runs skip the download when already present.
pnpm --filter @t19/e2e exec playwright install chromium --only-shell
# Prune older Chromium headless-shell revisions so Playwright upgrades
# do not accumulate and fill the VM's root disk.
if [ -d "${PLAYWRIGHT_BROWSERS_PATH}" ]; then
mapfile -t shells < <(
find "${PLAYWRIGHT_BROWSERS_PATH}" -maxdepth 1 -mindepth 1 -type d \
-name 'chromium_headless_shell-*' \
| sort -Vr
)
if [ "${#shells[@]}" -gt 1 ]; then
for old_shell in "${shells[@]:1}"; do
echo "Pruning stale Playwright browser cache: ${old_shell}"
rm -rf "${old_shell}"
done
fi
fi
- name: Start API, client preview, and run Playwright E2E
run: |
set -euo pipefail
read -r api_port client_port < <(python3 -c 'import socket; s1=socket.socket(); s1.bind(("127.0.0.1",0)); s2=socket.socket(); s2.bind(("127.0.0.1",0)); print(s1.getsockname()[1], s2.getsockname()[1]); s1.close(); s2.close()')
echo "Starting E2E API on 127.0.0.1:${api_port} and client preview on 127.0.0.1:${client_port}"
HOST=127.0.0.1 PORT="${api_port}" DATABASE_URL="${E2E_DATABASE_URL}" \
node server/dist/index.js > "${RUNNER_TEMP}/e2e-api.log" 2>&1 &
echo $! > "${RUNNER_TEMP}/e2e-api.pid"
VITE_API_PROXY_TARGET="http://127.0.0.1:${api_port}" \
pnpm --filter @t19/client exec vite preview --host 127.0.0.1 --port "${client_port}" --strictPort \
> "${RUNNER_TEMP}/e2e-client.log" 2>&1 &
echo $! > "${RUNNER_TEMP}/e2e-client.pid"
api_ready=0
for _ in $(seq 1 30); do
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 2 \
-X POST "http://127.0.0.1:${api_port}/graphql" \
-H 'content-type: application/json' \
-d '{"query":"{ __typename }"}' 2>/dev/null || echo 000)
if [ "${code}" = "200" ]; then
api_ready=1
break
fi
sleep 0.5
done
if [ "${api_ready}" -ne 1 ]; then
echo "::error::E2E API failed to become ready."
cat "${RUNNER_TEMP}/e2e-api.log" || true
exit 1
fi
client_ready=0
for _ in $(seq 1 30); do
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 2 \
"http://127.0.0.1:${client_port}/project2/" 2>/dev/null || echo 000)
if [ "${code}" = "200" ]; then
client_ready=1
break
fi
sleep 0.5
done
if [ "${client_ready}" -ne 1 ]; then
echo "::error::E2E client preview failed to become ready."
cat "${RUNNER_TEMP}/e2e-client.log" || true
exit 1
fi
E2E_BASE_URL="http://127.0.0.1:${client_port}/project2/" pnpm test:e2e
- name: Print E2E server logs on failure
if: failure()
run: |
set -uo pipefail
for logfile in "${RUNNER_TEMP}/e2e-api.log" "${RUNNER_TEMP}/e2e-client.log"; do
if [ -f "${logfile}" ]; then
echo "=== Last 50 lines of ${logfile} ==="
tail -n 50 "${logfile}"
else
echo "=== ${logfile} not found ==="
fi
done
- name: Clean up E2E servers, database, and temporary artifacts
if: always()
run: |
set -uo pipefail
for pidfile in "${RUNNER_TEMP}/e2e-client.pid" "${RUNNER_TEMP}/e2e-api.pid"; do
if [ -f "${pidfile}" ]; then
pid="$(cat "${pidfile}")"
if [ -n "${pid}" ] && kill -0 "${pid}" 2>/dev/null; then
kill "${pid}" 2>/dev/null || true
for _ in $(seq 1 10); do
kill -0 "${pid}" 2>/dev/null || break
sleep 0.2
done
kill -9 "${pid}" 2>/dev/null || true
fi
rm -f "${pidfile}"
fi
done
rm -f "${RUNNER_TEMP}/e2e-api.log" "${RUNNER_TEMP}/e2e-client.log"
rm -rf e2e/test-results e2e/playwright-report
if [ -z "${PGDATA:-}" ]; then
exit 0
fi
if [ -f "${PGDATA}/postmaster.pid" ]; then
if ! command -v pg_ctl >/dev/null 2>&1; then
echo "::error::pg_ctl is not on PATH; refusing to delete ${PGDATA} while PostgreSQL may be running."
exit 1
fi
pg_ctl -D "${PGDATA}" -m immediate stop
for _ in $(seq 1 20); do
[ -f "${PGDATA}/postmaster.pid" ] || break
sleep 0.5
done
if [ -f "${PGDATA}/postmaster.pid" ]; then
echo "::error::PostgreSQL did not stop; refusing to delete ${PGDATA}."
exit 1
fi
fi
rm -rf "${PGDATA}"
deploy:
name: Deploy to the group VM
# All three verification jobs have to pass before touching production.
needs: [quality, integration, e2e]
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
# Pinned to the `project2` label on purpose. This job writes to
# /var/www/html/project2 and restarts crate-api, both of which only exist
# on it2810-19. If a second runner is ever registered to this repo from a
# different machine, this must not land there.
runs-on: [self-hosted, linux, x64, project2]
steps:
- name: Checkout
uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0
- name: Install pnpm
uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4.3.0
with:
version: 10.33.0
- name: Set up Node.js
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 24
cache: pnpm
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Build client
run: pnpm build
# Deploy the API first, then swap the Apache frontend last, under one EXIT
# trap installed at the very top of the step.
#
# Why API first, frontend last:
# - Deploying, migrating, restarting, and verifying the API before touching
# `/var/www/html/project2` avoids serving a new frontend against the old
# API during the server install/build/migration window and keeps rollback
# simpler if the API fails.
#
# Frontend swap semantics:
# - This is a staged directory swap with backup (`.new`/`.prev` siblings,
# or a temp backup fallback if `/var/www/html` is not writable), not a
# strictly atomic rename: two `mv` calls leave a brief swap window.
#
# Forward-only database migration policy (expand first, contract later):
# - Drizzle SQL migrations (`server/drizzle/`) and the in-place MusicBrainz
# import are forward-only and are NOT automatically rolled back. Any
# schema change must stay backward-compatible with the previous release
# (expand in one PR, contract in a later PR). If `server/drizzle/`
# changed and migrations were already applied before a failure, automatic
# API code rollback is skipped and a loud error is emitted for manual
# intervention.
- name: Deploy API, publish frontend, run smoke checks, and roll back on failure
run: |
set -euo pipefail
DEPLOY_ROOT="${HOME}/T19-Project-2"
WEB_ROOT="/var/www/html/project2"
WEB_PARENT="$(dirname "${WEB_ROOT}")"
WEB_NEW="${WEB_ROOT}.new"
PREV_SHA=""
API_TOUCHED=0
MIGRATIONS_CHANGED=0
MIGRATIONS_APPLIED=0
FRONTEND_SWAPPED=0
FRONTEND_SWAP_MODE=""
FRONTEND_PREV=""
DEPLOY_OK=0
wait_for_api() {
local code="000"
printf 'Waiting for the API'
for _ in $(seq 1 30); do
code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 2 \
-X POST http://localhost/graphql \
-H 'content-type: application/json' \
-d '{"query":"{ __typename }"}' 2>/dev/null || echo 000)
if [ "${code}" = "200" ]; then
echo
echo "POST /graphql : 200"
return 0
fi
printf '.'
sleep 1
done
echo
echo "::error::crate-api restarted but /graphql never returned 200 (last code ${code})."
return 1
}
rollback() {
set +e
if [ "${API_TOUCHED}" -eq 0 ] && [ "${FRONTEND_SWAPPED}" -eq 0 ] && [ -z "${FRONTEND_PREV}" ] && [ ! -e "${WEB_NEW}" ]; then
echo "Deploy failed before modifying production state; nothing to roll back."
return 0
fi
echo "::warning::Deploy or smoke check failed; running rollback..."
# Always remove any leftover staging directory.
if [ -e "${WEB_NEW}" ]; then
rm -rf "${WEB_NEW}"
fi
# Roll back the frontend if it was swapped; otherwise remove any
# partial backup directory so `.prev` is never left behind.
if [ "${FRONTEND_SWAPPED}" -eq 1 ]; then
if [ -n "${FRONTEND_PREV}" ] && [ -d "${FRONTEND_PREV}" ]; then
if [ "${FRONTEND_SWAP_MODE}" = "sibling" ]; then
if rm -rf "${WEB_ROOT}" && mv "${FRONTEND_PREV}" "${WEB_ROOT}"; then
echo "Frontend rolled back from ${FRONTEND_PREV}."
else
echo "::error::Rollback failed: could not restore previous frontend from ${FRONTEND_PREV}"
fi
else
if find "${WEB_ROOT}" -mindepth 1 -delete \
&& cp -a "${FRONTEND_PREV}/." "${WEB_ROOT}/" \
&& chmod -R a+rX "${WEB_ROOT}" \
&& rm -rf "${FRONTEND_PREV}"; then
echo "Frontend rolled back from ${FRONTEND_PREV}."
else
echo "::error::Rollback failed: could not restore previous frontend from ${FRONTEND_PREV}"
fi
fi
fi
elif [ -n "${FRONTEND_PREV}" ] && [ -e "${FRONTEND_PREV}" ]; then
rm -rf "${FRONTEND_PREV}"
fi
if [ "${API_TOUCHED}" -eq 1 ]; then
if [ "${MIGRATIONS_APPLIED}" -eq 1 ] && [ "${MIGRATIONS_CHANGED}" -eq 1 ]; then
echo "::error::Database migrations changed and were already applied; skipping automatic API code rollback — manual intervention required"
elif [ -n "${PREV_SHA}" ]; then
echo "Rolling back API in ${DEPLOY_ROOT} to ${PREV_SHA}"
if ! (
git -C "${DEPLOY_ROOT}" checkout --force "${PREV_SHA}" \
&& pnpm install --dir "${DEPLOY_ROOT}" --frozen-lockfile \
&& pnpm --dir "${DEPLOY_ROOT}" --filter @t19/server build \
&& sudo /usr/bin/systemctl restart crate-api \
&& wait_for_api
); then
echo "::error::Rollback failed, crate-api may be down"
fi
fi
fi
}
on_exit() {
local status=$?
if [ "${DEPLOY_OK}" -ne 1 ]; then
rollback
if [ "${status}" -ne 0 ]; then
exit "${status}"
fi
exit 1
fi
}
trap on_exit EXIT
# #42 has landed, so `server/` is expected and the unit is expected
# to exist. These used to skip, which meant the deploy job could go
# green without deploying anything. rachelks on #45: that is the
# wrong failure mode.
if [ ! -f /etc/systemd/system/crate-api.service ]; then
echo "::error::crate-api.service is not installed on this machine."
exit 1
fi
if [ ! -d server ]; then
echo "::error::server/ is missing from the checkout."
exit 1
fi
if [ ! -d "${DEPLOY_ROOT}/.git" ]; then
echo "::error::${DEPLOY_ROOT} is not a git clone. See #44."
exit 1
fi
PREV_SHA="$(git -C "${DEPLOY_ROOT}" rev-parse HEAD)"
echo "Deploying ${GITHUB_SHA} to ${DEPLOY_ROOT} (previous HEAD: ${PREV_SHA})"
git -C "${DEPLOY_ROOT}" fetch --quiet origin
if [ -n "$(git -C "${DEPLOY_ROOT}" diff --name-only "${PREV_SHA}" "${GITHUB_SHA}" -- server/drizzle/)" ]; then
MIGRATIONS_CHANGED=1
echo "Detected migration changes in server/drizzle/ between ${PREV_SHA} and ${GITHUB_SHA}."
fi
# --force so a dirty tree cannot block the deploy. .env is gitignored
# and so survives the checkout; it holds DATABASE_URL.
API_TOUCHED=1
git -C "${DEPLOY_ROOT}" checkout --force "${GITHUB_SHA}"
echo " at $(git -C "${DEPLOY_ROOT}" rev-parse --short HEAD)"
if [ ! -f "${DEPLOY_ROOT}/.env" ]; then
echo "::error::${DEPLOY_ROOT}/.env is missing. crate-api will not start without DATABASE_URL."
exit 1
fi
pnpm install --dir "${DEPLOY_ROOT}" --frozen-lockfile
pnpm --dir "${DEPLOY_ROOT}" --filter @t19/server build
if [ ! -f "${DEPLOY_ROOT}/server/dist/index.js" ]; then
echo "::error::server built but server/dist/index.js is missing."
exit 1
fi
# `db:migrate` is idempotent (verified on #46), so this runs on every
# deploy and not only when the migration list changes.
echo
echo "Applying database migrations"
db_url="$(sed -n 's/^DATABASE_URL=//p' "${DEPLOY_ROOT}/.env" | tail -n 1)"
if [ -z "${db_url}" ]; then
echo "::error::DATABASE_URL is not set in ${DEPLOY_ROOT}/.env, so migrations cannot run."
exit 1
fi
MIGRATIONS_APPLIED=1
DATABASE_URL="${db_url}" pnpm --dir "${DEPLOY_ROOT}" --filter @t19/server db:migrate
# #63 ships the reproducible real-album snapshot. Import it on deploy
# so the application catalog is present on the VM as well as locally.
# The importer is idempotent and preserves album IDs and user data.
echo
echo "Importing the MusicBrainz catalog snapshot"
DATABASE_URL="${db_url}" pnpm --dir "${DEPLOY_ROOT}" --filter @t19/server db:import:musicbrainz
sudo /usr/bin/systemctl restart crate-api
wait_for_api
# Verify the API through the same Apache proxy the browser uses before
# swapping the frontend. This is the acceptance line of #6.
echo
echo "API smoke suite:"
CHECK_BODY='import json,sys; p=json.load(sys.stdin); e=p.get("errors"); n=p.get("data"); print(f"errors: {e}" if e else (f"no data: {p}" if n is None else "")); sys.exit(1 if (e or n is None) else 0)'
check() {
local label="$1" body="$2" resp code json detail
resp=$(curl -s -X POST http://localhost/graphql \
-H 'content-type: application/json' \
-d "${body}" -w '\n%{http_code}')
code="${resp##*$'\n'}"
json="${resp%$'\n'*}"
if [ "${code}" != "200" ]; then
echo "::error::${label}: HTTP ${code} body: ${json}"
return 1
fi
detail=$(printf '%s' "${json}" | python3 -c "${CHECK_BODY}" 2>&1) || {
echo "::error::${label}: ${detail:-body check failed} body: ${json}"
return 1
}
printf ' %-22s %s ok\n' "${label}" "${code}"
}
check '{ __typename }' '{"query":"{ __typename }"}'
check 'searchAlbums' '{"query":"{ searchAlbums(input:{query:\"\",sort:TITLE_ASC},first:1){totalCount pageInfo{hasNextPage}} }"}'
CHECK_TOTAL='import json,sys; p=json.load(sys.stdin); t=p["data"]["searchAlbums"]["totalCount"]; print(t) if isinstance(t,int) and t>=0 else sys.exit(f"totalCount is not a non-negative integer: {t!r}")'
totals=$(curl -s -X POST http://localhost/graphql \
-H 'content-type: application/json' \
-d '{"query":"{ searchAlbums(input:{query:\"\",sort:TITLE_ASC},first:1){totalCount} }"}')
if total=$(printf '%s' "${totals}" | python3 -c "${CHECK_TOTAL}" 2>&1); then
echo " totalCount ${total} albums"
else
echo "::error::totalCount assertion failed: ${total} body: ${totals}"
exit 1
fi
# Publish the frontend last via a staged directory swap with backup.
echo
echo "Publishing frontend to ${WEB_ROOT} (staged directory swap with backup)"
if [ -w "${WEB_PARENT}" ]; then
FRONTEND_SWAP_MODE="sibling"
FRONTEND_PREV="${WEB_ROOT}.prev"
rm -rf "${WEB_NEW}" "${FRONTEND_PREV}"
mkdir -p "${WEB_NEW}"
cp -r client/dist/. "${WEB_NEW}/"
chmod -R a+rX "${WEB_NEW}"
if [ -d "${WEB_ROOT}" ]; then
FRONTEND_SWAPPED=1
mv "${WEB_ROOT}" "${FRONTEND_PREV}"
fi
FRONTEND_SWAPPED=1
mv "${WEB_NEW}" "${WEB_ROOT}"
else
echo "::warning::${WEB_PARENT} is not writable; using temp backup for rollback."
FRONTEND_SWAP_MODE="copy"
FRONTEND_PREV="${RUNNER_TEMP}/project2.prev"
rm -rf "${FRONTEND_PREV}"
if [ -d "${WEB_ROOT}" ]; then
cp -a "${WEB_ROOT}" "${FRONTEND_PREV}"
fi
FRONTEND_SWAPPED=1
find "${WEB_ROOT}" -mindepth 1 -delete
cp -r client/dist/. "${WEB_ROOT}/"
chmod -R a+rX "${WEB_ROOT}"
fi
echo "Frontend smoke checks:"
if curl -fsS -o /dev/null http://localhost/project2/; then
echo " GET /project2/ 200 ok"
else
echo "::error::GET /project2/ failed"
exit 1
fi
# Client-side routes must fall back to index.html (#82). Without the
# FallbackResource in docs/VM-setup.md this is an Apache 404.
if curl -fsS -o /dev/null http://localhost/project2/album/1; then
echo " GET /project2/album/1 200 ok"
else
echo "::error::GET /project2/album/1 failed: Apache has no SPA fallback (#82)"
exit 1
fi
DEPLOY_OK=1
# Remove the previous frontend backup only once all checks pass.
if [ -n "${FRONTEND_PREV}" ] && [ -d "${FRONTEND_PREV}" ]; then
rm -rf "${FRONTEND_PREV}"
fi