Skip to main content

apple_web_service_isahc_client/
lib.rs

1pub use isahc;
2
3//
4//
5//
6use std::{io, time::Duration};
7
8pub use apple_web_service_client::Client;
9use apple_web_service_client::{async_trait, Body, Request, Response};
10use isahc::{config::Configurable, AsyncReadResponseExt, HttpClient};
11
12pub struct IsahcClient {
13    http_client: HttpClient,
14}
15
16impl IsahcClient {
17    pub fn new() -> Result<Self, isahc::Error> {
18        Ok(Self::with(
19            HttpClient::builder()
20                .timeout(Duration::from_secs(5))
21                .connect_timeout(Duration::from_secs(5))
22                .build()?,
23        ))
24    }
25
26    pub fn with(http_client: HttpClient) -> Self {
27        Self { http_client }
28    }
29}
30
31#[async_trait]
32impl Client for IsahcClient {
33    async fn respond(&self, request: Request<Body>) -> io::Result<Response<Body>> {
34        let req_uri = request.uri().to_owned();
35        let req_body_len = request.body().len();
36
37        let resp = self.http_client.send_async(request).await?;
38        let (head, body) = resp.into_parts();
39
40        let mut body_buf = Vec::with_capacity(body.len().unwrap_or_else(|| {
41            if req_uri.to_string().contains("verifyReceipt") {
42                req_body_len as u64 * 2
43            } else {
44                4 * 1024
45            }
46        }) as usize);
47
48        let mut resp = Response::from_parts(head, body);
49        resp.copy_to(&mut body_buf).await?;
50
51        let (head, _) = resp.into_parts();
52        let resp = Response::from_parts(head, body_buf);
53
54        Ok(resp)
55    }
56}