use std::str::FromStr;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::Duration;
use mln_style::crs::TileMatrixSet;
use mln_style::string::to_string_double;
use mln_style::tileset::Scheme;
use crate::storage::chrono::Timestamp;
use crate::storage::response::{Caching, Data, Response};
use crate::storage::token::replace_tokens;
use crate::text::font_stack::{FontStack, font_stack_to_string};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum TileTemplateToken {
Z,
X,
Y,
Quadkey,
Bbox,
BboxEpsg3857,
Prefix,
Ratio,
}
impl FromStr for TileTemplateToken {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"z" => Ok(Self::Z),
"x" => Ok(Self::X),
"y" => Ok(Self::Y),
"quadkey" => Ok(Self::Quadkey),
"bbox" => Ok(Self::Bbox),
"bbox-epsg-3857" => Ok(Self::BboxEpsg3857),
"prefix" => Ok(Self::Prefix),
"ratio" => Ok(Self::Ratio),
_ => Err(()),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum Kind {
Unknown = 0,
Style,
Source,
Tile,
Glyphs,
SpriteImage,
SpriteJSON,
Image,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Priority {
#[default]
Regular,
Low,
}
#[derive(Clone, Debug, Default)]
pub struct RequestOrder(Arc<AtomicU32>);
impl RequestOrder {
#[must_use]
pub fn get(&self) -> u32 {
self.0.load(Ordering::Relaxed)
}
pub(crate) fn set(&self, order: u32) {
self.0.store(order, Ordering::Relaxed);
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Usage {
#[default]
Online,
Offline,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StoragePolicy {
#[default]
Permanent,
Volatile,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TileData {
pub url_template: String,
pub(crate) pixel_ratio: u8,
pub x: i32,
pub y: i32,
pub z: i8,
pub format: TileFormat,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TileFormat {
Mvt,
Mlt,
Image,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct LoadingMethod(pub u8);
impl LoadingMethod {
#[cfg(test)]
pub(crate) const NONE: LoadingMethod = LoadingMethod(0b00);
pub const CACHE: LoadingMethod = LoadingMethod(0b01);
pub const NETWORK: LoadingMethod = LoadingMethod(0b10);
pub const ALL: LoadingMethod = LoadingMethod(0b01 | 0b10);
}
#[derive(Clone, Debug)]
pub struct Resource {
pub kind: Kind,
pub loading_method: LoadingMethod,
pub usage: Usage,
pub priority: Priority,
pub order: RequestOrder,
pub url: String,
pub tile_data: Option<TileData>,
pub data_range: Option<(u64, u64)>,
pub prior_modified: Option<Timestamp>,
pub prior_etag: Option<String>,
pub prior_caching: Caching,
pub prior_data: Option<Data>,
pub minimum_update_interval: Duration,
pub storage_policy: StoragePolicy,
}
fn quad_key(x: i32, y: i32, z: i8) -> String {
let mut quad_key = String::with_capacity(z.max(0) as usize);
let mut i = z;
while i > 0 {
let mask: i32 = 1 << (i - 1);
quad_key.push((b'0' + u8::from(x & mask != 0) + (if y & mask != 0 { 2 } else { 0 })) as char);
i -= 1;
}
quad_key
}
fn tile_bbox_in(tile_matrix_set: &TileMatrixSet, x: i32, y: i32, z: i8) -> String {
let tiles = 2f64.powi(i32::from(z));
let tile_extent = tile_matrix_set.extent_at_zoom0 / tiles;
let [grid_min_x, grid_max_y] = tile_matrix_set.origin;
let grid_min_y = grid_max_y - tile_matrix_set.extent_at_zoom0;
let row_from_bottom = tiles - f64::from(y) - 1.0;
[
grid_min_x + f64::from(x) * tile_extent,
grid_min_y + row_from_bottom * tile_extent,
grid_min_x + (f64::from(x) + 1.0) * tile_extent,
grid_min_y + (row_from_bottom + 1.0) * tile_extent,
]
.map(to_string_double)
.join(",")
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TileAddressing {
pub scheme: Scheme,
pub tile_matrix_set: TileMatrixSet,
}
impl From<Scheme> for TileAddressing {
fn from(scheme: Scheme) -> Self {
TileAddressing { scheme, tile_matrix_set: TileMatrixSet::WEB_MERCATOR }
}
}
fn sprite_url(base: &str, pixel_ratio: f32, extension: &str) -> String {
let fragment = base.find('#').unwrap_or(base.len());
let query = base.find('?').filter(|&query| query < fragment);
let path_end = query.unwrap_or(fragment);
let suffix = if pixel_ratio > 1.0 { "@2x" } else { "" };
format!("{}{suffix}{extension}{}", &base[..path_end], query.map_or("", |query| &base[query..fragment]))
}
fn encode_font_stack(font_stack: &FontStack) -> String {
let hex = b"0123456789abcdef";
let mut encoded = String::new();
for byte in font_stack_to_string(font_stack).bytes() {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
encoded.push(byte as char);
} else {
encoded.push('%');
encoded.push(hex[(byte >> 4) as usize] as char);
encoded.push(hex[(byte & 0x0f) as usize] as char);
}
}
encoded
}
impl Resource {
pub(crate) fn new(kind: Kind, url: impl Into<String>) -> Self {
Self::with_tile_data(kind, url, None, LoadingMethod::ALL)
}
pub(crate) fn with_tile_data(
kind: Kind,
url: impl Into<String>,
tile_data: Option<TileData>,
loading_method: LoadingMethod,
) -> Self {
Resource {
kind,
loading_method,
usage: Usage::Online,
priority: Priority::Regular,
order: RequestOrder::default(),
url: url.into(),
tile_data,
data_range: None,
prior_modified: None,
prior_etag: None,
prior_caching: Caching::default(),
prior_data: None,
minimum_update_interval: Duration::ZERO,
storage_policy: StoragePolicy::Permanent,
}
}
pub fn set_prior(&mut self, response: &Response) {
self.prior_data = None;
self.prior_modified = response.modified;
self.prior_etag.clone_from(&response.etag);
self.prior_caching = response.caching;
}
#[must_use]
pub fn deliver(&self, mut response: Response) -> Response {
if !response.not_modified {
return response;
}
response.modified = response.modified.or(self.prior_modified);
if response.etag.is_none() {
response.etag.clone_from(&self.prior_etag);
}
if let Some(data) = &self.prior_data {
response.data = Some(Arc::clone(data));
response.not_modified = false;
response.prior = true;
}
response
}
#[cfg(any(test, feature = "sqlite"))]
pub(crate) fn set_priority(&mut self, p: Priority) {
self.priority = p;
}
#[cfg(feature = "sqlite")]
pub(crate) fn set_usage(&mut self, u: Usage) {
self.usage = u;
}
#[must_use]
pub fn has_loading_method(&self, method: LoadingMethod) -> bool {
(self.loading_method.0 & method.0) != 0
}
#[must_use]
pub fn style(url: &str) -> Resource {
Resource::new(Kind::Style, url)
}
#[must_use]
pub fn source(url: &str) -> Resource {
Resource::new(Kind::Source, url)
}
#[must_use]
pub fn image(url: &str) -> Resource {
Resource::new(Kind::Image, url)
}
#[must_use]
pub fn sprite_image(base: &str, pixel_ratio: f32) -> Resource {
Resource::new(Kind::SpriteImage, sprite_url(base, pixel_ratio, ".png"))
}
#[must_use]
pub fn sprite_json(base: &str, pixel_ratio: f32) -> Resource {
Resource::new(Kind::SpriteJSON, sprite_url(base, pixel_ratio, ".json"))
}
#[must_use]
pub fn glyphs(url_template: &str, font_stack: &FontStack, glyph_range: (u16, u16)) -> Resource {
Resource::new(
Kind::Glyphs,
replace_tokens(url_template, |token: &str| -> Option<String> {
if token == "fontstack" {
Some(encode_font_stack(font_stack))
} else if token == "range" {
Some(format!("{}-{}", glyph_range.0, glyph_range.1))
} else {
None
}
}),
)
}
#[must_use]
pub(crate) fn font_face(url: &str) -> Resource {
Resource::new(Kind::Glyphs, url)
}
#[must_use]
#[expect(
clippy::too_many_arguments,
reason = "the tileset's template, the tile and its tileset's addressing and format"
)]
pub fn tile(
url_template: &str,
pixel_ratio: f32,
x: i32,
y: i32,
z: i8,
addressing: impl Into<TileAddressing>,
format: TileFormat,
loading_method: LoadingMethod,
) -> Resource {
let TileAddressing { scheme, tile_matrix_set } = addressing.into();
let supports_ratio = url_template.contains("{ratio}");
let row = y;
let mut y = y;
if scheme == Scheme::Tms {
y = (1i32 << z).wrapping_sub(y).wrapping_sub(1);
}
let hex = b"0123456789abcdef";
let url = replace_tokens(url_template, |token: &str| -> Option<String> {
token.parse::<TileTemplateToken>().ok().map(|token| match token {
TileTemplateToken::Z => z.to_string(),
TileTemplateToken::X => x.to_string(),
TileTemplateToken::Y => y.to_string(),
TileTemplateToken::Quadkey => quad_key(x, y, z),
TileTemplateToken::Bbox => tile_bbox_in(&tile_matrix_set, x, row, z),
TileTemplateToken::BboxEpsg3857 => tile_bbox_in(&TileMatrixSet::WEB_MERCATOR, x, row, z),
TileTemplateToken::Prefix => {
[hex[x.rem_euclid(16) as usize] as char, hex[y.rem_euclid(16) as usize] as char].iter().collect()
}
TileTemplateToken::Ratio => {
if pixel_ratio > 1.0 {
"@2x".to_owned()
} else {
String::new()
}
}
})
});
Resource::with_tile_data(
Kind::Tile,
url,
Some(TileData {
url_template: url_template.to_owned(),
pixel_ratio: if supports_ratio && pixel_ratio > 1.0 { 2 } else { 1 },
x,
y,
z,
format,
}),
loading_method,
)
}
}
#[cfg(test)]
mod tests {
use approx::assert_abs_diff_eq;
use super::*;
mod deliver {
use super::super::*;
fn at(secs: i64) -> Timestamp {
Timestamp::from_secs(1000 + secs)
}
fn waiting(caching: Caching) -> Resource {
let mut resource = Resource::style("https://example.com/style.json");
resource.prior_data = Some(Arc::new(b"cached".to_vec()));
resource.prior_etag = Some("a".to_owned());
resource.prior_caching = caching;
resource
}
#[test]
fn a_304_delivers_the_copy_with_its_caching_rules() {
let resource = waiting(Caching { expires: Some(at(-10)), ..Caching::default() });
let renewed = Response {
not_modified: true,
caching: Caching { expires: Some(at(100)), ..Caching::default() },
..Response::default()
};
let delivered = resource.deliver(renewed);
assert!(!delivered.not_modified);
assert_eq!(Some(b"cached".as_slice()), delivered.data.as_deref().map(Vec::as_slice));
assert_eq!((Some(at(100)), Some("a")), (delivered.caching.expires, delivered.etag.as_deref()));
}
}
#[test]
fn a_tile_url_fills_in_its_template() {
let mercator_box = "-20037508.342789244,0,0,20037508.342789244";
#[rustfmt::skip]
let cases = [
("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),
("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),
("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),
("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),
("http://example.com/{quadkey}.png", (0, 0, 1), 2.0, Scheme::Xyz, "http://example.com/0.png".to_owned(), 0, 1),
("http://example.com/{quadkey}.png", (0, 0, 2), 2.0, Scheme::Xyz, "http://example.com/00.png".to_owned(), 0, 1),
("http://example.com/{quadkey}.png", (1, 1, 2), 2.0, Scheme::Xyz, "http://example.com/03.png".to_owned(), 1, 1),
("http://example.com/{quadkey}.png", (29, 3, 6), 2.0, Scheme::Xyz, "http://example.com/011123.png".to_owned(), 3, 1),
("http://example.com/{quadkey}.png", (22914, 52870, 17), 2.0, Scheme::Xyz, "http://example.com/02301322130000230.png".to_owned(), 52870, 1),
("http://example.com/?bbox={bbox-epsg-3857}", (0, 0, 1), 2.0, Scheme::Xyz, format!("http://example.com/?bbox={mercator_box}"), 0, 1),
("http://example.com/?bbox={bbox}", (0, 0, 1), 2.0, Scheme::Xyz, format!("http://example.com/?bbox={mercator_box}"), 0, 1),
];
for (template, (x, y, z), map_ratio, scheme, url, stored_y, pixel_ratio) in cases {
let resource = Resource::tile(template, map_ratio, x, y, z, scheme, TileFormat::Mvt, LoadingMethod::ALL);
assert_eq!((Kind::Tile, url.as_str()), (resource.kind, resource.url.as_str()), "{template} {x}/{y}/{z}");
let tile = resource.tile_data.as_ref().unwrap();
let address = (tile.url_template.as_str(), tile.pixel_ratio, tile.x, tile.y, tile.z);
assert_eq!((template, pixel_ratio, x, stored_y, z), address, "{template} {x}/{y}/{z}");
}
}
fn identity_tile_url(url: &str, x: i32, y: i32, z: i8, scheme: Scheme) -> String {
let tile_matrix_set = TileMatrixSet { origin: [-90.0, 90.0], extent_at_zoom0: 180.0 };
let addressing = TileAddressing { scheme, tile_matrix_set };
Resource::tile(url, 1.0, x, y, z, addressing, TileFormat::Image, LoadingMethod::ALL).url
}
#[test]
fn tile_bbox_in_a_registered_projections_tile_matrix_set() {
let t = "http://example.com/?bbox={bbox}";
assert_eq!("http://example.com/?bbox=0,0,90,90", identity_tile_url(t, 1, 0, 1, Scheme::Xyz));
assert_eq!("http://example.com/?bbox=-90,-90,0,0", identity_tile_url(t, 0, 1, 1, Scheme::Xyz));
assert_eq!("http://example.com/?bbox=45,-90,90,-45", identity_tile_url(t, 3, 3, 2, Scheme::Xyz));
assert_eq!(
"http://example.com/?bbox=-20037508.342789244,0,0,20037508.342789244",
identity_tile_url("http://example.com/?bbox={bbox-epsg-3857}", 0, 0, 1, Scheme::Xyz)
);
}
#[test]
fn tms_flips_only_y_and_bbox_stays_the_box_of_the_tile() {
let url = identity_tile_url("http://example.com/{y}?bbox={bbox}", 1, 0, 1, Scheme::Tms);
assert_eq!("http://example.com/1?bbox=0,0,90,90", url);
}
#[test]
fn a_tiles_bbox_is_its_box_in_the_tile_matrix_set() {
let expect_bbox = |tile_matrix_set: TileMatrixSet, (x, y, z), scheme, path: &str, box_: [f64; 4]| {
let addressing = TileAddressing { scheme, tile_matrix_set };
let template = "http://example.com/{z}/{x}/{y}?bbox={bbox}";
let url = Resource::tile(template, 1.0, x, y, z, addressing, TileFormat::Image, LoadingMethod::ALL).url;
let prefix = format!("http://example.com/{path}?bbox=");
let numbers = url.strip_prefix(&prefix).unwrap_or_else(|| panic!("{url}"));
let numbers: Vec<f64> = numbers.split(',').map(|number| number.parse().unwrap()).collect();
let extent = tile_matrix_set.extent_at_zoom0;
assert_eq!(4, numbers.len(), "{url}");
for (expected, actual) in box_.iter().zip(&numbers) {
assert_abs_diff_eq!(expected, actual, epsilon = extent * 1e-15);
}
};
let (xyz, tms) = (Scheme::Xyz, Scheme::Tms);
let mercator = TileMatrixSet::WEB_MERCATOR;
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]);
let box_ = [-9_783.939_620_502_293, 6_721_566.519_285_258, 0.0, 6_731_350.458_905_76];
expect_bbox(mercator, (2047, 1360, 12), xyz, "12/2047/1360", box_);
expect_bbox(mercator, (2047, 1360, 12), tms, "12/2047/2735", box_);
let nztm2000_quad =
TileMatrixSet { origin: [-3_260_586.728_4, 10_438_190.165_2], extent_at_zoom0: 10_018_754.171_4 };
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];
expect_bbox(nztm2000_quad, (7, 9, 4), xyz, "4/7/9", box_);
expect_bbox(nztm2000_quad, (7, 9, 4), tms, "4/7/6", box_);
let identity = TileMatrixSet { origin: [-90.0, 90.0], extent_at_zoom0: 180.0 };
let url = |tile_matrix_set, (x, y, z), scheme| {
let addressing = TileAddressing { scheme, tile_matrix_set };
let template = "http://example.com/{z}/{x}/{y}?bbox={bbox}";
Resource::tile(template, 1.0, x, y, z, addressing, TileFormat::Image, LoadingMethod::ALL).url
};
assert_eq!("http://example.com/1/1/0?bbox=0,0,90,90", url(identity, (1, 0, 1), xyz));
assert_eq!("http://example.com/1/1/1?bbox=0,0,90,90", url(identity, (1, 0, 1), tms));
let epsg3413 = TileMatrixSet { origin: [-4_194_304.0, 4_194_304.0], extent_at_zoom0: 8_388_608.0 };
assert_eq!("http://example.com/4/7/6?bbox=-524288,-1048576,0,-524288", url(epsg3413, (7, 9, 4), tms));
}
#[test]
fn a_glyph_url_names_its_percent_encoded_font_stack_and_range() {
let template = "http://example.com/{fontstack}/{range}";
let resource = Resource::glyphs(template, &vec!["stack".to_owned()], (0, 255));
assert_eq!((Kind::Glyphs, "http://example.com/stack/0-255"), (resource.kind, resource.url.as_str()));
let resource = Resource::glyphs(template, &vec!["Open Sans".to_owned(), "cø".to_owned()], (0, 255));
assert_eq!("http://example.com/Open%20Sans%2cc%c3%b8/0-255", resource.url);
}
#[test]
fn a_sprite_url_takes_its_ratio_and_extension_before_the_query() {
let cases = [
("http://example.com/sprite", "http://example.com/sprite@2x.png", "http://example.com/sprite@2x.json"),
(
"http://example.com/sprite?query=true",
"http://example.com/sprite@2x.png?query=true",
"http://example.com/sprite@2x.json?query=true",
),
(
"http://example.com/sprite?query=true#fragment",
"http://example.com/sprite@2x.png?query=true",
"http://example.com/sprite@2x.json?query=true",
),
(
"http://example.com/sprite#fragment?ignored=true",
"http://example.com/sprite@2x.png",
"http://example.com/sprite@2x.json",
),
];
for (url, image, json) in cases {
let resource = Resource::sprite_image(url, 2.0);
assert_eq!((Kind::SpriteImage, image), (resource.kind, resource.url.as_str()), "{url}");
let resource = Resource::sprite_json(url, 2.0);
assert_eq!((Kind::SpriteJSON, json), (resource.kind, resource.url.as_str()), "{url}");
}
}
}