Cotton code
200 lines · 6.9 KB · RustRaw
//! `<dataDir>/sessions/index.json` — what `list` answers from after a restart.//!//! A DAEMON RESTART ENDS ITS CHILDREN. The pseudo-terminals are owned by this//! process and nothing re-parents them, so every session this file remembers//! from a previous run is `ended`, its scrollback still readable and its agent//! gone. The index exists so that is a STATE somebody can see rather than a//! session that vanished: `list` keeps answering for it, and the phone's card//! shows the last thing it said.//!//! The file is rewritten whole on every change (write beside, then rename), a//! few kilobytes at a time. There is no second writer: one daemon per data//! directory, refused at the socket.use std::collections::BTreeMap;use std::path::{Path, PathBuf};use serde::{Deserialize, Serialize};use crate::protocol::Tool;/// One remembered session.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct IndexEntry {    /// The host's id.    pub id: String,    /// Which agent.    pub tool: Tool,    /// The launch it answered. EMPTY for an adopted session — nobody    /// launched it.    #[serde(default)]    pub launch_id: String,    /// The agent's own session id, once it is known.    #[serde(default)]    pub agent_session_id: Option<String>,    /// Where it ran.    pub cwd: String,    /// RFC 3339.    pub started_at: String,    /// RFC 3339, once it ended.    #[serde(default)]    pub ended_at: Option<String>,    /// How it ended.    #[serde(default)]    pub exit: Option<Exit>,    /// Whether this host found the session rather than spawning it.    ///    /// An adopted session has no pseudo-terminal here, so a restart of this    /// daemon does not end it — see [`Index::end_everything_left_running`].    #[serde(default)]    pub adopted: bool,}/// How a session's process went away.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]pub struct Exit {    /// The exit code, when it had one.    pub code: Option<i32>,    /// The signal that ended it, when one did.    pub signal: Option<i32>,}/// The whole file.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]pub struct Index {    /// Oldest first.    #[serde(default)]    pub sessions: Vec<IndexEntry>,}/// What can go wrong reading or writing it.#[derive(Debug, thiserror::Error)]pub enum IndexError {    /// The file is there and is not this file.    ///    /// Named rather than replaced with an empty index: silently starting over    /// would delete the person's session history to make a bug go away.    #[error("{path} is not a session index this host wrote — {source}")]    NotAnIndex {        /// Which file.        path: PathBuf,        /// What serde said.        source: serde_json::Error,    },    /// The disk.    #[error("the session index at {path}: {source}")]    Io {        /// Which file.        path: PathBuf,        /// What the operating system said.        source: std::io::Error,    },}impl Index {    /// Read it. A file that is not there is an empty index — a host that has    /// never run has no sessions, which is a fact and not a failure.    pub fn load(path: &Path) -> Result<Self, IndexError> {        let text = match std::fs::read_to_string(path) {            Ok(text) => text,            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Self::default()),            Err(source) => {                return Err(IndexError::Io {                    path: path.to_path_buf(),                    source,                })            }        };        serde_json::from_str(&text).map_err(|source| IndexError::NotAnIndex {            path: path.to_path_buf(),            source,        })    }    /// Write it, beside then renamed.    pub fn save(&self, path: &Path) -> Result<(), IndexError> {        let io = |source: std::io::Error| IndexError::Io {            path: path.to_path_buf(),            source,        };        if let Some(parent) = path.parent() {            std::fs::create_dir_all(parent).map_err(io)?;        }        let text = serde_json::to_string_pretty(self).map_err(|source| IndexError::NotAnIndex {            path: path.to_path_buf(),            source,        })?;        let beside = path.with_extension("json.writing");        std::fs::write(&beside, text.as_bytes()).map_err(io)?;        std::fs::rename(&beside, path).map_err(io)?;        Ok(())    }    /// Add a session, or replace the entry with the same id.    pub fn upsert(&mut self, entry: IndexEntry) {        match self.sessions.iter_mut().find(|held| held.id == entry.id) {            Some(held) => *held = entry,            None => self.sessions.push(entry),        }    }    /// Stamp a session ended. An id this index does not know is a no-op that    /// ANSWERS so, rather than inventing a row for a session nobody started.    pub fn end(&mut self, id: &str, at: &str, exit: Exit) -> bool {        match self.sessions.iter_mut().find(|held| held.id == id) {            Some(held) => {                held.ended_at = Some(at.to_string());                held.exit = Some(exit);                true            }            None => false,        }    }    /// Mark every session this index remembers as ended, at `at`.    ///    /// What a daemon calls on the way UP, over what a previous daemon left:    /// those children are gone, and an entry still reading `running` would be    /// a card on the phone waiting for a process that no longer exists. The    /// exit is `{code: null, signal: null}` because nobody was there to reap    /// it — an honest "we do not know", never a fabricated 0.    ///    /// **An ADOPTED session is left alone.** This host never owned its    /// process, so a restart here took nothing away from it: its transcript is    /// still being written and the first scan of the new run reads the state    /// straight back out of it. Ending it would be this host claiming to have    /// killed something it cannot even see.    pub fn end_everything_left_running(&mut self, at: &str) -> usize {        let mut ended = 0;        for held in &mut self.sessions {            if held.adopted {                continue;            }            if held.ended_at.is_none() {                held.ended_at = Some(at.to_string());                held.exit = Some(Exit {                    code: None,                    signal: None,                });                ended += 1;            }        }        ended    }    /// The agent session ids this index knows, by host id.    pub fn agent_session_ids(&self) -> BTreeMap<String, String> {        self.sessions            .iter()            .filter_map(|held| {                held.agent_session_id                    .as_ref()                    .map(|agent| (held.id.clone(), agent.clone()))            })            .collect()    }}#[cfg(test)]#[path = "index_tests.rs"]mod index_tests;