Skip to main content

nativeview_engine/persistence/
mod.rs

1//! Crash-atomic persistence (`Frame0File` + `StateFile`) with zero `mmap` and zero `unsafe`.
2
3mod frame0_file;
4mod state_file;
5
6use std::fmt;
7use std::io;
8use std::path::Path;
9#[cfg(not(target_arch = "wasm32"))]
10use std::path::PathBuf;
11#[cfg(not(target_arch = "wasm32"))]
12use std::sync::atomic::{AtomicU64, Ordering};
13
14use nativeview_store::wire::WireError;
15
16pub use frame0_file::{
17    AppBuildId, DEFAULT_FRAME0_FILE_NAME, FRAME0_FOOTER_SIZE, Frame0File, Frame0Footer, Frame0Meta,
18    Frame0Miss, MAX_FRAME0_FILE_BYTES,
19};
20pub use state_file::{
21    DEFAULT_STATE_FILE_NAME, MAX_STATE_FILE_BYTES, STATE_FILE_HEADER_SIZE, STATE_FILE_MAGIC,
22    StateByteLen, StateFile, StateRecoveryStats, StateSaveOutcome,
23};
24
25#[cfg(not(target_arch = "wasm32"))]
26static ATOMIC_TMP_SEQ: AtomicU64 = AtomicU64::new(0);
27
28#[derive(Debug)]
29pub enum PersistenceError {
30    Io(io::Error),
31    PayloadTooLarge(usize),
32    InvalidNv02(WireError),
33    Corrupt(&'static str),
34    SchemaMismatch { expected: u32, actual: u32 },
35}
36
37impl fmt::Display for PersistenceError {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        match self {
40            Self::Io(e) => write!(f, "persistence I/O error: {e}"),
41            Self::PayloadTooLarge(n) => write!(f, "payload length {n} exceeds persistence limit"),
42            Self::InvalidNv02(e) => write!(f, "invalid NV02 keyframe: {e}"),
43            Self::Corrupt(m) => write!(f, "corrupt persistence file: {m}"),
44            Self::SchemaMismatch { expected, actual } => {
45                write!(f, "schema mismatch: {expected} != {actual}")
46            }
47        }
48    }
49}
50
51impl std::error::Error for PersistenceError {}
52
53impl From<io::Error> for PersistenceError {
54    fn from(e: io::Error) -> Self {
55        Self::Io(e)
56    }
57}
58
59impl From<WireError> for PersistenceError {
60    fn from(e: WireError) -> Self {
61        Self::InvalidNv02(e)
62    }
63}
64
65#[cfg(not(target_arch = "wasm32"))]
66pub(crate) enum ReadBoundedError {
67    Io(io::Error),
68    TooLarge,
69}
70
71#[cfg(not(target_arch = "wasm32"))]
72pub(crate) fn read_file_bounded(
73    file: &mut std::fs::File,
74    max_bytes: usize,
75    buf: &mut Vec<u8>,
76) -> Result<(), ReadBoundedError> {
77    use std::io::Read as _;
78
79    buf.clear();
80    if let Ok(meta) = file.metadata()
81        && let Ok(len) = usize::try_from(meta.len())
82    {
83        let reserve_target = len.min(max_bytes);
84        if buf.capacity() < reserve_target {
85            let _ = buf.try_reserve(reserve_target.saturating_sub(buf.len()));
86        }
87    }
88    let limit = (max_bytes as u64).saturating_add(1);
89    file.take(limit)
90        .read_to_end(buf)
91        .map_err(ReadBoundedError::Io)?;
92    if buf.len() > max_bytes {
93        buf.clear();
94        return Err(ReadBoundedError::TooLarge);
95    }
96    Ok(())
97}
98
99#[cfg(not(target_arch = "wasm32"))]
100pub(crate) fn rename_with_retry(src: &Path, dst: &Path) -> io::Result<()> {
101    #[cfg(windows)]
102    {
103        let mut attempt = 0u32;
104        loop {
105            match std::fs::rename(src, dst) {
106                Ok(()) => return Ok(()),
107                Err(e) if e.kind() == io::ErrorKind::PermissionDenied && attempt < 4 => {
108                    std::thread::sleep(std::time::Duration::from_millis(1u64 << attempt));
109                    attempt += 1;
110                }
111                Err(e) => return Err(e),
112            }
113        }
114    }
115    #[cfg(not(windows))]
116    {
117        std::fs::rename(src, dst)
118    }
119}
120
121#[cfg(not(target_arch = "wasm32"))]
122fn sync_parent_dir(path: &Path) -> io::Result<()> {
123    #[cfg(unix)]
124    {
125        let dir = path
126            .parent()
127            .filter(|p| !p.as_os_str().is_empty())
128            .unwrap_or_else(|| Path::new("."));
129        std::fs::File::open(dir)?.sync_all()
130    }
131    #[cfg(not(unix))]
132    {
133        let _ = path;
134        Ok(())
135    }
136}
137
138#[cfg(not(target_arch = "wasm32"))]
139pub(crate) fn backup_rotated_file(path: &Path, suffix: &str) -> io::Result<()> {
140    let Some(name) = path.file_name() else {
141        return Err(io::Error::new(
142            io::ErrorKind::InvalidInput,
143            "persistence path must include a file name",
144        ));
145    };
146    let mut backup_name = name.to_os_string();
147    backup_name.push(".");
148    backup_name.push(suffix);
149    let backup = path.with_file_name(backup_name);
150    rename_with_retry(path, &backup)
151}
152
153#[cfg(not(target_arch = "wasm32"))]
154pub(crate) fn backup_corrupt_file(path: &Path) {
155    if backup_rotated_file(path, "corrupt").is_err() {
156        let _ = std::fs::remove_file(path);
157    }
158}
159
160#[inline]
161pub(crate) fn remove_corrupt_frame0(disk_path: Option<&Path>) {
162    #[cfg(not(target_arch = "wasm32"))]
163    if let Some(path) = disk_path {
164        let _ = std::fs::remove_file(path);
165    }
166    #[cfg(target_arch = "wasm32")]
167    let _ = disk_path;
168}
169
170/// Atomically writes `bytes` to `path` via exclusive `create_new` sibling temp file ->
171/// optional `sync_all` -> `rename` -> optional parent-directory `sync_all`.
172#[cfg(not(target_arch = "wasm32"))]
173pub fn write_file_atomic(path: &Path, bytes: &[u8], sync: bool) -> Result<(), PersistenceError> {
174    use std::io::Write as _;
175
176    let Some(file_name) = path.file_name() else {
177        return Err(PersistenceError::Io(io::Error::new(
178            io::ErrorKind::InvalidInput,
179            "persistence path must include a file name",
180        )));
181    };
182    if let Some(parent) = path.parent()
183        && !parent.as_os_str().is_empty()
184    {
185        std::fs::create_dir_all(parent)?;
186    }
187
188    let pid = std::process::id();
189    let nonce = std::time::SystemTime::now()
190        .duration_since(std::time::UNIX_EPOCH)
191        .map_or(0u64, |d| d.as_nanos() as u64);
192    let mut created: Option<(PathBuf, std::fs::File)> = None;
193    for _ in 0..32 {
194        let seq = ATOMIC_TMP_SEQ.fetch_add(1, Ordering::Relaxed);
195        let mut tmp_name = file_name.to_os_string();
196        tmp_name.push(format!(".tmp.{pid}.{nonce:x}.{seq}"));
197        let tmp = path.with_file_name(tmp_name);
198        match std::fs::OpenOptions::new()
199            .write(true)
200            .create_new(true)
201            .open(&tmp)
202        {
203            Ok(file) => {
204                created = Some((tmp, file));
205                break;
206            }
207            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
208            Err(e) => return Err(PersistenceError::Io(e)),
209        }
210    }
211    let Some((tmp, mut file)) = created else {
212        return Err(PersistenceError::Io(io::Error::new(
213            io::ErrorKind::AlreadyExists,
214            "could not allocate unique atomic temp file",
215        )));
216    };
217
218    let write_res = (|| -> io::Result<()> {
219        file.write_all(bytes)?;
220        if sync {
221            file.sync_all()?;
222        }
223        Ok(())
224    })();
225    drop(file);
226
227    if let Err(e) = write_res.and_then(|()| rename_with_retry(&tmp, path)) {
228        let _ = std::fs::remove_file(&tmp);
229        return Err(PersistenceError::Io(e));
230    }
231    if sync {
232        sync_parent_dir(path)?;
233    }
234    Ok(())
235}
236
237#[cfg(target_arch = "wasm32")]
238pub fn write_file_atomic(_path: &Path, _bytes: &[u8], _sync: bool) -> Result<(), PersistenceError> {
239    Err(PersistenceError::Io(io::Error::new(
240        io::ErrorKind::Unsupported,
241        "unsupported on wasm32",
242    )))
243}