http-query 0.2.0

A client and server SDK for the HTTP QUERY method (RFC 10008).
Documentation
//! Interpreting QUERY-relevant response metadata.

use crate::accept_query::{matches_media_range, parse_accept_query};
use crate::consts::*;
use http::HeaderMap;

/// QUERY-relevant metadata extracted from a response.
#[derive(Debug, Clone)]
pub struct ResponseInfo {
    /// The response status code.
    pub status: u16,
    /// The `Content-Location` field: the stored result of the query (§2.3).
    pub content_location: Option<String>,
    /// The `Location` field: the equivalent resource (§2.4).
    pub location: Option<String>,
    /// The advertised query media ranges, parsed from `Accept-Query`.
    pub accept_query: Vec<String>,
    /// The methods advertised in `Allow`.
    pub allow: Vec<String>,
}

impl ResponseInfo {
    /// Extracts QUERY-relevant metadata from a status code and header map.
    pub fn from_headers(status: u16, headers: &HeaderMap) -> Self {
        ResponseInfo {
            status,
            content_location: header_str(headers, HEADER_CONTENT_LOCATION),
            location: header_str(headers, HEADER_LOCATION),
            accept_query: parse_accept_query(header_values(headers, HEADER_ACCEPT_QUERY)),
            allow: parse_header_list(header_values(headers, HEADER_ALLOW)),
        }
    }

    /// The URI of the stored result of the query just run (`Content-Location`,
    /// RFC 10008 §2.3). A GET to this URI retrieves that result.
    pub fn result_uri(&self) -> Option<&str> {
        self.content_location.as_deref()
    }

    /// The URI of the equivalent resource for the query (`Location`, RFC 10008
    /// §2.4). A GET to this URI re-runs the query for a current result.
    pub fn equivalent_resource_uri(&self) -> Option<&str> {
        self.location.as_deref()
    }
}

/// A server's advertised support for the QUERY method.
#[derive(Debug, Clone)]
pub struct Discovery {
    /// Whether the response advertises QUERY (via `Allow` or `Accept-Query`).
    pub supports_query: bool,
    /// The methods advertised in `Allow`.
    pub allow: Vec<String>,
    /// The advertised query media ranges, parsed from `Accept-Query`.
    pub accept_query: Vec<String>,
}

impl Discovery {
    /// Interprets a response's header fields as QUERY support metadata.
    pub fn from_headers(headers: &HeaderMap) -> Self {
        let allow = parse_header_list(header_values(headers, HEADER_ALLOW));
        let accept_query = parse_accept_query(header_values(headers, HEADER_ACCEPT_QUERY));
        let supports_query =
            !accept_query.is_empty() || allow.iter().any(|method| method == METHOD_QUERY);
        Discovery {
            supports_query,
            allow,
            accept_query,
        }
    }

    /// Reports whether `media_type` is covered by the advertised `Accept-Query`
    /// media ranges, honoring the `*/*` and `type/*` wildcards.
    pub fn accepts_media_type(&self, media_type: &str) -> bool {
        self.accept_query
            .iter()
            .any(|range| matches_media_range(range, media_type))
    }
}

/// Reports whether a response advertises support for the QUERY method.
pub fn supports_query(headers: &HeaderMap) -> bool {
    Discovery::from_headers(headers).supports_query
}

fn header_str(headers: &HeaderMap, name: &str) -> Option<String> {
    headers
        .get(name)
        .and_then(|value| value.to_str().ok())
        .map(|s| s.to_string())
}

fn header_values<'a>(headers: &'a HeaderMap, name: &'a str) -> impl Iterator<Item = String> + 'a {
    headers
        .get_all(name)
        .iter()
        .filter_map(|value| value.to_str().ok().map(|s| s.to_string()))
}

fn parse_header_list<I: IntoIterator<Item = String>>(values: I) -> Vec<String> {
    let mut items = Vec::new();
    for value in values {
        for part in value.split(',') {
            let trimmed = part.trim();
            if !trimmed.is_empty() {
                items.push(trimmed.to_string());
            }
        }
    }
    items
}

#[cfg(test)]
mod tests {
    use super::*;
    use http::HeaderValue;

    fn headers(pairs: &[(&'static str, &str)]) -> HeaderMap {
        let mut map = HeaderMap::new();
        for (name, value) in pairs {
            map.append(*name, HeaderValue::from_str(value).unwrap());
        }
        map
    }

    #[test]
    fn discovery_from_allow_and_accept_query() {
        let h = headers(&[
            (HEADER_ALLOW, "GET, QUERY, OPTIONS"),
            (
                HEADER_ACCEPT_QUERY,
                r#""application/jsonpath", application/sql"#,
            ),
        ]);
        let d = Discovery::from_headers(&h);
        assert!(d.supports_query);
        assert!(d.accepts_media_type("application/sql"));
        assert!(d.accepts_media_type("application/jsonpath"));
        assert!(!d.accepts_media_type("text/plain"));
    }

    #[test]
    fn result_vs_equivalent() {
        let h = headers(&[
            (HEADER_CONTENT_LOCATION, "/results/17"),
            (HEADER_LOCATION, "/queries/42"),
        ]);
        let info = ResponseInfo::from_headers(200, &h);
        assert_eq!(info.result_uri(), Some("/results/17"));
        assert_eq!(info.equivalent_resource_uri(), Some("/queries/42"));
    }
}