1use std::path::{Path, PathBuf};
4use std::sync::atomic::{AtomicU64, Ordering};
5use std::thread::sleep;
6use std::time::Duration;
7
8use geolith::error::{GeolithError, Result};
9use geolith::geometry::mercator::TileCoord;
10use geolith::output::hilbert::tile_to_pmtiles_id;
11use geolith::output::writer::{Compression, PmtilesWriter, TileType};
12use rayon::prelude::*;
13
14use crate::raster::cache::TileCache;
15use crate::raster::fetch::{FetchOutcome, TileFetcher, fetch_with_retry};
16use crate::raster::pyramid::PyramidSpec;
17use crate::raster::template::UrlTemplate;
18
19#[derive(Debug, Clone)]
21pub struct RasterBuildOptions {
22 pub template: UrlTemplate,
24 pub pyramid: PyramidSpec,
26 pub tile_type: TileType,
28 pub concurrency: usize,
30 pub request_delay: Duration,
32 pub attempts: u32,
34 pub cache_dir: PathBuf,
36 pub name: String,
38 pub attribution: Option<String>,
40}
41
42#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct RasterBuildStats {
45 pub downloaded: u64,
47 pub cached: u64,
49 pub missing: u64,
51 pub tiles_written: u64,
53 pub unique_tiles: usize,
55}
56
57pub fn build_raster_archive(
65 fetcher: &dyn TileFetcher,
66 options: &RasterBuildOptions,
67 output: &Path,
68) -> Result<RasterBuildStats> {
69 let cache = TileCache::open(&options.cache_dir)?;
70 let tiles = options.pyramid.tiles();
71
72 let downloaded = AtomicU64::new(0);
73 let cached = AtomicU64::new(0);
74
75 let pool = rayon::ThreadPoolBuilder::new()
76 .num_threads(options.concurrency.max(1))
77 .build()
78 .map_err(|e| GeolithError::RasterSource(format!("download pool: {e}")))?;
79
80 pool.install(|| {
81 tiles.par_iter().try_for_each(|&tile| -> Result<()> {
82 if cache.tile(tile).is_some() || cache.is_missing(tile) {
83 cached.fetch_add(1, Ordering::Relaxed);
84 return Ok(());
85 }
86 let url = options.template.expand(tile);
87 match fetch_with_retry(fetcher, &url, options.attempts)? {
88 FetchOutcome::Tile(bytes) => cache.put(tile, &bytes)?,
89 FetchOutcome::Missing => cache.mark_missing(tile)?,
90 }
91 downloaded.fetch_add(1, Ordering::Relaxed);
92 if !options.request_delay.is_zero() {
93 sleep(options.request_delay);
94 }
95 Ok(())
96 })
97 })?;
98
99 let mut writer = PmtilesWriter::create(
100 output,
101 Compression::None,
102 options.tile_type,
103 options.pyramid.min_zoom,
104 options.pyramid.max_zoom,
105 )?;
106 let bounds = options.pyramid.covered_bounds();
107 writer.set_bounds(bounds.0, bounds.1, bounds.2, bounds.3);
108
109 let mut ordered: Vec<(u64, TileCoord)> = tiles
110 .iter()
111 .map(|&tile| (tile_to_pmtiles_id(tile), tile))
112 .collect();
113 ordered.sort_unstable_by_key(|(id, _)| *id);
114
115 let mut missing = 0_u64;
116 for (tile_id, tile) in &ordered {
117 match cache.tile(*tile) {
118 Some(bytes) => {
119 writer.write_tile(*tile_id, &bytes)?;
120 }
121 None => missing += 1,
122 }
123 }
124
125 let stats = RasterBuildStats {
126 downloaded: downloaded.into_inner(),
127 cached: cached.into_inner(),
128 missing,
129 tiles_written: writer.tiles_written(),
130 unique_tiles: writer.unique_tiles(),
131 };
132
133 let metadata = raster_metadata(options);
134 writer.finalize(serde_json::to_string(&metadata)?.as_bytes())?;
135 Ok(stats)
136}
137
138fn raster_metadata(options: &RasterBuildOptions) -> serde_json::Value {
139 let format = match options.tile_type {
140 TileType::Png => "png",
141 TileType::Webp => "webp",
142 TileType::Avif => "avif",
143 _ => "jpeg",
144 };
145 let mut metadata = serde_json::json!({
146 "name": options.name,
147 "format": format,
148 "type": "baselayer",
149 "minzoom": options.pyramid.min_zoom.to_string(),
150 "maxzoom": options.pyramid.max_zoom.to_string(),
151 });
152 metadata["attribution"] = serde_json::Value::String(geolith::attribution::with_credit(
153 options.attribution.as_deref().unwrap_or_default(),
154 ));
155 if let Some((min_lon, min_lat, max_lon, max_lat)) = options.pyramid.bbox {
156 metadata["geolith:bbox"] =
157 serde_json::Value::String(format!("{min_lon},{min_lat},{max_lon},{max_lat}"));
158 metadata["geolith:bbox_min_zoom"] =
159 serde_json::Value::String(options.pyramid.bbox_min_zoom.to_string());
160 }
161 metadata
162}
163
164#[cfg(test)]
165mod tests {
166 use super::*;
167
168 struct StubFetcher;
169
170 impl TileFetcher for StubFetcher {
171 fn fetch(&self, url: &str) -> Result<FetchOutcome> {
172 if url.contains("/2/") {
173 return Ok(FetchOutcome::Missing);
174 }
175 Ok(FetchOutcome::Tile(format!("payload:{url}").into_bytes()))
176 }
177 }
178
179 fn options(dir: &Path) -> RasterBuildOptions {
180 RasterBuildOptions {
181 template: UrlTemplate::parse("https://t.example/{z}/{x}/{y}.jpg").expect("template"),
182 pyramid: PyramidSpec {
183 min_zoom: 0,
184 max_zoom: 1,
185 bbox: None,
186 bbox_min_zoom: 0,
187 },
188 tile_type: TileType::Jpeg,
189 concurrency: 2,
190 request_delay: Duration::ZERO,
191 attempts: 2,
192 cache_dir: dir.join("cache"),
193 name: "test-raster".into(),
194 attribution: Some("© Test".into()),
195 }
196 }
197
198 #[test]
199 fn downloads_and_packs_the_pyramid() {
200 let dir = tempfile::tempdir().expect("tempdir");
201 let output = dir.path().join("out.pmtiles");
202 let stats =
203 build_raster_archive(&StubFetcher, &options(dir.path()), &output).expect("build");
204 assert_eq!(stats.downloaded, 5);
205 assert_eq!(stats.cached, 0);
206 assert_eq!(stats.missing, 0);
207 assert_eq!(stats.tiles_written, 5);
208 assert!(output.exists());
209 }
210
211 #[test]
212 fn second_run_resumes_entirely_from_cache() {
213 let dir = tempfile::tempdir().expect("tempdir");
214 let opts = options(dir.path());
215 let output = dir.path().join("out.pmtiles");
216 build_raster_archive(&StubFetcher, &opts, &output).expect("first build");
217 let stats = build_raster_archive(&StubFetcher, &opts, &output).expect("second build");
218 assert_eq!(stats.downloaded, 0, "no re-downloads on resume");
219 assert_eq!(stats.cached, 5);
220 assert_eq!(stats.tiles_written, 5);
221 }
222
223 #[test]
224 fn missing_tiles_are_recorded_and_skipped() {
225 let dir = tempfile::tempdir().expect("tempdir");
226 let mut opts = options(dir.path());
227 opts.pyramid.max_zoom = 2;
228 let output = dir.path().join("out.pmtiles");
229 let stats = build_raster_archive(&StubFetcher, &opts, &output).expect("build");
230 assert_eq!(stats.missing, 16, "all z2 tiles are upstream-missing");
231 assert_eq!(stats.tiles_written, 5);
232 let stats2 = build_raster_archive(&StubFetcher, &opts, &output).expect("rebuild");
233 assert_eq!(stats2.cached, 21, "miss markers also resume");
234 assert_eq!(stats2.downloaded, 0);
235 }
236
237 #[test]
238 fn tiles_are_written_in_pmtiles_id_order() {
239 let dir = tempfile::tempdir().expect("tempdir");
240 let output = dir.path().join("out.pmtiles");
241 build_raster_archive(&StubFetcher, &options(dir.path()), &output).expect("build");
242 let bytes = std::fs::read(&output).expect("archive bytes");
243 assert_eq!(&bytes[0..7], b"PMTiles", "valid magic");
244 }
245
246 #[test]
247 fn hybrid_archive_declares_world_bounds_not_just_the_bbox() {
248 let dir = tempfile::tempdir().expect("tempdir");
249 let mut opts = options(dir.path());
250 opts.pyramid = PyramidSpec {
251 min_zoom: 0,
252 max_zoom: 2,
253 bbox: Some((68.0, 6.5, 97.5, 37.2)),
254 bbox_min_zoom: 2,
255 };
256 let output = dir.path().join("hybrid.pmtiles");
257 build_raster_archive(&StubFetcher, &opts, &output).expect("build");
258
259 let (min_lon, min_lat, max_lon, max_lat) = read_bounds(&output);
260 assert!(
261 min_lon <= -179.0 && max_lon >= 179.0,
262 "z0/z1 hold planet tiles, so the archive must not claim bbox-only \
263 coverage: got lon {min_lon}..{max_lon}"
264 );
265 assert!(
266 min_lat < -80.0 && max_lat > 80.0,
267 "lat {min_lat}..{max_lat}"
268 );
269 }
270
271 #[test]
272 fn bbox_only_archive_declares_the_bbox() {
273 let dir = tempfile::tempdir().expect("tempdir");
274 let mut opts = options(dir.path());
275 opts.pyramid = PyramidSpec {
276 min_zoom: 1,
277 max_zoom: 2,
278 bbox: Some((68.0, 6.5, 97.5, 37.2)),
279 bbox_min_zoom: 0,
280 };
281 let output = dir.path().join("bbox-only.pmtiles");
282 build_raster_archive(&StubFetcher, &opts, &output).expect("build");
283
284 let (min_lon, min_lat, max_lon, max_lat) = read_bounds(&output);
285 assert!((min_lon - 68.0).abs() < 0.01, "min_lon {min_lon}");
286 assert!((max_lon - 97.5).abs() < 0.01, "max_lon {max_lon}");
287 assert!((min_lat - 6.5).abs() < 0.01, "min_lat {min_lat}");
288 assert!((max_lat - 37.2).abs() < 0.01, "max_lat {max_lat}");
289 }
290
291 fn read_bounds(path: &Path) -> (f64, f64, f64, f64) {
294 let bytes = std::fs::read(path).expect("archive bytes");
295 let at = |offset: usize| -> f64 {
296 let raw = i32::from_le_bytes(
297 bytes[offset..offset + 4]
298 .try_into()
299 .expect("4 bytes for an E7 field"),
300 );
301 f64::from(raw) / 1e7
302 };
303 (at(102), at(106), at(110), at(114))
304 }
305
306 #[test]
307 fn a_raster_archive_without_attribution_carries_the_credit_alone() {
308 let dir = tempfile::tempdir().expect("tempdir");
309 let mut raster = options(dir.path());
310 raster.attribution = None;
311 assert_eq!(raster_metadata(&raster)["attribution"], "© geolith");
312 }
313
314 #[test]
315 fn metadata_names_format_and_attribution() {
316 let dir = tempfile::tempdir().expect("tempdir");
317 let metadata = raster_metadata(&options(dir.path()));
318 assert_eq!(metadata["format"], "jpeg");
319 assert_eq!(metadata["attribution"], "© Test | © geolith");
320 assert_eq!(metadata["minzoom"], "0");
321 }
322
323 #[test]
324 fn metadata_describes_the_pyramid_shape() {
325 let dir = tempfile::tempdir().expect("tempdir");
326 let mut opts = options(dir.path());
327 opts.pyramid = PyramidSpec {
328 min_zoom: 0,
329 max_zoom: 12,
330 bbox: Some((68.0, 6.5, 97.5, 37.2)),
331 bbox_min_zoom: 9,
332 };
333 let metadata = raster_metadata(&opts);
334
335 assert_eq!(
336 metadata["geolith:bbox"], "68,6.5,97.5,37.2",
337 "consumers cannot tell which zooms are clipped without the bbox"
338 );
339 assert_eq!(metadata["geolith:bbox_min_zoom"], "9");
340 }
341
342 #[test]
343 fn metadata_omits_pyramid_shape_when_unclipped() {
344 let dir = tempfile::tempdir().expect("tempdir");
345 let metadata = raster_metadata(&options(dir.path()));
346 assert!(
347 metadata.get("geolith:bbox").is_none(),
348 "a planet pyramid has no clipped region to describe"
349 );
350 assert!(metadata.get("geolith:bbox_min_zoom").is_none());
351 }
352}