From c7811b75aed7ec451be501b6afc3262dd67c7fbe Mon Sep 17 00:00:00 2001 From: hauke Date: Fri, 6 Nov 2026 11:50:43 +0100 Subject: [PATCH] fix #14740: faster update retries and release safety checks Co-Authored-By: Claude Opus 5.5 (1M context) --- RELEASING.md | 30 +++++-- scripts/build-release.sh | 46 +++++++++++ src-tauri/src/lib.rs | 15 +++- src-tauri/src/updater.rs | 163 +++++++++++++++++++++++++++++++++++---- 4 files changed, 232 insertions(+), 22 deletions(-) diff --git a/RELEASING.md b/RELEASING.md index 490c168..2f65429 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -95,10 +95,16 @@ with `404`, which falls through as intended. ## Releasing a version -Example: version `0.1.1`. Versions are semantic versions and must be higher than the -installed one. +Example: version `0.1.1`. Versions are semantic versions and must be greater than the +installed one. The script refuses a version that is not greater than the committed +one. The committed version itself is allowed while there is no tag `v` yet, +e.g. for the first release `0.1.0`. -1. Start from a clean `master` with the tests passing (`cargo test --workspace`). +1. Start from `master` with no uncommitted changes to tracked files (the script + refuses otherwise; untracked files do not matter) and the tests passing + (`cargo test --workspace`). If a build failed after the script had set the version, + reset that first: + `git checkout src-tauri/tauri.conf.json src-tauri/Cargo.toml Cargo.lock ui/package.json`. 2. Build (works in fish and bash; without `TAURI_SIGNING_PRIVATE_KEY_PASSWORD` the script asks for the password): @@ -108,6 +114,7 @@ installed one. ``` The script: + - checks that the tree is clean and the version is greater (see above), - checks the key and password by signing a probe file, and stops if the key does not belong to `plugins.updater.pubkey`, - sets the version in `src-tauri/tauri.conf.json`, `src-tauri/Cargo.toml` and @@ -148,10 +155,12 @@ installed one. . Do not mark it as a draft or a pre-release, otherwise it is not the "latest" release. -7. Upload **every** file from `dist-release/0.1.1/` as a release asset, including the - `.sig` files and `latest.json`. Keep the file names: `latest.json` points to them. +7. Upload every file from `dist-release/0.1.1/` as a release asset, keeping the file + names (`latest.json` points to them). Upload the installers, packages and `.sig` + files first and **`latest.json` last**. As soon as `latest.json` is visible, + installed apps may try to download the files it lists. -8. Once the assets are uploaded, publish the feed for URL 2 as well: +8. Only after all assets are uploaded, publish the feed for URL 2 as well: ```sh cp dist-release/0.1.1/latest.json latest.json @@ -184,7 +193,11 @@ After publishing 0.1.0 and then 0.1.1: progress bar, asks for no admin rights, and the app restarts as 0.1.1. The banner is gone. -Failed checks (offline, no release yet) are not shown. The log +The app also shows its main window on the first start of a new version, even if it +was started with `--autostart` (the installer restarts it with its old arguments). + +Failed checks (offline, no release yet) are not shown. They are retried after 1, 5 +and 30 minutes, then every 6 hours. The log (`%LOCALAPPDATA%\eu.euvino.callrecorder\logs`) has an Info line `update check failed: …`. @@ -192,6 +205,9 @@ Failed checks (offline, no release yet) are not shown. The log - `scripts/build-windows.sh` alone builds an unsigned test installer without updater artifacts when no signing key is set. +- `RELEASE_ALLOW_DIRTY=1` lets `build-release.sh` build with uncommitted changes to + tracked files, and `RELEASE_ALLOW_NOT_NEWER=1` lets it build a version that is not + greater than the committed one. Use them only for test builds; never publish one. - `RELEASE_ALLOW_KEY_MISMATCH=1` lets `build-release.sh` build with a key that does not match `plugins.updater.pubkey`. Use it only to test the pipeline with a throwaway key. Installed apps reject such a release, so never publish it. diff --git a/scripts/build-release.sh b/scripts/build-release.sh index 211adb7..3ad7d7d 100755 --- a/scripts/build-release.sh +++ b/scripts/build-release.sh @@ -38,6 +38,52 @@ command -v jq >/dev/null 2>&1 || die "jq not found on PATH" # shellcheck source=release.env source "${SCRIPT_DIR}/release.env" +# --- Safety checks ---------------------------------------------------------- +# The release must be built from committed sources, and the version bump this +# script makes must be the only change to commit afterwards. Untracked files +# are ignored. +if [ -n "$(git -C "${REPO_ROOT}" status --porcelain --untracked-files=no)" ]; then + if [ "${RELEASE_ALLOW_DIRTY:-}" = "1" ]; then + echo "WARNING: building from uncommitted changes (RELEASE_ALLOW_DIRTY=1)." >&2 + else + die "uncommitted changes to tracked files; commit them first (or reset a version bump left by a failed build): +$(git -C "${REPO_ROOT}" status --short --untracked-files=no)" + fi +fi + +# Whether semantic version $1 is greater than $2 (build metadata ignored). +version_gt() { + local a="${1%%+*}" b="${2%%+*}" + local a_pre="" b_pre="" i + [[ "${a}" == *-* ]] && a_pre="${a#*-}" + [[ "${b}" == *-* ]] && b_pre="${b#*-}" + local -a a_core b_core + IFS=. read -ra a_core <<<"${a%%-*}" + IFS=. read -ra b_core <<<"${b%%-*}" + for i in 0 1 2; do + ((10#${a_core[i]} > 10#${b_core[i]})) && return 0 + ((10#${a_core[i]} < 10#${b_core[i]})) && return 1 + done + # Same core: a release is greater than its pre-releases. + [ -z "${a_pre}" ] && [ -n "${b_pre}" ] && return 0 + [ -z "${a_pre}" ] || [ -z "${b_pre}" ] && return 1 + [ "${a_pre}" != "${b_pre}" ] && + [ "$(printf '%s\n%s\n' "${a_pre}" "${b_pre}" | sort -V | tail -n 1)" = "${a_pre}" ] +} + +# Installed apps only update to a greater version. The committed version may +# be built again as long as it has not been released (no tag v), +# e.g. for the first release. +CURRENT="$(git -C "${REPO_ROOT}" show HEAD:src-tauri/tauri.conf.json | jq -r .version)" +if ! version_gt "${VERSION}" "${CURRENT}" && + ! { [ "${VERSION}" = "${CURRENT}" ] && [ -z "$(git -C "${REPO_ROOT}" tag -l "v${CURRENT}")" ]; }; then + if [ "${RELEASE_ALLOW_NOT_NEWER:-}" = "1" ]; then + echo "WARNING: ${VERSION} is not greater than the current version ${CURRENT} (RELEASE_ALLOW_NOT_NEWER=1); installed apps will not update to it." >&2 + else + die "${VERSION} is not greater than the current version ${CURRENT}" + fi +fi + # --- Updater signing key --------------------------------------------------- # `cargo tauri build` reads only TAURI_SIGNING_PRIVATE_KEY (key or path). if [ -n "${TAURI_SIGNING_PRIVATE_KEY_PATH:-}" ]; then diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index b8c3a85..bf5cbf8 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -48,6 +48,13 @@ pub fn run() { .level(log::LevelFilter::Info) // flacenc logs per-encode statistics at Info. .level_for("flacenc", log::LevelFilter::Warn) + // The updater plugin logs an Error for every endpoint + // that fails, also for the expected 404 of a feed URL + // that is not served while the other one is. Every + // check and install result reaches `updater`, which + // logs it (failed checks at Info, failed installs at + // Error), so the plugin's own lines are dropped. + .level_for("tauri_plugin_updater", log::LevelFilter::Off) .max_file_size(LOG_FILE_SIZE) .rotation_strategy(RotationStrategy::KeepSome(2)) .timezone_strategy(TimezoneStrategy::UseLocal) @@ -72,6 +79,10 @@ pub fn run() { Vec::new() }); let autostart = state.settings().autostart; + let new_version = updater::first_start_of_version( + &config_dir.join("last-version"), + &app.package_info().version.to_string(), + ); // Before anything can start a run. processing::clear_upload_dir(app.handle()); app.manage(state); @@ -88,7 +99,9 @@ pub fn run() { tray::create(app.handle())?; detection::spawn(app.handle().clone()); updater::spawn(app.handle().clone()); - if !std::env::args().any(|arg| arg == AUTOSTART_ARG) { + // After an update the installer restarts the app with its old + // arguments; the main window shows the new version even then. + if new_version || !std::env::args().any(|arg| arg == AUTOSTART_ARG) { commands::show_main(app.handle()); } Ok(()) diff --git a/src-tauri/src/updater.rs b/src-tauri/src/updater.rs index a4155f0..5eb85d0 100644 --- a/src-tauri/src/updater.rs +++ b/src-tauri/src/updater.rs @@ -1,15 +1,18 @@ //! Self-update (Windows only): checks the release feed (`plugins.updater` -//! in `tauri.conf.json`) at startup and every 6 h, tells the main window -//! about a newer version and installs it when the user asks, but never while -//! a recording runs or a call is being processed. +//! in `tauri.conf.json`) at startup and every 6 h (sooner after a failed +//! check), tells the main window about a newer version and installs it when +//! the user asks, but never while a recording runs or a call is being +//! processed. //! //! On Windows the NSIS installer runs in passive mode for the current user //! (no admin rights) and restarts the app; installing ends this process. +use std::fs; +use std::path::Path; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Mutex; use std::thread; -use std::time::Duration; +use std::time::{Duration, SystemTime}; use serde::Serialize; use tauri::{AppHandle, Emitter, Manager}; @@ -17,7 +20,24 @@ use tauri_plugin_updater::{Update, UpdaterExt}; use crate::state::AppState; +/// Time between checks once a check succeeded (whether or not it found an +/// update). const CHECK_INTERVAL: Duration = Duration::from_secs(6 * 60 * 60); +/// Waits after the 1st, 2nd and 3rd failed check in a row; from the 4th +/// failure on, [`CHECK_INTERVAL`]. +const RETRY_DELAYS: [Duration; 3] = [ + Duration::from_secs(60), + Duration::from_secs(5 * 60), + Duration::from_secs(30 * 60), +]; +/// How often the check loop looks at the wall clock. Shorter than the first +/// retry delay, so retries are on time; checks are scheduled by wall-clock +/// time, so a PC that slept through a due check checks soon after waking. +const WAKE_INTERVAL: Duration = Duration::from_secs(30); +/// Limit for asking the feed for a new version. +const CHECK_TIMEOUT: Duration = Duration::from_secs(30); +/// Limit for downloading the installer. +const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(15 * 60); /// Progress steps while the download size is unknown. const MIB: u64 = 1024 * 1024; /// Why the banner cannot install yet; the banner shows the same hint. @@ -53,16 +73,47 @@ pub fn spawn(app: AppHandle) { log::info!("update check disabled on this platform"); return; } - thread::spawn(move || loop { - tauri::async_runtime::block_on(check(&app)); - thread::sleep(CHECK_INTERVAL); + thread::spawn(move || { + let mut last_attempt = None; + let mut failures = 0; + loop { + let now = SystemTime::now(); + if check_due(last_attempt, failures, now) { + last_attempt = Some(now); + if tauri::async_runtime::block_on(check(&app)) { + failures = 0; + } else { + failures = failures.saturating_add(1); + } + } + thread::sleep(WAKE_INTERVAL); + } }); } -/// Asks the release feed for a newer version. Failures (offline, no release -/// yet) are expected and only logged. -async fn check(app: &AppHandle) { - let result = match app.updater() { +/// Whether the next update check is due at `now`, given when the last one +/// started (`None`: none yet) and how many checks in a row failed. Uses the +/// wall clock, which keeps running in standby; a clock that went back makes +/// the check due. +fn check_due(last_attempt: Option, failures: u32, now: SystemTime) -> bool { + let Some(last) = last_attempt else { + return true; + }; + let wait = match failures { + 0 => CHECK_INTERVAL, + n => RETRY_DELAYS + .get(n as usize - 1) + .copied() + .unwrap_or(CHECK_INTERVAL), + }; + now.duration_since(last) + .map_or(true, |elapsed| elapsed >= wait) +} + +/// Asks the release feed for a newer version; `false` if the check failed. +/// Failures (offline, no release yet) are expected and only logged. +async fn check(app: &AppHandle) -> bool { + let result = match app.updater_builder().timeout(CHECK_TIMEOUT).build() { Ok(updater) => updater.check().await, Err(e) => Err(e), }; @@ -72,12 +123,37 @@ async fn check(app: &AppHandle) { let version = update.version.clone(); *lock(&app.state::().update) = Some(update); let _ = app.emit("update-available", info(app, version)); + true + } + Ok(None) => { + log::info!("no update available"); + true + } + Err(e) => { + log::info!("update check failed: {e}"); + false } - Ok(None) => log::info!("no update available"), - Err(e) => log::info!("update check failed: {e}"), } } +/// Whether this is the first start of `version` (e.g. right after an +/// update), going by the version remembered in `path`; remembers `version` +/// for the next start. +pub fn first_start_of_version(path: &Path, version: &str) -> bool { + let previous = fs::read_to_string(path).ok(); + if previous.as_deref().map(str::trim) == Some(version) { + return false; + } + let written = path + .parent() + .map_or(Ok(()), fs::create_dir_all) + .and_then(|()| fs::write(path, version)); + if let Err(e) = written { + log::warn!("could not remember the app version: {e}"); + } + true +} + fn info(app: &AppHandle, version: String) -> UpdateInfo { UpdateInfo { version, @@ -111,9 +187,10 @@ pub async fn install_update(app: AppHandle) -> Result<(), String> { } async fn download_and_install(app: &AppHandle) -> Result<(), String> { - let update = lock(&app.state::().update) + let mut update = lock(&app.state::().update) .clone() .ok_or_else(|| "Kein Update verfügbar".to_string())?; + update.timeout = Some(DOWNLOAD_TIMEOUT); let state = app.state::(); if state.recording_or_processing() { return Err(BUSY.to_string()); @@ -180,6 +257,64 @@ fn lock(mutex: &Mutex) -> std::sync::MutexGuard<'_, T> { mod tests { use super::*; + const MIN: Duration = Duration::from_secs(60); + const HOUR: Duration = Duration::from_secs(60 * 60); + + fn t0() -> SystemTime { + SystemTime::UNIX_EPOCH + Duration::from_secs(1_800_000_000) + } + + #[test] + fn the_first_check_is_due_at_once() { + assert!(check_due(None, 0, t0())); + } + + #[test] + fn after_a_successful_check_the_next_is_due_in_6_hours() { + assert!(!check_due(Some(t0()), 0, t0() + 6 * HOUR - MIN)); + assert!(check_due(Some(t0()), 0, t0() + 6 * HOUR)); + } + + #[test] + fn failed_checks_are_retried_after_1_5_and_30_minutes_then_6_hours() { + for (failures, wait) in [ + (1, MIN), + (2, 5 * MIN), + (3, 30 * MIN), + (4, 6 * HOUR), + (9, 6 * HOUR), + ] { + let last = Some(t0()); + assert!( + !check_due(last, failures, t0() + wait - Duration::from_secs(1)), + "{failures}" + ); + assert!(check_due(last, failures, t0() + wait), "{failures}"); + } + } + + #[test] + fn a_check_is_due_after_standby_by_the_wall_clock() { + // Days in standby: whatever the interval, the check is due on wake-up. + assert!(check_due(Some(t0()), 0, t0() + 48 * HOUR)); + } + + #[test] + fn a_check_is_due_when_the_clock_went_back() { + assert!(check_due(Some(t0()), 0, t0() - HOUR)); + } + + #[test] + fn the_first_start_of_a_version_is_noticed_once() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config").join("last-version"); + assert!(first_start_of_version(&path, "0.1.0")); + assert!(!first_start_of_version(&path, "0.1.0")); + assert!(first_start_of_version(&path, "0.1.1")); + assert!(!first_start_of_version(&path, "0.1.1")); + assert_eq!(fs::read_to_string(&path).unwrap(), "0.1.1"); + } + fn reported(meter: &mut ProgressMeter, chunks: &[usize], total: Option) -> Vec { chunks .iter()