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    /// The worker of a database at `cache_path`, with the extension that
48    /// `make` makes, whose tasks run from `queue`.
49    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        // A cache hit that leaves `accessed` timestamps to write, while no
61        // write is due, makes one due. A failed write isn't retried until
62        // the next cache hit, so an idle map stays idle.
63        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    /// Answers a request with the stored copy, whatever its freshness: its
79    /// caching rules say how it may be used. Without a copy, the answer has
80    /// no content and a `NotFound` error.
81    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
102/// A cache that a [`Loader`](crate::storage::Loader) reads before the network, and
103/// stores the network's responses in.
104pub trait Cache: FileSource {
105    /// Stores a response to `resource`, unless the resource is volatile.
106    fn put(&self, resource: &Resource, response: &Response);
107}
108
109/// The `Database` file source: the ambient cache and the offline regions,
110/// in an SQLite database that a worker thread owns, with the worker's
111/// extension `E` beside it. Its drop or [`shut_down`](Self::shut_down) waits
112/// for the worker to end, unless it runs on the worker's thread. When the
113/// worker's thread can't start, the source logs why, fails each request, and
114/// drops the work sent to it.
115pub struct DatabaseFileSource<E: 'static = ()> {
116    queue: DatabaseQueue<E>,
117    /// The worker's thread, until the database shuts down.
118    thread: Mutex<Option<std::thread::JoinHandle<()>>>,
119}
120
121impl DatabaseFileSource {
122    /// A database at `cache_path`, created if needed; `":memory:"` keeps it
123    /// in memory. Offline regions download through `network`, and can't
124    /// without one.
125    #[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    /// The database at `cache_path`, opened read-only: it answers requests
131    /// but stores nothing.
132    #[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    /// A database at `cache_path`, read-only or not, whose worker keeps the
140    /// extension that `make` makes on the worker's thread, from the
141    /// worker's queue and the database's network.
142    #[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            // What comes once the database has dropped drops at once, so the
157            // handles that the worker's extension holds can't keep the queue
158            // alive.
159            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    /// Holds the database thread until the guard drops (`crate::storage::tests::pause`).
173    #[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    /// Whether a task waits on the database thread for its time to come,
179    /// such as a write of cache hits' `accessed` timestamps.
180    #[cfg(test)]
181    pub(crate) fn has_timed_task(&self) -> bool {
182        self.queue.next_deadline().is_some()
183    }
184
185    /// Deletes the database file and starts an empty one. The callback runs
186    /// on the database thread.
187    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    /// Vacuums the database file to the space its data needs. The callback
192    /// runs on the database thread.
193    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    /// Makes the ambient cache's resources revalidate with their server
198    /// before use. Offline regions' resources are unaffected. The callback
199    /// runs on the database thread.
200    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    /// Erases the ambient cache's resources. Offline regions' resources are
205    /// unaffected. The callback runs on the database thread.
206    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    /// Limits the database to `size` bytes, evicting ambient resources to
211    /// fit. Offline regions count towards the limit but are never evicted; 0
212    /// disables the ambient cache. The callback runs on the database thread.
213    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    /// Runs `f` on the database thread, after the requests and operations
222    /// sent before it.
223    pub fn invoke(&self, f: impl FnOnce(&mut DatabaseWorker<E>) + Send + 'static) {
224        self.queue.post(f);
225    }
226
227    /// Stops the database, as its drop does, for an owner that must know
228    /// its worker has ended although the database may be held elsewhere.
229    /// The first call waits for the worker, unless it runs on the worker's
230    /// thread; a later call returns at once, so one owner shuts it down.
231    /// The work sent after drops, and requests fail as when the thread
232    /// didn't start.
233    pub fn shut_down(&self) {
234        self.queue.stop();
235        // Released before the join, as the thread may load from this source
236        // meanwhile.
237        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    /// The last owner of a database may drop it on the database's thread.
305    #[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}