forked from hyperium/hyper-util
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconn.rs
More file actions
401 lines (362 loc) · 12.4 KB
/
conn.rs
File metadata and controls
401 lines (362 loc) · 12.4 KB
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
//! Tower layers and services for HTTP/1 and HTTP/2 client connections.
//!
//! This module provides Tower-compatible layers that wrap Hyper's low-level
//! HTTP client connection types, making them easier to compose with other
//! middleware and connection pooling strategies.
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};
use http::{Request, Response};
use tower_service::Service;
use crate::common::future::poll_fn;
type BoxError = Box<dyn std::error::Error + Send + Sync>;
/// A Tower [`Layer`](tower_layer::Layer) for creating HTTP/1 client connections.
///
/// This layer wraps a connection service (typically a TCP or TLS connector) and
/// performs the HTTP/1 handshake, producing an [`Http1ClientService`] that can
/// send requests.
///
/// Use [`http1()`] to create a layer with default settings, or construct from
/// a [`hyper::client::conn::http1::Builder`] for custom configuration.
///
/// # Example
///
/// ```ignore
/// use hyper_util::client::conn::http1;
/// use hyper::{client::connect::HttpConnector, body::Bytes};
/// use tower:: ServiceBuilder;
/// use http_body_util::Empty;
///
/// let connector = HttpConnector::new();
/// let layer: Http1Layer<Empty<Bytes>> = http1();
/// let client = ServiceBuilder::new()
/// .layer(layer)
/// .service(connector);
/// ```
#[cfg(feature = "http1")]
pub struct Http1Layer<B> {
builder: hyper::client::conn::http1::Builder,
_body: PhantomData<fn(B)>,
}
/// Creates an [`Http1Layer`] with default HTTP/1 settings.
///
/// For custom settings, construct an [`Http1Layer`] from a
/// [`hyper::client::conn::http1::Builder`] using `.into()`.
#[cfg(feature = "http1")]
pub fn http1<B>() -> Http1Layer<B> {
Http1Layer {
builder: hyper::client::conn::http1::Builder::new(),
_body: PhantomData,
}
}
#[cfg(feature = "http1")]
impl<M, B> tower_layer::Layer<M> for Http1Layer<B> {
type Service = Http1Connect<M, B>;
fn layer(&self, inner: M) -> Self::Service {
Http1Connect {
inner,
builder: self.builder.clone(),
_body: self._body,
}
}
}
#[cfg(feature = "http1")]
impl<B> Clone for Http1Layer<B> {
fn clone(&self) -> Self {
Self {
builder: self.builder.clone(),
_body: self._body.clone(),
}
}
}
#[cfg(feature = "http1")]
impl<B> From<hyper::client::conn::http1::Builder> for Http1Layer<B> {
fn from(builder: hyper::client::conn::http1::Builder) -> Self {
Self {
builder,
_body: PhantomData,
}
}
}
/// A Tower [`Service`] that establishes HTTP/1 connections.
///
/// This service wraps an underlying connection service (e.g., TCP or TLS) and
/// performs the HTTP/1 handshake when called. The resulting service can be used
/// to send HTTP requests over the established connection.
#[cfg(feature = "http1")]
pub struct Http1Connect<M, B> {
inner: M,
builder: hyper::client::conn::http1::Builder,
_body: PhantomData<fn(B)>,
}
#[cfg(feature = "http1")]
impl<M, Dst, B> Service<Dst> for Http1Connect<M, B>
where
M: Service<Dst>,
M::Future: Send + 'static,
M::Response: hyper::rt::Read + hyper::rt::Write + Unpin + Send + 'static,
M::Error: Into<BoxError>,
B: hyper::body::Body + Send + 'static,
B::Data: Send + 'static,
B::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
{
type Response = Http1ClientService<B>;
type Error = BoxError;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx).map_err(Into::into)
}
fn call(&mut self, dst: Dst) -> Self::Future {
let fut = self.inner.call(dst);
let builder = self.builder.clone();
Box::pin(async move {
let io = fut.await.map_err(Into::into)?;
let (mut tx, conn) = builder.handshake(io).await?;
//todo: pass in Executor
tokio::spawn(async move {
if let Err(e) = conn.await {
eprintln!("connection error: {:?}", e);
}
});
// todo: wait for ready? or factor out to other middleware?
poll_fn(|cx| tx.poll_ready(cx)).await?;
Ok(Http1ClientService::new(tx))
})
}
}
#[cfg(feature = "http1")]
impl<M: Clone, B> Clone for Http1Connect<M, B> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
builder: self.builder.clone(),
_body: self._body.clone(),
}
}
}
/// A Tower [`Layer`](tower_layer::Layer) for creating HTTP/2 client connections.
///
/// This layer wraps a connection service (typically a TCP or TLS connector) and
/// performs the HTTP/2 handshake, producing an [`Http2ClientService`] that can
/// send requests.
///
/// Use [`http2()`] to create a layer with a specific executor, or construct from
/// a [`hyper::client::conn::http2::Builder`] for custom configuration.
///
/// # Example
///
/// ```ignore
/// use hyper_util::client::conn::http2;
/// use hyper::{client::connect::HttpConnector, body::Bytes};
/// use tower:: ServiceBuilder;
/// use http_body_util::Empty;
///
/// let connector = HttpConnector::new();
/// let layer: Http2Layer<Empty<Bytes>> = http2();
/// let client = ServiceBuilder::new()
/// .layer(layer)
/// .service(connector);
/// ```
#[cfg(feature = "http2")]
pub struct Http2Layer<B, E> {
builder: hyper::client::conn::http2::Builder<E>,
_body: PhantomData<fn(B)>,
}
/// Creates an [`Http2Layer`] with default HTTP/1 settings.
///
/// For custom settings, construct an [`Http2Layer`] from a
/// [`hyper::client::conn::http2::Builder`] using `.into()`.
#[cfg(feature = "http2")]
pub fn http2<B, E>(executor: E) -> Http2Layer<B, E>
where
E: Clone,
{
Http2Layer {
builder: hyper::client::conn::http2::Builder::new(executor),
_body: PhantomData,
}
}
#[cfg(feature = "http2")]
impl<M, B, E> tower_layer::Layer<M> for Http2Layer<B, E>
where
E: Clone,
{
type Service = Http2Connect<M, B, E>;
fn layer(&self, inner: M) -> Self::Service {
Http2Connect {
inner,
builder: hyper::client::conn::http2::Builder::new(crate::rt::TokioExecutor::new()),
_body: self._body,
}
}
}
#[cfg(feature = "http2")]
impl<B, E: Clone> Clone for Http2Layer<B, E> {
fn clone(&self) -> Self {
Self {
builder: self.builder.clone(),
_body: self._body.clone(),
}
}
}
#[cfg(feature = "http2")]
impl<B, E> From<hyper::client::conn::http2::Builder<E>> for Http2Layer<B, E> {
fn from(builder: hyper::client::conn::http2::Builder<E>) -> Self {
Self {
builder,
_body: PhantomData,
}
}
}
/// A Tower [`Service`] that establishes HTTP/2 connections.
///
/// This service wraps an underlying connection service (e.g., TCP or TLS) and
/// performs the HTTP/2 handshake when called. The resulting service can be used
/// to send HTTP requests over the established connection.
#[cfg(feature = "http2")]
#[derive(Debug)]
pub struct Http2Connect<M, B, E> {
inner: M,
builder: hyper::client::conn::http2::Builder<E>,
_body: PhantomData<fn(B)>,
}
#[cfg(feature = "http2")]
impl<M, Dst, B, E> Service<Dst> for Http2Connect<M, B, E>
where
M: Service<Dst>,
M::Future: Send + 'static,
M::Response: hyper::rt::Read + hyper::rt::Write + Unpin + Send + 'static,
M::Error: Into<BoxError>,
B: hyper::body::Body + Unpin + Send + 'static,
B::Data: Send + 'static,
B::Error: Into<BoxError>,
E: hyper::rt::bounds::Http2ClientConnExec<B, M::Response> + Unpin + Clone + Send + 'static,
{
type Response = Http2ClientService<B>;
type Error = BoxError;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx).map_err(Into::into)
}
fn call(&mut self, dst: Dst) -> Self::Future {
let fut = self.inner.call(dst);
let builder = self.builder.clone();
Box::pin(async move {
let io = fut.await.map_err(Into::into)?;
let (mut tx, conn) = builder.handshake(io).await?;
tokio::spawn(async move {
if let Err(e) = conn.await {
eprintln!("connection error: {:?}", e);
}
});
// todo: wait for ready? or factor out to other middleware?
poll_fn(|cx| tx.poll_ready(cx)).await?;
Ok(Http2ClientService::new(tx))
})
}
}
#[cfg(feature = "http2")]
impl<M: Clone, B, E: Clone> Clone for Http2Connect<M, B, E> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
builder: self.builder.clone(),
_body: self._body.clone(),
}
}
}
/// A Tower [`Service`] that sends HTTP/1 requests over an established connection.
///
/// This is a thin wrapper around [`hyper::client::conn::http1::SendRequest`] that implements
/// the Tower `Service` trait, making it composable with other Tower middleware.
///
/// The service maintains a single HTTP/1 connection and can be used to send multiple
/// sequential requests. For concurrent requests or connection pooling, wrap this service
/// with appropriate middleware.
#[cfg(feature = "http1")]
#[derive(Debug)]
pub struct Http1ClientService<B> {
tx: hyper::client::conn::http1::SendRequest<B>,
}
#[cfg(feature = "http1")]
impl<B> Http1ClientService<B> {
/// Constructs a new HTTP/1 client service from a Hyper `SendRequest`.
///
/// Typically you won't call this directly; instead, use [`Http1Connect`] to
/// establish connections and produce this service.
pub fn new(tx: hyper::client::conn::http1::SendRequest<B>) -> Self {
Self { tx }
}
/// Checks if the connection side has been closed.
pub fn is_closed(&self) -> bool {
self.tx.is_closed()
}
}
#[cfg(feature = "http1")]
impl<B> Service<Request<B>> for Http1ClientService<B>
where
B: hyper::body::Body + Send + 'static,
{
type Response = Response<hyper::body::Incoming>;
type Error = hyper::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.tx.poll_ready(cx)
}
fn call(&mut self, req: Request<B>) -> Self::Future {
let fut = self.tx.send_request(req);
Box::pin(fut)
}
}
/// A Tower [`Service`] that sends HTTP/2 requests over an established connection.
///
/// This is a thin wrapper around [`hyper::client::conn::http2::SendRequest`] that implements
/// the Tower `Service` trait, making it composable with other Tower middleware.
///
/// The service maintains a single HTTP/2 connection and supports multiplexing multiple
/// concurrent requests over that connection. The service can be cloned to send requests
/// concurrently, or used with the [`Singleton`](crate::client::pool::singleton::Singleton) pool service.
#[cfg(feature = "http2")]
#[derive(Debug)]
pub struct Http2ClientService<B> {
tx: hyper::client::conn::http2::SendRequest<B>,
}
#[cfg(feature = "http2")]
impl<B> Http2ClientService<B> {
/// Constructs a new HTTP/2 client service from a Hyper `SendRequest`.
///
/// Typically you won't call this directly; instead, use [`Http2Connect`] to
/// establish connections and produce this service.
pub fn new(tx: hyper::client::conn::http2::SendRequest<B>) -> Self {
Self { tx }
}
/// Checks if the connection side has been closed.
pub fn is_closed(&self) -> bool {
self.tx.is_closed()
}
}
#[cfg(feature = "http2")]
impl<B> Service<Request<B>> for Http2ClientService<B>
where
B: hyper::body::Body + Send + 'static,
{
type Response = Response<hyper::body::Incoming>;
type Error = hyper::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.tx.poll_ready(cx)
}
fn call(&mut self, req: Request<B>) -> Self::Future {
let fut = self.tx.send_request(req);
Box::pin(fut)
}
}
#[cfg(feature = "http2")]
impl<B> Clone for Http2ClientService<B> {
fn clone(&self) -> Self {
Self {
tx: self.tx.clone(),
}
}
}