Skip to main content

mln_engine/storage/
offline.rs

1// rapidjson parsing is serde_json (as everywhere in the port); `IsDouble()`
2// is `is_f64()` (a number written with a fraction or exponent, or an integer
3// too large for 64 bits).
4
5use geo_types::Geometry;
6use mln_style::error::Error;
7#[cfg(any(test, feature = "sqlite"))]
8use mln_style::geo::LatLng;
9use mln_style::geo::LatLngBounds;
10#[cfg(any(test, feature = "sqlite"))]
11use serde_json::{Map, Value as Json};
12
13use crate::storage::chrono::Timestamp;
14use crate::storage::response::ResourceError;
15
16fn check_definition(min_zoom: f64, max_zoom: f64, pixel_ratio: f32) -> Result<(), Error> {
17    if !min_zoom.is_finite() || min_zoom < 0.0 || max_zoom.is_nan() || max_zoom < min_zoom {
18        return Err(Error::invalid_argument("offline region zoom range is invalid"));
19    }
20    if !pixel_ratio.is_finite() || pixel_ratio < 0.0 {
21        return Err(Error::invalid_argument("offline region pixel ratio is invalid"));
22    }
23    Ok(())
24}
25
26/// An offline region defined by a style URL, geographic bounding box, zoom
27/// range, and device pixel ratio.
28///
29/// Both minZoom and maxZoom must be ≥ 0, and maxZoom must be ≥ minZoom.
30///
31/// maxZoom may be ∞, in which case for each tile source, the region will
32/// include tiles from minZoom up to the maximum zoom level provided by that
33/// source.
34///
35/// pixelRatio must be ≥ 0 and should typically be 1.0 or 2.0.
36#[derive(Clone, Debug, PartialEq)]
37pub struct OfflineTilePyramidRegionDefinition {
38    pub(crate) style_url: String,
39    pub bounds: LatLngBounds,
40    pub(crate) min_zoom: f64,
41    pub(crate) max_zoom: f64,
42    pub(crate) pixel_ratio: f32,
43    pub(crate) include_ideographs: bool,
44}
45
46impl OfflineTilePyramidRegionDefinition {
47    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a
48    /// negative or reversed zoom range, or a negative or infinite pixel ratio.
49    pub fn new(
50        style_url: impl Into<String>,
51        bounds: LatLngBounds,
52        min_zoom: f64,
53        max_zoom: f64,
54        pixel_ratio: f32,
55        include_ideographs: bool,
56    ) -> Result<Self, Error> {
57        check_definition(min_zoom, max_zoom, pixel_ratio)?;
58        Ok(OfflineTilePyramidRegionDefinition {
59            style_url: style_url.into(),
60            bounds,
61            min_zoom,
62            max_zoom,
63            pixel_ratio,
64            include_ideographs,
65        })
66    }
67}
68
69/// An offline region defined by a style URL, geometry, zoom range, and
70/// device pixel ratio.
71///
72/// Both minZoom and maxZoom must be ≥ 0, and maxZoom must be ≥ minZoom.
73///
74/// maxZoom may be ∞, in which case for each tile source, the region will
75/// include tiles from minZoom up to the maximum zoom level provided by that
76/// source.
77///
78/// pixelRatio must be ≥ 0 and should typically be 1.0 or 2.0.
79#[derive(Clone, Debug, PartialEq)]
80pub struct OfflineGeometryRegionDefinition {
81    pub(crate) style_url: String,
82    pub geometry: Geometry<f64>,
83    pub(crate) min_zoom: f64,
84    pub(crate) max_zoom: f64,
85    pub(crate) pixel_ratio: f32,
86    pub(crate) include_ideographs: bool,
87}
88
89impl OfflineGeometryRegionDefinition {
90    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a
91    /// negative or reversed zoom range, or a negative or infinite pixel ratio.
92    pub fn new(
93        style_url: impl Into<String>,
94        geometry: Geometry<f64>,
95        min_zoom: f64,
96        max_zoom: f64,
97        pixel_ratio: f32,
98        include_ideographs: bool,
99    ) -> Result<Self, Error> {
100        check_definition(min_zoom, max_zoom, pixel_ratio)?;
101        Ok(OfflineGeometryRegionDefinition {
102            style_url: style_url.into(),
103            geometry,
104            min_zoom,
105            max_zoom,
106            pixel_ratio,
107            include_ideographs,
108        })
109    }
110}
111
112/// The offline region definition types supported
113/// (`std::variant<OfflineTilePyramidRegionDefinition, OfflineGeometryRegionDefinition>`).
114#[derive(Clone, Debug, PartialEq)]
115pub enum OfflineRegionDefinition {
116    TilePyramid(OfflineTilePyramidRegionDefinition),
117    Geometry(OfflineGeometryRegionDefinition),
118}
119
120impl From<OfflineTilePyramidRegionDefinition> for OfflineRegionDefinition {
121    fn from(definition: OfflineTilePyramidRegionDefinition) -> Self {
122        OfflineRegionDefinition::TilePyramid(definition)
123    }
124}
125
126impl From<OfflineGeometryRegionDefinition> for OfflineRegionDefinition {
127    fn from(definition: OfflineGeometryRegionDefinition) -> Self {
128        OfflineRegionDefinition::Geometry(definition)
129    }
130}
131
132impl OfflineRegionDefinition {
133    // The common members, for the C++ `std::visit([](auto& region) {...})`.
134
135    #[must_use]
136    pub fn style_url(&self) -> &str {
137        match self {
138            OfflineRegionDefinition::TilePyramid(r) => &r.style_url,
139            OfflineRegionDefinition::Geometry(r) => &r.style_url,
140        }
141    }
142
143    #[must_use]
144    pub fn min_zoom(&self) -> f64 {
145        match self {
146            OfflineRegionDefinition::TilePyramid(r) => r.min_zoom,
147            OfflineRegionDefinition::Geometry(r) => r.min_zoom,
148        }
149    }
150
151    #[must_use]
152    pub fn max_zoom(&self) -> f64 {
153        match self {
154            OfflineRegionDefinition::TilePyramid(r) => r.max_zoom,
155            OfflineRegionDefinition::Geometry(r) => r.max_zoom,
156        }
157    }
158
159    #[must_use]
160    pub fn pixel_ratio(&self) -> f32 {
161        match self {
162            OfflineRegionDefinition::TilePyramid(r) => r.pixel_ratio,
163            OfflineRegionDefinition::Geometry(r) => r.pixel_ratio,
164        }
165    }
166
167    #[must_use]
168    pub fn include_ideographs(&self) -> bool {
169        match self {
170            OfflineRegionDefinition::TilePyramid(r) => r.include_ideographs,
171            OfflineRegionDefinition::Geometry(r) => r.include_ideographs,
172        }
173    }
174}
175
176/// Decodes a region definition from JSON. A definition that isn't one fails
177/// with [`ErrorKind::Native`](mln_style::error::ErrorKind), and one
178/// with invalid values with the constructors' error.
179#[cfg(any(test, feature = "sqlite"))]
180pub(crate) fn decode_offline_region_definition(region: &[u8]) -> Result<OfflineRegionDefinition, Error> {
181    let malformed = || Error::native("Malformed offline region definition");
182
183    // `doc.Parse<0>(region.c_str())` (stops at the first NUL byte).
184    let end = region.iter().position(|&b| b == 0).unwrap_or(region.len());
185    let doc: Option<Json> = serde_json::from_slice(&region[..end]).ok();
186    let Some(doc) = doc else {
187        return Err(malformed());
188    };
189    // `HasMember` on a non-object asserts in C++; a definition is always an
190    // object.
191    let member = |name: &str| doc.as_object().and_then(|o| o.get(name));
192    let is_double = |v: Option<&Json>| v.is_some_and(Json::is_f64);
193
194    // validation
195
196    let has_valid_bounds =
197        || member("bounds").and_then(Json::as_array).is_some_and(|b| b.len() == 4 && b.iter().all(Json::is_f64));
198
199    let has_valid_geometry = || member("geometry").is_some_and(Json::is_object);
200
201    if !member("style_url").is_some_and(Json::is_string)
202        || !(has_valid_bounds() || has_valid_geometry())
203        || !is_double(member("min_zoom"))
204        || (member("max_zoom").is_some() && !is_double(member("max_zoom")))
205        || !is_double(member("pixel_ratio"))
206        || (member("include_ideographs").is_some() && !member("include_ideographs").is_some_and(Json::is_boolean))
207    {
208        return Err(malformed());
209    }
210
211    // Common properties
212
213    let style_url = member("style_url").and_then(Json::as_str).unwrap_or_default().to_owned();
214    let min_zoom = member("min_zoom").and_then(Json::as_f64).unwrap_or_default();
215    let max_zoom = member("max_zoom").map_or(f64::INFINITY, |v| v.as_f64().unwrap_or_default());
216    let pixel_ratio = member("pixel_ratio").and_then(Json::as_f64).unwrap_or_default() as f32;
217    let include_ideographs = member("include_ideographs").is_none_or(|v| v.as_bool().unwrap_or_default());
218
219    if let Some(bounds) = member("bounds") {
220        // `bounds` is present but may be invalid when `geometry` is valid:
221        // C++ then reads the members of whatever it holds (undefined for a
222        // non-array); the port treats that as malformed.
223        let bounds = bounds.as_array().filter(|b| b.len() == 4).ok_or_else(malformed)?;
224        let get = |i: usize| bounds[i].as_f64().unwrap_or_default();
225        let latlng = |lat: f64, lon: f64| LatLng::new(lat, lon);
226        Ok(OfflineTilePyramidRegionDefinition::new(
227            style_url,
228            LatLngBounds::hull(latlng(get(0), get(1))?, latlng(get(2), get(3))?),
229            min_zoom,
230            max_zoom,
231            pixel_ratio,
232            include_ideographs,
233        )?
234        .into())
235    } else {
236        // A null geometry covers no tiles, as an empty collection does.
237        let geometry = match member("geometry") {
238            None | Some(Json::Null) => Geometry::GeometryCollection(geo_types::GeometryCollection(Vec::new())),
239            Some(json) => serde_json::from_value::<geojson::Geometry>(json.clone())
240                .map_err(geojson::Error::from)
241                .and_then(feature::geojson::geometry)
242                .map_err(|e| Error::native(e.to_string()))?,
243        };
244        Ok(OfflineGeometryRegionDefinition::new(
245            style_url,
246            geometry,
247            min_zoom,
248            max_zoom,
249            pixel_ratio,
250            include_ideographs,
251        )?
252        .into())
253    }
254}
255
256#[cfg(any(test, feature = "sqlite"))]
257#[must_use]
258pub(crate) fn encode_offline_region_definition(region: &OfflineRegionDefinition) -> String {
259    let mut json = Map::new();
260
261    // Encode common properties
262    json.insert("style_url".into(), region.style_url().into());
263    json.insert("min_zoom".into(), region.min_zoom().into());
264    if region.max_zoom().is_finite() {
265        json.insert("max_zoom".into(), region.max_zoom().into());
266    }
267    json.insert("pixel_ratio".into(), f64::from(region.pixel_ratio()).into());
268    json.insert("include_ideographs".into(), region.include_ideographs().into());
269
270    // Encode specific properties
271    match region {
272        OfflineRegionDefinition::TilePyramid(region) => {
273            let bounds = &region.bounds;
274            json.insert("bounds".into(), [bounds.south(), bounds.west(), bounds.north(), bounds.east()].into());
275        }
276        OfflineRegionDefinition::Geometry(region) => {
277            let geometry = geojson::Geometry::new((&region.geometry).into());
278            json.insert("geometry".into(), serde_json::to_value(geometry).unwrap_or_default());
279        }
280    }
281
282    Json::Object(json).to_string()
283}
284
285/// Arbitrary binary region metadata. The contents are opaque to the mbgl
286/// implementation; it just stores and retrieves a BLOB.
287pub type OfflineRegionMetadata = Vec<u8>;
288
289/// A region is either inactive (not downloading, but previously-downloaded
290/// resources are available for use), or active (resources are being
291/// downloaded or will be downloaded, if necessary, when network access is
292/// available).
293#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
294pub enum OfflineRegionDownloadState {
295    #[default]
296    Inactive,
297    Active,
298}
299
300/// A region's status: its active/inactive state, the number of resources
301/// that have completed downloading and their total size in bytes, and the
302/// total number of resources that are required.
303#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
304pub struct OfflineRegionStatus {
305    pub download_state: OfflineRegionDownloadState,
306
307    /// The number of resources that have been fully downloaded and are ready
308    /// for offline access.
309    pub completed_resource_count: u64,
310
311    /// The cumulative size, in bytes, of all resources (inclusive of tiles)
312    /// that have been fully downloaded.
313    pub completed_resource_size: u64,
314
315    /// The number of tiles that are known to be required for this region.
316    /// This is a subset of `completedResourceCount`.
317    pub completed_tile_count: u64,
318
319    /// The number of tiles that are known to be required for this region.
320    pub required_tile_count: u64,
321
322    /// The cumulative size, in bytes, of all tiles that have been fully
323    /// downloaded. This is a subset of `completedResourceSize`.
324    pub completed_tile_size: u64,
325
326    /// The number of resources that are known to be required for this
327    /// region. See the documentation for `requiredResourceCountIsPrecise`
328    /// for an important caveat about this number.
329    pub required_resource_count: u64,
330
331    /// This property is true when the value of requiredResourceCount is a
332    /// precise count of the number of required resources, and false when it
333    /// is merely a lower bound.
334    pub required_resource_count_is_precise: bool,
335}
336
337impl OfflineRegionStatus {
338    #[must_use]
339    pub fn complete(&self) -> bool {
340        self.completed_resource_count >= self.required_resource_count
341    }
342}
343
344/// How long a region's stored resources stay usable, from their caching
345/// rules.
346#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
347pub struct OfflineRegionExpiry {
348    /// When the first of the region's resources goes stale, which may have
349    /// passed; `None` if none ever does. Maps show a stale resource while
350    /// they revalidate it, unless it must revalidate first, and a download
351    /// refreshes it.
352    pub stale_after: Option<Timestamp>,
353    /// When the first of its resources that must revalidate once stale
354    /// stops being usable until maps reach the server, which may have
355    /// passed; `None` if none ever does.
356    pub usable_offline_until: Option<Timestamp>,
357    /// The resources that are stale now, tiles included.
358    pub stale_resource_count: u64,
359    /// The stale resources that maps can't use now until they reach the
360    /// server.
361    pub unusable_resource_count: u64,
362}
363
364/// A region can have a single observer, which gets notified whenever a
365/// change to the region's status occurs. The methods run on the database
366/// thread. They take `&self`: the download calls them re-entrantly, e.g. an
367/// observer that deactivates the download from `status_changed` gets a
368/// nested `status_changed`.
369pub trait OfflineRegionObserver {
370    /// Notified of a change in the status of an offline region.
371    fn status_changed(&self, _status: OfflineRegionStatus) {}
372
373    /// Notified of errors encountered while downloading regional resources.
374    fn response_error(&self, _error: ResourceError) {}
375}
376
377/// A region in the offline database.
378#[derive(Clone, Debug, PartialEq)]
379pub struct OfflineRegion {
380    /// The database's id for the region.
381    pub id: i64,
382    /// The area and zoom levels the region downloads.
383    pub definition: OfflineRegionDefinition,
384    /// The app's bytes for the region.
385    pub metadata: OfflineRegionMetadata,
386}
387
388pub type OfflineRegions = Vec<OfflineRegion>;