http-query 0.1.0

A client and server SDK for the HTTP QUERY method (RFC 10008).
Documentation
//! Cache-key helpers for QUERY responses.

use crate::consts::METHOD_QUERY;
use sha2::{Digest, Sha256};
use std::fmt::Write;

/// Computes a stable cache key for a QUERY request.
///
/// Unlike GET, a QUERY cache entry must be keyed on the request content in
/// addition to the method and URI (RFC 10008 ยง2.7), because the query travels
/// in the body. The returned value is the hex-encoded SHA-256 of those inputs.
pub fn cache_key(target_url: &str, content_type: &str, body: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(METHOD_QUERY.as_bytes());
    hasher.update([0]);
    hasher.update(target_url.as_bytes());
    hasher.update([0]);
    hasher.update(content_type.as_bytes());
    hasher.update([0]);
    hasher.update(body);

    let digest = hasher.finalize();
    let mut out = String::with_capacity(64);
    for byte in digest {
        let _ = write!(out, "{byte:02x}");
    }
    out
}

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

    #[test]
    fn depends_on_body_and_url() {
        let base = cache_key("https://example.org/s", "application/json", br#"{"q":"a"}"#);
        let same = cache_key("https://example.org/s", "application/json", br#"{"q":"a"}"#);
        let other_body = cache_key("https://example.org/s", "application/json", br#"{"q":"b"}"#);
        let other_url = cache_key("https://example.org/t", "application/json", br#"{"q":"a"}"#);

        assert_eq!(base, same);
        assert_ne!(base, other_body);
        assert_ne!(base, other_url);
        assert_eq!(base.len(), 64);
    }
}