Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
354 lines
12 KiB
Rust
354 lines
12 KiB
Rust
//! Self-update (Windows only): checks the release feed (`plugins.updater`
|
|
//! 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, SystemTime};
|
|
|
|
use serde::Serialize;
|
|
use tauri::{AppHandle, Emitter, Manager};
|
|
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.
|
|
const BUSY: &str = "Nach der laufenden Aufnahme/Verarbeitung möglich";
|
|
|
|
/// The newest update found, and whether one is being installed.
|
|
#[derive(Default)]
|
|
pub struct PendingUpdate {
|
|
update: Mutex<Option<Update>>,
|
|
installing: AtomicBool,
|
|
}
|
|
|
|
/// Payload of `update-available` and answer of `get_update`.
|
|
#[derive(Serialize, Clone, Debug, PartialEq)]
|
|
pub struct UpdateInfo {
|
|
pub version: String,
|
|
/// `false` while a recording runs or a call is being processed.
|
|
pub can_install: bool,
|
|
}
|
|
|
|
/// Payload of `update-progress`.
|
|
#[derive(Serialize, Clone, Debug, PartialEq)]
|
|
pub struct Progress {
|
|
pub downloaded: u64,
|
|
/// `None` if the server sends no size.
|
|
pub total: Option<u64>,
|
|
}
|
|
|
|
/// Starts the periodic update check. Only on Windows: Debian builds do not
|
|
/// update themselves.
|
|
pub fn spawn(app: AppHandle) {
|
|
if !cfg!(windows) {
|
|
log::info!("update check disabled on this platform");
|
|
return;
|
|
}
|
|
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);
|
|
}
|
|
});
|
|
}
|
|
|
|
/// 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),
|
|
};
|
|
match result {
|
|
Ok(Some(update)) => {
|
|
log::info!("update available: {}", update.version);
|
|
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
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 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,
|
|
can_install: !app.state::<AppState>().recording_or_processing(),
|
|
}
|
|
}
|
|
|
|
/// The update found by the last check, if any.
|
|
#[tauri::command]
|
|
pub fn get_update(app: AppHandle) -> Option<UpdateInfo> {
|
|
let version = lock(&app.state::<PendingUpdate>().update)
|
|
.as_ref()
|
|
.map(|update| update.version.clone())?;
|
|
Some(info(&app, version))
|
|
}
|
|
|
|
/// Downloads, verifies and installs the update found, then restarts the
|
|
/// app. Returns only on failure.
|
|
#[tauri::command]
|
|
pub async fn install_update(app: AppHandle) -> Result<(), String> {
|
|
let pending = app.state::<PendingUpdate>();
|
|
if pending.installing.swap(true, Ordering::SeqCst) {
|
|
return Err("Das Update wird bereits installiert".to_string());
|
|
}
|
|
let result = download_and_install(&app).await;
|
|
pending.installing.store(false, Ordering::SeqCst);
|
|
if let Err(e) = &result {
|
|
log::error!("update failed: {e}");
|
|
}
|
|
result
|
|
}
|
|
|
|
async fn download_and_install(app: &AppHandle) -> Result<(), String> {
|
|
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());
|
|
}
|
|
log::info!("downloading update {}", update.version);
|
|
let mut meter = ProgressMeter::default();
|
|
let bytes = update
|
|
.download(
|
|
|chunk, total| {
|
|
if let Some(progress) = meter.add(chunk, total) {
|
|
let _ = app.emit("update-progress", progress);
|
|
}
|
|
},
|
|
|| {},
|
|
)
|
|
.await
|
|
.map_err(|e| format!("Download fehlgeschlagen: {e}"))?;
|
|
// A call may have started during the download.
|
|
if state.recording_or_processing() {
|
|
return Err(BUSY.to_string());
|
|
}
|
|
log::info!("installing update {}", update.version);
|
|
// On Windows this starts the installer and ends the app.
|
|
update
|
|
.install(bytes)
|
|
.map_err(|e| format!("Installation fehlgeschlagen: {e}"))?;
|
|
app.restart()
|
|
}
|
|
|
|
/// Counts downloaded bytes and decides when the banner hears about them:
|
|
/// at every whole percent, or every MiB while the size is unknown.
|
|
#[derive(Default)]
|
|
struct ProgressMeter {
|
|
downloaded: u64,
|
|
reported_step: Option<u64>,
|
|
}
|
|
|
|
impl ProgressMeter {
|
|
fn add(&mut self, chunk: usize, total: Option<u64>) -> Option<Progress> {
|
|
self.downloaded += chunk as u64;
|
|
let step = match total {
|
|
Some(total) if total > 0 => self.downloaded * 100 / total,
|
|
_ => self.downloaded / MIB,
|
|
};
|
|
if self.reported_step == Some(step) {
|
|
return None;
|
|
}
|
|
self.reported_step = Some(step);
|
|
Some(Progress {
|
|
downloaded: self.downloaded,
|
|
total,
|
|
})
|
|
}
|
|
}
|
|
|
|
/// Locks ignoring poisoning, like the app state does.
|
|
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
|
mutex
|
|
.lock()
|
|
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
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()
|
|
.filter_map(|&chunk| meter.add(chunk, total))
|
|
.map(|progress| progress.downloaded)
|
|
.collect()
|
|
}
|
|
|
|
#[test]
|
|
fn progress_is_reported_once_per_whole_percent() {
|
|
let mut meter = ProgressMeter::default();
|
|
// 1000 bytes: 10 bytes are one percent.
|
|
let chunks = [4, 4, 4, 4, 4, 980];
|
|
assert_eq!(reported(&mut meter, &chunks, Some(1000)), [4, 12, 20, 1000]);
|
|
}
|
|
|
|
#[test]
|
|
fn the_first_chunk_is_always_reported() {
|
|
let mut meter = ProgressMeter::default();
|
|
assert_eq!(
|
|
meter.add(1, Some(1_000_000)),
|
|
Some(Progress {
|
|
downloaded: 1,
|
|
total: Some(1_000_000)
|
|
})
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn without_a_size_progress_is_reported_every_mib() {
|
|
let mut meter = ProgressMeter::default();
|
|
let half = (MIB / 2) as usize;
|
|
let reports = reported(&mut meter, &[half, half, half, half, half], None);
|
|
assert_eq!(reports, [MIB / 2, MIB, 2 * MIB]);
|
|
}
|
|
}
|