diff --git a/crates/accshift-core/src/platforms/battle_net/tests.rs b/crates/accshift-core/src/platforms/battle_net/tests.rs index caf51418..bcbb717f 100644 --- a/crates/accshift-core/src/platforms/battle_net/tests.rs +++ b/crates/accshift-core/src/platforms/battle_net/tests.rs @@ -663,3 +663,40 @@ fn a_setup_that_fails_after_quitting_the_launcher_starts_it_again() { assert_eq!(result, Ok(7)); assert!(!restarted); } + +#[test] +fn a_local_config_without_owed_names_still_loads() { + let _guard = crate::config::config_io_test_mutex() + .lock() + .unwrap_or_else(|e| e.into_inner()); + let root = std::env::temp_dir().join(format!( + "accshift-battlenet-owed-legacy-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + let _ = std::fs::remove_dir_all(&root); + let ctx = TestCtx { root: root.clone() }; + // A local file as 2.0.1 leaves it with nothing owed (the field is skipped + // when empty) or as 2.0.0 left it, before the field existed. + let local = crate::storage::local_config_path(&ctx).unwrap(); + std::fs::create_dir_all(local.parent().unwrap()).unwrap(); + std::fs::write( + &local, + r#"{"steam":{"path_override":""},"battleNet":{"path_override":"D:/Games/Battle.net"}}"#, + ) + .unwrap(); + + let config = crate::config::load_config(&ctx); + assert_eq!(config.battle_net.path_override, "D:/Games/Battle.net"); + assert!(config.battle_net.owed_saved_accounts.is_empty()); + let (merged, owed) = with_owed_saved_accounts(&ctx, vec!["new@example.com".to_string()]); + assert!(owed.is_empty()); + assert_eq!(merged, vec!["new@example.com".to_string()]); + + // The first owed list lands beside the fields already there. + owe_saved_accounts(&ctx, &["old@example.com".to_string()]); + let config = crate::config::load_config(&ctx); + assert_eq!(config.battle_net.path_override, "D:/Games/Battle.net"); + assert_eq!(config.battle_net.owed_saved_accounts, ["old@example.com"]); + let _ = std::fs::remove_dir_all(&root); +} diff --git a/crates/accshift-egui/Cargo.toml b/crates/accshift-egui/Cargo.toml index 63ec5f44..dda61891 100644 --- a/crates/accshift-egui/Cargo.toml +++ b/crates/accshift-egui/Cargo.toml @@ -71,7 +71,7 @@ image-webp = "0.2" [target.'cfg(not(windows))'.dependencies] egui = { version = "0.37", features = ["default_fonts"] } -# Unix termination signals (window/signal.rs): SIGTERM and SIGINT run the same +# Unix termination signals (window/signal.rs): SIGTERM, SIGINT and SIGHUP run the same # orderly shutdown as a normal quit. `libc` is already in the workspace graph. [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/crates/accshift-egui/src/app/saves.rs b/crates/accshift-egui/src/app/saves.rs index f55abe9b..3c026a3d 100644 --- a/crates/accshift-egui/src/app/saves.rs +++ b/crates/accshift-egui/src/app/saves.rs @@ -92,6 +92,7 @@ impl AppModel { .run(move |backend| backend.save_client_storage_store(store_id, &save.value)); self.saves.push((store_id, pending)); } + let mut reported = false; self.saves.retain_mut(|(id, pending)| { let result = match pending.poll() { Poll::Waiting => return true, @@ -103,7 +104,15 @@ impl AppModel { self.backup.save_failed(error); } b.stores.finish_save(id, &result); + reported = true; false }); + // The job's wake brought this frame and is spent. A write that ends + // frees its store, whose next write the timed repaint above left + // out and may be due already, and a backup's drain ran earlier in + // this frame: without one more frame both wait for the next input. + if reported { + ctx.request_repaint(); + } } } diff --git a/crates/accshift-egui/src/app/tests.rs b/crates/accshift-egui/src/app/tests.rs index 20628c3d..8ce35a57 100644 --- a/crates/accshift-egui/src/app/tests.rs +++ b/crates/accshift-egui/src/app/tests.rs @@ -13,7 +13,9 @@ use super::*; mod backup_restore; mod early_boot; +mod held; mod native_regressions; +mod pump; mod real_unreadable; mod shortcuts; mod updates; diff --git a/crates/accshift-egui/src/app/tests/backup_restore.rs b/crates/accshift-egui/src/app/tests/backup_restore.rs index f8e9094c..c48d8a4a 100644 --- a/crates/accshift-egui/src/app/tests/backup_restore.rs +++ b/crates/accshift-egui/src/app/tests/backup_restore.rs @@ -4,6 +4,8 @@ //! closing under it. An export waits behind the same boundary. use super::super::settings_panel::SettingsAction; +use super::held::HeldCommands; +use super::pump; use super::*; use accshift_app::i18n::{translate, Locale}; use serde_json::json; @@ -68,13 +70,38 @@ fn frame(app: &mut AppModel, ctx: &Context) { output.textures_delta.clear(); } +/// Frames until `condition` holds: [`pump::until`]. +#[track_caller] fn pump_until(app: &mut AppModel, ctx: &Context, condition: impl Fn(&AppModel) -> bool) { - let deadline = Instant::now() + std::time::Duration::from_secs(3); - while !condition(app) { - assert!(Instant::now() < deadline, "the condition never held"); - frame(app, ctx); - std::thread::sleep(std::time::Duration::from_millis(1)); - } + pump::until(app, ctx, frame, condition); +} + +#[test] +fn a_slow_frame_is_not_a_hang() { + // Regression (SLOW_FRAME): the wait's deadline counted the frames + // themselves. On a loaded runner one debug frame outlasted it, and a + // condition two frames away "never held" though nothing was stuck. + let ctx = Context::default(); + let (mut app, mock) = restore_app(&ctx); + let mut held = HeldCommands::new(&mock); + // The panel's mount job cannot land before the first frame polls it. + held.hold("steam_has_api_key"); + app.toggle_settings_panel(); + let limit = std::time::Duration::from_millis(50); + pump::within( + &mut app, + &ctx, + limit, + |app, ctx| { + frame(app, ctx); + held.release("steam_has_api_key"); + // The frame outlasts the limit, and asks for the next one itself: + // however late the job lands, no wait for it counts as idle. + std::thread::sleep(limit * 3); + ctx.request_repaint(); + }, + |a| a.settings_panel.as_ref().is_some_and(|p| p.hydrated), + ); } fn note(app: &AppModel) -> String { @@ -156,6 +183,71 @@ fn a_restore_waits_for_a_running_save_and_holds_new_writes() { assert!(app.backup.card.notice.contains("pre-restore-1")); } +/// Well inside the next deadline the app asks a frame for on its own (a +/// toast's expiry, seconds away), so a wait that needs a frame nobody asked +/// for does not hold within it. +const NO_TIMER: std::time::Duration = std::time::Duration::from_millis(500); + +/// Answers the note write in flight in place of the mock, whose held call is +/// then released: the answer is in before the next frame and no wake came +/// with it, as when the job's wake brought a frame drawn before this one. +fn answer_note_write(app: &mut AppModel, held: &mut HeldCommands) { + let (_, pending) = app + .saves + .iter_mut() + .find(|(store, _)| *store == "client.account-card-notes") + .expect("no note write in flight"); + let (answer, answered) = std::sync::mpsc::channel(); + answer.send(Ok(None)).unwrap(); + // The held call's own Pending is dropped before its release: its + // answer then has no one to go to, and its job wakes nothing. + *pending = Pending::from_receiver(answered); + held.release(SAVE); +} + +#[test] +fn a_write_ending_under_the_boundary_wakes_the_restore() { + // Regression (DRAIN_WAKE): the frame that reports a write runs the + // boundary's drain before it, and asked for no frame after: the restore + // waited for an unrelated deadline or the next mouse move. + let ctx = Context::default(); + let (mut app, mock) = restore_app(&ctx); + let mut held = HeldCommands::new(&mock); + frame(&mut app, &ctx); + held.hold(SAVE); + set_note(&mut app, "typed before"); + pump_until(&mut app, &ctx, |_| mock.waiting(SAVE) == 1); + app.start_backup_restore("C:/b.json".into(), String::new()); + held.hold("backup_restore"); + answer_note_write(&mut app, &mut held); + pump::within(&mut app, &ctx, NO_TIMER, frame, |_| { + mock.waiting("backup_restore") == 1 + }); + held.release("backup_restore"); + pump_until(&mut app, &ctx, |a| !a.backup.holds_writes()); +} + +#[test] +fn a_note_typed_while_its_store_writes_is_written_when_that_write_ends() { + // Regression (DRAIN_WAKE): a write due while its store still wrote was + // left out of the timed repaint, and the frame that reported the write + // asked for none: it waited for an unrelated deadline or the next input. + let ctx = Context::default(); + let (mut app, mock) = restore_app(&ctx); + let mut held = HeldCommands::new(&mock); + frame(&mut app, &ctx); + held.hold(SAVE); + set_note(&mut app, "first"); + pump_until(&mut app, &ctx, |_| mock.waiting(SAVE) == 1); + set_note(&mut app, "second"); + answer_note_write(&mut app, &mut held); + pump::within(&mut app, &ctx, NO_TIMER, frame, |_| mock.seen(SAVE) == 2); + pump_until(&mut app, &ctx, |a| { + !a.booted().unwrap().stores.storage().has_unsaved() + }); + assert_eq!(note(&app), "second"); +} + #[test] fn restored_settings_keep_the_restored_platform_they_enable() { let ctx = Context::default(); @@ -353,11 +445,7 @@ fn a_picker_that_fails_says_why() { app.import_backup(); } pump_until(&mut app, &ctx, |_| mock.seen(command) == 1); - let deadline = Instant::now() + std::time::Duration::from_secs(3); - while !app.backup.card.error && Instant::now() < deadline { - frame(&mut app, &ctx); - std::thread::sleep(std::time::Duration::from_millis(1)); - } + pump_until(&mut app, &ctx, |a| a.backup.card.error); assert!( app.backup.card.error && app.backup.card.notice.contains(odd), "PICKER_ERROR: {command} said {:?}", @@ -770,12 +858,12 @@ fn a_restore_whose_theme_cannot_be_read_keeps_it_selected_until_it_loads() { assert!(mock.fail("list_custom_themes", None)); focus(&mut app, &ctx, false); focus(&mut app, &ctx, true); - let deadline = Instant::now() + std::time::Duration::from_secs(3); - while app.booted().unwrap().registry.document("mine").is_none() { - assert!(Instant::now() < deadline, "the theme never loaded"); - focus(&mut app, &ctx, true); - std::thread::sleep(std::time::Duration::from_millis(1)); - } + pump::until( + &mut app, + &ctx, + |app, ctx| focus(app, ctx, true), + |a| a.booted().unwrap().registry.document("mine").is_some(), + ); let b = app.booted().unwrap(); assert_eq!(b.stores.settings().theme_id, "mine"); assert_ne!(b.theme.vars.bg_card, before, "the theme does not draw"); @@ -807,15 +895,7 @@ fn theme_restore_app( fn refocus_until(app: &mut AppModel, ctx: &Context, loaded: impl Fn(&AppModel) -> bool) { focus(app, ctx, false); focus(app, ctx, true); - let deadline = Instant::now() + std::time::Duration::from_secs(3); - while !loaded(app) { - assert!( - Instant::now() < deadline, - "the themes were not read again on the next focus" - ); - focus(app, ctx, true); - std::thread::sleep(std::time::Duration::from_millis(1)); - } + pump::until(app, ctx, |app, ctx| focus(app, ctx, true), loaded); } #[test] @@ -1260,11 +1340,11 @@ fn a_panel_edit_made_during_the_restore_never_lands_over_it() { mock.release("backup_restore"); pump_until(&mut app, &ctx, |a| !a.backup.holds_writes()); assert!(!app.backup.card.error, "{}", app.backup.card.notice); - // Past the panel's save debounce. - let until = Instant::now() + std::time::Duration::from_millis(400); - while Instant::now() < until { + // Until the panel has no save left to run: one still queued runs at + // its deadline, which the app asks a frame for. + pump_until(&mut app, &ctx, |a| a.settings_panel_deadline().is_none()); + for _ in 0..3 { frame(&mut app, &ctx); - std::thread::sleep(std::time::Duration::from_millis(5)); } let panel = app.settings_panel.as_ref().unwrap().draft.language; let stored = app.booted().unwrap().stores.settings().language; diff --git a/crates/accshift-egui/src/app/tests/held.rs b/crates/accshift-egui/src/app/tests/held.rs new file mode 100644 index 00000000..e016259a --- /dev/null +++ b/crates/accshift-egui/src/app/tests/held.rs @@ -0,0 +1,41 @@ +//! A guard for commands a test holds at the mock. + +use std::sync::Arc; + +use accshift_app::mock::MockBackend; + +/// Commands held at the mock for one test, released when it drops. A failed +/// assertion then unwinds through the release: otherwise a worker stays parked +/// at the hold and `Jobs::drop`, joining it, hangs the suite. +pub(super) struct HeldCommands { + mock: Arc, + commands: Vec<&'static str>, +} + +impl HeldCommands { + /// Declare it after the app so it drops first. + pub(super) fn new(mock: &Arc) -> Self { + Self { + mock: mock.clone(), + commands: Vec::new(), + } + } + + pub(super) fn hold(&mut self, command: &'static str) { + self.commands.push(command); + assert!(self.mock.hold(command), "{command} could not be held"); + } + + pub(super) fn release(&mut self, command: &str) { + self.commands.retain(|held| *held != command); + self.mock.release(command); + } +} + +impl Drop for HeldCommands { + fn drop(&mut self) { + for command in self.commands.drain(..) { + self.mock.release(command); + } + } +} diff --git a/crates/accshift-egui/src/app/tests/native_regressions.rs b/crates/accshift-egui/src/app/tests/native_regressions.rs index b3af6edf..e0348105 100644 --- a/crates/accshift-egui/src/app/tests/native_regressions.rs +++ b/crates/accshift-egui/src/app/tests/native_regressions.rs @@ -1,3 +1,5 @@ +use super::held::HeldCommands; +use super::pump; use super::*; use egui::{pos2, vec2, Id, RawInput, Rect, Sense, ViewportId}; use serde_json::json; @@ -110,26 +112,16 @@ fn frame(app: &mut AppModel, ctx: &Context, focused: bool, minimized: bool) { output.textures_delta.clear(); } +/// Focused frames until `condition` holds: [`pump::until`]. +#[track_caller] fn pump_until(app: &mut AppModel, ctx: &Context, condition: impl Fn(&AppModel) -> bool) { - let deadline = Instant::now() + std::time::Duration::from_secs(10); - while !condition(app) { - assert!( - Instant::now() < deadline, - "condition did not become true within 10 s" - ); - frame(app, ctx, true, false); - std::thread::sleep(std::time::Duration::from_millis(1)); - } + pump::until(app, ctx, |app, ctx| frame(app, ctx, true, false), condition); } /// Frames until no external refresh runs, accounts it reloads included. +#[track_caller] fn wait_refresh_over(app: &mut AppModel, ctx: &Context) { - let deadline = Instant::now() + std::time::Duration::from_secs(10); - while app.external_refresh.running() { - assert!(Instant::now() < deadline, "the refresh never ended"); - frame(app, ctx, true, false); - std::thread::sleep(std::time::Duration::from_millis(1)); - } + pump_until(app, ctx, |a| !a.external_refresh.running()); } #[test] @@ -154,42 +146,6 @@ fn native_external_storage_on_focus_refreshes_stores_and_accounts() { assert_eq!(b.accounts.loading.loader.current_account(), "external"); } -/// Commands held at the mock for one test, released when it drops. A failed -/// assertion then unwinds through the release: otherwise a worker stays parked -/// at the hold and `Jobs::drop`, joining it, hangs the suite. -struct HeldCommands { - mock: Arc, - commands: Vec<&'static str>, -} - -impl HeldCommands { - /// Declare it after the app so it drops first. - fn new(mock: &Arc) -> Self { - Self { - mock: mock.clone(), - commands: Vec::new(), - } - } - - fn hold(&mut self, command: &'static str) { - self.commands.push(command); - assert!(self.mock.hold(command), "{command} could not be held"); - } - - fn release(&mut self, command: &str) { - self.commands.retain(|held| *held != command); - self.mock.release(command); - } -} - -impl Drop for HeldCommands { - fn drop(&mut self) { - for command in self.commands.drain(..) { - self.mock.release(command); - } - } -} - /// Waits until a call of `command` sits at its hold in the mock. fn wait_held(mock: &MockBackend, command: &str) { let deadline = Instant::now() + std::time::Duration::from_secs(10); diff --git a/crates/accshift-egui/src/app/tests/pump.rs b/crates/accshift-egui/src/app/tests/pump.rs new file mode 100644 index 00000000..f5305454 --- /dev/null +++ b/crates/accshift-egui/src/app/tests/pump.rs @@ -0,0 +1,121 @@ +//! Frames on the mock backend until a condition holds, each one drawn when +//! the app asks for it, as the window's event loop would. +//! +//! Only the idle wait between frames is bounded, never a frame: a debug +//! frame on a loaded runner can take seconds (the first ones rasterize +//! their glyphs), and a deadline that counted the frames failed waits that +//! were only slow, two frames away from holding. + +use std::sync::{Arc, Condvar, Mutex}; +use std::time::{Duration, Instant}; + +use egui::Context; + +use super::AppModel; + +/// How long the app may sit idle, the condition false and no frame asked +/// for, before the wait counts as a hang. +const IDLE_LIMIT: Duration = Duration::from_secs(3); +/// A backstop for an app that asks for a frame after every frame. +const MAX_FRAMES: u32 = 2_000; +/// How often an idle wait reads the condition again, for a state no frame +/// reports (a mocked call reaching its hold). +const IDLE_POLL: Duration = Duration::from_millis(1); + +/// The next frame the app asked for since the last one began, as the +/// context's repaint observer sees it: a job whose result landed asks for +/// one through the pool's wake, a debounce for one at its deadline. +#[derive(Default)] +struct Wakes { + due: Mutex>, + asked: Condvar, +} + +impl Wakes { + /// Watches every repaint request `ctx` gets from now on. + fn observe(ctx: &Context) -> Arc { + let wakes = Arc::new(Self::default()); + let seen = Arc::clone(&wakes); + ctx.set_repaint_observer(move |info| { + let Some(at) = Instant::now().checked_add(info.delay) else { + return; + }; + let mut due = seen.due.lock().unwrap_or_else(|p| p.into_inner()); + if due.is_none_or(|due| at < due) { + *due = Some(at); + seen.asked.notify_all(); + } + }); + wakes + } + + fn clear(&self) { + *self.due.lock().unwrap_or_else(|p| p.into_inner()) = None; + } + + /// Waits at most `limit` for a frame the app asked for to come due; + /// true when one did. + fn wait_due(&self, limit: Duration) -> bool { + let due = self.due.lock().unwrap_or_else(|p| p.into_inner()); + let now = Instant::now(); + let wait = match *due { + Some(at) if at <= now => return true, + Some(at) => (at - now).min(limit), + None => limit, + }; + let (due, _) = self + .asked + .wait_timeout(due, wait) + .unwrap_or_else(|p| p.into_inner()); + due.is_some_and(|at| at <= Instant::now()) + } +} + +/// Draws frames with `draw` until `condition` holds. +#[track_caller] +pub(super) fn until( + app: &mut AppModel, + ctx: &Context, + draw: impl FnMut(&mut AppModel, &Context), + condition: impl Fn(&AppModel) -> bool, +) { + within(app, ctx, IDLE_LIMIT, draw, condition); +} + +/// [`until`], idle for at most `idle_limit` in all. +#[track_caller] +pub(super) fn within( + app: &mut AppModel, + ctx: &Context, + idle_limit: Duration, + mut draw: impl FnMut(&mut AppModel, &Context), + condition: impl Fn(&AppModel) -> bool, +) { + let wakes = Wakes::observe(ctx); + let mut idle = Duration::ZERO; + let mut frames = 0; + while !condition(app) { + assert!( + frames < MAX_FRAMES, + "the condition never held: {frames} frames drawn" + ); + wakes.clear(); + draw(app, ctx); + frames += 1; + loop { + if condition(app) { + return; + } + assert!( + idle < idle_limit, + "the condition never held: the app sat idle {idle:?} with no frame to draw" + ); + let waited = Instant::now(); + let due = wakes.wait_due(IDLE_POLL); + idle += waited.elapsed(); + if due { + break; + } + } + } +} diff --git a/crates/accshift-egui/src/lib.rs b/crates/accshift-egui/src/lib.rs index 6a42a3e7..1a2dbe75 100644 --- a/crates/accshift-egui/src/lib.rs +++ b/crates/accshift-egui/src/lib.rs @@ -647,5 +647,76 @@ mod tests { drop(shell); let _ = std::fs::remove_dir_all(&dir.0); } + + /// The runner's path for a Unix termination signal, end to end: the + /// installed handler wakes the loop (here a channel stands for the + /// event loop proxy), which runs [`Shell::close`]. A store write still + /// pending lands on disk. + #[cfg(unix)] + fn a_signal_flushes_a_pending_write(sig: libc::c_int, tag: &str) { + use accshift_app::backend::Backend; + use accshift_app::storage::CLIENT_STORE_SETTINGS; + use std::time::Duration; + + let _lock = crate::window::signal::test_lock(sig); + let dir = scratch(tag); + let backend = Arc::new(RealBackend::with_context(dir.clone())); + let ctx = egui::Context::default(); + let mut app = crate::AppModel::real(&ctx, backend.clone(), None, None); + app.wait_boot(&ctx).expect("boot on scratch dir"); + backend.boot_state().mark_completed(); + { + let booted = app.booted_mut().expect("booted"); + let mut next = booted.stores.settings().clone(); + next.close_to_tray = true; + booted.stores.save_settings(&next); + } + let mut shell = Shell::new(Screen::App(Box::new(app)), None) + .with_window(Host::new(backend.clone(), 0)); + + let (quit_tx, quit_rx) = std::sync::mpsc::channel(); + let guard = crate::window::signal::install(move || { + let _ = quit_tx.send(()); + }) + .expect("signal handler installed"); + assert_eq!(unsafe { libc::raise(sig) }, 0); + quit_rx + .recv_timeout(Duration::from_secs(5)) + .expect("the handler woke the loop"); + // A close request now quits instead of hiding to the tray. + assert!(crate::window::session_ending()); + let mut hidden = 0; + shell.close(Some(geometry(1040.0)), || hidden += 1); + drop(guard); + + assert_eq!(hidden, 1); + let snapshot = backend + .load_client_storage_snapshot() + .expect("snapshot on disk"); + assert_eq!( + snapshot + .stores + .get(CLIENT_STORE_SETTINGS) + .and_then(|v| v.get("closeToTray")) + .and_then(|v| v.as_bool()), + Some(true), + "the write pending at the signal must be on disk" + ); + drop(shell); + } + + #[cfg(unix)] + #[test] + fn sigterm_flushes_a_pending_write_to_disk() { + a_signal_flushes_a_pending_write(libc::SIGTERM, "sigterm-flush"); + } + + // Regression: `SIGHUP` (a closed terminal, a session hanging up) kept + // its default action and ended the process with the write unsaved. + #[cfg(unix)] + #[test] + fn sighup_flushes_a_pending_write_to_disk() { + a_signal_flushes_a_pending_write(libc::SIGHUP, "sighup-flush"); + } } } diff --git a/crates/accshift-egui/src/window/mod.rs b/crates/accshift-egui/src/window/mod.rs index ab61a37a..e65552db 100644 --- a/crates/accshift-egui/src/window/mod.rs +++ b/crates/accshift-egui/src/window/mod.rs @@ -145,7 +145,8 @@ pub fn restore_position(window: &egui_winit::winit::window::Window, saved: &conf } /// The OS is ending the session (Windows `WM_ENDSESSION`, or Unix -/// `SIGTERM`/`SIGINT`): a close request quits instead of hiding to the tray. +/// `SIGTERM`/`SIGINT`/`SIGHUP`): a close request quits instead of hiding to +/// the tray. pub fn session_ending() -> bool { #[cfg(windows)] return frame::session_ending(); diff --git a/crates/accshift-egui/src/window/signal.rs b/crates/accshift-egui/src/window/signal.rs index 54728380..32e62b5e 100644 --- a/crates/accshift-egui/src/window/signal.rs +++ b/crates/accshift-egui/src/window/signal.rs @@ -1,4 +1,5 @@ -//! Unix `SIGTERM` and `SIGINT` handling: turns a termination signal into a +//! Unix `SIGTERM`, `SIGINT` and `SIGHUP` handling: turns a termination +//! signal (a session logout, `kill`, Ctrl+C, a closed terminal) into a //! wake on the winit event loop so the app runs its normal close sequence //! (window geometry, pending store writes, telemetry session end, single //! instance release) before exiting. @@ -83,10 +84,25 @@ mod imp { } } + /// The signals that run the close sequence. `SIGHUP` too: its default + /// action ends the process on the spot, so a closed terminal or a session + /// that hangs up would lose the pending writes. An ignored `SIGHUP` + /// stays ignored so `nohup` keeps working. + const SIGNALS: [libc::c_int; 3] = [libc::SIGTERM, libc::SIGINT, libc::SIGHUP]; + + /// Puts back the dispositions `install` replaced, last first. + fn restore(previous: &[(libc::c_int, libc::sigaction)]) { + for (sig, prev) in previous.iter().rev() { + // SAFETY: `prev` is the disposition `sigaction` returned for `sig`. + unsafe { + let _ = libc::sigaction(*sig, prev, std::ptr::null_mut()); + } + } + } + pub struct Guard { write_fd: libc::c_int, - prev_term: libc::sigaction, - prev_int: libc::sigaction, + previous: Vec<(libc::c_int, libc::sigaction)>, thread: Option>, } @@ -94,10 +110,7 @@ mod imp { fn drop(&mut self) { // Restore previous dispositions before closing the pipe so no // later signal invokes `handle_signal` against a closed fd. - unsafe { - let _ = libc::sigaction(libc::SIGTERM, &self.prev_term, std::ptr::null_mut()); - let _ = libc::sigaction(libc::SIGINT, &self.prev_int, std::ptr::null_mut()); - } + restore(&self.previous); SIGNAL_WRITE_FD.retire(); // Closing the write end wakes the watcher thread with EOF. unsafe { @@ -149,28 +162,27 @@ mod imp { libc::sigemptyset(&mut action.sa_mask); } - let mut prev_term: libc::sigaction = unsafe { std::mem::zeroed() }; - let mut prev_int: libc::sigaction = unsafe { std::mem::zeroed() }; - let term_ok = unsafe { libc::sigaction(libc::SIGTERM, &action, &mut prev_term) } == 0; - if !term_ok { - SIGNAL_WRITE_FD.retire(); - unsafe { - let _ = libc::close(read_fd); - let _ = libc::close(write_fd); - } - return None; - } - let int_ok = unsafe { libc::sigaction(libc::SIGINT, &action, &mut prev_int) } == 0; - if !int_ok { - unsafe { - let _ = libc::sigaction(libc::SIGTERM, &prev_term, std::ptr::null_mut()); + let mut previous = Vec::with_capacity(SIGNALS.len()); + for sig in SIGNALS { + let mut prev: libc::sigaction = unsafe { std::mem::zeroed() }; + // SAFETY: a null action only reads the current disposition. + let read = unsafe { libc::sigaction(sig, std::ptr::null(), &mut prev) } == 0; + // `nohup` leaves SIGHUP ignored and expects it to stay so. SIGINT + // and SIGTERM always close cleanly, even when a shell without job + // control started the app in the background with them ignored. + if sig == libc::SIGHUP && read && prev.sa_sigaction == libc::SIG_IGN { + continue; } - SIGNAL_WRITE_FD.retire(); - unsafe { - let _ = libc::close(read_fd); - let _ = libc::close(write_fd); + if unsafe { libc::sigaction(sig, &action, &mut prev) } != 0 { + restore(&previous); + SIGNAL_WRITE_FD.retire(); + unsafe { + let _ = libc::close(read_fd); + let _ = libc::close(write_fd); + } + return None; } - return None; + previous.push((sig, prev)); } let thread = match std::thread::Builder::new() @@ -202,10 +214,7 @@ mod imp { }) { Ok(thread) => thread, Err(_) => { - unsafe { - let _ = libc::sigaction(libc::SIGTERM, &prev_term, std::ptr::null_mut()); - let _ = libc::sigaction(libc::SIGINT, &prev_int, std::ptr::null_mut()); - } + restore(&previous); SIGNAL_WRITE_FD.retire(); unsafe { let _ = libc::close(read_fd); @@ -217,8 +226,7 @@ mod imp { Some(Guard { write_fd, - prev_term, - prev_int, + previous, thread: Some(thread), }) } @@ -239,6 +247,20 @@ mod imp { pub use imp::{install, received, Guard}; +/// Serializes the tests that install the handler: the dispositions and the +/// pipe slot are process-wide. Also puts `sig` back to its default action, so +/// a test run that inherited it ignored still sees the handler take it. +#[cfg(all(test, unix))] +pub(crate) fn test_lock(sig: libc::c_int) -> std::sync::MutexGuard<'static, ()> { + static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + let guard = LOCK.lock().unwrap_or_else(|e| e.into_inner()); + // SAFETY: `SIG_DFL` is a valid disposition for any catchable signal. + unsafe { + libc::signal(sig, libc::SIG_DFL); + } + guard +} + #[cfg(test)] mod tests { use super::*; @@ -295,16 +317,11 @@ mod tests { #[cfg(unix)] mod unix_tests { use super::*; - use std::sync::{mpsc, Mutex, OnceLock}; + use std::sync::mpsc; use std::time::Duration; - fn signal_test_lock() -> &'static Mutex<()> { - static LOCK: OnceLock> = OnceLock::new(); - LOCK.get_or_init(|| Mutex::new(())) - } - fn assert_signal_triggers_quit(sig: libc::c_int) { - let _lock = signal_test_lock().lock().unwrap_or_else(|e| e.into_inner()); + let _lock = test_lock(sig); let (tx, rx) = mpsc::channel(); let guard = install(move || { let _ = tx.send(()); @@ -329,9 +346,61 @@ mod tests { assert_signal_triggers_quit(libc::SIGINT); } + // Regression: `SIGHUP` kept its default action, which ends the + // process before the close sequence flushes the pending writes. + #[test] + fn sighup_triggers_orderly_quit_callback() { + assert_signal_triggers_quit(libc::SIGHUP); + } + + #[test] + fn a_signal_the_parent_left_ignored_stays_ignored() { + let _lock = test_lock(libc::SIGHUP); + unsafe { + libc::signal(libc::SIGHUP, libc::SIG_IGN); + } + let (tx, rx) = mpsc::channel(); + let guard = install(move || { + let _ = tx.send(()); + }) + .expect("signal handler installed"); + assert_eq!(unsafe { libc::raise(libc::SIGHUP) }, 0); + assert!(rx.recv_timeout(Duration::from_millis(300)).is_err()); + assert!(!received()); + drop(guard); + let mut now: libc::sigaction = unsafe { std::mem::zeroed() }; + unsafe { + libc::sigaction(libc::SIGHUP, std::ptr::null(), &mut now); + libc::signal(libc::SIGHUP, libc::SIG_DFL); + } + assert_eq!(now.sa_sigaction, libc::SIG_IGN); + } + + // A shell without job control starts background jobs with SIGINT + // ignored: `kill -INT` must still close the app cleanly. + #[test] + fn an_ignored_sigint_still_triggers_orderly_quit() { + let _lock = test_lock(libc::SIGINT); + unsafe { + libc::signal(libc::SIGINT, libc::SIG_IGN); + } + let (tx, rx) = mpsc::channel(); + let guard = install(move || { + let _ = tx.send(()); + }) + .expect("signal handler installed"); + assert_eq!(unsafe { libc::raise(libc::SIGINT) }, 0); + rx.recv_timeout(Duration::from_secs(2)) + .expect("signal callback fired"); + drop(guard); + unsafe { + libc::signal(libc::SIGINT, libc::SIG_DFL); + } + } + #[test] fn dropping_guard_without_signal_exits_watcher_cleanly() { - let _lock = signal_test_lock().lock().unwrap_or_else(|e| e.into_inner()); + let _lock = test_lock(libc::SIGTERM); let (tx, rx) = mpsc::channel(); let guard = install(move || { let _ = tx.send(());