Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/korp-map

crates/korp-map-wire/src/cache.rs

//! **HTTP caching of the HTTP door's replies**: a strong `ETag` and `Cache-Control`.
//!
//! A reply is a function of the server build, the region's `data_version` and the
//! query, so its tag is a hash of the three ([`tag_for`]): the build id
//! ([`ServerConfig::build_id`](crate::ServerConfig::build_id)), because another binary
//! (a new encoder, a dependency bump) may write other bytes for the same data and query;
//! the query as the server parsed it (numbers as numbers, the server's default `max`
//! applied), so two spellings of one query share a tag; and a new cut of the region
//! changes every tag of it. `/v1/regions` is tagged by the build and every region's
//! name, bbox and `data_version`. (A served file's tag is its sha256, [`crate::files`].)
//!
//! An encoded reply's tag carries its coding (`"<hash>-zstd"`): a strong tag names one
//! representation. `If-None-Match` is compared as RFC 9110 says (weakly), so any coding
//! of the same reply matches, and `*` matches any reply. A match is answered `304 Not
//! Modified` before the source is read.

use crate::source::Region;

/// FNV-1a, 64 bits. Stable across builds and platforms (unlike `std`'s hasher), which a
/// tag a client keeps for an hour needs.
fn fnv1a(bytes: impl IntoIterator<Item = u8>) -> u64 {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for b in bytes {
        h ^= u64::from(b);
        h = h.wrapping_mul(0x0100_0000_01b3);
    }
    h
}

/// [`fnv1a`] over `parts`, each followed by a 0 byte.
#[must_use]
pub fn fnv64(parts: &[&[u8]]) -> u64 {
    fnv1a(parts.iter().flat_map(|p| p.iter().copied().chain([0u8])))
}

/// The tag (without quotes) of the reply of server build `build` to `query` on a region
/// at `data_version`.
#[must_use]
pub fn tag_for(build: &str, data_version: &str, query: &str) -> String {
    format!(
        "{:016x}",
        fnv64(&[build.as_bytes(), data_version.as_bytes(), query.as_bytes()])
    )
}

/// The tag of server build `build`'s `/v1/regions` reply.
#[must_use]
pub fn regions_tag(build: &str, regions: &[Region]) -> String {
    let mut parts: Vec<Vec<u8>> = Vec::new();
    for r in regions {
        parts.push(r.name.as_bytes().to_vec());
        parts.push(format!("{:?}", r.bbox.to_array()).into_bytes());
        parts.push(r.data_version.as_bytes().to_vec());
    }
    let refs: Vec<&[u8]> = parts.iter().map(Vec::as_slice).collect();
    tag_for(build, "regions", &format!("{:016x}", fnv64(&refs)))
}

/// The `ETag` header value: `"<tag>"`, or `"<tag>-<coding>"` for an encoded reply.
#[must_use]
pub fn etag(tag: &str, coding: Option<&str>) -> String {
    match coding {
        Some(c) => format!("\"{tag}-{c}\""),
        None => format!("\"{tag}\""),
    }
}

/// The entity tag in `if_none_match` that matches `tag` (weak comparison: `W/` and a
/// coding suffix are ignored; `*` matches), as it was sent.
#[must_use]
pub fn matching<'a>(if_none_match: &'a str, tag: &str) -> Option<&'a str> {
    if_none_match.split(',').map(str::trim).find(|t| {
        if *t == "*" {
            return true;
        }
        let t = t.strip_prefix("W/").unwrap_or(t);
        let Some(inner) = t.strip_prefix('"').and_then(|t| t.strip_suffix('"')) else {
            return false;
        };
        let base = inner.split_once('-').map_or(inner, |(b, _)| b);
        base == tag
    })
}

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

    #[test]
    fn the_hash_is_fnv1a_and_separates_its_parts() {
        assert_eq!(
            fnv1a(*b"a"),
            0xaf63_dc4c_8601_ec8c,
            "the published FNV-1a 64 of \"a\""
        );
        assert_eq!(fnv64(&[b"a"]), fnv1a(*b"a\0"));
        assert_ne!(fnv64(&[b"ab", b"c"]), fnv64(&[b"a", b"bc"]));
        assert_eq!(tag_for("b", "v1", "q").len(), 16);
        assert_ne!(tag_for("b", "v1", "q"), tag_for("b", "v2", "q"));
        assert_ne!(tag_for("b", "v1", "q"), tag_for("b", "v1", "r"));
        assert_ne!(
            tag_for("b1", "v1", "q"),
            tag_for("b2", "v1", "q"),
            "another build, another tag"
        );
    }

    #[test]
    fn if_none_match_is_compared_weakly() {
        let t = tag_for("b", "v1", "q");
        assert_eq!(matching(&etag(&t, None), &t), Some(etag(&t, None).as_str()));
        let z = etag(&t, Some("zstd"));
        assert_eq!(matching(&z, &t), Some(z.as_str()));
        let list = format!("\"other\", W/{z}");
        assert_eq!(matching(&list, &t), Some(format!("W/{z}").as_str()));
        assert_eq!(matching("*", &t), Some("*"));
        assert_eq!(matching("\"other\"", &t), None);
        assert_eq!(
            matching(&t, &t),
            None,
            "an unquoted tag is not an entity tag"
        );
        assert_eq!(matching("", &t), None);
    }

    #[test]
    fn the_regions_tag_follows_every_data_version() {
        let r = |v: &str| Region {
            name: "sweden".into(),
            bbox: BBox::new(10.0, 55.0, 25.0, 70.0).unwrap(),
            data_version: v.into(),
        };
        assert_eq!(regions_tag("b", &[r("a")]), regions_tag("b", &[r("a")]));
        assert_ne!(regions_tag("b", &[r("a")]), regions_tag("b", &[r("b")]));
        assert_ne!(regions_tag("b", &[r("a")]), regions_tag("b", &[]));
        assert_ne!(regions_tag("b1", &[r("a")]), regions_tag("b2", &[r("a")]));
    }
}