1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
//! http-client implementation for isahc

#[cfg(feature = "unstable-config")]
use std::convert::TryFrom;

use async_std::io::BufReader;
#[cfg(feature = "unstable-config")]
use isahc::config::Configurable;
use isahc::{http, ResponseExt};

use crate::Config;

use super::{async_trait, Body, Error, HttpClient, Request, Response};

/// Curl-based HTTP Client.
#[derive(Debug)]
pub struct IsahcClient {
    client: isahc::HttpClient,
    config: Config,
}

impl Default for IsahcClient {
    fn default() -> Self {
        Self::new()
    }
}

impl IsahcClient {
    /// Create a new instance.
    pub fn new() -> Self {
        Self::from_client(isahc::HttpClient::new().unwrap())
    }

    /// Create from externally initialized and configured client.
    pub fn from_client(client: isahc::HttpClient) -> Self {
        Self {
            client,
            config: Config::default(),
        }
    }
}

#[async_trait]
impl HttpClient for IsahcClient {
    async fn send(&self, mut req: Request) -> Result<Response, Error> {
        let mut builder = http::Request::builder()
            .uri(req.url().as_str())
            .method(http::Method::from_bytes(req.method().to_string().as_bytes()).unwrap());

        for (name, value) in req.iter() {
            builder = builder.header(name.as_str(), value.as_str());
        }

        let body = req.take_body();
        let body = match body.len() {
            Some(len) => isahc::Body::from_reader_sized(body, len as u64),
            None => isahc::Body::from_reader(body),
        };

        let request = builder.body(body).unwrap();
        let res = self.client.send_async(request).await.map_err(Error::from)?;
        let maybe_metrics = res.metrics().cloned();
        let (parts, body) = res.into_parts();
        let body = Body::from_reader(BufReader::new(body), None);
        let mut response = http_types::Response::new(parts.status.as_u16());
        for (name, value) in &parts.headers {
            response.append_header(name.as_str(), value.to_str().unwrap());
        }

        if let Some(metrics) = maybe_metrics {
            response.ext_mut().insert(metrics);
        }

        response.set_body(body);
        Ok(response)
    }

    #[cfg_attr(feature = "docs", doc(cfg(feature = "unstable-config")))]
    #[cfg(feature = "unstable-config")]
    /// Override the existing configuration with new configuration.
    ///
    /// Config options may not impact existing connections.
    fn set_config(&mut self, config: Config) -> http_types::Result<()> {
        let mut builder = isahc::HttpClient::builder();

        if !config.http_keep_alive {
            builder = builder.connection_cache_size(0);
        }
        if config.tcp_no_delay {
            builder = builder.tcp_nodelay();
        }
        if let Some(timeout) = config.timeout {
            builder = builder.timeout(timeout);
        }

        self.client = builder.build()?;
        self.config = config;

        Ok(())
    }

    #[cfg_attr(feature = "docs", doc(cfg(feature = "unstable-config")))]
    #[cfg(feature = "unstable-config")]
    /// Get the current configuration.
    fn config(&self) -> &Config {
        &self.config
    }
}

#[cfg_attr(feature = "docs", doc(cfg(feature = "unstable-config")))]
#[cfg(feature = "unstable-config")]
impl TryFrom<Config> for IsahcClient {
    type Error = isahc::Error;

    fn try_from(config: Config) -> Result<Self, Self::Error> {
        let mut builder = isahc::HttpClient::builder();

        if !config.http_keep_alive {
            builder = builder.connection_cache_size(0);
        }
        if config.tcp_no_delay {
            builder = builder.tcp_nodelay();
        }
        if let Some(timeout) = config.timeout {
            builder = builder.timeout(timeout);
        }

        Ok(Self {
            client: builder.build()?,
            config,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_std::prelude::*;
    use async_std::task;
    use http_types::url::Url;
    use http_types::Result;
    use std::time::Duration;

    fn build_test_request(url: Url) -> Request {
        let mut req = Request::new(http_types::Method::Post, url);
        req.set_body("hello");
        req.append_header("test", "value");
        req
    }

    #[async_std::test]
    async fn basic_functionality() -> Result<()> {
        let port = portpicker::pick_unused_port().unwrap();
        let mut app = tide::new();
        app.at("/").all(|mut r: tide::Request<()>| async move {
            let mut response = tide::Response::new(http_types::StatusCode::Ok);
            response.set_body(r.body_bytes().await.unwrap());
            Ok(response)
        });

        let server = task::spawn(async move {
            app.listen(("localhost", port)).await?;
            Result::Ok(())
        });

        let client = task::spawn(async move {
            task::sleep(Duration::from_millis(100)).await;
            let request =
                build_test_request(Url::parse(&format!("http://localhost:{}/", port)).unwrap());
            let mut response: Response = IsahcClient::new().send(request).await?;
            assert_eq!(response.body_string().await.unwrap(), "hello");
            Ok(())
        });

        server.race(client).await?;

        Ok(())
    }
}