Skip to main content

tame_gcs/
response.rs

1use crate::error::{self, Error};
2
3pub trait ApiResponse<B>: Sized + TryFrom<http::Response<B>, Error = Error>
4where
5    B: AsRef<[u8]>,
6{
7    fn try_from_parts(resp: http::response::Response<B>) -> Result<Self, Error> {
8        if resp.status().is_success() {
9            Self::try_from(resp)
10        } else {
11            // If we get an error, but with a JSON payload, attempt to deserialize
12            // an ApiError from it, otherwise fallback to the simple HttpStatus
13            if let Some(ct) = resp
14                .headers()
15                .get(http::header::CONTENT_TYPE)
16                .and_then(|ct| ct.to_str().ok())
17            {
18                if ct.starts_with("application/json") {
19                    if let Ok(api_err) =
20                        serde_json::from_slice::<error::ApiError>(resp.body().as_ref())
21                    {
22                        return Err(Error::Api(api_err));
23                    }
24                }
25            }
26            Err(Error::from(resp.status()))
27        }
28    }
29}
30
31pub struct Response<T> {
32    body: bytes::BytesMut,
33    parts: http::response::Builder,
34    content_len: usize,
35
36    _response: std::marker::PhantomData<fn() -> T>,
37}
38
39impl<T> Response<T>
40where
41    T: ApiResponse<bytes::Bytes>,
42{
43    pub fn new(parts: http::response::Builder) -> Self {
44        let body = match parts
45            .headers_ref()
46            .and_then(crate::util::get_content_length)
47        {
48            Some(u) => bytes::BytesMut::with_capacity(u),
49            None => bytes::BytesMut::new(),
50        };
51
52        let content_len = body.capacity();
53
54        Self {
55            body,
56            parts,
57            content_len,
58            _response: Default::default(),
59        }
60    }
61
62    /// Try to get an [`http::Response`]
63    pub fn get_response(mut self) -> Result<http::Response<bytes::Bytes>, Error> {
64        if self.body.len() >= self.content_len {
65            let buf = self.body.split_to(self.content_len);
66            let response = self.parts.body(buf.freeze())?;
67            Ok(response)
68        } else {
69            // We need more data, it's possible in a streaming scenario they can
70            // call us again with more data
71            Err(Error::InsufficientData)
72        }
73    }
74
75    /// Try to parse all the data buffered so far into a response type.
76    pub fn parse(self) -> Result<T, Error> {
77        let response = self.get_response()?;
78        T::try_from_parts(response)
79    }
80}
81
82impl<T> std::io::Write for Response<T> {
83    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
84        self.body.extend_from_slice(buf);
85        Ok(buf.len())
86    }
87
88    fn flush(&mut self) -> std::io::Result<()> {
89        Ok(())
90    }
91}