1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
47#[serde(rename_all = "lowercase")]
48pub enum Source {
49 Main,
50 Backup,
51}
52
53#[derive(Clone, Debug, PartialEq)]
55pub struct Read<T> {
56 pub value: T,
57 pub source: Source,
58 pub from_version: u32,
59 pub notes: Vec<String>,
61}
62
63#[derive(Debug)]
65pub enum PersistError {
66 Io {
67 path: PathBuf,
68 error: io::Error,
69 },
70 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#[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 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 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 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 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 ¬es {
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
239pub const DEBOUNCE: f64 = 1.0;
242
243const LONGEST: f64 = 5.0;
246
247#[derive(Clone, Debug, Default)]
249struct Slot {
250 pending: Option<String>,
252 due: f64,
254 since: f64,
256 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#[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 pub fn persist(&self) -> &Persist {
290 &self.persist
291 }
292
293 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 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 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 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 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 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 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 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 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 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 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}