fix(host): what holds the books is known, not guessed; a command joins what starts beside it
Plan P15 unit A5, fix round. A server answering its admin socket with no host over it was taken to be "the app". Three wrong outcomes followed: a `serve` started while a killed host's server was still finishing its last backup was told "the app has these books open" and exited, `close` and `doctor` said "the app" during such a close, and a command attached to another command's short-lived server as if it were the app (refused "not open" for another company, or its server closed under the other). A server now says what it is. `wanderbooks server --started-by app|host|command` writes run/server.info beside its lock (who started it, its pid, whether it has begun to close), moved into place whole as soon as the lock is its, rewritten `closing` the moment it is told to close, removed just before the lock goes. It is read only while the lock is held, which is when it is the lock holder's. A file beside the lock, not a field in the admin hello: it also covers a server that has no admin socket yet (opening) and costs the older admin protocol nothing. A server that says nothing (an earlier build's) is taken for the app's, as before. `opener::what_holds` reads it: only a server the app started, not closing and answering, is the app. A command's server, or one that is closing (the app's, or the orphan of a host that went), is waited for, said in words, bounded by `open_wait` (a bridge waits as long as its session does), and the holder or command goes on once it is gone. `close`, `doctor` and the bridge say the true thing for each. A command racing another program's start no longer fails with "close it" or waits silently 300 s: if its own server loses the lock to a program that started after its look, it lets its start go and joins what runs (`wait_ready_unless_beaten`, `reach`), inside one `open_wait`. A command's own server is started clean, as a host is: the host's environment only, the root as an absolute path, `/` as its folder (Windows: `run/`), and every server closes the descriptors above 2 at its start, so one that outlives its command (still closing after 90 s) 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 user's session (ssh agent, git configuration) for backups; it too loses stray descriptors, since the server does that for any starter. Test knobs: `--start-delay` (a server's slow start) and `timer_hold=1` for a command's own server, following `--timer-hold`. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
6b95ce59ad
commit
2ff2913274
9 files changed
+598
-80
No files matched your search
@@ -311,6 +311,16 @@
|
||||
//! request that arrives once the server is closing and finds a book's
|
||||
//! door shut is refused as closing (503, `closing`), not recorded:
|
||||
//! the door is shut (INVARIANT 11), as in a close of one book.
|
||||
//! 16. A server says what it is, beside its lock (`run/server.info`),
|
||||
//! when it is started with `--started-by`: who started it (the app,
|
||||
//! a `serve` host, or a command that runs one for the length of its
|
||||
//! work), its process id, and whether it has begun to close. The
|
||||
//! file is written whole and moved into place as soon as the lock is
|
||||
//! the server's, rewritten with `closing` the moment it is told to
|
||||
//! close, and removed just before the lock is let go; it is read only
|
||||
//! while the lock is held, which is when it is the lock holder's. A
|
||||
//! program that finds a server holding the books reads it before it
|
||||
//! decides what that server is.
|
||||
//! SCENARIOS:
|
||||
//! 1. Two books open; one is closed while agents call both: the other
|
||||
//! answers throughout, the closed one's calls are refused unrun
|
||||
@@ -414,6 +424,90 @@ pub const ADMIN_SOCKET: &str = "admin.sock";
|
||||
pub const SERVER_LOCK: &str = "server.lock";
|
||||
/// What the server prints on stdout when it is ready (INVARIANT 5).
|
||||
pub const READY: &str = "ready";
|
||||
/// What a server says of itself, beside its lock: who started it, and
|
||||
/// whether it has begun to close (INVARIANT 16).
|
||||
pub const SERVER_INFO: &str = "server.info";
|
||||
|
||||
/// Who started a server (INVARIANT 16): the program a caller finds holding
|
||||
/// the books decides what to do from it, and so the words it says are the
|
||||
/// true ones.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum StartedBy {
|
||||
/// The desktop app: the books server is its child, for as long as its
|
||||
/// window runs.
|
||||
App,
|
||||
/// A `wanderbooks serve` host: the host holds `run/host.lock` as long
|
||||
/// as it lives, so a server of its starting that is found with no host
|
||||
/// is an orphan, closing.
|
||||
Host,
|
||||
/// A command that runs a server of its own for the length of its work.
|
||||
Command,
|
||||
}
|
||||
|
||||
impl StartedBy {
|
||||
/// The flag value (`--started-by`).
|
||||
pub fn flag(self) -> &'static str {
|
||||
match self {
|
||||
StartedBy::App => "app",
|
||||
StartedBy::Host => "host",
|
||||
StartedBy::Command => "command",
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(value: &str) -> Result<Self, String> {
|
||||
match value {
|
||||
"app" => Ok(StartedBy::App),
|
||||
"host" => Ok(StartedBy::Host),
|
||||
"command" => Ok(StartedBy::Command),
|
||||
other => Err(format!(
|
||||
"--started-by takes app, host or command, not {other}"
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a server says of itself in `run/server.info` (INVARIANT 16).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ServerInfo {
|
||||
/// Who started it.
|
||||
pub by: StartedBy,
|
||||
/// Its process id.
|
||||
pub pid: u32,
|
||||
/// It has begun to close: running calls finish, the last backups are
|
||||
/// made. It still answers its admin socket until it is gone.
|
||||
pub closing: bool,
|
||||
}
|
||||
|
||||
/// What the server holding `run/server.lock` says of itself: `None` when
|
||||
/// there is no such file, or it is not (yet) readable: a server of an
|
||||
/// earlier build says nothing, and a starting one says it just after it
|
||||
/// takes the lock. Only meaningful while that lock is held.
|
||||
pub fn read_server_info(run: &Path) -> Option<ServerInfo> {
|
||||
let text = std::fs::read_to_string(run.join(SERVER_INFO)).ok()?;
|
||||
serde_json::from_str(&text).ok()
|
||||
}
|
||||
|
||||
/// Say what this server is (INVARIANT 16): written whole beside the lock
|
||||
/// and moved into place, so a reader sees one version or the other.
|
||||
fn write_server_info(run: &Path, info: &ServerInfo) -> std::io::Result<()> {
|
||||
let text = serde_json::to_string(info).map_err(std::io::Error::other)?;
|
||||
let temp = run.join(format!("{SERVER_INFO}.{}.tmp", info.pid));
|
||||
std::fs::write(&temp, text)?;
|
||||
std::fs::rename(&temp, run.join(SERVER_INFO)).inspect_err(|_| {
|
||||
let _ = std::fs::remove_file(&temp);
|
||||
})
|
||||
}
|
||||
|
||||
/// Removes `run/server.info` when the server is done with it, before the
|
||||
/// lock goes (INVARIANT 16).
|
||||
struct InfoGuard(PathBuf);
|
||||
|
||||
impl Drop for InfoGuard {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// How large an MCP request may be (plan 3.2): files come only through
|
||||
/// uploads (`/b/{book}/u/{upload}`), never in a request (D-46).
|
||||
@@ -3220,6 +3314,9 @@ fn print_usage(prog: &str) {
|
||||
eprintln!(" --http [ADDR]: also serve the MCP door on loopback only (default");
|
||||
eprintln!(" 127.0.0.1:7411), for a TLS proxy or a tunnel in front of it. Off unless");
|
||||
eprintln!(" given; any other address is refused.");
|
||||
eprintln!(" --start-delay MS: wait this long before taking the lock (tests).");
|
||||
eprintln!(" --started-by app | host | command: who started it, said in run/server.info");
|
||||
eprintln!(" so a program that finds it holding the books knows what it is.");
|
||||
eprintln!(" --open all | none | ID[,ID...]: which books are open at the start (default");
|
||||
eprintln!(" all). A book left closed opens when asked (`wanderbooks books open ID`).");
|
||||
}
|
||||
@@ -3237,6 +3334,8 @@ pub fn run(
|
||||
let mut isolation = Isolation::SameUser;
|
||||
let mut tunnel: Option<std::net::SocketAddr> = None;
|
||||
let mut open_at_start = OpenAtStart::All;
|
||||
let mut started_by: Option<StartedBy> = None;
|
||||
let mut start_delay = Duration::ZERO;
|
||||
let mut args = args.into_iter().peekable();
|
||||
while let Some(arg) = args.next() {
|
||||
match arg.as_str() {
|
||||
@@ -3266,6 +3365,26 @@ pub fn run(
|
||||
open_at_start =
|
||||
OpenAtStart::parse(&args.next().ok_or("--open needs all, none, or ids")?)?;
|
||||
}
|
||||
// Who started this server (INVARIANT 16): the app, a `serve`
|
||||
// host or a command. Without it a server says nothing of
|
||||
// itself, as every earlier build's did not.
|
||||
"--started-by" => {
|
||||
started_by = Some(StartedBy::parse(
|
||||
&args
|
||||
.next()
|
||||
.ok_or("--started-by needs app, host or command")?,
|
||||
)?);
|
||||
}
|
||||
// How long this server waits before it first tries to take the
|
||||
// lock (tests of a program that starts or finds the books in
|
||||
// that time: a slow start).
|
||||
"--start-delay" => {
|
||||
let ms: u64 = args
|
||||
.next()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.ok_or("--start-delay needs milliseconds")?;
|
||||
start_delay = Duration::from_millis(ms);
|
||||
}
|
||||
// How long the books stay unwritten before a backup (tests).
|
||||
"--backup-quiet" => {
|
||||
let ms: u64 = args
|
||||
@@ -3359,6 +3478,11 @@ pub fn run(
|
||||
let _in_runtime = rt.enter();
|
||||
watch_for_close(&stops)?;
|
||||
}
|
||||
// The test knob `--start-delay`: a slow start, told to close or not.
|
||||
let delayed = std::time::Instant::now();
|
||||
while delayed.elapsed() < start_delay && !stops.close.is_cancelled() {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
// INVARIANT 1: a server still finishing (its host gone) has the lock;
|
||||
// this one waits for it, touching nothing, until told to close.
|
||||
let mut said = false;
|
||||
@@ -3394,6 +3518,28 @@ pub fn run(
|
||||
ledger_store::winsec::set_owner_only(&lock_path)
|
||||
.map_err(|e| format!("can't make the server lock private: {}", e.kind()))?;
|
||||
}
|
||||
// INVARIANT 16: what this server is, said as soon as the lock is its
|
||||
// and until just before it lets the lock go; `closing` from the moment
|
||||
// it is told to close.
|
||||
let info_guard = match started_by {
|
||||
Some(by) => {
|
||||
let mut info = ServerInfo {
|
||||
by,
|
||||
pid: std::process::id(),
|
||||
closing: stops.close.is_cancelled(),
|
||||
};
|
||||
write_server_info(&run, &info)
|
||||
.map_err(|e| format!("can't say what this server is: {}", e.kind()))?;
|
||||
let (close, there) = (stops.close.clone(), run.clone());
|
||||
rt.spawn(async move {
|
||||
close.cancelled().await;
|
||||
info.closing = true;
|
||||
let _ = write_server_info(&there, &info);
|
||||
});
|
||||
Some(InfoGuard(run.join(SERVER_INFO)))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let books = Arc::new(
|
||||
Books::new(root.clone(), backup_quiet, drill_first, isolation).with_timers(timers),
|
||||
);
|
||||
@@ -3442,6 +3588,7 @@ pub fn run(
|
||||
for name in [MCP_SOCKET, ADMIN_SOCKET] {
|
||||
let _ = std::fs::remove_file(run.join(name));
|
||||
}
|
||||
drop(info_guard);
|
||||
drop(lock);
|
||||
served
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user