http-query 0.2.0

A client and server SDK for the HTTP QUERY method (RFC 10008).
Documentation
//! An async QUERY client built on [`reqwest`].

use crate::consts::{query_method, DEFAULT_MAX_REDIRECTS, HEADER_CONTENT_TYPE, MEDIA_TYPE_JSON};
use crate::error::{Error, Result};
use crate::response::Discovery;
use reqwest::redirect::Policy;
use reqwest::{Client as HttpClient, Method, Response, StatusCode, Url};
use serde::de::DeserializeOwned;
use serde::Serialize;

/// An async client for sending HTTP QUERY requests.
///
/// The client wraps a [`reqwest::Client`]; clone it freely (it is cheap and
/// shares the underlying connection pool).
///
/// Redirects are handled per RFC 10008 §2.5: `301`, `302`, `307` and `308`
/// re-issue the QUERY with its body, while `303` switches to `GET`. To make
/// this possible the client built by [`Client::new`] disables reqwest's own
/// redirect following.
#[derive(Clone, Debug)]
pub struct Client {
    http: HttpClient,
    base_url: Option<Url>,
    max_redirects: usize,
}

impl Client {
    /// Creates a client with a default [`reqwest::Client`] (redirects disabled
    /// so QUERY redirects can be handled per RFC 10008 §2.5).
    pub fn new() -> Self {
        let http = HttpClient::builder()
            .redirect(Policy::none())
            .build()
            .expect("building a default reqwest client should not fail");
        Client {
            http,
            base_url: None,
            max_redirects: DEFAULT_MAX_REDIRECTS,
        }
    }

    /// Creates a client wrapping an existing [`reqwest::Client`].
    ///
    /// For RFC 10008 §2.5 redirect handling to work correctly, `http` must be
    /// built with redirects disabled (`reqwest::redirect::Policy::none()`);
    /// otherwise reqwest follows redirects itself and downgrades QUERY to GET.
    pub fn with_http_client(http: HttpClient) -> Self {
        Client {
            http,
            base_url: None,
            max_redirects: DEFAULT_MAX_REDIRECTS,
        }
    }

    /// Sets a base URL used to resolve relative request URLs.
    pub fn with_base_url(mut self, base: &str) -> Result<Self> {
        self.base_url = Some(Url::parse(base).map_err(|e| Error::Invalid(e.to_string()))?);
        Ok(self)
    }

    /// Sets the maximum number of redirects to follow (default
    /// [`DEFAULT_MAX_REDIRECTS`]).
    pub fn with_max_redirects(mut self, max: usize) -> Self {
        self.max_redirects = max;
        self
    }

    fn resolve(&self, url: &str) -> Result<Url> {
        match &self.base_url {
            Some(base) => base.join(url).map_err(|e| Error::Invalid(e.to_string())),
            None => Url::parse(url).map_err(|e| Error::Invalid(e.to_string())),
        }
    }

    /// Sends a QUERY request with a raw body and the given content type.
    ///
    /// Redirects are followed per RFC 10008 §2.5: `301`/`302`/`307`/`308`
    /// re-issue the QUERY with the body; `303` switches to `GET`. Exceeding
    /// [`Client::with_max_redirects`] returns [`Error::TooManyRedirects`].
    pub async fn query(
        &self,
        url: &str,
        content_type: &str,
        body: impl Into<Vec<u8>>,
    ) -> Result<Response> {
        let mut target = self.resolve(url)?;
        let body = body.into();
        let mut method = query_method();
        let mut send_body = true;
        let mut redirects = 0usize;

        loop {
            let mut builder = self.http.request(method.clone(), target.clone());
            if send_body {
                builder = builder
                    .header(HEADER_CONTENT_TYPE, content_type)
                    .body(body.clone());
            }
            let resp = builder.send().await?;

            if !is_redirect(resp.status()) {
                return Ok(resp);
            }

            let location = resp
                .headers()
                .get(reqwest::header::LOCATION)
                .and_then(|value| value.to_str().ok())
                .filter(|value| !value.is_empty())
                .map(|value| value.to_string());
            let location = match location {
                Some(location) => location,
                None => return Ok(resp),
            };

            if redirects >= self.max_redirects {
                return Err(Error::TooManyRedirects);
            }
            redirects += 1;

            target = target
                .join(&location)
                .map_err(|e| Error::Invalid(e.to_string()))?;

            // RFC 10008 §2.5: only 303 changes the method (to GET) and drops the
            // body; 301/302/307/308 preserve the QUERY method and re-send it.
            if resp.status() == StatusCode::SEE_OTHER {
                method = Method::GET;
                send_body = false;
            }
        }
    }

    /// Sends a QUERY request with a string body.
    pub async fn query_string(
        &self,
        url: &str,
        content_type: &str,
        body: impl Into<String>,
    ) -> Result<Response> {
        self.query(url, content_type, body.into()).await
    }

    /// Sends a QUERY request whose body is `value` serialized to JSON.
    pub async fn query_json<T: Serialize + ?Sized>(
        &self,
        url: &str,
        value: &T,
    ) -> Result<Response> {
        let body = serde_json::to_vec(value)?;
        self.query(url, MEDIA_TYPE_JSON, body).await
    }

    /// Sends a JSON QUERY request and decodes a JSON response, validating the
    /// status first.
    pub async fn query_json_into<T, R>(&self, url: &str, value: &T) -> Result<R>
    where
        T: Serialize + ?Sized,
        R: DeserializeOwned,
    {
        let resp = self.query_json(url, value).await?;
        let resp = check_status(resp).await?;
        Ok(resp.json::<R>().await?)
    }

    /// Issues an `OPTIONS` request and reports QUERY support from the response.
    pub async fn options(&self, url: &str) -> Result<Discovery> {
        let target = self.resolve(url)?;
        let resp = self.http.request(Method::OPTIONS, target).send().await?;
        Ok(Discovery::from_headers(resp.headers()))
    }

    /// Performs a GET on the stored result of the query (`Content-Location`,
    /// RFC 10008 §2.3), resolved against the original request URL.
    pub async fn fetch_result(&self, resp: &Response) -> Result<Response> {
        self.fetch_relative(
            resp,
            crate::consts::HEADER_CONTENT_LOCATION,
            Error::NoQueryResult,
        )
        .await
    }

    /// Performs a GET on the equivalent resource (`Location`, RFC 10008 §2.4),
    /// which re-runs the query without resending the body.
    pub async fn fetch_equivalent(&self, resp: &Response) -> Result<Response> {
        self.fetch_relative(
            resp,
            crate::consts::HEADER_LOCATION,
            Error::NoEquivalentResource,
        )
        .await
    }

    async fn fetch_relative(
        &self,
        resp: &Response,
        header: &str,
        missing: Error,
    ) -> Result<Response> {
        let reference = resp
            .headers()
            .get(header)
            .and_then(|value| value.to_str().ok())
            .filter(|value| !value.is_empty());
        let reference = match reference {
            Some(reference) => reference,
            None => return Err(missing),
        };
        let target = resp
            .url()
            .join(reference)
            .map_err(|e| Error::Invalid(e.to_string()))?;
        Ok(self.http.get(target).send().await?)
    }
}

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

fn is_redirect(status: StatusCode) -> bool {
    matches!(
        status,
        StatusCode::MOVED_PERMANENTLY
            | StatusCode::FOUND
            | StatusCode::SEE_OTHER
            | StatusCode::TEMPORARY_REDIRECT
            | StatusCode::PERMANENT_REDIRECT
    )
}

/// Validates a response's status, turning a non-2xx status into
/// [`Error::Status`] (consuming the body for the error message).
pub async fn check_status(resp: Response) -> Result<Response> {
    if resp.status().is_success() {
        Ok(resp)
    } else {
        let status = resp.status().as_u16();
        let body = resp.text().await.unwrap_or_default();
        Err(Error::Status { status, body })
    }
}