use std::{
sync::{Arc, Condvar, Mutex, RwLock, Weak},
time::Duration,
};
use super::Topology;
use crate::{
cmap::{options::ConnectionPoolOptions, Connection, ConnectionPool},
error::Result,
options::{ClientOptions, StreamAddress},
};
#[derive(Debug)]
pub(crate) struct Server {
pub(crate) address: StreamAddress,
topology: Weak<RwLock<Topology>>,
pool: ConnectionPool,
condvar: Condvar,
condvar_mutex: Mutex<()>,
}
impl Server {
pub(crate) fn new(
topology: Weak<RwLock<Topology>>,
address: StreamAddress,
options: &ClientOptions,
) -> Self {
Self {
topology,
pool: ConnectionPool::new(
address.clone(),
Some(ConnectionPoolOptions::from_client_options(options)),
),
condvar: Default::default(),
condvar_mutex: Default::default(),
address,
}
}
pub(crate) fn checkout_connection(&self) -> Result<Connection> {
self.pool.check_out()
}
pub(crate) fn clear_connection_pool(&self) {
self.pool.clear();
}
pub(crate) fn topology(&self) -> Option<Arc<RwLock<Topology>>> {
self.topology.upgrade()
}
pub(crate) fn wait_timeout(&self, duration: Duration) -> bool {
self.condvar
.wait_timeout(self.condvar_mutex.lock().unwrap(), duration)
.unwrap()
.1
.timed_out()
}
pub(crate) fn request_topology_check(&self) {
self.condvar.notify_all()
}
}