Skip to main content

allsource_core/application/services/
projection.rs

1use crate::{
2    domain::entities::Event,
3    error::Result,
4    infrastructure::{
5        hash_state::{FastDashMap, fast_dashmap},
6        memory::ledger::{MapCharge, Owner, Tally},
7        observability::{heap::json_heap_bytes, metrics::MetricsRegistry},
8    },
9};
10use chrono::{DateTime, Utc};
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13use std::{
14    mem::size_of,
15    path::PathBuf,
16    sync::{
17        Arc,
18        atomic::{AtomicU64, Ordering},
19    },
20    time::Instant,
21};
22
23/// A projection aggregates events into a queryable view
24pub trait Projection: Send + Sync {
25    /// Get the name of this projection
26    fn name(&self) -> &str;
27
28    /// Process an event and update the projection state
29    fn process(&self, event: &Event) -> Result<()>;
30
31    /// Get the current state of the projection for an entity
32    fn get_state(&self, entity_id: &str) -> Option<Value>;
33
34    /// Clear all projection state
35    fn clear(&self);
36
37    /// Snapshot the entire projection state for checkpointing.
38    /// Returns `None` if the projection does not support checkpointing.
39    fn snapshot(&self) -> Option<Value> {
40        None
41    }
42
43    /// Restore projection state from a previously saved snapshot.
44    fn restore(&self, _snapshot: &Value) -> Result<()> {
45        Ok(())
46    }
47}
48
49/// A checkpoint of a projection's state, persisted to disk.
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct ProjectionCheckpoint {
52    pub projection_name: String,
53    pub state: Value,
54    pub last_event_timestamp: DateTime<Utc>,
55    pub event_count: u64,
56}
57
58/// Configuration for projection checkpointing behaviour.
59#[derive(Debug, Clone)]
60pub struct CheckpointConfig {
61    pub enabled: bool,
62    /// Checkpoint after every N events processed by a projection.
63    pub interval_events: u64,
64    /// Checkpoint after M seconds since the last checkpoint.
65    pub interval_seconds: u64,
66}
67
68impl Default for CheckpointConfig {
69    fn default() -> Self {
70        Self {
71            enabled: true,
72            interval_events: 10_000,
73            interval_seconds: 300,
74        }
75    }
76}
77
78/// Per-projection tracking state for checkpointing.
79struct ProjectionState {
80    projection: Arc<dyn Projection>,
81    events_since_checkpoint: AtomicU64,
82    total_event_count: AtomicU64,
83    /// The timestamp of the checkpoint that was restored (if any).
84    /// Events at or before this timestamp are skipped during replay.
85    restored_up_to: parking_lot::Mutex<Option<DateTime<Utc>>>,
86}
87
88/// Entity snapshot projection - maintains current state of each entity
89pub struct EntitySnapshotProjection {
90    name: String,
91    /// entity_id -> (latest state, last event timestamp)
92    states: Arc<FastDashMap<String, (Value, DateTime<Utc>)>>,
93    states_charge: MapCharge,
94    states_owned: Tally,
95}
96
97impl EntitySnapshotProjection {
98    pub fn new(name: impl Into<String>) -> Self {
99        Self {
100            name: name.into(),
101            states: Arc::new(fast_dashmap()),
102            states_charge: MapCharge::new(
103                Owner::ProjectionPermanent,
104                size_of::<(String, (Value, DateTime<Utc>))>(),
105            ),
106            states_owned: Tally::new(Owner::ProjectionPermanent),
107        }
108    }
109
110    fn charge_state(&self, key: &str, state: &Value) {
111        self.states_owned
112            .add(key.len() as u64 + json_heap_bytes(state) as u64);
113    }
114
115    /// Get all entity states
116    pub fn get_all_states(&self) -> Vec<(String, Value)> {
117        self.states
118            .iter()
119            .map(|entry| (entry.key().clone(), entry.value().0.clone()))
120            .collect()
121    }
122}
123
124impl Projection for EntitySnapshotProjection {
125    fn name(&self) -> &str {
126        &self.name
127    }
128
129    fn process(&self, event: &Event) -> Result<()> {
130        // Timestamp-aware merge strategy: only merge if the event is at least
131        // as new as the last processed event for this entity. This ensures
132        // convergence during bidirectional sync where events may arrive out of
133        // order. In the normal (non-sync) case, events are always in order so
134        // this condition is always true.
135        let key = event.entity_id_str();
136        if !self.states.contains_key(key) {
137            self.states_charge.ensure(
138                &self.states,
139                key,
140                || key.to_string(),
141                || (event.payload.clone(), event.timestamp),
142                0,
143            );
144            self.charge_state(key, &event.payload);
145        }
146        self.states
147            .entry(key.to_string())
148            .and_modify(|(state, last_ts)| {
149                if event.timestamp >= *last_ts {
150                    // Merge the event payload into existing state
151                    let before = json_heap_bytes(state) as u64;
152                    if let (Value::Object(map), Value::Object(payload_map)) =
153                        (&mut *state, &event.payload)
154                    {
155                        for (key, value) in payload_map {
156                            map.insert(key.clone(), value.clone());
157                        }
158                    }
159                    self.states_owned
160                        .adjust(before, json_heap_bytes(state) as u64);
161                    *last_ts = event.timestamp;
162                }
163                // Out-of-order event: skip merge to ensure convergence
164            })
165            .or_insert_with(|| (event.payload.clone(), event.timestamp));
166
167        Ok(())
168    }
169
170    fn get_state(&self, entity_id: &str) -> Option<Value> {
171        self.states.get(entity_id).map(|v| v.0.clone())
172    }
173
174    fn clear(&self) {
175        self.states.clear();
176        self.states_owned.take();
177    }
178
179    fn snapshot(&self) -> Option<Value> {
180        let entries: Vec<(String, Value, DateTime<Utc>)> = self
181            .states
182            .iter()
183            .map(|entry| {
184                let (state, ts) = entry.value().clone();
185                (entry.key().clone(), state, ts)
186            })
187            .collect();
188        serde_json::to_value(entries).ok()
189    }
190
191    fn restore(&self, snapshot: &Value) -> Result<()> {
192        let entries: Vec<(String, Value, DateTime<Utc>)> = serde_json::from_value(snapshot.clone())
193            .map_err(|e| crate::error::AllSourceError::StorageError(e.to_string()))?;
194        self.states.clear();
195        self.states_owned.take();
196        for (key, state, ts) in entries {
197            self.charge_state(&key, &state);
198            self.states.insert(key, (state, ts));
199        }
200        Ok(())
201    }
202}
203
204/// Event counter projection - counts events by type
205pub struct EventCounterProjection {
206    name: String,
207    /// event_type -> count
208    counts: Arc<FastDashMap<String, u64>>,
209    counts_charge: MapCharge,
210}
211
212impl EventCounterProjection {
213    pub fn new(name: impl Into<String>) -> Self {
214        Self {
215            name: name.into(),
216            counts: Arc::new(fast_dashmap()),
217            counts_charge: MapCharge::new(
218                Owner::ProjectionEventCounters,
219                size_of::<(String, u64)>(),
220            ),
221        }
222    }
223
224    /// Get count for a specific event type
225    pub fn get_count(&self, event_type: &str) -> u64 {
226        self.counts.get(event_type).map_or(0, |v| *v)
227    }
228
229    /// Get all event type counts
230    pub fn get_all_counts(&self) -> Vec<(String, u64)> {
231        self.counts
232            .iter()
233            .map(|entry| (entry.key().clone(), *entry.value()))
234            .collect()
235    }
236}
237
238impl Projection for EventCounterProjection {
239    fn name(&self) -> &str {
240        &self.name
241    }
242
243    fn process(&self, event: &Event) -> Result<()> {
244        let key = event.event_type_str();
245        self.counts_charge.ensure(
246            &self.counts,
247            key,
248            || key.to_string(),
249            || 0,
250            key.len() as u64,
251        );
252        self.counts
253            .entry(key.to_string())
254            .and_modify(|count| *count += 1)
255            .or_insert(1);
256
257        Ok(())
258    }
259
260    fn get_state(&self, event_type: &str) -> Option<Value> {
261        self.counts
262            .get(event_type)
263            .map(|count| serde_json::json!({ "count": *count }))
264    }
265
266    fn clear(&self) {
267        self.counts.clear();
268        self.counts_charge.clear_owned();
269    }
270
271    fn snapshot(&self) -> Option<Value> {
272        let entries: Vec<(String, u64)> = self
273            .counts
274            .iter()
275            .map(|entry| (entry.key().clone(), *entry.value()))
276            .collect();
277        serde_json::to_value(entries).ok()
278    }
279
280    fn restore(&self, snapshot: &Value) -> Result<()> {
281        let entries: Vec<(String, u64)> = serde_json::from_value(snapshot.clone())
282            .map_err(|e| crate::error::AllSourceError::StorageError(e.to_string()))?;
283        self.counts.clear();
284        self.counts_charge.clear_owned();
285        for (key, count) in entries {
286            self.counts_charge.ensure(
287                &self.counts,
288                key.as_str(),
289                || key.clone(),
290                || count,
291                key.len() as u64,
292            );
293            self.counts.insert(key, count);
294        }
295        Ok(())
296    }
297}
298
299/// Projection manager handles multiple projections
300pub struct ProjectionManager {
301    states: Vec<ProjectionState>,
302    metrics: Arc<MetricsRegistry>,
303    checkpoint_config: CheckpointConfig,
304    checkpoint_dir: Option<PathBuf>,
305    last_checkpoint_time: parking_lot::Mutex<Instant>,
306}
307
308impl ProjectionManager {
309    pub fn new() -> Self {
310        Self::with_metrics(MetricsRegistry::new())
311    }
312
313    pub fn with_metrics(metrics: Arc<MetricsRegistry>) -> Self {
314        Self {
315            states: Vec::new(),
316            metrics,
317            checkpoint_config: CheckpointConfig::default(),
318            checkpoint_dir: None,
319            last_checkpoint_time: parking_lot::Mutex::new(Instant::now()),
320        }
321    }
322
323    /// Set checkpoint configuration and directory.
324    pub fn with_checkpoint_config(mut self, config: CheckpointConfig, dir: PathBuf) -> Self {
325        self.checkpoint_config = config;
326        self.checkpoint_dir = Some(dir);
327        self
328    }
329
330    /// Register a new projection. If a checkpoint file exists on disk, restore
331    /// from it so that only events newer than `last_event_timestamp` need to be
332    /// replayed.
333    pub fn register(&mut self, projection: Arc<dyn Projection>) {
334        let name = projection.name().to_string();
335        tracing::info!("Registering projection: {name}");
336
337        let state = ProjectionState {
338            projection,
339            events_since_checkpoint: AtomicU64::new(0),
340            total_event_count: AtomicU64::new(0),
341            restored_up_to: parking_lot::Mutex::new(None),
342        };
343
344        // Attempt to restore from checkpoint
345        if self.checkpoint_config.enabled
346            && let Some(path) = self.checkpoint_path(&name)
347            && path.exists()
348        {
349            self.try_restore_checkpoint(&path, state.projection.as_ref(), &state);
350        }
351
352        self.states.push(state);
353        self.metrics.projections_total.set(self.states.len() as i64);
354    }
355
356    /// Try to read a checkpoint file and restore the projection from it.
357    fn try_restore_checkpoint(
358        &self,
359        path: &std::path::Path,
360        projection: &dyn Projection,
361        state: &ProjectionState,
362    ) {
363        let name = projection.name();
364        let data = match std::fs::read_to_string(path) {
365            Ok(d) => d,
366            Err(e) => {
367                tracing::warn!("Failed to read checkpoint file for projection '{name}': {e}");
368                return;
369            }
370        };
371        let checkpoint: ProjectionCheckpoint = match serde_json::from_str(&data) {
372            Ok(c) => c,
373            Err(e) => {
374                tracing::warn!("Failed to parse checkpoint for projection '{name}': {e}");
375                return;
376            }
377        };
378        match projection.restore(&checkpoint.state) {
379            Ok(()) => {
380                state
381                    .total_event_count
382                    .store(checkpoint.event_count, Ordering::Relaxed);
383                *state.restored_up_to.lock() = Some(checkpoint.last_event_timestamp);
384                let count = checkpoint.event_count;
385                let ts = checkpoint.last_event_timestamp;
386                tracing::info!(
387                    "Restored projection '{name}' from checkpoint (event_count={count}, up_to={ts})",
388                );
389            }
390            Err(e) => {
391                tracing::warn!("Failed to restore projection '{name}' from checkpoint: {e}",);
392            }
393        }
394    }
395
396    /// Process an event through all projections.
397    /// Events at or before a projection's restored checkpoint timestamp are
398    /// skipped (they were already folded into the restored state).
399    #[cfg_attr(feature = "hotpath", hotpath::measure)]
400    pub fn process_event(&self, event: &Event) -> Result<()> {
401        let timer = self.metrics.projection_duration_seconds.start_timer();
402
403        for state in &self.states {
404            let name = state.projection.name();
405
406            // Skip events that are already covered by the restored checkpoint.
407            {
408                let restored = state.restored_up_to.lock();
409                if restored.is_some_and(|up_to| event.timestamp <= up_to) {
410                    continue;
411                }
412            }
413
414            match state.projection.process(event) {
415                Ok(()) => {
416                    self.metrics
417                        .projection_events_processed
418                        .with_label_values(&[name])
419                        .inc();
420                    state
421                        .events_since_checkpoint
422                        .fetch_add(1, Ordering::Relaxed);
423                    state.total_event_count.fetch_add(1, Ordering::Relaxed);
424                }
425                Err(e) => {
426                    self.metrics
427                        .projection_errors_total
428                        .with_label_values(&[name])
429                        .inc();
430                    tracing::error!(
431                        "Projection '{name}' failed to process event {}: {e}",
432                        event.id,
433                    );
434                    // Continue processing other projections even if one fails
435                }
436            }
437        }
438
439        // Check if we should write a checkpoint (by event count or time).
440        if self.checkpoint_config.enabled && self.checkpoint_dir.is_some() {
441            self.maybe_checkpoint();
442        }
443
444        timer.observe_duration();
445        Ok(())
446    }
447
448    /// Check whether the event or time interval threshold has been reached
449    /// and checkpoint all projections if so.
450    fn maybe_checkpoint(&self) {
451        let events_threshold = self.checkpoint_config.interval_events;
452        let time_threshold = self.checkpoint_config.interval_seconds;
453
454        let any_exceeded = self
455            .states
456            .iter()
457            .any(|s| s.events_since_checkpoint.load(Ordering::Relaxed) >= events_threshold);
458
459        let time_exceeded = {
460            let last = self.last_checkpoint_time.lock();
461            last.elapsed().as_secs() >= time_threshold
462        };
463
464        if (any_exceeded || time_exceeded) && self.checkpoint_all().is_err() {
465            tracing::error!("Failed to write projection checkpoints");
466        }
467    }
468
469    /// Checkpoint all projections that support snapshotting.
470    pub fn checkpoint_all(&self) -> Result<()> {
471        for state in &self.states {
472            self.checkpoint_one(state)?;
473        }
474        *self.last_checkpoint_time.lock() = Instant::now();
475        Ok(())
476    }
477
478    /// Checkpoint a single projection.
479    fn checkpoint_one(&self, state: &ProjectionState) -> Result<()> {
480        let name = state.projection.name();
481        let Some(snapshot) = state.projection.snapshot() else {
482            return Ok(());
483        };
484
485        let Some(path) = self.checkpoint_path(name) else {
486            return Ok(());
487        };
488
489        let checkpoint = ProjectionCheckpoint {
490            projection_name: name.to_string(),
491            state: snapshot,
492            last_event_timestamp: Utc::now(),
493            event_count: state.total_event_count.load(Ordering::Relaxed),
494        };
495
496        let json = serde_json::to_string_pretty(&checkpoint)
497            .map_err(|e| crate::error::AllSourceError::StorageError(e.to_string()))?;
498
499        if let Some(parent) = path.parent() {
500            std::fs::create_dir_all(parent)
501                .map_err(|e| crate::error::AllSourceError::StorageError(e.to_string()))?;
502        }
503
504        std::fs::write(&path, json)
505            .map_err(|e| crate::error::AllSourceError::StorageError(e.to_string()))?;
506
507        state.events_since_checkpoint.store(0, Ordering::Relaxed);
508
509        tracing::debug!("Checkpointed projection '{name}'");
510        Ok(())
511    }
512
513    /// Build the checkpoint file path for a projection.
514    fn checkpoint_path(&self, name: &str) -> Option<PathBuf> {
515        self.checkpoint_dir
516            .as_ref()
517            .map(|dir| dir.join(format!("{name}.checkpoint.json")))
518    }
519
520    /// Get a projection by name
521    pub fn get_projection(&self, name: &str) -> Option<Arc<dyn Projection>> {
522        self.states
523            .iter()
524            .find(|s| s.projection.name() == name)
525            .map(|s| Arc::clone(&s.projection))
526    }
527
528    /// List all projections
529    pub fn list_projections(&self) -> Vec<(String, Arc<dyn Projection>)> {
530        self.states
531            .iter()
532            .map(|s| (s.projection.name().to_string(), Arc::clone(&s.projection)))
533            .collect()
534    }
535
536    /// Clear all projections
537    pub fn clear_all(&self) {
538        for state in &self.states {
539            state.projection.clear();
540        }
541    }
542
543    /// Return the restored-up-to timestamp for a given projection (if any).
544    /// Useful in tests to verify that a checkpoint was restored.
545    pub fn restored_up_to(&self, name: &str) -> Option<DateTime<Utc>> {
546        self.states
547            .iter()
548            .find(|s| s.projection.name() == name)
549            .and_then(|s| *s.restored_up_to.lock())
550    }
551}
552
553impl Default for ProjectionManager {
554    fn default() -> Self {
555        Self::new()
556    }
557}
558
559#[cfg(test)]
560mod tests {
561    use super::*;
562    use uuid::Uuid;
563
564    fn create_test_event(entity_id: &str, event_type: &str) -> Event {
565        Event::reconstruct_from_strings(
566            Uuid::new_v4(),
567            event_type.to_string(),
568            entity_id.to_string(),
569            "default".to_string(),
570            serde_json::json!({
571                "name": "Test User",
572                "email": "test@example.com"
573            }),
574            chrono::Utc::now(),
575            None,
576            1,
577        )
578    }
579
580    fn create_test_event_with_timestamp(
581        entity_id: &str,
582        event_type: &str,
583        timestamp: DateTime<Utc>,
584    ) -> Event {
585        Event::reconstruct_from_strings(
586            Uuid::new_v4(),
587            event_type.to_string(),
588            entity_id.to_string(),
589            "default".to_string(),
590            serde_json::json!({
591                "name": "Test User",
592                "email": "test@example.com"
593            }),
594            timestamp,
595            None,
596            1,
597        )
598    }
599
600    #[test]
601    fn test_entity_snapshot_projection() {
602        let projection = EntitySnapshotProjection::new("test");
603        let event = create_test_event("user-123", "user.created");
604
605        projection.process(&event).unwrap();
606
607        let state = projection.get_state("user-123").unwrap();
608        assert_eq!(state["name"], "Test User");
609    }
610
611    #[test]
612    fn test_event_counter_projection() {
613        let projection = EventCounterProjection::new("counter");
614
615        let event1 = create_test_event("user-123", "user.created");
616        let event2 = create_test_event("user-456", "user.created");
617        let event3 = create_test_event("user-123", "user.updated");
618
619        projection.process(&event1).unwrap();
620        projection.process(&event2).unwrap();
621        projection.process(&event3).unwrap();
622
623        assert_eq!(projection.get_count("user.created"), 2);
624        assert_eq!(projection.get_count("user.updated"), 1);
625    }
626
627    #[test]
628    fn test_projection_manager() {
629        let mut manager = ProjectionManager::new();
630
631        let snapshot = Arc::new(EntitySnapshotProjection::new("snapshot"));
632        let counter = Arc::new(EventCounterProjection::new("counter"));
633
634        manager.register(snapshot.clone());
635        manager.register(counter.clone());
636
637        let event = create_test_event("user-123", "user.created");
638        manager.process_event(&event).unwrap();
639
640        assert!(snapshot.get_state("user-123").is_some());
641        assert_eq!(counter.get_count("user.created"), 1);
642    }
643
644    #[test]
645    fn test_entity_snapshot_snapshot_restore() {
646        let projection = EntitySnapshotProjection::new("snap");
647        let event = create_test_event("user-1", "user.created");
648        projection.process(&event).unwrap();
649
650        let snap = projection.snapshot().expect("snapshot should be Some");
651
652        let projection2 = EntitySnapshotProjection::new("snap");
653        projection2.restore(&snap).unwrap();
654
655        let state = projection2.get_state("user-1").unwrap();
656        assert_eq!(state["name"], "Test User");
657    }
658
659    #[test]
660    fn test_event_counter_snapshot_restore() {
661        let projection = EventCounterProjection::new("counter");
662        for _ in 0..5 {
663            let event = create_test_event("user-1", "user.created");
664            projection.process(&event).unwrap();
665        }
666
667        let snap = projection.snapshot().expect("snapshot should be Some");
668
669        let projection2 = EventCounterProjection::new("counter");
670        projection2.restore(&snap).unwrap();
671
672        assert_eq!(projection2.get_count("user.created"), 5);
673    }
674
675    #[test]
676    fn test_checkpoint_write_and_read() {
677        let dir = tempfile::tempdir().unwrap();
678        let checkpoint_dir = dir.path().join("projections");
679
680        let config = CheckpointConfig {
681            enabled: true,
682            interval_events: 100,
683            interval_seconds: 3600,
684        };
685
686        let mut manager =
687            ProjectionManager::new().with_checkpoint_config(config, checkpoint_dir.clone());
688
689        let counter = Arc::new(EventCounterProjection::new("counter"));
690        manager.register(counter.clone());
691
692        // Process some events
693        for i in 0..50 {
694            let event = create_test_event(&format!("user-{i}"), "user.created");
695            manager.process_event(&event).unwrap();
696        }
697
698        // Manually trigger checkpoint
699        manager.checkpoint_all().unwrap();
700
701        // Verify the file was written
702        let cp_path = checkpoint_dir.join("counter.checkpoint.json");
703        assert!(cp_path.exists());
704
705        // Read and verify the checkpoint content
706        let data = std::fs::read_to_string(&cp_path).unwrap();
707        let checkpoint: ProjectionCheckpoint = serde_json::from_str(&data).unwrap();
708        assert_eq!(checkpoint.projection_name, "counter");
709        assert_eq!(checkpoint.event_count, 50);
710    }
711
712    #[test]
713    fn test_checkpoint_restore_on_register() {
714        let dir = tempfile::tempdir().unwrap();
715        let checkpoint_dir = dir.path().join("projections");
716
717        let config = CheckpointConfig {
718            enabled: true,
719            interval_events: 100_000,
720            interval_seconds: 3600,
721        };
722
723        // Phase 1: process events and checkpoint
724        {
725            let mut manager = ProjectionManager::new()
726                .with_checkpoint_config(config.clone(), checkpoint_dir.clone());
727
728            let counter = Arc::new(EventCounterProjection::new("counter"));
729            manager.register(counter.clone());
730
731            for i in 0..100 {
732                let event = create_test_event(&format!("user-{i}"), "user.created");
733                manager.process_event(&event).unwrap();
734            }
735
736            manager.checkpoint_all().unwrap();
737
738            assert_eq!(counter.get_count("user.created"), 100);
739        }
740
741        // Phase 2: create new manager, register same projection, verify restore
742        {
743            let mut manager =
744                ProjectionManager::new().with_checkpoint_config(config, checkpoint_dir);
745
746            let counter = Arc::new(EventCounterProjection::new("counter"));
747            manager.register(counter.clone());
748
749            // The projection should have been restored from the checkpoint
750            assert_eq!(counter.get_count("user.created"), 100);
751
752            // The manager should have recorded that events up to the checkpoint
753            // timestamp can be skipped
754            assert!(manager.restored_up_to("counter").is_some());
755        }
756    }
757
758    #[test]
759    fn test_checkpoint_skips_old_events_during_replay() {
760        let dir = tempfile::tempdir().unwrap();
761        let checkpoint_dir = dir.path().join("projections");
762
763        let config = CheckpointConfig {
764            enabled: true,
765            interval_events: 100_000,
766            interval_seconds: 3600,
767        };
768
769        let checkpoint_time = Utc::now();
770
771        // Phase 1: process 1000 events and checkpoint
772        {
773            let mut manager = ProjectionManager::new()
774                .with_checkpoint_config(config.clone(), checkpoint_dir.clone());
775
776            let counter = Arc::new(EventCounterProjection::new("counter"));
777            manager.register(counter.clone());
778
779            for i in 0..1000 {
780                let event = create_test_event_with_timestamp(
781                    &format!("user-{i}"),
782                    "user.created",
783                    checkpoint_time,
784                );
785                manager.process_event(&event).unwrap();
786            }
787
788            manager.checkpoint_all().unwrap();
789            assert_eq!(counter.get_count("user.created"), 1000);
790        }
791
792        // Phase 2: simulate restart — restore from checkpoint and replay
793        {
794            let mut manager =
795                ProjectionManager::new().with_checkpoint_config(config, checkpoint_dir);
796
797            let counter = Arc::new(EventCounterProjection::new("counter"));
798            manager.register(counter.clone());
799
800            // Counter should be restored
801            assert_eq!(counter.get_count("user.created"), 1000);
802
803            // Replay the old 1000 events (should be skipped because their
804            // timestamp <= checkpoint timestamp)
805            for i in 0..1000 {
806                let event = create_test_event_with_timestamp(
807                    &format!("user-{i}"),
808                    "user.created",
809                    checkpoint_time,
810                );
811                manager.process_event(&event).unwrap();
812            }
813
814            // Count should still be 1000 — old events were skipped
815            assert_eq!(counter.get_count("user.created"), 1000);
816
817            // Now process 10 NEW events with a later timestamp
818            let later = checkpoint_time + chrono::Duration::seconds(10);
819            for i in 0..10 {
820                let event = create_test_event_with_timestamp(
821                    &format!("new-user-{i}"),
822                    "user.created",
823                    later,
824                );
825                manager.process_event(&event).unwrap();
826            }
827
828            // Now we should have 1010 total
829            assert_eq!(counter.get_count("user.created"), 1010);
830        }
831    }
832
833    #[test]
834    fn test_auto_checkpoint_by_event_count() {
835        let dir = tempfile::tempdir().unwrap();
836        let checkpoint_dir = dir.path().join("projections");
837
838        let config = CheckpointConfig {
839            enabled: true,
840            interval_events: 50, // checkpoint every 50 events
841            interval_seconds: 3600,
842        };
843
844        let mut manager =
845            ProjectionManager::new().with_checkpoint_config(config, checkpoint_dir.clone());
846
847        let counter = Arc::new(EventCounterProjection::new("counter"));
848        manager.register(counter.clone());
849
850        // Process 60 events — should trigger auto-checkpoint at 50
851        for i in 0..60 {
852            let event = create_test_event(&format!("user-{i}"), "user.created");
853            manager.process_event(&event).unwrap();
854        }
855
856        // Checkpoint file should exist
857        let cp_path = checkpoint_dir.join("counter.checkpoint.json");
858        assert!(cp_path.exists());
859    }
860
861    #[test]
862    fn test_default_noop_snapshot_restore() {
863        // A projection that does NOT implement snapshot/restore should use the
864        // default no-op implementations and not break anything.
865        struct MinimalProjection;
866        impl Projection for MinimalProjection {
867            fn name(&self) -> &'static str {
868                "minimal"
869            }
870            fn process(&self, _event: &Event) -> Result<()> {
871                Ok(())
872            }
873            fn get_state(&self, _entity_id: &str) -> Option<Value> {
874                None
875            }
876            fn clear(&self) {}
877        }
878
879        let projection = MinimalProjection;
880        assert!(projection.snapshot().is_none());
881        assert!(projection.restore(&Value::Null).is_ok());
882    }
883
884    #[test]
885    fn test_checkpoint_with_no_dir_is_noop() {
886        // When no checkpoint_dir is configured, checkpoint operations should
887        // succeed silently (no-op).
888        let mut manager = ProjectionManager::new();
889        let counter = Arc::new(EventCounterProjection::new("counter"));
890        manager.register(counter.clone());
891
892        for _ in 0..10 {
893            let event = create_test_event("user-1", "user.created");
894            manager.process_event(&event).unwrap();
895        }
896
897        // Should not error even without a checkpoint directory
898        manager.checkpoint_all().unwrap();
899    }
900}