alloy_transport_http/
reqwest_transport.rs

1use crate::{Http, HttpConnect};
2use alloy_json_rpc::{RequestPacket, ResponsePacket};
3use alloy_transport::{
4    utils::guess_local_url, BoxTransport, TransportConnect, TransportError, TransportErrorKind,
5    TransportFut, TransportResult,
6};
7use std::task;
8use tower::Service;
9use tracing::{debug, debug_span, trace, Instrument};
10use url::Url;
11
12/// Rexported from [`reqwest`].
13pub use reqwest::Client;
14
15/// An [`Http`] transport using [`reqwest`].
16pub type ReqwestTransport = Http<Client>;
17
18/// Connection details for a [`ReqwestTransport`].
19pub type ReqwestConnect = HttpConnect<ReqwestTransport>;
20
21impl TransportConnect for ReqwestConnect {
22    fn is_local(&self) -> bool {
23        guess_local_url(self.url.as_str())
24    }
25
26    async fn get_transport(&self) -> Result<BoxTransport, TransportError> {
27        Ok(BoxTransport::new(Http::with_client(Client::new(), self.url.clone())))
28    }
29}
30
31impl Http<Client> {
32    /// Create a new [`Http`] transport.
33    pub fn new(url: Url) -> Self {
34        Self { client: Default::default(), url }
35    }
36
37    async fn do_reqwest(self, req: RequestPacket) -> TransportResult<ResponsePacket> {
38        let resp = self
39            .client
40            .post(self.url)
41            .json(&req)
42            .headers(req.headers())
43            .send()
44            .await
45            .map_err(TransportErrorKind::custom)?;
46        let status = resp.status();
47
48        debug!(%status, "received response from server");
49
50        // Unpack data from the response body. We do this regardless of
51        // the status code, as we want to return the error in the body
52        // if there is one.
53        let body = resp.bytes().await.map_err(TransportErrorKind::custom)?;
54
55        debug!(bytes = body.len(), "retrieved response body. Use `trace` for full body");
56        trace!(body = %String::from_utf8_lossy(&body), "response body");
57
58        if !status.is_success() {
59            return Err(TransportErrorKind::http_error(
60                status.as_u16(),
61                String::from_utf8_lossy(&body).into_owned(),
62            ));
63        }
64
65        // Deserialize a Box<RawValue> from the body. If deserialization fails, return
66        // the body as a string in the error. The conversion to String
67        // is lossy and may not cover all the bytes in the body.
68        serde_json::from_slice(&body)
69            .map_err(|err| TransportError::deser_err(err, String::from_utf8_lossy(&body)))
70    }
71}
72
73impl Service<RequestPacket> for Http<reqwest::Client> {
74    type Response = ResponsePacket;
75    type Error = TransportError;
76    type Future = TransportFut<'static>;
77
78    #[inline]
79    fn poll_ready(&mut self, _cx: &mut task::Context<'_>) -> task::Poll<Result<(), Self::Error>> {
80        // `reqwest` always returns `Ok(())`.
81        task::Poll::Ready(Ok(()))
82    }
83
84    #[inline]
85    fn call(&mut self, req: RequestPacket) -> Self::Future {
86        let this = self.clone();
87        let span = debug_span!("ReqwestTransport", url = %this.url);
88        Box::pin(this.do_reqwest(req).instrument(span))
89    }
90}