use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use crate::error::TmuxFzfError;
use crate::host::Host;
use crate::tmux::{TmuxClient, TmuxSession, TmuxWindow};
pub const BASE_INTERVAL: Duration = Duration::from_secs(5);
pub const MAX_INTERVAL: Duration = Duration::from_secs(60);
const STOP_CHECK: Duration = Duration::from_millis(250);
const PROBE_SCRIPT: &str = "printf \"tmux=%s\\n\" \"$(command -v tmux)\"; \
printf \"tango=%s\\n\" \"$(tango attach --help >/dev/null 2>&1 && command -v tango)\"";
const LOGIN_SHELL_WRAPPER: &str = "exec \"${SHELL:-/bin/sh}\" -l -c \"$0\"";
#[derive(Debug, Clone, PartialEq)]
pub enum HostState {
Loading,
Online {
sessions: Vec<TmuxSession>,
windows: HashMap<Arc<str>, Vec<TmuxWindow>>,
tmux_path: String,
tango_path: Option<String>,
},
Offline { error: String },
NoTmux,
}
#[derive(Debug)]
pub struct HostUpdate {
pub alias: Arc<str>,
pub state: HostState,
}
pub struct PollerHandle {
pub alias: Arc<str>,
stop: Arc<AtomicBool>,
wake: Arc<AtomicBool>,
}
impl PollerHandle {
pub fn stop(&self) {
self.stop.store(true, Ordering::Relaxed);
}
pub fn wake(&self) {
self.wake.store(true, Ordering::Relaxed);
}
}
impl Drop for PollerHandle {
fn drop(&mut self) {
self.stop();
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Probe {
pub tmux_path: Option<String>,
pub tango_path: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProbeOutcome {
Unreachable(String),
Ran(Probe),
}
pub fn parse_probe_output(stdout: &str) -> Probe {
let mut probe = Probe { tmux_path: None, tango_path: None };
for line in stdout.lines() {
let Some((key, value)) = line.split_once('=') else { continue };
let value = value.trim();
let slot = match key.trim() {
"tmux" => &mut probe.tmux_path,
"tango" => &mut probe.tango_path,
_ => continue,
};
if !value.is_empty() {
*slot = Some(value.to_string());
}
}
probe
}
pub fn classify_probe(exit_code: Option<i32>, stdout: &str, stderr: &str) -> ProbeOutcome {
match exit_code {
Some(255) | None => ProbeOutcome::Unreachable(summarize_error(stderr)),
Some(_) => ProbeOutcome::Ran(parse_probe_output(stdout)),
}
}
pub fn summarize_error(text: &str) -> String {
let line = text
.lines()
.map(str::trim)
.find(|l| !l.is_empty())
.unwrap_or("unknown error");
let line = line.find("ssh: ").map(|i| &line[i..]).unwrap_or(line);
line.to_string()
}
pub fn next_interval(current: Duration, ok: bool) -> Duration {
if ok {
BASE_INTERVAL
} else {
(current * 2).min(MAX_INTERVAL)
}
}
pub fn spawn_poller(alias: Arc<str>, tx: Sender<HostUpdate>) -> PollerHandle {
let stop = Arc::new(AtomicBool::new(false));
let wake = Arc::new(AtomicBool::new(false));
let (thread_stop, thread_wake) = (Arc::clone(&stop), Arc::clone(&wake));
let thread_alias = Arc::clone(&alias);
let thread_name = format!("tango-poll-{}", alias);
let spawned = thread::Builder::new()
.name(thread_name)
.spawn(move || poll_loop(thread_alias, tx, thread_stop, thread_wake));
if spawned.is_err() {
stop.store(true, Ordering::Relaxed);
}
PollerHandle { alias, stop, wake }
}
fn poll_loop(alias: Arc<str>, tx: Sender<HostUpdate>, stop: Arc<AtomicBool>, wake: Arc<AtomicBool>) {
let host = Host::remote(&alias);
let mut interval = BASE_INTERVAL;
let mut probe: Option<Probe> = None;
while !stop.load(Ordering::Relaxed) {
let state = poll_once(&host, &mut probe);
let ok = matches!(state, HostState::Online { .. });
if !ok {
probe = None;
}
if tx.send(HostUpdate { alias: Arc::clone(&alias), state }).is_err() {
return;
}
interval = next_interval(interval, ok);
if sleep_until_stopped(interval, &stop, &wake) {
interval = BASE_INTERVAL;
}
}
}
fn poll_once(host: &Host, probe: &mut Option<Probe>) -> HostState {
if probe.is_none() {
match run_probe(host) {
Ok(found) => *probe = Some(found),
Err(state) => return state,
}
}
let Some(tmux_path) = probe.as_ref().and_then(|p| p.tmux_path.clone()) else {
return HostState::NoTmux;
};
let tango_path = probe.as_ref().and_then(|p| p.tango_path.clone());
let mut client = TmuxClient::for_host(host.clone()).with_program(&tmux_path);
let sessions = match client.list_sessions() {
Ok(sessions) => sessions,
Err(TmuxFzfError::NoSessions) => Vec::new(),
Err(e) => return HostState::Offline { error: summarize_error(&e.to_string()) },
};
let mut windows: HashMap<Arc<str>, Vec<TmuxWindow>> = HashMap::new();
if !sessions.is_empty() {
if let Ok(pairs) = client.list_all_windows() {
for (session, window) in pairs {
windows.entry(session).or_default().push(window);
}
}
}
HostState::Online { sessions, windows, tmux_path, tango_path }
}
fn run_probe(host: &Host) -> Result<Probe, HostState> {
let first = execute_probe(host, &["-c", PROBE_SCRIPT])?;
if first.tmux_path.is_some() {
return Ok(first);
}
let retry = execute_probe(host, &["-c", LOGIN_SHELL_WRAPPER, PROBE_SCRIPT])?;
if retry.tmux_path.is_some() {
Ok(retry)
} else {
Err(HostState::NoTmux)
}
}
fn execute_probe(host: &Host, sh_args: &[&str]) -> Result<Probe, HostState> {
let output = host
.command("sh", sh_args, false)
.stdin(std::process::Stdio::null())
.output()
.map_err(|e| HostState::Offline { error: format!("cannot run ssh: {}", e) })?;
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
match classify_probe(output.status.code(), &stdout, &stderr) {
ProbeOutcome::Unreachable(error) => Err(HostState::Offline { error }),
ProbeOutcome::Ran(probe) => Ok(probe),
}
}
fn sleep_until_stopped(total: Duration, stop: &AtomicBool, wake: &AtomicBool) -> bool {
let mut slept = Duration::ZERO;
while slept < total && !stop.load(Ordering::Relaxed) {
if wake.swap(false, Ordering::Relaxed) {
return true;
}
let step = STOP_CHECK.min(total - slept);
thread::sleep(step);
slept += step;
}
wake.swap(false, Ordering::Relaxed)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreviewKey {
pub host: Arc<str>,
pub target: String,
}
#[derive(Debug, Clone)]
pub struct PreviewRequest {
pub key: PreviewKey,
pub tmux_path: String,
}
#[derive(Debug)]
pub struct PreviewResult {
pub key: PreviewKey,
pub content: Result<String, String>,
}
pub fn spawn_previewer(alias: Arc<str>, results: Sender<PreviewResult>) -> Sender<PreviewRequest> {
let (tx, rx) = mpsc::channel();
let host = Host::remote(&alias);
let capture = move |req: &PreviewRequest| {
TmuxClient::for_host(host.clone())
.with_program(&req.tmux_path)
.capture_pane(&req.key.target)
.map_err(|e| summarize_error(&e.to_string()))
};
let _ = thread::Builder::new()
.name(format!("tango-preview-{}", alias))
.spawn(move || preview_loop(rx, results, capture));
tx
}
fn preview_loop(
rx: Receiver<PreviewRequest>,
tx: Sender<PreviewResult>,
capture: impl Fn(&PreviewRequest) -> Result<String, String>,
) {
while let Ok(mut req) = rx.recv() {
while let Ok(newer) = rx.try_recv() {
req = newer;
}
let content = capture(&req);
if tx.send(PreviewResult { key: req.key, content }).is_err() {
return;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn next_interval_doubles_on_failure_and_caps_at_max() {
let mut d = BASE_INTERVAL;
let mut seen = Vec::new();
for _ in 0..6 {
d = next_interval(d, false);
seen.push(d.as_secs());
}
assert_eq!(seen, vec![10, 20, 40, 60, 60, 60]);
}
#[test]
fn next_interval_resets_to_base_on_success() {
assert_eq!(next_interval(MAX_INTERVAL, true), BASE_INTERVAL);
assert_eq!(next_interval(BASE_INTERVAL, true), BASE_INTERVAL);
}
#[test]
fn parse_probe_output_reads_both_paths() {
let probe = parse_probe_output("tmux=/usr/bin/tmux\ntango=/home/k/.cargo/bin/tango\n");
assert_eq!(probe.tmux_path.as_deref(), Some("/usr/bin/tmux"));
assert_eq!(probe.tango_path.as_deref(), Some("/home/k/.cargo/bin/tango"));
}
#[test]
fn parse_probe_output_treats_empty_value_as_absent() {
let probe = parse_probe_output("tmux=/usr/bin/tmux\ntango=\n");
assert_eq!(probe.tmux_path.as_deref(), Some("/usr/bin/tmux"));
assert_eq!(probe.tango_path, None);
}
#[test]
fn parse_probe_output_with_nothing_found() {
let probe = parse_probe_output("tmux=\ntango=\n");
assert_eq!(probe, Probe { tmux_path: None, tango_path: None });
}
#[test]
fn parse_probe_output_ignores_login_banner_noise() {
let probe = parse_probe_output("Welcome to box\ntmux=/opt/homebrew/bin/tmux\nfoo=bar\n");
assert_eq!(probe.tmux_path.as_deref(), Some("/opt/homebrew/bin/tmux"));
assert_eq!(probe.tango_path, None);
}
#[test]
fn classify_probe_exit_255_is_unreachable_with_ssh_message() {
let outcome = classify_probe(
Some(255),
"",
"ssh: connect to host box port 22: Connection refused\r\n",
);
assert_eq!(
outcome,
ProbeOutcome::Unreachable("ssh: connect to host box port 22: Connection refused".into())
);
}
#[test]
fn classify_probe_signal_death_is_unreachable() {
assert!(matches!(classify_probe(None, "", ""), ProbeOutcome::Unreachable(_)));
}
#[test]
fn classify_probe_exit_zero_parses_stdout() {
let outcome = classify_probe(Some(0), "tmux=/usr/bin/tmux\ntango=\n", "");
assert_eq!(
outcome,
ProbeOutcome::Ran(Probe { tmux_path: Some("/usr/bin/tmux".into()), tango_path: None })
);
}
#[test]
fn summarize_error_takes_first_nonempty_line_from_ssh() {
let text = "tmux error: tmux list-sessions failed: ssh: Could not resolve hostname box: nodename nor servname provided\nsecond line";
assert_eq!(
summarize_error(text),
"ssh: Could not resolve hostname box: nodename nor servname provided"
);
}
#[test]
fn summarize_error_keeps_non_ssh_lines_and_handles_empty() {
assert_eq!(summarize_error("\n server exited unexpectedly \n"), "server exited unexpectedly");
assert_eq!(summarize_error(""), "unknown error");
}
fn handle() -> PollerHandle {
PollerHandle {
alias: "box".into(),
stop: Arc::new(AtomicBool::new(false)),
wake: Arc::new(AtomicBool::new(false)),
}
}
#[test]
fn poller_handle_stop_flag_is_observed() {
let handle = handle();
let (stop, wake) = (Arc::clone(&handle.stop), Arc::clone(&handle.wake));
let started = std::time::Instant::now();
let sleeper = thread::spawn(move || sleep_until_stopped(Duration::from_secs(30), &stop, &wake));
drop(handle);
let woken = sleeper.join().unwrap();
assert!(started.elapsed() < Duration::from_secs(5), "drop must wake the sleeper promptly");
assert!(!woken, "a stop is not a wake");
}
#[test]
fn wake_cuts_a_backoff_sleep_short_exactly_once() {
let handle = handle();
let (stop, wake) = (Arc::clone(&handle.stop), Arc::clone(&handle.wake));
let started = std::time::Instant::now();
let sleeper = thread::spawn(move || {
let first = sleep_until_stopped(MAX_INTERVAL, &stop, &wake);
let after_first = started.elapsed();
let second = sleep_until_stopped(Duration::from_millis(600), &stop, &wake);
(first, after_first, second, started.elapsed())
});
thread::sleep(Duration::from_millis(100));
handle.wake();
let (first, after_first, second, total) = sleeper.join().unwrap();
assert!(first, "wake must report itself so poll_loop resets the backoff");
assert!(after_first < Duration::from_secs(2), "woke after {:?}", after_first);
assert!(!second, "the wake flag must be consumed by the first sleep");
assert!(total - after_first >= Duration::from_millis(600), "second sleep cut short: {:?}", total - after_first);
}
#[test]
fn preview_loop_skips_requests_superseded_while_a_capture_runs() {
let request = |target: &str| PreviewRequest {
key: PreviewKey { host: "box".into(), target: target.to_string() },
tmux_path: "/usr/bin/tmux".to_string(),
};
let (req_tx, req_rx) = mpsc::channel();
let (res_tx, res_rx) = mpsc::channel();
let (started_tx, started_rx) = mpsc::channel();
let (release_tx, release_rx) = mpsc::channel::<()>();
let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
let worker = {
let captured = Arc::clone(&captured);
thread::spawn(move || {
preview_loop(req_rx, res_tx, |req| {
captured.lock().unwrap().push(req.key.target.clone());
if req.key.target == "a:" {
started_tx.send(()).unwrap();
release_rx.recv().unwrap();
}
Ok(format!("content of {}", req.key.target))
})
})
};
req_tx.send(request("a:")).unwrap();
started_rx.recv().unwrap();
for target in ["b:", "c:1", "d:"] {
req_tx.send(request(target)).unwrap();
}
release_tx.send(()).unwrap();
drop(req_tx);
worker.join().unwrap();
let captured = captured.lock().unwrap().clone();
assert_eq!(captured, vec!["a:", "d:"], "only the newest queued request should be captured");
let results: Vec<(String, Result<String, String>)> =
res_rx.try_iter().map(|r| (r.key.target, r.content)).collect();
assert_eq!(
results,
vec![
("a:".to_string(), Ok("content of a:".to_string())),
("d:".to_string(), Ok("content of d:".to_string())),
],
"each capture must report back under its own key"
);
}
#[test]
fn probe_script_is_single_quote_free() {
assert!(!PROBE_SCRIPT.contains('\''), "{}", PROBE_SCRIPT);
assert!(!LOGIN_SHELL_WRAPPER.contains('\''), "{}", LOGIN_SHELL_WRAPPER);
}
}