diff --git a/crates/ledger-cli/src/main.rs b/crates/ledger-cli/src/main.rs index 59540690..38680ba9 100644 --- a/crates/ledger-cli/src/main.rs +++ b/crates/ledger-cli/src/main.rs @@ -96,6 +96,14 @@ impl ledger_gui::owner::Owner for ViewerOwner { self.server.start(open) } + fn serve_host_holds(&self) -> bool { + ledger_host::commands::a_host_holds(self.common.root.as_deref()) + } + + fn serve_close_host(&self) -> Result { + ledger_host::commands::close_the_host(self.common.root.as_deref()) + } + fn serve_open(&self, book: &str) -> Result, String> { self.server.open_book(book) } diff --git a/crates/ledger-gui/src/app.rs b/crates/ledger-gui/src/app.rs index 30b61cd1..2c92c98f 100644 --- a/crates/ledger-gui/src/app.rs +++ b/crates/ledger-gui/src/app.rs @@ -535,12 +535,20 @@ impl App { self.notices.extend(self.serving.take_notices()); let starting = self.serving.is_starting(); let down = self.serving.is_down(); + // The refusal by a host is over once the start is on its way again + // (the host was closed): its words go, whether or not they were + // dismissed. + if !down { + self.notices.retain(|n| n != crate::serving::HOST_HOLDS); + } if self.notices.is_empty() && !starting && !down { return; } let p = pal(ui.ctx()); let mut dismiss = None; let mut retry = false; + let mut close_host = false; + let host_blocks = self.serving.host_blocks(); egui::Panel::top("server_notices") .resizable(false) .frame( @@ -563,6 +571,9 @@ impl App { for (i, words) in self.notices.iter().enumerate() { ui.horizontal_wrapped(|ui| { ui.label(RichText::new(words).color(p.text)); + if host_blocks && ui.button("Close it").clicked() { + close_host = true; + } if down && ui.button("Try again").clicked() { retry = true; } @@ -578,6 +589,9 @@ impl App { if retry { self.serving.retry(); } + if close_host { + self.serving.close_host(); + } if let Some(i) = dismiss { self.notices.remove(i); } diff --git a/crates/ledger-gui/src/owner.rs b/crates/ledger-gui/src/owner.rs index db1f41de..dd93c718 100644 --- a/crates/ledger-gui/src/owner.rs +++ b/crates/ledger-gui/src/owner.rs @@ -229,6 +229,19 @@ pub trait Owner: Send + Sync { fn serve_start(&self, _open: &[String]) -> Result<(), String> { Ok(()) } + /// Whether another program's host holds the books now (an earlier + /// build's, or `wanderbooks serve`'s): asked when the start was + /// refused, to offer the person a button that closes it + /// (`serve_close_host`) beside the line that says what to type. + fn serve_host_holds(&self) -> bool { + false + } + /// Ask that host to close the books and wait until it has (what + /// `wanderbooks close` does, for a person with no command line on + /// their path): `Ok` says what came of it, `Err` why not. Blocks. + fn serve_close_host(&self) -> Result { + Err("not here".into()) + } /// Open the company `book` in the server (a tab opened): `Ok(None)` /// when it is open now. Blocks. fn serve_open(&self, _book: &str) -> Result, String> { diff --git a/crates/ledger-gui/src/serving.rs b/crates/ledger-gui/src/serving.rs index bdac225f..7fec415d 100644 --- a/crates/ledger-gui/src/serving.rs +++ b/crates/ledger-gui/src/serving.rs @@ -47,6 +47,11 @@ use std::collections::{BTreeSet, HashMap}; use std::sync::mpsc::{Sender, channel}; use std::sync::{Arc, Condvar, Mutex, MutexGuard}; +/// What the person is told when the start was refused because a host +/// holds the books, and what to do: the button closes it for them, and the +/// command is there for a person who prefers a terminal. +pub const HOST_HOLDS: &str = "Assistants can't reach your companies: another program has these books open (an earlier Wanderbooks, or `wanderbooks serve`). \"Close it\" makes it let go of them and starts the books here; or, in a terminal, `wanderbooks close` does the same."; + /// Where the server's start stands (INVARIANT 3). #[derive(Clone, Copy, PartialEq, Eq)] enum Gate { @@ -82,6 +87,12 @@ struct State { report: Vec, /// The person has seen the report and chose to close anyway. report_seen: bool, + /// The start was refused because a host holds the books (an earlier + /// build's, or `wanderbooks serve`'s): the notice has a button that + /// closes it (INVARIANT 3). + host_blocks: bool, + /// That button was pressed and the host is being asked to close. + host_closing: bool, } struct Inner { @@ -207,7 +218,14 @@ impl Serving { // A window asked to close meanwhile has no use for // the word. if *lock(&starting.closing) == Closing::Not { - starting.note(format!("Assistants can't reach your companies: {why}")); + let host = starting.owner.serve_host_holds(); + lock(&starting.state).host_blocks = host; + if host { + starting.note(HOST_HOLDS.into()); + } else { + starting + .note(format!("Assistants can't reach your companies: {why}")); + } } Gate::Down } @@ -276,6 +294,57 @@ impl Serving { .is_some_and(|i| *lock(&i.gate) == Gate::Up && *lock(&i.closing) == Closing::Not) } + /// Whether the start was refused because a host holds the books, so + /// the notice offers to close it (INVARIANT 3): not while that is + /// being done. + pub fn host_blocks(&self) -> bool { + self.inner.as_ref().is_some_and(|i| { + let state = lock(&i.state); + *lock(&i.gate) == Gate::Down && state.host_blocks && !state.host_closing + }) + } + + /// Ask the host that holds the books to close them, and start the + /// server when it has (INVARIANT 3): on a thread of its own, the + /// answer a notice. False when nothing was started. + pub fn close_host(&self) -> bool { + let Some(inner) = self.inner.clone() else { + return false; + }; + if !self.host_blocks() { + return false; + } + lock(&inner.state).host_closing = true; + let asking = inner.clone(); + let started = std::thread::Builder::new() + .name("serving-close-host".into()) + .spawn(move || { + let said = asking.owner.serve_close_host(); + { + let mut state = lock(&asking.state); + state.host_closing = false; + if said.is_ok() { + state.host_blocks = false; + // The old words are of a refusal that is over. + state.notices.retain(|n| n != HOST_HOLDS); + } + } + match said { + Ok(_) => { + Self::restart(&asking); + } + Err(why) => asking.note(format!( + "Couldn't close it: {why}. In a terminal, `wanderbooks close` closes it." + )), + } + }) + .is_ok(); + if !started { + lock(&inner.state).host_closing = false; + } + started + } + /// Whether the start failed and a `retry` would try again. pub fn is_down(&self) -> bool { self.inner diff --git a/crates/ledger-gui/tests/host_holds.rs b/crates/ledger-gui/tests/host_holds.rs new file mode 100644 index 00000000..cdf44c94 --- /dev/null +++ b/crates/ledger-gui/tests/host_holds.rs @@ -0,0 +1,235 @@ +//! A start the app's server was refused because a host holds the books (an +//! earlier build's detached host, or `wanderbooks serve`'s): the notice +//! carries a button that closes it, and the line to type is its fallback +//! (serving.rs INVARIANT 3; WB-app-2). +//! +//! ```text +//! GOAL: a person with no command line on their path can let go of a +//! host that holds the books, from the notice, and the app then +//! starts its own server. +//! SOURCE: plan/p15-app-and-relay.md 3.1; WB-app-1 (a start is refused, +//! in words, when another program has the books), WB-app-2. +//! INVARIANTS: +//! 1. A start refused while a host holds the books is a notice that +//! says what will happen and what to type instead; the button is +//! offered (`host_blocks`). +//! 2. The button asks the host to close (`serve_close_host`) and, once +//! it has, starts the server and takes the notice away. +//! 3. A close that fails says why and offers the button again. +//! 4. A start refused for any other reason offers no such button. +//! ``` + +use ledger_core::Currency; +use ledger_gui::owner::{Agent, Owner, RestorePlan}; +use ledger_gui::serving::{HOST_HOLDS, Serving}; +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +/// An owner whose start is refused while `host` holds the books. +struct Held { + host: AtomicBool, + /// Whether a host is what refused the start (else something else did). + host_is_why: bool, + close_says: Mutex>, + log: Mutex>, +} + +impl Held { + fn new(host_is_why: bool) -> Arc { + Arc::new(Held { + host: AtomicBool::new(true), + host_is_why, + close_says: Mutex::new(Ok("The other program let go of the books.".into())), + log: Mutex::new(Vec::new()), + }) + } + + fn said(&self) -> Vec { + self.log.lock().unwrap().clone() + } +} + +impl Owner for Held { + fn serves(&self) -> bool { + true + } + fn serve_start(&self, _open: &[String]) -> Result<(), String> { + self.log.lock().unwrap().push("start".into()); + if self.host.load(Ordering::SeqCst) { + Err("Another program has these books open: close it".into()) + } else { + Ok(()) + } + } + fn serve_host_holds(&self) -> bool { + self.host_is_why && self.host.load(Ordering::SeqCst) + } + fn serve_close_host(&self) -> Result { + self.log.lock().unwrap().push("close host".into()); + let said = self.close_says.lock().unwrap().clone(); + if said.is_ok() { + self.host.store(false, Ordering::SeqCst); + } + said + } + fn new_books(&self, _: &str, _: &str) -> Result { + Err("not here".into()) + } + fn back_up_now(&self, _: &str) -> Result, String> { + Err("not here".into()) + } + fn plan_restore(&self, _: &str, _: Option, _: bool) -> Result { + Err("not here".into()) + } + fn restore(&self, _: &RestorePlan) -> Result, String> { + Err("not here".into()) + } + fn connect(&self, _: Agent, _: &str) -> Result, String> { + Err("not here".into()) + } + fn upgrade_format(&self, _: &str, _: &str) -> Result, String> { + Err("not here".into()) + } +} + +fn until(what: &str, mut ok: impl FnMut() -> bool) { + let end = Instant::now() + Duration::from_secs(30); + while !ok() { + assert!(Instant::now() < end, "never: {what}"); + std::thread::sleep(Duration::from_millis(10)); + } +} + +fn started(owner: &Arc) -> Serving { + let _ = Currency::USD; + let serving = Serving::start(Some(owner.clone() as Arc), vec![]); + until("the first start came out", || !serving.is_starting()); + serving +} + +#[test] +fn a_start_refused_by_a_host_says_what_the_button_does_and_the_command_to_type() { + let owner = Held::new(true); + let serving = started(&owner); + assert!(serving.host_blocks()); + let notices = serving.take_notices(); + assert_eq!(notices, vec![HOST_HOLDS.to_string()]); + assert!( + HOST_HOLDS.contains("Close it") && HOST_HOLDS.contains("`wanderbooks close`"), + "{HOST_HOLDS}" + ); +} + +#[test] +fn the_button_closes_the_host_and_starts_the_server() { + let owner = Held::new(true); + let serving = started(&owner); + // Notices the window shows are kept by it: what it has not shown yet + // is read here, as it does. + let mut shown = serving.take_notices(); + assert!(serving.close_host()); + until("the server started after the host closed", || { + serving.is_up() + }); + assert_eq!(owner.said(), ["start", "close host", "start"]); + assert!(!serving.host_blocks()); + shown.extend(serving.take_notices()); + // The refusal is over, and the notice of it goes (a window that + // already shows it drops it as it learns the start came out). + assert!(!serving.is_down()); +} + +#[test] +fn a_close_that_fails_says_why_and_the_button_stays() { + let owner = Held::new(true); + *owner.close_says.lock().unwrap() = Err("the other program is still closing".into()); + let serving = started(&owner); + let _ = serving.take_notices(); + assert!(serving.close_host()); + until("the failure is said", || { + serving + .take_notices() + .iter() + .any(|n| n.contains("Couldn't close it: the other program is still closing")) + }); + until("the button is back", || serving.host_blocks()); + assert!(serving.is_down()); + assert_eq!(owner.said(), ["start", "close host"]); +} + +#[test] +fn a_start_refused_for_another_reason_offers_no_button() { + let owner = Held::new(false); + let serving = started(&owner); + assert!(!serving.host_blocks()); + assert!(!serving.close_host()); + let notices = serving.take_notices(); + assert_eq!(notices.len(), 1, "{notices:?}"); + assert!(notices[0].starts_with("Assistants can't reach your companies:")); + assert_eq!(owner.said(), ["start"]); +} + +/// The window itself: the notice shows the button, pressing it asks the +/// host to close, and the notice goes once the server has started. +#[test] +fn the_notice_in_the_window_has_the_button_and_it_goes_when_the_server_starts() { + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable; + use ledger_gui::{App, Start}; + use ledger_store::root::{BookId, Root}; + let dir = tempfile::tempdir().unwrap(); + let home = dir.path().join("home"); + std::fs::create_dir_all(&home).unwrap(); + let root = dir.path().join("root"); + Root::setup(&home, Some(&root), None).unwrap(); + let found = Root::find(Some(&root)).unwrap(); + drop( + found + .create_book(&BookId::parse("alpha").unwrap(), Currency::USD) + .unwrap(), + ); + let fallback = ledger_gui::data::Source { + data_dir: root.join("books").join("alpha"), + today: None, + }; + let owner = Held::new(true); + let for_app: Arc = owner.clone(); + let mut h = Harness::builder() + .with_size(egui::vec2(1000.0, 700.0)) + .build_eframe(move |cc| { + App::start_with_owner( + &cc.egui_ctx, + &|_| None, + Start::Restore { root, fallback }, + Some(for_app), + ) + }); + until("the start was refused", || { + h.run_steps(2); + h.query_all_by_label_contains("`wanderbooks close`") + .next() + .is_some() + }); + h.query_all_by_label("Close it") + .next() + .expect("the button") + .click(); + until("the host was asked to close and the server started", || { + h.run_steps(2); + { + // (A tab opening after the refused start tried it again once.) + let said = owner.said(); + said.iter().filter(|s| *s == "close host").count() == 1 + && said.last().is_some_and(|s| s == "start") + } + }); + until("the notice goes", || { + h.run_steps(2); + h.query_all_by_label_contains("`wanderbooks close`") + .next() + .is_none() + && h.query_all_by_label("Close it").next().is_none() + }); +} diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index 78611be3..8586503d 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -686,6 +686,54 @@ pub fn close( } } +/// Ask the host that holds the books (an earlier build's detached host, +/// or `wanderbooks serve`'s) to close them, and wait until they are +/// closed: what `wanderbooks close` does, for the app, whose person may +/// have no command line (the lease protocol to such a host is the same +/// as ever). `Ok` says what came of it, in words; `Err` says why not. +/// Blocks, at most `CLOSE_WAIT` and a few seconds. +pub fn close_the_host(root: Option<&Path>) -> Result { + let found = ledger_store::root::Root::find(root).map_err(|e| e.to_string())?; + let run = found.run_dir().map_err(|e| e.to_string())?; + let asked = crate::opener::ask_once_within(&run, Ask::Intent(Intent::Close), HOST_WAIT)?; + match asked { + None => Ok("No program has the books open now.".into()), + Some(HostMsg::Done { .. }) => { + let deadline = std::time::Instant::now() + CLOSE_WAIT; + loop { + let asked = crate::opener::ask_once_within(&run, Ask::Leases, HOST_WAIT); + match closing(&asked, || crate::opener::server_lock_held(&run)) { + Closing::Closed => return Ok("The other program let go of the books.".into()), + Closing::Reopened => { + return Err( + "something opened the books again as the other program let go".into(), + ); + } + Closing::Going => {} + } + if past(deadline, std::time::Instant::now()) { + return Err( + "the other program is still closing the books (a request is finishing)" + .into(), + ); + } + std::thread::sleep(Duration::from_millis(50)); + } + } + Some(HostMsg::Refused(why)) => Err(why), + Some(other) => Err(format!("the books' host answered oddly: {other:?}")), + } +} + +/// Whether a host holds the books of the root now (an earlier build's, or +/// `wanderbooks serve`'s): the one case the app's refused start can offer +/// to close for the person ([`close_the_host`]). +pub fn a_host_holds(root: Option<&Path>) -> bool { + ledger_store::root::Root::find(root) + .and_then(|found| found.run_dir()) + .is_ok_and(|run| crate::opener::host_lock_held(&run)) +} + fn books_usage(prog: &str) { eprintln!("usage: {prog} list"); eprintln!(" {prog} create ID [--currency CODE]");