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 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 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    pub fn set_priority(&mut self, p: Priority) {
282        self.priority = p;
283    }
284
285    pub fn set_usage(&mut self, u: Usage) {
286        self.usage = u;
287    }
288
289    #[must_use]
290    pub fn has_loading_method(&self, method: LoadingMethod) -> bool {
291        (self.loading_method.0 & method.0) != 0
292    }
293
294    #[must_use]
295    pub fn style(url: &str) -> Resource {
296        Resource::new(Kind::Style, url)
297    }
298
299    #[must_use]
300    pub fn source(url: &str) -> Resource {
301        Resource::new(Kind::Source, url)
302    }
303
304    #[must_use]
305    pub fn image(url: &str) -> Resource {
306        Resource::new(Kind::Image, url)
307    }
308
309    #[must_use]
310    pub fn sprite_image(base: &str, pixel_ratio: f32) -> Resource {
311        Resource::new(Kind::SpriteImage, sprite_url(base, pixel_ratio, ".png"))
312    }
313
314    #[must_use]
315    pub fn sprite_json(base: &str, pixel_ratio: f32) -> Resource {
316        Resource::new(Kind::SpriteJSON, sprite_url(base, pixel_ratio, ".json"))
317    }
318
319    #[must_use]
320    pub fn glyphs(url_template: &str, font_stack: &FontStack, glyph_range: (u16, u16)) -> Resource {
321        Resource::new(
322            Kind::Glyphs,
323            replace_tokens(url_template, |token: &str| -> Option<String> {
324                if token == "fontstack" {
325                    Some(encode_font_stack(font_stack))
326                } else if token == "range" {
327                    Some(glyph_range.0.to_string() + "-" + &glyph_range.1.to_string())
328                } else {
329                    None
330                }
331            }),
332        )
333    }
334
335    #[must_use]
336    pub fn font_face(url: &str) -> Resource {
337        Resource::new(Kind::Glyphs, url)
338    }
339
340    #[must_use]
341    #[expect(
342        clippy::too_many_arguments,
343        reason = "the tileset's template, the tile and its tileset's scheme and format"
344    )]
345    pub fn tile(
346        url_template: &str,
347        pixel_ratio: f32,
348        x: i32,
349        y: i32,
350        z: i8,
351        scheme: Scheme,
352        format: TileFormat,
353        loading_method: LoadingMethod,
354    ) -> Resource {
355        let supports_ratio = url_template.contains("{ratio}");
356        let mut y = y;
357        if scheme == Scheme::TMS {
358            y = (1i32 << z).wrapping_sub(y).wrapping_sub(1);
359        }
360        let hex = b"0123456789abcdef";
361        let url = replace_tokens(url_template, |token: &str| -> Option<String> {
362            token.parse::<TileTemplateToken>().ok().map(|token| {
363                match token {
364                    TileTemplateToken::Z => z.to_string(),
365                    TileTemplateToken::X => x.to_string(),
366                    TileTemplateToken::Y => y.to_string(),
367                    TileTemplateToken::Quadkey => get_quad_key(x, y, z),
368                    // The spec defines `{bbox}` as `{bbox-epsg-3857}` under every
369                    // projection mln-rs has: mercator, globe and vertical-perspective.
370                    TileTemplateToken::Bbox | TileTemplateToken::BboxEpsg3857 => get_tile_bbox(x, y, z),
371                    TileTemplateToken::Prefix => {
372                        [hex[x.rem_euclid(16) as usize] as char, hex[y.rem_euclid(16) as usize] as char]
373                            .iter()
374                            .collect()
375                    }
376                    TileTemplateToken::Ratio => {
377                        if pixel_ratio > 1.0 {
378                            "@2x".to_owned()
379                        } else {
380                            String::new()
381                        }
382                    }
383                }
384            })
385        });
386        Resource::with_tile_data(
387            Kind::Tile,
388            url,
389            Some(TileData {
390                url_template: url_template.to_owned(),
391                pixel_ratio: if supports_ratio && pixel_ratio > 1.0 { 2 } else { 1 },
392                x,
393                y,
394                z,
395                format,
396            }),
397            loading_method,
398        )
399    }
400}
401
402#[cfg(test)]
403mod tests {
404    use super::*;
405
406    mod deliver {
407        use super::super::*;
408
409        fn at(secs: i64) -> Timestamp {
410            Timestamp::from_secs(1000 + secs)
411        }
412
413        fn waiting(caching: Caching) -> Resource {
414            let mut resource = Resource::style("https://example.com/style.json");
415            resource.prior_data = Some(Arc::new(b"cached".to_vec()));
416            resource.prior_etag = Some("a".to_owned());
417            resource.prior_caching = caching;
418            resource
419        }
420
421        #[test]
422        fn a_304_delivers_the_copy_with_its_caching_rules() {
423            let resource = waiting(Caching { expires: Some(at(-10)), ..Caching::default() });
424            let renewed = Response {
425                not_modified: true,
426                caching: Caching { expires: Some(at(100)), ..Caching::default() },
427                ..Response::default()
428            };
429            let delivered = resource.deliver(renewed);
430            assert!(!delivered.not_modified);
431            assert_eq!(Some(b"cached".as_slice()), delivered.data.as_deref().map(Vec::as_slice));
432            assert_eq!((Some(at(100)), Some("a")), (delivered.caching.expires, delivered.etag.as_deref()));
433        }
434    }
435
436    fn tile(url: &str, ratio: f32, x: i32, y: i32, z: i8, scheme: Scheme) -> Resource {
437        Resource::tile(url, ratio, x, y, z, scheme, TileFormat::Mvt, LoadingMethod::All)
438    }
439
440    fn check_tile(r: &Resource, url: &str, template: &str, pixel_ratio: u8, x: i32, y: i32, z: i8) {
441        assert_eq!(Kind::Tile, r.kind);
442        assert_eq!(url, r.url);
443        let tile_data = r.tile_data.as_ref().unwrap();
444        assert_eq!(template, tile_data.url_template);
445        assert_eq!(pixel_ratio, tile_data.pixel_ratio);
446        assert_eq!(x, tile_data.x);
447        assert_eq!(y, tile_data.y);
448        assert_eq!(z, tile_data.z);
449    }
450
451    // gtest: Resource.Style
452    #[test]
453    fn style() {
454        let resource = Resource::style("http://example.com");
455        assert_eq!(Kind::Style, resource.kind);
456        assert_eq!("http://example.com", resource.url);
457    }
458
459    // gtest: Resource.Source
460    #[test]
461    fn source() {
462        let resource = Resource::source("http://example.com");
463        assert_eq!(Kind::Source, resource.kind);
464        assert_eq!("http://example.com", resource.url);
465    }
466
467    // gtest: Resource.Tile
468    #[test]
469    fn tile_test() {
470        let t = "http://example.com/{z}/{x}/{y}{ratio}.png";
471        check_tile(&tile(t, 2.0, 1, 2, 3, Scheme::XYZ), "http://example.com/3/1/2@2x.png", t, 2, 1, 2, 3);
472
473        let t = "http://example.com/{prefix}/{z}/{x}/{y}.mvt";
474        check_tile(&tile(t, 2.0, 1, 2, 3, Scheme::XYZ), "http://example.com/12/3/1/2.mvt", t, 1, 1, 2, 3);
475
476        let t = "http://example.com/{quadkey}.png";
477        check_tile(&tile(t, 2.0, 0, 0, 1, Scheme::XYZ), "http://example.com/0.png", t, 1, 0, 0, 1);
478        check_tile(&tile(t, 2.0, 0, 0, 2, Scheme::XYZ), "http://example.com/00.png", t, 1, 0, 0, 2);
479        check_tile(&tile(t, 2.0, 1, 1, 2, Scheme::XYZ), "http://example.com/03.png", t, 1, 1, 1, 2);
480        check_tile(
481            &tile(t, 2.0, 22914, 52870, 17, Scheme::XYZ),
482            "http://example.com/02301322130000230.png",
483            t,
484            1,
485            22914,
486            52870,
487            17,
488        );
489        // Test case confirmed by quadkeytools package
490        check_tile(&tile(t, 2.0, 29, 3, 6, Scheme::XYZ), "http://example.com/011123.png", t, 1, 29, 3, 6);
491
492        let t = "http://example.com/?bbox={bbox-epsg-3857}";
493        check_tile(
494            &tile(t, 2.0, 0, 0, 1, Scheme::XYZ),
495            "http://example.com/?bbox=-20037508.342789244,0,0,20037508.342789244",
496            t,
497            1,
498            0,
499            0,
500            1,
501        );
502
503        let t = "http://example.com/{z}/{x}/{y}{ratio}.png";
504        check_tile(&tile(t, 1.0, 1, 2, 3, Scheme::TMS), "http://example.com/3/1/5.png", t, 1, 1, 5, 3);
505    }
506
507    #[test]
508    fn tile_bbox_matches_epsg_3857() {
509        let t = "http://example.com/?bbox={bbox}";
510        check_tile(
511            &tile(t, 1.0, 0, 0, 1, Scheme::XYZ),
512            "http://example.com/?bbox=-20037508.342789244,0,0,20037508.342789244",
513            t,
514            1,
515            0,
516            0,
517            1,
518        );
519    }
520
521    // gtest: Resource.Glyphs
522    #[test]
523    fn glyphs() {
524        let resource = Resource::glyphs("http://example.com/{fontstack}/{range}", &vec!["stack".to_owned()], (0, 255));
525        assert_eq!(Kind::Glyphs, resource.kind);
526        assert_eq!("http://example.com/stack/0-255", resource.url);
527
528        let resource = Resource::glyphs(
529            "http://example.com/{fontstack}/{range}",
530            &vec!["Open Sans".to_owned(), "cø".to_owned()],
531            (0, 255),
532        );
533        assert_eq!("http://example.com/Open%20Sans%2cc%c3%b8/0-255", resource.url);
534    }
535
536    // gtest: Resource.SpriteImage
537    #[test]
538    fn sprite_image() {
539        let resource = Resource::sprite_image("http://example.com/sprite", 2.0);
540        assert_eq!(Kind::SpriteImage, resource.kind);
541        assert_eq!("http://example.com/sprite@2x.png", resource.url);
542
543        let param_resource = Resource::sprite_image("http://example.com/sprite?query=true", 2.0);
544        assert_eq!(Kind::SpriteImage, param_resource.kind);
545        assert_eq!("http://example.com/sprite@2x.png?query=true", param_resource.url);
546
547        let fragment_resource = Resource::sprite_image("http://example.com/sprite?query=true#fragment", 2.0);
548        assert_eq!("http://example.com/sprite@2x.png?query=true", fragment_resource.url);
549    }
550
551    // gtest: Resource.Image
552    #[test]
553    fn image() {
554        let resource = Resource::image("http://example.com/sprite.jpg");
555        assert_eq!(Kind::Image, resource.kind);
556        assert_eq!("http://example.com/sprite.jpg", resource.url);
557    }
558
559    // gtest: Resource.SpriteJSON
560    #[test]
561    fn sprite_json() {
562        let resource = Resource::sprite_json("http://example.com/sprite", 2.0);
563        assert_eq!(Kind::SpriteJSON, resource.kind);
564        assert_eq!("http://example.com/sprite@2x.json", resource.url);
565
566        let param_resource = Resource::sprite_json("http://example.com/sprite?query=true", 2.0);
567        assert_eq!(Kind::SpriteJSON, param_resource.kind);
568        assert_eq!("http://example.com/sprite@2x.json?query=true", param_resource.url);
569
570        let fragment_resource = Resource::sprite_json("http://example.com/sprite#fragment?ignored=true", 2.0);
571        assert_eq!("http://example.com/sprite@2x.json", fragment_resource.url);
572    }
573}