Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Typed errors #58

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 18 additions & 32 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,9 @@ use hyper::{client::connect::HttpConnector, service::Service, Uri};
use tokio::io::{AsyncRead, AsyncWrite};
use tokio_tls::TlsConnector;

use crate::error::HttpsConnectorError;
use crate::stream::MaybeHttpsStream;

type BoxError = Box<dyn std::error::Error + Send + Sync>;

/// A Connector for the `https` scheme.
#[derive(Clone)]
pub struct HttpsConnector<T> {
Expand Down Expand Up @@ -85,16 +84,16 @@ where
T: Service<Uri>,
T::Response: AsyncRead + AsyncWrite + Send + Unpin,
T::Future: Send + 'static,
T::Error: Into<BoxError>,
T::Error: Send + Sync + 'static,
{
type Response = MaybeHttpsStream<T::Response>;
type Error = BoxError;
type Future = HttpsConnecting<T::Response>;
type Error = HttpsConnectorError<T::Error>;
type Future = HttpsConnecting<T::Response, Self::Error>;

fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
match self.http.poll_ready(cx) {
Poll::Ready(Ok(())) => Poll::Ready(Ok(())),
Poll::Ready(Err(e)) => Poll::Ready(Err(e.into())),
Poll::Ready(Err(e)) => Poll::Ready(Err(HttpsConnectorError::HttpConnector(e))),
Poll::Pending => Poll::Pending,
}
}
Expand All @@ -103,20 +102,21 @@ where
let is_https = dst.scheme_str() == Some("https");
// Early abort if HTTPS is forced but can't be used
if !is_https && self.force_https {
return err(ForceHttpsButUriNotHttps.into());
return err(HttpsConnectorError::ForceHttpsButUriNotHttps);
}

let host = dst.host()
.unwrap_or("")
.to_owned();
let host = dst.host().unwrap_or("").to_owned();
let connecting = self.http.call(dst);
let tls = self.tls.clone();
let fut = async move {
let tcp = connecting.await.map_err(Into::into)?;
let tcp = connecting
.await
.map_err(HttpsConnectorError::HttpConnector)?;
let maybe = if is_https {
let tls = tls
.connect(&host, tcp)
.await?;
.await
.map_err(|e| HttpsConnectorError::NativeTls(e))?;
MaybeHttpsStream::Https(tls)
} else {
MaybeHttpsStream::Http(tcp)
Expand All @@ -127,39 +127,25 @@ where
}
}

fn err<T>(e: BoxError) -> HttpsConnecting<T> {
fn err<T, E: Send + 'static>(e: E) -> HttpsConnecting<T, E> {
HttpsConnecting(Box::pin(async { Err(e) }))
}

type BoxedFut<T> =
Pin<Box<dyn Future<Output = Result<MaybeHttpsStream<T>, BoxError>> + Send>>;
type BoxedFut<T, E> = Pin<Box<dyn Future<Output = Result<MaybeHttpsStream<T>, E>> + Send>>;

/// A Future representing work to connect to a URL, and a TLS handshake.
pub struct HttpsConnecting<T>(BoxedFut<T>);
pub struct HttpsConnecting<T, E>(BoxedFut<T, E>);

impl<T: AsyncRead + AsyncWrite + Unpin> Future for HttpsConnecting<T> {
type Output = Result<MaybeHttpsStream<T>, BoxError>;
impl<T: AsyncRead + AsyncWrite + Unpin, E> Future for HttpsConnecting<T, E> {
type Output = Result<MaybeHttpsStream<T>, E>;

fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut self.0).poll(cx)
}
}

impl<T> fmt::Debug for HttpsConnecting<T> {
impl<T, E> fmt::Debug for HttpsConnecting<T, E> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("HttpsConnecting")
}
}

// ===== Custom Errors =====

#[derive(Debug)]
struct ForceHttpsButUriNotHttps;

impl fmt::Display for ForceHttpsButUriNotHttps {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("https required but URI was not https")
}
}

impl std::error::Error for ForceHttpsButUriNotHttps {}
55 changes: 55 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/// HttpsConnectorError represents a HttpsConnector error.
pub enum HttpsConnectorError<E: Send> {
/// An https:// URI was provided when the force_https option was on.
ForceHttpsButUriNotHttps,
/// Underlying HttpConnector failed when setting up an HTTP connection.
HttpConnector(E),
/// `native_tls` failed when setting up a TLS connection.
NativeTls(native_tls::Error),

#[doc(hidden)]
__Nonexhaustive,
}

impl<E: Send + std::fmt::Debug> std::fmt::Debug for HttpsConnectorError<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
HttpsConnectorError::ForceHttpsButUriNotHttps => {
f.write_str("HttpsConnectorError::ForceHttpsButUriNotHttps")
}
HttpsConnectorError::HttpConnector(err) => f
.debug_tuple("HttpsConnectorError::HttpConnector")
.field(err)
.finish(),
HttpsConnectorError::NativeTls(err) => f
.debug_tuple("HttpsConnectorError::NativeTls")
.field(err)
.finish(),
HttpsConnectorError::__Nonexhaustive => unimplemented!(),
}
}
}

impl<E: Send + std::fmt::Display> std::fmt::Display for HttpsConnectorError<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
HttpsConnectorError::ForceHttpsButUriNotHttps => {
write!(f, "https required but URI was not https")
}
HttpsConnectorError::HttpConnector(err) => write!(f, "http connector error: {}", err),
HttpsConnectorError::NativeTls(err) => write!(f, "native tls error: {}", err),
HttpsConnectorError::__Nonexhaustive => unimplemented!(),
}
}
}

impl<E: Send + std::error::Error + 'static> std::error::Error for HttpsConnectorError<E> {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
HttpsConnectorError::ForceHttpsButUriNotHttps => None,
HttpsConnectorError::HttpConnector(err) => Some(err),
HttpsConnectorError::NativeTls(err) => Some(err),
HttpsConnectorError::__Nonexhaustive => unimplemented!(),
}
}
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@
pub extern crate native_tls;

pub use client::{HttpsConnecting, HttpsConnector};
pub use error::HttpsConnectorError;
pub use stream::{MaybeHttpsStream, TlsStream};

mod client;
mod error;
mod stream;