mirror of
https://github.com/serai-dex/serai.git
synced 2025-12-08 12:19:24 +00:00
Make simple_request::Client generic to the executor
Part of https://github.com/serai-dex/serai/issues/682. We don't remove the use of `tokio::sync::Mutex` now as `hyper` pulls in `tokio::sync` anyways, so there's no point in replacing it. This doesn't yet solve TLS for non-`tokio` `Client`s.
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "simple-request"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
description = "A simple HTTP(S) request library"
|
||||
license = "MIT"
|
||||
repository = "https://github.com/serai-dex/serai/tree/develop/common/request"
|
||||
@@ -19,10 +19,10 @@ workspace = true
|
||||
[dependencies]
|
||||
tower-service = { version = "0.3", default-features = false }
|
||||
hyper = { version = "1", default-features = false, features = ["http1", "client"] }
|
||||
hyper-util = { version = "0.1", default-features = false, features = ["http1", "client-legacy", "tokio"] }
|
||||
hyper-util = { version = "0.1", default-features = false, features = ["http1", "client-legacy"] }
|
||||
http-body-util = { version = "0.1", default-features = false }
|
||||
futures-util = { version = "0.3", default-features = false, features = ["std"] }
|
||||
tokio = { version = "1", default-features = false }
|
||||
tokio = { version = "1", default-features = false, features = ["sync"] }
|
||||
|
||||
hyper-rustls = { version = "0.27", default-features = false, features = ["http1", "ring", "rustls-native-certs", "native-tokio"], optional = true }
|
||||
|
||||
@@ -30,7 +30,8 @@ zeroize = { version = "1", optional = true }
|
||||
base64ct = { version = "1", features = ["alloc"], optional = true }
|
||||
|
||||
[features]
|
||||
tls = ["hyper-rustls"]
|
||||
tokio = ["hyper-util/tokio"]
|
||||
tls = ["tokio", "hyper-rustls"]
|
||||
webpki-roots = ["tls", "hyper-rustls/webpki-roots"]
|
||||
basic-auth = ["zeroize", "base64ct"]
|
||||
default = ["tls"]
|
||||
|
||||
@@ -1,19 +1,20 @@
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||
#![doc = include_str!("../README.md")]
|
||||
|
||||
use core::{pin::Pin, future::Future};
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::Mutex;
|
||||
use futures_util::FutureExt;
|
||||
use ::tokio::sync::Mutex;
|
||||
|
||||
use tower_service::Service as TowerService;
|
||||
use hyper::{Uri, header::HeaderValue, body::Bytes, client::conn::http1::SendRequest, rt::Executor};
|
||||
pub use hyper;
|
||||
|
||||
use hyper_util::client::legacy::{Client as HyperClient, connect::HttpConnector};
|
||||
|
||||
#[cfg(feature = "tls")]
|
||||
use hyper_rustls::{HttpsConnectorBuilder, HttpsConnector};
|
||||
use hyper::{Uri, header::HeaderValue, body::Bytes, client::conn::http1::SendRequest};
|
||||
use hyper_util::{
|
||||
rt::tokio::TokioExecutor,
|
||||
client::legacy::{Client as HyperClient, connect::HttpConnector},
|
||||
};
|
||||
pub use hyper;
|
||||
|
||||
mod request;
|
||||
pub use request::*;
|
||||
@@ -37,21 +38,32 @@ type Connector = HttpConnector;
|
||||
type Connector = HttpsConnector<HttpConnector>;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum Connection {
|
||||
enum Connection<
|
||||
E: 'static + Send + Sync + Clone + Executor<Pin<Box<dyn Send + Future<Output = ()>>>>,
|
||||
> {
|
||||
ConnectionPool(HyperClient<Connector, Full<Bytes>>),
|
||||
Connection {
|
||||
executor: E,
|
||||
connector: Connector,
|
||||
host: Uri,
|
||||
connection: Arc<Mutex<Option<SendRequest<Full<Bytes>>>>>,
|
||||
},
|
||||
}
|
||||
|
||||
/// An HTTP client.
|
||||
///
|
||||
/// `tls` is only guaranteed to work when using the `tokio` executor. Instantiating a client when
|
||||
/// the `tls` feature is active without using the `tokio` executor will cause errors.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Client {
|
||||
connection: Connection,
|
||||
pub struct Client<
|
||||
E: 'static + Send + Sync + Clone + Executor<Pin<Box<dyn Send + Future<Output = ()>>>>,
|
||||
> {
|
||||
connection: Connection<E>,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
impl<E: 'static + Send + Sync + Clone + Executor<Pin<Box<dyn Send + Future<Output = ()>>>>>
|
||||
Client<E>
|
||||
{
|
||||
#[allow(clippy::unnecessary_wraps)]
|
||||
fn connector() -> Result<Connector, Error> {
|
||||
let mut res = HttpConnector::new();
|
||||
@@ -59,6 +71,15 @@ impl Client {
|
||||
res.set_nodelay(true);
|
||||
res.set_reuse_address(true);
|
||||
|
||||
#[cfg(feature = "tls")]
|
||||
if core::any::TypeId::of::<E>() !=
|
||||
core::any::TypeId::of::<hyper_util::rt::tokio::TokioExecutor>()
|
||||
{
|
||||
Err(Error::ConnectionError(
|
||||
"`tls` feature enabled but not using the `tokio` executor".into(),
|
||||
))?;
|
||||
}
|
||||
|
||||
#[cfg(feature = "tls")]
|
||||
res.enforce_http(false);
|
||||
#[cfg(feature = "tls")]
|
||||
@@ -79,19 +100,23 @@ impl Client {
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
pub fn with_connection_pool() -> Result<Client, Error> {
|
||||
pub fn with_executor_and_connection_pool(executor: E) -> Result<Client<E>, Error> {
|
||||
Ok(Client {
|
||||
connection: Connection::ConnectionPool(
|
||||
HyperClient::builder(TokioExecutor::new())
|
||||
HyperClient::builder(executor)
|
||||
.pool_idle_timeout(core::time::Duration::from_secs(60))
|
||||
.build(Self::connector()?),
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn without_connection_pool(host: &str) -> Result<Client, Error> {
|
||||
pub fn with_executor_and_without_connection_pool(
|
||||
executor: E,
|
||||
host: &str,
|
||||
) -> Result<Client<E>, Error> {
|
||||
Ok(Client {
|
||||
connection: Connection::Connection {
|
||||
executor,
|
||||
connector: Self::connector()?,
|
||||
host: {
|
||||
let uri: Uri = host.parse().map_err(|_| Error::InvalidUri)?;
|
||||
@@ -105,7 +130,7 @@ impl Client {
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn request<R: Into<Request>>(&self, request: R) -> Result<Response<'_>, Error> {
|
||||
pub async fn request<R: Into<Request>>(&self, request: R) -> Result<Response<'_, E>, Error> {
|
||||
let request: Request = request.into();
|
||||
let Request { mut request, response_size_limit } = request;
|
||||
if let Some(header_host) = request.headers().get(hyper::header::HOST) {
|
||||
@@ -141,7 +166,7 @@ impl Client {
|
||||
Connection::ConnectionPool(client) => {
|
||||
client.request(request).await.map_err(Error::HyperUtil)?
|
||||
}
|
||||
Connection::Connection { connector, host, connection } => {
|
||||
Connection::Connection { executor, connector, host, connection } => {
|
||||
let mut connection_lock = connection.lock().await;
|
||||
|
||||
// If there's not a connection...
|
||||
@@ -153,9 +178,8 @@ impl Client {
|
||||
let call_res = call_res.map_err(Error::ConnectionError);
|
||||
let (requester, connection) =
|
||||
hyper::client::conn::http1::handshake(call_res?).await.map_err(Error::Hyper)?;
|
||||
// This will die when we drop the requester, so we don't need to track an AbortHandle
|
||||
// for it
|
||||
tokio::spawn(connection);
|
||||
// This task will die when we drop the requester
|
||||
executor.execute(Box::pin(connection.map(|_| ())));
|
||||
*connection_lock = Some(requester);
|
||||
}
|
||||
|
||||
@@ -178,3 +202,22 @@ impl Client {
|
||||
Ok(Response { response, size_limit: response_size_limit, client: self })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "tokio")]
|
||||
mod tokio {
|
||||
use hyper_util::rt::tokio::TokioExecutor;
|
||||
use super::*;
|
||||
|
||||
pub type TokioClient = Client<TokioExecutor>;
|
||||
impl Client<TokioExecutor> {
|
||||
pub fn with_connection_pool() -> Result<Self, Error> {
|
||||
Self::with_executor_and_connection_pool(TokioExecutor::new())
|
||||
}
|
||||
|
||||
pub fn without_connection_pool(host: &str) -> Result<Self, Error> {
|
||||
Self::with_executor_and_without_connection_pool(TokioExecutor::new(), host)
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "tokio")]
|
||||
pub use tokio::TokioClient;
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
use core::{pin::Pin, future::Future};
|
||||
use std::io;
|
||||
|
||||
use hyper::{
|
||||
StatusCode,
|
||||
header::{HeaderValue, HeaderMap},
|
||||
body::Incoming,
|
||||
rt::Executor,
|
||||
};
|
||||
use http_body_util::BodyExt;
|
||||
|
||||
@@ -14,13 +16,18 @@ use crate::{Client, Error};
|
||||
// Borrows the client so its async task lives as long as this response exists.
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug)]
|
||||
pub struct Response<'a> {
|
||||
pub struct Response<
|
||||
'a,
|
||||
E: 'static + Send + Sync + Clone + Executor<Pin<Box<dyn Send + Future<Output = ()>>>>,
|
||||
> {
|
||||
pub(crate) response: hyper::Response<Incoming>,
|
||||
pub(crate) size_limit: Option<usize>,
|
||||
pub(crate) client: &'a Client,
|
||||
pub(crate) client: &'a Client<E>,
|
||||
}
|
||||
|
||||
impl Response<'_> {
|
||||
impl<E: 'static + Send + Sync + Clone + Executor<Pin<Box<dyn Send + Future<Output = ()>>>>>
|
||||
Response<'_, E>
|
||||
{
|
||||
pub fn status(&self) -> StatusCode {
|
||||
self.response.status()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user