use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::Duration;
use httpmock::MockServer;
use mln_engine::storage::offline::{OfflineRegionDownloadState, OfflineTilePyramidRegionDefinition};
use mln_engine::storage::resource::Kind;
use mln_engine::storage::response::Caching;
use mln_engine::storage::{ResourceError, Response};
use mln_runtime::{
CacheDatabaseOperation, ErrorKind, EventMask, EventSource, ResourceProvider, ResourceRequest, Runtime,
RuntimeEventKind, RuntimeOptions,
};
use mln_style::geo::{LatLng, LatLngBounds};
use crate::support::{EMPTY_STYLE, EventLog, TempDir, map, runtime, wait, wait_err};
fn style_response() -> Response {
Response { data: Some(Arc::new(EMPTY_STYLE.as_bytes().to_vec())), ..Response::default() }
}
#[test]
fn a_provider_serves_a_scheme_the_library_cant_load() {
let runtime = runtime();
let seen = Arc::new(parking_lot::Mutex::new(Vec::new()));
let record = Arc::clone(&seen);
wait(runtime.set_resource_provider(move |request: ResourceRequest| {
record.lock().push((request.resource().kind, request.resource().url.clone()));
assert!(!request.is_cancelled());
request.respond(style_response()).unwrap();
}));
let map = map(&runtime);
wait(map.set_style_url("custom://styles/empty"));
assert_eq!(vec![(Kind::Style, "custom://styles/empty".to_owned())], *seen.lock());
assert_eq!(EMPTY_STYLE, wait(map.loaded_style_json()));
}
#[test]
fn a_provider_answers_later_from_another_thread() {
let runtime = runtime();
wait(runtime.set_resource_provider(|request: ResourceRequest| {
std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(20));
request.respond(style_response()).unwrap();
});
}));
let map = map(&runtime);
wait(map.set_style_url("custom://late"));
}
struct AnswersInline {
returned: Arc<AtomicBool>,
}
impl ResourceProvider for AnswersInline {
fn request(&self, request: ResourceRequest) {
request.respond(style_response()).unwrap();
std::thread::sleep(Duration::from_millis(100));
self.returned.store(true, Ordering::SeqCst);
}
}
#[test]
fn an_answer_inside_the_providers_call_arrives_after_the_call_returns() {
let runtime = runtime();
let returned = Arc::new(AtomicBool::new(false));
wait(runtime.set_resource_provider(AnswersInline { returned: Arc::clone(&returned) }));
let map = map(&runtime);
wait(map.set_style_url("custom://inline"));
assert_eq!(EMPTY_STYLE, wait(map.loaded_style_json()));
assert!(returned.load(Ordering::SeqCst));
}
struct Lingering {
requests: std::sync::mpsc::Sender<ResourceRequest>,
dropped: Arc<AtomicBool>,
}
impl ResourceProvider for Lingering {
fn request(&self, request: ResourceRequest) {
self.requests.send(request).unwrap();
std::thread::sleep(Duration::from_millis(200));
}
}
impl Drop for Lingering {
fn drop(&mut self) {
self.dropped.store(true, Ordering::SeqCst);
}
}
#[test]
fn a_replacement_completes_after_the_call_to_the_provider_it_replaces() {
let runtime = runtime();
let (requests, received) = std::sync::mpsc::channel();
let dropped = Arc::new(AtomicBool::new(false));
wait(runtime.set_resource_provider(Lingering { requests, dropped: Arc::clone(&dropped) }));
let map = map(&runtime);
let style = map.set_style_url("custom://lingering");
let request = received.recv_timeout(Duration::from_secs(10)).unwrap();
wait(runtime.clear_resource_provider());
assert!(dropped.load(Ordering::SeqCst));
request.respond(style_response()).unwrap();
wait(style);
}
struct Routed {
prefix: &'static str,
served: Arc<AtomicUsize>,
}
impl ResourceProvider for Routed {
fn serves(&self, _kind: Kind, url: &str) -> bool {
url.starts_with(self.prefix)
}
fn request(&self, request: ResourceRequest) {
self.served.fetch_add(1, Ordering::SeqCst);
request.respond(style_response()).unwrap();
}
}
#[test]
fn a_provider_passes_through_or_leaves_what_it_doesnt_serve() {
let server = MockServer::start();
let style = server.mock(|when, then| {
when.method("GET").path("/style.json");
then.status(200).body(EMPTY_STYLE);
});
let runtime = runtime();
let served = Arc::new(AtomicUsize::new(0));
wait(runtime.set_resource_provider(Routed { prefix: "custom://", served: Arc::clone(&served) }));
let map = map(&runtime);
wait(map.set_style_url(server.url("/style.json")));
assert_eq!((0, 1), (served.load(Ordering::SeqCst), style.calls()));
wait(runtime.set_resource_provider(|request: ResourceRequest| request.pass_through().unwrap()));
wait(runtime.run_cache_database_operation(CacheDatabaseOperation::Clear));
wait(map.set_style_url(server.url("/style.json?again")));
assert_eq!(2, style.calls());
wait(runtime.clear_resource_provider());
assert_eq!(ErrorKind::Failed, wait_err(map.set_style_url("custom://styles/empty")).kind);
}
#[test]
fn a_request_dropped_unanswered_fails() {
let runtime = runtime();
wait(runtime.set_resource_provider(drop::<ResourceRequest>));
let map = map(&runtime);
let error = wait_err(map.set_style_url("custom://dropped"));
assert_eq!(ErrorKind::Failed, error.kind);
assert!(error.message.contains("without a response"), "{}", error.message);
}
#[test]
fn a_scheme_that_nothing_loads_fails_and_says_why() {
let runtime = runtime();
let map = map(&runtime);
let error = wait_err(map.set_style_url("jar://user:password@archive/style.json?access_token=secret#token"));
assert!(error.message.contains(r#"unsupported URL scheme "jar""#), "{}", error.message);
assert!(error.message.contains(r#""jar://archive/style.json""#), "{}", error.message);
assert!(error.message.contains("register a resource provider"), "{}", error.message);
for secret in ["user", "password", "access_token", "secret"] {
assert!(!error.message.contains(secret), "{}", error.message);
}
wait(runtime.set_resource_provider(|request: ResourceRequest| request.pass_through().unwrap()));
let error = wait_err(map.set_style_url("jar:file:/packaged/style.json"));
assert!(error.message.contains("the registered resource provider declined"), "{}", error.message);
}
#[test]
fn a_not_modified_answer_delivers_the_cached_copy() {
let dir = TempDir::new();
let options = RuntimeOptions { cache_path: Some(dir.path("cache.db")), ..RuntimeOptions::default() };
let runtime = Runtime::new(&options).unwrap();
let revalidations = Arc::new(AtomicUsize::new(0));
let counted = Arc::clone(&revalidations);
wait(runtime.set_resource_provider(move |request: ResourceRequest| {
if request.resource().prior_data.is_some() {
counted.fetch_add(1, Ordering::SeqCst);
assert_eq!(Some("\"v1\""), request.resource().prior_etag.as_deref());
request.respond(Response { not_modified: true, ..Response::default() }).unwrap();
} else {
let caching =
Caching { expires: Some(mln_engine::storage::chrono::Timestamp::from_secs(1)), must_revalidate: true };
let response = Response { etag: Some("\"v1\"".to_owned()), caching, ..style_response() };
request.respond(response).unwrap();
}
}));
let first = map(&runtime);
wait(first.set_style_url("custom://cached"));
let second = map(&runtime);
wait(second.set_style_url("custom://cached"));
assert_eq!(EMPTY_STYLE, wait(second.loaded_style_json()));
assert_eq!(1, revalidations.load(Ordering::SeqCst));
}
#[test]
fn a_cancelled_request_calls_back_and_takes_no_answer() {
let runtime = runtime();
let (requests, held) = std::sync::mpsc::channel();
wait(runtime.set_resource_provider(move |request: ResourceRequest| requests.send(request).unwrap()));
let map = map(&runtime);
let load = map.set_style_url("custom://never").unwrap();
let request = held.recv_timeout(crate::support::TIMEOUT).unwrap();
let (cancelled, on_cancel) = std::sync::mpsc::channel();
request.on_cancel(move || cancelled.send(()).unwrap()).unwrap();
assert_eq!(ErrorKind::InvalidState, request.on_cancel(|| {}).unwrap_err().kind);
wait(map.set_style_json(EMPTY_STYLE));
assert_eq!(ErrorKind::Cancelled, load.wait().unwrap_err().kind);
on_cancel.recv_timeout(crate::support::TIMEOUT).unwrap();
assert!(request.is_cancelled());
assert_eq!(ErrorKind::Cancelled, request.on_cancel(|| {}).unwrap_err().kind);
assert_eq!(ErrorKind::InvalidState, request.respond(style_response()).unwrap_err().kind);
}
#[test]
fn a_resource_transform_rewrites_or_fails_requests() {
let server = MockServer::start();
server.mock(|when, then| {
when.method("GET").path("/style.json");
then.status(200).body(EMPTY_STYLE);
});
let runtime = runtime();
let base = server.base_url();
wait(runtime.set_resource_transform(move |kind, url, done| {
if url.contains("blocked") {
done(Err(ResourceError::new(mln_engine::storage::response::Reason::Other, "blocked by the transform")));
} else {
assert_eq!(Kind::Style, kind);
done(Ok(url.replace("http://nowhere.invalid", &base)));
}
}));
let map = map(&runtime);
wait(map.set_style_url("http://nowhere.invalid/style.json"));
let error = wait_err(map.set_style_url("http://nowhere.invalid/blocked.json"));
assert!(error.message.contains("blocked by the transform"), "{}", error.message);
wait(runtime.clear_resource_transform());
assert_eq!(ErrorKind::Failed, wait_err(map.set_style_url("http://nowhere.invalid/style.json?2")).kind);
}
#[test]
fn a_header_transform_adds_headers() {
let server = MockServer::start();
let style = server.mock(|when, then| {
when.method("GET").path("/style.json").header("x-token", "secret");
then.status(200).body(EMPTY_STYLE);
});
let runtime = runtime();
wait(runtime.set_http_header_transform(|kind, _url| {
assert_eq!(Kind::Style, kind);
vec![("X-Token".to_owned(), "secret".to_owned()), ("User-Agent".to_owned(), "spoofed".to_owned())]
}));
let map = map(&runtime);
wait(map.set_style_url(server.url("/style.json")));
assert_eq!(1, style.calls());
wait(runtime.clear_http_header_transform());
assert_eq!(ErrorKind::Failed, wait_err(map.set_style_url(server.url("/style.json?2"))).kind);
}
#[test]
fn cache_operations_change_what_the_ambient_cache_serves() {
let server = MockServer::start();
let fresh = server.mock(|when, then| {
when.method("GET").path("/style.json").header_missing("if-none-match");
then.status(200).header("Cache-Control", "max-age=3600").header("ETag", "\"v1\"").body(EMPTY_STYLE);
});
let revalidated = server.mock(|when, then| {
when.method("GET").path("/style.json").header("if-none-match", "\"v1\"");
then.status(304).header("Cache-Control", "max-age=3600").header("ETag", "\"v1\"");
});
let dir = TempDir::new();
let options = RuntimeOptions { cache_path: Some(dir.path("cache.db")), ..RuntimeOptions::default() };
let runtime = Runtime::new(&options).unwrap();
let bounds = LatLngBounds::hull(LatLng::new(1.0, 2.0).unwrap(), LatLng::new(3.0, 4.0).unwrap());
let definition =
OfflineTilePyramidRegionDefinition::new("custom://style.json", bounds, 0.0, 0.0, 1.0, false).unwrap().into();
wait(runtime.offline().create_region(definition, b"kept".to_vec()));
let regions = || wait(runtime.offline().regions()).len();
let map = map(&runtime);
let load = || wait(map.set_style_url(server.url("/style.json")));
let calls = || (fresh.calls(), revalidated.calls());
load();
assert_eq!((1, 0), calls());
load();
assert_eq!((1, 0), calls());
wait(runtime.run_cache_database_operation(CacheDatabaseOperation::Invalidate));
load();
let deadline = std::time::Instant::now() + Duration::from_secs(60);
while calls() != (1, 1) {
assert!(std::time::Instant::now() < deadline, "never revalidated: {:?}", calls());
std::thread::sleep(Duration::from_millis(5));
}
wait(runtime.run_cache_database_operation(CacheDatabaseOperation::Clear));
load();
assert_eq!((2, 1), calls());
assert_eq!(1, regions());
wait(runtime.run_cache_database_operation(CacheDatabaseOperation::Pack));
load();
assert_eq!((2, 1), calls());
wait(runtime.run_cache_database_operation(CacheDatabaseOperation::Reset));
assert_eq!(0, regions());
load();
assert_eq!((3, 1), calls());
wait(runtime.set_maximum_ambient_cache_size(1 << 20));
wait(map.release());
wait(runtime.release());
}
#[test]
fn cache_settings_sent_before_the_first_map_reach_its_requests() {
let server = MockServer::start();
let style = server.mock(|when, then| {
when.method("GET").path("/style.json");
then.status(200).header("Cache-Control", "max-age=3600").body(EMPTY_STYLE);
});
let dir = TempDir::new();
let options = RuntimeOptions { cache_path: Some(dir.path("cache.db")), ..RuntimeOptions::default() };
let runtime = Runtime::new(&options).unwrap();
wait(runtime.set_maximum_ambient_cache_size(0));
assert_eq!(0, wait(runtime.offline().regions()).len());
let map = map(&runtime);
wait(map.set_style_url(server.url("/style.json")));
wait(map.set_style_url(server.url("/style.json")));
assert_eq!(2, style.calls());
wait(map.release());
wait(runtime.release());
}
#[test]
fn a_runtime_without_maps_runs_cache_and_offline_calls_and_releases() {
let untouched = runtime();
wait(untouched.release());
let runtime = runtime();
assert_eq!(0, wait(runtime.offline().regions()).len());
wait(runtime.set_maximum_ambient_cache_size(1 << 20));
wait(runtime.run_cache_database_operation(CacheDatabaseOperation::Clear));
wait(runtime.release());
}
struct Gate {
entered: std::sync::mpsc::Sender<()>,
gate: parking_lot::Mutex<std::sync::mpsc::Receiver<()>>,
}
impl ResourceProvider for Gate {
fn request(&self, _request: ResourceRequest) {}
}
impl Drop for Gate {
fn drop(&mut self) {
let _ = self.entered.send(());
let _ = self.gate.lock().recv_timeout(crate::support::TIMEOUT);
}
}
#[test]
fn an_offline_operation_sent_before_a_release_completes_first() {
let dir = TempDir::new();
let cache = dir.path("release.db");
let bounds = LatLngBounds::hull(LatLng::new(1.0, 2.0).unwrap(), LatLng::new(3.0, 4.0).unwrap());
let definition =
OfflineTilePyramidRegionDefinition::new("custom://style.json", bounds, 0.0, 0.0, 1.0, false).unwrap().into();
let runtime =
Runtime::new(&RuntimeOptions { cache_path: Some(cache.clone()), ..RuntimeOptions::default() }).unwrap();
let (open, gate) = std::sync::mpsc::channel::<()>();
let (entered, parked) = std::sync::mpsc::channel::<()>();
wait(runtime.set_resource_provider(Gate { entered, gate: parking_lot::Mutex::new(gate) }));
let cleared = runtime.clear_resource_provider();
parked.recv_timeout(crate::support::TIMEOUT).unwrap();
let (record, order) = std::sync::mpsc::channel();
let record_created = record.clone();
let created = runtime.offline().create_region(definition, b"raced".to_vec()).unwrap();
created.on_complete(move |result| drop(record_created.send(result.map(|_| "created").map_err(|e| e.message))));
let released = runtime.release().unwrap();
released.on_complete(move |result| drop(record.send(result.map(|()| "released").map_err(|e| e.message))));
drop(open);
wait(cleared);
let next = || order.recv_timeout(crate::support::TIMEOUT).unwrap();
assert_eq!([Ok("created"), Ok("released")], [next(), next()]);
let reopened = Runtime::new(&RuntimeOptions { cache_path: Some(cache), ..RuntimeOptions::default() }).unwrap();
assert_eq!(1, wait(reopened.offline().regions()).len());
wait(reopened.release());
}
#[test]
fn a_merge_takes_only_a_readable_database_file() {
let dir = TempDir::new();
let side = dir.path("side.db");
let missing = dir.path("missing.db");
let bounds = LatLngBounds::hull(LatLng::new(1.0, 2.0).unwrap(), LatLng::new(3.0, 4.0).unwrap());
let definition =
OfflineTilePyramidRegionDefinition::new("custom://style.json", bounds, 0.0, 0.0, 1.0, false).unwrap().into();
let writer = Runtime::new(&RuntimeOptions { cache_path: Some(side.clone()), ..RuntimeOptions::default() }).unwrap();
wait(writer.offline().create_region(definition, b"side".to_vec()));
wait(writer.release());
let runtime = runtime();
let offline = runtime.offline();
for path in [missing.to_str().unwrap(), "", ":memory:", "file::memory:"] {
let error = offline.merge_regions(path).unwrap_err();
assert_eq!(ErrorKind::InvalidArgument, error.kind, "{path}");
assert!(error.message.contains("readable database file"), "{}", error.message);
}
assert!(!missing.exists());
let merged = wait(offline.merge_regions(side.to_str().unwrap()));
assert_eq!(vec![b"side".to_vec()], merged.iter().map(|region| region.metadata.clone()).collect::<Vec<_>>());
assert_eq!(merged, wait(offline.regions()));
}
#[test]
fn an_offline_region_downloads_and_reports_its_progress() {
let server = MockServer::start();
server.mock(|when, then| {
when.method("GET").path("/style.json");
then.status(200).body(EMPTY_STYLE);
});
let dir = TempDir::new();
let options = RuntimeOptions { cache_path: Some(dir.path("cache.db")), ..RuntimeOptions::default() };
let runtime = Runtime::new(&options).unwrap();
let log = EventLog::install(&runtime);
let offline = runtime.offline();
let bounds = LatLngBounds::hull(LatLng::new(1.0, 2.0).unwrap(), LatLng::new(3.0, 4.0).unwrap());
let definition = OfflineTilePyramidRegionDefinition::new(server.url("/style.json"), bounds, 0.0, 0.0, 1.0, false)
.unwrap()
.into();
let region = wait(offline.create_region(definition, b"one".to_vec()));
let id = region.id;
assert_eq!(vec![region.clone()], wait(offline.regions()));
assert_eq!(Some(region), wait(offline.region(id)));
assert_eq!(None, wait(offline.region(id + 1)));
assert_eq!(b"two", wait(offline.update_region_metadata(id, b"two".to_vec())).metadata.as_slice());
assert_eq!(ErrorKind::InvalidArgument, offline.set_region_observed(id, EventMask::ALL).unwrap_err().kind);
wait(offline.set_region_observed(id, EventMask::ALL_RUNTIME_EVENTS));
wait(offline.set_region_download_state(id, OfflineRegionDownloadState::Active));
let done = log.wait_for(|event| {
matches!(&event.kind, RuntimeEventKind::OfflineRegionStatusChanged { region_id, status }
if *region_id == id && status.complete() && status.download_state == OfflineRegionDownloadState::Inactive)
});
let done = done.expect("the download finishes");
assert_eq!(EventSource::Runtime, done.source);
assert!(wait(offline.region_status(id)).complete());
let expiry = wait(offline.region_expiry(id));
assert!(expiry.stale_after.is_some());
assert_eq!(None, expiry.usable_offline_until);
assert_eq!((1, 0), (expiry.stale_resource_count, expiry.unusable_resource_count));
wait(offline.invalidate_region(id));
wait(offline.delete_region(id));
assert_eq!(wait(offline.regions()), Vec::<mln_engine::storage::offline::OfflineRegion>::new());
assert_eq!(ErrorKind::NotFound, wait_err(offline.region_status(id)).kind);
assert_eq!(ErrorKind::NotFound, wait_err(offline.region_expiry(id)).kind);
assert_eq!(ErrorKind::NotFound, wait_err(offline.delete_region(id)).kind);
assert_eq!(ErrorKind::NotFound, wait_err(offline.set_region_observed(id, EventMask::NONE)).kind);
wait(runtime.release());
}