Skip to main content

rayengine_core/save/
file.rs

1use super::*;
2use std::{
3    fs::{self, File, OpenOptions},
4    io::{Read, Write},
5    path::{Path, PathBuf},
6    sync::atomic::{AtomicU64, Ordering},
7};
8
9static NEXT_TEMP: AtomicU64 = AtomicU64::new(0);
10
11/// Reads only the named regular file. Limits and actual file length are checked
12/// before payload allocation; checksum validation precedes game decoding.
13/// Leftover temporary files are never discovered or promoted automatically.
14pub fn load(path: impl AsRef<Path>, limits: SaveLimits) -> Result<SaveData, SaveError> {
15    let mut file = File::open(path).map_err(|source| io_error(SaveStage::Read, source))?;
16    let metadata = file
17        .metadata()
18        .map_err(|source| io_error(SaveStage::Read, source))?;
19    if !metadata.is_file() {
20        return Err(SaveError::NotRegularFile);
21    }
22    let mut header = [0; HEADER_LEN];
23    let count = read_complete(&mut file, &mut header)?;
24    if count != HEADER_LEN {
25        return Err(SaveError::TruncatedHeader { bytes: count });
26    }
27    let (schema_version, size) = parse_header(&header, limits)?;
28    let total = (size as u64) + HEADER_LEN as u64;
29    if metadata.len() != total {
30        return Err(SaveError::LengthMismatch {
31            declared: size as u64,
32            actual: metadata.len().saturating_sub(HEADER_LEN as u64),
33        });
34    }
35    let mut payload = Vec::new();
36    payload
37        .try_reserve_exact(size)
38        .map_err(SaveError::Allocation)?;
39    payload.resize(size, 0);
40    let count = read_complete(&mut file, &mut payload)?;
41    if count != size {
42        return Err(SaveError::LengthMismatch {
43            declared: size as u64,
44            actual: count as u64,
45        });
46    }
47    if read_complete(&mut file, &mut [0])? != 0 {
48        return Err(SaveError::LengthMismatch {
49            declared: size as u64,
50            actual: size as u64 + 1,
51        });
52    }
53    verify_checksum(&header, &payload)?;
54    Ok(SaveData {
55        schema_version,
56        payload,
57    })
58}
59
60/// Reads/validates, then calls the game decoder once with its schema and bytes.
61/// This is the migration hook: reject unsupported schemas or convert older
62/// payloads explicitly. Decoder errors never trigger a write or fallback.
63pub fn load_with<T, E>(
64    path: impl AsRef<Path>,
65    limits: SaveLimits,
66    decode: impl FnOnce(u32, &[u8]) -> Result<T, E>,
67) -> Result<T, CodecError<E>> {
68    let data = load(path, limits).map_err(CodecError::Container)?;
69    decode(data.schema_version, &data.payload).map_err(CodecError::Payload)
70}
71
72/// Encodes the game's payload before touching the filesystem, then writes it.
73/// The byte limit applies after serialization; the game's encoder owns its
74/// allocation policy. Serialization errors preserve the existing destination.
75pub fn save_with<T, E>(
76    path: impl AsRef<Path>,
77    schema_version: u32,
78    value: &T,
79    options: SaveOptions,
80    encode: impl FnOnce(&T) -> Result<Vec<u8>, E>,
81) -> Result<(), CodecError<E>> {
82    let payload = encode(value).map_err(CodecError::Payload)?;
83    save(path, schema_version, &payload, options).map_err(CodecError::Container)
84}
85
86/// Writes a validated container to a unique sibling, then replaces the name.
87/// The destination is never truncated. Parent directories must already exist.
88/// Linux durable writes sync the file before rename and the parent after it.
89/// Failures before rename preserve the destination; rename errors are reported
90/// as ambiguous, and a directory-sync error reports an already-installed save.
91/// Check [`SaveError::commit_state`] before deciding recovery. Concurrent saves
92/// use unique temporaries; last replacement wins, without game-state locking.
93/// Temporary cleanup is best effort on error/unwind; process crashes can leave
94/// uncommitted siblings. Unix files use mode 0600; old metadata is not copied.
95pub fn save(
96    path: impl AsRef<Path>,
97    schema_version: u32,
98    payload: &[u8],
99    options: SaveOptions,
100) -> Result<(), SaveError> {
101    save_using(
102        path.as_ref(),
103        schema_version,
104        payload,
105        options,
106        &mut NativeOps,
107    )
108}
109
110fn save_using(
111    path: &Path,
112    schema: u32,
113    payload: &[u8],
114    options: SaveOptions,
115    ops: &mut impl FileOps,
116) -> Result<(), SaveError> {
117    let header = make_header(schema, payload, options.limits)?;
118    if path.file_name().is_none() {
119        return Err(SaveError::InvalidPath);
120    }
121    let parent = path
122        .parent()
123        .filter(|p| !p.as_os_str().is_empty())
124        .unwrap_or(Path::new("."));
125    let directory = open_directory(parent, options.durability)?;
126    let mut temp = Temporary::create(parent)?;
127    let file = temp.file.as_mut().expect("temporary open");
128    ops.write(file, &header, payload)
129        .map_err(|source| io_error(SaveStage::WriteTemporary, source))?;
130    if options.durability == Durability::Durable {
131        ops.sync_file(file)
132            .map_err(|source| io_error(SaveStage::SyncTemporary, source))?;
133    }
134    // Close before rename for platforms whose open handles prevent replacement.
135    drop(temp.file.take());
136    ops.rename(&temp.path, path)
137        .map_err(|source| io_error(SaveStage::Rename, source))?;
138    temp.committed = true;
139    if let Some(directory) = directory {
140        ops.sync_directory(&directory)
141            .map_err(|source| io_error(SaveStage::SyncDirectory, source))?;
142    }
143    Ok(())
144}
145
146fn open_directory(parent: &Path, durability: Durability) -> Result<Option<File>, SaveError> {
147    if durability == Durability::Atomic {
148        return Ok(None);
149    }
150    #[cfg(target_os = "linux")]
151    {
152        File::open(parent)
153            .map(Some)
154            .map_err(|source| io_error(SaveStage::OpenDirectory, source))
155    }
156    #[cfg(not(target_os = "linux"))]
157    {
158        let _ = parent;
159        Err(SaveError::UnsupportedDurability)
160    }
161}
162
163fn io_error(stage: SaveStage, source: io::Error) -> SaveError {
164    SaveError::Io { stage, source }
165}
166
167fn read_complete(file: &mut File, output: &mut [u8]) -> Result<usize, SaveError> {
168    let mut count = 0;
169    while count < output.len() {
170        match file.read(&mut output[count..]) {
171            Ok(0) => break,
172            Ok(bytes) => count += bytes,
173            Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
174            Err(source) => return Err(io_error(SaveStage::Read, source)),
175        }
176    }
177    Ok(count)
178}
179
180struct Temporary {
181    path: PathBuf,
182    file: Option<File>,
183    committed: bool,
184}
185impl Temporary {
186    fn create(parent: &Path) -> Result<Self, SaveError> {
187        for _ in 0..128 {
188            // `try_update` is newer than our Rust 1.89 minimum.
189            #[allow(deprecated)]
190            let id = NEXT_TEMP
191                .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
192                .map_err(|_| {
193                    io_error(
194                        SaveStage::CreateTemporary,
195                        io::Error::other("temporary name space exhausted"),
196                    )
197                })?;
198            // Independent of destination length/encoding, including Unix byte paths.
199            let path = parent.join(format!(
200                ".rayengine-save-{}-{id:016x}.tmp",
201                std::process::id()
202            ));
203            let mut options = OpenOptions::new();
204            options.write(true).create_new(true);
205            #[cfg(unix)]
206            {
207                use std::os::unix::fs::OpenOptionsExt;
208                options.mode(0o600);
209            }
210            match options.open(&path) {
211                Ok(file) => {
212                    return Ok(Self {
213                        path,
214                        file: Some(file),
215                        committed: false,
216                    });
217                }
218                Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
219                Err(source) => return Err(io_error(SaveStage::CreateTemporary, source)),
220            }
221        }
222        Err(io_error(
223            SaveStage::CreateTemporary,
224            io::Error::new(
225                io::ErrorKind::AlreadyExists,
226                "temporary file collision limit exceeded",
227            ),
228        ))
229    }
230}
231impl Drop for Temporary {
232    fn drop(&mut self) {
233        drop(self.file.take());
234        if !self.committed {
235            let _ = fs::remove_file(&self.path);
236        }
237    }
238}
239
240// Monomorphized production operations, with a private test seam for real-file
241// partial write/fsync/rename errors. No public test hooks or virtual dispatch.
242trait FileOps {
243    fn write(&mut self, file: &mut File, header: &[u8], payload: &[u8]) -> io::Result<()>;
244    fn sync_file(&mut self, file: &File) -> io::Result<()>;
245    fn rename(&mut self, from: &Path, to: &Path) -> io::Result<()>;
246    fn sync_directory(&mut self, directory: &File) -> io::Result<()>;
247}
248struct NativeOps;
249impl FileOps for NativeOps {
250    fn write(&mut self, file: &mut File, header: &[u8], payload: &[u8]) -> io::Result<()> {
251        file.write_all(header)?;
252        file.write_all(payload)
253    }
254    fn sync_file(&mut self, file: &File) -> io::Result<()> {
255        file.sync_all()
256    }
257    fn rename(&mut self, from: &Path, to: &Path) -> io::Result<()> {
258        fs::rename(from, to)
259    }
260    fn sync_directory(&mut self, directory: &File) -> io::Result<()> {
261        directory.sync_all()
262    }
263}
264
265#[cfg(test)]
266mod tests;