Skip to main content

mln_style/source/
mod.rs

1//! Source types as values.
2//!
3//! A source type is a marker type that implements [`StyleSourceType`]. A
4//! style holds each of its sources as a [`Source`]: its id, the members every
5//! source has ([`SourceCommon`]) and its type's [`SourceData<T>`], shared as
6//! an `Arc<dyn ErasedSource>`. A [`StyleRegistry`](crate::StyleRegistry)
7//! holds the types as `&'static dyn ErasedStyleSourceType`, by name. An
8//! erased value gets back to its type only through [`SourceData::recover`].
9//!
10//! A source's description is what loading its options finds, such as the
11//! tileset of a TileJSON. This crate holds it without knowing its type, as an
12//! [`ErasedDescription`]: the engine's half of the source type says how it
13//! loads, and the map's loader applies what a load finds as an
14//! [`Edit::SetSourceDescription`](crate::Edit).
15
16use std::any::Any;
17use std::marker::PhantomData;
18use std::num::NonZeroU64;
19use std::sync::Arc;
20use std::sync::atomic::{AtomicU64, Ordering};
21use std::time::Duration;
22
23use crate::conversion::{Convertible, Error};
24use crate::expression::Functions;
25use crate::layer::SourceKind;
26use crate::{constants, log_target};
27
28mod convert;
29pub mod dynamic;
30mod list;
31
32pub use convert::convert_source;
33pub use list::SourceList;
34
35/// What the engine needs to know about a source type besides its data. The
36/// name identifies the type: two registries that agree on a name agree on
37/// the type.
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub struct SourceTypeInfo {
40    /// The source type as style JSON names it, or as the API does for a type
41    /// that style JSON can't create.
42    pub name: &'static str,
43    /// The kind of layer that the type's sources feed.
44    pub layer_kind: SourceKind,
45    /// Whether style JSON can create a source of the type.
46    pub from_json: bool,
47}
48
49/// A source's description, of the type its source type's loading half
50/// names, which this crate holds without reading it.
51pub type ErasedDescription = Arc<dyn Any + Send + Sync>;
52
53/// A source type's style half: its name, what its sources hold and how style
54/// JSON describes them.
55pub trait StyleSourceType: Sized + Send + Sync + 'static {
56    const INFO: SourceTypeInfo;
57
58    /// What the style or the API gives: a URL, an inline tileset, GeoJSON
59    /// options, coordinates.
60    type Options: Clone + Send + Sync + 'static;
61
62    /// The data of a source from its style JSON `value`, whose expressions
63    /// parse against `functions`. Only a type whose [`INFO`](Self::INFO)
64    /// has `from_json` is asked.
65    fn from_json(_value: &Convertible<'_>, _functions: &Arc<Functions>, error: &mut Error) -> Option<SourceData<Self>> {
66        error.message = "invalid source type".to_owned();
67        None
68    }
69}
70
71fn warn_if_overscale_factor_caps_prefetch_delta(overscale: Option<u8>, prefetch: Option<u8>) {
72    let prefetch_delta = std::cmp::max(constants::DEFAULT_PREFETCH_ZOOM_DELTA, prefetch.unwrap_or(0));
73    if let Some(overscale) = overscale
74        && overscale < prefetch_delta
75    {
76        tracing::warn!(
77            target: log_target::STYLE,
78            delta = i32::from(overscale),
79            "Parent tile overscale factor caps the prefetch delta"
80        );
81    }
82}
83
84/// The members every source has, which tune how its tiles load.
85#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
86pub struct SourceCommon {
87    /// How many zoom levels below the ideal ones to load tiles of first;
88    /// `None` uses the map's.
89    pub prefetch_zoom_delta: Option<u8>,
90    /// How many zoom levels a parent tile may stand in for its children
91    /// while they load; `None` doesn't limit it.
92    pub max_overscale_factor: Option<u8>,
93    /// How long a tile waits before it reloads after its data expires.
94    pub minimum_tile_update_interval: Duration,
95    /// Whether the source's tiles stay out of the offline cache.
96    pub volatile: bool,
97}
98
99/// The data of a source of the type `T`: its options and what loading them
100/// found.
101pub struct SourceData<T: StyleSourceType> {
102    pub options: T::Options,
103    /// `None` until the source's description loads.
104    pub description: Option<ErasedDescription>,
105    /// Grows with each change to the options or the data that starts a new
106    /// load, and tags that load.
107    pub load: u64,
108}
109
110impl<T: StyleSourceType> Clone for SourceData<T> {
111    fn clone(&self) -> Self {
112        SourceData { options: self.options.clone(), description: self.description.clone(), load: self.load }
113    }
114}
115
116impl<T: StyleSourceType> SourceData<T> {
117    /// A source of `options` whose description hasn't loaded.
118    #[must_use]
119    pub fn new(options: T::Options) -> Self {
120        SourceData { options, description: None, load: 0 }
121    }
122
123    /// A source of `options` with `description`.
124    #[must_use]
125    pub fn with_description(options: T::Options, description: ErasedDescription) -> Self {
126        SourceData { options, description: Some(description), load: 0 }
127    }
128
129    /// `source`'s data as a `T` source's, or `None` for another type's.
130    #[must_use]
131    pub fn recover(source: &Source) -> Option<&Self> {
132        let any: &dyn Any = &*source.data;
133        any.downcast_ref()
134    }
135
136    /// The source's description as a `D`, or `None` until it loads or if
137    /// it's another type.
138    #[must_use]
139    pub fn description<D: Any>(&self) -> Option<&D> {
140        self.description.as_deref()?.downcast_ref()
141    }
142}
143
144/// A source's data, whichever its type.
145pub trait ErasedSource: Any + Send + Sync {
146    fn source_type(&self) -> &'static dyn ErasedStyleSourceType;
147
148    /// [`SourceData::load`].
149    fn load(&self) -> u64;
150
151    /// [`SourceData::description`].
152    fn description(&self) -> Option<&ErasedDescription>;
153
154    /// This data with `description` in place of its description.
155    fn with_description(&self, description: Option<ErasedDescription>) -> Arc<dyn ErasedSource>;
156}
157
158impl<T: StyleSourceType> ErasedSource for SourceData<T> {
159    fn source_type(&self) -> &'static dyn ErasedStyleSourceType {
160        style_source_entry::<T>()
161    }
162
163    fn load(&self) -> u64 {
164        self.load
165    }
166
167    fn description(&self) -> Option<&ErasedDescription> {
168        self.description.as_ref()
169    }
170
171    fn with_description(&self, description: Option<ErasedDescription>) -> Arc<dyn ErasedSource> {
172        Arc::new(SourceData::<T> { options: self.options.clone(), description, load: self.load })
173    }
174}
175
176/// Which source a [`Source`] is, of all the sources made in the process:
177/// the versions of one source share it, and two sources that only share an
178/// id don't.
179#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
180pub struct SourceInstance(NonZeroU64);
181
182impl SourceInstance {
183    fn next() -> Self {
184        static NEXT: AtomicU64 = AtomicU64::new(1);
185        let value = NEXT.fetch_add(1, Ordering::Relaxed);
186        SourceInstance(NonZeroU64::new(value).unwrap_or(NonZeroU64::MIN))
187    }
188}
189
190/// A source of a style version: its id, which instance it is, the members
191/// every source has, and its type's data. A clone shares the data; two
192/// sources are the same when [`Source::ptr_eq`] says so.
193#[derive(Clone)]
194pub struct Source {
195    id: Arc<str>,
196    instance: SourceInstance,
197    common: SourceCommon,
198    data: Arc<dyn ErasedSource>,
199}
200
201impl Source {
202    /// A new source `id` of `data`, with the default common members.
203    #[must_use]
204    pub fn new<T: StyleSourceType>(id: &str, data: SourceData<T>) -> Self {
205        Self::from_erased(id, Arc::new(data))
206    }
207
208    /// A new source `id` of erased `data`, with the default common members.
209    #[must_use]
210    pub fn from_erased(id: &str, data: Arc<dyn ErasedSource>) -> Self {
211        Source { id: Arc::from(id), instance: SourceInstance::next(), common: SourceCommon::default(), data }
212    }
213
214    /// This source with `data` in place of its data.
215    #[must_use]
216    pub fn with_data<T: StyleSourceType>(&self, data: SourceData<T>) -> Self {
217        self.with_erased_data(Arc::new(data))
218    }
219
220    fn with_erased_data(&self, data: Arc<dyn ErasedSource>) -> Self {
221        Source { id: Arc::clone(&self.id), instance: self.instance, common: self.common, data }
222    }
223
224    /// This source with `description` as its description.
225    #[must_use]
226    pub fn with_description(&self, description: Option<ErasedDescription>) -> Self {
227        self.with_erased_data(self.data.with_description(description))
228    }
229
230    /// This source with `common` in place of its common members. Logs a
231    /// warning when its overscale factor caps its prefetch delta.
232    #[must_use]
233    pub fn with_common(&self, common: SourceCommon) -> Self {
234        warn_if_overscale_factor_caps_prefetch_delta(common.max_overscale_factor, common.prefetch_zoom_delta);
235        Source { id: Arc::clone(&self.id), instance: self.instance, common, data: Arc::clone(&self.data) }
236    }
237
238    #[must_use]
239    pub fn id(&self) -> &str {
240        &self.id
241    }
242
243    #[must_use]
244    pub fn instance(&self) -> SourceInstance {
245        self.instance
246    }
247
248    #[must_use]
249    pub fn info(&self) -> SourceTypeInfo {
250        self.data.source_type().info()
251    }
252
253    #[must_use]
254    pub fn source_type(&self) -> &'static dyn ErasedStyleSourceType {
255        self.data.source_type()
256    }
257
258    #[must_use]
259    pub fn common(&self) -> &SourceCommon {
260        &self.common
261    }
262
263    /// The source's type's data.
264    #[must_use]
265    pub fn data(&self) -> &dyn ErasedSource {
266        &*self.data
267    }
268
269    /// Whether `a` and `b` are the same source: the same id, instance and
270    /// common members, and data that's the same allocation.
271    #[must_use]
272    pub fn ptr_eq(a: &Source, b: &Source) -> bool {
273        Arc::ptr_eq(&a.data, &b.data) && a.common == b.common && a.instance == b.instance && a.id == b.id
274    }
275}
276
277// Debug is not a supertrait, for the reason at
278// `impl Debug for dyn ErasedLayerStyle` (layer/type_.rs).
279impl std::fmt::Debug for Source {
280    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
281        f.debug_struct("Source")
282            .field("id", &self.id)
283            .field("instance", &self.instance)
284            .field("type", &self.info().name)
285            .field("common", &self.common)
286            .finish_non_exhaustive()
287    }
288}
289
290/// A source type, whichever it is.
291pub trait ErasedStyleSourceType: Send + Sync + 'static {
292    fn info(&self) -> SourceTypeInfo;
293
294    /// The source `id` of [`StyleSourceType::from_json`]'s data.
295    fn create_from_json(
296        &self,
297        id: &str,
298        value: &Convertible<'_>,
299        functions: &Arc<Functions>,
300        error: &mut Error,
301    ) -> Option<Source>;
302}
303
304/// The [`ErasedStyleSourceType`] of `T`, which [`style_source_entry`]
305/// returns.
306pub struct SourceTypeEntry<T>(PhantomData<fn() -> T>);
307
308impl<T: 'static> SourceTypeEntry<T> {
309    pub const INSTANCE: &'static Self = &SourceTypeEntry(PhantomData);
310}
311
312impl<T: StyleSourceType> ErasedStyleSourceType for SourceTypeEntry<T> {
313    fn info(&self) -> SourceTypeInfo {
314        T::INFO
315    }
316
317    fn create_from_json(
318        &self,
319        id: &str,
320        value: &Convertible<'_>,
321        functions: &Arc<Functions>,
322        error: &mut Error,
323    ) -> Option<Source> {
324        T::from_json(value, functions, error).map(|data| Source::new(id, data))
325    }
326}
327
328/// The source type `T` as a value.
329#[must_use]
330pub const fn style_source_entry<T: StyleSourceType>() -> &'static dyn ErasedStyleSourceType {
331    SourceTypeEntry::<T>::INSTANCE
332}
333
334#[cfg(test)]
335mod tests {
336    use tracing::Level;
337
338    use super::*;
339    use crate::tests::util::LogCapture;
340
341    struct Plain;
342
343    impl StyleSourceType for Plain {
344        const INFO: SourceTypeInfo =
345            SourceTypeInfo { name: "test:plain", layer_kind: SourceKind::Raster, from_json: false };
346        type Options = ();
347    }
348
349    /// A source whose overscale factor is below its prefetch delta, the
350    /// default delta or its own when that is larger, logs that the factor
351    /// caps it.
352    #[test]
353    fn an_overscale_factor_below_the_prefetch_delta_is_logged() {
354        // (max overscale factor, prefetch zoom delta, whether it warns)
355        let cases = [
356            (None, None, false),
357            (Some(3), None, true),
358            (Some(constants::DEFAULT_PREFETCH_ZOOM_DELTA), None, false),
359            (Some(3), Some(2), true),
360            (Some(5), Some(6), true),
361            (Some(6), Some(6), false),
362        ];
363        for (max_overscale_factor, prefetch_zoom_delta, warns) in cases {
364            let log = LogCapture::new();
365            let common = SourceCommon { prefetch_zoom_delta, max_overscale_factor, ..SourceCommon::default() };
366            let _ = Source::new("source", SourceData::<Plain>::new(())).with_common(common);
367            let warning = format!(
368                "Parent tile overscale factor caps the prefetch delta delta={}",
369                max_overscale_factor.unwrap_or_default()
370            );
371            let case = (max_overscale_factor, prefetch_zoom_delta);
372            assert_eq!(usize::from(warns), log.count(Level::WARN, log_target::STYLE, &warning), "{case:?}");
373            assert!(log.unchecked().is_empty(), "{case:?}: {:?}", log.unchecked());
374        }
375    }
376}