|
| 1 | +//! Client Connection Pooling |
| 2 | +use std::borrow::ToOwned; |
| 3 | +use std::collections::HashMap; |
| 4 | +use std::io::{self, Read, Write}; |
| 5 | +use std::net::{SocketAddr, Shutdown}; |
| 6 | +use std::sync::{Arc, Mutex}; |
| 7 | + |
| 8 | +use net::{NetworkConnector, NetworkStream, HttpConnector}; |
| 9 | + |
| 10 | +/// The `NetworkConnector` that behaves as a connection pool used by hyper's `Client`. |
| 11 | +pub struct Pool<C: NetworkConnector> { |
| 12 | + connector: C, |
| 13 | + inner: Arc<Mutex<PoolImpl<<C as NetworkConnector>::Stream>>> |
| 14 | +} |
| 15 | + |
| 16 | +/// Config options for the `Pool`. |
| 17 | +#[derive(Debug)] |
| 18 | +pub struct Config { |
| 19 | + /// The maximum idle connections *per host*. |
| 20 | + pub max_idle: usize, |
| 21 | +} |
| 22 | + |
| 23 | +impl Default for Config { |
| 24 | + #[inline] |
| 25 | + fn default() -> Config { |
| 26 | + Config { |
| 27 | + max_idle: 5, |
| 28 | + } |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +#[derive(Debug)] |
| 33 | +struct PoolImpl<S> { |
| 34 | + conns: HashMap<Key, Vec<S>>, |
| 35 | + config: Config, |
| 36 | +} |
| 37 | + |
| 38 | +type Key = (String, u16, Scheme); |
| 39 | + |
| 40 | +fn key<T: Into<Scheme>>(host: &str, port: u16, scheme: T) -> Key { |
| 41 | + (host.to_owned(), port, scheme.into()) |
| 42 | +} |
| 43 | + |
| 44 | +#[derive(Clone, PartialEq, Eq, Debug, Hash)] |
| 45 | +enum Scheme { |
| 46 | + Http, |
| 47 | + Https, |
| 48 | + Other(String) |
| 49 | +} |
| 50 | + |
| 51 | +impl<'a> From<&'a str> for Scheme { |
| 52 | + fn from(s: &'a str) -> Scheme { |
| 53 | + match s { |
| 54 | + "http" => Scheme::Http, |
| 55 | + "https" => Scheme::Https, |
| 56 | + s => Scheme::Other(String::from(s)) |
| 57 | + } |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +impl Pool<HttpConnector> { |
| 62 | + /// Creates a `Pool` with an `HttpConnector`. |
| 63 | + #[inline] |
| 64 | + pub fn new(config: Config) -> Pool<HttpConnector> { |
| 65 | + Pool::with_connector(config, HttpConnector(None)) |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +impl<C: NetworkConnector> Pool<C> { |
| 70 | + /// Creates a `Pool` with a specified `NetworkConnector`. |
| 71 | + #[inline] |
| 72 | + pub fn with_connector(config: Config, connector: C) -> Pool<C> { |
| 73 | + Pool { |
| 74 | + connector: connector, |
| 75 | + inner: Arc::new(Mutex::new(PoolImpl { |
| 76 | + conns: HashMap::new(), |
| 77 | + config: config, |
| 78 | + })) |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + /// Clear all idle connections from the Pool, closing them. |
| 83 | + #[inline] |
| 84 | + pub fn clear_idle(&mut self) { |
| 85 | + self.inner.lock().unwrap().conns.clear(); |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +impl<S> PoolImpl<S> { |
| 90 | + fn reuse(&mut self, key: Key, conn: S) { |
| 91 | + trace!("reuse {:?}", key); |
| 92 | + let conns = self.conns.entry(key).or_insert(vec![]); |
| 93 | + if conns.len() < self.config.max_idle { |
| 94 | + conns.push(conn); |
| 95 | + } |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +impl<C: NetworkConnector<Stream=S>, S: NetworkStream + Send> NetworkConnector for Pool<C> { |
| 100 | + type Stream = PooledStream<S>; |
| 101 | + fn connect(&mut self, host: &str, port: u16, scheme: &str) -> io::Result<PooledStream<S>> { |
| 102 | + let key = key(host, port, scheme); |
| 103 | + let mut locked = self.inner.lock().unwrap(); |
| 104 | + let mut should_remove = false; |
| 105 | + let conn = match locked.conns.get_mut(&key) { |
| 106 | + Some(ref mut vec) => { |
| 107 | + should_remove = vec.len() == 1; |
| 108 | + vec.pop().unwrap() |
| 109 | + } |
| 110 | + _ => try!(self.connector.connect(host, port, scheme)) |
| 111 | + }; |
| 112 | + if should_remove { |
| 113 | + locked.conns.remove(&key); |
| 114 | + } |
| 115 | + Ok(PooledStream { |
| 116 | + inner: Some((key, conn)), |
| 117 | + is_closed: false, |
| 118 | + is_drained: false, |
| 119 | + pool: self.inner.clone() |
| 120 | + }) |
| 121 | + } |
| 122 | +} |
| 123 | + |
| 124 | +/// A Stream that will try to be returned to the Pool when dropped. |
| 125 | +pub struct PooledStream<S> { |
| 126 | + inner: Option<(Key, S)>, |
| 127 | + is_closed: bool, |
| 128 | + is_drained: bool, |
| 129 | + pool: Arc<Mutex<PoolImpl<S>>> |
| 130 | +} |
| 131 | + |
| 132 | +impl<S: NetworkStream> Read for PooledStream<S> { |
| 133 | + #[inline] |
| 134 | + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { |
| 135 | + match self.inner.as_mut().unwrap().1.read(buf) { |
| 136 | + Ok(0) => { |
| 137 | + self.is_drained = true; |
| 138 | + Ok(0) |
| 139 | + } |
| 140 | + r => r |
| 141 | + } |
| 142 | + } |
| 143 | +} |
| 144 | + |
| 145 | +impl<S: NetworkStream> Write for PooledStream<S> { |
| 146 | + #[inline] |
| 147 | + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
| 148 | + self.inner.as_mut().unwrap().1.write(buf) |
| 149 | + } |
| 150 | + |
| 151 | + #[inline] |
| 152 | + fn flush(&mut self) -> io::Result<()> { |
| 153 | + self.inner.as_mut().unwrap().1.flush() |
| 154 | + } |
| 155 | +} |
| 156 | + |
| 157 | +impl<S: NetworkStream> NetworkStream for PooledStream<S> { |
| 158 | + #[inline] |
| 159 | + fn peer_addr(&mut self) -> io::Result<SocketAddr> { |
| 160 | + self.inner.as_mut().unwrap().1.peer_addr() |
| 161 | + } |
| 162 | + |
| 163 | + #[inline] |
| 164 | + fn close(&mut self, how: Shutdown) -> io::Result<()> { |
| 165 | + self.is_closed = true; |
| 166 | + self.inner.as_mut().unwrap().1.close(how) |
| 167 | + } |
| 168 | +} |
| 169 | + |
| 170 | +impl<S> Drop for PooledStream<S> { |
| 171 | + fn drop(&mut self) { |
| 172 | + trace!("PooledStream.drop, is_closed={}, is_drained={}", self.is_closed, self.is_drained); |
| 173 | + if !self.is_closed && self.is_drained { |
| 174 | + self.inner.take().map(|(key, conn)| { |
| 175 | + if let Ok(mut pool) = self.pool.lock() { |
| 176 | + pool.reuse(key, conn); |
| 177 | + } |
| 178 | + // else poisoned, give up |
| 179 | + }); |
| 180 | + } |
| 181 | + } |
| 182 | +} |
| 183 | + |
| 184 | +#[cfg(test)] |
| 185 | +mod tests { |
| 186 | + use std::net::Shutdown; |
| 187 | + use mock::MockConnector; |
| 188 | + use net::{NetworkConnector, NetworkStream}; |
| 189 | + |
| 190 | + use super::{Pool, key}; |
| 191 | + |
| 192 | + macro_rules! mocked { |
| 193 | + () => ({ |
| 194 | + Pool::with_connector(Default::default(), MockConnector) |
| 195 | + }) |
| 196 | + } |
| 197 | + |
| 198 | + #[test] |
| 199 | + fn test_connect_and_drop() { |
| 200 | + let mut pool = mocked!(); |
| 201 | + let key = key("127.0.0.1", 3000, "http"); |
| 202 | + pool.connect("127.0.0.1", 3000, "http").unwrap().is_drained = true; |
| 203 | + { |
| 204 | + let locked = pool.inner.lock().unwrap(); |
| 205 | + assert_eq!(locked.conns.len(), 1); |
| 206 | + assert_eq!(locked.conns.get(&key).unwrap().len(), 1); |
| 207 | + } |
| 208 | + pool.connect("127.0.0.1", 3000, "http").unwrap().is_drained = true; //reused |
| 209 | + { |
| 210 | + let locked = pool.inner.lock().unwrap(); |
| 211 | + assert_eq!(locked.conns.len(), 1); |
| 212 | + assert_eq!(locked.conns.get(&key).unwrap().len(), 1); |
| 213 | + } |
| 214 | + } |
| 215 | + |
| 216 | + #[test] |
| 217 | + fn test_closed() { |
| 218 | + let mut pool = mocked!(); |
| 219 | + let mut stream = pool.connect("127.0.0.1", 3000, "http").unwrap(); |
| 220 | + stream.close(Shutdown::Both).unwrap(); |
| 221 | + drop(stream); |
| 222 | + let locked = pool.inner.lock().unwrap(); |
| 223 | + assert_eq!(locked.conns.len(), 0); |
| 224 | + } |
| 225 | + |
| 226 | + |
| 227 | +} |
0 commit comments