Skip to main content

helia_bitswap/
session.rs

1use crate::{Result, WantListEntry, WantType};
2use cid::Cid;
3use helia_interface::HeliaError;
4use libp2p::PeerId;
5use std::collections::{HashMap, HashSet, VecDeque};
6use std::time::{Duration, Instant};
7use tracing::{debug, info, warn};
8
9/// A bitswap session for efficient block retrieval
10pub struct Session {
11    /// Session ID
12    id: String,
13    /// Blocks this session is interested in
14    interests: HashSet<Cid>,
15    /// Blocks that have been received
16    received_blocks: HashSet<Cid>,
17    /// Peers that are part of this session
18    peers: HashSet<PeerId>,
19    /// When the session was created
20    created_at: Instant,
21    /// Last activity time
22    last_activity: Instant,
23    /// Session timeout
24    timeout: Duration,
25    /// Whether the session is active
26    active: bool,
27    /// Session priority
28    priority: i32,
29    /// Maximum number of peers to use
30    max_peers: usize,
31    /// Session statistics
32    stats: SessionStats,
33}
34
35/// Session statistics
36#[derive(Debug, Clone, Default)]
37pub struct SessionStats {
38    /// Number of blocks requested
39    pub blocks_requested: u64,
40    /// Number of blocks received
41    pub blocks_received: u64,
42    /// Number of blocks failed
43    pub blocks_failed: u64,
44    /// Total bytes received
45    pub bytes_received: u64,
46    /// Number of peers tried
47    pub peers_tried: u64,
48    /// Average response time in milliseconds
49    pub average_response_time_ms: f64,
50    /// Session duration
51    pub duration: Duration,
52}
53
54/// Session configuration
55#[derive(Debug, Clone)]
56pub struct SessionConfig {
57    /// Session timeout
58    pub timeout: Duration,
59    /// Session priority
60    pub priority: i32,
61    /// Maximum number of peers to use
62    pub max_peers: usize,
63    /// Whether to rebroadcast wants periodically
64    pub rebroadcast_wants: bool,
65    /// Rebroadcast interval
66    pub rebroadcast_interval: Duration,
67}
68
69impl Default for SessionConfig {
70    fn default() -> Self {
71        Self {
72            timeout: Duration::from_secs(300), // 5 minutes
73            priority: 1,
74            max_peers: 10,
75            rebroadcast_wants: true,
76            rebroadcast_interval: Duration::from_secs(30),
77        }
78    }
79}
80
81impl Session {
82    /// Create a new session
83    pub fn new(id: String, config: SessionConfig) -> Self {
84        let now = Instant::now();
85        Self {
86            id,
87            interests: HashSet::new(),
88            received_blocks: HashSet::new(),
89            peers: HashSet::new(),
90            created_at: now,
91            last_activity: now,
92            timeout: config.timeout,
93            active: true,
94            priority: config.priority,
95            max_peers: config.max_peers,
96            stats: SessionStats::default(),
97        }
98    }
99
100    /// Get session ID
101    pub fn id(&self) -> &str {
102        &self.id
103    }
104
105    /// Check if session is active
106    pub fn is_active(&self) -> bool {
107        self.active && !self.is_expired()
108    }
109
110    /// Check if session has expired
111    pub fn is_expired(&self) -> bool {
112        Instant::now().duration_since(self.last_activity) > self.timeout
113    }
114
115    /// Add interest in a block
116    pub fn add_interest(&mut self, cid: Cid) {
117        debug!("Session {} adding interest in {}", self.id, cid);
118        self.interests.insert(cid);
119        self.update_activity();
120        self.stats.blocks_requested += 1;
121    }
122
123    /// Remove interest in a block
124    pub fn remove_interest(&mut self, cid: &Cid) {
125        debug!("Session {} removing interest in {}", self.id, cid);
126        self.interests.remove(cid);
127        self.update_activity();
128    }
129
130    /// Get all interests
131    pub fn interests(&self) -> &HashSet<Cid> {
132        &self.interests
133    }
134
135    /// Get pending interests (not yet received)
136    pub fn pending_interests(&self) -> HashSet<Cid> {
137        self.interests
138            .difference(&self.received_blocks)
139            .cloned()
140            .collect()
141    }
142
143    /// Mark a block as received
144    pub fn mark_block_received(&mut self, cid: &Cid, size: usize) {
145        debug!("Session {} received block {}", self.id, cid);
146        self.received_blocks.insert(*cid);
147        self.interests.remove(cid);
148        self.update_activity();
149
150        self.stats.blocks_received += 1;
151        self.stats.bytes_received += size as u64;
152    }
153
154    /// Mark a block as failed
155    pub fn mark_block_failed(&mut self, cid: &Cid) {
156        warn!("Session {} failed to get block {}", self.id, cid);
157        self.interests.remove(cid);
158        self.update_activity();
159        self.stats.blocks_failed += 1;
160    }
161
162    /// Add a peer to the session
163    pub fn add_peer(&mut self, peer_id: PeerId) -> bool {
164        if self.peers.len() >= self.max_peers {
165            return false;
166        }
167
168        if self.peers.insert(peer_id) {
169            debug!("Session {} added peer {}", self.id, peer_id);
170            self.update_activity();
171            self.stats.peers_tried += 1;
172            true
173        } else {
174            false
175        }
176    }
177
178    /// Remove a peer from the session
179    pub fn remove_peer(&mut self, peer_id: &PeerId) {
180        if self.peers.remove(peer_id) {
181            debug!("Session {} removed peer {}", self.id, peer_id);
182            self.update_activity();
183        }
184    }
185
186    /// Get session peers
187    pub fn peers(&self) -> &HashSet<PeerId> {
188        &self.peers
189    }
190
191    /// Get session priority
192    pub fn priority(&self) -> i32 {
193        self.priority
194    }
195
196    /// Set session priority
197    pub fn set_priority(&mut self, priority: i32) {
198        self.priority = priority;
199        self.update_activity();
200    }
201
202    /// Generate wantlist for this session
203    pub fn generate_wantlist(&self) -> Vec<WantListEntry> {
204        self.pending_interests()
205            .into_iter()
206            .map(|cid| WantListEntry {
207                cid,
208                priority: self.priority,
209                want_type: WantType::WantBlock,
210                cancel: false,
211                send_dont_have: true,
212            })
213            .collect()
214    }
215
216    /// Check if session wants a specific block
217    pub fn wants_block(&self, cid: &Cid) -> bool {
218        self.interests.contains(cid) && !self.received_blocks.contains(cid)
219    }
220
221    /// Close the session
222    pub fn close(&mut self) {
223        info!("Closing session {}", self.id);
224        self.active = false;
225        self.interests.clear();
226        self.peers.clear();
227    }
228
229    /// Update last activity time
230    fn update_activity(&mut self) {
231        self.last_activity = Instant::now();
232    }
233
234    /// Get session statistics
235    pub fn statistics(&self) -> SessionStats {
236        let mut stats = self.stats.clone();
237        stats.duration = Instant::now().duration_since(self.created_at);
238
239        // Calculate average response time if we have received blocks
240        if stats.blocks_received > 0 {
241            // This is a simplified calculation - in a real implementation,
242            // you'd track individual request/response times
243            stats.average_response_time_ms =
244                stats.duration.as_millis() as f64 / stats.blocks_received as f64;
245        }
246
247        stats
248    }
249
250    /// Get completion percentage
251    pub fn completion_percentage(&self) -> f64 {
252        if self.stats.blocks_requested == 0 {
253            return 100.0;
254        }
255
256        (self.stats.blocks_received as f64 / self.stats.blocks_requested as f64) * 100.0
257    }
258}
259
260/// Manages multiple bitswap sessions
261pub struct SessionManager {
262    /// Active sessions
263    sessions: HashMap<String, Session>,
264    /// Session creation counter for unique IDs
265    session_counter: u64,
266    /// Default session configuration
267    default_config: SessionConfig,
268    /// Whether the manager is running
269    running: bool,
270}
271
272impl SessionManager {
273    /// Create a new session manager
274    pub fn new() -> Self {
275        Self {
276            sessions: HashMap::new(),
277            session_counter: 0,
278            default_config: SessionConfig::default(),
279            running: false,
280        }
281    }
282
283    /// Create a new session manager with custom config
284    pub fn with_config(config: SessionConfig) -> Self {
285        Self {
286            sessions: HashMap::new(),
287            session_counter: 0,
288            default_config: config,
289            running: false,
290        }
291    }
292
293    /// Start the session manager
294    pub async fn start(&mut self) -> Result<()> {
295        if self.running {
296            return Ok(());
297        }
298
299        info!("Starting session manager");
300        self.running = true;
301        Ok(())
302    }
303
304    /// Stop the session manager
305    pub async fn stop(&mut self) -> Result<()> {
306        if !self.running {
307            return Ok(());
308        }
309
310        info!("Stopping session manager");
311
312        // Close all sessions
313        for session in self.sessions.values_mut() {
314            session.close();
315        }
316        self.sessions.clear();
317
318        self.running = false;
319        Ok(())
320    }
321
322    /// Create a new session
323    pub fn create_session(&mut self) -> Result<String> {
324        self.create_session_with_config(self.default_config.clone())
325    }
326
327    /// Create a new session with custom config
328    pub fn create_session_with_config(&mut self, config: SessionConfig) -> Result<String> {
329        if !self.running {
330            return Err(HeliaError::other("Session manager not running"));
331        }
332
333        self.session_counter += 1;
334        let session_id = format!("session-{}", self.session_counter);
335
336        let session = Session::new(session_id.clone(), config);
337        self.sessions.insert(session_id.clone(), session);
338
339        info!("Created session {}", session_id);
340        Ok(session_id)
341    }
342
343    /// Get a session
344    pub fn get_session(&self, session_id: &str) -> Option<&Session> {
345        self.sessions.get(session_id)
346    }
347
348    /// Get a mutable session
349    pub fn get_session_mut(&mut self, session_id: &str) -> Option<&mut Session> {
350        self.sessions.get_mut(session_id)
351    }
352
353    /// Close a session
354    pub fn close_session(&mut self, session_id: &str) -> Result<()> {
355        if let Some(mut session) = self.sessions.remove(session_id) {
356            session.close();
357            info!("Closed session {}", session_id);
358        }
359        Ok(())
360    }
361
362    /// Get all active sessions
363    pub fn active_sessions(&self) -> Vec<&Session> {
364        self.sessions.values().filter(|s| s.is_active()).collect()
365    }
366
367    /// Get sessions interested in a specific block
368    pub fn sessions_wanting_block(&self, cid: &Cid) -> Vec<&Session> {
369        self.sessions
370            .values()
371            .filter(|s| s.is_active() && s.wants_block(cid))
372            .collect()
373    }
374
375    /// Clean up expired sessions
376    pub fn cleanup_expired_sessions(&mut self) -> usize {
377        let expired_sessions: Vec<String> = self
378            .sessions
379            .iter()
380            .filter(|(_, session)| session.is_expired())
381            .map(|(id, _)| id.clone())
382            .collect();
383
384        let count = expired_sessions.len();
385
386        for session_id in expired_sessions {
387            warn!("Removing expired session: {}", session_id);
388            let _ = self.close_session(&session_id);
389        }
390
391        count
392    }
393
394    /// Get all wantlists from active sessions
395    pub fn get_all_wantlists(&self) -> HashMap<String, Vec<WantListEntry>> {
396        self.sessions
397            .iter()
398            .filter(|(_, session)| session.is_active())
399            .map(|(id, session)| (id.clone(), session.generate_wantlist()))
400            .collect()
401    }
402
403    /// Get aggregated wantlist across all sessions
404    pub fn get_aggregated_wantlist(&self) -> Vec<WantListEntry> {
405        let mut aggregated: HashMap<Cid, WantListEntry> = HashMap::new();
406
407        for session in self.sessions.values() {
408            if session.is_active() {
409                for entry in session.generate_wantlist() {
410                    // Use highest priority for each CID across sessions
411                    aggregated
412                        .entry(entry.cid)
413                        .and_modify(|existing| {
414                            if entry.priority > existing.priority {
415                                existing.priority = entry.priority;
416                            }
417                        })
418                        .or_insert(entry);
419                }
420            }
421        }
422
423        aggregated.into_values().collect()
424    }
425
426    /// Get session count
427    pub fn session_count(&self) -> usize {
428        self.sessions.len()
429    }
430
431    /// Get active session count
432    pub fn active_session_count(&self) -> usize {
433        self.sessions.values().filter(|s| s.is_active()).count()
434    }
435
436    /// Get manager statistics
437    pub fn get_statistics(&self) -> SessionManagerStats {
438        let mut stats = SessionManagerStats::default();
439
440        stats.total_sessions = self.sessions.len();
441        stats.active_sessions = self.active_session_count();
442
443        for session in self.sessions.values() {
444            let session_stats = session.statistics();
445            stats.total_blocks_requested += session_stats.blocks_requested;
446            stats.total_blocks_received += session_stats.blocks_received;
447            stats.total_blocks_failed += session_stats.blocks_failed;
448            stats.total_bytes_received += session_stats.bytes_received;
449
450            if session.is_active() {
451                stats.total_pending_interests += session.pending_interests().len() as u64;
452            }
453        }
454
455        if stats.total_blocks_requested > 0 {
456            stats.success_rate =
457                (stats.total_blocks_received as f64 / stats.total_blocks_requested as f64) * 100.0;
458        }
459
460        stats
461    }
462}
463
464impl Default for SessionManager {
465    fn default() -> Self {
466        Self::new()
467    }
468}
469
470/// Statistics about the session manager
471#[derive(Debug, Clone, Default)]
472pub struct SessionManagerStats {
473    /// Total number of sessions
474    pub total_sessions: usize,
475    /// Number of active sessions
476    pub active_sessions: usize,
477    /// Total blocks requested across all sessions
478    pub total_blocks_requested: u64,
479    /// Total blocks received across all sessions
480    pub total_blocks_received: u64,
481    /// Total blocks failed across all sessions
482    pub total_blocks_failed: u64,
483    /// Total bytes received across all sessions
484    pub total_bytes_received: u64,
485    /// Total pending interests across active sessions
486    pub total_pending_interests: u64,
487    /// Success rate as percentage
488    pub success_rate: f64,
489}
490
491#[cfg(test)]
492mod tests {
493    use super::*;
494
495    #[tokio::test]
496    async fn test_session_manager_lifecycle() {
497        let mut manager = SessionManager::new();
498        assert!(!manager.running);
499
500        assert!(manager.start().await.is_ok());
501        assert!(manager.running);
502
503        assert!(manager.stop().await.is_ok());
504        assert!(!manager.running);
505    }
506
507    #[tokio::test]
508    async fn test_session_creation() {
509        let mut manager = SessionManager::new();
510        manager.start().await.unwrap();
511
512        let session_id = manager.create_session().unwrap();
513        assert_eq!(manager.session_count(), 1);
514
515        let session = manager.get_session(&session_id).unwrap();
516        assert!(session.is_active());
517        assert_eq!(session.id(), session_id);
518    }
519
520    #[test]
521    fn test_session_interests() {
522        let mut session = Session::new("test".to_string(), SessionConfig::default());
523        let cid = Cid::default();
524
525        assert!(!session.wants_block(&cid));
526
527        session.add_interest(cid);
528        assert!(session.wants_block(&cid));
529        assert_eq!(session.interests().len(), 1);
530
531        session.mark_block_received(&cid, 100);
532        assert!(!session.wants_block(&cid));
533        assert_eq!(session.pending_interests().len(), 0);
534    }
535
536    #[test]
537    fn test_session_wantlist() {
538        let mut session = Session::new("test".to_string(), SessionConfig::default());
539        let cid1 = Cid::default();
540
541        session.add_interest(cid1);
542
543        let wantlist = session.generate_wantlist();
544        assert_eq!(wantlist.len(), 1);
545        assert_eq!(wantlist[0].cid, cid1);
546        assert!(!wantlist[0].cancel);
547    }
548
549    #[test]
550    fn test_session_statistics() {
551        let mut session = Session::new("test".to_string(), SessionConfig::default());
552        let cid = Cid::default();
553
554        session.add_interest(cid);
555        session.mark_block_received(&cid, 100);
556
557        let stats = session.statistics();
558        assert_eq!(stats.blocks_requested, 1);
559        assert_eq!(stats.blocks_received, 1);
560        assert_eq!(stats.bytes_received, 100);
561        assert_eq!(session.completion_percentage(), 100.0);
562    }
563
564    #[tokio::test]
565    async fn test_session_cleanup() {
566        let mut manager = SessionManager::new();
567        let config = SessionConfig {
568            timeout: Duration::from_millis(1), // Very short timeout
569            ..Default::default()
570        };
571        manager.start().await.unwrap();
572
573        let session_id = manager.create_session_with_config(config).unwrap();
574        assert_eq!(manager.session_count(), 1);
575
576        // Wait for expiration
577        tokio::time::sleep(Duration::from_millis(10)).await;
578
579        let cleaned = manager.cleanup_expired_sessions();
580        assert_eq!(cleaned, 1);
581        assert_eq!(manager.session_count(), 0);
582    }
583}