ferravex_render/storage/
native.rs

1use super::*;
2use ferravex_play::persistence::Document;
3use std::{
4    io::{Read, Write},
5    path::{Path, PathBuf},
6    sync::atomic::{AtomicU64, Ordering},
7};
8/// Files live under root/owner/slot.fxsave. Root must be absolute.
9///
10/// Replacing an existing, structurally valid save retains its exact bytes in
11/// `slot.fxsave.bak`. Malformed or oversized originals never replace that backup.
12/// Loads still report the original file, including corruption; recovery is an
13/// explicit operation using [`Self::recover`]. Temporary files left by a stopped
14/// process are never loaded or promoted. Writers to the same slot should be
15/// serialized when the ordering of backup generations matters.
16pub struct FileStore {
17    root: PathBuf,
18}
19impl FileStore {
20    pub fn new(root: PathBuf) -> Result<Self, StorageError> {
21        if !root.is_absolute() {
22            return Err(StorageError::InvalidKey);
23        }
24        Ok(Self { root })
25    }
26    pub fn platform() -> Result<Self, StorageError> {
27        fn absolute(key: &str) -> Option<PathBuf> {
28            std::env::var_os(key)
29                .map(PathBuf::from)
30                .filter(|p| p.is_absolute())
31        }
32        if let Some(root) = absolute("FERRAVEX_SAVE_DIR") {
33            return Self::new(root);
34        }
35        #[cfg(target_os = "windows")]
36        let root = absolute("LOCALAPPDATA").or_else(|| absolute("APPDATA"));
37        #[cfg(any(target_os = "macos", target_os = "ios"))]
38        let root = absolute("HOME").map(|p| p.join("Library/Application Support"));
39        #[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "ios")))]
40        let root =
41            absolute("XDG_DATA_HOME").or_else(|| absolute("HOME").map(|p| p.join(".local/share")));
42        Self::new(
43            root.ok_or(StorageError::Unavailable)?
44                .join("ferravex/saves"),
45        )
46    }
47    pub fn root(&self) -> &Path {
48        &self.root
49    }
50    /// Restore the previous save only after validating it as `T`.
51    ///
52    /// Returns `false` when no backup exists. Invalid, incompatible, oversized or
53    /// unreadable backups return an error without changing the current file. A
54    /// successful recovery copies the backup atomically, preserving its original
55    /// generation and the backup itself. Reopen any cached [`Slot`] afterwards.
56    /// This also allows an explicit rollback of a healthy current save.
57    ///
58    /// `DurabilityUncertain` means the replacement completed but synchronizing
59    /// its directory failed. Other errors leave the destination uncommitted.
60    ///
61    /// ```no_run
62    /// use ferravex_render::storage::{FileStore, RecordBook, Slot, StorageError};
63    ///
64    /// # fn restore_records() -> Result<(), StorageError> {
65    /// let files = FileStore::platform()?;
66    /// if files.recover::<RecordBook>("my-game", "records")? {
67    ///     let restored = Slot::with_backend(
68    ///         "my-game", "records", RecordBook::default(), files,
69    ///     )?;
70    ///     assert!(restored.generation() > 0);
71    /// }
72    /// # Ok(())
73    /// # }
74    /// ```
75    pub fn recover<T: SaveData>(&self, owner: &str, slot: &str) -> Result<bool, StorageError> {
76        validate(owner, slot, T::MAX_BYTES)?;
77        let path = self.path(owner, slot);
78        let Some(bytes) = read(&path.with_extension("fxsave.bak"), T::MAX_BYTES)? else {
79            return Ok(false);
80        };
81        T::decode(&bytes)?;
82        atomic_write(&path, &bytes, T::MAX_BYTES)?;
83        Ok(true)
84    }
85    fn path(&self, owner: &str, slot: &str) -> PathBuf {
86        self.root.join(owner).join(format!("{slot}.fxsave"))
87    }
88}
89impl Backend for FileStore {
90    fn load(&self, owner: &str, slot: &str, limit: usize) -> Result<Option<Vec<u8>>, StorageError> {
91        validate(owner, slot, limit)?;
92        read(&self.path(owner, slot), limit)
93    }
94    fn store(&self, owner: &str, slot: &str, bytes: &[u8]) -> Result<(), StorageError> {
95        validate(owner, slot, bytes.len())?;
96        let path = self.path(owner, slot);
97        match read(&path, MAX_SAVE_BYTES) {
98            Ok(Some(previous)) if Document::decode(&previous).is_ok() => {
99                // Finish the backup before touching the original. In particular,
100                // uncertain *backup* durability must not tell Slot that the new
101                // primary value was committed.
102                atomic_write(
103                    &path.with_extension("fxsave.bak"),
104                    &previous,
105                    MAX_SAVE_BYTES,
106                )
107                .map_err(|_| StorageError::Unavailable)?;
108            }
109            Ok(_) | Err(StorageError::TooLarge) => {}
110            Err(error) => return Err(error),
111        }
112        atomic_write(&path, bytes, MAX_SAVE_BYTES)
113    }
114}
115pub(crate) fn read(path: &Path, limit: usize) -> Result<Option<Vec<u8>>, StorageError> {
116    let metadata = match std::fs::metadata(path) {
117        Ok(m) => m,
118        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
119        Err(_) => return Err(StorageError::Unavailable),
120    };
121    if !metadata.is_file() {
122        return Err(StorageError::Unavailable);
123    }
124    if metadata.len() > limit as u64 {
125        return Err(StorageError::TooLarge);
126    }
127    let mut file = match std::fs::File::open(path) {
128        Ok(file) => file,
129        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
130        Err(_) => return Err(StorageError::Unavailable),
131    };
132    // The path may have been atomically replaced since the first metadata check.
133    // Inspect the opened file too, so allocation and bounds describe this read.
134    let metadata = file.metadata().map_err(|_| StorageError::Unavailable)?;
135    if !metadata.is_file() {
136        return Err(StorageError::Unavailable);
137    }
138    if metadata.len() > limit as u64 {
139        return Err(StorageError::TooLarge);
140    }
141    let mut bytes = Vec::with_capacity(metadata.len() as usize);
142    let mut chunk = [0u8; 4096];
143    loop {
144        let amount = (limit - bytes.len()).min(chunk.len() - 1) + 1;
145        let n = match file.read(&mut chunk[..amount]) {
146            Ok(n) => n,
147            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
148            Err(_) => return Err(StorageError::Unavailable),
149        };
150        if n == 0 {
151            return Ok(Some(bytes));
152        }
153        if n > limit - bytes.len() {
154            return Err(StorageError::TooLarge);
155        }
156        if bytes.len() + n > bytes.capacity() {
157            bytes.reserve_exact(n);
158        }
159        bytes.extend_from_slice(&chunk[..n]);
160    }
161}
162
163pub(crate) fn atomic_write(path: &Path, bytes: &[u8], limit: usize) -> Result<(), StorageError> {
164    if bytes.len() > limit {
165        return Err(StorageError::TooLarge);
166    }
167    static NEXT: AtomicU64 = AtomicU64::new(0);
168    if path.file_name().is_none() {
169        return Err(StorageError::InvalidKey);
170    }
171    let dir = parent_dir(path);
172    create_dir_durable(dir).map_err(|_| StorageError::Unavailable)?;
173    let mut temp = None;
174    for _ in 0..16 {
175        let name = dir.join(format!(
176            ".save-{}-{}.tmp",
177            std::process::id(),
178            NEXT.fetch_add(1, Ordering::Relaxed)
179        ));
180        match std::fs::OpenOptions::new()
181            .write(true)
182            .create_new(true)
183            .open(&name)
184        {
185            Ok(file) => {
186                temp = Some((name, file));
187                break;
188            }
189            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
190            Err(_) => return Err(StorageError::Unavailable),
191        }
192    }
193    let (temp, mut file) = temp.ok_or(StorageError::Unavailable)?;
194    let result = (|| {
195        file.write_all(bytes)?;
196        file.sync_all()?;
197        drop(file);
198        // Same-directory rename replaces the destination without an unlink gap
199        // on platforms supporting atomic replacement, including Unix/Windows.
200        std::fs::rename(&temp, path)
201    })();
202    if result.is_err() {
203        let _ = std::fs::remove_file(&temp);
204        return Err(StorageError::Unavailable);
205    }
206    sync_dir(dir).map_err(|_| StorageError::DurabilityUncertain)
207}
208fn parent_dir(path: &Path) -> &Path {
209    path.parent()
210        .filter(|parent| !parent.as_os_str().is_empty())
211        .unwrap_or_else(|| Path::new("."))
212}
213fn create_dir_durable(dir: &Path) -> std::io::Result<()> {
214    let mut missing = Vec::new();
215    let mut ancestor = dir;
216    loop {
217        match std::fs::metadata(ancestor) {
218            Ok(_) => break,
219            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
220                missing.push(ancestor);
221                let parent = parent_dir(ancestor);
222                if parent == ancestor {
223                    return Err(e);
224                }
225                ancestor = parent;
226            }
227            Err(e) => return Err(e),
228        }
229    }
230    std::fs::create_dir_all(dir)?;
231    // Sync newly-created directory entries as well as the final file entry.
232    // Otherwise a first save could lose its entire owner/root directory on crash.
233    for path in missing.into_iter().rev() {
234        sync_dir(parent_dir(path))?;
235    }
236    Ok(())
237}
238fn sync_dir(dir: &Path) -> std::io::Result<()> {
239    #[cfg(unix)]
240    std::fs::File::open(dir)?.sync_all()?;
241    #[cfg(not(unix))]
242    let _ = dir; // std has no portable directory synchronization primitive.
243    Ok(())
244}