//! Each machine's connection gate (MACH-014, MACH-015): work for a remote machine follows the //! machine's connection state instead of retrying on its own. //! //! The front end's supervisor (`MachineConnection`, `ui/src/services/machines.ts`) is the only //! thing that decides whether a machine is reachable. It reports every change with //! `machine_set_reachable` (open while the machine is connected with its daemon running). While a //! machine's gate is closed: //! //! - [`super::relay::SshRelayConnector::open`] refuses at once with //! [`DaemonError::NotRunning`], starting no `ssh.exe`, so one-shot requests (`machine_request`, //! file and git host calls) fail fast instead of logging in; //! - the remote retry loops (status and grid subscriptions, attach sessions) wait in //! [`MachineGate::resume`] and start again a uniformly random 0–1 s after it opens, so a //! reconnect does not log in every stream at the same instant. //! //! A failure while the gate is still open (the link dropped, but the supervisor has not probed //! yet) also waits: [`MachineGate::suspect`] asks the supervisor to probe now (the //! `machine-suspect` event, at most once per [`SUSPECT_INTERVAL`] per machine), and the loop //! resumes only once a probe newer than its failed attempt has reached the daemon //! ([`GateState::confirmed`]). One probe then answers for every stream on the machine. //! //! The registry is process-wide ([`registry`]): every connector for a machine (the shared //! [`super::machine::MachineClients`] one, and the git host's own) sees the same gate. A machine //! the supervisor has not reported yet is closed. The local daemon has no gate. use std::collections::HashMap; use std::sync::{Arc, Mutex, OnceLock}; use std::time::{Duration, Instant}; use tokio::sync::watch; use super::client::DaemonError; /// The longest resume jitter: streams resume spread over this much time (MACH-014). pub const RESUME_JITTER_MAX: Duration = Duration::from_secs(1); /// How often a machine may ask its supervisor for an early probe. pub const SUSPECT_INTERVAL: Duration = Duration::from_secs(5); /// A machine's reported reachability. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct GateState { /// The supervisor reports the machine connected with its daemon running. pub open: bool, /// Bumped by every probe that reached the daemon (and by opening the gate): a loop that /// failed at `confirmed == n` retries once `confirmed > n`. pub confirmed: u64, } impl GateState { /// Whether a loop whose last attempt failed at `after` (or that has not failed: `None`) /// may try again. pub fn allows(self, after: Option) -> bool { self.open && after.is_none_or(|ticket| self.confirmed > ticket) } } /// The resume jitter for a uniform sample `unit` in [0, 1]: 0–1 s. pub fn resume_delay(unit: f64) -> Duration { RESUME_JITTER_MAX.mul_f64(if unit.is_finite() { unit.clamp(0.0, 1.0) } else { 0.0 }) } /// A uniform sample in [0, 1) from the OS random source (through a v4 UUID's random bits). pub fn random_unit() -> f64 { const BITS: u32 = 53; let random = uuid::Uuid::new_v4().as_u128() as u64 & ((1 << BITS) - 1); random as f64 / (1u64 << BITS) as f64 } type SuspectHook = Arc; struct Inner { machine_id: String, state: watch::Sender, last_suspect: Mutex>, on_suspect: Option, } /// One machine's gate. Cheap to clone; clones share the state. #[derive(Clone)] pub struct MachineGate { inner: Arc, } impl std::fmt::Debug for MachineGate { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("MachineGate") .field("machine_id", &self.inner.machine_id) .field("state", &self.state()) .finish() } } impl MachineGate { /// A closed gate for `machine_id` with no supervisor hook (tests). pub fn new(machine_id: &str) -> Self { Self::with_hook(machine_id, None) } fn with_hook(machine_id: &str, on_suspect: Option) -> Self { Self { inner: Arc::new(Inner { machine_id: machine_id.to_ascii_lowercase(), state: watch::Sender::new(GateState::default()), last_suspect: Mutex::new(None), on_suspect, }), } } pub fn machine_id(&self) -> &str { &self.inner.machine_id } pub fn state(&self) -> GateState { *self.inner.state.borrow() } pub fn is_open(&self) -> bool { self.state().open } /// The supervisor's verdict. Opening counts as a confirmation: it follows a probe that /// reached the daemon. pub fn set_open(&self, open: bool) { self.inner.state.send_modify(|state| { if open && !state.open { state.confirmed += 1; } state.open = open; }); } /// A probe reached the machine's daemon. pub fn confirm(&self) { self.inner.state.send_modify(|state| state.confirmed += 1); } /// The error a closed gate gives a connection attempt. pub fn closed_error(&self) -> DaemonError { DaemonError::NotRunning(format!( "Machine {} is not connected; waiting for it to reconnect", self.inner.machine_id )) } /// Ask the supervisor for an early probe, at most once per [`SUSPECT_INTERVAL`]. pub fn suspect(&self) { let Some(hook) = &self.inner.on_suspect else { return; }; let now = Instant::now(); { let mut last = self .inner .last_suspect .lock() .unwrap_or_else(|p| p.into_inner()); if last.is_some_and(|at| now.duration_since(at) < SUSPECT_INTERVAL) { return; } *last = Some(now); } hook(&self.inner.machine_id); } /// Wait until the gate allows an attempt (see [`GateState::allows`]); true when it had to /// wait. pub async fn wait(&self, after: Option) -> bool { if self.state().allows(after) { return false; } let mut rx = self.inner.state.subscribe(); // The sender lives as long as `self`, so this only ends when the gate allows it. let _ = rx.wait_for(|state| state.allows(after)).await; true } /// Before an attempt: wait while the gate does not allow one, then (only if it had to /// wait) sleep the resume jitter, so the machine's streams do not all log in at once. /// `after` is the [`GateState::confirmed`] the previous attempt failed at, if it failed; /// a failure first asks the supervisor to probe. pub async fn resume(&self, after: Option) { if after.is_some() && !self.state().allows(after) { self.suspect(); } if self.wait(after).await { tokio::time::sleep(resume_delay(random_unit())).await; } } } /// Every machine's gate, by lowercased id. #[derive(Default)] pub struct MachineGates { gates: Mutex>, on_suspect: OnceLock, } impl MachineGates { /// The gate for `machine_id`, created closed. pub fn gate(&self, machine_id: &str) -> MachineGate { let key = machine_id.to_ascii_lowercase(); let hook = self.on_suspect.get().cloned(); self.gates .lock() .unwrap_or_else(|p| p.into_inner()) .entry(key) .or_insert_with(|| MachineGate::with_hook(machine_id, hook)) .clone() } /// Where [`MachineGate::suspect`] goes (the app emits `machine-suspect`). Set once, before /// any gate exists; later calls are ignored. pub fn set_suspect_hook(&self, hook: impl Fn(&str) + Send + Sync + 'static) { let _ = self.on_suspect.set(Arc::new(hook)); } } /// The process-wide registry. pub fn registry() -> &'static MachineGates { static GATES: OnceLock = OnceLock::new(); GATES.get_or_init(MachineGates::default) } #[cfg(test)] mod tests { use super::*; use std::sync::atomic::{AtomicUsize, Ordering}; #[test] fn given_samples_should_jitter_between_zero_and_one_second() { assert_eq!(resume_delay(0.0), Duration::ZERO); assert_eq!(resume_delay(0.5), Duration::from_millis(500)); assert_eq!(resume_delay(1.0), Duration::from_secs(1)); assert_eq!(resume_delay(7.0), Duration::from_secs(1)); assert_eq!(resume_delay(-1.0), Duration::ZERO); assert_eq!(resume_delay(f64::NAN), Duration::ZERO); for _ in 0..100 { let unit = random_unit(); assert!((0.0..1.0).contains(&unit), "{unit}"); } } #[test] fn given_gate_state_should_allow_only_open_and_newer_confirmations() { let closed = GateState { open: false, confirmed: 3, }; let open = GateState { open: true, confirmed: 3, }; assert!(!closed.allows(None)); assert!(open.allows(None)); assert!(open.allows(Some(2))); assert!(!open.allows(Some(3))); assert!(!closed.allows(Some(2))); } #[test] fn given_opening_should_count_as_a_confirmation() { let gate = MachineGate::new("M1"); assert_eq!(gate.machine_id(), "m1"); assert_eq!(gate.state(), GateState::default()); gate.set_open(true); assert_eq!( gate.state(), GateState { open: true, confirmed: 1 } ); // Already open: no new confirmation. gate.set_open(true); gate.confirm(); assert_eq!(gate.state().confirmed, 2); gate.set_open(false); assert!(!gate.is_open()); assert!(matches!(gate.closed_error(), DaemonError::NotRunning(_))); } #[test] fn given_registry_should_share_one_gate_per_machine_in_any_case() { let gates = MachineGates::default(); gates.gate("ABC").set_open(true); assert!(gates.gate("abc").is_open()); assert!(!gates.gate("other").is_open()); } #[test] fn given_repeated_suspicion_should_ask_the_supervisor_once_per_interval() { let gates = MachineGates::default(); let calls = Arc::new(AtomicUsize::new(0)); let counted = calls.clone(); gates.set_suspect_hook(move |id| { assert_eq!(id, "m1"); counted.fetch_add(1, Ordering::SeqCst); }); let gate = gates.gate("m1"); gate.suspect(); gate.suspect(); gates.gate("M1").suspect(); assert_eq!(calls.load(Ordering::SeqCst), 1); } #[tokio::test(start_paused = true)] async fn given_closed_gate_should_resume_after_it_opens_with_at_most_one_second_of_jitter() { let gate = MachineGate::new("m1"); let waiter = { let gate = gate.clone(); tokio::spawn(async move { gate.resume(None).await; tokio::time::Instant::now() }) }; tokio::time::sleep(Duration::from_secs(30)).await; assert!(!waiter.is_finished()); let opened = tokio::time::Instant::now(); gate.set_open(true); let resumed = waiter.await.unwrap(); assert!(resumed - opened <= RESUME_JITTER_MAX); } #[tokio::test(start_paused = true)] async fn given_open_gate_should_not_delay_a_first_attempt() { let gate = MachineGate::new("m1"); gate.set_open(true); let before = tokio::time::Instant::now(); gate.resume(None).await; assert_eq!(tokio::time::Instant::now(), before); } #[tokio::test(start_paused = true)] async fn given_a_failure_while_open_should_wait_for_a_newer_probe() { let gate = MachineGate::new("m1"); gate.set_open(true); let ticket = gate.state().confirmed; let waiter = { let gate = gate.clone(); tokio::spawn(async move { gate.resume(Some(ticket)).await }) }; tokio::time::sleep(Duration::from_secs(5)).await; assert!(!waiter.is_finished()); gate.confirm(); waiter.await.unwrap(); } }