Skip to main content

eggfetch_core/transport/
dialer.rs

1//! Caller-supplied byte-stream dialing for native Rust consumers.
2
3use std::error::Error as StdError;
4use std::fmt;
5use std::future::Future;
6use std::pin::Pin;
7use std::sync::Arc;
8
9use http::Uri;
10use hyper_util::client::legacy::connect::{Connected, Connection};
11use hyper_util::rt::TokioIo;
12use tokio::io::{AsyncRead, AsyncWrite};
13use tower_service::Service;
14
15/// The logical destination supplied to a [`Dialer`].
16///
17/// This contains only the URL's logical host and effective port. It never
18/// contains credentials, headers, paths, query strings, or request bodies.
19#[derive(Clone, PartialEq, Eq, Hash)]
20pub struct DialTarget {
21    host: String,
22    port: u16,
23}
24
25impl DialTarget {
26    /// Create a logical dialing target.
27    #[must_use]
28    pub fn new(host: impl Into<String>, port: u16) -> Self {
29        Self {
30            host: host.into(),
31            port,
32        }
33    }
34
35    /// Return the logical host or IP literal.
36    #[must_use]
37    pub fn host(&self) -> &str {
38        &self.host
39    }
40
41    /// Return the effective HTTP or HTTPS port.
42    #[must_use]
43    pub const fn port(&self) -> u16 {
44        self.port
45    }
46}
47
48impl fmt::Debug for DialTarget {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        f.debug_struct("DialTarget")
51            .field("host", &self.host)
52            .field("port", &self.port)
53            .finish()
54    }
55}
56
57/// Broad category for an application-owned dialing failure.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
59pub enum DialErrorKind {
60    /// The route could not reach the logical destination.
61    Connection,
62    /// Establishment exceeded the caller's route deadline or was cancelled.
63    Timeout,
64    /// The caller-owned transport rejected its credentials or authorization.
65    Authentication,
66    /// The route or destination was explicitly rejected.
67    Rejected,
68    /// A failure that does not fit another category.
69    Other,
70}
71
72/// Error returned by a caller-supplied [`Dialer`].
73///
74/// The source is retained so an embedding application can recover its own
75/// transport error. Callers should ensure their error's `Display` and `Debug`
76/// implementations do not expose secrets.
77pub struct DialError {
78    kind: DialErrorKind,
79    message: String,
80    source: Option<Arc<dyn StdError + Send + Sync>>,
81}
82
83impl DialError {
84    /// Construct an error without a nested source.
85    #[must_use]
86    pub fn new(kind: DialErrorKind, message: impl Into<String>) -> Self {
87        Self {
88            kind,
89            message: message.into(),
90            source: None,
91        }
92    }
93
94    /// Construct an error while retaining the caller's source error.
95    #[must_use]
96    pub fn with_source<E>(kind: DialErrorKind, message: impl Into<String>, source: E) -> Self
97    where
98        E: StdError + Send + Sync + 'static,
99    {
100        Self {
101            kind,
102            message: message.into(),
103            source: Some(Arc::new(source)),
104        }
105    }
106
107    /// Return the broad failure category.
108    #[must_use]
109    pub const fn kind(&self) -> DialErrorKind {
110        self.kind
111    }
112
113    /// Return the caller-provided safe description.
114    #[must_use]
115    pub fn message(&self) -> &str {
116        &self.message
117    }
118}
119
120impl Clone for DialError {
121    fn clone(&self) -> Self {
122        Self {
123            kind: self.kind,
124            message: self.message.clone(),
125            source: self.source.clone(),
126        }
127    }
128}
129
130impl fmt::Debug for DialError {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        f.debug_struct("DialError")
133            .field("kind", &self.kind)
134            .field("message", &self.message)
135            // The source remains available through `Error::source`, but its
136            // Debug implementation belongs to the embedding application and
137            // may contain secrets or unbounded transport state.
138            .field("source", &self.source.as_ref().map(|_| "<redacted>"))
139            .finish()
140    }
141}
142
143impl fmt::Display for DialError {
144    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145        write!(f, "{}: {}", self.kind, self.message)
146    }
147}
148
149impl StdError for DialError {
150    fn source(&self) -> Option<&(dyn StdError + 'static)> {
151        self.source
152            .as_deref()
153            .map(|source| source as &(dyn StdError + 'static))
154    }
155}
156
157impl fmt::Display for DialErrorKind {
158    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159        f.write_str(match self {
160            Self::Connection => "connection",
161            Self::Timeout => "timeout",
162            Self::Authentication => "authentication",
163            Self::Rejected => "rejected",
164            Self::Other => "transport",
165        })
166    }
167}
168
169/// Object-safe stream returned by a [`Dialer`].
170pub trait DialStreamTrait: AsyncRead + AsyncWrite + Send + Unpin {}
171
172impl<T> DialStreamTrait for T where T: AsyncRead + AsyncWrite + Send + Unpin {}
173
174/// Erased Tokio-compatible stream supplied by a caller-owned route.
175pub type DialStream = Box<dyn DialStreamTrait>;
176
177/// Boxed future returned by [`Dialer::dial`].
178pub type DialFuture<'a> = Pin<Box<dyn Future<Output = Result<DialStream, DialError>> + Send + 'a>>;
179
180/// Supplies the raw byte stream used to reach a logical HTTP(S) origin.
181///
182/// Eggfetch remains responsible for HTTP framing, destination TLS, SNI and
183/// certificate verification. A dialer controls only the physical route to
184/// the supplied logical host and port.
185pub trait Dialer: Send + Sync + 'static {
186    /// Establish a raw stream for the logical destination.
187    fn dial(&self, target: DialTarget) -> DialFuture<'_>;
188}
189
190impl<T> Dialer for Arc<T>
191where
192    T: Dialer + ?Sized,
193{
194    fn dial(&self, target: DialTarget) -> DialFuture<'_> {
195        self.as_ref().dial(target)
196    }
197}
198
199/// Crate-internal Hyper adapter for the public [`Dialer`] contract.
200#[derive(Clone)]
201pub(crate) struct DialerConnector {
202    dialer: Arc<dyn Dialer>,
203}
204
205/// Hyper-runtime adapter around the caller's Tokio stream.
206pub(crate) struct DialerConnection {
207    inner: TokioIo<DialStream>,
208}
209
210impl DialerConnection {
211    fn new(stream: DialStream) -> Self {
212        Self {
213            inner: TokioIo::new(stream),
214        }
215    }
216}
217
218impl hyper::rt::Read for DialerConnection {
219    fn poll_read(
220        mut self: Pin<&mut Self>,
221        cx: &mut std::task::Context<'_>,
222        buf: hyper::rt::ReadBufCursor<'_>,
223    ) -> std::task::Poll<std::io::Result<()>> {
224        Pin::new(&mut self.inner).poll_read(cx, buf)
225    }
226}
227
228impl hyper::rt::Write for DialerConnection {
229    fn poll_write(
230        mut self: Pin<&mut Self>,
231        cx: &mut std::task::Context<'_>,
232        buf: &[u8],
233    ) -> std::task::Poll<std::io::Result<usize>> {
234        Pin::new(&mut self.inner).poll_write(cx, buf)
235    }
236
237    fn poll_flush(
238        mut self: Pin<&mut Self>,
239        cx: &mut std::task::Context<'_>,
240    ) -> std::task::Poll<std::io::Result<()>> {
241        Pin::new(&mut self.inner).poll_flush(cx)
242    }
243
244    fn poll_shutdown(
245        mut self: Pin<&mut Self>,
246        cx: &mut std::task::Context<'_>,
247    ) -> std::task::Poll<std::io::Result<()>> {
248        Pin::new(&mut self.inner).poll_shutdown(cx)
249    }
250
251    fn is_write_vectored(&self) -> bool {
252        self.inner.is_write_vectored()
253    }
254
255    fn poll_write_vectored(
256        mut self: Pin<&mut Self>,
257        cx: &mut std::task::Context<'_>,
258        bufs: &[std::io::IoSlice<'_>],
259    ) -> std::task::Poll<std::io::Result<usize>> {
260        Pin::new(&mut self.inner).poll_write_vectored(cx, bufs)
261    }
262}
263
264impl Connection for DialerConnection {
265    fn connected(&self) -> Connected {
266        Connected::new()
267    }
268}
269
270impl DialerConnector {
271    pub(crate) fn new(dialer: Arc<dyn Dialer>) -> Self {
272        Self { dialer }
273    }
274}
275
276impl Service<Uri> for DialerConnector {
277    type Response = DialerConnection;
278    type Error = Box<dyn StdError + Send + Sync>;
279    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
280
281    fn poll_ready(
282        &mut self,
283        _cx: &mut std::task::Context<'_>,
284    ) -> std::task::Poll<Result<(), Self::Error>> {
285        std::task::Poll::Ready(Ok(()))
286    }
287
288    fn call(&mut self, dst: Uri) -> Self::Future {
289        let host = dst.host().map(str::to_owned);
290        let port = dst.port_u16().or_else(|| match dst.scheme_str() {
291            Some("https") => Some(443),
292            Some("http") => Some(80),
293            _ => None,
294        });
295        let dialer = self.dialer.clone();
296        Box::pin(async move {
297            let host = host.ok_or_else(|| {
298                Box::new(crate::error::Error::Connect(
299                    "custom dialer target has no host".into(),
300                )) as Box<dyn StdError + Send + Sync>
301            })?;
302            let port = port.ok_or_else(|| {
303                Box::new(crate::error::Error::Connect(
304                    "custom dialer target has no effective port".into(),
305                )) as Box<dyn StdError + Send + Sync>
306            })?;
307            dialer
308                .dial(DialTarget::new(host, port))
309                .await
310                .map(DialerConnection::new)
311                .map_err(|error| {
312                    Box::new(crate::error::Error::CustomTransport(Arc::new(error)))
313                        as Box<dyn StdError + Send + Sync>
314                })
315        })
316    }
317}
318
319#[cfg(test)]
320mod tests {
321    use super::*;
322
323    #[derive(Debug)]
324    struct SecretSource;
325
326    impl fmt::Display for SecretSource {
327        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
328            f.write_str("secret-source")
329        }
330    }
331
332    impl StdError for SecretSource {}
333
334    #[test]
335    fn debug_does_not_delegate_to_caller_source() {
336        let error = DialError::with_source(
337            DialErrorKind::Connection,
338            "safe route description",
339            SecretSource,
340        );
341        let debug = format!("{error:?}");
342        assert!(debug.contains("safe route description"));
343        assert!(debug.contains("<redacted>"));
344        assert!(!debug.contains("SecretSource"));
345        assert!(StdError::source(&error).is_some());
346    }
347}