Skip to main content

tmux_tango/
remote.rs

1//! Background polling of remote hosts.
2//!
3//! Each configured host gets its own thread that probes the machine once (where are `tmux`
4//! and `tango`?), then lists sessions and windows on a slow cadence and ships snapshots to
5//! the TUI over a channel. The TUI thread never touches ssh, so a dead or slow host costs it
6//! nothing but a stale node. Failures back off exponentially so an unreachable host is not
7//! hammered every few seconds for the life of the process.
8
9use std::collections::HashMap;
10use std::sync::atomic::{AtomicBool, Ordering};
11use std::sync::mpsc::{self, Receiver, Sender};
12use std::sync::Arc;
13use std::thread;
14use std::time::Duration;
15
16use crate::error::TmuxFzfError;
17use crate::host::Host;
18use crate::tmux::{TmuxClient, TmuxSession, TmuxWindow};
19
20/// Poll cadence while a host is healthy.
21pub const BASE_INTERVAL: Duration = Duration::from_secs(5);
22/// Cap on the backoff while a host is failing.
23pub const MAX_INTERVAL: Duration = Duration::from_secs(60);
24/// Granularity at which a sleeping poller notices a stop request.
25const STOP_CHECK: Duration = Duration::from_millis(250);
26
27/// Shell snippet that reports where `tmux` and a usable `tango` live. The `tango attach --help`
28/// check doubles as a version gate: a tango too old to have `attach` is reported as absent so
29/// the attach degrades to plain tmux instead of failing on the remote.
30const PROBE_SCRIPT: &str = "printf \"tmux=%s\\n\" \"$(command -v tmux)\"; \
31     printf \"tango=%s\\n\" \"$(tango attach --help >/dev/null 2>&1 && command -v tango)\"";
32
33/// Re-run the probe under the user's *login* shell so PATH additions from `.zprofile` /
34/// `.bash_profile` (Homebrew, `~/.cargo/bin`) are visible. `sh -c '<wrapper>' '<script>'`
35/// passes the script as `$0`, which sidesteps a second layer of quoting.
36const LOGIN_SHELL_WRAPPER: &str = "exec \"${SHELL:-/bin/sh}\" -l -c \"$0\"";
37
38#[derive(Debug, Clone, PartialEq)]
39pub enum HostState {
40    /// No poll has completed yet.
41    Loading,
42    Online {
43        sessions: Vec<TmuxSession>,
44        /// Windows keyed by session name, from one `list-windows -a` call.
45        windows: HashMap<Arc<str>, Vec<TmuxWindow>>,
46        /// Absolute path of the remote tmux binary.
47        tmux_path: String,
48        /// Absolute path of a remote tango with `attach`, if any.
49        tango_path: Option<String>,
50    },
51    /// ssh could not reach the host, or tmux failed there.
52    Offline { error: String },
53    /// ssh works but there is no tmux on the host.
54    NoTmux,
55}
56
57#[derive(Debug)]
58pub struct HostUpdate {
59    pub alias: Arc<str>,
60    pub state: HostState,
61}
62
63/// Owner handle for a poller thread. The thread exits at its next stop check; it is never
64/// joined, because a poller blocked in a 5 s ssh connect must not delay TUI shutdown.
65pub struct PollerHandle {
66    pub alias: Arc<str>,
67    stop: Arc<AtomicBool>,
68    wake: Arc<AtomicBool>,
69}
70
71impl PollerHandle {
72    pub fn stop(&self) {
73        self.stop.store(true, Ordering::Relaxed);
74    }
75
76    /// Cut the current sleep short and drop the failure backoff, so a host the user just
77    /// reconnected is re-polled now rather than up to `MAX_INTERVAL` later.
78    pub fn wake(&self) {
79        self.wake.store(true, Ordering::Relaxed);
80    }
81}
82
83impl Drop for PollerHandle {
84    fn drop(&mut self) {
85        self.stop();
86    }
87}
88
89/// What the probe found on a host.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct Probe {
92    pub tmux_path: Option<String>,
93    pub tango_path: Option<String>,
94}
95
96/// Outcome of one probe command, before the login-shell retry is considered.
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub enum ProbeOutcome {
99    /// ssh itself failed (exit 255, killed, or could not spawn).
100    Unreachable(String),
101    /// ssh ran the script; here is what it reported.
102    Ran(Probe),
103}
104
105/// Parse the probe script's stdout (`tmux=…` / `tango=…` lines). Empty values are absent.
106pub fn parse_probe_output(stdout: &str) -> Probe {
107    let mut probe = Probe { tmux_path: None, tango_path: None };
108    for line in stdout.lines() {
109        let Some((key, value)) = line.split_once('=') else { continue };
110        let value = value.trim();
111        let slot = match key.trim() {
112            "tmux" => &mut probe.tmux_path,
113            "tango" => &mut probe.tango_path,
114            _ => continue,
115        };
116        if !value.is_empty() {
117            *slot = Some(value.to_string());
118        }
119    }
120    probe
121}
122
123/// Interpret an ssh exit status plus captured output. ssh reserves exit 255 for its own
124/// failures; anything else is the remote command's status, and the script always exits 0.
125pub fn classify_probe(exit_code: Option<i32>, stdout: &str, stderr: &str) -> ProbeOutcome {
126    match exit_code {
127        Some(255) | None => ProbeOutcome::Unreachable(summarize_error(stderr)),
128        Some(_) => ProbeOutcome::Ran(parse_probe_output(stdout)),
129    }
130}
131
132/// Reduce an error blob to the single line a tree node can show: the first non-empty line,
133/// starting at `ssh:` when ssh is the one complaining, since the tmux prefixes our client
134/// wraps around it add nothing on a remote host.
135pub fn summarize_error(text: &str) -> String {
136    let line = text
137        .lines()
138        .map(str::trim)
139        .find(|l| !l.is_empty())
140        .unwrap_or("unknown error");
141    let line = line.find("ssh: ").map(|i| &line[i..]).unwrap_or(line);
142    line.to_string()
143}
144
145/// 5 s while healthy; on failure double the current wait up to 60 s.
146pub fn next_interval(current: Duration, ok: bool) -> Duration {
147    if ok {
148        BASE_INTERVAL
149    } else {
150        (current * 2).min(MAX_INTERVAL)
151    }
152}
153
154/// Start polling `alias` on its own thread. Updates arrive on `tx`; the thread exits when the
155/// handle is stopped/dropped or the receiver is gone.
156pub fn spawn_poller(alias: Arc<str>, tx: Sender<HostUpdate>) -> PollerHandle {
157    let stop = Arc::new(AtomicBool::new(false));
158    let wake = Arc::new(AtomicBool::new(false));
159    let (thread_stop, thread_wake) = (Arc::clone(&stop), Arc::clone(&wake));
160    let thread_alias = Arc::clone(&alias);
161    let thread_name = format!("tango-poll-{}", alias);
162    let spawned = thread::Builder::new()
163        .name(thread_name)
164        .spawn(move || poll_loop(thread_alias, tx, thread_stop, thread_wake));
165    if spawned.is_err() {
166        // Out of threads: leave the host in Loading forever rather than crash the TUI.
167        stop.store(true, Ordering::Relaxed);
168    }
169    PollerHandle { alias, stop, wake }
170}
171
172fn poll_loop(alias: Arc<str>, tx: Sender<HostUpdate>, stop: Arc<AtomicBool>, wake: Arc<AtomicBool>) {
173    let host = Host::remote(&alias);
174    let mut interval = BASE_INTERVAL;
175    let mut probe: Option<Probe> = None;
176
177    while !stop.load(Ordering::Relaxed) {
178        let state = poll_once(&host, &mut probe);
179        let ok = matches!(state, HostState::Online { .. });
180        if !ok {
181            // Paths may differ after a reinstall or reboot; re-probe once the host is back.
182            probe = None;
183        }
184        if tx.send(HostUpdate { alias: Arc::clone(&alias), state }).is_err() {
185            return;
186        }
187        interval = next_interval(interval, ok);
188        if sleep_until_stopped(interval, &stop, &wake) {
189            interval = BASE_INTERVAL;
190        }
191    }
192}
193
194/// One full poll: probe if needed, then list sessions and windows.
195fn poll_once(host: &Host, probe: &mut Option<Probe>) -> HostState {
196    if probe.is_none() {
197        match run_probe(host) {
198            Ok(found) => *probe = Some(found),
199            Err(state) => return state,
200        }
201    }
202    let Some(tmux_path) = probe.as_ref().and_then(|p| p.tmux_path.clone()) else {
203        return HostState::NoTmux;
204    };
205    let tango_path = probe.as_ref().and_then(|p| p.tango_path.clone());
206
207    let mut client = TmuxClient::for_host(host.clone()).with_program(&tmux_path);
208    let sessions = match client.list_sessions() {
209        Ok(sessions) => sessions,
210        Err(TmuxFzfError::NoSessions) => Vec::new(),
211        Err(e) => return HostState::Offline { error: summarize_error(&e.to_string()) },
212    };
213
214    // Best effort: a window listing failure should not hide the sessions we already have.
215    let mut windows: HashMap<Arc<str>, Vec<TmuxWindow>> = HashMap::new();
216    if !sessions.is_empty() {
217        if let Ok(pairs) = client.list_all_windows() {
218            for (session, window) in pairs {
219                windows.entry(session).or_default().push(window);
220            }
221        }
222    }
223
224    HostState::Online { sessions, windows, tmux_path, tango_path }
225}
226
227/// Probe under a plain `sh`, then under the login shell if tmux was not found the first time.
228fn run_probe(host: &Host) -> Result<Probe, HostState> {
229    let first = execute_probe(host, &["-c", PROBE_SCRIPT])?;
230    if first.tmux_path.is_some() {
231        return Ok(first);
232    }
233    let retry = execute_probe(host, &["-c", LOGIN_SHELL_WRAPPER, PROBE_SCRIPT])?;
234    if retry.tmux_path.is_some() {
235        Ok(retry)
236    } else {
237        Err(HostState::NoTmux)
238    }
239}
240
241fn execute_probe(host: &Host, sh_args: &[&str]) -> Result<Probe, HostState> {
242    let output = host
243        .command("sh", sh_args, false)
244        .stdin(std::process::Stdio::null())
245        .output()
246        .map_err(|e| HostState::Offline { error: format!("cannot run ssh: {}", e) })?;
247    let stdout = String::from_utf8_lossy(&output.stdout);
248    let stderr = String::from_utf8_lossy(&output.stderr);
249    match classify_probe(output.status.code(), &stdout, &stderr) {
250        ProbeOutcome::Unreachable(error) => Err(HostState::Offline { error }),
251        ProbeOutcome::Ran(probe) => Ok(probe),
252    }
253}
254
255/// Sleep `total`, ending early on a stop or a wake. Returns whether a wake ended it, and
256/// clears the flag so the next sleep is a full one.
257fn sleep_until_stopped(total: Duration, stop: &AtomicBool, wake: &AtomicBool) -> bool {
258    let mut slept = Duration::ZERO;
259    while slept < total && !stop.load(Ordering::Relaxed) {
260        if wake.swap(false, Ordering::Relaxed) {
261            return true;
262        }
263        let step = STOP_CHECK.min(total - slept);
264        thread::sleep(step);
265        slept += step;
266    }
267    wake.swap(false, Ordering::Relaxed)
268}
269
270/// Which remote pane a preview shows: `"<session>:"` (the session's current window) or
271/// `"<session>:<index>"`, on the host `host`.
272#[derive(Debug, Clone, PartialEq, Eq)]
273pub struct PreviewKey {
274    pub host: Arc<str>,
275    pub target: String,
276}
277
278#[derive(Debug, Clone)]
279pub struct PreviewRequest {
280    pub key: PreviewKey,
281    /// Absolute path of the remote tmux, from the host's `Online` snapshot.
282    pub tmux_path: String,
283}
284
285#[derive(Debug)]
286pub struct PreviewResult {
287    pub key: PreviewKey,
288    /// Pane content with escape sequences, or a one-line error.
289    pub content: Result<String, String>,
290}
291
292/// Start a capture worker for `alias`; send it requests on the returned `Sender`. The thread
293/// exits once that sender is dropped (after any in-flight ssh returns); it is never joined.
294pub fn spawn_previewer(alias: Arc<str>, results: Sender<PreviewResult>) -> Sender<PreviewRequest> {
295    let (tx, rx) = mpsc::channel();
296    let host = Host::remote(&alias);
297    let capture = move |req: &PreviewRequest| {
298        TmuxClient::for_host(host.clone())
299            .with_program(&req.tmux_path)
300            .capture_pane(&req.key.target)
301            .map_err(|e| summarize_error(&e.to_string()))
302    };
303    // Out of threads: the request sender just goes nowhere and the preview stays "loading".
304    let _ = thread::Builder::new()
305        .name(format!("tango-preview-{}", alias))
306        .spawn(move || preview_loop(rx, results, capture));
307    tx
308}
309
310/// Serve capture requests, newest first: everything queued behind the next request is
311/// skipped, so a cursor sweeping across many remote rows costs one capture, not one per row.
312fn preview_loop(
313    rx: Receiver<PreviewRequest>,
314    tx: Sender<PreviewResult>,
315    capture: impl Fn(&PreviewRequest) -> Result<String, String>,
316) {
317    while let Ok(mut req) = rx.recv() {
318        while let Ok(newer) = rx.try_recv() {
319            req = newer;
320        }
321        let content = capture(&req);
322        if tx.send(PreviewResult { key: req.key, content }).is_err() {
323            return;
324        }
325    }
326}
327
328#[cfg(test)]
329mod tests {
330    use super::*;
331
332    #[test]
333    fn next_interval_doubles_on_failure_and_caps_at_max() {
334        let mut d = BASE_INTERVAL;
335        let mut seen = Vec::new();
336        for _ in 0..6 {
337            d = next_interval(d, false);
338            seen.push(d.as_secs());
339        }
340        assert_eq!(seen, vec![10, 20, 40, 60, 60, 60]);
341    }
342
343    #[test]
344    fn next_interval_resets_to_base_on_success() {
345        assert_eq!(next_interval(MAX_INTERVAL, true), BASE_INTERVAL);
346        assert_eq!(next_interval(BASE_INTERVAL, true), BASE_INTERVAL);
347    }
348
349    #[test]
350    fn parse_probe_output_reads_both_paths() {
351        let probe = parse_probe_output("tmux=/usr/bin/tmux\ntango=/home/k/.cargo/bin/tango\n");
352        assert_eq!(probe.tmux_path.as_deref(), Some("/usr/bin/tmux"));
353        assert_eq!(probe.tango_path.as_deref(), Some("/home/k/.cargo/bin/tango"));
354    }
355
356    #[test]
357    fn parse_probe_output_treats_empty_value_as_absent() {
358        let probe = parse_probe_output("tmux=/usr/bin/tmux\ntango=\n");
359        assert_eq!(probe.tmux_path.as_deref(), Some("/usr/bin/tmux"));
360        assert_eq!(probe.tango_path, None);
361    }
362
363    #[test]
364    fn parse_probe_output_with_nothing_found() {
365        let probe = parse_probe_output("tmux=\ntango=\n");
366        assert_eq!(probe, Probe { tmux_path: None, tango_path: None });
367    }
368
369    #[test]
370    fn parse_probe_output_ignores_login_banner_noise() {
371        // A chatty .profile may print before our lines; only key=value lines count.
372        let probe = parse_probe_output("Welcome to box\ntmux=/opt/homebrew/bin/tmux\nfoo=bar\n");
373        assert_eq!(probe.tmux_path.as_deref(), Some("/opt/homebrew/bin/tmux"));
374        assert_eq!(probe.tango_path, None);
375    }
376
377    #[test]
378    fn classify_probe_exit_255_is_unreachable_with_ssh_message() {
379        let outcome = classify_probe(
380            Some(255),
381            "",
382            "ssh: connect to host box port 22: Connection refused\r\n",
383        );
384        assert_eq!(
385            outcome,
386            ProbeOutcome::Unreachable("ssh: connect to host box port 22: Connection refused".into())
387        );
388    }
389
390    #[test]
391    fn classify_probe_signal_death_is_unreachable() {
392        assert!(matches!(classify_probe(None, "", ""), ProbeOutcome::Unreachable(_)));
393    }
394
395    #[test]
396    fn classify_probe_exit_zero_parses_stdout() {
397        let outcome = classify_probe(Some(0), "tmux=/usr/bin/tmux\ntango=\n", "");
398        assert_eq!(
399            outcome,
400            ProbeOutcome::Ran(Probe { tmux_path: Some("/usr/bin/tmux".into()), tango_path: None })
401        );
402    }
403
404    #[test]
405    fn summarize_error_takes_first_nonempty_line_from_ssh() {
406        let text = "tmux error: tmux list-sessions failed: ssh: Could not resolve hostname box: nodename nor servname provided\nsecond line";
407        assert_eq!(
408            summarize_error(text),
409            "ssh: Could not resolve hostname box: nodename nor servname provided"
410        );
411    }
412
413    #[test]
414    fn summarize_error_keeps_non_ssh_lines_and_handles_empty() {
415        assert_eq!(summarize_error("\n  server exited unexpectedly  \n"), "server exited unexpectedly");
416        assert_eq!(summarize_error(""), "unknown error");
417    }
418
419    fn handle() -> PollerHandle {
420        PollerHandle {
421            alias: "box".into(),
422            stop: Arc::new(AtomicBool::new(false)),
423            wake: Arc::new(AtomicBool::new(false)),
424        }
425    }
426
427    #[test]
428    fn poller_handle_stop_flag_is_observed() {
429        let handle = handle();
430        let (stop, wake) = (Arc::clone(&handle.stop), Arc::clone(&handle.wake));
431        let started = std::time::Instant::now();
432        let sleeper = thread::spawn(move || sleep_until_stopped(Duration::from_secs(30), &stop, &wake));
433        drop(handle);
434        let woken = sleeper.join().unwrap();
435        assert!(started.elapsed() < Duration::from_secs(5), "drop must wake the sleeper promptly");
436        assert!(!woken, "a stop is not a wake");
437    }
438
439    #[test]
440    fn wake_cuts_a_backoff_sleep_short_exactly_once() {
441        let handle = handle();
442        let (stop, wake) = (Arc::clone(&handle.stop), Arc::clone(&handle.wake));
443        let started = std::time::Instant::now();
444        let sleeper = thread::spawn(move || {
445            let first = sleep_until_stopped(MAX_INTERVAL, &stop, &wake);
446            let after_first = started.elapsed();
447            // A flag left set would turn every later sleep into a 250 ms spin against ssh.
448            let second = sleep_until_stopped(Duration::from_millis(600), &stop, &wake);
449            (first, after_first, second, started.elapsed())
450        });
451        thread::sleep(Duration::from_millis(100));
452        handle.wake();
453        let (first, after_first, second, total) = sleeper.join().unwrap();
454        assert!(first, "wake must report itself so poll_loop resets the backoff");
455        assert!(after_first < Duration::from_secs(2), "woke after {:?}", after_first);
456        assert!(!second, "the wake flag must be consumed by the first sleep");
457        assert!(total - after_first >= Duration::from_millis(600), "second sleep cut short: {:?}", total - after_first);
458    }
459
460    #[test]
461    fn preview_loop_skips_requests_superseded_while_a_capture_runs() {
462        let request = |target: &str| PreviewRequest {
463            key: PreviewKey { host: "box".into(), target: target.to_string() },
464            tmux_path: "/usr/bin/tmux".to_string(),
465        };
466        let (req_tx, req_rx) = mpsc::channel();
467        let (res_tx, res_rx) = mpsc::channel();
468        let (started_tx, started_rx) = mpsc::channel();
469        let (release_tx, release_rx) = mpsc::channel::<()>();
470        let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
471
472        let worker = {
473            let captured = Arc::clone(&captured);
474            thread::spawn(move || {
475                preview_loop(req_rx, res_tx, |req| {
476                    captured.lock().unwrap().push(req.key.target.clone());
477                    if req.key.target == "a:" {
478                        // Stand in for a slow ssh round trip on the first capture.
479                        started_tx.send(()).unwrap();
480                        release_rx.recv().unwrap();
481                    }
482                    Ok(format!("content of {}", req.key.target))
483                })
484            })
485        };
486
487        req_tx.send(request("a:")).unwrap();
488        started_rx.recv().unwrap();
489        for target in ["b:", "c:1", "d:"] {
490            req_tx.send(request(target)).unwrap();
491        }
492        release_tx.send(()).unwrap();
493        drop(req_tx);
494        worker.join().unwrap();
495
496        let captured = captured.lock().unwrap().clone();
497        assert_eq!(captured, vec!["a:", "d:"], "only the newest queued request should be captured");
498        let results: Vec<(String, Result<String, String>)> =
499            res_rx.try_iter().map(|r| (r.key.target, r.content)).collect();
500        assert_eq!(
501            results,
502            vec![
503                ("a:".to_string(), Ok("content of a:".to_string())),
504                ("d:".to_string(), Ok("content of d:".to_string())),
505            ],
506            "each capture must report back under its own key"
507        );
508    }
509
510    #[test]
511    fn probe_script_is_single_quote_free() {
512        // The script travels inside one single-quoted ssh argument and then inside
513        // `sh -c '...'`; a stray `'` would break both layers.
514        assert!(!PROBE_SCRIPT.contains('\''), "{}", PROBE_SCRIPT);
515        assert!(!LOGIN_SHELL_WRAPPER.contains('\''), "{}", LOGIN_SHELL_WRAPPER);
516    }
517}