agent_ssh/
snapshot_store.rs1use std::{
2 env, fs,
3 path::{Path, PathBuf},
4 time::{SystemTime, UNIX_EPOCH},
5};
6
7use anyhow::{Context, Result, bail};
8
9pub fn default_directory() -> Result<PathBuf> {
10 #[cfg(windows)]
11 let base = env::var_os("LOCALAPPDATA")
12 .filter(|s| !s.is_empty())
13 .map(PathBuf::from)
14 .context("LOCALAPPDATA is unavailable; provide a snapshot path")?;
15 #[cfg(not(windows))]
16 let base = match env::var_os("XDG_STATE_HOME").filter(|s| Path::new(s).is_absolute()) {
17 Some(path) => PathBuf::from(path),
18 None => PathBuf::from(
19 env::var_os("HOME")
20 .filter(|s| !s.is_empty())
21 .context("HOME is unavailable; provide a snapshot path")?,
22 )
23 .join(".local/state"),
24 };
25 if !base.is_absolute() {
26 bail!("snapshot state directory must be absolute; provide a snapshot path");
27 }
28 Ok(base.join("agent-ssh/snapshots"))
29}
30
31pub fn new_path(directory: &Path, now: SystemTime) -> Result<PathBuf> {
32 let timestamp = now
33 .duration_since(UNIX_EPOCH)
34 .context("system clock is before the UTC epoch")?;
35 Ok(directory.join(format!(
36 "snapshot-{:020}-{:09}.json",
37 timestamp.as_secs(),
38 timestamp.subsec_nanos()
39 )))
40}
41
42pub fn write_timestamped(state: &crate::snapshot::SavedState, directory: &Path) -> Result<PathBuf> {
43 write_with_clock(state, directory, SystemTime::now)
44}
45
46fn write_with_clock(
47 state: &crate::snapshot::SavedState,
48 directory: &Path,
49 mut now: impl FnMut() -> SystemTime,
50) -> Result<PathBuf> {
51 fs::create_dir_all(directory)?;
52 for _ in 0..8 {
53 let path = new_path(directory, now())?;
54 match state.write_new(&path) {
55 Ok(()) => return Ok(path),
56 Err(error)
57 if error
58 .downcast_ref::<std::io::Error>()
59 .is_some_and(|e| e.kind() == std::io::ErrorKind::AlreadyExists) =>
60 {
61 continue;
62 }
63 Err(error) => return Err(error),
64 }
65 }
66 bail!("snapshot timestamp collisions; retry agent-ssh save or provide a new path")
67}
68
69fn managed_name(name: &str) -> bool {
70 let Some(timestamp) = name
71 .strip_prefix("snapshot-")
72 .and_then(|s| s.strip_suffix(".json"))
73 else {
74 return false;
75 };
76 let Some((seconds, nanos)) = timestamp.split_once('-') else {
77 return false;
78 };
79 seconds.len() == 20
80 && nanos.len() == 9
81 && seconds
82 .bytes()
83 .chain(nanos.bytes())
84 .all(|b| b.is_ascii_digit())
85 && seconds.parse::<u64>().is_ok()
86 && nanos.parse::<u32>().is_ok_and(|n| n < 1_000_000_000)
87}
88
89pub fn latest(directory: &Path) -> Result<PathBuf> {
90 let entries = fs::read_dir(directory).with_context(|| {
91 format!(
92 "cannot read snapshot directory {}; use agent-ssh save first or load PATH",
93 directory.display()
94 )
95 })?;
96 let mut newest = None;
97 for entry in entries {
98 let entry = entry?;
99 if !entry.file_type()?.is_file() {
100 continue;
101 }
102 let name = entry.file_name();
103 let Some(name) = name.to_str().filter(|name| managed_name(name)) else {
104 continue;
105 };
106 if newest
107 .as_ref()
108 .is_none_or(|current: &String| name > current.as_str())
109 {
110 newest = Some(name.to_owned());
111 }
112 }
113 newest
114 .map(|name| directory.join(name))
115 .context("no managed snapshots found; use agent-ssh save first or load PATH")
116}
117
118#[cfg(test)]
119mod tests {
120 use super::*;
121 use std::time::Duration;
122
123 fn remove_test_directory(path: &Path) {
124 let path = path.canonicalize().unwrap();
125 let temporary = env::temp_dir().canonicalize().unwrap();
126 assert_eq!(path.parent(), Some(temporary.as_path()));
127 assert!(
128 path.file_name()
129 .unwrap()
130 .to_str()
131 .unwrap()
132 .starts_with("agent-ssh-")
133 );
134 fs::remove_dir_all(path).unwrap();
135 }
136
137 #[test]
138 fn timestamp_names_sort_by_utc_time_and_preserve_no_overwrite() {
139 let directory = env::temp_dir().join(format!(
140 "agent-ssh-store-{}-{}",
141 std::process::id(),
142 SystemTime::now()
143 .duration_since(UNIX_EPOCH)
144 .unwrap()
145 .as_nanos()
146 ));
147 fs::create_dir(&directory).unwrap();
148 let older = new_path(&directory, UNIX_EPOCH + Duration::new(10, 999_999_999)).unwrap();
149 let newer = new_path(&directory, UNIX_EPOCH + Duration::new(11, 0)).unwrap();
150 fs::write(&older, b"old").unwrap();
151 fs::write(&newer, b"new but corrupt").unwrap();
152 fs::write(directory.join("unrelated.json"), b"unrelated").unwrap();
153 fs::create_dir(new_path(&directory, UNIX_EPOCH + Duration::new(99, 0)).unwrap()).unwrap();
154 assert_eq!(latest(&directory).unwrap(), newer);
155 assert!(
156 fs::OpenOptions::new()
157 .write(true)
158 .create_new(true)
159 .open(&newer)
160 .is_err()
161 );
162 assert_eq!(fs::read(newer).unwrap(), b"new but corrupt");
163 remove_test_directory(&directory);
164 }
165
166 #[test]
167 fn unrelated_names_and_symlinks_do_not_become_snapshots() {
168 for name in [
169 "snapshot-1-000000000.json",
170 "snapshot-00000000000000000001-00000000.json",
171 "snapshot-18446744073709551616-000000000.json",
172 "snapshot-00000000000000000001-000000000.json.bak",
173 ] {
174 assert!(!managed_name(name));
175 }
176 assert!(managed_name("snapshot-00000000000000000001-999999999.json"));
177 #[cfg(unix)]
178 {
179 let directory = env::temp_dir().join(format!(
180 "agent-ssh-symlink-{}-{}",
181 std::process::id(),
182 SystemTime::now()
183 .duration_since(UNIX_EPOCH)
184 .unwrap()
185 .as_nanos()
186 ));
187 fs::create_dir(&directory).unwrap();
188 fs::write(directory.join("target"), b"data").unwrap();
189 std::os::unix::fs::symlink(
190 directory.join("target"),
191 new_path(&directory, SystemTime::now()).unwrap(),
192 )
193 .unwrap();
194 assert!(latest(&directory).is_err());
195 remove_test_directory(&directory);
196 }
197 }
198
199 #[test]
200 fn timestamp_collisions_retry_without_replacing_a_recovery_copy() {
201 let directory = env::temp_dir().join(format!(
202 "agent-ssh-collision-{}-{}",
203 std::process::id(),
204 SystemTime::now()
205 .duration_since(UNIX_EPOCH)
206 .unwrap()
207 .as_nanos()
208 ));
209 fs::create_dir(&directory).unwrap();
210 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();
211 let first = UNIX_EPOCH + Duration::new(1, 0);
212 let next = UNIX_EPOCH + Duration::new(1, 100);
213 let original = new_path(&directory, first).unwrap();
214 fs::write(&original, b"recovery copy").unwrap();
215 let mut calls = 0;
216 let written = write_with_clock(&state, &directory, || {
217 calls += 1;
218 if calls == 1 { first } else { next }
219 })
220 .unwrap();
221 assert_eq!(written, new_path(&directory, next).unwrap());
222 assert_eq!(calls, 2);
223 assert_eq!(fs::read(original).unwrap(), b"recovery copy");
224 assert!(crate::snapshot::SavedState::parse(&fs::read_to_string(written).unwrap()).is_ok());
225 let mut attempts = 0;
226 assert!(
227 write_with_clock(&state, &directory, || {
228 attempts += 1;
229 first
230 })
231 .is_err()
232 );
233 assert_eq!(attempts, 8);
234 remove_test_directory(&directory);
235 }
236}