1use 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#[derive(Clone, PartialEq, Eq, Hash)]
20pub struct DialTarget {
21 host: String,
22 port: u16,
23}
24
25impl DialTarget {
26 #[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 #[must_use]
37 pub fn host(&self) -> &str {
38 &self.host
39 }
40
41 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
59pub enum DialErrorKind {
60 Connection,
62 Timeout,
64 Authentication,
66 Rejected,
68 Other,
70}
71
72pub struct DialError {
78 kind: DialErrorKind,
79 message: String,
80 source: Option<Arc<dyn StdError + Send + Sync>>,
81}
82
83impl DialError {
84 #[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 #[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 #[must_use]
109 pub const fn kind(&self) -> DialErrorKind {
110 self.kind
111 }
112
113 #[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 .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
169pub trait DialStreamTrait: AsyncRead + AsyncWrite + Send + Unpin {}
171
172impl<T> DialStreamTrait for T where T: AsyncRead + AsyncWrite + Send + Unpin {}
173
174pub type DialStream = Box<dyn DialStreamTrait>;
176
177pub type DialFuture<'a> = Pin<Box<dyn Future<Output = Result<DialStream, DialError>> + Send + 'a>>;
179
180pub trait Dialer: Send + Sync + 'static {
186 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#[derive(Clone)]
201pub(crate) struct DialerConnector {
202 dialer: Arc<dyn Dialer>,
203}
204
205pub(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}