Skip to main content

victauri_core/
recording.rs

1//! Time-travel recording: captures event streams and state checkpoints
2//! for replay and debugging.
3
4use chrono::{DateTime, Utc};
5use serde::{Deserialize, Serialize};
6use std::collections::VecDeque;
7use std::sync::{Arc, Mutex};
8
9use crate::error::VictauriError;
10use crate::event::{AppEvent, IpcCall};
11
12const DEFAULT_MAX_CHECKPOINTS: usize = 1000;
13const DEFAULT_MAX_EVENTS: usize = 50_000;
14
15/// A snapshot of application state taken at a specific point during recording.
16#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
17pub struct StateCheckpoint {
18    /// Unique identifier for this checkpoint.
19    pub id: String,
20    /// Optional human-readable label for the checkpoint.
21    pub label: Option<String>,
22    /// When the checkpoint was created.
23    pub timestamp: DateTime<Utc>,
24    /// Serialized application state at the checkpoint.
25    pub state: serde_json::Value,
26    /// Index into the event stream at the time of this checkpoint.
27    pub event_index: usize,
28}
29
30/// A complete recorded session with events and state checkpoints. Serializable for export/import.
31#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
32pub struct RecordedSession {
33    /// Unique session identifier (UUID).
34    pub id: String,
35    /// When the recording session began.
36    pub started_at: DateTime<Utc>,
37    /// All events captured during the session, in order.
38    pub events: Vec<RecordedEvent>,
39    /// State checkpoints created during the session.
40    pub checkpoints: Vec<StateCheckpoint>,
41}
42
43/// A single event captured during a recording session, with its sequence index.
44#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
45pub struct RecordedEvent {
46    /// Monotonically increasing sequence number within the recording session.
47    pub index: usize,
48    /// When the event occurred.
49    pub timestamp: DateTime<Utc>,
50    /// The captured application event.
51    pub event: AppEvent,
52}
53
54/// Thread-safe session recorder for time-travel debugging. Records events and
55/// state checkpoints during a recording session. Only one session can be active at a time.
56#[derive(Debug, Clone)]
57pub struct EventRecorder {
58    recording: Arc<Mutex<Option<ActiveRecording>>>,
59    last_session: Arc<Mutex<Option<RecordedSession>>>,
60    max_events: usize,
61}
62
63#[derive(Debug, Clone)]
64struct ActiveRecording {
65    session_id: String,
66    started_at: DateTime<Utc>,
67    events: VecDeque<RecordedEvent>,
68    checkpoints: VecDeque<StateCheckpoint>,
69    event_counter: usize,
70    max_events: usize,
71    max_checkpoints: usize,
72}
73
74impl EventRecorder {
75    /// Creates a new recorder with the given maximum event capacity.
76    ///
77    /// ```
78    /// use victauri_core::EventRecorder;
79    ///
80    /// let recorder = EventRecorder::new(1000);
81    /// assert!(!recorder.is_recording());
82    /// assert_eq!(recorder.event_count(), 0);
83    /// ```
84    #[must_use]
85    pub fn new(max_events: usize) -> Self {
86        Self {
87            recording: Arc::new(Mutex::new(None)),
88            last_session: Arc::new(Mutex::new(None)),
89            max_events,
90        }
91    }
92
93    /// Starts a new recording session; returns `Err` if one is already active.
94    ///
95    /// # Errors
96    ///
97    /// Returns [`VictauriError::RecordingAlreadyActive`] if a session is already in progress.
98    ///
99    /// # Examples
100    ///
101    /// ```
102    /// use victauri_core::EventRecorder;
103    ///
104    /// let recorder = EventRecorder::new(1000);
105    /// recorder.start("session-1".to_string()).unwrap();
106    /// assert!(recorder.is_recording());
107    /// ```
108    pub fn start(&self, session_id: String) -> crate::error::Result<()> {
109        let mut rec = crate::acquire_lock(&self.recording, "EventRecorder");
110        if rec.is_some() {
111            return Err(VictauriError::RecordingAlreadyActive);
112        }
113        *rec = Some(ActiveRecording {
114            session_id,
115            started_at: Utc::now(),
116            events: VecDeque::new(),
117            checkpoints: VecDeque::new(),
118            event_counter: 0,
119            max_events: self.max_events,
120            max_checkpoints: DEFAULT_MAX_CHECKPOINTS,
121        });
122        Ok(())
123    }
124
125    /// Stops the active recording and returns the completed session, or None if not recording.
126    ///
127    /// # Examples
128    ///
129    /// ```
130    /// use victauri_core::EventRecorder;
131    ///
132    /// let recorder = EventRecorder::new(1000);
133    /// recorder.start("session-1".to_string()).unwrap();
134    /// let session = recorder.stop().expect("should return session");
135    /// assert_eq!(session.id, "session-1");
136    /// assert!(!recorder.is_recording());
137    /// ```
138    #[must_use]
139    pub fn stop(&self) -> Option<RecordedSession> {
140        let mut rec = crate::acquire_lock(&self.recording, "EventRecorder");
141        rec.take().map(|r| {
142            let session = RecordedSession {
143                id: r.session_id,
144                started_at: r.started_at,
145                events: r.events.into_iter().collect(),
146                checkpoints: r.checkpoints.into_iter().collect(),
147            };
148            *crate::acquire_lock(&self.last_session, "EventRecorder::last_session") =
149                Some(session.clone());
150            session
151        })
152    }
153
154    /// Returns true if a recording session is currently active.
155    #[must_use]
156    pub fn is_recording(&self) -> bool {
157        crate::acquire_lock(&self.recording, "EventRecorder").is_some()
158    }
159
160    /// Appends an event to the active recording, evicting the oldest if at capacity.
161    pub fn record_event(&self, event: AppEvent) {
162        let mut rec = crate::acquire_lock(&self.recording, "EventRecorder");
163        if let Some(ref mut active) = *rec {
164            let timestamp = event.timestamp();
165            let index = active.event_counter;
166            active.event_counter += 1;
167
168            if active.events.len() >= active.max_events {
169                active.events.pop_front();
170            }
171
172            active.events.push_back(RecordedEvent {
173                index,
174                timestamp,
175                event,
176            });
177        }
178    }
179
180    /// Creates a named state checkpoint at the current event index; returns `Err` if not recording.
181    ///
182    /// # Errors
183    ///
184    /// Returns [`VictauriError::NoActiveRecording`] if no session is in progress.
185    pub fn checkpoint(
186        &self,
187        id: String,
188        label: Option<String>,
189        state: serde_json::Value,
190    ) -> crate::error::Result<()> {
191        let mut rec = crate::acquire_lock(&self.recording, "EventRecorder");
192        if let Some(ref mut active) = *rec {
193            let event_index = active.event_counter;
194            if active.checkpoints.len() >= active.max_checkpoints {
195                active.checkpoints.pop_front();
196            }
197            active.checkpoints.push_back(StateCheckpoint {
198                id,
199                label,
200                timestamp: Utc::now(),
201                state,
202                event_index,
203            });
204            Ok(())
205        } else {
206            Err(VictauriError::NoActiveRecording)
207        }
208    }
209
210    /// Returns the number of events recorded so far, or 0 if not recording.
211    #[must_use]
212    pub fn event_count(&self) -> usize {
213        crate::acquire_lock(&self.recording, "EventRecorder")
214            .as_ref()
215            .map_or(0, |r| r.events.len())
216    }
217
218    /// Returns the number of checkpoints created so far, or 0 if not recording.
219    #[must_use]
220    pub fn checkpoint_count(&self) -> usize {
221        crate::acquire_lock(&self.recording, "EventRecorder")
222            .as_ref()
223            .map_or(0, |r| r.checkpoints.len())
224    }
225
226    /// Returns all events with an index >= the given value.
227    #[must_use]
228    pub fn events_since(&self, index: usize) -> Vec<RecordedEvent> {
229        let rec = crate::acquire_lock(&self.recording, "EventRecorder");
230        match rec.as_ref() {
231            Some(active) => active
232                .events
233                .iter()
234                .filter(|e| e.index >= index)
235                .cloned()
236                .collect(),
237            None => Vec::new(),
238        }
239    }
240
241    /// Returns events whose timestamps fall within the given inclusive range.
242    #[must_use]
243    pub fn events_between(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> Vec<RecordedEvent> {
244        let rec = crate::acquire_lock(&self.recording, "EventRecorder");
245        match rec.as_ref() {
246            Some(active) => active
247                .events
248                .iter()
249                .filter(|e| e.timestamp >= from && e.timestamp <= to)
250                .cloned()
251                .collect(),
252            None => Vec::new(),
253        }
254    }
255
256    /// Returns all checkpoints from the active recording session.
257    #[must_use]
258    pub fn get_checkpoints(&self) -> Vec<StateCheckpoint> {
259        let rec = crate::acquire_lock(&self.recording, "EventRecorder");
260        match rec.as_ref() {
261            Some(active) => active.checkpoints.iter().cloned().collect(),
262            None => Vec::new(),
263        }
264    }
265
266    /// Returns events recorded between two named checkpoints.
267    ///
268    /// # Errors
269    ///
270    /// - [`VictauriError::NoActiveRecording`] if no session is active.
271    /// - [`VictauriError::CheckpointNotFound`] if either checkpoint ID does not exist.
272    pub fn events_between_checkpoints(
273        &self,
274        from_checkpoint_id: &str,
275        to_checkpoint_id: &str,
276    ) -> crate::error::Result<Vec<RecordedEvent>> {
277        let rec = crate::acquire_lock(&self.recording, "EventRecorder");
278        let active = rec.as_ref().ok_or(VictauriError::NoActiveRecording)?;
279
280        let from_idx = active
281            .checkpoints
282            .iter()
283            .find(|c| c.id == from_checkpoint_id)
284            .ok_or_else(|| VictauriError::CheckpointNotFound {
285                id: from_checkpoint_id.to_string(),
286            })?
287            .event_index;
288        let to_idx = active
289            .checkpoints
290            .iter()
291            .find(|c| c.id == to_checkpoint_id)
292            .ok_or_else(|| VictauriError::CheckpointNotFound {
293                id: to_checkpoint_id.to_string(),
294            })?
295            .event_index;
296
297        let (start, end) = if from_idx <= to_idx {
298            (from_idx, to_idx)
299        } else {
300            (to_idx, from_idx)
301        };
302
303        Ok(active
304            .events
305            .iter()
306            .filter(|e| e.index >= start && e.index < end)
307            .cloned()
308            .collect())
309    }
310
311    /// Snapshot the current recording as a session WITHOUT stopping it.
312    /// Falls back to the last stopped session if no active recording.
313    #[must_use]
314    pub fn export(&self) -> Option<RecordedSession> {
315        let rec = crate::acquire_lock(&self.recording, "EventRecorder");
316        if let Some(r) = rec.as_ref() {
317            return Some(RecordedSession {
318                id: r.session_id.clone(),
319                started_at: r.started_at,
320                events: r.events.iter().cloned().collect(),
321                checkpoints: r.checkpoints.iter().cloned().collect(),
322            });
323        }
324        drop(rec);
325        crate::acquire_lock(&self.last_session, "EventRecorder::last_session").clone()
326    }
327
328    /// Import a previously exported session, replacing any active recording.
329    pub fn import(&self, session: RecordedSession) {
330        let event_counter = session.events.last().map_or(0, |e| e.index + 1);
331        let max_events = self.max_events;
332        let mut rec = crate::acquire_lock(&self.recording, "EventRecorder");
333        *rec = Some(ActiveRecording {
334            session_id: session.id,
335            started_at: session.started_at,
336            events: session.events.into_iter().collect(),
337            checkpoints: session.checkpoints.into_iter().collect(),
338            event_counter,
339            max_events,
340            max_checkpoints: DEFAULT_MAX_CHECKPOINTS,
341        });
342    }
343
344    /// Extracts IPC calls in order from the active recording or last stopped session for replay.
345    #[must_use]
346    pub fn ipc_replay_sequence(&self) -> Vec<IpcCall> {
347        let rec = crate::acquire_lock(&self.recording, "EventRecorder");
348        if let Some(active) = rec.as_ref() {
349            return active
350                .events
351                .iter()
352                .filter_map(|re| match &re.event {
353                    AppEvent::Ipc(call) => Some(call.clone()),
354                    _ => None,
355                })
356                .collect();
357        }
358        drop(rec);
359        let last = crate::acquire_lock(&self.last_session, "EventRecorder::last_session");
360        last.as_ref().map_or_else(Vec::new, |session| {
361            session
362                .events
363                .iter()
364                .filter_map(|re| match &re.event {
365                    AppEvent::Ipc(call) => Some(call.clone()),
366                    _ => None,
367                })
368                .collect()
369        })
370    }
371}
372
373impl Default for EventRecorder {
374    fn default() -> Self {
375        Self::new(DEFAULT_MAX_EVENTS)
376    }
377}