//! `cotton-session-host restart` — the BUNDLED binary asking the RUNNING one //! whether it is still the same program. //! //! The app cannot answer this question by itself. It would have to speak the //! helper's socket protocol in Swift, which `PROTOCOL.md` forbids outright — //! one implementation, and a second serde definition of the same wire is the //! drift that rule exists to prevent. So the app runs the binary it SHIPS, //! from `Contents/Helpers/cotton-session-host`, and that binary knows two //! things nothing else does at once: what it is (`HOST_VERSION` and its own //! file's fingerprint) and what the daemon on the socket says it is. //! //! Four answers, and every one of them is a sentence a person reads on //! Settings › This Mac › Serving: //! //! | verdict | what happened | //! |---|---| //! | `current` | the helper is this binary. Nothing to do. | //! | `restarting` | it is an older one and it is exiting now; launchd's `KeepAlive` starts this one. | //! | `deferred` | it is an older one, sessions are alive, and it restarts when the last one ends. | //! | `unreachable` | nothing answered the socket. The app falls back to `launchctl kickstart -k`. | //! //! **The wording is decided HERE**, so the log line and the page's sentence //! are one string rather than two wordings of the same answer in two //! languages — the rule `CodeCredentialEnrolment` keeps on the Swift side. use std::path::Path; use std::time::Duration; use tokio::io::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader}; use tokio::net::UnixStream; use crate::protocol::{line, parse, Event, Request}; /// How long each question to the helper is given. /// /// A `sample` re-detects the agents, which runs `claude --version` and /// `codex --version` as subprocesses; ten seconds is far above what those cost /// and far below anything a person waits through at launch. pub const ASK_TIMEOUT: Duration = Duration::from_secs(10); /// What a helper says it is. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Reported { /// `HOST_VERSION` — the app's version on a shipped build. pub version: String, /// The executable's fingerprint ([`crate::binary::Fingerprint::short`]), /// empty when the binary could not be stat'ed. pub fingerprint: String, } /// **IS THE RUNNING HELPER THIS BINARY?** Pure, so both halves of the answer /// are tests. /// /// The VERSION alone is not enough — a rebuild at the same version is a /// different program, and the whole of a development loop is exactly that. The /// FINGERPRINT alone is not enough either: a helper old enough to predate the /// field reports none, and reading an empty string as "different" would ask /// every such helper to restart on every launch for ever. So: a version that /// differs is stale, and a fingerprint that differs is stale when BOTH ends /// have one. pub fn is_stale(helper: &Reported, bundled: &Reported) -> bool { if helper.version != bundled.version { return true; } !helper.fingerprint.is_empty() && !bundled.fingerprint.is_empty() && helper.fingerprint != bundled.fingerprint } /// What the subcommand decided. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Outcome { /// The helper is this binary. Current, /// It is exiting now. Restarting, /// It restarts when the last of these sessions ends. Deferred { /// How many host-owned sessions are holding it. sessions_running: u32, }, /// It could not be asked at all: nothing is listening on the socket, or /// what is listening is too old to know the verb — which is the helper /// this whole path exists for. Either way the app's answer is /// `launchctl kickstart -k`, so they are one outcome. Unreachable { /// The sentence for the log, never for the page. said: String, }, } impl Outcome { /// The word the app switches on. pub fn verdict(&self) -> &'static str { match self { Outcome::Current => "current", Outcome::Restarting => "restarting", Outcome::Deferred { .. } => "deferred", Outcome::Unreachable { .. } => "unreachable", } } } /// **THE ONE WORDING.** Pure, so the sentence is held by a test. /// /// The clause alone, with no `Session host:` in front of it: the page puts a /// capitalised prefix on and the boot log puts a lowercase one on, exactly as /// they already do for every other sentence about this helper. pub fn sentence(outcome: &Outcome, helper: &Reported, bundled: &Reported) -> String { match outcome { Outcome::Current => format!("helper {}, current", shown(&bundled.version)), Outcome::Restarting => format!( "helper {}, restarting for {}", shown(&helper.version), shown(&bundled.version) ), Outcome::Deferred { sessions_running } => format!( "restart pending: {sessions_running} session(s) running, helper {} for {}", shown(&helper.version), shown(&bundled.version) ), // It reads the same for a socket nothing is listening on and for a // helper too old to know the verb, because the app does the same // thing about both: `launchctl kickstart -k`. The reason is in the // clause, which is the part an operator reads. Outcome::Unreachable { said } => { format!("this Mac's helper could not be asked to restart — {said}; asking launchd for a fresh one") } } } /// A version nobody reported still reads as something. fn shown(version: &str) -> &str { if version.is_empty() { "an unknown version" } else { version } } /// The one line this command prints, which is the whole of its interface. /// /// camelCase because the reader is Swift, and `JSONSerialization` on the other /// end reads exactly these five keys /// (`apps/cotton/Sources/CottonHost/SessionHostAgent.swift`). pub fn answer(outcome: &Outcome, helper: &Reported, bundled: &Reported) -> String { let sessions = match outcome { Outcome::Deferred { sessions_running } => *sessions_running, _ => 0, }; serde_json::json!({ "verdict": outcome.verdict(), "helperVersion": helper.version, "bundledVersion": bundled.version, "sessionsRunning": sessions, "line": sentence(outcome, helper, bundled), }) .to_string() } /// What this binary is. pub fn bundled(exe: Option<&Path>) -> Reported { Reported { version: crate::HOST_VERSION.to_string(), fingerprint: exe .and_then(crate::binary::read) .map(crate::binary::Fingerprint::short) .unwrap_or_default(), } } /// Ask the helper on `socket` what it is, and ask it to restart when it is not /// this binary. /// /// Answers the outcome and what the helper said about itself — the caller /// prints both. pub async fn run(socket: &Path, bundled: &Reported) -> (Outcome, Reported) { let mut helper = Reported::default(); let stream = match tokio::time::timeout(ASK_TIMEOUT, UnixStream::connect(socket)).await { Ok(Ok(stream)) => stream, Ok(Err(error)) => { return ( Outcome::Unreachable { said: format!("{} — {error}", socket.display()), }, helper, ) } Err(_) => { return ( Outcome::Unreachable { said: format!("{} did not accept a connection", socket.display()), }, helper, ) } }; let (read, mut write) = stream.into_split(); let mut reader = BufReader::new(read); match ask(&mut reader, &mut write, &Request::Sample).await { Ok(Event::Sample { sample }) => { helper = Reported { version: sample.host_version.clone(), fingerprint: sample.binary_fingerprint.clone(), }; } Ok(other) => { return ( Outcome::Unreachable { said: format!("it answered a sample with {}", named(&other)), }, helper, ) } Err(said) => return (Outcome::Unreachable { said }, helper), } if !is_stale(&helper, bundled) { return (Outcome::Current, helper); } match ask(&mut reader, &mut write, &Request::Restart).await { Ok(Event::Restarting { restarting, sessions_running, }) => { let outcome = if restarting { Outcome::Restarting } else { Outcome::Deferred { sessions_running } }; (outcome, helper) } // A HELPER TOO OLD TO KNOW THE VERB refuses the line by name, which // is the stale helper this whole path exists for. It is grouped with // the unreachable ones because the app does the same thing about both // — `launchctl kickstart -k` — and the reason stays in the clause. Ok(Event::Error { message }) => ( Outcome::Unreachable { said: format!("it refused a restart — {message}"), }, helper, ), Ok(other) => ( Outcome::Unreachable { said: format!("it answered a restart with {}", named(&other)), }, helper, ), Err(said) => (Outcome::Unreachable { said }, helper), } } /// Put one request on the wire and read the one answer it earns. async fn ask( reader: &mut BufReader, write: &mut tokio::net::unix::OwnedWriteHalf, request: &Request, ) -> Result { let text = line(request).map_err(|error| error.to_string())?; write .write_all(text.as_bytes()) .await .map_err(|error| format!("the request did not go — {error}"))?; write .flush() .await .map_err(|error| format!("the request did not go — {error}"))?; let mut answer = String::new(); match tokio::time::timeout(ASK_TIMEOUT, reader.read_line(&mut answer)).await { Ok(Ok(0)) => Err("it closed the socket without answering".to_string()), Ok(Ok(_)) => parse::(&answer).map_err(|error| error.to_string()), Ok(Err(error)) => Err(format!("the socket went — {error}")), Err(_) => Err(format!( "it did not answer within {} ms", ASK_TIMEOUT.as_millis() )), } } /// An event's tag, for a sentence that has to name what arrived instead. fn named(event: &Event) -> String { serde_json::to_value(event) .ok() .and_then(|value| value.get("t")?.as_str().map(str::to_string)) .unwrap_or_else(|| "something this command does not understand".to_string()) } #[cfg(test)] #[path = "restart_tests.rs"] mod restart_tests;