feat(host): nothing starts a detached host but wanderbooks serve

Plan P15 3.1: the desktop app is the host. The bridge and every command that
needs the books now find what runs (a host held by serve, the app's server,
or nothing) and never start a host. The permanent run/app-hosted marker is
gone: a root is the app's only while a server runs on it with no host.

- opener: no host and no server is HoldError::NotRunning for every holder
  but serve; a server holding run/server.lock with no admin socket yet is
  waited for, in words (an opening or finishing server); the admin socket
  answering is the leaseless hold on the app's server, marker or none.
- commands: with nothing running, a command that manages the books' files
  or reads (list, create, adopt, restore, back-up, upgrade, token, connect)
  runs a server of its own, the one the app starts, for the length of the
  work and closes it, taking the same server.lock and books.lock; a command
  that needs an open company held by Wanderbooks (books open/close, upload,
  download) says "Start Wanderbooks first". The format upgrade goes to the
  server as an admin request when no host is there. doctor and close say
  what runs. hold_for_viewer and close_books are removed.
- bridge: the line to the app is the default with no host; a bridge whose
  host went away becomes it. The words an assistant gets name both ways to
  start the books (the app, or wanderbooks serve).
- app server: the child is its own process group on Unix (a terminal Ctrl+C
  reaches the window alone) and breaks away from a launcher's job on
  Windows (a kill-on-close job no longer kills it mid-backup); a stale
  marker from an earlier build is removed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 11:03:23 -07:00
1 parent 8d2187bae7
commit 22f447c0ba
5 files changed
+573 -285

No files matched your search

+59 -10
View File
@@ -28,7 +28,7 @@
//! leaves it alone: nothing is signalled. //! leaves it alone: nothing is signalled.
//! 6. A tab's company is opened and closed in the server by request; a //! 6. A tab's company is opened and closed in the server by request; a
//! company closed is not reachable, one opened is. //! company closed is not reachable, one opened is.
//! 7. The bridge, for a root the app has served and with no host: //! 7. The bridge, with no host (and no mark of any kind on the root):
//! "Wanderbooks isn't running" with the app not running, "Company X //! "Wanderbooks isn't running" with the app not running, "Company X
//! isn't open" with it running and the company not, and neither once //! 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 //! both are so, in a session that was already running; it starts no
@@ -49,9 +49,7 @@
mod common; mod common;
use common::{BOOK, Home, Server, clean_env}; use common::{BOOK, Home, Server, clean_env};
use ledger_host::app_server::{ use ledger_host::app_server::{ANOTHER_HAS_THEM, AppHost, AppServer, RETIRED_MARKER, Stopped};
ANOTHER_HAS_THEM, APP_MARKER, AppHost, AppServer, Stopped, app_hosted,
};
use ledger_host::opener::{host_lock_held, server_lock_held}; use ledger_host::opener::{host_lock_held, server_lock_held};
use ledger_mcp::admin::{Request, Response}; use ledger_mcp::admin::{Request, Response};
use serde_json::{Value, json}; use serde_json::{Value, json};
@@ -98,7 +96,10 @@ fn the_server_is_a_child_that_closes_when_its_input_does() {
let run = home.run(); let run = home.run();
let server = start(&home, &[]); let server = start(&home, &[]);
server.wait_ready(Duration::from_secs(60)).unwrap(); server.wait_ready(Duration::from_secs(60)).unwrap();
assert!(app_hosted(&run), "the root is the app's from now on"); assert!(
!run.join(RETIRED_MARKER).exists(),
"nothing marks the root as the app's"
);
assert!(server_lock_held(&run), "it holds the server lock"); assert!(server_lock_held(&run), "it holds the server lock");
assert!(!host_lock_held(&run), "no host was started beside it"); assert!(!host_lock_held(&run), "no host was started beside it");
assert!( assert!(
@@ -123,6 +124,49 @@ fn the_server_is_a_child_that_closes_when_its_input_does() {
); );
} }
/// A mark an earlier build left (`run/app-hosted`) means nothing now: the
/// root works as one without it, and the next start of the app's server
/// removes it (app_server.rs INVARIANT 7).
#[test]
fn a_mark_an_earlier_build_left_is_ignored_and_removed() {
let home = Home::new("app-old-mark");
let run = home.run();
std::fs::write(run.join(RETIRED_MARKER), b"").unwrap();
// Nothing runs: the bridge says so in words, mark or none.
let mut bridge = Bridge::start(&home);
assert!(error_of(&bridge.initialize()).starts_with("Wanderbooks isn't running"));
let server = start(&home, &[]);
server.wait_ready(Duration::from_secs(60)).unwrap();
assert!(
!run.join(RETIRED_MARKER).exists(),
"the old mark is removed"
);
assert!(matches!(home.admin(Request::List), Response::Books(_)));
assert_eq!(server.stop(Duration::from_secs(60)), Stopped::Closed);
}
/// The server is in a process group of its own, so a Ctrl+C at the
/// terminal the window was started from (sent to the terminal's
/// foreground group, the window's) never reaches it: it closes by its
/// input alone (app_server.rs INVARIANT 3).
#[cfg(unix)]
#[test]
fn the_server_has_a_process_group_of_its_own_so_a_terminal_ctrl_c_misses_it() {
let home = Home::new("app-group");
let server = start(&home, &[]);
server.wait_ready(Duration::from_secs(60)).unwrap();
let pid = server.pid() as libc::pid_t;
// SAFETY: getpgid and getpgrp only read process-group ids.
let (its, ours) = unsafe { (libc::getpgid(pid), libc::getpgrp()) };
assert_eq!(its, pid, "it leads a group of its own");
assert_ne!(its, ours, "it is not in the window's group");
// The group the terminal signals is the window's: a SIGINT sent to
// every process of that group but ours cannot be shown here, so the
// property is what makes it hold: nothing of the server is in it.
assert_eq!(server.exited(), None);
assert_eq!(server.stop(Duration::from_secs(60)), Stopped::Closed);
}
#[test] #[test]
fn opening_and_closing_a_company_drives_the_servers_book() { fn opening_and_closing_a_company_drives_the_servers_book() {
let home = Home::new("app-tabs"); let home = Home::new("app-tabs");
@@ -162,7 +206,10 @@ fn a_start_is_refused_when_another_program_has_the_books() {
let other = Server::start_with(&home, &["--open", "none"]); let other = Server::start_with(&home, &["--open", "none"]);
let refused = try_start().err().expect("refused"); let refused = try_start().err().expect("refused");
assert_eq!(refused, ANOTHER_HAS_THEM); assert_eq!(refused, ANOTHER_HAS_THEM);
assert!(!run.join(APP_MARKER).exists(), "a refusal touches nothing"); assert!(
!run.join(RETIRED_MARKER).exists(),
"a refusal touches nothing"
);
other.close(); other.close();
until("the other let go", || !server_lock_held(&run)); until("the other let go", || !server_lock_held(&run));
// A host holds them. // A host holds them.
@@ -174,7 +221,7 @@ fn a_start_is_refused_when_another_program_has_the_books() {
.unwrap(); .unwrap();
lock.lock().unwrap(); lock.lock().unwrap();
assert_eq!(try_start().err().expect("refused"), ANOTHER_HAS_THEM); assert_eq!(try_start().err().expect("refused"), ANOTHER_HAS_THEM);
assert!(!run.join(APP_MARKER).exists()); assert!(!run.join(RETIRED_MARKER).exists());
drop(lock); drop(lock);
// Held by nobody: it starts. // Held by nobody: it starts.
let server = try_start().expect("started"); let server = try_start().expect("started");
@@ -399,10 +446,12 @@ fn error_of(answer: &Value) -> String {
fn the_bridge_says_the_app_isnt_running_then_works_once_it_is() { fn the_bridge_says_the_app_isnt_running_then_works_once_it_is() {
let home = Home::new("app-bridge"); let home = Home::new("app-bridge");
let run = home.run(); let run = home.run();
// The app has served this root (it wrote its mark), and isn't running. // The app isn't running, and no host is: a root that was never the
std::fs::write(run.join(APP_MARKER), b"").unwrap(); // app's, so nothing marks it.
let mut bridge = Bridge::start(&home); let mut bridge = Bridge::start(&home);
let not_running = format!("Wanderbooks isn't running: start Wanderbooks and open {BOOK}."); let not_running = format!(
"Wanderbooks isn't running: start Wanderbooks and open {BOOK} (on a computer with no screen, run `wanderbooks serve`), then try again."
);
assert_eq!(error_of(&bridge.initialize()), not_running); assert_eq!(error_of(&bridge.initialize()), not_running);
assert_eq!(error_of(&bridge.start_call()), not_running); assert_eq!(error_of(&bridge.start_call()), not_running);
// No host was started for it. // No host was started for it.
+82 -43
View File
@@ -41,11 +41,16 @@
//! request, waiting for the server to be ready first; a close that //! 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 //! says its last backup was not whole is returned as a notice, never
//! as a plain success. //! as a plain success.
//! 7. Starting writes `run/app-hosted`, a file with nothing in it: the //! 7. Nothing marks a root as the app's. Whether the app (or another
//! root is this app's from then on, and the agents' bridge says //! server) has a root is read from what is running: no host holds
//! "Wanderbooks isn't running" for it, instead of starting a host //! `run/host.lock`, a server holds `run/server.lock`, and its admin
//! (bridge.rs INVARIANT 12). The marker is never removed: a root the //! socket answers ([`the_apps_server_runs`]). An earlier build wrote
//! app has served is the app's for good. //! a permanent file `run/app-hosted`; it means nothing now and is
//! removed at the next start of the app's server ([`RETIRED_MARKER`]).
//! With the app closed, the agents' bridge says "Wanderbooks isn't
//! running" (bridge.rs INVARIANT 12) whether or not the root was ever
//! the app's, and no program starts a host: only `wanderbooks serve`
//! does.
//! 8. A server the window started is either managed by the window or //! 8. A server the window started is either managed by the window or
//! stopped, never neither ([`AppHost`]): one that is alive and not //! stopped, never neither ([`AppHost`]): one that is alive and not
//! yet ready is waited for, not given up on; a start that fails, or //! yet ready is waited for, not given up on; a start that fails, or
@@ -72,7 +77,7 @@
//! holds a token's text. //! holds a token's text.
//! ``` //! ```
use crate::host::{SERVER_LOG, children_executable, open_log, private_options}; use crate::host::{SERVER_LOG, children_executable, open_log};
use crate::opener::{host_lock_held, server_lock_held}; use crate::opener::{host_lock_held, server_lock_held};
use ledger_mcp::admin::{self, CloseOutcome, OpenOutcome, Request, Response}; use ledger_mcp::admin::{self, CloseOutcome, OpenOutcome, Request, Response};
use ledger_store::root::Root; use ledger_store::root::Root;
@@ -82,9 +87,10 @@ use std::process::{Command, Stdio};
use std::sync::{Arc, Condvar, Mutex}; use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
/// The file in `run/` that says the root is the desktop app's /// The file an earlier build left in `run/` to say the root was the
/// (INVARIANT 7). /// desktop app's. Nothing reads it any more (INVARIANT 7); it is removed
pub const APP_MARKER: &str = "app-hosted"; /// when the app's server starts.
pub const RETIRED_MARKER: &str = "app-hosted";
/// How long a server may take to say it is ready: it opens and verifies /// 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 /// every company it was told to, and a large one rebuilding a drifted
@@ -131,6 +137,50 @@ impl Shared {
} }
} }
/// Windows: no console window of its own (CREATE_NO_WINDOW), so the
/// window's own Ctrl+C never reaches the server: it closes by its input
/// alone.
#[cfg(windows)]
const NO_WINDOW: u32 = 0x0800_0000;
/// Windows: leave the job the window runs in (CREATE_BREAKAWAY_FROM_JOB).
/// A launcher that puts the window in a job that kills everything in it
/// when the window dies would otherwise kill the server too, in the
/// middle of a backup, where the window's death is meant to reach it as
/// the end of its input and nothing more (INVARIANT 3). The server does
/// not outlive the window by it: it closes when its input does.
#[cfg(windows)]
const BREAKAWAY: u32 = 0x0100_0000;
/// Spawn the server with its input and output piped and its errors to
/// `log`. Windows: breaking away from the window's job, and without that
/// if the job does not let a process leave it.
fn spawn_child(command: &mut Command, log: &std::fs::File) -> Result<std::process::Child, String> {
let again = |e: std::io::Error| format!("can't start the books server: {e}");
let go = |command: &mut Command| -> Result<std::process::Child, std::io::Error> {
command
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(log.try_clone()?)
.spawn()
};
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(NO_WINDOW | BREAKAWAY);
match go(command) {
Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
command.creation_flags(NO_WINDOW);
go(command).map_err(again)
}
other => other.map_err(again),
}
}
#[cfg(not(windows))]
{
go(command).map_err(again)
}
}
/// What [`AppServer::stop`] came to. /// What [`AppServer::stop`] came to.
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
pub enum Stopped { pub enum Stopped {
@@ -163,16 +213,11 @@ pub struct AppServer {
pid: u32, pid: u32,
} }
/// Whether the root whose `run/` folder this is belongs to the desktop /// Whether a server runs for the app (or any program that is not a host)
/// app (INVARIANT 7). /// now: no host holds the root, a server does, and its admin socket
pub fn app_hosted(run: &Path) -> bool { /// answers (INVARIANT 7).
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 { pub fn the_apps_server_runs(run: &Path) -> bool {
app_hosted(run) && !host_lock_held(run) && server_lock_held(run) !host_lock_held(run) && server_lock_held(run) && crate::opener::admin_answers(run) == Ok(true)
} }
impl AppServer { impl AppServer {
@@ -197,12 +242,8 @@ impl AppServer {
if host_lock_held(&run) || server_lock_held(&run) { if host_lock_held(&run) || server_lock_held(&run) {
return Err(ANOTHER_HAS_THEM.into()); return Err(ANOTHER_HAS_THEM.into());
} }
private_options() // The mark an earlier build left means nothing now (INVARIANT 7).
.create(true) let _ = std::fs::remove_file(run.join(RETIRED_MARKER));
.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)) let log = open_log(&run.join(SERVER_LOG))
.map_err(|e| format!("can't open the server's log: {}", e.kind()))?; .map_err(|e| format!("can't open the server's log: {}", e.kind()))?;
let mut command = Command::new(exe); let mut command = Command::new(exe);
@@ -210,27 +251,20 @@ impl AppServer {
{ {
use std::os::unix::process::CommandExt; use std::os::unix::process::CommandExt;
command.arg0("wanderbooks"); command.arg0("wanderbooks");
// A group of its own: a Ctrl+C at the terminal the window was
// started from goes to the terminal's foreground group, the
// window's, and never to the server, which would close the
// books under an open window. The server closes by its input
// alone (INVARIANT 3), and a window that dies closes that.
command.process_group(0);
} }
command.arg("server"); command.arg("server");
if let Some(root) = root { if let Some(root) = root {
command.arg("--root").arg(root); command.arg("--root").arg(root);
} }
command.arg("--open").arg(open_argument(open)); 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); configure(&mut command);
let mut child = command let mut child = spawn_child(&mut command, &log)?;
.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 stdin = child.stdin.take();
let stdout = child.stdout.take(); let stdout = child.stdout.take();
let pid = child.id(); let pid = child.id();
@@ -350,6 +384,13 @@ impl AppServer {
} }
} }
/// One admin request, once the server is ready (a command's own
/// server: commands.rs `Reached`): its answer, or why not in words.
pub fn call(&self, request: Request, wait: Option<Duration>) -> Result<Response, String> {
self.wait_ready(READY_WAIT)?;
self.ask(request, wait)
}
/// Open the company `id` in the server, so assistants can reach it /// 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. /// (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. /// It waits for the server to be ready, and for the open.
@@ -891,12 +932,10 @@ mod tests {
} }
#[test] #[test]
fn a_root_is_the_apps_only_once_marked() { fn a_root_is_read_from_what_runs_and_not_from_a_file() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
assert!(!app_hosted(dir.path())); // A mark an earlier build left is nothing: no server runs there.
std::fs::write(dir.path().join(APP_MARKER), b"").unwrap(); std::fs::write(dir.path().join(RETIRED_MARKER), b"").unwrap();
assert!(app_hosted(dir.path()));
// No server runs there: not the app's server.
assert!(!the_apps_server_runs(dir.path())); assert!(!the_apps_server_runs(dir.path()));
} }
} }
+51 -30
View File
@@ -54,19 +54,22 @@
//! refusal, which says how the human makes one; but when the token //! 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 //! 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. //! 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 //! 12. With no host running (every root but a headless `wanderbooks
//! no host running, the bridge is a thin line to the app's server //! serve`'s), the bridge is a thin line to whatever server runs and
//! and nothing more: it holds no lease and starts no host (a //! nothing more: it holds no lease and starts no host (a detached
//! detached host is not how the desktop runs). With the app not //! host is not how the desktop runs; only `wanderbooks serve` starts
//! running, every call is answered "Wanderbooks isn't running: //! one). With nothing running, every call is answered "Wanderbooks
//! start Wanderbooks and open BOOK." (`not_running_words`); with //! isn't running: start Wanderbooks and open BOOK (on a computer
//! the app running but BOOK not open in it, "Company BOOK isn't //! with no screen, run `wanderbooks serve`), then try again."
//! open: open it in Wanderbooks." (`not_open_words`, for the //! (`not_running_words`); with the app running but BOOK not open in
//! server's `closed` refusal at the door). Neither is final: the //! it, "Company BOOK isn't open: open it in Wanderbooks."
//! call after the app starts, or the company opens, goes through, //! (`not_open_words`, for the server's `closed` refusal at the
//! in a session that was already running. A root no app has served, //! door). Neither is final: the call after the app starts, or the
//! and any root a host holds, behave as in 1 to 11 (`wanderbooks //! company opens, goes through, in a session that was already
//! serve`, the headless host). //! running. A root a host holds (`wanderbooks serve`, the headless
//! host) behaves as in 1 to 11: the bridge holds a lease on it; and
//! when that host goes and nothing takes its place, the bridge
//! becomes the line above, in words, instead of starting another.
//! ``` //! ```
use crate::knobs::{FLAG, Knobs}; use crate::knobs::{FLAG, Knobs};
@@ -100,7 +103,9 @@ const MAYBE_RAN: &str = "the connection to the books server broke while this cal
/// What the agent is told when the app is not running (INVARIANT 12). /// What the agent is told when the app is not running (INVARIANT 12).
fn not_running_words(book: &str) -> String { fn not_running_words(book: &str) -> String {
format!("Wanderbooks isn't running: start Wanderbooks and open {book}.") format!(
"Wanderbooks isn't running: start Wanderbooks and open {book} (on a computer with no screen, run `wanderbooks serve`), then try again."
)
} }
/// What the agent is told when the app runs but the company is not open /// What the agent is told when the app runs but the company is not open
@@ -191,8 +196,9 @@ struct Bridge {
/// The server's channel, for its owner check (INVARIANT 9). /// The server's channel, for its owner check (INVARIANT 9).
endpoint: ledger_mcp::ipc::Endpoint, endpoint: ledger_mcp::ipc::Endpoint,
/// Whether this is the line to the desktop app's server, with no host /// Whether this is the line to the desktop app's server, with no host
/// and no lease (INVARIANT 12). /// and no lease (INVARIANT 12). It turns true when a host the bridge
app: bool, /// held is gone and nothing took its place.
app: std::sync::atomic::AtomicBool,
} }
/// Who has the server's socket, when it isn't plainly this account. /// Who has the server's socket, when it isn't plainly this account.
@@ -923,7 +929,7 @@ impl Bridge {
Some(Link::Failed(why)) => return self.answer(&id, error(&id, why)), Some(Link::Failed(why)) => return self.answer(&id, error(&id, why)),
// The desktop app can't be reached, or the company isn't open // The desktop app can't be reached, or the company isn't open
// in it: said now, not "opening" (INVARIANT 12). // in it: said now, not "opening" (INVARIANT 12).
Some(Link::Refused(why)) if self.app => return self.answer(&id, error(&id, why)), Some(Link::Refused(why)) if self.is_app() => return self.answer(&id, error(&id, why)),
_ => None, _ => None,
}; };
let result = result.unwrap_or_else(|| { let result = result.unwrap_or_else(|| {
@@ -955,7 +961,7 @@ impl Bridge {
let run_dir = opener.run_dir().to_path_buf(); let run_dir = opener.run_dir().to_path_buf();
let root = run_dir.parent().unwrap_or(&run_dir).to_path_buf(); 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 account = crate::tokens::Account::new(&root, &self.book, &self.token_name);
let _ = self.token_file.set((account, run_dir)); let _ = self.token_file.set((account, run_dir.clone()));
let mut epoch = 0u64; let mut epoch = 0u64;
loop { loop {
let mut lease = match opener.hold().await { let mut lease = match opener.hold().await {
@@ -965,6 +971,15 @@ impl Bridge {
self.link.send_replace(Link::Closed); self.link.send_replace(Link::Closed);
return; return;
} }
// The host this bridge held is gone (`wanderbooks serve`
// ended) and nothing runs: the bridge becomes the line to
// whatever runs next, and says so in words until then
// (INVARIANT 12).
Err(crate::opener::HoldError::NotRunning) => {
self.app.store(true, std::sync::atomic::Ordering::SeqCst);
self.link.send_replace(Link::Opening);
return self.keep_in_app(run_dir).await;
}
Err(crate::opener::HoldError::Failed(why)) => { Err(crate::opener::HoldError::Failed(why)) => {
self.link.send_replace(Link::Failed(why)); self.link.send_replace(Link::Failed(why));
return; return;
@@ -1051,11 +1066,16 @@ impl Bridge {
} }
} }
/// Whether this is the line to the app's (or any host-less) server.
fn is_app(&self) -> bool {
self.app.load(std::sync::atomic::Ordering::SeqCst)
}
/// The words for a refusal at the server's door: for the desktop app's /// 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 /// `closed` refusal, the bridge's own (INVARIANT 12); else the
/// server's. /// server's.
fn refusal_words(&self, closed: bool, body: &str) -> String { fn refusal_words(&self, closed: bool, body: &str) -> String {
if self.app && closed { if self.is_app() && closed {
not_open_words(&self.book) not_open_words(&self.book)
} else { } else {
body.trim().chars().take(500).collect() body.trim().chars().take(500).collect()
@@ -1382,11 +1402,11 @@ async fn skip_line<R: tokio::io::AsyncBufRead + Unpin>(input: &mut R) -> bool {
} }
} }
/// Whether the bridge is the line to the desktop app's server for the /// Whether the bridge is the line to the app's server for the root whose
/// root whose `run/` folder this is (INVARIANT 12): an app has served the /// `run/` folder this is (INVARIANT 12): no host holds it. The server
/// root, and no host holds it. /// answering, or not running at all, is looked at call by call.
fn serves_the_app(run: &std::path::Path) -> bool { fn serves_the_app(run: &std::path::Path) -> bool {
crate::app_server::app_hosted(run) && !crate::opener::host_lock_held(run) !crate::opener::host_lock_held(run)
} }
fn usage(prog: &str) { fn usage(prog: &str) {
@@ -1470,7 +1490,7 @@ pub fn run(
next_id: std::sync::atomic::AtomicU64::new(1), next_id: std::sync::atomic::AtomicU64::new(1),
pending: Mutex::new(std::collections::HashMap::new()), pending: Mutex::new(std::collections::HashMap::new()),
endpoint, endpoint,
app, app: std::sync::atomic::AtomicBool::new(app),
}); });
let keeper = if app { let keeper = if app {
tokio::spawn(bridge.clone().keep_in_app(run_dir)) tokio::spawn(bridge.clone().keep_in_app(run_dir))
@@ -1834,7 +1854,7 @@ mod against_a_server {
next_id: std::sync::atomic::AtomicU64::new(1), next_id: std::sync::atomic::AtomicU64::new(1),
pending: Mutex::new(std::collections::HashMap::new()), pending: Mutex::new(std::collections::HashMap::new()),
endpoint, endpoint,
app, app: std::sync::atomic::AtomicBool::new(app),
}); });
(bridge, rx) (bridge, rx)
} }
@@ -2605,7 +2625,7 @@ mod against_a_server {
fn the_two_messages_are_plain_and_name_the_company() { fn the_two_messages_are_plain_and_name_the_company() {
assert_eq!( assert_eq!(
not_running_words("acme"), not_running_words("acme"),
"Wanderbooks isn't running: start Wanderbooks and open acme." "Wanderbooks isn't running: start Wanderbooks and open acme (on a computer with no screen, run `wanderbooks serve`), then try again."
); );
assert_eq!( assert_eq!(
not_open_words("acme"), not_open_words("acme"),
@@ -2614,12 +2634,13 @@ mod against_a_server {
} }
#[test] #[test]
fn a_root_is_the_apps_only_when_marked_and_no_host_holds_it() { fn a_root_is_the_line_to_the_app_when_no_host_holds_it() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
assert!(!serves_the_app(dir.path()), "no app has served it"); assert!(serves_the_app(dir.path()), "no host holds it");
std::fs::write(dir.path().join(crate::app_server::APP_MARKER), b"").unwrap(); // A mark an earlier build left changes nothing.
std::fs::write(dir.path().join(crate::app_server::RETIRED_MARKER), b"").unwrap();
assert!(serves_the_app(dir.path())); assert!(serves_the_app(dir.path()));
// A host holding the root is the headless path, marked or not. // A host holding the root is the headless path.
let lock = std::fs::File::create(dir.path().join(crate::lease::HOST_LOCK)).unwrap(); let lock = std::fs::File::create(dir.path().join(crate::lease::HOST_LOCK)).unwrap();
lock.lock().unwrap(); lock.lock().unwrap();
assert!(!serves_the_app(dir.path())); assert!(!serves_the_app(dir.path()));
+299 -171
View File
@@ -108,7 +108,7 @@ fn exit(code: i32) -> Box<dyn std::error::Error> {
async fn open(opener: &mut Opener) -> Result<Lease, HoldError> { async fn open(opener: &mut Opener) -> Result<Lease, HoldError> {
let deadline = tokio::time::Instant::now() + opener.knobs().open_wait; let deadline = tokio::time::Instant::now() + opener.knobs().open_wait;
let too_long = || -> HoldError { let too_long = || -> HoldError {
"the books didn't open in time: run `wanderbooks doctor` to see why".into() "the books didn't open in time (Wanderbooks may still be opening a large company: try again in a moment): run `wanderbooks doctor` to see why".into()
}; };
loop { loop {
let mut lease = tokio::time::timeout_at(deadline, opener.hold()) let mut lease = tokio::time::timeout_at(deadline, opener.hold())
@@ -145,6 +145,135 @@ async fn open(opener: &mut Opener) -> Result<Lease, HoldError> {
} }
} }
/// Whether a command can do its work with no program holding the books
/// open, and what its own server then has open.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Direct {
/// It needs the books held open by Wanderbooks (the app, or `serve`):
/// with none running it says so ([`START_WANDERBOOKS`]).
No,
/// It manages the books' files, or reads: with nothing running it runs
/// a books server of its own for as long as the work takes (the same
/// server, taking the same locks, started the way the app starts its
/// own), with these companies open, and lets go of it when it is done.
With(Vec<String>),
}
/// What a request needs (the table in docs/spec/claims/app.md, WB-app-5).
fn direct_for(request: &Request) -> Direct {
match request {
// Opening and closing a company in a running server mean nothing
// with none running; the sessions and the backfill are of a
// running server's.
Request::OpenBook { .. }
| Request::CloseBook { .. }
| Request::Sessions
| Request::Extract { .. } => Direct::No,
// Work on an open company.
Request::BackUpNow { id, .. } | Request::UpgradeFormat { id, .. } => {
Direct::With(vec![id.clone()])
}
// The rest read the list, or make and move files and tokens.
_ => Direct::With(Vec::new()),
}
}
/// How long a command waits for its own server to close when it is done:
/// the same as the window's (a last backup of what it opened).
const OWN_STOP_WAIT: Duration = crate::app_server::STOP_WAIT;
/// What a command holds while it works: a lease on a host or on the app's
/// server (no host behind it), or its own server, which it closes when it
/// is done.
struct Reached {
run_dir: PathBuf,
/// Held while the work runs (None for the app's server).
lease: Option<Lease>,
/// The command's own server, when nothing else ran.
own: Option<std::sync::Arc<crate::app_server::AppServer>>,
}
/// What a command says when the books were closed under it.
fn closed_just_now() -> String {
"the books were closed just now (Close the books): nothing was done".to_string()
}
/// A hold that failed, in words.
fn hold_words(e: HoldError) -> String {
match e {
HoldError::ClosedByOwner => closed_just_now(),
HoldError::NotRunning => crate::opener::START_WANDERBOOKS.to_string(),
HoldError::Failed(why) => why,
}
}
impl Reached {
/// The admin socket of what is held.
fn admin_socket(&self) -> PathBuf {
self.run_dir.join(ledger_mcp::local::ADMIN_SOCKET)
}
/// One admin request, off the async threads.
async fn ask(&self, request: Request, wait: Option<Duration>) -> Result<Response, String> {
let socket = self.admin_socket();
tokio::task::spawn_blocking(move || admin::call_within(&socket, request, wait))
.await
.map_err(|e| e.to_string())?
.map_err(|e| e.to_string())
}
/// Let go: the lease ends, and a server of the command's own is
/// closed (its last backups made), waited for, and said so when it is
/// still at it.
async fn release(self) {
drop(self.lease);
if let Some(own) = self.own {
let stopped = tokio::task::spawn_blocking(move || own.stop(OWN_STOP_WAIT)).await;
match stopped {
Ok(crate::app_server::Stopped::Closed) | Err(_) => {}
Ok(crate::app_server::Stopped::Failed(why)) => {
eprintln!("warning: {why}: `wanderbooks doctor` has its last words");
}
Ok(crate::app_server::Stopped::StillClosing) => {
eprintln!("note: {}", crate::app_server::STILL_CLOSING);
}
}
}
}
}
/// Hold the books for a command, or, with nothing running and the work
/// one `direct` allows, run a server of its own (WB-app-5).
async fn reach(opener: &mut Opener, common: &Common, direct: &Direct) -> Result<Reached, String> {
let run_dir = opener.run_dir().to_path_buf();
match open(opener).await {
Ok(lease) => Ok(Reached {
run_dir,
lease: Some(lease),
own: None,
}),
Err(HoldError::NotRunning) => {
let Direct::With(books) = direct else {
return Err(crate::opener::START_WANDERBOOKS.to_string());
};
let (root, books) = (common.root.clone(), books.clone());
let own = tokio::task::spawn_blocking(move || {
let server = crate::app_server::AppServer::start(root.as_deref(), &books)?;
server.wait_ready(crate::app_server::READY_WAIT)?;
Ok::<_, String>(server)
})
.await
.map_err(|e| e.to_string())??;
Ok(Reached {
run_dir,
lease: None,
own: Some(std::sync::Arc::new(own)),
})
}
Err(e) => Err(hold_words(e)),
}
}
/// Ask the server's admin socket, holding the books open meanwhile. /// Ask the server's admin socket, holding the books open meanwhile.
fn with_server(common: &Common, request: Request) -> Result<Response, String> { fn with_server(common: &Common, request: Request) -> Result<Response, String> {
with_server_in(common, request).map(|(answer, _)| answer) with_server_in(common, request).map(|(answer, _)| answer)
@@ -153,34 +282,40 @@ fn with_server(common: &Common, request: Request) -> Result<Response, String> {
/// [`with_server`], with the root's `run/` folder too (where the /// [`with_server`], with the root's `run/` folder too (where the
/// token files live). /// token files live).
fn with_server_in(common: &Common, request: Request) -> Result<(Response, PathBuf), String> { fn with_server_in(common: &Common, request: Request) -> Result<(Response, PathBuf), String> {
let direct = direct_for(&request);
with_server_as(common, request, direct)
}
/// [`with_server_in`] with what a command with nothing running may do
/// ([`Direct`]) said by the caller: a list that must show what an open
/// company waits for, for one.
fn with_server_as(
common: &Common,
request: Request,
direct: Direct,
) -> Result<(Response, PathBuf), String> {
let rt = tokio::runtime::Builder::new_multi_thread() let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all() .enable_all()
.build() .build()
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
let outcome = rt.block_on(async { let outcome = rt.block_on(async {
let mut opener = Opener::new(common.root.as_deref(), common.knobs, Kind::Cli, None)?; let mut opener = Opener::new(common.root.as_deref(), common.knobs, Kind::Cli, None)?;
let lease = open(&mut opener).await.map_err(|e| match e { let reached = reach(&mut opener, common, &direct).await?;
HoldError::ClosedByOwner => { let run_dir = reached.run_dir.clone();
"the books were closed just now (Close the books): nothing was done".to_string()
}
HoldError::Failed(why) => why,
})?;
let run_dir = opener.run_dir().to_path_buf();
// The books are open: asked about a format upgrade first // The books are open: asked about a format upgrade first
// (INVARIANT 6). // (INVARIANT 6). (A server of the command's own has only what
if common.ask_upgrades && !ASKED_UPGRADES.swap(true, std::sync::atomic::Ordering::SeqCst) { // the command named open: nothing waits there to be offered.)
if common.ask_upgrades
&& reached.own.is_none()
&& !ASKED_UPGRADES.swap(true, std::sync::atomic::Ordering::SeqCst)
{
let run = run_dir.clone(); let run = run_dir.clone();
let _ = tokio::task::spawn_blocking(move || offer_upgrades(&run)).await; let _ = tokio::task::spawn_blocking(move || offer_upgrades(&run)).await;
} }
let socket = run_dir.join(ledger_mcp::local::ADMIN_SOCKET);
// A list is quick; a create or an adoption takes what it takes. // A list is quick; a create or an adoption takes what it takes.
let wait = matches!(request, Request::List | Request::TokenList).then_some(LIST_WAIT); let wait = matches!(request, Request::List | Request::TokenList).then_some(LIST_WAIT);
let answer = let answer = reached.ask(request, wait).await;
tokio::task::spawn_blocking(move || admin::call_within(&socket, request, wait)) reached.release().await;
.await
.map_err(|e| e.to_string())?
.map_err(|e| e.to_string());
drop(lease);
answer.map(|a| (a, run_dir)) answer.map(|a| (a, run_dir))
}); });
// Past its deadline, the command ends: nothing pending holds it. // Past its deadline, the command ends: nothing pending holds it.
@@ -222,7 +357,7 @@ fn no_host(server_lock_held: bool) -> &'static str {
if server_lock_held { if server_lock_held {
"The books are closing: a books server is finishing its last call." "The books are closing: a books server is finishing its last call."
} else { } else {
"The books are closed." "The books are closed: Wanderbooks isn't running. Open the Wanderbooks app, or, on a computer with no screen, run `wanderbooks serve`."
} }
} }
@@ -327,8 +462,8 @@ pub fn serve(
println!("The books were closed (Close the books)."); println!("The books were closed (Close the books).");
return Ok(()); return Ok(());
} }
Err(HoldError::Failed(why)) => { Err(e @ (HoldError::Failed(_) | HoldError::NotRunning)) => {
eprintln!("error: {why}"); eprintln!("error: {}", hold_words(e));
return Err(exit(1)); return Err(exit(1));
} }
}; };
@@ -427,6 +562,14 @@ pub fn close(
exit(1) exit(1)
})?; })?;
match asked { match asked {
None if crate::app_server::the_apps_server_runs(&run) => {
println!("{APP_HAS_THEM}.");
Ok(())
}
None if crate::opener::server_lock_held(&run) => {
println!("The books are closing: a books server is finishing its last call.");
Ok(())
}
None => { None => {
println!("The books are already closed."); println!("The books are already closed.");
Ok(()) Ok(())
@@ -558,7 +701,21 @@ pub fn books(
// (INVARIANT 6), unless it is the upgrade itself. // (INVARIANT 6), unless it is the upgrade itself.
common.ask_upgrades = !matches!(words.as_slice(), ["upgrade", ..]); common.ask_upgrades = !matches!(words.as_slice(), ["upgrade", ..]);
let answer = match words.as_slice() { let answer = match words.as_slice() {
["list"] => with_server(&common, Request::List), ["list"] => match listed_while_closed(&common) {
Ok(Some(ids)) => {
if ids.is_empty() {
println!("No books yet: `wanderbooks books create ID` starts some.");
}
for id in ids {
println!(
"{id} not open: Wanderbooks isn't running (start it, or run `wanderbooks serve`, to open it)"
);
}
return Ok(());
}
Ok(None) => with_server(&common, Request::List),
Err(why) => Err(why),
},
["create", new] => with_server( ["create", new] => with_server(
&common, &common,
Request::Create { Request::Create {
@@ -745,6 +902,21 @@ pub fn books(
} }
/// One book, as `books list` and `doctor` show it. /// One book, as `books list` and `doctor` show it.
/// The books of the root by name, read from the folder and no more, when
/// nothing runs: no host and no server holds the root, so there is no open
/// or closed to tell, and nothing is changed or read of the books, which
/// is why it takes no lock (WB-app-5). `None` when something runs: ask it.
fn listed_while_closed(common: &Common) -> Result<Option<Vec<String>>, String> {
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())?;
if crate::opener::host_lock_held(&run) || crate::opener::server_lock_held(&run) {
return Ok(None);
}
let ids = found.list_books().map_err(|e| e.to_string())?;
Ok(Some(ids.iter().map(|id| id.to_string()).collect()))
}
fn book_line(b: &admin::BookStatus) -> String { fn book_line(b: &admin::BookStatus) -> String {
if b.closed { if b.closed {
return format!( return format!(
@@ -915,13 +1087,36 @@ fn consent_now(run: &Path, book: &str, passphrase: &str) -> Result<Vec<String>,
// Refused: nothing was done (the server says so too). // Refused: nothing was done (the server says so too).
Some(HostMsg::Refused(why)) => Err(format!("not upgraded: {why}")), Some(HostMsg::Refused(why)) => Err(format!("not upgraded: {why}")),
Some(HostMsg::Uncertain(why)) => Err(why), Some(HostMsg::Uncertain(why)) => Err(why),
// Sent, and the host gone without an answer (closed, or killed): // No host: the app's server, or one of the command's own, takes
// its server may have done it all the same. // it as an admin request (WB-app-2).
None => Err( None => upgrade_by_admin(run, book, passphrase),
"the books' host gave no answer, so it may or may not have been done: `wanderbooks books list` says whether the books still wait for it" Some(other) => Err(format!("the books' host answered oddly: {other:?}")),
}
}
/// The format upgrade as an admin request to the server that runs with no
/// host (the app's, or a command's own): what it said, a line each; or
/// why not, which says whether it may have been done all the same.
fn upgrade_by_admin(run: &Path, book: &str, passphrase: &str) -> Result<Vec<String>, String> {
let request = Request::UpgradeFormat {
id: book.to_string(),
passphrase: admin::Passphrase(passphrase.to_string()),
};
match admin::call_within(
&run.join(ledger_mcp::local::ADMIN_SOCKET),
request,
Some(UPGRADE_WAIT),
) {
Ok(Response::FormatUpgraded(u)) => Ok(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(), .into(),
), ),
Some(other) => Err(format!("the books' host answered oddly: {other:?}")), Err(admin::CallError::NotSent(why)) => Err(format!("not upgraded: {why}")),
Err(admin::CallError::Unknown(why)) => Err(format!(
"{why}, so it may or may not have been done: `wanderbooks books list` says whether the books still wait for it"
)),
} }
} }
@@ -947,18 +1142,16 @@ pub fn upgrade_format(
let not_sent = |why: String| format!("not upgraded: {why}"); let not_sent = |why: String| format!("not upgraded: {why}");
let mut opener = let mut opener =
Opener::new(common.root.as_deref(), common.knobs, Kind::Cli, None).map_err(not_sent)?; Opener::new(common.root.as_deref(), common.knobs, Kind::Cli, None).map_err(not_sent)?;
let lease = open(&mut opener).await.map_err(|e| match e { // With nothing running, a server of its own with this company
HoldError::ClosedByOwner => { // open does it.
"not upgraded: the books were closed just now (Close the books): nothing was done" let reached = reach(&mut opener, common, &Direct::With(vec![book.clone()]))
.to_string() .await
} .map_err(not_sent)?;
HoldError::Failed(why) => not_sent(why), let run = reached.run_dir.clone();
})?;
let run = opener.run_dir().to_path_buf();
let asked = tokio::task::spawn_blocking(move || consent_now(&run, &book, &passphrase)) let asked = tokio::task::spawn_blocking(move || consent_now(&run, &book, &passphrase))
.await .await
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
drop(lease); reached.release().await;
asked asked
}); });
rt.shutdown_timeout(Duration::from_secs(1)); rt.shutdown_timeout(Duration::from_secs(1));
@@ -1057,9 +1250,14 @@ fn upgrade(common: &Common, book: &str) -> Result<(), Box<dyn std::error::Error>
Ok(id) => id.to_string(), Ok(id) => id.to_string(),
Err(e) => return fail(e.to_string()), Err(e) => return fail(e.to_string()),
}; };
let listed = match with_server(common, Request::List) { // With nothing running, the list is of a server of its own with this
// company open, so what it waits for shows.
let listed = match with_server_as(common, Request::List, Direct::With(vec![book.clone()]))
.map(|(answer, _)| answer)
{
Ok(Response::Books(books)) => books, Ok(Response::Books(books)) => books,
Ok(Response::Refused(why)) | Err(why) => return fail(why), Ok(Response::Refused(why)) => return fail(why),
Err(why) => return fail(why),
Ok(other) => return fail(format!("the books server answered oddly: {other:?}")), Ok(other) => return fail(format!("the books server answered oddly: {other:?}")),
}; };
let Some(status) = listed.into_iter().find(|b| b.id == book) else { let Some(status) = listed.into_iter().find(|b| b.id == book) else {
@@ -1129,37 +1327,10 @@ pub fn new_books(common: &Common, id: &str, currency: &str) -> Result<String, St
} }
} }
/// What closing the books says while the app has them open: the app's /// What `wanderbooks close` says while the app has the books open: the
/// tabs and its window close them. /// app's tabs and its window close them (the app has no host to ask).
const APP_HAS_THEM: &str = "Wanderbooks (the app) has these books open: close a company's tab to close that company, or close the window to close them all"; const APP_HAS_THEM: &str = "Wanderbooks (the app) has these books open: close a company's tab to close that company, or close the window to close them all";
/// "Close the books": everything holding them lets go (the lease
/// socket's close intent). What came of it.
pub fn close_books(common: &Common) -> Result<String, String> {
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
.map(|d| {
let mut c = d.chars();
c.next()
.map(|first| format!("{}{}.", first.to_uppercase(), c.as_str()))
.unwrap_or_default()
})
.filter(|d| !d.is_empty())
.unwrap_or_else(|| "The books are closing.".into())),
Some(HostMsg::Refused(why)) => Err(why),
Some(HostMsg::Uncertain(why)) => Err(why),
Some(other) => Err(format!("the books' host answered oddly: {other:?}")),
}
}
/// An update the host has downloaded and checked, waiting for the owner /// An update the host has downloaded and checked, waiting for the owner
/// (the viewer's notice; P11a step 4). /// (the viewer's notice; P11a step 4).
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
@@ -1276,61 +1447,6 @@ const NO_SELF_UPDATE: &str = "self-update isn't available on this platform";
/// The longest an agent's own command may take to add the books. /// The longest an agent's own command may take to add the books.
const CONNECT_WAIT: Duration = Duration::from_secs(60); const CONNECT_WAIT: Duration = Duration::from_secs(60);
/// How long the viewer's hold waits before trying again after books that
/// wouldn't open.
const VIEWER_RETRY: Duration = Duration::from_secs(30);
/// Hold the books `book` open while the viewer runs (a lease of kind
/// app), on a thread of its own: the window never waits for it. It lets
/// go only when the owner closes the books (and when the viewer ends,
/// with the process); books that stop, or won't open, are tried again.
pub fn hold_for_viewer(common: &Common, book: Option<String>) -> std::thread::JoinHandle<()> {
let common = common.clone();
std::thread::spawn(move || {
let Ok(rt) = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
else {
return;
};
rt.block_on(async {
let Ok(mut opener) = Opener::new(common.root.as_deref(), common.knobs, Kind::App, book)
else {
return;
};
loop {
// The same opener each time round (it knows it held the
// books, so it never reopens books the owner closed); its
// failures counted afresh.
opener.forget_failures();
loop {
let mut lease = match open(&mut opener).await {
Ok(lease) => lease,
Err(HoldError::ClosedByOwner) => return,
Err(HoldError::Failed(_)) => break,
};
match lease.next().await {
Some(HostMsg::Ending {
reason: Reason::ClosedByOwner,
..
}) => return,
Some(HostMsg::Ending {
reason: Reason::Restarting | Reason::Closing,
..
}) => {}
_ => {
if opener.failed().await.is_err() {
break;
}
}
}
}
tokio::time::sleep(VIEWER_RETRY).await;
}
});
})
}
/// What a backup made now came to, a line each. /// What a backup made now came to, a line each.
pub fn backed_up_lines(head_seq: u64, targets: &[admin::BackedUpTarget]) -> Vec<String> { pub fn backed_up_lines(head_seq: u64, targets: &[admin::BackedUpTarget]) -> Vec<String> {
if targets.is_empty() { if targets.is_empty() {
@@ -2775,6 +2891,52 @@ fn log_tail(run: &Path, name: &str, root: &Path, n: usize) -> Vec<String> {
.collect() .collect()
} }
/// `doctor`'s look at a running server through its admin socket: each
/// book and why one didn't open, the agents' tokens, who is connected.
fn admin_report(run: &Path) {
// Each book, and why one didn't open.
let socket = run.join(ledger_mcp::local::ADMIN_SOCKET);
// A quick look: a wedged server doesn't hang the doctor.
let listed = admin::call_within(&socket, Request::List, Some(DOCTOR_WAIT));
if let Err(why) = &listed {
println!(" The books server doesn't answer: {why}");
}
if let Ok(admin::Response::Books(books)) = listed {
for b in books {
println!(" {}", book_line(&b));
if let Some(line) = database_line(&b) {
println!(" {line}");
}
}
// Agents' tokens: how many each book has.
match admin::call_within(&socket, Request::TokenList, Some(DOCTOR_WAIT)) {
Ok(admin::Response::Tokens(tokens)) if tokens.is_empty() => {
println!("Agents' tokens: none yet (`wanderbooks token create --book ID`).")
}
Ok(admin::Response::Tokens(tokens)) => {
println!("Agents' tokens:");
for t in tokens {
println!(" {} {} {}", t.book, t.name, t.scopes.join(","));
}
}
Ok(admin::Response::Refused(why)) => println!("Agents' tokens: {why}"),
Ok(_) | Err(_) => {}
}
// Who is connected to each open book, and what it is doing.
match admin::call_within(&socket, Request::Sessions, Some(DOCTOR_WAIT)) {
Ok(admin::Response::Sessions(open)) => {
for line in session_lines(&open) {
println!("{line}");
}
}
Ok(admin::Response::Refused(why)) => {
println!("Assistants connected: {why}")
}
Ok(_) | Err(_) => {}
}
}
}
/// `wanderbooks doctor`: whether the books are open, who holds them, and /// `wanderbooks doctor`: whether the books are open, who holds them, and
/// what the host and the server last said. It names no folder. /// what the host and the server last said. It names no folder.
pub fn doctor( pub fn doctor(
@@ -2824,51 +2986,20 @@ pub fn doctor(
} }
let run = root.run_dir().map_err(|e| e.to_string())?; let run = root.run_dir().map_err(|e| e.to_string())?;
match crate::opener::ask_once_within(&run, Ask::Leases, DOCTOR_WAIT) { match crate::opener::ask_once_within(&run, Ask::Leases, DOCTOR_WAIT) {
Ok(None) => println!("{}", no_host(crate::opener::server_lock_held(&run))), // No host: the app's server (or another that runs without one),
// one still opening or finishing, or nothing (WB-app-3).
Ok(None) if crate::app_server::the_apps_server_runs(&run) => {
println!("The books are open: Wanderbooks (the app) has them.");
admin_report(&run);
}
Ok(None) if crate::opener::server_lock_held(&run) => println!(
"Wanderbooks is opening the books (or finishing the last backup of the last session): its server isn't answering yet."
),
Ok(None) => println!("{}", no_host(false)),
Ok(Some(HostMsg::Leases { ready, leases })) => { Ok(Some(HostMsg::Leases { ready, leases })) => {
if ready { if ready {
println!("The books are open."); println!("The books are open.");
// Each book, and why one didn't open. admin_report(&run);
let socket = run.join(ledger_mcp::local::ADMIN_SOCKET);
// A quick look: a wedged server doesn't hang the doctor.
let listed = admin::call_within(&socket, Request::List, Some(DOCTOR_WAIT));
if let Err(why) = &listed {
println!(" The books server doesn't answer: {why}");
}
if let Ok(admin::Response::Books(books)) = listed {
for b in books {
println!(" {}", book_line(&b));
if let Some(line) = database_line(&b) {
println!(" {line}");
}
}
// Agents' tokens: how many each book has.
match admin::call_within(&socket, Request::TokenList, Some(DOCTOR_WAIT)) {
Ok(admin::Response::Tokens(tokens)) if tokens.is_empty() => println!(
"Agents' tokens: none yet (`wanderbooks token create --book ID`)."
),
Ok(admin::Response::Tokens(tokens)) => {
println!("Agents' tokens:");
for t in tokens {
println!(" {} {} {}", t.book, t.name, t.scopes.join(","));
}
}
Ok(admin::Response::Refused(why)) => println!("Agents' tokens: {why}"),
Ok(_) | Err(_) => {}
}
// Who is connected to each open book, and what it is doing.
match admin::call_within(&socket, Request::Sessions, Some(DOCTOR_WAIT)) {
Ok(admin::Response::Sessions(open)) => {
for line in session_lines(&open) {
println!("{line}");
}
}
Ok(admin::Response::Refused(why)) => {
println!("Assistants connected: {why}")
}
Ok(_) | Err(_) => {}
}
}
} else { } else {
println!("The books are opening (the books server isn't ready yet)."); println!("The books are opening (the books server isn't ready yet).");
} }
@@ -3240,12 +3371,8 @@ fn on_the_socket(
Kind::Cli, Kind::Cli,
None, None,
)?; )?;
let lease = open(&mut opener).await.map_err(|e| match e { // A call to an open book: with nothing running there is none.
HoldError::ClosedByOwner => { let reached = reach(&mut opener, common, &Direct::No).await?;
"the books were closed just now (Close the books): nothing was done".to_string()
}
HoldError::Failed(why) => why,
})?;
let run_dir = opener.run_dir().to_path_buf(); let run_dir = opener.run_dir().to_path_buf();
let root = run_dir.parent().unwrap_or(&run_dir).to_path_buf(); let root = run_dir.parent().unwrap_or(&run_dir).to_path_buf();
let account = crate::tokens::Account::new(&root, book, token_name); let account = crate::tokens::Account::new(&root, book, token_name);
@@ -3277,7 +3404,7 @@ fn on_the_socket(
.await .await
.map_err(|e| format!("the books server's answer was cut off: {e}"))? .map_err(|e| format!("the books server's answer was cut off: {e}"))?
.to_vec(); .to_vec();
drop(lease); reached.release().await;
Ok::<_, String>((status, headers, body)) Ok::<_, String>((status, headers, body))
}); });
rt.shutdown_timeout(Duration::from_secs(1)); rt.shutdown_timeout(Duration::from_secs(1));
@@ -3782,7 +3909,8 @@ mod tests {
#[test] #[test]
fn doctor_tells_closing_from_closed() { fn doctor_tells_closing_from_closed() {
assert!(no_host(true).contains("closing")); assert!(no_host(true).contains("closing"));
assert_eq!(no_host(false), "The books are closed."); assert!(no_host(false).starts_with("The books are closed: Wanderbooks isn't running."));
assert!(no_host(false).contains("wanderbooks serve"));
} }
fn adopted() -> admin::Adopted { fn adopted() -> admin::Adopted {
+82 -31
View File
@@ -1,19 +1,21 @@
//! Holding the books: how every holder takes its lease (plan 3.9). //! Holding the books: how every holder takes its lease (plan 3.9).
//! //!
//! ```text //! ```text
//! GOAL: a holder gets its lease on the one host, starting one when none //! GOAL: a holder gets its lease on the one host (the headless `serve`'s,
//! answers, even when several holders start at once; across a //! started by `serve` alone, even when several start at once) or on
//! the desktop app's own server; across a
//! restart it simply holds again; a host that keeps failing is //! restart it simply holds again; a host that keeps failing is
//! given up on, plainly, instead of retried forever. //! given up on, plainly, instead of retried forever.
//! SOURCE: plan/served.md 3.9 ("One host, even in a race", "Closing": //! SOURCE: plan/served.md 3.9 ("One host, even in a race", "Closing":
//! backoff 1, 2, 4 … 60 s, at most five tries; "Restarting": //! backoff 1, 2, 4 … 60 s, at most five tries; "Restarting":
//! openers wait on update.lock); tests host_respawns, //! openers wait on update.lock); plan/p15-app-and-relay.md 3.1
//! respawn_backs_off. //! (only `serve` keeps a host; the app is the host otherwise),
//! WB-app-3, WB-app-5; tests host_respawns, respawn_backs_off.
//! INVARIANTS: //! INVARIANTS:
//! 1. Before each try the holder waits while a restart holds //! 1. Before each try the holder waits while a restart holds
//! run/update.lock. //! run/update.lock.
//! 2. No host answering: it starts one (cleanly, start.rs) and keeps //! 2. No host answering: `serve` starts one (cleanly, start.rs) and keeps
//! trying; //! trying (7);
//! a host that is closing or restarting turns it away and it tries //! a host that is closing or restarting turns it away and it tries
//! again until a host takes the lease. //! again until a host takes the lease.
//! 3. A start that brings no lease within START_WAIT (or whose host //! 3. A start that brings no lease within START_WAIT (or whose host
@@ -28,12 +30,21 @@
//! 5. A holder that has held before, turned away because the owner //! 5. A holder that has held before, turned away because the owner
//! closed the books, stays closed (HoldError::ClosedByOwner); a new //! closed the books, stays closed (HoldError::ClosedByOwner); a new
//! holder waits for a new host. //! holder waits for a new host.
//! 6. A root the desktop app has served (app_server.rs INVARIANT 7) //! 6. No host answering, a books server holding the books (`run/
//! with the app's own server running and no host: a command's or //! server.lock`), and its admin socket answering: the desktop app's
//! the viewer's hold is a lease on that server with no host behind //! own server (P15 3.1). A holder other than `wanderbooks serve`
//! it (ready at once, never ended: the app decides when the books //! takes a lease on it with no host behind it (ready at once, never
//! close), no host is started beside it, and `wanderbooks serve` //! ended: the app decides when the books close), and no host is
//! is told the app has the books. //! started beside it; `wanderbooks serve` is told the app has the
//! books. The server's lock held and no admin socket yet is a server
//! still opening its companies (or finishing its last backup): the
//! holder waits for it, in words, for as long as its own wait lasts.
//! 7. No host, no server: only `wanderbooks serve` starts a host (the
//! headless path, plan 3.1). Every other holder is turned away with
//! [`HoldError::NotRunning`], and says, in words, to start
//! Wanderbooks; a command that can do its work without the books
//! being held open runs its own server for the length of the work
//! instead (commands.rs).
//! ``` //! ```
use crate::knobs::Knobs; use crate::knobs::Knobs;
@@ -69,14 +80,22 @@ pub enum HoldError {
/// The owner closed the books, and this holder had held them /// The owner closed the books, and this holder had held them
/// (INVARIANT 5). /// (INVARIANT 5).
ClosedByOwner, ClosedByOwner,
/// Nothing holds the books (no host, no server), and this holder
/// starts none (INVARIANT 7).
NotRunning,
/// Anything else, in plain words. /// Anything else, in plain words.
Failed(String), Failed(String),
} }
/// What a person is told when nothing is running and the work needs the
/// books held open (INVARIANT 7).
pub const START_WANDERBOOKS: &str = "Start Wanderbooks first: nothing has the books open. Open the Wanderbooks app, or, on a computer with no screen, run `wanderbooks serve` and leave it running.";
impl std::fmt::Display for HoldError { impl std::fmt::Display for HoldError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
HoldError::ClosedByOwner => write!(f, "the owner closed the books"), HoldError::ClosedByOwner => write!(f, "the owner closed the books"),
HoldError::NotRunning => f.write_str(START_WANDERBOOKS),
HoldError::Failed(why) => f.write_str(why), HoldError::Failed(why) => f.write_str(why),
} }
} }
@@ -220,31 +239,44 @@ impl Opener {
Ok(()) Ok(())
} }
/// Start counting failures over (a holder that waited a while after /// Take a lease: on a host, on the app's server, or (`serve` alone) on
/// giving up tries again); what it has held is kept (INVARIANT 5). /// a host started for it (INVARIANTS 1-7).
pub fn forget_failures(&mut self) {
self.failures = 0;
}
/// Take a lease, starting a host if none answers (INVARIANTS 1-4).
pub async fn hold(&mut self) -> Result<Lease, HoldError> { pub async fn hold(&mut self) -> Result<Lease, HoldError> {
let mut started: Option<Instant> = None; let mut started: Option<Instant> = None;
let mut said_waiting = false;
loop { loop {
// The app has the books: its own server serves them, and no // The app has the books: its own server serves them, and no
// host is started beside it (INVARIANT 6). // host is started beside it (INVARIANT 6).
if crate::app_server::the_apps_server_runs(&self.run) { if !host_lock_held(&self.run) && server_lock_held(&self.run) {
if self.kind == Kind::Serve { match admin_answers(&self.run) {
return Err(HoldError::Failed( Ok(true) => {
"Wanderbooks (the app) has these books open: close it first, or use it" if self.kind == Kind::Serve {
.into(), 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,
});
}
Ok(false) => {
// Opening its companies, or finishing its last
// backup: wait for it, and say so once.
if !std::mem::replace(&mut said_waiting, true) && self.kind != Kind::Bridge
{
eprintln!(
"Wanderbooks is still opening (or closing) the books: waiting for it…"
);
}
tokio::time::sleep(Duration::from_millis(100)).await;
continue;
}
Err(why) => return Err(HoldError::Failed(why)),
} }
self.has_held = true;
return Ok(Lease {
id: 0,
link: None,
told_ready: false,
});
} }
wait_for_restart(&self.run).await; wait_for_restart(&self.run).await;
let endpoint = ledger_mcp::ipc::Endpoint::new(&self.run, lease::LEASE_SOCKET) let endpoint = ledger_mcp::ipc::Endpoint::new(&self.run, lease::LEASE_SOCKET)
@@ -280,6 +312,11 @@ impl Opener {
// for it rather than start another. // for it rather than start another.
let held = host_lock_held(&self.run); let held = host_lock_held(&self.run);
match started { match started {
// Nothing runs, and only `serve` starts a host
// (INVARIANT 7).
None if !held && self.kind != Kind::Serve => {
return Err(HoldError::NotRunning);
}
// A start that fails (a spawn error) is a // A start that fails (a spawn error) is a
// failure like any other (INVARIANT 3). // failure like any other (INVARIANT 3).
None if !held => match self.start().await { None if !held => match self.start().await {
@@ -420,6 +457,20 @@ pub fn host_lock_held(run: &Path) -> bool {
} }
} }
/// Whether the admin socket answers: the books server is up and ready
/// (it binds its sockets only once every company has been tried). A
/// socket of another account is an error.
pub fn admin_answers(run: &Path) -> Result<bool, String> {
let endpoint = ledger_mcp::ipc::Endpoint::new(run, ledger_mcp::local::ADMIN_SOCKET)
.map_err(|e| format!("can't reach the books server: {e}"))?;
match ledger_mcp::ipc::connect_std(&endpoint) {
Ok(stream) if ledger_mcp::ipc::peer_is_us(&stream) => Ok(true),
Ok(_) => Err("the books server's socket belongs to another account: not used".into()),
Err(e) if no_host(&e) => Ok(false),
Err(e) => Err(format!("can't reach the books server: {}", e.kind())),
}
}
/// Wait while a restart holds run/update.lock (INVARIANT 1). /// Wait while a restart holds run/update.lock (INVARIANT 1).
async fn wait_for_restart(run: &Path) { async fn wait_for_restart(run: &Path) {
// Looked at, not waited on in a thread: a holder that gives up while // Looked at, not waited on in a thread: a holder that gives up while