//! Starts `tursodb --sync-server` as a child process. use anyhow::{Context, Result, bail}; use std::net::TcpListener; use std::path::{Path, PathBuf}; use std::process::{Child, Command, Stdio}; use std::time::{Duration, Instant}; const START_ATTEMPTS: u32 = 5; const READY_TIMEOUT: Duration = Duration::from_secs(10); /// Ports of the servers that run in this process. Tests run in parallel: without this set, /// two of them can take the same free port, and one test then talks to the server of the /// other test. static PORTS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); /// A running sync server. The process is killed on drop. pub struct SyncServer { child: Child, port: u16, pub log_path: PathBuf, } impl SyncServer { /// Starts a server for the database at `db_path`. The server writes its log to /// `.log`. pub fn start(tursodb: &Path, db_path: &Path) -> Result { let log_path = db_path.with_extension("log"); let mut last_failure = String::new(); for attempt in 1..=START_ATTEMPTS { // Another process can take the port between this check and the server's bind. The // server then exits, and the next attempt takes another port. let port = TcpListener::bind(("127.0.0.1", 0))?.local_addr()?.port(); { let mut ports = PORTS.lock().unwrap(); if ports.contains(&port) { last_failure = format!("attempt {attempt}: port {port} is in use"); continue; } ports.push(port); } let log = std::fs::File::create(&log_path)?; let mut child = Command::new(tursodb) .arg(db_path) .arg("--sync-server") .arg(format!("127.0.0.1:{port}")) .env("RUST_LOG", std::env::var("RUST_LOG").unwrap_or_default()) .stdin(Stdio::null()) .stdout(log.try_clone()?) .stderr(log) .spawn() .with_context(|| format!("failed to start {}", tursodb.display()))?; let deadline = Instant::now() + READY_TIMEOUT; loop { // An HTTP response, not only a connection: when the server fails to bind, // the port can belong to another socket of this process. if crate::http::request(port, "GET", "/", &[], &[], Duration::from_secs(1)).is_ok() && child.try_wait()?.is_none() { return Ok(Self { child, port, log_path, }); } if let Some(status) = child.try_wait()? { PORTS.lock().unwrap().retain(|p| *p != port); last_failure = format!("attempt {attempt}: server exited with {status}"); break; } if Instant::now() >= deadline { PORTS.lock().unwrap().retain(|p| *p != port); let _ = child.kill(); let _ = child.wait(); last_failure = format!("attempt {attempt}: server did not listen in time"); break; } std::thread::sleep(Duration::from_millis(20)); } } bail!( "sync server failed to start: {last_failure} (log: {})", log_path.display() ) } pub fn port(&self) -> u16 { self.port } pub fn url(&self) -> String { format!("http://127.0.0.1:{}", self.port) } } impl Drop for SyncServer { fn drop(&mut self) { let _ = self.child.kill(); let _ = self.child.wait(); PORTS.lock().unwrap().retain(|p| *p != self.port); } }