From 742b5571a365b7a2d973a1a82acd8eee2c9095db Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 04:15:37 -0600 Subject: [PATCH] fix(pm-console): a machine's console runs from its own copy of main, fetched from GitHub On the laptop the console ran from the checkout the fleet's lanes work in. That checkout is not kept at main, so the console in service was main's code from the day before, and then another branch's altogether, put into service by the console's own redeploy when the checkout was switched to that branch (#13833). - The console runs from ~/.local/share/pm-console: a clone that fetches only main and only the console's part of the tree, a release laid out for each commit, and a link to the one in service. - redeploy.sh asks GitHub for main every minute. New console code is laid out as a release and started in a self-check; only then is the link moved and the release's own install.sh run. - install.sh waits for the console to answer its health check as that release's commit. The console says which commit it was started from, read from the release. - A release that does not start, or does not come up, does not stay: the one before it is put back and the unit fails. GitHub out of reach changes nothing, and is a failure after half an hour. - The console's four services run from the link, and from no checkout anything else works in. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YLT5K1QVuzZjfWGFhXSSNF --- ...rchitecture_pm_platform_cloudflare_core.md | 47 ++ planning/roadmaps/pm-stack.md | 1 + pm-stack/book/getting-started/installation.md | 2 +- pm-stack/console/README.md | 41 +- pm-stack/console/install.sh | 47 +- pm-stack/console/redeploy.sh | 173 ++++++-- pm-stack/console/src/server.ts | 26 +- pm-stack/console/test/console.test.ts | 30 +- pm-stack/console/test/install.test.ts | 211 +++++++++ pm-stack/console/test/redeploy.test.ts | 403 +++++++++++++----- .../pm-console-android-release.service | 2 +- pm-stack/systemd/pm-console-expose.service | 2 +- pm-stack/systemd/pm-console-redeploy.service | 9 +- pm-stack/systemd/pm-console.service | 5 +- 14 files changed, 809 insertions(+), 190 deletions(-) create mode 100644 pm-stack/console/test/install.test.ts diff --git a/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md b/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md index d6f4e1411b..7df69f309d 100644 --- a/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md +++ b/doc/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core/2026-11-23T06-50-00Z_architecture_pm_platform_cloudflare_core.md @@ -1676,3 +1676,50 @@ what each must make an agent do differently, written out in the tests; something to do is compared with what was filed before, whole. Twenty-two faults planted one at a time, all caught. In the Worker's real runtime, 54 of 54. + +## 2026-11-24T10:14Z Update: a machine's console runs from its own copy of main + +**What was wrong.** On the laptop the console ran from the checkout the +fleet's lanes work in. That checkout is not kept at main: lanes leave it +on their own branches, with half-written files, and the unit that would +pull main into it rightly refuses to. So the console in service was +main's code from the day before, and from 08:39Z on 2026-11-24 another +branch's code altogether (`9c2b4ad096e3`, a commit of a design branch), +put into service by the console's own redeploy when the checkout was +switched to that branch. Five passes over #13833 by five lanes each +found it still so, and changed nothing. + +**The source of truth is GitHub's main, not a directory on the laptop.** +A machine's console now runs from a copy that is its own, under +`~/.local/share/pm-console`: a clone that fetches only main and only +the console's part of the tree, a release laid out for each commit, and +a link to the one in service. Every minute `redeploy.sh` asks GitHub +for main; when the console's code there is not what is in service it +lays the commit out as a release, starts it in a self-check, and only +then moves the link and runs the release's own `install.sh`, which +restarts the service and waits for it to answer its health check as +that commit. A release that does not start or does not come up does not +stay: the one before it is put back and the unit fails, where the +Services screen and the notifications show it. GitHub out of reach +changes nothing, and is a failure after half an hour. + +**What a machine is, after this.** Still one of the machines that +report to Cloudflare, with what only a machine has: its units, the +dashboard, the fleet's own commands. What code it runs is no longer a +fact about a directory someone works in. + +**Checked.** Both scripts are run for real: against a bare repository +standing in for GitHub (reached over git's own protocol, allowing the +partial fetches GitHub allows), with stand-ins only for the program +that runs the self-check, for `systemctl` and for the health check. +What is in service is compared with the files of the commit pushed to +main, read back from git. A checkout on another branch with +half-written files, the script run from inside it: main is what goes +into service, and the checkout is left as it was. Thirty-three faults +planted one at a time, all caught after one test was tightened. + +**Not yet.** The edge still cannot tell by itself that a machine runs +other console code than it does: each says a commit, and two commits +can hold the same console. A release now records its console's tree +beside its commit, which is what the two sides would compare (#13833's +third point). diff --git a/planning/roadmaps/pm-stack.md b/planning/roadmaps/pm-stack.md index 2c1048f353..24dd189fd2 100644 --- a/planning/roadmaps/pm-stack.md +++ b/planning/roadmaps/pm-stack.md @@ -27,6 +27,7 @@ The roadmap of record is this file and its siblings in `planning/roadmaps/`. The | Notifications that say what happened and can be answered | shipped | A push carries the reply or the thing to do, and buttons that reply, mark it done, close it or restart a failed unit from the notification itself, kept and sent later with no connection. | #13504 | | What was finished, beside what is happening and what is next | shipped | A Done screen and a tile on Now: tasks the queue says are done, pull requests merged and issues closed, read by Cloudflare itself from the queue store and GitHub. | #13504 | | Ask a question, start work, or give a standing instruction | shipped | Ask says which it is; a question is answered and changes nothing, a standing instruction is recorded where every agent reads it, and each is filed and queued as that with no machine. | #13504 | +| A machine's console runs main, from GitHub | shipped | The console on a machine runs from its own copy of main, fetched from GitHub and laid out a release per commit, not from a checkout the fleet works in; a release that does not come up is taken out again. | #13833 | ## Next diff --git a/pm-stack/book/getting-started/installation.md b/pm-stack/book/getting-started/installation.md index 2cb001af9b..a8c0b5eb31 100644 --- a/pm-stack/book/getting-started/installation.md +++ b/pm-stack/book/getting-started/installation.md @@ -26,7 +26,7 @@ The user units `pm-aggregator`, `pm-projector`, `pm-dispatch`, and `pm-tunnel` a Nix packages in the tree are `pkgs/pm-aggregator` (the aggregator plus four script binaries: gather-quota, generate-digest, export-turso-stores, quota-weekly-review; it also bundles `pm-stack/kaneo-projects.json` and `pm-stack/grist/seed/roadmap.json`), `pkgs/pm-dispatch`, `pkgs/pm-projector`, and `pkgs/pm-git-sync` (a script wrapper, version 0.3.0). -There is no `pkgs/pm-console`, and the console is the one PM-stack app NixOS does **not** declare (T4, survey top-up 1): `pm-console` runs as the hand-installed user unit `pm-console.service`, copied from `pm-stack/systemd/pm-console.service` by `pm-stack/console/install.sh`, executing `bun run src/server.ts` straight out of the primary checkout on port 4872, and it is kept current by its own per-minute redeploy timer (`pm-console-redeploy.timer`), not by `nixos-rebuild switch`. A grep for `pm-console` over `nixos/` and `home/` returns nothing. Its edge release is below. +There is no `pkgs/pm-console`, and the console is the one PM-stack app NixOS does **not** declare (T4, survey top-up 1): `pm-console` runs as the hand-installed user unit `pm-console.service`, copied from `pm-stack/systemd/pm-console.service` by `pm-stack/console/install.sh`, executing `bun run src/server.ts` on port 4872 from its own copy of `main` under `~/.local/share/pm-console` (a release per commit, fetched from GitHub; not the primary checkout, which it ran from until 2026-11-24, #13833), and it is kept current by its own per-minute redeploy timer (`pm-console-redeploy.timer`), not by `nixos-rebuild switch`. A grep for `pm-console` over `nixos/` and `home/` returns nothing. Its edge release is below. Repo copies of further unit files live in `pm-stack/systemd/`: `pm-host-health` with its timer, `pm-invariant-sweeper` with its timer, `pm-kaneo-sync-guard` with its timer, `pm-quota-watchdog` with its timer, `pm-console-expose` with its timer, `pm-console-redeploy` with its timer, and `pm-console-android-release` with its timer. Of these repo copies, only the `pm-console*` family is installed from this directory by a live script (`pm-stack/console/install.sh`); the `pm-aggregator`, `pm-dispatch`, and `pm-tunnel` copies in the same directory are the pre-NixOS files the NixOS module header says are kept beside that history in git (T4, survey top-up 1). diff --git a/pm-stack/console/README.md b/pm-stack/console/README.md index 3e6f7f090c..0c836b0902 100644 --- a/pm-stack/console/README.md +++ b/pm-stack/console/README.md @@ -67,7 +67,9 @@ Between runs it shows as failed whenever its last run failed, so one bad run that the next run mends says nothing; five minutes of failing run after run is reported once ("A unit keeps failing", with what the unit is for), and so is its mending. That is what tells the owner when the -laptop's checkout has stopped following `main`. +laptop's checkout has stopped following `main`, and, for the console's +own copy of `main`, when `pm-console-redeploy` cannot put it into +service. ### The plan: roadmaps, bugs, intake @@ -321,13 +323,33 @@ dropped, sent, or tried again there. ### Merges deploy themselves -`pm-console-redeploy.timer` runs `redeploy.sh` every minute. When the -checkout holds console code that is not the code in service, the new -code is started in a self-check that listens on nothing -(`bun run src/server.ts --check`, with the service's own settings); only -if that passes is it put into service. Code that does not start is left -out, the old code keeps running, and the unit fails, which the Services -screen and notifications show. +On a machine the console runs from a copy of `main` that is its own, +under `~/.local/share/pm-console`: + +| There | What it is | +| -------------------- | --------------------------------------------------------------------------------- | +| `repo/` | a clone that fetches only `main` from GitHub, and only the console's part of it | +| `releases//` | the console's files at one commit of `main`, with `.release` saying which | +| `current` | a link to the release in service: what every one of the console's units runs from | + +Nothing else works there. (Until 2026-11-24 the console ran from the +checkout the fleet's lanes work in, and was whatever that checkout held: +`main`'s code from the day before, or another branch's. #13833.) + +`pm-console-redeploy.timer` runs `redeploy.sh` every minute. It asks +GitHub for `main`. When the console's code there (or one of its units, +or the dashboard's list of pages) is not what is in service, that +commit's files are laid out as a new release and started in a +self-check that listens on nothing (`bun run src/server.ts --check`, +with the service's own settings). Only if that passes is the release +made current and its own `install.sh` run, which installs the units, +restarts the service and waits for it to answer its health check as +that commit. A release that does not start, or does not come up, does +not stay: the one before it is put back, and the unit fails, which the +Services screen and notifications show. With GitHub out of reach +nothing changes, and after half an hour of that the unit fails too. +The newest releases are kept, always including the one in service and +the one before it. ## Sign-in @@ -371,7 +393,8 @@ app's link to this origin), and the two phone paths under ## Run ```bash -bash pm-stack/console/install.sh # user unit pm-console, port 4872, loopback only; and its three timers +bash pm-stack/console/redeploy.sh # from any checkout, once: makes the console's own copy of main and installs + # user unit pm-console (port 4872, loopback only) and its three timers from it python3 pm-stack/console/scripts/expose.py --owner you@example.com # first time: Access, console env, tunnel route, DNS, the edge's route python3 pm-stack/console/scripts/expose.py --check # what public exposure would change python3 pm-stack/console/scripts/expose.py # later runs (the timer's): the owner is remembered diff --git a/pm-stack/console/install.sh b/pm-stack/console/install.sh index 0d3897757e..81d2a9a149 100755 --- a/pm-stack/console/install.sh +++ b/pm-stack/console/install.sh @@ -1,6 +1,10 @@ #!/usr/bin/env bash -# install.sh — install or refresh the pm-console user unit on the host -# that runs the pm stack. Safe to run again: it never overwrites an +# install.sh — install or refresh the console's units on this machine +# from the release this file is part of, restart the console, and wait +# for it to answer as that release. +# +# redeploy.sh runs it once it has made a release current; that is the +# only way it is meant to run. Safe to run again: it never overwrites an # existing environment file. # # Usage: bash install.sh @@ -12,10 +16,11 @@ if [ "$#" -ne 0 ]; then fi cd "$(dirname "$0")" -SRC="$PWD" -EXPECTED="$HOME/git/code/pm-stack/console" -if [ "$SRC" != "$EXPECTED" ]; then - echo "install.sh: run from the primary checkout at $EXPECTED (the unit runs that checkout)" >&2 +SRC="$(pwd -P)" +SHARE="$HOME/.local/share/pm-console" +SERVED="$(cd "$SHARE/current/pm-stack/console" 2>/dev/null && pwd -P || true)" +if [ "$SRC" != "$SERVED" ]; then + echo "install.sh: this is not the release in service ($SHARE/current). Run redeploy.sh: it makes a release from main and then runs this." >&2 exit 1 fi STATE="$HOME/.local/state/pm-console" @@ -32,7 +37,7 @@ if [ ! -f "$STATE/.env" ]; then fi install -m 644 "$UNIT_SRC" "$UNIT_DST" # One timer keeps the public address as declared, and turns Google -# sign-in on by itself once its two secrets exist. Another puts merged +# sign-in on by itself once its two secrets exist. Another puts main's # console code into service, so a merge needs nobody at this machine. # The third signs the Android build GitHub makes, here where the key is, # and releases it. @@ -59,12 +64,30 @@ case "$PORT" in exit 1 ;; esac -for _ in 1 2 3 4 5 6 7 8 9 10; do - if curl -fsS "http://127.0.0.1:$PORT/console/health" >/dev/null 2>&1; then - echo "pm-console: running on http://127.0.0.1:$PORT/console/" - exit 0 +# The console says which commit it was started from. It has come up +# when it answers as this release's: an answer from anything else (the +# code before it, still running) is not that. +WANT="" +if [ -f "$SRC/.release" ]; then + WANT="$(sed -n 's/^commit=\([0-9a-f]\{12\}\).*/\1/p' "$SRC/.release" | head -n 1)" +fi +WAIT="${PM_CONSOLE_WAIT_SECONDS:-20}" +answered=no +got="" +for _ in $(seq 1 "$WAIT"); do + if said="$(curl -fsS "http://127.0.0.1:$PORT/console/health" 2>/dev/null)"; then + answered=yes + got="$(printf '%s' "$said" | sed -n 's/.*"version":"\([0-9a-f]\{12\}\)".*/\1/p')" + if [ -z "$WANT" ] || [ "$got" = "$WANT" ]; then + echo "pm-console: ${WANT:-this release} is running on http://127.0.0.1:$PORT/console/" + exit 0 + fi fi sleep 1 done -echo "pm-console: did not answer its health check; see: journalctl --user -u pm-console -n 50" >&2 +if [ "$answered" = yes ]; then + echo "pm-console: it answers its health check as ${got:-a build that does not say which it is}, not as $WANT; see: journalctl --user -u pm-console -n 50" >&2 +else + echo "pm-console: did not answer its health check; see: journalctl --user -u pm-console -n 50" >&2 +fi exit 1 diff --git a/pm-stack/console/redeploy.sh b/pm-stack/console/redeploy.sh index 38ecf294e6..78369b4edc 100755 --- a/pm-stack/console/redeploy.sh +++ b/pm-stack/console/redeploy.sh @@ -1,15 +1,31 @@ #!/usr/bin/env bash -# redeploy.sh — put merged console code into service on the host. +# redeploy.sh — put main's console code into service on this machine. # -# pm-console-redeploy.timer runs this every minute. It compares the -# console's code in the checkout (which pm-git-sync keeps at main) with -# the code that was last put into service. When they differ it first -# starts the new code in a self-check that listens on nothing, with the -# service's own settings; only if that passes does it run install.sh, -# which restarts the service. Code that does not start is left out of -# service, the old code keeps running, and this unit fails, which the -# console's Services screen and its notifications show. It is tried -# again only when the checkout moves to different code. +# The console runs from a copy of main that is its own, under +# ~/.local/share/pm-console: +# +# repo/ a clone that fetches only main from GitHub, and +# only the console's part of the tree +# releases// the console's files at one commit of main +# current -> releases/: what is in service +# +# Nothing else works there. Before, the console ran from the checkout +# the fleet's lanes work in and was whatever that checkout held: main's +# code from the day before, or another branch's (#13833). +# +# pm-console-redeploy.timer runs this every minute. It asks GitHub for +# main. When the console's code there, or its units, are not what is in +# service, it lays that commit's files out as a new release and starts +# them in a self-check that listens on nothing, with the service's own +# settings. Only if that passes is the release made current and its +# install.sh run, which restarts the service. A release that does not +# start, or does not come up in service, does not stay: the one before +# it is put back, this unit fails (which the console's Services screen +# and its notifications show), and that code is not tried again until +# main's console code changes. +# +# It runs the same from anywhere, and the first run on a machine makes +# the copy. # # Usage: bash redeploy.sh set -euo pipefail @@ -19,50 +35,91 @@ if [ "$#" -ne 0 ]; then exit 2 fi -cd "$(dirname "$0")" -SRC="$PWD" -REPO="$(git -C "$SRC" rev-parse --show-toplevel)" +SHARE="$HOME/.local/share/pm-console" STATE="$HOME/.local/state/pm-console" +REMOTE="${PM_CONSOLE_REMOTE:-https://github.com/developing-today/code.git}" +BRANCH=main BUN="${PM_CONSOLE_BUN:-/run/current-system/sw/bin/bun}" UNITS=(pm-console.service pm-console-expose.service pm-console-expose.timer pm-console-redeploy.service pm-console-redeploy.timer pm-console-android-release.service pm-console-android-release.timer) +# What of the repository the console needs on this machine: itself, the +# units it runs under, and the dashboard's list of its own pages. +CONSOLE=pm-stack/console +PAGES=pm-stack/aggregator/src/pages.ts +# How long GitHub may be out of reach before saying so is a failure. +UNREACHED_GRACE_SECONDS=1800 +# Releases kept besides the one in service and the one before it. +KEEP=3 -# What is in the checkout: the console's tree, and the units it runs -# under. A checkout that is part-way through an update (files that do -# not match its commit yet) is left for the next run — but not silently -# for hours (#13833): once it has skipped for more than a few minutes -# the run fails, which the console's Services screen and its -# notifications show, naming the paths that are stuck. -paths=(pm-stack/console) -for unit in "${UNITS[@]}"; do paths+=("pm-stack/systemd/$unit"); done -SKIP_GRACE_SECONDS=600 -SKIPPED="$STATE/deploy-skipped" -if ! git -C "$REPO" diff --quiet HEAD -- "${paths[@]}"; then - mkdir -p "$STATE" +mkdir -p "$SHARE/releases" "$STATE" +REPO="$SHARE/repo" +# One run at a time: a second one started meanwhile has nothing to add. +if command -v flock >/dev/null 2>&1; then + exec 9>"$SHARE/.lock" + flock -n 9 || exit 0 +fi + +# The clone, made if it is not there and put right if it has been +# changed: it asks GitHub for main alone, takes no file's contents until +# a checkout needs them, and checks out only the console's part. +if [ ! -d "$REPO/.git" ]; then + rm -rf "$REPO" + git init -q -b "$BRANCH" "$REPO" +fi +git -C "$REPO" config remote.origin.url "$REMOTE" +git -C "$REPO" config remote.origin.fetch "+refs/heads/$BRANCH:refs/remotes/origin/$BRANCH" +git -C "$REPO" config remote.origin.promisor true +git -C "$REPO" config remote.origin.partialclonefilter blob:none +git -C "$REPO" config core.sparseCheckout true +git -C "$REPO" config core.sparseCheckoutCone false +mkdir -p "$REPO/.git/info" +printf '/%s/\n/pm-stack/systemd/\n/%s\n' "$CONSOLE" "$PAGES" >"$REPO/.git/info/sparse-checkout" + +if ! git -C "$REPO" fetch --quiet --depth 1 --filter=blob:none origin "$BRANCH" 2>"$STATE/fetch.log"; then now="$(date +%s)" - first="$(cat "$SKIPPED" 2>/dev/null || true)" + first="$(cat "$STATE/unreached" 2>/dev/null || true)" case "$first" in - '' | *[!0-9]*) first="$now" && printf '%s\n' "$first" >"$SKIPPED" ;; + '' | *[!0-9]*) first="$now" && printf '%s\n' "$first" >"$STATE/unreached" ;; esac - if [ "$((now - first))" -ge "$SKIP_GRACE_SECONDS" ]; then - echo "redeploy: the checkout has been part-way through an update for $(((now - first) / 60)) minutes; the code in service is unchanged. Still different from its commit:" >&2 - git -C "$REPO" status --porcelain -- "${paths[@]}" >&2 + if [ "$((now - first))" -ge "$UNREACHED_GRACE_SECONDS" ]; then + echo "redeploy: GitHub has not answered for $(((now - first) / 60)) minutes; the code in service is unchanged:" >&2 + tail -n 5 "$STATE/fetch.log" >&2 exit 1 fi exit 0 fi -rm -f "$SKIPPED" -want="$(for path in "${paths[@]}"; do git -C "$REPO" rev-parse "HEAD:$path"; done | tr '\n' ' ')" +rm -f "$STATE/unreached" +sha="$(git -C "$REPO" rev-parse --verify "refs/remotes/origin/$BRANCH^{commit}")" + +# What main holds of the console: its tree, each unit, and the list of +# pages. (Names in a tree, so nothing has to be downloaded to tell.) +tree="$(git -C "$REPO" rev-parse --verify "$sha:$CONSOLE")" +want="$tree" +for unit in "${UNITS[@]}"; do + want+=" $(git -C "$REPO" rev-parse --verify "$sha:pm-stack/systemd/$unit")" +done +want+=" $(git -C "$REPO" rev-parse --verify --quiet "$sha:$PAGES" || echo none)" have="$(cat "$STATE/deployed" 2>/dev/null || true)" -if [ "$want" = "$have" ]; then +if [ "$want" = "$have" ] && [ -f "$SHARE/current/$CONSOLE/src/server.ts" ]; then exit 0 fi if [ "$want" = "$(cat "$STATE/deploy-failed" 2>/dev/null || true)" ]; then - echo "redeploy: this code did not pass its self-check (see $STATE/redeploy.log); the code in service is unchanged" >&2 + echo "redeploy: main's console code did not go into service when it was tried (see $STATE/redeploy.log); the code in service is unchanged" >&2 exit 1 fi -mkdir -p "$STATE" +# That commit's files, laid out as a release of their own. The clone's +# working tree is made exactly the commit first: nothing edited there, +# and nothing left behind from a commit before. +git -C "$REPO" checkout --quiet --force --detach "$sha" +git -C "$REPO" clean -qfdx +release="$SHARE/releases/$sha" +rm -rf "$release" "$release.new" +mkdir -p "$release.new" +cp -a "$REPO/pm-stack" "$release.new/pm-stack" +printf 'commit=%s\ntree=%s\n' "$sha" "$tree" >"$release.new/$CONSOLE/.release" +mv "$release.new" "$release" + # The service's own settings, read the way systemd reads them: one # KEY=value a line, and one pair of quotes around a value is not part of # the value (install.sh reads PM_CONSOLE_PORT="4872" the same way). @@ -83,14 +140,52 @@ if [ -f "$STATE/.env" ]; then esac done <"$STATE/.env" fi -if ! (cd "$SRC" && env "${settings[@]}" "$BUN" run src/server.ts --check) >"$STATE/redeploy.log" 2>&1; then +if ! (cd "$release/$CONSOLE" && env "${settings[@]}" "$BUN" run src/server.ts --check) >"$STATE/redeploy.log" 2>&1; then printf '%s' "$want" >"$STATE/deploy-failed" - echo "redeploy: the new code does not start; the code in service is unchanged:" >&2 + rm -rf "$release" + echo "redeploy: main's console code does not start; the code in service is unchanged:" >&2 tail -n 20 "$STATE/redeploy.log" >&2 exit 1 fi -bash "$SRC/install.sh" +# Into service: the link is moved in one step, and the release's own +# install.sh restarts the service and waits for it to answer as itself. +serve() { + ln -sfn "$1" "$SHARE/current.new" + mv -T "$SHARE/current.new" "$SHARE/current" + bash "$SHARE/current/$CONSOLE/install.sh" +} +before="$(readlink "$SHARE/current" 2>/dev/null || true)" +if ! serve "releases/$sha"; then + printf '%s' "$want" >"$STATE/deploy-failed" + if [ -n "$before" ] && [ "$before" != "releases/$sha" ] && [ -f "$SHARE/$before/$CONSOLE/install.sh" ]; then + if serve "$before"; then + echo "redeploy: ${sha:0:12} did not come up in service; ${before#releases/} is back in service" >&2 + else + echo "redeploy: ${sha:0:12} did not come up in service, and neither did ${before#releases/} when it was put back" >&2 + fi + else + echo "redeploy: ${sha:0:12} did not come up in service, and there is no release before it to put back" >&2 + fi + exit 1 +fi printf '%s' "$want" >"$STATE/deployed" rm -f "$STATE/deploy-failed" -echo "redeploy: $(git -C "$REPO" rev-parse --short HEAD) is in service" + +# Old releases are cleared away: the newest few are kept, and always +# the one in service and the one before it. +kept=0 +while IFS= read -r name; do + case "$name" in + *[!0-9a-f]* | '') continue ;; + esac + [ "${#name}" -eq 40 ] || continue + if [ "releases/$name" = "releases/$sha" ] || [ "releases/$name" = "$before" ]; then + continue + fi + kept=$((kept + 1)) + if [ "$kept" -gt "$((KEEP - 2))" ]; then + rm -rf "${SHARE:?}/releases/$name" + fi +done < <(ls -1t "$SHARE/releases") +echo "redeploy: ${sha:0:12} is in service" diff --git a/pm-stack/console/src/server.ts b/pm-stack/console/src/server.ts index 61a5890cd0..96874d5f16 100644 --- a/pm-stack/console/src/server.ts +++ b/pm-stack/console/src/server.ts @@ -229,7 +229,10 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul // Public, unauthenticated: nothing here says anything about the fleet. if (path === "/.well-known/assetlinks.json" && method === "GET") return json(assetLinks(deps.cfg)); - if (path === `${BASE}/health` && method === "GET") return json({ ok: true }); + // Which commit this console was started from, where it knows: + // install.sh waits for the console to answer as the release it has + // just put into service. + if (path === `${BASE}/health` && method === "GET") return json({ ok: true, version: deps.self?.version ?? null }); if (path === "/manifest.webmanifest" && method === "GET") return manifest(); // Not behind the sign-in, and checked here instead: a linked phone. if (deps.phones && deps.docs) { @@ -665,10 +668,27 @@ export function androidBuild(path: string) { }; } +/** What a release laid out by redeploy.sh says of itself, in the file + * beside its code: the commit of main it is, and its console's tree. + * Null for anything that is not such a file. */ +export function releaseSaid(text: string): { commit: string; tree: string | null } | null { + const commit = /^commit=([0-9a-f]{40})$/m.exec(text)?.[1]; + if (!commit) return null; + return { commit, tree: /^tree=([0-9a-f]{40})$/m.exec(text)?.[1] ?? null }; +} + /** The commit this console was started from, or nothing if it cannot - * be told (not a checkout, no git). The service is restarted when a - * merge is put into service, so this is the code that is running. */ + * be told. In service it runs from a release, which says; started from + * a checkout (by hand, or in a test), the checkout is asked. The + * service is restarted when a release is put into service, so this is + * the code that is running. */ async function runningCommit(): Promise { + try { + const said = releaseSaid(readFileSync(join(import.meta.dir, "..", ".release"), "utf8")); + if (said) return said.commit.slice(0, 12); + } catch { + // Not a release: a checkout. + } try { const git = Bun.spawn(["git", "-C", import.meta.dir, "rev-parse", "--short=12", "HEAD"], { stdout: "pipe", diff --git a/pm-stack/console/test/console.test.ts b/pm-stack/console/test/console.test.ts index f3b4e040f4..8a6adcb87c 100644 --- a/pm-stack/console/test/console.test.ts +++ b/pm-stack/console/test/console.test.ts @@ -29,7 +29,7 @@ import { import { type Config, ConfigError, type Issuer, readConfig } from "../src/config.ts"; import { HOLDABLE } from "../src/edge-proto.ts"; import { manageable, OpError, Ops, parseUnitFiles, parseUnits, type Run, triagePacket } from "../src/ops.ts"; -import { assetLinks, type Deps, handle } from "../src/server.ts"; +import { assetLinks, type Deps, handle, releaseSaid } from "../src/server.ts"; const NOW = 1_800_000_000_000; const ACCESS: Issuer = { @@ -1115,6 +1115,26 @@ describe("HTTP surface", () => { headers: { host: "pm.security.cab", "content-type": "application/json", ...headers }, }); + // A release laid out by redeploy.sh says which commit it is in a + // file beside the code. The oracle is that file's two lines as the + // script writes them (test/redeploy.test.ts reads the same file back). + test("a release says which commit it is, and anything that is not such a file says nothing", () => { + const commit = "0123456789abcdef0123456789abcdef01234567"; + const tree = "89abcdef0123456789abcdef0123456789abcdef"; + expect(releaseSaid(`commit=${commit}\ntree=${tree}\n`)).toEqual({ commit, tree }); + expect(releaseSaid(`commit=${commit}\n`)).toEqual({ commit, tree: null }); + for (const text of [ + "", + "commit=abc\n", + `tree=${tree}\n`, + `commit=${commit}0\n`, + ` commit=${commit}\n`, + `COMMIT=${commit}\n`, + ]) { + expect([text, releaseSaid(text)]).toEqual([text, null]); + } + }); + test("only the asset links and the health check answer without sign-in", async () => { const d = deps(401); const links = await handle(get("/.well-known/assetlinks.json"), d); @@ -1122,7 +1142,13 @@ describe("HTTP surface", () => { expect(await links.json()).toEqual(assetLinks(CFG)); expect(assetLinks(CFG)[0]).toMatchObject({ target: { package_name: "today.developing.pmconsole" } }); expect(assetLinks({ androidPackage: "p", androidFingerprints: [] })).toEqual([]); - expect(await (await handle(get("/console/health"), d)).json()).toEqual({ ok: true }); + // The health check says which commit this console was started from, + // where it knows: install.sh waits for it to answer as the release + // it has just put into service. + expect(await (await handle(get("/console/health"), d)).json()).toEqual({ ok: true, version: null }); + expect( + await (await handle(get("/console/health"), { ...d, self: { name: "amd", version: "0123456789ab" } })).json(), + ).toEqual({ ok: true, version: "0123456789ab" }); for (const path of [ "/console/", "/console/app.js", diff --git a/pm-stack/console/test/install.test.ts b/pm-stack/console/test/install.test.ts new file mode 100644 index 0000000000..039db7ba90 --- /dev/null +++ b/pm-stack/console/test/install.test.ts @@ -0,0 +1,211 @@ +// install.sh, run for real in a made-up home directory. +// +// The script under test is this repository's own file, placed in a +// release laid out the way redeploy.sh lays one out. Two programs are +// stand-ins, found first on its PATH: `systemctl` (records what it was +// asked) and `curl` (answers the console's health check as told). The +// oracle is what a machine must have afterwards: the release's own unit +// files installed, the service restarted, and success only when the +// console answers as that release's commit. +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { + chmodSync, + cpSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +const SCRIPT = join(import.meta.dir, "..", "install.sh"); +const SYSTEMD = join(import.meta.dir, "..", "..", "systemd"); +const UNITS = [ + "pm-console.service", + "pm-console-expose.service", + "pm-console-expose.timer", + "pm-console-redeploy.service", + "pm-console-redeploy.timer", + "pm-console-android-release.service", + "pm-console-android-release.timer", +]; +const COMMIT = "0123456789abcdef0123456789abcdef01234567"; + +let dir: string; +let home: string; +let share: string; +let log: string; + +/** A release as redeploy.sh lays one out, holding this repository's install.sh and units. */ +function release(commit: string, says = true) { + const root = join(share, "releases", commit); + mkdirSync(join(root, "pm-stack/console"), { recursive: true }); + mkdirSync(join(root, "pm-stack/systemd"), { recursive: true }); + cpSync(SCRIPT, join(root, "pm-stack/console/install.sh")); + for (const unit of UNITS) cpSync(join(SYSTEMD, unit), join(root, "pm-stack/systemd", unit)); + if (says) writeFileSync(join(root, "pm-stack/console/.release"), `commit=${commit}\ntree=${"a".repeat(40)}\n`); + return root; +} + +function serve(commit: string) { + rmSync(join(share, "current"), { force: true }); + symlinkSync(`releases/${commit}`, join(share, "current")); +} + +function run(script: string, env: Record = {}) { + const done = Bun.spawnSync(["bash", script], { + cwd: dir, + env: { + ...process.env, + HOME: home, + PATH: `${join(dir, "bin")}:${process.env.PATH}`, + PM_CONSOLE_WAIT_SECONDS: "2", + HEALTH: `{"ok":true,"version":"${COMMIT.slice(0, 12)}"}`, + ...env, + }, + }); + return { code: done.exitCode, out: done.stdout.toString(), err: done.stderr.toString() }; +} + +const events = () => (existsSync(log) ? readFileSync(log, "utf8").trim().split("\n").filter(Boolean) : []); +const installed = (unit: string) => join(home, ".config/systemd/user", unit); + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "pm-install-")); + home = join(dir, "home"); + share = join(home, ".local/share/pm-console"); + log = join(dir, "events.log"); + mkdirSync(join(dir, "bin"), { recursive: true }); + mkdirSync(share, { recursive: true }); + writeFileSync(join(dir, "bin/systemctl"), `#!/usr/bin/env bash\necho "systemctl $*" >>"${log}"\n`); + // The console's health check: answers what the test says, or not at all. + writeFileSync( + join(dir, "bin/curl"), + `#!/usr/bin/env bash\necho "curl \${*: -1}" >>"${log}"\n[ "$HEALTH" = none ] && exit 7\nprintf '%s' "$HEALTH"\n`, + ); + // No waiting between tries. + writeFileSync(join(dir, "bin/sleep"), "#!/usr/bin/env bash\nexit 0\n"); + for (const name of ["systemctl", "curl", "sleep"]) chmodSync(join(dir, "bin", name), 0o755); +}); + +afterEach(() => rmSync(dir, { recursive: true, force: true })); + +describe("install.sh", () => { + test("from the release in service: its own units are installed, the console restarted, and it has come up when it answers as that release", () => { + const root = release(COMMIT); + serve(COMMIT); + const done = run(join(root, "pm-stack/console/install.sh")); + expect([done.code, done.err]).toEqual([0, ""]); + expect(done.out).toContain(`${COMMIT.slice(0, 12)} is running on http://127.0.0.1:4872/console/`); + // Every unit of the console, as this release has it. + for (const unit of UNITS) { + expect(readFileSync(installed(unit), "utf8")).toBe(readFileSync(join(SYSTEMD, unit), "utf8")); + } + // A settings file is made where there was none, for the owner alone to read. + expect(readFileSync(join(home, ".local/state/pm-console/.env"), "utf8")).toBe( + "PM_CONSOLE_PORT=4872\nPM_CONSOLE_OWNER_EMAILS=\n", + ); + expect(events()).toEqual([ + "systemctl --user daemon-reload", + "systemctl --user enable pm-console.service", + "systemctl --user restart pm-console.service", + "systemctl --user enable --now pm-console-expose.timer pm-console-redeploy.timer pm-console-android-release.timer", + "curl http://127.0.0.1:4872/console/health", + ]); + }); + + test("run through the link that says which release is in service, it is the same release", () => { + release(COMMIT); + serve(COMMIT); + expect(run(join(share, "current/pm-stack/console/install.sh")).code).toBe(0); + }); + + test("the units it installs run the console from the release in service, and nothing from a checkout someone works in", () => { + for (const unit of UNITS.filter((name) => name.endsWith(".service"))) { + const text = readFileSync(join(SYSTEMD, unit), "utf8"); + expect([unit, /git\/code/.test(text)]).toEqual([unit, false]); + expect([unit, text.includes("%h/.local/share/pm-console/current/pm-stack/console")]).toEqual([unit, true]); + } + }); + + test("an existing settings file is never overwritten, and its port is the one asked", () => { + const root = release(COMMIT); + serve(COMMIT); + mkdirSync(join(home, ".local/state/pm-console"), { recursive: true }); + writeFileSync( + join(home, ".local/state/pm-console/.env"), + 'PM_CONSOLE_PORT="4999"\nPM_CONSOLE_OWNER_EMAILS=o@example.com\n', + ); + expect(run(join(root, "pm-stack/console/install.sh")).code).toBe(0); + expect(readFileSync(join(home, ".local/state/pm-console/.env"), "utf8")).toBe( + 'PM_CONSOLE_PORT="4999"\nPM_CONSOLE_OWNER_EMAILS=o@example.com\n', + ); + expect(events().at(-1)).toBe("curl http://127.0.0.1:4999/console/health"); + }); + + test("an answer from other code than this release's is not having come up: it fails, saying which answered", () => { + const root = release(COMMIT); + serve(COMMIT); + const other = run(join(root, "pm-stack/console/install.sh"), { HEALTH: '{"ok":true,"version":"ffffffffffff"}' }); + expect(other.code).toBe(1); + expect(other.err).toContain(`it answers its health check as ffffffffffff, not as ${COMMIT.slice(0, 12)}`); + // Asked for as long as it was given, not once. + expect(events().filter((e) => e.startsWith("curl"))).toHaveLength(2); + // Code from before the console said which commit it is: also not this release. + const old = run(join(root, "pm-stack/console/install.sh"), { HEALTH: '{"ok":true}' }); + expect(old.code).toBe(1); + expect(old.err).toContain("a build that does not say which it is"); + }); + + test("no answer at all fails, and says where to look", () => { + const root = release(COMMIT); + serve(COMMIT); + const done = run(join(root, "pm-stack/console/install.sh"), { HEALTH: "none" }); + expect(done.code).toBe(1); + expect(done.err).toContain("did not answer its health check"); + expect(done.err).toContain("journalctl --user -u pm-console"); + }); + + test("a release that does not say which commit it is has come up when the console answers at all", () => { + const root = release(COMMIT, false); + serve(COMMIT); + expect(run(join(root, "pm-stack/console/install.sh"), { HEALTH: '{"ok":true}' }).code).toBe(0); + }); + + test("from anywhere but the release in service it does nothing, and says how it is meant to be run", () => { + const root = release(COMMIT); + const other = release("f".repeat(40)); + serve("f".repeat(40)); + // Another release than the one in service, and a copy in no release at all. + const stray = join(dir, "checkout/pm-stack/console"); + mkdirSync(stray, { recursive: true }); + cpSync(SCRIPT, join(stray, "install.sh")); + for (const script of [join(root, "pm-stack/console/install.sh"), join(stray, "install.sh")]) { + const done = run(script); + expect(done.code).toBe(1); + expect(done.err).toContain("this is not the release in service"); + expect(done.err).toContain("Run redeploy.sh"); + } + expect(events()).toEqual([]); + expect(existsSync(installed("pm-console.service"))).toBe(false); + expect(existsSync(other)).toBe(true); + // With nothing in service at all, the same. + rmSync(join(share, "current")); + expect(run(join(root, "pm-stack/console/install.sh")).code).toBe(1); + expect(events()).toEqual([]); + }); + + test("it takes no arguments", () => { + const root = release(COMMIT); + serve(COMMIT); + const done = Bun.spawnSync(["bash", join(root, "pm-stack/console/install.sh"), "--now"], { + env: { ...process.env, HOME: home, PATH: `${join(dir, "bin")}:${process.env.PATH}` }, + }); + expect(done.exitCode).toBe(2); + expect(events()).toEqual([]); + }); +}); diff --git a/pm-stack/console/test/redeploy.test.ts b/pm-stack/console/test/redeploy.test.ts index 94319cecba..90c258f6e4 100644 --- a/pm-stack/console/test/redeploy.test.ts +++ b/pm-stack/console/test/redeploy.test.ts @@ -1,13 +1,30 @@ -// redeploy.sh, run for real against a small checkout made here. +// redeploy.sh, run for real against a stand-in for GitHub made here. // -// The script under test is this repository's own file, copied into a -// throwaway git repository shaped like the real one. Two things are -// stand-ins: the program that starts the console's self-check (a script -// that records what it was given and passes or fails as told) and -// install.sh (a script that records that it ran). Everything else, git -// included, is the real thing. +// The script under test is this repository's own file. GitHub is a bare +// git repository on disk, reached over git's own protocol and allowing +// the partial fetches GitHub allows; "main" there is whatever a working +// copy beside it last pushed. Two things are stand-ins: the program +// that starts the console's self-check (a script that records what it +// was given and passes or fails as told) and install.sh (a script that +// records that it ran, and fails in a release written to). Everything +// else, git included, is the real thing. +// +// The oracle for "what is in service" is the commit pushed to main: +// its files, read back from git, against the files of the release the +// script made current. import { afterEach, beforeEach, describe, expect, test } from "bun:test"; -import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { + chmodSync, + cpSync, + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + readlinkSync, + rmSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -23,18 +40,22 @@ const UNITS = [ ]; let dir: string; -let repo: string; +let origin: string; +let work: string; let home: string; +let share: string; let log: string; -function sh(cwd: string, ...argv: string[]) { - const done = Bun.spawnSync(argv, { cwd, env: { ...process.env, HOME: home, GIT_CONFIG_GLOBAL: "/dev/null" } }); +function sh(cwd: string, argv: string[], env: Record = {}) { + const done = Bun.spawnSync(argv, { + cwd, + env: { ...process.env, HOME: home, GIT_CONFIG_GLOBAL: "/dev/null", ...env }, + }); return { code: done.exitCode, out: done.stdout.toString(), err: done.stderr.toString() }; } -function git(...args: string[]) { - const done = sh( - repo, +function git(cwd: string, ...args: string[]) { + const done = sh(cwd, [ "git", "-c", "user.name=t", @@ -43,24 +64,31 @@ function git(...args: string[]) { "-c", "commit.gpgsign=false", ...args, - ); + ]); if (done.code !== 0) throw new Error(`git ${args.join(" ")}: ${done.err}`); return done.out.trim(); } -function run(env: Record = {}) { - const done = Bun.spawnSync(["bash", join(repo, "pm-stack/console/redeploy.sh")], { - cwd: dir, - env: { - ...process.env, - HOME: home, - GIT_CONFIG_GLOBAL: "/dev/null", - PM_CONSOLE_BUN: join(dir, "fake-bun"), - CHECK: "pass", - ...env, - }, +/** Run the script, from a copy that sits in no checkout at all unless a test says otherwise. */ +function run(env: Record = {}, script = join(dir, "redeploy.sh"), cwd = dir) { + return sh(cwd, ["bash", script], { + PM_CONSOLE_BUN: join(dir, "fake-bun"), + PM_CONSOLE_REMOTE: `file://${origin}`, + CHECK: "pass", + ...env, }); - return { code: done.exitCode, out: done.stdout.toString(), err: done.stderr.toString() }; +} + +/** Change files in the working copy, commit, and push to "GitHub"'s main. Answers the commit. */ +function push(message: string, files: Record) { + for (const [path, text] of Object.entries(files)) { + mkdirSync(join(work, path, ".."), { recursive: true }); + writeFileSync(join(work, path), text); + } + git(work, "add", "-A"); + git(work, "commit", "-q", "-m", message); + git(work, "push", "-q", "origin", "HEAD:main"); + return git(work, "rev-parse", "HEAD"); } const events = () => (existsSync(log) ? readFileSync(log, "utf8").trim().split("\n").filter(Boolean) : []); @@ -68,24 +96,36 @@ const state = (name: string) => { const path = join(home, ".local/state/pm-console", name); return existsSync(path) ? readFileSync(path, "utf8") : null; }; +/** The release in service, as the link says. */ +const current = () => (existsSync(join(share, "current")) ? readlinkSync(join(share, "current")) : null); +const releases = () => (existsSync(join(share, "releases")) ? readdirSync(join(share, "releases")).sort() : []); +const inService = (path: string) => readFileSync(join(share, "current", path), "utf8"); +/** A stand-in for install.sh that records the release it ran from, and fails if told to. */ +const installer = (fails = false) => + `echo "install $(basename "$(cd "$(dirname "$0")/../.." && pwd -P)")" >>"${log}"\n${fails ? "exit 1\n" : ""}`; beforeEach(() => { dir = mkdtempSync(join(tmpdir(), "pm-redeploy-")); - repo = join(dir, "repo"); + origin = join(dir, "origin.git"); + work = join(dir, "work"); home = join(dir, "home"); + share = join(home, ".local/share/pm-console"); log = join(dir, "events.log"); - mkdirSync(join(repo, "pm-stack/console/src"), { recursive: true }); - mkdirSync(join(repo, "pm-stack/systemd"), { recursive: true }); mkdirSync(join(home, ".local/state/pm-console"), { recursive: true }); - cpSync(SCRIPT, join(repo, "pm-stack/console/redeploy.sh")); - writeFileSync(join(repo, "pm-stack/console/install.sh"), `echo "install" >>"${log}"\n`); - writeFileSync(join(repo, "pm-stack/console/src/server.ts"), "// v1\n"); - for (const unit of UNITS) writeFileSync(join(repo, "pm-stack/systemd", unit), "[Unit]\n"); - // The stand-in for bun: records its arguments, the directory it ran - // in and one setting from the service's file, then passes or fails. + mkdirSync(work); + cpSync(SCRIPT, join(dir, "redeploy.sh")); + // "GitHub": bare, and allowing what GitHub allows a clone that takes only part of the tree. + git(dir, "init", "-q", "--bare", "-b", "main", origin); + git(origin, "config", "uploadpack.allowFilter", "true"); + git(origin, "config", "uploadpack.allowAnySHA1InWant", "true"); + git(work, "init", "-q", "-b", "main"); + git(work, "remote", "add", "origin", `file://${origin}`); + // The stand-in for bun: records its arguments, the directory and the + // release it ran in, and one setting from the service's file; then + // passes or fails. writeFileSync( join(dir, "fake-bun"), - `#!/usr/bin/env bash\necho "check $* in=$(basename "$PWD") port=\${PM_CONSOLE_PORT:-} note=\${PM_NOTE:-} plain=\${PM_PLAIN:-}" >>"${log}"\n[ "$CHECK" = pass ] || { echo "boom: cannot start" >&2; exit 1; }\necho "pm-console: check passed"\n`, + `#!/usr/bin/env bash\necho "check $* in=$(basename "$PWD") of=$(basename "$(cd ../.. && pwd -P)") port=\${PM_CONSOLE_PORT:-} note=\${PM_NOTE:-} plain=\${PM_PLAIN:-}" >>"${log}"\n[ "$CHECK" = pass ] || { echo "boom: cannot start"; exit 1; }\n`, ); chmodSync(join(dir, "fake-bun"), 0o755); // As systemd allows: a comment, a blank line, quoted values, a value with a space. @@ -93,131 +133,260 @@ beforeEach(() => { join(home, ".local/state/pm-console/.env"), '# settings\nPM_CONSOLE_PORT="4872"\n\nPM_NOTE=\'two words\'\nPM_PLAIN=it\'s "kept"\n', ); - git("init", "-q", "-b", "main"); - git("add", "-A"); - git("commit", "-q", "-m", "one"); + push("one", { + "pm-stack/console/src/server.ts": "// v1\n", + "pm-stack/console/public/app.js": "// app v1\n", + "pm-stack/console/redeploy.sh": readFileSync(SCRIPT, "utf8"), + "pm-stack/console/install.sh": installer(), + ...Object.fromEntries(UNITS.map((unit) => [`pm-stack/systemd/${unit}`, "[Unit]\n"])), + "pm-stack/systemd/pm-other.service": "[Unit]\n", + "pm-stack/aggregator/src/pages.ts": "export const PAGES = [];\n", + "pm-stack/aggregator/src/server.ts": "// the dashboard\n", + "README.md": "the rest of the repository\n", + "pkgs/id/src/main.rs": "fn main() {}\n", + }); }); afterEach(() => rmSync(dir, { recursive: true, force: true })); describe("redeploy.sh", () => { - test("new code is checked with the service's own settings, then put into service, once", () => { + test("the first run makes the console's own copy of main, checks it with the service's own settings, and puts it into service; once", () => { + const sha = git(work, "rev-parse", "HEAD"); const first = run(); - expect(first.code).toBe(0); - expect(first.out).toContain("is in service"); - // The check ran in the console's directory, with the settings file's values, spaces and all. + expect([first.code, first.err]).toEqual([0, ""]); + expect(first.out).toContain(`${sha.slice(0, 12)} is in service`); + // What is in service is that commit's console, laid out as a release of its own. + expect(current()).toBe(`releases/${sha}`); + expect(inService("pm-stack/console/src/server.ts")).toBe("// v1\n"); + expect(inService("pm-stack/systemd/pm-console.service")).toBe("[Unit]\n"); + expect(inService("pm-stack/aggregator/src/pages.ts")).toBe("export const PAGES = [];\n"); + // The release says which commit it is, and which tree its console is. + expect(inService("pm-stack/console/.release")).toBe( + `commit=${sha}\ntree=${git(work, "rev-parse", "HEAD:pm-stack/console")}\n`, + ); + // The check ran in that release's console directory, with the settings file's values, spaces and all; + // then that release's own install ran. expect(events()).toEqual([ - 'check run src/server.ts --check in=console port=4872 note=two words plain=it\'s "kept"', - "install", + `check run src/server.ts --check in=console of=${sha} port=4872 note=two words plain=it's "kept"`, + `install ${sha}`, ]); expect(state("deployed")).not.toBeNull(); - // Nothing has changed: nothing is checked or installed again. - expect(run().code).toBe(0); + // Nothing has changed on main: nothing is checked or installed again. + const again = run(); + expect([again.code, again.out, again.err]).toEqual([0, "", ""]); expect(events()).toHaveLength(2); }); - test("a change to the console or to one of its units is new code; a change elsewhere is not", () => { - run(); - writeFileSync(join(repo, "README.md"), "elsewhere\n"); - mkdirSync(join(repo, "pm-stack/aggregator"), { recursive: true }); - writeFileSync(join(repo, "pm-stack/aggregator/x.ts"), "x\n"); - writeFileSync(join(repo, "pm-stack/systemd/pm-other.service"), "[Unit]\n"); - git("add", "-A"); - git("commit", "-q", "-m", "elsewhere"); - run(); - expect(events()).toHaveLength(2); - writeFileSync(join(repo, "pm-stack/systemd/pm-console.service"), "[Unit]\nDescription=changed\n"); - git("commit", "-q", "-am", "unit"); + test("only the console's part of main is brought to this machine", () => { run(); - expect(events()).toHaveLength(4); - writeFileSync(join(repo, "pm-stack/console/src/server.ts"), "// v2\n"); - git("commit", "-q", "-am", "code"); + const listed = sh(join(share, "current"), ["find", ".", "-type", "f"]).out.trim().split("\n").sort(); + expect(listed).toEqual( + [ + "./pm-stack/aggregator/src/pages.ts", + "./pm-stack/console/.release", + "./pm-stack/console/install.sh", + "./pm-stack/console/public/app.js", + "./pm-stack/console/redeploy.sh", + "./pm-stack/console/src/server.ts", + ...UNITS.map((unit) => `./pm-stack/systemd/${unit}`), + "./pm-stack/systemd/pm-other.service", + ].sort(), + ); + // And the clone it is made from holds no file of the rest either. + expect(existsSync(join(share, "repo/README.md"))).toBe(false); + expect(existsSync(join(share, "repo/pkgs"))).toBe(false); + expect(existsSync(join(share, "repo/pm-stack/aggregator/src/server.ts"))).toBe(false); + }); + + test("what goes into service is main as GitHub has it, whatever the checkout the script is run from holds", () => { + const main = git(work, "rev-parse", "HEAD"); + // A checkout someone is working in: on another branch, with other + // console code committed there and more of it half-written on disk. + const lanes = join(dir, "lanes"); + git(dir, "clone", "-q", `file://${origin}`, lanes); + git(lanes, "checkout", "-q", "-b", "someone/elses-work"); + writeFileSync(join(lanes, "pm-stack/console/src/server.ts"), "// another branch's console\n"); + git(lanes, "commit", "-q", "-am", "theirs"); + writeFileSync(join(lanes, "pm-stack/console/public/app.js"), "// half written\n"); + const done = run({}, join(lanes, "pm-stack/console/redeploy.sh"), join(lanes, "pm-stack/console")); + expect(done.code).toBe(0); + expect(current()).toBe(`releases/${main}`); + expect(inService("pm-stack/console/src/server.ts")).toBe("// v1\n"); + expect(inService("pm-stack/console/public/app.js")).toBe("// app v1\n"); + // That checkout is as it was: its branch, its commit, its half-written file. + expect(git(lanes, "rev-parse", "--abbrev-ref", "HEAD")).toBe("someone/elses-work"); + expect(git(lanes, "status", "--porcelain")).toBe("M pm-stack/console/public/app.js"); + expect(readFileSync(join(lanes, "pm-stack/console/public/app.js"), "utf8")).toBe("// half written\n"); + }); + + test("a change on main to the console, one of its units or the dashboard's list of pages is new code; a change elsewhere is not", () => { run(); - expect(events()).toHaveLength(6); + const first = current(); + push("elsewhere", { + "README.md": "changed\n", + "pm-stack/aggregator/src/server.ts": "// changed\n", + "pm-stack/systemd/pm-other.service": "[Unit]\nDescription=changed\n", + "pkgs/id/src/main.rs": "fn main() { }\n", + }); + expect(run().code).toBe(0); + expect([current(), events().length]).toEqual([first, 2]); + const unit = push("unit", { "pm-stack/systemd/pm-console.service": "[Unit]\nDescription=changed\n" }); + expect(run().code).toBe(0); + expect([current(), events().length]).toEqual([`releases/${unit}`, 4]); + expect(inService("pm-stack/systemd/pm-console.service")).toBe("[Unit]\nDescription=changed\n"); + const code = push("code", { "pm-stack/console/src/server.ts": "// v2\n" }); + expect(run().code).toBe(0); + expect([current(), events().length]).toEqual([`releases/${code}`, 6]); + expect(inService("pm-stack/console/src/server.ts")).toBe("// v2\n"); + const pages = push("pages", { "pm-stack/aggregator/src/pages.ts": "export const PAGES = [1];\n" }); + expect(run().code).toBe(0); + expect([current(), events().length]).toEqual([`releases/${pages}`, 8]); + // A file taken off main is not left behind in the next release. + git(work, "rm", "-q", "pm-stack/console/public/app.js"); + git(work, "commit", "-q", "-m", "app removed"); + git(work, "push", "-q", "origin", "HEAD:main"); + expect(run().code).toBe(0); + expect(existsSync(join(share, "current/pm-stack/console/public/app.js"))).toBe(false); }); - test("code that does not start is never put into service, and is not tried again until the code changes", () => { + test("code that does not start is never put into service, and is not tried again until main's code changes", () => { run(); - const inService = state("deployed"); - writeFileSync(join(repo, "pm-stack/console/src/server.ts"), "// broken\n"); - git("commit", "-q", "-am", "broken"); + const good = current(); + const was = state("deployed"); + const broken = push("broken", { "pm-stack/console/src/server.ts": "// broken\n" }); const bad = run({ CHECK: "fail" }); expect(bad.code).toBe(1); expect(bad.err).toContain("the code in service is unchanged"); expect(bad.err).toContain("boom: cannot start"); - expect(events().filter((e) => e === "install")).toHaveLength(1); - expect(state("deployed")).toBe(inService); + // The release before it is still the one in service, and the one that failed is not kept. + expect(current()).toBe(good); + expect(releases()).not.toContain(broken); + expect(events().filter((e) => e.startsWith("install"))).toHaveLength(1); + expect(state("deployed")).toBe(was); // The next minute: still failed, and the check is not run again. - const again = run({ CHECK: "fail" }); - expect(again.code).toBe(1); + expect(run({ CHECK: "fail" }).code).toBe(1); expect(events().filter((e) => e.startsWith("check"))).toHaveLength(2); // Even if it would pass now: the same code is the same verdict. expect(run({ CHECK: "pass" }).code).toBe(1); + expect(current()).toBe(good); // A fix arrives: checked, installed, and the failure is forgotten. - writeFileSync(join(repo, "pm-stack/console/src/server.ts"), "// fixed\n"); - git("commit", "-q", "-am", "fixed"); + const fixed = push("fixed", { "pm-stack/console/src/server.ts": "// fixed\n" }); expect(run().code).toBe(0); - expect(events().filter((e) => e === "install")).toHaveLength(2); + expect(current()).toBe(`releases/${fixed}`); expect(state("deploy-failed")).toBeNull(); - expect(state("deployed")).not.toBe(inService); + expect(state("deployed")).not.toBe(was); }); - test("a checkout part-way through an update is left for the next run", () => { + test("a release that does not come up in service is taken out again, and the one before it is put back", () => { run(); - // A file changed on disk that its commit does not have yet. - writeFileSync(join(repo, "pm-stack/console/src/server.ts"), "// half written\n"); - const mid = run(); - expect(mid.code).toBe(0); - expect(events()).toHaveLength(2); + const good = current(); + const goodSha = (good as string).replace("releases/", ""); + const was = state("deployed"); + // It passes its self-check, and then its install fails: the service did not come up as it. + const bad = push("does not come up", { "pm-stack/console/install.sh": installer(true) }); + const done = run(); + expect(done.code).toBe(1); + expect(done.err).toContain("did not come up in service"); + expect(done.err).toContain("is back in service"); + expect(current()).toBe(good); + // Its install ran, failed, and the one before it was installed again. + expect(events().slice(2)).toEqual([ + `check run src/server.ts --check in=console of=${bad} port=4872 note=two words plain=it's "kept"`, + `install ${bad}`, + `install ${goodSha}`, + ]); + expect(state("deployed")).toBe(was); + // It is not tried again while main's code is the same ... + expect(run().code).toBe(1); + expect(events()).toHaveLength(5); + // Main goes back to exactly the code in service: there is nothing + // to put into service, and nothing is failing any more. + push("reverted", { "pm-stack/console/install.sh": installer() }); + const back = run(); + expect([back.code, back.out, back.err]).toEqual([0, "", ""]); + expect([current(), events().length]).toEqual([good, 5]); + // And when main's code is new again, it is tried again. + const fixed = push("comes up", { "pm-stack/console/src/server.ts": "// v2\n" }); + expect(run().code).toBe(0); + expect(current()).toBe(`releases/${fixed}`); + expect(state("deploy-failed")).toBeNull(); + }); + + test("the very first release not coming up leaves nothing marked as in service", () => { + const sha = push("does not come up", { "pm-stack/console/install.sh": installer(true) }); + const done = run(); + expect(done.code).toBe(1); + expect(done.err).toContain("there is no release before it to put back"); + expect(state("deployed")).toBeNull(); + expect(events()).toEqual([ + `check run src/server.ts --check in=console of=${sha} port=4872 note=two words plain=it's "kept"`, + `install ${sha}`, + ]); }); - test("a skip that lasts more than a few minutes fails loudly instead of staying silent", () => { + test("with GitHub out of reach nothing changes: quietly at first, and as a failure once it has been half an hour", () => { run(); - const inService = state("deployed"); - // A file changed on disk that its commit does not have yet. - writeFileSync(join(repo, "pm-stack/console/src/server.ts"), "// half written\n"); - // The first skip is quiet, and records when the skipping started. - expect(run().code).toBe(0); + const good = current(); + const nowhere = { PM_CONSOLE_REMOTE: `file://${join(dir, "no-such.git")}` }; + const quiet = run(nowhere); + expect([quiet.code, quiet.out]).toEqual([0, ""]); + expect(current()).toBe(good); + expect(state("unreached")).not.toBeNull(); expect(events()).toHaveLength(2); - expect(state("deploy-skipped")).not.toBeNull(); - // Still half-written past the grace period: the run fails, which - // the console's Services screen and its notifications show, naming - // what is stuck. Nothing is put into service. - const stale = `${Math.floor(Date.now() / 1000) - 601}\n`; - writeFileSync(join(home, ".local/state/pm-console/deploy-skipped"), stale); - const loud = run(); + // Twenty-nine minutes of it: still quiet. + const ago = (minutes: number) => `${Math.floor(Date.now() / 1000) - minutes * 60}\n`; + writeFileSync(join(home, ".local/state/pm-console/unreached"), ago(29)); + expect(run(nowhere).code).toBe(0); + // Thirty-one: the run fails, which the Services screen and the notifications show. + writeFileSync(join(home, ".local/state/pm-console/unreached"), ago(31)); + const loud = run(nowhere); expect(loud.code).toBe(1); - expect(loud.err).toContain("part-way through an update"); - expect(loud.err).toContain("server.ts"); - expect(events()).toHaveLength(2); - expect(state("deployed")).toBe(inService); + expect(loud.err).toContain("GitHub has not answered for 31 minutes"); + expect(loud.err).toContain("the code in service is unchanged"); + expect(current()).toBe(good); + // Reached again: forgotten, and main is followed as before. + const next = push("after", { "pm-stack/console/src/server.ts": "// after\n" }); + expect(run().code).toBe(0); + expect(state("unreached")).toBeNull(); + expect(current()).toBe(`releases/${next}`); }); - test("the skip record is forgotten once the checkout is whole again", () => { + test("old releases are cleared away; the one in service and the one before it are always kept", () => { + const made: string[] = [git(work, "rev-parse", "HEAD")]; run(); - writeFileSync(join(repo, "pm-stack/console/src/server.ts"), "// half written\n"); + for (let n = 2; n <= 6; n++) { + made.push(push(`v${n}`, { "pm-stack/console/src/server.ts": `// v${n}\n` })); + expect(run().code).toBe(0); + } + expect(current()).toBe(`releases/${made[5]}`); + expect(releases()).toEqual([made[3], made[4], made[5]].sort()); + // Something that is not a release is not touched: neither a name + // that is no commit's, nor one that only looks like the start of one. + mkdirSync(join(share, "releases/keep-me")); + mkdirSync(join(share, "releases/deadbeef")); + made.push(push("v7", { "pm-stack/console/src/server.ts": "// v7\n" })); expect(run().code).toBe(0); - expect(state("deploy-skipped")).not.toBeNull(); - git("commit", "-q", "-am", "finished"); - expect(run().code).toBe(0); - expect(state("deploy-skipped")).toBeNull(); + expect(releases()).toEqual([made[4], made[5], made[6], "deadbeef", "keep-me"].sort()); }); - test("an install that fails leaves the code marked as not in service", () => { - writeFileSync(join(repo, "pm-stack/console/install.sh"), `echo "install" >>"${log}"\nexit 1\n`); - git("commit", "-q", "-am", "install fails"); - expect(run().code).toBe(1); - expect(state("deployed")).toBeNull(); - // It is tried again, since the code itself passed its check. - expect(run().code).toBe(1); - expect(events().filter((e) => e === "install")).toHaveLength(2); + test("a copy that has been damaged is made again from GitHub", () => { + run(); + const sha = git(work, "rev-parse", "HEAD"); + // The link gone, the clone's settings changed by hand, a stray file in it. + rmSync(join(share, "current")); + git(join(share, "repo"), "config", "remote.origin.url", "file:///somewhere/else.git"); + writeFileSync(join(share, "repo/pm-stack/console/stray.txt"), "left behind\n"); + writeFileSync(join(share, "repo/pm-stack/console/src/server.ts"), "// edited in place\n"); + expect(run().code).toBe(0); + expect(current()).toBe(`releases/${sha}`); + expect(inService("pm-stack/console/src/server.ts")).toBe("// v1\n"); + expect(existsSync(join(share, "current/pm-stack/console/stray.txt"))).toBe(false); }); test("it takes no arguments", () => { - const done = Bun.spawnSync(["bash", join(repo, "pm-stack/console/redeploy.sh"), "--force"], { - env: { ...process.env, HOME: home }, - }); - expect(done.exitCode).toBe(2); + const done = sh(dir, ["bash", join(dir, "redeploy.sh"), "--force"]); + expect(done.code).toBe(2); expect(events()).toEqual([]); + expect(existsSync(share)).toBe(false); }); }); diff --git a/pm-stack/systemd/pm-console-android-release.service b/pm-stack/systemd/pm-console-android-release.service index 8d07d86ee2..ebcebe68c8 100644 --- a/pm-stack/systemd/pm-console-android-release.service +++ b/pm-stack/systemd/pm-console-android-release.service @@ -9,7 +9,7 @@ Type=oneshot # version of the app that is not released yet. Then the build is signed # on this machine, which holds the key, and released. The key is read # by apksigner here and goes nowhere. -ExecStart=/run/current-system/sw/bin/bash %h/git/code/pm-stack/console/android/release-built.sh +ExecStart=/run/current-system/sw/bin/bash %h/.local/share/pm-console/current/pm-stack/console/android/release-built.sh Environment=PATH=%h/.local/bin:/etc/profiles/per-user/%u/bin:/run/current-system/sw/bin:/usr/bin:/bin # The first run may have to fetch apksigner. TimeoutStartSec=900 diff --git a/pm-stack/systemd/pm-console-expose.service b/pm-stack/systemd/pm-console-expose.service index a654d8b550..5d3fd2bd43 100644 --- a/pm-stack/systemd/pm-console-expose.service +++ b/pm-stack/systemd/pm-console-expose.service @@ -7,6 +7,6 @@ After=network-online.target Type=oneshot # Changes only what is not already so. When the Google sign-in secrets # appear in the secret store, the next run turns Google sign-in on. -ExecStart=/etc/profiles/per-user/%u/bin/python3 %h/git/code/pm-stack/console/scripts/expose.py +ExecStart=/etc/profiles/per-user/%u/bin/python3 %h/.local/share/pm-console/current/pm-stack/console/scripts/expose.py Environment=PATH=%h/.local/bin:/run/current-system/sw/bin:/etc/profiles/per-user/%u/bin:/usr/bin:/bin TimeoutStartSec=600 diff --git a/pm-stack/systemd/pm-console-redeploy.service b/pm-stack/systemd/pm-console-redeploy.service index 82af79efe4..c54f7aa004 100644 --- a/pm-stack/systemd/pm-console-redeploy.service +++ b/pm-stack/systemd/pm-console-redeploy.service @@ -5,9 +5,10 @@ After=network-online.target [Service] Type=oneshot -# Does nothing unless the checkout holds console code that is not the -# code in service. New code is started in a self-check first; code that -# does not start is never put into service. -ExecStart=/run/current-system/sw/bin/bash %h/git/code/pm-stack/console/redeploy.sh +# Asks GitHub for main, and does nothing more unless the console's code +# there is not the code in service. New code is laid out as a release +# of its own and started in a self-check first; code that does not +# start, or does not come up in service, never stays in service. +ExecStart=/run/current-system/sw/bin/bash %h/.local/share/pm-console/current/pm-stack/console/redeploy.sh Environment=PATH=%h/.local/bin:/etc/profiles/per-user/%u/bin:/run/current-system/sw/bin:/usr/bin:/bin TimeoutStartSec=300 diff --git a/pm-stack/systemd/pm-console.service b/pm-stack/systemd/pm-console.service index 662a353f15..156bc21ccd 100644 --- a/pm-stack/systemd/pm-console.service +++ b/pm-stack/systemd/pm-console.service @@ -7,7 +7,10 @@ After=network-online.target # contention this unit gets nine times the processor share of a default one. CPUWeight=900 Type=simple -WorkingDirectory=%h/git/code/pm-stack/console +# The console's own copy of main, which redeploy.sh keeps: the release +# that is current when the service starts is the code it runs until it +# is restarted. It runs from no checkout that anything else works in. +WorkingDirectory=%h/.local/share/pm-console/current/pm-stack/console ExecStart=/run/current-system/sw/bin/bun run src/server.ts EnvironmentFile=%h/.local/state/pm-console/.env # The console shells out to fleet, gh (through fleet), systemctl and journalctl.