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