//! Single instance: forwarding a second start to the running app, and //! claiming the rendezvous file for this one. //! //! A normal start (no `--control`) looks for a running Lutra through the //! rendezvous file in the app data directory. If one answers and accepts //! its token, the start forwards its path (a folder becomes the project, a //! file opens in a tab), brings that window to the front and exits. //! Otherwise it starts, serves a token-protected listener on a free port //! of `127.0.0.1` and writes the rendezvous file, replacing a stale one. //! //! A start with `--control PORT` is a development or automation instance: //! it skips all of this, so several of them can run side by side, unless //! `LUTRA_RENDEZVOUS_DIR` names a rendezvous directory for it. use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::Duration; use lutra_control::client::{self, Unavailable}; use lutra_control::rendezvous::{self, Instance}; use crate::args::Args; use crate::host::Host; /// How long a second start waits for the running instance to answer. const PROBE_TIMEOUT: Duration = Duration::from_secs(5); /// The rendezvous directory this start uses, `None` if it does not take /// part in the single instance (see the module docs). pub fn rendezvous_dir(args: &Args) -> Option { let explicit = std::env::var_os(rendezvous::DIR_ENV).is_some_and(|v| !v.is_empty()); if args.control.is_some() && !explicit { return None; } rendezvous::dir() } /// Forwards `path` to a running instance found through `dir`. /// /// # Returns /// `Ok(true)` if an instance took the request (this process should exit), /// `Ok(false)` if none is running or its file is stale. /// /// # Errors /// A message if a running instance refused to open the path. pub fn forward(dir: &Path, path: Option<&Path>) -> Result { let mut client = match client::connect_live(dir, PROBE_TIMEOUT) { Ok((_, client)) => client, Err(Unavailable::Missing | Unavailable::Stale(_)) => return Ok(false), }; if let Some(path) = path { let path = std::path::absolute(path).map_err(|e| e.to_string())?; let opened = if path.is_dir() { client.open_folder(&path).map(|_| ()) } else { client.open_file(&path).map(|_| ()) }; opened.map_err(|e| format!("the running Lutra cannot open {}: {e}", path.display()))?; } let _ = client.focus(); Ok(true) } /// This process's claim on the rendezvous directory. #[derive(Debug)] pub struct Claim { /// The directory. dir: PathBuf, /// The token written there. token: String, } impl Claim { /// Serves the token-protected listener for `host` and writes the /// rendezvous file in `dir`, replacing any file there. /// /// # Errors /// A message if no token can be made, the port cannot be bound or the /// file cannot be written. pub fn take(dir: &Path, host: &Arc) -> Result { let token = rendezvous::new_token().map_err(|e| format!("cannot create a token: {e}"))?; let server = lutra_control::start_with_token(0, host.clone(), &token) .map_err(|e| format!("cannot serve the single-instance listener: {e}"))?; let instance = Instance { port: server.local_addr().port(), token: token.clone(), pid: std::process::id(), version: env!("CARGO_PKG_VERSION").to_string(), }; rendezvous::write(dir, &instance) .map_err(|e| format!("cannot write {}: {e}", rendezvous::path(dir).display()))?; Ok(Self { dir: dir.to_path_buf(), token, }) } /// Removes the rendezvous file if it is still this process's. Called /// when the app exits; a failure only leaves a stale file, which the /// next start replaces, so it is ignored. pub fn release(&self) { let _ = rendezvous::remove_if_ours(&self.dir, &self.token); } } #[cfg(test)] mod tests { use super::*; #[test] fn control_instances_skip_the_single_instance_by_default() { if std::env::var_os(rendezvous::DIR_ENV).is_some() { return; } let dev = Args { control: Some(7937), ..Args::default() }; assert_eq!(rendezvous_dir(&dev), None); assert_eq!(rendezvous_dir(&Args::default()), rendezvous::dir()); } #[test] fn nothing_to_forward_to_without_a_file() { let dir = tempfile::tempdir().unwrap(); assert_eq!(forward(dir.path(), None), Ok(false)); rendezvous::write( dir.path(), &Instance { port: 1, token: "t".into(), pid: 1, version: "0".into(), }, ) .unwrap(); assert_eq!(forward(dir.path(), None), Ok(false), "stale file"); } }