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
pub use crate::connection::Connection;
use crate::Result;
use async_std::sync::{Arc, RwLock};
use std::collections::HashMap;
use std::net::SocketAddr;

#[derive(Default)]
pub struct MinerList<CState: Clone + Sync + Send + 'static> {
    //@todo there are faster data structures than hashmap. Investigate using some of those.
    pub miners: RwLock<HashMap<SocketAddr, Arc<Connection<CState>>>>,
}

impl<CState: Clone + Sync + Send + 'static> MinerList<CState> {
    pub fn new() -> Self {
        MinerList {
            miners: RwLock::new(HashMap::new()),
        }
    }

    pub async fn add_miner(&self, addr: SocketAddr, miner: Arc<Connection<CState>>) -> Result<()> {
        self.miners.write().await.insert(addr, miner);
        // gauge!(
        //     "stratum.num_connections",
        //     self.miners.read().await.len() as f64
        // );
        Ok(())
    }

    pub async fn remove_miner(&self, addr: SocketAddr) -> Result<()> {
        self.miners.write().await.remove(&addr);
        // gauge!(
        //     "stratum.num_connections",
        //     self.miners.read().await.len() as f64
        // );
        Ok(())
    }

    pub async fn get_all_miners(&self) -> Vec<Arc<Connection<CState>>> {
        self.miners.read().await.values().cloned().collect()
    }

    pub async fn len(&self) -> usize {
        self.miners.read().await.len()
    }

    pub async fn is_empty(&self) -> bool {
        self.miners.read().await.is_empty()
    }

    pub async fn shutdown(&self) -> Result<()> {
        //@todo we need to parallize this async.
        for miner in self.miners.read().await.values() {
            miner.shutdown().await?;
        }

        Ok(())
    }
}