Skip to main content

agentmux_srv_core/registry/
atomic.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Atomic file write + rename helpers. All registry mutations route
5//! through these so readers never observe a half-written file.
6
7use std::io::Write;
8use std::path::Path;
9use std::time::{Duration, SystemTime};
10
11/// Name prefix of the sibling temp file [`write_atomic`] writes before it renames.
12const TEMP_PREFIX: &str = ".registry-tmp-";
13
14/// How old a leftover temp file must be before [`sweep_stale_temps`] removes it.
15/// A write holds its temp file for milliseconds (a write, an fsync, a rename), so a
16/// file this old belongs to a write that was cut short, never to one in flight in
17/// another process sharing the folder.
18pub const STALE_TEMP_AGE: Duration = Duration::from_secs(600);
19
20/// Whether `path` is a temp file [`write_atomic`] made: not a record, whatever
21/// its `.json` ending says.
22pub 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
28/// Remove the temp files in `dir` that an interrupted write left behind: only
29/// files named like [`write_atomic`]'s, and only those last changed more than
30/// `min_age` ago. Returns how many were removed. A folder that can't be read or
31/// a file that can't be removed is logged and left, never an error: this runs
32/// at start and must not stop it.
33pub 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
73/// Write `bytes` to `path` atomically: sibling temp file → fsync →
74/// rename over the target. Rename is atomic on every supported
75/// filesystem when source and destination live on the same volume,
76/// which is guaranteed here (sibling temp).
77pub 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
95/// Atomic rename. Used for retire/unretire (same-directory tree).
96pub 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}