http-query 0.1.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, HEADER_CONTENT_TYPE, MEDIA_TYPE_JSON};
use crate::error::{Error, Result};
use crate::response::Discovery;
use reqwest::{Body, Client as HttpClient, Method, Response, 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).
#[derive(Clone, Debug)]
pub struct Client {
    http: HttpClient,
    base_url: Option<Url>,
}

impl Client {
    /// Creates a client with a default [`reqwest::Client`].
    pub fn new() -> Self {
        Client {
            http: HttpClient::new(),
            base_url: None,
        }
    }

    /// Creates a client wrapping an existing [`reqwest::Client`].
    pub fn with_http_client(http: HttpClient) -> Self {
        Client {
            http,
            base_url: None,
        }
    }

    /// 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)
    }

    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.
    pub async fn query(
        &self,
        url: &str,
        content_type: &str,
        body: impl Into<Body>,
    ) -> Result<Response> {
        let target = self.resolve(url)?;
        let resp = self
            .http
            .request(query_method(), target)
            .header(HEADER_CONTENT_TYPE, content_type)
            .body(body)
            .send()
            .await?;
        Ok(resp)
    }

    /// 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());
        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()
    }
}

/// 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 })
    }
}