fix #14740: linux update check and upload safety

- 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>
This commit is contained in:
hauke
2026-11-09 10:50:12 +01:00
co-authored by Claude Opus 5.5
parent 083edf32a2
commit a0f89454f9
4 changed files with 273 additions and 41 deletions
+163 -23
View File
@@ -13,6 +13,7 @@
//! 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;
@@ -47,6 +48,17 @@ const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(15 * 60);
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)]
@@ -64,9 +76,10 @@ pub struct UpdateInfo {
}
/// Answer of `check_for_update_now`: what a check (background or manual)
/// found. `Available` 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.
/// 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 {
@@ -116,15 +129,42 @@ impl UpdateSchedule {
};
}
/// Runs one check attempt right now: serialized against any other check
/// (background or manual) via `running`, and recorded for the
/// scheduler exactly like a background attempt.
/// 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();
let result = check(app).await;
if only_if_due && !self.is_due(now) {
return None;
}
let result = check().await;
self.record(now, !matches!(result, UpdateCheckResult::Error { .. }));
result
Some(result)
}
}
@@ -146,8 +186,11 @@ pub fn spawn(app: AppHandle) {
}
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(&app));
tauri::async_runtime::block_on(app.state::<UpdateSchedule>().run_if_due(&app));
}
thread::sleep(WAKE_INTERVAL);
});
@@ -176,32 +219,62 @@ fn check_due(last_attempt: Option<SystemTime>, failures: u32, now: SystemTime) -
/// 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 result = match app.updater_builder().timeout(CHECK_TIMEOUT).build() {
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(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.clone()));
UpdateCheckResult::Available { version }
}
Ok(None) => {
log::info!("no update available");
UpdateCheckResult::None
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-Server nicht erreichbar: {e}"),
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.
@@ -258,6 +331,11 @@ pub fn get_update(app: AppHandle) -> Option<UpdateInfo> {
/// 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());
@@ -450,13 +528,40 @@ mod tests {
);
assert_eq!(
serde_json::to_value(UpdateCheckResult::Error {
message: "Update-Server nicht erreichbar: x".into()
message: "Update-Prüfung fehlgeschlagen: x".into()
})
.unwrap(),
serde_json::json!({"status": "error", "message": "Update-Server nicht erreichbar: x"})
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
@@ -485,4 +590,39 @@ mod tests {
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 { .. })));
}
}