diff --git a/.gitignore b/.gitignore index aa4eb4f..eb1d8d9 100644 --- a/.gitignore +++ b/.gitignore @@ -42,3 +42,4 @@ npm-debug.log /dist/ .DS_Store /.playwright-mcp/ +/REVISION diff --git a/README.md b/README.md index 8d1e18e..1a2f522 100644 --- a/README.md +++ b/README.md @@ -92,7 +92,7 @@ The dashboard opens at the same `http://localhost:4100` address. If a screenshot ./bin/install-launch-agent ``` -The installer copies the app to `~/Library/Application Support/LocalWebMonitorex`, prepares production assets there, installs a user LaunchAgent, and starts it. This lets the background process run outside protected project folders such as Documents. It starts again at login. Re-run the installer after pulling project updates. To restart it after saving a new port or watched range in **Settings**: +The installer builds the current commit into `~/Library/Application Support/LocalWebMonitorex-versions/`, points `~/Library/Application Support/LocalWebMonitorex` at it, installs a user LaunchAgent, and starts it. Running outside the project folder lets the background process work even when the checkout is in a protected folder such as Documents. It starts again at login. To restart it after saving a new port or watched range in **Settings**: ```bash launchctl kickstart -k gui/$(id -u)/com.localwebmonitorex @@ -104,7 +104,27 @@ The log is at `~/Library/Logs/LocalWebMonitorex.log`. To stop and remove automat ./bin/uninstall-launch-agent ``` -Removing the LaunchAgent keeps the installed copy and your saved preferences. +Removing the LaunchAgents keeps the installed copies and your saved preferences. + +#### Automatic updates + +The installer also adds `com.localwebmonitorex.updater`, which runs at login and then about once an hour. It never changes your source checkout. Each run: + +1. Fetches `main` from the checkout's `origin` (read over HTTPS) into a private repository in `~/Library/Application Support/LocalWebMonitorex-updater`. +2. Compares it with the installed commit. If they match, it records that the copy is up to date. +3. Exports the new commit into its own version directory and runs `bin/build-installation` there. +4. Starts that build on a spare loopback port with throwaway settings and an empty watched range, and waits for it to serve its own commit. +5. Points the installation at the new version and restarts `com.localwebmonitorex`. If the dashboard does not serve the new commit on your saved port within three minutes, it switches back and restarts the previous version. + +A failed fetch, build, smoke test, or restart keeps the current version running and is retried on the next run. The running version and the one before it are kept; older version directories are removed. If the installed commit is not on `main`, for example after installing from an unmerged branch, updates pause until you install from `main` again. A change to the LaunchAgent files themselves applies when you re-run the installer. + +**Settings → Updates** shows the installed commit, the last check, and whether the copy is up to date, behind `main` by some commits, or why the last update failed. Details are in `~/Library/Logs/LocalWebMonitorex-updater.log`. To check now: + +```bash +launchctl kickstart gui/$(id -u)/com.localwebmonitorex.updater +``` + +Installations made before the updater existed keep their files in place: re-run `./bin/install-launch-agent` from an up-to-date `main` checkout once. The installer keeps the old copy as the previous version and turns on the hourly updater. ## Configuration diff --git a/assets/css/app.css b/assets/css/app.css index 3f19ef7..fab213d 100644 --- a/assets/css/app.css +++ b/assets/css/app.css @@ -232,6 +232,13 @@ a { color:inherit; text-decoration:none; } .settings-range-fields > span { color:#87948a; padding-bottom:11px; } .settings-range-save { width:100%; height:41px; margin-top:13px; border:0; border-radius:5px; background:#20382f; color:#f4f8ea; font-size:12px; font-weight:700; } .settings-range-save:hover { background:#335943; } +.settings-updates { border-top:1px solid #d9e1d7; margin-top:38px; padding-top:29px; } +.settings-updates h3 { margin:0 0 8px; font-size:18px; letter-spacing:-.045em; } +.settings-updates-summary { margin:0; color:#355c41; font-size:12px; font-weight:700; line-height:1.5; } +.settings-updates-summary.failed { color:#9b3b2c; } +.settings-updates dl { display:grid; grid-template-columns:auto minmax(0,1fr); gap:6px 14px; margin:14px 0 0; font-size:12px; } +.settings-updates dt { color:#6d7b70; } +.settings-updates dd { margin:0; min-width:0; overflow-wrap:anywhere; } .settings-error,.settings-success { margin:11px 0 0; font-size:12px; line-height:1.5; } .settings-error { color:#a54334; } .settings-success { color:#357344; } @@ -252,6 +259,10 @@ html[data-theme="dark"] .app-notice.error { background:#432924; border-color:#8b html[data-theme="dark"] .brand-mark span { box-shadow:0 0 0 4px #0b1812; } html[data-theme="dark"] .eyebrow,html[data-theme="dark"] .section-index { color:#a2c5a4; } html[data-theme="dark"] .page-head p,html[data-theme="dark"] .settings-panel > p,html[data-theme="dark"] .settings-theme p,html[data-theme="dark"] .settings-range > p { color:#adbfaf; } +html[data-theme="dark"] .settings-updates { border-color:#3d5443; } +html[data-theme="dark"] .settings-updates dt { color:#adbfaf; } +html[data-theme="dark"] .settings-updates-summary { color:#b7ddb1; } +html[data-theme="dark"] .settings-updates-summary.failed { color:#ffb4a5; } html[data-theme="dark"] .scan-status { color:#b7ddb1; } html[data-theme="dark"] .pulse-dot { box-shadow:0 0 0 4px #24402a; } html[data-theme="dark"] .refresh-button,html[data-theme="dark"] .settings-shortcut { background:#1c2c22; border-color:#476050; color:#dcebdc; } diff --git a/bin/build-installation b/bin/build-installation new file mode 100755 index 0000000..6ff80a3 --- /dev/null +++ b/bin/build-installation @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# Prepares this project copy to run with `MIX_ENV=prod mix phx.server`. +# The installer and the updater both run it inside the copy they are building. +set -euo pipefail + +cd "$(dirname "${BASH_SOURCE[0]}")/.." + +mix deps.get +npm ci --prefix assets +./assets/node_modules/.bin/playwright install webkit +MIX_ENV=prod mix assets.deploy +MIX_ENV=prod mix compile diff --git a/bin/install-launch-agent b/bin/install-launch-agent index c6bd700..83853c5 100755 --- a/bin/install-launch-agent +++ b/bin/install-launch-agent @@ -7,24 +7,52 @@ if [[ "$(uname -s)" != "Darwin" ]]; then fi project_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)" -install_dir="$HOME/Library/Application Support/LocalWebMonitorex" +support_dir="$HOME/Library/Application Support" +install_link="$support_dir/LocalWebMonitorex" +versions_dir="$support_dir/LocalWebMonitorex-versions" +update_dir="$support_dir/LocalWebMonitorex-updater" agent_label="com.localwebmonitorex" +updater_label="com.localwebmonitorex.updater" agent_file="$HOME/Library/LaunchAgents/$agent_label.plist" +updater_file="$HOME/Library/LaunchAgents/$updater_label.plist" log_file="$HOME/Library/Logs/LocalWebMonitorex.log" +updater_log="$HOME/Library/Logs/LocalWebMonitorex-updater.log" +default_remote="https://github.com/sallaumen/LocalWebMonitorex.git" -mkdir -p "$install_dir" -if [[ "$project_dir" != "$install_dir" ]]; then - rsync -a --delete --exclude '/.git/' --exclude '/_build/' "$project_dir/" "$install_dir/" +case "$project_dir/" in + "$install_link/"* | "$versions_dir/"*) + echo "Run this installer from your source checkout, not from the installed copy." >&2 + exit 1 + ;; +esac + +if ! revision="$(git -C "$project_dir" rev-parse --verify HEAD 2>/dev/null)"; then + echo "Run this installer from a git checkout so the installed commit is known." >&2 + exit 1 +fi + +# The updater fetches anonymously, so an SSH GitHub remote is read over HTTPS. +remote="$(git -C "$project_dir" remote get-url origin 2>/dev/null || echo "$default_remote")" +case "$remote" in + git@github.com:*) remote="https://github.com/${remote#git@github.com:}" ;; + ssh://git@github.com/*) remote="https://github.com/${remote#ssh://git@github.com/}" ;; +esac + +version_name="$revision" +if [[ -n "$(git -C "$project_dir" status --porcelain 2>/dev/null)" ]]; then + version_name="$revision-local" fi +version_dir="$versions_dir/$version_name" -cd "$install_dir" -mix deps.get -npm ci --prefix assets -./assets/node_modules/.bin/playwright install webkit -MIX_ENV=prod mix assets.deploy +mkdir -p "$version_dir" "$update_dir" "$HOME/Library/LaunchAgents" "$HOME/Library/Logs" +rsync -a --delete --exclude '/.git' --exclude '/_build/' --exclude '/REVISION' \ + "$project_dir/" "$version_dir/" +printf '%s\n' "$revision" > "$version_dir/REVISION" +"$version_dir/bin/build-installation" -mkdir -p "$HOME/Library/LaunchAgents" "$HOME/Library/Logs" -PROJECT_DIR="$install_dir" AGENT_FILE="$agent_file" LOG_FILE="$log_file" python3 - <<'PY' +PROJECT_DIR="$install_link" UPDATE_DIR="$update_dir" VERSIONS_DIR="$versions_dir" \ + REMOTE="$remote" AGENT_FILE="$agent_file" UPDATER_FILE="$updater_file" \ + LOG_FILE="$log_file" UPDATER_LOG="$updater_log" python3 - <<'PY' import os import plistlib import shutil @@ -35,40 +63,87 @@ node = shutil.which("node") runtime_dirs = [os.path.dirname(tool) for tool in (mix, asdf, node) if tool] runtime_dirs += ["/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"] runtime_path = os.pathsep.join(dict.fromkeys(runtime_dirs)) +status_file = os.path.join(os.environ["UPDATE_DIR"], "status") -config = { +service = { "Label": "com.localwebmonitorex", "ProgramArguments": [mix, "phx.server"], "WorkingDirectory": os.environ["PROJECT_DIR"], - "EnvironmentVariables": {"MIX_ENV": "prod", "PHX_SERVER": "true", "PATH": runtime_path}, + "EnvironmentVariables": { + "MIX_ENV": "prod", + "PHX_SERVER": "true", + "PATH": runtime_path, + "LOCALWEBMONITOREX_UPDATE_STATUS": status_file, + }, "RunAtLoad": True, "KeepAlive": True, "StandardOutPath": os.environ["LOG_FILE"], "StandardErrorPath": os.environ["LOG_FILE"], } -with open(os.environ["AGENT_FILE"], "wb") as output: - plistlib.dump(config, output) +updater = { + "Label": "com.localwebmonitorex.updater", + "ProgramArguments": ["/bin/bash", os.path.join(os.environ["UPDATE_DIR"], "update-from-main")], + "EnvironmentVariables": { + "PATH": runtime_path, + "LOCALWEBMONITOREX_INSTALL_DIR": os.environ["PROJECT_DIR"], + "LOCALWEBMONITOREX_VERSIONS_DIR": os.environ["VERSIONS_DIR"], + "LOCALWEBMONITOREX_UPDATE_DIR": os.environ["UPDATE_DIR"], + "LOCALWEBMONITOREX_UPDATE_REMOTE": os.environ["REMOTE"], + }, + "StartInterval": 3600, + "RunAtLoad": True, + "Nice": 10, + "StandardOutPath": os.environ["UPDATER_LOG"], + "StandardErrorPath": os.environ["UPDATER_LOG"], +} + +for path, config in ((os.environ["AGENT_FILE"], service), (os.environ["UPDATER_FILE"], updater)): + with open(path, "wb") as output: + plistlib.dump(config, output) PY -agent_target="gui/$(id -u)/$agent_label" -launchctl bootout "$agent_target" >/dev/null 2>&1 || true -bootstrap_error="" -registered=false -for attempt in 1 2 3 4 5; do - if bootstrap_error="$(launchctl bootstrap "gui/$(id -u)" "$agent_file" 2>&1)"; then - registered=true - break - fi - sleep 1 +domain="gui/$(id -u)" +launchctl bootout "$domain/$updater_label" >/dev/null 2>&1 || true +launchctl bootout "$domain/$agent_label" >/dev/null 2>&1 || true + +# Earlier installers kept a real directory here; keep it as the previous version. +previous_version="" +if [[ -L "$install_link" ]]; then + previous_version="$(readlink "$install_link")" +elif [[ -d "$install_link" ]]; then + previous_version="$versions_dir/legacy-$(date +%s)" + mv "$install_link" "$previous_version" +fi +ln -sfn "$version_dir" "$install_link" + +for directory in "$versions_dir"/*; do + [[ -d "$directory" && ! -L "$directory" ]] || continue + [[ "$directory" == "$version_dir" || "$directory" == "$previous_version" ]] && continue + rm -rf "$directory" done -if [[ "$registered" != true ]]; then + +install -m 755 "$version_dir/bin/update-from-main" "$update_dir/update-from-main" + +bootstrap_agent() { + local file=$1 bootstrap_error="" + for _ in 1 2 3 4 5; do + if bootstrap_error="$(launchctl bootstrap "$domain" "$file" 2>&1)"; then + return 0 + fi + sleep 1 + done echo "$bootstrap_error" >&2 - exit 1 -fi -launchctl enable "$agent_target" -launchctl kickstart -k "$agent_target" + return 1 +} + +bootstrap_agent "$agent_file" +launchctl enable "$domain/$agent_label" +launchctl kickstart -k "$domain/$agent_label" +bootstrap_agent "$updater_file" +launchctl enable "$domain/$updater_label" echo "LocalWebMonitorex starts at login. Open http://localhost:4100 (or your saved port)." -echo "Installed at: $install_dir" -echo "Log: $log_file" +echo "Installed commit: $revision ($version_dir)" +echo "It checks $remote main about once an hour and updates itself." +echo "Logs: $log_file and $updater_log" diff --git a/bin/uninstall-launch-agent b/bin/uninstall-launch-agent index 72a6044..895fbec 100755 --- a/bin/uninstall-launch-agent +++ b/bin/uninstall-launch-agent @@ -1,10 +1,10 @@ #!/usr/bin/env bash set -euo pipefail -agent_label="com.localwebmonitorex" -agent_target="gui/$(id -u)/$agent_label" -agent_file="$HOME/Library/LaunchAgents/$agent_label.plist" - -launchctl bootout "$agent_target" >/dev/null 2>&1 || true -rm -f "$agent_file" -echo "LocalWebMonitorex was removed from login startup. Your port preference was kept." +domain="gui/$(id -u)" +for agent_label in com.localwebmonitorex.updater com.localwebmonitorex; do + launchctl bootout "$domain/$agent_label" >/dev/null 2>&1 || true + rm -f "$HOME/Library/LaunchAgents/$agent_label.plist" +done +echo "LocalWebMonitorex and its updater were removed from login startup." +echo "Your port preference and installed copies under ~/Library/Application Support were kept." diff --git a/bin/update-from-main b/bin/update-from-main new file mode 100755 index 0000000..394c7c2 --- /dev/null +++ b/bin/update-from-main @@ -0,0 +1,291 @@ +#!/usr/bin/env bash +# Keeps a macOS installation on remote main. The updater LaunchAgent runs a +# private copy of this script about once an hour. +# +# The installation path is a symlink to a built version directory. A newer main +# is fetched into a private repository, exported to its own version directory, +# built and started on a spare loopback port. Only a candidate that serves its +# own commit there replaces the running version. A failure leaves the current +# version running and records why in the status file the dashboard reads. +set -euo pipefail +umask 022 + +install_link=${LOCALWEBMONITOREX_INSTALL_DIR:-"$HOME/Library/Application Support/LocalWebMonitorex"} +versions_dir=${LOCALWEBMONITOREX_VERSIONS_DIR:-"$HOME/Library/Application Support/LocalWebMonitorex-versions"} +state_dir=${LOCALWEBMONITOREX_UPDATE_DIR:-"$HOME/Library/Application Support/LocalWebMonitorex-updater"} +remote=${LOCALWEBMONITOREX_UPDATE_REMOTE:-https://github.com/sallaumen/LocalWebMonitorex.git} +port_file=${LOCALWEBMONITOREX_CONFIG:-"${XDG_CONFIG_HOME:-$HOME/.config}/localwebmonitorex/port"} +agent_label=${LOCALWEBMONITOREX_AGENT_LABEL:-com.localwebmonitorex} +launchctl_command=${LOCALWEBMONITOREX_LAUNCHCTL:-launchctl} +read -r -a server_command <<<"${LOCALWEBMONITOREX_SERVER_COMMAND:-mix phx.server}" +build_seconds=${LOCALWEBMONITOREX_BUILD_SECONDS:-1800} +smoke_seconds=${LOCALWEBMONITOREX_SMOKE_SECONDS:-120} +health_seconds=${LOCALWEBMONITOREX_HEALTH_SECONDS:-180} + +mirror="$state_dir/repository" +status_file="$state_dir/status" +lock_dir="$state_dir/lock" + +installed="" +available="" +behind="" +phase="" +reason="" +checked_at="" +candidate="" +smoke_pid="" +smoke_dir="" + +log() { + printf '%s update-from-main: %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >&2 +} + +write_status() { + local temporary="$status_file.tmp.$$" + printf 'installed_sha=%s\navailable_sha=%s\nphase=%s\nbehind=%s\nreason=%s\nchecked_at=%s\n' \ + "$installed" "$available" "$phase" "$behind" "$reason" "$checked_at" >"$temporary" + mv -f "$temporary" "$status_file" +} + +# Records the outcome and ends the pass. Failures exit non-zero for the log. +finish() { + phase=$1 + reason=${2:-} + write_status + log "phase=$phase${reason:+ reason=$reason} installed=$installed available=$available" + [[ $phase != failed ]] || exit 1 + exit 0 +} + +alive() { + local state + state=$(ps -o stat= -p "$1" 2>/dev/null) || return 1 + [[ -n $state && $state != Z* ]] +} + +descendants() { + local child + for child in $(pgrep -P "$1" 2>/dev/null); do + echo "$child" + descendants "$child" + done +} + +# Stops a step and everything it started: TERM first, KILL after a grace. +stop_tree() { + local -a tree + read -r -a tree <<<"$1 $(descendants "$1" | tr '\n' ' ')" + kill -TERM "${tree[@]}" 2>/dev/null || true + for _ in $(seq 1 20); do + alive "$1" || break + sleep 0.5 + done + kill -KILL "${tree[@]}" 2>/dev/null || true + wait "$1" 2>/dev/null || true +} + +run_bounded() { + local limit=$1 pid waited=0 + shift + "$@" & + pid=$! + while alive "$pid"; do + if ((waited >= limit)); then + log "step ran past ${limit}s and was stopped: $*" + stop_tree "$pid" + return 124 + fi + sleep 1 + waited=$((waited + 1)) + done + wait "$pid" +} + +cleanup() { + [[ -z $smoke_pid ]] || stop_tree "$smoke_pid" + [[ -z $smoke_dir ]] || rm -rf "$smoke_dir" + rm -rf "$lock_dir" +} + +acquire_lock() { + local holder + mkdir -p "$state_dir" + if ! mkdir "$lock_dir" 2>/dev/null; then + holder=$(cat "$lock_dir/pid" 2>/dev/null || true) + if [[ -n $holder ]] && alive "$holder"; then + log "another update pass is running (pid $holder)" + exit 0 + fi + rm -rf "$lock_dir" + mkdir "$lock_dir" + fi + echo $$ >"$lock_dir/pid" + trap cleanup EXIT +} + +read_installed() { + installed=$(tr -d '[:space:]' <"$install_link/REVISION" 2>/dev/null || true) + [[ $installed =~ ^[0-9a-f]{40}$ ]] || { + installed="" + finish failed installed_revision_missing + } +} + +fetch_main() { + [[ -d $mirror ]] || git init --quiet --bare "$mirror" + GIT_HTTP_LOW_SPEED_LIMIT=1000 GIT_HTTP_LOW_SPEED_TIME=30 \ + run_bounded 300 git -C "$mirror" fetch --quiet "$remote" "+refs/heads/main:refs/heads/main" || + finish failed fetch_failed + available=$(git -C "$mirror" rev-parse --verify refs/heads/main) || finish failed fetch_failed +} + +compare_with_main() { + if [[ $installed == "$available" ]]; then + behind=0 + finish up_to_date + fi + git -C "$mirror" merge-base --is-ancestor "$installed" "$available" 2>/dev/null || + finish diverged + behind=$(git -C "$mirror" rev-list --count "$installed..$available") + phase=behind + write_status + log "installed $installed is $behind commit(s) behind main $available" +} + +discard_candidate() { + rm -rf "$candidate" + finish failed "$1" +} + +build_candidate() { + candidate="$versions_dir/$available" + [[ $candidate != "$(readlink "$install_link")" ]] || finish failed switch_failed + rm -rf "$candidate" + mkdir -p "$candidate" + git -C "$mirror" archive "$available" | tar -x -C "$candidate" || discard_candidate build_failed + printf '%s\n' "$available" >"$candidate/REVISION" + log "building $available" + (cd "$candidate" && run_bounded "$build_seconds" ./bin/build-installation) >&2 || + discard_candidate build_failed +} + +free_port() { + python3 -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1]); s.close()' +} + +# Waits until the dashboard on `port` serves the expected commit. +serves_revision() { + local port=$1 seconds=$2 revision=$3 watched_pid=${4:-} deadline body + deadline=$(($(date +%s) + seconds)) + while (($(date +%s) < deadline)); do + body=$(curl -fsS --max-time 3 "http://127.0.0.1:$port/" 2>/dev/null || true) + [[ $body != *"name=\"localwebmonitorex-revision\" content=\"$revision\""* ]] || return 0 + [[ -z $watched_pid ]] || alive "$watched_pid" || return 1 + sleep 2 + done + return 1 +} + +# The candidate gets its own port, an empty watched range and throwaway +# preferences, so it never scans for services or touches the user's settings. +smoke_test() { + local port + port=$(free_port) + smoke_dir=$(mktemp -d "$state_dir/smoke.XXXXXX") + printf '%s\n' "$port" >"$smoke_dir/port" + printf '%s-%s\n' "$port" "$port" >"$smoke_dir/range" + log "smoke testing $available on port $port" + ( + cd "$candidate" + exec env MIX_ENV=prod PHX_SERVER=true PORT="$port" \ + LOCALWEBMONITOREX_CONFIG="$smoke_dir/port" \ + LOCALWEBMONITOREX_RANGE_CONFIG="$smoke_dir/range" \ + LOCALWEBMONITOREX_UPDATE_STATUS="$smoke_dir/status" \ + "${server_command[@]}" + ) >&2 & + smoke_pid=$! + serves_revision "$port" "$smoke_seconds" "$available" "$smoke_pid" || + { stop_smoke && discard_candidate smoke_failed; } + stop_smoke +} + +stop_smoke() { + stop_tree "$smoke_pid" + smoke_pid="" + rm -rf "$smoke_dir" + smoke_dir="" +} + +dashboard_port() { + local port + port=$(tr -d '[:space:]' <"$port_file" 2>/dev/null || true) + if [[ $port =~ ^[0-9]+$ ]] && ((port >= 1024 && port <= 65535)); then + echo "$port" + else + echo 4100 + fi +} + +point_install_at() { + ln -sfn "$1" "$install_link" +} + +restart_agent() { + "$launchctl_command" kickstart -k "gui/$(id -u)/$agent_label" +} + +switch_to_candidate() { + local previous port + previous=$(readlink "$install_link") || finish failed switch_failed + port=$(dashboard_port) + point_install_at "$candidate" || finish failed switch_failed + log "restarting $agent_label on $available" + if restart_agent && serves_revision "$port" "$health_seconds" "$available"; then + installed=$available + behind=0 + return 0 + fi + log "the new version did not answer on port $port; restoring $previous" + point_install_at "$previous" + restart_agent || log "could not restart $agent_label on $previous" + finish failed restart_failed +} + +refresh_runner() { + local temporary="$state_dir/update-from-main.tmp.$$" + if ! install -m 755 "$candidate/bin/update-from-main" "$temporary" || + ! mv -f "$temporary" "$state_dir/update-from-main"; then + log "could not refresh the updater runner" + fi +} + +# Keeps the running version and the one before it for a manual rollback. +prune_versions() { + local keep_current=$1 keep_previous=$2 directory + for directory in "$versions_dir"/*; do + [[ -d $directory && ! -L $directory ]] || continue + [[ $directory == "$keep_current" || $directory == "$keep_previous" ]] && continue + rm -rf "$directory" + done +} + +main() { + local previous + acquire_lock + checked_at=$(date +%s) + read_installed + fetch_main + compare_with_main + build_candidate + smoke_test + previous=$(readlink "$install_link") + switch_to_candidate + phase=up_to_date + reason="" + write_status + refresh_runner + prune_versions "$candidate" "$previous" + log "updated to $available" +} + +main "$@" diff --git a/config/runtime.exs b/config/runtime.exs index 66cbd1d..1dee504 100644 --- a/config/runtime.exs +++ b/config/runtime.exs @@ -74,3 +74,6 @@ if config_env() == :prod do config :local_web_monitorex, LocalWebMonitorexWeb.Endpoint, secret_key_base: secret_key_base end + +config :local_web_monitorex, + update_status_file: System.get_env("LOCALWEBMONITOREX_UPDATE_STATUS") diff --git a/lib/local_web_monitorex/update_status.ex b/lib/local_web_monitorex/update_status.ex new file mode 100644 index 0000000..c8a2c91 --- /dev/null +++ b/lib/local_web_monitorex/update_status.ex @@ -0,0 +1,162 @@ +defmodule LocalWebMonitorex.UpdateStatus do + @moduledoc """ + Reads what the macOS updater last recorded about this installation. + + The updater writes `key=value` lines to a status file. The running copy's + own commit comes from its `REVISION` file, so a check made for another + installed commit is reported as pending instead of being trusted. + """ + + @reasons %{ + "fetch_failed" => :fetch_failed, + "build_failed" => :build_failed, + "smoke_failed" => :smoke_failed, + "switch_failed" => :switch_failed, + "restart_failed" => :restart_failed, + "installed_revision_missing" => :installed_revision_missing + } + + @failure_text %{ + fetch_failed: "could not reach GitHub", + build_failed: "the new version did not build", + smoke_failed: "the new version did not start", + switch_failed: "could not switch to the new version", + restart_failed: "the new version did not stay up, so the previous one was restored", + installed_revision_missing: "the installed commit is unknown", + unknown: "see the updater log" + } + + @type state :: + :unconfigured + | :pending + | :up_to_date + | :diverged + | {:behind, pos_integer()} + | {:failed, atom()} + + @type t :: %__MODULE__{ + installed: String.t() | nil, + available: String.t() | nil, + checked_at: DateTime.t() | nil, + state: state() + } + + defstruct installed: nil, available: nil, checked_at: nil, state: :unconfigured + + @spec status_path() :: String.t() | nil + def status_path, do: Application.get_env(:local_web_monitorex, :update_status_file) + + @spec revision_path() :: String.t() + def revision_path do + Application.get_env(:local_web_monitorex, :revision_file, Path.join(File.cwd!(), "REVISION")) + end + + @spec installed_revision(String.t()) :: String.t() | nil + def installed_revision(path \\ revision_path()) do + with {:ok, content} <- File.read(path), + sha when byte_size(sha) == 40 <- String.trim(content), + true <- hex?(sha) do + sha + else + _ -> nil + end + end + + @spec read(String.t() | nil, String.t()) :: t() + def read(status_path \\ status_path(), revision_path \\ revision_path()) do + installed = installed_revision(revision_path) + status = %__MODULE__{installed: installed} + + case read_fields(status_path) do + :unconfigured -> status + :missing -> %{status | state: :pending} + {:ok, fields} -> from_fields(status, fields) + end + end + + @spec summary(t()) :: String.t() + def summary(%__MODULE__{state: :up_to_date}), do: "Up to date with main" + def summary(%__MODULE__{state: {:behind, 1}}), do: "Behind main by 1 commit" + def summary(%__MODULE__{state: {:behind, count}}), do: "Behind main by #{count} commits" + def summary(%__MODULE__{state: :pending}), do: "Waiting for the first update check" + def summary(%__MODULE__{state: :unconfigured}), do: "Automatic updates are not set up" + + def summary(%__MODULE__{state: :diverged}), + do: "Installed commit is not on main; automatic updates are paused" + + def summary(%__MODULE__{state: {:failed, reason}}), + do: "Update failed: #{Map.fetch!(@failure_text, reason)}" + + @spec short_sha(String.t() | nil) :: String.t() + def short_sha(nil), do: "unknown" + def short_sha(sha), do: String.slice(sha, 0, 7) + + defp read_fields(nil), do: :unconfigured + + defp read_fields(path) do + case File.read(path) do + {:ok, content} -> {:ok, parse_fields(content)} + {:error, _reason} -> :missing + end + end + + defp parse_fields(content) do + content + |> String.split("\n", trim: true) + |> Enum.flat_map(&parse_line/1) + |> Map.new() + end + + defp parse_line(line) do + case String.split(line, "=", parts: 2) do + [key, value] -> [{key, String.trim(value)}] + _ -> [] + end + end + + defp from_fields(%{installed: installed} = status, %{"installed_sha" => installed} = fields) + when is_binary(installed) do + case state(fields) do + {:ok, state} -> + %{ + status + | state: state, + available: fields["available_sha"], + checked_at: checked_at(fields) + } + + :error -> + %{status | state: :pending} + end + end + + defp from_fields(status, _fields), do: %{status | state: :pending} + + defp state(%{"phase" => "up_to_date"}), do: {:ok, :up_to_date} + defp state(%{"phase" => "diverged"}), do: {:ok, :diverged} + defp state(%{"phase" => "failed"} = fields), do: {:ok, {:failed, reason(fields["reason"])}} + + defp state(%{"phase" => "behind", "behind" => behind}) do + case Integer.parse(behind) do + {count, ""} when count > 0 -> {:ok, {:behind, count}} + _ -> :error + end + end + + defp state(_fields), do: :error + + defp reason(value), do: Map.get(@reasons, value, :unknown) + + defp checked_at(%{"checked_at" => value}) do + with {seconds, ""} <- Integer.parse(value), + {:ok, datetime} <- DateTime.from_unix(seconds) do + datetime + else + _ -> nil + end + end + + defp checked_at(_fields), do: nil + + defp hex?(value), do: String.match?(value, ~r/\A[0-9a-f]+\z/) +end diff --git a/lib/local_web_monitorex_web/components/layouts.ex b/lib/local_web_monitorex_web/components/layouts.ex index eb015d4..e25fc05 100644 --- a/lib/local_web_monitorex_web/components/layouts.ex +++ b/lib/local_web_monitorex_web/components/layouts.ex @@ -3,5 +3,16 @@ defmodule LocalWebMonitorexWeb.Layouts do use LocalWebMonitorexWeb, :html + alias LocalWebMonitorex.UpdateStatus + embed_templates "layouts/*" + + @doc "Names the served commit so the updater can confirm which version answered." + def revision_meta(assigns) do + assigns = assign(assigns, :revision, UpdateStatus.installed_revision()) + + ~H""" + + """ + end end diff --git a/lib/local_web_monitorex_web/components/layouts/root.html.heex b/lib/local_web_monitorex_web/components/layouts/root.html.heex index 57a1398..818b187 100644 --- a/lib/local_web_monitorex_web/components/layouts/root.html.heex +++ b/lib/local_web_monitorex_web/components/layouts/root.html.heex @@ -5,6 +5,7 @@ + <.revision_meta />