1use std::str::FromStr;
2use std::sync::Arc;
3use std::sync::atomic::{AtomicU32, Ordering};
4use std::time::Duration;
5
6use mln_style::crs::TileMatrixSet;
7use mln_style::string::to_string_double;
8use mln_style::tileset::Scheme;
9
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#[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#[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#[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub enum TileFormat {
116 Mvt,
118 Mlt,
120 Image,
122}
123
124#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
126pub struct LoadingMethod(pub u8);
127
128impl LoadingMethod {
129 #[cfg(test)]
130 pub(crate) const NONE: LoadingMethod = LoadingMethod(0b00);
131 pub const CACHE: LoadingMethod = LoadingMethod(0b01);
133 pub const NETWORK: LoadingMethod = LoadingMethod(0b10);
135 pub const ALL: LoadingMethod = LoadingMethod(0b01 | 0b10);
137}
138
139#[derive(Clone, Debug)]
141pub struct Resource {
142 pub kind: Kind,
143 pub loading_method: LoadingMethod,
144 pub usage: Usage,
145 pub priority: Priority,
146 pub order: RequestOrder,
149 pub url: String,
150
151 pub tile_data: Option<TileData>,
153
154 pub data_range: Option<(u64, u64)>,
155 pub prior_modified: Option<Timestamp>,
159 pub prior_etag: Option<String>,
160 pub prior_caching: Caching,
161 pub prior_data: Option<Data>,
162 pub minimum_update_interval: Duration,
163 pub storage_policy: StoragePolicy,
164}
165
166fn quad_key(x: i32, y: i32, z: i8) -> String {
167 let mut quad_key = String::with_capacity(z.max(0) as usize);
168 let mut i = z;
169 while i > 0 {
170 let mask: i32 = 1 << (i - 1);
171 quad_key.push((b'0' + u8::from(x & mask != 0) + (if y & mask != 0 { 2 } else { 0 })) as char);
172 i -= 1;
173 }
174 quad_key
175}
176
177fn tile_bbox_in(tile_matrix_set: &TileMatrixSet, x: i32, y: i32, z: i8) -> String {
180 let tiles = 2f64.powi(i32::from(z));
181 let tile_extent = tile_matrix_set.extent_at_zoom0 / tiles;
182 let [grid_min_x, grid_max_y] = tile_matrix_set.origin;
183 let grid_min_y = grid_max_y - tile_matrix_set.extent_at_zoom0;
184 let row_from_bottom = tiles - f64::from(y) - 1.0;
185 [
186 grid_min_x + f64::from(x) * tile_extent,
187 grid_min_y + row_from_bottom * tile_extent,
188 grid_min_x + (f64::from(x) + 1.0) * tile_extent,
189 grid_min_y + (row_from_bottom + 1.0) * tile_extent,
190 ]
191 .map(to_string_double)
192 .join(",")
193}
194
195#[derive(Clone, Copy, Debug, PartialEq)]
200pub struct TileAddressing {
201 pub scheme: Scheme,
202 pub tile_matrix_set: TileMatrixSet,
203}
204
205impl From<Scheme> for TileAddressing {
206 fn from(scheme: Scheme) -> Self {
207 TileAddressing { scheme, tile_matrix_set: TileMatrixSet::WEB_MERCATOR }
208 }
209}
210
211fn sprite_url(base: &str, pixel_ratio: f32, extension: &str) -> String {
212 let fragment = base.find('#').unwrap_or(base.len());
213 let query = base.find('?').filter(|&query| query < fragment);
214 let path_end = query.unwrap_or(fragment);
215 let suffix = if pixel_ratio > 1.0 { "@2x" } else { "" };
216 format!("{}{suffix}{extension}{}", &base[..path_end], query.map_or("", |query| &base[query..fragment]))
217}
218
219fn encode_font_stack(font_stack: &FontStack) -> String {
220 let hex = b"0123456789abcdef";
221 let mut encoded = String::new();
222 for byte in font_stack_to_string(font_stack).bytes() {
223 if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
224 encoded.push(byte as char);
225 } else {
226 encoded.push('%');
227 encoded.push(hex[(byte >> 4) as usize] as char);
228 encoded.push(hex[(byte & 0x0f) as usize] as char);
229 }
230 }
231 encoded
232}
233
234impl Resource {
235 pub(crate) fn new(kind: Kind, url: impl Into<String>) -> Self {
236 Self::with_tile_data(kind, url, None, LoadingMethod::ALL)
237 }
238
239 pub(crate) fn with_tile_data(
240 kind: Kind,
241 url: impl Into<String>,
242 tile_data: Option<TileData>,
243 loading_method: LoadingMethod,
244 ) -> Self {
245 Resource {
246 kind,
247 loading_method,
248 usage: Usage::Online,
249 priority: Priority::Regular,
250 order: RequestOrder::default(),
251 url: url.into(),
252 tile_data,
253 data_range: None,
254 prior_modified: None,
255 prior_etag: None,
256 prior_caching: Caching::default(),
257 prior_data: None,
258 minimum_update_interval: Duration::ZERO,
259 storage_policy: StoragePolicy::Permanent,
260 }
261 }
262
263 pub fn set_prior(&mut self, response: &Response) {
267 self.prior_data = None;
268 self.prior_modified = response.modified;
269 self.prior_etag.clone_from(&response.etag);
270 self.prior_caching = response.caching;
271 }
272
273 #[must_use]
277 pub fn deliver(&self, mut response: Response) -> Response {
278 if !response.not_modified {
279 return response;
280 }
281 response.modified = response.modified.or(self.prior_modified);
282 if response.etag.is_none() {
283 response.etag.clone_from(&self.prior_etag);
284 }
285 if let Some(data) = &self.prior_data {
286 response.data = Some(Arc::clone(data));
287 response.not_modified = false;
288 response.prior = true;
289 }
290 response
291 }
292
293 #[cfg(any(test, feature = "sqlite"))]
294 pub(crate) fn set_priority(&mut self, p: Priority) {
295 self.priority = p;
296 }
297
298 #[cfg(feature = "sqlite")]
299 pub(crate) fn set_usage(&mut self, u: Usage) {
300 self.usage = u;
301 }
302
303 #[must_use]
304 pub fn has_loading_method(&self, method: LoadingMethod) -> bool {
305 (self.loading_method.0 & method.0) != 0
306 }
307
308 #[must_use]
309 pub fn style(url: &str) -> Resource {
310 Resource::new(Kind::Style, url)
311 }
312
313 #[must_use]
314 pub fn source(url: &str) -> Resource {
315 Resource::new(Kind::Source, url)
316 }
317
318 #[must_use]
319 pub fn image(url: &str) -> Resource {
320 Resource::new(Kind::Image, url)
321 }
322
323 #[must_use]
324 pub fn sprite_image(base: &str, pixel_ratio: f32) -> Resource {
325 Resource::new(Kind::SpriteImage, sprite_url(base, pixel_ratio, ".png"))
326 }
327
328 #[must_use]
329 pub fn sprite_json(base: &str, pixel_ratio: f32) -> Resource {
330 Resource::new(Kind::SpriteJSON, sprite_url(base, pixel_ratio, ".json"))
331 }
332
333 #[must_use]
334 pub fn glyphs(url_template: &str, font_stack: &FontStack, glyph_range: (u16, u16)) -> Resource {
335 Resource::new(
336 Kind::Glyphs,
337 replace_tokens(url_template, |token: &str| -> Option<String> {
338 if token == "fontstack" {
339 Some(encode_font_stack(font_stack))
340 } else if token == "range" {
341 Some(format!("{}-{}", glyph_range.0, glyph_range.1))
342 } else {
343 None
344 }
345 }),
346 )
347 }
348
349 #[must_use]
350 pub(crate) fn font_face(url: &str) -> Resource {
351 Resource::new(Kind::Glyphs, url)
352 }
353
354 #[must_use]
362 #[expect(
363 clippy::too_many_arguments,
364 reason = "the tileset's template, the tile and its tileset's addressing and format"
365 )]
366 pub fn tile(
367 url_template: &str,
368 pixel_ratio: f32,
369 x: i32,
370 y: i32,
371 z: i8,
372 addressing: impl Into<TileAddressing>,
373 format: TileFormat,
374 loading_method: LoadingMethod,
375 ) -> Resource {
376 let TileAddressing { scheme, tile_matrix_set } = addressing.into();
377 let supports_ratio = url_template.contains("{ratio}");
378 let row = y;
379 let mut y = y;
380 if scheme == Scheme::Tms {
381 y = (1i32 << z).wrapping_sub(y).wrapping_sub(1);
382 }
383 let hex = b"0123456789abcdef";
384 let url = replace_tokens(url_template, |token: &str| -> Option<String> {
385 token.parse::<TileTemplateToken>().ok().map(|token| match token {
386 TileTemplateToken::Z => z.to_string(),
387 TileTemplateToken::X => x.to_string(),
388 TileTemplateToken::Y => y.to_string(),
389 TileTemplateToken::Quadkey => quad_key(x, y, z),
390 TileTemplateToken::Bbox => tile_bbox_in(&tile_matrix_set, x, row, z),
391 TileTemplateToken::BboxEpsg3857 => tile_bbox_in(&TileMatrixSet::WEB_MERCATOR, x, row, z),
392 TileTemplateToken::Prefix => {
393 [hex[x.rem_euclid(16) as usize] as char, hex[y.rem_euclid(16) as usize] as char].iter().collect()
394 }
395 TileTemplateToken::Ratio => {
396 if pixel_ratio > 1.0 {
397 "@2x".to_owned()
398 } else {
399 String::new()
400 }
401 }
402 })
403 });
404 Resource::with_tile_data(
405 Kind::Tile,
406 url,
407 Some(TileData {
408 url_template: url_template.to_owned(),
409 pixel_ratio: if supports_ratio && pixel_ratio > 1.0 { 2 } else { 1 },
410 x,
411 y,
412 z,
413 format,
414 }),
415 loading_method,
416 )
417 }
418}
419
420#[cfg(test)]
421mod tests {
422 use approx::assert_abs_diff_eq;
423
424 use super::*;
425
426 mod deliver {
427 use super::super::*;
428
429 fn at(secs: i64) -> Timestamp {
430 Timestamp::from_secs(1000 + secs)
431 }
432
433 fn waiting(caching: Caching) -> Resource {
434 let mut resource = Resource::style("https://example.com/style.json");
435 resource.prior_data = Some(Arc::new(b"cached".to_vec()));
436 resource.prior_etag = Some("a".to_owned());
437 resource.prior_caching = caching;
438 resource
439 }
440
441 #[test]
442 fn a_304_delivers_the_copy_with_its_caching_rules() {
443 let resource = waiting(Caching { expires: Some(at(-10)), ..Caching::default() });
444 let renewed = Response {
445 not_modified: true,
446 caching: Caching { expires: Some(at(100)), ..Caching::default() },
447 ..Response::default()
448 };
449 let delivered = resource.deliver(renewed);
450 assert!(!delivered.not_modified);
451 assert_eq!(Some(b"cached".as_slice()), delivered.data.as_deref().map(Vec::as_slice));
452 assert_eq!((Some(at(100)), Some("a")), (delivered.caching.expires, delivered.etag.as_deref()));
453 }
454 }
455
456 #[test]
460 fn a_tile_url_fills_in_its_template() {
461 let mercator_box = "-20037508.342789244,0,0,20037508.342789244";
462 #[rustfmt::skip]
463 let cases = [
464 ("http://example.com/{z}/{x}/{y}{ratio}.png", (1, 2, 3), 2.0, Scheme::Xyz, "http://example.com/3/1/2@2x.png".to_owned(), 2, 2),
465 ("http://example.com/{z}/{x}/{y}{ratio}.png", (1, 2, 3), 2.0, Scheme::Tms, "http://example.com/3/1/5@2x.png".to_owned(), 5, 2),
466 ("http://example.com/{z}/{x}/{y}{ratio}.png", (1, 2, 3), 1.0, Scheme::Xyz, "http://example.com/3/1/2.png".to_owned(), 2, 1),
467 ("http://example.com/{prefix}/{z}/{x}/{y}.mvt", (1, 2, 3), 2.0, Scheme::Xyz, "http://example.com/12/3/1/2.mvt".to_owned(), 2, 1),
468 ("http://example.com/{quadkey}.png", (0, 0, 1), 2.0, Scheme::Xyz, "http://example.com/0.png".to_owned(), 0, 1),
469 ("http://example.com/{quadkey}.png", (0, 0, 2), 2.0, Scheme::Xyz, "http://example.com/00.png".to_owned(), 0, 1),
470 ("http://example.com/{quadkey}.png", (1, 1, 2), 2.0, Scheme::Xyz, "http://example.com/03.png".to_owned(), 1, 1),
471 ("http://example.com/{quadkey}.png", (29, 3, 6), 2.0, Scheme::Xyz, "http://example.com/011123.png".to_owned(), 3, 1),
472 ("http://example.com/{quadkey}.png", (22914, 52870, 17), 2.0, Scheme::Xyz, "http://example.com/02301322130000230.png".to_owned(), 52870, 1),
473 ("http://example.com/?bbox={bbox-epsg-3857}", (0, 0, 1), 2.0, Scheme::Xyz, format!("http://example.com/?bbox={mercator_box}"), 0, 1),
474 ("http://example.com/?bbox={bbox}", (0, 0, 1), 2.0, Scheme::Xyz, format!("http://example.com/?bbox={mercator_box}"), 0, 1),
475 ];
476 for (template, (x, y, z), map_ratio, scheme, url, stored_y, pixel_ratio) in cases {
477 let resource = Resource::tile(template, map_ratio, x, y, z, scheme, TileFormat::Mvt, LoadingMethod::ALL);
478 assert_eq!((Kind::Tile, url.as_str()), (resource.kind, resource.url.as_str()), "{template} {x}/{y}/{z}");
479 let tile = resource.tile_data.as_ref().unwrap();
480 let address = (tile.url_template.as_str(), tile.pixel_ratio, tile.x, tile.y, tile.z);
481 assert_eq!((template, pixel_ratio, x, stored_y, z), address, "{template} {x}/{y}/{z}");
482 }
483 }
484
485 fn identity_tile_url(url: &str, x: i32, y: i32, z: i8, scheme: Scheme) -> String {
488 let tile_matrix_set = TileMatrixSet { origin: [-90.0, 90.0], extent_at_zoom0: 180.0 };
489 let addressing = TileAddressing { scheme, tile_matrix_set };
490 Resource::tile(url, 1.0, x, y, z, addressing, TileFormat::Image, LoadingMethod::ALL).url
491 }
492
493 #[test]
496 fn tile_bbox_in_a_registered_projections_tile_matrix_set() {
497 let t = "http://example.com/?bbox={bbox}";
498 assert_eq!("http://example.com/?bbox=0,0,90,90", identity_tile_url(t, 1, 0, 1, Scheme::Xyz));
499 assert_eq!("http://example.com/?bbox=-90,-90,0,0", identity_tile_url(t, 0, 1, 1, Scheme::Xyz));
500 assert_eq!("http://example.com/?bbox=45,-90,90,-45", identity_tile_url(t, 3, 3, 2, Scheme::Xyz));
501 assert_eq!(
503 "http://example.com/?bbox=-20037508.342789244,0,0,20037508.342789244",
504 identity_tile_url("http://example.com/?bbox={bbox-epsg-3857}", 0, 0, 1, Scheme::Xyz)
505 );
506 }
507
508 #[test]
510 fn tms_flips_only_y_and_bbox_stays_the_box_of_the_tile() {
511 let url = identity_tile_url("http://example.com/{y}?bbox={bbox}", 1, 0, 1, Scheme::Tms);
512 assert_eq!("http://example.com/1?bbox=0,0,90,90", url);
513 }
514
515 #[test]
521 fn a_tiles_bbox_is_its_box_in_the_tile_matrix_set() {
522 let expect_bbox = |tile_matrix_set: TileMatrixSet, (x, y, z), scheme, path: &str, box_: [f64; 4]| {
523 let addressing = TileAddressing { scheme, tile_matrix_set };
524 let template = "http://example.com/{z}/{x}/{y}?bbox={bbox}";
525 let url = Resource::tile(template, 1.0, x, y, z, addressing, TileFormat::Image, LoadingMethod::ALL).url;
526 let prefix = format!("http://example.com/{path}?bbox=");
527 let numbers = url.strip_prefix(&prefix).unwrap_or_else(|| panic!("{url}"));
528 let numbers: Vec<f64> = numbers.split(',').map(|number| number.parse().unwrap()).collect();
529 let extent = tile_matrix_set.extent_at_zoom0;
530 assert_eq!(4, numbers.len(), "{url}");
531 for (expected, actual) in box_.iter().zip(&numbers) {
532 assert_abs_diff_eq!(expected, actual, epsilon = extent * 1e-15);
533 }
534 };
535 let (xyz, tms) = (Scheme::Xyz, Scheme::Tms);
536
537 let mercator = TileMatrixSet::WEB_MERCATOR;
538 expect_bbox(mercator, (0, 0, 1), xyz, "1/0/0", [-20_037_508.342_789_244, 0.0, 0.0, 20_037_508.342_789_244]);
539 let box_ = [-9_783.939_620_502_293, 6_721_566.519_285_258, 0.0, 6_731_350.458_905_76];
540 expect_bbox(mercator, (2047, 1360, 12), xyz, "12/2047/1360", box_);
541 expect_bbox(mercator, (2047, 1360, 12), tms, "12/2047/2735", box_);
542
543 let nztm2000_quad =
545 TileMatrixSet { origin: [-3_260_586.728_4, 10_438_190.165_2], extent_at_zoom0: 10_018_754.171_4 };
546 let box_ = [1_122_618.221_587_5, 4_176_468.808_075_001, 1_748_790.357_299_999_8, 4_802_640.943_787_501];
547 expect_bbox(nztm2000_quad, (7, 9, 4), xyz, "4/7/9", box_);
548 expect_bbox(nztm2000_quad, (7, 9, 4), tms, "4/7/6", box_);
549
550 let identity = TileMatrixSet { origin: [-90.0, 90.0], extent_at_zoom0: 180.0 };
552 let url = |tile_matrix_set, (x, y, z), scheme| {
553 let addressing = TileAddressing { scheme, tile_matrix_set };
554 let template = "http://example.com/{z}/{x}/{y}?bbox={bbox}";
555 Resource::tile(template, 1.0, x, y, z, addressing, TileFormat::Image, LoadingMethod::ALL).url
556 };
557 assert_eq!("http://example.com/1/1/0?bbox=0,0,90,90", url(identity, (1, 0, 1), xyz));
558 assert_eq!("http://example.com/1/1/1?bbox=0,0,90,90", url(identity, (1, 0, 1), tms));
559 let epsg3413 = TileMatrixSet { origin: [-4_194_304.0, 4_194_304.0], extent_at_zoom0: 8_388_608.0 };
560 assert_eq!("http://example.com/4/7/6?bbox=-524288,-1048576,0,-524288", url(epsg3413, (7, 9, 4), tms));
561 }
562
563 #[test]
564 fn a_glyph_url_names_its_percent_encoded_font_stack_and_range() {
565 let template = "http://example.com/{fontstack}/{range}";
566 let resource = Resource::glyphs(template, &vec!["stack".to_owned()], (0, 255));
567 assert_eq!((Kind::Glyphs, "http://example.com/stack/0-255"), (resource.kind, resource.url.as_str()));
568 let resource = Resource::glyphs(template, &vec!["Open Sans".to_owned(), "cø".to_owned()], (0, 255));
569 assert_eq!("http://example.com/Open%20Sans%2cc%c3%b8/0-255", resource.url);
570 }
571
572 #[test]
575 fn a_sprite_url_takes_its_ratio_and_extension_before_the_query() {
576 let cases = [
577 ("http://example.com/sprite", "http://example.com/sprite@2x.png", "http://example.com/sprite@2x.json"),
578 (
579 "http://example.com/sprite?query=true",
580 "http://example.com/sprite@2x.png?query=true",
581 "http://example.com/sprite@2x.json?query=true",
582 ),
583 (
584 "http://example.com/sprite?query=true#fragment",
585 "http://example.com/sprite@2x.png?query=true",
586 "http://example.com/sprite@2x.json?query=true",
587 ),
588 (
589 "http://example.com/sprite#fragment?ignored=true",
590 "http://example.com/sprite@2x.png",
591 "http://example.com/sprite@2x.json",
592 ),
593 ];
594 for (url, image, json) in cases {
595 let resource = Resource::sprite_image(url, 2.0);
596 assert_eq!((Kind::SpriteImage, image), (resource.kind, resource.url.as_str()), "{url}");
597 let resource = Resource::sprite_json(url, 2.0);
598 assert_eq!((Kind::SpriteJSON, json), (resource.kind, resource.url.as_str()), "{url}");
599 }
600 }
601}