use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::Duration;
use super::answer;
use super::network::{Network, Reply};
use crate::storage::chrono::{Timestamp, now, rfc1123};
use crate::storage::database_file_source::{Cache, DatabaseFileSource};
use crate::storage::file_source::FileSource;
use crate::storage::loader::Loader;
use crate::storage::resource::{Kind, LoadingMethod, Resource, StoragePolicy};
use crate::storage::resource_options::ResourceOptions;
use crate::storage::resource_transform::FinishedCallback;
use crate::storage::response::{Caching, Data, Reason, Response};
fn url(path: &str) -> String {
format!("http://example.invalid{path}")
}
const JAN_1_2015: Timestamp = Timestamp::from_secs(1_420_070_400);
const DEC_1_2014: Timestamp = Timestamp::from_secs(1_417_392_000);
fn routes() -> impl Fn(&Resource) -> Reply + Send + Sync + 'static {
let (cached, etagged) = (AtomicU32::new(0), AtomicU32::new(0));
move |resource| {
let path = resource.url.strip_prefix("http://example.invalid").unwrap_or_default();
let revalidated = || Reply::status(304).header("Cache-Control", "max-age=60, must-revalidate");
match path {
"/test" => Reply::ok("Hello World!"),
"/cache" => {
let n = cached.fetch_add(1, Ordering::SeqCst) + 1;
Reply::ok(&format!("Response {n}")).header("Cache-Control", "max-age=30")
}
"/revalidate-same" if resource.prior_etag.as_deref() == Some("snowfall") => revalidated(),
"/revalidate-same" => {
Reply::ok("Response").header("ETag", "snowfall").header("Cache-Control", "must-revalidate")
}
"/revalidate-modified"
if resource.prior_etag.is_none() && resource.prior_modified.is_some_and(|m| m >= JAN_1_2015) =>
{
revalidated()
}
"/revalidate-modified" => {
Reply::ok("Response").header("Last-Modified", rfc1123(JAN_1_2015)).header("Cache-Control", "no-cache")
}
"/revalidate-etag" => {
let n = etagged.fetch_add(1, Ordering::SeqCst) + 1;
Reply::ok(&format!("Response {n}"))
.header("ETag", format!("response-{n}"))
.header("Cache-Control", "must-revalidate")
}
_ => match path.strip_prefix("/load/") {
Some(n) => Reply::ok(&format!("Request {n}")),
None => Reply::status(404),
},
}
}
}
struct Sources {
loader: Loader,
database: Arc<DatabaseFileSource>,
network: Network,
}
impl Sources {
fn new() -> Self {
Self::serving(Network::serving(routes()))
}
fn serving(network: Network) -> Self {
let online: Arc<dyn FileSource> = Arc::<crate::storage::OnlineFileSource>::clone(&network.source);
let database = Arc::new(DatabaseFileSource::new(":memory:", Some(Arc::clone(&online))));
let loader = Loader::builder(&super::pool())
.network(online)
.database(Arc::<DatabaseFileSource>::clone(&database))
.build();
Sources { loader, database, network }
}
fn answers(&mut self, resource: &Resource, count: usize) -> Vec<Response> {
self.network.answers(&self.loader, resource, count)
}
fn answer(&mut self, resource: &Resource) -> Response {
self.answers(resource, 1).remove(0)
}
fn answers_with_cached(&mut self, url: &str, cached: &Response, count: usize) -> Vec<Response> {
let resource = Resource::new(Kind::Unknown, url);
self.database.put(&resource, cached);
self.answers(&resource, count)
}
}
fn data(res: &Response) -> &[u8] {
res.data.as_deref().map(Vec::as_slice).expect("data")
}
fn bytes(s: &str) -> Data {
Arc::new(s.as_bytes().to_vec())
}
fn hours_from_now(hours: i64) -> Timestamp {
Timestamp::from_secs(now().secs_since_epoch() + hours * 3600)
}
fn cached_value(expires: Timestamp) -> Response {
let mut response = Response::new();
response.data = Some(bytes("Cached value"));
response.caching.expires = Some(expires);
response
}
fn stale_at_once(res: &Response) -> bool {
res.caching.expires.is_some_and(|expires| expires <= now())
}
#[test]
fn a_cached_response_answers_a_later_request_unless_it_is_volatile() {
for (policy, cached) in [(StoragePolicy::Permanent, true), (StoragePolicy::Volatile, false)] {
let mut sources = Sources::new();
let mut resource = Resource::new(Kind::Unknown, url("/cache"));
resource.storage_policy = policy;
let first = sources.answer(&resource);
assert_eq!((None, b"Response 1".as_slice()), (first.error.clone(), data(&first)));
assert!(first.caching.expires.is_some() && !first.caching.must_revalidate);
let second = sources.answer(&resource);
assert_eq!(cached, data(&first) == data(&second), "{policy:?}");
if cached {
assert_eq!((first.caching, first.modified, first.etag), (second.caching, second.modified, second.etag));
}
}
}
#[test]
fn a_copy_that_must_revalidate_waits_for_the_server() {
type Validators = (Option<Timestamp>, Option<&'static str>);
let cases: [(&str, Validators); 2] =
[("/revalidate-same", (None, Some("snowfall"))), ("/revalidate-modified", (Some(JAN_1_2015), None))];
for (path, validators) in cases {
let mut sources = Sources::new();
let resource = Resource::new(Kind::Unknown, url(path));
let check = |res: &Response| {
assert_eq!(None, res.error, "{path}");
assert!(res.caching.must_revalidate, "{path}");
assert_eq!(validators, (res.modified, res.etag.as_deref()), "{path}");
};
let first = sources.answer(&resource);
check(&first);
assert!(stale_at_once(&first) && !first.not_modified, "{path}");
assert_eq!(b"Response", data(&first));
let (request, answers) = sources.network.request_from(&sources.loader, &resource);
sources.network.run_until(&answers, 1);
sources.network.advance(Duration::from_secs(60));
sources.network.run_until(&answers, 2);
drop(request);
let answers = answers.lock();
check(&answers[0]);
assert!(!answers[0].not_modified, "the requester's first sight of it: {path}");
assert_eq!(b"Response", data(&answers[0]));
check(&answers[1]);
assert!(answers[1].not_modified && answers[1].data.is_none(), "{path}");
assert!(answers[1].caching.expires.is_some(), "{path}");
}
}
#[test]
fn a_copy_whose_etag_changed_is_replaced() {
let mut sources = Sources::new();
let resource = Resource::new(Kind::Unknown, url("/revalidate-etag"));
for n in 1..=2 {
let res = sources.answer(&resource);
assert_eq!(None, res.error);
assert_eq!(format!("Response {n}").as_bytes(), data(&res));
assert_eq!(Some(format!("response-{n}")), res.etag);
assert!(stale_at_once(&res) && res.caching.must_revalidate);
}
}
#[test]
fn a_request_made_again_after_a_cancel_is_answered() {
let mut sources = Sources::new();
let resource = Resource::new(Kind::Unknown, url("/test"));
let (cancelled, not_answered) = sources.network.request_from(&sources.loader, &resource);
drop(cancelled);
let res = sources.answer(&resource);
assert_eq!((None, b"Hello World!".as_slice()), (res.error.clone(), data(&res)));
assert!(stale_at_once(&res));
assert!(not_answered.lock().is_empty());
}
#[test]
fn a_cache_only_request_returns_the_copy_fresh_or_stale() {
for expires in [hours_from_now(1), hours_from_now(-1)] {
let sources = Sources::new();
let resource = Resource::with_tile_data(Kind::Unknown, url("/test"), None, LoadingMethod::CACHE);
sources.database.put(&resource, &cached_value(expires));
let res = answer(&sources.loader, &resource);
assert_eq!((None, b"Cached value".as_slice()), (res.error.clone(), data(&res)));
assert_eq!(Some(expires), res.caching.expires);
}
let sources = Sources::new();
let resource = Resource::with_tile_data(Kind::Unknown, url("/test"), None, LoadingMethod::CACHE);
let res = answer(&sources.loader, &resource);
let error = res.error.as_ref().expect("an error");
assert_eq!((Reason::NotFound, "Not found in offline database"), (error.reason, error.message.as_str()));
assert!(res.data.is_none());
}
#[test]
fn a_network_only_request_skips_the_cache() {
struct Case {
path: &'static str,
prior_etag: Option<&'static str>,
prior_modified: Option<Timestamp>,
not_modified: bool,
}
let cases = [
Case { path: "/revalidate-same", prior_etag: Some("snowfall"), prior_modified: None, not_modified: true },
Case { path: "/revalidate-same", prior_etag: Some("sunshine"), prior_modified: None, not_modified: false },
Case { path: "/revalidate-same", prior_etag: None, prior_modified: None, not_modified: false },
Case { path: "/revalidate-modified", prior_etag: None, prior_modified: Some(JAN_1_2015), not_modified: true },
Case { path: "/revalidate-modified", prior_etag: None, prior_modified: Some(DEC_1_2014), not_modified: false },
];
for case in cases {
let mut sources = Sources::new();
let mut resource = Resource::new(Kind::Unknown, url(case.path));
resource.loading_method = LoadingMethod::NETWORK;
resource.prior_etag = case.prior_etag.map(str::to_owned);
resource.prior_modified = case.prior_modified;
sources.database.put(&resource, &cached_value(hours_from_now(1)));
let requested = now();
let res = sources.answer(&resource);
let label = (case.path, case.prior_etag, case.prior_modified);
assert_eq!(None, res.error, "{label:?}");
assert_eq!(case.not_modified, res.not_modified, "{label:?}");
assert!(res.caching.must_revalidate, "{label:?}");
if case.not_modified {
assert!(res.data.is_none(), "{label:?}");
assert!(Some(Timestamp::from_secs(requested.secs_since_epoch() + 60)) <= res.caching.expires, "{label:?}");
} else {
assert_eq!(b"Response", data(&res), "{label:?}");
assert!(stale_at_once(&res), "{label:?}");
}
}
}
#[test]
fn the_resource_transform_rewrites_urls_until_cleared() {
let mut sources = Sources::new();
let target = url("/test");
sources.network.source.set_resource_transform(Some(Arc::new(move |_: Kind, url: &str, done: FinishedCallback| {
done(Ok(if url == "localhost://test" { target.clone() } else { url.to_owned() }));
})));
let res = sources.answer(&Resource::new(Kind::Unknown, "localhost://test"));
assert_eq!((None, b"Hello World!".as_slice()), (res.error.clone(), data(&res)));
assert_eq!(vec![url("/test")], sources.network.server.requested());
sources.network.source.set_resource_transform(None);
let res = sources.answer(&Resource::new(Kind::Unknown, url("/test")));
assert_eq!((None, b"Hello World!".as_slice()), (res.error.clone(), data(&res)));
}
#[test]
fn a_stale_copy_that_must_revalidate_is_revalidated_with_the_server() {
let mut sources = Sources::new();
let mut resource = Resource::new(Kind::Unknown, url("/revalidate-same"));
resource.loading_method = LoadingMethod::CACHE;
let mut cached = cached_value(DEC_1_2014);
cached.modified = Some(DEC_1_2014);
cached.caching.must_revalidate = true;
cached.etag = Some("snowfall".to_owned());
sources.database.put(&resource, &cached);
let res = answer(&sources.loader, &resource);
assert_eq!(None, res.error);
assert!(!res.caching.is_usable(now()) && !res.not_modified);
assert_eq!(b"Cached value", data(&res));
assert_eq!((cached.caching, cached.modified, cached.etag), (res.caching, res.modified, res.etag.clone()));
resource.loading_method = LoadingMethod::NETWORK;
resource.prior_etag = res.etag;
resource.prior_modified = res.modified;
resource.prior_caching.expires = res.caching.expires;
resource.prior_data = Some(bytes("Prior value"));
let res = sources.answer(&resource);
assert_eq!(None, res.error);
assert!(!res.not_modified);
assert_eq!(b"Prior value", data(&res));
assert!(Some(now()) <= res.caching.expires && res.caching.must_revalidate);
assert_eq!((Some(DEC_1_2014), Some("snowfall")), (res.modified, res.etag.as_deref()));
}
#[test]
fn revalidating_a_cached_copy_waits_behind_new_resources() {
let mut sources = Sources::new();
let resource =
|n: u32| Resource::with_tile_data(Kind::Unknown, url(&format!("/load/{n}")), None, LoadingMethod::ALL);
for n in [3, 4] {
let mut response = cached_value(hours_from_now(-1));
response.data = Some(bytes(&format!("Cached Request {n}")));
sources.database.put(&resource(n), &response);
}
sources.network.source.set_maximum_concurrent_requests(1);
let order = [0, 1, 3, 4, 2];
let requests: Vec<_> = order.iter().map(|&n| sources.network.request_from(&sources.loader, &resource(n))).collect();
drop(sources.database.pause());
for (n, (_, answers)) in order.iter().zip(&requests) {
sources.network.run_until(answers, if [3, 4].contains(n) { 2 } else { 1 });
}
let cached: Vec<String> = requests
.iter()
.flat_map(|(_, answers)| answers.lock().clone())
.map(|res| String::from_utf8(data(&res).to_vec()).unwrap())
.filter(|data| data.starts_with("Cached"))
.collect();
assert_eq!(["Cached Request 3", "Cached Request 4"].to_vec(), cached);
let requested: Vec<String> = sources.network.server.requested();
let expected: Vec<String> = [0, 1, 2, 3, 4].iter().map(|n| url(&format!("/load/{n}"))).collect();
assert_eq!(expected, requested);
}
#[test]
fn a_revalidated_copy_is_not_delivered_twice() {
let mut cached = Response::new();
cached.data = Some(bytes("data"));
cached.etag = Some("snowfall".to_owned());
let answers = Sources::new().answers_with_cached(&url("/revalidate-same"), &cached, 2);
for res in &answers {
assert_eq!((None, None, Some("snowfall")), (res.error.clone(), res.modified, res.etag.as_deref()));
}
assert_eq!(b"data", data(&answers[0]));
assert!(!answers[0].not_modified);
assert!(answers[1].not_modified && answers[1].data.is_none());
}
#[test]
fn a_request_no_source_accepts_is_unsupported() {
let loader = Loader::new(&ResourceOptions::default(), &super::pool());
let resource = Resource::with_tile_data(Kind::Unknown, "http://example.com/x.json", None, LoadingMethod::NONE);
let res = answer(&loader, &resource);
assert!(res.no_content);
assert_eq!("Unsupported resource request.", res.error.unwrap().message);
}
fn with_caching(mut response: Response, change: impl FnOnce(&mut Caching)) -> Response {
change(&mut response.caching);
response
}
#[test]
fn a_stale_copy_shows_while_it_revalidates_unless_it_must_revalidate() {
let stale = cached_value(hours_from_now(-1));
let answers = Sources::new().answers_with_cached(&url("/test"), &stale, 2);
assert_eq!(b"Cached value", data(&answers[0]));
assert_eq!(b"Hello World!", data(&answers[1]));
let must_revalidate = with_caching(stale, |caching| caching.must_revalidate = true);
let answers = Sources::new().answers_with_cached(&url("/test"), &must_revalidate, 1);
assert_eq!(b"Hello World!", data(&answers[0]));
}
#[test]
fn a_stale_copy_shows_when_the_server_cant_be_reached() {
let unreachable = || Sources::serving(Network::serving(|_| Reply::Refused));
let stale = cached_value(hours_from_now(-1));
let answers = unreachable().answers_with_cached(&url("/test"), &stale, 2);
assert_eq!(b"Cached value", data(&answers[0]));
assert_eq!(Reason::Connection, answers[1].error.as_ref().expect("an error").reason);
let must_revalidate = with_caching(stale, |caching| caching.must_revalidate = true);
let answers = unreachable().answers_with_cached(&url("/test"), &must_revalidate, 1);
assert_eq!(Reason::Connection, answers[0].error.as_ref().expect("an error").reason);
}