Merge branch 't3/wanderbooks-app-hosted-bridge': nothing on the desktop starts a detached host (P15 A5)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
commit
610e41d1d1
34 files changed
+2967
-527
No files matched your search
@@ -41,11 +41,19 @@
|
||||
//! request, waiting for the server to be ready first; a close that
|
||||
//! says its last backup was not whole is returned as a notice, never
|
||||
//! as a plain success.
|
||||
//! 7. Starting writes `run/app-hosted`, a file with nothing in it: the
|
||||
//! root is this app's from then on, and the agents' bridge says
|
||||
//! "Wanderbooks isn't running" for it, instead of starting a host
|
||||
//! (bridge.rs INVARIANT 12). The marker is never removed: a root the
|
||||
//! app has served is the app's for good.
|
||||
//! 7. Nothing marks a root as the app's. What holds a root is read from
|
||||
//! what runs: no host holds `run/host.lock`, a server holds
|
||||
//! `run/server.lock`, and the server says what started it and
|
||||
//! whether it is closing (`run/server.info`, ledger-mcp local.rs
|
||||
//! INVARIANT 16; [`crate::opener::what_holds`]). Only a server the
|
||||
//! app started, not closing, with its admin socket answering, is the
|
||||
//! app's ([`the_apps_server_runs`]). An earlier build wrote 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
|
||||
//! stopped, never neither ([`AppHost`]): one that is alive and not
|
||||
//! yet ready is waited for, not given up on; a start that fails, or
|
||||
@@ -70,11 +78,25 @@
|
||||
//! request `wanderbooks token revoke` makes, and its copy in the
|
||||
//! token file goes with it ([`AppHost::revoke_token`]). Neither ever
|
||||
//! holds a token's text.
|
||||
//! 13. A command's own server ([`AppServer::start_for_command`]) is the
|
||||
//! same server, started as `--started-by command`, and clean: the
|
||||
//! host's environment only (start.rs `clean_environment`), the root
|
||||
//! as an absolute path, `/` as its folder (the root's `run/` on
|
||||
//! Windows), and every server closes the descriptors above 2 at its
|
||||
//! start whoever started it, so one that outlives its command holds
|
||||
//! none of the invoker's pipes. The app's own child keeps its
|
||||
//! environment: it is the window's child, closes with the window and
|
||||
//! needs the person's session (ssh agent, git configuration) for its
|
||||
//! backups. A command's server that does not get ready because
|
||||
//! another program holds the books (one that started after the
|
||||
//! command's look) has lost: [`AppServer::wait_ready_unless_beaten`]
|
||||
//! says so, and the command stops it and joins what runs.
|
||||
//! ```
|
||||
|
||||
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 ledger_mcp::admin::{self, CloseOutcome, OpenOutcome, Request, Response};
|
||||
pub use ledger_mcp::local::StartedBy;
|
||||
use ledger_store::root::Root;
|
||||
use std::io::BufRead;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -82,9 +104,10 @@ use std::process::{Command, Stdio};
|
||||
use std::sync::{Arc, Condvar, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// The file in `run/` that says the root is the desktop app's
|
||||
/// (INVARIANT 7).
|
||||
pub const APP_MARKER: &str = "app-hosted";
|
||||
/// The file an earlier build left in `run/` to say the root was the
|
||||
/// desktop app's. Nothing reads it any more (INVARIANT 7); it is removed
|
||||
/// 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
|
||||
/// every company it was told to, and a large one rebuilding a drifted
|
||||
@@ -96,6 +119,19 @@ pub const READY_WAIT: Duration = Duration::from_secs(300);
|
||||
/// and running calls finish first.
|
||||
pub const STOP_WAIT: Duration = Duration::from_secs(90);
|
||||
|
||||
/// How long another program holding the books, while this server has not
|
||||
/// taken them, is seen before this one is taken to have lost the race.
|
||||
const BEATEN_AFTER: Duration = Duration::from_millis(300);
|
||||
|
||||
/// What [`AppServer::wait_ready_unless_beaten`] came to.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Waited {
|
||||
/// The server is ready.
|
||||
Ready,
|
||||
/// Another program took the books first.
|
||||
Beaten,
|
||||
}
|
||||
|
||||
/// What a refused start says (INVARIANT 1).
|
||||
pub const ANOTHER_HAS_THEM: &str = "Another program has these books open: another Wanderbooks window, `wanderbooks serve`, or a books server that is still finishing its last backup. Close it (`wanderbooks close` closes the books) or wait a moment, then start Wanderbooks again.";
|
||||
|
||||
@@ -131,6 +167,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.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Stopped {
|
||||
@@ -173,16 +253,11 @@ pub struct AppServer {
|
||||
pid: u32,
|
||||
}
|
||||
|
||||
/// Whether the root whose `run/` folder this is belongs to the desktop
|
||||
/// app (INVARIANT 7).
|
||||
pub fn app_hosted(run: &Path) -> bool {
|
||||
run.join(APP_MARKER).is_file()
|
||||
}
|
||||
|
||||
/// Whether a books server runs for the app now: the root is the app's,
|
||||
/// no host holds it, and a server does.
|
||||
/// Whether a server runs for the app (or any program that is not a host)
|
||||
/// now: no host holds the root, a server does, and its admin socket
|
||||
/// answers (INVARIANT 7).
|
||||
pub fn the_apps_server_runs(run: &Path) -> bool {
|
||||
app_hosted(run) && !host_lock_held(run) && server_lock_held(run)
|
||||
crate::opener::what_holds(run) == Ok(crate::opener::Holder::App)
|
||||
}
|
||||
|
||||
impl AppServer {
|
||||
@@ -194,6 +269,38 @@ impl AppServer {
|
||||
Self::start_in(&children_executable(), root, open, |_| {})
|
||||
}
|
||||
|
||||
/// The server of a command that does its own work with nothing else
|
||||
/// running (commands.rs `reach`): the same server, started clean as a
|
||||
/// host starts it (INVARIANT 13), saying it is a command's.
|
||||
pub fn start_for_command(
|
||||
root: Option<&Path>,
|
||||
open: &[String],
|
||||
knobs: &crate::knobs::Knobs,
|
||||
) -> Result<Self, String> {
|
||||
let d = crate::knobs::Knobs::default();
|
||||
Self::start_as(
|
||||
&children_executable(),
|
||||
root,
|
||||
open,
|
||||
StartedBy::Command,
|
||||
|command| {
|
||||
// The timings a test shortened, as the host passes them on.
|
||||
for (flag, now, default) in [
|
||||
("--backup-quiet", knobs.backup_quiet, d.backup_quiet),
|
||||
("--drill-first", knobs.drill_first, d.drill_first),
|
||||
("--start-delay", knobs.server_delay, d.server_delay),
|
||||
] {
|
||||
if now != default {
|
||||
command.arg(flag).arg(now.as_millis().to_string());
|
||||
}
|
||||
}
|
||||
if knobs.timer_hold {
|
||||
command.arg("--timer-hold");
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// [`AppServer::start`] from the program `exe`, `configure` having the
|
||||
/// last word on its command (tests give it an environment of its own).
|
||||
pub fn start_in(
|
||||
@@ -201,18 +308,27 @@ impl AppServer {
|
||||
root: Option<&Path>,
|
||||
open: &[String],
|
||||
configure: impl FnOnce(&mut Command),
|
||||
) -> Result<Self, String> {
|
||||
Self::start_as(exe, root, open, StartedBy::App, configure)
|
||||
}
|
||||
|
||||
/// [`AppServer::start_in`] for a server started `by` the app or a
|
||||
/// command, which it says of itself (`--started-by`, INVARIANT 13).
|
||||
/// A command's is started clean (INVARIANT 13).
|
||||
pub fn start_as(
|
||||
exe: &Path,
|
||||
root: Option<&Path>,
|
||||
open: &[String],
|
||||
by: StartedBy,
|
||||
configure: impl FnOnce(&mut Command),
|
||||
) -> Result<Self, String> {
|
||||
let found = Root::find(root).map_err(|e| e.to_string())?;
|
||||
let run = found.run_dir().map_err(|e| e.to_string())?;
|
||||
if host_lock_held(&run) || server_lock_held(&run) {
|
||||
return Err(ANOTHER_HAS_THEM.into());
|
||||
}
|
||||
private_options()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.write(true)
|
||||
.open(run.join(APP_MARKER))
|
||||
.map_err(|e| format!("can't mark these books as the app's: {}", e.kind()))?;
|
||||
// The mark an earlier build left means nothing now (INVARIANT 7).
|
||||
let _ = std::fs::remove_file(run.join(RETIRED_MARKER));
|
||||
let log = open_log(&run.join(SERVER_LOG))
|
||||
.map_err(|e| format!("can't open the server's log: {}", e.kind()))?;
|
||||
let mut command = Command::new(exe);
|
||||
@@ -220,27 +336,33 @@ impl AppServer {
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
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");
|
||||
if let Some(root) = root {
|
||||
command.arg("--started-by").arg(by.flag());
|
||||
if by == StartedBy::Command {
|
||||
// Nothing of the invoker's reaches a server that may outlive
|
||||
// the command (INVARIANT 13): the host's environment, and a
|
||||
// folder of its own to stand in (the root's absolute path
|
||||
// goes on, as the host's does). Its descriptors are closed by
|
||||
// the server itself at its start.
|
||||
command.arg("--root").arg(found.path());
|
||||
crate::start::clean_environment(&mut command)?;
|
||||
#[cfg(unix)]
|
||||
command.current_dir("/");
|
||||
#[cfg(windows)]
|
||||
command.current_dir(&run);
|
||||
} else if let Some(root) = root {
|
||||
command.arg("--root").arg(root);
|
||||
}
|
||||
command.arg("--open").arg(open_argument(open));
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
// CREATE_NO_WINDOW: a console of its own that nobody sees, so
|
||||
// the window's own Ctrl+C never reaches it (it closes by its
|
||||
// input alone).
|
||||
command.creation_flags(0x0800_0000);
|
||||
}
|
||||
configure(&mut command);
|
||||
let mut child = command
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(log)
|
||||
.spawn()
|
||||
.map_err(|e| format!("can't start the books server: {e}"))?;
|
||||
let mut child = spawn_child(&mut command, &log)?;
|
||||
let stdin = child.stdin.take();
|
||||
let stdout = child.stdout.take();
|
||||
let pid = child.id();
|
||||
@@ -340,6 +462,50 @@ impl AppServer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Wait for the server to be ready, up to `within`, but not for
|
||||
/// another program that took the books first: if, while this server
|
||||
/// is not ready, a host or another server holds them (a command racing
|
||||
/// the app's start, or `serve`'s), this one has lost the race and the
|
||||
/// caller is to join what runs (commands.rs `reach`). Seen for as long
|
||||
/// as [`BEATEN_AFTER`], so the moment between this server taking the
|
||||
/// lock and saying so is not taken for losing.
|
||||
pub fn wait_ready_unless_beaten(&self, within: Duration) -> Result<Waited, String> {
|
||||
let deadline = Instant::now() + within;
|
||||
let mut beaten_since: Option<Instant> = None;
|
||||
loop {
|
||||
let slice = Duration::from_millis(50).min(
|
||||
deadline
|
||||
.checked_duration_since(Instant::now())
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
match self.wait_ready(slice) {
|
||||
Ok(()) => return Ok(Waited::Ready),
|
||||
Err(why) if self.exited().is_some() => return Err(why),
|
||||
Err(why) => {
|
||||
if Instant::now() >= deadline {
|
||||
return Err(why);
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.another_holds() {
|
||||
let since = *beaten_since.get_or_insert_with(Instant::now);
|
||||
if since.elapsed() >= BEATEN_AFTER {
|
||||
return Ok(Waited::Beaten);
|
||||
}
|
||||
} else {
|
||||
beaten_since = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a host, or a server that is not this one, holds the books.
|
||||
fn another_holds(&self) -> bool {
|
||||
host_lock_held(&self.run)
|
||||
|| (server_lock_held(&self.run)
|
||||
&& ledger_mcp::local::read_server_info(&self.run)
|
||||
.is_none_or(|info| info.pid != self.pid))
|
||||
}
|
||||
|
||||
/// Whether the server has said it is ready (and is still there).
|
||||
pub fn is_ready(&self) -> bool {
|
||||
matches!(&*self.shared.phase(), Phase::Ready)
|
||||
@@ -360,6 +526,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
|
||||
/// (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.
|
||||
@@ -979,12 +1152,10 @@ mod tests {
|
||||
}
|
||||
|
||||
#[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();
|
||||
assert!(!app_hosted(dir.path()));
|
||||
std::fs::write(dir.path().join(APP_MARKER), b"").unwrap();
|
||||
assert!(app_hosted(dir.path()));
|
||||
// No server runs there: not the app's server.
|
||||
// A mark an earlier build left is nothing: no server runs there.
|
||||
std::fs::write(dir.path().join(RETIRED_MARKER), b"").unwrap();
|
||||
assert!(!the_apps_server_runs(dir.path()));
|
||||
}
|
||||
}
|
||||
@@ -54,19 +54,32 @@
|
||||
//! refusal, which says how the human makes one; but when the token
|
||||
//! file is there and couldn't be read, with that instead: the token
|
||||
//! is not said to be missing. The token is never written to the agent or to stderr.
|
||||
//! 12. For a root the desktop app serves (app_server.rs INVARIANT 7) with
|
||||
//! no host running, the bridge is a thin line to the app's server
|
||||
//! and nothing more: it holds no lease and starts no host (a
|
||||
//! detached host is not how the desktop runs). With the app not
|
||||
//! running, every call is answered "Wanderbooks isn't running:
|
||||
//! start Wanderbooks and open BOOK." (`not_running_words`); with
|
||||
//! the app running but BOOK not open in it, "Company BOOK isn't
|
||||
//! open: open it in Wanderbooks." (`not_open_words`, for the
|
||||
//! server's `closed` refusal at the door). Neither is final: the
|
||||
//! call after the app starts, or the company opens, goes through,
|
||||
//! in a session that was already running. A root no app has served,
|
||||
//! and any root a host holds, behave as in 1 to 11 (`wanderbooks
|
||||
//! serve`, the headless host).
|
||||
//! 12. With no host running (every root but a headless `wanderbooks
|
||||
//! serve`'s), the bridge is a thin line to whatever server runs and
|
||||
//! nothing more: it holds no lease and starts no host (a detached
|
||||
//! host is not how the desktop runs; only `wanderbooks serve` starts
|
||||
//! one). With nothing running, every call is answered "Wanderbooks
|
||||
//! isn't running: start Wanderbooks and open BOOK (on a computer
|
||||
//! with no screen, run `wanderbooks serve`), then try again."
|
||||
//! (`not_running_words`); with a server holding the books and no
|
||||
//! socket yet (the app opening large companies), "Wanderbooks is
|
||||
//! still opening its companies…: try again shortly."
|
||||
//! (`opening_words`); with the app running but BOOK not open in it, "Company BOOK isn't open: open it in Wanderbooks."
|
||||
//! (`not_open_words`, for the server's `closed` refusal at the
|
||||
//! door). Neither is final: the call after the app starts, or the
|
||||
//! company opens, goes through, in a session that was already
|
||||
//! running. A root 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;
|
||||
//! and when the app takes its place (its lease would be one with no
|
||||
//! host behind it, which never ends: `Lease::is_hostless`) it
|
||||
//! becomes the line above too, and says the same words when the app
|
||||
//! is closed. What holds the books is read before a session is
|
||||
//! tried (opener.rs INVARIANT 6a): a command's server, for the
|
||||
//! length of its work, is told as "A wanderbooks command has the
|
||||
//! books for a moment" (`command_words`), and a server that is
|
||||
//! closing as the opening words, not as the app.
|
||||
//! ```
|
||||
|
||||
use crate::knobs::{FLAG, Knobs};
|
||||
@@ -100,7 +113,27 @@ 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).
|
||||
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 a server holds the books and is not
|
||||
/// answering yet: the app opening its companies (a large one takes a
|
||||
/// while), or finishing a last backup (INVARIANT 12).
|
||||
fn opening_words(book: &str) -> String {
|
||||
format!(
|
||||
"Wanderbooks is still opening its companies, or finishing the last backup of the last session: {book} can be reached in a moment. Try again shortly."
|
||||
)
|
||||
}
|
||||
|
||||
/// What the agent is told when a command of the owner's has the books for
|
||||
/// a moment (a server of its own, for the length of its work): the app is
|
||||
/// not running, and it is not that either.
|
||||
fn command_words(book: &str) -> String {
|
||||
format!(
|
||||
"A wanderbooks command has the books for a moment: {book} can be reached in a moment. Try again shortly."
|
||||
)
|
||||
}
|
||||
|
||||
/// What the agent is told when the app runs but the company is not open
|
||||
@@ -191,8 +224,9 @@ struct Bridge {
|
||||
/// The server's channel, for its owner check (INVARIANT 9).
|
||||
endpoint: ledger_mcp::ipc::Endpoint,
|
||||
/// Whether this is the line to the desktop app's server, with no host
|
||||
/// and no lease (INVARIANT 12).
|
||||
app: bool,
|
||||
/// and no lease (INVARIANT 12). It turns true when a host the bridge
|
||||
/// 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.
|
||||
@@ -923,7 +957,7 @@ impl Bridge {
|
||||
Some(Link::Failed(why)) => return self.answer(&id, error(&id, why)),
|
||||
// The desktop app can't be reached, or the company isn't open
|
||||
// in it: said now, not "opening" (INVARIANT 12).
|
||||
Some(Link::Refused(why)) if self.app => return self.answer(&id, error(&id, why)),
|
||||
Some(Link::Refused(why)) if self.is_app() => return self.answer(&id, error(&id, why)),
|
||||
_ => None,
|
||||
};
|
||||
let result = result.unwrap_or_else(|| {
|
||||
@@ -955,7 +989,7 @@ impl Bridge {
|
||||
let run_dir = opener.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 _ = self.token_file.set((account, run_dir));
|
||||
let _ = self.token_file.set((account, run_dir.clone()));
|
||||
let mut epoch = 0u64;
|
||||
loop {
|
||||
let mut lease = match opener.hold().await {
|
||||
@@ -965,11 +999,31 @@ impl Bridge {
|
||||
self.link.send_replace(Link::Closed);
|
||||
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)) => {
|
||||
self.link.send_replace(Link::Failed(why));
|
||||
return;
|
||||
}
|
||||
};
|
||||
// The host this bridge held went, and the app started in its
|
||||
// place: its lease is on a server with no host, which never
|
||||
// ends, so it would never see the app go. The bridge becomes
|
||||
// the line to whatever runs, as a fresh one is, and says the
|
||||
// same words when the app closes (INVARIANT 12).
|
||||
if lease.is_hostless() {
|
||||
drop(lease);
|
||||
self.app.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
self.link.send_replace(Link::Opening);
|
||||
return self.keep_in_app(run_dir).await;
|
||||
}
|
||||
// Until this lease ends: whenever the server is ready and no
|
||||
// session is up, open one. The lease is always heard, even
|
||||
// while a session is being opened or a try waits (INVARIANT 1).
|
||||
@@ -1051,11 +1105,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
|
||||
/// `closed` refusal, the bridge's own (INVARIANT 12); else the
|
||||
/// server's.
|
||||
fn refusal_words(&self, closed: bool, body: &str) -> String {
|
||||
if self.app && closed {
|
||||
if self.is_app() && closed {
|
||||
not_open_words(&self.book)
|
||||
} else {
|
||||
body.trim().chars().take(500).collect()
|
||||
@@ -1071,18 +1130,38 @@ impl Bridge {
|
||||
async fn keep_in_app(self: Arc<Self>, run_dir: PathBuf) {
|
||||
let root = run_dir.parent().unwrap_or(&run_dir).to_path_buf();
|
||||
let account = crate::tokens::Account::new(&root, &self.book, &self.token_name);
|
||||
let _ = self.token_file.set((account, run_dir));
|
||||
let _ = self.token_file.set((account, run_dir.clone()));
|
||||
let mut epoch = 0u64;
|
||||
loop {
|
||||
if matches!(&*self.link.borrow(), Link::Opening) {
|
||||
match self.socket_is_ours() {
|
||||
// What holds the books is read before a session is tried
|
||||
// (opener.rs INVARIANT 6a): a command's server, or one
|
||||
// that is closing, is not the app, whatever its socket
|
||||
// answers.
|
||||
let held =
|
||||
crate::opener::what_holds(&run_dir).unwrap_or(crate::opener::Holder::Nothing);
|
||||
let owner_check = match held {
|
||||
crate::opener::Holder::Command | crate::opener::Holder::Closing => {
|
||||
Err(Owner::Unreachable)
|
||||
}
|
||||
_ => self.socket_is_ours(),
|
||||
};
|
||||
match owner_check {
|
||||
Err(Owner::Other(why)) => {
|
||||
self.link.send_replace(Link::Failed(why));
|
||||
return;
|
||||
}
|
||||
Err(Owner::Unreachable) => {
|
||||
self.link
|
||||
.send_replace(Link::Refused(not_running_words(&self.book)));
|
||||
// A server holding the books with no socket yet is
|
||||
// opening (or finishing), not absent.
|
||||
let words = match held {
|
||||
crate::opener::Holder::Command => command_words(&self.book),
|
||||
_ if crate::opener::server_lock_held(&run_dir) => {
|
||||
opening_words(&self.book)
|
||||
}
|
||||
_ => not_running_words(&self.book),
|
||||
};
|
||||
self.link.send_replace(Link::Refused(words));
|
||||
}
|
||||
Ok(()) => match self.open_session(epoch + 1).await {
|
||||
Ok(up) => {
|
||||
@@ -1382,11 +1461,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
|
||||
/// root whose `run/` folder this is (INVARIANT 12): an app has served the
|
||||
/// root, and no host holds it.
|
||||
/// Whether the bridge is the line to the app's server for the root whose
|
||||
/// `run/` folder this is (INVARIANT 12): no host holds it. The server
|
||||
/// answering, or not running at all, is looked at call by call.
|
||||
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) {
|
||||
@@ -1470,7 +1549,7 @@ pub fn run(
|
||||
next_id: std::sync::atomic::AtomicU64::new(1),
|
||||
pending: Mutex::new(std::collections::HashMap::new()),
|
||||
endpoint,
|
||||
app,
|
||||
app: std::sync::atomic::AtomicBool::new(app),
|
||||
});
|
||||
let keeper = if app {
|
||||
tokio::spawn(bridge.clone().keep_in_app(run_dir))
|
||||
@@ -1834,7 +1913,7 @@ mod against_a_server {
|
||||
next_id: std::sync::atomic::AtomicU64::new(1),
|
||||
pending: Mutex::new(std::collections::HashMap::new()),
|
||||
endpoint,
|
||||
app,
|
||||
app: std::sync::atomic::AtomicBool::new(app),
|
||||
});
|
||||
(bridge, rx)
|
||||
}
|
||||
@@ -2605,7 +2684,7 @@ mod against_a_server {
|
||||
fn the_two_messages_are_plain_and_name_the_company() {
|
||||
assert_eq!(
|
||||
not_running_words("acme"),
|
||||
"Wanderbooks isn't running: start Wanderbooks and open acme."
|
||||
"Wanderbooks isn't running: start Wanderbooks and open acme (on a computer with no screen, run `wanderbooks serve`), then try again."
|
||||
);
|
||||
assert_eq!(
|
||||
not_open_words("acme"),
|
||||
@@ -2614,12 +2693,13 @@ mod against_a_server {
|
||||
}
|
||||
|
||||
#[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();
|
||||
assert!(!serves_the_app(dir.path()), "no app has served it");
|
||||
std::fs::write(dir.path().join(crate::app_server::APP_MARKER), b"").unwrap();
|
||||
assert!(serves_the_app(dir.path()), "no host holds it");
|
||||
// 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()));
|
||||
// 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();
|
||||
lock.lock().unwrap();
|
||||
assert!(!serves_the_app(dir.path()));
|
||||
@@ -2670,6 +2750,26 @@ mod against_a_server {
|
||||
keeper.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn with_a_server_still_opening_the_answer_says_so_and_not_that_nothing_runs() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
// A server holds the books and has bound no socket yet.
|
||||
let lock = std::fs::File::create(dir.path().join(ledger_mcp::local::SERVER_LOCK)).unwrap();
|
||||
lock.lock().unwrap();
|
||||
let (b, mut rx) = app_bridge_at(&dir.path().join("mcp.sock"), knobs(3000, 3000));
|
||||
let keeper = tokio::spawn(b.clone().keep_in_app(dir.path().to_path_buf()));
|
||||
let call: Value = serde_json::from_str(CALL).unwrap();
|
||||
b.waiting(&json!(7));
|
||||
b.clone().request_on(call, json!(7), "tools/call").await;
|
||||
let said = told(&mut rx, 3000).await.unwrap()["error"]["message"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
assert_eq!(said, opening_words("acme"));
|
||||
assert!(!said.contains("isn't running"));
|
||||
keeper.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn with_the_app_running_a_company_that_is_not_open_is_said_in_words() {
|
||||
let server = Server::start();
|
||||
|
||||
+475
-186
@@ -7,17 +7,35 @@
|
||||
//!
|
||||
//! ```text
|
||||
//! GOAL: from a terminal, or the viewer's menu, the owner holds the books
|
||||
//! open, closes them, makes, adopts, backs up and restores books and
|
||||
//! connects agents, without ever naming or touching the books'
|
||||
//! private folder.
|
||||
//! open (`serve`), closes them, makes, adopts, backs up and restores
|
||||
//! books and connects agents, without ever naming or touching the
|
||||
//! books' private folder, and without any command leaving a host or a
|
||||
//! server running that nothing manages.
|
||||
//! SOURCE: plan/served.md 3.9 (a terminal running `wanderbooks serve`, and
|
||||
//! any command that needs the server, holds a lease; "Close the
|
||||
//! books" ends every lease), 3.1 (the CLI talks to admin.sock and
|
||||
//! never reads the books), 5.5 (adopt; preview and confirmation at
|
||||
//! the terminal).
|
||||
//! any command that needs a host, holds a lease), 3.1 (the CLI
|
||||
//! talks to admin.sock and never reads the books), 5.5 (adopt;
|
||||
//! preview and confirmation at the terminal);
|
||||
//! plan/p15-app-and-relay.md 3.1 (the app is the host; only `serve`
|
||||
//! keeps a detached host), WB-app-5.
|
||||
//! INVARIANTS:
|
||||
//! 1. A command that needs the server holds a lease while it runs, and
|
||||
//! lets go when it ends.
|
||||
//! 1. A command that needs the server finds what holds the books: a
|
||||
//! host (it holds a lease while it runs, and lets go when it ends),
|
||||
//! the app's server (no lease: the app decides when the books
|
||||
//! close), or nothing. With nothing running it starts no host: a
|
||||
//! command that only reads, or manages the books' files, runs a
|
||||
//! server of its own for the length of the work and closes it
|
||||
//! (waiting for its last backup); one that needs a company held open
|
||||
//! says "Start Wanderbooks first" ([`Direct`], [`reach`]; WB-app-5).
|
||||
//! A server of its own takes the locks the app's server takes, so
|
||||
//! two programs never hold one set of books. What it finds is read,
|
||||
//! not guessed (opener.rs INVARIANT 6a): only a server the app
|
||||
//! started is the app's; another command's server, or a closing one,
|
||||
//! is waited for, in words, inside one `open_wait`. A program that
|
||||
//! takes the books between its look and its own server's start (the
|
||||
//! app, `serve`, another command) is joined: its server lets go of
|
||||
//! the start and it looks again. Its own server is started clean (a
|
||||
//! host's environment, `/` for its folder), and closes the invoker's
|
||||
//! descriptors at its start.
|
||||
//! 2. Nothing printed names the data root.
|
||||
//! 3. Adoption and restoring are previewed first and go ahead only on a
|
||||
//! yes at the terminal, or --yes; a vault beside the books must be
|
||||
@@ -31,8 +49,7 @@
|
||||
//! makes the books' agent token only when there is no token file for
|
||||
//! it, replacing the server's (no one could be using it: the bridge
|
||||
//! reads its token from this file).
|
||||
//! 5. The viewer's hold lets go only when the owner closes the books;
|
||||
//! books that stop, or won't open, are tried again.
|
||||
//! 5. (Retired with the viewer's lease: the app is the host.)
|
||||
//! 6. Books waiting for a format upgrade (plan 3.9, D-39): the owner's
|
||||
//! commands that open the books (`serve`, `books`, `token`,
|
||||
//! `connect`) ask for the go-ahead once each time they run, at a
|
||||
@@ -40,12 +57,13 @@
|
||||
//! the foreground: the question, then the owner passphrase, which only
|
||||
//! the server checks); elsewhere they only say so, on stderr. Only a passphrase typed
|
||||
//! at a terminal (or in the viewer) is sent, through the lease
|
||||
//! socket's consent_format_upgrade; declining changes nothing.
|
||||
//! socket's consent_format_upgrade (a host), or as the admin request
|
||||
//! `UpgradeFormat` (no host); declining changes nothing.
|
||||
//! ```
|
||||
|
||||
use crate::knobs::{FLAG, Knobs};
|
||||
use crate::lease::{Ask, HostMsg, Intent, Kind, Reason};
|
||||
use crate::opener::{HoldError, Lease, Opener};
|
||||
use crate::opener::{HoldError, Holder, Lease, Opener};
|
||||
use ledger_mcp::admin::{self, Request, Response};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
@@ -106,12 +124,20 @@ fn exit(code: i32) -> Box<dyn std::error::Error> {
|
||||
|
||||
/// Hold the books and wait until they are open (INVARIANT 1).
|
||||
async fn open(opener: &mut Opener) -> Result<Lease, HoldError> {
|
||||
let deadline = tokio::time::Instant::now() + opener.knobs().open_wait;
|
||||
// One bounded wait for the whole command: the deadline a caller set
|
||||
// (`reach`), else `open_wait` from now. The opener's own waits for
|
||||
// another program's server (WB-app-5) end at it with their own words;
|
||||
// the timeout here is a moment later, for what has none.
|
||||
let deadline = opener
|
||||
.deadline()
|
||||
.unwrap_or_else(|| tokio::time::Instant::now() + opener.knobs().open_wait);
|
||||
opener.wait_until(deadline);
|
||||
let grace = Duration::from_millis(500);
|
||||
let too_long = || -> HoldError {
|
||||
"the books didn't open in time: 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 {
|
||||
let mut lease = tokio::time::timeout_at(deadline, opener.hold())
|
||||
let mut lease = tokio::time::timeout_at(deadline + grace, opener.hold())
|
||||
.await
|
||||
.map_err(|_| too_long())??;
|
||||
loop {
|
||||
@@ -145,6 +171,180 @@ 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, and the sessions are of a running server's.
|
||||
Request::OpenBook { .. } | Request::CloseBook { .. } | Request::Sessions => Direct::No,
|
||||
// Work on one company, which the server opens (so the owner is
|
||||
// told of a format upgrade it waits for, INVARIANT 6).
|
||||
Request::BackUpNow { id, .. }
|
||||
| Request::UpgradeFormat { id, .. }
|
||||
| Request::Extract { id, .. } => Direct::With(vec![id.clone()]),
|
||||
Request::TokenCreate { book, .. }
|
||||
| Request::TokenCheck { book, .. }
|
||||
| Request::TokenRevoke { book, .. } => Direct::With(vec![book.clone()]),
|
||||
// The rest read the list, or make and move files.
|
||||
_ => 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).
|
||||
///
|
||||
/// Whatever is found is joined: a host, the app's server, and, once its
|
||||
/// work is done, a command's server or a closing one is waited for. A
|
||||
/// program that takes the books between the look and the command's own
|
||||
/// server taking them (the app starting, `serve`, another command) is
|
||||
/// joined too: the command's server has not got them, it lets go of its
|
||||
/// start and looks again. One wait covers all of it, `open_wait`, said in
|
||||
/// words (`Opener::hold` says what it waits for).
|
||||
async fn reach(opener: &mut Opener, common: &Common, direct: &Direct) -> Result<Reached, String> {
|
||||
let run_dir = opener.run_dir().to_path_buf();
|
||||
let deadline = tokio::time::Instant::now() + opener.knobs().open_wait;
|
||||
opener.wait_until(deadline);
|
||||
let mut said = false;
|
||||
loop {
|
||||
match open(opener).await {
|
||||
Ok(lease) => {
|
||||
return Ok(Reached {
|
||||
run_dir,
|
||||
lease: Some(lease),
|
||||
own: None,
|
||||
});
|
||||
}
|
||||
Err(HoldError::NotRunning) => {}
|
||||
Err(e) => return Err(hold_words(e)),
|
||||
}
|
||||
let Direct::With(books) = direct else {
|
||||
return Err(crate::opener::START_WANDERBOOKS.to_string());
|
||||
};
|
||||
let (root, books, knobs) = (common.root.clone(), books.clone(), common.knobs);
|
||||
let started = tokio::task::spawn_blocking(move || {
|
||||
let server = match crate::app_server::AppServer::start_for_command(
|
||||
root.as_deref(),
|
||||
&books,
|
||||
&knobs,
|
||||
) {
|
||||
Ok(server) => server,
|
||||
// Another program took the books since the look.
|
||||
Err(why) if why == crate::app_server::ANOTHER_HAS_THEM => {
|
||||
return Ok(None);
|
||||
}
|
||||
Err(why) => return Err(why),
|
||||
};
|
||||
match server.wait_ready_unless_beaten(crate::app_server::READY_WAIT)? {
|
||||
crate::app_server::Waited::Ready => Ok(Some(server)),
|
||||
// Another program took them first: this one's start is let
|
||||
// go of (it has not opened anything), and what runs is
|
||||
// looked at again.
|
||||
crate::app_server::Waited::Beaten => {
|
||||
server.stop(Duration::from_secs(10));
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())??;
|
||||
if let Some(own) = started {
|
||||
return Ok(Reached {
|
||||
run_dir,
|
||||
lease: None,
|
||||
own: Some(std::sync::Arc::new(own)),
|
||||
});
|
||||
}
|
||||
if tokio::time::Instant::now() >= deadline {
|
||||
return Err(format!(
|
||||
"Other programs kept the books for {} s while this command waited: try again in a moment (`wanderbooks doctor` says what has them).",
|
||||
opener.knobs().open_wait.as_secs()
|
||||
));
|
||||
}
|
||||
if !std::mem::replace(&mut said, true) {
|
||||
eprintln!("Another program started the books just now: waiting for it…");
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask the server's admin socket, holding the books open meanwhile.
|
||||
fn with_server(common: &Common, request: Request) -> Result<Response, String> {
|
||||
with_server_in(common, request).map(|(answer, _)| answer)
|
||||
@@ -153,34 +353,37 @@ fn with_server(common: &Common, request: Request) -> Result<Response, String> {
|
||||
/// [`with_server`], with the root's `run/` folder too (where the
|
||||
/// token files live).
|
||||
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()
|
||||
.enable_all()
|
||||
.build()
|
||||
.map_err(|e| e.to_string())?;
|
||||
let outcome = rt.block_on(async {
|
||||
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 {
|
||||
HoldError::ClosedByOwner => {
|
||||
"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 reached = reach(&mut opener, common, &direct).await?;
|
||||
let run_dir = reached.run_dir.clone();
|
||||
// The books are open: asked about a format upgrade first
|
||||
// (INVARIANT 6).
|
||||
// (INVARIANT 6). (A server of the command's own has only the
|
||||
// company the command names open.)
|
||||
if common.ask_upgrades && !ASKED_UPGRADES.swap(true, std::sync::atomic::Ordering::SeqCst) {
|
||||
let run = run_dir.clone();
|
||||
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.
|
||||
let wait = matches!(request, Request::List | Request::TokenList).then_some(LIST_WAIT);
|
||||
let answer =
|
||||
tokio::task::spawn_blocking(move || admin::call_within(&socket, request, wait))
|
||||
.await
|
||||
.map_err(|e| e.to_string())?
|
||||
.map_err(|e| e.to_string());
|
||||
drop(lease);
|
||||
let answer = reached.ask(request, wait).await;
|
||||
reached.release().await;
|
||||
answer.map(|a| (a, run_dir))
|
||||
});
|
||||
// Past its deadline, the command ends: nothing pending holds it.
|
||||
@@ -217,12 +420,29 @@ fn past(deadline: std::time::Instant, now: std::time::Instant) -> bool {
|
||||
now > deadline
|
||||
}
|
||||
|
||||
/// What is said of a server that is not the app's, in the words of its
|
||||
/// own state (`close`, `doctor`): never "the app" for what is not.
|
||||
fn held_words(holder: Holder) -> &'static str {
|
||||
match holder {
|
||||
Holder::Command => {
|
||||
"A wanderbooks command has the books open for a moment: they close when its work is done."
|
||||
}
|
||||
Holder::Closing => "The books are closing: a books server is finishing its last backups.",
|
||||
Holder::Opening => {
|
||||
"Wanderbooks is opening the books (or finishing the last backup of the last session): its server isn't answering yet."
|
||||
}
|
||||
Holder::Host | Holder::App | Holder::Nothing => {
|
||||
"The books are held: `wanderbooks doctor` says by what."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What `doctor` says of books no host holds.
|
||||
fn no_host(server_lock_held: bool) -> &'static str {
|
||||
if server_lock_held {
|
||||
"The books are closing: a books server is finishing its last call."
|
||||
} 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 +547,8 @@ pub fn serve(
|
||||
println!("The books were closed (Close the books).");
|
||||
return Ok(());
|
||||
}
|
||||
Err(HoldError::Failed(why)) => {
|
||||
eprintln!("error: {why}");
|
||||
Err(e @ (HoldError::Failed(_) | HoldError::NotRunning)) => {
|
||||
eprintln!("error: {}", hold_words(e));
|
||||
return Err(exit(1));
|
||||
}
|
||||
};
|
||||
@@ -427,8 +647,18 @@ pub fn close(
|
||||
exit(1)
|
||||
})?;
|
||||
match asked {
|
||||
// No host: what holds the books is read (WB-app-5), so what is
|
||||
// said of it is true.
|
||||
None => {
|
||||
println!("The books are already closed.");
|
||||
match crate::opener::what_holds(&run) {
|
||||
Ok(Holder::App) => println!("{APP_HAS_THEM}."),
|
||||
Ok(Holder::Nothing) => println!("The books are already closed."),
|
||||
Ok(other) => println!("{}", held_words(other)),
|
||||
Err(why) => {
|
||||
eprintln!("error: {why}");
|
||||
return Err(exit(1));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Some(HostMsg::Done { .. }) => {
|
||||
@@ -464,6 +694,54 @@ pub fn close(
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask the host that holds the books (an earlier build's detached host,
|
||||
/// or `wanderbooks serve`'s) to close them, and wait until they are
|
||||
/// closed: what `wanderbooks close` does, for the app, whose person may
|
||||
/// have no command line (the lease protocol to such a host is the same
|
||||
/// as ever). `Ok` says what came of it, in words; `Err` says why not.
|
||||
/// Blocks, at most `CLOSE_WAIT` and a few seconds.
|
||||
pub fn close_the_host(root: Option<&Path>) -> Result<String, String> {
|
||||
let found = ledger_store::root::Root::find(root).map_err(|e| e.to_string())?;
|
||||
let run = found.run_dir().map_err(|e| e.to_string())?;
|
||||
let asked = crate::opener::ask_once_within(&run, Ask::Intent(Intent::Close), HOST_WAIT)?;
|
||||
match asked {
|
||||
None => Ok("No program has the books open now.".into()),
|
||||
Some(HostMsg::Done { .. }) => {
|
||||
let deadline = std::time::Instant::now() + CLOSE_WAIT;
|
||||
loop {
|
||||
let asked = crate::opener::ask_once_within(&run, Ask::Leases, HOST_WAIT);
|
||||
match closing(&asked, || crate::opener::server_lock_held(&run)) {
|
||||
Closing::Closed => return Ok("The other program let go of the books.".into()),
|
||||
Closing::Reopened => {
|
||||
return Err(
|
||||
"something opened the books again as the other program let go".into(),
|
||||
);
|
||||
}
|
||||
Closing::Going => {}
|
||||
}
|
||||
if past(deadline, std::time::Instant::now()) {
|
||||
return Err(
|
||||
"the other program is still closing the books (a request is finishing)"
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
}
|
||||
Some(HostMsg::Refused(why)) => Err(why),
|
||||
Some(other) => Err(format!("the books' host answered oddly: {other:?}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a host holds the books of the root now (an earlier build's, or
|
||||
/// `wanderbooks serve`'s): the one case the app's refused start can offer
|
||||
/// to close for the person ([`close_the_host`]).
|
||||
pub fn a_host_holds(root: Option<&Path>) -> bool {
|
||||
ledger_store::root::Root::find(root)
|
||||
.and_then(|found| found.run_dir())
|
||||
.is_ok_and(|run| crate::opener::host_lock_held(&run))
|
||||
}
|
||||
|
||||
fn books_usage(prog: &str) {
|
||||
eprintln!("usage: {prog} list");
|
||||
eprintln!(" {prog} create ID [--currency CODE]");
|
||||
@@ -558,7 +836,21 @@ pub fn books(
|
||||
// (INVARIANT 6), unless it is the upgrade itself.
|
||||
common.ask_upgrades = !matches!(words.as_slice(), ["upgrade", ..]);
|
||||
let answer = match words.as_slice() {
|
||||
["list"] => with_server(&common, Request::List),
|
||||
["list"] => match listed_while_closed(&common) {
|
||||
Ok(Some(listed)) => {
|
||||
if listed.is_empty() {
|
||||
println!("No books yet: `wanderbooks books create ID` starts some.");
|
||||
}
|
||||
for (id, upgrade) in listed {
|
||||
println!(
|
||||
"{id} not open: Wanderbooks isn't running (start it, or run `wanderbooks serve`, to open it){upgrade}"
|
||||
);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
Ok(None) => with_server(&common, Request::List),
|
||||
Err(why) => Err(why),
|
||||
},
|
||||
["create", new] => with_server(
|
||||
&common,
|
||||
Request::Create {
|
||||
@@ -745,6 +1037,46 @@ pub fn books(
|
||||
}
|
||||
|
||||
/// 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), with what each waits for in words:
|
||||
/// a format upgrade is read from what the journal declares
|
||||
/// (`ledger_store::declared_format`: no lock, nothing written, the chain
|
||||
/// not verified, so it says what the books declare and no more), and a
|
||||
/// journal that can't be read says so and is not skipped. `None` when
|
||||
/// something runs: ask it.
|
||||
fn listed_while_closed(common: &Common) -> Result<Option<Vec<(String, 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()
|
||||
.filter_map(|id| {
|
||||
let waits = match ledger_store::declared_format(&found.book_dir(id)) {
|
||||
Ok(declared) if declared.upgrade().is_some() => {
|
||||
format!("; waiting for a format upgrade (`wanderbooks books upgrade {id}`)")
|
||||
}
|
||||
Ok(_) => String::new(),
|
||||
// A book that vanished since the list is not one of the
|
||||
// books; one that can't be read says why.
|
||||
Err(ledger_store::StoreError::Io(e))
|
||||
if e.kind() == std::io::ErrorKind::NotFound =>
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Err(e) => format!("; its format isn't known: {e}"),
|
||||
};
|
||||
Some((id.to_string(), waits))
|
||||
})
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
|
||||
fn book_line(b: &admin::BookStatus) -> String {
|
||||
if b.closed {
|
||||
return format!(
|
||||
@@ -915,13 +1247,36 @@ fn consent_now(run: &Path, book: &str, passphrase: &str) -> Result<Vec<String>,
|
||||
// Refused: nothing was done (the server says so too).
|
||||
Some(HostMsg::Refused(why)) => Err(format!("not upgraded: {why}")),
|
||||
Some(HostMsg::Uncertain(why)) => Err(why),
|
||||
// Sent, and the host gone without an answer (closed, or killed):
|
||||
// its server may have done it all the same.
|
||||
None => Err(
|
||||
"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"
|
||||
// No host: the app's server, or one of the command's own, takes
|
||||
// it as an admin request (WB-app-2).
|
||||
None => upgrade_by_admin(run, book, passphrase),
|
||||
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(),
|
||||
),
|
||||
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 +1302,16 @@ pub fn upgrade_format(
|
||||
let not_sent = |why: String| format!("not upgraded: {why}");
|
||||
let mut opener =
|
||||
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 {
|
||||
HoldError::ClosedByOwner => {
|
||||
"not upgraded: the books were closed just now (Close the books): nothing was done"
|
||||
.to_string()
|
||||
}
|
||||
HoldError::Failed(why) => not_sent(why),
|
||||
})?;
|
||||
let run = opener.run_dir().to_path_buf();
|
||||
// With nothing running, a server of its own with this company
|
||||
// open does it.
|
||||
let reached = reach(&mut opener, common, &Direct::With(vec![book.clone()]))
|
||||
.await
|
||||
.map_err(not_sent)?;
|
||||
let run = reached.run_dir.clone();
|
||||
let asked = tokio::task::spawn_blocking(move || consent_now(&run, &book, &passphrase))
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
drop(lease);
|
||||
reached.release().await;
|
||||
asked
|
||||
});
|
||||
rt.shutdown_timeout(Duration::from_secs(1));
|
||||
@@ -1057,9 +1410,14 @@ fn upgrade(common: &Common, book: &str) -> Result<(), Box<dyn std::error::Error>
|
||||
Ok(id) => id.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::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:?}")),
|
||||
};
|
||||
let Some(status) = listed.into_iter().find(|b| b.id == book) else {
|
||||
@@ -1129,37 +1487,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
|
||||
/// tabs and its window close them.
|
||||
/// What `wanderbooks close` says while the app has the books open: the
|
||||
/// 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";
|
||||
|
||||
/// "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
|
||||
/// (the viewer's notice; P11a step 4).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -1276,61 +1607,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.
|
||||
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.
|
||||
pub fn backed_up_lines(head_seq: u64, targets: &[admin::BackedUpTarget]) -> Vec<String> {
|
||||
if targets.is_empty() {
|
||||
@@ -2775,6 +3051,52 @@ fn log_tail(run: &Path, name: &str, root: &Path, n: usize) -> Vec<String> {
|
||||
.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
|
||||
/// what the host and the server last said. It names no folder.
|
||||
pub fn doctor(
|
||||
@@ -2824,51 +3146,21 @@ pub fn doctor(
|
||||
}
|
||||
let run = root.run_dir().map_err(|e| e.to_string())?;
|
||||
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) => match crate::opener::what_holds(&run) {
|
||||
Ok(Holder::App) => {
|
||||
println!("The books are open: Wanderbooks (the app) has them.");
|
||||
admin_report(&run);
|
||||
}
|
||||
Ok(Holder::Nothing) => println!("{}", no_host(false)),
|
||||
Ok(other) => println!("{}", held_words(other)),
|
||||
Err(why) => println!("The books server can't be asked: {why}"),
|
||||
},
|
||||
Ok(Some(HostMsg::Leases { ready, leases })) => {
|
||||
if ready {
|
||||
println!("The books are open.");
|
||||
// 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(_) => {}
|
||||
}
|
||||
}
|
||||
admin_report(&run);
|
||||
} else {
|
||||
println!("The books are opening (the books server isn't ready yet).");
|
||||
}
|
||||
@@ -3240,12 +3532,8 @@ fn on_the_socket(
|
||||
Kind::Cli,
|
||||
None,
|
||||
)?;
|
||||
let lease = open(&mut opener).await.map_err(|e| match e {
|
||||
HoldError::ClosedByOwner => {
|
||||
"the books were closed just now (Close the books): nothing was done".to_string()
|
||||
}
|
||||
HoldError::Failed(why) => why,
|
||||
})?;
|
||||
// A call to an open book: with nothing running there is none.
|
||||
let reached = reach(&mut opener, common, &Direct::No).await?;
|
||||
let run_dir = opener.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);
|
||||
@@ -3277,7 +3565,7 @@ fn on_the_socket(
|
||||
.await
|
||||
.map_err(|e| format!("the books server's answer was cut off: {e}"))?
|
||||
.to_vec();
|
||||
drop(lease);
|
||||
reached.release().await;
|
||||
Ok::<_, String>((status, headers, body))
|
||||
});
|
||||
rt.shutdown_timeout(Duration::from_secs(1));
|
||||
@@ -3782,7 +4070,8 @@ mod tests {
|
||||
#[test]
|
||||
fn doctor_tells_closing_from_closed() {
|
||||
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 {
|
||||
|
||||
@@ -94,11 +94,13 @@ pub(crate) fn private_options() -> std::fs::OpenOptions {
|
||||
/// Windows passes no descriptor to a child unless asked to, so there is
|
||||
/// nothing to close (INVARIANT 2).
|
||||
#[cfg(not(unix))]
|
||||
fn close_stray_descriptors() {}
|
||||
pub fn close_stray_descriptors() {}
|
||||
|
||||
/// Close every descriptor above 2 (INVARIANT 2).
|
||||
/// Close every descriptor above 2 (INVARIANT 2). The host does it at its
|
||||
/// start, and so does every books server (`wanderbooks server`), whoever
|
||||
/// started it: it holds none of its starter's pipes or sockets.
|
||||
#[cfg(unix)]
|
||||
fn close_stray_descriptors() {
|
||||
pub fn close_stray_descriptors() {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
// SAFETY: close_range only closes descriptors; nothing is open
|
||||
@@ -765,6 +767,11 @@ impl Host {
|
||||
#[cfg(unix)]
|
||||
command.arg0("wanderbooks");
|
||||
command.arg("server");
|
||||
// Said in its `run/server.info`: this host's, so that one found
|
||||
// with no host is known to be an orphan finishing (opener.rs).
|
||||
command
|
||||
.arg("--started-by")
|
||||
.arg(ledger_mcp::local::StartedBy::Host.flag());
|
||||
if self.explicit_root {
|
||||
command.arg("--root").arg(self.root.path());
|
||||
}
|
||||
|
||||
@@ -36,6 +36,11 @@ pub struct Knobs {
|
||||
/// How long between the host's looks for a newer release (plan
|
||||
/// P11a step 4: a day).
|
||||
pub update_check: Duration,
|
||||
/// A command's own server holds the jobs it runs inside their phases
|
||||
/// while `run/timer-hold` names them (the server's `--timer-hold`;
|
||||
/// tests of what a command holds while it works). Given as
|
||||
/// `timer_hold=1`.
|
||||
pub timer_hold: bool,
|
||||
}
|
||||
|
||||
impl Default for Knobs {
|
||||
@@ -51,6 +56,7 @@ impl Default for Knobs {
|
||||
backup_quiet: Duration::from_secs(30),
|
||||
drill_first: Duration::from_secs(60),
|
||||
update_check: Duration::from_secs(24 * 60 * 60),
|
||||
timer_hold: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -81,6 +87,7 @@ impl Knobs {
|
||||
"backup_quiet" => k.backup_quiet = d,
|
||||
"drill_first" => k.drill_first = d,
|
||||
"update_check" => k.update_check = d,
|
||||
"timer_hold" => k.timer_hold = ms != 0,
|
||||
other => return Err(format!("{FLAG}: there is no knob {other:?}")),
|
||||
}
|
||||
}
|
||||
@@ -108,6 +115,9 @@ impl Knobs {
|
||||
parts.push(format!("{name}={}", now.as_millis()));
|
||||
}
|
||||
}
|
||||
if self.timer_hold {
|
||||
parts.push("timer_hold=1".to_string());
|
||||
}
|
||||
(!parts.is_empty()).then(|| parts.join(","))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
//! The books open while something holds them (plan 3.9, D-21, D-23).
|
||||
//! The books open while something holds them (plan 3.9, D-21, D-23; plan
|
||||
//! P15 3.1, D-77, D-84).
|
||||
//!
|
||||
//! Nothing runs in the background: the first holder (the app, an agent's
|
||||
//! bridge, `wanderbooks serve`, or a command that needs the books) starts
|
||||
//! the **host**, which starts the books server and holds it open while
|
||||
//! any lease on its socket lasts, and closes it 10 s after the last one
|
||||
//! ends. Each part is a mode of the one `wanderbooks` executable:
|
||||
//! [`host::run`] (`wanderbooks host`), [`bridge::run`] (`wanderbooks
|
||||
//! mcp`), and the owner's commands in [`commands`] (`serve`, `close`,
|
||||
//! `books`, `token`, `connect`, `doctor`, `passphrase`, and what the
|
||||
//! viewer's Books menu does). Agents' tokens are kept in files under the data root
|
||||
//! ([`tokens`]).
|
||||
//! On the desktop the app is the host: [`app_server`] starts the books
|
||||
//! server as the window's child and closes it by closing its input.
|
||||
//! Nothing else on the desktop starts a detached host. The headless
|
||||
//! `wanderbooks serve` keeps one, as before: its host starts the books
|
||||
//! server and holds it open while any lease on its socket lasts, and
|
||||
//! closes it 10 s after the last one ends. Each part is a mode of the one
|
||||
//! `wanderbooks` executable: [`host::run`] (`wanderbooks host`),
|
||||
//! [`bridge::run`] (`wanderbooks mcp`, a line to whatever runs, in words
|
||||
//! when nothing does), and the owner's commands in [`commands`] (`serve`,
|
||||
//! `close`, `books`, `token`, `connect`, `doctor`, `passphrase`, and what
|
||||
//! the viewer's Books menu does), which talk to the running app's (or
|
||||
//! host's) server, or with nothing running run a server of their own for
|
||||
//! the length of the work, or say "Start Wanderbooks first". Agents'
|
||||
//! tokens are kept in files under the data root ([`tokens`]).
|
||||
|
||||
pub mod app_server;
|
||||
pub mod bridge;
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
//! Holding the books: how every holder takes its lease (plan 3.9).
|
||||
//!
|
||||
//! ```text
|
||||
//! GOAL: a holder gets its lease on the one host, starting one when none
|
||||
//! answers, even when several holders start at once; across a
|
||||
//! GOAL: a holder gets its lease on the one host (the headless `serve`'s,
|
||||
//! 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
|
||||
//! given up on, plainly, instead of retried forever.
|
||||
//! SOURCE: plan/served.md 3.9 ("One host, even in a race", "Closing":
|
||||
//! backoff 1, 2, 4 … 60 s, at most five tries; "Restarting":
|
||||
//! openers wait on update.lock); tests host_respawns,
|
||||
//! respawn_backs_off.
|
||||
//! openers wait on update.lock); plan/p15-app-and-relay.md 3.1
|
||||
//! (only `serve` keeps a host; the app is the host otherwise),
|
||||
//! WB-app-3, WB-app-5; tests host_respawns, respawn_backs_off.
|
||||
//! INVARIANTS:
|
||||
//! 1. Before each try the holder waits while a restart holds
|
||||
//! run/update.lock.
|
||||
//! 2. No host answering: it starts one (cleanly, start.rs) and keeps
|
||||
//! trying;
|
||||
//! 2. No host answering: `serve` starts one (cleanly, start.rs) and keeps
|
||||
//! trying (7);
|
||||
//! a host that is closing or restarting turns it away and it tries
|
||||
//! again until a host takes the lease.
|
||||
//! 3. A start that brings no lease within START_WAIT (or whose host
|
||||
@@ -28,12 +30,32 @@
|
||||
//! 5. A holder that has held before, turned away because the owner
|
||||
//! closed the books, stays closed (HoldError::ClosedByOwner); a new
|
||||
//! holder waits for a new host.
|
||||
//! 6. A root the desktop app has served (app_server.rs INVARIANT 7)
|
||||
//! with the app's own server running and no host: a command's or
|
||||
//! the viewer's hold is a lease on that server with no host behind
|
||||
//! it (ready at once, never ended: the app decides when the books
|
||||
//! close), no host is started beside it, and `wanderbooks serve`
|
||||
//! is told the app has the books.
|
||||
//! 6. No host answering, a books server holding the books (`run/
|
||||
//! server.lock`), and its admin socket answering: the desktop app's
|
||||
//! own server (P15 3.1). A holder other than `wanderbooks serve`
|
||||
//! takes a lease on it with no host behind it (ready at once, never
|
||||
//! ended: the app decides when the books close), and no host is
|
||||
//! 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.
|
||||
//! 6a. What holds the books is known, not guessed: a server says what
|
||||
//! started it and whether it is closing (`run/server.info`, ledger-mcp
|
||||
//! local.rs INVARIANT 16) and [`what_holds`] reads it. Only a server
|
||||
//! the app started, not closing, is "the app". A server a command
|
||||
//! started, a closing server (the app's, or the orphan of a host
|
||||
//! that was killed), is waited for: the holder says so, in words, and
|
||||
//! goes on once it is gone, for as long as its own wait lasts
|
||||
//! (`open_wait`, 120 s; a bridge waits as long as the session does),
|
||||
//! then says in words what it is still waiting for. A server that
|
||||
//! says nothing (an earlier build's) is taken for the app's, as it
|
||||
//! was before.
|
||||
//! 7. No host, no server: only `wanderbooks serve` starts a host (the
|
||||
//! headless path, plan 3.1). Every other holder is turned away with
|
||||
//! [`HoldError::NotRunning`], and says, in words, to start
|
||||
//! 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;
|
||||
@@ -51,6 +73,9 @@ const START_WAIT: Duration = Duration::from_secs(45);
|
||||
const LOCK_WAIT: Duration = Duration::from_secs(2);
|
||||
/// How long the host has to answer a hello.
|
||||
const ANSWER_WAIT: Duration = Duration::from_secs(10);
|
||||
/// How long `hold` looks again while it waits for a server that is
|
||||
/// closing or a command's (INVARIANT 6a).
|
||||
const WAIT_LOOK: Duration = Duration::from_millis(100);
|
||||
/// Tries after a failure before giving up (INVARIANT 3).
|
||||
pub const MAX_TRIES: u32 = 5;
|
||||
/// How long the books must stay open for earlier failures to be
|
||||
@@ -69,14 +94,22 @@ pub enum HoldError {
|
||||
/// The owner closed the books, and this holder had held them
|
||||
/// (INVARIANT 5).
|
||||
ClosedByOwner,
|
||||
/// Nothing holds the books (no host, no server), and this holder
|
||||
/// starts none (INVARIANT 7).
|
||||
NotRunning,
|
||||
/// Anything else, in plain words.
|
||||
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 {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
HoldError::ClosedByOwner => write!(f, "the owner closed the books"),
|
||||
HoldError::NotRunning => f.write_str(START_WANDERBOOKS),
|
||||
HoldError::Failed(why) => f.write_str(why),
|
||||
}
|
||||
}
|
||||
@@ -109,6 +142,10 @@ pub struct Opener {
|
||||
/// Flags the server this opener starts is started with (P9a):
|
||||
/// `--isolation` and `--http`. Empty for every ordinary holder.
|
||||
server_flags: Vec<String>,
|
||||
/// Until when a wait for another program's server lasts (INVARIANT
|
||||
/// 6a); the caller's own deadline, else `open_wait` from the first
|
||||
/// wait. A bridge has none.
|
||||
deadline: Option<Instant>,
|
||||
}
|
||||
|
||||
/// A held lease: the books stay open while it lives.
|
||||
@@ -129,6 +166,13 @@ struct HostLink {
|
||||
}
|
||||
|
||||
impl Lease {
|
||||
/// Whether this lease is on the app's server with no host behind it
|
||||
/// (INVARIANT 6): it never ends, so a holder that has one follows
|
||||
/// what runs by looking, as a bridge with no host does.
|
||||
pub fn is_hostless(&self) -> bool {
|
||||
self.link.is_none()
|
||||
}
|
||||
|
||||
/// The host's next word: `Ready`, or `Ending` with why; `None` when
|
||||
/// the host is gone without a word.
|
||||
pub async fn next(&mut self) -> Option<HostMsg> {
|
||||
@@ -174,9 +218,21 @@ impl Opener {
|
||||
opened_at: None,
|
||||
has_held: false,
|
||||
server_flags: Vec::new(),
|
||||
deadline: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Wait for another program's server (a command's, or one closing) no
|
||||
/// longer than until `deadline` (INVARIANT 6a).
|
||||
pub fn wait_until(&mut self, deadline: Instant) {
|
||||
self.deadline = Some(deadline);
|
||||
}
|
||||
|
||||
/// The deadline set by [`Opener::wait_until`], if any.
|
||||
pub fn deadline(&self) -> Option<Instant> {
|
||||
self.deadline
|
||||
}
|
||||
|
||||
/// Start the server this opener brings up with these flags (P9a:
|
||||
/// `--isolation`, `--http`). Only `serve` uses it: on the owner's own
|
||||
/// machine it is the one holder, so the host it starts is the server's
|
||||
@@ -220,31 +276,59 @@ impl Opener {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Start counting failures over (a holder that waited a while after
|
||||
/// giving up tries again); what it has held is kept (INVARIANT 5).
|
||||
pub fn forget_failures(&mut self) {
|
||||
self.failures = 0;
|
||||
}
|
||||
|
||||
/// Take a lease, starting a host if none answers (INVARIANTS 1-4).
|
||||
/// Take a lease: on a host, on the app's server, or (`serve` alone) on
|
||||
/// a host started for it (INVARIANTS 1-7).
|
||||
pub async fn hold(&mut self) -> Result<Lease, HoldError> {
|
||||
let mut started: Option<Instant> = None;
|
||||
let mut said_waiting = false;
|
||||
let mut waited_from: Option<Instant> = None;
|
||||
loop {
|
||||
// The app has the books: its own server serves them, and no
|
||||
// host is started beside it (INVARIANT 6).
|
||||
if crate::app_server::the_apps_server_runs(&self.run) {
|
||||
if self.kind == Kind::Serve {
|
||||
return Err(HoldError::Failed(
|
||||
"Wanderbooks (the app) has these books open: close it first, or use it"
|
||||
.into(),
|
||||
));
|
||||
// What holds the books is read, not guessed (INVARIANT 6a).
|
||||
match what_holds(&self.run)? {
|
||||
// The app has the books: its own server serves them, and
|
||||
// no host is started beside it (INVARIANT 6).
|
||||
Holder::App => {
|
||||
if self.kind == Kind::Serve {
|
||||
return Err(HoldError::Failed(
|
||||
"Wanderbooks (the app) has these books open: close it first, or use it"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
self.has_held = true;
|
||||
return Ok(Lease {
|
||||
id: 0,
|
||||
link: None,
|
||||
told_ready: false,
|
||||
});
|
||||
}
|
||||
self.has_held = true;
|
||||
return Ok(Lease {
|
||||
id: 0,
|
||||
link: None,
|
||||
told_ready: false,
|
||||
});
|
||||
// Opening its companies, or finishing its last backup:
|
||||
// wait for it, and say so once.
|
||||
Holder::Opening => {
|
||||
if !std::mem::replace(&mut said_waiting, true) && self.kind != Kind::Bridge {
|
||||
eprintln!(
|
||||
"Wanderbooks is still opening (or closing) the books: waiting for it…"
|
||||
);
|
||||
}
|
||||
tokio::time::sleep(WAIT_LOOK).await;
|
||||
continue;
|
||||
}
|
||||
// A command's server, or one closing: it ends soon, and
|
||||
// the books are free; wait for it, bounded (INVARIANT 6a).
|
||||
held @ (Holder::Command | Holder::Closing) => {
|
||||
let from = *waited_from.get_or_insert_with(Instant::now);
|
||||
if self.kind != Kind::Bridge {
|
||||
let until = self.deadline.unwrap_or_else(|| from + self.knobs.open_wait);
|
||||
if Instant::now() >= until {
|
||||
return Err(HoldError::Failed(held.still_waiting_words()));
|
||||
}
|
||||
}
|
||||
if !std::mem::replace(&mut said_waiting, true) && self.kind != Kind::Bridge {
|
||||
eprintln!("{}", held.waiting_words());
|
||||
}
|
||||
tokio::time::sleep(WAIT_LOOK).await;
|
||||
continue;
|
||||
}
|
||||
Holder::Host | Holder::Nothing => {}
|
||||
}
|
||||
wait_for_restart(&self.run).await;
|
||||
let endpoint = ledger_mcp::ipc::Endpoint::new(&self.run, lease::LEASE_SOCKET)
|
||||
@@ -280,6 +364,11 @@ impl Opener {
|
||||
// for it rather than start another.
|
||||
let held = host_lock_held(&self.run);
|
||||
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
|
||||
// failure like any other (INVARIANT 3).
|
||||
None if !held => match self.start().await {
|
||||
@@ -420,6 +509,94 @@ pub fn host_lock_held(run: &Path) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// What holds the books now, read from the locks, the server's own word
|
||||
/// about itself and its admin socket (INVARIANT 6a).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Holder {
|
||||
/// Nothing: no host, no server.
|
||||
Nothing,
|
||||
/// A host holds `run/host.lock` (`wanderbooks serve`'s, or an earlier
|
||||
/// build's): leases go to it.
|
||||
Host,
|
||||
/// The app's server, not closing, answering: no host behind it.
|
||||
App,
|
||||
/// A server the app started (or an earlier build's, which says
|
||||
/// nothing of itself) that is not answering yet: opening its
|
||||
/// companies, or finishing its last backup.
|
||||
Opening,
|
||||
/// A server a command started, for the length of its work.
|
||||
Command,
|
||||
/// A server that has begun to close (the app's, or the orphan of a
|
||||
/// host that went): finishing its last backups.
|
||||
Closing,
|
||||
}
|
||||
|
||||
impl Holder {
|
||||
/// What is said while waiting for this to finish (INVARIANT 6a).
|
||||
pub fn waiting_words(self) -> &'static str {
|
||||
match self {
|
||||
Holder::Command => {
|
||||
"Another wanderbooks command has the books open for a moment: waiting for it to finish…"
|
||||
}
|
||||
_ => {
|
||||
"Wanderbooks is closing the books (a last backup is being made): waiting for it to finish…"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What is said when the wait ran out (INVARIANT 6a).
|
||||
pub fn still_waiting_words(self) -> String {
|
||||
match self {
|
||||
Holder::Command => "Another wanderbooks command still has the books open after waiting for it: try again in a moment (`wanderbooks doctor` says what has them).".into(),
|
||||
_ => "Wanderbooks is still closing the books after waiting for it (a last backup is still being made): try again in a moment.".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What holds the books of the root whose `run/` folder this is
|
||||
/// (INVARIANT 6a). `Err` in words when the server's socket is another
|
||||
/// account's.
|
||||
pub fn what_holds(run: &Path) -> Result<Holder, String> {
|
||||
use ledger_mcp::local::StartedBy;
|
||||
if host_lock_held(run) {
|
||||
return Ok(Holder::Host);
|
||||
}
|
||||
if !server_lock_held(run) {
|
||||
return Ok(Holder::Nothing);
|
||||
}
|
||||
let info = ledger_mcp::local::read_server_info(run);
|
||||
Ok(match info {
|
||||
Some(i) if i.closing => Holder::Closing,
|
||||
Some(i) if i.by == StartedBy::Command => Holder::Command,
|
||||
// No host holds the books, so a server a host started is the
|
||||
// orphan of one that went: it is closing, as its input ended.
|
||||
Some(i) if i.by == StartedBy::Host => Holder::Closing,
|
||||
// The app's, or one that says nothing (an earlier build's, or a
|
||||
// newer one's, a moment before it writes its word).
|
||||
Some(_) | None => {
|
||||
if admin_answers(run)? {
|
||||
Holder::App
|
||||
} else {
|
||||
Holder::Opening
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the admin socket answers: the books server is up and ready
|
||||
/// (it binds its sockets only once every company has been tried). A
|
||||
/// socket of another account is an error.
|
||||
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).
|
||||
async fn wait_for_restart(run: &Path) {
|
||||
// Looked at, not waited on in a thread: a holder that gives up while
|
||||
@@ -518,6 +695,7 @@ mod tests {
|
||||
opened_at: None,
|
||||
has_held: false,
|
||||
server_flags: Vec::new(),
|
||||
deadline: None,
|
||||
};
|
||||
for _ in 0..MAX_TRIES {
|
||||
o.failed().await.unwrap();
|
||||
|
||||
@@ -258,6 +258,24 @@ fn host_env(
|
||||
env
|
||||
}
|
||||
|
||||
/// Give `command` the environment a host has (INVARIANT 1) and nothing of
|
||||
/// this process's: the books server a command runs for itself is started
|
||||
/// so, as the host's own is, since it may outlive the command that
|
||||
/// started it (commands.rs `reach`).
|
||||
pub(crate) fn clean_environment(command: &mut Command) -> Result<(), String> {
|
||||
let home = ledger_store::root::account_home().map_err(|e| e.to_string())?;
|
||||
command.env_clear();
|
||||
#[cfg(unix)]
|
||||
command.envs(host_env(
|
||||
&home,
|
||||
std::env::var_os("SSH_AUTH_SOCK").as_deref(),
|
||||
this_appimage().as_ref(),
|
||||
));
|
||||
#[cfg(windows)]
|
||||
command.envs(host_env(&home));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
/// Whether this process sits in a unit under this account's user manager
|
||||
/// (an app's scope or service, as uwsm makes for every app), whose stop
|
||||
|
||||
Reference in new issue
Block a user