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