use std::sync::{Arc, mpsc};
use super::{answer, temp_path, watch};
use crate::storage::chrono::now;
use crate::storage::database_file_source::{Cache, DatabaseFileSource};
use crate::storage::file_source::FileSource;
use crate::storage::offline_database::{DatabaseError, OfflineDatabase};
use crate::storage::resource::{Kind, LoadingMethod, Resource, StoragePolicy};
use crate::storage::response::{Reason, Response};
fn cache_only(url: &str) -> Resource {
Resource::with_tile_data(Kind::Unknown, url, None, LoadingMethod::CACHE)
}
fn cached() -> Response {
let mut response = Response::new();
response.data = Some(Arc::new(b"cached".to_vec()));
response
}
fn is_not_found(res: &Response) -> bool {
res.error.as_ref().is_some_and(|error| error.reason == Reason::NotFound)
}
#[test]
fn it_loads_what_may_come_from_the_cache_but_files_and_assets() {
let source = DatabaseFileSource::new(":memory:", None);
assert!(source.can_request(&cache_only("http://example.com")));
assert!(!source.can_request(&cache_only("asset://example.json")));
assert!(!source.can_request(&cache_only("file://example.json")));
let network_only = Resource::with_tile_data(Kind::Unknown, "http://example.com", None, LoadingMethod::NETWORK);
assert!(!source.can_request(&network_only));
}
#[test]
fn a_volatile_resource_is_neither_stored_nor_read_from_the_cache() {
let source = DatabaseFileSource::new(":memory:", None);
let mut volatile = cache_only("http://example.invalid/volatile");
volatile.storage_policy = StoragePolicy::Volatile;
source.put(&volatile, &cached());
let res = answer(&source, &cache_only("http://example.invalid/volatile"));
assert!(is_not_found(&res) && res.no_content, "{res:?}");
let stored = cache_only("http://example.invalid/stored");
source.put(&stored, &cached());
assert_eq!(cached().data, answer(&source, &stored).data);
let mut volatile = stored;
volatile.storage_policy = StoragePolicy::Volatile;
let res = answer(&source, &volatile);
assert!(is_not_found(&res) && res.no_content, "{res:?}");
}
#[test]
fn a_failed_accessed_flush_waits_for_the_next_read() {
let path = temp_path("maintenance.db");
let resource = cache_only("https://example.com/maintenance");
OfflineDatabase::new(&*path).put(&resource, &cached());
let marker = format!("accessed failure {path}");
let sql = rusqlite::Connection::open(&*path).unwrap();
sql.execute_batch("UPDATE resources SET accessed = 0").unwrap();
sql.execute_batch(&format!(
"CREATE TRIGGER fail_accessed BEFORE UPDATE OF accessed ON resources \
BEGIN SELECT RAISE(ABORT, '{marker}'); END"
))
.unwrap();
let (failed, failures) = mpsc::channel();
let _unwatch = watch(move |fields| {
if fields.contains("flush accessed timestamps") && fields.contains(&marker) {
let _ = failed.send(());
}
});
let source = DatabaseFileSource::new(&path, None);
assert_eq!(cached().data, answer(&source, &resource).data);
failures.recv().unwrap();
drop(source.pause());
assert!(failures.try_recv().is_err(), "failed flush retried while idle");
assert!(!source.has_timed_task(), "failed flush waits to retry while idle");
assert_eq!(cached().data, answer(&source, &resource).data);
failures.recv().unwrap();
}
fn maintain(operation: impl FnOnce(Box<dyn FnOnce(Result<(), DatabaseError>) + Send>)) -> Result<(), DatabaseError> {
let (tx, rx) = mpsc::channel();
operation(Box::new(move |result| tx.send(result).unwrap()));
rx.recv().expect("callback")
}
#[test]
fn cache_maintenance_reaches_the_database() {
let path = temp_path("cache-maintenance.db");
let source = DatabaseFileSource::new(&path, None);
let resource = cache_only("https://example.com/maintained");
source.put(&resource, &cached());
assert_eq!(cached().data, answer(&source, &resource).data);
maintain(|done| source.invalidate_ambient_cache(done)).unwrap();
let invalidated = answer(&source, &resource);
assert!(!invalidated.caching.is_fresh(now()) && invalidated.caching.is_usable(now()));
source.put(&resource, &cached());
maintain(|done| source.clear_ambient_cache(done)).unwrap();
assert!(is_not_found(&answer(&source, &resource)));
source.put(&resource, &cached());
maintain(|done| source.reset_database(done)).unwrap();
assert!(is_not_found(&answer(&source, &resource)));
maintain(|done| source.pack_database(done)).unwrap();
maintain(|done| source.set_maximum_ambient_cache_size(0, done)).unwrap();
source.put(&resource, &cached());
assert!(is_not_found(&answer(&source, &resource)));
let read_only = DatabaseFileSource::read_only(&path, None);
let error = maintain(|done| read_only.clear_ambient_cache(done)).unwrap_err();
assert_eq!("Cannot modify database in read-only mode", error.to_string());
}