use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use parking_lot::Mutex;
use crate::exec::queue::Queue;
use crate::log_target;
use crate::storage::constants::{ASSET_PROTOCOL, FILE_PROTOCOL};
use crate::storage::file_source::FileSource;
use crate::storage::offline_database::{DatabaseError, OfflineDatabase};
use crate::storage::request::Responder;
use crate::storage::resource::{LoadingMethod, Resource, StoragePolicy};
use crate::storage::response::{Reason, ResourceError, Response};
const ACCESSED_FLUSH_DELAY: Duration = Duration::from_millis(250);
pub type DatabaseQueue<E> = Queue<DatabaseWorker<E>>;
pub struct DatabaseWorker<E: 'static> {
pub db: OfflineDatabase,
pub extension: E,
network: Option<Arc<dyn FileSource>>,
}
type MakeExtension<E> = Box<dyn FnOnce(DatabaseQueue<E>, Option<Arc<dyn FileSource>>) -> E + Send>;
impl<E: 'static> DatabaseWorker<E> {
fn new(
queue: &DatabaseQueue<E>,
network: Option<Arc<dyn FileSource>>,
cache_path: &str,
read_only: bool,
make: MakeExtension<E>,
) -> Self {
let mut db = OfflineDatabase::new(cache_path);
if read_only {
db.reopen_database_read_only(true);
}
let due = Arc::new(AtomicBool::new(false));
let flush = queue.clone();
db.set_accessed_callback(Box::new(move || {
if !due.swap(true, Ordering::Relaxed) {
let due = Arc::clone(&due);
flush.post_after(ACCESSED_FLUSH_DELAY, move |worker| {
due.store(false, Ordering::Relaxed);
worker.db.flush_accessed();
});
}
}));
let extension = make(queue.clone(), network.clone());
DatabaseWorker { db, extension, network }
}
pub fn network(&self) -> Option<&Arc<dyn FileSource>> {
self.network.as_ref()
}
fn request(&mut self, resource: &Resource, responder: &Responder) {
let offline_response =
if resource.storage_policy == StoragePolicy::Volatile { None } else { self.db.get(resource) };
let response = offline_response.unwrap_or_else(|| {
let mut response = Response::new();
response.no_content = true;
response.error = Some(Box::new(ResourceError::new(Reason::NotFound, "Not found in offline database")));
response
});
responder.send(response);
}
fn maintain(
&mut self,
operation: impl FnOnce(&mut OfflineDatabase) -> Result<(), DatabaseError>,
callback: impl FnOnce(Result<(), DatabaseError>),
) {
callback(operation(&mut self.db));
}
}
pub trait Cache: FileSource {
fn put(&self, resource: &Resource, response: &Response);
}
pub struct DatabaseFileSource<E: 'static = ()> {
queue: DatabaseQueue<E>,
thread: Mutex<Option<std::thread::JoinHandle<()>>>,
}
impl DatabaseFileSource {
#[must_use]
pub fn new(cache_path: &str, network: Option<Arc<dyn FileSource>>) -> Self {
Self::with_extension(cache_path, network, false, |_, _| ())
}
#[must_use]
pub fn read_only(cache_path: &str, network: Option<Arc<dyn FileSource>>) -> Self {
Self::with_extension(cache_path, network, true, |_, _| ())
}
}
impl<E: 'static> DatabaseFileSource<E> {
#[must_use]
pub fn with_extension(
cache_path: &str,
network: Option<Arc<dyn FileSource>>,
read_only: bool,
make: impl FnOnce(DatabaseQueue<E>, Option<Arc<dyn FileSource>>) -> E + Send + 'static,
) -> Self {
let cache_path = cache_path.to_owned();
let make: MakeExtension<E> = Box::new(make);
let queue = DatabaseQueue::new();
let own = queue.clone();
let thread = crate::exec::thread::spawn("DatabaseFileSource", move || {
let mut worker = DatabaseWorker::new(&own, network, &cache_path, read_only, make);
own.run(&mut worker);
own.close();
drop(worker);
})
.inspect_err(|error| log::error!(target: log_target::DATABASE, "The database's thread didn't start: {error}"))
.ok();
if thread.is_none() {
queue.close();
}
DatabaseFileSource { queue, thread: Mutex::new(thread) }
}
#[cfg(test)]
pub(crate) fn pause(&self) -> crate::storage::tests::Paused {
crate::storage::tests::pause(|hold| self.invoke(move |_| hold()))
}
#[cfg(test)]
pub(crate) fn has_timed_task(&self) -> bool {
self.queue.next_deadline().is_some()
}
#[cfg(test)]
pub(crate) fn set_database_path(&self, path: &str, callback: Option<Box<dyn FnOnce() + Send>>) {
let path = path.to_owned();
self.invoke(move |t| {
t.db.change_path(&path);
if let Some(callback) = callback {
callback();
}
});
}
#[cfg(test)]
pub(crate) fn put_then(&self, resource: &Resource, response: &Response, then: Box<dyn FnOnce() + Send>) {
let resource = resource.clone();
let response = response.clone();
self.invoke(move |t| {
t.db.put(&resource, &response);
then();
});
}
pub fn reset_database(&self, callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static) {
self.invoke(move |t| t.maintain(OfflineDatabase::reset_database, callback));
}
pub fn pack_database(&self, callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static) {
self.invoke(move |t| t.maintain(OfflineDatabase::pack, callback));
}
pub fn invalidate_ambient_cache(&self, callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static) {
self.invoke(move |t| t.maintain(OfflineDatabase::invalidate_ambient_cache, callback));
}
pub fn clear_ambient_cache(&self, callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static) {
self.invoke(move |t| t.maintain(OfflineDatabase::clear_ambient_cache, callback));
}
pub fn set_maximum_ambient_cache_size(
&self,
size: u64,
callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static,
) {
self.invoke(move |t| t.maintain(|db| db.set_maximum_ambient_cache_size(size), callback));
}
pub fn invoke(&self, f: impl FnOnce(&mut DatabaseWorker<E>) + Send + 'static) {
self.queue.post(f);
}
pub fn shut_down(&self) {
self.queue.stop();
let thread = self.thread.lock().take();
if let Some(thread) = thread
&& thread.thread().id() != std::thread::current().id()
{
let _ = thread.join();
}
}
}
impl<E: 'static> Drop for DatabaseFileSource<E> {
fn drop(&mut self) {
self.shut_down();
}
}
impl<E: 'static> Cache for DatabaseFileSource<E> {
fn put(&self, resource: &Resource, response: &Response) {
if resource.storage_policy == StoragePolicy::Volatile {
return;
}
let resource = resource.clone();
let response = response.clone();
self.invoke(move |t| {
t.db.put(&resource, &response);
});
}
}
impl<E: 'static> FileSource for DatabaseFileSource<E> {
fn load(&self, resource: &Resource, responder: Responder) {
if self.thread.lock().is_none() {
let mut response = Response::new();
response.error = Some(Box::new(ResourceError::new(Reason::Other, "The database's thread isn't running.")));
responder.send(response);
return;
}
let resource = resource.clone();
self.invoke(move |worker| {
if !responder.is_cancelled() {
worker.request(&resource, &responder);
}
});
}
fn can_request(&self, resource: &Resource) -> bool {
resource.has_loading_method(LoadingMethod::Cache)
&& !resource.url.starts_with(ASSET_PROTOCOL)
&& !resource.url.starts_with(FILE_PROTOCOL)
}
}
#[cfg(test)]
mod tests {
use std::sync::mpsc;
use super::*;
#[test]
fn a_drop_waits_for_the_work_sent_before() {
let database = DatabaseFileSource::new(":memory:", None);
let ran = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&ran);
database.invoke(move |_| {
std::thread::sleep(Duration::from_millis(50));
flag.store(true, Ordering::SeqCst);
});
drop(database);
assert!(ran.load(Ordering::SeqCst));
}
#[test]
fn a_database_dropped_on_its_own_thread_ends() {
let database = DatabaseFileSource::new(":memory:", None);
let queue = database.queue.clone();
let (dropped, done) = mpsc::channel();
queue.post(move |_| {
drop(database);
dropped.send(()).unwrap();
});
done.recv_timeout(Duration::from_secs(10)).expect("the drop returns");
}
}