1use std::sync::Arc;
11use std::sync::atomic::{AtomicBool, Ordering};
12use std::time::Duration;
13
14use parking_lot::Mutex;
15
16use crate::exec::queue::Queue;
17use crate::log_target;
18use crate::storage::constants::{ASSET_PROTOCOL, FILE_PROTOCOL};
19use crate::storage::file_source::FileSource;
20use crate::storage::offline_database::{DatabaseError, OfflineDatabase};
21use crate::storage::request::Responder;
22use crate::storage::resource::{LoadingMethod, Resource, StoragePolicy};
23use crate::storage::response::{Reason, ResourceError, Response};
24
25const ACCESSED_FLUSH_DELAY: Duration = Duration::from_millis(250);
28
29pub(crate) type DatabaseQueue<E> = Queue<DatabaseWorker<E>>;
33
34pub struct DatabaseWorker<E: 'static> {
38 pub(crate) db: OfflineDatabase,
39 pub(crate) extension: E,
40}
41
42type MakeExtension<E> = Box<dyn FnOnce(DatabaseQueue<E>, Option<Arc<dyn FileSource>>) -> E + Send>;
45
46impl<E: 'static> DatabaseWorker<E> {
47 pub(crate) fn new(
50 queue: &DatabaseQueue<E>,
51 network: Option<Arc<dyn FileSource>>,
52 cache_path: &str,
53 read_only: bool,
54 make: MakeExtension<E>,
55 ) -> Self {
56 let mut db = OfflineDatabase::new(cache_path);
57 if read_only {
58 db.reopen_database_read_only(true);
59 }
60 let due = Arc::new(AtomicBool::new(false));
64 let flush = queue.clone();
65 db.set_accessed_callback(Box::new(move || {
66 if !due.swap(true, Ordering::Relaxed) {
67 let due = Arc::clone(&due);
68 flush.post_after(ACCESSED_FLUSH_DELAY, move |worker| {
69 due.store(false, Ordering::Relaxed);
70 worker.db.flush_accessed();
71 });
72 }
73 }));
74 let extension = make(queue.clone(), network);
75 DatabaseWorker { db, extension }
76 }
77
78 fn request(&mut self, resource: &Resource, responder: &Responder) {
82 let offline_response =
83 if resource.storage_policy == StoragePolicy::Volatile { None } else { self.db.get(resource) };
84 let response = offline_response.unwrap_or_else(|| {
85 let mut response = Response::new();
86 response.no_content = true;
87 response.error = Some(Box::new(ResourceError::new(Reason::NotFound, "Not found in offline database")));
88 response
89 });
90 responder.send(response);
91 }
92
93 fn maintain(
94 &mut self,
95 operation: impl FnOnce(&mut OfflineDatabase) -> Result<(), DatabaseError>,
96 callback: impl FnOnce(Result<(), DatabaseError>),
97 ) {
98 callback(operation(&mut self.db));
99 }
100}
101
102pub trait Cache: FileSource {
105 fn put(&self, resource: &Resource, response: &Response);
107}
108
109pub struct DatabaseFileSource<E: 'static = ()> {
116 queue: DatabaseQueue<E>,
117 thread: Mutex<Option<std::thread::JoinHandle<()>>>,
119}
120
121impl DatabaseFileSource {
122 #[must_use]
126 pub fn new(cache_path: &str, network: Option<Arc<dyn FileSource>>) -> Self {
127 Self::with_extension(cache_path, network, false, |_, _| ())
128 }
129
130 #[must_use]
133 pub fn read_only(cache_path: &str, network: Option<Arc<dyn FileSource>>) -> Self {
134 Self::with_extension(cache_path, network, true, |_, _| ())
135 }
136}
137
138impl<E: 'static> DatabaseFileSource<E> {
139 #[must_use]
143 pub(crate) fn with_extension(
144 cache_path: &str,
145 network: Option<Arc<dyn FileSource>>,
146 read_only: bool,
147 make: impl FnOnce(DatabaseQueue<E>, Option<Arc<dyn FileSource>>) -> E + Send + 'static,
148 ) -> Self {
149 let cache_path = cache_path.to_owned();
150 let make: MakeExtension<E> = Box::new(make);
151 let queue = DatabaseQueue::new();
152 let own = queue.clone();
153 let thread = crate::exec::thread::spawn("DatabaseFileSource", move || {
154 let mut worker = DatabaseWorker::new(&own, network, &cache_path, read_only, make);
155 own.run(&mut worker);
156 own.close();
160 drop(worker);
161 })
162 .inspect_err(
163 |error| tracing::error!(target: log_target::DATABASE, error = %error, "The database's thread didn't start"),
164 )
165 .ok();
166 if thread.is_none() {
167 queue.close();
168 }
169 DatabaseFileSource { queue, thread: Mutex::new(thread) }
170 }
171
172 #[cfg(test)]
174 pub(crate) fn pause(&self) -> crate::storage::tests::Paused {
175 crate::storage::tests::pause(|hold| self.invoke(move |_| hold()))
176 }
177
178 #[cfg(test)]
181 pub(crate) fn has_timed_task(&self) -> bool {
182 self.queue.next_deadline().is_some()
183 }
184
185 pub fn reset_database(&self, callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static) {
188 self.invoke(move |t| t.maintain(OfflineDatabase::reset_database, callback));
189 }
190
191 pub fn pack_database(&self, callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static) {
194 self.invoke(move |t| t.maintain(OfflineDatabase::pack, callback));
195 }
196
197 pub fn invalidate_ambient_cache(&self, callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static) {
201 self.invoke(move |t| t.maintain(OfflineDatabase::invalidate_ambient_cache, callback));
202 }
203
204 pub fn clear_ambient_cache(&self, callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static) {
207 self.invoke(move |t| t.maintain(OfflineDatabase::clear_ambient_cache, callback));
208 }
209
210 pub fn set_maximum_ambient_cache_size(
214 &self,
215 size: u64,
216 callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static,
217 ) {
218 self.invoke(move |t| t.maintain(|db| db.set_maximum_ambient_cache_size(size), callback));
219 }
220
221 pub fn invoke(&self, f: impl FnOnce(&mut DatabaseWorker<E>) + Send + 'static) {
224 self.queue.post(f);
225 }
226
227 pub fn shut_down(&self) {
234 self.queue.stop();
235 let thread = self.thread.lock().take();
238 if let Some(thread) = thread
239 && thread.thread().id() != std::thread::current().id()
240 {
241 let _ = thread.join();
242 }
243 }
244}
245
246impl<E: 'static> Drop for DatabaseFileSource<E> {
247 fn drop(&mut self) {
248 self.shut_down();
249 }
250}
251
252impl<E: 'static> Cache for DatabaseFileSource<E> {
253 fn put(&self, resource: &Resource, response: &Response) {
254 if resource.storage_policy == StoragePolicy::Volatile {
255 return;
256 }
257 let resource = resource.clone();
258 let response = response.clone();
259 self.invoke(move |t| {
260 t.db.put(&resource, &response);
261 });
262 }
263}
264
265impl<E: 'static> FileSource for DatabaseFileSource<E> {
266 fn load(&self, resource: &Resource, responder: Responder) {
267 if self.thread.lock().is_none() {
268 let mut response = Response::new();
269 response.error = Some(Box::new(ResourceError::new(Reason::Other, "The database's thread isn't running.")));
270 responder.send(response);
271 return;
272 }
273 let resource = resource.clone();
274 self.invoke(move |worker| {
275 if !responder.is_cancelled() {
276 worker.request(&resource, &responder);
277 }
278 });
279 }
280
281 fn can_request(&self, resource: &Resource) -> bool {
282 resource.has_loading_method(LoadingMethod::CACHE)
283 && !resource.url.starts_with(ASSET_PROTOCOL)
284 && !resource.url.starts_with(FILE_PROTOCOL)
285 }
286}
287
288#[cfg(test)]
289mod tests {
290 use std::sync::mpsc;
291
292 use super::*;
293
294 #[test]
295 fn a_drop_waits_for_the_work_sent_before() {
296 let database = DatabaseFileSource::new(":memory:", None);
297 let ran = Arc::new(AtomicBool::new(false));
298 let flag = Arc::clone(&ran);
299 database.invoke(move |_| flag.store(true, Ordering::SeqCst));
300 drop(database);
301 assert!(ran.load(Ordering::SeqCst));
302 }
303
304 #[test]
306 fn a_database_dropped_on_its_own_thread_ends() {
307 let database = DatabaseFileSource::new(":memory:", None);
308 let queue = database.queue.clone();
309 let (dropped, done) = mpsc::channel();
310 queue.post(move |_| {
311 drop(database);
312 dropped.send(()).unwrap();
313 });
314 done.recv().expect("the drop returns");
315 }
316}