chie-core 0.2.0

Core protocol logic for CHIE Protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
//! Content lifecycle event system for webhooks and callbacks.
//!
//! This module provides an event-driven system for tracking content lifecycle operations.
//! Applications can register event handlers to react to content additions, accesses, removals,
//! and other lifecycle events.
//!
//! # Example
//!
//! ```rust
//! use chie_core::lifecycle::{LifecycleEventManager, LifecycleEventType, ContentEvent};
//!
//! #[tokio::main]
//! async fn main() {
//!     let mut manager = LifecycleEventManager::new();
//!
//!     // Register an event handler
//!     manager.on(LifecycleEventType::ContentAdded, |event| {
//!         println!("Content added: {}", event.cid);
//!     });
//!
//!     // Emit an event
//!     manager.emit(ContentEvent {
//!         cid: "QmExample".to_string(),
//!         event_type: LifecycleEventType::ContentAdded,
//!         size_bytes: Some(1024),
//!         peer_id: None,
//!         metadata: None,
//!     }).await;
//! }
//! ```

use crate::http_pool::{HttpClientPool, HttpConfig};
use std::{
    collections::HashMap,
    sync::{Arc, Mutex},
};

/// Type of lifecycle event.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize)]
pub enum LifecycleEventType {
    /// Content was added to storage.
    ContentAdded,
    /// Content was accessed/requested.
    ContentAccessed,
    /// Content was removed from storage.
    ContentRemoved,
    /// Content was pinned.
    ContentPinned,
    /// Content was unpinned.
    ContentUnpinned,
    /// Chunk was transferred.
    ChunkTransferred,
    /// Bandwidth proof was generated.
    ProofGenerated,
    /// Storage quota exceeded.
    QuotaExceeded,
    /// Content verification failed.
    VerificationFailed,
    /// Peer connection established.
    PeerConnected,
    /// Peer connection lost.
    PeerDisconnected,
}

/// A content lifecycle event.
#[derive(Debug, Clone, serde::Serialize)]
pub struct ContentEvent {
    /// Content identifier.
    pub cid: String,
    /// Type of event.
    pub event_type: LifecycleEventType,
    /// Content size in bytes (if applicable).
    pub size_bytes: Option<u64>,
    /// Peer ID involved (if applicable).
    pub peer_id: Option<String>,
    /// Additional metadata (JSON-compatible).
    pub metadata: Option<HashMap<String, String>>,
}

impl ContentEvent {
    /// Create a simple event without optional fields.
    #[inline]
    #[must_use]
    pub fn simple(cid: String, event_type: LifecycleEventType) -> Self {
        Self {
            cid,
            event_type,
            size_bytes: None,
            peer_id: None,
            metadata: None,
        }
    }

    /// Create an event with size information.
    #[inline]
    #[must_use]
    pub fn with_size(cid: String, event_type: LifecycleEventType, size_bytes: u64) -> Self {
        Self {
            cid,
            event_type,
            size_bytes: Some(size_bytes),
            peer_id: None,
            metadata: None,
        }
    }

    /// Create an event with peer information.
    #[inline]
    #[must_use]
    pub fn with_peer(cid: String, event_type: LifecycleEventType, peer_id: String) -> Self {
        Self {
            cid,
            event_type,
            size_bytes: None,
            peer_id: Some(peer_id),
            metadata: None,
        }
    }

    /// Add metadata to the event.
    #[inline]
    #[must_use]
    pub fn with_metadata(mut self, key: String, value: String) -> Self {
        if self.metadata.is_none() {
            self.metadata = Some(HashMap::new());
        }
        if let Some(ref mut metadata) = self.metadata {
            metadata.insert(key, value);
        }
        self
    }
}

/// Type alias for event handler functions.
pub type EventHandler = Arc<dyn Fn(&ContentEvent) + Send + Sync>;

/// Webhook configuration for HTTP callbacks.
#[derive(Debug, Clone)]
pub struct WebhookConfig {
    /// Webhook URL.
    pub url: String,
    /// Events to trigger this webhook.
    pub events: Vec<LifecycleEventType>,
    /// Authentication header (optional).
    pub auth_header: Option<String>,
    /// Maximum retry attempts.
    pub max_retries: u32,
    /// Timeout in milliseconds.
    pub timeout_ms: u64,
}

impl WebhookConfig {
    /// Create a new webhook config for a URL.
    #[inline]
    #[must_use]
    pub fn new(url: String) -> Self {
        Self {
            url,
            events: vec![],
            auth_header: None,
            max_retries: 3,
            timeout_ms: 5000,
        }
    }

    /// Set which events should trigger this webhook.
    #[inline]
    #[must_use]
    pub fn for_events(mut self, events: Vec<LifecycleEventType>) -> Self {
        self.events = events;
        self
    }

    /// Add an authentication header.
    #[inline]
    #[must_use]
    pub fn with_auth(mut self, header: String) -> Self {
        self.auth_header = Some(header);
        self
    }
}

/// Event history entry.
#[derive(Debug, Clone)]
pub struct EventHistoryEntry {
    /// The event that occurred.
    pub event: ContentEvent,
    /// Timestamp in milliseconds since epoch.
    pub timestamp_ms: u64,
}

/// Lifecycle event manager for handling content events.
pub struct LifecycleEventManager {
    /// Event handlers by event type.
    handlers: Arc<Mutex<HashMap<LifecycleEventType, Vec<EventHandler>>>>,
    /// Webhook configurations.
    webhooks: Arc<Mutex<Vec<WebhookConfig>>>,
    /// Event history (limited size).
    history: Arc<Mutex<VecDeque<EventHistoryEntry>>>,
    /// Maximum history size.
    max_history_size: usize,
    /// Event statistics.
    stats: Arc<Mutex<HashMap<LifecycleEventType, u64>>>,
    /// HTTP client pool for webhook requests.
    http_pool: Arc<HttpClientPool>,
}

use std::collections::VecDeque;

/// Send a webhook HTTP POST request for an event.
async fn send_webhook_request(
    http_pool: &HttpClientPool,
    webhook: &WebhookConfig,
    event: &ContentEvent,
) -> Result<(), crate::http_pool::HttpError> {
    // Serialize event to JSON
    let json_body = serde_json::to_value(event)
        .map_err(|e| crate::http_pool::HttpError::Serialization(e.to_string()))?;

    // Build the request with timeout
    let request = http_pool.post_json(&webhook.url, json_body).await?;

    // Check response status
    if request.status().is_success() {
        Ok(())
    } else {
        Err(crate::http_pool::HttpError::Response {
            status: request.status(),
            message: format!("Webhook failed with status {}", request.status()),
        })
    }
}

impl LifecycleEventManager {
    /// Create a new lifecycle event manager.
    #[must_use]
    pub fn new() -> Self {
        Self {
            handlers: Arc::new(Mutex::new(HashMap::new())),
            webhooks: Arc::new(Mutex::new(Vec::new())),
            history: Arc::new(Mutex::new(VecDeque::new())),
            max_history_size: 1000,
            stats: Arc::new(Mutex::new(HashMap::new())),
            http_pool: Arc::new(HttpClientPool::new(HttpConfig::default())),
        }
    }

    /// Create a new manager with custom history size.
    #[must_use]
    #[inline]
    pub fn with_history_size(max_history_size: usize) -> Self {
        Self {
            handlers: Arc::new(Mutex::new(HashMap::new())),
            webhooks: Arc::new(Mutex::new(Vec::new())),
            history: Arc::new(Mutex::new(VecDeque::new())),
            max_history_size,
            stats: Arc::new(Mutex::new(HashMap::new())),
            http_pool: Arc::new(HttpClientPool::new(HttpConfig::default())),
        }
    }

    /// Register an event handler for a specific event type.
    pub fn on<F>(&mut self, event_type: LifecycleEventType, handler: F)
    where
        F: Fn(&ContentEvent) + Send + Sync + 'static,
    {
        let mut handlers = self.handlers.lock().unwrap();
        handlers
            .entry(event_type)
            .or_default()
            .push(Arc::new(handler));
    }

    /// Register a webhook for HTTP callbacks.
    pub fn register_webhook(&mut self, config: WebhookConfig) {
        let mut webhooks = self.webhooks.lock().unwrap();
        webhooks.push(config);
    }

    /// Emit an event, triggering all registered handlers.
    pub async fn emit(&self, event: ContentEvent) {
        // Update statistics
        {
            let mut stats = self.stats.lock().unwrap();
            *stats.entry(event.event_type).or_insert(0) += 1;
        }

        // Add to history
        {
            let mut history = self.history.lock().unwrap();
            history.push_back(EventHistoryEntry {
                event: event.clone(),
                timestamp_ms: crate::utils::current_timestamp_ms() as u64,
            });

            // Trim history if needed
            while history.len() > self.max_history_size {
                history.pop_front();
            }
        }

        // Call handlers
        {
            let handlers = self.handlers.lock().unwrap();
            if let Some(handlers_list) = handlers.get(&event.event_type) {
                for handler in handlers_list {
                    handler(&event);
                }
            }
        }

        // Trigger webhooks (in background)
        self.trigger_webhooks(&event).await;
    }

    /// Trigger webhooks for an event (async).
    async fn trigger_webhooks(&self, event: &ContentEvent) {
        let webhooks = self.webhooks.lock().unwrap().clone();

        for webhook in webhooks {
            // Check if this webhook should be triggered for this event type
            if !webhook.events.is_empty() && !webhook.events.contains(&event.event_type) {
                continue;
            }

            // Clone the http_pool Arc for this task
            let http_pool = Arc::clone(&self.http_pool);
            let event_clone = event.clone();
            let webhook_clone = webhook.clone();

            // Spawn a background task to send the webhook
            tokio::spawn(async move {
                // Attempt to send webhook with retries
                for attempt in 0..=webhook_clone.max_retries {
                    match send_webhook_request(&http_pool, &webhook_clone, &event_clone).await {
                        Ok(_) => {
                            // Success - webhook delivered
                            break;
                        }
                        Err(e) => {
                            // Log error (in production, use proper logging)
                            eprintln!(
                                "Webhook delivery failed (attempt {}/{}): {}",
                                attempt + 1,
                                webhook_clone.max_retries + 1,
                                e
                            );

                            // Don't retry if this was the last attempt
                            if attempt < webhook_clone.max_retries {
                                // Brief delay before retry
                                tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
                            }
                        }
                    }
                }
            });
        }
    }

    /// Get event history for a specific event type.
    #[must_use]
    #[inline]
    pub fn get_history(&self, event_type: Option<LifecycleEventType>) -> Vec<EventHistoryEntry> {
        let history = self.history.lock().unwrap();
        match event_type {
            Some(et) => history
                .iter()
                .filter(|entry| entry.event.event_type == et)
                .cloned()
                .collect(),
            None => history.iter().cloned().collect(),
        }
    }

    /// Get recent events (last N).
    #[must_use]
    #[inline]
    pub fn get_recent(&self, count: usize) -> Vec<EventHistoryEntry> {
        let history = self.history.lock().unwrap();
        history.iter().rev().take(count).cloned().collect()
    }

    /// Get event count for a specific type.
    #[must_use]
    #[inline]
    pub fn get_event_count(&self, event_type: LifecycleEventType) -> u64 {
        self.stats
            .lock()
            .unwrap()
            .get(&event_type)
            .copied()
            .unwrap_or(0)
    }

    /// Get total event count across all types.
    #[must_use]
    #[inline]
    pub fn get_total_event_count(&self) -> u64 {
        self.stats.lock().unwrap().values().sum()
    }

    /// Get all event statistics.
    #[must_use]
    #[inline]
    pub fn get_stats(&self) -> HashMap<LifecycleEventType, u64> {
        self.stats.lock().unwrap().clone()
    }

    /// Clear event history.
    pub fn clear_history(&mut self) {
        self.history.lock().unwrap().clear();
    }

    /// Reset event statistics.
    pub fn reset_stats(&mut self) {
        self.stats.lock().unwrap().clear();
    }

    /// Remove all handlers for an event type.
    pub fn clear_handlers(&mut self, event_type: LifecycleEventType) {
        self.handlers.lock().unwrap().remove(&event_type);
    }

    /// Remove all webhooks.
    pub fn clear_webhooks(&mut self) {
        self.webhooks.lock().unwrap().clear();
    }
}

impl Default for LifecycleEventManager {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU32, Ordering};

    #[tokio::test]
    async fn test_event_creation() {
        let event = ContentEvent::simple("QmTest".to_string(), LifecycleEventType::ContentAdded);
        assert_eq!(event.cid, "QmTest");
        assert_eq!(event.event_type, LifecycleEventType::ContentAdded);
        assert!(event.size_bytes.is_none());
    }

    #[tokio::test]
    async fn test_event_with_size() {
        let event =
            ContentEvent::with_size("QmTest".to_string(), LifecycleEventType::ContentAdded, 1024);
        assert_eq!(event.size_bytes, Some(1024));
    }

    #[tokio::test]
    async fn test_event_with_peer() {
        let event = ContentEvent::with_peer(
            "QmTest".to_string(),
            LifecycleEventType::ChunkTransferred,
            "peer123".to_string(),
        );
        assert_eq!(event.peer_id, Some("peer123".to_string()));
    }

    #[tokio::test]
    async fn test_event_with_metadata() {
        let event = ContentEvent::simple("QmTest".to_string(), LifecycleEventType::ContentAdded)
            .with_metadata("key1".to_string(), "value1".to_string())
            .with_metadata("key2".to_string(), "value2".to_string());

        assert!(event.metadata.is_some());
        let metadata = event.metadata.unwrap();
        assert_eq!(metadata.get("key1"), Some(&"value1".to_string()));
        assert_eq!(metadata.get("key2"), Some(&"value2".to_string()));
    }

    #[tokio::test]
    async fn test_handler_registration() {
        let mut manager = LifecycleEventManager::new();
        let counter = Arc::new(AtomicU32::new(0));
        let counter_clone = counter.clone();

        manager.on(LifecycleEventType::ContentAdded, move |_event| {
            counter_clone.fetch_add(1, Ordering::SeqCst);
        });

        let event = ContentEvent::simple("QmTest".to_string(), LifecycleEventType::ContentAdded);
        manager.emit(event).await;

        // Wait a bit for handler to execute
        tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;

        assert_eq!(counter.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn test_multiple_handlers() {
        let mut manager = LifecycleEventManager::new();
        let counter = Arc::new(AtomicU32::new(0));

        let counter1 = counter.clone();
        manager.on(LifecycleEventType::ContentAdded, move |_event| {
            counter1.fetch_add(1, Ordering::SeqCst);
        });

        let counter2 = counter.clone();
        manager.on(LifecycleEventType::ContentAdded, move |_event| {
            counter2.fetch_add(1, Ordering::SeqCst);
        });

        let event = ContentEvent::simple("QmTest".to_string(), LifecycleEventType::ContentAdded);
        manager.emit(event).await;

        tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;

        assert_eq!(counter.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn test_event_history() {
        let manager = LifecycleEventManager::new();

        let event1 = ContentEvent::simple("QmTest1".to_string(), LifecycleEventType::ContentAdded);
        let event2 =
            ContentEvent::simple("QmTest2".to_string(), LifecycleEventType::ContentAccessed);

        manager.emit(event1).await;
        manager.emit(event2).await;

        let history = manager.get_history(None);
        assert_eq!(history.len(), 2);
    }

    #[tokio::test]
    async fn test_filtered_history() {
        let manager = LifecycleEventManager::new();

        manager
            .emit(ContentEvent::simple(
                "Qm1".to_string(),
                LifecycleEventType::ContentAdded,
            ))
            .await;
        manager
            .emit(ContentEvent::simple(
                "Qm2".to_string(),
                LifecycleEventType::ContentAccessed,
            ))
            .await;
        manager
            .emit(ContentEvent::simple(
                "Qm3".to_string(),
                LifecycleEventType::ContentAdded,
            ))
            .await;

        let history = manager.get_history(Some(LifecycleEventType::ContentAdded));
        assert_eq!(history.len(), 2);
    }

    #[tokio::test]
    async fn test_recent_events() {
        let manager = LifecycleEventManager::new();

        for i in 0..5 {
            manager
                .emit(ContentEvent::simple(
                    format!("Qm{}", i),
                    LifecycleEventType::ContentAdded,
                ))
                .await;
        }

        let recent = manager.get_recent(3);
        assert_eq!(recent.len(), 3);
    }

    #[tokio::test]
    async fn test_event_statistics() {
        let manager = LifecycleEventManager::new();

        manager
            .emit(ContentEvent::simple(
                "Qm1".to_string(),
                LifecycleEventType::ContentAdded,
            ))
            .await;
        manager
            .emit(ContentEvent::simple(
                "Qm2".to_string(),
                LifecycleEventType::ContentAdded,
            ))
            .await;
        manager
            .emit(ContentEvent::simple(
                "Qm3".to_string(),
                LifecycleEventType::ContentAccessed,
            ))
            .await;

        assert_eq!(manager.get_event_count(LifecycleEventType::ContentAdded), 2);
        assert_eq!(
            manager.get_event_count(LifecycleEventType::ContentAccessed),
            1
        );
        assert_eq!(manager.get_total_event_count(), 3);
    }

    #[tokio::test]
    async fn test_history_size_limit() {
        let manager = LifecycleEventManager::with_history_size(5);

        for i in 0..10 {
            manager
                .emit(ContentEvent::simple(
                    format!("Qm{}", i),
                    LifecycleEventType::ContentAdded,
                ))
                .await;
        }

        let history = manager.get_history(None);
        assert_eq!(history.len(), 5);
    }

    #[tokio::test]
    async fn test_clear_history() {
        let mut manager = LifecycleEventManager::new();

        manager
            .emit(ContentEvent::simple(
                "Qm1".to_string(),
                LifecycleEventType::ContentAdded,
            ))
            .await;
        manager
            .emit(ContentEvent::simple(
                "Qm2".to_string(),
                LifecycleEventType::ContentAccessed,
            ))
            .await;

        assert_eq!(manager.get_history(None).len(), 2);

        manager.clear_history();
        assert_eq!(manager.get_history(None).len(), 0);
    }

    #[tokio::test]
    async fn test_reset_stats() {
        let mut manager = LifecycleEventManager::new();

        manager
            .emit(ContentEvent::simple(
                "Qm1".to_string(),
                LifecycleEventType::ContentAdded,
            ))
            .await;
        assert_eq!(manager.get_total_event_count(), 1);

        manager.reset_stats();
        assert_eq!(manager.get_total_event_count(), 0);
    }

    #[tokio::test]
    async fn test_webhook_config() {
        let webhook = WebhookConfig::new("https://example.com/webhook".to_string())
            .for_events(vec![
                LifecycleEventType::ContentAdded,
                LifecycleEventType::ContentRemoved,
            ])
            .with_auth("Bearer token123".to_string());

        assert_eq!(webhook.url, "https://example.com/webhook");
        assert_eq!(webhook.events.len(), 2);
        assert_eq!(webhook.auth_header, Some("Bearer token123".to_string()));
    }

    #[tokio::test]
    async fn test_webhook_registration() {
        let mut manager = LifecycleEventManager::new();
        let webhook = WebhookConfig::new("https://example.com/webhook".to_string());

        manager.register_webhook(webhook);

        // Emit event (webhook will be logged in debug mode)
        manager
            .emit(ContentEvent::simple(
                "Qm1".to_string(),
                LifecycleEventType::ContentAdded,
            ))
            .await;
    }

    #[tokio::test]
    async fn test_clear_handlers() {
        let mut manager = LifecycleEventManager::new();
        let counter = Arc::new(AtomicU32::new(0));
        let counter_clone = counter.clone();

        manager.on(LifecycleEventType::ContentAdded, move |_event| {
            counter_clone.fetch_add(1, Ordering::SeqCst);
        });

        manager
            .emit(ContentEvent::simple(
                "Qm1".to_string(),
                LifecycleEventType::ContentAdded,
            ))
            .await;
        tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
        assert_eq!(counter.load(Ordering::SeqCst), 1);

        manager.clear_handlers(LifecycleEventType::ContentAdded);
        manager
            .emit(ContentEvent::simple(
                "Qm2".to_string(),
                LifecycleEventType::ContentAdded,
            ))
            .await;
        tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
        assert_eq!(counter.load(Ordering::SeqCst), 1); // Should still be 1
    }
}