Skip to main content

http_query/
client.rs

1//! An async QUERY client built on [`reqwest`].
2
3use crate::consts::{query_method, DEFAULT_MAX_REDIRECTS, HEADER_CONTENT_TYPE, MEDIA_TYPE_JSON};
4use crate::error::{Error, Result};
5use crate::response::Discovery;
6use reqwest::redirect::Policy;
7use reqwest::{Client as HttpClient, Method, Response, StatusCode, Url};
8use serde::de::DeserializeOwned;
9use serde::Serialize;
10
11/// An async client for sending HTTP QUERY requests.
12///
13/// The client wraps a [`reqwest::Client`]; clone it freely (it is cheap and
14/// shares the underlying connection pool).
15///
16/// Redirects are handled per RFC 10008 §2.5: `301`, `302`, `307` and `308`
17/// re-issue the QUERY with its body, while `303` switches to `GET`. To make
18/// this possible the client built by [`Client::new`] disables reqwest's own
19/// redirect following.
20#[derive(Clone, Debug)]
21pub struct Client {
22    http: HttpClient,
23    base_url: Option<Url>,
24    max_redirects: usize,
25}
26
27impl Client {
28    /// Creates a client with a default [`reqwest::Client`] (redirects disabled
29    /// so QUERY redirects can be handled per RFC 10008 §2.5).
30    pub fn new() -> Self {
31        let http = HttpClient::builder()
32            .redirect(Policy::none())
33            .build()
34            .expect("building a default reqwest client should not fail");
35        Client {
36            http,
37            base_url: None,
38            max_redirects: DEFAULT_MAX_REDIRECTS,
39        }
40    }
41
42    /// Creates a client wrapping an existing [`reqwest::Client`].
43    ///
44    /// For RFC 10008 §2.5 redirect handling to work correctly, `http` must be
45    /// built with redirects disabled (`reqwest::redirect::Policy::none()`);
46    /// otherwise reqwest follows redirects itself and downgrades QUERY to GET.
47    pub fn with_http_client(http: HttpClient) -> Self {
48        Client {
49            http,
50            base_url: None,
51            max_redirects: DEFAULT_MAX_REDIRECTS,
52        }
53    }
54
55    /// Sets a base URL used to resolve relative request URLs.
56    pub fn with_base_url(mut self, base: &str) -> Result<Self> {
57        self.base_url = Some(Url::parse(base).map_err(|e| Error::Invalid(e.to_string()))?);
58        Ok(self)
59    }
60
61    /// Sets the maximum number of redirects to follow (default
62    /// [`DEFAULT_MAX_REDIRECTS`]).
63    pub fn with_max_redirects(mut self, max: usize) -> Self {
64        self.max_redirects = max;
65        self
66    }
67
68    fn resolve(&self, url: &str) -> Result<Url> {
69        match &self.base_url {
70            Some(base) => base.join(url).map_err(|e| Error::Invalid(e.to_string())),
71            None => Url::parse(url).map_err(|e| Error::Invalid(e.to_string())),
72        }
73    }
74
75    /// Sends a QUERY request with a raw body and the given content type.
76    ///
77    /// Redirects are followed per RFC 10008 §2.5: `301`/`302`/`307`/`308`
78    /// re-issue the QUERY with the body; `303` switches to `GET`. Exceeding
79    /// [`Client::with_max_redirects`] returns [`Error::TooManyRedirects`].
80    pub async fn query(
81        &self,
82        url: &str,
83        content_type: &str,
84        body: impl Into<Vec<u8>>,
85    ) -> Result<Response> {
86        let mut target = self.resolve(url)?;
87        let body = body.into();
88        let mut method = query_method();
89        let mut send_body = true;
90        let mut redirects = 0usize;
91
92        loop {
93            let mut builder = self.http.request(method.clone(), target.clone());
94            if send_body {
95                builder = builder
96                    .header(HEADER_CONTENT_TYPE, content_type)
97                    .body(body.clone());
98            }
99            let resp = builder.send().await?;
100
101            if !is_redirect(resp.status()) {
102                return Ok(resp);
103            }
104
105            let location = resp
106                .headers()
107                .get(reqwest::header::LOCATION)
108                .and_then(|value| value.to_str().ok())
109                .filter(|value| !value.is_empty())
110                .map(|value| value.to_string());
111            let location = match location {
112                Some(location) => location,
113                None => return Ok(resp),
114            };
115
116            if redirects >= self.max_redirects {
117                return Err(Error::TooManyRedirects);
118            }
119            redirects += 1;
120
121            target = target
122                .join(&location)
123                .map_err(|e| Error::Invalid(e.to_string()))?;
124
125            // RFC 10008 §2.5: only 303 changes the method (to GET) and drops the
126            // body; 301/302/307/308 preserve the QUERY method and re-send it.
127            if resp.status() == StatusCode::SEE_OTHER {
128                method = Method::GET;
129                send_body = false;
130            }
131        }
132    }
133
134    /// Sends a QUERY request with a string body.
135    pub async fn query_string(
136        &self,
137        url: &str,
138        content_type: &str,
139        body: impl Into<String>,
140    ) -> Result<Response> {
141        self.query(url, content_type, body.into()).await
142    }
143
144    /// Sends a QUERY request whose body is `value` serialized to JSON.
145    pub async fn query_json<T: Serialize + ?Sized>(
146        &self,
147        url: &str,
148        value: &T,
149    ) -> Result<Response> {
150        let body = serde_json::to_vec(value)?;
151        self.query(url, MEDIA_TYPE_JSON, body).await
152    }
153
154    /// Sends a JSON QUERY request and decodes a JSON response, validating the
155    /// status first.
156    pub async fn query_json_into<T, R>(&self, url: &str, value: &T) -> Result<R>
157    where
158        T: Serialize + ?Sized,
159        R: DeserializeOwned,
160    {
161        let resp = self.query_json(url, value).await?;
162        let resp = check_status(resp).await?;
163        Ok(resp.json::<R>().await?)
164    }
165
166    /// Issues an `OPTIONS` request and reports QUERY support from the response.
167    pub async fn options(&self, url: &str) -> Result<Discovery> {
168        let target = self.resolve(url)?;
169        let resp = self.http.request(Method::OPTIONS, target).send().await?;
170        Ok(Discovery::from_headers(resp.headers()))
171    }
172
173    /// Performs a GET on the stored result of the query (`Content-Location`,
174    /// RFC 10008 §2.3), resolved against the original request URL.
175    pub async fn fetch_result(&self, resp: &Response) -> Result<Response> {
176        self.fetch_relative(
177            resp,
178            crate::consts::HEADER_CONTENT_LOCATION,
179            Error::NoQueryResult,
180        )
181        .await
182    }
183
184    /// Performs a GET on the equivalent resource (`Location`, RFC 10008 §2.4),
185    /// which re-runs the query without resending the body.
186    pub async fn fetch_equivalent(&self, resp: &Response) -> Result<Response> {
187        self.fetch_relative(
188            resp,
189            crate::consts::HEADER_LOCATION,
190            Error::NoEquivalentResource,
191        )
192        .await
193    }
194
195    async fn fetch_relative(
196        &self,
197        resp: &Response,
198        header: &str,
199        missing: Error,
200    ) -> Result<Response> {
201        let reference = resp
202            .headers()
203            .get(header)
204            .and_then(|value| value.to_str().ok())
205            .filter(|value| !value.is_empty());
206        let reference = match reference {
207            Some(reference) => reference,
208            None => return Err(missing),
209        };
210        let target = resp
211            .url()
212            .join(reference)
213            .map_err(|e| Error::Invalid(e.to_string()))?;
214        Ok(self.http.get(target).send().await?)
215    }
216}
217
218impl Default for Client {
219    fn default() -> Self {
220        Self::new()
221    }
222}
223
224fn is_redirect(status: StatusCode) -> bool {
225    matches!(
226        status,
227        StatusCode::MOVED_PERMANENTLY
228            | StatusCode::FOUND
229            | StatusCode::SEE_OTHER
230            | StatusCode::TEMPORARY_REDIRECT
231            | StatusCode::PERMANENT_REDIRECT
232    )
233}
234
235/// Validates a response's status, turning a non-2xx status into
236/// [`Error::Status`] (consuming the body for the error message).
237pub async fn check_status(resp: Response) -> Result<Response> {
238    if resp.status().is_success() {
239        Ok(resp)
240    } else {
241        let status = resp.status().as_u16();
242        let body = resp.text().await.unwrap_or_default();
243        Err(Error::Status { status, body })
244    }
245}