use super::*;
pub fn install_only_streaming(
adopted: AdoptedMaster,
log_tx: std::sync::mpsc::Sender<String>,
can_launch_tx: std::sync::mpsc::Sender<()>,
confirm_fallback: &mut dyn FnMut(&str) -> bool,
) -> Result<AdoptedMaster> {
let host_label = adopted.host.clone();
let log_tx = spawn_log_tee(install_log_path(), log_tx);
let _ = log_tx.send(format!(
"Install session for {host_label} (croft {})",
env!("CARGO_PKG_VERSION")
));
let _ = log_tx.send(format!("Adopting control socket for {host_label}"));
let ssh = SshControl::adopt(adopted.clone());
let result =
install_only_streaming_over(&ssh, &host_label, &log_tx, &can_launch_tx, confirm_fallback);
std::mem::forget(ssh);
result.map(|_| adopted)
}
pub(super) fn install_only_streaming_over(
ssh: &SshControl,
host_label: &str,
log_tx: &std::sync::mpsc::Sender<String>,
can_launch_tx: &std::sync::mpsc::Sender<()>,
confirm_fallback: &mut dyn FnMut(&str) -> bool,
) -> Result<()> {
let _ = log_tx.send(format!("Checking installed croft on {host_label}"));
let present = remote_croft_present(ssh).unwrap_or(false);
if present {
let _ = can_launch_tx.send(());
}
let _ = log_tx.send("Hashing local source tree".to_string());
let local_stamp = local_source_stamp()?;
let _ = log_tx.send(format!(
"Local source stamp: {local_stamp} (source: {})",
env!("CARGO_MANIFEST_DIR")
));
if let Some(warning) = source_snapshot_warning() {
let _ = log_tx.send(warning);
}
if !remote_install_needed(ssh, &local_stamp)? {
let _ = log_tx.send(format!("Croft on {host_label} is already up to date."));
if !present {
let _ = can_launch_tx.send(());
}
return Ok(());
}
mark_remote_updating(ssh);
let bulk = crate::remote_bulk::establish(&ssh.host, &ssh.socket_path, |msg| {
let _ = log_tx.send(msg);
});
let _ = log_tx.send(format!("Installing/updating Croft on {host_label}"));
let mut gate = |reason: &str| {
if present {
let _ = log_tx.send(format!(
"Update NOT installed: cross-build unavailable ({reason}). Run `croft setup-cross` on this machine, then reconnect — updates then ship a prebuilt binary in seconds."
));
false
} else {
confirm_fallback(reason)
}
};
if let Err(e) = install_remote_croft_streaming(ssh, &bulk.lane, &local_stamp, log_tx, &mut gate)
{
clear_remote_updating(ssh);
return Err(e);
}
let _ = log_tx.send("Install complete.".to_string());
Ok(())
}
pub(crate) fn spawn_log_tee(
path: PathBuf,
downstream: std::sync::mpsc::Sender<String>,
) -> std::sync::mpsc::Sender<String> {
let (tx, rx) = std::sync::mpsc::channel::<String>();
std::thread::spawn(move || {
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
let mut file = std::fs::File::create(&path).ok();
while let Ok(line) = rx.recv() {
if let Some(f) = file.as_mut() {
use std::io::Write as _;
let secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let _ = writeln!(f, "[{secs}] {line}");
}
let _ = downstream.send(line);
}
});
tx
}
pub(super) fn install_log_path() -> PathBuf {
let home = std::env::var_os("HOME")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("."));
home.join(".cache").join("croft").join("install.log")
}
pub(super) fn ship_prebuilt_logged(
lane: &crate::remote_bulk::BulkLane,
ssh: &SshControl,
binary: &Path,
log_tx: &std::sync::mpsc::Sender<String>,
) -> Result<()> {
let dest = format!("{}:.cargo/bin/croft.new", ssh.host);
let status = run_command_streaming(
ship_file_rsync_command(lane, &ssh.socket_path, binary, &dest),
log_tx,
)
.context("rsyncing the prebuilt croft to the remote")?;
anyhow::ensure!(status.success(), "rsync exited with {status}");
Ok(())
}
pub(super) fn run_command_streaming(
mut cmd: Command,
log_tx: &std::sync::mpsc::Sender<String>,
) -> Result<std::process::ExitStatus> {
use std::io::{BufRead, BufReader};
cmd.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = cmd.spawn().context("spawning streaming subprocess")?;
let stdout = child.stdout.take().expect("stdout pipe");
let stderr = child.stderr.take().expect("stderr pipe");
let tx1 = log_tx.clone();
let h1 = std::thread::spawn(move || {
let r = BufReader::new(stdout);
for line in r.lines().map_while(|l| l.ok()) {
let _ = tx1.send(line);
}
});
let tx2 = log_tx.clone();
let h2 = std::thread::spawn(move || {
let r = BufReader::new(stderr);
for line in r.lines().map_while(|l| l.ok()) {
let _ = tx2.send(line);
}
});
let status = child.wait().context("waiting for subprocess")?;
let _ = h1.join();
let _ = h2.join();
Ok(status)
}
pub(super) fn install_remote_croft_streaming(
ssh: &SshControl,
lane: &crate::remote_bulk::BulkLane,
source_stamp: &str,
log_tx: &std::sync::mpsc::Sender<String>,
confirm_fallback: &mut dyn FnMut(&str) -> bool,
) -> Result<()> {
let mut ship = |binary: &Path| ship_prebuilt_logged(lane, ssh, binary, log_tx);
let mut run = |step: Command| run_command_streaming(step, log_tx);
let mut log = |m: String| {
let _ = log_tx.send(m);
};
match try_prebuilt_install(ssh, source_stamp, &mut ship, &mut run, &mut log) {
Ok(true) => return Ok(()),
Ok(false) => {}
Err(e) => log(format!("Prebuilt install failed ({e:#}); building instead")),
}
let reason = match try_local_cross_install_streaming(ssh, lane, source_stamp, log_tx) {
Ok(None) => return Ok(()),
Ok(Some(reason)) => reason,
Err(e) => format!("local cross-build failed: {e:#}"),
};
if !confirm_fallback(&reason) {
anyhow::bail!(
"cross-build unavailable ({reason}); remote compile declined — run `croft setup-cross`, then reconnect for the fast install"
);
}
let _ = log_tx.send(format!("Falling back to remote cargo install ({reason})"));
let _ = log_tx.send("Syncing source tree to remote".to_string());
sync_local_source_to_remote_streaming(ssh, lane, log_tx)?;
let _ = log_tx
.send("Running cargo install on remote (first time can take several minutes)".to_string());
let mut cmd = lane.ssh_command(&ssh.socket_path);
cmd.arg(&ssh.host).arg(remote_install_command(source_stamp));
let status = run_command_streaming(cmd, log_tx).context("installing croft on remote")?;
if !status.success() {
anyhow::bail!("remote croft install failed with {status}");
}
Ok(())
}
pub(super) fn try_local_cross_install_streaming(
ssh: &SshControl,
lane: &crate::remote_bulk::BulkLane,
source_stamp: &str,
log_tx: &std::sync::mpsc::Sender<String>,
) -> Result<Option<String>> {
if let Some(reason) = cross_compile_unavailable_reason() {
let _ = log_tx.send(format!("Local cross-build skipped: {reason}"));
return Ok(Some(reason));
}
let Some(triple) = remote_target_triple(ssh)? else {
let reason = String::from("could not detect the remote architecture");
let _ = log_tx.send(format!("Local cross-build skipped: {reason}"));
return Ok(Some(reason));
};
if !rust_target_installed(triple) {
let reason = format!(
"rustup target `{triple}` missing (run `rustup target add {triple}` once to enable the fast path)"
);
let _ = log_tx.send(format!("Local cross-build skipped: {reason}"));
return Ok(Some(reason));
}
let binary = cross_build_static(triple, log_tx)?;
let mkdir = ssh.background_shell("mkdir -p \"$HOME/.cargo/bin\" \"$HOME/.cache/croft\"");
let mkdir_status =
run_command_streaming(mkdir, log_tx).context("creating remote install dirs")?;
if !mkdir_status.success() {
anyhow::bail!("remote mkdir exited with {mkdir_status}");
}
let dest = format!("{}:.cargo/bin/croft.new", ssh.host);
let _ = log_tx.send(format!(
"Rsyncing binary to {dest} (bulk lane, {} KB/s cap)",
lane.bwlimit_kbps()
));
let rsync = ship_file_rsync_command(lane, &ssh.socket_path, &binary, &dest);
let rsync_status =
run_command_streaming(rsync, log_tx).context("rsyncing croft binary to remote")?;
if !rsync_status.success() {
anyhow::bail!("rsync exited with {rsync_status}");
}
let act = ssh.background_shell(&activate_command(source_stamp));
let act_status =
run_command_streaming(act, log_tx).context("activating remote croft binary")?;
if !act_status.success() {
anyhow::bail!("remote activation exited with {act_status}");
}
let _ = log_tx.send("Installed croft on remote via local cross-build.".to_string());
Ok(None)
}
pub(super) fn sync_local_source_to_remote_streaming(
ssh: &SshControl,
lane: &crate::remote_bulk::BulkLane,
log_tx: &std::sync::mpsc::Sender<String>,
) -> Result<()> {
let source = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let mkdir = ssh.background_shell(&remote_source_dir_prep(&source));
let mkdir_status =
run_command_streaming(mkdir, log_tx).context("creating remote source dir")?;
if !mkdir_status.success() {
anyhow::bail!("remote mkdir exited with {mkdir_status}");
}
let mut source_arg: std::ffi::OsString = source.clone().into_os_string();
source_arg.push("/");
let dest = format!("{}:.cache/croft/source/", ssh.host);
let rsync = source_sync_rsync_command(lane, &ssh.socket_path, &source_arg, &dest);
let status = run_command_streaming(rsync, log_tx).context("running rsync to remote")?;
if !status.success() {
anyhow::bail!("rsync exited with {status}");
}
Ok(())
}
pub(super) fn spawn_background_install(ssh: &SshControl) {
let adopted = AdoptedMaster {
host: ssh.host.clone(),
socket_dir: ssh.socket_dir.clone(),
socket_path: ssh.socket_path.clone(),
};
std::thread::spawn(move || {
let (log_tx, _) = std::sync::mpsc::channel();
let (can_launch_tx, _) = std::sync::mpsc::channel();
let _ = install_only_streaming(adopted, log_tx, can_launch_tx, &mut |_| false);
});
}