//! `<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};usecrate::protocol::Tool;/// One remembered session.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pubstructIndexEntry {/// 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)]pubstructExit {/// 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)]pubstructIndex {/// Oldest first. #[serde(default)]pub sessions: Vec<IndexEntry>,}/// What can go wrong reading or writing it.#[derive(Debug, thiserror::Error)]pubenumIndexError {/// 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, },}implIndex {/// 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.pubfn 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 => returnOk(Self::default()),Err(source) => {returnErr(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.pubfn save(&self, path: &Path) -> Result<(), IndexError> {let io = |source: std::io::Error| IndexError::Io { path: path.to_path_buf(), source, };ifletSome(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.pubfn upsert(&mutself, entry: IndexEntry) {matchself.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.pubfn end(&mutself, id: &str, at: &str, exit: Exit) -> bool {matchself.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.pubfn end_everything_left_running(&mutself, at: &str) -> usize {letmut ended = 0;for held in &mutself.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.pubfn 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;