Skip to main content

crisol_core/state/
journal.rs

1//! The append-only command journal and macros recorded from it.
2//!
3//! Every dispatched command can be appended with its arguments and a timestamp. A
4//! recorded range becomes a named macro; replaying the same `(command, args)` sequence
5//! is deterministic, so a recorded session doubles as a regression test.
6//!
7//! ```
8//! use crisol_core::state::journal;
9//! ```
10
11#[cfg(feature = "threads")]
12use std::path::Path;
13
14use serde_json::Value;
15
16use crate::commands::{Command, CommandId, CommandRegistry};
17
18/// One recorded command.
19#[derive(Clone, Debug, PartialEq)]
20#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
21#[non_exhaustive]
22/// # Example
23///
24/// ```
25/// use crisol_core::state::JournalEntry;
26/// ```
27pub struct JournalEntry {
28    /// Monotonic sequence number, starting at 1.
29    pub sequence: u64,
30    /// Seconds on the application clock (or Unix time).
31    pub timestamp: f64,
32    /// The command that ran.
33    pub command: CommandId,
34    /// Arguments, if the command has any.
35    pub args: Option<Value>,
36    /// A human label for the journal view.
37    pub label: Option<String>,
38}
39
40impl JournalEntry {
41    /// The command id and its arguments.
42    pub fn command(&self) -> &CommandId {
43        &self.command
44    }
45
46    /// The argument value.
47    pub fn args(&self) -> Option<&Value> {
48        self.args.as_ref()
49    }
50}
51
52/// A versioned, append-only journal.
53#[derive(Clone, Debug, PartialEq)]
54#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
55#[non_exhaustive]
56/// # Example
57///
58/// ```
59/// use crisol_core::state::CommandJournal;
60/// ```
61pub struct CommandJournal {
62    /// File format version. Currently 1.
63    pub version: u32,
64    /// The entries, oldest first.
65    pub entries: Vec<JournalEntry>,
66    next_sequence: u64,
67}
68
69impl Default for CommandJournal {
70    fn default() -> Self {
71        Self::new()
72    }
73}
74
75impl CommandJournal {
76    /// The current file version.
77    pub const VERSION: u32 = 1;
78
79    /// An empty journal.
80    pub fn new() -> Self {
81        Self {
82            version: Self::VERSION,
83            entries: Vec::new(),
84            next_sequence: 1,
85        }
86    }
87
88    /// Export the journal as a Python replay script.
89    pub fn export_python(&self) -> String {
90        let mut script = String::from("# Generated by crisol: replay this journal headlessly.\n");
91        for entry in &self.entries {
92            let id = entry.command.as_str().replace('\\', "\\\\").replace('"', "\\\"");
93            match &entry.args {
94                Some(args) => {
95                    script.push_str(&format!("run(\"{id}\", {args})\n"));
96                }
97                None => script.push_str(&format!("run(\"{id}\")\n")),
98            }
99        }
100        script
101    }
102
103    /// Export the journal as a Rust replay array.
104    pub fn export_rust(&self) -> String {
105        let mut out = String::from("// Generated by crisol: replay this journal.\n");
106        out.push_str("let commands = [\n");
107        for entry in &self.entries {
108            out.push_str(&format!("    \"{}\",\n", entry.command.as_str()));
109        }
110        out.push_str("];\n");
111        out
112    }
113
114    /// Append a command with no arguments.
115    pub fn append(&mut self, command: impl Into<CommandId>) -> &JournalEntry {
116        self.append_at(0.0, command, None, None)
117    }
118
119    /// Append a command with arguments.
120    pub fn append_with(
121        &mut self,
122        command: impl Into<CommandId>,
123        args: Value,
124        label: impl Into<String>,
125    ) -> &JournalEntry {
126        self.append_at(0.0, command, Some(args), Some(label.into()))
127    }
128
129    /// Append a command with an explicit timestamp.
130    pub fn append_at(
131        &mut self,
132        timestamp: f64,
133        command: impl Into<CommandId>,
134        args: Option<Value>,
135        label: Option<String>,
136    ) -> &JournalEntry {
137        let sequence = self.next_sequence;
138        self.next_sequence += 1;
139        self.entries.push(JournalEntry {
140            sequence,
141            timestamp,
142            command: command.into(),
143            args,
144            label,
145        });
146        // Just pushed; the journal never removes entries outside `clear`.
147        #[allow(clippy::indexing_slicing)]
148        &self.entries[self.entries.len() - 1]
149    }
150
151    /// The entries.
152    pub fn entries(&self) -> &[JournalEntry] {
153        &self.entries
154    }
155
156    /// Number of entries.
157    pub fn len(&self) -> usize {
158        self.entries.len()
159    }
160
161    /// Whether the journal is empty.
162    pub fn is_empty(&self) -> bool {
163        self.entries.is_empty()
164    }
165
166    /// The newest entry.
167    pub fn last(&self) -> Option<&JournalEntry> {
168        self.entries.last()
169    }
170
171    /// Entries with a sequence greater than `sequence`.
172    pub fn since(&self, sequence: u64) -> &[JournalEntry] {
173        let start = self.entries.partition_point(|entry| entry.sequence <= sequence);
174        self.entries.get(start..).unwrap_or_default()
175    }
176
177    /// Remove every entry and reset the sequence.
178    pub fn clear(&mut self) {
179        self.entries.clear();
180        self.next_sequence = 1;
181    }
182
183    /// Serialize the journal as pretty JSON.
184    ///
185    /// # Errors
186    /// When serialization fails (it does not for these types).
187    pub fn to_json(&self) -> Result<String, JournalError> {
188        serde_json::to_string_pretty(self).map_err(|error| JournalError::Json(error.to_string()))
189    }
190
191    /// Parse a journal, rejecting a newer version.
192    ///
193    /// # Errors
194    /// When the JSON is malformed or the version is newer than [`Self::VERSION`].
195    pub fn from_json(json: &str) -> Result<Self, JournalError> {
196        let journal: Self = serde_json::from_str(json).map_err(|error| JournalError::Json(error.to_string()))?;
197        if journal.version > Self::VERSION {
198            return Err(JournalError::UnsupportedVersion(journal.version));
199        }
200        Ok(journal)
201    }
202
203    /// Write the journal atomically.
204    ///
205    /// # Errors
206    /// When serialization or the write fails.
207    #[cfg(feature = "threads")]
208    pub fn save(&self, path: impl AsRef<Path>) -> Result<(), JournalError> {
209        let json = self.to_json()?;
210        crate::storage::atomic_write(path.as_ref(), json.as_bytes())
211            .map_err(|error| JournalError::Io(error.to_string()))
212    }
213
214    /// Read a journal from disk.
215    ///
216    /// # Errors
217    /// When the file cannot be read or parsed.
218    #[cfg(feature = "threads")]
219    pub fn load(path: impl AsRef<Path>) -> Result<Self, JournalError> {
220        let text = std::fs::read_to_string(path).map_err(|error| JournalError::Io(error.to_string()))?;
221        Self::from_json(&text)
222    }
223}
224
225/// A named sequence of journal entries.
226#[derive(Clone, Debug, PartialEq)]
227#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
228#[non_exhaustive]
229/// # Example
230///
231/// ```
232/// use crisol_core::state::Macro;
233/// ```
234pub struct Macro {
235    /// Display name.
236    pub name: String,
237    /// The registry id a macro is registered under.
238    pub command: CommandId,
239    /// The steps, in order.
240    pub steps: Vec<JournalEntry>,
241}
242
243impl Macro {
244    /// Replay the steps through `run`. The function receives each step's command and
245    /// arguments in the recorded order; no window or clock is involved.
246    pub fn replay(&self, mut run: impl FnMut(&JournalEntry)) {
247        for step in &self.steps {
248            run(step);
249        }
250    }
251
252    /// A registry id from a macro name, such as `macro.align-and-fit`.
253    pub fn command_id(name: &str) -> CommandId {
254        let slug: String = name
255            .chars()
256            .map(|character| {
257                if character.is_ascii_alphanumeric() {
258                    character.to_ascii_lowercase()
259                } else {
260                    '-'
261                }
262            })
263            .collect();
264        let slug = slug.trim_matches('-');
265        CommandId::new(format!("macro.{}", if slug.is_empty() { "untitled" } else { slug }))
266    }
267}
268
269/// The named macros, versioned for the workspace file.
270#[derive(Clone, Debug, Default, PartialEq)]
271#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
272#[non_exhaustive]
273/// # Example
274///
275/// ```
276/// use crisol_core::state::MacroLibrary;
277/// ```
278pub struct MacroLibrary {
279    /// File format version.
280    pub version: u32,
281    /// The macros.
282    pub macros: Vec<Macro>,
283}
284
285impl MacroLibrary {
286    /// The current file version.
287    pub const VERSION: u32 = 1;
288
289    /// An empty library.
290    pub fn new() -> Self {
291        Self {
292            version: Self::VERSION,
293            macros: Vec::new(),
294        }
295    }
296
297    /// Record the entries after `after_sequence` as a new macro and return it.
298    pub fn record_from(&mut self, journal: &CommandJournal, after_sequence: u64, name: impl Into<String>) -> &Macro {
299        let name = name.into();
300        let steps = journal.since(after_sequence).to_vec();
301        let command = Macro::command_id(&name);
302        self.macros.push(Macro { name, command, steps });
303        // Just pushed.
304        #[allow(clippy::indexing_slicing)]
305        &self.macros[self.macros.len() - 1]
306    }
307
308    /// Add an existing macro.
309    pub fn add(&mut self, macro_: Macro) {
310        self.macros.push(macro_);
311    }
312
313    /// The macros.
314    pub fn iter(&self) -> impl Iterator<Item = &Macro> {
315        self.macros.iter()
316    }
317
318    /// A macro by name.
319    pub fn get(&self, name: &str) -> Option<&Macro> {
320        self.macros.iter().find(|macro_| macro_.name == name)
321    }
322
323    /// A macro by its command id.
324    pub fn by_command(&self, command: &CommandId) -> Option<&Macro> {
325        self.macros.iter().find(|macro_| &macro_.command == command)
326    }
327
328    /// Register every macro as a command in `registry`.
329    pub fn register(&self, registry: &mut CommandRegistry) {
330        for macro_ in &self.macros {
331            registry.register(
332                Command::new(macro_.command.clone(), format!("Run macro: {}", macro_.name))
333                    .category("Macros")
334                    .description(format!("{} recorded steps", macro_.steps.len())),
335            );
336        }
337    }
338}
339
340/// Why a journal file could not be read or written.
341#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
342#[non_exhaustive]
343/// # Example
344///
345/// ```
346/// use crisol_core::state::JournalError;
347/// ```
348pub enum JournalError {
349    /// The JSON is malformed.
350    #[error("invalid journal JSON: {0}")]
351    Json(String),
352    /// The file version is newer than this crate understands.
353    #[error("unsupported journal version {0}")]
354    UnsupportedVersion(u32),
355    /// The file could not be read or written.
356    #[error("{0}")]
357    Io(String),
358}
359
360#[cfg(all(test, feature = "threads"))]
361mod tests {
362    use super::*;
363
364    #[test]
365    fn entries_are_append_only_and_sequenced() {
366        let mut journal = CommandJournal::new();
367        journal.append_at(1.0, "file.new", None, Some("New".to_owned()));
368        journal.append_with("file.save", Value::from(1), "Save");
369        assert_eq!(journal.len(), 2);
370        assert_eq!(journal.last().map(|entry| entry.sequence), Some(2));
371        assert_eq!(journal.since(1).len(), 1);
372        assert_eq!(journal.since(0).len(), 2);
373        assert!(journal.last().and_then(JournalEntry::args).is_some());
374    }
375
376    #[test]
377    fn a_macro_replays_the_recorded_commands() {
378        let mut journal = CommandJournal::new();
379        journal.append("file.new");
380        journal.append("edit.type");
381        let mut library = MacroLibrary::new();
382        let macro_ = library.record_from(&journal, 1, "New and type").clone();
383        assert_eq!(macro_.steps.len(), 1);
384        let mut replayed = Vec::new();
385        macro_.replay(|step| replayed.push(step.command.to_string()));
386        assert_eq!(replayed, ["edit.type"]);
387        assert_eq!(macro_.command.to_string(), "macro.new-and-type");
388    }
389
390    #[test]
391    fn registered_macros_are_commands() {
392        let mut journal = CommandJournal::new();
393        journal.append("file.new");
394        let mut library = MacroLibrary::new();
395        library.record_from(&journal, 0, "New");
396        let mut registry = CommandRegistry::new();
397        library.register(&mut registry);
398        assert!(registry.get(&Macro::command_id("New")).is_some());
399    }
400
401    #[test]
402    fn the_journal_round_trips_and_rejects_a_newer_version() {
403        let mut journal = CommandJournal::new();
404        journal.append_with("file.save", Value::from("a.rs"), "Save");
405        let json = journal.to_json().expect("serialize");
406        let back = CommandJournal::from_json(&json).expect("parse");
407        assert_eq!(back, journal);
408        let newer = json.replace("\"version\": 1", "\"version\": 9");
409        assert!(matches!(
410            CommandJournal::from_json(&newer),
411            Err(JournalError::UnsupportedVersion(9))
412        ));
413    }
414
415    #[test]
416    fn macros_round_trip_through_json() {
417        let mut journal = CommandJournal::new();
418        journal.append("file.new");
419        let mut library = MacroLibrary::new();
420        library.record_from(&journal, 0, "New");
421        let json = serde_json::to_string(&library).expect("serialize");
422        let back: MacroLibrary = serde_json::from_str(&json).expect("deserialize");
423        assert_eq!(back, library);
424    }
425}
426
427#[cfg(test)]
428mod export_tests {
429    use super::*;
430
431    #[test]
432    fn the_journal_exports_python_and_rust() {
433        let mut journal = CommandJournal::new();
434        journal.append("file.save");
435        journal.append("edit.paste");
436        let python = journal.export_python();
437        let rust = journal.export_rust();
438        assert!(python.contains("run(\"file.save\")"));
439        assert!(rust.contains("\"edit.paste\""));
440    }
441}