use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::Mutex;
use tonic::transport::Channel;
use tracing::{debug, trace};
pub struct ConnectionPool {
channels: Arc<Mutex<HashMap<String, Channel>>>,
}
impl Default for ConnectionPool {
fn default() -> Self {
Self::new()
}
}
impl ConnectionPool {
pub fn new() -> Self {
Self {
channels: Arc::new(Mutex::new(HashMap::new())),
}
}
pub async fn get_channel(
&self,
endpoint_uri: &str,
) -> Result<Channel, Box<dyn std::error::Error + Send + Sync>> {
trace!("Getting channel for endpoint: {}", endpoint_uri);
let mut channels = self.channels.lock().await;
if let Some(channel) = channels.get(endpoint_uri) {
debug!("Reusing existing channel for endpoint: {}", endpoint_uri);
return Ok(channel.clone());
}
debug!("Creating new channel for endpoint: {}", endpoint_uri);
let channel = Channel::from_shared(endpoint_uri.to_string())?.connect().await?;
channels.insert(endpoint_uri.to_string(), channel.clone());
Ok(channel)
}
}
impl Clone for ConnectionPool {
fn clone(&self) -> Self {
Self {
channels: self.channels.clone(),
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_module_compiles() {
}
}