crisol-core 1.0.0

Crisol core: an egui-free data model, themes, metrics, localization, commands, state, and storage.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Hot exit and crash recovery: dirty buffers stashed on a timer or on close, restored
//! with the workspace and journal after a crash.
//!
//! ```
//! use crisol_core::state::recovery;
//! ```

use std::path::Path;

use serde::{Deserialize, Serialize};

use super::journal::CommandJournal;
use super::session::Workspace;

/// One dirty buffer in the stash.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::state::StashDocument;
/// ```
pub struct StashDocument {
    /// Matches [`super::session::WorkspaceDocument::id`].
    pub id: String,
    /// Title at the time of the stash.
    pub title: String,
    /// The unsaved text.
    pub text: String,
}

impl StashDocument {
    /// A stashed buffer.
    pub fn new(id: impl Into<String>, title: impl Into<String>, text: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            title: title.into(),
            text: text.into(),
        }
    }
}

/// The versioned dirty-buffer stash.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::state::Stash;
/// ```
pub struct Stash {
    /// File format version.
    pub version: u32,
    /// The application clock when the stash was written.
    pub saved_at: f64,
    /// Dirty buffers.
    pub documents: Vec<StashDocument>,
}

impl Default for Stash {
    fn default() -> Self {
        Self {
            version: Self::VERSION,
            saved_at: 0.0,
            documents: Vec::new(),
        }
    }
}

impl Stash {
    /// The current file version.
    pub const VERSION: u32 = 1;

    /// An empty stash.
    pub fn new() -> Self {
        Self::default()
    }

    /// Capture dirty buffers. Buffers that are not dirty are skipped by the caller; this
    /// constructor keeps whatever it is given.
    pub fn capture(saved_at: f64, documents: impl IntoIterator<Item = StashDocument>) -> Self {
        Self {
            version: Self::VERSION,
            saved_at,
            documents: documents.into_iter().collect(),
        }
    }

    /// Whether there is anything to recover.
    pub fn is_empty(&self) -> bool {
        self.documents.is_empty()
    }

    /// Serialize as pretty JSON.
    ///
    /// # Errors
    /// When serialization fails (it does not for this type).
    pub fn to_json(&self) -> Result<String, RecoveryError> {
        serde_json::to_string_pretty(self).map_err(|error| RecoveryError::Json(error.to_string()))
    }

    /// Parse a stash, rejecting a newer version.
    ///
    /// # Errors
    /// When the JSON is malformed or the version is newer.
    pub fn from_json(json: &str) -> Result<Self, RecoveryError> {
        let stash: Self = serde_json::from_str(json).map_err(|error| RecoveryError::Json(error.to_string()))?;
        if stash.version > Self::VERSION {
            return Err(RecoveryError::UnsupportedVersion(stash.version));
        }
        Ok(stash)
    }

    /// Write atomically.
    ///
    /// # Errors
    /// When serialization or the write fails.
    #[cfg(feature = "threads")]
    pub fn save(&self, path: impl AsRef<Path>) -> Result<(), RecoveryError> {
        let json = self.to_json()?;
        crate::storage::atomic_write(path.as_ref(), json.as_bytes())
            .map_err(|error| RecoveryError::Io(error.to_string()))
    }

    /// Read from disk.
    ///
    /// # Errors
    /// When the file cannot be read or parsed.
    #[cfg(feature = "threads")]
    pub fn load(path: impl AsRef<Path>) -> Result<Self, RecoveryError> {
        let text = std::fs::read_to_string(path).map_err(|error| RecoveryError::Io(error.to_string()))?;
        Self::from_json(&text)
    }
}

/// What was found after a crash.
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::state::Recovery;
/// ```
pub struct Recovery {
    /// The workspace, when the file exists and parses.
    pub workspace: Option<Workspace>,
    /// The dirty-buffer stash.
    pub stash: Option<Stash>,
    /// The journal.
    pub journal: Option<CommandJournal>,
    /// Files that were present but could not be read.
    pub warnings: Vec<String>,
}

impl Recovery {
    /// A one-line description to show the user, or `None` when nothing was recovered.
    pub fn notice(&self) -> Option<String> {
        if self.workspace.is_none() && self.stash.is_none() && self.journal.is_none() {
            return None;
        }
        let mut parts = Vec::new();
        if let Some(workspace) = &self.workspace {
            parts.push(format!("{} tab(s)", workspace.documents.len()));
        }
        if let Some(stash) = &self.stash {
            parts.push(format!("{} unsaved buffer(s)", stash.documents.len()));
        }
        if let Some(journal) = &self.journal {
            parts.push(format!("{} journal entries", journal.len()));
        }
        Some(format!("Recovered {}", parts.join(", ")))
    }
}

/// Read the workspace, stash, and journal from a session directory.
///
/// A missing file is not a warning; a present file that fails to parse is, so a single
/// corrupt file does not block the rest of the recovery.
#[cfg(feature = "threads")]
/// # Example
///
/// ```
/// use crisol_core::state::recover;
/// ```
pub fn recover(directory: impl AsRef<Path>) -> Recovery {
    let directory = directory.as_ref();
    let mut recovery = Recovery::default();

    let workspace_path = directory.join("workspace.json");
    if workspace_path.is_file() {
        match Workspace::load(&workspace_path) {
            Ok(workspace) => recovery.workspace = Some(workspace),
            Err(error) => recovery.warnings.push(format!("{}: {error}", workspace_path.display())),
        }
    }

    let stash_path = directory.join("stash.json");
    if stash_path.is_file() {
        match Stash::load(&stash_path) {
            Ok(stash) => recovery.stash = Some(stash),
            Err(error) => recovery.warnings.push(format!("{}: {error}", stash_path.display())),
        }
    }

    let journal_path = directory.join("journal.json");
    if journal_path.is_file() {
        match CommandJournal::load(&journal_path) {
            Ok(journal) => recovery.journal = Some(journal),
            Err(error) => recovery.warnings.push(format!("{}: {error}", journal_path.display())),
        }
    }

    recovery
}

/// A timer for the hot-exit stash.
///
/// Call [`Self::due`] every frame; when it returns true, write the workspace, the dirty
/// buffers, and the journal with [`Self::save`]. The close path calls `save` once more
/// regardless of the timer.
#[derive(Clone, Debug, PartialEq)]
/// # Example
///
/// ```
/// use crisol_core::state::HotExit;
/// ```
pub struct HotExit {
    /// Seconds between automatic stashes.
    pub interval: f64,
    /// The clock of the last stash.
    pub last_saved: f64,
}

impl HotExit {
    /// A timer with a 10 s interval.
    pub fn new() -> Self {
        Self {
            interval: 10.0,
            last_saved: 0.0,
        }
    }

    /// A timer with a custom interval, clamped to at least one second.
    pub fn with_interval(interval: f64) -> Self {
        Self {
            interval: interval.max(1.0),
            last_saved: 0.0,
        }
    }

    /// Whether a stash is due at `now`.
    pub fn due(&self, now: f64) -> bool {
        now - self.last_saved >= self.interval
    }

    /// Write all three files and move the timer.
    ///
    /// # Errors
    /// When a file cannot be serialized or written.
    #[cfg(feature = "threads")]
    pub fn save(
        &mut self,
        now: f64,
        paths: &SessionPaths,
        workspace: &Workspace,
        stash: &Stash,
        journal: &CommandJournal,
    ) -> Result<(), RecoveryError> {
        workspace
            .save(paths.workspace())
            .map_err(|error| RecoveryError::Io(error.to_string()))?;
        stash.save(paths.stash())?;
        journal
            .save(paths.journal())
            .map_err(|error| RecoveryError::Io(error.to_string()))?;
        self.last_saved = now;
        Ok(())
    }
}

impl Default for HotExit {
    fn default() -> Self {
        Self::new()
    }
}

pub use crate::storage::SessionPaths;

/// Why recovery data could not be read or written.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::state::RecoveryError;
/// ```
pub enum RecoveryError {
    /// Malformed JSON.
    #[error("invalid recovery JSON: {0}")]
    Json(String),
    /// A newer file version.
    #[error("unsupported recovery version {0}")]
    UnsupportedVersion(u32),
    /// A read or write failure.
    #[error("{0}")]
    Io(String),
}

#[cfg(all(test, feature = "threads"))]
mod tests {
    use super::*;

    fn test_directory(prefix: &str) -> std::path::PathBuf {
        let thread: String = std::thread::current()
            .name()
            .unwrap_or("test")
            .chars()
            .map(|character| {
                if character.is_ascii_alphanumeric() {
                    character
                } else {
                    '_'
                }
            })
            .collect();
        std::env::temp_dir().join(format!("{prefix}-{}-{thread}", std::process::id()))
    }

    use crate::state::session::WorkspaceDocument;
    use std::path::PathBuf;

    fn directory() -> PathBuf {
        test_directory("crisol-recovery")
    }

    #[test]
    fn recovery_reads_workspace_stash_and_journal() {
        let directory = directory();
        let _ = std::fs::remove_dir_all(&directory);
        std::fs::create_dir_all(&directory).expect("create");
        let paths = SessionPaths::new(&directory);
        let mut workspace = Workspace::new();
        workspace.add_document(WorkspaceDocument::new("a", "A"));
        workspace.save(paths.workspace()).expect("workspace");
        Stash::capture(1.0, [StashDocument::new("a", "A", "unsaved")])
            .save(paths.stash())
            .expect("stash");
        let mut journal = CommandJournal::new();
        journal.append("file.new");
        journal.save(paths.journal()).expect("journal");

        let recovery = recover(&directory);
        assert_eq!(recovery.workspace.as_ref().map(|ws| ws.documents.len()), Some(1));
        assert_eq!(recovery.stash.as_ref().map(|stash| stash.documents.len()), Some(1));
        assert_eq!(recovery.journal.as_ref().map(CommandJournal::len), Some(1));
        assert!(recovery.warnings.is_empty());
        assert!(recovery.notice().is_some());
        let _ = std::fs::remove_dir_all(directory);
    }

    #[test]
    fn a_corrupt_file_is_a_warning_not_a_failure() {
        let directory = directory();
        let _ = std::fs::remove_dir_all(&directory);
        std::fs::create_dir_all(&directory).expect("create");
        let paths = SessionPaths::new(&directory);
        std::fs::write(paths.stash(), b"not json").expect("write");
        let recovery = recover(&directory);
        assert!(recovery.stash.is_none());
        assert_eq!(recovery.warnings.len(), 1);
        assert!(recovery.notice().is_none());
        let _ = std::fs::remove_dir_all(directory);
    }

    #[test]
    fn the_hot_exit_timer_fires_and_writes_all_files() {
        let directory = directory();
        let _ = std::fs::remove_dir_all(&directory);
        std::fs::create_dir_all(&directory).expect("create");
        let paths = SessionPaths::new(&directory);
        let mut timer = HotExit::with_interval(5.0);
        assert!(timer.due(5.0));
        let workspace = Workspace::new();
        let stash = Stash::new();
        let journal = CommandJournal::new();
        timer.save(5.0, &paths, &workspace, &stash, &journal).expect("save");
        assert!(!timer.due(9.0));
        assert!(timer.due(10.0));
        assert!(paths.workspace().is_file());
        assert!(paths.stash().is_file());
        assert!(paths.journal().is_file());
        let _ = std::fs::remove_dir_all(directory);
    }

    #[test]
    fn a_stash_round_trips() {
        let stash = Stash::capture(2.0, [StashDocument::new("a", "A", "text")]);
        let json = stash.to_json().expect("serialize");
        let back = Stash::from_json(&json).expect("parse");
        assert_eq!(back, stash);
        assert!(!back.is_empty());
    }
}