diff --git a/src-tauri/src/backend.rs b/src-tauri/src/backend.rs index 9c850d2..332bd35 100644 --- a/src-tauri/src/backend.rs +++ b/src-tauri/src/backend.rs @@ -235,7 +235,22 @@ async fn upload(app: &AppHandle, state: &AppState, id: CallId) -> CmdResult<()> .await .inspect_err(|e| log::warn!("call {id}: upload failed: {e}"))?; log::info!("call {id}: transcript uploaded (CRM id {crm_id})"); - state.mark_uploaded(id, &crm_id) + if let Err(e) = state.mark_uploaded(id, &crm_id) { + // The CRM already has it: a retry must never send it again, even + // though the row itself still shows no crm_transcript_id. + state.note_upload_confirmed_but_unsaved(id); + log::error!("call {id}: uploaded (CRM id {crm_id}) but could not save locally: {e}"); + return Err(unsaved_upload_message(&crm_id, &e)); + } + Ok(()) +} + +/// Message for an upload that reached the CRM (`crm_id`) but whose local +/// record (`mark_uploaded`) failed with `e`: names the CRM id so the user +/// can find it there, and says plainly not to upload the call again (the +/// app also refuses on its own, see `AppState::note_upload_confirmed_but_unsaved`). +fn unsaved_upload_message(crm_id: &str, e: &str) -> String { + format!("Hochgeladen (ID {crm_id}), aber lokal nicht gespeichert: {e} – nicht erneut hochladen") } /// [`Login`] through the login window, for the upload. @@ -448,6 +463,14 @@ mod tests { } } + #[test] + fn the_unsaved_upload_message_names_the_crm_id_and_warns_against_retrying() { + assert_eq!( + unsaved_upload_message("4711", "disk full"), + "Hochgeladen (ID 4711), aber lokal nicht gespeichert: disk full – nicht erneut hochladen" + ); + } + #[test] fn everyone_waiting_gets_the_one_login_result() { let waiters = LoginWaiters::default(); diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs index 593ac2b..34d7693 100644 --- a/src-tauri/src/state.rs +++ b/src-tauri/src/state.rs @@ -164,6 +164,12 @@ pub struct AppState { backend_key_lock: Mutex<()>, /// Calls whose transcript is being uploaded; one upload per call. uploading: Mutex>, + /// Calls whose transcript reached the CRM but could not be recorded + /// locally (`mark_uploaded` failed after a successful upload): + /// `claim_upload` refuses these for the rest of this run, so a retry + /// never creates a second copy at the CRM. In-memory only; a restart + /// forgets it (the row's `crm_transcript_id` is still empty then). + upload_confirmed_unsaved: Mutex>, } /// An upload reserved with [`AppState::claim_upload`]; released when @@ -217,6 +223,7 @@ impl AppState { .to_string(), backend_key_lock: Mutex::new(()), uploading: Mutex::new(HashSet::new()), + upload_confirmed_unsaved: Mutex::new(HashSet::new()), } } @@ -342,16 +349,21 @@ impl AppState { } /// Reserves call `id` for one upload; released when the claim is - /// dropped. A second upload of the same call is refused meanwhile, and a - /// call that already carries a CRM transcript id is refused outright: - /// the CRM must never get a duplicate. Both checks happen while - /// `uploading` is locked, so a second upload can never slip in between - /// this check and the one upload it allows. + /// dropped. A second upload of the same call is refused meanwhile, and + /// so is a call that already carries a CRM transcript id — or one the + /// CRM confirmed but whose id could not be saved locally, see + /// [`AppState::note_upload_confirmed_but_unsaved`]: the CRM must never + /// get a duplicate. All three checks happen while `uploading` is + /// locked, so a second upload can never slip in between this check and + /// the one upload it allows. pub fn claim_upload(&self, id: CallId) -> Result, String> { let mut uploading = lock(&self.uploading); if uploading.contains(&id) { return Err("Wird bereits hochgeladen".to_string()); } + if lock(&self.upload_confirmed_unsaved).contains(&id) { + return Err("Bereits hochgeladen".to_string()); + } if self.find_call(id)?.crm_transcript_id.is_some() { return Err("Bereits hochgeladen".to_string()); } @@ -364,6 +376,14 @@ impl AppState { lock(&self.uploading).contains(&id) } + /// Records that call `id`'s transcript reached the CRM, but saving that + /// locally (`mark_uploaded`) failed: [`AppState::claim_upload`] refuses + /// this call for the rest of the run, so a retry can never send the CRM + /// a second copy. In-memory only; see the field's doc comment. + pub fn note_upload_confirmed_but_unsaved(&self, id: CallId) { + lock(&self.upload_confirmed_unsaved).insert(id); + } + /// Changes and saves settings the app manages itself; saves only if /// something changed. fn update_settings(&self, change: impl FnOnce(&mut Settings)) -> Result<(), String> { @@ -1643,6 +1663,29 @@ mod tests { assert!(!f.state.is_uploading(id)); } + #[test] + fn an_upload_confirmed_but_unsaved_is_never_retried() { + // The CRM has the transcript, but mark_uploaded failed: the row + // itself still shows no crm_transcript_id. + let f = fixture(); + let (id, _, _) = finished_call(&f, "a"); + f.state.note_upload_confirmed_but_unsaved(id); + + assert!(f + .state + .call_detail(id) + .unwrap() + .call + .item + .crm_transcript_id + .is_none()); + assert_eq!( + f.state.claim_upload(id).err(), + Some("Bereits hochgeladen".to_string()) + ); + assert!(!f.state.is_uploading(id)); + } + #[test] fn an_upload_is_recorded_on_the_call() { let f = fixture(); diff --git a/src-tauri/src/updater.rs b/src-tauri/src/updater.rs index 75f8389..cfed782 100644 --- a/src-tauri/src/updater.rs +++ b/src-tauri/src/updater.rs @@ -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(&self, only_if_due: bool, check: F) -> Option + where + F: FnOnce() -> Fut, + Fut: Future, + { 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::().is_due(now) { - tauri::async_runtime::block_on(app.state::().run(&app)); + tauri::async_runtime::block_on(app.state::().run_if_due(&app)); } thread::sleep(WAKE_INTERVAL); }); @@ -176,32 +219,62 @@ fn check_due(last_attempt: Option, 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::().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::().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) -> (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 { /// 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::(); 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 { .. }))); + } } diff --git a/ui/src/routes/Settings.svelte b/ui/src/routes/Settings.svelte index eab921f..54ef445 100644 --- a/ui/src/routes/Settings.svelte +++ b/ui/src/routes/Settings.svelte @@ -71,6 +71,24 @@ let installProgress = $state(null) let installError = $state('') + /** The version to show as "available", if any. On Windows this comes + * from `pendingUpdate` (kept in sync with the banner by `get_update`/ + * `update-available`, so it is current even without a manual check). + * Everywhere else the backend never stores `pendingUpdate` for a found + * update (see `updater::check_outcome`), so a manual check's own result + * is the only source. It is also the fallback whenever `pendingUpdate` + * is not known (e.g. the follow-up `getUpdate()` failed, or + * `canSelfUpdate()` failed): a found update is never hidden. */ + let availableVersion = $derived( + (selfUpdateCapable === true ? pendingUpdate?.version : undefined) ?? + (checkResult?.status === 'available' ? checkResult.version : undefined), + ) + /** Whether the install button/progress can be offered for + * `availableVersion`: only once this build is confirmed able to + * self-update AND `pendingUpdate` (with its `can_install` guard) is + * actually known. */ + let canOfferInstall = $derived(selfUpdateCapable === true && pendingUpdate !== null) + onMount(() => { load() backendServer() @@ -97,20 +115,22 @@ /** "Nach Updates suchen": runs the same check as the background loop, * immediately. An available update also arrives via `update-available` - * (so the main window's banner shows it too), but is applied here as - * well in case that event is missed. */ + * (so the main window's banner shows it too, on Windows), but is applied + * here as well in case that event is missed. That follow-up fetch is + * best-effort: if it fails, the "available" result just found still + * stands — it must never be replaced by that unrelated failure. */ async function checkUpdateNow() { checking = true checkResult = null try { - const result = await checkForUpdateNow() - checkResult = result - if (result.status === 'available') pendingUpdate = await getUpdate() + checkResult = await checkForUpdateNow() } catch (err) { checkResult = { status: 'error', message: errorText(err) } - } finally { checking = false + return } + if (checkResult.status === 'available') await refreshPendingUpdate() + checking = false } async function refreshPendingUpdate() { @@ -470,24 +490,30 @@ {checkResult.message} {/if} - {#if pendingUpdate && selfUpdateCapable !== null} + {#if availableVersion !== undefined}
- Update verfügbar (v{pendingUpdate.version}) - {#if selfUpdateCapable} + Update verfügbar (v{availableVersion}) + {#if canOfferInstall} {#if installing} {updateProgressText(installProgress)} {:else} - - {#if !pendingUpdate.can_install} + {#if !pendingUpdate?.can_install} {UPDATE_BUSY_HINT} {/if} {/if} {#if installError} {installError} {/if} - {:else} + {:else if selfUpdateCapable !== true} + Updates gibt es unter Windows automatisch; unter Linux bitte das .deb neu installieren.