Skip to main content

mln_engine/storage/
offline.rs

1// Region definitions are JSON in the format MapLibre Native's offline API
2// writes, so that this reads its databases.
3
4use geo_types::Geometry;
5use mln_style::error::Error;
6#[cfg(any(test, feature = "sqlite"))]
7use mln_style::geo::LatLng;
8use mln_style::geo::LatLngBounds;
9#[cfg(any(test, feature = "sqlite"))]
10use serde_json::{Map, Value as Json};
11
12use crate::storage::chrono::Timestamp;
13use crate::storage::response::ResourceError;
14
15fn check_definition(min_zoom: f64, max_zoom: f64, pixel_ratio: f32) -> Result<(), Error> {
16    if !min_zoom.is_finite() || min_zoom < 0.0 || max_zoom.is_nan() || max_zoom < min_zoom {
17        return Err(Error::invalid_argument("offline region zoom range is invalid"));
18    }
19    if !pixel_ratio.is_finite() || pixel_ratio < 0.0 {
20        return Err(Error::invalid_argument("offline region pixel ratio is invalid"));
21    }
22    Ok(())
23}
24
25/// An offline region defined by a style URL, geographic bounding box, zoom
26/// range, and device pixel ratio.
27///
28/// Both minZoom and maxZoom must be ≥ 0, and maxZoom must be ≥ minZoom.
29///
30/// maxZoom may be ∞, in which case for each tile source, the region will
31/// include tiles from minZoom up to the maximum zoom level provided by that
32/// source.
33///
34/// pixelRatio must be ≥ 0 and should typically be 1.0 or 2.0.
35#[derive(Clone, Debug, PartialEq)]
36pub struct OfflineTilePyramidRegionDefinition {
37    pub(crate) style_url: String,
38    pub bounds: LatLngBounds,
39    pub(crate) min_zoom: f64,
40    pub(crate) max_zoom: f64,
41    pub(crate) pixel_ratio: f32,
42    pub(crate) include_ideographs: bool,
43}
44
45impl OfflineTilePyramidRegionDefinition {
46    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a
47    /// negative or reversed zoom range, or a negative or infinite pixel ratio.
48    pub fn new(
49        style_url: impl Into<String>,
50        bounds: LatLngBounds,
51        min_zoom: f64,
52        max_zoom: f64,
53        pixel_ratio: f32,
54        include_ideographs: bool,
55    ) -> Result<Self, Error> {
56        check_definition(min_zoom, max_zoom, pixel_ratio)?;
57        Ok(OfflineTilePyramidRegionDefinition {
58            style_url: style_url.into(),
59            bounds,
60            min_zoom,
61            max_zoom,
62            pixel_ratio,
63            include_ideographs,
64        })
65    }
66}
67
68/// An offline region defined by a style URL, geometry, zoom range, and
69/// device pixel ratio.
70///
71/// Both minZoom and maxZoom must be ≥ 0, and maxZoom must be ≥ minZoom.
72///
73/// maxZoom may be ∞, in which case for each tile source, the region will
74/// include tiles from minZoom up to the maximum zoom level provided by that
75/// source.
76///
77/// pixelRatio must be ≥ 0 and should typically be 1.0 or 2.0.
78#[derive(Clone, Debug, PartialEq)]
79pub struct OfflineGeometryRegionDefinition {
80    pub(crate) style_url: String,
81    pub geometry: Geometry<f64>,
82    pub(crate) min_zoom: f64,
83    pub(crate) max_zoom: f64,
84    pub(crate) pixel_ratio: f32,
85    pub(crate) include_ideographs: bool,
86}
87
88impl OfflineGeometryRegionDefinition {
89    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a
90    /// negative or reversed zoom range, or a negative or infinite pixel ratio.
91    pub fn new(
92        style_url: impl Into<String>,
93        geometry: Geometry<f64>,
94        min_zoom: f64,
95        max_zoom: f64,
96        pixel_ratio: f32,
97        include_ideographs: bool,
98    ) -> Result<Self, Error> {
99        check_definition(min_zoom, max_zoom, pixel_ratio)?;
100        Ok(OfflineGeometryRegionDefinition {
101            style_url: style_url.into(),
102            geometry,
103            min_zoom,
104            max_zoom,
105            pixel_ratio,
106            include_ideographs,
107        })
108    }
109}
110
111/// The offline region definition types supported.
112#[derive(Clone, Debug, PartialEq)]
113pub enum OfflineRegionDefinition {
114    TilePyramid(OfflineTilePyramidRegionDefinition),
115    Geometry(OfflineGeometryRegionDefinition),
116}
117
118impl From<OfflineTilePyramidRegionDefinition> for OfflineRegionDefinition {
119    fn from(definition: OfflineTilePyramidRegionDefinition) -> Self {
120        OfflineRegionDefinition::TilePyramid(definition)
121    }
122}
123
124impl From<OfflineGeometryRegionDefinition> for OfflineRegionDefinition {
125    fn from(definition: OfflineGeometryRegionDefinition) -> Self {
126        OfflineRegionDefinition::Geometry(definition)
127    }
128}
129
130impl OfflineRegionDefinition {
131    // The members both kinds of definition have.
132
133    #[must_use]
134    pub fn style_url(&self) -> &str {
135        match self {
136            OfflineRegionDefinition::TilePyramid(r) => &r.style_url,
137            OfflineRegionDefinition::Geometry(r) => &r.style_url,
138        }
139    }
140
141    #[must_use]
142    pub fn min_zoom(&self) -> f64 {
143        match self {
144            OfflineRegionDefinition::TilePyramid(r) => r.min_zoom,
145            OfflineRegionDefinition::Geometry(r) => r.min_zoom,
146        }
147    }
148
149    #[must_use]
150    pub fn max_zoom(&self) -> f64 {
151        match self {
152            OfflineRegionDefinition::TilePyramid(r) => r.max_zoom,
153            OfflineRegionDefinition::Geometry(r) => r.max_zoom,
154        }
155    }
156
157    #[must_use]
158    pub fn pixel_ratio(&self) -> f32 {
159        match self {
160            OfflineRegionDefinition::TilePyramid(r) => r.pixel_ratio,
161            OfflineRegionDefinition::Geometry(r) => r.pixel_ratio,
162        }
163    }
164
165    #[must_use]
166    pub fn include_ideographs(&self) -> bool {
167        match self {
168            OfflineRegionDefinition::TilePyramid(r) => r.include_ideographs,
169            OfflineRegionDefinition::Geometry(r) => r.include_ideographs,
170        }
171    }
172}
173
174/// Decodes a region definition from JSON. A definition that isn't one fails
175/// with [`ErrorKind::Failed`](mln_style::error::ErrorKind), and one
176/// with invalid values with the constructors' error.
177#[cfg(any(test, feature = "sqlite"))]
178pub(crate) fn decode_offline_region_definition(region: &[u8]) -> Result<OfflineRegionDefinition, Error> {
179    let malformed = || Error::failed("Malformed offline region definition");
180
181    let doc: Json = serde_json::from_slice(region).map_err(|_| malformed())?;
182    let doc = doc.as_object().ok_or_else(malformed)?;
183    let member = |name: &str| doc.get(name);
184    let number = |name: &str| member(name).map(|v| v.as_f64().ok_or_else(malformed)).transpose();
185
186    let style_url = member("style_url").and_then(Json::as_str).ok_or_else(malformed)?.to_owned();
187    let min_zoom = number("min_zoom")?.ok_or_else(malformed)?;
188    let max_zoom = number("max_zoom")?.unwrap_or(f64::INFINITY);
189    let pixel_ratio = number("pixel_ratio")?.ok_or_else(malformed)? as f32;
190    let include_ideographs = member("include_ideographs").map_or(Some(true), Json::as_bool).ok_or_else(malformed)?;
191
192    if let Some(bounds) = member("bounds") {
193        // A definition with `bounds` is a tile pyramid, whatever its
194        // `geometry`.
195        let bounds = bounds.as_array().ok_or_else(malformed)?;
196        let [south, west, north, east] = bounds.as_slice() else { return Err(malformed()) };
197        let coordinate = |v: &Json| v.as_f64().ok_or_else(malformed);
198        let (south, west, north, east) = (coordinate(south)?, coordinate(west)?, coordinate(north)?, coordinate(east)?);
199        Ok(OfflineTilePyramidRegionDefinition::new(
200            style_url,
201            LatLngBounds::hull(LatLng::new(south, west)?, LatLng::new(north, east)?),
202            min_zoom,
203            max_zoom,
204            pixel_ratio,
205            include_ideographs,
206        )?
207        .into())
208    } else {
209        let geometry = member("geometry").filter(|g| g.is_object()).ok_or_else(malformed)?;
210        let geometry = serde_json::from_value::<geojson::Geometry>(geometry.clone())
211            .map_err(geojson::Error::from)
212            .and_then(mln_style::feature::geojson::geometry)
213            .map_err(|e| Error::failed(e.to_string()))?;
214        Ok(OfflineGeometryRegionDefinition::new(
215            style_url,
216            geometry,
217            min_zoom,
218            max_zoom,
219            pixel_ratio,
220            include_ideographs,
221        )?
222        .into())
223    }
224}
225
226#[cfg(any(test, feature = "sqlite"))]
227#[must_use]
228pub(crate) fn encode_offline_region_definition(region: &OfflineRegionDefinition) -> String {
229    let mut json = Map::new();
230
231    // Encode common properties
232    json.insert("style_url".into(), region.style_url().into());
233    json.insert("min_zoom".into(), region.min_zoom().into());
234    if region.max_zoom().is_finite() {
235        json.insert("max_zoom".into(), region.max_zoom().into());
236    }
237    json.insert("pixel_ratio".into(), f64::from(region.pixel_ratio()).into());
238    json.insert("include_ideographs".into(), region.include_ideographs().into());
239
240    // Encode specific properties
241    match region {
242        OfflineRegionDefinition::TilePyramid(region) => {
243            let bounds = &region.bounds;
244            json.insert("bounds".into(), [bounds.south(), bounds.west(), bounds.north(), bounds.east()].into());
245        }
246        OfflineRegionDefinition::Geometry(region) => {
247            let geometry = geojson::GeometryValue::from(&region.geometry);
248            json.insert("geometry".into(), Json::from(&geometry));
249        }
250    }
251
252    Json::Object(json).to_string()
253}
254
255/// Arbitrary binary region metadata, which the database stores and returns
256/// as is.
257pub type OfflineRegionMetadata = Vec<u8>;
258
259/// A region is either inactive (not downloading, but previously-downloaded
260/// resources are available for use), or active (resources are being
261/// downloaded or will be downloaded, if necessary, when network access is
262/// available).
263#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
264pub enum OfflineRegionDownloadState {
265    #[default]
266    Inactive,
267    Active,
268}
269
270/// A region's status: its active/inactive state, the number of resources
271/// that have completed downloading and their total size in bytes, and the
272/// total number of resources that are required.
273#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
274pub struct OfflineRegionStatus {
275    pub download_state: OfflineRegionDownloadState,
276
277    /// The number of resources that have been fully downloaded and are ready
278    /// for offline access.
279    pub completed_resource_count: u64,
280
281    /// The cumulative size, in bytes, of all resources (inclusive of tiles)
282    /// that have been fully downloaded.
283    pub completed_resource_size: u64,
284
285    /// The number of tiles that are known to be required for this region.
286    /// This is a subset of [`Self::completed_resource_count`].
287    pub completed_tile_count: u64,
288
289    /// The number of tiles that are known to be required for this region.
290    pub required_tile_count: u64,
291
292    /// The cumulative size, in bytes, of all tiles that have been fully
293    /// downloaded. This is a subset of [`Self::completed_resource_size`].
294    pub completed_tile_size: u64,
295
296    /// The number of resources that are known to be required for this
297    /// region. See [`Self::required_resource_count_is_precise`] for an
298    /// important caveat about this number.
299    pub required_resource_count: u64,
300
301    /// True when [`Self::required_resource_count`] is a precise count of the
302    /// required resources, and false when it is merely a lower bound.
303    pub required_resource_count_is_precise: bool,
304}
305
306impl OfflineRegionStatus {
307    #[must_use]
308    pub fn complete(&self) -> bool {
309        self.completed_resource_count >= self.required_resource_count
310    }
311}
312
313/// How long a region's stored resources stay usable, from their caching
314/// rules.
315#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
316pub struct OfflineRegionExpiry {
317    /// When the first of the region's resources goes stale, which may have
318    /// passed; `None` if none ever does. Maps show a stale resource while
319    /// they revalidate it, unless it must revalidate first, and a download
320    /// refreshes it.
321    pub stale_after: Option<Timestamp>,
322    /// When the first of its resources that must revalidate once stale
323    /// stops being usable until maps reach the server, which may have
324    /// passed; `None` if none ever does.
325    pub usable_offline_until: Option<Timestamp>,
326    /// The resources that are stale now, tiles included.
327    pub stale_resource_count: u64,
328    /// The stale resources that maps can't use now until they reach the
329    /// server.
330    pub unusable_resource_count: u64,
331}
332
333/// A region can have a single observer, which gets notified whenever a
334/// change to the region's status occurs. The methods run on the database
335/// thread. They take `&self`: the download calls them re-entrantly, e.g. an
336/// observer that deactivates the download from `status_changed` gets a
337/// nested `status_changed`.
338pub trait OfflineRegionObserver {
339    /// Notified of a change in the status of an offline region.
340    fn status_changed(&self, _status: OfflineRegionStatus) {}
341
342    /// Notified of errors encountered while downloading regional resources.
343    fn response_error(&self, _error: ResourceError) {}
344}
345
346/// A region in the offline database.
347#[derive(Clone, Debug, PartialEq)]
348pub struct OfflineRegion {
349    /// The database's id for the region.
350    pub id: i64,
351    /// The area and zoom levels the region downloads.
352    pub definition: OfflineRegionDefinition,
353    /// The app's bytes for the region.
354    pub metadata: OfflineRegionMetadata,
355}
356
357#[cfg(feature = "sqlite")]
358pub(crate) type OfflineRegions = Vec<OfflineRegion>;
359
360#[cfg(test)]
361mod tests {
362    use geo_types::Point;
363
364    use super::*;
365
366    fn pyramid(max_zoom: f64) -> OfflineRegionDefinition {
367        let bounds =
368            LatLngBounds::hull(LatLng::new(37.6609, -122.5744).unwrap(), LatLng::new(37.8271, -122.3204).unwrap());
369        OfflineTilePyramidRegionDefinition::new("https://example.com/style", bounds, 0.0, max_zoom, 1.0, true)
370            .unwrap()
371            .into()
372    }
373
374    fn point(max_zoom: f64) -> OfflineRegionDefinition {
375        let point = Geometry::Point(Point::new(-122.5744, 37.6609));
376        OfflineGeometryRegionDefinition::new("https://example.com/style", point, 0.0, max_zoom, 2.0, false)
377            .unwrap()
378            .into()
379    }
380
381    /// A definition encodes as JSON, which decodes to it again. An infinite
382    /// max zoom is left out.
383    #[test]
384    fn a_definition_encodes_as_json_and_decodes_back() {
385        let cases = [
386            (
387                pyramid(20.0),
388                r#"{"style_url":"https://example.com/style","min_zoom":0.0,"max_zoom":20.0,"pixel_ratio":1.0,"include_ideographs":true,"bounds":[37.6609,-122.5744,37.8271,-122.3204]}"#,
389            ),
390            (
391                point(2.0),
392                r#"{"style_url":"https://example.com/style","min_zoom":0.0,"max_zoom":2.0,"pixel_ratio":2.0,"include_ideographs":false,"geometry":{"type":"Point","coordinates":[-122.5744,37.6609]}}"#,
393            ),
394            (
395                point(f64::INFINITY),
396                r#"{"style_url":"https://example.com/style","min_zoom":0.0,"pixel_ratio":2.0,"include_ideographs":false,"geometry":{"type":"Point","coordinates":[-122.5744,37.6609]}}"#,
397            ),
398        ];
399        for (definition, json) in cases {
400            assert_eq!(json, encode_offline_region_definition(&definition));
401            assert_eq!(definition, decode_offline_region_definition(json.as_bytes()).unwrap());
402        }
403    }
404
405    #[test]
406    fn a_malformed_definition_fails_to_decode() {
407        for malformed in [
408            "",
409            "{}",
410            "[]",
411            r#"{"style_url":"s","min_zoom":"0","pixel_ratio":1.0,"bounds":[1.0,2.0,3.0,4.0]}"#,
412            r#"{"style_url":"s","min_zoom":0.0,"bounds":[1.0,2.0,3.0,4.0]}"#,
413            r#"{"style_url":"s","min_zoom":0.0,"pixel_ratio":1.0}"#,
414            r#"{"style_url":"s","min_zoom":0.0,"pixel_ratio":1.0,"geometry":null}"#,
415            r#"{"style_url":"s","min_zoom":0.0,"pixel_ratio":1.0,"bounds":[1.0,2.0,3.0]}"#,
416            r#"{"style_url":"s","min_zoom":0.0,"pixel_ratio":1.0,"bounds":[1.0,2.0,3.0,"4"]}"#,
417            r#"{"style_url":"s","min_zoom":0.0,"pixel_ratio":1.0,"bounds":[1.0,2.0,3.0,4.0],"include_ideographs":1}"#,
418        ] {
419            assert_eq!(
420                "Malformed offline region definition",
421                decode_offline_region_definition(malformed.as_bytes()).unwrap_err().message,
422                "{malformed}"
423            );
424        }
425    }
426
427    /// The max zoom and whether to include ideographs default to infinity
428    /// and true, and numbers may be integers.
429    #[test]
430    fn a_definition_decodes_with_defaults_and_integers() {
431        let decoded = decode_offline_region_definition(
432            br#"{"style_url":"s","min_zoom":1.0,"pixel_ratio":1.0,"bounds":[1.0,2.0,3.0,4.0]}"#,
433        )
434        .unwrap();
435        assert_eq!((f64::INFINITY, true), (decoded.max_zoom(), decoded.include_ideographs()));
436
437        let decoded = decode_offline_region_definition(
438            br#"{"style_url":"s","min_zoom":0,"max_zoom":14,"pixel_ratio":2,"bounds":[1,2,3,4]}"#,
439        )
440        .unwrap();
441        assert_eq!((0.0, 14.0, 2.0), (decoded.min_zoom(), decoded.max_zoom(), decoded.pixel_ratio()));
442        let OfflineRegionDefinition::TilePyramid(region) = decoded else { panic!("a tile pyramid") };
443        assert_eq!(
444            (1.0, 2.0, 3.0, 4.0),
445            (region.bounds.south(), region.bounds.west(), region.bounds.north(), region.bounds.east())
446        );
447    }
448}