179 lines
9.3 KiB
Bash
Executable File
179 lines
9.3 KiB
Bash
Executable File
#!/usr/bin/env bash
|
||
# Deploys the live site (pre-launch: peppa.telecom.quest from this working copy) — PEP-172.
|
||
# The only way to update what users see. Every step is a check that cannot be skipped:
|
||
#
|
||
# 1. one deploy at a time (lock);
|
||
# 2. the working copy is `main` with no tracked changes (an agent's branch never goes live);
|
||
# 3. the target (origin/main, or the given sha on main) passed every CI check: lint, typecheck,
|
||
# build, test — otherwise refuse (--wait: wait for them, up to 40 min);
|
||
# 4. fast-forward only, dependencies installed;
|
||
# 5. migrations in the code that the database lacks → `peppa db backup` and `peppa db migrate`;
|
||
# 6. `next build` — a failure puts the old code and the old build back, nothing restarts;
|
||
# 7. web, watchdog and bot restart; /api/health must report the target commit with fresh
|
||
# heartbeats;
|
||
# 8. smoke: the main pages answer 200 for the test user, and the web log since the restart has no
|
||
# server errors — otherwise the previous commit and build come back (the database keeps the
|
||
# new columns: migrations only add, the backup is in ~/.peppa/backups).
|
||
#
|
||
# Usage: scripts/live-deploy.sh [--wait] [<sha>]
|
||
# Also installs the working copy's pre-commit hook: nobody commits in the live copy (PEP-172).
|
||
set -euo pipefail
|
||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||
cd "$ROOT"
|
||
WAIT=0 TARGET=""
|
||
for a in "$@"; do
|
||
case "$a" in
|
||
--wait) WAIT=1 ;;
|
||
-h|--help) sed -n '2,20p' "$0"; exit 0 ;;
|
||
*) TARGET=$a ;;
|
||
esac
|
||
done
|
||
PEPPA_HOME="${PEPPA_HOME:-$HOME/.peppa}"
|
||
LOG="$PEPPA_HOME/web.log"
|
||
URL="${PEPPA_WEB_URL:-https://peppa.telecom.quest}"
|
||
UIDN=$(id -u)
|
||
say() { printf '%s live-deploy: %s\n' "$(date +%H:%M:%S)" "$*"; }
|
||
die() { say "STOP — $*"; exit 1; }
|
||
|
||
# 1. Lock.
|
||
LOCK="$PEPPA_HOME/live-deploy.lock"
|
||
mkdir "$LOCK" 2>/dev/null || die "another deploy is running ($LOCK; remove it if that is not true)"
|
||
trap 'rmdir "$LOCK" 2>/dev/null || true' EXIT
|
||
|
||
set -a; . "$ROOT/.env"; set +a
|
||
. "$ROOT/scripts/gitea-lib.sh"
|
||
REPO="${GITEA_PLATFORM_REPO:-peppa/peppa}"
|
||
|
||
# The live copy refuses commits from now on (agents must work in worktrees).
|
||
HOOK="$(git rev-parse --git-path hooks)/pre-commit"
|
||
if ! grep -q "PEP-172/182" "$HOOK" 2>/dev/null; then
|
||
mkdir -p "$(dirname "$HOOK")"
|
||
cat >"$HOOK" <<'H'
|
||
#!/bin/sh
|
||
# PEP-172/182: this repository's own working copy is the one the live site runs from — no commits
|
||
# there. Worktrees (agents, coordinator) share this hooks directory and must keep committing.
|
||
[ -n "$PEPPA_LIVE_COMMIT_OK" ] && exit 0
|
||
top=$(git rev-parse --show-toplevel 2>/dev/null)
|
||
live=$(cd "$(git rev-parse --git-common-dir)/.." && pwd -P)
|
||
[ "$(cd "$top" && pwd -P)" = "$live" ] || exit 0
|
||
echo "Peppa FACTORY: в этой копии работает живой сайт — коммиты здесь запрещены. Работайте в git worktree." >&2
|
||
exit 1
|
||
H
|
||
chmod +x "$HOOK"
|
||
say "pre-commit hook installed: no commits in the live copy"
|
||
fi
|
||
|
||
# 2. Clean main.
|
||
BRANCH=$(git symbolic-ref --short -q HEAD || echo "(detached)")
|
||
[ "$BRANCH" = "main" ] || die "the working copy is on $BRANCH, not main — someone works here; save their work and run: git checkout main"
|
||
DIRTY=$(git status --porcelain --untracked-files=no)
|
||
[ -z "$DIRTY" ] || die "tracked files are modified in the live copy:
|
||
$DIRTY"
|
||
|
||
# 3. Target and its checks.
|
||
git fetch -q origin
|
||
TARGET=$(git rev-parse "${TARGET:-origin/main}^{commit}")
|
||
git merge-base --is-ancestor "$TARGET" origin/main || die "$TARGET is not on origin/main"
|
||
PREV=$(git rev-parse HEAD)
|
||
git merge-base --is-ancestor "$PREV" "$TARGET" || die "$TARGET is not ahead of the live commit $PREV (fast-forward only)"
|
||
checks() { # → "ok" | "pending" | "failed:<names>"
|
||
gitea_api "$GITEA_URL/api/v1/repos/$REPO/commits/$TARGET/status" | python3 -c '
|
||
import json, sys
|
||
need = ["peppa/lint", "peppa/typecheck", "peppa/build", "peppa/test"]
|
||
d = json.load(sys.stdin); st = {s["context"]: s["status"] for s in (d.get("statuses") or [])}
|
||
bad = [n for n in need if st.get(n) in ("failure", "error")]
|
||
print("failed:" + ",".join(bad) if bad else "ok" if all(st.get(n) == "success" for n in need) else "pending")'
|
||
}
|
||
for i in $(seq 1 80); do
|
||
C=$(checks || echo "pending")
|
||
[ "$C" = ok ] && break
|
||
case "$C" in failed:*) die "CI failed on ${TARGET:0:8}: ${C#failed:}" ;; esac
|
||
[ "$WAIT" = 1 ] || die "CI on ${TARGET:0:8} is not finished — run again later or with --wait"
|
||
[ "$i" = 1 ] && say "waiting for CI on ${TARGET:0:8}…"
|
||
sleep 30
|
||
done
|
||
[ "$C" = ok ] || die "CI on ${TARGET:0:8} did not finish in 40 min"
|
||
say "CI green on ${TARGET:0:8} (lint, typecheck, build, test)"
|
||
|
||
[ "$PREV" = "$TARGET" ] && say "already at ${TARGET:0:8} — rebuilding and checking anyway"
|
||
|
||
# 4. Code and dependencies.
|
||
restore_code() { git reset -q --hard "$PREV"; pnpm install --frozen-lockfile --offline >/dev/null 2>&1 || true; }
|
||
git merge -q --ff-only "$TARGET"
|
||
pnpm install --frozen-lockfile --offline >/dev/null 2>&1 || pnpm install --frozen-lockfile >/dev/null || { restore_code; die "pnpm install failed"; }
|
||
|
||
# 5. Migrations the database lacks.
|
||
DB="${PEPPA_DB:-$PEPPA_HOME/peppa.db}"
|
||
IN_CODE=$(ls packages/db/migrations/*.sql | wc -l | tr -d ' ')
|
||
IN_DB=$(sqlite3 "$DB" "select count(*) from __drizzle_migrations" 2>/dev/null || echo 0)
|
||
if [ "$IN_CODE" -gt "$IN_DB" ]; then
|
||
say "migrations: $IN_DB applied, $IN_CODE in the code — backup and migrate"
|
||
"$ROOT/packages/cli/bin/peppa" db backup >/dev/null || { restore_code; die "database backup failed"; }
|
||
"$ROOT/packages/cli/bin/peppa" db migrate || { restore_code; die "migration failed (backup in $PEPPA_HOME/backups)"; }
|
||
elif [ "$IN_CODE" -lt "$IN_DB" ]; then
|
||
restore_code; die "the database has more migrations ($IN_DB) than the code ($IN_CODE)"
|
||
fi
|
||
|
||
# 6. Build; the old build is kept (an APFS clone — instant) for the rollback.
|
||
WEB="$ROOT/apps/web"
|
||
rm -rf "$WEB/.next.prev"
|
||
[ -d "$WEB/.next" ] && cp -cR "$WEB/.next" "$WEB/.next.prev"
|
||
restore_build() { [ -d "$WEB/.next.prev" ] && { rm -rf "$WEB/.next"; mv "$WEB/.next.prev" "$WEB/.next"; }; }
|
||
if ! (cd "$WEB" && ./node_modules/.bin/next build >"$PEPPA_HOME/live-build.log" 2>&1); then
|
||
restore_code; restore_build
|
||
die "next build failed — old code and build kept, nothing restarted (log: $PEPPA_HOME/live-build.log)"
|
||
fi
|
||
say "built ${TARGET:0:8}"
|
||
|
||
# 7. Restart and health.
|
||
# PEP-202: the observer is restarted too once it is installed here.
|
||
restart() {
|
||
# PEP-225: the web agent of an older install starts `next start` directly — reinstall it once
|
||
# so it goes through apps/web/server.ts (the WebSocket channel); reinstalling restarts it.
|
||
local webplist="$HOME/Library/LaunchAgents/quest.telecom.peppa.web.plist"
|
||
if [ -f "$webplist" ] && ! grep -q 'server.ts' "$webplist"; then "$ROOT/scripts/install-launchd.sh" web >/dev/null; fi
|
||
for s in web watchdog bot; do launchctl kickstart -k "gui/$UIDN/quest.telecom.peppa.$s"; done
|
||
launchctl print "gui/$UIDN/quest.telecom.peppa.observer" >/dev/null 2>&1 && launchctl kickstart -k "gui/$UIDN/quest.telecom.peppa.observer" || true
|
||
}
|
||
MARK=$(wc -l <"$LOG" 2>/dev/null || echo 0)
|
||
RESTARTED=$(date -u +%Y-%m-%dT%H:%M:%S)
|
||
restart
|
||
healthy() { # <sha> — the target commit, every service up and heard from after the restart
|
||
curl -fsS -m 10 "$URL/api/health" 2>/dev/null | python3 -c '
|
||
import json, sys
|
||
d = json.load(sys.stdin); since = sys.argv[2]
|
||
svc = d.get("services", [])
|
||
ok = d.get("ok") and (d.get("commit") or "").startswith(sys.argv[1][:7]) and svc and all(
|
||
s.get("ok") and (s.get("lastHeartbeat") or "")[:19] >= since for s in svc)
|
||
sys.exit(0 if ok else 1)' "$1" "$RESTARTED"
|
||
}
|
||
rollback() {
|
||
say "ROLLBACK to ${PREV:0:8}: $1"
|
||
restore_code; restore_build; RESTARTED=$(date -u +%Y-%m-%dT%H:%M:%S); restart
|
||
for i in $(seq 1 60); do healthy "$PREV" && { say "rolled back — the site runs ${PREV:0:8}"; exit 1; }; sleep 3; done
|
||
say "rolled back, but health does not answer yet — check by hand"; exit 1
|
||
}
|
||
for i in $(seq 1 60); do healthy "$TARGET" && break; sleep 3; done
|
||
healthy "$TARGET" || rollback "health did not report ${TARGET:0:8} with every service heard from after the restart (3 min)"
|
||
say "health ok"
|
||
|
||
# 8. Smoke: the pages a person opens, as the test user, and no server errors in the log.
|
||
JAR=$(mktemp); trap 'rm -f "$JAR"; rmdir "$LOCK" 2>/dev/null || true' EXIT
|
||
LINK=$("$ROOT/packages/cli/bin/peppa" web login-link "${PEPPA_SMOKE_USER:-mock-pm}" 2>/dev/null | tail -1)
|
||
case "$LINK" in http*) ;; *) rollback "no login link for the smoke user (${PEPPA_SMOKE_USER:-mock-pm} must exist and be enabled)" ;; esac
|
||
curl -fsS -m 20 -c "$JAR" -b "$JAR" -L -o /dev/null "$LINK" || rollback "the login link did not sign in"
|
||
for p in / /projects /chats /help /settings /team; do
|
||
code=$(curl -s -m 30 -b "$JAR" -o /tmp/live-deploy-page.$$ -w '%{http_code}' "$URL$p")
|
||
grep -q "couldn.t load\|Application error\|Internal Server Error" /tmp/live-deploy-page.$$ && code="error-page"
|
||
rm -f /tmp/live-deploy-page.$$
|
||
[ "$code" = 200 ] || rollback "$p answered $code"
|
||
done
|
||
sleep 2
|
||
ERRS=$(tail -n +$((MARK + 1)) "$LOG" 2>/dev/null | grep -E "⨯|ERR_SQLITE|no such (table|column)" | head -3 || true)
|
||
[ -z "$ERRS" ] || rollback "server errors after the restart:
|
||
$ERRS"
|
||
rm -rf "$WEB/.next.prev"
|
||
# PEP-242: the project template goes to Gitea with every deploy; a failure does not roll back.
|
||
./packages/cli/bin/peppa template push --alert || say "project template not pushed (superadmin alerted)"
|
||
say "DONE — the site runs ${TARGET:0:8} (was ${PREV:0:8}); pages and health checked"
|