use std::{ collections::{HashMap, VecDeque}, path::PathBuf, sync::{Arc, Mutex}, time::Instant, }; use common::{model::Id, stats::Stats}; use usage::{Monitor, Wake}; use crate::hub::ConnId; #[derive(Default)] struct Inner { following: HashMap, latest: HashMap, } pub struct Change { pub stopped: Option, pub started: Option, pub latest: Option, } #[derive(Clone, Default)] pub struct Follows(Arc>); impl Follows { pub fn follow(&self, conn: ConnId, target: Option) -> Change { let mut inner = self.0.lock().unwrap(); let old = inner.following.remove(&conn); if let Some(target) = target { inner.following.insert(conn, target); } let stopped = old.filter(|old| !inner.following.values().any(|id| id == old)); if let Some(stopped) = stopped { inner.latest.remove(&stopped); } Change { stopped, started: target.filter(|target| { old != Some(*target) && inner.following.values().filter(|id| *id == target).count() == 1 }), latest: target.and_then(|target| inner.latest.get(&target).cloned()), } } pub fn leave(&self, conn: ConnId) -> Option { self.follow(conn, None).stopped } pub fn push(&self, user: Id, stats: Stats) -> Vec { let mut inner = self.0.lock().unwrap(); inner.latest.insert(user, stats); inner .following .iter() .filter(|(_, id)| **id == user) .map(|(conn, _)| *conn) .collect() } pub fn is_followed(&self, user: Id) -> bool { self.0 .lock() .unwrap() .following .values() .any(|id| *id == user) } } const HISTORY: usize = 60; #[derive(Default)] struct Rates { last: Option<(Instant, u64, u64)>, history: VecDeque<(u64, f32, f32)>, } #[derive(Clone)] pub struct Machine { monitor: Arc, rates: Arc>, } impl Machine { pub fn new(directory: PathBuf) -> Self { Self { monitor: Arc::new(Monitor::new(Wake::Always, Some(directory))), rates: Arc::default(), } } pub fn sample(&self, (sent, received): (u64, u64)) -> Stats { let now = Instant::now(); let mut rates = self.rates.lock().unwrap(); if let Some((at, last_sent, last_received)) = rates.last { let seconds = now.duration_since(at).as_secs_f32().max(f32::EPSILON); let kbps = |bytes: u64, last: u64| bytes.saturating_sub(last) as f32 * 8. / 1000. / seconds; let rate = ( common::time::now_ms(), kbps(sent, last_sent), kbps(received, last_received), ); rates.history.push_back(rate); while rates.history.len() > HISTORY { rates.history.pop_front(); } } rates.last = Some((now, sent, received)); Stats { traffic: rates.history.clone(), usage: self.monitor.latest().map(|usage| usage::Usage { threads: None, ..usage }), ..Stats::default() } } }