Skip to main content

allsource_core/application/services/
exactly_once.rs

1//! Exactly-once stream processing guarantees
2//!
3//! Provides deduplication and idempotency tracking for event ingestion and
4//! pipeline processing, ensuring that retried or duplicated events don't
5//! result in duplicate state changes.
6//!
7//! ## Mechanisms
8//!
9//! 1. **Idempotency keys**: Clients include an `idempotency_key` in event metadata.
10//!    The registry tracks which keys have been processed and rejects duplicates.
11//!
12//! 2. **Consumer offsets**: Pipeline processors track their read offset per stream.
13//!    On restart, processing resumes from the last committed offset.
14//!
15//! 3. **Processing receipts**: Each event processed by a pipeline gets a receipt
16//!    (hash of pipeline_id + event_id). Receipts prevent reprocessing during replays.
17//!
18//! ## TTL
19//!
20//! Idempotency keys expire after a configurable window (default 24 hours) to
21//! bound memory usage. Consumer offsets persist indefinitely.
22
23use crate::infrastructure::memory::ledger::{MapCharge, Owner, string_heap};
24use chrono::{DateTime, Duration, Utc};
25use dashmap::DashMap;
26use serde::{Deserialize, Serialize};
27use std::mem::size_of;
28use uuid::Uuid;
29
30/// Configuration for exactly-once processing
31#[derive(Debug, Clone)]
32pub struct ExactlyOnceConfig {
33    /// How long to keep idempotency keys before expiry
34    pub idempotency_ttl: Duration,
35    /// Maximum number of idempotency keys to retain (LRU eviction)
36    pub max_idempotency_keys: usize,
37}
38
39impl Default for ExactlyOnceConfig {
40    fn default() -> Self {
41        Self {
42            idempotency_ttl: Duration::hours(24),
43            max_idempotency_keys: 1_000_000,
44        }
45    }
46}
47
48/// An idempotency record
49#[derive(Debug, Clone, Serialize)]
50struct IdempotencyRecord {
51    /// The event ID that was created for this key
52    event_id: Uuid,
53    /// When this key was first seen
54    created_at: DateTime<Utc>,
55}
56
57/// Consumer offset for a pipeline
58#[derive(Debug, Clone, Serialize, Deserialize)]
59pub struct ConsumerOffset {
60    /// Pipeline ID
61    pub pipeline_id: String,
62    /// Stream/partition identifier
63    pub stream_id: String,
64    /// Last committed event offset (index into the event store)
65    pub offset: usize,
66    /// Last committed event ID
67    pub last_event_id: Uuid,
68    /// When offset was last updated
69    pub updated_at: DateTime<Utc>,
70}
71
72/// Processing receipt proving an event was handled by a pipeline
73#[derive(Debug, Clone, Hash, Eq, PartialEq)]
74struct ProcessingReceipt {
75    pipeline_id: String,
76    event_id: Uuid,
77}
78
79/// Result of an idempotency check
80#[derive(Debug, Clone, Serialize)]
81pub enum IdempotencyResult {
82    /// Key is new, proceed with processing
83    New,
84    /// Key was already processed, return the original event_id
85    Duplicate { original_event_id: Uuid },
86}
87
88/// Exactly-once processing registry
89pub struct ExactlyOnceRegistry {
90    config: ExactlyOnceConfig,
91    /// Idempotency key → record
92    idempotency_keys: DashMap<String, IdempotencyRecord>,
93    idempotency_charge: MapCharge,
94    /// (pipeline_id, stream_id) → consumer offset
95    consumer_offsets: DashMap<(String, String), ConsumerOffset>,
96    consumer_offsets_charge: MapCharge,
97    /// Set of processing receipts
98    processing_receipts: DashMap<ProcessingReceipt, DateTime<Utc>>,
99    processing_receipts_charge: MapCharge,
100}
101
102impl ExactlyOnceRegistry {
103    pub fn new(config: ExactlyOnceConfig) -> Self {
104        Self {
105            config,
106            idempotency_keys: DashMap::new(),
107            idempotency_charge: MapCharge::new(
108                Owner::Misc,
109                size_of::<(String, IdempotencyRecord)>(),
110            ),
111            consumer_offsets: DashMap::new(),
112            consumer_offsets_charge: MapCharge::new(
113                Owner::Misc,
114                size_of::<((String, String), ConsumerOffset)>(),
115            ),
116            processing_receipts: DashMap::new(),
117            processing_receipts_charge: MapCharge::new(
118                Owner::Misc,
119                size_of::<(ProcessingReceipt, DateTime<Utc>)>(),
120            ),
121        }
122    }
123
124    /// Check and register an idempotency key
125    ///
126    /// Returns `New` if the key hasn't been seen (and registers it),
127    /// or `Duplicate` with the original event_id if already processed.
128    pub fn check_idempotency(&self, key: &str, event_id: Uuid) -> IdempotencyResult {
129        let now = Utc::now();
130
131        // Check if key exists and is not expired
132        if let Some(existing) = self.idempotency_keys.get(key) {
133            let age = now - existing.created_at;
134            if age < self.config.idempotency_ttl {
135                return IdempotencyResult::Duplicate {
136                    original_event_id: existing.event_id,
137                };
138            }
139            // Expired — remove and treat as new
140            drop(existing);
141            self.idempotency_charge
142                .remove_entry(&self.idempotency_keys, key, |k, _| string_heap(k));
143        }
144
145        // Evict oldest keys if at capacity
146        if self.idempotency_keys.len() >= self.config.max_idempotency_keys {
147            self.evict_expired_keys();
148        }
149
150        // Register the new key
151        self.idempotency_charge.insert(
152            &self.idempotency_keys,
153            key.to_string(),
154            IdempotencyRecord {
155                event_id,
156                created_at: now,
157            },
158            |k, _| string_heap(k),
159        );
160
161        IdempotencyResult::New
162    }
163
164    /// Commit a consumer offset for a pipeline
165    pub fn commit_offset(&self, pipeline_id: &str, stream_id: &str, offset: usize, event_id: Uuid) {
166        let key = (pipeline_id.to_string(), stream_id.to_string());
167        self.consumer_offsets_charge.insert(
168            &self.consumer_offsets,
169            key,
170            ConsumerOffset {
171                pipeline_id: pipeline_id.to_string(),
172                stream_id: stream_id.to_string(),
173                offset,
174                last_event_id: event_id,
175                updated_at: Utc::now(),
176            },
177            |(pipeline, stream), offset| {
178                string_heap(pipeline)
179                    + string_heap(stream)
180                    + string_heap(&offset.pipeline_id)
181                    + string_heap(&offset.stream_id)
182            },
183        );
184    }
185
186    /// Get the last committed offset for a pipeline
187    pub fn get_offset(&self, pipeline_id: &str, stream_id: &str) -> Option<ConsumerOffset> {
188        let key = (pipeline_id.to_string(), stream_id.to_string());
189        self.consumer_offsets.get(&key).map(|v| v.clone())
190    }
191
192    /// Record that a pipeline has processed an event
193    pub fn record_processing(&self, pipeline_id: &str, event_id: Uuid) {
194        let receipt = ProcessingReceipt {
195            pipeline_id: pipeline_id.to_string(),
196            event_id,
197        };
198        self.processing_receipts_charge.insert(
199            &self.processing_receipts,
200            receipt,
201            Utc::now(),
202            |receipt, _| string_heap(&receipt.pipeline_id),
203        );
204    }
205
206    /// Check if a pipeline has already processed an event
207    pub fn was_processed(&self, pipeline_id: &str, event_id: Uuid) -> bool {
208        let receipt = ProcessingReceipt {
209            pipeline_id: pipeline_id.to_string(),
210            event_id,
211        };
212        self.processing_receipts.contains_key(&receipt)
213    }
214
215    /// Remove expired idempotency keys
216    fn evict_expired_keys(&self) {
217        let now = Utc::now();
218        let ttl = self.config.idempotency_ttl;
219        let expired: Vec<String> = self
220            .idempotency_keys
221            .iter()
222            .filter(|entry| now - entry.value().created_at >= ttl)
223            .map(|entry| entry.key().clone())
224            .collect();
225        for key in &expired {
226            self.idempotency_charge.remove_entry_if(
227                &self.idempotency_keys,
228                key,
229                |record| now - record.created_at >= ttl,
230                |k, _| string_heap(k),
231            );
232        }
233    }
234
235    /// Statistics about the exactly-once registry
236    pub fn stats(&self) -> ExactlyOnceStats {
237        ExactlyOnceStats {
238            idempotency_keys: self.idempotency_keys.len(),
239            consumer_offsets: self.consumer_offsets.len(),
240            processing_receipts: self.processing_receipts.len(),
241        }
242    }
243}
244
245/// Exactly-once registry statistics
246#[derive(Debug, Clone, Serialize)]
247pub struct ExactlyOnceStats {
248    pub idempotency_keys: usize,
249    pub consumer_offsets: usize,
250    pub processing_receipts: usize,
251}
252
253/// Extract an idempotency key from event metadata
254pub fn extract_idempotency_key(metadata: &Option<serde_json::Value>) -> Option<String> {
255    metadata
256        .as_ref()?
257        .get("idempotency_key")
258        .and_then(|v| v.as_str())
259        .map(std::string::ToString::to_string)
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265
266    fn registry() -> ExactlyOnceRegistry {
267        ExactlyOnceRegistry::new(ExactlyOnceConfig::default())
268    }
269
270    #[test]
271    fn test_new_idempotency_key() {
272        let reg = registry();
273        let id = Uuid::new_v4();
274        match reg.check_idempotency("key-1", id) {
275            IdempotencyResult::New => {}
276            IdempotencyResult::Duplicate { .. } => panic!("Expected New, got Duplicate"),
277        }
278    }
279
280    #[test]
281    fn test_duplicate_idempotency_key() {
282        let reg = registry();
283        let id1 = Uuid::new_v4();
284        let id2 = Uuid::new_v4();
285        reg.check_idempotency("key-1", id1);
286        match reg.check_idempotency("key-1", id2) {
287            IdempotencyResult::Duplicate { original_event_id } => {
288                assert_eq!(original_event_id, id1);
289            }
290            IdempotencyResult::New => panic!("Expected Duplicate, got New"),
291        }
292    }
293
294    #[test]
295    fn test_expired_key_treated_as_new() {
296        let reg = ExactlyOnceRegistry::new(ExactlyOnceConfig {
297            idempotency_ttl: Duration::seconds(-1), // Already expired
298            ..Default::default()
299        });
300        let id1 = Uuid::new_v4();
301        let id2 = Uuid::new_v4();
302        reg.check_idempotency("key-1", id1);
303        match reg.check_idempotency("key-1", id2) {
304            IdempotencyResult::New => {}
305            IdempotencyResult::Duplicate { .. } => panic!("Expected New (expired), got Duplicate"),
306        }
307    }
308
309    #[test]
310    fn test_consumer_offset_commit_and_get() {
311        let reg = registry();
312        let eid = Uuid::new_v4();
313        reg.commit_offset("pipeline-1", "stream-a", 42, eid);
314        let offset = reg.get_offset("pipeline-1", "stream-a").unwrap();
315        assert_eq!(offset.offset, 42);
316        assert_eq!(offset.last_event_id, eid);
317    }
318
319    #[test]
320    fn test_consumer_offset_not_found() {
321        let reg = registry();
322        assert!(reg.get_offset("nonexistent", "stream").is_none());
323    }
324
325    #[test]
326    fn test_processing_receipts() {
327        let reg = registry();
328        let eid = Uuid::new_v4();
329        assert!(!reg.was_processed("pipeline-1", eid));
330        reg.record_processing("pipeline-1", eid);
331        assert!(reg.was_processed("pipeline-1", eid));
332    }
333
334    #[test]
335    fn test_processing_receipt_different_pipeline() {
336        let reg = registry();
337        let eid = Uuid::new_v4();
338        reg.record_processing("pipeline-1", eid);
339        assert!(!reg.was_processed("pipeline-2", eid));
340    }
341
342    #[test]
343    fn test_extract_idempotency_key() {
344        let meta = Some(serde_json::json!({"idempotency_key": "abc-123"}));
345        assert_eq!(extract_idempotency_key(&meta), Some("abc-123".to_string()));
346
347        let no_key = Some(serde_json::json!({"source": "web"}));
348        assert_eq!(extract_idempotency_key(&no_key), None);
349
350        assert_eq!(extract_idempotency_key(&None), None);
351    }
352
353    #[test]
354    fn test_stats() {
355        let reg = registry();
356        let id = Uuid::new_v4();
357        reg.check_idempotency("k1", id);
358        reg.commit_offset("p1", "s1", 0, id);
359        reg.record_processing("p1", id);
360        let stats = reg.stats();
361        assert_eq!(stats.idempotency_keys, 1);
362        assert_eq!(stats.consumer_offsets, 1);
363        assert_eq!(stats.processing_receipts, 1);
364    }
365
366    #[test]
367    fn test_eviction_on_capacity() {
368        let reg = ExactlyOnceRegistry::new(ExactlyOnceConfig {
369            idempotency_ttl: Duration::seconds(-1), // All expired
370            max_idempotency_keys: 2,
371        });
372        // Fill to capacity with expired keys
373        reg.idempotency_keys.insert(
374            "old-1".to_string(),
375            IdempotencyRecord {
376                event_id: Uuid::new_v4(),
377                created_at: Utc::now() - Duration::hours(48),
378            },
379        );
380        reg.idempotency_keys.insert(
381            "old-2".to_string(),
382            IdempotencyRecord {
383                event_id: Uuid::new_v4(),
384                created_at: Utc::now() - Duration::hours(48),
385            },
386        );
387        // This should trigger eviction
388        let id = Uuid::new_v4();
389        reg.check_idempotency("new-key", id);
390        // Old expired keys should have been evicted
391        assert!(reg.idempotency_keys.len() <= 2);
392    }
393}