Skip to main content

utf8_forge/
writer.rs

1// Copyright 2026 houseme
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Crash-safe persistence.
16//!
17//! Never truncate-then-write: every overwrite goes through a temp file in the
18//! same directory + `fs::rename`, so a crash mid-write leaves either the old
19//! or the new content, never neither. Backups copy the original bytes
20//! *before* the rename, mirroring the tree structure under `--backup-dir`.
21
22use std::fs;
23use std::io::Write;
24use std::path::{Path, PathBuf};
25use std::process;
26use std::sync::atomic::{AtomicU64, Ordering};
27use std::time::{SystemTime, UNIX_EPOCH};
28
29use crate::error::ForgeError;
30
31/// Temp-name suffix with a process-local sequence independent of clock resolution.
32/// Shared with the fetcher's streaming temp files.
33pub(crate) fn unique_suffix() -> String {
34    static SEQUENCE: AtomicU64 = AtomicU64::new(0);
35    let nanos = SystemTime::now()
36        .duration_since(UNIX_EPOCH)
37        .map(|d| d.as_nanos())
38        .unwrap_or(0);
39    let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed);
40    format!("{}-{nanos}-{sequence}", process::id())
41}
42
43/// Atomically replace `path` with `bytes`.
44///
45/// The temp file is created in the destination's parent directory (same
46/// volume, so rename is atomic), given the original's permissions, fsynced,
47/// then renamed over the destination. Temp leftovers are cleaned up on error.
48pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), ForgeError> {
49    let parent = path
50        .parent()
51        .filter(|p| !p.as_os_str().is_empty())
52        .unwrap_or(Path::new("."));
53    // Keep the temp basename short even when the destination approaches the
54    // filesystem's name limit. Exclusive creation also refuses collisions
55    // and symlinks; cleanup starts only after this process owns the temp.
56    let tmp = parent.join(format!(".utf8-forge-tmp-{}", unique_suffix()));
57    let mut f = fs::File::create_new(&tmp)?;
58
59    let write_result = (|| -> std::io::Result<()> {
60        f.write_all(bytes)?;
61        // Preserve permissions before syncing, and fail without replacing
62        // the original if its permissions cannot be copied.
63        match fs::metadata(path) {
64            Ok(meta) => f.set_permissions(meta.permissions())?,
65            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
66            Err(e) => return Err(e),
67        }
68        f.sync_all()?;
69        drop(f);
70        fs::rename(&tmp, path)?;
71        // Best-effort directory fsync: without it a machine crash right after
72        // the rename can lose the rename itself. Ignored where the platform
73        // cannot open a directory as a file (e.g. Windows).
74        if let Ok(dir) = fs::File::open(parent) {
75            let _ = dir.sync_all();
76        }
77        Ok(())
78    })();
79
80    match write_result {
81        Ok(()) => Ok(()),
82        Err(e) => {
83            // Best-effort cleanup of the temp file; the original is intact.
84            let _ = fs::remove_file(&tmp);
85            Err(ForgeError::Io(e))
86        }
87    }
88}
89
90/// Copy the original bytes of `path` into `backup_dir`, mirroring the
91/// tree structure relative to `root`.
92///
93/// Called *before* the converted bytes are renamed into place, so the backup
94/// always holds the pre-conversion content and stays replayable.
95pub fn backup_original(
96    root: &Path,
97    path: &Path,
98    backup_dir: &Path,
99    original: &[u8],
100) -> Result<(), ForgeError> {
101    let rel = path.strip_prefix(root).map_err(|_| {
102        ForgeError::Io(std::io::Error::new(
103            std::io::ErrorKind::InvalidInput,
104            format!(
105                "file {} is not under root {}",
106                path.display(),
107                root.display()
108            ),
109        ))
110    })?;
111    let target: PathBuf = backup_dir.join(rel);
112    if let Some(parent) = target.parent() {
113        fs::create_dir_all(parent)?;
114    }
115    atomic_write(&target, original)
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121    use std::fs;
122
123    #[test]
124    fn atomic_write_replaces_content_and_cleans_up_temps() {
125        let dir = tempfile::tempdir().unwrap();
126        let p = dir.path().join("a.txt");
127        fs::write(&p, b"old").unwrap();
128
129        atomic_write(&p, b"new-bytes").unwrap();
130        assert_eq!(fs::read(&p).unwrap(), b"new-bytes");
131
132        let leftovers: Vec<_> = fs::read_dir(dir.path())
133            .unwrap()
134            .filter_map(|e| e.ok())
135            .filter(|e| {
136                e.file_name()
137                    .to_string_lossy()
138                    .starts_with(".utf8-forge-tmp")
139            })
140            .collect();
141        assert!(leftovers.is_empty(), "temp files must be renamed away");
142    }
143
144    #[test]
145    fn atomic_write_creates_file_when_missing() {
146        let dir = tempfile::tempdir().unwrap();
147        let p = dir.path().join("sub").join("b.txt");
148        // Parent does not exist → io error, original "missing" state preserved.
149        assert!(atomic_write(&p, b"x").is_err());
150        let p2 = dir.path().join("c.txt");
151        atomic_write(&p2, b"x").unwrap();
152        assert_eq!(fs::read(&p2).unwrap(), b"x");
153    }
154
155    #[test]
156    fn failed_rename_cleans_up_temp_and_keeps_destination() {
157        let dir = tempfile::tempdir().unwrap();
158        let destination = dir.path().join("occupied");
159        fs::create_dir(&destination).unwrap();
160        fs::write(destination.join("original"), b"old").unwrap();
161
162        assert!(atomic_write(&destination, b"replacement").is_err());
163        assert_eq!(fs::read(destination.join("original")).unwrap(), b"old");
164        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
165    }
166
167    #[test]
168    fn concurrent_writes_produce_complete_content_without_temp_leftovers() {
169        let dir = tempfile::tempdir().unwrap();
170        let path = dir.path().join("shared.cpp");
171        std::thread::scope(|scope| {
172            let handles: Vec<_> = (0..16u8)
173                .map(|value| {
174                    let path = &path;
175                    scope.spawn(move || atomic_write(path, &vec![value; 4096]))
176                })
177                .collect();
178            for handle in handles {
179                handle.join().unwrap().unwrap();
180            }
181        });
182        let bytes = fs::read(&path).unwrap();
183        assert_eq!(bytes.len(), 4096);
184        assert!(bytes[0] < 16);
185        assert!(bytes.iter().all(|byte| *byte == bytes[0]));
186        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
187    }
188
189    #[test]
190    fn backup_mirrors_relative_structure() {
191        let root = tempfile::tempdir().unwrap();
192        let backup = tempfile::tempdir().unwrap();
193        let src = root.path().join("GameServer").join("Channel.cpp");
194        fs::create_dir_all(src.parent().unwrap()).unwrap();
195        fs::write(&src, b"original").unwrap();
196
197        backup_original(root.path(), &src, backup.path(), b"original").unwrap();
198        let backed = backup.path().join("GameServer").join("Channel.cpp");
199        assert_eq!(fs::read(&backed).unwrap(), b"original");
200    }
201
202    #[test]
203    fn backup_rejects_path_outside_root() {
204        let root = tempfile::tempdir().unwrap();
205        let backup = tempfile::tempdir().unwrap();
206        let outside = tempfile::tempdir().unwrap();
207        let src = outside.path().join("x.cpp");
208        fs::write(&src, b"x").unwrap();
209        let res = backup_original(root.path(), &src, backup.path(), b"x");
210        assert!(res.is_err());
211    }
212}