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
9pub struct Session {
11 id: String,
13 interests: HashSet<Cid>,
15 received_blocks: HashSet<Cid>,
17 peers: HashSet<PeerId>,
19 created_at: Instant,
21 last_activity: Instant,
23 timeout: Duration,
25 active: bool,
27 priority: i32,
29 max_peers: usize,
31 stats: SessionStats,
33}
34
35#[derive(Debug, Clone, Default)]
37pub struct SessionStats {
38 pub blocks_requested: u64,
40 pub blocks_received: u64,
42 pub blocks_failed: u64,
44 pub bytes_received: u64,
46 pub peers_tried: u64,
48 pub average_response_time_ms: f64,
50 pub duration: Duration,
52}
53
54#[derive(Debug, Clone)]
56pub struct SessionConfig {
57 pub timeout: Duration,
59 pub priority: i32,
61 pub max_peers: usize,
63 pub rebroadcast_wants: bool,
65 pub rebroadcast_interval: Duration,
67}
68
69impl Default for SessionConfig {
70 fn default() -> Self {
71 Self {
72 timeout: Duration::from_secs(300), priority: 1,
74 max_peers: 10,
75 rebroadcast_wants: true,
76 rebroadcast_interval: Duration::from_secs(30),
77 }
78 }
79}
80
81impl Session {
82 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 pub fn id(&self) -> &str {
102 &self.id
103 }
104
105 pub fn is_active(&self) -> bool {
107 self.active && !self.is_expired()
108 }
109
110 pub fn is_expired(&self) -> bool {
112 Instant::now().duration_since(self.last_activity) > self.timeout
113 }
114
115 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 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 pub fn interests(&self) -> &HashSet<Cid> {
132 &self.interests
133 }
134
135 pub fn pending_interests(&self) -> HashSet<Cid> {
137 self.interests
138 .difference(&self.received_blocks)
139 .cloned()
140 .collect()
141 }
142
143 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 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 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 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 pub fn peers(&self) -> &HashSet<PeerId> {
188 &self.peers
189 }
190
191 pub fn priority(&self) -> i32 {
193 self.priority
194 }
195
196 pub fn set_priority(&mut self, priority: i32) {
198 self.priority = priority;
199 self.update_activity();
200 }
201
202 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 pub fn wants_block(&self, cid: &Cid) -> bool {
218 self.interests.contains(cid) && !self.received_blocks.contains(cid)
219 }
220
221 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 fn update_activity(&mut self) {
231 self.last_activity = Instant::now();
232 }
233
234 pub fn statistics(&self) -> SessionStats {
236 let mut stats = self.stats.clone();
237 stats.duration = Instant::now().duration_since(self.created_at);
238
239 if stats.blocks_received > 0 {
241 stats.average_response_time_ms =
244 stats.duration.as_millis() as f64 / stats.blocks_received as f64;
245 }
246
247 stats
248 }
249
250 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
260pub struct SessionManager {
262 sessions: HashMap<String, Session>,
264 session_counter: u64,
266 default_config: SessionConfig,
268 running: bool,
270}
271
272impl SessionManager {
273 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 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 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 pub async fn stop(&mut self) -> Result<()> {
306 if !self.running {
307 return Ok(());
308 }
309
310 info!("Stopping session manager");
311
312 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 pub fn create_session(&mut self) -> Result<String> {
324 self.create_session_with_config(self.default_config.clone())
325 }
326
327 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 pub fn get_session(&self, session_id: &str) -> Option<&Session> {
345 self.sessions.get(session_id)
346 }
347
348 pub fn get_session_mut(&mut self, session_id: &str) -> Option<&mut Session> {
350 self.sessions.get_mut(session_id)
351 }
352
353 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 pub fn active_sessions(&self) -> Vec<&Session> {
364 self.sessions.values().filter(|s| s.is_active()).collect()
365 }
366
367 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 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 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 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 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 pub fn session_count(&self) -> usize {
428 self.sessions.len()
429 }
430
431 pub fn active_session_count(&self) -> usize {
433 self.sessions.values().filter(|s| s.is_active()).count()
434 }
435
436 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#[derive(Debug, Clone, Default)]
472pub struct SessionManagerStats {
473 pub total_sessions: usize,
475 pub active_sessions: usize,
477 pub total_blocks_requested: u64,
479 pub total_blocks_received: u64,
481 pub total_blocks_failed: u64,
483 pub total_bytes_received: u64,
485 pub total_pending_interests: u64,
487 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), ..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 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}