Skip to main content

http_query/
response.rs

1//! Interpreting QUERY-relevant response metadata.
2
3use crate::accept_query::{matches_media_range, parse_accept_query};
4use crate::consts::*;
5use http::HeaderMap;
6
7/// QUERY-relevant metadata extracted from a response.
8#[derive(Debug, Clone)]
9pub struct ResponseInfo {
10    /// The response status code.
11    pub status: u16,
12    /// The `Content-Location` field: the stored result of the query (§2.3).
13    pub content_location: Option<String>,
14    /// The `Location` field: the equivalent resource (§2.4).
15    pub location: Option<String>,
16    /// The advertised query media ranges, parsed from `Accept-Query`.
17    pub accept_query: Vec<String>,
18    /// The methods advertised in `Allow`.
19    pub allow: Vec<String>,
20}
21
22impl ResponseInfo {
23    /// Extracts QUERY-relevant metadata from a status code and header map.
24    pub fn from_headers(status: u16, headers: &HeaderMap) -> Self {
25        ResponseInfo {
26            status,
27            content_location: header_str(headers, HEADER_CONTENT_LOCATION),
28            location: header_str(headers, HEADER_LOCATION),
29            accept_query: parse_accept_query(header_values(headers, HEADER_ACCEPT_QUERY)),
30            allow: parse_header_list(header_values(headers, HEADER_ALLOW)),
31        }
32    }
33
34    /// The URI of the stored result of the query just run (`Content-Location`,
35    /// RFC 10008 §2.3). A GET to this URI retrieves that result.
36    pub fn result_uri(&self) -> Option<&str> {
37        self.content_location.as_deref()
38    }
39
40    /// The URI of the equivalent resource for the query (`Location`, RFC 10008
41    /// §2.4). A GET to this URI re-runs the query for a current result.
42    pub fn equivalent_resource_uri(&self) -> Option<&str> {
43        self.location.as_deref()
44    }
45}
46
47/// A server's advertised support for the QUERY method.
48#[derive(Debug, Clone)]
49pub struct Discovery {
50    /// Whether the response advertises QUERY (via `Allow` or `Accept-Query`).
51    pub supports_query: bool,
52    /// The methods advertised in `Allow`.
53    pub allow: Vec<String>,
54    /// The advertised query media ranges, parsed from `Accept-Query`.
55    pub accept_query: Vec<String>,
56}
57
58impl Discovery {
59    /// Interprets a response's header fields as QUERY support metadata.
60    pub fn from_headers(headers: &HeaderMap) -> Self {
61        let allow = parse_header_list(header_values(headers, HEADER_ALLOW));
62        let accept_query = parse_accept_query(header_values(headers, HEADER_ACCEPT_QUERY));
63        let supports_query =
64            !accept_query.is_empty() || allow.iter().any(|method| method == METHOD_QUERY);
65        Discovery {
66            supports_query,
67            allow,
68            accept_query,
69        }
70    }
71
72    /// Reports whether `media_type` is covered by the advertised `Accept-Query`
73    /// media ranges, honoring the `*/*` and `type/*` wildcards.
74    pub fn accepts_media_type(&self, media_type: &str) -> bool {
75        self.accept_query
76            .iter()
77            .any(|range| matches_media_range(range, media_type))
78    }
79}
80
81/// Reports whether a response advertises support for the QUERY method.
82pub fn supports_query(headers: &HeaderMap) -> bool {
83    Discovery::from_headers(headers).supports_query
84}
85
86fn header_str(headers: &HeaderMap, name: &str) -> Option<String> {
87    headers
88        .get(name)
89        .and_then(|value| value.to_str().ok())
90        .map(|s| s.to_string())
91}
92
93fn header_values<'a>(headers: &'a HeaderMap, name: &'a str) -> impl Iterator<Item = String> + 'a {
94    headers
95        .get_all(name)
96        .iter()
97        .filter_map(|value| value.to_str().ok().map(|s| s.to_string()))
98}
99
100fn parse_header_list<I: IntoIterator<Item = String>>(values: I) -> Vec<String> {
101    let mut items = Vec::new();
102    for value in values {
103        for part in value.split(',') {
104            let trimmed = part.trim();
105            if !trimmed.is_empty() {
106                items.push(trimmed.to_string());
107            }
108        }
109    }
110    items
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116    use http::HeaderValue;
117
118    fn headers(pairs: &[(&'static str, &str)]) -> HeaderMap {
119        let mut map = HeaderMap::new();
120        for (name, value) in pairs {
121            map.append(*name, HeaderValue::from_str(value).unwrap());
122        }
123        map
124    }
125
126    #[test]
127    fn discovery_from_allow_and_accept_query() {
128        let h = headers(&[
129            (HEADER_ALLOW, "GET, QUERY, OPTIONS"),
130            (
131                HEADER_ACCEPT_QUERY,
132                r#""application/jsonpath", application/sql"#,
133            ),
134        ]);
135        let d = Discovery::from_headers(&h);
136        assert!(d.supports_query);
137        assert!(d.accepts_media_type("application/sql"));
138        assert!(d.accepts_media_type("application/jsonpath"));
139        assert!(!d.accepts_media_type("text/plain"));
140    }
141
142    #[test]
143    fn result_vs_equivalent() {
144        let h = headers(&[
145            (HEADER_CONTENT_LOCATION, "/results/17"),
146            (HEADER_LOCATION, "/queries/42"),
147        ]);
148        let info = ResponseInfo::from_headers(200, &h);
149        assert_eq!(info.result_uri(), Some("/results/17"));
150        assert_eq!(info.equivalent_resource_uri(), Some("/queries/42"));
151    }
152}