agentmux_srv_core/registry/
atomic.rs1use std::io::Write;
8use std::path::Path;
9use std::time::{Duration, SystemTime};
10
11const TEMP_PREFIX: &str = ".registry-tmp-";
13
14pub const STALE_TEMP_AGE: Duration = Duration::from_secs(600);
19
20pub fn is_temp_file(path: &Path) -> bool {
23 path.file_name()
24 .and_then(|n| n.to_str())
25 .is_some_and(|n| n.starts_with(TEMP_PREFIX))
26}
27
28pub fn sweep_stale_temps(dir: &Path, min_age: Duration) -> usize {
34 let entries = match std::fs::read_dir(dir) {
35 Ok(e) => e,
36 Err(e) => {
37 if e.kind() != std::io::ErrorKind::NotFound {
38 tracing::warn!(dir = %dir.display(), error = %e, "registry: could not look for leftover temp files");
39 }
40 return 0;
41 }
42 };
43 let now = SystemTime::now();
44 let mut removed = 0;
45 for entry in entries.flatten() {
46 let path = entry.path();
47 if !is_temp_file(&path) {
48 continue;
49 }
50 let Ok(meta) = entry.metadata() else { continue };
51 if !meta.is_file() {
52 continue;
53 }
54 let old_enough = meta
55 .modified()
56 .ok()
57 .and_then(|m| now.duration_since(m).ok())
58 .is_some_and(|age| age >= min_age);
59 if !old_enough {
60 continue;
61 }
62 match std::fs::remove_file(&path) {
63 Ok(()) => {
64 removed += 1;
65 tracing::info!(file = %path.display(), "registry: removed a temp file left by an interrupted write");
66 }
67 Err(e) => tracing::warn!(file = %path.display(), error = %e, "registry: could not remove a leftover temp file"),
68 }
69 }
70 removed
71}
72
73pub fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
78 let parent = path.parent().ok_or_else(|| {
79 std::io::Error::new(
80 std::io::ErrorKind::InvalidInput,
81 "write_atomic: path has no parent",
82 )
83 })?;
84 std::fs::create_dir_all(parent)?;
85 let mut tmp = tempfile::Builder::new()
86 .prefix(TEMP_PREFIX)
87 .suffix(".json")
88 .tempfile_in(parent)?;
89 tmp.as_file_mut().write_all(bytes)?;
90 tmp.as_file_mut().sync_all()?;
91 tmp.persist(path).map_err(|e| e.error)?;
92 Ok(())
93}
94
95pub fn rename_atomic(from: &Path, to: &Path) -> std::io::Result<()> {
97 if let Some(parent) = to.parent() {
98 std::fs::create_dir_all(parent)?;
99 }
100 std::fs::rename(from, to)
101}
102
103#[cfg(test)]
104mod tests {
105 use super::*;
106
107 #[test]
108 fn write_atomic_creates_parent_and_target() {
109 let tmp = tempfile::tempdir().unwrap();
110 let target = tmp.path().join("nested").join("file.json");
111 write_atomic(&target, b"hello").unwrap();
112 assert_eq!(std::fs::read(&target).unwrap(), b"hello");
113 }
114
115 #[test]
116 fn write_atomic_overwrites() {
117 let tmp = tempfile::tempdir().unwrap();
118 let target = tmp.path().join("a.json");
119 write_atomic(&target, b"v1").unwrap();
120 write_atomic(&target, b"v2-longer").unwrap();
121 assert_eq!(std::fs::read(&target).unwrap(), b"v2-longer");
122 }
123
124 fn aged(path: &Path, secs: u64) {
125 let f = std::fs::OpenOptions::new().write(true).open(path).unwrap();
126 f.set_modified(SystemTime::now() - Duration::from_secs(secs)).unwrap();
127 }
128
129 #[test]
130 fn sweep_removes_only_old_files_named_like_write_atomics_temp() {
131 let dir = tempfile::tempdir().unwrap();
132 let old_tmp = dir.path().join(".registry-tmp-old.json");
133 let fresh_tmp = dir.path().join(".registry-tmp-fresh.json");
134 let record = dir.path().join("abc.json");
135 let other_hidden = dir.path().join(".something-else.json");
136 for p in [&old_tmp, &fresh_tmp, &record, &other_hidden] {
137 std::fs::write(p, b"{}").unwrap();
138 }
139 for p in [&old_tmp, &record, &other_hidden] {
140 aged(p, 3600);
141 }
142 assert_eq!(sweep_stale_temps(dir.path(), STALE_TEMP_AGE), 1);
143 assert!(!old_tmp.exists(), "an old temp file is removed");
144 assert!(fresh_tmp.exists(), "a write that may be in flight is left");
145 assert!(record.exists(), "a record is never removed, however old");
146 assert!(other_hidden.exists(), "only the temp pattern is removed");
147 }
148
149 #[test]
150 fn sweep_of_a_missing_folder_is_a_no_op() {
151 let dir = tempfile::tempdir().unwrap();
152 assert_eq!(sweep_stale_temps(&dir.path().join("nope"), STALE_TEMP_AGE), 0);
153 }
154
155 #[test]
156 fn is_temp_file_matches_the_name_write_atomic_gives() {
157 let dir = tempfile::tempdir().unwrap();
158 let target = dir.path().join("a.json");
159 let tmp = tempfile::Builder::new().prefix(TEMP_PREFIX).suffix(".json").tempfile_in(dir.path()).unwrap();
160 assert!(is_temp_file(tmp.path()));
161 assert!(!is_temp_file(&target));
162 }
163
164 #[test]
165 fn rename_atomic_moves_file() {
166 let tmp = tempfile::tempdir().unwrap();
167 let from = tmp.path().join("from.json");
168 let to = tmp.path().join("retired").join("from.json");
169 std::fs::write(&from, b"x").unwrap();
170 rename_atomic(&from, &to).unwrap();
171 assert!(!from.exists());
172 assert_eq!(std::fs::read(&to).unwrap(), b"x");
173 }
174
175 #[test]
176 fn rename_atomic_does_not_create_when_missing() {
177 let tmp = tempfile::tempdir().unwrap();
178 let from = tmp.path().join("missing.json");
179 let to = tmp.path().join("retired.json");
180 let err = rename_atomic(&from, &to).unwrap_err();
181 assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
182 }
183}