diff --git a/deploy/compose-build-at-deploy.yml b/deploy/compose-build-at-deploy.yml index 049f6af..5cdba13 100644 --- a/deploy/compose-build-at-deploy.yml +++ b/deploy/compose-build-at-deploy.yml @@ -111,7 +111,52 @@ services: command: - /bin/sh - -c - - "rm -rf /app/* && cp -a /source/repo/api/. /app/ && npm install --omit=dev && exec node server.js" + - | + # Keep this container on the revision the clone holds. + # + # `web` needs nothing like this: it serves the frontend build out of a shared volume, so + # every deploy refreshes the app by itself. The api's code is copied INTO this container + # instead, and compose recreates a service only when its configuration or image changed — + # the clone is a volume, so neither does. Without the loop below the api silently keeps + # serving the previous revision after every deploy, which from the outside looks exactly + # like a route that does not exist yet (404 on an endpoint the frontend already calls). + # + # It is also a supervisor: if the server exits, the loop starts it again, where the old + # one-liner left that to the container restart policy (and a full re-copy with it). + src=/source/repo/api + pid='' + last='' + sync_code() { + # Everything except node_modules: the copy IS the code, while wiping the installed + # dependencies would mean a full `npm install` — a minute of downtime — on every deploy. + for f in /app/*; do + case "$$f" in */node_modules) ;; *) rm -rf "$$f" ;; esac + done + cp -a "$$src/." /app/ + } + start_api() { cd /app; node server.js & pid=$$!; } + trap 'kill "$$pid" 2>/dev/null; exit 0' TERM INT + while :; do + # server.js is written last by a fresh clone and removed first by `rm -rf /work/repo`, so + # this one test covers both "the clone is not ready yet" and "a deploy is in flight". + if [ -f "$$src/server.js" ]; then + stamp=$$(stat -c %Y "$$src/server.js" 2>/dev/null) + if [ "$$stamp" != "$$last" ]; then + last="$$stamp" + if [ -n "$$pid" ]; then kill "$$pid" 2>/dev/null; wait "$$pid" 2>/dev/null; fi + reinstall='' + if ! cmp -s "$$src/package.json" /app/package.json; then reinstall=1; fi + sync_code + if [ -n "$$reinstall" ]; then npm install --omit=dev; fi + echo "api: synced to the clone at $$(date -u +%H:%M:%SZ)" + start_api + elif [ -n "$$pid" ] && ! kill -0 "$$pid" 2>/dev/null; then + echo 'api: the server exited — starting it again' + start_api + fi + fi + sleep 15 + done restart: unless-stopped web-build: