Cotton code
208 lines · 8.0 KB · RustRaw
//! `cotton-session-host sessions` — **WHAT IS ALIVE ON THIS MAC, ASKED//! WITHOUT CHANGING ANYTHING.**//!//! `restart` exists for the app's question "is the running helper mine", and//! asking it puts `Request::Restart` on the wire. That is the wrong question//! to ask FIRST, and 2026-09-24 is why: the owner's session was mid-work when//! a release install relaunched the app, the app replaced the helper's launchd//! registration, `launchctl kickstart -k` ended the daemon, the pseudo-terminal//! master closed and the agent took a SIGHUP. Nothing wrote `ended`; the row//! sat `idle` for ever.//!//! **A live session outranks an update**, and the only way anything can apply//! that rule is to know the count BEFORE it acts. This subcommand is that//! question and nothing else: one `list`, no restart, no stop — the socket is//! read and the answer is one JSON line.//!//! `--end` is the deliberate exception, and it is never the default: it asks//! the helper to `stop` each live host-owned session, which is the ordinary//! end a session gets when a person withdraws it, exit code and all. The//! install lane passes it only behind `--end-sessions`//! (`apps/cotton/scripts/install-mac-release.sh`).//!//! **An ADOPTED session is never counted and never stopped.** It is somebody's//! own terminal that this host merely watches (`host_owned = false`); ending//! it is not this command's business, and holding an update for it would hold//! one for ever.//!//! The wording is decided HERE, for the same reason `restart` decides its own://! the Swift page, the boot log and the install script read one sentence//! rather than three wordings of it.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, SessionSummary};/// How long each question to the helper is given.////// A `list` is a map walk behind a mutex, so this is generous by design: the/// caller is an app at launch or an install lane about to quit an app, and/// both would rather wait five seconds than guess.pub const ASK_TIMEOUT: Duration = Duration::from_secs(5);/// What this command found.#[derive(Debug, Clone, Default, PartialEq)]pub struct Report {    /// The host-owned sessions that are still alive, newest last.    pub live: Vec<SessionSummary>,    /// The ids `--end` asked the helper to stop.    pub ended: Vec<String>,    /// Why the helper could not be asked at all. `None` when it answered.    ///    /// **An unreachable helper owns no pseudo-terminal**, so it holds nothing    /// up: a caller reads `live` as empty and carries on. The clause is here    /// for the operator, not for the decision.    pub said: Option<String>,}/// **IS THIS ONE OF THE SESSIONS AN UPDATE MUST WAIT FOR?** Pure.////// Host-owned and not `ended` — the same two facts `Host::host_owned_alive`/// counts, spelled once here because three callers now read them.pub fn is_live(session: &SessionSummary) -> bool {    session.host_owned && session.state != crate::protocol::SessionState::Ended}/// The live ones, in the order `list` gave them.pub fn live(sessions: &[SessionSummary]) -> Vec<SessionSummary> {    sessions.iter().filter(|s| is_live(s)).cloned().collect()}/// **THE ONE WORDING.** Pure, so the sentence is held by a test.////// The clause alone, with no `Session host:` in front of it — the rule every/// other sentence about this helper keeps.pub fn sentence(report: &Report) -> String {    if let Some(said) = &report.said {        return format!("this Mac's helper could not be asked what is running — {said}");    }    if !report.ended.is_empty() {        return format!("{} session(s) ended on this Mac", report.ended.len());    }    match report.live.len() {        0 => "no sessions are running on this Mac".to_string(),        n => format!("{n} session(s) running on this Mac"),    }}/// The one line this command prints, which is the whole of its interface.////// camelCase because one reader is Swift/// (`apps/cotton/Sources/CottonHost/SessionHostAgent.swift`) and the other is/// bash reading it with `grep`/`sed`, so `"live":` is spelled with no space/// after the colon by `serde_json` and both can find it.pub fn answer(report: &Report) -> String {    serde_json::json!({        "live": report.live.len(),        "reachable": report.said.is_none(),        "sessions": report            .live            .iter()            .map(|s| serde_json::json!({                "sessionId": s.session_id,                "tool": s.tool,                "state": s.state,                "cwd": s.cwd,            }))            .collect::<Vec<_>>(),        "ended": report.ended,        "line": sentence(report),    })    .to_string()}/// Ask the helper on `socket` what it is holding, and — only with `end` —/// ask it to stop each of them.pub async fn run(socket: &Path, end: bool) -> Report {    let mut report = Report::default();    let stream = match tokio::time::timeout(ASK_TIMEOUT, UnixStream::connect(socket)).await {        Ok(Ok(stream)) => stream,        Ok(Err(error)) => {            report.said = Some(format!("{} — {error}", socket.display()));            return report;        }        Err(_) => {            report.said = Some(format!("{} did not accept a connection", socket.display()));            return report;        }    };    let (read, mut write) = stream.into_split();    let mut reader = BufReader::new(read);    match ask(&mut reader, &mut write, &Request::List).await {        Ok(Event::Sessions { sessions }) => report.live = live(&sessions),        Ok(other) => {            report.said = Some(format!("it answered a list with {}", named(&other)));            return report;        }        Err(said) => {            report.said = Some(said);            return report;        }    }    if !end {        return report;    }    // ONE `stop` EACH, and the answers are not waited on one by one: `stop`    // runs SIGINT → SIGTERM → SIGKILL on the pty's own schedule    // (`crate::pty::StopSchedule`), so what this command reports is what it    // ASKED for. The caller re-asks (with no `--end`) to see it land, which is    // the shape the install lane wants anyway.    for session in &report.live {        let request = Request::Stop {            session_id: session.session_id.clone(),        };        match ask(&mut reader, &mut write, &request).await {            Ok(_) => report.ended.push(session.session_id.clone()),            Err(said) => {                report.said = Some(said);                break;            }        }    }    report}/// Put one request on the wire and read the one answer it earns.async fn ask(    reader: &mut BufReader<tokio::net::unix::OwnedReadHalf>,    write: &mut tokio::net::unix::OwnedWriteHalf,    request: &Request,) -> Result<Event, String> {    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::<Event>(&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 = "sessions_tests.rs"]mod sessions_tests;