#!/usr/bin/env bash # Ship ~/app to production: test it, compile it to one binary, back up the # data, switch app.service (port 8000) to the new binary, and check that it # answers. If it doesn't, the previous binary goes back. # Usage: app-release [entry] (default: package.json's "module", then "main") set -euo pipefail cd "$HOME/app" entry=${1:-$(bun -p 'const p = require("./package.json"); p.module ?? p.main ?? ""')} [ -n "$entry" ] || { echo "==> No entry point: set \"module\" in package.json, or pass one"; exit 1; } rev=$(git rev-parse --short HEAD 2>/dev/null || echo none) git diff --quiet HEAD 2>/dev/null || rev="$rev-dirty" out="$HOME/releases/app-$(date -u +%Y%m%d-%H%M%S)-$rev" mkdir -p "$HOME/releases" echo "==> Testing" bun install --frozen-lockfile if find . -path ./node_modules -prune -o \( -name '*.test.*' -o -name '*_test.*' -o -name '*.spec.*' -o -name '*_spec.*' \) -print | grep -q .; then bun test fi echo "==> Compiling $entry" build=$(mktemp -d) trap 'rm -rf "$build"' EXIT bun build "$entry" --compile --minify --sourcemap --bytecode \ --no-compile-autoload-dotenv --no-compile-autoload-bunfig --outfile "$build/app" mv "$build/app" "$out" # the source map is inside; the .map files beside it aren't needed echo "==> Backing up the data" "$HOME/bin/app-backup" release >/dev/null echo "==> Starting $(basename "$out")" previous=$(readlink "$HOME/releases/current" || true) ln -sfn "$out" "$HOME/releases/current.new" && mv -T "$HOME/releases/current.new" "$HOME/releases/current" sudo systemctl restart app for _ in $(seq 30); do code=$(curl -s -o /dev/null -m 5 -w '%{http_code}' http://localhost:8000/ || true) case $code in 000|5??) sleep 1 ;; *) break ;; esac done case $code in 000|5??) echo "==> FAILED: the new binary answers HTTP $code (journalctl -u app -n 50)" if [ -n "$previous" ]; then ln -sfn "$previous" "$HOME/releases/current.new" && mv -T "$HOME/releases/current.new" "$HOME/releases/current" sudo systemctl restart app echo "==> Back on $(basename "$previous")" fi rm -f "$out" exit 1 ;; esac # Keep the newest 5 binaries (about 100 MB each), and whatever is running. ls -1t "$HOME"/releases/app-* | tail -n +6 | { grep -vxF "$out" || true; } | xargs -r rm -- echo "==> Released $(basename "$out"): HTTP $code on port 8000"