crates/korp-map-wire/tests/cache.rs
//! **HTTP caching on the HTTP door**: every Arrow and JSON reply carries a strong `ETag`
//! and `Cache-Control`; the same request with `If-None-Match` is answered `304`; the tag
//! follows the region's `data_version` and the query as parsed.
mod common;
use std::sync::{Arc, Mutex};
use bytes::Bytes;
use common::*;
use http_body_util::{BodyExt, Empty};
use hyper_util::client::legacy::Client;
use hyper_util::rt::TokioExecutor;
use korp_map_wire::{
GeocodeQuery, GeocodeReply, MapQuery, MapReply, MapSource, Region, RevGeocodeQuery,
RevGeocodeReply, ServerConfig, WireError,
};
async fn get_h(url: &str, headers: &[(&str, &str)]) -> Reply {
let client = Client::builder(TokioExecutor::new()).build_http::<Empty<Bytes>>();
let mut req = http::Request::get(url);
for (k, v) in headers {
req = req.header(*k, *v);
}
let res = client
.request(req.body(Empty::new()).unwrap())
.await
.unwrap();
let status = res.status().as_u16();
let headers = res.headers().clone();
let body = res.into_body().collect().await.unwrap().to_bytes();
Reply {
status,
headers,
body,
}
}
/// The address server's source, with a `data_version` the test can change.
struct Versioned {
inner: AddressBook,
version: Mutex<String>,
}
impl MapSource for Versioned {
fn regions(&self) -> Result<Vec<Region>, WireError> {
let v = self.version.lock().unwrap().clone();
Ok(self
.inner
.regions()?
.into_iter()
.map(|r| Region {
data_version: v.clone(),
..r
})
.collect())
}
fn query(&self, q: &MapQuery) -> Result<MapReply, WireError> {
self.inner.query(q)
}
fn geocode(&self, q: &GeocodeQuery) -> Result<GeocodeReply, WireError> {
self.inner.geocode(q)
}
fn revgeocode(&self, q: &RevGeocodeQuery) -> Result<RevGeocodeReply, WireError> {
self.inner.revgeocode(q)
}
}
struct Server {
base: String,
source: Arc<Versioned>,
_tmp: tempfile::TempDir,
}
impl Server {
async fn start(cfg: ServerConfig) -> Self {
let tmp = tempfile::tempdir().unwrap();
let dir = write_region(tmp.path());
let source = Arc::new(Versioned {
inner: AddressBook {
map: korp_map_wire::FileSource::open_dir(&dir).unwrap(),
book: addresses(),
},
version: Mutex::new("cut-1".into()),
});
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let s = source.clone();
tokio::spawn(async move { korp_map_wire::serve(listener, s, cfg).await });
Self {
base,
source,
_tmp: tmp,
}
}
fn url(&self, p: &str) -> String {
format!("{}{p}", self.base)
}
}
const PATHS: [&str; 5] = [
"/v1/map/lines?region=testland&bbox=10,55,20,65&lod=15",
"/v1/map/points?region=testland&bbox=11,55,14.2,57.1&lod=12&max=9",
"/v1/geocode?region=testland&q=storgatan+5+uppsala",
"/v1/revgeocode?region=testland&lon=14.5&lat=61",
"/v1/regions",
];
#[tokio::test(flavor = "multi_thread")]
async fn a_reply_is_tagged_and_the_same_request_with_its_tag_is_304() {
let s = Server::start(ServerConfig::default()).await;
for p in PATHS {
let first = get_h(&s.url(p), &[]).await;
assert_eq!(first.status, 200, "{p}");
let etag = first
.header("etag")
.unwrap_or_else(|| panic!("{p}: no etag"))
.to_string();
assert!(
etag.starts_with('"') && etag.ends_with('"') && etag.len() == 18,
"{p}: {etag}"
);
let max_age = if p == "/v1/regions" { 60 } else { 3600 };
assert_eq!(
first.header("cache-control"),
Some(format!("public, max-age={max_age}").as_str()),
"{p}"
);
let again = get_h(&s.url(p), &[]).await;
assert_eq!(again.header("etag"), Some(etag.as_str()), "{p}: stable");
assert_eq!(again.body, first.body);
let nm = get_h(&s.url(p), &[("if-none-match", &etag)]).await;
assert_eq!(nm.status, 304, "{p}");
assert!(nm.body.is_empty(), "{p}");
assert_eq!(nm.header("etag"), Some(etag.as_str()), "{p}");
assert_eq!(
nm.header("cache-control"),
first.header("cache-control"),
"{p}"
);
assert_eq!(nm.header("vary"), Some("accept-encoding"), "{p}");
assert_eq!(nm.header("access-control-allow-origin"), Some("*"), "{p}");
let other = get_h(&s.url(p), &[("if-none-match", "\"0000000000000000\"")]).await;
assert_eq!(other.status, 200, "{p}: another tag is not a match");
let star = get_h(&s.url(p), &[("if-none-match", "*")]).await;
assert_eq!(star.status, 304, "{p}: * matches");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_new_data_version_changes_every_tag() {
let s = Server::start(ServerConfig::default()).await;
let mut before = Vec::new();
for p in PATHS {
before.push(
get_h(&s.url(p), &[])
.await
.header("etag")
.unwrap()
.to_string(),
);
}
*s.source.version.lock().unwrap() = "cut-2".into();
for (p, old) in PATHS.iter().zip(&before) {
let r = get_h(&s.url(p), &[("if-none-match", old)]).await;
assert_eq!(r.status, 200, "{p}: the old tag no longer matches");
assert_ne!(r.header("etag"), Some(old.as_str()), "{p}");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn another_build_gives_other_tags_and_never_a_304_for_the_old_ones() {
let build = |id: &str| ServerConfig {
build_id: id.into(),
..ServerConfig::default()
};
let a = Server::start(build("korp-map-server 0123456789abcdef")).await;
let a_again = Server::start(build("korp-map-server 0123456789abcdef")).await;
let b = Server::start(build("korp-map-server fedcba9876543210")).await;
for p in PATHS {
let ta = get_h(&a.url(p), &[]).await;
let tag_a = ta.header("etag").unwrap().to_string();
let tag_same = get_h(&a_again.url(p), &[]).await;
assert_eq!(
tag_same.header("etag"),
Some(tag_a.as_str()),
"{p}: same build, same tag"
);
let tb = get_h(&b.url(p), &[]).await;
assert_ne!(
tb.header("etag"),
Some(tag_a.as_str()),
"{p}: another build, another tag"
);
let revalidated = get_h(&b.url(p), &[("if-none-match", &tag_a)]).await;
assert_eq!(
revalidated.status, 200,
"{p}: the old build's tag is not this reply's"
);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn the_tag_follows_the_query_as_parsed() {
let s = Server::start(ServerConfig::default()).await;
let tag = |r: Reply| r.header("etag").unwrap().to_string();
let a = tag(get_h(
&s.url("/v1/map/lines?region=testland&bbox=10,55,20,65&lod=15"),
&[],
)
.await);
let b = tag(get_h(
&s.url("/v1/map/lines?lod=15&bbox=10.0,55.00,20,65®ion=testland&max=500000"),
&[],
)
.await);
assert_eq!(
a, b,
"the same query spelled otherwise, the default max named"
);
let c = tag(get_h(
&s.url("/v1/map/lines?region=testland&bbox=10,55,20,65&lod=14"),
&[],
)
.await);
let d = tag(get_h(
&s.url("/v1/map/areas?region=testland&bbox=10,55,20,65&lod=15"),
&[],
)
.await);
let e = tag(get_h(
&s.url("/v1/map/lines?region=testland&bbox=10,55,20,65&lod=15&compress=zstd"),
&[],
)
.await);
assert!(a != c && a != d && a != e && c != d, "{a} {c} {d} {e}");
}
#[tokio::test(flavor = "multi_thread")]
async fn an_encoded_reply_has_its_own_tag_and_either_tag_revalidates() {
let s = Server::start(ServerConfig::default()).await;
let p = PATHS[0];
let plain = get_h(&s.url(p), &[]).await;
let z = get_h(&s.url(p), &[("accept-encoding", "zstd")]).await;
assert_eq!(z.header("content-encoding"), Some("zstd"));
let (pt, zt) = (plain.header("etag").unwrap(), z.header("etag").unwrap());
assert_eq!(zt, format!("{}-zstd\"", pt.trim_end_matches('"')));
for (tag, enc) in [(pt, "zstd"), (zt, "zstd"), (zt, "identity")] {
let r = get_h(
&s.url(p),
&[("if-none-match", tag), ("accept-encoding", enc)],
)
.await;
assert_eq!(r.status, 304, "{tag} {enc}");
assert_eq!(r.header("etag"), Some(tag));
}
}
#[tokio::test(flavor = "multi_thread")]
async fn refusals_are_not_tagged_and_the_max_age_is_configurable() {
let s = Server::start(ServerConfig {
cache_max_age: Some(120),
regions_max_age: None,
..ServerConfig::default()
})
.await;
let r = get_h(
&s.url("/v1/map/lines?region=atlantis&bbox=10,55,20,65&lod=15"),
&[],
)
.await;
assert_eq!(r.status, 404);
assert_eq!(r.header("etag"), None);
assert_eq!(r.header("cache-control"), None);
let r = get_h(&s.url(PATHS[0]), &[]).await;
assert_eq!(r.header("cache-control"), Some("public, max-age=120"));
let r = get_h(&s.url("/v1/regions"), &[]).await;
assert!(r.header("etag").is_some());
assert_eq!(r.header("cache-control"), None);
}