Skip to main content

egui_pop_core/
persist.rs

1//! The persistence driver (ADR 0008): documents saved atomically with one
2//! backup, loaded through their schema's migrations, falling back to the
3//! backup when the main file is missing or unreadable.
4//!
5//! ```
6//! use egui_pop_core::persist::Persist;
7//! use egui_pop_model::values::{SettingsDoc, settings_schema};
8//!
9//! let dir = std::env::temp_dir().join(format!("egui-pop-doc-{}", std::process::id()));
10//! let persist = Persist::new(&dir);
11//! persist.save("settings", &settings_schema(), &SettingsDoc::default()).unwrap();
12//! let back = persist.load::<SettingsDoc>("settings", &settings_schema()).unwrap().unwrap();
13//! assert!(back.value.values.is_empty());
14//! # std::fs::remove_dir_all(&dir).unwrap();
15//! ```
16//!
17//! A [`Writer`] writes documents a short while after their last change
18//! (debounced, about a second), so what the user changed survives a
19//! crash and nothing waits for the exit:
20//!
21//! ```
22//! use egui_pop_core::persist::{Persist, Writer};
23//!
24//! let dir = std::env::temp_dir().join(format!("egui-pop-writer-{}", std::process::id()));
25//! let mut w = Writer::new(Persist::new(&dir), 1.0);
26//! assert!(w.offer("view", "{\"a\": 1}".into(), 10.0));
27//! assert!(w.offer("view", "{\"a\": 2}".into(), 10.5)); // the deadline moves
28//! assert!(w.tick(11.0).is_empty());
29//! assert_eq!(w.tick(11.5).len(), 1);
30//! assert!(!w.offer("view", "{\"a\": 2}".into(), 12.0)); // written already
31//! # std::fs::remove_dir_all(&dir).unwrap();
32//! ```
33
34use std::collections::BTreeMap;
35use std::fmt;
36use std::fs;
37use std::hash::{Hash as _, Hasher as _};
38use std::io::{self, Write as _};
39use std::path::{Path, PathBuf};
40
41use egui_pop_model::doc::{DocError, Schema};
42use serde::Serialize;
43use serde::de::DeserializeOwned;
44
45/// Which file a document came from.
46#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
47#[serde(rename_all = "lowercase")]
48pub enum Source {
49    Main,
50    Backup,
51}
52
53/// A document loaded from disk.
54#[derive(Clone, Debug, PartialEq)]
55pub struct Read<T> {
56    pub value: T,
57    pub source: Source,
58    pub from_version: u32,
59    /// What happened on the way: migrations, a fallback to the backup.
60    pub notes: Vec<String>,
61}
62
63/// Why a document could not be read or written.
64#[derive(Debug)]
65pub enum PersistError {
66    Io {
67        path: PathBuf,
68        error: io::Error,
69    },
70    /// Neither file could be read as a document.
71    Doc {
72        path: PathBuf,
73        error: DocError,
74        backup: Option<DocError>,
75    },
76}
77
78impl fmt::Display for PersistError {
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        match self {
81            PersistError::Io { path, error } => write!(f, "{}: {error}", path.display()),
82            PersistError::Doc {
83                path,
84                error,
85                backup,
86            } => {
87                write!(f, "{}: {error}", path.display())?;
88                if let Some(b) = backup {
89                    write!(f, " (backup: {b})")?;
90                }
91                Ok(())
92            }
93        }
94    }
95}
96
97impl std::error::Error for PersistError {}
98
99/// Documents in a directory: `<name>.json`, its backup `<name>.json.bak`
100/// and, while writing, `<name>.json.tmp`.
101#[derive(Clone, Debug)]
102pub struct Persist {
103    dir: PathBuf,
104}
105
106fn io_err(path: &Path) -> impl FnOnce(io::Error) -> PersistError + '_ {
107    move |error| PersistError::Io {
108        path: path.to_path_buf(),
109        error,
110    }
111}
112
113impl Persist {
114    pub fn new(dir: impl Into<PathBuf>) -> Self {
115        Self { dir: dir.into() }
116    }
117
118    pub fn dir(&self) -> &Path {
119        &self.dir
120    }
121
122    /// The path of a document.
123    pub fn path(&self, name: &str) -> PathBuf {
124        self.dir.join(format!("{name}.json"))
125    }
126
127    fn backup(&self, name: &str) -> PathBuf {
128        self.dir.join(format!("{name}.json.bak"))
129    }
130
131    /// Writes a document's text atomically, keeping the previous one as
132    /// the backup.
133    /// A name may hold `/` (`workspaces/photos/layout`): its folders are
134    /// made.
135    pub fn save_text(&self, name: &str, text: &str) -> Result<(), PersistError> {
136        let path = self.path(name);
137        let dir = path.parent().unwrap_or(&self.dir).to_path_buf();
138        fs::create_dir_all(&dir).map_err(io_err(&dir))?;
139        let tmp = self.dir.join(format!("{name}.json.tmp"));
140        {
141            let mut f = fs::File::create(&tmp).map_err(io_err(&tmp))?;
142            f.write_all(text.as_bytes()).map_err(io_err(&tmp))?;
143            f.sync_all().map_err(io_err(&tmp))?;
144        }
145        if path.exists() {
146            fs::rename(&path, self.backup(name)).map_err(io_err(&path))?;
147        }
148        fs::rename(&tmp, &path).map_err(io_err(&path))?;
149        Ok(())
150    }
151
152    /// Saves a document at its schema's current version.
153    pub fn save<T: Serialize>(
154        &self,
155        name: &str,
156        schema: &Schema,
157        value: &T,
158    ) -> Result<(), PersistError> {
159        let path = self.path(name);
160        let text = schema.save(value).map_err(|error| PersistError::Doc {
161            path,
162            error,
163            backup: None,
164        })?;
165        self.save_text(name, &text)
166    }
167
168    /// Loads a document: `None` when there is none (neither file exists).
169    pub fn load<T: DeserializeOwned>(
170        &self,
171        name: &str,
172        schema: &Schema,
173    ) -> Result<Option<Read<T>>, PersistError> {
174        let path = self.path(name);
175        let backup = self.backup(name);
176        let read = |p: &Path| -> Option<Result<String, io::Error>> {
177            match fs::read_to_string(p) {
178                Err(e) if e.kind() == io::ErrorKind::NotFound => None,
179                r => Some(r),
180            }
181        };
182        let main_error = match read(&path) {
183            None => None,
184            Some(Err(error)) => return Err(PersistError::Io { path, error }),
185            Some(Ok(text)) => match schema.load::<T>(&text) {
186                Ok(l) => {
187                    return Ok(Some(Read {
188                        value: l.value,
189                        source: Source::Main,
190                        from_version: l.from_version,
191                        notes: l.migrated.iter().map(|m| format!("migrated {m}")).collect(),
192                    }));
193                }
194                Err(e) => Some(e),
195            },
196        };
197        match read(&backup) {
198            None => match main_error {
199                None => Ok(None),
200                Some(error) => Err(PersistError::Doc {
201                    path,
202                    error,
203                    backup: None,
204                }),
205            },
206            Some(Err(error)) => Err(PersistError::Io {
207                path: backup,
208                error,
209            }),
210            Some(Ok(text)) => match schema.load::<T>(&text) {
211                Ok(l) => {
212                    let mut notes = vec![match &main_error {
213                        Some(e) => {
214                            format!("{} is unreadable ({e}): the backup is used", path.display())
215                        }
216                        None => format!("{} is missing: the backup is used", path.display()),
217                    }];
218                    notes.extend(l.migrated.iter().map(|m| format!("migrated {m}")));
219                    for n in &notes {
220                        log::warn!(target: "egui_pop", "{n}");
221                    }
222                    Ok(Some(Read {
223                        value: l.value,
224                        source: Source::Backup,
225                        from_version: l.from_version,
226                        notes,
227                    }))
228                }
229                Err(b) => Err(PersistError::Doc {
230                    path,
231                    error: main_error.unwrap_or(DocError::Parse("missing".into())),
232                    backup: Some(b),
233                }),
234            },
235        }
236    }
237}
238
239/// How long a [`Writer`] waits after a document's last change, by
240/// default, in seconds.
241pub const DEBOUNCE: f64 = 1.0;
242
243/// How long, at most, a document changing all the time waits, as a
244/// multiple of the delay.
245const LONGEST: f64 = 5.0;
246
247/// One document waiting to be written.
248#[derive(Clone, Debug, Default)]
249struct Slot {
250    /// The text to write, when it differs from what was written.
251    pending: Option<String>,
252    /// When to write it.
253    due: f64,
254    /// When the first unwritten change came (bounds the wait).
255    since: f64,
256    /// A fingerprint of what was written last.
257    written: Option<u64>,
258}
259
260fn fingerprint(text: &str) -> u64 {
261    let mut h = std::collections::hash_map::DefaultHasher::new();
262    text.hash(&mut h);
263    h.finish()
264}
265
266/// Writes documents a short while after their last change: each offer of
267/// a new text moves its deadline (`delay` seconds later, at most five
268/// delays after the first unwritten change); an offer of what was
269/// written last does nothing. Times are the caller's clock, in seconds
270/// (`motion::now` in an application). Writes are atomic
271/// ([`Persist::save_text`]).
272#[derive(Clone, Debug)]
273pub struct Writer {
274    persist: Persist,
275    delay: f64,
276    docs: BTreeMap<String, Slot>,
277}
278
279impl Writer {
280    pub fn new(persist: Persist, delay: f64) -> Self {
281        Self {
282            persist,
283            delay: delay.max(0.0),
284            docs: BTreeMap::new(),
285        }
286    }
287
288    /// Where it writes.
289    pub fn persist(&self) -> &Persist {
290        &self.persist
291    }
292
293    /// Offers a document's text: scheduled when it differs from what was
294    /// written last (or waits already). Whether it is to be written.
295    pub fn offer(&mut self, name: &str, text: String, now: f64) -> bool {
296        let print = fingerprint(&text);
297        let slot = self.docs.entry(name.to_string()).or_default();
298        if slot.pending.is_none() && slot.written == Some(print) {
299            return false;
300        }
301        if slot.pending.as_deref() == Some(text.as_str()) {
302            return true;
303        }
304        if slot.written == Some(print) {
305            // Back to what is on disk: nothing to write.
306            slot.pending = None;
307            return false;
308        }
309        if slot.pending.is_none() {
310            slot.since = now;
311        }
312        slot.pending = Some(text);
313        slot.due = (now + self.delay).min(slot.since + self.delay * LONGEST);
314        true
315    }
316
317    /// Offers a document at its schema's current version.
318    pub fn offer_doc<T: Serialize>(
319        &mut self,
320        name: &str,
321        schema: &Schema,
322        value: &T,
323        now: f64,
324    ) -> Result<bool, PersistError> {
325        let text = schema.save(value).map_err(|error| PersistError::Doc {
326            path: self.persist.path(name),
327            error,
328            backup: None,
329        })?;
330        Ok(self.offer(name, text, now))
331    }
332
333    /// Records that a document's text is on disk (loaded, or written by
334    /// someone else): offering it again writes nothing.
335    pub fn written(&mut self, name: &str, text: &str) {
336        let slot = self.docs.entry(name.to_string()).or_default();
337        slot.written = Some(fingerprint(text));
338        slot.pending = None;
339    }
340
341    /// The documents waiting, by name.
342    pub fn pending(&self) -> Vec<&str> {
343        self.docs
344            .iter()
345            .filter(|(_, s)| s.pending.is_some())
346            .map(|(n, _)| n.as_str())
347            .collect()
348    }
349
350    /// When the next write is due, if one waits.
351    pub fn next_due(&self) -> Option<f64> {
352        self.docs
353            .values()
354            .filter(|s| s.pending.is_some())
355            .map(|s| s.due)
356            .reduce(f64::min)
357    }
358
359    /// Writes the documents whose deadline passed; what was written, and
360    /// how it went. A failed write stays pending.
361    pub fn tick(&mut self, now: f64) -> Vec<(String, Result<(), PersistError>)> {
362        let due: Vec<String> = self
363            .docs
364            .iter()
365            .filter(|(_, s)| s.pending.is_some() && s.due <= now)
366            .map(|(n, _)| n.clone())
367            .collect();
368        due.into_iter().map(|n| self.write(n, now)).collect()
369    }
370
371    /// Writes every waiting document now.
372    pub fn flush(&mut self) -> Vec<(String, Result<(), PersistError>)> {
373        let due: Vec<String> = self.pending().into_iter().map(str::to_string).collect();
374        due.into_iter()
375            .map(|n| self.write(n, f64::INFINITY))
376            .collect()
377    }
378
379    fn write(&mut self, name: String, now: f64) -> (String, Result<(), PersistError>) {
380        let Some(slot) = self.docs.get_mut(&name) else {
381            return (name, Ok(()));
382        };
383        let Some(text) = slot.pending.take() else {
384            return (name, Ok(()));
385        };
386        let out = self.persist.save_text(&name, &text);
387        match &out {
388            Ok(()) => slot.written = Some(fingerprint(&text)),
389            Err(e) => {
390                log::warn!(target: "egui_pop", "writing `{name}`: {e}");
391                // Tried again after another delay.
392                slot.pending = Some(text);
393                if now.is_finite() {
394                    slot.due = now + self.delay;
395                }
396            }
397        }
398        (name, out)
399    }
400}
401
402#[cfg(test)]
403mod writer_tests {
404    use super::*;
405
406    fn dir(tag: &str) -> PathBuf {
407        std::env::temp_dir().join(format!("egui-pop-writer-{tag}-{}", std::process::id()))
408    }
409
410    #[test]
411    fn a_document_is_written_once_its_changes_settle() {
412        let d = dir("settle");
413        let mut w = Writer::new(Persist::new(&d), 1.0);
414        assert!(w.next_due().is_none());
415        assert!(w.offer("a", "1".into(), 0.0));
416        assert!(w.offer("a", "2".into(), 0.8));
417        assert_eq!(w.next_due(), Some(1.8));
418        assert!(w.tick(1.0).is_empty());
419        let wrote = w.tick(1.8);
420        assert_eq!(wrote.len(), 1);
421        assert!(wrote[0].1.is_ok());
422        assert_eq!(fs::read_to_string(d.join("a.json")).unwrap(), "2");
423        // The same text again: nothing; back and forth before the
424        // deadline: nothing either.
425        assert!(!w.offer("a", "2".into(), 2.0));
426        assert!(w.offer("a", "3".into(), 2.0));
427        assert!(!w.offer("a", "2".into(), 2.1));
428        assert!(w.pending().is_empty());
429        fs::remove_dir_all(&d).unwrap();
430    }
431
432    #[test]
433    fn a_document_changing_all_the_time_is_still_written() {
434        let d = dir("busy");
435        let mut w = Writer::new(Persist::new(&d), 1.0);
436        let mut wrote = 0;
437        for i in 0..100 {
438            let now = i as f64 * 0.1;
439            w.offer("b", format!("{i}"), now);
440            wrote += w.tick(now).len();
441        }
442        // Ten seconds of changes every tenth of a second: written every
443        // five seconds at least.
444        assert!(wrote >= 1, "{wrote}");
445        assert!(w.flush().len() == 1 || w.pending().is_empty());
446        assert!(w.pending().is_empty());
447        w.written("c", "x");
448        assert!(!w.offer("c", "x".into(), 0.0));
449        fs::remove_dir_all(&d).unwrap();
450    }
451}