perf(remote): prove a server that is already running in one round trip

Every new connection to a machine tty7 had been to before spent six
sequential round trips proving what it already had: uname, a home lookup and
a stat over SFTP, a control probe and a process scan. The SFTP session it
opened also stayed open for the life of the connection, one of the handful of
sessions the server allows it.

One `sh -c` script now answers the common case: this dialect's server is
installed, answers the bridge probe, and is the one running (or a build of the
same dialect). Anything else falls through to the full install path unchanged.
This commit is contained in:
l0ng-ai
2026-09-30 11:58:03 +08:00
parent aa1292767d
commit b0b7589e11
2 changed files with 170 additions and 1 deletions
+66 -1
View File
@@ -827,6 +827,59 @@ impl<'a> Installer<'a> {
Ok(report)
}
/// The answer [`Installer::run`] gives for a machine that already has this
/// dialect's server installed, serving, and the one running — found in one
/// round trip instead of the half dozen `run` spends finding it out.
///
/// That is the answer on every connect to a machine tty7 has been to before,
/// and `run` pays for it in sequence: `uname`, a home lookup and a `stat`
/// over SFTP, a control probe, a process scan. Six round trips before the
/// first pane — and the SFTP session it opens stays open for the life of
/// the connection, one of the handful of sessions the server allows it.
///
/// `None` means "go and ask properly", never "something is wrong": any
/// other state — nothing installed, nothing serving, another build running,
/// a remote shell that could not read the script — is `run`'s to handle.
pub fn quick_prove(&self) -> Option<ProvedServer> {
let out = self.ops.run(&self.quick_prove_command()).ok()?;
if !out.success() {
return None;
}
self.quick_verdict(&out.stdout)
}
fn quick_prove_command(&self) -> String {
let binary = format!(
"{}/{}",
asset::INSTALL_DIR_COMPONENTS.join("/"),
asset::binary_name(self.dialect.control, self.dialect.protocol)
);
// `sh -c`, because the login shell over there need not be a POSIX one.
let script = format!(
r#"b="$HOME/{binary}"; if [ -f "$b" ] && [ -x "$b" ] && "$b" --stdio --bridge </dev/null >/dev/null 2>&1; then printf '{QUICK_PROVE_MARK}%s\n' "$b"; {RUNNING_EXE_COMMAND}; fi"#
);
format!("sh -c {}", shell_quote(&script))
}
fn quick_verdict(&self, stdout: &str) -> Option<ProvedServer> {
let (first, rest) = stdout.split_once('\n')?;
let binary = first.strip_prefix(QUICK_PROVE_MARK)?;
if !binary.starts_with('/') {
return None;
}
// The same test `check_running_build` applies: whatever is running is
// either this very file or a build of the same dialect. Anything else
// is a mismatch to raise, and raising it is `run`'s job.
let running = rest.trim();
let ours = running.is_empty()
|| running == binary
|| asset::dialect_from_path(running) == Some(self.dialect.dialect());
ours.then(|| ProvedServer {
binary: binary.to_string(),
mismatch: None,
})
}
fn adoptable_running_server(&self) -> Result<Option<(String, RemoteProtocol)>, InstallError> {
let Some(exe) = self.running_server_exe() else {
return Ok(None);
@@ -1179,6 +1232,10 @@ impl<'a> Installer<'a> {
/// out its ten seconds for a daemon nobody had asked to stop.
const RUNNING_EXE_COMMAND: &str = r#"if [ -d /proc ]; then for p in /proc/[0-9]*; do e=$(readlink "$p/exe" 2>/dev/null) || continue; case "$e" in */tty7-server-*) printf '%s' "${e% (deleted)}"; break;; esac; done; else ps -xwwo pid=,comm= 2>/dev/null | while read -r pid e; do case "$e" in */tty7-server-*) printf '%s' "$e"; break;; esac; done; fi; true"#;
/// Starts the line [`Installer::quick_prove`]'s script prints once the server
/// answered, so nothing a login script prints can pass for it.
const QUICK_PROVE_MARK: &str = "tty7-quick-prove ";
const TERMINATE_RUNNING_COMMAND: &str = r#"if [ -d /proc ]; then for p in /proc/[0-9]*; do e=$(readlink "$p/exe" 2>/dev/null) || continue; case "$e" in */tty7-server-*) kill -TERM "${p#/proc/}" 2>/dev/null; break;; esac; done; else ps -xwwo pid=,comm= 2>/dev/null | while read -r pid e; do case "$e" in */tty7-server-*) kill -TERM "$pid" 2>/dev/null; break;; esac; done; fi; true"#;
/// The two files a launch writes beside the server binary. Named here because
@@ -1453,7 +1510,15 @@ pub fn ensure_remote_server_labeled(conn: &Arc<SshConnection>, host: &str) -> io
let fetch = default_fetcher();
let confirm = install_confirm();
let source = BundledOrRelease::discover(fetch.as_ref());
let report = Installer::with_source(&ops, &source, confirm.as_ref(), host).run()?;
let installer = Installer::with_source(&ops, &source, confirm.as_ref(), host);
if let Some(proved) = installer.quick_prove() {
log::info!(
"remote {host}: tty7-server already serving at {}",
proved.binary
);
return Ok(proved);
}
let report = installer.run()?;
log::info!(
"remote {host}: {} at {} ({}{})",
if report.installed {
@@ -2638,3 +2638,107 @@ mod proving_the_server_once_per_connection {
);
}
}
fn quick_with(stdout: &str) -> Option<ProvedServer> {
let (remote, release, user) = (FakeRemote::new(), FakeRelease::new(), FakeUser::approving());
installer(&remote, &release, &user, "box").quick_verdict(stdout)
}
const QUICK_BINARY: &str = "/home/u/.local/share/tty7/bin/tty7-server-c3p4";
#[test]
fn a_machine_already_serving_this_dialect_is_proved_in_one_round_trip() {
let proved = quick_with(&format!("{QUICK_PROVE_MARK}{QUICK_BINARY}\n{QUICK_BINARY}"))
.expect("installed, serving, and the one running");
assert_eq!(proved.binary, QUICK_BINARY);
assert_eq!(proved.mismatch, None);
let other_build_same_dialect = "/opt/tty7/tty7-server-c3p4";
assert!(
quick_with(&format!(
"{QUICK_PROVE_MARK}{QUICK_BINARY}\n{other_build_same_dialect}"
))
.is_some(),
"a build of the same dialect serves us, as `check_running_build` agrees"
);
assert!(
quick_with(&format!("{QUICK_PROVE_MARK}{QUICK_BINARY}\n")).is_some(),
"nothing found by the process scan is not a mismatch either"
);
}
#[test]
fn anything_short_of_that_goes_through_the_whole_install() {
assert!(quick_with("").is_none(), "not installed or not serving");
assert!(
quick_with(&format!(
"{QUICK_PROVE_MARK}{QUICK_BINARY}\n/x/tty7-server-c2p4"
))
.is_none(),
"another dialect is running: the mismatch is run's to raise"
);
assert!(
quick_with(&format!("Last login: today\n{QUICK_BINARY}")).is_none(),
"only the marked line names the binary"
);
assert!(
quick_with(&format!("{QUICK_PROVE_MARK}relative/path\n")).is_none(),
"a path that is not absolute is not one the route can run"
);
}
#[test]
fn the_quick_probe_through_its_real_ops_falls_back_when_the_answer_is_not_there() {
// FakeRemote answers the bridge probe with an empty stdout, the way a shell
// that never printed the marker would.
let remote = FakeRemote::new();
let (release, user) = (FakeRelease::new(), FakeUser::approving());
assert!(
installer(&remote, &release, &user, "box")
.quick_prove()
.is_none()
);
}
/// The script, run by a real `sh` against a real file, the way sshd would run
/// it: a server that answers the bridge probe is named on the marked line.
#[cfg(unix)]
#[test]
fn the_quick_probe_script_names_a_server_that_answers() {
use std::os::unix::fs::PermissionsExt as _;
let home = tempfile::tempdir().unwrap();
let bin = home.path().join(".local/share/tty7/bin");
std::fs::create_dir_all(&bin).unwrap();
let server = bin.join(asset::binary_name(CONTROL, PROTOCOL));
std::fs::write(&server, "#!/bin/sh\n[ \"$1 $2\" = \"--stdio --bridge\" ]\n").unwrap();
std::fs::set_permissions(&server, std::fs::Permissions::from_mode(0o755)).unwrap();
let remote = FakeRemote::new();
let (release, user) = (FakeRelease::new(), FakeUser::approving());
let cmd = installer(&remote, &release, &user, "box").quick_prove_command();
let run = |home: &std::path::Path| {
let out = std::process::Command::new("sh")
.arg("-c")
.arg(&cmd)
.env("HOME", home)
.output()
.unwrap();
assert!(out.status.success(), "{out:?}");
String::from_utf8(out.stdout).unwrap()
};
let stdout = run(home.path());
let first = stdout.lines().next().unwrap_or_default();
assert_eq!(
first,
format!("{QUICK_PROVE_MARK}{}", server.display()),
"{stdout:?}"
);
std::fs::write(&server, "#!/bin/sh\nexit 1\n").unwrap();
assert_eq!(
run(home.path()),
"",
"a server that does not answer is not named"
);
}