diff --git a/crates/ledger-cli/src/main.rs b/crates/ledger-cli/src/main.rs index ad72abe7..59540690 100644 --- a/crates/ledger-cli/src/main.rs +++ b/crates/ledger-cli/src/main.rs @@ -473,6 +473,10 @@ fn owner_passphrase(root: &ledger_store::root::Root) -> i32 { /// `wanderbooks server`: the books server for the data root, on its /// local sockets (plan 3.9). The host starts it. fn run_server(args: Vec) -> i32 { + // Whoever started the server, it holds none of that program's pipes or + // sockets: a server still closing after its starter has gone must not + // keep them open. + ledger_host::host::close_stray_descriptors(); match ledger_mcp::local::run("wanderbooks server", args) { Ok(()) => 0, Err(e) => match e.downcast_ref::() { diff --git a/crates/ledger-host/src/app_server.rs b/crates/ledger-host/src/app_server.rs index dee59f23..2727d5ea 100644 --- a/crates/ledger-host/src/app_server.rs +++ b/crates/ledger-host/src/app_server.rs @@ -80,6 +80,7 @@ use crate::host::{SERVER_LOG, children_executable, open_log}; use crate::opener::{host_lock_held, server_lock_held}; use ledger_mcp::admin::{self, CloseOutcome, OpenOutcome, Request, Response}; +pub use ledger_mcp::local::StartedBy; use ledger_store::root::Root; use std::io::BufRead; use std::path::{Path, PathBuf}; @@ -102,6 +103,19 @@ pub const READY_WAIT: Duration = Duration::from_secs(300); /// and running calls finish first. pub const STOP_WAIT: Duration = Duration::from_secs(90); +/// How long another program holding the books, while this server has not +/// taken them, is seen before this one is taken to have lost the race. +const BEATEN_AFTER: Duration = Duration::from_millis(300); + +/// What [`AppServer::wait_ready_unless_beaten`] came to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Waited { + /// The server is ready. + Ready, + /// Another program took the books first. + Beaten, +} + /// What a refused start says (INVARIANT 1). pub const ANOTHER_HAS_THEM: &str = "Another program has these books open: another Wanderbooks window, `wanderbooks serve`, or a books server that is still finishing its last backup. Close it (`wanderbooks close` closes the books) or wait a moment, then start Wanderbooks again."; @@ -217,7 +231,7 @@ pub struct AppServer { /// now: no host holds the root, a server does, and its admin socket /// answers (INVARIANT 7). pub fn the_apps_server_runs(run: &Path) -> bool { - !host_lock_held(run) && server_lock_held(run) && crate::opener::admin_answers(run) == Ok(true) + crate::opener::what_holds(run) == Ok(crate::opener::Holder::App) } impl AppServer { @@ -229,6 +243,38 @@ impl AppServer { Self::start_in(&children_executable(), root, open, |_| {}) } + /// The server of a command that does its own work with nothing else + /// running (commands.rs `reach`): the same server, started clean as a + /// host starts it (INVARIANT 13), saying it is a command's. + pub fn start_for_command( + root: Option<&Path>, + open: &[String], + knobs: &crate::knobs::Knobs, + ) -> Result { + let d = crate::knobs::Knobs::default(); + Self::start_as( + &children_executable(), + root, + open, + StartedBy::Command, + |command| { + // The timings a test shortened, as the host passes them on. + for (flag, now, default) in [ + ("--backup-quiet", knobs.backup_quiet, d.backup_quiet), + ("--drill-first", knobs.drill_first, d.drill_first), + ("--start-delay", knobs.server_delay, d.server_delay), + ] { + if now != default { + command.arg(flag).arg(now.as_millis().to_string()); + } + } + if knobs.timer_hold { + command.arg("--timer-hold"); + } + }, + ) + } + /// [`AppServer::start`] from the program `exe`, `configure` having the /// last word on its command (tests give it an environment of its own). pub fn start_in( @@ -236,6 +282,19 @@ impl AppServer { root: Option<&Path>, open: &[String], configure: impl FnOnce(&mut Command), + ) -> Result { + Self::start_as(exe, root, open, StartedBy::App, configure) + } + + /// [`AppServer::start_in`] for a server started `by` the app or a + /// command, which it says of itself (`--started-by`, INVARIANT 13). + /// A command's is started clean (INVARIANT 13). + pub fn start_as( + exe: &Path, + root: Option<&Path>, + open: &[String], + by: StartedBy, + configure: impl FnOnce(&mut Command), ) -> Result { let found = Root::find(root).map_err(|e| e.to_string())?; let run = found.run_dir().map_err(|e| e.to_string())?; @@ -259,7 +318,20 @@ impl AppServer { command.process_group(0); } command.arg("server"); - if let Some(root) = root { + command.arg("--started-by").arg(by.flag()); + if by == StartedBy::Command { + // Nothing of the invoker's reaches a server that may outlive + // the command (INVARIANT 13): the host's environment, and a + // folder of its own to stand in (the root's absolute path + // goes on, as the host's does). Its descriptors are closed by + // the server itself at its start. + command.arg("--root").arg(found.path()); + crate::start::clean_environment(&mut command)?; + #[cfg(unix)] + command.current_dir("/"); + #[cfg(windows)] + command.current_dir(&run); + } else if let Some(root) = root { command.arg("--root").arg(root); } command.arg("--open").arg(open_argument(open)); @@ -364,6 +436,50 @@ impl AppServer { } } + /// Wait for the server to be ready, up to `within`, but not for + /// another program that took the books first: if, while this server + /// is not ready, a host or another server holds them (a command racing + /// the app's start, or `serve`'s), this one has lost the race and the + /// caller is to join what runs (commands.rs `reach`). Seen for as long + /// as [`BEATEN_AFTER`], so the moment between this server taking the + /// lock and saying so is not taken for losing. + pub fn wait_ready_unless_beaten(&self, within: Duration) -> Result { + let deadline = Instant::now() + within; + let mut beaten_since: Option = None; + loop { + let slice = Duration::from_millis(50).min( + deadline + .checked_duration_since(Instant::now()) + .unwrap_or_default(), + ); + match self.wait_ready(slice) { + Ok(()) => return Ok(Waited::Ready), + Err(why) if self.exited().is_some() => return Err(why), + Err(why) => { + if Instant::now() >= deadline { + return Err(why); + } + } + } + if self.another_holds() { + let since = *beaten_since.get_or_insert_with(Instant::now); + if since.elapsed() >= BEATEN_AFTER { + return Ok(Waited::Beaten); + } + } else { + beaten_since = None; + } + } + } + + /// Whether a host, or a server that is not this one, holds the books. + fn another_holds(&self) -> bool { + host_lock_held(&self.run) + || (server_lock_held(&self.run) + && ledger_mcp::local::read_server_info(&self.run) + .is_none_or(|info| info.pid != self.pid)) + } + /// Whether the server has said it is ready (and is still there). pub fn is_ready(&self) -> bool { matches!(&*self.shared.phase(), Phase::Ready) diff --git a/crates/ledger-host/src/bridge.rs b/crates/ledger-host/src/bridge.rs index 6cda67f8..ae9486f9 100644 --- a/crates/ledger-host/src/bridge.rs +++ b/crates/ledger-host/src/bridge.rs @@ -119,6 +119,15 @@ fn opening_words(book: &str) -> String { ) } +/// What the agent is told when a command of the owner's has the books for +/// a moment (a server of its own, for the length of its work): the app is +/// not running, and it is not that either. +fn command_words(book: &str) -> String { + format!( + "A wanderbooks command has the books for a moment: {book} can be reached in a moment. Try again shortly." + ) +} + /// What the agent is told when the app runs but the company is not open /// in it (INVARIANT 12). fn not_open_words(book: &str) -> String { @@ -1106,7 +1115,19 @@ impl Bridge { let mut epoch = 0u64; loop { if matches!(&*self.link.borrow(), Link::Opening) { - match self.socket_is_ours() { + // What holds the books is read before a session is tried + // (opener.rs INVARIANT 6a): a command's server, or one + // that is closing, is not the app, whatever its socket + // answers. + let held = + crate::opener::what_holds(&run_dir).unwrap_or(crate::opener::Holder::Nothing); + let owner_check = match held { + crate::opener::Holder::Command | crate::opener::Holder::Closing => { + Err(Owner::Unreachable) + } + _ => self.socket_is_ours(), + }; + match owner_check { Err(Owner::Other(why)) => { self.link.send_replace(Link::Failed(why)); return; @@ -1114,10 +1135,12 @@ impl Bridge { Err(Owner::Unreachable) => { // A server holding the books with no socket yet is // opening (or finishing), not absent. - let words = if crate::opener::server_lock_held(&run_dir) { - opening_words(&self.book) - } else { - not_running_words(&self.book) + let words = match held { + crate::opener::Holder::Command => command_words(&self.book), + _ if crate::opener::server_lock_held(&run_dir) => { + opening_words(&self.book) + } + _ => not_running_words(&self.book), }; self.link.send_replace(Link::Refused(words)); } diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index c54c8285..78611be3 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -55,7 +55,7 @@ use crate::knobs::{FLAG, Knobs}; use crate::lease::{Ask, HostMsg, Intent, Kind, Reason}; -use crate::opener::{HoldError, Lease, Opener}; +use crate::opener::{HoldError, Holder, Lease, Opener}; use ledger_mcp::admin::{self, Request, Response}; use std::path::{Path, PathBuf}; use std::time::Duration; @@ -116,12 +116,20 @@ fn exit(code: i32) -> Box { /// Hold the books and wait until they are open (INVARIANT 1). async fn open(opener: &mut Opener) -> Result { - let deadline = tokio::time::Instant::now() + opener.knobs().open_wait; + // One bounded wait for the whole command: the deadline a caller set + // (`reach`), else `open_wait` from now. The opener's own waits for + // another program's server (WB-app-5) end at it with their own words; + // the timeout here is a moment later, for what has none. + let deadline = opener + .deadline() + .unwrap_or_else(|| tokio::time::Instant::now() + opener.knobs().open_wait); + opener.wait_until(deadline); + let grace = Duration::from_millis(500); let too_long = || -> HoldError { "the books didn't open in time (Wanderbooks may still be opening a large company: try again in a moment): run `wanderbooks doctor` to see why".into() }; loop { - let mut lease = tokio::time::timeout_at(deadline, opener.hold()) + let mut lease = tokio::time::timeout_at(deadline + grace, opener.hold()) .await .map_err(|_| too_long())??; loop { @@ -254,33 +262,78 @@ impl Reached { /// Hold the books for a command, or, with nothing running and the work /// one `direct` allows, run a server of its own (WB-app-5). +/// +/// Whatever is found is joined: a host, the app's server, and, once its +/// work is done, a command's server or a closing one is waited for. A +/// program that takes the books between the look and the command's own +/// server taking them (the app starting, `serve`, another command) is +/// joined too: the command's server has not got them, it lets go of its +/// start and looks again. One wait covers all of it, `open_wait`, said in +/// words (`Opener::hold` says what it waits for). async fn reach(opener: &mut Opener, common: &Common, direct: &Direct) -> Result { let run_dir = opener.run_dir().to_path_buf(); - match open(opener).await { - Ok(lease) => Ok(Reached { - run_dir, - lease: Some(lease), - own: None, - }), - Err(HoldError::NotRunning) => { - let Direct::With(books) = direct else { - return Err(crate::opener::START_WANDERBOOKS.to_string()); + let deadline = tokio::time::Instant::now() + opener.knobs().open_wait; + opener.wait_until(deadline); + let mut said = false; + loop { + match open(opener).await { + Ok(lease) => { + return Ok(Reached { + run_dir, + lease: Some(lease), + own: None, + }); + } + Err(HoldError::NotRunning) => {} + Err(e) => return Err(hold_words(e)), + } + let Direct::With(books) = direct else { + return Err(crate::opener::START_WANDERBOOKS.to_string()); + }; + let (root, books, knobs) = (common.root.clone(), books.clone(), common.knobs); + let started = tokio::task::spawn_blocking(move || { + let server = match crate::app_server::AppServer::start_for_command( + root.as_deref(), + &books, + &knobs, + ) { + Ok(server) => server, + // Another program took the books since the look. + Err(why) if why == crate::app_server::ANOTHER_HAS_THEM => { + return Ok(None); + } + Err(why) => return Err(why), }; - let (root, books) = (common.root.clone(), books.clone()); - let own = tokio::task::spawn_blocking(move || { - let server = crate::app_server::AppServer::start(root.as_deref(), &books)?; - server.wait_ready(crate::app_server::READY_WAIT)?; - Ok::<_, String>(server) - }) - .await - .map_err(|e| e.to_string())??; - Ok(Reached { + match server.wait_ready_unless_beaten(crate::app_server::READY_WAIT)? { + crate::app_server::Waited::Ready => Ok(Some(server)), + // Another program took them first: this one's start is let + // go of (it has not opened anything), and what runs is + // looked at again. + crate::app_server::Waited::Beaten => { + server.stop(Duration::from_secs(10)); + Ok(None) + } + } + }) + .await + .map_err(|e| e.to_string())??; + if let Some(own) = started { + return Ok(Reached { run_dir, lease: None, own: Some(std::sync::Arc::new(own)), - }) + }); } - Err(e) => Err(hold_words(e)), + if tokio::time::Instant::now() >= deadline { + return Err(format!( + "Other programs kept the books for {} s while this command waited: try again in a moment (`wanderbooks doctor` says what has them).", + opener.knobs().open_wait.as_secs() + )); + } + if !std::mem::replace(&mut said, true) { + eprintln!("Another program started the books just now: waiting for it…"); + } + tokio::time::sleep(Duration::from_millis(50)).await; } } @@ -359,6 +412,23 @@ fn past(deadline: std::time::Instant, now: std::time::Instant) -> bool { now > deadline } +/// What is said of a server that is not the app's, in the words of its +/// own state (`close`, `doctor`): never "the app" for what is not. +fn held_words(holder: Holder) -> &'static str { + match holder { + Holder::Command => { + "A wanderbooks command has the books open for a moment: they close when its work is done." + } + Holder::Closing => "The books are closing: a books server is finishing its last backups.", + Holder::Opening => { + "Wanderbooks is opening the books (or finishing the last backup of the last session): its server isn't answering yet." + } + Holder::Host | Holder::App | Holder::Nothing => { + "The books are held: `wanderbooks doctor` says by what." + } + } +} + /// What `doctor` says of books no host holds. fn no_host(server_lock_held: bool) -> &'static str { if server_lock_held { @@ -569,16 +639,18 @@ pub fn close( exit(1) })?; match asked { - None if crate::app_server::the_apps_server_runs(&run) => { - println!("{APP_HAS_THEM}."); - Ok(()) - } - None if crate::opener::server_lock_held(&run) => { - println!("The books are closing: a books server is finishing its last call."); - Ok(()) - } + // No host: what holds the books is read (WB-app-5), so what is + // said of it is true. None => { - println!("The books are already closed."); + match crate::opener::what_holds(&run) { + Ok(Holder::App) => println!("{APP_HAS_THEM}."), + Ok(Holder::Nothing) => println!("The books are already closed."), + Ok(other) => println!("{}", held_words(other)), + Err(why) => { + eprintln!("error: {why}"); + return Err(exit(1)); + } + } Ok(()) } Some(HostMsg::Done { .. }) => { @@ -2995,14 +3067,15 @@ pub fn doctor( match crate::opener::ask_once_within(&run, Ask::Leases, DOCTOR_WAIT) { // No host: the app's server (or another that runs without one), // one still opening or finishing, or nothing (WB-app-3). - Ok(None) if crate::app_server::the_apps_server_runs(&run) => { - println!("The books are open: Wanderbooks (the app) has them."); - admin_report(&run); - } - Ok(None) if crate::opener::server_lock_held(&run) => println!( - "Wanderbooks is opening the books (or finishing the last backup of the last session): its server isn't answering yet." - ), - Ok(None) => println!("{}", no_host(false)), + Ok(None) => match crate::opener::what_holds(&run) { + Ok(Holder::App) => { + println!("The books are open: Wanderbooks (the app) has them."); + admin_report(&run); + } + Ok(Holder::Nothing) => println!("{}", no_host(false)), + Ok(other) => println!("{}", held_words(other)), + Err(why) => println!("The books server can't be asked: {why}"), + }, Ok(Some(HostMsg::Leases { ready, leases })) => { if ready { println!("The books are open."); diff --git a/crates/ledger-host/src/host.rs b/crates/ledger-host/src/host.rs index 16e29dcf..fe0d1298 100644 --- a/crates/ledger-host/src/host.rs +++ b/crates/ledger-host/src/host.rs @@ -94,11 +94,13 @@ pub(crate) fn private_options() -> std::fs::OpenOptions { /// Windows passes no descriptor to a child unless asked to, so there is /// nothing to close (INVARIANT 2). #[cfg(not(unix))] -fn close_stray_descriptors() {} +pub fn close_stray_descriptors() {} -/// Close every descriptor above 2 (INVARIANT 2). +/// Close every descriptor above 2 (INVARIANT 2). The host does it at its +/// start, and so does every books server (`wanderbooks server`), whoever +/// started it: it holds none of its starter's pipes or sockets. #[cfg(unix)] -fn close_stray_descriptors() { +pub fn close_stray_descriptors() { #[cfg(target_os = "linux")] { // SAFETY: close_range only closes descriptors; nothing is open @@ -765,6 +767,11 @@ impl Host { #[cfg(unix)] command.arg0("wanderbooks"); command.arg("server"); + // Said in its `run/server.info`: this host's, so that one found + // with no host is known to be an orphan finishing (opener.rs). + command + .arg("--started-by") + .arg(ledger_mcp::local::StartedBy::Host.flag()); if self.explicit_root { command.arg("--root").arg(self.root.path()); } diff --git a/crates/ledger-host/src/knobs.rs b/crates/ledger-host/src/knobs.rs index bd7dd0c1..d1d2be46 100644 --- a/crates/ledger-host/src/knobs.rs +++ b/crates/ledger-host/src/knobs.rs @@ -36,6 +36,11 @@ pub struct Knobs { /// How long between the host's looks for a newer release (plan /// P11a step 4: a day). pub update_check: Duration, + /// A command's own server holds the jobs it runs inside their phases + /// while `run/timer-hold` names them (the server's `--timer-hold`; + /// tests of what a command holds while it works). Given as + /// `timer_hold=1`. + pub timer_hold: bool, } impl Default for Knobs { @@ -51,6 +56,7 @@ impl Default for Knobs { backup_quiet: Duration::from_secs(30), drill_first: Duration::from_secs(60), update_check: Duration::from_secs(24 * 60 * 60), + timer_hold: false, } } } @@ -81,6 +87,7 @@ impl Knobs { "backup_quiet" => k.backup_quiet = d, "drill_first" => k.drill_first = d, "update_check" => k.update_check = d, + "timer_hold" => k.timer_hold = ms != 0, other => return Err(format!("{FLAG}: there is no knob {other:?}")), } } @@ -108,6 +115,9 @@ impl Knobs { parts.push(format!("{name}={}", now.as_millis())); } } + if self.timer_hold { + parts.push("timer_hold=1".to_string()); + } (!parts.is_empty()).then(|| parts.join(",")) } diff --git a/crates/ledger-host/src/opener.rs b/crates/ledger-host/src/opener.rs index b5f468d5..ed019d33 100644 --- a/crates/ledger-host/src/opener.rs +++ b/crates/ledger-host/src/opener.rs @@ -39,6 +39,17 @@ //! books. The server's lock held and no admin socket yet is a server //! still opening its companies (or finishing its last backup): the //! holder waits for it, in words, for as long as its own wait lasts. +//! 6a. What holds the books is known, not guessed: a server says what +//! started it and whether it is closing (`run/server.info`, ledger-mcp +//! local.rs INVARIANT 16) and [`what_holds`] reads it. Only a server +//! the app started, not closing, is "the app". A server a command +//! started, a closing server (the app's, or the orphan of a host +//! that was killed), is waited for: the holder says so, in words, and +//! goes on once it is gone, for as long as its own wait lasts +//! (`open_wait`, 120 s; a bridge waits as long as the session does), +//! then says in words what it is still waiting for. A server that +//! says nothing (an earlier build's) is taken for the app's, as it +//! was before. //! 7. No host, no server: only `wanderbooks serve` starts a host (the //! headless path, plan 3.1). Every other holder is turned away with //! [`HoldError::NotRunning`], and says, in words, to start @@ -62,6 +73,9 @@ const START_WAIT: Duration = Duration::from_secs(45); const LOCK_WAIT: Duration = Duration::from_secs(2); /// How long the host has to answer a hello. const ANSWER_WAIT: Duration = Duration::from_secs(10); +/// How long `hold` looks again while it waits for a server that is +/// closing or a command's (INVARIANT 6a). +const WAIT_LOOK: Duration = Duration::from_millis(100); /// Tries after a failure before giving up (INVARIANT 3). pub const MAX_TRIES: u32 = 5; /// How long the books must stay open for earlier failures to be @@ -128,6 +142,10 @@ pub struct Opener { /// Flags the server this opener starts is started with (P9a): /// `--isolation` and `--http`. Empty for every ordinary holder. server_flags: Vec, + /// Until when a wait for another program's server lasts (INVARIANT + /// 6a); the caller's own deadline, else `open_wait` from the first + /// wait. A bridge has none. + deadline: Option, } /// A held lease: the books stay open while it lives. @@ -193,9 +211,21 @@ impl Opener { opened_at: None, has_held: false, server_flags: Vec::new(), + deadline: None, }) } + /// Wait for another program's server (a command's, or one closing) no + /// longer than until `deadline` (INVARIANT 6a). + pub fn wait_until(&mut self, deadline: Instant) { + self.deadline = Some(deadline); + } + + /// The deadline set by [`Opener::wait_until`], if any. + pub fn deadline(&self) -> Option { + self.deadline + } + /// Start the server this opener brings up with these flags (P9a: /// `--isolation`, `--http`). Only `serve` uses it: on the owner's own /// machine it is the one holder, so the host it starts is the server's @@ -244,39 +274,54 @@ impl Opener { pub async fn hold(&mut self) -> Result { let mut started: Option = None; let mut said_waiting = false; + let mut waited_from: Option = None; loop { - // The app has the books: its own server serves them, and no - // host is started beside it (INVARIANT 6). - if !host_lock_held(&self.run) && server_lock_held(&self.run) { - match admin_answers(&self.run) { - Ok(true) => { - if self.kind == Kind::Serve { - return Err(HoldError::Failed( - "Wanderbooks (the app) has these books open: close it first, or use it" - .into(), - )); - } - self.has_held = true; - return Ok(Lease { - id: 0, - link: None, - told_ready: false, - }); + // What holds the books is read, not guessed (INVARIANT 6a). + match what_holds(&self.run)? { + // The app has the books: its own server serves them, and + // no host is started beside it (INVARIANT 6). + Holder::App => { + if self.kind == Kind::Serve { + return Err(HoldError::Failed( + "Wanderbooks (the app) has these books open: close it first, or use it" + .into(), + )); } - Ok(false) => { - // Opening its companies, or finishing its last - // backup: wait for it, and say so once. - if !std::mem::replace(&mut said_waiting, true) && self.kind != Kind::Bridge - { - eprintln!( - "Wanderbooks is still opening (or closing) the books: waiting for it…" - ); - } - tokio::time::sleep(Duration::from_millis(100)).await; - continue; - } - Err(why) => return Err(HoldError::Failed(why)), + self.has_held = true; + return Ok(Lease { + id: 0, + link: None, + told_ready: false, + }); } + // Opening its companies, or finishing its last backup: + // wait for it, and say so once. + Holder::Opening => { + if !std::mem::replace(&mut said_waiting, true) && self.kind != Kind::Bridge { + eprintln!( + "Wanderbooks is still opening (or closing) the books: waiting for it…" + ); + } + tokio::time::sleep(WAIT_LOOK).await; + continue; + } + // A command's server, or one closing: it ends soon, and + // the books are free; wait for it, bounded (INVARIANT 6a). + held @ (Holder::Command | Holder::Closing) => { + let from = *waited_from.get_or_insert_with(Instant::now); + if self.kind != Kind::Bridge { + let until = self.deadline.unwrap_or_else(|| from + self.knobs.open_wait); + if Instant::now() >= until { + return Err(HoldError::Failed(held.still_waiting_words())); + } + } + if !std::mem::replace(&mut said_waiting, true) && self.kind != Kind::Bridge { + eprintln!("{}", held.waiting_words()); + } + tokio::time::sleep(WAIT_LOOK).await; + continue; + } + Holder::Host | Holder::Nothing => {} } wait_for_restart(&self.run).await; let endpoint = ledger_mcp::ipc::Endpoint::new(&self.run, lease::LEASE_SOCKET) @@ -457,6 +502,80 @@ pub fn host_lock_held(run: &Path) -> bool { } } +/// What holds the books now, read from the locks, the server's own word +/// about itself and its admin socket (INVARIANT 6a). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Holder { + /// Nothing: no host, no server. + Nothing, + /// A host holds `run/host.lock` (`wanderbooks serve`'s, or an earlier + /// build's): leases go to it. + Host, + /// The app's server, not closing, answering: no host behind it. + App, + /// A server the app started (or an earlier build's, which says + /// nothing of itself) that is not answering yet: opening its + /// companies, or finishing its last backup. + Opening, + /// A server a command started, for the length of its work. + Command, + /// A server that has begun to close (the app's, or the orphan of a + /// host that went): finishing its last backups. + Closing, +} + +impl Holder { + /// What is said while waiting for this to finish (INVARIANT 6a). + pub fn waiting_words(self) -> &'static str { + match self { + Holder::Command => { + "Another wanderbooks command has the books open for a moment: waiting for it to finish…" + } + _ => { + "Wanderbooks is closing the books (a last backup is being made): waiting for it to finish…" + } + } + } + + /// What is said when the wait ran out (INVARIANT 6a). + pub fn still_waiting_words(self) -> String { + match self { + Holder::Command => "Another wanderbooks command still has the books open after waiting for it: try again in a moment (`wanderbooks doctor` says what has them).".into(), + _ => "Wanderbooks is still closing the books after waiting for it (a last backup is still being made): try again in a moment.".into(), + } + } +} + +/// What holds the books of the root whose `run/` folder this is +/// (INVARIANT 6a). `Err` in words when the server's socket is another +/// account's. +pub fn what_holds(run: &Path) -> Result { + use ledger_mcp::local::StartedBy; + if host_lock_held(run) { + return Ok(Holder::Host); + } + if !server_lock_held(run) { + return Ok(Holder::Nothing); + } + let info = ledger_mcp::local::read_server_info(run); + Ok(match info { + Some(i) if i.closing => Holder::Closing, + Some(i) if i.by == StartedBy::Command => Holder::Command, + // No host holds the books, so a server a host started is the + // orphan of one that went: it is closing, as its input ended. + Some(i) if i.by == StartedBy::Host => Holder::Closing, + // The app's, or one that says nothing (an earlier build's, or a + // newer one's, a moment before it writes its word). + Some(_) | None => { + if admin_answers(run)? { + Holder::App + } else { + Holder::Opening + } + } + }) +} + /// Whether the admin socket answers: the books server is up and ready /// (it binds its sockets only once every company has been tried). A /// socket of another account is an error. @@ -569,6 +688,7 @@ mod tests { opened_at: None, has_held: false, server_flags: Vec::new(), + deadline: None, }; for _ in 0..MAX_TRIES { o.failed().await.unwrap(); diff --git a/crates/ledger-host/src/start.rs b/crates/ledger-host/src/start.rs index 45f2f9ae..47690f43 100644 --- a/crates/ledger-host/src/start.rs +++ b/crates/ledger-host/src/start.rs @@ -258,6 +258,24 @@ fn host_env( env } +/// Give `command` the environment a host has (INVARIANT 1) and nothing of +/// this process's: the books server a command runs for itself is started +/// so, as the host's own is, since it may outlive the command that +/// started it (commands.rs `reach`). +pub(crate) fn clean_environment(command: &mut Command) -> Result<(), String> { + let home = ledger_store::root::account_home().map_err(|e| e.to_string())?; + command.env_clear(); + #[cfg(unix)] + command.envs(host_env( + &home, + std::env::var_os("SSH_AUTH_SOCK").as_deref(), + this_appimage().as_ref(), + )); + #[cfg(windows)] + command.envs(host_env(&home)); + Ok(()) +} + #[cfg(unix)] /// Whether this process sits in a unit under this account's user manager /// (an app's scope or service, as uwsm makes for every app), whose stop diff --git a/crates/ledger-mcp/src/local.rs b/crates/ledger-mcp/src/local.rs index 4aed2d6b..78ff4ec7 100644 --- a/crates/ledger-mcp/src/local.rs +++ b/crates/ledger-mcp/src/local.rs @@ -311,6 +311,16 @@ //! request that arrives once the server is closing and finds a book's //! door shut is refused as closing (503, `closing`), not recorded: //! the door is shut (INVARIANT 11), as in a close of one book. +//! 16. A server says what it is, beside its lock (`run/server.info`), +//! when it is started with `--started-by`: who started it (the app, +//! a `serve` host, or a command that runs one for the length of its +//! work), its process id, and whether it has begun to close. The +//! file is written whole and moved into place as soon as the lock is +//! the server's, rewritten with `closing` the moment it is told to +//! close, and removed just before the lock is let go; it is read only +//! while the lock is held, which is when it is the lock holder's. A +//! program that finds a server holding the books reads it before it +//! decides what that server is. //! SCENARIOS: //! 1. Two books open; one is closed while agents call both: the other //! answers throughout, the closed one's calls are refused unrun @@ -414,6 +424,90 @@ pub const ADMIN_SOCKET: &str = "admin.sock"; pub const SERVER_LOCK: &str = "server.lock"; /// What the server prints on stdout when it is ready (INVARIANT 5). pub const READY: &str = "ready"; +/// What a server says of itself, beside its lock: who started it, and +/// whether it has begun to close (INVARIANT 16). +pub const SERVER_INFO: &str = "server.info"; + +/// Who started a server (INVARIANT 16): the program a caller finds holding +/// the books decides what to do from it, and so the words it says are the +/// true ones. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum StartedBy { + /// The desktop app: the books server is its child, for as long as its + /// window runs. + App, + /// A `wanderbooks serve` host: the host holds `run/host.lock` as long + /// as it lives, so a server of its starting that is found with no host + /// is an orphan, closing. + Host, + /// A command that runs a server of its own for the length of its work. + Command, +} + +impl StartedBy { + /// The flag value (`--started-by`). + pub fn flag(self) -> &'static str { + match self { + StartedBy::App => "app", + StartedBy::Host => "host", + StartedBy::Command => "command", + } + } + + fn parse(value: &str) -> Result { + match value { + "app" => Ok(StartedBy::App), + "host" => Ok(StartedBy::Host), + "command" => Ok(StartedBy::Command), + other => Err(format!( + "--started-by takes app, host or command, not {other}" + )), + } + } +} + +/// What a server says of itself in `run/server.info` (INVARIANT 16). +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct ServerInfo { + /// Who started it. + pub by: StartedBy, + /// Its process id. + pub pid: u32, + /// It has begun to close: running calls finish, the last backups are + /// made. It still answers its admin socket until it is gone. + pub closing: bool, +} + +/// What the server holding `run/server.lock` says of itself: `None` when +/// there is no such file, or it is not (yet) readable: a server of an +/// earlier build says nothing, and a starting one says it just after it +/// takes the lock. Only meaningful while that lock is held. +pub fn read_server_info(run: &Path) -> Option { + let text = std::fs::read_to_string(run.join(SERVER_INFO)).ok()?; + serde_json::from_str(&text).ok() +} + +/// Say what this server is (INVARIANT 16): written whole beside the lock +/// and moved into place, so a reader sees one version or the other. +fn write_server_info(run: &Path, info: &ServerInfo) -> std::io::Result<()> { + let text = serde_json::to_string(info).map_err(std::io::Error::other)?; + let temp = run.join(format!("{SERVER_INFO}.{}.tmp", info.pid)); + std::fs::write(&temp, text)?; + std::fs::rename(&temp, run.join(SERVER_INFO)).inspect_err(|_| { + let _ = std::fs::remove_file(&temp); + }) +} + +/// Removes `run/server.info` when the server is done with it, before the +/// lock goes (INVARIANT 16). +struct InfoGuard(PathBuf); + +impl Drop for InfoGuard { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} /// How large an MCP request may be (plan 3.2): files come only through /// uploads (`/b/{book}/u/{upload}`), never in a request (D-46). @@ -3220,6 +3314,9 @@ fn print_usage(prog: &str) { eprintln!(" --http [ADDR]: also serve the MCP door on loopback only (default"); eprintln!(" 127.0.0.1:7411), for a TLS proxy or a tunnel in front of it. Off unless"); eprintln!(" given; any other address is refused."); + eprintln!(" --start-delay MS: wait this long before taking the lock (tests)."); + eprintln!(" --started-by app | host | command: who started it, said in run/server.info"); + eprintln!(" so a program that finds it holding the books knows what it is."); eprintln!(" --open all | none | ID[,ID...]: which books are open at the start (default"); eprintln!(" all). A book left closed opens when asked (`wanderbooks books open ID`)."); } @@ -3237,6 +3334,8 @@ pub fn run( let mut isolation = Isolation::SameUser; let mut tunnel: Option = None; let mut open_at_start = OpenAtStart::All; + let mut started_by: Option = None; + let mut start_delay = Duration::ZERO; let mut args = args.into_iter().peekable(); while let Some(arg) = args.next() { match arg.as_str() { @@ -3266,6 +3365,26 @@ pub fn run( open_at_start = OpenAtStart::parse(&args.next().ok_or("--open needs all, none, or ids")?)?; } + // Who started this server (INVARIANT 16): the app, a `serve` + // host or a command. Without it a server says nothing of + // itself, as every earlier build's did not. + "--started-by" => { + started_by = Some(StartedBy::parse( + &args + .next() + .ok_or("--started-by needs app, host or command")?, + )?); + } + // How long this server waits before it first tries to take the + // lock (tests of a program that starts or finds the books in + // that time: a slow start). + "--start-delay" => { + let ms: u64 = args + .next() + .and_then(|v| v.parse().ok()) + .ok_or("--start-delay needs milliseconds")?; + start_delay = Duration::from_millis(ms); + } // How long the books stay unwritten before a backup (tests). "--backup-quiet" => { let ms: u64 = args @@ -3359,6 +3478,11 @@ pub fn run( let _in_runtime = rt.enter(); watch_for_close(&stops)?; } + // The test knob `--start-delay`: a slow start, told to close or not. + let delayed = std::time::Instant::now(); + while delayed.elapsed() < start_delay && !stops.close.is_cancelled() { + std::thread::sleep(Duration::from_millis(10)); + } // INVARIANT 1: a server still finishing (its host gone) has the lock; // this one waits for it, touching nothing, until told to close. let mut said = false; @@ -3394,6 +3518,28 @@ pub fn run( ledger_store::winsec::set_owner_only(&lock_path) .map_err(|e| format!("can't make the server lock private: {}", e.kind()))?; } + // INVARIANT 16: what this server is, said as soon as the lock is its + // and until just before it lets the lock go; `closing` from the moment + // it is told to close. + let info_guard = match started_by { + Some(by) => { + let mut info = ServerInfo { + by, + pid: std::process::id(), + closing: stops.close.is_cancelled(), + }; + write_server_info(&run, &info) + .map_err(|e| format!("can't say what this server is: {}", e.kind()))?; + let (close, there) = (stops.close.clone(), run.clone()); + rt.spawn(async move { + close.cancelled().await; + info.closing = true; + let _ = write_server_info(&there, &info); + }); + Some(InfoGuard(run.join(SERVER_INFO))) + } + None => None, + }; let books = Arc::new( Books::new(root.clone(), backup_quiet, drill_first, isolation).with_timers(timers), ); @@ -3442,6 +3588,7 @@ pub fn run( for name in [MCP_SOCKET, ADMIN_SOCKET] { let _ = std::fs::remove_file(run.join(name)); } + drop(info_guard); drop(lock); served }