diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index bf8abb0..e7d30e1 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1,5 +1,14 @@
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
@@ -11,7 +20,8 @@ on:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
- cancel-in-progress: true
+ # Cancel superseded PR runs, but never cancel an in-progress push/deploy on main.
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
quality:
@@ -22,15 +32,15 @@ jobs:
runs-on: [self-hosted, linux, x64]
steps:
- name: Checkout
- uses: actions/checkout@v4
+ uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0
- name: Install pnpm
- uses: pnpm/action-setup@v4
+ uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4.3.0
with:
version: 10.33.0
- name: Set up Node.js
- uses: actions/setup-node@v4
+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 24
cache: pnpm
@@ -107,15 +117,15 @@ jobs:
runs-on: [self-hosted, linux, x64]
steps:
- name: Checkout
- uses: actions/checkout@v4
+ uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0
- name: Install pnpm
- uses: pnpm/action-setup@v4
+ uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4.3.0
with:
version: 10.33.0
- name: Set up Node.js
- uses: actions/setup-node@v4
+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 24
cache: pnpm
@@ -209,11 +219,198 @@ jobs:
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
- # Both jobs have to pass. Deploying with the database layer untested is the
- # same gap as deploying a server that was never built (#44).
- needs: [quality, integration]
+ # 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
@@ -222,15 +419,15 @@ jobs:
runs-on: [self-hosted, linux, x64, project2]
steps:
- name: Checkout
- uses: actions/checkout@v4
+ uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0
- name: Install pnpm
- uses: pnpm/action-setup@v4
+ uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4.3.0
with:
version: 10.33.0
- name: Set up Node.js
- uses: actions/setup-node@v4
+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 24
cache: pnpm
@@ -241,43 +438,134 @@ jobs:
- name: Build client
run: pnpm build
- - name: Publish to Apache
- run: |
- set -euo pipefail
- find /var/www/html/project2 -mindepth 1 -delete
- cp -r client/dist/. /var/www/html/project2/
- chmod -R a+rX /var/www/html/project2
- curl -fsS -o /dev/null -w 'GET /project2/ : %{http_code}\n' http://localhost/project2/
- # Client-side routes must fall back to index.html (#82). Without the
- # FallbackResource in docs/VM-setup.md this is an Apache 404.
- curl -fsS -o /dev/null -w 'GET /project2/album/1 : %{http_code}\n' http://localhost/project2/album/1
-
- # Deploy the API. The unit runs `node dist/index.js` out of
- # ~/T19-Project-2/server, so that directory has to hold the build of the
- # commit we just tested. It is a git clone of main (see #44), so point it
- # at $GITHUB_SHA rather than copying files around, then install and build
- # there.
+ # Deploy the API first, then swap the Apache frontend last, under one EXIT
+ # trap installed at the very top of the step.
#
- # Deliberately not what earlier versions did:
+ # 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.
#
- # - The unit check is `[ -f ... ]`, not `systemctl list-unit-files | grep`.
- # `grep -q` exits on the first match and closes the pipe, `systemctl`
- # gets SIGPIPE and dies, and with `pipefail` the whole pipeline reports
- # failure. So the `if` took the else branch and skipped a service that
- # was definitely there. The log said "Failed to print table: Broken
- # pipe". Reported by rachelks.
+ # 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.
#
- # - The restart needs `sudo` and the runner has no TTY. That needs a
- # NOPASSWD rule scoped to exactly these commands. Without it the step
- # dies with "sudo: A terminal is required to authenticate".
- #
- # - No `sleep`. `Type=simple` reports active before Node binds the port.
- # Measured at about 1850 ms, so a fixed `sleep 2` has already produced a
- # 503 through Apache. Poll instead.
- - name: Deploy the API and restart crate-api
+ # 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
@@ -296,10 +584,18 @@ jobs:
exit 1
fi
- echo "Deploying ${GITHUB_SHA} to ${DEPLOY_ROOT}"
+ 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)"
@@ -316,20 +612,8 @@ jobs:
exit 1
fi
- # #5 landed migrations for tracks, simulated users, reviews and crate
- # items. A deploy that lands new migration files and never applies
- # them is the same gap as #44, one layer down: the code is current
- # and the schema is not. Migrate before the restart so the new build
- # is never pointed at an old database.
- #
# `db:migrate` is idempotent (verified on #46), so this runs on every
# deploy and not only when the migration list changes.
- #
- # DATABASE_URL comes from the same .env the systemd unit loads. The
- # server package scripts look for `server/.env` instead, which may
- # not exist here, so export it explicitly rather than assuming the
- # two agree. Node's --env-file does not override a variable already
- # in the environment, so this wins even if server/.env is present.
echo
echo "Applying database migrations"
db_url="$(sed -n 's/^DATABASE_URL=//p' "${DEPLOY_ROOT}/.env" | tail -n 1)"
@@ -337,6 +621,7 @@ jobs:
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
@@ -347,44 +632,15 @@ jobs:
DATABASE_URL="${db_url}" pnpm --dir "${DEPLOY_ROOT}" --filter @t19/server db:import:musicbrainz
sudo /usr/bin/systemctl restart crate-api
+ wait_for_api
- 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"
- break
- fi
- printf '.'
- sleep 1
- done
- if [ "${code:-000}" != "200" ]; then
- echo
- echo "::error::crate-api restarted but /graphql never returned 200 (last code ${code})."
- exit 1
- fi
-
- # Smoke suite, against the real port and through the same Apache
- # proxy the browser uses. This is the acceptance line of #6.
- #
- # GraphQL answers HTTP 200 even when the payload carries errors, so
- # the status code alone proves nothing (rachelks on #45). The body is
- # parsed as JSON and rejected unless it has a non-null `data` and no
- # `errors`, rather than grepping for the word "errors", which would
- # also fire on an album called "Errors".
- #
- # The validators live in shell variables on one line. A multi-line
- # python -c heredoc cannot be used here: the YAML block scalar would
- # end at the first unindented line and the workflow would not parse.
+ # Verify the API through the same Apache proxy the browser uses before
+ # swapping the frontend. This is the acceptance line of #6.
echo
- echo "Smoke suite:"
+ 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
+ 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}')
@@ -402,12 +658,8 @@ jobs:
}
check '{ __typename }' '{"query":"{ __typename }"}'
- # `sort` is `AlbumSort!` in AlbumSearchInput, so leaving it out makes
- # the query fail validation. That was a real bug in the first version
- # of this check.
check 'searchAlbums' '{"query":"{ searchAlbums(input:{query:\"\",sort:TITLE_ASC},first:1){totalCount pageInfo{hasNextPage}} }"}'
- # One assertion on the data itself, not just its presence.
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' \
@@ -419,16 +671,54 @@ jobs:
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
diff --git a/client/src/a11y.test.tsx b/client/src/a11y.test.tsx
index c2b81cd..53e3eac 100644
--- a/client/src/a11y.test.tsx
+++ b/client/src/a11y.test.tsx
@@ -1,4 +1,4 @@
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, vi } from 'vitest';
import { act, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MockedProvider } from '@apollo/client/testing/react';
@@ -7,6 +7,13 @@ import { GraphQLError } from 'graphql';
import axe from 'axe-core';
import App from './App.js';
+import AlbumDetailPage from './pages/AlbumDetailPage.js';
+import CratePage from './pages/CratePage.js';
+import ReviewForm from './components/ReviewForm.js';
+import { ALBUM_DETAIL } from './api/albumDetail.js';
+import { MY_CRATE } from './api/crate.js';
+import { UPSERT_REVIEW } from './api/reviews.js';
+import { MY_SEARCH_HISTORY } from './api/searchHistory.js';
import { searchHistoryMocks } from './test/searchHistoryMocks.js';
import { SEARCH_ALBUMS } from './api/searchAlbums.js';
import type {
@@ -193,4 +200,187 @@ describe('axe-core on the search page', () => {
act(() => target!.focus());
expect(target).toHaveFocus();
});
+
+ it('is clean with the recent-searches combobox open and an option active', async () => {
+ const historyMock: MockLink.MockedResponse = {
+ request: { query: MY_SEARCH_HISTORY },
+ result: {
+ data: {
+ mySearchHistory: [
+ { query: 'Blue', lastSearchedAt: '2026-11-10T12:00:00Z' },
+ { query: 'Abbey Road', lastSearchedAt: '2026-11-09T12:00:00Z' },
+ ],
+ },
+ },
+ maxUsageCount: Number.POSITIVE_INFINITY,
+ };
+
+ const { container } = render(
+
+
+ ,
+ );
+ await waitForQueries();
+
+ const user = userEvent.setup();
+ const combobox = screen.getByRole('combobox', { name: 'Search by album or artist' });
+ await user.click(combobox);
+ await user.keyboard('{ArrowDown}');
+
+ expect(screen.getByRole('listbox', { name: 'Recent searches' })).toBeInTheDocument();
+ expect(screen.getByRole('option', { name: 'Blue' })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ await expectNoViolations(container);
+ });
+});
+
+describe('axe-core across detail, crate, and review form error states', () => {
+ const albumDetailMock: MockLink.MockedResponse = {
+ request: {
+ query: ALBUM_DETAIL,
+ variables: { id: '1', reviewFirst: 10, reviewAfter: null },
+ },
+ result: {
+ data: {
+ album: {
+ id: '1',
+ title: 'Abbey Road',
+ releaseYear: 1969,
+ musicBrainzReleaseGroupId: null,
+ artists: [{ id: '1', name: 'The Beatles' }],
+ genres: [{ id: '1', name: 'Rock' }],
+ tracks: [
+ { id: '1', title: 'Come Together', trackNumber: 1, durationSeconds: 259 },
+ { id: '2', title: 'Something', trackNumber: 2, durationSeconds: null },
+ ],
+ averageRating: 4.8,
+ reviewCount: 1,
+ isInCrate: false,
+ myReview: null,
+ reviews: {
+ edges: [
+ {
+ cursor: 'cursor-1',
+ node: {
+ id: '1',
+ rating: 5,
+ comment: 'Timeless record.',
+ createdAt: '2026-10-20T12:00:00.000Z',
+ user: { displayName: 'Velvet Groove' },
+ },
+ },
+ ],
+ totalCount: 1,
+ pageInfo: { hasNextPage: false, endCursor: 'cursor-1' },
+ },
+ },
+ },
+ },
+ };
+
+ it('is clean on AlbumDetailPage with tracklist, reviews, and review form', async () => {
+ const { container } = render(
+
+
+ ,
+ );
+
+ await screen.findByRole('heading', { level: 1, name: 'Abbey Road' });
+ await expectNoViolations(container);
+ });
+
+ it('is clean on CratePage when populated and when empty', async () => {
+ const populatedMock: MockLink.MockedResponse = {
+ request: { query: MY_CRATE, variables: { first: 20, after: null } },
+ result: {
+ data: {
+ myCrate: {
+ edges: [
+ {
+ cursor: 'cursor-0',
+ node: {
+ __typename: 'CrateItem',
+ id: '10',
+ addedAt: '2026-11-01T12:00:00.000Z',
+ album: { ...album, __typename: 'Album', isInCrate: true },
+ },
+ },
+ ],
+ pageInfo: { hasNextPage: false, endCursor: 'cursor-0' },
+ totalCount: 1,
+ },
+ },
+ },
+ };
+ const emptyMock: MockLink.MockedResponse = {
+ request: { query: MY_CRATE, variables: { first: 20, after: null } },
+ result: {
+ data: {
+ myCrate: {
+ edges: [],
+ pageInfo: { hasNextPage: false, endCursor: null },
+ totalCount: 0,
+ },
+ },
+ },
+ };
+
+ const populated = render(
+
+
+ ,
+ );
+ await screen.findByRole('heading', { level: 3, name: 'Abbey Road' });
+ await expectNoViolations(populated.container);
+ populated.unmount();
+
+ const empty = render(
+
+
+ ,
+ );
+ await screen.findByRole('heading', { level: 2, name: 'Nothing saved yet' });
+ await expectNoViolations(empty.container);
+ });
+
+ it('is clean when ReviewForm shows validation and mutation error states', async () => {
+ const user = userEvent.setup();
+ const { container } = render(
+
+
+
Abbey Road
+
Ratings & reviews
+ {})} />
+
+ ,
+ );
+
+ // Client-side validation error (no rating selected).
+ await user.click(screen.getByRole('button', { name: 'Publish review' }));
+ expect(screen.getByRole('alert')).toHaveTextContent(
+ 'Choose a rating from 1 to 5 stars.',
+ );
+ await expectNoViolations(container);
+
+ // Server/network error state.
+ await user.click(screen.getByRole('radio', { name: '4 stars' }));
+ await user.type(screen.getByRole('textbox', { name: /Comment/ }), 'Nice');
+ await user.click(screen.getByRole('button', { name: 'Publish review' }));
+ expect(await screen.findByRole('alert')).toHaveTextContent(
+ 'Your review could not be saved. Please try again.',
+ );
+ await expectNoViolations(container);
+ });
});
diff --git a/client/src/test/setup.ts b/client/src/test/setup.ts
index e2a0e9b..5678d01 100644
--- a/client/src/test/setup.ts
+++ b/client/src/test/setup.ts
@@ -2,15 +2,19 @@ import '@testing-library/jest-dom/vitest';
import { cleanup } from '@testing-library/react';
import { afterEach, beforeEach } from 'vitest';
-// The URL is application state, not a browser detail: useSearchState reads it
-// and writes it. Tests render a mounted app, so each one has to start from a
-// known query string or the previous test's search leaks into the next.
+// The URL and Web Storage are application state, not browser details:
+// useSearchState, userIdentity and searchReturnState read and write them.
+// Reset all three around each test so state cannot leak across tests.
beforeEach(() => {
+ window.localStorage.clear();
+ window.sessionStorage.clear();
window.history.replaceState({}, '', '/');
});
afterEach(() => {
cleanup();
+ window.localStorage.clear();
+ window.sessionStorage.clear();
window.history.replaceState({}, '', '/');
});
diff --git a/client/vite.config.ts b/client/vite.config.ts
index 5f22a29..86d8747 100644
--- a/client/vite.config.ts
+++ b/client/vite.config.ts
@@ -1,6 +1,8 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
+const apiProxyTarget = process.env.VITE_API_PROXY_TARGET || 'http://127.0.0.1:3001';
+
export default defineConfig({
plugins: [react()],
// The course VM serves the built app from /project2.
@@ -9,7 +11,7 @@ export default defineConfig({
port: 5173,
proxy: {
// Matches Apache's production /graphql route; the local API uses port 3001.
- '/graphql': 'http://127.0.0.1:3001',
+ '/graphql': apiProxyTarget,
},
},
});
diff --git a/e2e/playwright.config.ts b/e2e/playwright.config.ts
index 00a603c..db22172 100644
--- a/e2e/playwright.config.ts
+++ b/e2e/playwright.config.ts
@@ -1,14 +1,32 @@
+import os from 'node:os';
import { defineConfig, devices } from '@playwright/test';
/**
- * The tests run against a stack that is already up: client, API and a database
- * loaded with `pnpm db:seed`. Nothing here starts servers, so the same tests can
- * point at a local dev stack or any other deployment through E2E_BASE_URL.
+ * The tests run against a stack seeded with `pnpm db:seed`.
+ *
+ * When `E2E_BASE_URL` is set (for example in CI or against a staging server),
+ * Playwright connects directly to that URL without starting servers. When
+ * `E2E_BASE_URL` is unset, `webServer` reuses an already-running local dev
+ * stack or starts the API and Vite dev server automatically.
*
* The base URL must end with a slash so that `page.goto('./')` and relative
* paths resolve under /project2/.
*/
-const baseURL = process.env.E2E_BASE_URL ?? 'http://localhost:5173/project2/';
+const customBaseURL = process.env.E2E_BASE_URL;
+const hostname = os.hostname();
+
+// Guard against accidentally running local `webServer` (which reuses port 3001)
+// on the production VM (`it2810-19`), where live `crate-api` listens on 3001
+// backed by the production database.
+if (!customBaseURL && (hostname === 'it2810-19' || hostname.startsWith('it2810-19.'))) {
+ throw new Error(
+ 'Refusing to start or reuse local webServer on it2810-19 without E2E_BASE_URL: ' +
+ 'port 3001 is used by live crate-api against the production database. ' +
+ 'Set E2E_BASE_URL to an isolated test stack instead.',
+ );
+}
+
+const baseURL = customBaseURL ?? 'http://localhost:5173/project2/';
export default defineConfig({
testDir: './tests',
@@ -22,5 +40,21 @@ export default defineConfig({
baseURL: baseURL.endsWith('/') ? baseURL : `${baseURL}/`,
trace: 'retain-on-failure',
},
+ webServer: customBaseURL
+ ? undefined
+ : [
+ {
+ command: 'pnpm --filter @t19/server dev',
+ port: 3001,
+ cwd: '..',
+ reuseExistingServer: !process.env.CI,
+ },
+ {
+ command: 'pnpm --filter @t19/client dev',
+ url: 'http://localhost:5173/project2/',
+ cwd: '..',
+ reuseExistingServer: !process.env.CI,
+ },
+ ],
projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
});
diff --git a/e2e/tests/a11y.spec.ts b/e2e/tests/a11y.spec.ts
index 59669ea..8dad549 100644
--- a/e2e/tests/a11y.spec.ts
+++ b/e2e/tests/a11y.spec.ts
@@ -1,6 +1,8 @@
import AxeBuilder from '@axe-core/playwright';
import { expect, test, type Page } from '@playwright/test';
+import { clearUserCrate, clearUserSearchHistory } from './cleanup.js';
+
/**
* axe-core in a real browser. Unlike the jsdom checks in the client unit tests,
* this sees real layout and computed colours, so colour contrast is included.
@@ -36,9 +38,129 @@ test('empty results have no axe violations', async ({ page }) => {
await expectNoViolations(page);
});
+const USER_ID_STORAGE_KEY = 'crate.user-id';
+const A11Y_E2E_USER_ID = '00000000-0000-4000-8000-00000000a11e';
+
test('album detail page has no axe violations', async ({ page }) => {
await page.goto('./?q=abbey');
await page.getByRole('link', { name: 'Abbey Road' }).click();
await expect(page.getByRole('heading', { level: 1, name: 'Abbey Road' })).toBeVisible();
await expectNoViolations(page);
});
+
+test('crate page has no axe violations when empty or populated', async ({
+ page,
+ request,
+}) => {
+ await clearUserCrate(request, A11Y_E2E_USER_ID);
+ await page.addInitScript(([key, id]) => window.localStorage.setItem(key, id), [
+ USER_ID_STORAGE_KEY,
+ A11Y_E2E_USER_ID,
+ ] as const);
+
+ // Ensure empty state first and scan it.
+ await page.goto('./crate');
+ await expect(page.getByRole('heading', { level: 1, name: 'Your crate' })).toBeVisible();
+ await expect(page.getByText('Your crate is empty.')).toBeVisible();
+ await expectNoViolations(page);
+
+ // Add an album, scan populated /crate, and clean up.
+ await page.goto('./?q=abbey');
+ const card = page
+ .getByRole('region', { name: 'Search results' })
+ .getByRole('listitem')
+ .filter({ hasText: 'Abbey Road' });
+ await card.getByRole('button', { name: 'Add to crate: Abbey Road' }).click();
+ await expect(
+ card.getByRole('button', { name: 'Remove from crate: Abbey Road' }),
+ ).toBeVisible();
+
+ await page.goto('./crate');
+ await expect(page.getByRole('heading', { level: 3, name: 'Abbey Road' })).toBeVisible();
+ await expectNoViolations(page);
+
+ await page.getByRole('button', { name: 'Remove from crate: Abbey Road' }).click();
+ await expect(page.getByText('Your crate is empty.')).toBeVisible();
+});
+
+test('dark mode views have no axe violations', async ({ page }) => {
+ await page.emulateMedia({ colorScheme: 'dark' });
+
+ await page.goto('./');
+ await expect(page.getByRole('heading', { level: 1 })).toBeVisible();
+ await expectNoViolations(page);
+
+ await page.goto('./?q=blue');
+ await expect(page.getByRole('status').filter({ hasText: 'Showing' })).toBeVisible();
+ await expectNoViolations(page);
+
+ await page.goto('./?q=abbey');
+ await page.getByRole('link', { name: 'Abbey Road' }).click();
+ await expect(page.getByRole('heading', { level: 1, name: 'Abbey Road' })).toBeVisible();
+ await expectNoViolations(page);
+
+ await page.goto('./crate');
+ await expect(page.getByRole('heading', { level: 1, name: 'Your crate' })).toBeVisible();
+ await expect(page.getByRole('status')).not.toHaveText(/Loading your crate/);
+ await expectNoViolations(page);
+});
+
+test('mobile viewport views have no axe violations', async ({ page }) => {
+ await page.setViewportSize({ width: 390, height: 844 });
+
+ await page.goto('./');
+ await expect(page.getByRole('heading', { level: 1 })).toBeVisible();
+ await expectNoViolations(page);
+
+ await page.goto('./?q=blue');
+ await expect(page.getByRole('status').filter({ hasText: 'Showing' })).toBeVisible();
+ await page.getByRole('button', { name: 'Filters' }).click();
+ await expect(page.getByRole('dialog', { name: 'Refine albums' })).toBeVisible();
+ await expectNoViolations(page);
+ await page.keyboard.press('Escape');
+
+ await page.goto('./?q=abbey');
+ await page.getByRole('link', { name: 'Abbey Road' }).click();
+ await expect(page.getByRole('heading', { level: 1, name: 'Abbey Road' })).toBeVisible();
+ await expectNoViolations(page);
+
+ await page.goto('./crate');
+ await expect(page.getByRole('heading', { level: 1, name: 'Your crate' })).toBeVisible();
+ await expect(page.getByRole('status')).not.toHaveText(/Loading your crate/);
+ await expectNoViolations(page);
+});
+
+test('open search-history combobox has no axe violations', async ({ page, request }) => {
+ await clearUserSearchHistory(request, A11Y_E2E_USER_ID);
+ await page.addInitScript(([key, id]) => window.localStorage.setItem(key, id), [
+ USER_ID_STORAGE_KEY,
+ A11Y_E2E_USER_ID,
+ ] as const);
+
+ await page.goto('./');
+ const combobox = page.getByRole('combobox', { name: 'Search by album or artist' });
+ await combobox.fill('abbey');
+ await page.getByRole('button', { name: 'Search', exact: true }).click();
+ await expect(page.getByRole('link', { name: 'Abbey Road' })).toBeVisible();
+
+ await combobox.click();
+ await expect(page.getByRole('listbox', { name: 'Recent searches' })).toBeVisible();
+ await page.keyboard.press('ArrowDown');
+ await expectNoViolations(page);
+
+ // Clean up recorded search.
+ await page.getByRole('button', { name: 'Clear recent searches', exact: true }).click();
+ await expect(page.getByRole('status', { name: 'Search history status' })).toHaveText(
+ 'Recent searches cleared.',
+ );
+});
+
+test('ReviewForm error state has no axe violations', async ({ page }) => {
+ await page.goto('./?q=abbey');
+ await page.getByRole('link', { name: 'Abbey Road' }).click();
+ await expect(page.getByRole('heading', { level: 1, name: 'Abbey Road' })).toBeVisible();
+
+ await page.getByRole('button', { name: 'Publish review' }).click();
+ await expect(page.getByRole('alert')).toHaveText('Choose a rating from 1 to 5 stars.');
+ await expectNoViolations(page);
+});
diff --git a/e2e/tests/cleanup.ts b/e2e/tests/cleanup.ts
new file mode 100644
index 0000000..b71fa56
--- /dev/null
+++ b/e2e/tests/cleanup.ts
@@ -0,0 +1,150 @@
+import { expect, type APIRequestContext } from '@playwright/test';
+
+type GraphQLResponse = {
+ data?: T;
+ errors?: Array<{ message: string }>;
+};
+
+async function graphql(
+ request: APIRequestContext,
+ userId: string,
+ query: string,
+ variables?: Record,
+): Promise {
+ const response = await request.post('/graphql', {
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-User-Id': userId,
+ },
+ data: { query, variables },
+ });
+ expect(response.ok(), `GraphQL cleanup HTTP ${response.status()}`).toBe(true);
+ const body = (await response.json()) as GraphQLResponse;
+ expect(body.errors ?? [], 'Unexpected GraphQL errors during E2E cleanup').toEqual([]);
+ if (!body.data) {
+ throw new Error('GraphQL cleanup response contained no data.');
+ }
+ return body.data;
+}
+
+/**
+ * Deletes any leftover review written by `userId` on the album with the given
+ * exact title so tests start deterministically even against a reused database.
+ */
+export async function clearUserReview(
+ request: APIRequestContext,
+ userId: string,
+ albumTitle: string,
+): Promise {
+ const search = await graphql<{
+ searchAlbums: {
+ edges: Array<{
+ node: { id: string; title: string; myReview: { id: string } | null };
+ }>;
+ };
+ }>(
+ request,
+ userId,
+ `
+ query CleanupFindReview($query: String!) {
+ searchAlbums(input: { query: $query, sort: TITLE_ASC }, first: 20) {
+ edges {
+ node {
+ id
+ title
+ myReview {
+ id
+ }
+ }
+ }
+ }
+ }
+ `,
+ { query: albumTitle },
+ );
+
+ for (const edge of search.searchAlbums.edges) {
+ if (edge.node.title === albumTitle && edge.node.myReview) {
+ await graphql(
+ request,
+ userId,
+ `
+ mutation CleanupDeleteReview($id: ID!) {
+ deleteReview(id: $id) {
+ deletedReviewId
+ }
+ }
+ `,
+ { id: edge.node.myReview.id },
+ );
+ }
+ }
+}
+
+/**
+ * Removes every album saved in `userId`'s crate across all pages via GraphQL
+ * so tests never rely on racy UI click loops against a reused database.
+ */
+export async function clearUserCrate(
+ request: APIRequestContext,
+ userId: string,
+): Promise {
+ for (let guard = 0; guard < 20; guard += 1) {
+ const data = await graphql<{
+ myCrate: {
+ edges: Array<{ node: { album: { id: string } } }>;
+ };
+ }>(
+ request,
+ userId,
+ `
+ query CleanupCrate {
+ myCrate(first: 50) {
+ edges {
+ node {
+ album {
+ id
+ }
+ }
+ }
+ }
+ }
+ `,
+ );
+
+ if (data.myCrate.edges.length === 0) return;
+
+ for (const edge of data.myCrate.edges) {
+ await graphql(
+ request,
+ userId,
+ `
+ mutation CleanupRemoveFromCrate($albumId: ID!) {
+ removeFromCrate(albumId: $albumId) {
+ removedAlbumId
+ }
+ }
+ `,
+ { albumId: edge.node.album.id },
+ );
+ }
+ }
+}
+
+/**
+ * Clears any saved search history for `userId` via GraphQL.
+ */
+export async function clearUserSearchHistory(
+ request: APIRequestContext,
+ userId: string,
+): Promise {
+ await graphql(
+ request,
+ userId,
+ `
+ mutation CleanupSearchHistory {
+ clearSearchHistory
+ }
+ `,
+ );
+}
diff --git a/e2e/tests/crate.spec.ts b/e2e/tests/crate.spec.ts
new file mode 100644
index 0000000..214d665
--- /dev/null
+++ b/e2e/tests/crate.spec.ts
@@ -0,0 +1,59 @@
+import { expect, test } from '@playwright/test';
+
+import { clearUserCrate } from './cleanup.js';
+
+/**
+ * End-to-end tests for Your Crate persistence against `pnpm db:seed`.
+ * Uses a dedicated fixed simulated user id and removes any leftover items via
+ * GraphQL before running so repeated runs against a reused DB are deterministic.
+ */
+const USER_ID_STORAGE_KEY = 'crate.user-id';
+const CRATE_E2E_USER_ID = '00000000-0000-4000-8000-000000000c2a';
+
+test('add album to crate, verify on /crate across reload, and remove it', async ({
+ page,
+ request,
+}) => {
+ await clearUserCrate(request, CRATE_E2E_USER_ID);
+ await page.addInitScript(([key, id]) => window.localStorage.setItem(key, id), [
+ USER_ID_STORAGE_KEY,
+ CRATE_E2E_USER_ID,
+ ] as const);
+
+ await page.goto('./crate');
+ await expect(page.getByRole('heading', { level: 1, name: 'Your crate' })).toBeVisible();
+ await expect(page.getByText('Your crate is empty.')).toBeVisible();
+
+ // Search for an album and save it from the search results.
+ await page.goto('./?q=abbey');
+ const results = page.getByRole('region', { name: 'Search results' });
+ const card = results.getByRole('listitem').filter({ hasText: 'Abbey Road' });
+ const addButton = card.getByRole('button', { name: 'Add to crate: Abbey Road' });
+ await expect(addButton).toBeVisible();
+ await addButton.click();
+ await expect(
+ card.getByRole('button', { name: 'Remove from crate: Abbey Road' }),
+ ).toBeVisible();
+
+ // Navigate to Your crate and confirm the saved album appears.
+ await page.getByRole('link', { name: 'Your crate' }).click();
+ await expect(page).toHaveURL(/\/crate$/);
+ await expect(page.getByRole('heading', { level: 1, name: 'Your crate' })).toBeVisible();
+ await expect(page.getByText('Showing 1 of 1 albums in your crate.')).toBeVisible();
+ await expect(page.getByRole('heading', { level: 3, name: 'Abbey Road' })).toBeVisible();
+
+ // Reload to verify server-side persistence.
+ await page.reload();
+ await expect(page.getByText('Showing 1 of 1 albums in your crate.')).toBeVisible();
+ await expect(page.getByRole('heading', { level: 3, name: 'Abbey Road' })).toBeVisible();
+
+ // Remove the album from the crate and verify the empty state persists on reload.
+ await page.getByRole('button', { name: 'Remove from crate: Abbey Road' }).click();
+ await expect(
+ page.getByRole('heading', { level: 2, name: 'Nothing saved yet' }),
+ ).toBeVisible();
+ await expect(page.getByText('Your crate is empty.')).toBeVisible();
+
+ await page.reload();
+ await expect(page.getByText('Your crate is empty.')).toBeVisible();
+});
diff --git a/e2e/tests/search.spec.ts b/e2e/tests/search.spec.ts
index 77424b8..cf16ca3 100644
--- a/e2e/tests/search.spec.ts
+++ b/e2e/tests/search.spec.ts
@@ -1,5 +1,7 @@
import { expect, test, type Page } from '@playwright/test';
+import { clearUserReview, clearUserSearchHistory } from './cleanup.js';
+
/**
* End-to-end tests against the curated catalog from `pnpm db:seed`. The Beatles
* have two albums there, Abbey Road (1969) and Revolver (1966), which is enough
@@ -29,7 +31,13 @@ function resultTitles(page: Page) {
test('search, filter, sort, open an album and keep a review across a reload', async ({
page,
+ request,
}) => {
+ // Remove any leftover state for the fixed E2E user deterministically via GraphQL
+ // so repeated runs against a reused database never race with initial page load.
+ await clearUserReview(request, E2E_USER_ID, 'Abbey Road');
+ await clearUserSearchHistory(request, E2E_USER_ID);
+
await page.addInitScript(([key, id]) => window.localStorage.setItem(key, id), [
USER_ID_STORAGE_KEY,
E2E_USER_ID,
@@ -67,17 +75,6 @@ test('search, filter, sort, open an album and keep a review across a reload', as
await expect(page.getByRole('heading', { level: 1, name: 'Abbey Road' })).toBeVisible();
await expect(page.getByText('The Beatles')).toBeVisible();
- // A run that failed after publishing leaves the fixed user's review behind.
- // Remove it first so the form starts empty.
- const leftover = page.getByRole('button', { name: 'Delete review' });
- if (await leftover.isVisible()) {
- await leftover.click();
- await page.getByRole('button', { name: 'Confirm delete' }).click();
- await expect(
- page.getByRole('status').filter({ hasText: 'Your review was deleted.' }),
- ).toBeVisible();
- }
-
// Write a review. The comment is unique so an old run cannot satisfy the check.
const comment = `E2E review ${Date.now()}`;
// The radios are visually hidden behind star labels, so click what a user sees.
@@ -196,3 +193,153 @@ test('keyboard only: skip link, search and open a result', async ({ page }) => {
await page.keyboard.press('Enter');
await expect(page.getByRole('heading', { level: 1, name: 'Abbey Road' })).toBeVisible();
});
+
+test('selects a previous query from search history with the keyboard', async ({
+ page,
+ request,
+}) => {
+ await clearUserSearchHistory(request, E2E_USER_ID);
+ await page.addInitScript(([key, id]) => window.localStorage.setItem(key, id), [
+ USER_ID_STORAGE_KEY,
+ E2E_USER_ID,
+ ] as const);
+ await page.goto('./');
+
+ await search(page, 'abbey');
+ await expect(page.getByRole('link', { name: 'Abbey Road' })).toBeVisible();
+
+ await search(page, 'coltrane');
+ await expect(page.getByRole('link', { name: 'A Love Supreme' })).toBeVisible();
+
+ const combobox = page.getByRole('combobox', { name: 'Search by album or artist' });
+ await combobox.click();
+ const listbox = page.getByRole('listbox', { name: 'Recent searches' });
+ await expect(listbox).toBeVisible();
+
+ // Newest first: index 0 is coltrane, index 1 is abbey.
+ await page.keyboard.press('ArrowDown');
+ await expect(listbox.getByRole('option', { name: 'coltrane' })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ await page.keyboard.press('ArrowDown');
+ await expect(listbox.getByRole('option', { name: 'abbey' })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ await page.keyboard.press('Enter');
+
+ await expect(page).toHaveURL(/[?&]q=abbey/);
+ await expect(page.getByRole('link', { name: 'Abbey Road' })).toBeVisible();
+
+ // Clean up history for the fixed E2E user.
+ await combobox.click();
+ await page.getByRole('button', { name: 'Clear recent searches', exact: true }).click();
+ await expect(page.getByRole('status', { name: 'Search history status' })).toHaveText(
+ 'Recent searches cleared.',
+ );
+});
+
+test('loads the next page of albums with Load more', async ({ page }) => {
+ await page.goto('./');
+ const browseRegion = page.getByRole('region', { name: 'Browse albums' });
+ await expect(page.getByRole('status').filter({ hasText: 'Showing' })).toHaveText(
+ 'Showing 20 of 24 matching albums.',
+ );
+ await expect(browseRegion.getByRole('heading', { level: 3 })).toHaveCount(20);
+
+ // Focusing the button suppresses the IntersectionObserver auto-load so we
+ // exercise explicit Load more activation deterministically.
+ const loadMore = page.getByRole('button', { name: 'Load more' });
+ await expect(loadMore).toBeVisible();
+ await loadMore.focus();
+ await page.keyboard.press('Enter');
+
+ await expect(page.getByRole('status').filter({ hasText: 'Showing' })).toHaveText(
+ 'Showing 24 of 24 matching albums.',
+ );
+ await expect(browseRegion.getByRole('heading', { level: 3 })).toHaveCount(24);
+ await expect(loadMore).toHaveCount(0);
+});
+
+test('validates, publishes, edits, and cleans up a review on an album page', async ({
+ page,
+ request,
+}) => {
+ const reviewUserId = '00000000-0000-4000-8000-000000000e2f';
+ await clearUserReview(request, reviewUserId, 'Revolver');
+ await page.addInitScript(([key, id]) => window.localStorage.setItem(key, id), [
+ USER_ID_STORAGE_KEY,
+ reviewUserId,
+ ] as const);
+
+ await page.goto('./?q=revolver');
+ await page.getByRole('link', { name: 'Revolver' }).click();
+ await expect(page.getByRole('heading', { level: 1, name: 'Revolver' })).toBeVisible();
+
+ // Submitting without a rating surfaces client-side validation.
+ await page.getByRole('button', { name: 'Publish review' }).click();
+ await expect(page.getByRole('alert')).toHaveText('Choose a rating from 1 to 5 stars.');
+
+ // Publish initial review.
+ const initialComment = `Initial E2E review ${Date.now()}`;
+ await page.locator('label').filter({ hasText: '3 stars' }).click();
+ await page.getByRole('textbox', { name: /Comment/ }).fill(initialComment);
+ await page.getByRole('button', { name: 'Publish review' }).click();
+ await expect(
+ page.getByRole('status').filter({ hasText: 'Your review was published.' }),
+ ).toBeVisible();
+
+ // Reload and verify unchanged saves are disabled until the user edits the review.
+ await page.reload();
+ const saveButton = page.getByRole('button', { name: 'Save changes' });
+ await expect(saveButton).toHaveAttribute('aria-disabled', 'true');
+
+ const updatedComment = `Edited E2E review ${Date.now()}`;
+ await page.locator('label').filter({ hasText: '5 stars' }).click();
+ await page.getByRole('textbox', { name: /Comment/ }).fill(updatedComment);
+ await expect(saveButton).toHaveAttribute('aria-disabled', 'false');
+ await saveButton.click();
+ await expect(
+ page.getByRole('status').filter({ hasText: 'Your review was updated.' }),
+ ).toBeVisible();
+
+ // Reload and confirm the edited rating and comment persisted.
+ await page.reload();
+ const myReview = page.getByRole('listitem').filter({ hasText: updatedComment });
+ await expect(myReview).toBeVisible();
+ await expect(myReview.getByRole('img', { name: '5 out of 5 stars' })).toBeVisible();
+ await expect(page.getByRole('radio', { name: '5 stars' })).toBeChecked();
+
+ // Clean up so the catalog stays clean.
+ await page.getByRole('button', { name: 'Delete review' }).click();
+ await page.getByRole('button', { name: 'Confirm delete' }).click();
+ await expect(
+ page.getByRole('status').filter({ hasText: 'Your review was deleted.' }),
+ ).toBeVisible();
+});
+
+test('restores results, filter chips, and sort from a shared multi-filter URL', async ({
+ page,
+}) => {
+ await page.goto('./?q=blue&genres=1&decades=1950&sort=TITLE_ASC');
+
+ await expect(page.getByRole('status').filter({ hasText: 'Showing' })).toHaveText(
+ /Showing 2 of 2 /,
+ );
+ await expect(resultTitles(page)).toHaveText(['Blue Train', 'Kind of Blue']);
+ await expect(page.getByRole('combobox', { name: 'Sort by' })).toHaveValue('TITLE_ASC');
+ await expect(
+ page.getByRole('button', { name: 'Filters (2)', exact: true }),
+ ).toBeVisible();
+
+ const activeFilters = page.getByRole('list', { name: 'Active filters' });
+ await expect(activeFilters).toContainText('Jazz');
+ await expect(activeFilters).toContainText('1950s');
+
+ // Reloading keeps the shared URL state intact.
+ await page.reload();
+ await expect(resultTitles(page)).toHaveText(['Blue Train', 'Kind of Blue']);
+ await expect(activeFilters).toContainText('Jazz');
+ await expect(activeFilters).toContainText('1950s');
+});
diff --git a/package.json b/package.json
index f4cdb3d..a815b52 100644
--- a/package.json
+++ b/package.json
@@ -10,12 +10,13 @@
"scripts": {
"dev": "pnpm --filter @t19/client dev",
"build": "pnpm -r build",
- "lint": "eslint .",
+ "lint": "eslint . --max-warnings 0",
"lint:fix": "eslint . --fix",
"format": "prettier --write .",
"format:check": "prettier --check .",
"typecheck": "pnpm -r typecheck",
"test": "pnpm -r test",
+ "test:integration": "pnpm --filter @t19/server test:integration",
"test:watch": "pnpm --filter @t19/client test:watch",
"test:e2e": "pnpm --filter @t19/e2e test:e2e",
"db:migrate": "pnpm --filter @t19/server db:migrate",
diff --git a/server/package.json b/server/package.json
index fd7ae66..bedc714 100644
--- a/server/package.json
+++ b/server/package.json
@@ -9,6 +9,7 @@
"start": "node --env-file-if-exists=.env dist/index.js",
"typecheck": "tsc --noEmit",
"test": "vitest run",
+ "test:integration": "node scripts/run-postgres-tests.mjs",
"db:generate": "drizzle-kit generate",
"db:migrate": "tsx --env-file-if-exists=.env src/db/migrate.ts",
"db:seed": "tsx --env-file-if-exists=.env src/db/seed.ts",
diff --git a/server/scripts/assert-postgres-tests.mjs b/server/scripts/assert-postgres-tests.mjs
index 798d9a6..08e5d09 100644
--- a/server/scripts/assert-postgres-tests.mjs
+++ b/server/scripts/assert-postgres-tests.mjs
@@ -23,6 +23,7 @@ export const databaseBackedFiles = [
'src/searchHistory.postgres.test.ts',
// Added with the crate query; not on main when this branch was cut.
'src/crate.postgres.test.ts',
+ 'src/reviews.postgres.test.ts',
'src/db/musicBrainzCatalog.test.ts',
'src/search/facets.postgres.test.ts',
'src/search/search.postgres.test.ts',
diff --git a/server/scripts/run-postgres-tests.mjs b/server/scripts/run-postgres-tests.mjs
new file mode 100644
index 0000000..cd68994
--- /dev/null
+++ b/server/scripts/run-postgres-tests.mjs
@@ -0,0 +1,40 @@
+// Runs the server Vitest suite and fails if any database-backed suite was
+// skipped. Requires TEST_DATABASE_URL to point at a migrated PostgreSQL database.
+import { spawnSync } from 'node:child_process';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const assertScript = fileURLToPath(
+ new URL('./assert-postgres-tests.mjs', import.meta.url),
+);
+const tempDir = mkdtempSync(join(tmpdir(), 't19-postgres-tests-'));
+const reportPath = join(tempDir, 'vitest.json');
+
+try {
+ const pnpmCmd = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm';
+ const vitest = spawnSync(
+ pnpmCmd,
+ [
+ 'exec',
+ 'vitest',
+ 'run',
+ '--reporter=default',
+ '--reporter=json',
+ `--outputFile=${reportPath}`,
+ ],
+ { stdio: 'inherit' },
+ );
+
+ if (vitest.status !== 0) {
+ process.exitCode = vitest.status ?? 1;
+ } else {
+ const check = spawnSync(process.execPath, [assertScript, reportPath], {
+ stdio: 'inherit',
+ });
+ process.exitCode = check.status ?? 1;
+ }
+} finally {
+ rmSync(tempDir, { recursive: true, force: true });
+}
diff --git a/server/src/crate.postgres.test.ts b/server/src/crate.postgres.test.ts
index b2ea838..0f3eb6d 100644
--- a/server/src/crate.postgres.test.ts
+++ b/server/src/crate.postgres.test.ts
@@ -276,3 +276,102 @@ describe.skipIf(!process.env.TEST_DATABASE_URL)('PostgreSQL myCrate', () => {
expect((await query(20, null, stranger)).totalCount).toBe(0);
});
});
+
+describe.skipIf(!process.env.TEST_DATABASE_URL)('PostgreSQL crate mutations', () => {
+ const pool = new pg.Pool({ connectionString: process.env.TEST_DATABASE_URL });
+ const db = drizzle(pool);
+ const word = `cratemut${Math.random()
+ .toString(36)
+ .replace(/[^a-z]/g, '')}`;
+ const owner = randomUUID();
+ const stranger = randomUUID();
+ let albumId = 0;
+
+ function ctx(userId: string | null = owner): Context {
+ return { db, userId, loaders: createLoaders(db, userId) };
+ }
+
+ beforeAll(async () => {
+ const [created] = await db
+ .insert(album)
+ .values({ title: `Crate mutation fixture ${word}`, releaseYear: 1999 })
+ .returning({ id: album.id });
+ albumId = created!.id;
+ });
+
+ afterAll(async () => {
+ await pool.query('DELETE FROM app_user WHERE id = ANY($1)', [[owner, stranger]]);
+ if (albumId > 0) {
+ await pool.query('DELETE FROM album WHERE id = $1', [albumId]);
+ }
+ await pool.end();
+ });
+
+ it('adds and removes crate items idempotently, primes loaders, and isolates users', async () => {
+ const ownerCtx = ctx(owner);
+ const first = await resolvers.Mutation.addToCrate(
+ {},
+ { albumId: String(albumId) },
+ ownerCtx,
+ );
+ expect(first.album.id).toBe(albumId);
+ expect(await ownerCtx.loaders.isInCrateByAlbum.load(albumId)).toBe(true);
+
+ // Repeating addToCrate returns the existing item without creating a duplicate row.
+ const second = await resolvers.Mutation.addToCrate(
+ {},
+ { albumId: String(albumId) },
+ ctx(owner),
+ );
+ expect(second.item.id).toBe(first.item.id);
+ const ownerRows = await db
+ .select()
+ .from(crateItem)
+ .where(eq(crateItem.userId, owner));
+ expect(ownerRows).toHaveLength(1);
+
+ // Another user saving the same album gets their own row.
+ const strangerAdd = await resolvers.Mutation.addToCrate(
+ {},
+ { albumId: String(albumId) },
+ ctx(stranger),
+ );
+ expect(strangerAdd.item.id).not.toBe(first.item.id);
+
+ // Removing deletes only the calling user's crate item and primes isInCrate to false.
+ const removeCtx = ctx(owner);
+ const removed = await resolvers.Mutation.removeFromCrate(
+ {},
+ { albumId: String(albumId) },
+ removeCtx,
+ );
+ expect(removed.removedAlbumId).toBe(String(albumId));
+ expect(await removeCtx.loaders.isInCrateByAlbum.load(albumId)).toBe(false);
+
+ // Repeating removeFromCrate when already absent succeeds idempotently.
+ const removedAgain = await resolvers.Mutation.removeFromCrate(
+ {},
+ { albumId: String(albumId) },
+ ctx(owner),
+ );
+ expect(removedAgain.removedAlbumId).toBe(String(albumId));
+
+ // Stranger's crate item is untouched.
+ const strangerCrate = await resolvers.Query.myCrate(
+ {},
+ { first: 20, after: null },
+ ctx(stranger),
+ );
+ expect(strangerCrate.totalCount).toBe(1);
+ expect(strangerCrate.edges[0]?.node.albumId).toBe(albumId);
+ });
+
+ it('rejects adding or removing a missing album', async () => {
+ await expect(
+ resolvers.Mutation.addToCrate({}, { albumId: '999999999' }, ctx(owner)),
+ ).rejects.toThrow('Album not found.');
+ await expect(
+ resolvers.Mutation.removeFromCrate({}, { albumId: '999999999' }, ctx(owner)),
+ ).rejects.toThrow('Album not found.');
+ });
+});
diff --git a/server/src/db/seed.ts b/server/src/db/seed.ts
index 1a32a0d..1dfe699 100644
--- a/server/src/db/seed.ts
+++ b/server/src/db/seed.ts
@@ -61,6 +61,37 @@ const albums: {
artists: ['Unknown Artist'],
genres: ['Rock'],
},
+ // Eight additional albums bring the seeded catalog to 24 (> PAGE_SIZE 20)
+ // so E2E tests exercise real keyset Load more pagination without altering the
+ // existing Beatles, Blue, Coltrane, or Rock search/facet counts.
+ { title: 'What’s Going On', year: 1971, artists: ['Marvin Gaye'], genres: ['Soul'] },
+ {
+ title: 'Songs in the Key of Life',
+ year: 1976,
+ artists: ['Stevie Wonder'],
+ genres: ['Soul', 'Pop'],
+ },
+ { title: 'Innervisions', year: 1973, artists: ['Stevie Wonder'], genres: ['Soul'] },
+ { title: 'Time Out', year: 1959, artists: ['Dave Brubeck Quartet'], genres: ['Jazz'] },
+ { title: 'Head Hunters', year: 1973, artists: ['Herbie Hancock'], genres: ['Jazz'] },
+ {
+ title: 'Selected Ambient Works 85–92',
+ year: 1992,
+ artists: ['Aphex Twin'],
+ genres: ['Electronic'],
+ },
+ {
+ title: 'Homogenic',
+ year: 1997,
+ artists: ['Björk'],
+ genres: ['Electronic', 'Pop'],
+ },
+ {
+ title: 'Low End Theory',
+ year: 1991,
+ artists: ['A Tribe Called Quest'],
+ genres: ['Hip hop'],
+ },
];
await db.transaction(async (tx) => {
diff --git a/server/src/reviews.postgres.test.ts b/server/src/reviews.postgres.test.ts
new file mode 100644
index 0000000..bb0cc4c
--- /dev/null
+++ b/server/src/reviews.postgres.test.ts
@@ -0,0 +1,298 @@
+import { randomUUID } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import { drizzle } from 'drizzle-orm/node-postgres';
+import { eq, inArray, sql } from 'drizzle-orm';
+import { createSchema, createYoga } from 'graphql-yoga';
+import pg from 'pg';
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
+
+import { album, appUser, review } from './db/schema.js';
+import { createLoaders } from './loaders/index.js';
+import { resolvers, type Context } from './resolvers.js';
+import { removeReview, saveReview } from './reviews.js';
+import { parseUserId } from './userIdentity.js';
+
+// Set TEST_DATABASE_URL to run these tests. Fixture albums and users are
+// isolated with random identifiers and deleted in afterAll.
+describe.skipIf(!process.env.TEST_DATABASE_URL)('PostgreSQL reviews', () => {
+ const pool = new pg.Pool({ connectionString: process.env.TEST_DATABASE_URL });
+ const db = drizzle(pool);
+ const word = `rev${Math.random()
+ .toString(36)
+ .replace(/[^a-z]/g, '')}`;
+ const owner = randomUUID();
+ const stranger = randomUUID();
+ const paginationUsers = Array.from({ length: 5 }, () => randomUUID());
+ const allUsers = [owner, stranger, ...paginationUsers];
+ let albumId = 0;
+
+ function ctx(userId: string | null = owner): Context {
+ return { db, userId, loaders: createLoaders(db, userId) };
+ }
+
+ async function storedAverageRating(id: number): Promise {
+ const [row] = await db
+ .select({ averageRating: album.averageRating })
+ .from(album)
+ .where(eq(album.id, id));
+ return row?.averageRating ?? null;
+ }
+
+ beforeAll(async () => {
+ const [created] = await db
+ .insert(album)
+ .values({ title: `Review fixture ${word}`, releaseYear: 1995 })
+ .returning({ id: album.id });
+ albumId = created!.id;
+ });
+
+ beforeEach(async () => {
+ await db.delete(review).where(eq(review.albumId, albumId));
+ await db.delete(appUser).where(inArray(appUser.id, allUsers));
+ });
+
+ afterAll(async () => {
+ await db.delete(appUser).where(inArray(appUser.id, allUsers));
+ if (albumId > 0) {
+ await db.delete(album).where(eq(album.id, albumId));
+ }
+ await pool.end();
+ });
+
+ it('creates a user, trims comments, updates in place, and fires DB rating and timestamp triggers', async () => {
+ const created = await saveReview(db, owner, {
+ albumId: String(albumId),
+ rating: 4,
+ comment: ' First listen ',
+ });
+
+ expect(created.review.rating).toBe(4);
+ expect(created.review.comment).toBe('First listen');
+ expect(created.album.id).toBe(albumId);
+ expect(await storedAverageRating(albumId)).toBe(4);
+
+ // Move updated_at into the past so the BEFORE UPDATE trigger change is unambiguous.
+ await db
+ .update(review)
+ .set({ updatedAt: new Date('2020-01-01T00:00:00Z') })
+ .where(eq(review.id, created.review.id));
+
+ const updated = await saveReview(db, owner, {
+ albumId: String(albumId),
+ rating: 5,
+ comment: ' Even better now ',
+ });
+
+ // Upsert must update the existing row rather than inserting a duplicate.
+ expect(updated.review.id).toBe(created.review.id);
+ expect(updated.review.rating).toBe(5);
+ expect(updated.review.comment).toBe('Even better now');
+ expect(updated.review.updatedAt.getTime()).toBeGreaterThan(
+ Date.parse('2020-01-02T00:00:00Z'),
+ );
+ expect(await storedAverageRating(albumId)).toBe(5);
+
+ const rows = await db.select().from(review).where(eq(review.albumId, albumId));
+ expect(rows).toHaveLength(1);
+
+ // Check loaders reflect the stored review and aggregates.
+ const ownerCtx = ctx(owner);
+ const parentAlbum = {
+ id: albumId,
+ title: '',
+ releaseYear: 1995,
+ musicBrainzReleaseGroupId: null,
+ };
+ expect(await resolvers.Album.reviewCount(parentAlbum, {}, ownerCtx)).toBe(1);
+ expect(await resolvers.Album.averageRating(parentAlbum, {}, ownerCtx)).toBe(5);
+ const mine = await resolvers.Album.myReview(parentAlbum, {}, ownerCtx);
+ expect(mine?.id).toBe(created.review.id);
+ });
+
+ it('rejects saving a review for a missing album', async () => {
+ await expect(
+ saveReview(db, owner, {
+ albumId: '999999999',
+ rating: 4,
+ comment: 'Missing album',
+ }),
+ ).rejects.toThrow('Album not found.');
+ });
+
+ it('prevents cross-user deletion and recalculates album average rating on delete', async () => {
+ const ownerReview = await saveReview(db, owner, {
+ albumId: String(albumId),
+ rating: 5,
+ comment: 'Owner review',
+ });
+ const strangerReview = await saveReview(db, stranger, {
+ albumId: String(albumId),
+ rating: 3,
+ comment: 'Stranger review',
+ });
+
+ expect(await storedAverageRating(albumId)).toBe(4);
+
+ // Stranger cannot delete owner's review.
+ await expect(
+ removeReview(db, stranger, String(ownerReview.review.id)),
+ ).rejects.toThrow('Review not found for this user.');
+ expect(await storedAverageRating(albumId)).toBe(4);
+
+ // Owner deletes their own review -> average drops to stranger's rating (3).
+ const deleted = await removeReview(db, owner, String(ownerReview.review.id));
+ expect(deleted.deletedReviewId).toBe(String(ownerReview.review.id));
+ expect(deleted.album.id).toBe(albumId);
+ expect(await storedAverageRating(albumId)).toBe(3);
+
+ // Deleting a second time fails cleanly.
+ await expect(removeReview(db, owner, String(ownerReview.review.id))).rejects.toThrow(
+ 'Review not found for this user.',
+ );
+
+ // Deleting the last remaining review resets album.average_rating to NULL.
+ await removeReview(db, stranger, String(strangerReview.review.id));
+ expect(await storedAverageRating(albumId)).toBeNull();
+ });
+
+ it('paginates reviewsForAlbum newest-first with deterministic cursor tie-breaking and rejects bad cursors', async () => {
+ await db.insert(appUser).values(
+ paginationUsers.map((id, index) => ({
+ id,
+ displayName: `Reviewer ${index + 1}`,
+ })),
+ );
+
+ // Three reviews share an exact timestamp so a page boundary of 2 lands inside the tie.
+ const timestamps = [
+ '2026-01-01T10:00:00Z',
+ '2026-01-03T10:00:00Z',
+ '2026-01-02T10:00:00Z',
+ '2026-01-02T10:00:00Z',
+ '2026-01-02T10:00:00Z',
+ ];
+ const insertedIds: number[] = [];
+ for (const [index, userId] of paginationUsers.entries()) {
+ const [row] = await db
+ .insert(review)
+ .values({
+ userId,
+ albumId,
+ rating: (index % 5) + 1,
+ comment: `Review #${index + 1}`,
+ createdAt: sql`${timestamps[index]!}::timestamptz`,
+ })
+ .returning({ id: review.id });
+ insertedIds.push(row!.id);
+ }
+
+ const albumRow = {
+ id: albumId,
+ title: `Review fixture ${word}`,
+ releaseYear: 1995,
+ musicBrainzReleaseGroupId: null,
+ };
+ const seen: number[] = [];
+ let after: string | null = null;
+
+ for (let guard = 0; guard < 10; guard += 1) {
+ const page = await resolvers.Album.reviews(
+ albumRow,
+ { first: 2, after },
+ ctx(owner),
+ );
+ expect(page.totalCount).toBe(5);
+ seen.push(...page.edges.map((edge) => edge.node.id));
+ if (!page.pageInfo.hasNextPage) break;
+ after = page.pageInfo.endCursor;
+ expect(after).not.toBeNull();
+ }
+
+ // Newest first: 3 Jan (index 1), then the three 2 Jan ties by descending id, then 1 Jan (index 0).
+ expect(seen).toEqual([
+ insertedIds[1],
+ insertedIds[4],
+ insertedIds[3],
+ insertedIds[2],
+ insertedIds[0],
+ ]);
+
+ await expect(
+ resolvers.Album.reviews(albumRow, { first: 2, after: 'not-a-cursor' }, ctx(owner)),
+ ).rejects.toThrow('Invalid review cursor.');
+ });
+
+ it('serves upsertReview, deleteReview, and Album.reviews through GraphQL Yoga', async () => {
+ const yoga = createYoga