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