├── .gitignore ├── bulk.yaml ├── src ├── basic.rs ├── connect.rs ├── uniform │ ├── pool.rs │ ├── connect.rs │ ├── failures.rs │ ├── sink.rs │ ├── chan.rs │ ├── aligner.rs │ └── mod.rs ├── lib.rs ├── metrics.rs ├── error_log.rs ├── config.rs └── queue.rs ├── Cargo.toml ├── LICENSE-MIT ├── vagga.yaml ├── README.md ├── .travis.yml ├── examples └── http.rs └── LICENSE-APACHE /.gitignore: -------------------------------------------------------------------------------- 1 | /.vagga 2 | Cargo.lock 3 | /target 4 | -------------------------------------------------------------------------------- /bulk.yaml: -------------------------------------------------------------------------------- 1 | minimum-bulk: v0.4.5 2 | 3 | versions: 4 | 5 | - file: Cargo.toml 6 | block-start: ^\[package\] 7 | block-end: ^\[.*\] 8 | regex: ^version\s*=\s*"(\S+)" 9 | -------------------------------------------------------------------------------- /src/basic.rs: -------------------------------------------------------------------------------- 1 | use connect::Connect; 2 | use config::PartialConfig; 3 | 4 | 5 | /// Start configuring pool by providing a connector 6 | pub fn pool_for(connector: C) 7 | -> PartialConfig 8 | { 9 | PartialConfig { 10 | connector: connector, 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/connect.rs: -------------------------------------------------------------------------------- 1 | use std::net::SocketAddr; 2 | 3 | use futures::{Future, IntoFuture}; 4 | 5 | 6 | /// This is a trait that is used for establishing a connection 7 | /// 8 | /// Usually just passing a closure is good enough 9 | pub trait Connect { 10 | /// A future retuned by `connect` method 11 | type Future: Future; 12 | /// Establish a connection to the specified address 13 | fn connect(&mut self, address: SocketAddr) -> Self::Future; 14 | } 15 | 16 | impl Connect for T 17 | where T: FnMut(SocketAddr) -> F, 18 | F: IntoFuture, 19 | { 20 | type Future = ::Future; 21 | fn connect(&mut self, address: SocketAddr) -> Self::Future { 22 | (self)(address).into_future() 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tk-pool" 3 | description = """ 4 | Generic connection pool for tokio 5 | """ 6 | license = "MIT/Apache-2.0" 7 | readme = "README.md" 8 | keywords = ["tokio", "connection-pool", "TCP", "connection", "pool"] 9 | homepage = "http://github.com/tailhook/tk-pool" 10 | documentation = "http://docs.rs/tk-pool" 11 | version = "0.5.3" 12 | authors = ["paul@colomiets.name"] 13 | 14 | [dependencies] 15 | futures = "0.1.10" 16 | abstract-ns = "0.4.0" 17 | tokio-core = "0.1.1" 18 | log = "0.4.1" 19 | rand = "0.4.2" 20 | void = "1.0.2" 21 | 22 | [dev-dependencies] 23 | argparse = "0.2.1" 24 | env_logger = "0.5.7" 25 | ns-std-threaded = "0.3.0" 26 | ns-router = "0.1.0" 27 | futures-cpupool = "0.1.2" 28 | tk-http = { version="0.3.5", default-features=false } 29 | 30 | 31 | [lib] 32 | name = "tk_pool" 33 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 The tk-pool Developers 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /vagga.yaml: -------------------------------------------------------------------------------- 1 | commands: 2 | 3 | make: !Command 4 | description: Build the library 5 | container: ubuntu 6 | run: [cargo, build] 7 | 8 | cargo: !Command 9 | description: Run arbitrary cargo command 10 | symlink-name: cargo 11 | container: ubuntu 12 | run: [cargo] 13 | 14 | test: !Command 15 | description: Run tests 16 | container: ubuntu 17 | run: [cargo, test] 18 | 19 | _bulk: !Command 20 | description: Run `bulk` command (for version bookkeeping) 21 | container: ubuntu 22 | run: [bulk] 23 | 24 | containers: 25 | 26 | ubuntu: 27 | setup: 28 | - !Ubuntu xenial 29 | - !Install [ca-certificates, git, build-essential, vim] 30 | 31 | - !TarInstall 32 | url: "https://static.rust-lang.org/dist/rust-1.25.0-x86_64-unknown-linux-gnu.tar.gz" 33 | script: "./install.sh --prefix=/usr \ 34 | --components=rustc,rust-std-x86_64-unknown-linux-gnu,cargo" 35 | - &bulk !Tar 36 | url: "https://github.com/tailhook/bulk/releases/download/v0.4.11/bulk-v0.4.11.tar.gz" 37 | sha256: b718bb8448e726690c94d98d004bf7575f7a429106ec26ad3faf11e0fd9a7978 38 | path: / 39 | 40 | environ: 41 | RUST_BACKTRACE: 1 42 | HOME: /work/target 43 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Tk-Pool 2 | ======= 3 | 4 | **Status: Beta** 5 | 6 | [Documentation](https://docs.rs/tk-pool) | 7 | [Github](https://github.com/tailhook/tk-pool) | 8 | [Crate](https://crates.io/crates/tk-pool) | 9 | [Examples](https://github.com/tailhook/tk-pool/tree/master/examples) 10 | 11 | 12 | A connection pool implementation for tokio. Main features: 13 | 14 | 1. Works for any request-reply protocol (actually for any `Sink`) 15 | 2. Provides both queue and pushback if needed 16 | 3. Allows pipelining (multiple in-flight request when multiplexing) 17 | 4. Auto-reconnects on broken connection 18 | 5. Adapts when DNS name change 19 | 20 | Multiple load-balancing strategies are in to do list. 21 | 22 | 23 | License 24 | ======= 25 | 26 | Licensed under either of 27 | 28 | * Apache License, Version 2.0, 29 | (./LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0) 30 | * MIT license (./LICENSE-MIT or http://opensource.org/licenses/MIT) 31 | at your option. 32 | 33 | Contribution 34 | ------------ 35 | 36 | Unless you explicitly state otherwise, any contribution intentionally 37 | submitted for inclusion in the work by you, as defined in the Apache-2.0 38 | license, shall be dual licensed as above, without any additional terms or 39 | conditions. 40 | 41 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | dist: trusty 3 | language: rust 4 | 5 | cache: 6 | - cargo 7 | 8 | before_cache: 9 | - rm -r $TRAVIS_BUILD_DIR/target/debug 10 | 11 | jobs: 12 | include: 13 | - os: linux 14 | rust: stable 15 | - os: linux 16 | rust: beta 17 | - os: linux 18 | rust: nightly 19 | 20 | # deploy 21 | - stage: publish 22 | os: linux 23 | rust: stable 24 | env: 25 | # CARGO_TOKEN 26 | - secure: "mF0qBgIiY2BFe7jzQYfgrzEyc1yb46BpjZJvz474pzVo/Pihyg5OfMFhDOKYk2SslVx5u91lLqc5KnUY8XbKB6R1DloW2AnEWa0/AwDu5ePpIEaRS0MazDlBOPi/ZDbWNiZAvT2Es4E9CT62OUSob/NRXt71jXa41EGi9AXAk42+KYMhkokfSIV7jnlhjzVhgkT9ptUXGnfS1WJfUl8GnLrvx5R8Gx7lqwscG8qxvyvqAx+0bZU2tLLuLPUsSbXcX07eAjUkqOWMGsPdDmMDd4AJfjXx9k/7bNGPTbw1PBjeNLCNgRsSAdNkv4NJVkA6Q0dxIydVuqIA32gKRJphLUVfx2N0mI+aXLbSlr0me9ps0dpf2+J2BuipBJhvM8zYnSlDyDAT9hkRQ5fQquV1V/fjAT82VTO8SKAUFhWa24R4iGr4xaVmUBN2coA3UVeUbyWfK/IdophwiEKQ+jywH31y/Rly15kbPlGR8o384GR4+r6e0YeMInfVgExcoHNmIMYEaV5cbFG+7RdvVdvwqzVGc5dklpG0ukXTyEWhdis4kFvDf2dtJtmZkGXNvo2L2Td3q7/MbmSajTkICOiS8eEWB7XN0YkEE06zAc6/taihbgX8SC24BD3+cp7n8J2UM+cLNOJMJMGcNDjcj4G4EaqEtIu1nvmc2jgXkv8E0lY=" 27 | install: true 28 | script: true 29 | 30 | deploy: 31 | - provider: script 32 | script: 'cargo publish --verbose --token=$CARGO_TOKEN' 33 | on: 34 | tags: true 35 | -------------------------------------------------------------------------------- /src/uniform/pool.rs: -------------------------------------------------------------------------------- 1 | use std::cell::RefCell; 2 | use std::rc::Rc; 3 | 4 | use abstract_ns::Address; 5 | use futures::{Future, Sink}; 6 | use futures::stream::FuturesUnordered; 7 | 8 | use error_log::{ErrorLog}; 9 | use connect::Connect; 10 | use uniform::aligner::Aligner; 11 | use uniform::failures::Blacklist; 12 | use uniform::{Connections, FutureOk, FutureErr}; 13 | 14 | 15 | pub struct Lazy 16 | where E: ErrorLog, 17 | C: Connect, 18 | <::Future as Future>::Item: Sink, 19 | { 20 | pub(in uniform) conn_limit: u32, 21 | pub(in uniform) reconnect_ms: (u64, u64), // easier to make random value 22 | pub(in uniform) futures: FuturesUnordered::Item>, 24 | Error=FutureErr>>>, 25 | pub(in uniform) connections: Rc::Future as Future>::Item as Sink>::SinkItem>>>, 27 | pub(in uniform) address: A, 28 | pub(in uniform) connector: C, 29 | pub(in uniform) errors: E, 30 | pub(in uniform) metrics: M, 31 | pub(in uniform) aligner: Aligner, 32 | pub(in uniform) blist: Blacklist, 33 | pub(in uniform) cur_address: Address, 34 | pub(in uniform) closing: bool, 35 | } 36 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! A connection pool implementation for tokio 2 | //! 3 | //! [Documentation](https://docs.rs/tk-pool) | 4 | //! [Github](https://github.com/tailhook/tk-pool) | 5 | //! [Crate](https://crates.io/crates/tk-pool) | 6 | //! [Examples](https://github.com/tailhook/tk-pool/tree/master/examples) 7 | //! 8 | //! A connection pool implementation for tokio. Main features: 9 | //! 10 | //! 1. Works for any request-reply protocol (actually for any `Sink`) 11 | //! 2. Provides both queue and pushback if needed 12 | //! 3. Allows pipelining (multiple in-flight request when multiplexing) 13 | //! 4. Auto-reconnects on broken connection 14 | //! 5. Adapts when DNS name change 15 | //! 16 | //! Multiple load-balancing strategies are in to do list. 17 | //! 18 | //! # Example 19 | //! 20 | //! ```rust,ignore 21 | //! 22 | //! let mut pool = 23 | //! pool_for(|addr| connect(addr)) 24 | //! .connect_to(ns.subscribe_many(address, default_port)) 25 | //! .lazy_uniform_connections(2) 26 | //! .with_queue_size(10) 27 | //! .spawn_on(&core.handle()); 28 | //! 29 | //! ``` 30 | //! 31 | #[macro_use] extern crate log; 32 | extern crate abstract_ns; 33 | extern crate futures; 34 | extern crate rand; 35 | extern crate tokio_core; 36 | extern crate void; 37 | 38 | mod connect; 39 | mod basic; 40 | pub mod queue; 41 | pub mod error_log; 42 | pub mod metrics; 43 | pub mod uniform; 44 | pub mod config; 45 | 46 | pub use basic::pool_for; 47 | pub use connect::Connect; 48 | -------------------------------------------------------------------------------- /src/uniform/connect.rs: -------------------------------------------------------------------------------- 1 | use futures::{Future, Async, Sink}; 2 | 3 | use uniform::{FutureOk, FutureErr}; 4 | use uniform::chan::Helper; 5 | 6 | 7 | pub(in uniform) struct ConnectFuture 8 | where F: Future, 9 | F::Item: Sink, 10 | { 11 | task: Option::SinkItem>>, 12 | future: F, 13 | } 14 | 15 | impl ConnectFuture 16 | where F: Future, 17 | F::Item: Sink, 18 | { 19 | pub fn new(task: Helper<::SinkItem>, future: F) 20 | -> ConnectFuture 21 | { 22 | ConnectFuture { task: Some(task), future } 23 | } 24 | } 25 | 26 | impl Future for ConnectFuture 27 | where F::Item: Sink, 28 | { 29 | type Item = FutureOk; 30 | type Error = FutureErr::SinkError>; 31 | fn poll(&mut self) -> Result, Self::Error> { 32 | let snk = { 33 | let task = self.task.as_ref().expect("poll invariant"); 34 | match task.poll_close() { 35 | Async::Ready(()) => { 36 | return Ok(Async::Ready(FutureOk::Aborted(task.addr()))); 37 | } 38 | Async::NotReady => {} 39 | } 40 | match self.future.poll() { 41 | Ok(Async::Ready(s)) => s, 42 | Ok(Async::NotReady) => return Ok(Async::NotReady), 43 | Err(e) => return Err(FutureErr::CantConnect(task.addr(), e)), 44 | } 45 | }; 46 | let task = self.task.take().expect("poll invariant"); 47 | Ok(Async::Ready(FutureOk::Connected(task, snk))) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/metrics.rs: -------------------------------------------------------------------------------- 1 | //! Metrics trait and no-op implementation 2 | 3 | /// An object implementing trait may collect metrics of a connection pool 4 | pub trait Collect: Clone + Send + Sync { 5 | /// We started establishing connection 6 | /// 7 | /// This pairs either with ``connection`` on success 8 | /// or ``connection_abort`` and ``connection_error`` on error 9 | fn connection_attempt(&self) {} 10 | /// Error establishing connection 11 | fn connection_error(&self) {} 12 | 13 | /// Aborted connection attempt (name changed, and doesn't include address) 14 | fn connection_abort(&self) {} 15 | /// Connection established successfully 16 | fn connection(&self) {} 17 | /// Connection closed (usully means name changed) 18 | fn disconnect(&self) {} 19 | 20 | /// Host address added to a blacklist (i.e. connection error) 21 | fn blacklist_add(&self) {} 22 | /// Host address removed from a blacklist 23 | /// 24 | /// Note this callback is only called when we're searching for a new 25 | /// connection and all others are busy. I.e. unlisting a host from a 26 | /// blacklist may be delayed arbitrarily when not under backpressure. 27 | /// This may be fixed in future. 28 | fn blacklist_remove(&self) {} 29 | 30 | /// Request queued in the internal queue 31 | fn request_queued(&self) {} 32 | /// Request unqueued from the internal queue and forwarded to a sink 33 | /// 34 | /// Note: this might not mean that request is already sent as we can't 35 | /// control the underlying sinks used. 36 | fn request_forwarded(&self) {} 37 | 38 | /// Connection pool is closed 39 | fn pool_closed(&self) {} 40 | } 41 | 42 | 43 | /// A object implementing Collect which is not interested in actual metrics 44 | #[derive(Debug, Clone)] 45 | pub struct Noop; 46 | 47 | impl Collect for Noop {} 48 | -------------------------------------------------------------------------------- /examples/http.rs: -------------------------------------------------------------------------------- 1 | extern crate tk_pool; 2 | extern crate tk_http; 3 | extern crate futures; 4 | extern crate abstract_ns; 5 | extern crate futures_cpupool; 6 | extern crate tokio_core; 7 | extern crate env_logger; 8 | extern crate ns_std_threaded; 9 | extern crate ns_router; 10 | extern crate log; 11 | 12 | use std::env; 13 | use std::time::Duration; 14 | 15 | use abstract_ns::HostResolve; 16 | use futures::{Future, Sink}; 17 | use futures::future::join_all; 18 | use tk_pool::{pool_for}; 19 | use tk_http::client::{Proto, Config as HConfig, Client, Error}; 20 | use ns_router::SubscribeExt; 21 | 22 | fn main() { 23 | if let Err(_) = env::var("RUST_LOG") { 24 | env::set_var("RUST_LOG", "warn"); 25 | } 26 | env_logger::init(); 27 | 28 | let mut lp = tokio_core::reactor::Core::new().unwrap(); 29 | let h1 = lp.handle(); 30 | let h2 = lp.handle(); 31 | 32 | let ns = ns_router::Router::from_config(&ns_router::Config::new() 33 | .set_fallthrough(ns_std_threaded::ThreadedResolver::new() 34 | .null_service_resolver() 35 | .interval_subscriber(Duration::new(1, 0), &h1)) 36 | .done(), 37 | &lp.handle()); 38 | 39 | let connection_config = HConfig::new() 40 | .inflight_request_limit(1) 41 | .done(); 42 | let mut pool = 43 | pool_for(move |addr| Proto::connect_tcp(addr, &connection_config, &h2)) 44 | .connect_to(ns.subscribe_many(&["httpbin.org"], 80)) 45 | .lazy_uniform_connections(2) 46 | .with_queue_size(16) 47 | .spawn_on(&lp.handle()) 48 | // This is needed for Client trait, (i.e. so that `.fetch_url()` works) 49 | // May be fixed in tk-http in future 50 | .sink_map_err(|_| Error::custom("Can't send request")); 51 | 52 | // Alternative config (not implemented) 53 | // let mut pool = 54 | // pool_for(|addr| Proto::connect_tcp(addr, &connection_config, &h2)) 55 | // .with_config_stream(ns, once_and_wait(Config::new() 56 | // .set_name(&["httpbin.org:80"]) 57 | // .lazy_uniform_connections(2) 58 | // .with_queue_size(10))) 59 | // .spawn_on(&lp.handle()); 60 | 61 | println!("We will send 16 requests over 1 connection per ip. \ 62 | Each requests hangs for 5 seconds at the server side \ 63 | (a feature of httpbin.org). Since httpbin nowadays has \ 64 | many IPs, expect script to finish in 5 or 10 seconds \ 65 | with first response coming in 5 seconds."); 66 | 67 | lp.run(futures::lazy(|| { 68 | join_all((0..16).map(move |_| { 69 | pool 70 | .fetch_url("http://httpbin.org/delay/5") 71 | .map(|r| { 72 | println!("Received {} bytes", r.body().len()) 73 | }) 74 | })) 75 | })).unwrap(); 76 | } 77 | -------------------------------------------------------------------------------- /src/uniform/failures.rs: -------------------------------------------------------------------------------- 1 | use std::collections::{HashSet, BinaryHeap}; 2 | use std::cmp::Ordering; 3 | use std::net::SocketAddr; 4 | use std::time::Instant; 5 | 6 | use futures::{Future, Async}; 7 | use tokio_core::reactor::{Handle, Timeout}; 8 | 9 | 10 | pub(crate) struct Blacklist { 11 | addrs: HashSet, 12 | heap: BinaryHeap, 13 | timeout: Option, 14 | handle: Handle, 15 | } 16 | 17 | #[derive(Eq)] 18 | pub struct Pair(Instant, SocketAddr); 19 | 20 | impl PartialOrd for Pair { 21 | fn partial_cmp(&self, other: &Pair) -> Option { 22 | Some(self.cmp(other)) 23 | } 24 | } 25 | 26 | impl Ord for Pair { 27 | fn cmp(&self, other: &Pair) -> Ordering { 28 | self.0.cmp(&other.0) 29 | } 30 | } 31 | 32 | impl PartialEq for Pair { 33 | fn eq(&self, other: &Pair) -> bool { 34 | self.0.eq(&other.0) 35 | } 36 | } 37 | 38 | impl Blacklist { 39 | pub fn new(h: &Handle) -> Blacklist { 40 | Blacklist { 41 | addrs: HashSet::new(), 42 | heap: BinaryHeap::new(), 43 | timeout: None, 44 | handle: h.clone(), 45 | } 46 | } 47 | pub fn blacklist(&mut self, addr: SocketAddr, time: Instant) { 48 | if self.addrs.contains(&addr) { 49 | // can't add again because is in heap 50 | return; 51 | } 52 | self.heap.push(Pair(time, addr)); 53 | self.addrs.insert(addr); 54 | } 55 | pub fn is_failing(&self, addr: SocketAddr) -> bool { 56 | return self.addrs.contains(&addr); 57 | } 58 | pub fn poll(&mut self) -> Async { 59 | loop { 60 | match self.heap.peek() { 61 | Some(&Pair(time, a)) if time <= Instant::now() => { 62 | self.timeout = None; 63 | self.addrs.remove(&a); 64 | self.heap.pop(); 65 | return Async::Ready(a); 66 | } 67 | Some(&Pair(time, _)) => { 68 | let timer_result = self.timeout.as_mut() 69 | .map(|x| x.poll().expect("timeout never fails")); 70 | match timer_result { 71 | Some(Async::NotReady) => return Async::NotReady, 72 | _ => { 73 | self.timeout = None; 74 | } 75 | } 76 | let mut timer = Timeout::new_at(time, &self.handle) 77 | .expect("timeout never fails"); 78 | match timer.poll().expect("timeout never fails") { 79 | Async::Ready(()) => continue, 80 | Async::NotReady => { 81 | self.timeout = Some(timer); 82 | return Async::NotReady; 83 | } 84 | } 85 | } 86 | None => { 87 | self.timeout = None; 88 | return Async::NotReady; 89 | } 90 | } 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/error_log.rs: -------------------------------------------------------------------------------- 1 | //! ErrorLog trait and default implementations 2 | //! 3 | use std::fmt; 4 | use std::net::SocketAddr; 5 | use std::marker::PhantomData; 6 | 7 | use config::{NewErrorLog}; 8 | 9 | /// A reason connection pool being shut down 10 | /// 11 | /// This value is passed to ``ErrorLog::pool_shutting_down`` method. 12 | #[derive(Debug)] 13 | pub enum ShutdownReason { 14 | /// Request stream is shutting down 15 | /// 16 | /// This usually means that all clones of ``queue::Pool`` object are 17 | /// destroyed 18 | RequestStreamClosed, 19 | /// Address stream is closed 20 | /// 21 | /// Shutting down address stream is commonly used to force shut down 22 | /// connection pool, even if there are users. Users will get an error 23 | /// on the next `start_send`. 24 | AddressStreamClosed, 25 | #[doc(hidden)] 26 | __Nonexhaustive, 27 | } 28 | 29 | 30 | /// The thrait that has appropriate hooks for logging different events 31 | /// 32 | /// There is a default ``WarnLogger``, but the idea is that you may give 33 | /// connection pool a name, change logging levels, and do other interesting 34 | /// stuff in your own error log handler. 35 | pub trait ErrorLog { 36 | /// Connection error type that is returned by connect/hanshake function 37 | type ConnectionError; 38 | /// Error when sending request returned by Sink 39 | type SinkError; 40 | /// Error when establishing a new connection 41 | fn connection_error(&self, _addr: SocketAddr, _e: Self::ConnectionError) {} 42 | /// Error when sending a request 43 | /// 44 | /// This also means connection is closed 45 | fn sink_error(&self, _addr: SocketAddr, _e: Self::SinkError) {} 46 | /// Pool is started to shut down for the specified reason 47 | fn pool_shutting_down(&self, _reason: ShutdownReason) {} 48 | /// Pool is fully closed at this moment 49 | fn pool_closed(&self) {} 50 | } 51 | 52 | 53 | /// A constructor for a default error logger 54 | pub struct WarnLogger; 55 | 56 | /// An instance of default error logger 57 | pub struct WarnLoggerInstance(PhantomData<* const (C, S)>); 58 | 59 | impl Clone for WarnLoggerInstance { 60 | fn clone(&self) -> Self { 61 | WarnLoggerInstance(PhantomData) 62 | } 63 | } 64 | 65 | impl NewErrorLog for WarnLogger { 66 | type ErrorLog = WarnLoggerInstance; 67 | fn construct(self) -> Self::ErrorLog { 68 | WarnLoggerInstance(PhantomData) 69 | } 70 | } 71 | 72 | impl ErrorLog for WarnLoggerInstance 73 | where C: fmt::Display, 74 | S: fmt::Display, 75 | { 76 | type ConnectionError = C; 77 | type SinkError = S; 78 | fn connection_error(&self, addr: SocketAddr, e: Self::ConnectionError) { 79 | warn!("Connecting to {} failed: {}", addr, e); 80 | } 81 | fn sink_error(&self, addr: SocketAddr, e: Self::SinkError) { 82 | warn!("Connection to {} errored: {}", addr, e); 83 | } 84 | /// Starting to shut down pool 85 | fn pool_shutting_down(&self, reason: ShutdownReason) { 86 | warn!("Shutting down connection pool: {}", reason); 87 | } 88 | /// This is triggered when pool done all the work and shut down entirely 89 | fn pool_closed(&self) { 90 | } 91 | } 92 | 93 | impl fmt::Display for ShutdownReason { 94 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 95 | use self::ShutdownReason::*; 96 | f.write_str(match *self { 97 | RequestStreamClosed => "request stream closed", 98 | AddressStreamClosed => "address stream closed", 99 | __Nonexhaustive => unreachable!(), 100 | }) 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/uniform/sink.rs: -------------------------------------------------------------------------------- 1 | use std::marker::PhantomData; 2 | 3 | use futures::{Future, Async, Sink, AsyncSink}; 4 | 5 | use uniform::{FutureOk, FutureErr}; 6 | use uniform::chan::{Action, Helper}; 7 | 8 | 9 | pub(in uniform) struct SinkFuture 10 | where S: Sink, 11 | { 12 | sink: S, 13 | task: Helper, 14 | phantom: PhantomData<*const E>, 15 | } 16 | 17 | impl SinkFuture { 18 | pub fn new(sink: S, task: Helper) 19 | -> SinkFuture 20 | { 21 | SinkFuture { sink, task, phantom: PhantomData } 22 | } 23 | } 24 | 25 | impl Future for SinkFuture { 26 | type Item = FutureOk; 27 | type Error = FutureErr; 28 | fn poll(&mut self) -> Result, Self::Error> { 29 | match self.task.take() { 30 | Action::StartSend(item) => match self.sink.start_send(item) { 31 | Ok(AsyncSink::Ready) => { 32 | // We need to flush data immediately because there is 33 | // no way to schedule a wakeup on poll_complete of parent 34 | // schedule 35 | // 36 | // TODO(tailhook) we might want to fix it by wrapping the 37 | // future into a refcell and calling 38 | // start_send manually instead of through 39 | // futures unordered. 40 | match self.sink.poll_complete() { 41 | Ok(_) => { 42 | // By contract there is no difference in Ready and 43 | // NotReady I.e. both of them may mean that another 44 | // element can be pushed now. They only distinquish 45 | // whether there is something left in the buffer. 46 | self.task.requeue(); 47 | Ok(Async::NotReady) 48 | } 49 | Err(e) => { 50 | self.task.closed(); 51 | Err(FutureErr::Disconnected(self.task.addr(), e)) 52 | } 53 | } 54 | } 55 | Ok(AsyncSink::NotReady(item)) => { 56 | self.task.backpressure(item); 57 | Ok(Async::NotReady) 58 | } 59 | Err(e) => { 60 | self.task.closed(); 61 | Err(FutureErr::Disconnected(self.task.addr(), e)) 62 | } 63 | } 64 | Action::Poll => match self.sink.poll_complete() { 65 | Ok(_) => { 66 | // By contract there is no difference in Ready and NotReady 67 | // I.e. both of them may mean that another element can 68 | // be pushed now. They only distinquish whether there is 69 | // something left in the buffer. 70 | self.task.requeue(); 71 | Ok(Async::NotReady) 72 | } 73 | Err(e) => { 74 | self.task.closed(); 75 | Err(FutureErr::Disconnected(self.task.addr(), e)) 76 | } 77 | } 78 | Action::Close => match self.sink.close() { 79 | Ok(Async::Ready(())) => { 80 | Ok(Async::Ready(FutureOk::Closed(self.task.addr()))) 81 | } 82 | Ok(Async::NotReady) => Ok(Async::NotReady), 83 | Err(e) => { 84 | self.task.closed(); 85 | Err(FutureErr::Disconnected(self.task.addr(), e)) 86 | } 87 | } 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/uniform/chan.rs: -------------------------------------------------------------------------------- 1 | use std::rc::Rc; 2 | use std::cell::RefCell; 3 | use std::net::SocketAddr; 4 | use std::hash::{Hash, Hasher}; 5 | 6 | use futures::Async; 7 | use futures::task::{self, Task}; 8 | use uniform::Connections; 9 | 10 | 11 | pub enum Action { 12 | StartSend(I), 13 | Poll, 14 | Close, 15 | } 16 | 17 | pub(in uniform) struct Inner { 18 | addr: SocketAddr, 19 | request: Option, 20 | connections: Rc>>, 21 | task: Option, 22 | pub(in uniform) queued: bool, 23 | // TODO(tailhook) verify that close flag is okay 24 | pub(in uniform) closed: bool, 25 | } 26 | 27 | pub struct Controller { 28 | pub(in uniform) inner: Rc>>, 29 | } 30 | 31 | pub(in uniform) struct Helper { 32 | pub(in uniform) inner: Rc>>, 33 | } 34 | 35 | impl PartialEq for Controller { 36 | fn eq(&self, other: &Controller) -> bool { 37 | &*self.inner.borrow() as *const _ == &*other.inner.borrow() as *const _ 38 | } 39 | } 40 | 41 | impl Eq for Controller {} 42 | 43 | impl Hash for Controller { 44 | fn hash(&self, hasher: &mut H) { 45 | hasher.write_usize((&*self.inner.borrow() as *const _) as usize); 46 | } 47 | } 48 | 49 | impl Helper { 50 | pub fn new(addr: SocketAddr, connections: Rc>>) 51 | -> Helper 52 | { 53 | let inner = Rc::new(RefCell::new(Inner { 54 | addr, connections, 55 | task: None, 56 | queued: false, 57 | closed: false, 58 | request: None, 59 | })); 60 | return Helper { inner } 61 | } 62 | pub fn controller(&self) -> Controller { 63 | Controller { 64 | inner: self.inner.clone(), 65 | } 66 | } 67 | pub fn poll_close(&self) -> Async<()> { 68 | let mut cell = self.inner.borrow_mut(); 69 | cell.task = Some(task::current()); 70 | if cell.closed { 71 | Async::Ready(()) 72 | } else { 73 | Async::NotReady 74 | } 75 | } 76 | pub fn take(&self) -> Action { 77 | let mut cell = self.inner.borrow_mut(); 78 | if cell.closed { 79 | return Action::Close; 80 | } 81 | match cell.request.take() { 82 | Some(item) => Action::StartSend(item), 83 | None => Action::Poll, 84 | } 85 | } 86 | pub fn backpressure(&self, value: I) { 87 | let mut cell = self.inner.borrow_mut(); 88 | cell.request = Some(value); 89 | assert!(!cell.queued); 90 | } 91 | pub fn requeue(&self) { 92 | let connections = { 93 | let mut cell = self.inner.borrow_mut(); 94 | cell.task = Some(task::current()); 95 | if cell.queued { 96 | return; 97 | } 98 | cell.connections.clone() 99 | }; 100 | connections.borrow_mut().add(self.controller()); 101 | } 102 | pub fn closed(&self) { 103 | self.inner.borrow_mut().closed = true; 104 | } 105 | pub fn addr(&self) -> SocketAddr { 106 | self.inner.borrow().addr 107 | } 108 | } 109 | 110 | impl Controller { 111 | pub fn close(&self) { 112 | let mut inner = self.inner.borrow_mut(); 113 | inner.closed = true; 114 | inner.task.as_ref().map(|x| x.notify()); 115 | } 116 | pub fn is_closed(&self) -> bool { 117 | self.inner.borrow().closed 118 | } 119 | pub fn request_back(&self) -> Option { 120 | let mut cell = self.inner.borrow_mut(); 121 | let res = cell.request.take(); 122 | res 123 | } 124 | pub fn request(&self, item: I) { 125 | let mut inner = self.inner.borrow_mut(); 126 | assert!(inner.request.is_none()); 127 | inner.request = Some(item); 128 | inner.task.as_ref().map(|x| x.notify()); 129 | } 130 | pub fn addr(&self) -> SocketAddr { 131 | self.inner.borrow().addr 132 | } 133 | } 134 | 135 | impl Drop for Helper { 136 | fn drop(&mut self) { 137 | let con = self.inner.borrow().connections.clone(); 138 | con.borrow_mut().all.remove(&self.controller()); 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/uniform/aligner.rs: -------------------------------------------------------------------------------- 1 | use std::u32; 2 | use std::collections::{HashSet, HashMap, BTreeMap}; 3 | use std::collections::btree_map::Entry::{Occupied}; 4 | use std::net::SocketAddr; 5 | 6 | use rand::{thread_rng, seq::sample_iter}; 7 | 8 | 9 | pub(crate) struct Aligner { 10 | items: BTreeMap>, 11 | addrs: HashMap, 12 | } 13 | 14 | 15 | impl Aligner { 16 | pub fn new() -> Aligner { 17 | Aligner { 18 | items: BTreeMap::new(), 19 | addrs: HashMap::new(), 20 | } 21 | } 22 | pub fn update(&mut self, new: N, old: O) 23 | where N: IntoIterator, 24 | O: IntoIterator, 25 | { 26 | { 27 | let zero = self.items.entry(0).or_insert_with(HashSet::new); 28 | for addr in new { 29 | let n = *self.addrs.entry(addr).or_insert(0); 30 | if n == 0 { 31 | zero.insert(addr); 32 | } 33 | } 34 | } 35 | for addr in old { 36 | if let Some(n) = self.addrs.remove(&addr) { 37 | match self.items.entry(n) { 38 | Occupied(mut o) => { 39 | o.get_mut().remove(&addr); 40 | if o.get().len() == 0 { 41 | o.remove_entry(); 42 | } 43 | } 44 | _ => {} 45 | } 46 | } 47 | } 48 | // in case we inserted it in the first line and did not delete yet 49 | match self.items.entry(0) { 50 | Occupied(o) => { 51 | if o.get().len() == 0 { 52 | o.remove_entry(); 53 | } 54 | } 55 | _ => {} 56 | } 57 | } 58 | pub fn get(&mut self, limit: u32, blist: F) -> Option 59 | where F: Fn(SocketAddr) -> bool 60 | { 61 | assert!(limit < u32::MAX); 62 | let mut result = None; 63 | for (&n, addrs) in self.items.iter_mut() { 64 | if n >= limit { 65 | return None; 66 | } 67 | let mut candidate = sample_iter(&mut thread_rng(), 68 | addrs.iter().filter(|&&x| !blist(x)).map(|&x| x), 69 | 1).unwrap_or_else(|v| v); 70 | match candidate.pop() { 71 | Some(a) => { 72 | addrs.remove(&a); 73 | result = Some((n, a)); 74 | break; 75 | } 76 | None => continue, 77 | } 78 | } 79 | if let Some((num, addr)) = result { 80 | self.items.entry(num+1) 81 | .or_insert_with(HashSet::new) 82 | .insert(addr); 83 | let old = self.addrs.insert(addr, num+1); 84 | debug_assert_eq!(old, Some(num)); 85 | return Some(addr); 86 | } 87 | return None; 88 | } 89 | pub fn put(&mut self, addr: SocketAddr) { 90 | if let Some(num) = self.addrs.get_mut(&addr) { 91 | assert!(*num > 0); 92 | match self.items.entry(*num) { 93 | Occupied(mut o) => { 94 | o.get_mut().remove(&addr); 95 | if o.get().len() == 0 { 96 | o.remove_entry(); 97 | } 98 | } 99 | _ => {} 100 | } 101 | *num -= 1; 102 | self.items.entry(*num).or_insert_with(HashSet::new).insert(addr); 103 | } 104 | } 105 | } 106 | 107 | #[cfg(test)] 108 | mod test { 109 | use std::net::{SocketAddr}; 110 | use std::collections::HashMap; 111 | use super::Aligner; 112 | 113 | fn addr(n: u8) -> SocketAddr { 114 | SocketAddr::new(format!("127.0.0.{}", n).parse().unwrap(), 80) 115 | } 116 | 117 | #[test] 118 | fn normal() { 119 | let mut a = Aligner::new(); 120 | a.update(vec![addr(1), addr(2), addr(3)], vec![]); 121 | 122 | let mut counter = HashMap::new(); 123 | for _ in 0..30 { 124 | *counter.entry(a.get(100, |_| false).unwrap()).or_insert(0) += 1; 125 | } 126 | assert_eq!(counter, vec![ 127 | (addr(1), 10), 128 | (addr(2), 10), 129 | (addr(3), 10), 130 | ].into_iter().collect::>()); 131 | } 132 | 133 | #[test] 134 | fn blacklisting() { 135 | let mut a = Aligner::new(); 136 | a.update(vec![addr(1), addr(2), addr(3)], vec![]); 137 | 138 | let mut counter = HashMap::new(); 139 | for _ in 0..6 { 140 | *counter.entry(a.get(100, |_| false).unwrap()).or_insert(0) += 1; 141 | } 142 | assert_eq!(counter, vec![ 143 | (addr(1), 2), 144 | (addr(2), 2), 145 | (addr(3), 2), 146 | ].into_iter().collect::>()); 147 | 148 | let blist1 = &|x| x == addr(1); 149 | for _ in 0..6 { 150 | *counter.entry(a.get(100, blist1).unwrap()).or_insert(0) += 1; 151 | } 152 | assert_eq!(counter, vec![ 153 | (addr(1), 2), 154 | (addr(2), 5), 155 | (addr(3), 5), 156 | ].into_iter().collect::>()); 157 | 158 | for _ in 0..9 { 159 | *counter.entry(a.get(100, |_| false).unwrap()).or_insert(0) += 1; 160 | } 161 | assert_eq!(counter, vec![ 162 | (addr(1), 7), 163 | (addr(2), 7), 164 | (addr(3), 7), 165 | ].into_iter().collect::>()); 166 | } 167 | 168 | #[test] 169 | fn update() { 170 | let mut a = Aligner::new(); 171 | a.update(vec![addr(1), addr(2), addr(3)], vec![]); 172 | 173 | let mut counter = HashMap::new(); 174 | for _ in 0..6 { 175 | *counter.entry(a.get(100, |_| false).unwrap()).or_insert(0) += 1; 176 | } 177 | assert_eq!(counter, vec![ 178 | (addr(1), 2), 179 | (addr(2), 2), 180 | (addr(3), 2), 181 | ].into_iter().collect::>()); 182 | 183 | a.update(vec![addr(4)], vec![addr(2)]); 184 | for _ in 0..8 { 185 | *counter.entry(a.get(100, |_| false).unwrap()).or_insert(0) += 1; 186 | } 187 | assert_eq!(counter, vec![ 188 | (addr(1), 4), 189 | (addr(2), 2), // still here because we count attempts not conns 190 | (addr(3), 4), 191 | (addr(4), 4), 192 | ].into_iter().collect::>()); 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /src/config.rs: -------------------------------------------------------------------------------- 1 | //! A number of traits to configure connection pool and their implementatons 2 | //! 3 | //! Usually you should start with ``pool_for`` and use methods to configure 4 | //! connection pool instead of poking at these types. 5 | //! 6 | use std::time::Duration; 7 | 8 | use abstract_ns::Address; 9 | use futures::{Future, Stream, Sink}; 10 | use tokio_core::reactor::Handle; 11 | use void::Void; 12 | 13 | use error_log::{ErrorLog, WarnLogger}; 14 | use connect::Connect; 15 | use metrics::{self, Collect}; 16 | use uniform::LazyUniform; 17 | 18 | /// A constructor for metrics collector object used for connection pool 19 | pub trait NewMetrics { 20 | type Collect: Collect; 21 | fn construct(self) -> Self::Collect; 22 | } 23 | 24 | /// A constructor for queue 25 | /// 26 | /// This trait is currently *sealed*, we will unseal it once it stabilized 27 | pub trait NewQueue: private::NewQueue { 28 | /// Connection pool instance type 29 | type Pool; 30 | } 31 | 32 | impl> NewQueue for T { 33 | type Pool = T::Pool; 34 | } 35 | 36 | /// A constructor for multiplexer 37 | /// 38 | /// This trait is currently *sealed*, we will unseal it once it stabilized 39 | pub trait NewMux: private::NewMux 40 | where A: Stream, 41 | C: Connect + 'static, 42 | <::Future as Future>::Item: Sink, 43 | E: ErrorLog< 44 | ConnectionError=::Error, 45 | SinkError=<::Item as Sink>::SinkError, 46 | >, 47 | E: 'static, 48 | M: Collect + 'static, 49 | {} 50 | 51 | pub(crate) mod private { 52 | use futures::{Stream, Future, Sink}; 53 | use void::Void; 54 | use connect::Connect; 55 | use metrics::Collect; 56 | use error_log::ErrorLog; 57 | use abstract_ns::Address; 58 | use tokio_core::reactor::Handle; 59 | 60 | pub struct Done; 61 | 62 | pub trait NewMux 63 | where A: Stream, 64 | C: Connect + 'static, 65 | <::Future as Future>::Item: Sink, 66 | E: ErrorLog< 67 | ConnectionError=::Error, 68 | SinkError=<::Item as Sink>::SinkError, 69 | >, 70 | E: 'static, 71 | M: Collect + 'static, 72 | { 73 | type Sink: Sink< 74 | SinkItem=<::Item as Sink>::SinkItem, 75 | SinkError=Done, 76 | >; 77 | fn construct(self, 78 | h: &Handle, address: A, connector: C, errors: E, metrics: M) 79 | -> Self::Sink; 80 | } 81 | 82 | pub trait NewQueue { 83 | type Pool; 84 | fn spawn_on(self, pool: S, e: E, metrics: M, handle: &Handle) 85 | -> Self::Pool 86 | where S: Sink + 'static, 87 | E: ErrorLog + 'static, 88 | M: Collect + 'static; 89 | } 90 | 91 | } 92 | 93 | /// A constructor for error log 94 | pub trait NewErrorLog { 95 | type ErrorLog: ErrorLog; 96 | fn construct(self) -> Self::ErrorLog; 97 | } 98 | 99 | /// A configuration builder that holds onto `Connect` object 100 | #[derive(Debug)] 101 | pub struct PartialConfig { 102 | pub(crate) connector: C, 103 | } 104 | 105 | /// A fully configured pool but you might override some defaults 106 | pub struct PoolConfig { 107 | pub(crate) connector: C, 108 | pub(crate) address: A, 109 | pub(crate) mux: X, 110 | pub(crate) queue: Q, 111 | pub(crate) errors: E, 112 | pub(crate) metrics: M, 113 | } 114 | 115 | /// A constructor for a default multiplexer 116 | pub struct DefaultMux; 117 | 118 | /// A constructor for a default queue 119 | pub struct DefaultQueue; 120 | 121 | /// A constructor for a fixed-size dumb queue 122 | pub struct Queue(pub(crate) usize); 123 | 124 | /// A constructor for a default (no-op) metrics collector 125 | pub struct NoopMetrics; 126 | 127 | impl NewMetrics for NoopMetrics { 128 | type Collect = metrics::Noop; 129 | fn construct(self) -> metrics::Noop { 130 | metrics::Noop 131 | } 132 | } 133 | 134 | impl PartialConfig { 135 | /// Create a configuration by adding an address stream 136 | pub fn connect_to(self, address_stream: A) 137 | -> PoolConfig 138 | where A: Stream, 139 | { 140 | PoolConfig { 141 | address: address_stream, 142 | connector: self.connector, 143 | mux: DefaultMux, 144 | errors: WarnLogger, 145 | queue: DefaultQueue, 146 | metrics: NoopMetrics, 147 | } 148 | } 149 | } 150 | 151 | impl PoolConfig { 152 | /// Spawn a connection pool on the main loop specified by handle 153 | pub fn spawn_on(self, h: &Handle) 154 | -> ::Future as Future>::Item as Sink>::SinkItem, 156 | ::Collect, 157 | >>::Pool 158 | where A: Stream, 159 | C: Connect + 'static, 160 | <::Future as Future>::Item: Sink, 161 | M: NewMetrics, 162 | M::Collect: 'static, 163 | X: NewMux, 164 | >::Sink: 'static, 165 | E: NewErrorLog< 166 | <::Future as Future>::Error, 167 | <<::Future as Future>::Item as Sink>::SinkError, 168 | >, 169 | E::ErrorLog: Clone + 'static, 170 | Q: NewQueue< 171 | <<::Future as Future>::Item as Sink>::SinkItem, 172 | ::Collect, 173 | Pool=::Future as Future>::Item as Sink>::SinkItem, 175 | ::Collect, 176 | >>::Pool 177 | >, 178 | 179 | { 180 | let m = self.metrics.construct(); 181 | let e = self.errors.construct(); 182 | let p = self.mux.construct(h, 183 | self.address, self.connector, e.clone(), m.clone()); 184 | self.queue.spawn_on(p, e, m, h) 185 | } 186 | 187 | /// Configure a uniform connection pool with specified number of 188 | /// per-host connections crated lazily (i.e. when there are requests) 189 | pub fn lazy_uniform_connections(self, num: u32) 190 | -> PoolConfig 191 | { 192 | PoolConfig { 193 | mux: LazyUniform { 194 | conn_limit: num, 195 | reconnect_timeout: Duration::from_millis(100), 196 | }, 197 | address: self.address, 198 | connector: self.connector, 199 | errors: self.errors, 200 | queue: self.queue, 201 | metrics: self.metrics, 202 | } 203 | } 204 | 205 | /// Add a queue of size num used when no connection can accept a message 206 | pub fn with_queue_size(self, num: usize) 207 | -> PoolConfig 208 | { 209 | PoolConfig { 210 | queue: Queue(num), 211 | address: self.address, 212 | connector: self.connector, 213 | mux: self.mux, 214 | errors: self.errors, 215 | metrics: self.metrics, 216 | } 217 | } 218 | 219 | /// Override metrics reporter 220 | pub fn metrics(self, metrics: NM) 221 | -> PoolConfig 222 | where NM: NewMetrics, 223 | { 224 | PoolConfig { 225 | queue: self.queue, 226 | address: self.address, 227 | connector: self.connector, 228 | mux: self.mux, 229 | errors: self.errors, 230 | metrics: metrics, 231 | } 232 | } 233 | 234 | /// Override error reporter 235 | pub fn errors(self, errors: NE) 236 | -> PoolConfig 237 | where NE: ErrorLog, 238 | { 239 | PoolConfig { 240 | queue: self.queue, 241 | address: self.address, 242 | connector: self.connector, 243 | mux: self.mux, 244 | errors: errors, 245 | metrics: self.metrics, 246 | } 247 | } 248 | } 249 | 250 | 251 | -------------------------------------------------------------------------------- /src/queue.rs: -------------------------------------------------------------------------------- 1 | //! A queue (buffer) of requests sent to connection pool 2 | use std::fmt; 3 | use futures::{AsyncSink, Stream, StartSend, Poll, Async}; 4 | use futures::sync::mpsc::{self, channel, Sender}; 5 | use futures::sink::Sink; 6 | use futures::stream::Fuse; 7 | use futures::future::Future; 8 | use tokio_core::reactor::Handle; 9 | 10 | use metrics::Collect; 11 | use error_log::{ErrorLog, ShutdownReason}; 12 | use config::{Queue, DefaultQueue, private}; 13 | 14 | 15 | /// Pool is an object you use to access a connection pool 16 | /// 17 | /// Usually the whole logic of connection pool is spawned in another future. 18 | /// This object encapsulates a channel that is used to communicate with pool. 19 | /// This object also contains a clone of metrics collection object as it's 20 | /// very important to collect metrics at this side of a channel. 21 | #[derive(Debug)] 22 | pub struct Pool { 23 | channel: Sender, 24 | metrics: M, 25 | } 26 | 27 | /// Error returned by the sink, when underlying pool is closed 28 | /// 29 | /// The error contains underlying item that was sent using `start_send` 30 | pub struct QueueError(V); 31 | 32 | 33 | /// This is similar to `Forward` from `futures` but has metrics and errors 34 | #[derive(Debug)] 35 | #[must_use = "futures do nothing unless polled"] 36 | struct ForwardFuture 37 | where S: Sink 38 | { 39 | receiver: Fuse>, 40 | buffer: Option, 41 | metrics: M, 42 | errors: E, 43 | sink: S, 44 | } 45 | 46 | impl private::NewQueue for DefaultQueue { 47 | type Pool = Pool; 48 | fn spawn_on(self, pool: S, err: E, metrics: M, handle: &Handle) 49 | -> Self::Pool 50 | where S: Sink + 'static, 51 | E: ErrorLog + 'static, 52 | M: Collect + 'static, 53 | { 54 | Queue(100).spawn_on(pool, err, metrics, handle) 55 | } 56 | } 57 | 58 | impl private::NewQueue for Queue { 59 | type Pool = Pool; 60 | fn spawn_on(self, pool: S, e: E, metrics: M, handle: &Handle) 61 | -> Self::Pool 62 | where S: Sink + 'static, 63 | E: ErrorLog + 'static, 64 | M: Collect + 'static, 65 | { 66 | // one item is buffered ForwardFuture 67 | let buf_size = self.0.saturating_sub(1); 68 | let (tx, rx) = channel(buf_size); 69 | handle.spawn(ForwardFuture { 70 | receiver: rx.fuse(), 71 | metrics: metrics.clone(), 72 | errors: e, 73 | sink: pool, 74 | buffer: None, 75 | }); 76 | return Pool { 77 | channel: tx, 78 | metrics, 79 | }; 80 | } 81 | } 82 | 83 | 84 | trait AssertTraits: Clone + Send + Sync {} 85 | impl AssertTraits for Pool {} 86 | 87 | impl Clone for Pool { 88 | fn clone(&self) -> Self { 89 | Pool { 90 | channel: self.channel.clone(), 91 | metrics: self.metrics.clone(), 92 | } 93 | } 94 | } 95 | 96 | impl ForwardFuture 97 | where S: Sink, 98 | M: Collect, 99 | E: ErrorLog, 100 | { 101 | fn poll_forever(&mut self) -> Async<()> { 102 | if let Some(item) = self.buffer.take() { 103 | match self.sink.start_send(item) { 104 | Ok(AsyncSink::Ready) => { 105 | self.metrics.request_forwarded(); 106 | } 107 | Ok(AsyncSink::NotReady(item)) => { 108 | self.buffer = Some(item); 109 | return Async::NotReady; 110 | } 111 | Err(private::Done) => return Async::Ready(()), 112 | } 113 | } 114 | 115 | let was_done = self.receiver.is_done(); 116 | loop { 117 | match self.receiver.poll() { 118 | Ok(Async::Ready(Some(item))) => { 119 | match self.sink.start_send(item) { 120 | Ok(AsyncSink::Ready) => { 121 | self.metrics.request_forwarded(); 122 | continue; 123 | } 124 | Ok(AsyncSink::NotReady(item)) => { 125 | self.buffer = Some(item); 126 | return Async::NotReady; 127 | } 128 | Err(private::Done) => return Async::Ready(()), 129 | } 130 | } 131 | Ok(Async::Ready(None)) => { 132 | if !was_done { 133 | self.errors.pool_shutting_down( 134 | ShutdownReason::RequestStreamClosed); 135 | } 136 | match self.sink.close() { 137 | Ok(Async::NotReady) => { 138 | return Async::NotReady; 139 | } 140 | Ok(Async::Ready(())) | Err(private::Done) => { 141 | return Async::Ready(()); 142 | } 143 | } 144 | } 145 | Ok(Async::NotReady) => match self.sink.poll_complete() { 146 | Ok(_) => { 147 | return Async::NotReady; 148 | } 149 | Err(private::Done) => { 150 | return Async::Ready(()); 151 | } 152 | } 153 | // No errors in channel receiver 154 | Err(()) => unreachable!(), 155 | } 156 | } 157 | } 158 | } 159 | 160 | impl Future for ForwardFuture 161 | where S: Sink, 162 | M: Collect, 163 | E: ErrorLog, 164 | { 165 | type Item = (); 166 | type Error = (); // Really Void 167 | fn poll(&mut self) -> Result, ()> { 168 | match self.poll_forever() { 169 | Async::NotReady => Ok(Async::NotReady), 170 | Async::Ready(()) => { 171 | self.errors.pool_closed(); 172 | self.metrics.pool_closed(); 173 | Ok(Async::Ready(())) 174 | } 175 | } 176 | } 177 | } 178 | 179 | 180 | impl Sink for Pool 181 | where M: Collect, 182 | { 183 | type SinkItem=V; 184 | type SinkError=QueueError; 185 | 186 | fn start_send(&mut self, item: Self::SinkItem) 187 | -> StartSend 188 | { 189 | match self.channel.start_send(item) { 190 | Ok(AsyncSink::Ready) => { 191 | self.metrics.request_queued(); 192 | Ok(AsyncSink::Ready) 193 | } 194 | Ok(AsyncSink::NotReady(item)) => Ok(AsyncSink::NotReady(item)), 195 | Err(e) => Err(QueueError(e.into_inner())), 196 | } 197 | } 198 | fn poll_complete(&mut self) -> Poll<(), Self::SinkError> { 199 | // TODO(tailhook) turn closed flag into error 200 | self.channel.poll_complete() 201 | .map_err(|_| { 202 | // In fact poll_complete of the channel does nothing for now 203 | // Even if this is fixed there is no sense to return error for 204 | // it because error contains a value SinkItem and there is no way 205 | // to construct a value from nothing 206 | unreachable!(); 207 | }) 208 | } 209 | fn close(&mut self) -> Poll<(), Self::SinkError> { 210 | self.channel.close() 211 | .map_err(|_| { 212 | // In fact close of the channel does nothing for now 213 | // Even if this is fixed there is no sense to return error for 214 | // it because error contains a value SinkItem and there is no way 215 | // to construct a value from nothing 216 | unreachable!(); 217 | }) 218 | } 219 | } 220 | 221 | impl QueueError { 222 | /// Return ownership of contained message 223 | pub fn into_inner(self) -> T { 224 | self.0 225 | } 226 | } 227 | 228 | impl fmt::Display for QueueError { 229 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 230 | f.write_str("connection pool is closed") 231 | } 232 | } 233 | 234 | impl fmt::Debug for QueueError { 235 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 236 | f.write_str("QueueError(_)") 237 | } 238 | } 239 | 240 | impl ::std::error::Error for QueueError { 241 | fn description(&self) -> &str { 242 | "QueueError" 243 | } 244 | fn cause(&self) -> Option<&::std::error::Error> { 245 | None 246 | } 247 | } 248 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /src/uniform/mod.rs: -------------------------------------------------------------------------------- 1 | //! A uniform connection pool implementation 2 | //! 3 | //! Uniform pool has the following properties: 4 | //! 5 | //! 1. Attempts to connect same number of connections to every host 6 | //! 2. Distributes requests by round-robin until pushback happens 7 | //! 8 | mod aligner; 9 | mod chan; 10 | mod connect; 11 | mod failures; 12 | mod sink; 13 | mod pool; 14 | 15 | use std::cell::RefCell; 16 | use std::collections::{VecDeque, HashSet}; 17 | use std::net::SocketAddr; 18 | use std::rc::Rc; 19 | use std::time::{Duration, Instant}; 20 | 21 | use abstract_ns::Address; 22 | use futures::{Future, Async, Sink, AsyncSink, Stream}; 23 | use futures::stream::FuturesUnordered; 24 | use rand::{thread_rng, Rng}; 25 | use tokio_core::reactor::Handle; 26 | use void::{Void, unreachable}; 27 | 28 | use config::{NewMux, private}; 29 | use error_log::{ErrorLog, ShutdownReason}; 30 | use connect::Connect; 31 | use metrics::Collect; 32 | use uniform::aligner::Aligner; 33 | use uniform::chan::{Controller, Helper}; 34 | use uniform::connect::ConnectFuture; 35 | use uniform::failures::Blacklist; 36 | use uniform::sink::SinkFuture; 37 | use uniform::pool::Lazy; 38 | 39 | 40 | enum FutureOk 41 | where S: Sink 42 | { 43 | Connected(Helper, S), 44 | /// Aborted connect attempt (i.e. when establishing or handshaking) 45 | Aborted(SocketAddr), 46 | /// Closed working connection 47 | Closed(SocketAddr), 48 | } 49 | 50 | enum FutureErr { 51 | CantConnect(SocketAddr, E), 52 | Disconnected(SocketAddr, F), 53 | } 54 | 55 | /// A constructor for a uniform connection pool with lazy connections 56 | pub struct LazyUniform { 57 | pub(crate) conn_limit: u32, 58 | pub(crate) reconnect_timeout: Duration, 59 | } 60 | 61 | struct Connections { 62 | queue: VecDeque>, 63 | all: HashSet>, 64 | } 65 | 66 | impl Connections { 67 | fn new() -> Connections{ 68 | Connections { 69 | queue: VecDeque::new(), 70 | all: HashSet::new(), 71 | } 72 | } 73 | fn add(&mut self, ctr: Controller) { 74 | { 75 | let mut inner = ctr.inner.borrow_mut(); 76 | assert!(!inner.closed); 77 | assert!(!inner.queued); 78 | inner.queued = true; 79 | } 80 | self.queue.push_back(ctr); 81 | } 82 | fn has_ready(&self) -> bool { 83 | self.queue.len() > 0 84 | } 85 | fn next(&mut self) -> Option> { 86 | self.queue.pop_front() 87 | .map(|ctr| { 88 | { 89 | let mut inner = ctr.inner.borrow_mut(); 90 | assert!(inner.queued); 91 | inner.queued = false; 92 | } 93 | ctr 94 | }) 95 | } 96 | } 97 | impl NewMux for LazyUniform 98 | where A: Stream, 99 | C: Connect + 'static, 100 | <::Future as Future>::Item: Sink, 101 | E: ErrorLog< 102 | ConnectionError=::Error, 103 | SinkError=<::Item as Sink>::SinkError, 104 | >, 105 | E: 'static, 106 | M: Collect + 'static, 107 | {} 108 | 109 | impl private::NewMux for LazyUniform 110 | where A: Stream, 111 | C: Connect + 'static, 112 | <::Future as Future>::Item: Sink, 113 | E: ErrorLog< 114 | ConnectionError=::Error, 115 | SinkError=<::Item as Sink>::SinkError, 116 | >, 117 | E: 'static, 118 | M: Collect + 'static, 119 | { 120 | type Sink = Lazy; 121 | fn construct(self, 122 | h: &Handle, address: A, connector: C, errors: E, metrics: M) 123 | -> Lazy 124 | { 125 | let reconn_ms = self.reconnect_timeout.as_secs() * 1000 + 126 | (self.reconnect_timeout.subsec_nanos() / 1000_000) as u64; 127 | Lazy { 128 | conn_limit: self.conn_limit, 129 | reconnect_ms: (reconn_ms / 2, reconn_ms * 3 / 2), 130 | futures: FuturesUnordered::new(), 131 | connections: Rc::new(RefCell::new(Connections::new())), 132 | blist: Blacklist::new(h), 133 | aligner: Aligner::new(), 134 | closing: false, 135 | cur_address: [][..].into(), 136 | address, connector, errors, metrics, 137 | } 138 | } 139 | } 140 | 141 | impl Lazy 142 | where A: Stream, 143 | C: Connect + 'static, 144 | <::Future as Future>::Item: Sink, 145 | E: ErrorLog< 146 | ConnectionError=::Error, 147 | SinkError=<::Item as Sink>::SinkError, 148 | >, 149 | M: Collect + 'static, 150 | { 151 | fn new_addr(&mut self) -> Option
{ 152 | let mut result = None; 153 | loop { 154 | match self.address.poll() { 155 | Ok(Async::Ready(Some(addr))) => result = Some(addr), 156 | Ok(Async::Ready(None)) => { 157 | self.errors.pool_shutting_down( 158 | ShutdownReason::AddressStreamClosed); 159 | self.start_closing(); 160 | result = None; 161 | break; 162 | } 163 | Ok(Async::NotReady) => break, 164 | Err(e) => unreachable(e), 165 | } 166 | } 167 | return result; 168 | } 169 | fn check_for_address_updates(&mut self) { 170 | let new_addr = match self.new_addr() { 171 | Some(new) => { 172 | if new != self.cur_address { 173 | new 174 | } else { 175 | return; 176 | } 177 | } 178 | _ => return, 179 | }; 180 | let (old, new) = self.cur_address.at(0) 181 | .compare_addresses(&new_addr.at(0)); 182 | debug!("New address, to be retired {:?}, \ 183 | to be connected {:?}", old, new); 184 | for task in &self.connections.borrow().all { 185 | if old.contains(&task.addr()) { 186 | task.close(); 187 | } 188 | } 189 | self.aligner.update(new, old); 190 | self.cur_address = new_addr; 191 | } 192 | fn do_connect(&mut self) -> Option { 193 | let ref blist = self.blist; 194 | let new = self.aligner.get(self.conn_limit, |a| blist.is_failing(a)); 195 | if let Some(addr) = new { 196 | self.metrics.connection_attempt(); 197 | let task = Helper::new(addr, self.connections.clone()); 198 | self.connections.borrow_mut() 199 | .all.insert(task.controller()); 200 | self.futures.push( 201 | Box::new(ConnectFuture::new(task, 202 | self.connector.connect(addr)))); 203 | debug!("Connecting to {}", addr); 204 | return Some(addr); 205 | } 206 | return None; 207 | } 208 | fn start_closing(&mut self) { 209 | if !self.closing { 210 | self.closing = true; 211 | for conn in &self.connections.borrow_mut().all { 212 | conn.close(); 213 | } 214 | } 215 | } 216 | fn poll_futures(&mut self) { 217 | loop { 218 | match self.futures.poll() { 219 | Ok(Async::NotReady) => break, 220 | Ok(Async::Ready(None)) => break, 221 | Ok(Async::Ready(Some(FutureOk::Connected(task, sink)))) => { 222 | self.metrics.connection(); 223 | debug!("Connected to {}", task.addr()); 224 | // helper will add itself to the active queue on wakeup 225 | self.futures.push(Box::new(SinkFuture::new(sink, task))); 226 | } 227 | Err(FutureErr::CantConnect(sa, err)) => { 228 | self.metrics.connection_error(); 229 | self.errors.connection_error(sa, err); 230 | let (min, max) = self.reconnect_ms; 231 | let dur = Duration::from_millis( 232 | thread_rng().gen_range(min, max)); 233 | self.metrics.blacklist_add(); 234 | self.blist.blacklist(sa, Instant::now() + dur); 235 | self.aligner.put(sa); 236 | } 237 | Err(FutureErr::Disconnected(sa, err)) => { 238 | self.metrics.disconnect(); 239 | // TODO(tailhook) blacklist connection if it was 240 | // recently connected 241 | self.errors.sink_error(sa, err); 242 | self.aligner.put(sa); 243 | } 244 | Ok(Async::Ready(Some(FutureOk::Aborted(_)))) => { 245 | self.metrics.connection_abort(); 246 | } 247 | Ok(Async::Ready(Some(FutureOk::Closed(_)))) => { 248 | self.metrics.disconnect(); 249 | } 250 | } 251 | } 252 | } 253 | } 254 | 255 | impl Sink for Lazy 256 | where A: Stream, 257 | C: Connect + 'static, 258 | ::Item: Sink, 259 | E: ErrorLog< 260 | ConnectionError=::Error, 261 | SinkError=<::Item as Sink>::SinkError>, 262 | M: Collect + 'static, 263 | { 264 | type SinkItem = <::Item as Sink>::SinkItem; 265 | type SinkError = private::Done; 266 | fn start_send(&mut self, mut v: Self::SinkItem) 267 | -> Result, private::Done> 268 | { 269 | if self.closing { 270 | self.poll_futures(); 271 | if self.futures.len() == 0 { 272 | return Err(private::Done); 273 | } 274 | return Ok(AsyncSink::NotReady(v)); 275 | } else { 276 | self.check_for_address_updates(); 277 | 'outer: loop { 278 | loop { 279 | let ctr = self.connections.borrow_mut().next(); 280 | if let Some(ctr) = ctr { 281 | if ctr.is_closed() { continue } 282 | ctr.request(v); 283 | self.poll_futures(); 284 | if let Some(request) = ctr.request_back() { 285 | v = request; 286 | continue; 287 | } else { 288 | // Note: we assume that controller put itself back 289 | // to the active queue 290 | return Ok(AsyncSink::Ready); 291 | } 292 | } else { 293 | self.poll_futures(); 294 | if !self.connections.borrow().has_ready() { 295 | break; 296 | } 297 | } 298 | } 299 | loop { 300 | while let Some(addr) = self.do_connect() { 301 | self.poll_futures(); 302 | if self.connections.borrow().has_ready() { 303 | continue 'outer; 304 | } 305 | if !self.blist.is_failing(addr) { 306 | // Waiting for connect 307 | return Ok(AsyncSink::NotReady(v)); 308 | } 309 | } 310 | if let Async::Ready(_) = self.blist.poll() { 311 | self.metrics.blacklist_remove(); 312 | while let Async::Ready(_) = self.blist.poll() { 313 | self.metrics.blacklist_remove(); 314 | } 315 | } else { 316 | // log backpressure issue, not sure how 317 | return Ok(AsyncSink::NotReady(v)); 318 | } 319 | } 320 | } 321 | } 322 | } 323 | fn poll_complete(&mut self) -> Result, private::Done> { 324 | if self.closing { 325 | self.poll_futures(); 326 | if self.futures.len() == 0 { 327 | return Err(private::Done); 328 | } 329 | return Ok(Async::NotReady); 330 | } else { 331 | self.poll_futures(); 332 | while let Async::Ready(_) = self.blist.poll() { 333 | self.metrics.blacklist_remove(); 334 | } 335 | } 336 | // TODO(tailhook) maybe we can track if connections have everything 337 | // flushed 338 | return Ok(Async::NotReady); 339 | } 340 | fn close(&mut self) -> Result, private::Done> { 341 | self.start_closing(); 342 | self.poll_futures(); 343 | if self.futures.len() == 0 { 344 | return Ok(Async::Ready(())); 345 | } 346 | return Ok(Async::NotReady); 347 | } 348 | } 349 | 350 | --------------------------------------------------------------------------------