Skip to main content

runifold_core/
recorder.rs

1use std::{fmt, sync::Arc};
2
3use crate::{EventFactory, EventId, Journal, JournalError, RunEvent, RunEventKind, RunId};
4
5/// Cloneable event emitter bound to one run and a shared journal.
6#[derive(Clone)]
7pub struct RunRecorder {
8    journal: Arc<dyn Journal>,
9    events: Arc<EventFactory>,
10}
11
12impl RunRecorder {
13    /// Creates a recorder for one run.
14    pub fn new(journal: Arc<dyn Journal>, run_id: RunId, parent_run_id: Option<RunId>) -> Self {
15        Self {
16            journal,
17            events: Arc::new(EventFactory::new(run_id, parent_run_id)),
18        }
19    }
20
21    /// Creates a recorder for a child run using the same journal.
22    #[must_use]
23    pub fn child(&self, run_id: RunId, parent_run_id: RunId) -> Self {
24        Self::new(self.journal.clone(), run_id, Some(parent_run_id))
25    }
26
27    /// Emits and records one immutable event.
28    ///
29    /// # Errors
30    ///
31    /// Returns [`JournalError`] when the journal rejects the event.
32    pub fn record(
33        &self,
34        kind: RunEventKind,
35        caused_by: Option<EventId>,
36    ) -> Result<RunEvent, JournalError> {
37        let event = self.events.emit(kind, caused_by);
38        self.journal.record(&event)?;
39        Ok(event)
40    }
41}
42
43impl fmt::Debug for RunRecorder {
44    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
45        formatter.write_str("RunRecorder(..)")
46    }
47}