Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs
This commit is contained in:
+276
@@ -0,0 +1,276 @@
|
||||
use crate::async_impl::h3_client::dns::resolve;
|
||||
use crate::dns::DynResolver;
|
||||
use crate::error::BoxError;
|
||||
use bytes::Bytes;
|
||||
use h3::client::SendRequest;
|
||||
use h3_quinn::{Connection, OpenStreams};
|
||||
use http::Uri;
|
||||
use hyper_util::client::legacy::connect::dns::Name;
|
||||
use quinn::crypto::rustls::QuicClientConfig;
|
||||
use quinn::{ClientConfig, Endpoint, TransportConfig};
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
type H3Connection = (
|
||||
h3::client::Connection<Connection, Bytes>,
|
||||
SendRequest<OpenStreams, Bytes>,
|
||||
);
|
||||
|
||||
const HAPPY_EYEBALLS_DELAY: Duration = Duration::from_millis(250);
|
||||
|
||||
/// H3 Client Config
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct H3ClientConfig {
|
||||
/// Set the maximum HTTP/3 header size this client is willing to accept.
|
||||
///
|
||||
/// See [header size constraints] section of the specification for details.
|
||||
///
|
||||
/// [header size constraints]: https://www.rfc-editor.org/rfc/rfc9114.html#name-header-size-constraints
|
||||
///
|
||||
/// Please see docs in [`Builder`] in [`h3`].
|
||||
///
|
||||
/// [`Builder`]: https://docs.rs/h3/latest/h3/client/struct.Builder.html#method.max_field_section_size
|
||||
pub(crate) max_field_section_size: Option<u64>,
|
||||
|
||||
/// Enable whether to send HTTP/3 protocol grease on the connections.
|
||||
///
|
||||
/// Just like in HTTP/2, HTTP/3 also uses the concept of "grease"
|
||||
///
|
||||
/// to prevent potential interoperability issues in the future.
|
||||
/// In HTTP/3, the concept of grease is used to ensure that the protocol can evolve
|
||||
/// and accommodate future changes without breaking existing implementations.
|
||||
///
|
||||
/// Please see docs in [`Builder`] in [`h3`].
|
||||
///
|
||||
/// [`Builder`]: https://docs.rs/h3/latest/h3/client/struct.Builder.html#method.send_grease
|
||||
pub(crate) send_grease: Option<bool>,
|
||||
}
|
||||
|
||||
impl Default for H3ClientConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_field_section_size: None,
|
||||
send_grease: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct H3Connector {
|
||||
resolver: DynResolver,
|
||||
endpoint: Endpoint,
|
||||
client_config: H3ClientConfig,
|
||||
local_addr: Option<IpAddr>,
|
||||
}
|
||||
|
||||
impl H3Connector {
|
||||
pub fn new(
|
||||
resolver: DynResolver,
|
||||
tls: rustls::ClientConfig,
|
||||
local_addr: Option<IpAddr>,
|
||||
transport_config: TransportConfig,
|
||||
client_config: H3ClientConfig,
|
||||
) -> Result<H3Connector, BoxError> {
|
||||
let quic_client_config = Arc::new(QuicClientConfig::try_from(tls)?);
|
||||
let mut config = ClientConfig::new(quic_client_config);
|
||||
// FIXME: Replace this when there is a setter.
|
||||
config.transport_config(Arc::new(transport_config));
|
||||
|
||||
// Pipe the local address through to the endpoint creation
|
||||
let socket_addr = match local_addr {
|
||||
Some(ip) => SocketAddr::new(ip, 0),
|
||||
None => "[::]:0".parse::<SocketAddr>().unwrap(),
|
||||
};
|
||||
|
||||
let mut endpoint = Endpoint::client(socket_addr)?;
|
||||
endpoint.set_default_client_config(config);
|
||||
|
||||
Ok(Self {
|
||||
resolver,
|
||||
endpoint,
|
||||
client_config,
|
||||
local_addr,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn connect(&mut self, dest: Uri) -> Result<H3Connection, BoxError> {
|
||||
let host = dest
|
||||
.host()
|
||||
.ok_or("destination must have a host")?
|
||||
.trim_start_matches('[')
|
||||
.trim_end_matches(']');
|
||||
let port = dest.port_u16().unwrap_or(443);
|
||||
|
||||
let addrs = if let Some(addr) = IpAddr::from_str(host).ok() {
|
||||
// If the host is already an IP address, skip resolving.
|
||||
vec![SocketAddr::new(addr, port)]
|
||||
} else {
|
||||
let addrs = resolve(&mut self.resolver, Name::from_str(host)?).await?;
|
||||
let addrs = addrs.map(|mut addr| {
|
||||
addr.set_port(port);
|
||||
addr
|
||||
});
|
||||
addrs.collect()
|
||||
};
|
||||
|
||||
self.remote_connect(addrs, host).await
|
||||
}
|
||||
|
||||
async fn remote_connect(
|
||||
&mut self,
|
||||
addrs: Vec<SocketAddr>,
|
||||
server_name: &str,
|
||||
) -> Result<H3Connection, BoxError> {
|
||||
if addrs.is_empty() {
|
||||
return Err("no addresses to connect to".into());
|
||||
}
|
||||
|
||||
let (mut ipv6_addrs, mut ipv4_addrs): (Vec<SocketAddr>, Vec<SocketAddr>) =
|
||||
addrs.into_iter().partition(|addr| addr.is_ipv6());
|
||||
|
||||
if let Some(local_ip) = self.local_addr {
|
||||
if local_ip.is_ipv6() {
|
||||
ipv4_addrs.clear();
|
||||
} else {
|
||||
ipv6_addrs.clear();
|
||||
}
|
||||
}
|
||||
|
||||
if ipv6_addrs.is_empty() {
|
||||
return Self::try_addresses_static(
|
||||
&self.endpoint,
|
||||
&ipv4_addrs,
|
||||
server_name,
|
||||
&self.client_config,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
if ipv4_addrs.is_empty() {
|
||||
return Self::try_addresses_static(
|
||||
&self.endpoint,
|
||||
&ipv6_addrs,
|
||||
server_name,
|
||||
&self.client_config,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
let endpoint = self.endpoint.clone();
|
||||
let client_config = self.client_config.clone();
|
||||
|
||||
if self.local_addr.is_some() {
|
||||
return match Self::try_addresses_static(
|
||||
&endpoint,
|
||||
&ipv6_addrs,
|
||||
server_name,
|
||||
&client_config,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(conn) => Ok(conn),
|
||||
Err(_) => {
|
||||
Self::try_addresses_static(&endpoint, &ipv4_addrs, server_name, &client_config)
|
||||
.await
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
Self::try_addresses_happy_eyeballs(
|
||||
&endpoint,
|
||||
&ipv6_addrs,
|
||||
&ipv4_addrs,
|
||||
server_name,
|
||||
&client_config,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn try_addresses_static(
|
||||
endpoint: &Endpoint,
|
||||
addrs: &[SocketAddr],
|
||||
server_name: &str,
|
||||
client_config: &H3ClientConfig,
|
||||
) -> Result<H3Connection, BoxError> {
|
||||
let mut last_err: Option<BoxError> = None;
|
||||
|
||||
for addr in addrs {
|
||||
match endpoint.connect(*addr, server_name) {
|
||||
Ok(connecting) => match connecting.await {
|
||||
Ok(new_conn) => {
|
||||
let quinn_conn = Connection::new(new_conn);
|
||||
let mut h3_client_builder = h3::client::builder();
|
||||
if let Some(max_field_section_size) = client_config.max_field_section_size {
|
||||
h3_client_builder.max_field_section_size(max_field_section_size);
|
||||
}
|
||||
if let Some(send_grease) = client_config.send_grease {
|
||||
h3_client_builder.send_grease(send_grease);
|
||||
}
|
||||
return Ok(h3_client_builder.build(quinn_conn).await?);
|
||||
}
|
||||
Err(e) => {
|
||||
last_err = Some(Box::new(e) as BoxError);
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
last_err = Some(Box::new(e) as BoxError);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Err(last_err.unwrap_or_else(|| "no addresses available".into()))
|
||||
}
|
||||
|
||||
async fn try_addresses_happy_eyeballs(
|
||||
endpoint: &Endpoint,
|
||||
ipv6_addrs: &[SocketAddr],
|
||||
ipv4_addrs: &[SocketAddr],
|
||||
server_name: &str,
|
||||
client_config: &H3ClientConfig,
|
||||
) -> Result<H3Connection, BoxError> {
|
||||
let ipv6_connect =
|
||||
Self::try_addresses_static(endpoint, ipv6_addrs, server_name, client_config);
|
||||
tokio::pin!(ipv6_connect);
|
||||
|
||||
let delay = tokio::time::sleep(HAPPY_EYEBALLS_DELAY);
|
||||
tokio::pin!(delay);
|
||||
|
||||
tokio::select! {
|
||||
result = &mut ipv6_connect => {
|
||||
return match result {
|
||||
Ok(conn) => Ok(conn),
|
||||
Err(_) => {
|
||||
Self::try_addresses_static(endpoint, ipv4_addrs, server_name, client_config).await
|
||||
}
|
||||
};
|
||||
}
|
||||
_ = &mut delay => {}
|
||||
}
|
||||
|
||||
let ipv4_connect =
|
||||
Self::try_addresses_static(endpoint, ipv4_addrs, server_name, client_config);
|
||||
tokio::pin!(ipv4_connect);
|
||||
|
||||
let wait_for_ipv6 = tokio::select! {
|
||||
result = &mut ipv6_connect => {
|
||||
match result {
|
||||
Ok(conn) => return Ok(conn),
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
result = &mut ipv4_connect => {
|
||||
match result {
|
||||
Ok(conn) => return Ok(conn),
|
||||
Err(_) => true,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if wait_for_ipv6 {
|
||||
ipv6_connect.await
|
||||
} else {
|
||||
ipv4_connect.await
|
||||
}
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
use core::task;
|
||||
use hyper_util::client::legacy::connect::dns::Name;
|
||||
use std::future::Future;
|
||||
use std::net::SocketAddr;
|
||||
use std::task::Poll;
|
||||
use tower_service::Service;
|
||||
|
||||
// Trait from hyper to implement DNS resolution for HTTP/3 client.
|
||||
pub trait Resolve {
|
||||
type Addrs: Iterator<Item = SocketAddr>;
|
||||
type Error: Into<Box<dyn std::error::Error + Send + Sync>>;
|
||||
type Future: Future<Output = Result<Self::Addrs, Self::Error>>;
|
||||
|
||||
fn poll_ready(&mut self, cx: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>>;
|
||||
fn resolve(&mut self, name: Name) -> Self::Future;
|
||||
}
|
||||
|
||||
impl<S> Resolve for S
|
||||
where
|
||||
S: Service<Name>,
|
||||
S::Response: Iterator<Item = SocketAddr>,
|
||||
S::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
|
||||
{
|
||||
type Addrs = S::Response;
|
||||
type Error = S::Error;
|
||||
type Future = S::Future;
|
||||
|
||||
fn poll_ready(&mut self, cx: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
Service::poll_ready(self, cx)
|
||||
}
|
||||
|
||||
fn resolve(&mut self, name: Name) -> Self::Future {
|
||||
Service::call(self, name)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn resolve<R>(resolver: &mut R, name: Name) -> Result<R::Addrs, R::Error>
|
||||
where
|
||||
R: Resolve,
|
||||
{
|
||||
std::future::poll_fn(|cx| resolver.poll_ready(cx)).await?;
|
||||
resolver.resolve(name).await
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
#![cfg(feature = "http3")]
|
||||
|
||||
pub(crate) mod connect;
|
||||
pub(crate) mod dns;
|
||||
mod pool;
|
||||
|
||||
use crate::async_impl::body::ResponseBody;
|
||||
use crate::async_impl::h3_client::pool::{Key, Pool, PoolClient};
|
||||
use crate::error::{BoxError, Error, Kind};
|
||||
use crate::{error, Body};
|
||||
use connect::H3Connector;
|
||||
use http::{Request, Response};
|
||||
use log::trace;
|
||||
use std::future::{self, Future};
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::Duration;
|
||||
use sync_wrapper::SyncWrapper;
|
||||
use tower::Service;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct H3Client {
|
||||
pool: Pool,
|
||||
connector: H3Connector,
|
||||
}
|
||||
|
||||
impl H3Client {
|
||||
pub fn new(connector: H3Connector, pool_timeout: Option<Duration>) -> Self {
|
||||
H3Client {
|
||||
pool: Pool::new(pool_timeout),
|
||||
connector,
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_pooled_client(&mut self, key: Key) -> Result<PoolClient, BoxError> {
|
||||
if let Some(client) = self.pool.try_pool(&key) {
|
||||
trace!("getting client from pool with key {key:?}");
|
||||
return Ok(client);
|
||||
}
|
||||
|
||||
trace!("did not find connection {key:?} in pool so connecting...");
|
||||
|
||||
let dest = pool::domain_as_uri(key.clone());
|
||||
|
||||
let lock = match self.pool.connecting(&key) {
|
||||
pool::Connecting::InProgress(waiter) => {
|
||||
trace!("connecting to {key:?} is already in progress, subscribing...");
|
||||
|
||||
match waiter.receive().await {
|
||||
Some(client) => return Ok(client),
|
||||
None => return Err("failed to establish connection for HTTP/3 request".into()),
|
||||
}
|
||||
}
|
||||
pool::Connecting::Acquired(lock) => lock,
|
||||
};
|
||||
trace!("connecting to {key:?}...");
|
||||
let (driver, tx) = self.connector.connect(dest).await?;
|
||||
trace!("saving new pooled connection to {key:?}");
|
||||
Ok(self.pool.new_connection(lock, driver, tx))
|
||||
}
|
||||
|
||||
async fn send_request(
|
||||
mut self,
|
||||
key: Key,
|
||||
req: Request<Body>,
|
||||
) -> Result<Response<ResponseBody>, Error> {
|
||||
let mut pooled = match self.get_pooled_client(key).await {
|
||||
Ok(client) => client,
|
||||
Err(e) => return Err(error::request(e)),
|
||||
};
|
||||
pooled
|
||||
.send_request(req)
|
||||
.await
|
||||
.map_err(|e| Error::new(Kind::Request, Some(e)))
|
||||
}
|
||||
|
||||
pub fn request(&self, mut req: Request<Body>) -> H3ResponseFuture {
|
||||
let pool_key = match pool::extract_domain(req.uri_mut()) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
return H3ResponseFuture {
|
||||
inner: SyncWrapper::new(Box::pin(future::ready(Err(e)))),
|
||||
}
|
||||
}
|
||||
};
|
||||
H3ResponseFuture {
|
||||
inner: SyncWrapper::new(Box::pin(self.clone().send_request(pool_key, req))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Service<Request<Body>> for H3Client {
|
||||
type Response = Response<ResponseBody>;
|
||||
type Error = Error;
|
||||
type Future = H3ResponseFuture;
|
||||
|
||||
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Request<Body>) -> Self::Future {
|
||||
self.request(req)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct H3ResponseFuture {
|
||||
inner: SyncWrapper<Pin<Box<dyn Future<Output = Result<Response<ResponseBody>, Error>> + Send>>>,
|
||||
}
|
||||
|
||||
impl Future for H3ResponseFuture {
|
||||
type Output = Result<Response<ResponseBody>, Error>;
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
self.inner.get_mut().as_mut().poll(cx)
|
||||
}
|
||||
}
|
||||
+405
@@ -0,0 +1,405 @@
|
||||
use bytes::Bytes;
|
||||
use std::collections::HashMap;
|
||||
use std::future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::mpsc::{Receiver, TryRecvError};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::{oneshot, watch};
|
||||
use tokio::time::Instant;
|
||||
|
||||
use crate::async_impl::body::ResponseBody;
|
||||
use crate::error::{BoxError, Error, Kind};
|
||||
use crate::Body;
|
||||
use bytes::Buf;
|
||||
use h3::client::SendRequest;
|
||||
use h3_quinn::{Connection, OpenStreams};
|
||||
use http::uri::{Authority, Scheme};
|
||||
use http::{Request, Response, Uri};
|
||||
use log::{error, trace};
|
||||
|
||||
pub(super) type Key = (Scheme, Authority);
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Pool {
|
||||
inner: Arc<Mutex<PoolInner>>,
|
||||
}
|
||||
|
||||
struct ConnectingLockInner {
|
||||
key: Key,
|
||||
pool: Arc<Mutex<PoolInner>>,
|
||||
}
|
||||
|
||||
/// A lock that ensures only one HTTP/3 connection is established per host at a
|
||||
/// time. The lock is automatically released when dropped.
|
||||
pub struct ConnectingLock(Option<ConnectingLockInner>);
|
||||
|
||||
/// A waiter that allows subscribers to receive updates when a new connection is
|
||||
/// established or when the connection attempt fails. For example, when
|
||||
/// connection lock is dropped due to an error.
|
||||
pub struct ConnectingWaiter {
|
||||
receiver: watch::Receiver<Option<PoolClient>>,
|
||||
}
|
||||
|
||||
pub enum Connecting {
|
||||
/// A connection attempt is already in progress.
|
||||
/// You must subscribe to updates instead of initiating a new connection.
|
||||
InProgress(ConnectingWaiter),
|
||||
/// The connection lock has been acquired, allowing you to initiate a
|
||||
/// new connection.
|
||||
Acquired(ConnectingLock),
|
||||
}
|
||||
|
||||
impl ConnectingLock {
|
||||
fn new(key: Key, pool: Arc<Mutex<PoolInner>>) -> Self {
|
||||
Self(Some(ConnectingLockInner { key, pool }))
|
||||
}
|
||||
|
||||
/// Forget the lock and return corresponding Key
|
||||
fn forget(mut self) -> Key {
|
||||
// Unwrap is safe because the Option can be None only after dropping the
|
||||
// lock
|
||||
self.0.take().unwrap().key
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ConnectingLock {
|
||||
fn drop(&mut self) {
|
||||
if let Some(ConnectingLockInner { key, pool }) = self.0.take() {
|
||||
let mut pool = pool.lock().unwrap();
|
||||
pool.connecting.remove(&key);
|
||||
trace!("HTTP/3 connecting lock for {:?} is dropped", key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ConnectingWaiter {
|
||||
pub async fn receive(mut self) -> Option<PoolClient> {
|
||||
match self.receiver.wait_for(Option::is_some).await {
|
||||
// unwrap because we already checked that option is Some
|
||||
Ok(ok) => Some(ok.as_ref().unwrap().to_owned()),
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Pool {
|
||||
pub fn new(timeout: Option<Duration>) -> Self {
|
||||
Self {
|
||||
inner: Arc::new(Mutex::new(PoolInner {
|
||||
connecting: HashMap::new(),
|
||||
idle_conns: HashMap::new(),
|
||||
timeout,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
/// Acquire a connecting lock. This is to ensure that we have only one HTTP3
|
||||
/// connection per host.
|
||||
pub fn connecting(&self, key: &Key) -> Connecting {
|
||||
let mut inner = self.inner.lock().unwrap();
|
||||
|
||||
if let Some(sender) = inner.connecting.get(key) {
|
||||
Connecting::InProgress(ConnectingWaiter {
|
||||
receiver: sender.subscribe(),
|
||||
})
|
||||
} else {
|
||||
let (tx, _) = watch::channel(None);
|
||||
inner.connecting.insert(key.clone(), tx);
|
||||
Connecting::Acquired(ConnectingLock::new(key.clone(), Arc::clone(&self.inner)))
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
return None;
|
||||
}
|
||||
|
||||
if let Some(duration) = timeout {
|
||||
if Instant::now().saturating_duration_since(conn.idle_timeout) > duration {
|
||||
trace!("pooled connection expired");
|
||||
inner.idle_conns.remove(&key);
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inner
|
||||
.idle_conns
|
||||
.get_mut(&key)
|
||||
.and_then(|conn| Some(conn.pool()))
|
||||
}
|
||||
|
||||
pub fn new_connection(
|
||||
&mut self,
|
||||
lock: ConnectingLock,
|
||||
mut driver: h3::client::Connection<Connection, Bytes>,
|
||||
tx: SendRequest<OpenStreams, Bytes>,
|
||||
) -> PoolClient {
|
||||
let (close_tx, close_rx) = std::sync::mpsc::channel();
|
||||
tokio::spawn(async move {
|
||||
let e = future::poll_fn(|cx| driver.poll_close(cx)).await;
|
||||
trace!("poll_close returned error {e:?}");
|
||||
close_tx.send(e).ok();
|
||||
});
|
||||
|
||||
let mut inner = self.inner.lock().unwrap();
|
||||
|
||||
// We clean up "connecting" here so we don't have to acquire the lock again.
|
||||
let key = lock.forget();
|
||||
let Some(notifier) = inner.connecting.remove(&key) else {
|
||||
unreachable!("there should be one connecting lock at a time");
|
||||
};
|
||||
let client = PoolClient::new(tx);
|
||||
|
||||
// Send the client to all our awaiters
|
||||
let pool_client = if let Err(watch::error::SendError(Some(unsent_client))) =
|
||||
notifier.send(Some(client.clone()))
|
||||
{
|
||||
// If there are no awaiters, the client is returned to us. As a
|
||||
// micro optimisation, let's reuse it and avoid cloning.
|
||||
unsent_client
|
||||
} else {
|
||||
client.clone()
|
||||
};
|
||||
|
||||
let conn = PoolConnection::new(pool_client, close_rx);
|
||||
inner.insert(key, conn);
|
||||
|
||||
client
|
||||
}
|
||||
}
|
||||
|
||||
struct PoolInner {
|
||||
connecting: HashMap<Key, watch::Sender<Option<PoolClient>>>,
|
||||
idle_conns: HashMap<Key, PoolConnection>,
|
||||
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 {
|
||||
inner: SendRequest<OpenStreams, Bytes>,
|
||||
}
|
||||
|
||||
impl PoolClient {
|
||||
pub fn new(tx: SendRequest<OpenStreams, Bytes>) -> Self {
|
||||
Self { inner: tx }
|
||||
}
|
||||
|
||||
pub async fn send_request(
|
||||
&mut self,
|
||||
req: Request<Body>,
|
||||
) -> Result<Response<ResponseBody>, BoxError> {
|
||||
use hyper::body::Body as _;
|
||||
|
||||
let (head, mut req_body) = req.into_parts();
|
||||
let mut req = Request::from_parts(head, ());
|
||||
|
||||
if let Some(n) = req_body.size_hint().exact() {
|
||||
if n > 0 {
|
||||
req.headers_mut()
|
||||
.insert(http::header::CONTENT_LENGTH, n.into());
|
||||
}
|
||||
}
|
||||
|
||||
let (mut send, mut recv) = self.inner.send_request(req).await?.split();
|
||||
|
||||
let (tx, mut rx) = oneshot::channel::<Result<(), BoxError>>();
|
||||
tokio::spawn(async move {
|
||||
let mut req_body = Pin::new(&mut req_body);
|
||||
loop {
|
||||
match std::future::poll_fn(|cx| req_body.as_mut().poll_frame(cx)).await {
|
||||
Some(Ok(frame)) => {
|
||||
if let Ok(b) = frame.into_data() {
|
||||
if let Err(e) = send.send_data(Bytes::copy_from_slice(&b)).await {
|
||||
if is_stop_sending(&e) {
|
||||
let _ = tx.send(Ok(()));
|
||||
return;
|
||||
}
|
||||
if let Err(e) = tx.send(Err(e.into())) {
|
||||
error!("Failed to communicate send.send_data() error: {e:?}");
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Err(e)) => {
|
||||
if let Err(e) = tx.send(Err(e.into())) {
|
||||
error!("Failed to communicate req_body read error: {e:?}");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
|
||||
if let Err(e) = send.finish().await {
|
||||
if !is_stop_sending(&e) {
|
||||
if let Err(e) = tx.send(Err(e.into())) {
|
||||
error!("Failed to communicate send.finish read error: {e:?}");
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let _ = tx.send(Ok(()));
|
||||
});
|
||||
|
||||
tokio::select! {
|
||||
Ok(Err(e)) = &mut rx => Err(e),
|
||||
resp = recv.recv_response() => {
|
||||
let resp = resp?;
|
||||
let resp_body = crate::async_impl::body::boxed(Incoming::new(recv, resp.headers(), rx));
|
||||
Ok(resp.map(|_| resp_body))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PoolConnection {
|
||||
// This receives errors from polling h3 driver.
|
||||
close_rx: Receiver<h3::error::ConnectionError>,
|
||||
client: PoolClient,
|
||||
idle_timeout: Instant,
|
||||
}
|
||||
|
||||
impl PoolConnection {
|
||||
pub fn new(client: PoolClient, close_rx: Receiver<h3::error::ConnectionError>) -> Self {
|
||||
Self {
|
||||
close_rx,
|
||||
client,
|
||||
idle_timeout: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn pool(&mut self) -> PoolClient {
|
||||
self.idle_timeout = Instant::now();
|
||||
self.client.clone()
|
||||
}
|
||||
|
||||
pub fn is_invalid(&self) -> bool {
|
||||
match self.close_rx.try_recv() {
|
||||
Err(TryRecvError::Empty) => false,
|
||||
Err(TryRecvError::Disconnected) => true,
|
||||
Ok(_) => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Incoming<S, B> {
|
||||
inner: h3::client::RequestStream<S, B>,
|
||||
content_length: Option<u64>,
|
||||
send_rx: oneshot::Receiver<Result<(), BoxError>>,
|
||||
}
|
||||
|
||||
impl<S, B> Incoming<S, B> {
|
||||
fn new(
|
||||
stream: h3::client::RequestStream<S, B>,
|
||||
headers: &http::header::HeaderMap,
|
||||
send_rx: oneshot::Receiver<Result<(), BoxError>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
inner: stream,
|
||||
content_length: headers
|
||||
.get(http::header::CONTENT_LENGTH)
|
||||
.and_then(|h| h.to_str().ok())
|
||||
.and_then(|v| v.parse().ok()),
|
||||
send_rx,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, B> http_body::Body for Incoming<S, B>
|
||||
where
|
||||
S: h3::quic::RecvStream,
|
||||
{
|
||||
type Data = Bytes;
|
||||
type Error = crate::error::Error;
|
||||
|
||||
fn poll_frame(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context,
|
||||
) -> Poll<Option<Result<hyper::body::Frame<Self::Data>, Self::Error>>> {
|
||||
if let Ok(Err(e)) = self.send_rx.try_recv() {
|
||||
return Poll::Ready(Some(Err(crate::error::body(e))));
|
||||
}
|
||||
|
||||
match futures_core::ready!(self.inner.poll_recv_data(cx)) {
|
||||
Ok(Some(mut b)) => Poll::Ready(Some(Ok(hyper::body::Frame::data(
|
||||
b.copy_to_bytes(b.remaining()),
|
||||
)))),
|
||||
Ok(None) => Poll::Ready(None),
|
||||
Err(e) => Poll::Ready(Some(Err(crate::error::body(e)))),
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> hyper::body::SizeHint {
|
||||
if let Some(content_length) = self.content_length {
|
||||
hyper::body::SizeHint::with_exact(content_length)
|
||||
} else {
|
||||
hyper::body::SizeHint::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)) => {
|
||||
let scheme_str = scheme.as_str();
|
||||
if scheme_str != "https" && scheme_str != "h3" {
|
||||
return Err(Error::new(
|
||||
Kind::Request,
|
||||
Some(Box::new(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
format!(
|
||||
"HTTP/3 only supports 'https' or 'h3' schemes, got: {}",
|
||||
scheme_str
|
||||
),
|
||||
))),
|
||||
));
|
||||
}
|
||||
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")
|
||||
}
|
||||
|
||||
/// Indicates the remote requested the peer to stop sending data without error.
|
||||
fn is_stop_sending(e: &h3::error::StreamError) -> bool {
|
||||
matches!(
|
||||
e,
|
||||
h3::error::StreamError::RemoteTerminate {
|
||||
code: h3::error::Code::H3_NO_ERROR,
|
||||
..
|
||||
}
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user