diff --git a/docs/environment-variables.md b/docs/environment-variables.md index 7cc4be5c..695d218e 100644 --- a/docs/environment-variables.md +++ b/docs/environment-variables.md @@ -1,6 +1,6 @@ # AstrBot Desktop 环境变量清单 -更新时间:2026-11-14 +更新时间:2026-11-15 主要来源:桌面运行时 Rust 模块(如 `src-tauri/src/backend/config.rs`、`src-tauri/src/update_channel.rs`、`src-tauri/src/bridge/updater_messages.rs`、`src-tauri/src/runtime_paths.rs`、`src-tauri/src/launch_plan.rs`)、资源准备脚本(`scripts/prepare-resources*.mjs`)和发布工作流(`.github/workflows/build-desktop-tauri.yml`)。以下按主要解析/写入阶段分组。 @@ -31,6 +31,14 @@ | `ASTRBOT_DESKTOP_UPDATER_STABLE_ENDPOINT` | stable 通道 manifest URL 覆盖 | 未设置则读 `plugins.updater.channelEndpoints.stable`,再回退 `plugins.updater.endpoints[0]` | | `ASTRBOT_DESKTOP_UPDATER_NIGHTLY_ENDPOINT` | nightly 通道 manifest URL 覆盖 | 未设置则读 `plugins.updater.channelEndpoints.nightly` | +### 外部后端与托管后端的地址 + +`ASTRBOT_BACKEND_URL` 设置桌面端连接的地址,不会改变后端子进程实际使用的 dashboard host/port;后者由 `DASHBOARD_HOST` / `ASTRBOT_DASHBOARD_HOST`、对应端口变量及 `cmd_config.json` 决定。由桌面端托管后端时,这两组配置应指向同一个后端监听端点。 + +如果只需连接独立运行的本机或远端后端,请同时设置 `ASTRBOT_BACKEND_URL` 和 `ASTRBOT_BACKEND_AUTO_START=0`。首次连接时,地址可达就使用已有服务;地址不可达则报告错误,不自动创建替代后端。非托管后端通过后端 API 重启;重启超时后,桌面端不会自动启动一个托管进程来替代它。 + +托管进程停止后的重启及 Windows 更新准备,会检查配置地址是否仍有 TCP listener。非回环地址可能是本机局域网地址或指向本机的域名,因此不会仅因地址不是 `localhost` 就跳过检查。如果配置地址指向独立远端服务或持续监听的反向代理,TCP listener 仍存在时会保守拒绝替代启动;该检查无法判断代理后的旧进程是否已经退出。 + ## 2. 源码与资源准备(开发态运行时 / `prepare-resources` / backend build) | 变量 | 用途 | 默认值/行为 | diff --git a/src-tauri/src/app_constants.rs b/src-tauri/src/app_constants.rs index 19cc5f6a..4021df15 100644 --- a/src-tauri/src/app_constants.rs +++ b/src-tauri/src/app_constants.rs @@ -9,6 +9,13 @@ pub(crate) const DESKTOP_AUTH_REQUEST_TIMEOUT_MS: u64 = 2_500; pub(crate) const GRACEFUL_RESTART_START_TIME_TIMEOUT_MS: u64 = 1_800; pub(crate) const GRACEFUL_RESTART_POLL_INTERVAL_MS: u64 = 350; pub(crate) const GRACEFUL_STOP_TIMEOUT_MS: u64 = 10_000; +// Upper bound for confirming the previously spawned backend has really left the OS +// before a restart is allowed to spawn a replacement. The stop path can spend up to +// GRACEFUL_STOP_TIMEOUT_MS plus the force-kill follow-up, so this only covers the +// final "PID is gone" hand-off; it must stay short enough that a genuine failure is +// reported to the user instead of turning a restart into a long hang. +pub(crate) const BACKEND_EXIT_CONFIRM_TIMEOUT_MS: u64 = 3_000; +pub(crate) const BACKEND_EXIT_CONFIRM_POLL_INTERVAL_MS: u64 = 100; #[cfg(target_os = "windows")] pub(crate) const SYSTEM_SHUTDOWN_STOP_TIMEOUT_MS: u64 = 2_000; pub(crate) const DEFAULT_BACKEND_READY_POLL_INTERVAL_MS: u64 = 300; diff --git a/src-tauri/src/app_types.rs b/src-tauri/src/app_types.rs index b27a4b8c..0e80c834 100644 --- a/src-tauri/src/app_types.rs +++ b/src-tauri/src/app_types.rs @@ -4,13 +4,15 @@ use std::{ path::PathBuf, process::Child, sync::{ - atomic::{AtomicBool, Ordering}, + atomic::{AtomicBool, AtomicU32, Ordering}, Arc, Mutex, }, }; use tauri::menu::{CheckMenuItem, MenuItem}; -use crate::{backend, desktop_auth::DesktopSessionSecret, exit_state, DEFAULT_BACKEND_URL}; +use crate::{ + backend, desktop_auth::DesktopSessionSecret, exit_state, process_control, DEFAULT_BACKEND_URL, +}; #[derive(Clone)] pub(crate) struct TrayMenuState { @@ -67,7 +69,13 @@ pub(crate) struct LaunchPlan { #[derive(Debug)] pub(crate) struct BackendState { pub(crate) child: Mutex>, + /// Identity of the last process this shell spawned, captured while it was still + /// running. Kept separately from `child` because the `Child` handle is consumed or + /// dropped while the OS may still be tearing the process down. + pub(crate) last_spawned_identity: Mutex>, pub(crate) backend_url: String, + /// Keep a timed-out DNS worker reserved until it finishes, so retries stay bounded. + pub(crate) endpoint_resolver: Mutex>>, pub(crate) restart_auth_token: Mutex>, pub(crate) desktop_session_secret: DesktopSessionSecret, pub(crate) startup_loading_mode: Mutex>, @@ -75,6 +83,9 @@ pub(crate) struct BackendState { pub(crate) exit_state: Mutex, pub(crate) is_spawning: AtomicBool, pub(crate) is_restarting: AtomicBool, + /// PID the current restart flow stopped, or 0 when nothing was stopped. Set before + /// the stop so the flow can confirm that exact process left the OS before respawning. + pub(crate) restart_stop_pid: AtomicU32, } #[derive(Debug, serde::Serialize)] @@ -106,11 +117,6 @@ pub(crate) struct AtomicFlagGuard<'a> { } impl<'a> AtomicFlagGuard<'a> { - pub(crate) fn set(flag: &'a AtomicBool) -> Self { - flag.store(true, Ordering::Relaxed); - Self { flag } - } - pub(crate) fn try_set(flag: &'a AtomicBool) -> Option { flag.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) .ok()?; @@ -128,11 +134,13 @@ impl Default for BackendState { fn default() -> Self { Self { child: Mutex::new(None), + last_spawned_identity: Mutex::new(None), backend_url: backend::config::normalize_backend_url( &env::var("ASTRBOT_BACKEND_URL") .unwrap_or_else(|_| DEFAULT_BACKEND_URL.to_string()), DEFAULT_BACKEND_URL, ), + endpoint_resolver: Mutex::new(None), restart_auth_token: Mutex::new(None), desktop_session_secret: DesktopSessionSecret::generate() .expect("failed to generate secure desktop session secret"), @@ -141,6 +149,7 @@ impl Default for BackendState { exit_state: Mutex::new(exit_state::ExitStateMachine::default()), is_spawning: AtomicBool::new(false), is_restarting: AtomicBool::new(false), + restart_stop_pid: AtomicU32::new(0), } } } @@ -151,16 +160,6 @@ mod tests { use super::AtomicFlagGuard; - #[test] - fn atomic_flag_guard_set_resets_flag_on_drop() { - let flag = AtomicBool::new(false); - { - let _guard = AtomicFlagGuard::set(&flag); - assert!(flag.load(Ordering::Relaxed)); - } - assert!(!flag.load(Ordering::Relaxed)); - } - #[test] fn atomic_flag_guard_try_set_rejects_double_set_until_drop() { let flag = AtomicBool::new(false); diff --git a/src-tauri/src/backend/http.rs b/src-tauri/src/backend/http.rs index 4b77f4db..e2b85a5a 100644 --- a/src-tauri/src/backend/http.rs +++ b/src-tauri/src/backend/http.rs @@ -1,10 +1,10 @@ use std::{ io::{ErrorKind, Read, Write}, - net::{TcpStream, ToSocketAddrs}, + net::{SocketAddr, TcpStream, ToSocketAddrs}, time::{Duration, Instant}, }; -use url::Url; +use url::{Host, Url}; use crate::{ backend::http_response, @@ -15,6 +15,107 @@ use crate::{ const MAX_BACKEND_HTTP_HEADER_BYTES: usize = 64 * 1024; const MAX_BACKEND_HTTP_BODY_BYTES: usize = 32 * 1024 * 1024; +/// Require refused connections on every resolved address before permitting a respawn. +fn confirm_backend_endpoint_available_with_resolver( + backend_url: &str, + resolver_worker: &std::sync::Mutex>>, + timeout: Duration, + resolve: F, +) -> Result<(), String> +where + F: FnOnce(String, u16) -> std::io::Result> + Send + 'static, +{ + let parsed = Url::parse(backend_url); + // Diagnostics need only the network origin. Userinfo, paths, queries and fragments + // can contain credentials, and invalid input must never be echoed as a fallback. + let display_url = match &parsed { + Ok(url) if matches!(url.scheme(), "http" | "https") => url.origin().ascii_serialization(), + _ => "".to_string(), + }; + let inconclusive = |reason: &str| { + format!( + "Cannot confirm backend endpoint {display_url} is available: {reason}. Refusing to start another backend." + ) + }; + let deadline = Instant::now() + .checked_add(timeout) + .ok_or_else(|| inconclusive("invalid probe timeout"))?; + let parsed = parsed.map_err(|error| inconclusive(&format!("invalid URL: {error}")))?; + if !matches!(parsed.scheme(), "http" | "https") { + return Err(inconclusive("unsupported backend URL scheme")); + } + let port = parsed + .port_or_known_default() + .ok_or_else(|| inconclusive("URL has no port"))?; + let addrs = match parsed.host() { + Some(Host::Ipv4(ip)) => vec![SocketAddr::from((ip, port))], + Some(Host::Ipv6(ip)) => vec![SocketAddr::from((ip, port))], + Some(Host::Domain(host)) => { + let host = host.to_string(); + let mut worker = resolver_worker + .lock() + .map_err(|_| inconclusive("name resolution worker lock poisoned"))?; + if worker.as_ref().is_some_and(|worker| !worker.is_finished()) { + return Err(inconclusive( + "previous name resolution is still running; retry after it finishes", + )); + } + if let Some(finished) = worker.take() { + // A panicked resolver has finished too; joining releases its resources + // and leaves a fresh attempt possible without poisoning this mutex. + let _ = finished.join(); + } + let (sender, receiver) = std::sync::mpsc::sync_channel(1); + // The OS resolver cannot be cancelled. Retain its handle after a timeout + // so another probe cannot accumulate another outstanding resolver. + *worker = Some( + std::thread::Builder::new() + .name("backend-endpoint-resolver".to_string()) + .spawn(move || { + let _ = sender.send(resolve(host, port)); + }) + .map_err(|error| { + inconclusive(&format!("could not start name resolution: {error}")) + })?, + ); + drop(worker); + let remaining = deadline + .checked_duration_since(Instant::now()) + .filter(|remaining| !remaining.is_zero()) + .ok_or_else(|| inconclusive("probe timed out during name resolution"))?; + receiver + .recv_timeout(remaining) + .map_err(|error| inconclusive(&format!("name resolution did not finish: {error}")))? + .map_err(|error| inconclusive(&format!("name resolution failed: {error}")))? + } + None => return Err(inconclusive("URL has no host")), + }; + if addrs.is_empty() { + return Err(inconclusive("name resolution returned no addresses")); + } + + for address in addrs { + let remaining = deadline + .checked_duration_since(Instant::now()) + .filter(|remaining| !remaining.is_zero()) + .ok_or_else(|| inconclusive("probe timed out"))?; + match TcpStream::connect_timeout(&address, remaining) { + Ok(_) => { + return Err(format!( + "Backend endpoint {display_url} is already answering. Stop the existing backend before starting another." + )); + } + Err(error) if error.kind() == ErrorKind::ConnectionRefused => {} + Err(error) => { + return Err(inconclusive(&format!( + "connection to {address} failed: {error}" + ))); + } + } + } + Ok(()) +} + trait ResponseReader: Read { fn set_response_read_timeout(&self, timeout: Duration) -> std::io::Result<()>; } @@ -33,6 +134,19 @@ struct BackendRequestOptions<'a> { } impl BackendState { + pub(crate) fn confirm_backend_endpoint_available(&self, timeout_ms: u64) -> Result<(), String> { + confirm_backend_endpoint_available_with_resolver( + &self.backend_url, + &self.endpoint_resolver, + Duration::from_millis(timeout_ms.max(1)), + |host, port| { + (host.as_str(), port) + .to_socket_addrs() + .map(Iterator::collect) + }, + ) + } + pub(crate) fn ping_backend(&self, timeout_ms: u64) -> bool { let parsed = match Url::parse(&self.backend_url) { Ok(url) => url, @@ -374,6 +488,312 @@ fn read_http_response_bytes( mod tests { use super::*; + #[test] + fn restart_endpoint_probe_retries_do_not_accumulate_blocked_resolvers() { + let resolver_worker = std::sync::Mutex::new(None); + let starts = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let mut releases = Vec::new(); + let mut completions = Vec::new(); + for _ in 0..4 { + let (release, blocked) = std::sync::mpsc::channel(); + let (started, started_receiver) = std::sync::mpsc::channel(); + let (finished, completed) = std::sync::mpsc::channel(); + let starts_for_worker = std::sync::Arc::clone(&starts); + let result = confirm_backend_endpoint_available_with_resolver( + "http://backend.invalid:6185/", + &resolver_worker, + Duration::from_millis(30), + move |_, _| { + starts_for_worker.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let _ = started.send(()); + let _ = blocked.recv_timeout(Duration::from_secs(2)); + let _ = finished.send(()); + Err(std::io::Error::from(ErrorKind::TimedOut)) + }, + ); + assert!(result.is_err()); + let _ = started_receiver.recv_timeout(Duration::from_secs(1)); + releases.push(release); + completions.push(completed); + } + for release in releases { + let _ = release.send(()); + } + for completed in completions { + let _ = completed.recv_timeout(Duration::from_secs(1)); + } + assert_eq!( + starts.load(std::sync::atomic::Ordering::SeqCst), + 1, + "a timed-out resolver must retain its reservation until it finishes" + ); + } + + #[test] + fn restart_endpoint_probe_can_retry_after_the_timed_out_resolver_finishes() { + let resolver_worker = std::sync::Mutex::new(None); + let (release, blocked) = std::sync::mpsc::channel(); + assert!(confirm_backend_endpoint_available_with_resolver( + "http://backend.invalid:6185/", + &resolver_worker, + Duration::from_millis(30), + move |_, _| { + let _ = blocked.recv_timeout(Duration::from_secs(2)); + Err(std::io::Error::from(ErrorKind::TimedOut)) + }, + ) + .is_err()); + release.send(()).expect("release blocked resolver"); + let deadline = Instant::now() + Duration::from_secs(1); + while !resolver_worker + .lock() + .unwrap() + .as_ref() + .unwrap() + .is_finished() + { + assert!( + Instant::now() < deadline, + "resolver must finish after release" + ); + std::thread::sleep(Duration::from_millis(1)); + } + + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind listener"); + let address = listener.local_addr().unwrap(); + drop(listener); + let result = confirm_backend_endpoint_available_with_resolver( + "http://backend.invalid:6185/", + &resolver_worker, + Duration::from_millis(200), + move |_, _| Ok(vec![address]), + ); + assert!( + result.is_ok(), + "finished resolver must allow retry: {result:?}" + ); + } + + #[test] + fn restart_endpoint_probe_can_retry_after_the_resolver_panics() { + let resolver_worker = std::sync::Mutex::new(None); + assert!(confirm_backend_endpoint_available_with_resolver( + "http://backend.invalid:6185/", + &resolver_worker, + Duration::from_millis(200), + |_, _| panic!("resolver panic for regression test"), + ) + .is_err()); + let deadline = Instant::now() + Duration::from_secs(1); + while !resolver_worker + .lock() + .unwrap() + .as_ref() + .unwrap() + .is_finished() + { + assert!(Instant::now() < deadline, "panicked resolver must finish"); + std::thread::sleep(Duration::from_millis(1)); + } + + let error = confirm_backend_endpoint_available_with_resolver( + "http://backend.invalid:6185/", + &resolver_worker, + Duration::from_millis(200), + |_, _| Err(std::io::Error::from(ErrorKind::PermissionDenied)), + ) + .unwrap_err(); + assert!( + error.contains("name resolution failed"), + "retry did not run: {error}" + ); + assert!(!resolver_worker.is_poisoned()); + } + + #[test] + fn restart_endpoint_resolution_errors_redact_url_credentials() { + let error = confirm_backend_endpoint_available_with_resolver( + "http://sample-user:sample-password@backend.invalid:6185/?token=sample-token", + &std::sync::Mutex::new(None), + Duration::from_millis(200), + |_, _| Err(std::io::Error::from(ErrorKind::PermissionDenied)), + ) + .unwrap_err(); + assert!(error.contains("name resolution failed")); + assert!(error.contains("http://backend.invalid:6185")); + assert!(!error.contains("sample-user")); + assert!(!error.contains("sample-password")); + assert!(!error.contains("sample-token")); + } + + #[test] + fn restart_endpoint_errors_redact_credentials_without_changing_the_url() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind listener"); + let backend_url = format!( + "http://sample-user:sample-password@{}/?token=sample-token#sample-fragment", + listener.local_addr().expect("listener address") + ); + let state = BackendState { + backend_url: backend_url.clone(), + ..BackendState::default() + }; + let error = state.confirm_backend_endpoint_available(200).unwrap_err(); + assert!(!error.contains("sample-user"), "username leaked: {error}"); + assert!( + !error.contains("sample-password"), + "password leaked: {error}" + ); + assert!(!error.contains("sample-token"), "query leaked: {error}"); + assert!( + !error.contains("sample-fragment"), + "fragment leaked: {error}" + ); + assert!(error.contains(&listener.local_addr().unwrap().to_string())); + assert_eq!(state.backend_url, backend_url); + } + + #[test] + fn restart_endpoint_errors_never_echo_unparseable_or_unsupported_input() { + for backend_url in [ + "http://sample-user:sample-password@[invalid/", + "custom:sample-user:sample-password@backend", + ] { + let error = confirm_backend_endpoint_available_with_resolver( + backend_url, + &std::sync::Mutex::new(None), + Duration::from_millis(100), + |_, _| panic!("invalid endpoint must not resolve"), + ) + .unwrap_err(); + assert!(!error.contains("sample-user"), "username leaked: {error}"); + assert!( + !error.contains("sample-password"), + "password leaked: {error}" + ); + } + } + + #[test] + fn restart_endpoint_probe_rejects_invalid_urls() { + let state = BackendState { + backend_url: "not a backend URL".to_string(), + ..BackendState::default() + }; + + assert!( + state.confirm_backend_endpoint_available(50).is_err(), + "an invalid endpoint must not authorize a replacement backend" + ); + } + + #[test] + fn restart_endpoint_probe_rejects_a_listening_backend() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind listener"); + let state = BackendState { + backend_url: format!( + "http://{}/", + listener.local_addr().expect("listener address") + ), + ..BackendState::default() + }; + + let error = state + .confirm_backend_endpoint_available(200) + .expect_err("an answering endpoint must block a respawn"); + assert!(error.contains("already answering")); + } + + #[test] + fn restart_endpoint_probe_accepts_refused_loopback_connections() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind listener"); + let address = listener.local_addr().expect("listener address"); + drop(listener); + + let result = confirm_backend_endpoint_available_with_resolver( + &format!("http://{address}/"), + &std::sync::Mutex::new(None), + Duration::from_millis(200), + |_, _| panic!("numeric addresses must not invoke DNS"), + ); + assert!( + result.is_ok(), + "a refused connection must permit respawn: {result:?}" + ); + } + + #[test] + fn restart_endpoint_probe_does_not_treat_resolution_errors_as_available() { + let error = confirm_backend_endpoint_available_with_resolver( + "http://backend.invalid:6185/", + &std::sync::Mutex::new(None), + Duration::from_millis(200), + |_, _| Err(std::io::Error::from(ErrorKind::PermissionDenied)), + ) + .expect_err("an inconclusive resolution must block a respawn"); + + assert!(error.contains("Cannot confirm backend endpoint")); + assert!(error.contains("name resolution failed")); + } + + #[test] + fn restart_endpoint_probe_rejects_empty_resolution_results() { + assert!(confirm_backend_endpoint_available_with_resolver( + "http://backend.invalid:6185/", + &std::sync::Mutex::new(None), + Duration::from_millis(200), + |_, _| Ok(Vec::new()), + ) + .is_err()); + } + + #[test] + fn restart_endpoint_probe_bounds_hostname_resolution_by_the_total_deadline() { + let (release, blocked) = std::sync::mpsc::channel(); + let (finished, completed) = std::sync::mpsc::channel(); + let start = Instant::now(); + let result = confirm_backend_endpoint_available_with_resolver( + "http://backend.invalid:6185/", + &std::sync::Mutex::new(None), + Duration::from_millis(100), + move |_, _| { + let _ = blocked.recv_timeout(Duration::from_secs(2)); + let _ = finished.send(()); + Err(std::io::Error::from(ErrorKind::TimedOut)) + }, + ); + let elapsed = start.elapsed(); + let _ = release.send(()); + completed + .recv_timeout(Duration::from_secs(1)) + .expect("resolver worker must finish after being released"); + + assert!(result.is_err(), "a timed-out probe must block a respawn"); + assert!( + elapsed >= Duration::from_millis(100) && elapsed < Duration::from_millis(350), + "DNS must share the probe deadline instead of blocking for {elapsed:?}" + ); + } + + #[test] + fn restart_endpoint_probe_checks_every_resolved_address() { + let available_listener = + std::net::TcpListener::bind("127.0.0.1:0").expect("bind available address"); + let available = available_listener.local_addr().expect("available address"); + let occupied_listener = + std::net::TcpListener::bind("127.0.0.1:0").expect("bind occupied address"); + let occupied = occupied_listener.local_addr().expect("occupied address"); + drop(available_listener); + + let error = confirm_backend_endpoint_available_with_resolver( + "http://backend.invalid:6185/", + &std::sync::Mutex::new(None), + Duration::from_millis(200), + move |_, _| Ok(vec![available, occupied]), + ) + .expect_err("one answering address must block a respawn"); + assert!(error.contains("already answering")); + } + #[test] fn is_complete_http_response_respects_content_length() { let raw = b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ntest"; diff --git a/src-tauri/src/backend/launch.rs b/src-tauri/src/backend/launch.rs index d0931660..de930c1e 100644 --- a/src-tauri/src/backend/launch.rs +++ b/src-tauri/src/backend/launch.rs @@ -412,6 +412,10 @@ impl BackendState { return Ok(()); } + // Every replacement and initial managed start shares this gate. Do not hold + // the child mutex while waiting; the final spawn checks exit under that lock. + self.confirm_previous_backend_exited()?; + if !plan.cwd.exists() { fs::create_dir_all(&plan.cwd).map_err(|error| { format!( @@ -522,6 +526,53 @@ impl BackendState { command.stderr(Stdio::null()); } + let Some(child_pid) = self.spawn_backend_command( + &mut command, + plan, + #[cfg(test)] + || {}, + )? + else { + return Ok(()); + }; + if let Some(log_path) = backend_log_path { + self.start_backend_log_rotation_worker(app, log_path, child_pid); + } else { + self.stop_backend_log_rotation_worker(); + } + Ok(()) + } + + /// Spawn and register the child atomically with respect to exit cleanup. + fn spawn_backend_command( + &self, + command: &mut Command, + plan: &crate::LaunchPlan, + #[cfg(test)] after_quitting_check: impl FnOnce(), + ) -> Result, String> { + #[cfg(test)] + let check_quitting = || { + let quitting = self.is_quitting(); + after_quitting_check(); + quitting + }; + #[cfg(not(test))] + let check_quitting = || self.is_quitting(); + // Keep the child-slot check and spawn in the same critical section, including + // callers that do not hold the high-level backend action reservation. + let mut child_guard = self + .child + .lock() + .map_err(|_| "Backend process lock poisoned.")?; + // Exit marks the state before taking this same child lock. If exit wins, + // refuse the replacement; if spawn wins, cleanup sees and stops the child. + if check_quitting() { + return Err("Desktop is exiting; refusing to start the backend.".to_string()); + } + if child_guard.is_some() { + append_desktop_log("backend child already exists, skip re-spawn"); + return Ok(None); + } let child = command.spawn().map_err(|error| { format!( "Failed to spawn backend process with command {:?}: {}", @@ -535,16 +586,12 @@ impl BackendState { build_debug_command(plan), plan.cwd.display() )); - *self - .child - .lock() - .map_err(|_| "Backend process lock poisoned.")? = Some(child); - if let Some(log_path) = backend_log_path { - self.start_backend_log_rotation_worker(app, log_path, child_pid); - } else { - self.stop_backend_log_rotation_worker(); - } - Ok(()) + *child_guard = Some(child); + // Record the identity while the process is certainly alive; a later restart uses + // it to prove the process is gone instead of trusting the `Child` handle. + self.record_spawned_identity(child_pid); + drop(child_guard); + Ok(Some(child_pid)) } } @@ -585,6 +632,162 @@ mod tests { ASTRBOT_DASHBOARD_PORT_ENV, ]; + #[test] + fn spawn_backend_command_coordinates_with_exit_cleanup() { + use crate::{lifecycle::cleanup, BackendState, LaunchPlan}; + + let executable = env::current_exe().expect("test executable"); + let plan = LaunchPlan { + cmd: executable.to_string_lossy().into_owned(), + args: vec!["--help".to_string()], + cwd: env::current_dir().expect("current directory"), + root_dir: None, + webui_dir: None, + webui_cache_version: None, + packaged_core_version: None, + packaged_webui_index_sha256: None, + packaged_webui_entry_digests: None, + startup_heartbeat_path: None, + packaged_mode: false, + }; + + let state = BackendState::default(); + let spawned = state + .spawn_backend_command( + Command::new(&executable) + .arg("--help") + .stdout(std::process::Stdio::null()), + &plan, + || {}, + ) + .expect("spawn before exit starts"); + assert_eq!(state.tracked_child_pid(), spawned); + assert!(spawned.is_some()); + assert!(state.try_begin_exit_cleanup()); + cleanup::stop_backend_for_exit(&state, cleanup::ExitTrigger::ExitRequested, |_| {}); + assert!(state.child.lock().unwrap().is_none()); + + for cleanup_completed in [false, true] { + let state = BackendState::default(); + if cleanup_completed { + assert!(state.try_begin_exit_cleanup()); + cleanup::stop_backend_for_exit(&state, cleanup::ExitTrigger::ExitRequested, |_| {}); + state.allow_next_exit_request(); + } else { + state.mark_quitting(); + } + let result = state.spawn_backend_command( + Command::new(&executable) + .arg("--help") + .stdout(std::process::Stdio::null()), + &plan, + || {}, + ); + let mut child = state.child.lock().unwrap().take(); + if let Some(child) = child.as_mut() { + let _ = child.kill(); + child.wait().expect("reap unexpected replacement"); + } + + assert!( + child.is_none(), + "shutdown must not leave a replacement child" + ); + assert!( + result.is_err_and(|error| error.contains("exiting")), + "shutdown must reject the spawn before running the command" + ); + } + } + + #[test] + fn spawn_backend_command_keeps_the_child_lock_from_exit_check_through_spawn() { + use std::{ + sync::{mpsc, TryLockError}, + time::Duration, + }; + + use crate::{lifecycle::cleanup, BackendState, LaunchPlan}; + + let executable = env::current_exe().expect("test executable"); + let plan = LaunchPlan { + cmd: executable.to_string_lossy().into_owned(), + args: vec!["--help".to_string()], + cwd: env::current_dir().expect("current directory"), + root_dir: None, + webui_dir: None, + webui_cache_version: None, + packaged_core_version: None, + packaged_webui_index_sha256: None, + packaged_webui_entry_digests: None, + startup_heartbeat_path: None, + packaged_mode: false, + }; + let state = BackendState::default(); + let (checked_tx, checked_rx) = mpsc::channel(); + let (resume_tx, resume_rx) = mpsc::channel(); + + std::thread::scope(|scope| { + let spawning_state = &state; + let spawning = scope.spawn(move || { + spawning_state.spawn_backend_command( + Command::new(&executable) + .arg("--help") + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()), + &plan, + || { + checked_tx.send(()).expect("announce exit-check barrier"); + resume_rx + .recv_timeout(Duration::from_secs(5)) + .expect("resume after marking exit"); + }, + ) + }); + + checked_rx + .recv_timeout(Duration::from_secs(5)) + .expect("spawn reaches the exit-check barrier"); + assert!(state.try_begin_exit_cleanup()); + let child_locked_during_check = match state.child.try_lock() { + Ok(guard) => { + drop(guard); + false + } + Err(TryLockError::WouldBlock) => true, + Err(TryLockError::Poisoned(_)) => panic!("child slot lock poisoned"), + }; + if !child_locked_during_check { + cleanup::stop_backend_for_exit(&state, cleanup::ExitTrigger::ExitRequested, |_| {}); + state.allow_next_exit_request(); + } + resume_tx.send(()).expect("release spawn barrier"); + if child_locked_during_check { + cleanup::stop_backend_for_exit(&state, cleanup::ExitTrigger::ExitRequested, |_| {}); + state.allow_next_exit_request(); + } + let result = spawning.join().expect("spawn worker finishes"); + let mut unexpected_child = state.child.lock().unwrap().take(); + if let Some(child) = unexpected_child.as_mut() { + let _ = child.kill(); + child.wait().expect("reap unexpected replacement"); + } + + assert!( + unexpected_child.is_none(), + "exit cleanup must not leave a replacement child" + ); + assert!( + child_locked_during_check, + "the exit-state query must run while holding the child lock" + ); + assert!( + matches!(result, Ok(Some(_))), + "spawn that won the exit-state check must register a child for cleanup: {result:?}" + ); + }); + } + fn get_command_env_value(command: &Command, key: &str) -> Option> { command .get_envs() diff --git a/src-tauri/src/backend/process_lifecycle.rs b/src-tauri/src/backend/process_lifecycle.rs index 7370f694..60ac42a2 100644 --- a/src-tauri/src/backend/process_lifecycle.rs +++ b/src-tauri/src/backend/process_lifecycle.rs @@ -11,15 +11,51 @@ use std::{ use tauri::{AppHandle, Manager}; use crate::{ - append_desktop_log, logging, process_control, BackendState, BACKEND_LOG_MAX_BYTES, + append_desktop_log, append_restart_log, logging, process_control, BackendState, + BACKEND_EXIT_CONFIRM_POLL_INTERVAL_MS, BACKEND_EXIT_CONFIRM_TIMEOUT_MS, BACKEND_LOG_MAX_BYTES, BACKEND_LOG_ROTATION_CHECK_INTERVAL, GRACEFUL_STOP_TIMEOUT_MS, LOG_BACKUP_COUNT, }; +/// Confirm the recorded process identity independently without signalling a reused PID. +fn confirm_process_identity_exit( + identity: process_control::ProcessIdentity, + timeout: Duration, + log: F, +) -> Result<(), String> +where + F: FnOnce(&str), +{ + let outcome = process_control::wait_for_process_identity_exit( + identity, + timeout, + Duration::from_millis(BACKEND_EXIT_CONFIRM_POLL_INTERVAL_MS), + ); + if outcome == process_control::ProcessExitOutcome::StillRunning { + let error = format!( + "Backend exit could not be confirmed after the stop request: pid={}, waited {}ms. The process may still be running or its identity may be unavailable. Wait and retry; stop it manually only after verifying it is the backend.", + identity.pid, timeout.as_millis() + ); + log(&error); + return Err(error); + } + Ok(()) +} + impl BackendState { pub(crate) fn stop_backend(&self) -> Result<(), String> { self.stop_backend_with_timeout(Duration::from_millis(GRACEFUL_STOP_TIMEOUT_MS)) } + /// Stop and verify both the process and endpoint before a Windows installation. + pub(crate) fn stop_backend_before_update_install(&self) -> Result<(), String> { + self.stop_backend().map_err(|error| { + format!("Failed to stop backend before Windows update install: {error}") + })?; + self.confirm_previous_backend_exited().map_err(|error| { + format!("Failed to confirm backend exit before Windows update install: {error}") + }) + } + pub(crate) fn stop_backend_with_timeout(&self, timeout: Duration) -> Result<(), String> { self.stop_backend_log_rotation_worker(); let mut guard = self @@ -27,12 +63,65 @@ impl BackendState { .lock() .map_err(|_| "Backend process lock poisoned.".to_string())?; - let Some(child) = guard.as_mut() else { + // A completed `Child` is not evidence that the backend endpoint is unused. + // Drop it without another stop request; callers verify the endpoint before + // reporting a bridge stop or spawning a replacement. + let (pid, already_exited) = { + let Some(child) = guard.as_mut() else { + if let Some(pid) = self.last_recorded_pid() { + let _ = self.restart_stop_pid.compare_exchange( + 0, + pid, + Ordering::AcqRel, + Ordering::Acquire, + ); + } + return Ok(()); + }; + let pid = child.id(); + // Keep the stop target even when this handle has already exited, so update + // recovery and retries run the same process confirmation as a restart. + self.restart_stop_pid.store(pid, Ordering::Release); + match child.try_wait() { + Ok(Some(status)) => (pid, Some(status.to_string())), + Ok(None) => (pid, None), + Err(error) => { + append_desktop_log(&format!( + "failed to poll backend process status before stop: pid={pid}, error={error}" + )); + (pid, None) + } + } + }; + if let Some(status) = already_exited { + append_desktop_log(&format!( + "backend process already exited before stop, drop stale handle: pid={pid}, status={status}" + )); + *guard = None; return Ok(()); + } + + // Prefer the identity captured while the process was certainly alive. Re-reading it + // here could describe a recycled PID instead of the backend this shell spawned. + let identity = self.stop_identity(pid); + let graceful = { + let Some(child) = guard.as_mut() else { + return Ok(()); + }; + process_control::stop_child_process_gracefully(child, timeout, append_desktop_log) }; - if process_control::stop_child_process_gracefully(child, timeout, append_desktop_log) { + if graceful { + // Drop the reaped handle before confirming so a retried stop cannot taskkill + // the stale PID, and release the child lock before the confirming wait so the + // bridge and readiness probes are not blocked for the whole timeout. *guard = None; + drop(guard); + confirm_process_identity_exit( + identity, + Duration::from_millis(BACKEND_EXIT_CONFIRM_TIMEOUT_MS), + append_restart_log, + )?; return Ok(()); } @@ -42,6 +131,15 @@ impl BackendState { )) } + /// Identity to hold a stop against, preferring the one recorded at spawn time. + /// + /// The recorded identity was captured while the process was certainly alive; capturing + /// again after the fact can describe a recycled PID. + fn stop_identity(&self, pid: u32) -> process_control::ProcessIdentity { + self.spawned_identity_for(pid) + .unwrap_or_else(|| process_control::capture_process_identity(pid)) + } + #[cfg(target_os = "windows")] pub(crate) fn stop_backend_for_system_shutdown(&self, timeout: Duration) -> Result<(), String> { self.stop_backend_log_rotation_worker(); @@ -54,6 +152,8 @@ impl BackendState { return Ok(()); }; + // System shutdown is time critical, so unlike the restart flow it does not spend + // extra time confirming the exit; the OS is about to terminate everything anyway. if process_control::stop_child_process_for_system_shutdown( child, timeout, @@ -69,6 +169,63 @@ impl BackendState { )) } + /// Remember which process was just spawned, while it is certainly still alive. + pub(crate) fn record_spawned_identity(&self, pid: u32) { + let identity = process_control::capture_process_identity(pid); + match self.last_spawned_identity.lock() { + Ok(mut guard) => *guard = Some(identity), + Err(error) => append_desktop_log(&format!( + "backend last-spawned identity lock poisoned on spawn: pid={pid}, error={error}" + )), + } + } + + /// Identity recorded for `pid`, used to detect PID recycling across a restart. + pub(crate) fn spawned_identity_for( + &self, + pid: u32, + ) -> Option { + match self.last_spawned_identity.lock() { + Ok(guard) => guard.filter(|identity| identity.pid == pid), + Err(error) => { + append_desktop_log(&format!( + "backend last-spawned identity lock poisoned when reading pid={pid}: {error}" + )); + None + } + } + } + + /// PID of the child handle this shell still tracks, without polling it. + pub(crate) fn tracked_child_pid(&self) -> Option { + match self.child.lock() { + Ok(guard) => guard.as_ref().map(std::process::Child::id), + Err(error) => { + append_desktop_log(&format!( + "backend child lock poisoned when reading tracked pid: {error}" + )); + None + } + } + } + + /// PID the shell last spawned, kept even after the `Child` handle was dropped. + /// + /// This is what lets a restart name the backend that it must confirm gone when the + /// handle was already reaped — the exact situation that used to hide a still-running + /// backend behind a handle reporting `None`. + pub(crate) fn last_recorded_pid(&self) -> Option { + match self.last_spawned_identity.lock() { + Ok(guard) => guard.map(|identity| identity.pid), + Err(error) => { + append_desktop_log(&format!( + "backend last-spawned identity lock poisoned when reading pid: {error}" + )); + None + } + } + } + pub(crate) fn stop_backend_log_rotation_worker(&self) { match self.log_rotator_stop.lock() { Ok(mut guard) => { @@ -95,19 +252,27 @@ impl BackendState { } }; - let Some(child) = guard.as_mut() else { - return false; + let poll = { + let Some(child) = guard.as_mut() else { + return false; + }; + if child.id() != child_pid { + return false; + } + child.try_wait() }; - if child.id() != child_pid { - return false; - } - match child.try_wait() { + match poll { Ok(None) => true, Ok(Some(status)) => { append_desktop_log(&format!( "backend process exited, stop log rotator worker: pid={child_pid}, status={status}" )); + // Drop the reaped handle right away. Keeping it would leave a `Child` + // whose `try_wait` returns `Some` instantly, and the restart flow would + // read that as "backend already stopped" while the PID may already have + // been recycled by an unrelated process. + *guard = None; false } Err(error) => { @@ -165,3 +330,40 @@ impl BackendState { }); } } + +#[cfg(test)] +mod tests { + use super::confirm_process_identity_exit; + use crate::process_control; + use std::time::Duration; + + #[test] + fn failed_stop_confirmation_logs_the_returned_error() { + let identity = process_control::capture_process_identity(std::process::id()); + let mut messages = Vec::new(); + + let error = confirm_process_identity_exit(identity, Duration::ZERO, |message| { + messages.push(message.to_string()); + }) + .expect_err("a live process must fail exit confirmation"); + + assert_eq!(messages, vec![error]); + } + + #[test] + fn successful_stop_confirmation_does_not_log_an_error() { + let identity = process_control::ProcessIdentity { + pid: 0, + created_at: None, + }; + let mut messages = Vec::new(); + + assert_eq!( + confirm_process_identity_exit(identity, Duration::ZERO, |message| { + messages.push(message.to_string()); + }), + Ok(()) + ); + assert!(messages.is_empty()); + } +} diff --git a/src-tauri/src/backend/readiness.rs b/src-tauri/src/backend/readiness.rs index 6f7f33cf..16613dd2 100644 --- a/src-tauri/src/backend/readiness.rs +++ b/src-tauri/src/backend/readiness.rs @@ -551,6 +551,28 @@ mod tests { use super::*; + #[test] + fn readiness_does_not_equate_slow_http_with_an_available_endpoint() { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind slow backend"); + let state = BackendState { + backend_url: format!("http://{}/", listener.local_addr().unwrap()), + ..BackendState::default() + }; + // The listener accepts TCP handshakes but never responds to HTTP requests. + let (http_status, tcp_reachable) = state.probe_backend_readiness("/", 50); + assert!(http_status.is_none()); + assert!(tcp_reachable); + assert!( + state.ping_backend(50), + "the initial readiness branch must skip spawning" + ); + let error = state + .confirm_previous_backend_exited() + .expect_err("the final spawn gate must reject a surviving TCP listener"); + assert!(error.contains("already answering")); + assert!(state.child.lock().unwrap().is_none()); + } + fn sha256_hex(payload: &[u8]) -> String { format!("{:x}", Sha256::digest(payload)) } diff --git a/src-tauri/src/backend/restart.rs b/src-tauri/src/backend/restart.rs index ad06dd3f..a775559c 100644 --- a/src-tauri/src/backend/restart.rs +++ b/src-tauri/src/backend/restart.rs @@ -7,11 +7,62 @@ use std::{ use tauri::AppHandle; use crate::{ - append_desktop_log, append_restart_log, backend, AtomicFlagGuard, BackendBridgeState, - BackendState, LaunchPlan, GRACEFUL_RESTART_POLL_INTERVAL_MS, + append_desktop_log, append_restart_log, backend, process_control, AtomicFlagGuard, + BackendBridgeState, BackendState, LaunchPlan, BACKEND_EXIT_CONFIRM_POLL_INTERVAL_MS, + BACKEND_EXIT_CONFIRM_TIMEOUT_MS, GRACEFUL_RESTART_POLL_INTERVAL_MS, GRACEFUL_RESTART_REQUEST_TIMEOUT_MS, }; +/// Gate a respawn on observable facts instead of the previous `Child` handle. +/// +/// Two independent checks run before any spawn, in this order: +/// 1. the recorded process identity is no longer present, allowing a reused PID only +/// when its creation timestamp proves that it is a different process; +/// 2. the backend endpoint explicitly refuses connections on every resolved address. +/// +/// The endpoint probe is a closure so it is evaluated only after the PID gate passes. +/// Sampling it up front would judge the port while the old backend is still shutting +/// down, and a backend that leaves during the wait would be reported as a conflict. +/// +/// Both failures return an error instead of force-killing the PID. After a multi-second +/// pause the PID may already belong to an unrelated process, and terminating an unknown +/// process is worse than telling the user to stop the old backend manually. +fn preflight_before_respawn( + stopped_pid: u32, + identity: Option, + timeout: Duration, + poll_interval: Duration, + probe: P, + endpoint_probe: E, +) -> Result<(), String> +where + P: Fn(u32) -> process_control::ProcessProbe, + E: FnOnce() -> Result<(), String>, +{ + // A first managed start has no stopped PID. An uncertain unmanaged restart + // must be rejected by its strategy before it can reach this endpoint-only gate. + if stopped_pid != 0 { + let identity = identity.unwrap_or(process_control::ProcessIdentity { + pid: stopped_pid, + created_at: None, + }); + let outcome = process_control::wait_for_process_identity_exit_with( + identity, + timeout, + poll_interval, + probe, + ); + if outcome == process_control::ProcessExitOutcome::StillRunning { + return Err(format!( + "Previous backend exit could not be confirmed: pid={stopped_pid} still exists or cannot be inspected after {}ms. Wait and retry. Stop it manually only after verifying it is the backend.", + timeout.as_millis() + )); + } + } + + endpoint_probe() +} + impl BackendState { fn sanitize_auth_token(auth_token: Option<&str>) -> Option { let token = auth_token?; @@ -110,30 +161,41 @@ impl BackendState { } pub(crate) fn stop_backend_for_bridge(&self) -> Result<(), String> { - let has_managed_child = self - .child - .lock() - .map_err(|_| "Backend process lock poisoned.".to_string())? - .is_some(); - if has_managed_child { - return self.stop_backend(); + let _spawn_guard = AtomicFlagGuard::try_set(&self.is_spawning) + .ok_or_else(|| "Backend action already in progress.".to_string())?; + if self.has_managed_backend()? { + self.stop_backend()?; + return self.confirm_previous_backend_exited(); } - if self.ping_backend(backend::runtime::backend_ping_timeout_ms( + self.confirm_backend_endpoint_available(backend::runtime::backend_ping_timeout_ms( append_desktop_log, - )) { - return Err("Backend is running but not managed by desktop process.".to_string()); - } - Ok(()) + )) } - fn has_managed_child(&self) -> Result { - self.child + /// Keep desktop ownership after an exited child is reaped or a stop is retried. + pub(crate) fn has_managed_backend(&self) -> Result { + let has_child = self + .child + .lock() + .map(|guard| guard.is_some()) + .map_err(|error| { + let message = + format!("backend child lock poisoned while resolving managed state: {error}"); + append_desktop_log(&message); + message + })?; + if has_child || self.restart_stop_pid.load(Ordering::Acquire) != 0 { + return Ok(true); + } + + // Reaping an exited child must not change who manages its replacement. + self.last_spawned_identity .lock() .map(|guard| guard.is_some()) .map_err(|error| { let message = format!( - "backend child lock poisoned while resolving restart strategy: {error}" + "backend spawn identity lock poisoned while resolving managed state: {error}" ); append_desktop_log(&message); message @@ -143,12 +205,12 @@ impl BackendState { fn restart_strategy( &self, plan: &LaunchPlan, - has_managed_child: bool, + has_managed_backend: bool, ) -> backend::restart_strategy::RestartStrategy { backend::restart_strategy::compute_restart_strategy( cfg!(target_os = "windows"), plan.packaged_mode, - has_managed_child, + has_managed_backend, ) } @@ -170,19 +232,11 @@ impl BackendState { fn execute_graceful_restart_strategy( &self, strategy: backend::restart_strategy::RestartStrategy, - auth_token: Option<&str>, - previous_start_time: Option, - packaged_mode: bool, - ) -> Result<(), String> { - // Contract: this function interprets the pure (strategy, outcome) pair and either - // returns early on a completed graceful restart or performs the managed fallback path. - let outcome = match strategy { - backend::restart_strategy::RestartStrategy::ManagedSkipGraceful => { - backend::restart_strategy::GracefulRestartOutcome::RequestRejected - } - _ => self.try_graceful_restart_and_wait(auth_token, previous_start_time, packaged_mode), - }; + outcome: backend::restart_strategy::GracefulRestartOutcome, + ) -> Result { + use backend::restart_strategy::RestartAction; + // Interpret the strategy and observed API outcome before any managed fallback. match (strategy, outcome) { ( backend::restart_strategy::RestartStrategy::ManagedWithGracefulFallback, @@ -193,13 +247,14 @@ impl BackendState { backend::restart_strategy::GracefulRestartOutcome::Completed, ) => { append_restart_log("graceful restart completed via backend api"); - Ok(()) + Ok(RestartAction::GracefulCompleted) } (backend::restart_strategy::RestartStrategy::ManagedSkipGraceful, _) => { append_restart_log( "skip graceful restart for packaged windows managed backend; using managed restart", ); - self.stop_backend_for_restart_flow() + self.stop_backend_for_restart_flow()?; + Ok(RestartAction::LaunchManagedReplacement) } ( backend::restart_strategy::RestartStrategy::ManagedWithGracefulFallback, @@ -208,7 +263,8 @@ impl BackendState { append_restart_log(&format!( "graceful restart did not complete, fallback to managed restart: {error}" )); - self.stop_backend_for_restart_flow() + self.stop_backend_for_restart_flow()?; + Ok(RestartAction::LaunchManagedReplacement) } ( backend::restart_strategy::RestartStrategy::ManagedWithGracefulFallback, @@ -217,16 +273,18 @@ impl BackendState { append_restart_log( "graceful restart request was rejected, fallback to managed restart", ); - self.stop_backend_for_restart_flow() + self.stop_backend_for_restart_flow()?; + Ok(RestartAction::LaunchManagedReplacement) } ( backend::restart_strategy::RestartStrategy::UnmanagedWithGracefulProbe, backend::restart_strategy::GracefulRestartOutcome::WaitFailed(error), ) => { - append_restart_log(&format!( - "graceful restart did not complete for unmanaged backend, bootstrap managed restart: {error}" - )); - self.stop_backend_for_restart_flow() + let error = format!( + "Graceful restart did not complete and backend is not desktop-managed; refusing to start a replacement because the old process may still be restarting: {error}" + ); + append_restart_log(&error); + Err(error) } ( backend::restart_strategy::RestartStrategy::UnmanagedWithGracefulProbe, @@ -239,15 +297,68 @@ impl BackendState { } fn stop_backend_for_restart_flow(&self) -> Result<(), String> { + // Remember which PID to confirm before spawning. The tracked handle wins; when it + // is already gone it was reaped after an earlier exit, and the PID recorded at + // spawn time is the one that must still be proven gone. + let pid = self + .tracked_child_pid() + .or_else(|| self.last_recorded_pid()) + .unwrap_or(0); + self.restart_stop_pid.store(pid, Ordering::Release); self.stop_backend() } + /// Refuse to spawn unless the old backend is provably gone. + /// + /// Runs both gates exactly once, in this order: + /// 1) the recorded process identity is no longer present; + /// 2) the backend endpoint explicitly refuses connections. + /// + /// An unknown process identity or endpoint result blocks the replacement. A missing + /// creation timestamp can also conservatively block a reused PID, so a failed check + /// preserves the target for a retry instead of asserting that the backend is alive. + /// + /// A failure returns an error instead of force-killing the PID: after a multi-second + /// pause the PID may already belong to an unrelated process, and terminating an + /// unknown process is worse than telling the user to stop the old backend manually. + pub(crate) fn confirm_previous_backend_exited(&self) -> Result<(), String> { + let stopped_pid = self.restart_stop_pid.load(Ordering::Acquire); + let identity = self.spawned_identity_for(stopped_pid); + let result = preflight_before_respawn( + stopped_pid, + identity, + Duration::from_millis(BACKEND_EXIT_CONFIRM_TIMEOUT_MS), + Duration::from_millis(BACKEND_EXIT_CONFIRM_POLL_INTERVAL_MS), + process_control::probe_process, + || { + self.confirm_backend_endpoint_available(backend::runtime::backend_ping_timeout_ms( + append_desktop_log, + )) + }, + ); + if result.is_ok() { + let _ = self.restart_stop_pid.compare_exchange( + stopped_pid, + 0, + Ordering::AcqRel, + Ordering::Acquire, + ); + } + match &result { + Ok(()) if stopped_pid != 0 => append_restart_log(&format!( + "previous backend confirmed exited before respawn: pid={stopped_pid}" + )), + Ok(()) => {} + Err(error) => append_restart_log(error), + } + result + } + fn launch_backend_after_restart( &self, app: &AppHandle, plan: &LaunchPlan, ) -> Result<(), String> { - let _spawn_guard = AtomicFlagGuard::set(&self.is_spawning); self.start_backend_process(app, plan)?; self.wait_for_backend(plan) } @@ -259,37 +370,39 @@ impl BackendState { ) -> Result<(), String> { append_restart_log("backend restart requested"); + let _spawn_guard = AtomicFlagGuard::try_set(&self.is_spawning) + .ok_or_else(|| "Backend action already in progress.".to_string())?; let _restart_guard = AtomicFlagGuard::try_set(&self.is_restarting) .ok_or_else(|| "Backend action already in progress.".to_string())?; let plan = self.resolve_launch_plan(app)?; - let has_managed_child = self.has_managed_child()?; - let strategy = self.restart_strategy(&plan, has_managed_child); + let has_managed_backend = self.has_managed_backend()?; + let strategy = self.restart_strategy(&plan, has_managed_backend); let normalized_param = Self::sanitize_auth_token(auth_token); if let Some(token) = normalized_param.as_deref() { self.set_restart_auth_token(Some(token)); } let restart_auth_token = normalized_param.or_else(|| self.get_restart_auth_token()); let previous_start_time = self.fetch_backend_start_time(); - match self.execute_graceful_restart_strategy( - strategy, - restart_auth_token.as_deref(), - previous_start_time, - plan.packaged_mode, - ) { - Ok(()) - if strategy != backend::restart_strategy::RestartStrategy::ManagedSkipGraceful => - { - self.verify_running_resource_identity( + let outcome = match strategy { + backend::restart_strategy::RestartStrategy::ManagedSkipGraceful => { + backend::restart_strategy::GracefulRestartOutcome::RequestRejected + } + _ => self.try_graceful_restart_and_wait( + restart_auth_token.as_deref(), + previous_start_time, + plan.packaged_mode, + ), + }; + match self.execute_graceful_restart_strategy(strategy, outcome)? { + backend::restart_strategy::RestartAction::GracefulCompleted => self + .verify_running_resource_identity( &plan, backend::runtime::backend_ping_timeout_ms(append_desktop_log).max(1_000), - )?; - return Ok(()); + ), + backend::restart_strategy::RestartAction::LaunchManagedReplacement => { + self.launch_backend_after_restart(app, &plan) } - Ok(()) => {} - Err(error) => return Err(error), } - - self.launch_backend_after_restart(app, &plan) } pub(crate) fn bridge_state(&self, app: &AppHandle) -> BackendBridgeState { @@ -317,8 +430,256 @@ impl BackendState { #[cfg(test)] mod tests { - use super::BackendState; - use crate::backend::restart_strategy::RestartStrategy; + use std::{ + net::TcpListener, + process::{Command, Stdio}, + sync::{atomic::Ordering, Mutex}, + }; + + use super::{preflight_before_respawn, BackendState}; + use crate::{ + backend::restart_strategy::RestartStrategy, process_control::ProcessIdentity, + process_control::ProcessProbe, + }; + + #[test] + fn managed_backend_classification_survives_a_reaped_child() { + let mut child = Command::new(std::env::current_exe().expect("locate test executable")) + .arg("--list") + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("spawn a short-lived child"); + let state = BackendState::default(); + state.record_spawned_identity(child.id()); + child.wait().expect("reap the child"); + + assert!(state.child.lock().unwrap().is_none()); + assert_eq!(state.restart_stop_pid.load(Ordering::Acquire), 0); + assert!( + state.has_managed_backend().unwrap(), + "reaping the child must not discard desktop ownership of its backend" + ); + } + + #[test] + fn managed_backend_classification_recognizes_a_pending_stop() { + let state = BackendState::default(); + state.restart_stop_pid.store(14360, Ordering::Release); + + assert!( + state.has_managed_backend().unwrap(), + "a pending stop must retain desktop management even without a child handle" + ); + } + + #[test] + fn backend_without_a_managed_child_or_history_stays_unmanaged() { + assert!(!BackendState::default().has_managed_backend().unwrap()); + } + + #[test] + fn bridge_stop_retry_does_not_clear_a_live_pending_process() { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind backend endpoint"); + let state = BackendState { + backend_url: format!("http://{}/", listener.local_addr().unwrap()), + ..BackendState::default() + }; + drop(listener); + let pid = std::process::id(); + state.record_spawned_identity(pid); + state.restart_stop_pid.store(pid, Ordering::Release); + + let error = state + .stop_backend_for_bridge() + .expect_err("a refused endpoint does not prove the pending process exited"); + + assert!(error.contains("could not be confirmed"), "{error}"); + assert_eq!(state.restart_stop_pid.load(Ordering::Acquire), pid); + assert!(!state.is_spawning.load(Ordering::Acquire)); + } + + #[test] + fn managed_restart_fallback_requests_a_replacement_after_stopping() { + use crate::backend::restart_strategy::{GracefulRestartOutcome, RestartAction}; + + for outcome in [ + GracefulRestartOutcome::WaitFailed("backend exited".to_string()), + GracefulRestartOutcome::RequestRejected, + ] { + let state = BackendState::default(); + let result = state.execute_graceful_restart_strategy( + RestartStrategy::ManagedWithGracefulFallback, + outcome, + ); + + assert_eq!(result, Ok(RestartAction::LaunchManagedReplacement)); + } + } + + #[test] + fn completed_graceful_restart_does_not_request_a_replacement() { + use crate::backend::restart_strategy::{GracefulRestartOutcome, RestartAction}; + + for strategy in [ + RestartStrategy::ManagedWithGracefulFallback, + RestartStrategy::UnmanagedWithGracefulProbe, + ] { + let state = BackendState::default(); + state.restart_stop_pid.store(14360, Ordering::Release); + + assert_eq!( + state + .execute_graceful_restart_strategy(strategy, GracefulRestartOutcome::Completed), + Ok(RestartAction::GracefulCompleted) + ); + assert_eq!(state.restart_stop_pid.load(Ordering::Acquire), 14360); + } + } + + #[test] + fn packaged_windows_restart_requests_a_replacement_after_stopping() { + use crate::backend::restart_strategy::{GracefulRestartOutcome, RestartAction}; + + let state = BackendState::default(); + assert_eq!( + state.execute_graceful_restart_strategy( + RestartStrategy::ManagedSkipGraceful, + GracefulRestartOutcome::RequestRejected, + ), + Ok(RestartAction::LaunchManagedReplacement) + ); + } + + #[test] + fn unmanaged_restart_timeout_never_authorizes_managed_fallback() { + let state = BackendState::default(); + // A timed-out unmanaged restart must be rejected without consulting the + // endpoint: a transient refusal would not prove that its process exited. + + let result = state.execute_graceful_restart_strategy( + RestartStrategy::UnmanagedWithGracefulProbe, + crate::backend::restart_strategy::GracefulRestartOutcome::WaitFailed( + "restart timed out between listeners".to_string(), + ), + ); + + let error = result.expect_err("an untracked restart must not enter managed fallback"); + assert!(error.contains("not desktop-managed"), "{error}"); + assert!( + error.contains("restart timed out between listeners"), + "{error}" + ); + assert_eq!(state.restart_stop_pid.load(Ordering::Acquire), 0); + assert!(state.child.lock().unwrap().is_none()); + } + + #[test] + fn unmanaged_restart_completion_and_rejection_do_not_touch_managed_state() { + use crate::backend::restart_strategy::GracefulRestartOutcome; + + for outcome in [ + GracefulRestartOutcome::Completed, + GracefulRestartOutcome::RequestRejected, + ] { + let state = BackendState::default(); + state.restart_stop_pid.store(14360, Ordering::Release); + let completed = outcome == GracefulRestartOutcome::Completed; + + let result = state.execute_graceful_restart_strategy( + RestartStrategy::UnmanagedWithGracefulProbe, + outcome, + ); + + assert_eq!(result.is_ok(), completed); + assert_eq!(state.restart_stop_pid.load(Ordering::Acquire), 14360); + assert!(state.child.lock().unwrap().is_none()); + } + } + + #[test] + fn bridge_stop_rejects_an_action_already_in_progress() { + let state = BackendState { + backend_url: "invalid URL".to_string(), + ..BackendState::default() + }; + state.is_spawning.store(true, Ordering::Release); + + assert_eq!( + state.stop_backend_for_bridge(), + Err("Backend action already in progress.".to_string()) + ); + assert!(state.is_spawning.load(Ordering::Acquire)); + } + + #[test] + fn bridge_stop_reports_an_answering_backend_after_dropping_a_stale_child() { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind backend endpoint"); + let mut child = Command::new(std::env::current_exe().expect("locate test executable")) + .arg("--list") + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("spawn a short-lived child"); + child.wait().expect("reap the child"); + let state = BackendState { + child: Mutex::new(Some(child)), + backend_url: format!("http://{}/", listener.local_addr().unwrap()), + ..BackendState::default() + }; + + assert!(state.stop_backend_for_bridge().is_err()); + assert!(state.child.lock().unwrap().is_none()); + assert!(!state.is_spawning.load(Ordering::Acquire)); + } + + #[test] + fn bridge_stop_rejects_an_inconclusive_endpoint_probe() { + let state = BackendState { + backend_url: "invalid URL".to_string(), + ..BackendState::default() + }; + + let error = state + .stop_backend_for_bridge() + .expect_err("a failed probe must not report a successful stop"); + assert!(error.contains("Cannot confirm backend endpoint")); + assert!(!state.is_spawning.load(Ordering::Acquire)); + } + + #[test] + fn failed_endpoint_confirmation_retains_the_pid_for_a_retry() { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind backend endpoint"); + let mut child = Command::new(std::env::current_exe().expect("locate test executable")) + .arg("--list") + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("spawn a short-lived child"); + let pid = child.id(); + child.wait().expect("reap the child"); + let state = BackendState { + backend_url: format!("http://{}/", listener.local_addr().unwrap()), + ..BackendState::default() + }; + state.restart_stop_pid.store(pid, Ordering::Release); + + assert!(state.confirm_previous_backend_exited().is_err()); + assert_eq!(state.restart_stop_pid.load(Ordering::Acquire), pid); + drop(listener); + assert_eq!(state.confirm_previous_backend_exited(), Ok(())); + assert_eq!(state.restart_stop_pid.load(Ordering::Acquire), 0); + } + + #[test] + fn stopping_an_empty_child_slot_remembers_the_last_spawned_identity() { + let state = BackendState::default(); + let pid = std::process::id(); + state.record_spawned_identity(pid); + + assert_eq!(state.stop_backend(), Ok(())); + assert_eq!(state.restart_stop_pid.load(Ordering::Acquire), pid); + } #[test] fn sanitize_auth_token_rejects_empty_and_newline_tokens() { @@ -353,9 +714,193 @@ mod tests { }; let state = BackendState::default(); - assert_eq!( - state.restart_strategy(&plan, true), + // A managed child on Windows packaged mode skips the graceful restart path; the + // graceful fallback only applies elsewhere. Keep the platform in the expectation so + // the delegating wrapper is asserted against the same inputs the strategy module sees. + let expected = if cfg!(target_os = "windows") { + RestartStrategy::ManagedSkipGraceful + } else { RestartStrategy::ManagedWithGracefulFallback + }; + assert_eq!(state.restart_strategy(&plan, true), expected); + } + + fn identity(pid: u32, created_at: Option) -> Option { + Some(ProcessIdentity { pid, created_at }) + } + + #[test] + fn preflight_blocks_the_spawn_while_the_old_pid_is_still_alive() { + let result = preflight_before_respawn( + 14360, + identity(14360, Some(100)), + std::time::Duration::from_millis(50), + std::time::Duration::from_millis(10), + |_| ProcessProbe::Alive { + created_at: Some(100), + }, + || Ok(()), + ); + + let error = result.expect_err("a still-running backend must block the respawn"); + assert!( + error.contains("could not be confirmed"), + "unexpected error: {error}" + ); + assert!( + error.contains("Wait and retry"), + "unexpected error: {error}" + ); + assert!(error.contains("pid=14360"), "unexpected error: {error}"); + assert!( + error.contains("Stop it manually"), + "the error must tell the user what to do: {error}" + ); + } + + #[test] + fn preflight_allows_the_spawn_once_the_old_pid_is_gone() { + let probes = Mutex::new(Vec::new()); + let result = preflight_before_respawn( + 14360, + identity(14360, Some(100)), + std::time::Duration::from_millis(1_000), + std::time::Duration::from_millis(10), + |pid| { + probes.lock().expect("lock probes").push(pid); + ProcessProbe::Missing + }, + || Ok(()), + ); + + assert!(result.is_ok(), "unexpected error: {result:?}"); + assert_eq!( + *probes.lock().expect("lock probes"), + vec![14360], + "a gone PID should be answered on the first probe" + ); + } + + #[test] + fn preflight_treats_a_recycled_pid_as_exited() { + // The PID answers, but the creation stamp differs, so it is a different process. + let result = preflight_before_respawn( + 14360, + identity(14360, Some(100)), + std::time::Duration::from_millis(80), + std::time::Duration::from_millis(10), + |_| ProcessProbe::Alive { + created_at: Some(999), + }, + || Ok(()), + ); + + assert!(result.is_ok(), "unexpected error: {result:?}"); + } + + #[test] + fn preflight_reports_a_timeout_when_the_old_pid_never_leaves() { + let start = std::time::Instant::now(); + let result = preflight_before_respawn( + 14360, + identity(14360, Some(100)), + std::time::Duration::from_millis(60), + std::time::Duration::from_millis(10), + |_| ProcessProbe::Alive { + created_at: Some(100), + }, + || Ok(()), + ); + + assert!(result.is_err()); + let elapsed = start.elapsed(); + assert!( + elapsed >= std::time::Duration::from_millis(60), + "the wait must honour the timeout before reporting failure" + ); + assert!( + elapsed < std::time::Duration::from_millis(310), + "the wait must stay within the timeout plus scheduling tolerance: {elapsed:?}" + ); + } + + #[test] + fn preflight_blocks_the_spawn_when_the_endpoint_still_answers() { + // The tracked PID exited, but something else still serves the backend URL. + let result = preflight_before_respawn( + 14360, + identity(14360, Some(100)), + std::time::Duration::from_millis(50), + std::time::Duration::from_millis(10), + |_| ProcessProbe::Missing, + || Err("endpoint occupied".to_string()), + ); + + let error = result.expect_err("an answering endpoint must block the respawn"); + assert_eq!(error, "endpoint occupied"); + } + + #[test] + fn preflight_skips_the_endpoint_probe_when_the_pid_gate_fails() { + // The PID failure must short-circuit before the (expensive) endpoint probe runs. + let endpoint_called = std::cell::Cell::new(false); + let result = preflight_before_respawn( + 14360, + identity(14360, Some(100)), + std::time::Duration::from_millis(20), + std::time::Duration::from_millis(10), + |_| ProcessProbe::Alive { + created_at: Some(100), + }, + || { + endpoint_called.set(true); + Ok(()) + }, + ); + + assert!(result.is_err()); + assert!( + !endpoint_called.get(), + "the endpoint probe must not run once the PID gate already failed" + ); + } + + #[test] + fn preflight_for_a_first_managed_start_only_checks_the_endpoint() { + let ok = preflight_before_respawn( + 0, + None, + std::time::Duration::from_millis(50), + std::time::Duration::from_millis(10), + |_| panic!("no PID means nothing to probe"), + || Ok(()), + ); + assert!(ok.is_ok()); + + let blocked = preflight_before_respawn( + 0, + None, + std::time::Duration::from_millis(50), + std::time::Duration::from_millis(10), + |_| panic!("no PID means nothing to probe"), + || Err("endpoint occupied".to_string()), + ); + assert!(blocked.is_err()); + } + + #[test] + fn preflight_preserves_an_inconclusive_endpoint_error() { + let result = preflight_before_respawn( + 0, + None, + std::time::Duration::from_millis(50), + std::time::Duration::from_millis(10), + |_| panic!("there is no stopped PID to probe"), + || Err("DNS resolution timed out; endpoint availability is unknown".to_string()), + ); + assert_eq!( + result, + Err("DNS resolution timed out; endpoint availability is unknown".to_string()) ); } } diff --git a/src-tauri/src/backend/restart_strategy.rs b/src-tauri/src/backend/restart_strategy.rs index 670aed03..20236e82 100644 --- a/src-tauri/src/backend/restart_strategy.rs +++ b/src-tauri/src/backend/restart_strategy.rs @@ -12,14 +12,20 @@ pub(crate) enum GracefulRestartOutcome { RequestRejected, } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum RestartAction { + GracefulCompleted, + LaunchManagedReplacement, +} + pub(crate) fn compute_restart_strategy( is_windows: bool, packaged_mode: bool, - has_managed_child: bool, + has_managed_backend: bool, ) -> RestartStrategy { - if is_windows && packaged_mode && has_managed_child { + if is_windows && packaged_mode && has_managed_backend { RestartStrategy::ManagedSkipGraceful - } else if has_managed_child { + } else if has_managed_backend { RestartStrategy::ManagedWithGracefulFallback } else { RestartStrategy::UnmanagedWithGracefulProbe diff --git a/src-tauri/src/bridge/commands.rs b/src-tauri/src/bridge/commands.rs index c81eab97..8f5dfeaa 100644 --- a/src-tauri/src/bridge/commands.rs +++ b/src-tauri/src/bridge/commands.rs @@ -27,8 +27,8 @@ use crate::bridge::updater_types::{ }; use crate::{ append_desktop_log, restart_backend_flow, runtime_paths, shell_locale, tray, update_channel, - BackendBridgeResult, BackendBridgeState, BackendState, DesktopAuthBridgeResult, - DEFAULT_SHELL_LOCALE, + AtomicFlagGuard, BackendBridgeResult, BackendBridgeState, BackendState, + DesktopAuthBridgeResult, DEFAULT_SHELL_LOCALE, }; fn resolve_update_channel(app_handle: &AppHandle) -> update_channel::UpdateChannel { @@ -107,16 +107,27 @@ fn short_circuit_update_install( } } -fn has_managed_backend_child(state: &BackendState) -> bool { - match state.child.lock() { - Ok(guard) => guard.is_some(), - Err(_) => { - append_desktop_log( - "backend child lock poisoned while checking managed backend state; assuming no managed backend child", - ); - false - } +#[cfg(test)] +fn update_backend_state(managed: bool) -> BackendState { + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("reserve backend endpoint"); + let state = BackendState { + backend_url: format!("http://{}/", listener.local_addr().unwrap()), + ..BackendState::default() + }; + drop(listener); + if managed { + let mut child = Command::new(std::env::current_exe().expect("current test executable")) + .arg("--list") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("spawn managed backend child"); + state.record_spawned_identity(child.id()); + child.wait().expect("reap managed backend child"); + *state.child.lock().unwrap() = Some(child); } + state } #[cfg(test)] @@ -129,11 +140,13 @@ where InstallUpdate: FnOnce() -> Result<(), String>, RestartBackend: FnOnce() -> Result<(), String>, { + let state = update_backend_state(backend_was_stopped); run_native_update_install_with_validation( install_update, || Ok(()), restart_backend_after_failed_install, - backend_was_stopped, + &state, + true, ) } @@ -141,13 +154,28 @@ fn run_native_update_install_with_validation, - backend_was_stopped: bool, + state: &BackendState, + is_windows: bool, ) -> DesktopAppUpdateResult where InstallUpdate: FnOnce() -> Result<(), String>, ValidateInstall: FnOnce() -> Result<(), String>, RestartBackend: FnOnce() -> Result<(), String>, { + let backend_was_stopped = if is_windows { + match state.has_managed_backend() { + Ok(true) => { + if let Err(error) = state.stop_backend_before_update_install() { + return map_update_install_error(error); + } + true + } + Ok(false) => false, + Err(error) => return map_update_install_error(error), + } + } else { + false + }; let failure = match install_update() { Ok(()) => validate_install() .err() @@ -181,6 +209,8 @@ fn build_restart_backend_after_failed_install( "update install failed before exit, revalidating resources before restarting managed backend", ); let restart_plan = state.resolve_launch_plan(&app_handle)?; + // The shared launch path confirms process exit and endpoint availability again + // after the installation attempt, before creating any replacement. state.start_backend_process(&app_handle, &restart_plan)?; state.wait_for_backend(&restart_plan) } @@ -766,7 +796,17 @@ pub(crate) async fn desktop_bridge_install_app_update( AppUpdateProgress::stage("installing"), ); let state = app_handle.state::(); - let stop_managed_backend = cfg!(target_os = "windows") && has_managed_backend_child(&state); + let Some(_spawn_guard) = AtomicFlagGuard::try_set(&state.is_spawning) else { + return map_update_install_error("Backend action already in progress."); + }; + let stop_managed_backend = if cfg!(target_os = "windows") { + match state.has_managed_backend() { + Ok(managed) => managed, + Err(error) => return map_update_install_error(error), + } + } else { + false + }; let restart_backend_after_failed_install = if stop_managed_backend { match state.resolve_launch_plan(&app_handle) { Ok(_) => {} @@ -784,17 +824,6 @@ pub(crate) async fn desktop_bridge_install_app_update( None }; - let backend_was_stopped = if stop_managed_backend { - if let Err(error) = state.stop_backend() { - return map_update_install_error(format!( - "Failed to stop backend before Windows update install: {error}" - )); - } - true - } else { - false - }; - let expected_version = update.version.clone(); let validation_app_handle = app_handle.clone(); let result = run_native_update_install_with_validation( @@ -806,7 +835,8 @@ pub(crate) async fn desktop_bridge_install_app_update( ) }, restart_backend_after_failed_install, - backend_was_stopped, + &state, + cfg!(target_os = "windows"), ); if result.ok { app_handle.request_restart(); @@ -938,6 +968,194 @@ mod tests { assert_eq!(result, map_update_install_ok()); } + #[test] + fn windows_update_install_does_not_proceed_while_an_untracked_endpoint_answers() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind surviving backend"); + let state = BackendState { + backend_url: format!("http://{}/", listener.local_addr().unwrap()), + ..BackendState::default() + }; + let mut child = Command::new(std::env::current_exe().expect("current test executable")) + .arg("--list") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("spawn stale backend child"); + state.record_spawned_identity(child.id()); + child.wait().expect("wait for stale backend child"); + *state.child.lock().unwrap() = Some(child); + let events = RefCell::new(Vec::new()); + + for _ in 0..2 { + let result = run_native_update_install_with_validation( + || { + events.borrow_mut().push("install"); + Ok(()) + }, + || { + events.borrow_mut().push("validate"); + Ok(()) + }, + Some(|| { + events.borrow_mut().push("recover"); + Ok(()) + }), + &state, + true, + ); + + assert!( + !result.ok, + "a surviving listener must block Windows installation" + ); + assert!(result + .reason + .as_deref() + .unwrap() + .contains("already answering")); + assert!( + events.borrow().is_empty(), + "installer and recovery must not run" + ); + assert!(state.child.lock().unwrap().is_none()); + assert_ne!( + state + .restart_stop_pid + .load(std::sync::atomic::Ordering::Acquire), + 0, + "a rejected preparation must retain the stop target" + ); + } + } + + #[test] + fn windows_update_install_keeps_ownership_after_the_child_slot_is_cleared() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind surviving backend"); + let state = BackendState { + backend_url: format!("http://{}/", listener.local_addr().unwrap()), + ..BackendState::default() + }; + let mut child = Command::new(std::env::current_exe().expect("current test executable")) + .arg("--list") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("spawn previously managed backend child"); + state.record_spawned_identity(child.id()); + child.wait().expect("reap previously managed backend child"); + drop(child); + assert!(state.child.lock().unwrap().is_none()); + assert_eq!( + state + .restart_stop_pid + .load(std::sync::atomic::Ordering::Acquire), + 0 + ); + let events = RefCell::new(Vec::new()); + + let result = run_native_update_install_with_validation( + || { + events.borrow_mut().push("install"); + Ok(()) + }, + || { + events.borrow_mut().push("validate"); + Ok(()) + }, + Some(|| { + events.borrow_mut().push("recover"); + Ok(()) + }), + &state, + true, + ); + + assert!( + !result.ok, + "a surviving endpoint of a previously managed backend must block installation" + ); + assert!(result + .reason + .as_deref() + .unwrap() + .contains("already answering")); + assert!( + events.borrow().is_empty(), + "installer and recovery must not run" + ); + } + + #[test] + fn windows_update_install_does_not_manage_an_external_only_backend() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind external backend"); + let state = BackendState { + backend_url: format!("http://{}/", listener.local_addr().unwrap()), + ..BackendState::default() + }; + let events = RefCell::new(Vec::new()); + + let result = run_native_update_install_with_validation( + || { + events.borrow_mut().push("install"); + Err("installer failed".to_string()) + }, + || { + events.borrow_mut().push("validate"); + Ok(()) + }, + Some(|| { + events.borrow_mut().push("recover"); + Ok(()) + }), + &state, + true, + ); + + assert_eq!( + result, + map_update_install_error("Failed to install update: installer failed") + ); + assert_eq!(*events.borrow(), vec!["install"]); + assert!(state.last_recorded_pid().is_none()); + } + + #[test] + fn run_native_update_install_prepares_before_installing_and_validating() { + let state = update_backend_state(true); + let events = RefCell::new(Vec::new()); + let result = run_native_update_install_with_validation( + || { + assert!( + state.child.lock().unwrap().is_none(), + "the managed child must be cleared before installation" + ); + assert_eq!( + state + .restart_stop_pid + .load(std::sync::atomic::Ordering::Acquire), + 0, + "the stop target must be confirmed before installation" + ); + events.borrow_mut().push("install"); + Ok(()) + }, + || { + events.borrow_mut().push("validate"); + Ok(()) + }, + Some(|| { + events.borrow_mut().push("recover"); + Ok(()) + }), + &state, + true, + ); + assert!(result.ok); + assert_eq!(*events.borrow(), vec!["install", "validate"]); + } + #[test] fn run_native_update_install_skips_restart_when_backend_was_not_stopped() { let mut restart_called = false; @@ -1011,6 +1229,7 @@ mod tests { #[test] fn run_native_update_install_rejects_post_install_validation_failures() { + let state = update_backend_state(true); let events = Rc::new(RefCell::new(Vec::new())); let restart_events = Rc::clone(&events); @@ -1021,6 +1240,7 @@ mod tests { restart_events.borrow_mut().push("restart"); Ok(()) }), + &state, true, ); @@ -1034,7 +1254,7 @@ mod tests { } #[test] - fn has_managed_backend_child_returns_false_when_lock_is_poisoned() { + fn windows_update_install_refuses_a_poisoned_backend_ownership_lock() { let state = BackendState::default(); let _ = std::panic::catch_unwind(AssertUnwindSafe(|| { let _guard = state @@ -1044,6 +1264,20 @@ mod tests { panic!("poison backend child lock"); })); - assert!(!has_managed_backend_child(&state)); + let installed = RefCell::new(false); + let result = run_native_update_install_with_validation( + || { + *installed.borrow_mut() = true; + Ok(()) + }, + || Ok(()), + None:: Result<(), String>>, + &state, + true, + ); + + assert!(!result.ok); + assert!(result.reason.as_deref().unwrap().contains("lock poisoned")); + assert!(!*installed.borrow()); } } diff --git a/src-tauri/src/process_control.rs b/src-tauri/src/process_control.rs index 43149372..e7742f24 100644 --- a/src-tauri/src/process_control.rs +++ b/src-tauri/src/process_control.rs @@ -12,17 +12,42 @@ use std::{ use windows_sys::Win32::{ Foundation::{ CloseHandle, ERROR_ACCESS_DENIED, ERROR_INVALID_PARAMETER, ERROR_NOT_FOUND, - ERROR_NO_MORE_FILES, HANDLE, INVALID_HANDLE_VALUE, + ERROR_NO_MORE_FILES, FILETIME, HANDLE, INVALID_HANDLE_VALUE, STILL_ACTIVE, }, System::{ Diagnostics::ToolHelp::{ CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W, TH32CS_SNAPPROCESS, }, - Threading::{OpenProcess, TerminateProcess, PROCESS_TERMINATE}, + Threading::{ + GetExitCodeProcess, GetProcessTimes, OpenProcess, TerminateProcess, + PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_TERMINATE, + }, }, }; +/// Identity of a process this shell spawned and still believes it owns. +/// +/// `created_at` is the platform creation timestamp when the platform exposes one. +/// Comparing it across probes is what keeps a recycled PID from being mistaken for the +/// backend that was captured before a stop. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct ProcessIdentity { + pub(crate) pid: u32, + pub(crate) created_at: Option, +} + +/// Result of a single liveness probe for one PID. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ProcessProbe { + /// No running process owns this PID. + Missing, + /// A running process owns this PID; `created_at` is set when the platform reports it. + Alive { created_at: Option }, + /// The platform refused to answer. Callers must not read this as proof of exit. + Unknown, +} + const FORCE_STOP_WAIT_MIN_MS: u64 = 200; #[cfg(target_os = "windows")] const WINDOWS_GRACEFUL_STOP_NONZERO_WAIT_MS: u64 = 350; @@ -213,6 +238,232 @@ fn is_process_snapshot_end_error(error: &io::Error) -> bool { code as u32 == ERROR_NO_MORE_FILES } +/// Probe a PID for liveness on Windows without trusting any `Child` handle. +/// +/// `OpenProcess` fails with `ERROR_INVALID_PARAMETER` only when the PID is truly gone, +/// so it separates "no such process" from "the process exists but denies us access". +/// A live process is additionally stamped with its creation time, which is what makes +/// PID recycling detectable: a recycled PID would come back with a different stamp. +#[cfg(target_os = "windows")] +fn probe_pid_windows(pid: u32) -> ProcessProbe { + if pid == 0 { + return ProcessProbe::Missing; + } + + let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) }; + if handle.is_null() { + let error = io::Error::last_os_error(); + return match error.raw_os_error().map(|code| code as u32) { + Some(ERROR_INVALID_PARAMETER) => ProcessProbe::Missing, + // The PID still resolves but we may not query it: treat as alive so a + // permission problem can never be mistaken for a clean exit. + Some(ERROR_ACCESS_DENIED) => ProcessProbe::Alive { created_at: None }, + _ => ProcessProbe::Unknown, + }; + } + + let mut exit_code: u32 = 0; + let exit_code_ok = unsafe { GetExitCodeProcess(handle, &mut exit_code) } != 0; + if exit_code_ok && exit_code != STILL_ACTIVE as u32 { + close_handle(handle); + return ProcessProbe::Missing; + } + + let created_at = process_creation_time(handle); + close_handle(handle); + + if !exit_code_ok { + return ProcessProbe::Unknown; + } + + ProcessProbe::Alive { created_at } +} + +/// Read a process creation timestamp in 100 ns units, matching `FILETIME` semantics. +#[cfg(target_os = "windows")] +fn process_creation_time(handle: HANDLE) -> Option { + let mut creation = FILETIME { + dwLowDateTime: 0, + dwHighDateTime: 0, + }; + let mut exit = creation; + let mut kernel = creation; + let mut user = creation; + let ok = + unsafe { GetProcessTimes(handle, &mut creation, &mut exit, &mut kernel, &mut user) } != 0; + if !ok { + return None; + } + + Some((u64::from(creation.dwHighDateTime) << 32) | u64::from(creation.dwLowDateTime)) +} + +/// Probe a PID for liveness on Unix via the `/proc` filesystem, which also exposes the +/// process start time needed for recycling detection. +#[cfg(not(target_os = "windows"))] +fn probe_pid_unix(pid: u32, proc_root: &std::path::Path) -> ProcessProbe { + use std::fs; + + if pid == 0 { + return ProcessProbe::Missing; + } + + let proc_dir = proc_root.join(pid.to_string()); + match fs::metadata(&proc_dir) { + Ok(_) => {} + Err(error) if error.kind() == io::ErrorKind::NotFound => { + return match fs::metadata(proc_root.join("self")) { + Ok(_) => ProcessProbe::Missing, + Err(error) if error.kind() == io::ErrorKind::NotFound => { + // No procfs: honour POSIX signal 0 as the liveness test instead. + probe_pid_with_signal(pid) + } + Err(_) => ProcessProbe::Unknown, + }; + } + // An unreadable entry does not prove that the process has exited. + Err(_) => return ProcessProbe::Unknown, + } + + let stat = match fs::read_to_string(proc_dir.join("stat")) { + Ok(stat) => stat, + Err(error) if error.kind() == io::ErrorKind::NotFound => return ProcessProbe::Missing, + Err(_) => return ProcessProbe::Unknown, + }; + + // A zombie or dead task still holds a /proc entry but no longer runs, so treat both + // as exited. Field 3 of /proc//stat is the state letter, after the "(name)" tail. + let state = stat + .rsplit_once(')') + .and_then(|(_, trailer)| trailer.trim_start().chars().next()); + if matches!(state, Some('Z') | Some('X') | Some('x')) { + return ProcessProbe::Missing; + } + + let created_at = stat + .rsplit_once(')') + .and_then(|(_, trailer)| trailer.split_whitespace().nth(19)) + .and_then(|value| value.parse::().ok()); + + ProcessProbe::Alive { created_at } +} + +#[cfg(not(target_os = "windows"))] +fn probe_pid_with_signal(pid: u32) -> ProcessProbe { + // `SystemTime` has no per-process creation stamp, so recycling stays undetectable + // on exotic platforms; falling back to `Unknown` would be worse than a plain probe. + // Signal 0 performs the permission and existence checks without delivering a signal. + let output = std::process::Command::new("kill") + .args(["-0", &pid.to_string()]) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .stdin(Stdio::null()) + .output(); + match output { + Ok(output) if output.status.success() => ProcessProbe::Alive { created_at: None }, + Ok(output) => { + let stderr = String::from_utf8_lossy(&output.stderr).to_lowercase(); + if stderr.contains("no such process") { + ProcessProbe::Missing + } else if stderr.contains("permitted") || stderr.contains("permission denied") { + // The PID exists but belongs to another user, so it is still alive. + ProcessProbe::Alive { created_at: None } + } else { + // The `kill` invocation itself failed, which says nothing about the PID. + // Reporting Unknown makes the caller refuse the restart instead of + // assuming a clean exit. + ProcessProbe::Unknown + } + } + Err(_) => ProcessProbe::Unknown, + } +} + +/// Probe one PID for liveness. Never blocks longer than a couple of system calls. +pub(crate) fn probe_process(pid: u32) -> ProcessProbe { + #[cfg(target_os = "windows")] + { + probe_pid_windows(pid) + } + #[cfg(not(target_os = "windows"))] + { + probe_pid_unix(pid, std::path::Path::new("/proc")) + } +} + +fn probe_matches_identity(probe: ProcessProbe, identity: ProcessIdentity) -> bool { + match probe { + ProcessProbe::Missing => false, + ProcessProbe::Unknown => true, + ProcessProbe::Alive { created_at } => match (identity.created_at, created_at) { + (Some(expected), Some(actual)) => expected == actual, + // Without a timestamp on either side the PID alone is all we have, so a + // live process on that PID must be treated as the old backend. + _ => true, + }, + } +} + +/// Capture the identity of a still-running process, so later probes can tell the +/// original process apart from a recycled PID. +pub(crate) fn capture_process_identity(pid: u32) -> ProcessIdentity { + let created_at = match probe_process(pid) { + ProcessProbe::Alive { created_at } => created_at, + ProcessProbe::Missing | ProcessProbe::Unknown => None, + }; + ProcessIdentity { pid, created_at } +} + +/// Outcome of waiting for a previously spawned process to disappear. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ProcessExitOutcome { + /// The PID is gone, or it now belongs to a different process. + Exited, + /// The PID still answers and still matches the captured identity. + StillRunning, +} + +/// Poll until the captured process is gone or `timeout` elapses. +/// +/// This deliberately ignores the `Child` handle. `Child::try_wait` reports `Some` for a +/// handle whose process is long gone, which is exactly how a restart used to conclude +/// "backend stopped" while an unrelated process still held the listening port. +pub(crate) fn wait_for_process_identity_exit( + identity: ProcessIdentity, + timeout: Duration, + poll_interval: Duration, +) -> ProcessExitOutcome { + wait_for_process_identity_exit_with(identity, timeout, poll_interval, probe_process) +} + +/// Same as [`wait_for_process_identity_exit`] with an injectable probe, so the timeout and +/// recycling rules can be exercised without spawning real processes. +pub(crate) fn wait_for_process_identity_exit_with( + identity: ProcessIdentity, + timeout: Duration, + poll_interval: Duration, + probe: F, +) -> ProcessExitOutcome +where + F: Fn(u32) -> ProcessProbe, +{ + let start = Instant::now(); + let poll_interval = poll_interval.max(Duration::from_millis(10)); + + loop { + if !probe_matches_identity(probe(identity.pid), identity) { + return ProcessExitOutcome::Exited; + } + + if start.elapsed() >= timeout { + return ProcessExitOutcome::StillRunning; + } + + let remaining = timeout.saturating_sub(start.elapsed()); + thread::sleep(poll_interval.min(remaining)); + } +} + #[cfg(target_os = "windows")] fn terminate_process_by_pid(pid: u32) -> io::Result<()> { let handle = unsafe { OpenProcess(PROCESS_TERMINATE, 0, pid) }; @@ -454,4 +705,199 @@ mod tests { assert_eq!(snapshot.len(), 1); assert!(snapshot[0].contains("shorten graceful wait")); } + + fn test_identity(pid: u32, created_at: Option) -> ProcessIdentity { + ProcessIdentity { pid, created_at } + } + + #[test] + fn missing_probe_never_matches_a_identity() { + assert!(!probe_matches_identity( + ProcessProbe::Missing, + test_identity(42, Some(7)) + )); + assert!(!probe_matches_identity( + ProcessProbe::Missing, + test_identity(42, None) + )); + } + + #[test] + fn alive_probe_matches_only_when_the_creation_stamp_agrees() { + assert!(probe_matches_identity( + ProcessProbe::Alive { + created_at: Some(7) + }, + test_identity(42, Some(7)) + )); + assert!( + !probe_matches_identity( + ProcessProbe::Alive { + created_at: Some(8) + }, + test_identity(42, Some(7)) + ), + "a different creation stamp means the PID was recycled" + ); + assert!( + probe_matches_identity( + ProcessProbe::Alive { created_at: None }, + test_identity(42, None) + ), + "without timestamps the PID alone is the only evidence left" + ); + assert!( + probe_matches_identity( + ProcessProbe::Alive { + created_at: Some(7) + }, + test_identity(42, None) + ), + "an unknown expected stamp must not clear a live PID" + ); + } + + #[test] + fn unknown_probe_is_treated_as_still_running() { + assert!( + probe_matches_identity(ProcessProbe::Unknown, test_identity(42, Some(7))), + "a probe the OS refused to answer must never be read as proof of exit" + ); + } + + #[test] + fn wait_returns_exited_as_soon_as_the_probe_reports_missing() { + let outcome = wait_for_process_identity_exit_with( + test_identity(42, Some(7)), + Duration::from_millis(1_000), + Duration::from_millis(10), + |_| ProcessProbe::Missing, + ); + + assert_eq!(outcome, ProcessExitOutcome::Exited); + } + + #[test] + fn wait_returns_still_running_after_the_timeout_elapses() { + let start = Instant::now(); + let outcome = wait_for_process_identity_exit_with( + test_identity(42, Some(7)), + Duration::from_millis(50), + Duration::from_millis(10), + |_| ProcessProbe::Alive { + created_at: Some(7), + }, + ); + + assert_eq!(outcome, ProcessExitOutcome::StillRunning); + assert!( + start.elapsed() >= Duration::from_millis(50), + "the timeout must actually be spent before giving up" + ); + } + + #[test] + fn wait_keeps_polling_until_a_late_exit_is_observed() { + let remaining = Mutex::new(3_u8); + let outcome = wait_for_process_identity_exit_with( + test_identity(42, Some(7)), + Duration::from_millis(2_000), + Duration::from_millis(10), + |_| { + let mut remaining = remaining.lock().expect("lock remaining"); + if *remaining == 0 { + ProcessProbe::Missing + } else { + *remaining -= 1; + ProcessProbe::Alive { + created_at: Some(7), + } + } + }, + ); + + assert_eq!(outcome, ProcessExitOutcome::Exited); + } + + #[test] + fn wait_treats_the_current_process_as_alive() { + // Sanity check of the real probe: this test process is definitely running, so a + // zero timeout must report it as still there rather than missing. + let identity = capture_process_identity(std::process::id()); + let outcome = + wait_for_process_identity_exit(identity, Duration::ZERO, Duration::from_millis(10)); + assert_eq!(outcome, ProcessExitOutcome::StillRunning); + } + + #[test] + fn wait_reports_an_impossible_pid_as_exited() { + // PID 0 is never a real user process on Windows, and the Unix probe rejects it too. + let identity = test_identity(0, None); + let outcome = wait_for_process_identity_exit( + identity, + Duration::from_millis(50), + Duration::from_millis(10), + ); + assert_eq!(outcome, ProcessExitOutcome::Exited); + } + + #[test] + #[cfg(not(target_os = "windows"))] + fn signal_probe_reports_a_missing_pid_as_exited() { + // Reap a real child so the PID is valid but no longer exists. An out-of-range + // PID can be rejected as invalid input by kill rather than reported as missing. + let mut child = Command::new("sh") + .args(["-c", "exit 0"]) + .spawn() + .expect("spawn short-lived child"); + let pid = child.id(); + assert!(child.wait().expect("reap short-lived child").success()); + + assert_eq!(probe_pid_with_signal(pid), ProcessProbe::Missing); + } + + #[test] + #[cfg(unix)] + fn proc_probe_keeps_metadata_errors_inconclusive() { + let proc_root = tempfile::tempdir().expect("create proc fixture"); + std::fs::create_dir(proc_root.path().join("self")).expect("create self entry"); + let pid_entry = proc_root.path().join("42"); + std::os::unix::fs::symlink("42", &pid_entry).expect("create symlink loop"); + assert!(std::fs::metadata(pid_entry).is_err()); + + assert_eq!(probe_pid_unix(42, proc_root.path()), ProcessProbe::Unknown); + } + + #[test] + #[cfg(unix)] + fn proc_probe_keeps_procfs_detection_errors_inconclusive() { + let proc_root = tempfile::tempdir().expect("create proc fixture"); + std::os::unix::fs::symlink("self", proc_root.path().join("self")) + .expect("create self symlink loop"); + + assert_eq!( + probe_pid_unix(std::process::id(), proc_root.path()), + ProcessProbe::Unknown + ); + } + + #[test] + #[cfg(unix)] + fn proc_probe_reports_a_missing_entry_when_procfs_is_available() { + let proc_root = tempfile::tempdir().expect("create proc fixture"); + std::fs::create_dir(proc_root.path().join("self")).expect("create self entry"); + + assert_eq!(probe_pid_unix(42, proc_root.path()), ProcessProbe::Missing); + } + + #[test] + #[cfg(unix)] + fn proc_probe_uses_signal_when_procfs_is_absent() { + let fixture = tempfile::tempdir().expect("create absent proc fixture"); + + assert_eq!( + probe_pid_unix(std::process::id(), &fixture.path().join("absent")), + ProcessProbe::Alive { created_at: None } + ); + } }