diff --git a/crates/ledger-cli/src/main.rs b/crates/ledger-cli/src/main.rs index 42aab5b1..ddf6173b 100644 --- a/crates/ledger-cli/src/main.rs +++ b/crates/ledger-cli/src/main.rs @@ -70,20 +70,62 @@ fn gui_args(args: Vec) -> Vec { /// The viewer's owner (ledger-gui owner.rs): its Books menu, done as the /// command line does it (the books server, the agents' own commands). #[cfg(feature = "gui")] -struct ViewerOwner(ledger_host::commands::Common); +struct ViewerOwner { + common: ledger_host::commands::Common, + /// The books server this window runs, a child process of it (plan P15 + /// 3.1): started with the window, closed with it. All of what is done + /// with it is `AppHost`'s, which the tests drive. + server: ledger_host::app_server::AppHost, +} + +#[cfg(feature = "gui")] +impl ViewerOwner { + fn new(common: ledger_host::commands::Common) -> Self { + let server = ledger_host::app_server::AppHost::new(common.root.clone()); + Self { common, server } + } +} #[cfg(feature = "gui")] impl ledger_gui::owner::Owner for ViewerOwner { + fn serves(&self) -> bool { + true + } + + fn serve_start(&self, open: &[String]) -> Result<(), String> { + self.server.start(open) + } + + fn serve_open(&self, book: &str) -> Result, String> { + self.server.open_book(book) + } + + fn serve_close(&self, book: &str) -> Result, String> { + self.server.close_book(book) + } + + fn serve_not_open(&self, wanted: &[String]) -> Vec<(String, String)> { + self.server.not_open(wanted) + } + + fn serve_stop(&self) -> Result, String> { + self.server.stop(ledger_host::app_server::STOP_WAIT) + } + + fn serve_exited(&self) -> Option { + self.server.exited() + } + fn close_books(&self) -> Result { - ledger_host::commands::close_books(&self.0) + ledger_host::commands::close_books(&self.common) } fn new_books(&self, id: &str, currency: &str) -> Result { - ledger_host::commands::new_books_and_home(&self.0, id, currency) + ledger_host::commands::new_books_and_home(&self.common, id, currency) } fn back_up_now(&self, book: &str) -> Result, String> { - ledger_host::commands::back_up_now(&self.0, book, false) + ledger_host::commands::back_up_now(&self.common, book, false) } fn plan_restore( @@ -92,7 +134,7 @@ impl ledger_gui::owner::Owner for ViewerOwner { id: Option, replace: bool, ) -> Result { - let p = ledger_host::commands::plan_restore(&self.0, source, id, replace, false)?; + let p = ledger_host::commands::plan_restore(&self.common, source, id, replace, false)?; Ok(ledger_gui::owner::RestorePlan { source: p.source, id: p.id, @@ -104,7 +146,7 @@ impl ledger_gui::owner::Owner for ViewerOwner { fn restore(&self, plan: &ledger_gui::owner::RestorePlan) -> Result, String> { ledger_host::commands::carry_out_restore( - &self.0, + &self.common, &ledger_host::commands::RestorePlan { source: plan.source.clone(), id: plan.id.clone(), @@ -121,11 +163,11 @@ impl ledger_gui::owner::Owner for ViewerOwner { ledger_gui::owner::Agent::Claude => "claude", ledger_gui::owner::Agent::Codex => "codex", }; - ledger_host::commands::connect_and_home(&self.0, agent, book) + ledger_host::commands::connect_and_home(&self.common, agent, book) } fn first_run(&self) -> ledger_gui::owner::FirstRun { - let s = ledger_host::commands::first_run_state(&self.0); + let s = ledger_host::commands::first_run_state(&self.common); ledger_gui::owner::FirstRun { root: s.root, books: s.books, @@ -134,16 +176,16 @@ impl ledger_gui::owner::Owner for ViewerOwner { } fn set_up(&self) -> Result, String> { - ledger_host::commands::set_up_root(&self.0) + ledger_host::commands::set_up_root(&self.common) } fn set_passphrase(&self, new: &str) -> Result<(), String> { - ledger_host::commands::set_first_passphrase(&self.0, new) + ledger_host::commands::set_first_passphrase(&self.common, new) } - fn hold(&self, book: &str) { - ledger_host::commands::hold_for_viewer(&self.0, Some(book.to_string())); - } + /// Nothing: the window's server holds the books for as long as the + /// window runs, a company at a time (`serve_open`), and no host does. + fn hold(&self, _book: &str) {} fn agent_start( &self, @@ -177,23 +219,28 @@ impl ledger_gui::owner::Owner for ViewerOwner { }) } + /// Handed to the window's own server as an admin request: there is + /// no host here, and so no lease socket to ask (app_server.rs + /// INVARIANT 10). fn upgrade_format(&self, book: &str, passphrase: &str) -> Result, String> { - ledger_host::commands::upgrade_format(&self.0, book, passphrase) + self.server.upgrade_format(book, passphrase) } fn update_waiting(&self) -> Option { - ledger_host::commands::update_waiting(&self.0).map(|u| ledger_gui::owner::UpdateWaiting { - version: u.version, - staged_at: u.staged_at, + ledger_host::commands::update_waiting(&self.common).map(|u| { + ledger_gui::owner::UpdateWaiting { + version: u.version, + staged_at: u.staged_at, + } }) } fn check_for_updates(&self) -> Result, String> { - ledger_host::commands::check_for_updates(&self.0).map(|l| vec![l]) + ledger_host::commands::check_for_updates(&self.common).map(|l| vec![l]) } fn apply_update(&self) -> Result, String> { - ledger_host::commands::apply_update(&self.0).map(|l| vec![l]) + ledger_host::commands::apply_update(&self.common).map(|l| vec![l]) } } @@ -222,7 +269,6 @@ fn run_gui(args: Vec) -> i32 { } } let root = value("--root").map(PathBuf::from); - let book = value("--book"); if known { // The viewer asks about a format upgrade in its own window, makes // the first books when there are none, and starts the agent in @@ -231,10 +277,10 @@ fn run_gui(args: Vec) -> i32 { root: root.clone(), ..Default::default() }; - ledger_gui::owner::set_owner(std::sync::Arc::new(ViewerOwner(common.clone()))); - if ledger_gui::book_in_root(root.as_deref(), book.as_deref()).is_ok() { - ledger_host::commands::hold_for_viewer(&common, book); - } + // The window runs the books server itself, as a child process + // (plan P15 3.1), once it knows which companies it opens: no + // host is started for it. + ledger_gui::owner::set_owner(std::sync::Arc::new(ViewerOwner::new(common))); } } match ledger_gui::run("wanderbooks gui", args) { diff --git a/crates/ledger-cli/tests/app_server.rs b/crates/ledger-cli/tests/app_server.rs new file mode 100644 index 00000000..ab903fdb --- /dev/null +++ b/crates/ledger-cli/tests/app_server.rs @@ -0,0 +1,716 @@ +//! The app as the host (ledger-host app_server.rs and bridge.rs INVARIANT +//! 12; plan/p15-app-and-relay.md 3.1; WB-app-1, WB-app-3): the books +//! server is a child process of the window, and the bridge talks to the +//! running app and says so in words when it cannot. +//! +//! ```text +//! GOAL: the child starts, answers, opens and closes one company at a +//! time on request, closes cleanly when its input does (the +//! window's close, or the window's death), is never killed, and a +//! start is refused while another program holds the books; and an +//! agent's bridge is told, in words, that the app isn't running or +//! that the company isn't open, then goes through once it is. +//! SOURCE: plan/p15-app-and-relay.md 3.1 (the app starts the server as a +//! child and closes it by closing its input; the bridge answers +//! "Wanderbooks isn't running" or "Company X isn't open"), D-44, +//! D-77, D-84, WB-app-1, WB-app-3. +//! INVARIANTS: +//! 1. A server started by `AppServer` is `wanderbooks server` of this +//! program on the test's own root alone, says ready, and holds +//! run/server.lock until it exits. +//! 2. Closing its input (`stop`) closes the books as the host does: +//! exit 0, the lock let go, the socket removed. +//! 3. A window that is killed outright leaves no server: its input +//! closes with it and the books close cleanly. +//! 4. A start is refused, in words, while a server or a host holds the +//! books, and touches nothing. +//! 5. A stop that runs out of time says the server is still closing and +//! leaves it alone: nothing is signalled. +//! 6. A tab's company is opened and closed in the server by request; a +//! company closed is not reachable, one opened is. +//! 7. The bridge, for a root the app has served and with no host: +//! "Wanderbooks isn't running" with the app not running, "Company X +//! isn't open" with it running and the company not, and neither once +//! both are so, in a session that was already running; it starts no +//! host. +//! 8. What the window runs with its server is `AppHost` (the program's +//! `ViewerOwner` only forwards to it): a server that is alive and +//! late is waited for and stays managed; one that never became ready +//! is stopped when the window stops, and a window stopped before the +//! child was stored stops it; the window's stop says, in words, each +//! company whose closing backup was incomplete and a server that +//! exited badly; the format upgrade reaches the server; a company +//! that is not open is told. +//! ``` + +mod common; + +use common::{BOOK, Home, Server, clean_env}; +use ledger_host::app_server::{ + ANOTHER_HAS_THEM, APP_MARKER, AppHost, AppServer, Stopped, app_hosted, +}; +use ledger_host::opener::{host_lock_held, server_lock_held}; +use ledger_mcp::admin::{Request, Response}; +use serde_json::{Value, json}; +use std::io::{BufRead, BufReader, Write}; +use std::path::Path; +use std::process::{Child, Command, Stdio}; +use std::sync::mpsc; +use std::time::{Duration, Instant}; + +fn exe() -> &'static Path { + Path::new(env!("CARGO_BIN_EXE_wanderbooks")) +} + +/// The server the app starts, on `home`'s root alone, with `open` open. +fn start(home: &Home, open: &[String]) -> AppServer { + let dir = home.dir.path().to_path_buf(); + AppServer::start_in(exe(), Some(&home.root()), open, move |c: &mut Command| { + clean_env(c, &dir); + c.env("XDG_CONFIG_HOME", dir.join(".config")); + }) + .unwrap_or_else(|why| panic!("{why}")) +} + +/// Wait until `ok`, at most a minute. +fn until(what: &str, mut ok: impl FnMut() -> bool) { + let end = Instant::now() + Duration::from_secs(60); + while !ok() { + assert!(Instant::now() < end, "never: {what}"); + std::thread::sleep(Duration::from_millis(20)); + } +} + +/// Whether the books `id` are open, by the server's own list. +fn open_in_server(home: &Home, id: &str) -> bool { + match home.admin(Request::List) { + Response::Books(books) => books.iter().any(|b| b.id == id && b.open), + other => panic!("{other:?}"), + } +} + +#[test] +fn the_server_is_a_child_that_closes_when_its_input_does() { + let home = Home::new("app-child"); + let run = home.run(); + let server = start(&home, &[]); + server.wait_ready(Duration::from_secs(60)).unwrap(); + assert!(app_hosted(&run), "the root is the app's from now on"); + assert!(server_lock_held(&run), "it holds the server lock"); + assert!(!host_lock_held(&run), "no host was started beside it"); + assert!( + matches!(home.admin(Request::List), Response::Books(_)), + "it answers on its admin socket" + ); + assert_eq!(server.exited(), None); + // Closed by closing its input, as the host does. + assert_eq!(server.stop(Duration::from_secs(60)), Stopped::Closed); + assert!( + server + .exited() + .is_some_and(|how| how.contains("exit status: 0") || how.contains("exit code: 0")), + "it exited cleanly: {:?}", + server.exited() + ); + until("the lock is let go", || !server_lock_held(&run)); + #[cfg(unix)] + assert!( + !run.join("admin.sock").exists() && !run.join("mcp.sock").exists(), + "its sockets are removed" + ); +} + +#[test] +fn opening_and_closing_a_company_drives_the_servers_book() { + let home = Home::new("app-tabs"); + let server = start(&home, &[]); + server.wait_ready(Duration::from_secs(60)).unwrap(); + home.create(BOOK, "USD"); + assert!(open_in_server(&home, BOOK)); + // A tab closed: the book is closed in the server. + assert_eq!(server.close_book(BOOK), Ok(None)); + assert!(!open_in_server(&home, BOOK)); + // Closed again, or one that isn't there: nothing to say. + assert_eq!(server.close_book(BOOK), Ok(None)); + // A tab opened: the book is open again. + assert_eq!(server.open_book(BOOK), Ok(None)); + assert!(open_in_server(&home, BOOK)); + assert_eq!(server.open_book(BOOK), Ok(None), "already open: fine"); + // A company that isn't in the root is said in words. + let refused = server.open_book("nope").unwrap_err(); + assert!(refused.contains("no books called"), "{refused}"); + assert_eq!(server.stop(Duration::from_secs(60)), Stopped::Closed); + // After it, a request says so rather than hanging. + assert!(server.open_book(BOOK).is_err()); +} + +#[test] +fn a_start_is_refused_when_another_program_has_the_books() { + let home = Home::new("app-refused"); + let run = home.run(); + let dir = home.dir.path().to_path_buf(); + let try_start = || { + let dir = dir.clone(); + AppServer::start_in(exe(), Some(&home.root()), &[], move |c: &mut Command| { + clean_env(c, &dir); + }) + }; + // A books server holds them (another window, or one still finishing). + let other = Server::start_with(&home, &["--open", "none"]); + let refused = try_start().err().expect("refused"); + assert_eq!(refused, ANOTHER_HAS_THEM); + assert!(!run.join(APP_MARKER).exists(), "a refusal touches nothing"); + other.close(); + until("the other let go", || !server_lock_held(&run)); + // A host holds them. + let lock = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(run.join("host.lock")) + .unwrap(); + lock.lock().unwrap(); + assert_eq!(try_start().err().expect("refused"), ANOTHER_HAS_THEM); + assert!(!run.join(APP_MARKER).exists()); + drop(lock); + // Held by nobody: it starts. + let server = try_start().expect("started"); + server.wait_ready(Duration::from_secs(60)).unwrap(); + assert_eq!(server.stop(Duration::from_secs(60)), Stopped::Closed); +} + +/// What the helper process below says, one line each. +const CHILD_PID: &str = "wb-app-child-pid "; +const READY: &str = "wb-app-ready"; + +/// Not a test of its own: the "window" the next test kills. It starts the +/// books server as the app does and then waits to be killed; run by any +/// other means it does nothing. +#[test] +fn a_window_that_is_about_to_die() { + let Some(home) = std::env::var_os("WB_APP_DYING_HOME") else { + return; + }; + let home = std::path::PathBuf::from(home); + let root = ledger_store::root::default_root(&home); + let dir = home.clone(); + let server = AppServer::start_in(exe(), Some(&root), &[], move |c: &mut Command| { + clean_env(c, &dir); + c.env("XDG_CONFIG_HOME", dir.join(".config")); + }) + .expect("started"); + server.wait_ready(Duration::from_secs(60)).unwrap(); + println!("{CHILD_PID}{}", server.pid()); + println!("{READY}"); + let _ = std::io::stdout().flush(); + std::thread::sleep(Duration::from_secs(600)); +} + +#[test] +fn a_window_that_dies_leaves_no_server_and_no_half_closed_book() { + let home = Home::new("app-dies"); + let run = home.run(); + let mut window = Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "a_window_that_is_about_to_die", "--nocapture"]) + .env("WB_APP_DYING_HOME", home.dir.path()) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + // Whatever happens, the stand-in window does not outlive this test. + struct Reap(Child); + impl Drop for Reap { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + let mut lines = BufReader::new(window.stdout.take().unwrap()).lines(); + let mut server_pid = None; + loop { + let line = lines.next().expect("the window said ready").unwrap(); + if let Some(pid) = line.strip_prefix(CHILD_PID) { + server_pid = pid.trim().parse::().ok(); + } + if line == READY { + break; + } + } + let mut window = Reap(window); + assert!(server_lock_held(&run), "the server is running"); + home.create(BOOK, "USD"); + // The window is killed outright: no chance to close anything. + window.0.kill().unwrap(); + window.0.wait().unwrap(); + until("the server let go of the books", || !server_lock_held(&run)); + #[cfg(unix)] + { + let pid = server_pid.expect("the window gave the server's pid") as i32; + until("the server's process is gone", || { + // SAFETY: signal 0 only asks whether the process exists; the + // pid is the server this test's own helper started. + unsafe { libc::kill(pid, 0) != 0 } + }); + assert!( + !run.join("admin.sock").exists(), + "the books closed as at any close: the socket is removed" + ); + } + let _ = server_pid; + // The books are whole: a new server opens them without a word. + let again = start(&home, &[BOOK.to_string()]); + again.wait_ready(Duration::from_secs(60)).unwrap(); + assert!(open_in_server(&home, BOOK)); + assert_eq!(again.stop(Duration::from_secs(60)), Stopped::Closed); +} + +/// A "server" that takes five seconds to close once its input ends. +#[cfg(unix)] +fn slow_closer(dir: &Path) -> std::path::PathBuf { + use std::os::unix::fs::PermissionsExt; + let path = dir.join("slow-server"); + std::fs::write( + &path, + "#!/bin/sh\necho ready\ncat >/dev/null\nsleep 5\nexit 0\n", + ) + .unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + path +} + +#[cfg(unix)] +#[test] +fn a_stop_that_runs_out_of_time_leaves_the_server_closing_and_says_so() { + let home = Home::new("app-slow"); + let slow = slow_closer(home.dir.path()); + let server = AppServer::start_in(&slow, Some(&home.root()), &[], |_| {}).unwrap(); + server.wait_ready(Duration::from_secs(60)).unwrap(); + let pid = server.pid() as i32; + let started = Instant::now(); + assert_eq!( + server.stop(Duration::from_millis(300)), + Stopped::StillClosing + ); + assert!( + started.elapsed() < Duration::from_secs(4), + "the window is not held for the server's whole close" + ); + // Left alone: still running, nothing signalled. + assert_eq!(server.exited(), None); + // SAFETY: signal 0 only asks whether the process exists; it is the + // child this test started. + assert_eq!(unsafe { libc::kill(pid, 0) }, 0, "it was not killed"); + // It finishes by itself. + assert_eq!(server.stop(Duration::from_secs(30)), Stopped::Closed); +} + +/// An agent's bridge, spoken to as a client over stdio. +struct Bridge { + child: Child, + stdin: std::process::ChildStdin, + lines: mpsc::Receiver, + next: u64, +} + +impl Bridge { + fn start(home: &Home) -> Self { + let mut c = Command::new(exe()); + c.args(["mcp", "--book", BOOK, "--root"]).arg(home.root()); + clean_env(&mut c, home.dir.path()); + let mut child = c + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .unwrap(); + let stdin = child.stdin.take().unwrap(); + let stdout = child.stdout.take().unwrap(); + let (tx, lines) = mpsc::channel(); + std::thread::spawn(move || { + for line in BufReader::new(stdout).lines().map_while(Result::ok) { + if let Ok(v) = serde_json::from_str::(&line) { + let _ = tx.send(v); + } + } + }); + Self { + child, + stdin, + lines, + next: 1, + } + } + + /// Send a request and return the answer to it. + fn ask(&mut self, method: &str, params: Value) -> Value { + let id = self.next; + self.next += 1; + let line = json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}); + writeln!(self.stdin, "{line}").unwrap(); + self.stdin.flush().unwrap(); + let end = Instant::now() + Duration::from_secs(60); + loop { + let left = end.saturating_duration_since(Instant::now()); + let said = self + .lines + .recv_timeout(left) + .unwrap_or_else(|_| panic!("no answer to {method}")); + if said["id"] == json!(id) { + return said; + } + } + } + + fn initialize(&mut self) -> Value { + self.ask( + "initialize", + json!({"protocolVersion": common::PROTOCOL, "capabilities": {}, + "clientInfo": {"name": "test", "version": "0"}}), + ) + } + + fn start_call(&mut self) -> Value { + self.ask( + "tools/call", + json!({"name": "books.start", "arguments": {}}), + ) + } +} + +impl Drop for Bridge { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +fn error_of(answer: &Value) -> String { + answer["error"]["message"] + .as_str() + .unwrap_or_else(|| panic!("an error was expected: {answer}")) + .to_string() +} + +#[test] +fn the_bridge_says_the_app_isnt_running_then_works_once_it_is() { + let home = Home::new("app-bridge"); + let run = home.run(); + // The app has served this root (it wrote its mark), and isn't running. + std::fs::write(run.join(APP_MARKER), b"").unwrap(); + let mut bridge = Bridge::start(&home); + let not_running = format!("Wanderbooks isn't running: start Wanderbooks and open {BOOK}."); + assert_eq!(error_of(&bridge.initialize()), not_running); + assert_eq!(error_of(&bridge.start_call()), not_running); + // No host was started for it. + assert!(!host_lock_held(&run)); + assert!(!run.join("lease.sock").exists()); + // The app starts, with the company closed. + let server = start(&home, &[]); + server.wait_ready(Duration::from_secs(60)).unwrap(); + home.create(BOOK, "USD"); + let token = home.token_with(BOOK, "agent", &["read", "write", "post", "admin"]); + ledger_host::tokens::keeper(&run) + .set( + &ledger_host::tokens::Account::new(&home.root(), BOOK, "agent"), + &token, + ) + .unwrap(); + assert_eq!(server.close_book(BOOK), Ok(None)); + let not_open = format!("Company {BOOK} isn't open: open it in Wanderbooks."); + assert_eq!(error_of(&bridge.start_call()), not_open); + // Its tab opens: the same session goes through. + assert_eq!(server.open_book(BOOK), Ok(None)); + let answered = bridge.start_call(); + assert!( + answered.get("error").is_none() && answered.get("result").is_some(), + "{answered}" + ); + assert!(!host_lock_held(&run), "still no host"); + // The company's tab closes under the running session: said again. + assert_eq!(server.close_book(BOOK), Ok(None)); + assert_eq!(error_of(&bridge.start_call()), not_open); + // The window closes: said again, in the same session. + assert_eq!(server.stop(Duration::from_secs(60)), Stopped::Closed); + assert_eq!(error_of(&bridge.start_call()), not_running); +} + +/// The window's host, starting the real server of this program on +/// `home`'s root alone, looking at it every `slice` while it starts. +fn host_of(home: &Home, slice: Duration) -> AppHost { + let dir = home.dir.path().to_path_buf(); + let root = home.root(); + AppHost::with_starter(slice, move |open| { + let dir = dir.clone(); + AppServer::start_in(exe(), Some(&root), open, move |c: &mut Command| { + clean_env(c, &dir); + c.env("XDG_CONFIG_HOME", dir.join(".config")); + }) + }) +} + +/// An executable shell script `body` in `dir`. +#[cfg(unix)] +fn script(dir: &Path, name: &str, body: &str) -> std::path::PathBuf { + use std::os::unix::fs::PermissionsExt; + let path = dir.join(name); + std::fs::write(&path, body).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + path +} + +/// A host whose "server" is `program`, which is not a books server. +#[cfg(unix)] +fn host_of_program( + program: std::path::PathBuf, + home: &Home, + started: std::sync::Arc, +) -> AppHost { + let root = home.root(); + AppHost::with_starter(Duration::from_millis(100), move |open| { + started.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + AppServer::start_in(&program, Some(&root), open, |_| {}) + }) +} + +#[cfg(unix)] +fn alive(pid: u32) -> bool { + // SAFETY: signal 0 only asks whether the process exists; the pid is a + // child this test started. + unsafe { libc::kill(pid as i32, 0) == 0 } +} + +/// A server that is alive but never ready, and a window that stops: no +/// server is left running that nothing manages (finding: a failed or +/// late start). +#[cfg(unix)] +#[test] +fn a_server_that_never_gets_ready_is_stopped_with_the_window_and_not_left_behind() { + let home = Home::new("host-never-ready"); + let never = script( + home.dir.path(), + "never-ready", + "#!/bin/sh\ncat >/dev/null\nexit 0\n", + ); + let started = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let host = std::sync::Arc::new(host_of_program(never, &home, started)); + let starting = std::thread::spawn({ + let host = host.clone(); + move || host.start(&[]) + }); + until("the server was started", || host.running().is_ok()); + let pid = host.running().unwrap().pid(); + // Waited for, not given up on: well past several looks at it. + std::thread::sleep(Duration::from_millis(500)); + assert!(!starting.is_finished(), "a live server is waited for"); + assert!(alive(pid)); + // The window closes: the server's input closes, it exits, the start + // ends, and nothing runs. + assert_eq!(host.stop(Duration::from_secs(30)), Ok(None)); + let came = starting.join().unwrap(); + assert!(came.is_err(), "{came:?}"); + until("the server's process is gone", || !alive(pid)); +} + +/// The window closes after the child was spawned and before the start +/// stored it (finding: the window closed before the start thread stored +/// the child): the start stops it itself. +#[cfg(unix)] +#[test] +fn a_window_closed_before_the_child_was_stored_stops_the_child() { + let home = Home::new("host-closed-early"); + let never = script( + home.dir.path(), + "never-ready", + "#!/bin/sh\ncat >/dev/null\nexit 0\n", + ); + let pids = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let me: std::sync::Arc>>> = + std::sync::Arc::new(std::sync::Mutex::new(None)); + let root = home.root(); + let host = std::sync::Arc::new(AppHost::with_starter(Duration::from_millis(100), { + let (pids, me) = (pids.clone(), me.clone()); + move |open| { + let server = AppServer::start_in(&never, Some(&root), open, |_| {})?; + pids.lock().unwrap().push(server.pid()); + // The window is closed right here: after the spawn, before + // the host has the child. + let host = me.lock().unwrap().clone().unwrap(); + assert_eq!(host.stop(Duration::from_secs(5)), Ok(None)); + Ok(server) + } + })); + *me.lock().unwrap() = Some(host.clone()); + let came = host.start(&[]); + assert!(came.is_err(), "{came:?}"); + let pid = pids.lock().unwrap()[0]; + until("the child is gone", || !alive(pid)); + // And no start after the window has closed spawns anything. + let before = pids.lock().unwrap().len(); + assert!(host.start(&[]).is_err()); + assert_eq!(pids.lock().unwrap().len(), before); +} + +/// A server that is alive but late (still waiting on another's lock, or +/// opening a big company) is waited for, and then managed like any. +#[cfg(unix)] +#[test] +fn a_late_server_is_waited_for_and_stays_the_windows_to_manage() { + let home = Home::new("host-late"); + let late = script( + home.dir.path(), + "late", + &format!("#!/bin/sh\nsleep 1\nexec \"{}\" \"$@\"\n", exe().display()), + ); + let dir = home.dir.path().to_path_buf(); + let root = home.root(); + let host = AppHost::with_starter(Duration::from_millis(150), move |open| { + let dir = dir.clone(); + AppServer::start_in(&late, Some(&root), open, move |c: &mut Command| { + clean_env(c, &dir); + c.env("XDG_CONFIG_HOME", dir.join(".config")); + }) + }); + let begun = Instant::now(); + host.start(&[]).expect("started, late"); + assert!( + begun.elapsed() >= Duration::from_millis(900), + "{:?}", + begun.elapsed() + ); + // Managed: a tab's company opens and closes in it. + home.create(BOOK, "USD"); + assert_eq!(host.close_book(BOOK), Ok(None)); + assert_eq!(host.open_book(BOOK), Ok(None)); + assert_eq!(host.stop(Duration::from_secs(60)), Ok(None)); +} + +#[test] +fn a_whole_close_says_nothing_and_a_second_stop_is_quiet() { + let home = Home::new("host-whole"); + let host = host_of(&home, Duration::from_secs(60)); + host.start(&[]).unwrap(); + home.create(BOOK, "USD"); + assert_eq!(host.stop(Duration::from_secs(60)), Ok(None)); + assert_eq!(host.stop(Duration::from_secs(60)), Ok(None)); + assert!(!server_lock_held(&home.run())); +} + +/// A server that exits badly is said, in words (finding: the window's +/// close hides a failed exit). +#[cfg(unix)] +#[test] +fn a_server_that_exits_badly_is_said_when_the_window_closes() { + let home = Home::new("host-bad-exit"); + let bad = script( + home.dir.path(), + "bad-exit", + &format!( + "#!/bin/sh\necho {}\ncat >/dev/null\nexit 3\n", + ledger_mcp::local::READY + ), + ); + let started = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let host = host_of_program(bad, &home, started); + host.start(&[]).unwrap(); + let said = host.stop(Duration::from_secs(30)).unwrap().expect("a word"); + assert!( + said.contains("ended badly") && said.contains("exit status: 3"), + "{said}" + ); +} + +/// A company whose last backup is not whole at the window's close is +/// named, in words, with the reason (finding: the window's close hides an +/// incomplete last backup). +#[test] +fn a_closing_backup_that_was_not_whole_is_said_when_the_window_closes() { + let home = Home::new("host-backup"); + let host = host_of(&home, Duration::from_secs(60)); + host.start(&[]).unwrap(); + home.create(BOOK, "USD"); + // A backup folder that becomes a file: the backup cannot be made. + let disk = home.dir.path().join("disk"); + std::fs::create_dir_all(&disk).unwrap(); + let mut w = common::Wire::new(&home, BOOK); + w.initialize("owner"); + let set = w.call( + "books.set_setting", + json!({"changes": [{"key": "backup.folder", "value": disk.display().to_string()}], + "decided_by": "Test Owner", "note": "Backups."}), + ); + assert_eq!(set["result"]["isError"], json!(false), "{set}"); + let drafted = w.call( + "books.draft_entry", + json!({"date": "2026-03-01", "description": "moves the head"}), + ); + assert_eq!(drafted["result"]["isError"], json!(false), "{drafted}"); + w.end(); + std::fs::remove_dir_all(&disk).unwrap(); + std::fs::write(&disk, b"not a folder").unwrap(); + let said = host + .stop(Duration::from_secs(60)) + .unwrap() + .expect("the incomplete backup is said"); + assert!( + said.contains(BOOK) && said.contains("last backup wasn't whole"), + "{said}" + ); + assert!( + !said.contains(&home.dir.path().display().to_string()), + "names the home: {said}" + ); +} + +#[test] +fn a_company_the_server_does_not_have_open_is_told() { + let home = Home::new("host-not-open"); + let host = host_of(&home, Duration::from_secs(60)); + host.start(&[]).unwrap(); + home.create(BOOK, "USD"); + assert_eq!(host.not_open(&[BOOK.to_string()]), vec![]); + // Closed in the server: it is not open for assistants. + assert_eq!(host.close_book(BOOK), Ok(None)); + let told = host.not_open(&[BOOK.to_string(), "nope".to_string()]); + assert_eq!(told.len(), 2, "{told:?}"); + assert_eq!(told[0].0, BOOK); + assert!( + told[0].1.contains("couldn't be opened for your assistants"), + "{told:?}" + ); + assert_eq!(told[1].0, "nope"); + assert!(told[1].1.contains("doesn't have it"), "{told:?}"); + // Nothing is said about a server that isn't there. + assert_eq!(host.stop(Duration::from_secs(60)), Ok(None)); + assert_eq!(host.not_open(&[BOOK.to_string()]), vec![]); +} + +/// The format upgrade, asked under the app: it goes to the window's own +/// server and is answered by it, not by a host lease that does not exist +/// (finding: "Upgrade format" is broken under the app). +#[test] +fn the_format_upgrade_goes_to_the_windows_own_server() { + let home = Home::new("host-upgrade"); + let host = host_of(&home, Duration::from_secs(60)); + // No server yet: said before anything is done, in words. + let early = host.upgrade_format(BOOK, "a passphrase").unwrap_err(); + assert!( + early.contains("isn't running") && early.contains("nothing was done"), + "{early}" + ); + host.start(&[]).unwrap(); + home.create(BOOK, "USD"); + // The server answers (a refusal of this passphrase, or books already + // in this format): never the lease-socket's "host gave no answer". + match host.upgrade_format(BOOK, "not the owner passphrase") { + Ok(lines) => assert!(!lines.is_empty()), + Err(why) => { + assert!(why.starts_with("not upgraded: "), "{why}"); + assert!(!why.contains("host gave no answer"), "{why}"); + } + } + // A company that isn't there is refused by the server, in its words. + let refused = host.upgrade_format("nope", "x").unwrap_err(); + assert!(refused.starts_with("not upgraded: "), "{refused}"); + assert_eq!(host.stop(Duration::from_secs(60)), Ok(None)); +} diff --git a/crates/ledger-gui/src/app.rs b/crates/ledger-gui/src/app.rs index 8737e322..51b3acf3 100644 --- a/crates/ledger-gui/src/app.rs +++ b/crates/ledger-gui/src/app.rs @@ -7,7 +7,8 @@ //! (the color scheme, the dock's preferences) is kept once. //! SOURCE: plan/p15-app-and-relay.md 3.2 (tabs: `App` holds the per-app //! state and a `CompanyView` per tab); D-78 (one top-level tab per -//! open company). +//! open company); 3.1 (a tab is a company open in the books +//! server the app runs); WB-app-2, WB-app-4. //! INVARIANTS: //! 1. One view per open company, no company twice: opening one that is //! open shows its tab instead, and start-up opens each company of the @@ -52,12 +53,30 @@ //! (an export, a backup) is stopped with its tab, with no question. //! 6. The viewer stays read-only: a tab not in front reads what a tab //! in front reads, and writes nothing either. +//! 8. A tab is a company open in the books server the program runs for +//! the window, when it runs one (serving.rs, WB-app-2): the +//! companies restored at the start are opened with the server, a +//! company opened later when its tab opens, and closed when its tab +//! closes. What fails, and a server that stops on its own, is a +//! notice under the tab bar, in words, until dismissed. Where the +//! session list and the connection states will go (A4) is +//! `Self::connection_slot`. +//! 9. Asked to close, a window with a server stays up, saying it is +//! closing the books, until the server has exited or its bounded +//! close has run out (and then says what is left); a close is never +//! begun while a job that changes the books runs (7) (WB-app-4). +//! When the close says something was not whole (a company's last +//! backup, a server that exited badly), the window stays up showing +//! it, with a "Close anyway" button; closing again is not that. +//! A server still starting is said under the tab bar, and one whose +//! start failed has a "Try again" button there (WB-app-2). //! ``` use crate::company::CompanyView; use crate::data::Source; use crate::nav::Route; use crate::scheme_menu::SchemeMenu; +use crate::serving::Serving; use crate::tabs::{Listed, Tab, TabAction, TabBar}; use crate::theme::{self, pal}; use egui::{Frame, RichText, Ui}; @@ -138,6 +157,14 @@ pub struct App { /// Whether the list of open companies is written when the app saves /// (INVARIANT 3: not after a start that named a company). writes_open_list: bool, + /// The window asked to close and the server's close is being waited + /// for: the window closes when it is done (INVARIANT 9). + closing_window: bool, + /// The books server the program runs for the window, if it runs one: + /// a tab is a company open in it (INVARIANT 8). + serving: Serving, + /// What the server work has said that the person has not dismissed. + notices: Vec, } /// What a window is called when no company is in front. @@ -161,6 +188,18 @@ impl App { ctx: &egui::Context, get: &dyn Fn(&str) -> Option, start: Start, + ) -> Self { + Self::start_with_owner(ctx, get, start, crate::owner::current()) + } + + /// [`Self::start_with`], with the program's owner given (tests give + /// one that hosts a server of its own): the server it hosts starts + /// with the companies this start opens (INVARIANT 8). + pub fn start_with_owner( + ctx: &egui::Context, + get: &dyn Fn(&str) -> Option, + start: Start, + owner: Option>, ) -> Self { let mut app = Self::without_books(ctx, get); match start { @@ -171,6 +210,9 @@ impl App { .map(std::path::Path::to_path_buf); app.remember_all(get); app.remember_scope(get, &kept_scope_of(&source.data_dir)); + // A company of a data root is served; the demo's is not. + let id = crate::owner::book_id_of_dir(&source.data_dir); + app.serving = Serving::start(owner, id.into_iter().collect()); app.open(ctx, source); } Start::Restore { root, fallback } => { @@ -181,7 +223,10 @@ impl App { let wanted: Vec = get(&open_key(&root)) .map(|v| v.split(',').map(str::to_string).collect()) .unwrap_or_default(); + // The companies this start opens, in order (INVARIANT 3): + // the server starts with exactly these open. let mut opened = Vec::new(); + let mut sources = Vec::new(); for id in wanted { // Gone, or listed twice: skipped, with no word. if !there.contains(&id) || opened.contains(&id) { @@ -193,13 +238,16 @@ impl App { let Ok(r) = ledger_store::root::Root::find(Some(&root)) else { break; }; - let source = Source { + sources.push(Source { data_dir: r.book_dir(&book), today: app.today, - }; - app.open(ctx, source); + }); opened.push(id); } + app.serving = Serving::start(owner, opened.clone()); + for source in sources { + app.open(ctx, source); + } if app.views.is_empty() { app.open(ctx, fallback); } else { @@ -287,6 +335,9 @@ impl App { first_run_source: (None, None), close_dialog: false, writes_open_list: true, + closing_window: false, + serving: Serving::off(), + notices: Vec::new(), } } @@ -374,6 +425,140 @@ impl App { }); } + /// Asked to close, a window with a server stays up, saying it is + /// closing the books, until the server has exited or its bounded + /// close has run out (INVARIANT 9). A job that changes the books holds + /// the window first (`guard_close`), and no close begins meanwhile. + fn guard_server_close(&mut self, ctx: &egui::Context) { + if !self.serving.is_on() || !self.holding().is_empty() { + return; + } + let asked = ctx.input(|i| i.viewport().close_requested()); + // What the close said was not whole is read before the window goes + // (INVARIANT 9): asking again is not reading it. + let report = self.serving.close_report(); + if asked && (!self.serving.is_closed() || !report.is_empty()) { + ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); + self.serving.begin_stop(); + self.closing_window = true; + } + if !self.closing_window { + return; + } + if self.serving.is_closed() { + if report.is_empty() { + self.closing_window = false; + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + return; + } + let mut close_anyway = false; + egui::Modal::new(egui::Id::new("wanderbooks-closed-with-problems")).show(ctx, |ui| { + ui.set_max_width(520.0); + ui.heading("Your books did not close cleanly"); + ui.add_space(4.0); + for line in &report { + ui.label(line); + ui.add_space(2.0); + } + ui.add_space(6.0); + if ui.button("Close anyway").clicked() { + close_anyway = true; + } + }); + if close_anyway { + self.serving.acknowledge_close(); + self.closing_window = false; + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + return; + } + egui::Modal::new(egui::Id::new("wanderbooks-closing-books")).show(ctx, |ui| { + ui.set_max_width(460.0); + ui.heading("Closing your books"); + ui.add_space(4.0); + ui.label( + "Finishing what is running and making each company's last backup. \ + This can take a minute; the window closes by itself.", + ); + ui.add_space(6.0); + ui.spinner(); + }); + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } + + /// The notices from the server work, shown under the tab bar until + /// dismissed (INVARIANT 8). + fn show_notices(&mut self, ui: &mut Ui) { + self.notices.extend(self.serving.take_notices()); + let starting = self.serving.is_starting(); + let down = self.serving.is_down(); + if self.notices.is_empty() && !starting && !down { + return; + } + let p = pal(ui.ctx()); + let mut dismiss = None; + let mut retry = false; + egui::Panel::top("server_notices") + .resizable(false) + .frame( + Frame::new() + .fill(p.warning_soft) + .inner_margin(egui::Margin::symmetric(12, 6)), + ) + .show(ui, |ui| { + if starting { + ui.horizontal_wrapped(|ui| { + ui.spinner(); + ui.label( + RichText::new( + "Starting the books server for your assistants: another program may still be finishing with the books.", + ) + .color(p.text), + ); + }); + } + for (i, words) in self.notices.iter().enumerate() { + ui.horizontal_wrapped(|ui| { + ui.label(RichText::new(words).color(p.text)); + if down && ui.button("Try again").clicked() { + retry = true; + } + if ui.button("Dismiss").clicked() { + dismiss = Some(i); + } + }); + } + if down && self.notices.is_empty() && ui.button("Try again").clicked() { + retry = true; + } + }); + if retry { + self.serving.retry(); + } + if let Some(i) = dismiss { + self.notices.remove(i); + } + if starting { + ui.ctx() + .request_repaint_after(std::time::Duration::from_millis(500)); + } + } + + /// What the server work has said that has not been dismissed (tests). + pub fn notices(&mut self) -> &[String] { + self.notices.extend(self.serving.take_notices()); + &self.notices + } + + /// The server work of the window (tests). + pub fn serving(&self) -> &Serving { + &self.serving + } + + /// Where the connection states and the list of who is connected will + /// be shown (plan 3.3, unit A4); nothing is drawn yet. + fn connection_slot(&mut self, _ui: &mut Ui) {} + /// The window's title now. pub fn window_title(&self) -> String { match self.active_view() { @@ -417,7 +602,13 @@ impl App { return i; } let view = CompanyView::open(ctx, source).with_dock(self.new_dock()); - self.add_view(view) + let at = self.add_view(view); + // A tab is a company open in the server (INVARIANT 8): one this + // start opened is open in it already. + if let Some(id) = self.views[at].book_id() { + self.serving.open(&id); + } + at } /// Close tab `i`: its view is dropped (INVARIANT 2). The tab after it, @@ -438,6 +629,10 @@ impl App { self.kept.insert(stored(&scope, k), v); }); } + // The company is closed in the server with its tab (INVARIANT 8). + if let Some(id) = view.book_id() { + self.serving.close(&id); + } drop(view); if i < self.active || self.active >= self.views.len() { self.active = self.active.saturating_sub(1); @@ -496,6 +691,11 @@ impl App { match crate::book_in_root(root.as_deref(), Some(id)) { Ok(data_dir) => { self.today = today; + // The first company of a first run: the server starts with + // it (INVARIANT 8), if the program runs one. + if !self.serving.is_on() { + self.serving = Serving::start(crate::owner::current(), vec![id.to_string()]); + } self.open(ctx, Source { data_dir, today }); self.welcome = None; } @@ -758,6 +958,7 @@ impl eframe::App for App { v.pump(&ctx, i == self.active); } self.guard_close(&ctx); + self.guard_server_close(&ctx); self.check_identities(); self.learn_names(); let tabs: Vec = self @@ -781,6 +982,8 @@ impl eframe::App for App { // The bar goes across the whole window, above everything of the // company in front: a tab is the top level (D-78). let action = self.tabs.show(ui, &tabs, shown, &others); + self.show_notices(ui); + self.connection_slot(ui); let active = self.active; match self.views.get_mut(active) { Some(v) => v.ui(ui, &mut self.schemes), diff --git a/crates/ledger-gui/src/lib.rs b/crates/ledger-gui/src/lib.rs index 80daf6ab..75d17ce0 100644 --- a/crates/ledger-gui/src/lib.rs +++ b/crates/ledger-gui/src/lib.rs @@ -23,6 +23,7 @@ mod prefs; mod receipts; mod scheme_menu; mod schemes; +pub mod serving; pub mod tabs; #[cfg(test)] mod test_support; diff --git a/crates/ledger-gui/src/owner.rs b/crates/ledger-gui/src/owner.rs index b5b45019..5b124fa7 100644 --- a/crates/ledger-gui/src/owner.rs +++ b/crates/ledger-gui/src/owner.rs @@ -157,6 +157,48 @@ pub struct UpdateWaiting { /// over the books server and the agents' own commands). Each blocks: the /// menu calls it off the UI thread. pub trait Owner: Send + Sync { + /// Whether this program hosts the books' server for the window (plan + /// P15 3.1: the app starts it, as a child process, and closes it): when + /// it does not, the window asks nothing of a server (`serve_*`). + fn serves(&self) -> bool { + false + } + /// Start the books server with the companies `open` (their ids) open, + /// and return when it is ready, or why it is not. Blocks. + fn serve_start(&self, _open: &[String]) -> Result<(), String> { + Ok(()) + } + /// 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> { + Ok(None) + } + /// Close the company `book` in the server (a tab closed): `Ok(None)` + /// when it is closed, `Ok(Some(words))` when it is closed but its last + /// backup wasn't whole, `Err` when it could not be asked or refused. + /// Blocks (a backup is made first). + fn serve_close(&self, _book: &str) -> Result, String> { + Ok(None) + } + /// Of the companies `wanted` (asked to be open at the start), those + /// the server does not have open now, each with why in words: asked + /// once the server is ready. Blocks. + fn serve_not_open(&self, _wanted: &[String]) -> Vec<(String, String)> { + Vec::new() + } + /// Close the server (the window closed): each open company is closed + /// first, then the server's input, and the exit is waited for, for a + /// bounded time. `Ok(Some(words))` says what was not whole, a line + /// each: a company whose last backup was incomplete, a server that + /// exited badly, one still finishing by itself after the wait. Blocks. + fn serve_stop(&self) -> Result, String> { + Ok(None) + } + /// Why the server is gone, if it has exited on its own. Cheap: asked + /// on every frame. + fn serve_exited(&self) -> Option { + None + } /// Close the books: everything holding them lets go. fn close_books(&self) -> Result; /// New, empty books `id` in `currency`. @@ -235,8 +277,13 @@ pub fn current() -> Option> { /// The id of books of the data root (their folder's name), or None for /// books outside one, the demo's (INVARIANT 4). pub fn book_id(books: &Books) -> Option { - ledger_store::root::inside_a_root(&books.data_dir) - .then(|| books.data_dir.file_name()?.to_str().map(str::to_string)) + book_id_of_dir(&books.data_dir) +} + +/// [`book_id`] of the books in `dir`. +pub fn book_id_of_dir(dir: &std::path::Path) -> Option { + ledger_store::root::inside_a_root(dir) + .then(|| dir.file_name()?.to_str().map(str::to_string)) .flatten() } diff --git a/crates/ledger-gui/src/serving.rs b/crates/ledger-gui/src/serving.rs new file mode 100644 index 00000000..c3ae7350 --- /dev/null +++ b/crates/ledger-gui/src/serving.rs @@ -0,0 +1,452 @@ +//! The window's line to the books server (plan P15 3.1; D-77, D-78). +//! +//! ```text +//! GOAL: a tab is a company open in the books server, and the server is +//! the app's child: it starts with the companies the window +//! restored, a tab opened or closed opens or closes that company in +//! it, and closing the window closes it, in view and in bounded +//! time. What fails is said to the person, never swallowed. +//! SOURCE: plan/p15-app-and-relay.md 3.1 (the app starts the server and +//! closes it by closing its input; opening or closing a tab is +//! the server opening or closing that book), 3.2, D-77, D-78, +//! WB-app-2, WB-app-4. +//! INVARIANTS: +//! 1. Nothing here touches the UI thread's time: every request to the +//! server runs on a thread of its own, and the window only reads +//! the notices those threads leave. +//! 2. A company's requests are one queue, in the order they were made +//! (a tab closed and opened again is a close, then an open); no +//! company's request waits for another company's, so closing one +//! company's tab, which makes its last backup, delays no other. +//! 3. No request is made before the server has started, and none after +//! a start that failed (the person was told why, once). A start that +//! failed is tried again, with the companies wanted then, when the +//! next tab opens or the person asks (`retry`); the owner has +//! stopped the server that failed, so no second one runs beside it. +//! A server still starting is waited for, in view (`is_starting`). +//! 4. A company the window opened at the start is not opened again; a +//! company whose open failed, at the start (the server's list says +//! it isn't open: `serve_not_open`) or later, is a notice, and is +//! asked for again the next time its tab opens. +//! 5. A failed request, a close whose last backup wasn't whole, and a +//! server that has exited on its own are each a notice, in words, +//! once; the window shows them until they are dismissed. +//! 6. The server is closed once: by `begin_stop` (the window asked to +//! close, with the wait in view), else when this is dropped. Neither +//! returns before the owner's bounded close has, and neither kills +//! anything. What the close says was not whole (a company's last +//! backup, a server that exited badly) is the close's report: the +//! window stays up showing it until the person closes anyway +//! (`close_report`, `acknowledge_close`). +//! 7. Without an owner that hosts a server (the viewer on its own, the +//! demo, tests) it does nothing at all. +//! ``` + +use crate::owner::Owner; +use std::collections::{BTreeSet, HashMap}; +use std::sync::mpsc::{Sender, channel}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard}; + +/// Where the server's start stands (INVARIANT 3). +#[derive(Clone, Copy, PartialEq, Eq)] +enum Gate { + Starting, + Up, + Down, +} + +/// Where the server's close stands (INVARIANT 6). +#[derive(Clone, Copy, PartialEq, Eq)] +enum Closing { + Not, + Running, + Done, +} + +enum Cmd { + Open, + Close, +} + +#[derive(Default)] +struct State { + /// The companies the server has open, or is being asked to have. + wanted: BTreeSet, + /// What the person has not been told yet. + notices: Vec, + /// One queue per company (INVARIANT 2). + lanes: HashMap>, + /// The server's exit has been said. + exit_said: bool, + /// What the server's close said was not whole, a line each. + report: Vec, + /// The person has seen the report and chose to close anyway. + report_seen: bool, +} + +struct Inner { + owner: Arc, + gate: Mutex, + gate_changed: Condvar, + closing: Mutex, + closing_changed: Condvar, + state: Mutex, +} + +fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) +} + +impl Inner { + fn note(&self, words: String) { + lock(&self.state).notices.push(words); + } + + /// Wait for the start to have come out: whether the server is up. + fn up(&self) -> bool { + let mut gate = lock(&self.gate); + while *gate == Gate::Starting { + gate = self + .gate_changed + .wait(gate) + .unwrap_or_else(|e| e.into_inner()); + } + *gate == Gate::Up + } + + /// Close the server, once; the others wait for that one to be done. + fn close_server(&self) { + { + let mut closing = lock(&self.closing); + if *closing != Closing::Not { + while *closing != Closing::Done { + closing = self + .closing_changed + .wait(closing) + .unwrap_or_else(|e| e.into_inner()); + } + return; + } + *closing = Closing::Running; + } + let said: Vec = match self.owner.serve_stop() { + Ok(None) => Vec::new(), + Ok(Some(words)) => words.lines().map(str::to_string).collect(), + Err(why) => vec![format!( + "The books server could not be closed cleanly: {why}" + )], + }; + for line in &said { + // The window may be gone before anyone reads the report. + eprintln!("wanderbooks: {line}"); + } + lock(&self.state).report = said; + *lock(&self.closing) = Closing::Done; + self.closing_changed.notify_all(); + } +} + +/// The window's line to the server; one per window. +pub struct Serving { + inner: Option>, +} + +impl Serving { + /// No server: nothing is asked of any (INVARIANT 7). + pub fn off() -> Self { + Self { inner: None } + } + + /// Start the server with the companies `open` open, if `owner` hosts + /// one; the start runs on a thread of its own (INVARIANT 1). + pub fn start(owner: Option>, open: Vec) -> Self { + let Some(owner) = owner.filter(|o| o.serves()) else { + return Self::off(); + }; + let inner = Arc::new(Inner { + owner, + gate: Mutex::new(Gate::Starting), + gate_changed: Condvar::new(), + closing: Mutex::new(Closing::Not), + closing_changed: Condvar::new(), + state: Mutex::new(State { + wanted: open.iter().cloned().collect(), + ..State::default() + }), + }); + if !Self::spawn_start(&inner) { + inner.note( + "Assistants can't reach your companies: the books server could not be started." + .into(), + ); + *lock(&inner.gate) = Gate::Down; + } + Self { inner: Some(inner) } + } + + /// Start the server, on a thread of its own, with the companies + /// wanted now (INVARIANTS 1, 3, 4): false when no thread could be made. + fn spawn_start(inner: &Arc) -> bool { + let open: Vec = lock(&inner.state).wanted.iter().cloned().collect(); + let starting = inner.clone(); + std::thread::Builder::new() + .name("serving-start".into()) + .spawn(move || { + let came = match starting.owner.serve_start(&open) { + Ok(()) => { + // The server says ready once each company was + // tried: the ones that did not open are said, and + // asked for again with their tab (INVARIANT 4). + for (id, words) in starting.owner.serve_not_open(&open) { + lock(&starting.state).wanted.remove(&id); + starting.note(words); + } + Gate::Up + } + Err(why) => { + // 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}")); + } + Gate::Down + } + }; + *lock(&starting.gate) = came; + starting.gate_changed.notify_all(); + }) + .is_ok() + } + + /// Try a start that failed again, with the companies wanted now + /// (INVARIANT 3): true when one has begun. + pub fn retry(&self) -> bool { + let Some(inner) = &self.inner else { + return false; + }; + Self::restart(inner) + } + + fn restart(inner: &Arc) -> bool { + if *lock(&inner.closing) != Closing::Not { + return false; + } + { + let mut gate = lock(&inner.gate); + if *gate != Gate::Down { + return false; + } + *gate = Gate::Starting; + } + if Self::spawn_start(inner) { + return true; + } + inner.note( + "Assistants can't reach your companies: the books server could not be started.".into(), + ); + *lock(&inner.gate) = Gate::Down; + false + } + + /// Whether the server is still starting (INVARIANT 3): its tabs wait + /// for it, and the window says so. + pub fn is_starting(&self) -> bool { + self.inner + .as_ref() + .is_some_and(|i| *lock(&i.gate) == Gate::Starting) + } + + /// Whether the start failed and a `retry` would try again. + pub fn is_down(&self) -> bool { + self.inner + .as_ref() + .is_some_and(|i| *lock(&i.gate) == Gate::Down) + && !self.is_closing() + } + + /// Whether a server is being hosted for this window. + pub fn is_on(&self) -> bool { + self.inner.is_some() + } + + /// A tab for the company `id` opened: ask the server to open it, unless + /// it has it (INVARIANT 4). + pub fn open(&self, id: &str) { + let Some(inner) = &self.inner else { return }; + let fresh = lock(&inner.state).wanted.insert(id.to_string()); + // After a failed start the next tab is the next try (INVARIANT 3): + // the start opens every company wanted, this one included. + // A company already wanted is the window's own start-up opening + // the tabs it restored, which the start has in its list. + if fresh { + if Self::restart(inner) { + return; + } + Self::send(inner, id, Cmd::Open); + } + } + + /// The tab of the company `id` closed: ask the server to close it. + pub fn close(&self, id: &str) { + let Some(inner) = &self.inner else { return }; + let had = lock(&inner.state).wanted.remove(id); + if had { + Self::send(inner, id, Cmd::Close); + } + } + + /// Whether the server has, or is being asked to have, `id` open + /// (tests). + pub fn wants(&self, id: &str) -> bool { + self.inner + .as_ref() + .is_some_and(|i| lock(&i.state).wanted.contains(id)) + } + + /// Queue `cmd` for the company `id` on its own thread, made the first + /// time (INVARIANT 2). + fn send(inner: &Arc, id: &str, cmd: Cmd) { + let mut state = lock(&inner.state); + let mut cmd = cmd; + if let Some(lane) = state.lanes.get(id) { + match lane.send(cmd) { + Ok(()) => return, + // Its thread is gone: the command comes back, for a new one. + Err(back) => cmd = back.0, + } + } + let (tx, rx) = channel::(); + let worker = inner.clone(); + let book = id.to_string(); + let started = std::thread::Builder::new() + .name(format!("serving-{id}")) + .spawn(move || { + for cmd in rx { + // INVARIANT 3. + if !worker.up() { + continue; + } + match cmd { + Cmd::Open => match worker.owner.serve_open(&book) { + Ok(None) => {} + Ok(Some(words)) => worker.note(words), + Err(why) => { + lock(&worker.state).wanted.remove(&book); + worker.note(why); + } + }, + Cmd::Close => match worker.owner.serve_close(&book) { + Ok(None) => {} + Ok(Some(words)) => worker.note(words), + Err(why) => worker.note(format!( + "{book} could not be closed to your assistants: {why}" + )), + }, + } + } + }); + match started { + Ok(_) => { + let _ = tx.send(cmd); + state.lanes.insert(id.to_string(), tx); + } + Err(_) => { + drop(state); + inner.note(format!( + "Assistants may not be able to reach {id}: a thread could not be started." + )); + } + } + } + + /// What the person has not been told yet (INVARIANT 5), and, once, + /// that the server exited on its own. + pub fn take_notices(&self) -> Vec { + let Some(inner) = &self.inner else { + return Vec::new(); + }; + let closing = *lock(&inner.closing) != Closing::Not; + let mut state = lock(&inner.state); + if !state.exit_said + && !closing + && let Some(why) = inner.owner.serve_exited() + { + state.exit_said = true; + state.notices.push(format!( + "{why}. Assistants can't reach your companies until Wanderbooks is started again." + )); + } + std::mem::take(&mut state.notices) + } + + /// What the server's close said was not whole, a line each, until the + /// person has closed anyway (INVARIANT 6); nothing before the close + /// is done, or when it was whole. + pub fn close_report(&self) -> Vec { + let Some(inner) = &self.inner else { + return Vec::new(); + }; + if *lock(&inner.closing) != Closing::Done { + return Vec::new(); + } + let state = lock(&inner.state); + if state.report_seen { + Vec::new() + } else { + state.report.clone() + } + } + + /// The person has read the close's report and closes anyway. + pub fn acknowledge_close(&self) { + if let Some(inner) = &self.inner { + lock(&inner.state).report_seen = true; + } + } + + /// The window was asked to close: close the server on a thread of its + /// own, so the window can say so while it does (INVARIANT 6). + pub fn begin_stop(&self) { + let Some(inner) = &self.inner else { return }; + if *lock(&inner.closing) != Closing::Not { + return; + } + let inner = inner.clone(); + let spawned = std::thread::Builder::new() + .name("serving-stop".into()) + .spawn({ + let inner = inner.clone(); + move || inner.close_server() + }); + if spawned.is_err() { + inner.close_server(); + } + } + + /// Whether the close has begun. + pub fn is_closing(&self) -> bool { + self.inner + .as_ref() + .is_some_and(|i| *lock(&i.closing) != Closing::Not) + } + + /// Whether the close is done (or there is no server to close). + pub fn is_closed(&self) -> bool { + self.inner + .as_ref() + .is_none_or(|i| *lock(&i.closing) == Closing::Done) + } +} + +impl Drop for Serving { + /// The window is gone without having been asked to close first (a + /// signal, a test): the server is closed here, in bounded time, with + /// a line on stderr (INVARIANT 6). + fn drop(&mut self) { + let Some(inner) = &self.inner else { return }; + if *lock(&inner.closing) == Closing::Not { + eprintln!("wanderbooks: closing the books before it exits"); + } + inner.close_server(); + } +} diff --git a/crates/ledger-gui/tests/serving.rs b/crates/ledger-gui/tests/serving.rs new file mode 100644 index 00000000..6c5b7da5 --- /dev/null +++ b/crates/ledger-gui/tests/serving.rs @@ -0,0 +1,674 @@ +//! The window and the books server it runs (serving.rs, app.rs; +//! plan/p15-app-and-relay.md 3.1; WB-app-2, WB-app-4): a tab is a company +//! open in the server, and closing the window closes the server in view. +//! +//! ```text +//! GOAL: the server is started with the companies the window restored; +//! a tab opened or closed opens or closes that company in it; what +//! fails is said in words; closing the window closes the server and +//! says so while it waits, and the wait is the owner's bounded one. +//! SOURCE: plan/p15-app-and-relay.md 3.1 (a tab is a company open in the +//! server; the app closes it by closing its input; the close +//! dialog shows the wait), D-77, D-78, WB-app-2, WB-app-4. +//! INVARIANTS: +//! 1. The server starts once, with the restored companies, and none of +//! them is asked to open again. +//! 2. A tab opened is `serve_open`, a tab closed is `serve_close`, for +//! that company, in the order the tabs were opened and closed. +//! 3. A start that failed is a notice, and nothing is asked of the +//! server after it. +//! 4. A close that wasn't whole, a company that wouldn't open, and a +//! server that exited on its own are notices, in words. +//! 5. Asked to close, the window stays up saying it is closing the books +//! until the owner's close has returned; the owner is asked to close +//! once, however many times it is asked. +//! 6. A window with no owner that hosts a server asks nothing of any. +//! 7. A start that failed is tried again by the next tab that opens, or +//! by the person (`retry`); one still going is said to be starting. +//! 8. A company wanted at the start that the server did not open is a +//! notice, and its tab asks again when it opens. +//! 9. A close that says something was not whole keeps the window up, +//! showing it, until the person closes anyway. +//! ``` + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use ledger_core::Currency; +use ledger_gui::data::Source; +use ledger_gui::owner::{Agent, Owner, RestorePlan}; +use ledger_gui::serving::Serving; +use ledger_gui::{App, Start}; +use ledger_store::root::{BookId, Root}; +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +/// A data root of its own, with companies made in it. +struct World { + _dir: tempfile::TempDir, + root: PathBuf, +} + +impl World { + fn new(ids: &[&str]) -> World { + let dir = tempfile::Builder::new() + .prefix("wb-gui-serving-") + .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(); + for id in ids { + drop( + found + .create_book(&BookId::parse(id).unwrap(), Currency::USD) + .unwrap(), + ); + } + World { _dir: dir, root } + } + + fn source(&self, id: &str) -> Source { + Source { + data_dir: self.root.join("books").join(id), + today: None, + } + } + + /// The kept preferences that restore these companies as tabs. + fn kept(&self, open: &[&str]) -> HashMap { + HashMap::from([(ledger_gui::app::open_key(&self.root), open.join(","))]) + } + + fn start(&self, open: &[&str], owner: &Arc) -> App { + let kept = self.kept(open); + let owner: Arc = owner.clone(); + App::start_with_owner( + &egui::Context::default(), + &|k| kept.get(k).cloned(), + Start::Restore { + root: self.root.clone(), + fallback: self.source(open.first().copied().unwrap_or("alpha")), + }, + Some(owner), + ) + } +} + +/// An owner that hosts a server of its own, recording what it is asked. +#[derive(Default)] +struct Fake { + /// What was asked, in order: "start alpha,beta", "open gamma", "close + /// beta", "stop". + log: Mutex>, + /// What starting says, if not well. + start_says: Mutex>, + /// What closing each company says, if not plainly well. + close_says: Mutex, String>>>, + /// What opening each company says, if not well. + open_says: Mutex>, + /// How long the close of the server takes, and what it says after. + stop_takes: Mutex, + stop_says: Mutex>, + /// Why the server is gone, once it is. + exited: Mutex>, + /// How long starting takes. + start_takes: Mutex, + /// The wanted companies the server did not open, and why. + not_open_says: Mutex>, +} + +impl Fake { + fn new() -> Arc { + Arc::new(Fake::default()) + } + + fn said(&self) -> Vec { + self.log.lock().unwrap().clone() + } + + fn note(&self, what: String) { + self.log.lock().unwrap().push(what); + } +} + +impl Owner for Fake { + fn serves(&self) -> bool { + true + } + fn serve_start(&self, open: &[String]) -> Result<(), String> { + self.note(format!("start {}", open.join(","))); + std::thread::sleep(*self.start_takes.lock().unwrap()); + match self.start_says.lock().unwrap().clone() { + Some(why) => Err(why), + None => Ok(()), + } + } + fn serve_not_open(&self, _wanted: &[String]) -> Vec<(String, String)> { + std::mem::take(&mut *self.not_open_says.lock().unwrap()) + } + fn serve_open(&self, book: &str) -> Result, String> { + self.note(format!("open {book}")); + match self.open_says.lock().unwrap().remove(book) { + Some(why) => Err(why), + None => Ok(None), + } + } + fn serve_close(&self, book: &str) -> Result, String> { + self.note(format!("close {book}")); + self.close_says + .lock() + .unwrap() + .remove(book) + .unwrap_or(Ok(None)) + } + fn serve_stop(&self) -> Result, String> { + self.note("stop".into()); + std::thread::sleep(*self.stop_takes.lock().unwrap()); + Ok(self.stop_says.lock().unwrap().clone()) + } + fn serve_exited(&self) -> Option { + self.exited.lock().unwrap().clone() + } + fn close_books(&self) -> Result { + Err("not here".into()) + } + 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()) + } +} + +/// Wait until `ok` holds (the requests run on threads of their own). +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)); + } +} + +/// How long to wait for something that must NOT happen. +fn a_while() { + std::thread::sleep(Duration::from_millis(300)); +} + +fn tab_of(app: &App, id: &str) -> usize { + app.views() + .iter() + .position(|v| v.book_id().as_deref() == Some(id)) + .unwrap_or_else(|| panic!("no tab for {id}")) +} + +#[test] +fn the_companies_the_window_restores_are_the_servers_to_open() { + let w = World::new(&["alpha", "beta", "gamma"]); + let owner = Fake::new(); + let app = w.start(&["alpha", "beta"], &owner); + until("the server started", || !owner.said().is_empty()); + a_while(); + // Started once, with exactly the restored companies open; neither is + // asked to open again. + assert_eq!(owner.said(), vec!["start alpha,beta".to_string()]); + assert_eq!(app.views().len(), 2); + drop(app); +} + +#[test] +fn a_tab_opening_asks_the_server_to_open_that_company() { + let w = World::new(&["alpha", "gamma"]); + let owner = Fake::new(); + let ctx = egui::Context::default(); + let mut app = w.start(&["alpha"], &owner); + app.open(&ctx, w.source("gamma")); + until("gamma asked", || { + owner.said().contains(&"open gamma".to_string()) + }); + assert_eq!(owner.said()[0], "start alpha"); + assert!(app.serving().wants("gamma")); + // A company already open shows its tab and asks nothing more. + app.open(&ctx, w.source("gamma")); + a_while(); + assert_eq!( + owner.said().iter().filter(|s| *s == "open gamma").count(), + 1 + ); + drop(app); +} + +#[test] +fn a_tab_closing_asks_the_server_to_close_that_company() { + let w = World::new(&["alpha", "beta"]); + let owner = Fake::new(); + let ctx = egui::Context::default(); + let mut app = w.start(&["alpha", "beta"], &owner); + let beta = tab_of(&app, "beta"); + app.close(beta); + until("beta closed", || { + owner.said().contains(&"close beta".to_string()) + }); + assert!(!app.serving().wants("beta")); + assert!(app.serving().wants("alpha"), "the other stays open"); + // Closed and opened again: a close, then an open, in that order. + app.open(&ctx, w.source("beta")); + until("beta opened again", || { + owner.said().contains(&"open beta".to_string()) + }); + let said = owner.said(); + let close = said.iter().position(|s| s == "close beta").unwrap(); + let open = said.iter().position(|s| s == "open beta").unwrap(); + assert!(close < open, "{said:?}"); + assert!( + !said.contains(&"close alpha".to_string()), + "closing one tab closes no other: {said:?}" + ); + drop(app); +} + +#[test] +fn a_close_that_was_not_whole_is_said_to_the_person() { + let w = World::new(&["alpha", "beta"]); + let owner = Fake::new(); + owner.close_says.lock().unwrap().insert( + "beta".into(), + Ok(Some( + "beta is closed to your assistants, but its last backup wasn't whole: the backup folder is gone." + .into(), + )), + ); + owner.close_says.lock().unwrap().insert( + "alpha".into(), + Err("the books server isn't answering".into()), + ); + let mut app = w.start(&["alpha", "beta"], &owner); + let (beta, alpha) = (tab_of(&app, "beta"), tab_of(&app, "alpha")); + app.close(beta); + until("a notice about beta", || { + app.notices().iter().any(|n| n.contains("wasn't whole")) + }); + // A refused close is said too, naming the company. + let alpha = if alpha > beta { alpha - 1 } else { alpha }; + app.close(alpha); + until("a notice about alpha", || { + app.notices() + .iter() + .any(|n| n.contains("alpha could not be closed") && n.contains("isn't answering")) + }); + // A company that would not open for assistants is said too, and asked + // for again the next time its tab opens. + owner.open_says.lock().unwrap().insert( + "beta".into(), + "beta couldn't be opened for your assistants: x".into(), + ); + let ctx = egui::Context::default(); + app.open(&ctx, w.source("beta")); + until("a notice about the open", || { + app.notices() + .iter() + .any(|n| n.contains("couldn't be opened")) + }); + until("beta no longer wanted", || !app.serving().wants("beta")); + drop(app); +} + +#[test] +fn a_refused_start_is_said_and_nothing_is_asked_of_the_server() { + let w = World::new(&["alpha", "gamma"]); + let owner = Fake::new(); + *owner.start_says.lock().unwrap() = Some("Another program has these books open".into()); + let ctx = egui::Context::default(); + let mut app = w.start(&["alpha"], &owner); + until("the refusal is said", || { + app.notices() + .iter() + .any(|n| n.contains("Another program has these books open")) + }); + app.open(&ctx, w.source("gamma")); + app.close(tab_of(&app, "alpha")); + a_while(); + // The next tab is a new try at the start (INVARIANT 7), which fails + // the same way; no company is asked to open or close in a server that + // isn't there. + assert_eq!( + owner.said(), + vec!["start alpha".to_string(), "start alpha,gamma".to_string()] + ); + drop(app); +} + +#[test] +fn a_server_that_exits_on_its_own_is_said_once() { + let w = World::new(&["alpha"]); + let owner = Fake::new(); + let mut app = w.start(&["alpha"], &owner); + until("started", || !owner.said().is_empty()); + assert!(app.notices().is_empty()); + *owner.exited.lock().unwrap() = Some("the books server stopped (exit status: 1)".into()); + let said: Vec = app.notices().to_vec(); + assert_eq!(said.len(), 1, "{said:?}"); + assert!( + said[0].contains("exit status: 1") && said[0].contains("can't reach your companies"), + "{said:?}" + ); + assert_eq!(app.notices().len(), 1, "said once, not every frame"); + drop(app); +} + +#[test] +fn closing_the_window_stops_the_server_and_waits_for_it() { + let w = World::new(&["alpha"]); + let owner = Fake::new(); + *owner.stop_takes.lock().unwrap() = Duration::from_millis(600); + let kept = w.kept(&["alpha"]); + let (root, fallback) = (w.root.clone(), w.source("alpha")); + 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, + &|k| kept.get(k).cloned(), + Start::Restore { root, fallback }, + Some(for_app), + ) + }); + h.run_steps(3); + // The window is asked to close. + h.input_mut() + .viewports + .entry(egui::ViewportId::ROOT) + .or_default() + .events + .push(egui::ViewportEvent::Close); + h.run_steps(2); + until("the close began", || h.state().serving().is_closing()); + h.run_steps(2); + assert!( + h.query_by_label_contains("Closing your books").is_some(), + "the window says it is closing the books while it waits" + ); + assert!(!h.state().serving().is_closed(), "the wait is not over"); + // Asked again meanwhile: the owner is still asked once. + h.input_mut() + .viewports + .entry(egui::ViewportId::ROOT) + .or_default() + .events + .push(egui::ViewportEvent::Close); + h.run_steps(2); + until("the close is done", || h.state().serving().is_closed()); + h.run_steps(3); + assert!( + h.query_by_label_contains("Closing your books").is_none(), + "the message goes when the wait does" + ); + assert_eq!( + owner.said().iter().filter(|s| *s == "stop").count(), + 1, + "{:?}", + owner.said() + ); + drop(h); + assert_eq!( + owner.said().iter().filter(|s| *s == "stop").count(), + 1, + "dropping the window asks no second time: {:?}", + owner.said() + ); +} + +#[test] +fn a_server_that_will_not_exit_is_left_closing_and_the_window_closes() { + let w = World::new(&["alpha"]); + let owner = Fake::new(); + *owner.stop_says.lock().unwrap() = Some("The books are still closing in the background".into()); + let serving = Serving::start(Some(owner.clone() as Arc), vec!["alpha".into()]); + until("started", || !owner.said().is_empty()); + serving.begin_stop(); + until("the close returned", || serving.is_closed()); + // The wait ended with the owner's word; the person is told what is + // left (the close's report, which the window shows, `close_report`). + let report = serving.close_report(); + assert!( + report.iter().any(|n| n.contains("still closing")), + "{report:?}" + ); + drop(serving); + drop(w); +} + +#[test] +fn a_window_with_no_server_asks_nothing_of_any() { + let w = World::new(&["alpha", "gamma"]); + let ctx = egui::Context::default(); + // An owner that does not host a server: the default. + struct Plain; + impl Owner for Plain { + fn close_books(&self) -> Result { + Err("not here".into()) + } + 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()) + } + } + let kept = w.kept(&["alpha"]); + let mut app = App::start_with_owner( + &ctx, + &|k| kept.get(k).cloned(), + Start::Restore { + root: w.root.clone(), + fallback: w.source("alpha"), + }, + Some(Arc::new(Plain)), + ); + assert!(!app.serving().is_on()); + app.open(&ctx, w.source("gamma")); + app.close(0); + assert!(app.notices().is_empty()); + assert!(app.serving().is_closed(), "nothing to close"); + // And no owner at all. + let app = App::start_with_owner( + &ctx, + &|k| kept.get(k).cloned(), + Start::Restore { + root: w.root.clone(), + fallback: w.source("alpha"), + }, + None, + ); + assert!(!app.serving().is_on()); +} + +#[test] +fn a_failed_start_is_tried_again_when_the_next_tab_opens() { + let w = World::new(&["alpha", "gamma"]); + let owner = Fake::new(); + *owner.start_says.lock().unwrap() = Some("Another program has these books open".into()); + let ctx = egui::Context::default(); + let mut app = w.start(&["alpha"], &owner); + until("the refusal is said", || { + app.notices() + .iter() + .any(|n| n.contains("Another program has these books open")) + }); + until("the start is over", || !app.serving().is_starting()); + assert!(app.serving().is_down(), "the window offers to try again"); + // Whatever held the books has let go: the next tab is the next try. + *owner.start_says.lock().unwrap() = None; + app.open(&ctx, w.source("gamma")); + until("started again", || owner.said().len() == 2); + until("up", || !app.serving().is_starting()); + a_while(); + // The new start has every company wanted, so none is asked for twice. + assert_eq!( + owner.said(), + vec!["start alpha".to_string(), "start alpha,gamma".to_string()] + ); + assert!(!app.serving().is_down()); + // And it is up: a tab closing is asked of the server now. + app.close(tab_of(&app, "gamma")); + until("gamma closed", || { + owner.said().contains(&"close gamma".to_string()) + }); + drop(app); +} + +#[test] +fn the_person_can_try_a_failed_start_again() { + let owner = Fake::new(); + *owner.start_says.lock().unwrap() = Some("the books server stopped (exit status: 1)".into()); + let serving = Serving::start(Some(owner.clone() as Arc), vec!["alpha".into()]); + until("down", || serving.is_down()); + assert!(serving.retry(), "asked again, it starts again"); + until("settled", || !serving.is_starting()); + assert!(serving.is_down(), "failed again: it can be tried again"); + *owner.start_says.lock().unwrap() = None; + assert!(serving.retry()); + until("up", || !serving.is_starting() && !serving.is_down()); + assert!(!serving.retry(), "a server that is up is not started again"); + assert_eq!( + owner + .said() + .iter() + .filter(|s| s.starts_with("start")) + .count(), + 3 + ); + let notices = serving.take_notices(); + assert_eq!(notices.len(), 2, "each failure said once: {notices:?}"); +} + +#[test] +fn a_server_still_starting_is_said_to_be_starting() { + let owner = Fake::new(); + *owner.start_takes.lock().unwrap() = Duration::from_millis(600); + let serving = Serving::start(Some(owner.clone() as Arc), vec!["alpha".into()]); + assert!(serving.is_starting()); + assert!(!serving.is_down(), "waited for, not given up on"); + until("up", || !serving.is_starting()); + assert!(!serving.is_down()); + assert!(serving.take_notices().is_empty()); +} + +#[test] +fn a_company_that_did_not_open_at_the_start_is_said_and_asked_for_again() { + let w = World::new(&["alpha", "beta"]); + let owner = Fake::new(); + *owner.not_open_says.lock().unwrap() = vec![( + "beta".into(), + "beta couldn't be opened for your assistants: a damaged line.".into(), + )]; + // The tabs are opened (and wanted) before the server says ready. + *owner.start_takes.lock().unwrap() = Duration::from_millis(300); + let ctx = egui::Context::default(); + let mut app = w.start(&["alpha", "beta"], &owner); + until("the failed open is said", || { + app.notices().iter().any(|n| n.contains("a damaged line")) + }); + assert!(!app.serving().wants("beta"), "not open in the server"); + assert!(app.serving().wants("alpha")); + // Its tab closed and opened again asks the server again. + app.close(tab_of(&app, "beta")); + a_while(); + assert!( + !owner.said().contains(&"close beta".to_string()), + "nothing to close: it was never open: {:?}", + owner.said() + ); + app.open(&ctx, w.source("beta")); + until("beta asked for", || { + owner.said().contains(&"open beta".to_string()) + }); + drop(app); +} + +#[test] +fn a_close_that_was_not_whole_keeps_the_window_up_until_the_person_closes_anyway() { + let w = World::new(&["alpha"]); + let owner = Fake::new(); + *owner.stop_says.lock().unwrap() = Some( + "alpha is closed to your assistants, but its last backup wasn't whole: the folder is gone\nThe books server ended badly (exit status: 1)." + .into(), + ); + let kept = w.kept(&["alpha"]); + let (root, fallback) = (w.root.clone(), w.source("alpha")); + 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, + &|k| kept.get(k).cloned(), + Start::Restore { root, fallback }, + Some(for_app), + ) + }); + h.run_steps(3); + let ask_to_close = |h: &mut Harness<'_, App>| { + h.input_mut() + .viewports + .entry(egui::ViewportId::ROOT) + .or_default() + .events + .push(egui::ViewportEvent::Close); + h.run_steps(2); + }; + ask_to_close(&mut h); + until("the close is done", || h.state().serving().is_closed()); + h.run_steps(3); + // The close is over, and the window says what was not whole. + assert!(h.query_by_label_contains("did not close cleanly").is_some()); + assert!( + h.query_by_label_contains("last backup wasn't whole") + .is_some() + ); + assert!(h.query_by_label_contains("ended badly").is_some()); + assert_eq!(h.state().serving().close_report().len(), 2); + // Asked to close again, it is not "close anyway": still up, still said. + ask_to_close(&mut h); + h.run_steps(2); + assert!(h.query_by_label_contains("did not close cleanly").is_some()); + assert_eq!(h.state().serving().close_report().len(), 2); + // The button is. + h.get_by_label("Close anyway").click(); + h.run_steps(3); + assert!(h.state().serving().close_report().is_empty()); + assert_eq!( + owner.said().iter().filter(|s| *s == "stop").count(), + 1, + "the owner closed the server once: {:?}", + owner.said() + ); +} diff --git a/crates/ledger-host/src/app_server.rs b/crates/ledger-host/src/app_server.rs new file mode 100644 index 00000000..c3752800 --- /dev/null +++ b/crates/ledger-host/src/app_server.rs @@ -0,0 +1,800 @@ +//! The app's books server: a child process of the window (plan P15 3.1). +//! +//! ```text +//! GOAL: the desktop app is the host. It starts the books server from its +//! own executable when the window starts and closes it by closing +//! the server's input when the window closes; a window that dies +//! any way at all leaves no server behind and no book half-closed; +//! and no window ever waits forever on a server that will not exit. +//! SOURCE: plan/p15-app-and-relay.md 3.1 (the app starts the server as a +//! child, from its own executable, and closes it by closing its +//! input, exactly as the host does), D-77 (the app is the host), +//! D-84 (a child and not a thread: a crash in the window or its +//! graphics driver closes the server's input, and the books +//! close cleanly), WB-app-1, WB-app-2, WB-app-4; host.rs +//! INVARIANTS 3 and 10 (the host's own way: close the input, +//! never kill). +//! INVARIANTS: +//! 1. A start is refused, in words, when another program has these +//! books open: a host holds `run/host.lock`, or a server holds +//! `run/server.lock` (one still finishing after its window went +//! included). The locks are the existing ones; nothing is added to +//! them. Nothing is touched by a refused start. +//! 2. The server is this program's own executable, started as +//! `wanderbooks server --open IDS` (the companies the window +//! restored as tabs; `none` when there are none), its input a pipe +//! this struct holds, its output read for the ready line, its error +//! output the root's `run/server.log`. On Windows it has no console +//! window of its own. +//! 3. The server's input is closed when [`AppServer::stop`] is called, +//! when the value is dropped, and when this process ends for any +//! reason (the system closes the pipe): the server then closes as +//! local.rs INVARIANT 6 says. Nothing here sends it a signal or +//! kills it, ever. +//! 4. [`AppServer::stop`] waits for the exit at most as long as it is +//! told and then says the server is still closing: the window can +//! end while the server finishes its backup alone, and the next +//! start is refused, in words (1), until it has. +//! 5. A server that exits on its own is known as soon as it has +//! (`exited`), and every call that needs it says so, in words. +//! 6. A book is opened or closed in the server only by an admin +//! request, waiting for the server to be ready first; a close that +//! says its last backup was not whole is returned as a notice, never +//! as a plain success. +//! 7. Starting writes `run/app-hosted`, a file with nothing in it: the +//! root is this app's from then on, and the agents' bridge says +//! "Wanderbooks isn't running" for it, instead of starting a host +//! (bridge.rs INVARIANT 12). The marker is never removed: a root the +//! app has served is the app's for good. +//! 8. A server the window started is either managed by the window or +//! stopped, never neither ([`AppHost`]): one that is alive and not +//! yet ready is waited for, not given up on; a start that fails, or +//! a window closed before the start has stored the server, closes +//! that server's input and waits for it, bounded. +//! 9. The window's close closes each open company first, by an admin +//! request, so a closing backup that was not whole is returned in +//! words, and a server that exits badly is returned in words too +//! ([`AppHost::stop`]): a close is never silent about either. What +//! the server does for the headless path is not changed. +//! 10. The format upgrade of a company, under the app, goes to the +//! server as an admin request (`UpgradeFormat`), the way the host +//! hands it on; there is no host and no lease socket to ask. +//! 11. After the server is ready, the companies the window wanted open +//! are checked against the server's list: one that is not open is +//! returned in words ([`AppHost::not_open`]). +//! ``` + +use crate::host::{SERVER_LOG, children_executable, open_log, private_options}; +use crate::opener::{host_lock_held, server_lock_held}; +use ledger_mcp::admin::{self, CloseOutcome, OpenOutcome, Request, Response}; +use ledger_store::root::Root; +use std::io::BufRead; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::{Duration, Instant}; + +/// The file in `run/` that says the root is the desktop app's +/// (INVARIANT 7). +pub const APP_MARKER: &str = "app-hosted"; + +/// How long a server may take to say it is ready: it opens and verifies +/// every company it was told to, and a large one rebuilding a drifted +/// database takes a while. +pub const READY_WAIT: Duration = Duration::from_secs(300); + +/// How long [`AppServer::stop`] callers wait for a close, by default: the +/// last backup of a company is allowed 60 s (local.rs `BACKUP_AT_CLOSE`), +/// and running calls finish first. +pub const STOP_WAIT: Duration = Duration::from_secs(90); + +/// 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."; + +/// Where the server is in its life. +#[derive(Clone, Debug, PartialEq, Eq)] +enum Phase { + /// Started, not yet ready. + Starting, + /// Ready: its sockets are bound and the companies tried. + Ready, + /// Gone: how (in words), and whether it was a clean exit. + Exited(String, bool), +} + +struct Shared { + phase: Mutex, + changed: Condvar, +} + +impl Shared { + fn phase(&self) -> std::sync::MutexGuard<'_, Phase> { + self.phase.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn set(&self, to: Phase) { + let mut phase = self.phase(); + // Exited is final; Ready only follows Starting. + match (&*phase, &to) { + (Phase::Exited(..), _) | (Phase::Ready, Phase::Starting) => {} + _ => *phase = to, + } + self.changed.notify_all(); + } +} + +/// What [`AppServer::stop`] came to. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Stopped { + /// The server has exited cleanly: every company is closed and let go. + Closed, + /// The server has exited, and not cleanly (a nonzero status, or a + /// signal): how, in words. Its books may not have been closed whole. + Failed(String), + /// The server was told to close and has not exited within the wait; + /// it goes on closing by itself (INVARIANT 4). + StillClosing, +} + +/// The books server, a child process of this one. +pub struct AppServer { + run: PathBuf, + /// The server's input: dropping it closes the books (INVARIANT 3). + stdin: Mutex>, + shared: Arc, + pid: u32, +} + +/// Whether the root whose `run/` folder this is belongs to the desktop +/// app (INVARIANT 7). +pub fn app_hosted(run: &Path) -> bool { + run.join(APP_MARKER).is_file() +} + +/// Whether a books server runs for the app now: the root is the app's, +/// no host holds it, and a server does. +pub fn the_apps_server_runs(run: &Path) -> bool { + app_hosted(run) && !host_lock_held(run) && server_lock_held(run) +} + +impl AppServer { + /// Start the server of the data root (`root`, else this account's), + /// from this program's own executable, with the companies `open` open + /// (INVARIANTS 1, 2). It returns at once; [`AppServer::wait_ready`] + /// waits for the ready line. + pub fn start(root: Option<&Path>, open: &[String]) -> Result { + Self::start_in(&children_executable(), root, open, |_| {}) + } + + /// [`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( + exe: &Path, + root: Option<&Path>, + open: &[String], + 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())?; + if host_lock_held(&run) || server_lock_held(&run) { + return Err(ANOTHER_HAS_THEM.into()); + } + private_options() + .create(true) + .truncate(false) + .write(true) + .open(run.join(APP_MARKER)) + .map_err(|e| format!("can't mark these books as the app's: {}", e.kind()))?; + let log = open_log(&run.join(SERVER_LOG)) + .map_err(|e| format!("can't open the server's log: {}", e.kind()))?; + let mut command = Command::new(exe); + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + command.arg0("wanderbooks"); + } + command.arg("server"); + if let Some(root) = root { + command.arg("--root").arg(root); + } + command.arg("--open").arg(open_argument(open)); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + // CREATE_NO_WINDOW: a console of its own that nobody sees, so + // the window's own Ctrl+C never reaches it (it closes by its + // input alone). + command.creation_flags(0x0800_0000); + } + configure(&mut command); + let mut child = command + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(log) + .spawn() + .map_err(|e| format!("can't start the books server: {e}"))?; + let stdin = child.stdin.take(); + let stdout = child.stdout.take(); + let pid = child.id(); + let shared = Arc::new(Shared { + phase: Mutex::new(Phase::Starting), + changed: Condvar::new(), + }); + if let Some(stdout) = stdout { + let shared = shared.clone(); + std::thread::Builder::new() + .name("app-server-ready".into()) + .spawn(move || { + // Read to the end, whatever it says: a pipe nobody + // reads could stop the server one day. + for line in std::io::BufReader::new(stdout).lines() { + match line { + Ok(line) if line == ledger_mcp::local::READY => { + shared.set(Phase::Ready); + } + Ok(_) => {} + Err(_) => break, + } + } + }) + .map_err(|e| format!("can't watch the books server: {e}"))?; + } + { + let shared = shared.clone(); + std::thread::Builder::new() + .name("app-server-exit".into()) + .spawn(move || { + let (said, clean) = match child.wait() { + Ok(status) => ( + format!("the books server stopped ({status})"), + status.success(), + ), + Err(e) => (format!("the books server stopped ({})", e.kind()), false), + }; + shared.set(Phase::Exited(said, clean)); + }) + .map_err(|e| format!("can't watch the books server: {e}"))?; + } + Ok(Self { + run, + stdin: Mutex::new(stdin), + shared, + pid, + }) + } + + /// The server's process id (tests; never signalled by this program). + pub fn pid(&self) -> u32 { + self.pid + } + + /// The root's `run/` folder. + pub fn run_dir(&self) -> &Path { + &self.run + } + + /// Why the server is gone, if it is (INVARIANT 5). + pub fn exited(&self) -> Option { + match &*self.shared.phase() { + Phase::Exited(why, _) => Some(why.clone()), + _ => None, + } + } + + /// Wait at most `within` for the server to be ready: Ok when it is, + /// else why not, in words (it exited, or is still opening). + pub fn wait_ready(&self, within: Duration) -> Result<(), String> { + let deadline = Instant::now() + within; + let mut phase = self.shared.phase(); + loop { + match &*phase { + Phase::Ready => return Ok(()), + Phase::Exited(why, _) => { + return Err(format!( + "{why}: its log is {} in the books' run folder", + SERVER_LOG + )); + } + Phase::Starting => {} + } + let Some(left) = deadline.checked_duration_since(Instant::now()) else { + return Err(format!( + "the books server is still opening the companies after {} s", + within.as_secs() + )); + }; + phase = self + .shared + .changed + .wait_timeout(phase, left) + .unwrap_or_else(|e| e.into_inner()) + .0; + } + } + + /// Whether the server has said it is ready (and is still there). + pub fn is_ready(&self) -> bool { + matches!(&*self.shared.phase(), Phase::Ready) + } + + /// Wait for the server to be ready for as long as it lives: a server + /// still opening companies, or waiting for another server to finish + /// (local.rs INVARIANT 1), is waited for and not given up on; `Err` + /// only when it has exited (INVARIANT 8). `slice` is how long each + /// wait runs before the server is looked at again. + pub fn wait_started(&self, slice: Duration) -> Result<(), String> { + loop { + match self.wait_ready(slice) { + Ok(()) => return Ok(()), + Err(_) if self.exited().is_none() => {} + Err(why) => return Err(why), + } + } + } + + /// Open the company `id` in the server, so assistants can reach it + /// (INVARIANT 6): `Ok(None)` when it is open now, `Err` with why not. + /// It waits for the server to be ready, and for the open. + pub fn open_book(&self, id: &str) -> Result, String> { + self.wait_ready(READY_WAIT)?; + match self.ask(Request::OpenBook { id: id.into() }, None)? { + Response::OpenBook { outcome, .. } => open_words(id, outcome), + Response::Refused(why) => Err(why), + other => Err(format!("the books server answered oddly: {other:?}")), + } + } + + /// Close the company `id` in the server (INVARIANT 6): running calls + /// on it finish, its assistants' sessions end, its last backup is made + /// and it is let go. `Ok(None)` when that is all so; `Ok(Some(words))` + /// when it is closed but its last backup wasn't whole; `Err` when the + /// request itself failed (the company may still be open). + pub fn close_book(&self, id: &str) -> Result, String> { + self.close_book_within(id, None) + } + + /// [`AppServer::close_book`], waiting at most `wait` for the answer. + pub fn close_book_within( + &self, + id: &str, + wait: Option, + ) -> Result, String> { + self.wait_ready(READY_WAIT)?; + match self.ask(Request::CloseBook { id: id.into() }, wait)? { + Response::CloseBook { outcome, .. } => Ok(close_words(id, outcome)), + Response::Refused(why) => Err(why), + other => Err(format!("the books server answered oddly: {other:?}")), + } + } + + /// The books the server holds, and whether each is open (INVARIANT 9). + pub fn books(&self, wait: Option) -> Result, String> { + self.wait_ready(READY_WAIT)?; + match self.ask(Request::List, wait)? { + Response::Books(books) => Ok(books), + Response::Refused(why) => Err(why), + other => Err(format!("the books server answered oddly: {other:?}")), + } + } + + /// The owner's go-ahead for the format upgrade of the company `id`, + /// with the owner passphrase they typed, sent to the server as the + /// host sends it (INVARIANT 10): what came of it, a line each; or why + /// not, which says whether it may have been done all the same. + pub fn upgrade_format(&self, id: &str, passphrase: &str) -> Result, String> { + self.wait_ready(READY_WAIT) + .map_err(|why| format!("not upgraded: {why}"))?; + let request = Request::UpgradeFormat { + id: id.into(), + passphrase: admin::Passphrase(passphrase.into()), + }; + match self.ask_raw(request, None) { + Ok(Response::FormatUpgraded(u)) => Ok(crate::commands::upgraded_lines(&u)), + Ok(Response::Refused(why)) => Err(format!("not upgraded: {why}")), + Ok(_) => Err( + "the books server answered oddly, so it may or may not have been done: `wanderbooks books list` says whether the books still wait for it" + .into(), + ), + Err(admin::CallError::NotSent(why)) => Err(format!("not upgraded: {why}")), + Err(admin::CallError::Unknown(why)) => Err(why), + } + } + + /// One admin request, answered or why not in words. + fn ask(&self, request: Request, wait: Option) -> Result { + self.ask_raw(request, wait).map_err(|e| e.to_string()) + } + + /// One admin request, as the admin socket answers it. + fn ask_raw( + &self, + request: Request, + wait: Option, + ) -> Result { + if let Some(why) = self.exited() { + return Err(admin::CallError::NotSent(why)); + } + admin::call_within( + &self.run.join(ledger_mcp::local::ADMIN_SOCKET), + request, + wait, + ) + } + + /// Close the server's input: it begins to close the books and exits + /// when it is done (INVARIANT 3). Does not wait. + pub fn close_input(&self) { + *self.stdin.lock().unwrap_or_else(|e| e.into_inner()) = None; + } + + /// Close the server's input and wait at most `within` for it to exit + /// (INVARIANTS 3, 4). Never kills it. + pub fn stop(&self, within: Duration) -> Stopped { + self.close_input(); + let deadline = Instant::now() + within; + let mut phase = self.shared.phase(); + loop { + if let Phase::Exited(how, clean) = &*phase { + return if *clean { + Stopped::Closed + } else { + Stopped::Failed(how.clone()) + }; + } + let Some(left) = deadline.checked_duration_since(Instant::now()) else { + return Stopped::StillClosing; + }; + phase = self + .shared + .changed + .wait_timeout(phase, left) + .unwrap_or_else(|e| e.into_inner()) + .0; + } + } +} + +/// How long a server whose start has failed is waited for to close +/// (INVARIANT 8): it exits as soon as its input ends if it was waiting +/// or opening, and makes a last backup of what it had open. +pub const FAILED_START_STOP_WAIT: Duration = Duration::from_secs(30); + +/// What it says when the server is still closing after a stop ran out of +/// time (INVARIANT 4). +pub const STILL_CLOSING: &str = "The books are still closing in the background (most likely a last backup): Wanderbooks finishes it on its own. Start it again once it has."; + +type Starter = Box Result + Send + Sync>; + +/// What the window does with its books server, whole: start it, open and +/// close its companies, ask which are open, hand it the format upgrade, +/// stop it. The program's owner (`ViewerOwner` in ledger-cli) only +/// forwards to this, so what the tests drive is what the window runs. +pub struct AppHost { + starter: Starter, + slice: Duration, + server: Mutex>>, + /// The window has asked to close (INVARIANT 8): no server is started + /// after it, and one stored just before it is stopped. + stopped: std::sync::atomic::AtomicBool, +} + +impl AppHost { + /// A host that starts the data root's server (`root`, else this + /// account's) from this program's own executable. + pub fn new(root: Option) -> Self { + Self::with_starter(READY_WAIT, move |open| { + AppServer::start(root.as_deref(), open) + }) + } + + /// A host that starts its server with `starter` (tests give it + /// another program and an environment of its own); `slice` is how + /// long a wait for the ready line runs before the server is looked + /// at again. + pub fn with_starter( + slice: Duration, + starter: impl Fn(&[String]) -> Result + Send + Sync + 'static, + ) -> Self { + Self { + starter: Box::new(starter), + slice, + server: Mutex::new(None), + stopped: std::sync::atomic::AtomicBool::new(false), + } + } + + fn slot(&self) -> std::sync::MutexGuard<'_, Option>> { + self.server.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn closing(&self) -> bool { + self.stopped.load(std::sync::atomic::Ordering::SeqCst) + } + + /// The running server, or why there is none. + pub fn running(&self) -> Result, String> { + self.slot() + .clone() + .ok_or_else(|| "the books server isn't running".to_string()) + } + + /// Start the server with the companies `open` open and return when it + /// is ready, or why it will not be (INVARIANT 8). Blocks. Called again + /// after a start that failed, it starts a new server; called while one + /// runs it waits for that one. + pub fn start(&self, open: &[String]) -> Result<(), String> { + if self.closing() { + return Err("Wanderbooks is closing".into()); + } + let alive = self.slot().clone().filter(|s| s.exited().is_none()); + let server = match alive { + Some(server) => server, + None => { + let server = Arc::new((self.starter)(open)?); + let mut slot = self.slot(); + // The window may have asked to close since the check + // above: it looks at the slot after setting the flag, so + // one of the two sees the other. + if self.closing() { + drop(slot); + server.stop(FAILED_START_STOP_WAIT); + return Err("Wanderbooks is closing".into()); + } + *slot = Some(server.clone()); + server + } + }; + match server.wait_started(self.slice) { + Ok(()) => Ok(()), + Err(why) => { + // Managed or stopped, never neither: this server is let + // go of, and its input closed. + { + let mut slot = self.slot(); + if slot.as_ref().is_some_and(|s| Arc::ptr_eq(s, &server)) { + *slot = None; + } + } + Err(match server.stop(FAILED_START_STOP_WAIT) { + Stopped::StillClosing => { + format!("{why}; it is still closing in the background") + } + _ => why, + }) + } + } + } + + /// Open the company `id` in the server (a tab opened). + pub fn open_book(&self, id: &str) -> Result, String> { + self.running()?.open_book(id) + } + + /// Close the company `id` in the server (a tab closed). + pub fn close_book(&self, id: &str) -> Result, String> { + self.running()?.close_book(id) + } + + /// Why the server is gone, if it exited on its own. + pub fn exited(&self) -> Option { + self.slot().as_ref()?.exited() + } + + /// For each of the companies `wanted` that the server does not have + /// open (INVARIANT 11): its id, and why in words. Nothing is said for + /// a server that isn't running. + pub fn not_open(&self, wanted: &[String]) -> Vec<(String, String)> { + let Ok(server) = self.running() else { + return Vec::new(); + }; + let books = match server.books(Some(Duration::from_secs(30))) { + Ok(books) => books, + Err(why) => { + return wanted + .iter() + .map(|id| { + ( + id.clone(), + format!("can't tell whether {id} is open for your assistants: {why}"), + ) + }) + .collect(); + } + }; + wanted + .iter() + .filter_map(|id| { + let held = books.iter().find(|b| &b.id == id); + let not_open = match held { + Some(b) if b.open => return None, + Some(b) => b + .problem + .clone() + .unwrap_or_else(|| "it isn't open in the books server".into()), + None => "the books server doesn't have it".into(), + }; + let words = open_words(id, OpenOutcome::CouldNotOpen(not_open)) + .err() + .unwrap_or_default(); + Some((id.clone(), words)) + }) + .collect() + } + + /// The format upgrade of the company `id` (INVARIANT 10). + pub fn upgrade_format(&self, id: &str, passphrase: &str) -> Result, String> { + match self.running() { + Ok(server) => server.upgrade_format(id, passphrase), + Err(_) => Err( + "not upgraded: the books server isn't running, so nothing was done. Assistants can't reach your companies either: try again from the notice at the top of the window, or restart Wanderbooks" + .into(), + ), + } + } + + /// Close the window's books (INVARIANT 9): each open company is closed + /// first, so its closing backup is reported if it was not whole; then + /// the server's input is closed and its exit waited for, the whole + /// taking about `within`. `Ok(None)` when all went whole; else the + /// words, a line each (the companies whose backup was incomplete, a + /// server that exited badly or is still closing). Never kills. + pub fn stop(&self, within: Duration) -> Result, String> { + self.stopped + .store(true, std::sync::atomic::Ordering::SeqCst); + let Some(server) = self.slot().take() else { + return Ok(None); + }; + let begun = Instant::now(); + let mut said: Vec = Vec::new(); + if server.is_ready() && server.exited().is_none() { + match server.books(Some(within)) { + Ok(books) => { + let open: Vec = + books.into_iter().filter(|b| b.open).map(|b| b.id).collect(); + // Each company's last backup runs on its own: none + // waits for another's. + let notices: Vec> = std::thread::scope(|scope| { + let handles: Vec<_> = open + .iter() + .map(|id| { + let server = &server; + scope.spawn(move || { + match server.close_book_within(id, Some(within)) { + Ok(notice) => notice, + Err(why) => { + Some(format!("{id} could not be closed cleanly: {why}")) + } + } + }) + }) + .collect(); + handles + .into_iter() + .map(|h| h.join().unwrap_or(None)) + .collect() + }); + said.extend(notices.into_iter().flatten()); + } + Err(why) => said.push(format!( + "Couldn't check that each company closed whole: {why}" + )), + } + } + let left = within + .saturating_sub(begun.elapsed()) + .max(Duration::from_secs(5)); + match server.stop(left) { + Stopped::Closed => {} + Stopped::Failed(how) => said.push(format!( + "The books server ended badly ({how}). Its log is {SERVER_LOG} in the books' run folder; `wanderbooks doctor` says whether the books are whole." + )), + Stopped::StillClosing => said.push(STILL_CLOSING.into()), + } + Ok(if said.is_empty() { + None + } else { + Some(said.join("\n")) + }) + } +} + +/// What opening the company `id` came to, for the person: `Ok(None)` when +/// it is open, else why not (INVARIANT 6). +fn open_words(id: &str, outcome: OpenOutcome) -> Result, String> { + match outcome { + OpenOutcome::Opened | OpenOutcome::AlreadyOpen => Ok(None), + OpenOutcome::NoSuchBook => Err(format!( + "there are no books called {id:?}, so assistants can't reach them" + )), + OpenOutcome::CouldNotOpen(why) => Err(format!( + "{id} couldn't be opened for your assistants: {why}. You can still read it in this window." + )), + } +} + +/// What closing the company `id` came to: a notice when its last backup +/// wasn't whole, never a plain success then (INVARIANT 6). +fn close_words(id: &str, outcome: CloseOutcome) -> Option { + match outcome { + CloseOutcome::Closed | CloseOutcome::WasNotOpen | CloseOutcome::NoSuchBook => None, + CloseOutcome::ClosedBackupIncomplete(why) => Some(format!( + "{id} is closed to your assistants, but its last backup wasn't whole: {why}. What it holds since the last good backup isn't backed up." + )), + } +} + +/// `--open`'s value for these companies. +fn open_argument(open: &[String]) -> String { + if open.is_empty() { + "none".into() + } else { + open.join(",") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn no_company_is_none_and_the_rest_are_a_list() { + assert_eq!(open_argument(&[]), "none"); + assert_eq!(open_argument(&["acme".into()]), "acme"); + assert_eq!(open_argument(&["acme".into(), "beta".into()]), "acme,beta"); + } + + #[test] + fn a_close_with_an_incomplete_backup_is_a_notice_never_a_plain_success() { + assert_eq!(close_words("acme", CloseOutcome::Closed), None); + assert_eq!(close_words("acme", CloseOutcome::WasNotOpen), None); + let said = close_words( + "acme", + CloseOutcome::ClosedBackupIncomplete("the backup folder is gone".into()), + ) + .expect("a notice"); + assert!( + said.contains("acme") + && said.contains("last backup wasn't whole") + && said.contains("the backup folder is gone"), + "{said}" + ); + } + + #[test] + fn an_open_that_did_not_happen_says_why() { + assert_eq!(open_words("acme", OpenOutcome::Opened), Ok(None)); + assert_eq!(open_words("acme", OpenOutcome::AlreadyOpen), Ok(None)); + let refused = open_words("acme", OpenOutcome::CouldNotOpen("a damaged line".into())) + .expect_err("not opened"); + assert!( + refused.contains("acme") && refused.contains("a damaged line"), + "{refused}" + ); + assert!(open_words("acme", OpenOutcome::NoSuchBook).is_err()); + } + + #[test] + fn a_server_that_has_exited_stays_exited() { + let shared = Shared { + phase: Mutex::new(Phase::Starting), + changed: Condvar::new(), + }; + shared.set(Phase::Ready); + assert_eq!(*shared.phase(), Phase::Ready); + shared.set(Phase::Starting); + assert_eq!(*shared.phase(), Phase::Ready, "ready doesn't go back"); + shared.set(Phase::Exited("gone".into(), true)); + shared.set(Phase::Ready); + assert_eq!(*shared.phase(), Phase::Exited("gone".into(), true)); + } + + #[test] + fn a_root_is_the_apps_only_once_marked() { + let dir = tempfile::tempdir().unwrap(); + assert!(!app_hosted(dir.path())); + std::fs::write(dir.path().join(APP_MARKER), b"").unwrap(); + assert!(app_hosted(dir.path())); + // No server runs there: not the app's server. + assert!(!the_apps_server_runs(dir.path())); + } +} diff --git a/crates/ledger-host/src/bridge.rs b/crates/ledger-host/src/bridge.rs index 09f08b4c..4bdfb238 100644 --- a/crates/ledger-host/src/bridge.rs +++ b/crates/ledger-host/src/bridge.rs @@ -6,7 +6,9 @@ //! no call the agent made can ever run twice. //! SOURCE: plan/served.md 3.9 ("The bridge and slow starts", "Closing", //! "Restarting"), 3.1 (the bridge never reads the books; it has -//! no data-dir flag); the plan's tests bridge_opens_closed_books, +//! no data-dir flag); plan/p15-app-and-relay.md 3.1 (the bridge +//! is a thin line to the running app and says in words when it +//! can't be), D-44, D-77, WB-app-3; the plan's tests bridge_opens_closed_books, //! bridge_survives_server_restart, bridge_initializes_during_cold_start, //! no_local_agent_tcp, close_now_ends_every_lease (in //! ledger-cli's open_while_held.rs, under names of their own); @@ -52,6 +54,19 @@ //! refusal, which says how the human makes one; but when the token //! file is there and couldn't be read, with that instead: the token //! is not said to be missing. The token is never written to the agent or to stderr. +//! 12. For a root the desktop app serves (app_server.rs INVARIANT 7) with +//! no host running, the bridge is a thin line to the app's server +//! and nothing more: it holds no lease and starts no host (a +//! detached host is not how the desktop runs). With the app not +//! running, every call is answered "Wanderbooks isn't running: +//! start Wanderbooks and open BOOK." (`not_running_words`); with +//! the app running but BOOK not open in it, "Company BOOK isn't +//! open: open it in Wanderbooks." (`not_open_words`, for the +//! server's `closed` refusal at the door). Neither is final: the +//! call after the app starts, or the company opens, goes through, +//! in a session that was already running. A root no app has served, +//! and any root a host holds, behave as in 1 to 11 (`wanderbooks +//! serve`, the headless host). //! ``` use crate::knobs::{FLAG, Knobs}; @@ -83,6 +98,17 @@ const NO_SESSION: &str = "Not Found: Session not found"; /// What a call cut off after it was sent is answered with (INVARIANT 4). const MAYBE_RAN: &str = "the connection to the books server broke while this call was running, so it may or may not have been done: check before trying it again (books.digest shows the latest changes)"; +/// What the agent is told when the app is not running (INVARIANT 12). +fn not_running_words(book: &str) -> String { + format!("Wanderbooks isn't running: start Wanderbooks and open {book}.") +} + +/// 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 { + format!("Company {book} isn't open: open it in Wanderbooks.") +} + /// What the agent is told once the owner closed the books (INVARIANT 6). const CLOSED_BY_OWNER: &str = "the owner closed the books (Close the books, or `wanderbooks close`): nothing more can be done in this session. Start a new agent session to open them again."; @@ -164,6 +190,9 @@ struct Bridge { pending: Mutex>, /// The server's channel, for its owner check (INVARIANT 9). endpoint: ledger_mcp::ipc::Endpoint, + /// Whether this is the line to the desktop app's server, with no host + /// and no lease (INVARIANT 12). + app: bool, } /// Who has the server's socket, when it isn't plainly this account. @@ -516,6 +545,7 @@ impl Bridge { if refused.as_deref() == Some(REFUSED_CLOSING.as_bytes()) { return Sent::NotRun(NotRun::Closing); } + let closed = refused.as_deref() == Some(b"closed".as_slice()); let refused = refused.is_some(); let is_stream = response .headers() @@ -524,11 +554,15 @@ impl Bridge { .is_some_and(|t| t.starts_with("text/event-stream")); let body = match response.text().await { Ok(b) => b, - Err(_) if refused => return Sent::Refused("the books server refused the call".into()), + Err(_) if refused => { + return Sent::Refused( + self.refusal_words(closed, "the books server refused the call"), + ); + } Err(_) => return Sent::MaybeRan, }; if refused { - return Sent::Refused(body.trim().chars().take(500).collect()); + return Sent::Refused(self.refusal_words(closed, &body)); } let answered = |messages: Vec| { // The server's "closing: not run" (INVARIANT 4). @@ -612,6 +646,10 @@ impl Bridge { .and_then(|v| v.to_str().ok()) .map(str::to_string); let status = response.status(); + let closed = response + .headers() + .get(ledger_mcp::local::REFUSED_HEADER) + .is_some_and(|v| v.as_bytes() == b"closed"); let is_stream = response .headers() .get("content-type") @@ -624,7 +662,7 @@ impl Bridge { // initialize the server won't take): the server's words. Not // asked again until the next call. 404 | 503 if !body.starts_with(CLOSING) => { - return Err(Some(body.trim().chars().take(500).collect())); + return Err(Some(self.refusal_words(closed, &body))); } 400..=499 => return Err(Some(body.trim().chars().take(500).collect())), _ => return Err(None), @@ -883,6 +921,9 @@ impl Bridge { // Not "opening now": closed by the owner, or can't open. Some(Link::Closed) => return self.answer(&id, error(&id, CLOSED_BY_OWNER)), Some(Link::Failed(why)) => return self.answer(&id, error(&id, why)), + // The desktop app can't be reached, or the company isn't open + // in it: said now, not "opening" (INVARIANT 12). + Some(Link::Refused(why)) if self.app => return self.answer(&id, error(&id, why)), _ => None, }; let result = result.unwrap_or_else(|| { @@ -1010,6 +1051,78 @@ impl Bridge { } } + /// The words for a refusal at the server's door: for the desktop app's + /// `closed` refusal, the bridge's own (INVARIANT 12); else the + /// server's. + fn refusal_words(&self, closed: bool, body: &str) -> String { + if self.app && closed { + not_open_words(&self.book) + } else { + body.trim().chars().take(500).collect() + } + } + + /// The line to the desktop app's server (INVARIANT 12): no lease, no + /// host. Whenever a session is wanted it looks for the app's socket: + /// none answering is `Refused` with the words for it, which every + /// call is answered with and which the next call looks at again; the + /// company not open is the server's own refusal, in the bridge's + /// words. + async fn keep_in_app(self: Arc, run_dir: PathBuf) { + let root = run_dir.parent().unwrap_or(&run_dir).to_path_buf(); + let account = crate::tokens::Account::new(&root, &self.book, &self.token_name); + let _ = self.token_file.set((account, run_dir)); + let mut epoch = 0u64; + loop { + if matches!(&*self.link.borrow(), Link::Opening) { + match self.socket_is_ours() { + Err(Owner::Other(why)) => { + self.link.send_replace(Link::Failed(why)); + return; + } + Err(Owner::Unreachable) => { + self.link + .send_replace(Link::Refused(not_running_words(&self.book))); + } + Ok(()) => match self.open_session(epoch + 1).await { + Ok(up) => { + epoch = up.epoch; + self.after_new_session(&up).await; + self.link.send_replace(Link::Ready(Arc::new(up))); + } + Err(Some(why)) => { + self.link.send_replace(Link::Refused(why)); + } + // Not answering yet (opening, or on its way out): + // look again soon, answering nothing meanwhile. + Err(None) => { + tokio::time::sleep(Duration::from_millis(100)).await; + continue; + } + }, + } + } + // Until a session is wanted again: the agent initialized, or + // a session is found gone, or a call asks again. + self.renew.notified().await; + let stale = match &*self.link.borrow() { + Link::Ready(up) => { + up.init.is_none() + && self + .agent_init + .lock() + .unwrap_or_else(|e| e.into_inner()) + .is_some() + } + Link::Refused(_) => true, + _ => false, + }; + if stale { + self.link.send_replace(Link::Opening); + } + } + } + /// A session with the server: with the agent's initialize when it /// sent one, else none (a client without the handshake), within /// UPSTREAM_WAIT. @@ -1269,6 +1382,13 @@ async fn skip_line(input: &mut R) -> bool { } } +/// Whether the bridge is the line to the desktop app's server for the +/// root whose `run/` folder this is (INVARIANT 12): an app has served the +/// root, and no host holds it. +fn serves_the_app(run: &std::path::Path) -> bool { + crate::app_server::app_hosted(run) && !crate::opener::host_lock_held(run) +} + fn usage(prog: &str) { // (`--root DIR` too, for tests: the bridge never needs a folder.) eprintln!("usage: {prog} --book ID [--token NAME]"); @@ -1314,6 +1434,10 @@ pub fn run( .map_err(|e| e.to_string())? .to_string(); let opener = Opener::new(root.as_deref(), knobs, Kind::Bridge, Some(book.clone()))?; + // The desktop app's root with no host on it: the line to the app's + // server, no lease (INVARIANT 12). Settled once, here. + let app = serves_the_app(opener.run_dir()); + let run_dir = opener.run_dir().to_path_buf(); // Kept for the whole session: the client reaches the channel by it. let endpoint = ledger_mcp::ipc::Endpoint::new(opener.run_dir(), ledger_mcp::local::MCP_SOCKET) .map_err(|e| format!("can't reach the books server: {e}"))?; @@ -1346,8 +1470,13 @@ pub fn run( next_id: std::sync::atomic::AtomicU64::new(1), pending: Mutex::new(std::collections::HashMap::new()), endpoint, + app, }); - let keeper = tokio::spawn(bridge.clone().keep(opener)); + let keeper = if app { + tokio::spawn(bridge.clone().keep_in_app(run_dir)) + } else { + tokio::spawn(bridge.clone().keep(opener)) + }; let writer = tokio::spawn(async move { let mut out = tokio::io::stdout(); while let Some(message) = outbox.recv().await { @@ -1662,6 +1791,20 @@ mod against_a_server { } fn bridge_at(socket: &Path, knobs: Knobs) -> (Arc, mpsc::UnboundedReceiver) { + bridge_for(socket, knobs, false) + } + + /// A bridge that is the line to the desktop app's server (INVARIANT + /// 12). + fn app_bridge_at(socket: &Path, knobs: Knobs) -> (Arc, mpsc::UnboundedReceiver) { + bridge_for(socket, knobs, true) + } + + fn bridge_for( + socket: &Path, + knobs: Knobs, + app: bool, + ) -> (Arc, mpsc::UnboundedReceiver) { let endpoint = ledger_mcp::ipc::Endpoint::new( socket.parent().unwrap(), socket.file_name().and_then(|n| n.to_str()).unwrap(), @@ -1691,6 +1834,7 @@ mod against_a_server { next_id: std::sync::atomic::AtomicU64::new(1), pending: Mutex::new(std::collections::HashMap::new()), endpoint, + app, }); (bridge, rx) } @@ -2456,4 +2600,113 @@ mod against_a_server { let mut r = tokio::io::BufReader::new(&b""[..]); assert!(!skip_line(&mut r).await); } + + #[test] + fn the_two_messages_are_plain_and_name_the_company() { + assert_eq!( + not_running_words("acme"), + "Wanderbooks isn't running: start Wanderbooks and open acme." + ); + assert_eq!( + not_open_words("acme"), + "Company acme isn't open: open it in Wanderbooks." + ); + } + + #[test] + fn a_root_is_the_apps_only_when_marked_and_no_host_holds_it() { + let dir = tempfile::tempdir().unwrap(); + assert!(!serves_the_app(dir.path()), "no app has served it"); + std::fs::write(dir.path().join(crate::app_server::APP_MARKER), b"").unwrap(); + assert!(serves_the_app(dir.path())); + // A host holding the root is the headless path, marked or not. + let lock = std::fs::File::create(dir.path().join(crate::lease::HOST_LOCK)).unwrap(); + lock.lock().unwrap(); + assert!(!serves_the_app(dir.path())); + } + + const CLOSED_WORDS: &str = "The books \"acme\" aren't open: open them in Wanderbooks."; + + fn closed_reply() -> Reply { + Reply { + status: 503, + headers: vec![(ledger_mcp::local::REFUSED_HEADER, "closed".into())], + body: CLOSED_WORDS.into(), + cut: false, + } + } + + #[tokio::test] + async fn with_the_app_not_running_every_call_is_answered_in_words() { + let dir = tempfile::tempdir().unwrap(); + // Nothing listens here. + let (b, mut rx) = app_bridge_at(&dir.path().join("mcp.sock"), knobs(3000, 3000)); + let keeper = tokio::spawn(b.clone().keep_in_app(dir.path().to_path_buf())); + let init = json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-06-18", "capabilities": {}}}); + b.waiting(&json!(1)); + b.clone().request(init).await; + assert_eq!( + told(&mut rx, 3000).await.unwrap()["error"]["message"], + not_running_words("acme") + ); + let call: Value = serde_json::from_str(CALL).unwrap(); + b.waiting(&json!(7)); + b.clone() + .request_on(call.clone(), json!(7), "tools/call") + .await; + assert_eq!( + told(&mut rx, 3000).await.unwrap()["error"]["message"], + not_running_words("acme") + ); + // Asked again, the same: the answer is not final, it is looked at + // afresh at each call (the app may have started since). + b.waiting(&json!(8)); + b.clone().request_on(call, json!(8), "tools/call").await; + assert_eq!( + told(&mut rx, 3000).await.unwrap()["error"]["message"], + not_running_words("acme") + ); + keeper.abort(); + } + + #[tokio::test] + async fn with_the_app_running_a_company_that_is_not_open_is_said_in_words() { + let server = Server::start(); + let (b, mut rx) = app_bridge_at(&server.socket, knobs(3000, 3000)); + let dir = tempfile::tempdir().unwrap(); + let keeper = tokio::spawn(b.clone().keep_in_app(dir.path().to_path_buf())); + let call: Value = serde_json::from_str(CALL).unwrap(); + // A call with no session first (a client without the handshake). + server.script([closed_reply()]); + b.waiting(&json!(7)); + b.clone().request_on(call, json!(7), "tools/call").await; + assert_eq!( + told(&mut rx, 3000).await.unwrap()["error"]["message"], + not_open_words("acme") + ); + // The agent's initialize: refused at the door, said as it is. + server.script([closed_reply(), closed_reply()]); + let init = json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2025-06-18", "capabilities": {}}}); + b.waiting(&json!(1)); + b.clone().request(init).await; + assert_eq!( + told(&mut rx, 3000).await.unwrap()["error"]["message"], + not_open_words("acme") + ); + keeper.abort(); + } + + #[tokio::test] + async fn a_host_bridge_passes_the_servers_words_on_as_they_are() { + let server = Server::start(); + let (b, _rx) = bridge_at(&server.socket, knobs(1000, 1000)); + let message: Value = serde_json::from_str(CALL).unwrap(); + server.script([closed_reply()]); + assert_eq!( + what(&b.send(&message, &up(1)).await), + format!("refused {CLOSED_WORDS}") + ); + } } diff --git a/crates/ledger-host/src/commands.rs b/crates/ledger-host/src/commands.rs index e1b22d2e..f4ec92a9 100644 --- a/crates/ledger-host/src/commands.rs +++ b/crates/ledger-host/src/commands.rs @@ -1129,12 +1129,20 @@ pub fn new_books(common: &Common, id: &str, currency: &str) -> Result Result { let found = ledger_store::root::Root::find(common.root.as_deref()).map_err(|e| e.to_string())?; let run = found.run_dir().map_err(|e| e.to_string())?; + // The app's own server: no host to ask (it isn't "closed": it is open). + if crate::app_server::the_apps_server_runs(&run) { + return Err(APP_HAS_THEM.into()); + } match crate::opener::ask_once_within(&run, Ask::Intent(Intent::Close), HOST_WAIT)? { None => Ok("The books are closed.".into()), Some(HostMsg::Done { detail }) => Ok(detail diff --git a/crates/ledger-host/src/host.rs b/crates/ledger-host/src/host.rs index a9f5be9f..16e29dcf 100644 --- a/crates/ledger-host/src/host.rs +++ b/crates/ledger-host/src/host.rs @@ -83,7 +83,7 @@ pub const EXIT_ANOTHER_HOST: i32 = 3; /// File options for what the host makes: mode 0600 on Unix; on Windows /// the file takes the owner-only DACL its folder carries (P11c). -fn private_options() -> std::fs::OpenOptions { +pub(crate) fn private_options() -> std::fs::OpenOptions { #[allow(unused_mut)] let mut options = std::fs::OpenOptions::new(); #[cfg(unix)] @@ -182,7 +182,7 @@ fn take_host_lock_within(run: &Path, wait: Duration) -> Result std::io::Result { +pub(crate) fn open_log(path: &Path) -> std::io::Result { open_log_within(path, LOG_LIMIT) } @@ -195,7 +195,7 @@ fn open_log_within(path: &Path, limit: u64) -> std::io::Result { } /// The executable the server is started from (INVARIANT 3). -fn children_executable() -> PathBuf { +pub(crate) fn children_executable() -> PathBuf { if cfg!(target_os = "linux") { PathBuf::from("/proc/self/exe") } else { diff --git a/crates/ledger-host/src/lib.rs b/crates/ledger-host/src/lib.rs index 65a76939..e49ba2d4 100644 --- a/crates/ledger-host/src/lib.rs +++ b/crates/ledger-host/src/lib.rs @@ -11,6 +11,7 @@ //! viewer's Books menu does). Agents' tokens are kept in files under the data root //! ([`tokens`]). +pub mod app_server; pub mod bridge; pub mod channel; pub mod commands; diff --git a/crates/ledger-host/src/opener.rs b/crates/ledger-host/src/opener.rs index e0638566..4d2d5f62 100644 --- a/crates/ledger-host/src/opener.rs +++ b/crates/ledger-host/src/opener.rs @@ -28,6 +28,12 @@ //! 5. A holder that has held before, turned away because the owner //! closed the books, stays closed (HoldError::ClosedByOwner); a new //! holder waits for a new host. +//! 6. A root the desktop app has served (app_server.rs INVARIANT 7) +//! with the app's own server running and no host: a command's or +//! the viewer's hold is a lease on that server with no host behind +//! it (ready at once, never ended: the app decides when the books +//! close), no host is started beside it, and `wanderbooks serve` +//! is told the app has the books. //! ``` use crate::knobs::Knobs; @@ -109,6 +115,15 @@ pub struct Opener { pub struct Lease { /// Its number. pub id: u64, + /// The host's connection; none for the lease on the app's own server + /// (INVARIANT 6). + link: Option, + /// Whether `Ready` was said yet, for a lease with no host. + told_ready: bool, +} + +/// A lease's connection to the host. +struct HostLink { lines: tokio::io::Lines>>, _write: ledger_mcp::ipc::ConnectedWrite, } @@ -117,8 +132,17 @@ impl Lease { /// The host's next word: `Ready`, or `Ending` with why; `None` when /// the host is gone without a word. pub async fn next(&mut self) -> Option { + let Some(link) = self.link.as_mut() else { + // The app's own server: ready now, and no host to say more + // (INVARIANT 6). + if !self.told_ready { + self.told_ready = true; + return Some(HostMsg::Ready); + } + return std::future::pending().await; + }; loop { - match self.lines.next_line().await { + match link.lines.next_line().await { Ok(Some(line)) => match serde_json::from_str::(&line) { Ok(msg) => return Some(msg), Err(_) => continue, @@ -206,6 +230,22 @@ impl Opener { pub async fn hold(&mut self) -> Result { let mut started: Option = None; loop { + // The app has the books: its own server serves them, and no + // host is started beside it (INVARIANT 6). + if crate::app_server::the_apps_server_runs(&self.run) { + 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, + }); + } wait_for_restart(&self.run).await; let endpoint = ledger_mcp::ipc::Endpoint::new(&self.run, lease::LEASE_SOCKET) .map_err(|e| format!("can't reach the books' host: {e}"))?; @@ -308,8 +348,11 @@ impl Opener { Ok(match first { HostMsg::Held { lease } => Asked::Held(Lease { id: lease, - lines, - _write: write, + link: Some(HostLink { + lines, + _write: write, + }), + told_ready: false, }), HostMsg::Ending { reason: Reason::ServerFailed, diff --git a/docs/spec/claims/app.md b/docs/spec/claims/app.md new file mode 100644 index 00000000..bcb7baa6 --- /dev/null +++ b/docs/spec/claims/app.md @@ -0,0 +1,123 @@ +# Claims: app + +Wanderbooks' own product rules for the desktop app as the host of the books +(plan P15, `plan/p15-app-and-relay.md`). No authority outside this product +states them: bookspec's rules are about the books, and these are about who +holds them open and how an assistant is told. They are `WB-app-`. + +Rules: none from bookspec's list; these are product rules only. + +--- + +### Product rules + +**WB-app-1 The app is the host: the books server is its child, and no one +else's.** Starting Wanderbooks starts the books server as a child process, +from the app's own executable; closing the window closes the server's +input, and the server closes as it always does (running calls finish, +nothing is killed, the last backup of each company is made). A window that +dies any way at all (a crash, a kill, a driver fault) closes the same +input, because the system closes the pipe, so no server is left behind and +no company is half closed. Starting is refused, in words, when another +program already has these books open: the host's lock (`run/host.lock`) or +the server's (`run/server.lock`) is held, the second including a server +still finishing a backup after its window went. The server is a process and +not a thread so that a fault in the window can never take a book down in +the middle of a write (D-84). A server the window started is either managed +by the window or stopped: one that is alive but not yet ready (opening big +companies, or waiting for another server to finish) is waited for, in view; +a start that fails, or a window closed before the start has the child, +closes the child's input and waits for it, so none is left running that +nothing manages. The `run/app-hosted` marker, written by every start, is +permanent: nothing ever removes it, so a root the app has served is the +app's for good. A headless user who ran the desktop app once on a root sees, +from then on, an agent's bridge (`wanderbooks mcp`) answer "Wanderbooks isn't +running" when no app runs, and not start a host on demand as it did before; +a host they start themselves (`wanderbooks serve`) holds the root and the +bridge uses it as always (WB-app-3). Deleting the marker by hand gives the +root back to the on-demand host. +*Enforced:* `ledger_host::app_server::AppServer` (`start_in`, `stop`, its +`Drop`), `AppHost::start` and `AppHost::stop`, `ANOTHER_HAS_THEM`; the server's own close, ledger-mcp +`local::run` (INVARIANT 6). +*Checked:* `ledger-cli` `app_server.rs` (`the_server_is_a_child_that_closes_when_its_input_does`, +`a_window_that_dies_leaves_no_server_and_no_half_closed_book`, +`a_start_is_refused_when_another_program_has_the_books`, +`a_stop_that_runs_out_of_time_leaves_the_server_closing_and_says_so`, +`a_server_that_never_gets_ready_is_stopped_with_the_window_and_not_left_behind`, +`a_window_closed_before_the_child_was_stored_stops_the_child`, +`a_late_server_is_waited_for_and_stays_the_windows_to_manage`). + +**WB-app-2 A tab is a company open in the server.** A company has a tab +exactly while the server has it open to assistants: the companies the +window restores as tabs are opened when the server starts, opening a tab +asks the server to open that company, closing a tab asks it to close that +company. The window itself reads the journal on its own, read-only, and +never writes the books. A request that fails is shown to the person in +words and is never swallowed: a close that says its last backup was not +whole, a company that would not open for assistants, a server that stopped +or never started. A request for one company never waits for another's. A start that failed +(another program had the books) is tried again by the next tab that opens, +or by the "Try again" button beside its notice; a server still starting is +said to be starting. A company the window wanted open that the server does +not have open when it says ready (it failed to open) is a notice for that +company. The format upgrade of a company, asked in the window, is an admin +request to this same server (`UpgradeFormat`), since there is no host. +*Enforced:* `ledger_gui::serving::Serving` (`start`, `open`, `close`, +`take_notices`), `ledger_gui::app::App::open` and `App::close`, +`ledger_host::app_server::AppServer::open_book` and `close_book`, +`AppHost::not_open` and `AppHost::upgrade_format`, `Serving::retry`. +*Checked:* `ledger-gui` `tests/serving.rs` (`a_tab_opening_asks_the_server_to_open_that_company`, +`a_tab_closing_asks_the_server_to_close_that_company`, +`the_companies_the_window_restores_are_the_servers_to_open`, +`a_close_that_was_not_whole_is_said_to_the_person`, +`a_refused_start_is_said_and_nothing_is_asked_of_the_server`, +`a_failed_start_is_tried_again_when_the_next_tab_opens`, +`the_person_can_try_a_failed_start_again`, `a_server_still_starting_is_said_to_be_starting`, +`a_company_that_did_not_open_at_the_start_is_said_and_asked_for_again`); +`ledger-cli` `app_server.rs` (`opening_and_closing_a_company_drives_the_servers_book`, +`a_company_the_server_does_not_have_open_is_told`, +`the_format_upgrade_goes_to_the_windows_own_server`); +`ledger-host` `app_server.rs` tests (`a_close_with_an_incomplete_backup_is_a_notice_never_a_plain_success`, +`an_open_that_did_not_happen_says_why`). + +**WB-app-3 The bridge speaks to the running app and says so in words.** +`wanderbooks mcp --book X` connects to the root's `run/mcp.sock`. For a +root the app has served (it wrote `run/app-hosted`) with no host holding +it, the bridge holds no lease and starts no host. With the app not +running, every call is answered "Wanderbooks isn't running: start +Wanderbooks and open X."; with the app running but the company not open in +it, "Company X isn't open: open it in Wanderbooks." Neither answer is +final: the call after the app starts, or the company is opened, goes +through, in a session already running. A root no app has served, and any +root a host holds (`wanderbooks serve`, the headless host), behave as they +did: the bridge holds a lease and starts a host. +*Enforced:* `ledger_host::bridge` (`serves_the_app`, `keep_in_app`, +`not_running_words`, `not_open_words`), INVARIANT 12. +*Checked:* `ledger-host` bridge tests (`with_the_app_not_running_every_call_is_answered_in_words`, +`with_the_app_running_a_company_that_is_not_open_is_said_in_words`, +`a_host_bridge_passes_the_servers_words_on_as_they_are`); +`ledger-cli` `app_server.rs` (`the_bridge_says_the_app_isnt_running_then_works_once_it_is`: not +running, then running with the company closed, then open, then closed +again, then the window closed, in one session, with no host started). + +**WB-app-4 Closing the window is bounded and visible.** Asked to close, the +window stays up and says it is closing the books (finishing what is +running, making each company's last backup) until the server has exited, +or until 90 seconds have passed. Each open company is closed first, so the +window can say, in words, each company whose closing backup was not whole, +a server that exited badly, and one that is still finishing by itself; when +it has anything to say it stays up, showing it, with a "Close anyway" +button, and closing the window again is not that. It never kills the server. A close does not begin +while a job that changes the books is running (a restore, a format +upgrade: they hold the window already). A server that has exited on its own +is shown to the person at once, as a notice that assistants cannot reach +their companies. +*Enforced:* `ledger_gui::app::App` (`guard_server_close`), +`ledger_gui::serving::Serving::begin_stop`, `ledger_host::app_server::STOP_WAIT`. +*Checked:* `ledger-gui` `tests/serving.rs` (`closing_the_window_stops_the_server_and_waits_for_it`, +`a_server_that_will_not_exit_is_left_closing_and_the_window_closes`, +`a_close_that_was_not_whole_keeps_the_window_up_until_the_person_closes_anyway`, +`a_server_that_exits_on_its_own_is_said_once`); `ledger-cli` `app_server.rs` +(`a_stop_that_runs_out_of_time_leaves_the_server_closing_and_says_so`, +`a_closing_backup_that_was_not_whole_is_said_when_the_window_closes`, +`a_server_that_exits_badly_is_said_when_the_window_closes`).