//! How a desktop app process ends. //! //! `exit` (what `-[NSApplication terminate:]` and returning from `main` call) //! runs C++ static destructors and `atexit` handlers while threads Hex does //! not join are still running: CoreAudio's IO threads or ggml's residency-set //! keep-alive. Those destructors tear down native globals under them; ggml's //! Metal device list aborts in `ggml_metal_rsets_free` unless every Metal //! buffer was already freed. So Hex drains its own work first, then ends with //! `_exit`, which runs none of them. Nothing Hex keeps relies on them: the //! drain flushes the event log, and settings, history, and meetings are saved //! atomically when they change. A meeting recording at quit keeps its audio //! and finishes its transcript at the next launch. //! //! The drain runs on the main thread, so a worker that never stops would hang //! quit, logout, and updates. After [`DEADLINE`] the process ends anyway; a //! meeting still recording gets [`MEETING_DEADLINE`] to finalise its audio. //! Dropping the transcription engine cancels its job and normally returns at //! once; only a wedged native run reaches either bound, and `_exit` is what //! makes leaving it running safe. //! //! Linux's service stop has the same shape with a longer bound: the host arms //! [`arm_deadline`] when stopping begins, and a drain still running after //! [`STOP_DEADLINE`] ends with the same `_exit`, logging what was pending. //! Windows' teardown arms [`arm_windows_deadline`] with the same kind of //! bound, since it runs after the loop and has no other deadline. use std::io::Write; use std::sync::Mutex; #[cfg(any(target_os = "linux", target_os = "windows"))] use std::sync::Once; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; /// How long quitting waits for the drain before ending the process anyway. const DEADLINE: Duration = Duration::from_secs(5); /// How long an in-flight meeting recording gets from the quit's start to /// finalise its audio and write `final.pending`. Its capture threads can take /// longer to stop than the rest of the drain, and ending early loses the /// recording. const MEETING_DEADLINE: Duration = Duration::from_secs(30); /// How long a Linux stop may drain before the process ends anyway. Shorter /// than the unit's `TimeoutStopSec=30`, with room for a CPU transcription to /// finish. #[cfg(target_os = "linux")] const STOP_DEADLINE: Duration = Duration::from_secs(20); /// How long a Windows exit may drain before the process ends anyway: the /// same bound as Linux's stop, with room for a meeting recording to finalise. #[cfg(target_os = "windows")] const WINDOWS_DEADLINE: Duration = Duration::from_secs(20); static QUITTING: AtomicBool = AtomicBool::new(false); /// Whether the process has begun quitting. Work that would outlast the /// drain, such as loading a model, checks this and stops instead. pub(crate) fn quitting() -> bool { QUITTING.load(Ordering::Acquire) } /// Marks the process as quitting without ending it: the Linux and Windows /// apps, which end by returning from `main` once their workers stop. #[cfg(not(target_os = "macos"))] pub(crate) fn begin_quitting() { QUITTING.store(true, Ordering::Release); } #[cfg(test)] pub(crate) fn begin_quitting_for_test() { QUITTING.store(true, Ordering::Release); } /// Work that must finish before the process ends, run once by whichever /// quit path gets there first. pub(crate) struct Drain(Mutex>>); impl Drain { pub(crate) const fn new() -> Self { Self(Mutex::new(None)) } pub(crate) fn set(&self, work: impl FnOnce() + Send + 'static) { *self.lock() = Some(Box::new(work)); } /// Runs the drain if nothing has yet; reports whether this call ran it. pub(crate) fn run(&self) -> bool { let work = self.lock().take(); let ran = work.is_some(); if let Some(work) = work { work(); } ran } fn lock(&self) -> std::sync::MutexGuard<'_, Option>> { self.0.lock().unwrap_or_else(|error| error.into_inner()) } } /// Drains, then ends the process without running static destructors. pub(crate) fn finish(drain: &Drain) -> ! { finish_within(drain, DEADLINE, 0) } /// `finish`, ending with `code`: a launch whose window never started exits 1. pub(crate) fn finish_with(drain: &Drain, code: i32) -> ! { finish_within(drain, DEADLINE, code) } fn finish_within(drain: &Drain, deadline: Duration, code: i32) -> ! { QUITTING.store(true, Ordering::Release); let started = std::time::Instant::now(); let _ = std::thread::Builder::new() .name("hex-exit-deadline".into()) .spawn(move || { std::thread::sleep(deadline); // A recording in flight may have started just before quitting was // marked (or be finalising its audio now). It gets the meeting // bound from the quit's start, so the recorder can write its WAV // headers and `final.pending` before `_exit`. let bound = started + MEETING_DEADLINE; let mut waiting = false; while crate::meeting::recording() && std::time::Instant::now() < bound { if !waiting { waiting = true; tracing::info!("waiting for a meeting recording to finish before stopping"); } std::thread::sleep(Duration::from_millis(100)); } if waiting { // The meeting finished, but the drain still has joins, audio // restore, and the event-log flush left. Give it the ordinary // deadline again, capped by the meeting bound from the quit. let grace = bound .saturating_duration_since(std::time::Instant::now()) .min(DEADLINE); if !grace.is_zero() { std::thread::sleep(grace); } } tracing::warn!("Hex stopped before its workers finished"); end_process(code); }); drain.run(); tracing::info!("Hex stopped"); end_process(code) } fn end_process(code: i32) -> ! { let _ = std::io::stdout().flush(); let _ = std::io::stderr().flush(); // SAFETY: `_exit` ends the process immediately; nothing runs after it. unsafe { libc::_exit(code) } } /// What a stopping Linux process is still waiting on, named in the deadline's /// log so a stuck stop shows its last stage. #[cfg(target_os = "linux")] #[derive(Clone, Copy)] pub(crate) enum PendingWork { /// The host still drains the listener, an uncommitted shortcut edit, or /// model preparation; the window and meetings may also be stopping. Draining = 1, /// The listener drained; the socket server, window, meetings, local API, /// or tray are still stopping. Teardown = 2, } #[cfg(target_os = "linux")] static PENDING_WORK: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); /// Records what a stopping Linux process is doing, for the deadline's log. #[cfg(target_os = "linux")] pub(crate) fn set_pending_work(work: PendingWork) { PENDING_WORK.store(work as u8, Ordering::Release); } #[cfg(target_os = "linux")] fn pending_work() -> &'static str { match PENDING_WORK.load(Ordering::Acquire) { 1 => { "the listener, a shortcut edit, or model preparation (the window and meetings may also be stopping)" } 2 => { "the listener drained; the socket server, window, meetings, local API, or tray are still stopping" } _ => "the host had not noticed the stop yet", } } /// Ends a stopping Linux process even if its orderly shutdown wedges, naming /// what was still pending. Only the first call arms it, so every shutdown /// trigger can call it. #[cfg(target_os = "linux")] pub(crate) fn arm_deadline() { static ARMED: Once = Once::new(); ARMED.call_once(|| { if let Err(error) = run_deadline(STOP_DEADLINE, false, pending_work, || end_process(0)) { tracing::warn!(%error, "could not arm Hex's exit deadline"); } }); } /// Bounds a Windows exit's teardown on the main thread, as Linux's stop is /// bounded: a worker that never stops cannot hold the process open. Meeting /// audio still in flight extends the bound to [`MEETING_DEADLINE`]. Only the /// first call arms it. #[cfg(target_os = "windows")] pub(crate) fn arm_windows_deadline(code: i32) { static ARMED: Once = Once::new(); ARMED.call_once(|| { if let Err(error) = run_deadline( WINDOWS_DEADLINE, true, || "the runtime, meetings, local API, or tray", move || end_process(code), ) { tracing::warn!(%error, "could not arm Hex's exit deadline"); } }); } /// Starts the detached named thread that runs `exit` after `deadline`; the /// result reports whether it started. With `wait_for_meeting`, meeting audio /// still in flight extends the wait to [`MEETING_DEADLINE`], polled rather /// than read once so audio that starts during the drain is covered. #[cfg(any(target_os = "linux", target_os = "windows"))] fn run_deadline( deadline: Duration, wait_for_meeting: bool, pending: impl Fn() -> &'static str + Send + 'static, exit: impl FnOnce() + Send + 'static, ) -> std::io::Result<()> { std::thread::Builder::new() .name("hex-exit-deadline".into()) .spawn(move || { let started = std::time::Instant::now(); std::thread::sleep(deadline); if wait_for_meeting { let bound = started + MEETING_DEADLINE; let mut waiting = false; while crate::meeting::recording() && std::time::Instant::now() < bound { if !waiting { waiting = true; tracing::info!("waiting for meeting audio to finish before stopping"); } std::thread::sleep(Duration::from_millis(100)); } } tracing::warn!( pending = pending(), "Hex's shutdown did not finish before its exit deadline" ); exit(); }) .map(|_| ()) } #[cfg(test)] mod tests { use super::*; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; #[test] fn a_drain_runs_once_whichever_path_comes_first() { let drain = Drain::new(); let runs = Arc::new(AtomicUsize::new(0)); let counted = runs.clone(); drain.set(move || { counted.fetch_add(1, Ordering::SeqCst); }); assert!(drain.run()); assert!(!drain.run()); assert_eq!(runs.load(Ordering::SeqCst), 1); } const CHILD: &str = "HEX_PROCESS_EXIT_CHILD"; /// The child half of `finishing_stops_the_listener_and_skips_static_destructors`. #[test] fn finishing_child() { if std::env::var_os(CHILD).is_none() { return; } extern "C" fn static_destructor() { // What ggml's Metal teardown does with a live buffer. std::process::abort(); } /// A native session the listener frees when it stops. struct Session; impl Drop for Session { fn drop(&mut self) { print!("freed "); } } static DRAIN: Drain = Drain::new(); static STOP: AtomicBool = AtomicBool::new(false); // SAFETY: registers a plain C function with no captured state. unsafe { libc::atexit(static_destructor) }; let listener = std::thread::spawn(|| { let _session = Session; while !STOP.load(Ordering::SeqCst) { std::thread::yield_now(); } }); DRAIN.set(move || { STOP.store(true, Ordering::SeqCst); listener.join().unwrap(); print!("drained"); }); finish(&DRAIN); } /// The child half of `a_stuck_drain_still_ends_the_process`. #[test] fn stuck_child() { if std::env::var_os(CHILD).is_none() { return; } static DRAIN: Drain = Drain::new(); DRAIN.set(|| { loop { std::thread::park(); } }); finish_within(&DRAIN, Duration::from_millis(50), 0); } /// The child half of `a_failed_launch_ends_with_its_code`. #[test] fn failing_child() { if std::env::var_os(CHILD).is_none() { return; } static DRAIN: Drain = Drain::new(); finish_with(&DRAIN, 1); } fn run_child(name: &str) -> std::process::Output { std::process::Command::new(std::env::current_exe().unwrap()) .args([ "--exact", &format!("desktop::process_exit::tests::{name}"), "--nocapture", ]) .env(CHILD, "1") .output() .unwrap() } #[test] fn finishing_stops_the_listener_and_skips_static_destructors() { let output = run_child("finishing_child"); assert!( output.status.success(), "the child ran an atexit handler: {:?}", output.status ); assert!( String::from_utf8_lossy(&output.stdout).contains("freed drained"), "the listener did not stop and free its session before the process ended" ); } #[test] fn a_stuck_drain_still_ends_the_process() { assert!(run_child("stuck_child").status.success()); } #[test] fn a_failed_launch_ends_with_its_code() { let output = run_child("failing_child"); assert_eq!( output.status.code(), Some(1), "a launch whose window never started must not report success" ); } #[cfg(target_os = "linux")] #[test] fn exit_deadline_fires_only_after_its_deadline() { let (fired, received) = std::sync::mpsc::channel(); run_deadline( Duration::from_millis(100), false, || "test", move || { let _ = fired.send(()); }, ) .unwrap(); assert!( received.recv_timeout(Duration::from_millis(20)).is_err(), "the exit deadline fired before its deadline" ); received .recv_timeout(Duration::from_secs(5)) .expect("the exit deadline did not fire"); } }