/
pool.rs
205 lines (175 loc) · 5.51 KB
/
pool.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
use bytes::Bytes;
use std::collections::HashMap;
use std::sync::mpsc::{Receiver, TryRecvError};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::time::Instant;
use crate::error::{BoxError, Error, Kind};
use crate::Body;
use bytes::Buf;
use futures_util::future;
use h3::client::Connection as H3Conn;
use h3::client::SendRequest;
use h3_quinn::{Connection, OpenStreams};
use http::uri::{Authority, Scheme};
use http::{Request, Response, Uri};
use hyper::Body as HyperBody;
use log::trace;
pub(super) type Key = (Scheme, Authority);
#[derive(Clone)]
pub struct Pool {
inner: Arc<Mutex<PoolInner>>,
}
impl Pool {
pub fn new(max_idle_per_host: usize, timeout: Option<Duration>) -> Self {
Self {
inner: Arc::new(Mutex::new(PoolInner {
idle_conns: HashMap::new(),
max_idle_per_host,
timeout,
})),
}
}
pub fn try_pool(&self, key: &Key) -> Option<PoolClient> {
let mut inner = self.inner.lock().unwrap();
let timeout = inner.timeout;
if let Some(conn) = inner.idle_conns.get(&key) {
// We check first if the connection still valid
// and if not, we remove it from the pool.
if conn.is_invalid() {
trace!("pooled HTTP/3 connection is invalid so removing it...");
inner.idle_conns.remove(&key);
}
}
inner
.idle_conns
.get_mut(&key)
.and_then(|conn| match conn.idle.pop() {
Some(idle) => {
if let Some(duration) = timeout {
if Instant::now().saturating_duration_since(idle.idle_at) > duration {
trace!("pooled client expired");
return None;
}
}
conn.push_client(idle.value.clone());
Some(idle.value)
}
None => None,
})
}
pub fn new_connection(
&mut self,
key: Key,
mut driver: H3Conn<Connection, Bytes>,
tx: SendRequest<OpenStreams, Bytes>,
) -> PoolClient {
let (send, receive) = std::sync::mpsc::channel();
tokio::spawn(async move {
if let Err(e) = future::poll_fn(|cx| driver.poll_close(cx)).await {
trace!("poll_close returned error {:?}", e);
send.send(e).ok();
}
});
let mut inner = self.inner.lock().unwrap();
let mut conn = PoolConnection::new(receive, inner.max_idle_per_host);
let client = PoolClient::new(tx);
conn.push_client(client.clone());
inner.insert(key, conn);
client
}
}
struct PoolInner {
idle_conns: HashMap<Key, PoolConnection>,
max_idle_per_host: usize,
timeout: Option<Duration>,
}
impl PoolInner {
fn insert(&mut self, key: Key, conn: PoolConnection) {
if self.idle_conns.contains_key(&key) {
trace!("connection already exists for key {:?}", key);
}
self.idle_conns.insert(key, conn);
}
}
#[derive(Clone)]
pub struct PoolClient {
tx: SendRequest<OpenStreams, Bytes>,
}
impl PoolClient {
pub fn new(tx: SendRequest<OpenStreams, Bytes>) -> Self {
Self { tx }
}
pub async fn send_request(
&mut self,
req: Request<Body>,
) -> Result<Response<HyperBody>, BoxError> {
let (head, req_body) = req.into_parts();
let req = Request::from_parts(head, ());
let mut stream = self.tx.send_request(req).await?;
match req_body.as_bytes() {
Some(b) if !b.is_empty() => {
stream.send_data(Bytes::copy_from_slice(b)).await?;
}
_ => {}
}
stream.finish().await?;
let resp = stream.recv_response().await?;
let mut resp_body = Vec::new();
while let Some(chunk) = stream.recv_data().await? {
resp_body.extend(chunk.chunk())
}
Ok(resp.map(|_| HyperBody::from(resp_body)))
}
}
pub struct PoolConnection {
// This receives errors from polling h3 driver.
rx: Receiver<h3::Error>,
idle: Vec<Idle>,
max_idle_per_host: usize,
}
impl PoolConnection {
pub fn new(rx: Receiver<h3::Error>, max_idle_per_host: usize) -> Self {
Self {
rx,
idle: Vec::new(),
max_idle_per_host,
}
}
pub fn push_client(&mut self, client: PoolClient) {
if self.idle.len() >= self.max_idle_per_host {
trace!("max idle per host reached for HTTP/3 pool connection");
return;
}
self.idle.push(Idle {
idle_at: Instant::now(),
value: client,
});
}
pub fn is_invalid(&self) -> bool {
match self.rx.try_recv() {
Err(TryRecvError::Empty) => false,
Err(TryRecvError::Disconnected) => true,
Ok(_) => true,
}
}
}
struct Idle {
idle_at: Instant,
value: PoolClient,
}
pub(crate) fn extract_domain(uri: &mut Uri) -> Result<Key, Error> {
let uri_clone = uri.clone();
match (uri_clone.scheme(), uri_clone.authority()) {
(Some(scheme), Some(auth)) => Ok((scheme.clone(), auth.clone())),
_ => Err(Error::new(Kind::Request, None::<Error>)),
}
}
pub(crate) fn domain_as_uri((scheme, auth): Key) -> Uri {
http::uri::Builder::new()
.scheme(scheme)
.authority(auth)
.path_and_query("/")
.build()
.expect("domain is valid Uri")
}