Skip to main content

mln_engine/offline/
database_file_source.rs

1// `DatabaseFileSource` is in `storage`, which knows no styles, while
2// `OfflineDownload` parses them, so the region API is an extension trait here, on a
3// database whose worker keeps the regions' `Downloads` beside the database.
4// Its calls run on the database's thread, after those sent before.
5
6use std::sync::Arc;
7
8use crate::offline::offline_download::{Downloads, Post};
9use crate::storage::database_file_source::DatabaseQueue;
10#[cfg(feature = "bench")]
11use crate::storage::database_file_source::DatabaseWorker;
12use crate::storage::offline::{
13    OfflineRegion, OfflineRegionDefinition, OfflineRegionDownloadState, OfflineRegionExpiry, OfflineRegionMetadata,
14    OfflineRegionObserver, OfflineRegionStatus, OfflineRegions,
15};
16use crate::storage::offline_database::{DatabaseError, OfflineDatabase};
17use crate::storage::{DatabaseFileSource, FileSource};
18
19/// A database whose worker downloads its offline regions.
20pub type RegionDatabase = DatabaseFileSource<Downloads>;
21
22/// A database at `cache_path` whose regions download through `network` and
23/// read their styles against `registry`.
24#[must_use]
25pub fn region_database(
26    cache_path: &str,
27    network: Option<Arc<dyn FileSource>>,
28    registry: Arc<crate::Registry>,
29) -> RegionDatabase {
30    DatabaseFileSource::with_extension(cache_path, network, false, downloads(registry))
31}
32
33/// [`region_database`]'s worker at `cache_path`, and the queue that it and
34/// its downloads post to, with no thread: the caller runs the queue.
35#[cfg(feature = "bench")]
36pub(crate) fn region_worker(
37    cache_path: &str,
38    network: Arc<dyn FileSource>,
39    registry: Arc<crate::Registry>,
40) -> (DatabaseQueue<Downloads>, DatabaseWorker<Downloads>) {
41    let queue = DatabaseQueue::new();
42    let worker = DatabaseWorker::new(&queue, Some(network), cache_path, false, Box::new(downloads(registry)));
43    (queue, worker)
44}
45
46/// Makes a database worker's downloads, which read their styles against
47/// `registry`.
48fn downloads(
49    registry: Arc<crate::Registry>,
50) -> impl FnOnce(DatabaseQueue<Downloads>, Option<Arc<dyn FileSource>>) -> Downloads + Send + 'static {
51    |worker, network| Downloads::new(network, post_to(worker), registry)
52}
53
54/// Posts a download's task to the database's worker.
55fn post_to(worker: DatabaseQueue<Downloads>) -> Post {
56    Arc::new(move |task| worker.post(move |worker| task(&mut worker.db, &mut worker.extension)))
57}
58
59/// The region `region_id`, or [`DatabaseError::RegionNotFound`] when the
60/// database has none with that ID.
61fn require_region(db: &mut OfflineDatabase, region_id: i64) -> Result<OfflineRegion, DatabaseError> {
62    db.region(region_id)?.ok_or(DatabaseError::RegionNotFound(region_id))
63}
64
65/// The offline region API of a [`RegionDatabase`]. Every callback runs on
66/// the database thread.
67pub trait DatabaseFileSourceExt {
68    /// Lists every region in the database.
69    fn list_offline_regions(&self, callback: impl FnOnce(Result<OfflineRegions, DatabaseError>) + Send + 'static);
70
71    /// Gets the region `region_id`, or `None` if the database has none with
72    /// that id.
73    fn get_offline_region(
74        &self,
75        region_id: i64,
76        callback: impl FnOnce(Result<Option<OfflineRegion>, DatabaseError>) + Send + 'static,
77    );
78
79    /// Creates a region. The region starts inactive;
80    /// `set_offline_region_download_state` starts its download.
81    fn create_offline_region(
82        &self,
83        definition: &OfflineRegionDefinition,
84        metadata: &OfflineRegionMetadata,
85        callback: impl FnOnce(Result<OfflineRegion, DatabaseError>) + Send + 'static,
86    );
87
88    /// Replaces the region's metadata, and gives the updated region. Fails
89    /// when the database has no region `region_id`.
90    fn update_offline_metadata(
91        &self,
92        region_id: i64,
93        metadata: &OfflineRegionMetadata,
94        callback: impl FnOnce(Result<OfflineRegion, DatabaseError>) + Send + 'static,
95    );
96
97    /// Sets the region's only observer, replacing the previous one; `None`
98    /// removes it. Its methods run on the database thread. Fails when the
99    /// database has no region `region_id`.
100    fn set_offline_region_observer(
101        &self,
102        region_id: i64,
103        observer: Option<Box<dyn OfflineRegionObserver + Send>>,
104        callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static,
105    );
106
107    /// Starts or stops the region's download. Fails when the database has no
108    /// region `region_id`.
109    fn set_offline_region_download_state(
110        &self,
111        region_id: i64,
112        state: OfflineRegionDownloadState,
113        callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static,
114    );
115
116    /// Gives the region's download progress. Fails when the database has no
117    /// region `region_id`.
118    fn get_offline_region_status(
119        &self,
120        region_id: i64,
121        callback: impl FnOnce(Result<OfflineRegionStatus, DatabaseError>) + Send + 'static,
122    );
123
124    /// Gives how long the region's stored resources stay usable. Fails when
125    /// the database has no region `region_id`.
126    fn get_offline_region_expiry(
127        &self,
128        region_id: i64,
129        callback: impl FnOnce(Result<OfflineRegionExpiry, DatabaseError>) + Send + 'static,
130    );
131
132    /// Copies the regions of another database, and the resources and tiles
133    /// they use, into this one. Identical regions become one. The side
134    /// database is upgraded to the current schema in place, so it must be
135    /// writable.
136    fn merge_offline_regions(
137        &self,
138        side_database_path: &str,
139        callback: impl FnOnce(Result<OfflineRegions, DatabaseError>) + Send + 'static,
140    );
141
142    /// Stops the region's download and deletes the region, evicting the
143    /// resources no other region uses. Fails when the database has no region
144    /// `region_id`.
145    fn delete_offline_region(&self, region_id: i64, callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static);
146
147    /// Makes the region's resources stale, so maps revalidate them with
148    /// their server when they next use them, and its next download refreshes
149    /// them, which transfers nothing for resources that haven't changed.
150    /// Resources that must revalidate can't be used until they have.
151    fn invalidate_offline_region(
152        &self,
153        region_id: i64,
154        callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static,
155    );
156}
157
158impl DatabaseFileSourceExt for RegionDatabase {
159    fn list_offline_regions(&self, callback: impl FnOnce(Result<OfflineRegions, DatabaseError>) + Send + 'static) {
160        self.invoke(move |t| callback(t.db.list_regions()));
161    }
162
163    fn get_offline_region(
164        &self,
165        region_id: i64,
166        callback: impl FnOnce(Result<Option<OfflineRegion>, DatabaseError>) + Send + 'static,
167    ) {
168        self.invoke(move |t| callback(t.db.region(region_id)));
169    }
170
171    fn create_offline_region(
172        &self,
173        definition: &OfflineRegionDefinition,
174        metadata: &OfflineRegionMetadata,
175        callback: impl FnOnce(Result<OfflineRegion, DatabaseError>) + Send + 'static,
176    ) {
177        let (definition, metadata) = (definition.clone(), metadata.clone());
178        self.invoke(move |t| callback(t.db.create_region(&definition, &metadata)));
179    }
180
181    fn update_offline_metadata(
182        &self,
183        region_id: i64,
184        metadata: &OfflineRegionMetadata,
185        callback: impl FnOnce(Result<OfflineRegion, DatabaseError>) + Send + 'static,
186    ) {
187        let metadata = metadata.clone();
188        self.invoke(move |t| {
189            let result = require_region(&mut t.db, region_id)
190                .and_then(|_| t.db.update_metadata(region_id, &metadata))
191                .and_then(|_| require_region(&mut t.db, region_id));
192            callback(result);
193        });
194    }
195
196    fn set_offline_region_observer(
197        &self,
198        region_id: i64,
199        observer: Option<Box<dyn OfflineRegionObserver + Send>>,
200        callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static,
201    ) {
202        self.invoke(move |t| {
203            let download = t.extension.download(&mut t.db, region_id);
204            callback(download.map(|download| {
205                download.set_observer(observer.map(|observer| -> Box<dyn OfflineRegionObserver> { observer }));
206            }));
207        });
208    }
209
210    fn set_offline_region_download_state(
211        &self,
212        region_id: i64,
213        download_state: OfflineRegionDownloadState,
214        callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static,
215    ) {
216        self.invoke(move |t| {
217            let download = t.extension.download(&mut t.db, region_id);
218            callback(download.map(|download| download.set_state(download_state)));
219        });
220    }
221
222    fn get_offline_region_status(
223        &self,
224        region_id: i64,
225        callback: impl FnOnce(Result<OfflineRegionStatus, DatabaseError>) + Send + 'static,
226    ) {
227        self.invoke(move |t| {
228            let download = t.extension.download(&mut t.db, region_id);
229            callback(download.map(|download| download.status(&mut t.db)));
230        });
231    }
232
233    fn get_offline_region_expiry(
234        &self,
235        region_id: i64,
236        callback: impl FnOnce(Result<OfflineRegionExpiry, DatabaseError>) + Send + 'static,
237    ) {
238        self.invoke(move |t| {
239            callback(require_region(&mut t.db, region_id).and_then(|_| t.db.region_expiry(region_id)));
240        });
241    }
242
243    fn merge_offline_regions(
244        &self,
245        side_database_path: &str,
246        callback: impl FnOnce(Result<OfflineRegions, DatabaseError>) + Send + 'static,
247    ) {
248        let side_database_path = side_database_path.to_owned();
249        self.invoke(move |t| callback(t.db.merge_database(&side_database_path)));
250    }
251
252    fn delete_offline_region(&self, region_id: i64, callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static) {
253        self.invoke(move |t| {
254            let result = require_region(&mut t.db, region_id).and_then(|region| {
255                drop(t.extension.remove(region_id));
256                t.db.delete_region(&region)
257            });
258            callback(result);
259        });
260    }
261
262    fn invalidate_offline_region(
263        &self,
264        region_id: i64,
265        callback: impl FnOnce(Result<(), DatabaseError>) + Send + 'static,
266    ) {
267        self.invoke(move |t| {
268            let result = require_region(&mut t.db, region_id).and_then(|_| t.db.invalidate_region(region_id));
269            callback(result);
270        });
271    }
272}