- Linux: ask the feed for the windows-x86_64 entry only to learn the version; report it (the settings show the .deb hint) without storing a pending update or announcing it. install_update refuses off Windows. - Background checks re-check is_due once the running lock is held. - Check errors read "Update-Prüfung fehlgeschlagen: …". - Settings: a failed follow-up getUpdate() never hides a found update; an unknown canSelfUpdate() shows it without an install button. - An upload the CRM accepted but that could not be saved locally names the CRM id and is refused for re-upload until the app restarts. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
629 lines
23 KiB
Rust
629 lines
23 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. The settings' "Nach Updates suchen" button
|
||
//! ([`check_for_update_now`]) runs the very same check immediately, counts
|
||
//! as an attempt for the same scheduler ([`UpdateSchedule`]) and never runs
|
||
//! at the same time as the background loop.
|
||
//!
|
||
//! On Windows the NSIS installer runs in passive mode for the current user
|
||
//! (no admin rights) and restarts the app; installing ends this process.
|
||
//! Debian builds never self-update; a manual check still asks the feed
|
||
//! there (see [`can_self_update`]).
|
||
|
||
use std::fs;
|
||
use std::future::Future;
|
||
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 feed's key for the one installable release this app ever builds for
|
||
/// itself (see `UpdaterBuilder::target`). Asked explicitly on platforms
|
||
/// that cannot self-update, since the feed has no entry of their own and
|
||
/// the updater's automatic target lookup would otherwise fail with
|
||
/// `TargetsNotFound` even when a newer version exists.
|
||
const WINDOWS_TARGET: &str = "windows-x86_64";
|
||
/// Why installing is refused outright on this platform (`install_update`'s
|
||
/// own guard, in case a future feed ever gets a non-Windows entry and
|
||
/// `check` started finding updates there too).
|
||
const LINUX_CANNOT_INSTALL: &str =
|
||
"Updates werden unter Linux nicht automatisch installiert – bitte das .deb neu installieren.";
|
||
|
||
/// 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,
|
||
}
|
||
|
||
/// Answer of `check_for_update_now`: what a check (background or manual)
|
||
/// found. On Windows, `Available` also leaves the same state `get_update`
|
||
/// reads and fires the same `update-available` event as the background
|
||
/// loop, so the main window's banner shows it too; elsewhere it only
|
||
/// reports the version (see `check_outcome`).
|
||
#[derive(Serialize, Clone, Debug, PartialEq)]
|
||
#[serde(tag = "status", rename_all = "lowercase")]
|
||
pub enum UpdateCheckResult {
|
||
/// No newer version on the feed.
|
||
None,
|
||
Available {
|
||
version: String,
|
||
},
|
||
/// The feed could not be asked; safe to show (never a secret).
|
||
Error {
|
||
message: String,
|
||
},
|
||
}
|
||
|
||
/// When the last check attempt (background or manual) started and how many
|
||
/// failed in a row, shared so a manual check feeds the same scheduler the
|
||
/// background loop uses: success resets the 6 h interval and the failure
|
||
/// count, a failure advances the backoff by one step. `running` also
|
||
/// serializes checks, so a manual and a background check never run at once.
|
||
#[derive(Default)]
|
||
pub struct UpdateSchedule {
|
||
state: Mutex<Schedule>,
|
||
running: tokio::sync::Mutex<()>,
|
||
}
|
||
|
||
#[derive(Default, Clone, Copy)]
|
||
struct Schedule {
|
||
last_attempt: Option<SystemTime>,
|
||
failures: u32,
|
||
}
|
||
|
||
impl UpdateSchedule {
|
||
/// Whether a check is due at `now`, per the last recorded attempt.
|
||
fn is_due(&self, now: SystemTime) -> bool {
|
||
let s = lock(&self.state);
|
||
check_due(s.last_attempt, s.failures, now)
|
||
}
|
||
|
||
/// Records the outcome of a check attempt that started at `now`.
|
||
fn record(&self, now: SystemTime, success: bool) {
|
||
let mut s = lock(&self.state);
|
||
s.last_attempt = Some(now);
|
||
s.failures = if success {
|
||
0
|
||
} else {
|
||
s.failures.saturating_add(1)
|
||
};
|
||
}
|
||
|
||
/// Runs one check attempt right now, unconditionally: for a manual
|
||
/// check, which the user asked for regardless of whether one is due.
|
||
/// Serialized against any other check (background or manual) via
|
||
/// `running`, and recorded for the scheduler exactly like a background
|
||
/// attempt.
|
||
async fn run(&self, app: &AppHandle) -> UpdateCheckResult {
|
||
self.attempt(false, || check(app))
|
||
.await
|
||
.expect("an unconditional attempt always runs")
|
||
}
|
||
|
||
/// For the background loop: like [`UpdateSchedule::run`], but only if a
|
||
/// check is still due once `running` is held (see `attempt`).
|
||
async fn run_if_due(&self, app: &AppHandle) {
|
||
self.attempt(true, || check(app)).await;
|
||
}
|
||
|
||
/// One serialized, recorded check attempt: takes `running`, then (if
|
||
/// `only_if_due`) re-checks `is_due` before calling `check`. Without
|
||
/// that re-check, a background tick that found a check due but then
|
||
/// had to wait behind a manual check (or another tick) would run its
|
||
/// own check right after, although the one it waited for just made the
|
||
/// next one not due any more. `None`: skipped, nothing recorded.
|
||
async fn attempt<F, Fut>(&self, only_if_due: bool, check: F) -> Option<UpdateCheckResult>
|
||
where
|
||
F: FnOnce() -> Fut,
|
||
Fut: Future<Output = UpdateCheckResult>,
|
||
{
|
||
let _serialize = self.running.lock().await;
|
||
let now = SystemTime::now();
|
||
if only_if_due && !self.is_due(now) {
|
||
return None;
|
||
}
|
||
let result = check().await;
|
||
self.record(now, !matches!(result, UpdateCheckResult::Error { .. }));
|
||
Some(result)
|
||
}
|
||
}
|
||
|
||
/// 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 (a manual check from the settings still asks the feed
|
||
/// on Linux, see `check_for_update_now`).
|
||
pub fn spawn(app: AppHandle) {
|
||
if !cfg!(windows) {
|
||
log::info!("update check disabled on this platform");
|
||
return;
|
||
}
|
||
thread::spawn(move || loop {
|
||
let now = SystemTime::now();
|
||
// Cheap early exit so most wake-ups never touch `running`; the due
|
||
// check that decides whether a check actually runs happens again
|
||
// inside `run_if_due`, once `running` is held (see its doc comment).
|
||
if app.state::<UpdateSchedule>().is_due(now) {
|
||
tauri::async_runtime::block_on(app.state::<UpdateSchedule>().run_if_due(&app));
|
||
}
|
||
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: the one implementation the
|
||
/// background loop and a manual check (`check_for_update_now`) both run.
|
||
/// A failed check (offline, no release yet) is expected; only logged here,
|
||
/// and shown to the user only by a manual check (via the returned message).
|
||
///
|
||
/// The feed only ever has a `windows-x86_64` entry (Debian builds never
|
||
/// self-update, see `RELEASING.md`). On Windows the automatic target lookup
|
||
/// finds it on its own; on any other platform it is asked for explicitly
|
||
/// ([`WINDOWS_TARGET`]), only to learn the version number — see
|
||
/// [`check_outcome`] for why nothing is stored or announced there.
|
||
async fn check(app: &AppHandle) -> UpdateCheckResult {
|
||
let is_windows = cfg!(windows);
|
||
let mut builder = app.updater_builder().timeout(CHECK_TIMEOUT);
|
||
if !is_windows {
|
||
builder = builder.target(WINDOWS_TARGET);
|
||
}
|
||
let result = match builder.build() {
|
||
Ok(updater) => updater.check().await,
|
||
Err(e) => Err(e),
|
||
};
|
||
match result {
|
||
Ok(found) => {
|
||
let version = found.as_ref().map(|update| update.version.clone());
|
||
match &version {
|
||
Some(v) => log::info!("update available: {v}"),
|
||
None => log::info!("no update available"),
|
||
}
|
||
let (outcome, offer_install) = check_outcome(is_windows, version.clone());
|
||
if let (Some(update), true) = (found, offer_install) {
|
||
*lock(&app.state::<PendingUpdate>().update) = Some(update);
|
||
let _ = app.emit(
|
||
"update-available",
|
||
info(app, version.expect("offer_install implies a version")),
|
||
);
|
||
}
|
||
outcome
|
||
}
|
||
Err(e) => {
|
||
log::info!("update check failed: {e}");
|
||
UpdateCheckResult::Error {
|
||
message: format!("Update-Prüfung fehlgeschlagen: {e}"),
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// What a feed answer (`version`, if any) means on this platform: the
|
||
/// result to return either way, and whether to remember the update for
|
||
/// `install_update` and announce it to the main window's banner. Only
|
||
/// Windows self-updates, so only there is a found update ever stored or
|
||
/// announced; elsewhere a manual check still reports the version (the
|
||
/// settings show it with a "not on this platform" hint instead of an
|
||
/// install button), but nothing is kept to install.
|
||
fn check_outcome(is_windows: bool, version: Option<String>) -> (UpdateCheckResult, bool) {
|
||
match version {
|
||
Some(version) => (UpdateCheckResult::Available { version }, is_windows),
|
||
None => (UpdateCheckResult::None, 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(),
|
||
}
|
||
}
|
||
|
||
/// "Nach Updates suchen" in the settings: runs the same check as the
|
||
/// background loop, immediately, reusing its scheduling (a success resets
|
||
/// the 6 h interval and the failure count, same as a background success)
|
||
/// and never running at the same time as a background check. Works on
|
||
/// every platform; see `can_self_update` for whether this build can then
|
||
/// install what it finds.
|
||
#[tauri::command]
|
||
pub async fn check_for_update_now(app: AppHandle) -> UpdateCheckResult {
|
||
app.state::<UpdateSchedule>().run(&app).await
|
||
}
|
||
|
||
/// Whether this build can install an update itself (Windows only: Debian
|
||
/// builds ship a `.deb` and never self-update, see `spawn`).
|
||
#[tauri::command]
|
||
pub fn can_self_update() -> bool {
|
||
cfg!(windows)
|
||
}
|
||
|
||
/// 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> {
|
||
// Defense in depth: `check` only ever stores a pending update on
|
||
// Windows, but this guard holds even if that ever changes.
|
||
if !cfg!(windows) {
|
||
return Err(LINUX_CANNOT_INSTALL.to_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]);
|
||
}
|
||
|
||
#[test]
|
||
fn update_check_result_maps_to_a_tagged_status() {
|
||
assert_eq!(
|
||
serde_json::to_value(UpdateCheckResult::None).unwrap(),
|
||
serde_json::json!({"status": "none"})
|
||
);
|
||
assert_eq!(
|
||
serde_json::to_value(UpdateCheckResult::Available {
|
||
version: "0.3.0".into()
|
||
})
|
||
.unwrap(),
|
||
serde_json::json!({"status": "available", "version": "0.3.0"})
|
||
);
|
||
assert_eq!(
|
||
serde_json::to_value(UpdateCheckResult::Error {
|
||
message: "Update-Prüfung fehlgeschlagen: x".into()
|
||
})
|
||
.unwrap(),
|
||
serde_json::json!({"status": "error", "message": "Update-Prüfung fehlgeschlagen: x"})
|
||
);
|
||
}
|
||
|
||
/// Only Windows self-updates: elsewhere a found update is still
|
||
/// reported (so the settings can show the version), but never stored
|
||
/// for `install_update` or announced to the banner.
|
||
#[test]
|
||
fn only_windows_offers_to_install_a_found_update() {
|
||
assert_eq!(
|
||
check_outcome(true, Some("0.3.0".into())),
|
||
(
|
||
UpdateCheckResult::Available {
|
||
version: "0.3.0".into()
|
||
},
|
||
true
|
||
)
|
||
);
|
||
assert_eq!(
|
||
check_outcome(false, Some("0.3.0".into())),
|
||
(
|
||
UpdateCheckResult::Available {
|
||
version: "0.3.0".into()
|
||
},
|
||
false
|
||
)
|
||
);
|
||
assert_eq!(check_outcome(true, None), (UpdateCheckResult::None, false));
|
||
assert_eq!(check_outcome(false, None), (UpdateCheckResult::None, false));
|
||
}
|
||
|
||
/// A manual check feeds the very scheduler the background loop reads
|
||
/// (`record` is the one function either kind of attempt calls): a
|
||
/// failure advances the backoff by exactly the one step a single
|
||
/// failure always does (never more just for being a manual attempt),
|
||
/// and a success resets the interval to 6 h and the failure count.
|
||
#[test]
|
||
fn a_manual_checks_result_feeds_the_background_scheduler() {
|
||
let schedule = UpdateSchedule::default();
|
||
assert!(schedule.is_due(t0()), "nothing attempted yet");
|
||
|
||
// One failed manual check: due again after the 1st retry delay,
|
||
// exactly as check_due(_, 1, _) says, not sooner and not later.
|
||
schedule.record(t0(), false);
|
||
assert!(!schedule.is_due(t0() + MIN - Duration::from_secs(1)));
|
||
assert!(schedule.is_due(t0() + MIN));
|
||
|
||
// A second failed attempt (background or manual, the scheduler does
|
||
// not distinguish) advances to the 2nd retry delay, not further.
|
||
schedule.record(t0() + MIN, false);
|
||
assert!(!schedule.is_due(t0() + MIN + 5 * MIN - Duration::from_secs(1)));
|
||
assert!(schedule.is_due(t0() + MIN + 5 * MIN));
|
||
|
||
// A manual check that then succeeds resets the interval to 6 h and
|
||
// the failure count, exactly like a background success.
|
||
schedule.record(t0() + MIN, true);
|
||
assert!(!schedule.is_due(t0() + MIN + 6 * HOUR - MIN));
|
||
assert!(schedule.is_due(t0() + MIN + 6 * HOUR));
|
||
}
|
||
|
||
/// A background tick that found a check due, but only got `running`
|
||
/// after a manual check finished, must not check again: `is_due` is
|
||
/// re-checked once the lock is held. Sequential here (the tick's own
|
||
/// early `is_due` happened before the manual check, so only the
|
||
/// re-check inside `attempt` can stop it).
|
||
#[test]
|
||
fn a_background_attempt_rechecks_due_once_it_holds_the_lock() {
|
||
let schedule = UpdateSchedule::default();
|
||
assert!(
|
||
schedule.is_due(SystemTime::now()),
|
||
"the tick saw a due check"
|
||
);
|
||
|
||
let manual = tauri::async_runtime::block_on(
|
||
schedule.attempt(false, || async { UpdateCheckResult::None }),
|
||
);
|
||
assert_eq!(manual, Some(UpdateCheckResult::None));
|
||
|
||
let mut checked = false;
|
||
let background = tauri::async_runtime::block_on(schedule.attempt(true, || {
|
||
checked = true;
|
||
async { UpdateCheckResult::None }
|
||
}));
|
||
assert_eq!(background, None);
|
||
assert!(!checked, "no second check right after the manual one");
|
||
|
||
// A manual check always runs, due or not.
|
||
let again = tauri::async_runtime::block_on(schedule.attempt(false, || async {
|
||
UpdateCheckResult::Error {
|
||
message: "x".into(),
|
||
}
|
||
}));
|
||
assert!(matches!(again, Some(UpdateCheckResult::Error { .. })));
|
||
}
|
||
}
|