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
use std::sync::{
    atomic::{AtomicU32, Ordering},
    Arc,
};

use crate::{
    cmap::{establish::ConnectionEstablisher, options::ConnectionPoolOptions, ConnectionPool},
    options::{ClientOptions, ServerAddress},
    sdam::TopologyUpdater,
};

/// Contains the state for a given server in the topology.
#[derive(Debug)]
pub(crate) struct Server {
    pub(crate) address: ServerAddress,

    /// The connection pool for the server.
    pub(crate) pool: ConnectionPool,

    /// Number of operations currently using this server.
    operation_count: AtomicU32,
}

impl Server {
    #[cfg(test)]
    pub(crate) fn new_mocked(address: ServerAddress, operation_count: u32) -> Self {
        Self {
            address: address.clone(),
            pool: ConnectionPool::new_mocked(address),
            operation_count: AtomicU32::new(operation_count),
        }
    }

    /// Create a new reference counted `Server`, including its connection pool.
    pub(crate) fn new(
        address: ServerAddress,
        options: ClientOptions,
        connection_establisher: ConnectionEstablisher,
        topology_updater: TopologyUpdater,
        topology_id: bson::oid::ObjectId,
    ) -> Arc<Server> {
        Arc::new(Self {
            pool: ConnectionPool::new(
                address.clone(),
                connection_establisher,
                topology_updater,
                topology_id,
                Some(ConnectionPoolOptions::from_client_options(&options)),
            ),
            address,
            operation_count: AtomicU32::new(0),
        })
    }

    pub(crate) fn increment_operation_count(&self) {
        self.operation_count.fetch_add(1, Ordering::SeqCst);
    }

    pub(crate) fn decrement_operation_count(&self) {
        self.operation_count.fetch_sub(1, Ordering::SeqCst);
    }

    pub(crate) fn operation_count(&self) -> u32 {
        self.operation_count.load(Ordering::SeqCst)
    }
}