dropbox_sdk/
async_client_trait.rs

1//! Everything needed to implement your async HTTP client.
2
3use std::future::{Future, ready};
4use std::sync::Arc;
5use bytes::Bytes;
6use futures::AsyncRead;
7pub use crate::client_trait_common::{HttpRequest, TeamSelect};
8use crate::Error;
9
10/// The base HTTP asynchronous client trait.
11pub trait HttpClient: Sync {
12    /// The concrete type of request supported by the client.
13    type Request: HttpRequest + Send;
14
15    /// Make a HTTP request.
16    fn execute(
17        &self,
18        request: Self::Request,
19        body: Bytes,
20    ) -> impl Future<Output = Result<HttpRequestResultRaw, Error>> + Send;
21
22    /// Create a new request instance for the given URL. It should be a POST request.
23    fn new_request(&self, url: &str) -> Self::Request;
24
25    /// Attempt to update the current authentication token. The previously fetched token is given
26    /// as a way to avoid repeat updates in case of a race. If the update is successful, return
27    /// `true` and the current request will be retried with a newly-fetched token. Return `false` if
28    /// authentication is not supported, or return an error if the update operation fails.
29    fn update_token(
30        &self,
31        _old_token: Arc<String>,
32    ) -> impl Future<Output = Result<bool, Error>> + Send {
33        ready(Ok(false))
34    }
35
36    /// The client's current authentication token, if any.
37    fn token(&self) -> Option<Arc<String>> {
38        None
39    }
40
41    /// The currently set path root, if any.
42    fn path_root(&self) -> Option<&str> {
43        None
44    }
45
46    /// The alternate user or team context currently set, if any.
47    fn team_select(&self) -> Option<&TeamSelect> {
48        None
49    }
50
51    /// This should only be implemented by (or called on) the blanket impl for sync HTTP clients
52    /// implemented in this module.
53    ///
54    /// It's necessary because
55    ///   * there's no efficient way to implement an async client which takes a request body slice
56    ///     (making a Bytes involves a copy)
57    ///   * there IS a way to do it for sync clients
58    ///   * the signature of the sync upload routes takes the body this way
59    ///   * we don't want to break compatibility
60    ///
61    /// Only the sync routes take a body arg this way, and this logic only gets invoked for those,
62    /// so only the sync HTTP client wrapper needs to implement it.
63    #[doc(hidden)]
64    #[cfg(feature = "sync_routes")]
65    fn execute_borrowed_body(
66        &self,
67        _request: Self::Request,
68        _body_slice: &[u8],
69    ) -> impl Future<Output = Result<HttpRequestResultRaw, Error>> + Send {
70        unimplemented!();
71        #[allow(unreachable_code)] // otherwise it complains that `()` is not a future.
72        async move { unimplemented!() }
73    }
74}
75
76/// The raw response from the server, including an async streaming response body.
77pub struct HttpRequestResultRaw {
78    /// HTTP response code.
79    pub status: u16,
80
81    /// The value of the `Dropbox-API-Result` header, if present.
82    pub result_header: Option<String>,
83
84    /// The value of the `Content-Length` header, if present.
85    pub content_length: Option<u64>,
86
87    /// The response body stream.
88    pub body: Box<dyn AsyncRead + Send + Unpin>,
89}
90
91/// The response from the server, parsed into a given type, including a body stream if it is from
92/// a Download style request.
93pub struct HttpRequestResult<T> {
94    /// The API result, parsed into the given type.
95    pub result: T,
96
97    /// The value of the `Content-Length` header in the response, if any. Only expected to not be
98    /// `None` if `body` is also not `None`.
99    pub content_length: Option<u64>,
100
101    /// The response body stream, if any. Only expected to not be `None` for
102    /// [`Style::Download`](crate::client_trait_common::Style::Download) endpoints.
103    pub body: Option<Box<dyn AsyncRead + Unpin + Send>>,
104}
105
106/// Blanket implementation of the async interface for all sync clients.
107/// This is necessary because all the machinery is actually implemented in terms of the async
108/// client.
109#[cfg(feature = "sync_routes")]
110impl<T: crate::client_trait::HttpClient + Sync> HttpClient for T {
111    type Request = T::Request;
112
113    async fn execute(&self, request: Self::Request, body: Bytes)
114        -> Result<HttpRequestResultRaw, Error>
115    {
116        self.execute_borrowed_body(request, &body).await
117    }
118
119    async fn execute_borrowed_body(&self, request: Self::Request, body_slice: &[u8])
120        -> Result<HttpRequestResultRaw, Error>
121    {
122        self.execute(request, body_slice).map(|r| {
123            HttpRequestResultRaw {
124                status: r.status,
125                result_header: r.result_header,
126                content_length: r.content_length,
127                body: Box::new(SyncReadAdapter { inner: r.body }),
128            }
129        })
130    }
131
132    fn new_request(&self, url: &str) -> Self::Request {
133        self.new_request(url)
134    }
135
136    fn update_token(&self, old_token: Arc<String>)
137        -> impl Future<Output=Result<bool, Error>> + Send
138    {
139        ready(self.update_token(old_token))
140    }
141
142    fn token(&self) -> Option<Arc<String>> {
143        self.token()
144    }
145
146    fn path_root(&self) -> Option<&str> {
147        self.path_root()
148    }
149
150    fn team_select(&self) -> Option<&TeamSelect> {
151        self.team_select()
152    }
153}
154
155/// Marker trait to indicate that a HTTP client supports unauthenticated routes.
156pub trait NoauthClient: HttpClient {}
157
158/// Marker trait to indicate that a HTTP client supports User authentication.
159/// Team authentication works by adding a `Authorization: Bearer <TOKEN>` header.
160pub trait UserAuthClient: HttpClient {}
161
162/// Marker trait to indicate that a HTTP client supports Team authentication.
163/// Team authentication works by adding a `Authorization: Bearer <TOKEN>` header, and optionally a
164/// `Dropbox-API-Select-Admin` or `Dropbox-API-Select-User` header.
165pub trait TeamAuthClient: HttpClient {}
166
167/// Marker trait to indicate that a HTTP client supports App authentication.
168/// App authentication works by adding a `Authorization: Basic <base64(APP_KEY:APP_SECRET)>` header
169/// to the HTTP request.
170pub trait AppAuthClient: HttpClient {}
171
172// blanket impls to convert the sync marker traits to the async ones:
173#[cfg(feature = "sync_routes")]
174impl<T: crate::client_trait::NoauthClient + Sync> NoauthClient for T {}
175#[cfg(feature = "sync_routes")]
176impl<T: crate::client_trait::UserAuthClient + Sync> UserAuthClient for T {}
177#[cfg(feature = "sync_routes")]
178impl<T: crate::client_trait::TeamAuthClient + Sync> TeamAuthClient for T {}
179#[cfg(feature = "sync_routes")]
180impl<T: crate::client_trait::AppAuthClient + Sync> AppAuthClient for T {}
181
182#[cfg(feature = "sync_routes")]
183pub(crate) struct SyncReadAdapter {
184    pub inner: Box<dyn std::io::Read + Send>,
185}
186
187#[cfg(feature = "sync_routes")]
188impl AsyncRead for SyncReadAdapter {
189    fn poll_read(
190        mut self: std::pin::Pin<&mut Self>,
191        _cx: &mut std::task::Context<'_>,
192        buf: &mut [u8],
193    ) -> std::task::Poll<std::io::Result<usize>> {
194        std::task::Poll::Ready(std::io::Read::read(&mut self.inner, buf))
195    }
196
197    fn poll_read_vectored(
198        mut self: std::pin::Pin<&mut Self>,
199        _cx: &mut std::task::Context<'_>,
200        bufs: &mut [std::io::IoSliceMut<'_>],
201    ) -> std::task::Poll<std::io::Result<usize>> {
202        std::task::Poll::Ready(std::io::Read::read_vectored(&mut self.inner, bufs))
203    }
204}