Skip to main content

http_query/
cache.rs

1//! Cache-key helpers for QUERY responses.
2
3use crate::consts::METHOD_QUERY;
4use sha2::{Digest, Sha256};
5use std::fmt::Write;
6
7/// Computes a stable cache key for a QUERY request.
8///
9/// Unlike GET, a QUERY cache entry must be keyed on the request content in
10/// addition to the method and URI (RFC 10008 ยง2.7), because the query travels
11/// in the body. The returned value is the hex-encoded SHA-256 of those inputs.
12pub fn cache_key(target_url: &str, content_type: &str, body: &[u8]) -> String {
13    let mut hasher = Sha256::new();
14    hasher.update(METHOD_QUERY.as_bytes());
15    hasher.update([0]);
16    hasher.update(target_url.as_bytes());
17    hasher.update([0]);
18    hasher.update(content_type.as_bytes());
19    hasher.update([0]);
20    hasher.update(body);
21
22    let digest = hasher.finalize();
23    let mut out = String::with_capacity(64);
24    for byte in digest {
25        let _ = write!(out, "{byte:02x}");
26    }
27    out
28}
29
30#[cfg(test)]
31mod tests {
32    use super::*;
33
34    #[test]
35    fn depends_on_body_and_url() {
36        let base = cache_key("https://example.org/s", "application/json", br#"{"q":"a"}"#);
37        let same = cache_key("https://example.org/s", "application/json", br#"{"q":"a"}"#);
38        let other_body = cache_key("https://example.org/s", "application/json", br#"{"q":"b"}"#);
39        let other_url = cache_key("https://example.org/t", "application/json", br#"{"q":"a"}"#);
40
41        assert_eq!(base, same);
42        assert_ne!(base, other_body);
43        assert_ne!(base, other_url);
44        assert_eq!(base.len(), 64);
45    }
46}