Skip to main content

allsource_core/application/services/
replay.rs

1use crate::{
2    application::{dto::QueryEventsRequest, services::projection::Projection},
3    domain::entities::Event,
4    error::{AllSourceError, Result},
5    store::EventStore,
6};
7use chrono::{DateTime, Utc};
8use parking_lot::RwLock;
9use serde::{Deserialize, Serialize};
10use std::sync::{
11    Arc,
12    atomic::{AtomicBool, AtomicU64, Ordering},
13};
14use uuid::Uuid;
15
16/// Status of a replay operation
17#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
18#[serde(rename_all = "lowercase")]
19pub enum ReplayStatus {
20    /// Replay is pending and hasn't started yet
21    Pending,
22    /// Replay is currently running
23    Running,
24    /// Replay completed successfully
25    Completed,
26    /// Replay failed with an error
27    Failed,
28    /// Replay was cancelled by user
29    Cancelled,
30}
31
32/// Configuration for replay operations
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct ReplayConfig {
35    /// Batch size for processing events
36    pub batch_size: usize,
37
38    /// Whether to run replay in parallel
39    pub parallel: bool,
40
41    /// Number of parallel workers (if parallel is true)
42    pub workers: usize,
43
44    /// Whether to emit progress events
45    pub emit_progress: bool,
46
47    /// Progress reporting interval (every N events)
48    pub progress_interval: usize,
49}
50
51impl Default for ReplayConfig {
52    fn default() -> Self {
53        Self {
54            batch_size: 1000,
55            parallel: false,
56            workers: 4,
57            emit_progress: true,
58            progress_interval: 1000,
59        }
60    }
61}
62
63/// Request to start a replay operation
64#[derive(Debug, Clone, Serialize, Deserialize)]
65pub struct StartReplayRequest {
66    /// Optional projection name to rebuild (if None, replays all projections)
67    pub projection_name: Option<String>,
68
69    /// Start from this timestamp (if None, starts from beginning)
70    pub from_timestamp: Option<DateTime<Utc>>,
71
72    /// End at this timestamp (if None, goes to end)
73    pub to_timestamp: Option<DateTime<Utc>>,
74
75    /// Filter by entity_id (optional)
76    pub entity_id: Option<String>,
77
78    /// Filter by event_type (optional)
79    pub event_type: Option<String>,
80
81    /// Replay configuration
82    pub config: Option<ReplayConfig>,
83}
84
85/// Response from starting a replay
86#[derive(Debug, Clone, Serialize, Deserialize)]
87pub struct StartReplayResponse {
88    pub replay_id: Uuid,
89    pub status: ReplayStatus,
90    pub started_at: DateTime<Utc>,
91    pub total_events: usize,
92}
93
94/// Progress information for a replay
95#[derive(Debug, Clone, Serialize, Deserialize)]
96pub struct ReplayProgress {
97    pub replay_id: Uuid,
98    pub status: ReplayStatus,
99    pub started_at: DateTime<Utc>,
100    pub updated_at: DateTime<Utc>,
101    pub completed_at: Option<DateTime<Utc>>,
102    pub total_events: usize,
103    pub processed_events: usize,
104    pub failed_events: usize,
105    pub progress_percentage: f64,
106    pub events_per_second: f64,
107    pub error_message: Option<String>,
108}
109
110/// Manages event replay and projection rebuilding
111pub struct ReplayManager {
112    /// Active replay operations
113    replays: Arc<RwLock<Vec<ReplayState>>>,
114}
115
116/// Internal state for a replay operation
117struct ReplayState {
118    id: Uuid,
119    projection_name: Option<String>,
120    status: Arc<RwLock<ReplayStatus>>,
121    started_at: DateTime<Utc>,
122    completed_at: Arc<RwLock<Option<DateTime<Utc>>>>,
123    total_events: usize,
124    processed_events: Arc<AtomicU64>,
125    failed_events: Arc<AtomicU64>,
126    error_message: Arc<RwLock<Option<String>>>,
127    cancelled: Arc<AtomicBool>,
128}
129
130impl ReplayManager {
131    pub fn new() -> Self {
132        Self {
133            replays: Arc::new(RwLock::new(Vec::new())),
134        }
135    }
136
137    /// Start a replay operation
138    pub fn start_replay(
139        &self,
140        store: Arc<EventStore>,
141        request: StartReplayRequest,
142    ) -> Result<StartReplayResponse> {
143        let replay_id = Uuid::new_v4();
144        let started_at = Utc::now();
145        let config = request.config.unwrap_or_default();
146
147        // Query events to replay
148        let query = QueryEventsRequest {
149            entity_id: request.entity_id.clone(),
150            event_type: request.event_type.clone(),
151            tenant_id: None,
152            as_of: request.to_timestamp,
153            since: request.from_timestamp,
154            until: request.to_timestamp,
155            limit: None,
156            event_type_prefix: None,
157            exclude_event_type_prefix: None,
158            payload_filter: None,
159        };
160
161        let events = store.query(&query)?;
162        let total_events = events.len();
163
164        tracing::info!(
165            "🔄 Starting replay {} for {} events{}",
166            replay_id,
167            total_events,
168            request
169                .projection_name
170                .as_ref()
171                .map(|n| format!(" (projection: {n})"))
172                .unwrap_or_default()
173        );
174
175        // Create replay state
176        let state = ReplayState {
177            id: replay_id,
178            projection_name: request.projection_name.clone(),
179            status: Arc::new(RwLock::new(ReplayStatus::Running)),
180            started_at,
181            completed_at: Arc::new(RwLock::new(None)),
182            total_events,
183            processed_events: Arc::new(AtomicU64::new(0)),
184            failed_events: Arc::new(AtomicU64::new(0)),
185            error_message: Arc::new(RwLock::new(None)),
186            cancelled: Arc::new(AtomicBool::new(false)),
187        };
188
189        // Store replay state
190        self.replays.write().push(state);
191
192        // Get the state references we need
193        let replays = Arc::clone(&self.replays);
194        let replay_idx = replays.read().len() - 1;
195
196        // Spawn replay task
197        tokio::spawn(async move {
198            let result = Self::run_replay(
199                store,
200                events,
201                request.projection_name,
202                config,
203                replays.clone(),
204                replay_idx,
205            )
206            .await;
207
208            // Update final status
209            let mut replays_lock = replays.write();
210            if let Some(state) = replays_lock.get_mut(replay_idx) {
211                *state.completed_at.write() = Some(Utc::now());
212
213                match result {
214                    Ok(()) => {
215                        if state.cancelled.load(Ordering::Relaxed) {
216                            *state.status.write() = ReplayStatus::Cancelled;
217                            tracing::info!("🛑 Replay {} cancelled", state.id);
218                        } else {
219                            *state.status.write() = ReplayStatus::Completed;
220                            tracing::info!("✅ Replay {} completed successfully", state.id);
221                        }
222                    }
223                    Err(e) => {
224                        *state.status.write() = ReplayStatus::Failed;
225                        *state.error_message.write() = Some(e.to_string());
226                        tracing::error!("❌ Replay {} failed: {}", state.id, e);
227                    }
228                }
229            }
230        });
231
232        Ok(StartReplayResponse {
233            replay_id,
234            status: ReplayStatus::Running,
235            started_at,
236            total_events,
237        })
238    }
239
240    /// Internal replay execution
241    async fn run_replay(
242        store: Arc<EventStore>,
243        events: Vec<Event>,
244        projection_name: Option<String>,
245        config: ReplayConfig,
246        replays: Arc<RwLock<Vec<ReplayState>>>,
247        replay_idx: usize,
248    ) -> Result<()> {
249        let total = events.len();
250        let projections = store.projections.read();
251
252        // Get target projection(s)
253        let target_projections: Vec<(String, Arc<dyn Projection>)> =
254            if let Some(name) = projection_name {
255                if let Some(proj) = projections.get_projection(&name) {
256                    vec![(name, proj)]
257                } else {
258                    return Err(AllSourceError::ValidationError(format!(
259                        "Projection not found: {name}"
260                    )));
261                }
262            } else {
263                projections.list_projections()
264            };
265
266        drop(projections); // Release lock
267
268        // Process events in batches
269        for (batch_idx, chunk) in events.chunks(config.batch_size).enumerate() {
270            // Check if cancelled
271            {
272                let replays_lock = replays.read();
273                if let Some(state) = replays_lock.get(replay_idx)
274                    && state.cancelled.load(Ordering::Relaxed)
275                {
276                    return Ok(());
277                }
278            }
279
280            // Process batch
281            for event in chunk {
282                // Apply event to each target projection
283                for (proj_name, projection) in &target_projections {
284                    if let Err(e) = projection.process(event) {
285                        tracing::warn!(
286                            "Failed to process event {} in projection {}: {}",
287                            event.id,
288                            proj_name,
289                            e
290                        );
291
292                        // Increment failed counter
293                        let replays_lock = replays.read();
294                        if let Some(state) = replays_lock.get(replay_idx) {
295                            state.failed_events.fetch_add(1, Ordering::Relaxed);
296                        }
297                    }
298                }
299
300                // Increment processed counter
301                let replays_lock = replays.read();
302                if let Some(state) = replays_lock.get(replay_idx) {
303                    let processed = state.processed_events.fetch_add(1, Ordering::Relaxed) + 1;
304
305                    // Emit progress
306                    if config.emit_progress && processed % config.progress_interval as u64 == 0 {
307                        let progress = (processed as f64 / total as f64) * 100.0;
308                        tracing::debug!(
309                            "Replay progress: {}/{} ({:.1}%)",
310                            processed,
311                            total,
312                            progress
313                        );
314                    }
315                }
316            }
317        }
318
319        Ok(())
320    }
321
322    /// Get progress for a replay operation
323    pub fn get_progress(&self, replay_id: Uuid) -> Result<ReplayProgress> {
324        let replays = self.replays.read();
325
326        let state = replays.iter().find(|r| r.id == replay_id).ok_or_else(|| {
327            AllSourceError::ValidationError(format!("Replay not found: {replay_id}"))
328        })?;
329
330        let processed = state.processed_events.load(Ordering::Relaxed);
331        let failed = state.failed_events.load(Ordering::Relaxed);
332        let total_events = state.total_events;
333        let started_at = state.started_at;
334        let status = *state.status.read();
335        let completed_at = *state.completed_at.read();
336        let error_message = state.error_message.read().clone();
337
338        drop(replays); // Release lock before calculations
339
340        let progress_percentage = if total_events > 0 {
341            (processed as f64 / total_events as f64) * 100.0
342        } else {
343            0.0
344        };
345
346        let updated_at = Utc::now();
347        let elapsed_seconds = (updated_at - started_at).num_seconds().max(1) as f64;
348        let events_per_second = processed as f64 / elapsed_seconds;
349
350        Ok(ReplayProgress {
351            replay_id,
352            status,
353            started_at,
354            updated_at,
355            completed_at,
356            total_events,
357            processed_events: processed as usize,
358            failed_events: failed as usize,
359            progress_percentage,
360            events_per_second,
361            error_message,
362        })
363    }
364
365    /// Cancel a running replay
366    pub fn cancel_replay(&self, replay_id: Uuid) -> Result<()> {
367        let replays = self.replays.read();
368
369        let state = replays.iter().find(|r| r.id == replay_id).ok_or_else(|| {
370            AllSourceError::ValidationError(format!("Replay not found: {replay_id}"))
371        })?;
372
373        let status = *state.status.read();
374        if status != ReplayStatus::Running {
375            return Err(AllSourceError::ValidationError(format!(
376                "Cannot cancel replay in status: {status:?}"
377            )));
378        }
379
380        state.cancelled.store(true, Ordering::Relaxed);
381        tracing::info!("🛑 Cancelling replay {}", replay_id);
382
383        Ok(())
384    }
385
386    /// List all replay operations
387    pub fn list_replays(&self) -> Vec<ReplayProgress> {
388        let replays = self.replays.read();
389
390        replays
391            .iter()
392            .map(|state| {
393                let processed = state.processed_events.load(Ordering::Relaxed);
394                let failed = state.failed_events.load(Ordering::Relaxed);
395                let progress_percentage = if state.total_events > 0 {
396                    (processed as f64 / state.total_events as f64) * 100.0
397                } else {
398                    0.0
399                };
400
401                let updated_at = Utc::now();
402                let elapsed_seconds = (updated_at - state.started_at).num_seconds().max(1) as f64;
403                let events_per_second = processed as f64 / elapsed_seconds;
404
405                ReplayProgress {
406                    replay_id: state.id,
407                    status: *state.status.read(),
408                    started_at: state.started_at,
409                    updated_at,
410                    completed_at: *state.completed_at.read(),
411                    total_events: state.total_events,
412                    processed_events: processed as usize,
413                    failed_events: failed as usize,
414                    progress_percentage,
415                    events_per_second,
416                    error_message: state.error_message.read().clone(),
417                }
418            })
419            .collect()
420    }
421
422    /// Delete a completed or failed replay from history
423    pub fn delete_replay(&self, replay_id: Uuid) -> Result<bool> {
424        let mut replays = self.replays.write();
425
426        let idx = replays
427            .iter()
428            .position(|r| r.id == replay_id)
429            .ok_or_else(|| {
430                AllSourceError::ValidationError(format!("Replay not found: {replay_id}"))
431            })?;
432
433        let status = *replays[idx].status.read();
434        if status == ReplayStatus::Running {
435            return Err(AllSourceError::ValidationError(
436                "Cannot delete a running replay. Cancel it first.".to_string(),
437            ));
438        }
439
440        replays.remove(idx);
441        tracing::info!("🗑️  Deleted replay {}", replay_id);
442
443        Ok(true)
444    }
445}
446
447impl Default for ReplayManager {
448    fn default() -> Self {
449        Self::new()
450    }
451}
452
453#[cfg(test)]
454mod tests {
455    use super::*;
456    use crate::domain::entities::Event;
457    use serde_json::json;
458
459    #[tokio::test]
460    async fn test_replay_manager_creation() {
461        let manager = ReplayManager::new();
462        let replays = manager.list_replays();
463        assert_eq!(replays.len(), 0);
464    }
465
466    #[tokio::test]
467    async fn test_replay_progress_tracking() {
468        let manager = ReplayManager::new();
469        let store = Arc::new(EventStore::new());
470
471        // Ingest some test events
472        for i in 0..10 {
473            let event = Event::from_strings(
474                "test.event".to_string(),
475                "test-entity".to_string(),
476                "default".to_string(),
477                json!({"value": i}),
478                None,
479            )
480            .unwrap();
481            store.ingest(&event).unwrap();
482        }
483
484        // Start replay
485        let request = StartReplayRequest {
486            projection_name: None,
487            from_timestamp: None,
488            to_timestamp: None,
489            entity_id: None,
490            event_type: None,
491            config: Some(ReplayConfig {
492                batch_size: 5,
493                parallel: false,
494                workers: 1,
495                emit_progress: true,
496                progress_interval: 5,
497            }),
498        };
499
500        let response = manager.start_replay(store, request).unwrap();
501        assert_eq!(response.status, ReplayStatus::Running);
502        assert_eq!(response.total_events, 10);
503
504        // Wait a bit for replay to process
505        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
506
507        // Check progress
508        let progress = manager.get_progress(response.replay_id).unwrap();
509        assert!(progress.processed_events <= 10);
510    }
511}