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(|error| log::error!(target: log_target::DATABASE, "The database's thread didn't start: {error}"))
161        .ok();
162        if thread.is_none() {
163            queue.close();
164        }
165        DatabaseFileSource { queue, thread: Mutex::new(thread) }
166    }
167
168    /// Holds the database thread until the guard drops (`crate::storage::tests::pause`).
169    #[cfg(test)]
170    pub(crate) fn pause(&self) -> crate::storage::tests::Paused {
171        crate::storage::tests::pause(|hold| self.invoke(move |_| hold()))
172    }
173
174    /// Whether a task waits on the database thread for its time to come,
175    /// such as a write of cache hits' `accessed` timestamps.
176    #[cfg(test)]
177    pub(crate) fn has_timed_task(&self) -> bool {
178        self.queue.next_deadline().is_some()
179    }
180
181    /// Switches to the database at `path`, creating it if needed. The
182    /// callback runs on the database thread.
183    #[cfg(test)]
184    pub(crate) fn set_database_path(&self, path: &str, callback: Option<Box<dyn FnOnce() + Send>>) {
185        let path = path.to_owned();
186        self.invoke(move |t| {
187            t.db.change_path(&path);
188            if let Some(callback) = callback {
189                callback();
190            }
191        });
192    }
193
194    /// Stores a response to `resource`, then runs `then` on the database
195    /// thread.
196    #[cfg(test)]
197    pub(crate) fn put_then(&self, resource: &Resource, response: &Response, then: Box<dyn FnOnce() + Send>) {
198        let resource = resource.clone();
199        let response = response.clone();
200        self.invoke(move |t| {
201            t.db.put(&resource, &response);
202            then();
203        });
204    }
205
206    /// Deletes the database file and starts an empty one. The callback runs
207    /// on the database thread.
208    pub fn reset_database(&self, callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static) {
209        self.invoke(move |t| t.maintain(OfflineDatabase::reset_database, callback));
210    }
211
212    /// Vacuums the database file to the space its data needs. The callback
213    /// runs on the database thread.
214    pub fn pack_database(&self, callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static) {
215        self.invoke(move |t| t.maintain(OfflineDatabase::pack, callback));
216    }
217
218    /// Makes the ambient cache's resources revalidate with their server
219    /// before use. Offline regions' resources are unaffected. The callback
220    /// runs on the database thread.
221    pub fn invalidate_ambient_cache(&self, callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static) {
222        self.invoke(move |t| t.maintain(OfflineDatabase::invalidate_ambient_cache, callback));
223    }
224
225    /// Erases the ambient cache's resources. Offline regions' resources are
226    /// unaffected. The callback runs on the database thread.
227    pub fn clear_ambient_cache(&self, callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static) {
228        self.invoke(move |t| t.maintain(OfflineDatabase::clear_ambient_cache, callback));
229    }
230
231    /// Limits the database to `size` bytes, evicting ambient resources to
232    /// fit. Offline regions count towards the limit but are never evicted; 0
233    /// disables the ambient cache. The callback runs on the database thread.
234    pub fn set_maximum_ambient_cache_size(
235        &self,
236        size: u64,
237        callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static,
238    ) {
239        self.invoke(move |t| t.maintain(|db| db.set_maximum_ambient_cache_size(size), callback));
240    }
241
242    /// Runs `f` on the database thread, after the requests and operations
243    /// sent before it.
244    pub fn invoke(&self, f: impl FnOnce(&mut DatabaseWorker<E>) + Send + 'static) {
245        self.queue.post(f);
246    }
247
248    /// Stops the database, as its drop does, for an owner that must know
249    /// its worker has ended although the database may be held elsewhere.
250    /// The first call waits for the worker, unless it runs on the worker's
251    /// thread; a later call returns at once, so one owner shuts it down.
252    /// The work sent after drops, and requests fail as when the thread
253    /// didn't start.
254    pub fn shut_down(&self) {
255        self.queue.stop();
256        // Released before the join, as the thread may load from this source
257        // meanwhile.
258        let thread = self.thread.lock().take();
259        if let Some(thread) = thread
260            && thread.thread().id() != std::thread::current().id()
261        {
262            let _ = thread.join();
263        }
264    }
265}
266
267impl<E: 'static> Drop for DatabaseFileSource<E> {
268    fn drop(&mut self) {
269        self.shut_down();
270    }
271}
272
273impl<E: 'static> Cache for DatabaseFileSource<E> {
274    fn put(&self, resource: &Resource, response: &Response) {
275        if resource.storage_policy == StoragePolicy::Volatile {
276            return;
277        }
278        let resource = resource.clone();
279        let response = response.clone();
280        self.invoke(move |t| {
281            t.db.put(&resource, &response);
282        });
283    }
284}
285
286impl<E: 'static> FileSource for DatabaseFileSource<E> {
287    fn load(&self, resource: &Resource, responder: Responder) {
288        if self.thread.lock().is_none() {
289            let mut response = Response::new();
290            response.error = Some(Box::new(ResourceError::new(Reason::Other, "The database's thread isn't running.")));
291            responder.send(response);
292            return;
293        }
294        let resource = resource.clone();
295        self.invoke(move |worker| {
296            if !responder.is_cancelled() {
297                worker.request(&resource, &responder);
298            }
299        });
300    }
301
302    fn can_request(&self, resource: &Resource) -> bool {
303        resource.has_loading_method(LoadingMethod::Cache)
304            && !resource.url.starts_with(ASSET_PROTOCOL)
305            && !resource.url.starts_with(FILE_PROTOCOL)
306    }
307}
308
309#[cfg(test)]
310mod tests {
311    use std::sync::mpsc;
312
313    use super::*;
314
315    #[test]
316    fn a_drop_waits_for_the_work_sent_before() {
317        let database = DatabaseFileSource::new(":memory:", None);
318        let ran = Arc::new(AtomicBool::new(false));
319        let flag = Arc::clone(&ran);
320        database.invoke(move |_| {
321            std::thread::sleep(Duration::from_millis(50));
322            flag.store(true, Ordering::SeqCst);
323        });
324        drop(database);
325        assert!(ran.load(Ordering::SeqCst));
326    }
327
328    /// The last owner of a database may drop it on the database's thread.
329    #[test]
330    fn a_database_dropped_on_its_own_thread_ends() {
331        let database = DatabaseFileSource::new(":memory:", None);
332        let queue = database.queue.clone();
333        let (dropped, done) = mpsc::channel();
334        queue.post(move |_| {
335            drop(database);
336            dropped.send(()).unwrap();
337        });
338        done.recv_timeout(Duration::from_secs(10)).expect("the drop returns");
339    }
340}