Skip to main content

mln_engine/storage/
database_file_source.rs

1// The database runs on a worker thread of its own ("DatabaseFileSource"),
2// which owns it and runs the tasks of its queue: requests and operations
3// reach the worker as tasks, and the responses go to the requests'
4// responders.
5//
6// The offline region downloads need the style parser: `offline` keeps them in the worker's extension, which the
7// worker owns beside the database, and which posts its own work to the
8// worker's queue.
9
10use 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
25/// How long cache hits' `accessed` timestamps wait, so that the reads of a
26/// map load share one write.
27const ACCESSED_FLUSH_DELAY: Duration = Duration::from_millis(250);
28
29/// The queue of a database's worker, whose tasks run on the database's
30/// thread in the order they were posted. Once the database has dropped, the
31/// worker has ended and the queue drops what is posted to it.
32pub(crate) type DatabaseQueue<E> = Queue<DatabaseWorker<E>>;
33
34/// What a database's worker owns, on the database's thread: the database,
35/// and what an extension keeps beside it, such as the offline regions'
36/// downloads.
37pub struct DatabaseWorker<E: 'static> {
38    pub(crate) db: OfflineDatabase,
39    pub(crate) extension: E,
40}
41
42/// Makes the extension of a database worker, on the worker's thread, from
43/// the worker's queue and its network.
44type MakeExtension<E> = Box<dyn FnOnce(DatabaseQueue<E>, Option<Arc<dyn FileSource>>) -> E + Send>;
45
46impl<E: 'static> DatabaseWorker<E> {
47    fn new(
48        queue: &DatabaseQueue<E>,
49        network: Option<Arc<dyn FileSource>>,
50        cache_path: &str,
51        read_only: bool,
52        make: MakeExtension<E>,
53    ) -> Self {
54        let mut db = OfflineDatabase::new(cache_path);
55        if read_only {
56            db.reopen_database_read_only(true);
57        }
58        // A cache hit that leaves `accessed` timestamps to write, while no
59        // write is due, makes one due. A failed write isn't retried until
60        // the next cache hit, so an idle map stays idle.
61        let due = Arc::new(AtomicBool::new(false));
62        let flush = queue.clone();
63        db.set_accessed_callback(Box::new(move || {
64            if !due.swap(true, Ordering::Relaxed) {
65                let due = Arc::clone(&due);
66                flush.post_after(ACCESSED_FLUSH_DELAY, move |worker| {
67                    due.store(false, Ordering::Relaxed);
68                    worker.db.flush_accessed();
69                });
70            }
71        }));
72        let extension = make(queue.clone(), network);
73        DatabaseWorker { db, extension }
74    }
75
76    /// Answers a request with the stored copy, whatever its freshness: its
77    /// caching rules say how it may be used. Without a copy, the answer has
78    /// no content and a `NotFound` error.
79    fn request(&mut self, resource: &Resource, responder: &Responder) {
80        let offline_response =
81            if resource.storage_policy == StoragePolicy::Volatile { None } else { self.db.get(resource) };
82        let response = offline_response.unwrap_or_else(|| {
83            let mut response = Response::new();
84            response.no_content = true;
85            response.error = Some(Box::new(ResourceError::new(Reason::NotFound, "Not found in offline database")));
86            response
87        });
88        responder.send(response);
89    }
90
91    fn maintain(
92        &mut self,
93        operation: impl FnOnce(&mut OfflineDatabase) -> Result<(), DatabaseError>,
94        callback: impl FnOnce(Result<(), DatabaseError>),
95    ) {
96        callback(operation(&mut self.db));
97    }
98}
99
100/// A cache that a [`Loader`](crate::storage::Loader) reads before the network, and
101/// stores the network's responses in.
102pub trait Cache: FileSource {
103    /// Stores a response to `resource`, unless the resource is volatile.
104    fn put(&self, resource: &Resource, response: &Response);
105}
106
107/// The `Database` file source: the ambient cache and the offline regions,
108/// in an SQLite database that a worker thread owns, with the worker's
109/// extension `E` beside it. Its drop or [`shut_down`](Self::shut_down) waits
110/// for the worker to end, unless it runs on the worker's thread. When the
111/// worker's thread can't start, the source logs why, fails each request, and
112/// drops the work sent to it.
113pub struct DatabaseFileSource<E: 'static = ()> {
114    queue: DatabaseQueue<E>,
115    /// The worker's thread, until the database shuts down.
116    thread: Mutex<Option<std::thread::JoinHandle<()>>>,
117}
118
119impl DatabaseFileSource {
120    /// A database at `cache_path`, created if needed; `":memory:"` keeps it
121    /// in memory. Offline regions download through `network`, and can't
122    /// without one.
123    #[must_use]
124    pub fn new(cache_path: &str, network: Option<Arc<dyn FileSource>>) -> Self {
125        Self::with_extension(cache_path, network, false, |_, _| ())
126    }
127
128    /// The database at `cache_path`, opened read-only: it answers requests
129    /// but stores nothing.
130    #[must_use]
131    pub fn read_only(cache_path: &str, network: Option<Arc<dyn FileSource>>) -> Self {
132        Self::with_extension(cache_path, network, true, |_, _| ())
133    }
134}
135
136impl<E: 'static> DatabaseFileSource<E> {
137    /// A database at `cache_path`, read-only or not, whose worker keeps the
138    /// extension that `make` makes on the worker's thread, from the
139    /// worker's queue and the database's network.
140    #[must_use]
141    pub(crate) fn with_extension(
142        cache_path: &str,
143        network: Option<Arc<dyn FileSource>>,
144        read_only: bool,
145        make: impl FnOnce(DatabaseQueue<E>, Option<Arc<dyn FileSource>>) -> E + Send + 'static,
146    ) -> Self {
147        let cache_path = cache_path.to_owned();
148        let make: MakeExtension<E> = Box::new(make);
149        let queue = DatabaseQueue::new();
150        let own = queue.clone();
151        let thread = crate::exec::thread::spawn("DatabaseFileSource", move || {
152            let mut worker = DatabaseWorker::new(&own, network, &cache_path, read_only, make);
153            own.run(&mut worker);
154            // What comes once the database has dropped drops at once, so the
155            // handles that the worker's extension holds can't keep the queue
156            // alive.
157            own.close();
158            drop(worker);
159        })
160        .inspect_err(
161            |error| tracing::error!(target: log_target::DATABASE, error = %error, "The database's thread didn't start"),
162        )
163        .ok();
164        if thread.is_none() {
165            queue.close();
166        }
167        DatabaseFileSource { queue, thread: Mutex::new(thread) }
168    }
169
170    /// Holds the database thread until the guard drops (`crate::storage::tests::pause`).
171    #[cfg(test)]
172    pub(crate) fn pause(&self) -> crate::storage::tests::Paused {
173        crate::storage::tests::pause(|hold| self.invoke(move |_| hold()))
174    }
175
176    /// Whether a task waits on the database thread for its time to come,
177    /// such as a write of cache hits' `accessed` timestamps.
178    #[cfg(test)]
179    pub(crate) fn has_timed_task(&self) -> bool {
180        self.queue.next_deadline().is_some()
181    }
182
183    /// Switches to the database at `path`, creating it if needed. The
184    /// callback runs on the database thread.
185    #[cfg(test)]
186    pub(crate) fn set_database_path(&self, path: &str, callback: Option<Box<dyn FnOnce() + Send>>) {
187        let path = path.to_owned();
188        self.invoke(move |t| {
189            t.db.change_path(&path);
190            if let Some(callback) = callback {
191                callback();
192            }
193        });
194    }
195
196    /// Stores a response to `resource`, then runs `then` on the database
197    /// thread.
198    #[cfg(test)]
199    pub(crate) fn put_then(&self, resource: &Resource, response: &Response, then: Box<dyn FnOnce() + Send>) {
200        let resource = resource.clone();
201        let response = response.clone();
202        self.invoke(move |t| {
203            t.db.put(&resource, &response);
204            then();
205        });
206    }
207
208    /// Deletes the database file and starts an empty one. The callback runs
209    /// on the database thread.
210    pub fn reset_database(&self, callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static) {
211        self.invoke(move |t| t.maintain(OfflineDatabase::reset_database, callback));
212    }
213
214    /// Vacuums the database file to the space its data needs. The callback
215    /// runs on the database thread.
216    pub fn pack_database(&self, callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static) {
217        self.invoke(move |t| t.maintain(OfflineDatabase::pack, callback));
218    }
219
220    /// Makes the ambient cache's resources revalidate with their server
221    /// before use. Offline regions' resources are unaffected. The callback
222    /// runs on the database thread.
223    pub fn invalidate_ambient_cache(&self, callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static) {
224        self.invoke(move |t| t.maintain(OfflineDatabase::invalidate_ambient_cache, callback));
225    }
226
227    /// Erases the ambient cache's resources. Offline regions' resources are
228    /// unaffected. The callback runs on the database thread.
229    pub fn clear_ambient_cache(&self, callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static) {
230        self.invoke(move |t| t.maintain(OfflineDatabase::clear_ambient_cache, callback));
231    }
232
233    /// Limits the database to `size` bytes, evicting ambient resources to
234    /// fit. Offline regions count towards the limit but are never evicted; 0
235    /// disables the ambient cache. The callback runs on the database thread.
236    pub fn set_maximum_ambient_cache_size(
237        &self,
238        size: u64,
239        callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static,
240    ) {
241        self.invoke(move |t| t.maintain(|db| db.set_maximum_ambient_cache_size(size), callback));
242    }
243
244    /// Runs `f` on the database thread, after the requests and operations
245    /// sent before it.
246    pub fn invoke(&self, f: impl FnOnce(&mut DatabaseWorker<E>) + Send + 'static) {
247        self.queue.post(f);
248    }
249
250    /// Stops the database, as its drop does, for an owner that must know
251    /// its worker has ended although the database may be held elsewhere.
252    /// The first call waits for the worker, unless it runs on the worker's
253    /// thread; a later call returns at once, so one owner shuts it down.
254    /// The work sent after drops, and requests fail as when the thread
255    /// didn't start.
256    pub fn shut_down(&self) {
257        self.queue.stop();
258        // Released before the join, as the thread may load from this source
259        // meanwhile.
260        let thread = self.thread.lock().take();
261        if let Some(thread) = thread
262            && thread.thread().id() != std::thread::current().id()
263        {
264            let _ = thread.join();
265        }
266    }
267}
268
269impl<E: 'static> Drop for DatabaseFileSource<E> {
270    fn drop(&mut self) {
271        self.shut_down();
272    }
273}
274
275impl<E: 'static> Cache for DatabaseFileSource<E> {
276    fn put(&self, resource: &Resource, response: &Response) {
277        if resource.storage_policy == StoragePolicy::Volatile {
278            return;
279        }
280        let resource = resource.clone();
281        let response = response.clone();
282        self.invoke(move |t| {
283            t.db.put(&resource, &response);
284        });
285    }
286}
287
288impl<E: 'static> FileSource for DatabaseFileSource<E> {
289    fn load(&self, resource: &Resource, responder: Responder) {
290        if self.thread.lock().is_none() {
291            let mut response = Response::new();
292            response.error = Some(Box::new(ResourceError::new(Reason::Other, "The database's thread isn't running.")));
293            responder.send(response);
294            return;
295        }
296        let resource = resource.clone();
297        self.invoke(move |worker| {
298            if !responder.is_cancelled() {
299                worker.request(&resource, &responder);
300            }
301        });
302    }
303
304    fn can_request(&self, resource: &Resource) -> bool {
305        resource.has_loading_method(LoadingMethod::CACHE)
306            && !resource.url.starts_with(ASSET_PROTOCOL)
307            && !resource.url.starts_with(FILE_PROTOCOL)
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use std::sync::mpsc;
314
315    use super::*;
316
317    #[test]
318    fn a_drop_waits_for_the_work_sent_before() {
319        let database = DatabaseFileSource::new(":memory:", None);
320        let ran = Arc::new(AtomicBool::new(false));
321        let flag = Arc::clone(&ran);
322        database.invoke(move |_| {
323            std::thread::sleep(Duration::from_millis(50));
324            flag.store(true, Ordering::SeqCst);
325        });
326        drop(database);
327        assert!(ran.load(Ordering::SeqCst));
328    }
329
330    /// The last owner of a database may drop it on the database's thread.
331    #[test]
332    fn a_database_dropped_on_its_own_thread_ends() {
333        let database = DatabaseFileSource::new(":memory:", None);
334        let queue = database.queue.clone();
335        let (dropped, done) = mpsc::channel();
336        queue.post(move |_| {
337            drop(database);
338            dropped.send(()).unwrap();
339        });
340        done.recv_timeout(Duration::from_secs(10)).expect("the drop returns");
341    }
342}