agent-ssh 0.3.6

Arrange agent terminal layouts and reconnect through provider attachment plans
Documentation
use std::{
    env, fs,
    path::{Path, PathBuf},
    time::{SystemTime, UNIX_EPOCH},
};

use anyhow::{Context, Result, bail};

pub fn default_directory() -> Result<PathBuf> {
    #[cfg(windows)]
    let base = env::var_os("LOCALAPPDATA")
        .filter(|s| !s.is_empty())
        .map(PathBuf::from)
        .context("LOCALAPPDATA is unavailable; provide a snapshot path")?;
    #[cfg(not(windows))]
    let base = match env::var_os("XDG_STATE_HOME").filter(|s| Path::new(s).is_absolute()) {
        Some(path) => PathBuf::from(path),
        None => PathBuf::from(
            env::var_os("HOME")
                .filter(|s| !s.is_empty())
                .context("HOME is unavailable; provide a snapshot path")?,
        )
        .join(".local/state"),
    };
    if !base.is_absolute() {
        bail!("snapshot state directory must be absolute; provide a snapshot path");
    }
    Ok(base.join("agent-ssh/snapshots"))
}

pub fn new_path(directory: &Path, now: SystemTime) -> Result<PathBuf> {
    let timestamp = now
        .duration_since(UNIX_EPOCH)
        .context("system clock is before the UTC epoch")?;
    Ok(directory.join(format!(
        "snapshot-{:020}-{:09}.json",
        timestamp.as_secs(),
        timestamp.subsec_nanos()
    )))
}

pub fn write_timestamped(state: &crate::snapshot::SavedState, directory: &Path) -> Result<PathBuf> {
    write_with_clock(state, directory, SystemTime::now)
}

fn write_with_clock(
    state: &crate::snapshot::SavedState,
    directory: &Path,
    mut now: impl FnMut() -> SystemTime,
) -> Result<PathBuf> {
    fs::create_dir_all(directory)?;
    for _ in 0..8 {
        let path = new_path(directory, now())?;
        match state.write_new(&path) {
            Ok(()) => return Ok(path),
            Err(error)
                if error
                    .downcast_ref::<std::io::Error>()
                    .is_some_and(|e| e.kind() == std::io::ErrorKind::AlreadyExists) =>
            {
                continue;
            }
            Err(error) => return Err(error),
        }
    }
    bail!("snapshot timestamp collisions; retry agent-ssh save or provide a new path")
}

fn managed_name(name: &str) -> bool {
    let Some(timestamp) = name
        .strip_prefix("snapshot-")
        .and_then(|s| s.strip_suffix(".json"))
    else {
        return false;
    };
    let Some((seconds, nanos)) = timestamp.split_once('-') else {
        return false;
    };
    seconds.len() == 20
        && nanos.len() == 9
        && seconds
            .bytes()
            .chain(nanos.bytes())
            .all(|b| b.is_ascii_digit())
        && seconds.parse::<u64>().is_ok()
        && nanos.parse::<u32>().is_ok_and(|n| n < 1_000_000_000)
}

pub fn latest(directory: &Path) -> Result<PathBuf> {
    let entries = fs::read_dir(directory).with_context(|| {
        format!(
            "cannot read snapshot directory {}; use agent-ssh save first or load PATH",
            directory.display()
        )
    })?;
    let mut newest = None;
    for entry in entries {
        let entry = entry?;
        if !entry.file_type()?.is_file() {
            continue;
        }
        let name = entry.file_name();
        let Some(name) = name.to_str().filter(|name| managed_name(name)) else {
            continue;
        };
        if newest
            .as_ref()
            .is_none_or(|current: &String| name > current.as_str())
        {
            newest = Some(name.to_owned());
        }
    }
    newest
        .map(|name| directory.join(name))
        .context("no managed snapshots found; use agent-ssh save first or load PATH")
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    fn remove_test_directory(path: &Path) {
        let path = path.canonicalize().unwrap();
        let temporary = env::temp_dir().canonicalize().unwrap();
        assert_eq!(path.parent(), Some(temporary.as_path()));
        assert!(
            path.file_name()
                .unwrap()
                .to_str()
                .unwrap()
                .starts_with("agent-ssh-")
        );
        fs::remove_dir_all(path).unwrap();
    }

    #[test]
    fn timestamp_names_sort_by_utc_time_and_preserve_no_overwrite() {
        let directory = env::temp_dir().join(format!(
            "agent-ssh-store-{}-{}",
            std::process::id(),
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        fs::create_dir(&directory).unwrap();
        let older = new_path(&directory, UNIX_EPOCH + Duration::new(10, 999_999_999)).unwrap();
        let newer = new_path(&directory, UNIX_EPOCH + Duration::new(11, 0)).unwrap();
        fs::write(&older, b"old").unwrap();
        fs::write(&newer, b"new but corrupt").unwrap();
        fs::write(directory.join("unrelated.json"), b"unrelated").unwrap();
        fs::create_dir(new_path(&directory, UNIX_EPOCH + Duration::new(99, 0)).unwrap()).unwrap();
        assert_eq!(latest(&directory).unwrap(), newer);
        assert!(
            fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(&newer)
                .is_err()
        );
        assert_eq!(fs::read(newer).unwrap(), b"new but corrupt");
        remove_test_directory(&directory);
    }

    #[test]
    fn unrelated_names_and_symlinks_do_not_become_snapshots() {
        for name in [
            "snapshot-1-000000000.json",
            "snapshot-00000000000000000001-00000000.json",
            "snapshot-18446744073709551616-000000000.json",
            "snapshot-00000000000000000001-000000000.json.bak",
        ] {
            assert!(!managed_name(name));
        }
        assert!(managed_name("snapshot-00000000000000000001-999999999.json"));
        #[cfg(unix)]
        {
            let directory = env::temp_dir().join(format!(
                "agent-ssh-symlink-{}-{}",
                std::process::id(),
                SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_nanos()
            ));
            fs::create_dir(&directory).unwrap();
            fs::write(directory.join("target"), b"data").unwrap();
            std::os::unix::fs::symlink(
                directory.join("target"),
                new_path(&directory, SystemTime::now()).unwrap(),
            )
            .unwrap();
            assert!(latest(&directory).is_err());
            remove_test_directory(&directory);
        }
    }

    #[test]
    fn timestamp_collisions_retry_without_replacing_a_recovery_copy() {
        let directory = env::temp_dir().join(format!(
            "agent-ssh-collision-{}-{}",
            std::process::id(),
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        fs::create_dir(&directory).unwrap();
        let state = crate::snapshot::SavedState::parse(r#"{"version":3,"restorable":false,"selected_tab":0,"tabs":[{"title":"fixture","root":{"kind":"pane","pane":{"key":"fixture","title":"fixture","target":{"kind":"unavailable","reason":"fixture"}}}}]}"#).unwrap();
        let first = UNIX_EPOCH + Duration::new(1, 0);
        let next = UNIX_EPOCH + Duration::new(1, 100);
        let original = new_path(&directory, first).unwrap();
        fs::write(&original, b"recovery copy").unwrap();
        let mut calls = 0;
        let written = write_with_clock(&state, &directory, || {
            calls += 1;
            if calls == 1 { first } else { next }
        })
        .unwrap();
        assert_eq!(written, new_path(&directory, next).unwrap());
        assert_eq!(calls, 2);
        assert_eq!(fs::read(original).unwrap(), b"recovery copy");
        assert!(crate::snapshot::SavedState::parse(&fs::read_to_string(written).unwrap()).is_ok());
        let mut attempts = 0;
        assert!(
            write_with_clock(&state, &directory, || {
                attempts += 1;
                first
            })
            .is_err()
        );
        assert_eq!(attempts, 8);
        remove_test_directory(&directory);
    }
}