Skip to main content

mln_engine/storage/
resource.rs

1use std::str::FromStr;
2use std::sync::Arc;
3use std::sync::atomic::{AtomicU32, Ordering};
4use std::time::Duration;
5
6use mln_style::string::to_string_double;
7use mln_style::tileset::Scheme;
8
9use crate::geo::constants::{EARTH_RADIUS_M, M2PI};
10use crate::storage::chrono::Timestamp;
11use crate::storage::response::{Caching, Data, Response};
12use crate::storage::token::replace_tokens;
13use crate::text::font_stack::{FontStack, font_stack_to_string};
14
15/// Token that may appear in a tile URL template.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17enum TileTemplateToken {
18    Z,
19    X,
20    Y,
21    Quadkey,
22    Bbox,
23    BboxEpsg3857,
24    Prefix,
25    Ratio,
26}
27
28impl FromStr for TileTemplateToken {
29    type Err = ();
30
31    fn from_str(s: &str) -> Result<Self, Self::Err> {
32        match s {
33            "z" => Ok(Self::Z),
34            "x" => Ok(Self::X),
35            "y" => Ok(Self::Y),
36            "quadkey" => Ok(Self::Quadkey),
37            "bbox" => Ok(Self::Bbox),
38            "bbox-epsg-3857" => Ok(Self::BboxEpsg3857),
39            "prefix" => Ok(Self::Prefix),
40            "ratio" => Ok(Self::Ratio),
41            _ => Err(()),
42        }
43    }
44}
45
46/// The kind of a resource. The values are stored in the offline database.
47#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
48#[repr(u8)]
49pub enum Kind {
50    Unknown = 0,
51    Style,
52    Source,
53    Tile,
54    Glyphs,
55    SpriteImage,
56    SpriteJSON,
57    Image,
58}
59
60#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
61pub enum Priority {
62    #[default]
63    Regular,
64    Low,
65}
66
67/// Where a request stands among the waiting requests of its [`Priority`]:
68/// a file source that makes requests wait starts the one with the lowest
69/// value first, and those with the same value in the order they came.
70///
71/// A clone shares the value, so whoever made a request can change where it
72/// stands while it waits, through the [`Resource`] it kept. A request that
73/// has started isn't affected.
74#[derive(Clone, Debug, Default)]
75pub struct RequestOrder(Arc<AtomicU32>);
76
77impl RequestOrder {
78    #[must_use]
79    pub fn get(&self) -> u32 {
80        self.0.load(Ordering::Relaxed)
81    }
82
83    pub(crate) fn set(&self, order: u32) {
84        self.0.store(order, Ordering::Relaxed);
85    }
86}
87
88#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
89pub enum Usage {
90    #[default]
91    Online,
92    Offline,
93}
94
95#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
96pub enum StoragePolicy {
97    #[default]
98    Permanent,
99    Volatile,
100}
101
102#[derive(Clone, Debug, PartialEq, Eq)]
103pub struct TileData {
104    pub url_template: String,
105    pub(crate) pixel_ratio: u8,
106    pub x: i32,
107    pub y: i32,
108    pub z: i8,
109    pub format: TileFormat,
110}
111
112/// What a tile's data is, which decides the media types that an HTTP
113/// request for it accepts.
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub enum TileFormat {
116    /// A Mapbox Vector Tile.
117    Mvt,
118    /// A MapLibre Tile.
119    Mlt,
120    /// An image: a raster or raster-dem tile.
121    Image,
122}
123
124/// A bitmask of the ways a resource may be loaded.
125#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
126pub struct LoadingMethod(pub u8);
127
128#[expect(non_upper_case_globals, reason = "the bit flags keep MapLibre Native's names")]
129impl LoadingMethod {
130    #[cfg(test)]
131    pub(crate) const None: LoadingMethod = LoadingMethod(0b00);
132    pub(crate) const Cache: LoadingMethod = LoadingMethod(0b01);
133    pub const Network: LoadingMethod = LoadingMethod(0b10);
134
135    pub const CacheOnly: LoadingMethod = Self::Cache;
136    pub const NetworkOnly: LoadingMethod = Self::Network;
137    pub const All: LoadingMethod = LoadingMethod(0b01 | 0b10);
138}
139
140/// `Resource`.
141#[derive(Clone, Debug)]
142pub struct Resource {
143    pub kind: Kind,
144    pub loading_method: LoadingMethod,
145    pub usage: Usage,
146    pub priority: Priority,
147    /// Zero, ahead of every request that sets it, unless the requester says
148    /// otherwise.
149    pub order: RequestOrder,
150    pub url: String,
151
152    /// Includes auxiliary data if this is a tile request.
153    pub tile_data: Option<TileData>,
154
155    pub data_range: Option<(u64, u64)>,
156    /// The copy of the resource the requester has or the cache holds, which
157    /// a request revalidates: its validators and caching rules, and its data
158    /// if the requester waits for it (see [`Resource::deliver`]).
159    pub prior_modified: Option<Timestamp>,
160    pub prior_etag: Option<String>,
161    pub prior_caching: Caching,
162    pub prior_data: Option<Data>,
163    pub minimum_update_interval: Duration,
164    pub storage_policy: StoragePolicy,
165}
166
167fn get_quad_key(x: i32, y: i32, z: i8) -> String {
168    let mut quad_key = String::with_capacity(z.max(0) as usize);
169    let mut i = z;
170    while i > 0 {
171        let mask: i32 = 1 << (i - 1);
172        quad_key.push((b'0' + u8::from(x & mask != 0) + (if y & mask != 0 { 2 } else { 0 })) as char);
173        i -= 1;
174    }
175    quad_key
176}
177
178fn get_merc_coord(x: i32, y: i32, z: i8) -> (f64, f64) {
179    let resolution = (M2PI * EARTH_RADIUS_M / 256.0) / 2f64.powi(i32::from(z));
180    (f64::from(x) * resolution - M2PI * EARTH_RADIUS_M / 2.0, f64::from(y) * resolution - M2PI * EARTH_RADIUS_M / 2.0)
181}
182
183fn get_tile_bbox(x: i32, y: i32, z: i8) -> String {
184    // Alter the y for the Google/OSM tile scheme.
185    let y = (2f64.powi(i32::from(z)) as i32).wrapping_sub(y).wrapping_sub(1);
186
187    let min = get_merc_coord(x.wrapping_mul(256), y.wrapping_mul(256), z);
188    let max = get_merc_coord(x.wrapping_add(1).wrapping_mul(256), y.wrapping_add(1).wrapping_mul(256), z);
189
190    to_string_double(min.0)
191        + ","
192        + &to_string_double(min.1)
193        + ","
194        + &to_string_double(max.0)
195        + ","
196        + &to_string_double(max.1)
197}
198
199fn sprite_url(base: &str, pixel_ratio: f32, extension: &str) -> String {
200    let fragment = base.find('#').unwrap_or(base.len());
201    let query = base.find('?').filter(|&query| query < fragment);
202    let path_end = query.unwrap_or(fragment);
203    let suffix = if pixel_ratio > 1.0 { "@2x" } else { "" };
204    format!("{}{suffix}{extension}{}", &base[..path_end], query.map_or("", |query| &base[query..fragment]))
205}
206
207fn encode_font_stack(font_stack: &FontStack) -> String {
208    let hex = b"0123456789abcdef";
209    let mut encoded = String::new();
210    for byte in font_stack_to_string(font_stack).bytes() {
211        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
212            encoded.push(byte as char);
213        } else {
214            encoded.push('%');
215            encoded.push(hex[(byte >> 4) as usize] as char);
216            encoded.push(hex[(byte & 0x0f) as usize] as char);
217        }
218    }
219    encoded
220}
221
222impl Resource {
223    pub(crate) fn new(kind: Kind, url: impl Into<String>) -> Self {
224        Self::with_tile_data(kind, url, None, LoadingMethod::All)
225    }
226
227    pub(crate) fn with_tile_data(
228        kind: Kind,
229        url: impl Into<String>,
230        tile_data: Option<TileData>,
231        loading_method: LoadingMethod,
232    ) -> Self {
233        Resource {
234            kind,
235            loading_method,
236            usage: Usage::Online,
237            priority: Priority::Regular,
238            order: RequestOrder::default(),
239            url: url.into(),
240            tile_data,
241            data_range: None,
242            prior_modified: None,
243            prior_etag: None,
244            prior_caching: Caching::default(),
245            prior_data: None,
246            minimum_update_interval: Duration::ZERO,
247            storage_policy: StoragePolicy::Permanent,
248        }
249    }
250
251    /// Takes the validators and caching rules of `response`, a copy of the
252    /// resource, as the prior copy's. The requester has that copy, so no data
253    /// waits for it.
254    pub fn set_prior(&mut self, response: &Response) {
255        self.prior_data = None;
256        self.prior_modified = response.modified;
257        self.prior_etag.clone_from(&response.etag);
258        self.prior_caching = response.caching;
259    }
260
261    /// What a revalidation's answer `response` delivers: a 304 keeps the
262    /// prior copy's validators it lacks, and to a requester that waits for
263    /// that copy in `prior_data`, delivers it. Any other answer as it is.
264    #[must_use]
265    pub fn deliver(&self, mut response: Response) -> Response {
266        if !response.not_modified {
267            return response;
268        }
269        response.modified = response.modified.or(self.prior_modified);
270        if response.etag.is_none() {
271            response.etag.clone_from(&self.prior_etag);
272        }
273        if let Some(data) = &self.prior_data {
274            response.data = Some(Arc::clone(data));
275            response.not_modified = false;
276            response.prior = true;
277        }
278        response
279    }
280
281    #[cfg(any(test, feature = "sqlite"))]
282    pub(crate) fn set_priority(&mut self, p: Priority) {
283        self.priority = p;
284    }
285
286    #[cfg(feature = "sqlite")]
287    pub(crate) fn set_usage(&mut self, u: Usage) {
288        self.usage = u;
289    }
290
291    #[must_use]
292    pub fn has_loading_method(&self, method: LoadingMethod) -> bool {
293        (self.loading_method.0 & method.0) != 0
294    }
295
296    #[must_use]
297    pub fn style(url: &str) -> Resource {
298        Resource::new(Kind::Style, url)
299    }
300
301    #[must_use]
302    pub fn source(url: &str) -> Resource {
303        Resource::new(Kind::Source, url)
304    }
305
306    #[must_use]
307    pub fn image(url: &str) -> Resource {
308        Resource::new(Kind::Image, url)
309    }
310
311    #[must_use]
312    pub fn sprite_image(base: &str, pixel_ratio: f32) -> Resource {
313        Resource::new(Kind::SpriteImage, sprite_url(base, pixel_ratio, ".png"))
314    }
315
316    #[must_use]
317    pub fn sprite_json(base: &str, pixel_ratio: f32) -> Resource {
318        Resource::new(Kind::SpriteJSON, sprite_url(base, pixel_ratio, ".json"))
319    }
320
321    #[must_use]
322    pub fn glyphs(url_template: &str, font_stack: &FontStack, glyph_range: (u16, u16)) -> Resource {
323        Resource::new(
324            Kind::Glyphs,
325            replace_tokens(url_template, |token: &str| -> Option<String> {
326                if token == "fontstack" {
327                    Some(encode_font_stack(font_stack))
328                } else if token == "range" {
329                    Some(glyph_range.0.to_string() + "-" + &glyph_range.1.to_string())
330                } else {
331                    None
332                }
333            }),
334        )
335    }
336
337    #[must_use]
338    pub(crate) fn font_face(url: &str) -> Resource {
339        Resource::new(Kind::Glyphs, url)
340    }
341
342    #[must_use]
343    #[expect(
344        clippy::too_many_arguments,
345        reason = "the tileset's template, the tile and its tileset's scheme and format"
346    )]
347    pub fn tile(
348        url_template: &str,
349        pixel_ratio: f32,
350        x: i32,
351        y: i32,
352        z: i8,
353        scheme: Scheme,
354        format: TileFormat,
355        loading_method: LoadingMethod,
356    ) -> Resource {
357        let supports_ratio = url_template.contains("{ratio}");
358        let mut y = y;
359        if scheme == Scheme::TMS {
360            y = (1i32 << z).wrapping_sub(y).wrapping_sub(1);
361        }
362        let hex = b"0123456789abcdef";
363        let url = replace_tokens(url_template, |token: &str| -> Option<String> {
364            token.parse::<TileTemplateToken>().ok().map(|token| {
365                match token {
366                    TileTemplateToken::Z => z.to_string(),
367                    TileTemplateToken::X => x.to_string(),
368                    TileTemplateToken::Y => y.to_string(),
369                    TileTemplateToken::Quadkey => get_quad_key(x, y, z),
370                    // The spec defines `{bbox}` as `{bbox-epsg-3857}` under every
371                    // projection mln-rs has: mercator, globe and vertical-perspective.
372                    TileTemplateToken::Bbox | TileTemplateToken::BboxEpsg3857 => get_tile_bbox(x, y, z),
373                    TileTemplateToken::Prefix => {
374                        [hex[x.rem_euclid(16) as usize] as char, hex[y.rem_euclid(16) as usize] as char]
375                            .iter()
376                            .collect()
377                    }
378                    TileTemplateToken::Ratio => {
379                        if pixel_ratio > 1.0 {
380                            "@2x".to_owned()
381                        } else {
382                            String::new()
383                        }
384                    }
385                }
386            })
387        });
388        Resource::with_tile_data(
389            Kind::Tile,
390            url,
391            Some(TileData {
392                url_template: url_template.to_owned(),
393                pixel_ratio: if supports_ratio && pixel_ratio > 1.0 { 2 } else { 1 },
394                x,
395                y,
396                z,
397                format,
398            }),
399            loading_method,
400        )
401    }
402}
403
404#[cfg(test)]
405mod tests {
406    use super::*;
407
408    mod deliver {
409        use super::super::*;
410
411        fn at(secs: i64) -> Timestamp {
412            Timestamp::from_secs(1000 + secs)
413        }
414
415        fn waiting(caching: Caching) -> Resource {
416            let mut resource = Resource::style("https://example.com/style.json");
417            resource.prior_data = Some(Arc::new(b"cached".to_vec()));
418            resource.prior_etag = Some("a".to_owned());
419            resource.prior_caching = caching;
420            resource
421        }
422
423        #[test]
424        fn a_304_delivers_the_copy_with_its_caching_rules() {
425            let resource = waiting(Caching { expires: Some(at(-10)), ..Caching::default() });
426            let renewed = Response {
427                not_modified: true,
428                caching: Caching { expires: Some(at(100)), ..Caching::default() },
429                ..Response::default()
430            };
431            let delivered = resource.deliver(renewed);
432            assert!(!delivered.not_modified);
433            assert_eq!(Some(b"cached".as_slice()), delivered.data.as_deref().map(Vec::as_slice));
434            assert_eq!((Some(at(100)), Some("a")), (delivered.caching.expires, delivered.etag.as_deref()));
435        }
436    }
437
438    fn tile(url: &str, ratio: f32, x: i32, y: i32, z: i8, scheme: Scheme) -> Resource {
439        Resource::tile(url, ratio, x, y, z, scheme, TileFormat::Mvt, LoadingMethod::All)
440    }
441
442    fn check_tile(r: &Resource, url: &str, template: &str, pixel_ratio: u8, x: i32, y: i32, z: i8) {
443        assert_eq!(Kind::Tile, r.kind);
444        assert_eq!(url, r.url);
445        let tile_data = r.tile_data.as_ref().unwrap();
446        assert_eq!(template, tile_data.url_template);
447        assert_eq!(pixel_ratio, tile_data.pixel_ratio);
448        assert_eq!(x, tile_data.x);
449        assert_eq!(y, tile_data.y);
450        assert_eq!(z, tile_data.z);
451    }
452
453    // gtest: Resource.Style
454    #[test]
455    fn style() {
456        let resource = Resource::style("http://example.com");
457        assert_eq!(Kind::Style, resource.kind);
458        assert_eq!("http://example.com", resource.url);
459    }
460
461    // gtest: Resource.Source
462    #[test]
463    fn source() {
464        let resource = Resource::source("http://example.com");
465        assert_eq!(Kind::Source, resource.kind);
466        assert_eq!("http://example.com", resource.url);
467    }
468
469    // gtest: Resource.Tile
470    #[test]
471    fn tile_test() {
472        let t = "http://example.com/{z}/{x}/{y}{ratio}.png";
473        check_tile(&tile(t, 2.0, 1, 2, 3, Scheme::XYZ), "http://example.com/3/1/2@2x.png", t, 2, 1, 2, 3);
474
475        let t = "http://example.com/{prefix}/{z}/{x}/{y}.mvt";
476        check_tile(&tile(t, 2.0, 1, 2, 3, Scheme::XYZ), "http://example.com/12/3/1/2.mvt", t, 1, 1, 2, 3);
477
478        let t = "http://example.com/{quadkey}.png";
479        check_tile(&tile(t, 2.0, 0, 0, 1, Scheme::XYZ), "http://example.com/0.png", t, 1, 0, 0, 1);
480        check_tile(&tile(t, 2.0, 0, 0, 2, Scheme::XYZ), "http://example.com/00.png", t, 1, 0, 0, 2);
481        check_tile(&tile(t, 2.0, 1, 1, 2, Scheme::XYZ), "http://example.com/03.png", t, 1, 1, 1, 2);
482        check_tile(
483            &tile(t, 2.0, 22914, 52870, 17, Scheme::XYZ),
484            "http://example.com/02301322130000230.png",
485            t,
486            1,
487            22914,
488            52870,
489            17,
490        );
491        // Test case confirmed by quadkeytools package
492        check_tile(&tile(t, 2.0, 29, 3, 6, Scheme::XYZ), "http://example.com/011123.png", t, 1, 29, 3, 6);
493
494        let t = "http://example.com/?bbox={bbox-epsg-3857}";
495        check_tile(
496            &tile(t, 2.0, 0, 0, 1, Scheme::XYZ),
497            "http://example.com/?bbox=-20037508.342789244,0,0,20037508.342789244",
498            t,
499            1,
500            0,
501            0,
502            1,
503        );
504
505        let t = "http://example.com/{z}/{x}/{y}{ratio}.png";
506        check_tile(&tile(t, 1.0, 1, 2, 3, Scheme::TMS), "http://example.com/3/1/5.png", t, 1, 1, 5, 3);
507    }
508
509    #[test]
510    fn tile_bbox_matches_epsg_3857() {
511        let t = "http://example.com/?bbox={bbox}";
512        check_tile(
513            &tile(t, 1.0, 0, 0, 1, Scheme::XYZ),
514            "http://example.com/?bbox=-20037508.342789244,0,0,20037508.342789244",
515            t,
516            1,
517            0,
518            0,
519            1,
520        );
521    }
522
523    // gtest: Resource.Glyphs
524    #[test]
525    fn glyphs() {
526        let resource = Resource::glyphs("http://example.com/{fontstack}/{range}", &vec!["stack".to_owned()], (0, 255));
527        assert_eq!(Kind::Glyphs, resource.kind);
528        assert_eq!("http://example.com/stack/0-255", resource.url);
529
530        let resource = Resource::glyphs(
531            "http://example.com/{fontstack}/{range}",
532            &vec!["Open Sans".to_owned(), "cø".to_owned()],
533            (0, 255),
534        );
535        assert_eq!("http://example.com/Open%20Sans%2cc%c3%b8/0-255", resource.url);
536    }
537
538    // gtest: Resource.SpriteImage
539    #[test]
540    fn sprite_image() {
541        let resource = Resource::sprite_image("http://example.com/sprite", 2.0);
542        assert_eq!(Kind::SpriteImage, resource.kind);
543        assert_eq!("http://example.com/sprite@2x.png", resource.url);
544
545        let param_resource = Resource::sprite_image("http://example.com/sprite?query=true", 2.0);
546        assert_eq!(Kind::SpriteImage, param_resource.kind);
547        assert_eq!("http://example.com/sprite@2x.png?query=true", param_resource.url);
548
549        let fragment_resource = Resource::sprite_image("http://example.com/sprite?query=true#fragment", 2.0);
550        assert_eq!("http://example.com/sprite@2x.png?query=true", fragment_resource.url);
551    }
552
553    // gtest: Resource.Image
554    #[test]
555    fn image() {
556        let resource = Resource::image("http://example.com/sprite.jpg");
557        assert_eq!(Kind::Image, resource.kind);
558        assert_eq!("http://example.com/sprite.jpg", resource.url);
559    }
560
561    // gtest: Resource.SpriteJSON
562    #[test]
563    fn sprite_json() {
564        let resource = Resource::sprite_json("http://example.com/sprite", 2.0);
565        assert_eq!(Kind::SpriteJSON, resource.kind);
566        assert_eq!("http://example.com/sprite@2x.json", resource.url);
567
568        let param_resource = Resource::sprite_json("http://example.com/sprite?query=true", 2.0);
569        assert_eq!(Kind::SpriteJSON, param_resource.kind);
570        assert_eq!("http://example.com/sprite@2x.json?query=true", param_resource.url);
571
572        let fragment_resource = Resource::sprite_json("http://example.com/sprite#fragment?ignored=true", 2.0);
573        assert_eq!("http://example.com/sprite@2x.json", fragment_resource.url);
574    }
575}