fix #14740: faster update retries and release safety checks

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
hauke
2026-11-06 11:50:43 +01:00
co-authored by Claude Opus 5.5
parent bda584deda
commit c7811b75ae
4 changed files with 232 additions and 22 deletions
+149 -14
View File
@@ -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<SystemTime>, 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::<PendingUpdate>().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::<PendingUpdate>().update)
let mut update = lock(&app.state::<PendingUpdate>().update)
.clone()
.ok_or_else(|| "Kein Update verfügbar".to_string())?;
update.timeout = Some(DOWNLOAD_TIMEOUT);
let state = app.state::<AppState>();
if state.recording_or_processing() {
return Err(BUSY.to_string());
@@ -180,6 +257,64 @@ fn lock<T>(mutex: &Mutex<T>) -> 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<u64>) -> Vec<u64> {
chunks
.iter()