mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
// Region definitions are JSON in the format MapLibre Native's offline API
// writes, so that this reads its databases.

use geo_types::Geometry;
use mln_style::error::Error;
#[cfg(any(test, feature = "sqlite"))]
use mln_style::geo::LatLng;
use mln_style::geo::LatLngBounds;
#[cfg(any(test, feature = "sqlite"))]
use serde_json::{Map, Value as Json};

use crate::storage::chrono::Timestamp;
use crate::storage::response::ResourceError;

fn check_definition(min_zoom: f64, max_zoom: f64, pixel_ratio: f32) -> Result<(), Error> {
    if !min_zoom.is_finite() || min_zoom < 0.0 || max_zoom.is_nan() || max_zoom < min_zoom {
        return Err(Error::invalid_argument("offline region zoom range is invalid"));
    }
    if !pixel_ratio.is_finite() || pixel_ratio < 0.0 {
        return Err(Error::invalid_argument("offline region pixel ratio is invalid"));
    }
    Ok(())
}

/// An offline region defined by a style URL, geographic bounding box, zoom
/// range, and device pixel ratio.
///
/// Both minZoom and maxZoom must be ≥ 0, and maxZoom must be ≥ minZoom.
///
/// maxZoom may be ∞, in which case for each tile source, the region will
/// include tiles from minZoom up to the maximum zoom level provided by that
/// source.
///
/// pixelRatio must be ≥ 0 and should typically be 1.0 or 2.0.
#[derive(Clone, Debug, PartialEq)]
pub struct OfflineTilePyramidRegionDefinition {
    pub(crate) style_url: String,
    pub bounds: LatLngBounds,
    pub(crate) min_zoom: f64,
    pub(crate) max_zoom: f64,
    pub(crate) pixel_ratio: f32,
    pub(crate) include_ideographs: bool,
}

impl OfflineTilePyramidRegionDefinition {
    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a
    /// negative or reversed zoom range, or a negative or infinite pixel ratio.
    pub fn new(
        style_url: impl Into<String>,
        bounds: LatLngBounds,
        min_zoom: f64,
        max_zoom: f64,
        pixel_ratio: f32,
        include_ideographs: bool,
    ) -> Result<Self, Error> {
        check_definition(min_zoom, max_zoom, pixel_ratio)?;
        Ok(OfflineTilePyramidRegionDefinition {
            style_url: style_url.into(),
            bounds,
            min_zoom,
            max_zoom,
            pixel_ratio,
            include_ideographs,
        })
    }
}

/// An offline region defined by a style URL, geometry, zoom range, and
/// device pixel ratio.
///
/// Both minZoom and maxZoom must be ≥ 0, and maxZoom must be ≥ minZoom.
///
/// maxZoom may be ∞, in which case for each tile source, the region will
/// include tiles from minZoom up to the maximum zoom level provided by that
/// source.
///
/// pixelRatio must be ≥ 0 and should typically be 1.0 or 2.0.
#[derive(Clone, Debug, PartialEq)]
pub struct OfflineGeometryRegionDefinition {
    pub(crate) style_url: String,
    pub geometry: Geometry<f64>,
    pub(crate) min_zoom: f64,
    pub(crate) max_zoom: f64,
    pub(crate) pixel_ratio: f32,
    pub(crate) include_ideographs: bool,
}

impl OfflineGeometryRegionDefinition {
    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a
    /// negative or reversed zoom range, or a negative or infinite pixel ratio.
    pub fn new(
        style_url: impl Into<String>,
        geometry: Geometry<f64>,
        min_zoom: f64,
        max_zoom: f64,
        pixel_ratio: f32,
        include_ideographs: bool,
    ) -> Result<Self, Error> {
        check_definition(min_zoom, max_zoom, pixel_ratio)?;
        Ok(OfflineGeometryRegionDefinition {
            style_url: style_url.into(),
            geometry,
            min_zoom,
            max_zoom,
            pixel_ratio,
            include_ideographs,
        })
    }
}

/// The offline region definition types supported.
#[derive(Clone, Debug, PartialEq)]
pub enum OfflineRegionDefinition {
    TilePyramid(OfflineTilePyramidRegionDefinition),
    Geometry(OfflineGeometryRegionDefinition),
}

impl From<OfflineTilePyramidRegionDefinition> for OfflineRegionDefinition {
    fn from(definition: OfflineTilePyramidRegionDefinition) -> Self {
        OfflineRegionDefinition::TilePyramid(definition)
    }
}

impl From<OfflineGeometryRegionDefinition> for OfflineRegionDefinition {
    fn from(definition: OfflineGeometryRegionDefinition) -> Self {
        OfflineRegionDefinition::Geometry(definition)
    }
}

impl OfflineRegionDefinition {
    // The members both kinds of definition have.

    #[must_use]
    pub fn style_url(&self) -> &str {
        match self {
            OfflineRegionDefinition::TilePyramid(r) => &r.style_url,
            OfflineRegionDefinition::Geometry(r) => &r.style_url,
        }
    }

    #[must_use]
    pub fn min_zoom(&self) -> f64 {
        match self {
            OfflineRegionDefinition::TilePyramid(r) => r.min_zoom,
            OfflineRegionDefinition::Geometry(r) => r.min_zoom,
        }
    }

    #[must_use]
    pub fn max_zoom(&self) -> f64 {
        match self {
            OfflineRegionDefinition::TilePyramid(r) => r.max_zoom,
            OfflineRegionDefinition::Geometry(r) => r.max_zoom,
        }
    }

    #[must_use]
    pub fn pixel_ratio(&self) -> f32 {
        match self {
            OfflineRegionDefinition::TilePyramid(r) => r.pixel_ratio,
            OfflineRegionDefinition::Geometry(r) => r.pixel_ratio,
        }
    }

    #[must_use]
    pub fn include_ideographs(&self) -> bool {
        match self {
            OfflineRegionDefinition::TilePyramid(r) => r.include_ideographs,
            OfflineRegionDefinition::Geometry(r) => r.include_ideographs,
        }
    }
}

/// Decodes a region definition from JSON. A definition that isn't one fails
/// with [`ErrorKind::Failed`](mln_style::error::ErrorKind), and one
/// with invalid values with the constructors' error.
#[cfg(any(test, feature = "sqlite"))]
pub(crate) fn decode_offline_region_definition(region: &[u8]) -> Result<OfflineRegionDefinition, Error> {
    let malformed = || Error::failed("Malformed offline region definition");

    let doc: Json = serde_json::from_slice(region).map_err(|_| malformed())?;
    let doc = doc.as_object().ok_or_else(malformed)?;
    let member = |name: &str| doc.get(name);
    let number = |name: &str| member(name).map(|v| v.as_f64().ok_or_else(malformed)).transpose();

    let style_url = member("style_url").and_then(Json::as_str).ok_or_else(malformed)?.to_owned();
    let min_zoom = number("min_zoom")?.ok_or_else(malformed)?;
    let max_zoom = number("max_zoom")?.unwrap_or(f64::INFINITY);
    let pixel_ratio = number("pixel_ratio")?.ok_or_else(malformed)? as f32;
    let include_ideographs = member("include_ideographs").map_or(Some(true), Json::as_bool).ok_or_else(malformed)?;

    if let Some(bounds) = member("bounds") {
        // A definition with `bounds` is a tile pyramid, whatever its
        // `geometry`.
        let bounds = bounds.as_array().ok_or_else(malformed)?;
        let [south, west, north, east] = bounds.as_slice() else { return Err(malformed()) };
        let coordinate = |v: &Json| v.as_f64().ok_or_else(malformed);
        let (south, west, north, east) = (coordinate(south)?, coordinate(west)?, coordinate(north)?, coordinate(east)?);
        Ok(OfflineTilePyramidRegionDefinition::new(
            style_url,
            LatLngBounds::hull(LatLng::new(south, west)?, LatLng::new(north, east)?),
            min_zoom,
            max_zoom,
            pixel_ratio,
            include_ideographs,
        )?
        .into())
    } else {
        let geometry = member("geometry").filter(|g| g.is_object()).ok_or_else(malformed)?;
        let geometry = serde_json::from_value::<geojson::Geometry>(geometry.clone())
            .map_err(geojson::Error::from)
            .and_then(mln_style::feature::geojson::geometry)
            .map_err(|e| Error::failed(e.to_string()))?;
        Ok(OfflineGeometryRegionDefinition::new(
            style_url,
            geometry,
            min_zoom,
            max_zoom,
            pixel_ratio,
            include_ideographs,
        )?
        .into())
    }
}

#[cfg(any(test, feature = "sqlite"))]
#[must_use]
pub(crate) fn encode_offline_region_definition(region: &OfflineRegionDefinition) -> String {
    let mut json = Map::new();

    // Encode common properties
    json.insert("style_url".into(), region.style_url().into());
    json.insert("min_zoom".into(), region.min_zoom().into());
    if region.max_zoom().is_finite() {
        json.insert("max_zoom".into(), region.max_zoom().into());
    }
    json.insert("pixel_ratio".into(), f64::from(region.pixel_ratio()).into());
    json.insert("include_ideographs".into(), region.include_ideographs().into());

    // Encode specific properties
    match region {
        OfflineRegionDefinition::TilePyramid(region) => {
            let bounds = &region.bounds;
            json.insert("bounds".into(), [bounds.south(), bounds.west(), bounds.north(), bounds.east()].into());
        }
        OfflineRegionDefinition::Geometry(region) => {
            let geometry = geojson::GeometryValue::from(&region.geometry);
            json.insert("geometry".into(), Json::from(&geometry));
        }
    }

    Json::Object(json).to_string()
}

/// Arbitrary binary region metadata, which the database stores and returns
/// as is.
pub type OfflineRegionMetadata = Vec<u8>;

/// A region is either inactive (not downloading, but previously-downloaded
/// resources are available for use), or active (resources are being
/// downloaded or will be downloaded, if necessary, when network access is
/// available).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum OfflineRegionDownloadState {
    #[default]
    Inactive,
    Active,
}

/// A region's status: its active/inactive state, the number of resources
/// that have completed downloading and their total size in bytes, and the
/// total number of resources that are required.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct OfflineRegionStatus {
    pub download_state: OfflineRegionDownloadState,

    /// The number of resources that have been fully downloaded and are ready
    /// for offline access.
    pub completed_resource_count: u64,

    /// The cumulative size, in bytes, of all resources (inclusive of tiles)
    /// that have been fully downloaded.
    pub completed_resource_size: u64,

    /// The number of tiles that are known to be required for this region.
    /// This is a subset of [`Self::completed_resource_count`].
    pub completed_tile_count: u64,

    /// The number of tiles that are known to be required for this region.
    pub required_tile_count: u64,

    /// The cumulative size, in bytes, of all tiles that have been fully
    /// downloaded. This is a subset of [`Self::completed_resource_size`].
    pub completed_tile_size: u64,

    /// The number of resources that are known to be required for this
    /// region. See [`Self::required_resource_count_is_precise`] for an
    /// important caveat about this number.
    pub required_resource_count: u64,

    /// True when [`Self::required_resource_count`] is a precise count of the
    /// required resources, and false when it is merely a lower bound.
    pub required_resource_count_is_precise: bool,
}

impl OfflineRegionStatus {
    #[must_use]
    pub fn complete(&self) -> bool {
        self.completed_resource_count >= self.required_resource_count
    }
}

/// How long a region's stored resources stay usable, from their caching
/// rules.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct OfflineRegionExpiry {
    /// When the first of the region's resources goes stale, which may have
    /// passed; `None` if none ever does. Maps show a stale resource while
    /// they revalidate it, unless it must revalidate first, and a download
    /// refreshes it.
    pub stale_after: Option<Timestamp>,
    /// When the first of its resources that must revalidate once stale
    /// stops being usable until maps reach the server, which may have
    /// passed; `None` if none ever does.
    pub usable_offline_until: Option<Timestamp>,
    /// The resources that are stale now, tiles included.
    pub stale_resource_count: u64,
    /// The stale resources that maps can't use now until they reach the
    /// server.
    pub unusable_resource_count: u64,
}

/// A region can have a single observer, which gets notified whenever a
/// change to the region's status occurs. The methods run on the database
/// thread. They take `&self`: the download calls them re-entrantly, e.g. an
/// observer that deactivates the download from `status_changed` gets a
/// nested `status_changed`.
pub trait OfflineRegionObserver {
    /// Notified of a change in the status of an offline region.
    fn status_changed(&self, _status: OfflineRegionStatus) {}

    /// Notified of errors encountered while downloading regional resources.
    fn response_error(&self, _error: ResourceError) {}
}

/// A region in the offline database.
#[derive(Clone, Debug, PartialEq)]
pub struct OfflineRegion {
    /// The database's id for the region.
    pub id: i64,
    /// The area and zoom levels the region downloads.
    pub definition: OfflineRegionDefinition,
    /// The app's bytes for the region.
    pub metadata: OfflineRegionMetadata,
}

#[cfg(feature = "sqlite")]
pub(crate) type OfflineRegions = Vec<OfflineRegion>;

#[cfg(test)]
mod tests {
    use geo_types::Point;

    use super::*;

    fn pyramid(max_zoom: f64) -> OfflineRegionDefinition {
        let bounds =
            LatLngBounds::hull(LatLng::new(37.6609, -122.5744).unwrap(), LatLng::new(37.8271, -122.3204).unwrap());
        OfflineTilePyramidRegionDefinition::new("https://example.com/style", bounds, 0.0, max_zoom, 1.0, true)
            .unwrap()
            .into()
    }

    fn point(max_zoom: f64) -> OfflineRegionDefinition {
        let point = Geometry::Point(Point::new(-122.5744, 37.6609));
        OfflineGeometryRegionDefinition::new("https://example.com/style", point, 0.0, max_zoom, 2.0, false)
            .unwrap()
            .into()
    }

    /// A definition encodes as JSON, which decodes to it again. An infinite
    /// max zoom is left out.
    #[test]
    fn a_definition_encodes_as_json_and_decodes_back() {
        let cases = [
            (
                pyramid(20.0),
                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]}"#,
            ),
            (
                point(2.0),
                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]}}"#,
            ),
            (
                point(f64::INFINITY),
                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]}}"#,
            ),
        ];
        for (definition, json) in cases {
            assert_eq!(json, encode_offline_region_definition(&definition));
            assert_eq!(definition, decode_offline_region_definition(json.as_bytes()).unwrap());
        }
    }

    #[test]
    fn a_malformed_definition_fails_to_decode() {
        for malformed in [
            "",
            "{}",
            "[]",
            r#"{"style_url":"s","min_zoom":"0","pixel_ratio":1.0,"bounds":[1.0,2.0,3.0,4.0]}"#,
            r#"{"style_url":"s","min_zoom":0.0,"bounds":[1.0,2.0,3.0,4.0]}"#,
            r#"{"style_url":"s","min_zoom":0.0,"pixel_ratio":1.0}"#,
            r#"{"style_url":"s","min_zoom":0.0,"pixel_ratio":1.0,"geometry":null}"#,
            r#"{"style_url":"s","min_zoom":0.0,"pixel_ratio":1.0,"bounds":[1.0,2.0,3.0]}"#,
            r#"{"style_url":"s","min_zoom":0.0,"pixel_ratio":1.0,"bounds":[1.0,2.0,3.0,"4"]}"#,
            r#"{"style_url":"s","min_zoom":0.0,"pixel_ratio":1.0,"bounds":[1.0,2.0,3.0,4.0],"include_ideographs":1}"#,
        ] {
            assert_eq!(
                "Malformed offline region definition",
                decode_offline_region_definition(malformed.as_bytes()).unwrap_err().message,
                "{malformed}"
            );
        }
    }

    /// The max zoom and whether to include ideographs default to infinity
    /// and true, and numbers may be integers.
    #[test]
    fn a_definition_decodes_with_defaults_and_integers() {
        let decoded = decode_offline_region_definition(
            br#"{"style_url":"s","min_zoom":1.0,"pixel_ratio":1.0,"bounds":[1.0,2.0,3.0,4.0]}"#,
        )
        .unwrap();
        assert_eq!((f64::INFINITY, true), (decoded.max_zoom(), decoded.include_ideographs()));

        let decoded = decode_offline_region_definition(
            br#"{"style_url":"s","min_zoom":0,"max_zoom":14,"pixel_ratio":2,"bounds":[1,2,3,4]}"#,
        )
        .unwrap();
        assert_eq!((0.0, 14.0, 2.0), (decoded.min_zoom(), decoded.max_zoom(), decoded.pixel_ratio()));
        let OfflineRegionDefinition::TilePyramid(region) = decoded else { panic!("a tile pyramid") };
        assert_eq!(
            (1.0, 2.0, 3.0, 4.0),
            (region.bounds.south(), region.bounds.west(), region.bounds.north(), region.bounds.east())
        );
    }
}