nativeview_engine/persistence/
state_file.rs1#[cfg(not(target_arch = "wasm32"))]
4use std::io;
5use std::path::{Path, PathBuf};
6
7use nativeview_abi::{Xxh64Hasher, xxh64};
8use nativeview_codec::ByteReader;
9
10use super::{PersistenceError, write_file_atomic};
11#[cfg(not(target_arch = "wasm32"))]
12use super::{ReadBoundedError, backup_corrupt_file, backup_rotated_file, read_file_bounded};
13
14pub const DEFAULT_STATE_FILE_NAME: &str = "state.nv";
15pub const STATE_FILE_MAGIC: [u8; 8] = *b"NV_STATE";
16pub const STATE_FILE_HEADER_SIZE: usize = 24;
17pub const MAX_STATE_FILE_BYTES: usize = 64 * 1024 * 1024;
19
20const STATE_XXH64_SEED: u64 = 0x4E56_4553_5441_5445;
21
22#[inline]
23fn state_envelope_xxh64(header_prefix_16: &[u8], payload: &[u8]) -> u64 {
24 let mut hasher = Xxh64Hasher::new(STATE_XXH64_SEED);
25 hasher.update(header_prefix_16);
26 hasher.update(payload);
27 hasher.digest()
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
31pub struct StateRecoveryStats {
32 pub loaded_from_disk: bool,
33 pub recovered_from_corrupt: bool,
34 pub rotated_from_older_schema: Option<u32>,
37 pub generation: u64,
38}
39
40#[repr(transparent)]
42#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
43pub struct StateByteLen(pub usize);
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub struct StateSaveOutcome {
47 pub generation: u64,
48 pub byte_len: StateByteLen,
49 pub payload_checksum: u64,
50}
51
52pub struct StateFile {
55 path: Option<PathBuf>,
56 schema_version: u32,
57 sync_on_save: bool,
58 generation: u64,
59 recovery: StateRecoveryStats,
60 cached: Option<Vec<u8>>,
61}
62
63impl StateFile {
64 pub fn open(path: impl AsRef<Path>, schema_version: u32) -> Result<Self, PersistenceError> {
65 Self::open_with_sync(path, schema_version, true)
66 }
67
68 pub fn open_with_sync(
69 path: impl AsRef<Path>,
70 schema_version: u32,
71 sync_on_save: bool,
72 ) -> Result<Self, PersistenceError> {
73 let path = path.as_ref().to_path_buf();
74 #[cfg(not(target_arch = "wasm32"))]
75 let (recovery, cached) = {
76 require_file_name(&path)?;
77 if let Some(parent) = path.parent()
78 && !parent.as_os_str().is_empty()
79 {
80 std::fs::create_dir_all(parent)?;
81 }
82 let mut r = StateRecoveryStats::default();
83 let mut cached = None;
84 match std::fs::File::open(&path) {
85 Ok(mut file) => {
86 let mut raw = Vec::new();
87 match read_file_bounded(
88 &mut file,
89 MAX_STATE_FILE_BYTES + STATE_FILE_HEADER_SIZE,
90 &mut raw,
91 ) {
92 Ok(()) => match Self::decode_envelope(&raw, schema_version) {
93 Ok(payload) => {
94 r.loaded_from_disk = true;
95 r.generation = 1;
96 cached = Some(payload.to_vec());
97 }
98 Err(PersistenceError::SchemaMismatch { expected, actual }) => {
99 if actual < expected {
100 drop(file);
101 backup_rotated_file(&path, &format!("v{actual}"))?;
102 r.rotated_from_older_schema = Some(actual);
103 } else {
104 return Err(PersistenceError::SchemaMismatch {
105 expected,
106 actual,
107 });
108 }
109 }
110 Err(
111 PersistenceError::Corrupt(_) | PersistenceError::PayloadTooLarge(_),
112 ) => {
113 drop(file);
114 backup_corrupt_file(&path);
115 r.recovered_from_corrupt = true;
116 }
117 Err(e) => return Err(e),
118 },
119 Err(ReadBoundedError::Io(e)) => return Err(PersistenceError::Io(e)),
120 Err(ReadBoundedError::TooLarge) => {
121 drop(file);
122 backup_corrupt_file(&path);
123 r.recovered_from_corrupt = true;
124 }
125 }
126 }
127 Err(e) if e.kind() == io::ErrorKind::NotFound => {}
128 Err(e) => return Err(PersistenceError::Io(e)),
129 }
130 (r, cached)
131 };
132 #[cfg(target_arch = "wasm32")]
133 let (recovery, cached) = (StateRecoveryStats::default(), None);
134
135 Ok(Self {
136 path: Some(path),
137 schema_version,
138 sync_on_save,
139 generation: recovery.generation,
140 recovery,
141 cached,
142 })
143 }
144
145 pub fn new_in_memory(schema_version: u32) -> Self {
146 Self {
147 path: None,
148 schema_version,
149 sync_on_save: false,
150 generation: 0,
151 recovery: StateRecoveryStats::default(),
152 cached: None,
153 }
154 }
155
156 #[inline]
157 pub fn path(&self) -> Option<&Path> {
158 self.path.as_deref()
159 }
160
161 #[inline]
162 pub fn schema_version(&self) -> u32 {
163 self.schema_version
164 }
165
166 #[inline]
167 pub fn generation(&self) -> u64 {
168 self.generation
169 }
170
171 #[inline]
172 pub fn recovery_stats(&self) -> StateRecoveryStats {
173 self.recovery
174 }
175
176 pub fn encode_envelope(
177 schema_version: u32,
178 payload: &[u8],
179 ) -> Result<Vec<u8>, PersistenceError> {
180 if payload.len() > MAX_STATE_FILE_BYTES {
181 return Err(PersistenceError::PayloadTooLarge(payload.len()));
182 }
183 let len = u32::try_from(payload.len())
184 .map_err(|_| PersistenceError::PayloadTooLarge(payload.len()))?;
185 let mut out = Vec::with_capacity(STATE_FILE_HEADER_SIZE + payload.len());
186 out.extend_from_slice(&STATE_FILE_MAGIC);
187 out.extend_from_slice(&schema_version.to_le_bytes());
188 out.extend_from_slice(&len.to_le_bytes());
189 let checksum = state_envelope_xxh64(&out[0..16], payload);
190 out.extend_from_slice(&checksum.to_le_bytes());
191 out.extend_from_slice(payload);
192 Ok(out)
193 }
194
195 pub fn decode_envelope(bytes: &[u8], expected_schema: u32) -> Result<&[u8], PersistenceError> {
196 if bytes.len() > MAX_STATE_FILE_BYTES + STATE_FILE_HEADER_SIZE {
197 return Err(PersistenceError::PayloadTooLarge(bytes.len()));
198 }
199 if bytes.len() < STATE_FILE_HEADER_SIZE {
200 return Err(PersistenceError::Corrupt("state file truncated"));
201 }
202 let mut r = ByteReader::new(&bytes[..STATE_FILE_HEADER_SIZE]);
203 let magic = r
204 .read_array::<8>()
205 .map_err(|_| PersistenceError::Corrupt("state file truncated"))?;
206 let schema = r
207 .read_u32()
208 .map_err(|_| PersistenceError::Corrupt("state file truncated"))?;
209 let payload_len = r
210 .read_u32()
211 .map_err(|_| PersistenceError::Corrupt("state file truncated"))?
212 as usize;
213 let expected_hash = r
214 .read_u64()
215 .map_err(|_| PersistenceError::Corrupt("state file truncated"))?;
216 let payload = &bytes[STATE_FILE_HEADER_SIZE..];
217 if state_envelope_xxh64(&bytes[0..16], payload) != expected_hash {
218 return Err(PersistenceError::Corrupt("state envelope XXH64 mismatch"));
219 }
220 if magic != STATE_FILE_MAGIC {
221 return Err(PersistenceError::Corrupt("invalid state file magic"));
222 }
223 if payload.len() != payload_len {
224 return Err(PersistenceError::Corrupt("state payload length mismatch"));
225 }
226 if schema != expected_schema {
227 return Err(PersistenceError::SchemaMismatch {
228 expected: expected_schema,
229 actual: schema,
230 });
231 }
232 Ok(payload)
233 }
234
235 pub fn load(&self) -> Result<Option<Vec<u8>>, PersistenceError> {
238 Ok(self.cached.clone())
239 }
240
241 pub fn save(&mut self, payload: &[u8]) -> Result<StateSaveOutcome, PersistenceError> {
242 let env = Self::encode_envelope(self.schema_version, payload)?;
243 let payload_checksum = xxh64(payload, STATE_XXH64_SEED);
244 let byte_len = env.len();
245 if let Some(path) = self.path.as_deref() {
246 write_file_atomic(path, &env, self.sync_on_save)?;
247 }
248 self.cached = Some(payload.to_vec());
249 self.generation = self.generation.saturating_add(1);
250 Ok(StateSaveOutcome {
251 generation: self.generation,
252 byte_len: StateByteLen(byte_len),
253 payload_checksum,
254 })
255 }
256
257 pub fn quarantine_corrupt(&mut self) -> Result<(), PersistenceError> {
259 #[cfg(not(target_arch = "wasm32"))]
260 if let Some(path) = self.path.as_deref() {
261 backup_corrupt_file(path);
262 }
263 self.cached = None;
264 self.generation = 0;
265 self.recovery.loaded_from_disk = false;
266 self.recovery.recovered_from_corrupt = true;
267 self.recovery.generation = 0;
268 Ok(())
269 }
270
271 pub fn reset(&mut self) -> Result<(), PersistenceError> {
272 #[cfg(not(target_arch = "wasm32"))]
273 if let Some(path) = self.path.as_deref() {
274 Self::remove(path)?;
275 }
276 self.cached = None;
277 Ok(())
278 }
279
280 #[cfg(not(target_arch = "wasm32"))]
282 pub fn remove(path: &Path) -> Result<(), PersistenceError> {
283 require_file_name(path)?;
284 match std::fs::remove_file(path) {
285 Ok(()) => Ok(()),
286 Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
287 Err(e) => Err(PersistenceError::Io(e)),
288 }
289 }
290}
291
292#[cfg(not(target_arch = "wasm32"))]
294fn require_file_name(path: &Path) -> Result<(), PersistenceError> {
295 if path.file_name().is_none() {
296 return Err(PersistenceError::Io(io::Error::new(
297 io::ErrorKind::InvalidInput,
298 "state file path must include a file name",
299 )));
300 }
301 Ok(())
302}