1use std::sync::Arc;
5
6use linera_base::time::Duration;
7
8use super::{transport, GrpcError};
9
10#[derive(Clone, Default)]
12pub struct GrpcConnectionPool {
13 options: transport::Options,
14 channels: Arc<papaya::HashMap<String, transport::Channel>>,
15}
16
17impl GrpcConnectionPool {
18 pub fn new(options: transport::Options) -> Self {
20 Self {
21 options,
22 channels: Arc::new(papaya::HashMap::default()),
23 }
24 }
25
26 pub fn with_connect_timeout(mut self, connect_timeout: impl Into<Option<Duration>>) -> Self {
28 self.options.connect_timeout = connect_timeout.into();
29 self
30 }
31
32 pub fn with_timeout(mut self, timeout: impl Into<Option<Duration>>) -> Self {
34 self.options.timeout = timeout.into();
35 self
36 }
37
38 pub fn channel(&self, address: String) -> Result<transport::Channel, GrpcError> {
42 let pinned = self.channels.pin();
43 if let Some(channel) = pinned.get(&address) {
44 return Ok(channel.clone());
45 }
46 let channel = transport::create_channel(address.clone(), &self.options)?;
47 Ok(pinned.get_or_insert(address, channel).clone())
48 }
49}