test(cli): the detached-host tests follow the new shape: only serve starts a host

Plan P15 unit A5. Nothing but `wanderbooks serve` starts a host, so the tests
that had a bridge or a command start one now have `serve` hold the books (a
`serve` the harness keeps: Home::keep_host), or run a server of their own
(the commands), or are retired. Every test of the three files plan section 6
names, and what became of it:

open_while_held.rs (44 tests)
 KEPT, still true for serve (28): closing_the_books_ends_every_lease_and_the_bridge_stays_closed,
  closing_during_a_burst_of_posts_through_the_bridge_loses_nothing,
  a_killed_host_is_replaced_by_its_holders,
  holders_back_off_and_give_up_on_a_host_that_keeps_failing,
  the_lease_socket_takes_only_the_owners_intents, a_restart_is_not_a_close,
  another_apps_appimage_is_never_run_as_the_host,
  the_host_outlives_the_app_scope_that_started_it,
  the_bridge_serves_a_client_without_initialize,
  the_bridge_recovers_when_the_server_dies_under_it,
  a_message_too_large_is_refused_and_the_session_goes_on,
  malformed_and_boundary_input_never_ends_the_session,
  the_host_starts_without_a_scope_when_systemd_run_fails,
  a_scrubbed_app_scope_doesnt_take_the_host_with_it,
  doctor_doesnt_hang_on_a_frozen_host, doctor_doesnt_hang_on_a_frozen_server,
  serve_hears_ctrl_c_while_it_waits_to_try_again,
  every_malformed_message_is_answered, books_that_didnt_open_refuse_plainly,
  close_and_list_dont_hang_on_frozen_processes,
  the_books_command_takes_its_flags_and_asks_before_adopting,
  adopted_books_old_copies_are_put_aside_from_the_command_line,
  the_token_commands_and_the_bridge (the bridges there are held by serve
  through Agent::start), an_agent_sends_and_saves_files_with_the_commands_it_is_given,
  a_backup_is_restored_from_the_command_line,
  books_are_backed_up_now_from_the_command_line,
  connect_makes_anew_a_token_whose_file_is_gone_and_says_when_an_agent_refuses,
  token_check_says_where_the_token_file_stands_and_an_unreadable_one_is_said
  (these commands now run a server of their own with nothing running).
 MOVED, rewritten for the new shape (15):
  a_command_opens_the_books_and_they_close_after_the_last_holder ->
   a_command_leaves_nothing_running_and_serve_closes_after_its_last_holder;
  openers_share_one_host_and_one_server ->
   serve_and_the_bridges_share_one_host_and_one_server (two serves at once
   are the race now);
  the_bridge_opens_closed_books_and_holds_them_for_the_session ->
   the_bridge_reaches_the_books_serve_holds_and_holds_them_for_the_session;
  the_host_starts_clean_from_a_hostile_bridge ->
   the_host_serve_starts_is_clean_from_a_hostile_serve;
  the_bridge_answers_initialize_itself_during_a_slow_start,
  the_bridge_gives_up_on_books_that_never_open, a_call_cancelled_at_once_is_never_made,
  a_signalled_bridge_goes_at_once, books_made_mid_session_and_bad_requests
   (a slow `serve` holds the host; the bridge starts after it holds the root);
  books_commands_hold_the_books_while_they_run (serve holds, the commands lease);
  a_command_ends_at_its_deadline_during_a_restart (`token list`: `books list`
   with nothing running reads the folder and waits for nothing);
  a_bridge_started_without_stderr_keeps_its_descriptors_apart,
  the_commands_given_run_as_the_agents_own_token,
  an_agent_is_connected_and_reaches_the_books_by_what_it_was_given
   (Home::keep_host);
  doctor_says_whether_the_books_are_open_and_what_holds_them (new closed words).
 RETIRED (1): the_viewers_hold_new_books_and_close_the_books. Its viewer
  lease (hold_for_viewer) and "Close the books" (close_books) no longer
  exist: the app is the host. Covered by ledger-gui serving.rs
  (a_tab_opening_asks_the_server_to_open_that_company, a_tab_closing_asks_the_server_to_close_that_company,
  closing_the_window_stops_the_server_and_waits_for_it), owner_menu.rs (no
  "Close the books" item), and the replacement
  the_viewers_new_books_are_made_by_the_server (new_books through a server).
 Behaviours retired inside the moved tests, and what covers them: a command
  or a bridge starting a host and holding it for the close delay does not
  exist (app_server.rs: a_command_with_the_app_running_goes_to_its_server_and_leaves_it_running,
  with_nothing_running_a_command_runs_its_own_server_or_says_to_start_wanderbooks,
  the_bridge_says_the_app_isnt_running_then_works_once_it_is,
  a_command_leaves_nothing_running_and_serve_closes_after_its_last_holder);
  the close delay itself is kept for serve's host (same test).

update.rs (16 tests)
 KEPT (6): an_update_replaces_the_program_keeps_the_old_one_and_rollback_brings_it_back,
  update_is_atomic, failed_update_rolls_back, unsigned_update_refused,
  package_managed_install_refuses_update, rollback_refuses_after_a_book_consented_to_a_newer_format,
  an_update_never_replaces_another_apps_appimage (the `update` command and
  the AppImage guard: no host involved).
 MOVED (9): bridge_survives_update, update_waits_for_a_running_call,
  a_replaced_appimage_restarts_the_books, the_host_stages_a_daily_update_and_the_next_start_applies_it,
  a_daily_update_that_is_not_ours_is_not_staged,
  update_installs_the_copy_the_host_staged_without_downloading_again,
  a_staged_update_that_was_tampered_with_is_dropped_not_applied,
  books_start_says_an_update_waits, the_owner_accepts_a_staged_update_in_the_app:
  the host they describe is serve's (restart onto a replaced file,
  update.lock, the daily look, the staged copy applied before a host
  starts), so the harness's Agent::start has a `serve` hold the books
  (Home::keep_host); the bridge's tool calls carry the request_key every
  write needs since D-88. RETIRED (0).

translocation.rs (1 test)
 KEPT: translocated_app_refuses_to_connect. The refusal stays: an agent's
 pointer file records this program's path, which a quarantined download
 loses when the app closes, whatever starts the books.

app_server.rs: no test retired. Changed: the_bridge_says_the_app_isnt_running_then_works_once_it_is
(no marker; the words now name `wanderbooks serve`), a refusal touches
nothing (the retired marker). New: a_mark_an_earlier_build_left_is_ignored_and_removed,
a_terminal_ctrl_c_reaches_the_window_and_never_the_server (fails without the
server's own process group: checked by removing it),
a_command_with_the_app_running_goes_to_its_server_and_leaves_it_running,
with_nothing_running_a_command_runs_its_own_server_or_says_to_start_wanderbooks,
a_command_waits_in_words_for_a_server_that_is_still_opening.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 11:34:19 -07:00
1 parent d81f6d5c83
commit e9a520138d
3 files changed
+380 -81

No files matched your search

+204 -11
View File
@@ -148,25 +148,212 @@ fn a_mark_an_earlier_build_left_is_ignored_and_removed() {
/// 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).
/// input alone (app_server.rs INVARIANT 3). The window here is a process
/// of its own in a group of its own, that ignores the signal as a window
/// that handles Ctrl+C does; the group is sent SIGINT, as a terminal does.
#[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");
fn a_terminal_ctrl_c_reaches_the_window_and_never_the_server() {
let home = Home::new("app-ctrl-c");
let run = home.run();
let mut window = {
use std::os::unix::process::CommandExt;
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())
.env("WB_APP_IGNORE_SIGINT", "1")
.process_group(0)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap()
};
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::<i32>().ok();
}
if line == READY {
break;
}
}
let mut window = Reap(window);
let server_pid = server_pid.expect("the window gave the server's pid");
let window_group = window.0.id() as i32;
// SAFETY: getpgid only reads a process-group id.
let (its, ours) = unsafe { (libc::getpgid(server_pid), libc::getpgrp()) };
assert_ne!(its, window_group, "the server is in the window's group");
assert_ne!(its, ours);
// The terminal's Ctrl+C: SIGINT to the window's whole group.
// SAFETY: the group of a process this test started and leads.
assert_eq!(unsafe { libc::killpg(window_group, libc::SIGINT) }, 0);
// The window is still there, and so is the server, with its books
// open and answering: nothing closed them.
std::thread::sleep(Duration::from_millis(1500));
assert!(window.0.try_wait().unwrap().is_none(), "the window died");
assert!(server_lock_held(&run), "the server closed on Ctrl+C");
assert!(matches!(home.admin(Request::List), Response::Books(_)));
// The window going is what closes it.
window.0.kill().unwrap();
window.0.wait().unwrap();
until("the server let go of the books", || !server_lock_held(&run));
}
/// A command run (as a subprocess, as a person's terminal does) while the
/// app's server runs goes to it: no host, no second server, and what it
/// says is the app's (WB-app-5). It never closes the app's books.
#[test]
fn a_command_with_the_app_running_goes_to_its_server_and_leaves_it_running() {
let home = Home::new("app-command");
let run = home.run();
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.
home.create(BOOK, "USD");
let command = |args: &[&str]| {
let mut c = Command::new(exe());
c.args(args)
.arg("--root")
.arg(home.root())
.stdin(Stdio::null());
clean_env(&mut c, home.dir.path());
c.output().unwrap()
};
let said = |o: &std::process::Output| String::from_utf8_lossy(&o.stdout).into_owned();
let listed = command(&["books", "list"]);
assert!(listed.status.success(), "{listed:?}");
assert!(
said(&listed).contains(&format!("{BOOK} open")),
"{listed:?}"
);
// A company is opened and closed in the app's server by the command.
let closed = command(&["books", "close", BOOK]);
assert!(closed.status.success(), "{closed:?}");
assert!(!open_in_server(&home, BOOK));
let opened = command(&["books", "open", BOOK]);
assert!(opened.status.success(), "{opened:?}");
assert!(open_in_server(&home, BOOK));
// `close` and `doctor` say whose the books are, in words.
let said_close = command(&["close"]);
assert!(
said(&said_close).contains("Wanderbooks (the app) has these books open"),
"{said_close:?}"
);
let doctor = command(&["doctor"]);
assert!(
said(&doctor).contains("Wanderbooks (the app) has them")
&& said(&doctor).contains(&format!("{BOOK} open")),
"{doctor:?}"
);
// Through all of it: no host, one server, still the app's.
assert!(!host_lock_held(&run));
assert!(!run.join("lease.sock").exists());
assert_eq!(server.exited(), None);
assert!(server_lock_held(&run));
assert_eq!(server.stop(Duration::from_secs(60)), Stopped::Closed);
}
/// With nothing running, a command that manages the books' files runs a
/// server of its own and leaves nothing behind; one that needs an open
/// company says to start Wanderbooks (WB-app-5).
#[test]
fn with_nothing_running_a_command_runs_its_own_server_or_says_to_start_wanderbooks() {
let home = Home::new("app-own");
let run = home.run();
let command = |args: &[&str]| {
let mut c = Command::new(exe());
c.args(args)
.arg("--root")
.arg(home.root())
.stdin(Stdio::null());
clean_env(&mut c, home.dir.path());
c.output().unwrap()
};
let created = command(&["books", "create", BOOK]);
assert!(created.status.success(), "{created:?}");
assert!(!server_lock_held(&run), "the command's server was left");
assert!(!host_lock_held(&run));
// The folder is read for a list: nothing is open.
let listed = command(&["books", "list"]);
assert!(
String::from_utf8_lossy(&listed.stdout)
.contains(&format!("{BOOK} not open: Wanderbooks isn't running")),
"{listed:?}"
);
// Work on a company opens it in the command's own server, then closes.
let token = command(&["token", "create", "--book", BOOK]);
assert!(token.status.success(), "{token:?}");
let backed = command(&["books", "back-up", BOOK]);
assert!(
backed.status.success() || String::from_utf8_lossy(&backed.stderr).contains("backup"),
"{backed:?}"
);
assert!(!server_lock_held(&run), "the command's server was left");
// Opening a company means nothing with no server: said in words.
let open = command(&["books", "open", BOOK]);
assert_eq!(open.status.code(), Some(1), "{open:?}");
let err = String::from_utf8_lossy(&open.stderr);
assert!(
err.contains("Start Wanderbooks first") && err.contains("wanderbooks serve"),
"{err}"
);
assert!(!server_lock_held(&run));
}
/// A command arriving while a server holds the books and has no admin
/// socket yet (the app opening large companies, or finishing a backup)
/// waits, says so in words, and then says plainly that it is still
/// opening: it neither fails with a connection error nor starts a second
/// server beside it (WB-app-5). Here the server is stood in for by its
/// lock.
#[test]
fn a_command_waits_in_words_for_a_server_that_is_still_opening() {
let home = Home::new("app-opening");
let run = home.run();
let lock = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(run.join("server.lock"))
.unwrap();
lock.lock().unwrap();
let mut c = Command::new(exe());
c.args(["token", "list", "--root"])
.arg(home.root())
.args(["--test-knobs", "open_wait=1500"])
.stdin(Stdio::null());
clean_env(&mut c, home.dir.path());
let started = Instant::now();
let out = c.output().unwrap();
assert_eq!(out.status.code(), Some(1), "{out:?}");
let (said, err) = (
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr),
);
assert!(
err.contains("Wanderbooks is still opening (or closing) the books: waiting for it"),
"{said} {err}"
);
assert!(
err.contains("didn't open in time") && err.contains("try again in a moment"),
"{err}"
);
assert!(!err.contains("can't reach"), "a connection error: {err}");
assert!(started.elapsed() < Duration::from_secs(10));
// No server of its own was started beside the one holding the lock.
assert!(!host_lock_held(&run));
drop(lock);
}
#[test]
fn opening_and_closing_a_company_drives_the_servers_book() {
let home = Home::new("app-tabs");
@@ -242,6 +429,12 @@ fn a_window_that_is_about_to_die() {
return;
};
let home = std::path::PathBuf::from(home);
#[cfg(unix)]
if std::env::var_os("WB_APP_IGNORE_SIGINT").is_some() {
// A window that survives its terminal's Ctrl+C (it handles it).
// SAFETY: setting a signal's disposition to ignore.
unsafe { libc::signal(libc::SIGINT, libc::SIG_IGN) };
}
let root = ledger_store::root::default_root(&home);
let dir = home.clone();
let server = AppServer::start_in(exe(), Some(&root), &[], move |c: &mut Command| {
+143 -70
View File
@@ -28,6 +28,11 @@ const KNOBS: &str =
struct Home {
dir: tempfile::TempDir,
exe: PathBuf,
/// The `wanderbooks serve` that holds this home's books for the
/// agents of the test ([`Home::keep_host`]): since P15 only `serve`
/// starts a host, so an agent's bridge finds it running or finds
/// nothing.
serving: std::sync::Mutex<Option<Running>>,
}
/// Wait until a program just copied can be run. A child another test
@@ -70,6 +75,16 @@ impl Home {
Self {
dir,
exe: PathBuf::from(env!("CARGO_BIN_EXE_wanderbooks")),
serving: std::sync::Mutex::new(None),
}
}
/// Run `wanderbooks serve` for this home and keep it running until the
/// home goes: the one thing that starts a host (WB-app-5). Once only.
fn keep_host(&self) {
let mut serving = self.serving.lock().unwrap();
if serving.is_none() {
*serving = Some(serve(self));
}
}
@@ -315,6 +330,7 @@ struct Agent {
impl Agent {
fn start(home: &Home, book: &str) -> Self {
home.keep_host();
let mut c = home.cmd("mcp");
c.args(["--book", book]);
let mut a = Self::from(c);
@@ -474,6 +490,21 @@ fn post_one(a: &mut Agent, n: u64) -> Result<u64, String> {
Ok(id)
}
/// A `serve` whose server is slow to open (the knobs' `server_delay`),
/// waited for only until its host holds the root: a bridge started then is
/// held by it and waits for the books, as a bridge once did for a host it
/// started itself (P15: only `serve` starts a host).
fn slow_serve(home: &Home, knobs: &str) -> Running {
let mut c = home.cmd("serve");
c.args(["--test-knobs", knobs]);
let r = Running::start(c);
assert!(
wait_for(20, || ledger_host::opener::host_lock_held(&home.run_dir())),
"the host never started"
);
r
}
fn serve(home: &Home) -> Running {
let r = Running::start(home.cmd("serve"));
// The first time, it says how to let go.
@@ -481,49 +512,73 @@ fn serve(home: &Home) -> Running {
r
}
/// P15 (WB-app-5): a command with nothing running runs a server of its own
/// and leaves nothing behind: no host, no server, no socket. The host `serve`
/// holds still closes `close_after` after its last holder lets go, whoever
/// that is.
#[test]
fn a_command_opens_the_books_and_they_close_after_the_last_holder() {
fn a_command_leaves_nothing_running_and_serve_closes_after_its_last_holder() {
let home = Home::new("last");
assert!(home.host().is_none());
home.create("acme");
// The command let go; the books stay open for the close delay, then
// close.
assert!(home.host().is_some(), "closed at once");
assert!(home.wait_closed(10), "never closed");
// The commands (a create, a token) ran a server of their own and let go
// of it: nothing of the root is left.
assert!(home.host().is_none(), "a command started a host");
assert!(home.pids("server").is_empty(), "a server was left running");
for sock in ["lease.sock", "mcp.sock", "admin.sock"] {
assert!(!home.run_dir().join(sock).exists(), "{sock} left behind");
}
// A lease arriving within the delay cancels the close.
home.create("beta");
std::thread::sleep(Duration::from_millis(200));
let host = home.host().unwrap();
home.create("gamma");
std::thread::sleep(Duration::from_millis(1000));
assert_eq!(
home.host(),
Some(host),
"closed though a lease came in time"
assert!(!ledger_host::opener::server_lock_held(&home.run_dir()));
// An agent session with nothing running starts no host either.
let mut a = Agent::from({
let mut c = home.cmd("mcp");
c.args(["--book", "acme"]);
c
});
let init = a.initialize();
assert!(
init["error"]["message"]
.as_str()
.is_some_and(|m| m.starts_with("Wanderbooks isn't running")),
"{init}"
);
assert!(home.wait_closed(10));
// An agent session killed outright: closed after the delay, too.
let mut a = Agent::start(&home, "acme");
a.initialize();
a.call("books.start", json!({})).unwrap();
a.run.child.kill().unwrap();
a.run.child.wait().unwrap();
std::thread::sleep(Duration::from_millis(300));
assert!(home.host().is_some(), "closed before the delay");
assert!(home.wait_closed(10), "never closed after the bridge died");
assert!(home.host().is_none(), "a bridge started a host");
drop(a);
// A holder that is killed: closed after the delay, not before.
let mut held = serve(&home);
let leases = home.lease_line("{\"proto\":1,\"leases\":null}\n");
assert!(leases.contains("\"serve\""), "{leases}");
assert!(leases.contains(&held.child.id().to_string()), "{leases}");
// A command while serve holds the books shares its host: a lease that
// comes in time cancels nothing, and no second host starts.
home.create("beta");
assert_eq!(home.pids("host").len(), 1, "one host");
held.child.kill().unwrap();
held.child.wait().unwrap();
std::thread::sleep(Duration::from_millis(300));
assert!(home.host().is_some(), "closed before the delay");
assert!(home.wait_closed(10), "never closed after the holder died");
// The last holder is an agent's bridge: serve lets go (Ctrl-C), the
// host stays for the bridge past the close delay, and closes after the
// bridge is killed, not before.
let mut held = serve(&home);
let mut bridge = Running::start({
let mut c = home.cmd("mcp");
c.args(["--book", "acme"]);
c
});
assert!(wait_for(30, || home
.lease_line("{\"proto\":1,\"leases\":null}\n")
.contains("\"bridge\"")));
held.signal(libc::SIGINT);
assert!(held.wait(10).is_some_and(|s| s.success()));
std::thread::sleep(Duration::from_millis(3500));
assert!(home.host().is_some(), "closed under a bridge that holds");
bridge.child.kill().unwrap();
bridge.child.wait().unwrap();
std::thread::sleep(Duration::from_millis(300));
assert!(home.host().is_some(), "closed before the delay");
assert!(home.wait_closed(10), "never closed after the bridge died");
// Ctrl-C at the terminal: serve lets go, and the books close.
let mut held = serve(&home);
held.signal(libc::SIGINT);
@@ -535,13 +590,21 @@ fn a_command_opens_the_books_and_they_close_after_the_last_holder() {
}
#[test]
fn openers_share_one_host_and_one_server() {
fn serve_and_the_bridges_share_one_host_and_one_server() {
let home = Home::new("share");
home.create("acme");
assert!(home.wait_closed(10));
// All at once, from closed.
let mut holders = vec![
// Two `serve`s at once, from closed (the only programs that start a
// host): one host, one server, and both hold it.
let held = vec![
Running::start(home.cmd("serve")),
Running::start(home.cmd("serve")),
];
for h in &held {
h.expect("The books are open", 30);
}
// Two bridges and a command, all at once, on the host they started.
let holders = vec![
Running::start({
let mut c = home.cmd("mcp");
c.args(["--book", "acme"]);
@@ -558,7 +621,6 @@ fn openers_share_one_host_and_one_server() {
c.arg("list").stdin(Stdio::null());
move || c.output().unwrap()
});
holders[0].expect("The books are open", 30);
let out = list.join().unwrap();
assert!(
String::from_utf8_lossy(&out.stdout).contains("acme open"),
@@ -576,15 +638,17 @@ fn openers_share_one_host_and_one_server() {
== 2),
"the bridges' leases"
);
holders.clear();
drop(holders);
drop(held);
assert!(home.wait_closed(15));
}
#[test]
fn the_bridge_opens_closed_books_and_holds_them_for_the_session() {
fn the_bridge_reaches_the_books_serve_holds_and_holds_them_for_the_session() {
let home = Home::new("bridge");
home.create("acme");
assert!(home.wait_closed(10));
// Held by `serve` (Agent::start): the bridge starts no host itself.
let mut a = Agent::start(&home, "acme");
let init = a.initialize();
// Ready in time: the server's own answer, its connect text.
@@ -605,7 +669,7 @@ fn the_bridge_opens_closed_books_and_holds_them_for_the_session() {
assert!(a.call("books.get_entry", json!({"entry_id": 999})).is_err());
let unknown = a.request("no/such/method", json!({}), 20);
assert!(unknown.get("error").is_some(), "{unknown}");
// Held while the session lasts, even past the close delay.
// Held (by serve, and by the bridge's own lease) past the close delay.
std::thread::sleep(Duration::from_millis(1500));
assert!(home.host().is_some());
// The bridge never uses TCP (no_local_agent_tcp), and TCP is off.
@@ -615,7 +679,8 @@ fn the_bridge_opens_closed_books_and_holds_them_for_the_session() {
assert!(tcp_sockets(pid).is_empty(), "pid {pid} has TCP sockets");
}
assert!(a.end().is_some_and(|s| s.success()));
assert!(home.wait_closed(10));
// The session's end leaves the host to `serve`, which still holds.
assert!(home.host().is_some(), "serve's host went with a session");
// Unknown books: a plain error, no folder named.
let mut a = Agent::start(&home, "nobody");
a.initialize();
@@ -656,6 +721,10 @@ fn the_bridge_answers_initialize_itself_during_a_slow_start() {
let home = Home::new("cold");
home.create("acme");
assert!(home.wait_closed(10));
let _slow = slow_serve(
&home,
"close_after=1500,backoff=50,server_delay=3000,init_wait=300,queue_wait=30000",
);
let mut c = home.cmd("mcp");
c.args([
"--book",
@@ -725,6 +794,10 @@ fn the_bridge_gives_up_on_books_that_never_open() {
let home = Home::new("never");
home.create("acme");
assert!(home.wait_closed(10));
let _slow = slow_serve(
&home,
"close_after=800,backoff=50,server_delay=20000,init_wait=200,queue_wait=1000",
);
let mut c = home.cmd("mcp");
c.args([
"--book",
@@ -833,17 +906,16 @@ fn closing_during_a_burst_of_posts_through_the_bridge_loses_nothing() {
}
#[test]
fn the_host_starts_clean_from_a_hostile_bridge() {
fn the_host_serve_starts_is_clean_from_a_hostile_serve() {
let home = Home::new("clean");
home.create("acme");
assert!(home.wait_closed(10));
// A pipe the bridge inherits; the host must not.
// A pipe `serve` inherits; the host it starts must not (start.rs).
let (read_end, write_end) = std::io::pipe().unwrap();
use std::os::fd::AsRawFd;
let leaked = write_end.as_raw_fd();
let mut c = home.cmd("mcp");
c.args(["--book", "acme"])
.env("XDG_DATA_HOME", "/tmp/wb-evil-data")
let mut c = home.cmd("serve");
c.env("XDG_DATA_HOME", "/tmp/wb-evil-data")
.env("LD_PRELOAD", "/nonexistent/wb-evil.so")
.env("WB_EVIL", "1")
.env("XDG_RUNTIME_DIR", "/tmp")
@@ -861,9 +933,8 @@ fn the_host_starts_clean_from_a_hostile_bridge() {
});
}
}
let mut a = Agent::from(c);
a.initialize();
a.call("books.start", json!({})).unwrap();
let held = Running::start(c);
held.expect("The books are open", 30);
let host = home.host().expect("a host");
let environ = std::fs::read(format!("/proc/{host}/environ")).unwrap();
let vars: Vec<String> = environ
@@ -915,7 +986,7 @@ fn the_host_starts_clean_from_a_hostile_bridge() {
let after = stat.rsplit_once(") ").unwrap().1.to_string();
after.split_whitespace().nth(3).unwrap().to_string()
};
assert_ne!(session(host), session(a.run.child.id()));
assert_ne!(session(host), session(held.child.id()));
assert_eq!(
session(host),
host.to_string(),
@@ -1129,6 +1200,9 @@ fn books_commands_hold_the_books_while_they_run() {
String::from_utf8_lossy(&out.stdout).contains("No books yet"),
"{out:?}"
);
// Held open by `serve`, so what the commands make is open (a command
// with nothing running makes it and lets go: WB-app-5).
home.keep_host();
home.create("acme");
let out = home.books(&["create", "acme"]);
assert_eq!(out.status.code(), Some(1));
@@ -1363,6 +1437,10 @@ fn a_call_cancelled_at_once_is_never_made() {
let home = Home::new("cancel");
home.create("acme");
assert!(home.wait_closed(10));
let _slow = slow_serve(
&home,
"close_after=1500,backoff=50,server_delay=1500,init_wait=200,queue_wait=30000",
);
let mut c = home.cmd("mcp");
c.args([
"--book",
@@ -1411,7 +1489,11 @@ fn doctor_says_whether_the_books_are_open_and_what_holds_them() {
assert!(home.wait_closed(10));
let text = |o: std::process::Output| String::from_utf8_lossy(&o.stdout).into_owned();
let closed = text(home.cmd("doctor").output().unwrap());
assert!(closed.contains("The books are closed."), "{closed}");
assert!(
closed.contains("The books are closed: Wanderbooks isn't running.")
&& closed.contains("wanderbooks serve"),
"{closed}"
);
assert!(closed.contains("same_user (advisory)"), "{closed}");
let _held = serve(&home);
let open = text(home.cmd("doctor").output().unwrap());
@@ -1434,6 +1516,10 @@ fn a_signalled_bridge_goes_at_once() {
let home = Home::new("sigbridge");
home.create("acme");
assert!(home.wait_closed(10));
let _slow = slow_serve(
&home,
"close_after=1500,backoff=50,server_delay=20000,init_wait=200,queue_wait=30000",
);
let mut c = home.cmd("mcp");
c.args([
"--book",
@@ -1661,7 +1747,7 @@ fn a_command_ends_at_its_deadline_during_a_restart() {
lock.lock().unwrap();
let started = Instant::now();
let out = home
.cmd("books")
.cmd("token")
.args(["list", "--test-knobs", "open_wait=1000,close_after=2500"])
.stdin(Stdio::null())
.output()
@@ -1872,6 +1958,10 @@ fn books_made_mid_session_and_bad_requests() {
let home2 = Home::new("dupid");
home2.create("acme");
assert!(home2.wait_closed(10));
let _slow = slow_serve(
&home2,
"close_after=2500,backoff=50,server_delay=2000,init_wait=200,queue_wait=30000",
);
let mut c = home2.cmd("mcp");
c.args([
"--book",
@@ -2107,6 +2197,7 @@ fn a_bridge_started_without_stderr_keeps_its_descriptors_apart() {
use std::os::unix::process::CommandExt;
let home = Home::new("nostderr");
home.create("acme");
home.keep_host();
let mut c = home.cmd("mcp");
c.args(["--book", "acme"]);
// SAFETY: close is async-signal-safe.
@@ -2412,6 +2503,7 @@ fn the_commands_given_run_as_the_agents_own_token() {
.output()
.unwrap();
assert!(out.status.success(), "{out:?}");
home.keep_host();
let mut c = home.cmd("mcp");
c.args(["--book", "acme", "--token", "bookkeeper"]);
let mut a = Agent::from(c);
@@ -2711,6 +2803,7 @@ fn an_agent_is_connected_and_reaches_the_books_by_what_it_was_given() {
assert!(!said.contains("wb_"), "a token's text was shown");
// The command it was given reaches the books (with the token kept).
let given: Vec<&str> = add.split(" -- ").nth(1).unwrap().split(' ').collect();
home.keep_host();
let mut c = Command::new(given[0]);
c.args(&given[1..])
.env_clear()
@@ -2808,28 +2901,20 @@ fn books_are_backed_up_now_from_the_command_line() {
}
/// The viewer's owner (ledger-cli's `ViewerOwner`, over these ledger-host
/// functions): its hold is a lease of kind app; new books are made by the
/// server; "Close the books" ends every lease, the viewer's hold with it.
/// (A `serve` holds the books first: run in this test's process, a hold
/// that had to start the host would start this test's own program.)
/// functions): new books are made by the server that runs (here a `serve`
/// host's; under the app, the app's). The viewer's hold and "Close the
/// books" are gone: the app is the host (WB-app-5).
#[test]
fn the_viewers_hold_new_books_and_close_the_books() {
use ledger_host::commands::{Common, close_books, hold_for_viewer, new_books};
fn the_viewers_new_books_are_made_by_the_server() {
use ledger_host::commands::{Common, new_books};
let home = Home::new("viewer-owner");
home.create("acme");
let serving = serve(&home);
let _serving = serve(&home);
let common = Common {
root: Some(home.root()),
knobs: ledger_host::knobs::Knobs::parse(KNOBS).unwrap(),
..Default::default()
};
let hold = hold_for_viewer(&common, Some("acme".into()));
assert!(
wait_for(20, || home
.lease_line("{\"proto\":1,\"leases\":null}\n")
.contains("\"app\"")),
"the viewer's lease never showed"
);
assert_eq!(
new_books(&common, "beta", "USD").unwrap(),
"Made new books \"beta\" (USD)."
@@ -2844,18 +2929,6 @@ fn the_viewers_hold_new_books_and_close_the_books() {
String::from_utf8_lossy(&out.stdout).contains("beta open"),
"{out:?}"
);
let said = close_books(&common).unwrap();
assert!(said.starts_with("The books are closing"), "{said}");
// The viewer's hold lets go, for good (closed by the owner).
let (tx, rx) = mpsc::channel();
std::thread::spawn(move || {
let _ = tx.send(hold.join().is_ok());
});
assert_eq!(rx.recv_timeout(Duration::from_secs(30)), Ok(true));
serving.expect("closed", 30);
assert!(home.wait_closed(30));
// Closed: said so.
assert_eq!(close_books(&common).unwrap(), "The books are closed.");
}
#[test]
+33
View File
@@ -83,6 +83,9 @@ struct Home {
/// from an image's mount, and `APPIMAGE` names this other file, the
/// one an update replaces.
image: Option<PathBuf>,
/// The `wanderbooks serve` that holds the books for the test's agents
/// ([`Home::keep_host`]): since P15 only `serve` starts a host.
serving: std::sync::Mutex<Option<std::process::Child>>,
}
impl Home {
@@ -106,6 +109,7 @@ impl Home {
dir,
exe,
image: None,
serving: std::sync::Mutex::new(None),
};
home.runnable();
home
@@ -147,6 +151,32 @@ impl Home {
}
}
/// Hold the books with a `wanderbooks serve` (started again when the
/// last one has ended, as a `close` ends it): the one program that
/// starts a host (WB-app-5). It starts, as a host does, applying a
/// staged update first, and the bridges of the test then lease it.
fn keep_host(&self) {
let mut serving = self.serving.lock().unwrap();
if let Some(child) = serving.as_mut()
&& child.try_wait().unwrap().is_none()
{
return;
}
let child = self
.cmd("serve")
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.unwrap();
*serving = Some(child);
let sock = self.root().join("run/mcp.sock");
assert!(
wait_for(60, || sock.exists()),
"the books never opened under serve"
);
}
/// The environment of the pretend AppImage, if this is one.
fn image_env(&self, c: &mut Command) {
if let Some(image) = &self.image {
@@ -618,6 +648,7 @@ struct Agent {
impl Agent {
fn start(home: &Home, book: &str) -> Self {
home.keep_host();
let mut c = home.cmd("mcp");
c.args(["--book", book]);
let mut child = c
@@ -651,6 +682,8 @@ impl Agent {
}
fn send(&mut self, message: Value) {
// A tool call carries the request key every write needs (D-88).
let message = common::with_request_key(&message.to_string());
let stdin = self.child.stdin.as_mut().unwrap();
writeln!(stdin, "{message}").unwrap();
stdin.flush().unwrap();