1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub struct SourceTypeInfo {
40 pub name: &'static str,
43 pub layer_kind: SourceKind,
45 pub from_json: bool,
47}
48
49pub type ErasedDescription = Arc<dyn Any + Send + Sync>;
52
53pub trait StyleSourceType: Sized + Send + Sync + 'static {
56 const INFO: SourceTypeInfo;
57
58 type Options: Clone + Send + Sync + 'static;
61
62 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
86pub struct SourceCommon {
87 pub prefetch_zoom_delta: Option<u8>,
90 pub max_overscale_factor: Option<u8>,
93 pub minimum_tile_update_interval: Duration,
95 pub volatile: bool,
97}
98
99pub struct SourceData<T: StyleSourceType> {
102 pub options: T::Options,
103 pub description: Option<ErasedDescription>,
105 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 #[must_use]
119 pub fn new(options: T::Options) -> Self {
120 SourceData { options, description: None, load: 0 }
121 }
122
123 #[must_use]
125 pub fn with_description(options: T::Options, description: ErasedDescription) -> Self {
126 SourceData { options, description: Some(description), load: 0 }
127 }
128
129 #[must_use]
131 pub fn recover(source: &Source) -> Option<&Self> {
132 let any: &dyn Any = &*source.data;
133 any.downcast_ref()
134 }
135
136 #[must_use]
139 pub fn description<D: Any>(&self) -> Option<&D> {
140 self.description.as_deref()?.downcast_ref()
141 }
142}
143
144pub trait ErasedSource: Any + Send + Sync {
146 fn source_type(&self) -> &'static dyn ErasedStyleSourceType;
147
148 fn load(&self) -> u64;
150
151 fn description(&self) -> Option<&ErasedDescription>;
153
154 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#[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#[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 #[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 #[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 #[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 #[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 #[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 #[must_use]
265 pub fn data(&self) -> &dyn ErasedSource {
266 &*self.data
267 }
268
269 #[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
277impl 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
290pub trait ErasedStyleSourceType: Send + Sync + 'static {
292 fn info(&self) -> SourceTypeInfo;
293
294 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
304pub 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#[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 #[test]
353 fn an_overscale_factor_below_the_prefetch_delta_is_logged() {
354 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}