Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / map / src / main / rust / tests / real_archive.rs
real_archive.rs564 lines · 24.7 KiBRaw
| 1 | //! The renderer's reader against a REAL planet archive (`planet4.mamaps` / `planet5.mamaps`, or the |
| 2 | //! byte-identical local build `scripts/maps/inputs/world.mamaps`). |
| 3 | //! |
| 4 | //! By default these tests run against a small SYNTHETIC archive built |
| 5 | //! in-test (see `fixture.rs`): the same reader paths, without the |
| 6 | //! 80 GB input. Set the env var to run them against the planet instead: |
| 7 | //! |
| 8 | //! ```text |
| 9 | //! MAMAPS_REAL_ARCHIVE=/path/to/world.mamaps \ |
| 10 | //! cargo test -p map_renderer --test real_archive -- --nocapture --test-threads=1 |
| 11 | //! ``` |
| 12 | //! |
| 13 | //! Everything goes through the code the app runs: `FileRangeReader` (the device's |
| 14 | //! `TileSource.LocalFile` path), tilecodec's `MamapsArchive` (the shared decoder the |
| 15 | //! writer tools also use), the app's style table, `geometry::build_toggled` (the worker's |
| 16 | //! tessellation entry point) and `source::discover` (overlay segments beside the base). |
| 17 | //! Graph/transit (the `offlinerouter` crate) and POI (Kotlin) have their own real-archive |
| 18 | //! tests; here the section directory is checked so every kind they read is present. |
| 19 | |
| 20 | use std::collections::BTreeMap; |
| 21 | use std::path::{Path, PathBuf}; |
| 22 | use std::sync::Arc; |
| 23 | |
| 24 | use map_renderer::style::{self, KindFilter, LayerToggles}; |
| 25 | use map_renderer::tile::geometry; |
| 26 | use map_renderer::tile::source::{discover, FileRangeReader}; |
| 27 | use tilecodec::mamaps::archive::{self as sidecar, ArchiveView}; |
| 28 | use tilecodec::mamaps::body::Body; |
| 29 | use tilecodec::mamaps::header::Header; |
| 30 | use tilecodec::mamaps::read::{LeafCache, MamapsArchive, TileSource}; |
| 31 | |
| 32 | #[path = "real_archive/fixture.rs"] |
| 33 | mod fixture; |
| 34 | |
| 35 | // planet4 claims FLAG_RINGS_VALIDATED without earning it; the renderer must keep repairing. |
| 36 | const _: () = assert!(!geometry::TRUST_RINGS_VALIDATED); |
| 37 | |
| 38 | /// Cities the task names, plus a mountain for the DEM. |
| 39 | const CITIES: &[(&str, f64, f64)] = &[ |
| 40 | ("SF", 37.7749, -122.4194), |
| 41 | ("NYC", 40.7580, -73.9855), |
| 42 | ("London", 51.5074, -0.1278), |
| 43 | ("Tokyo", 35.6812, 139.7671), |
| 44 | ]; |
| 45 | const ZOOMS: &[u8] = &[0, 4, 8, 10, 12, 13, 14]; |
| 46 | |
| 47 | fn acquire(tag: &str, build: impl FnOnce(&Path)) -> (PathBuf, bool) { |
| 48 | fixture::acquire(tag, build) |
| 49 | } |
| 50 | |
| 51 | fn tile_of(lat: f64, lon: f64, z: u8) -> (u32, u32) { |
| 52 | fixture::tile_of(lat, lon, z) |
| 53 | } |
| 54 | |
| 55 | fn open(path: &Path) -> MamapsArchive<FileRangeReader> { |
| 56 | MamapsArchive::open_with_cache( |
| 57 | FileRangeReader::open(path).expect("FileRangeReader::open"), |
| 58 | Arc::new(LeafCache::new()), |
| 59 | ) |
| 60 | .expect("the app's reader refused the archive") |
| 61 | } |
| 62 | |
| 63 | fn all_on() -> LayerToggles { |
| 64 | LayerToggles { poi: true, transit: true, traffic: true, safety: true } |
| 65 | } |
| 66 | |
| 67 | fn layer_name(id: u8) -> &'static str { |
| 68 | tilecodec::mamaps::dict::LAYERS.get(id as usize).copied().unwrap_or("?") |
| 69 | } |
| 70 | |
| 71 | #[test] |
| 72 | fn header_version_and_dictionary_are_accepted() { |
| 73 | let (path, planet) = acquire("header", |p| { |
| 74 | fixture::write_archive(p, &[(0, 0, 0, fixture::rich_body(120))]); |
| 75 | }); |
| 76 | let mut head = vec![0u8; tilecodec::mamaps::header::HEADER_LEN]; |
| 77 | { |
| 78 | use std::io::Read as _; |
| 79 | std::fs::File::open(&path).unwrap().read_exact(&mut head).unwrap(); |
| 80 | } |
| 81 | let header = Header::parse(&head).expect("header parse (version gate)"); |
| 82 | println!( |
| 83 | "header: version byte {} flags {:#06x} compression {} layers {} z{}-{} build {:#018x} len {}", |
| 84 | head[7], header.flags, header.compression, header.layer_count, header.min_zoom, |
| 85 | header.max_zoom, header.build_id, header.file_len |
| 86 | ); |
| 87 | if planet { |
| 88 | // planet4 is a v9 archive; planet5 a v10 one (dictionary-zstd bodies). Both must open. |
| 89 | match head[7] { |
| 90 | tilecodec::mamaps::header::FORMAT_VERSION_V9 => {} |
| 91 | tilecodec::mamaps::header::FORMAT_VERSION_HEADER_V10 |
| 92 | | tilecodec::mamaps::header::FORMAT_VERSION_HEADER_V11 => { |
| 93 | assert_eq!(header.compression, tilecodec::mamaps::header::COMPRESSION_ZSTD_DICT); |
| 94 | } |
| 95 | v => panic!("planet4 is v9 and planet5 v10/v11 (superblocks), got v{v}"), |
| 96 | } |
| 97 | } else { |
| 98 | // The synthetic writer's header must sit in the reader's accepted set. |
| 99 | match head[7] { |
| 100 | tilecodec::mamaps::header::FORMAT_VERSION |
| 101 | | tilecodec::mamaps::header::FORMAT_VERSION_V9 |
| 102 | | tilecodec::mamaps::header::FORMAT_VERSION_HEADER_V10 |
| 103 | | tilecodec::mamaps::header::FORMAT_VERSION_HEADER_V11 => {} |
| 104 | v => panic!("synthetic archive carries a version the reader refuses, got v{v}"), |
| 105 | } |
| 106 | assert_eq!(header.build_id, fixture::BUILD_ID); |
| 107 | } |
| 108 | assert_eq!(header.file_len, std::fs::metadata(&path).unwrap().len()); |
| 109 | assert!(header.compressed() && header.rings_validated() && header.leaves_compressed()); |
| 110 | // The header claims validated rings, but the renderer does not trust it (see |
| 111 | // geometry::TRUST_RINGS_VALIDATED, pinned off below); this test runs the same policy. |
| 112 | assert_eq!(header.min_zoom, 0); |
| 113 | assert_eq!(header.max_zoom, 14); |
| 114 | |
| 115 | let archive = open(&path); |
| 116 | // `MamapsArchive::open` already validated the dictionary against the compiled-in |
| 117 | // schema; pin the layer list the style is written against. |
| 118 | assert_eq!( |
| 119 | archive.dictionary.layers, |
| 120 | [ |
| 121 | "landtype", |
| 122 | "roads", |
| 123 | "boundaries", |
| 124 | "buildings", |
| 125 | "places", |
| 126 | "poi", |
| 127 | "transit", |
| 128 | "traffic", |
| 129 | "junction", |
| 130 | "safety", |
| 131 | ] |
| 132 | ); |
| 133 | assert_eq!(header.layer_count as usize, archive.dictionary.layers.len()); |
| 134 | println!( |
| 135 | "dictionary: {} layers, {} kinds, {} details", |
| 136 | archive.dictionary.layers.len(), |
| 137 | archive.dictionary.kinds.len(), |
| 138 | archive.dictionary.details.len() |
| 139 | ); |
| 140 | } |
| 141 | |
| 142 | #[test] |
| 143 | fn section_directory_carries_every_kind_the_app_reads() { |
| 144 | let (path, _planet) = acquire("sections", |p| { |
| 145 | fixture::write_archive(p, &[(0, 0, 0, fixture::rich_body(120))]); |
| 146 | fixture::append_sidecar(p); |
| 147 | }); |
| 148 | let file = std::fs::File::open(&path).unwrap(); |
| 149 | // SAFETY: read-only mapping of a file nobody writes while the test runs. |
| 150 | let bytes = unsafe { memmap2::Mmap::map(&file) }.expect("mmap"); |
| 151 | let header = Header::parse(&bytes[..tilecodec::mamaps::header::HEADER_LEN]).unwrap(); |
| 152 | let view = ArchiveView::parse(&bytes, &header).expect("ArchiveView::parse (container checks)"); |
| 153 | let required = [ |
| 154 | (sidecar::ARCHIVE_KIND_GRAPH_META, "graph meta"), |
| 155 | (sidecar::ARCHIVE_KIND_GRAPH_NODES, "graph nodes"), |
| 156 | (sidecar::ARCHIVE_KIND_GRAPH_EDGES, "graph edges"), |
| 157 | (sidecar::ARCHIVE_KIND_GRAPH_INTERMEDIATE, "graph intermediate"), |
| 158 | (sidecar::ARCHIVE_KIND_GRAPH_NAMES, "road names"), |
| 159 | (sidecar::ARCHIVE_KIND_GRAPH_LANES, "lanes"), |
| 160 | (sidecar::ARCHIVE_KIND_POI_INDEX, "poi index"), |
| 161 | (sidecar::ARCHIVE_KIND_POI_NAMES, "poi names"), |
| 162 | (sidecar::ARCHIVE_KIND_POI_ATTRS, "poi attrs"), |
| 163 | (sidecar::ARCHIVE_KIND_POI_SPATIAL, "poi spatial"), |
| 164 | (sidecar::ARCHIVE_KIND_POI_WORDS, "poi words"), |
| 165 | (sidecar::ARCHIVE_KIND_TRANSIT, "transit"), |
| 166 | (sidecar::ARCHIVE_KIND_GRAPH_OVERLAY, "highway overlay"), |
| 167 | (sidecar::ARCHIVE_KIND_POI_REGION, "poi region"), |
| 168 | ]; |
| 169 | for (kind, name) in required { |
| 170 | let (off, len) = |
| 171 | view.location(kind).unwrap_or_else(|| panic!("kind {kind} ({name}) missing")); |
| 172 | let s = view.section(&bytes, kind).unwrap(); |
| 173 | println!("kind {kind:2} {name:<18} @{off} len {len} magic {:02x?}", &s[..4.min(s.len())]); |
| 174 | } |
| 175 | // Optional, and absent from planet4 (road_graph ran without --dem): the router reads |
| 176 | // a missing elevation section as "no profile". |
| 177 | println!( |
| 178 | "kind 7 elevation present: {}", |
| 179 | view.location(sidecar::ARCHIVE_KIND_GRAPH_ELEVATION).is_some() |
| 180 | ); |
| 181 | } |
| 182 | |
| 183 | #[derive(Default)] |
| 184 | struct LayerTally { |
| 185 | tiles: usize, |
| 186 | features: usize, |
| 187 | } |
| 188 | |
| 189 | #[test] |
| 190 | fn every_layer_decodes_and_tessellates_in_four_cities() { |
| 191 | let (path, planet) = acquire("cities", |p| { |
| 192 | let mut tiles = Vec::new(); |
| 193 | for &(_, lat, lon) in CITIES { |
| 194 | for &z in ZOOMS { |
| 195 | let (x, y) = tile_of(lat, lon, z); |
| 196 | tiles.push((z, x, y, fixture::rich_body(120))); |
| 197 | } |
| 198 | } |
| 199 | fixture::write_archive(p, &tiles); |
| 200 | }); |
| 201 | let archive = open(&path); |
| 202 | let layers = style::layers(); |
| 203 | let rings_validated = archive.header.rings_validated() && geometry::TRUST_RINGS_VALIDATED; |
| 204 | let mut tally: BTreeMap<&'static str, LayerTally> = BTreeMap::new(); |
| 205 | let mut versions: BTreeMap<u8, usize> = BTreeMap::new(); |
| 206 | let ( |
| 207 | mut tiles, |
| 208 | mut meshes, |
| 209 | mut labels, |
| 210 | mut buildings, |
| 211 | mut carriageways, |
| 212 | mut traffic, |
| 213 | mut regions, |
| 214 | ) = (0, 0, 0, 0, 0, 0, 0); |
| 215 | let mut extra: BTreeMap<&'static str, usize> = BTreeMap::new(); |
| 216 | for &(city, lat, lon) in CITIES { |
| 217 | for &z in ZOOMS { |
| 218 | let (x, y) = tile_of(lat, lon, z); |
| 219 | let raw = archive.tile_bytes(z, x, y).expect("tile_bytes"); |
| 220 | let body: Body = archive |
| 221 | .tile(z, x, y) |
| 222 | .unwrap_or_else(|e| panic!("{city} {z}/{x}/{y}: decode failed: {e}")) |
| 223 | .unwrap_or_else(|| panic!("{city} {z}/{x}/{y}: absent")); |
| 224 | // Byte 3 of the stored body header is the body version (v10 = narrowed records). |
| 225 | if let Some(raw) = raw { |
| 226 | *versions.entry(raw[3]).or_default() += 1; |
| 227 | } |
| 228 | tiles += 1; |
| 229 | let mut line = format!("{city:<6} {z:2}/{x}/{y}:"); |
| 230 | for layer in &body.layers { |
| 231 | let t = tally.entry(layer_name(layer.layer_id)).or_default(); |
| 232 | t.tiles += 1; |
| 233 | t.features += layer.features.len(); |
| 234 | line += &format!(" {}={}", layer_name(layer.layer_id), layer.features.len()); |
| 235 | } |
| 236 | for (name, present) in [ |
| 237 | ("names", !body.names.is_empty()), |
| 238 | ("ids", !body.ids.is_empty()), |
| 239 | ("turn_lanes", !body.turn_lanes.is_empty()), |
| 240 | ("buildings_table", !body.buildings.is_empty()), |
| 241 | ("heightmap", body.heightmap.is_some()), |
| 242 | ("carriageways", !body.carriageways.is_empty()), |
| 243 | ("convention", body.convention.is_some()), |
| 244 | ("region_links", !body.region_links.is_empty()), |
| 245 | ] { |
| 246 | if present { |
| 247 | *extra.entry(name).or_default() += 1; |
| 248 | } |
| 249 | } |
| 250 | let mesh = geometry::build_toggled( |
| 251 | &body, |
| 252 | layers, |
| 253 | z, |
| 254 | x, |
| 255 | y, |
| 256 | rings_validated, |
| 257 | all_on(), |
| 258 | &KindFilter::all(), |
| 259 | 1, |
| 260 | ); |
| 261 | assert_eq!((mesh.z, mesh.x, mesh.y), (z, x, y)); |
| 262 | meshes += mesh.meshes.iter().filter(|m| !m.indices.is_empty()).count(); |
| 263 | labels += mesh.labels.len(); |
| 264 | buildings += usize::from(!mesh.buildings.indices.is_empty()); |
| 265 | carriageways += mesh.carriageways.len(); |
| 266 | traffic += mesh.traffic.len(); |
| 267 | regions += mesh.regions.len(); |
| 268 | assert!( |
| 269 | mesh.meshes.iter().any(|m| !m.indices.is_empty()), |
| 270 | "{city} {z}/{x}/{y}: nothing tessellated" |
| 271 | ); |
| 272 | println!("{line} | meshes {} labels {}", mesh.meshes.len(), mesh.labels.len()); |
| 273 | } |
| 274 | } |
| 275 | println!("body versions: {versions:?}"); |
| 276 | println!("optional body sections (tiles carrying): {extra:?}"); |
| 277 | println!( |
| 278 | "tiles {tiles} non-empty meshes {meshes} labels {labels} building tiles {buildings} carriageways {carriageways} traffic {traffic} regions {regions}" |
| 279 | ); |
| 280 | for (name, t) in &tally { |
| 281 | println!("layer {name:<10} tiles {:3} features {}", t.tiles, t.features); |
| 282 | } |
| 283 | if planet { |
| 284 | for name in tilecodec::mamaps::dict::LAYERS { |
| 285 | if *name == "junction" { |
| 286 | // planet5 (~50 GB revision) builds with --no-junction-layer: lane connectors are drawn |
| 287 | // only by the carriageway style layers, which style::LANE_RENDERING drops for release. |
| 288 | // planet4 still carries them; either is valid. |
| 289 | continue; |
| 290 | } |
| 291 | if *name == "traffic" { |
| 292 | // The writer stopped emitting `traffic` features (mamaps_build extract_part3.rs: |
| 293 | // "dropped as of the NA diet"); the layer stays in the dictionary with zero |
| 294 | // features. Pinned so a rebuild that brings it back is noticed. |
| 295 | assert!(!tally.contains_key(name), "traffic layer is back: wire up and test it"); |
| 296 | continue; |
| 297 | } |
| 298 | assert!( |
| 299 | tally.get(name).is_some_and(|t| t.features > 0), |
| 300 | "layer {name} never appeared in {tiles} city tiles" |
| 301 | ); |
| 302 | } |
| 303 | // planet4 carries v10 bodies, planet5 v11 (MED-residual heightmaps); never a mix. |
| 304 | assert!( |
| 305 | versions.len() == 1 && versions.keys().all(|&v| (10..=12).contains(&v)), |
| 306 | "expected one body version, v10 (planet4) or v11/v12 (planet5), got {versions:?}" |
| 307 | ); |
| 308 | } else { |
| 309 | // The synthetic body carries every layer but `traffic` (which the |
| 310 | // writer no longer emits, exactly as on the planet). |
| 311 | for name in [ |
| 312 | "landtype", |
| 313 | "roads", |
| 314 | "boundaries", |
| 315 | "buildings", |
| 316 | "places", |
| 317 | "poi", |
| 318 | "transit", |
| 319 | "junction", |
| 320 | "safety", |
| 321 | ] { |
| 322 | assert!( |
| 323 | tally.get(name).is_some_and(|t| t.features > 0), |
| 324 | "layer {name} never appeared in {tiles} synthetic tiles" |
| 325 | ); |
| 326 | } |
| 327 | assert!(!tally.contains_key("traffic"), "traffic layer is back: wire up and test it"); |
| 328 | assert!(versions.len() == 1, "expected one body version, got {versions:?}"); |
| 329 | } |
| 330 | assert!(buildings > 0, "no 3D buildings tessellated"); |
| 331 | // Lane rendering is switched off in the style (style::LANE_RENDERING, z16+ overzoom), so |
| 332 | // carriageway meshes stay empty by design; the tables themselves must still decode. |
| 333 | assert!(extra.contains_key("carriageways"), "no carriageway tables decoded"); |
| 334 | assert!(extra.contains_key("turn_lanes"), "no turn-lane tables decoded"); |
| 335 | assert_eq!(traffic, 0); |
| 336 | assert!(labels > 0, "no labels shaped"); |
| 337 | assert!(regions > 0, "no region-mask shapes (boundaries)"); |
| 338 | assert!(extra.contains_key("heightmap"), "no heightmap on any city tile"); |
| 339 | assert!(extra.contains_key("region_links"), "no region-link tables decoded"); |
| 340 | } |
| 341 | |
| 342 | #[test] |
| 343 | fn dem_heightmaps_sample_and_drape() { |
| 344 | // (name, lat, lon, zoom, min peak metres, synthetic heightmap lo..hi) |
| 345 | type DemCase = (&'static str, f64, f64, u8, i32, (i32, i32)); |
| 346 | let cases: &[DemCase] = &[ |
| 347 | ("Fuji", 35.3606, 138.7274, 12, 2500, (100, 3000)), |
| 348 | ("Fuji", 35.3606, 138.7274, 10, 2000, (100, 3000)), |
| 349 | ("SF Twin Peaks", 37.7544, -122.4477, 12, 150, (20, 220)), |
| 350 | ("Denver flat", 39.7392, -104.9903, 12, 1400, (1500, 1700)), |
| 351 | ]; |
| 352 | let (path, _planet) = acquire("dem", |p| { |
| 353 | let tiles: Vec<(u8, u32, u32, Body)> = cases |
| 354 | .iter() |
| 355 | .map(|&(_, lat, lon, z, _, (lo, hi))| { |
| 356 | let (x, y) = tile_of(lat, lon, z); |
| 357 | (z, x, y, fixture::dem_body(lo, hi)) |
| 358 | }) |
| 359 | .collect(); |
| 360 | fixture::write_archive(p, &tiles); |
| 361 | }); |
| 362 | let archive = open(&path); |
| 363 | let layers = style::layers(); |
| 364 | // Mount Fuji (3776 m) and the SF hills on the planet; synthetic |
| 365 | // heightmaps encode the same relief ranges in-test. |
| 366 | for &(name, lat, lon, z, min_peak, _) in cases { |
| 367 | let (x, y) = tile_of(lat, lon, z); |
| 368 | let body = archive.tile(z, x, y).unwrap().expect("tile present"); |
| 369 | let hm = |
| 370 | body.heightmap.as_ref().unwrap_or_else(|| panic!("{name} {z}/{x}/{y}: no heightmap")); |
| 371 | assert_eq!(hm.samples.len(), hm.dim as usize * hm.dim as usize); |
| 372 | let metres: Vec<i32> = |
| 373 | hm.samples.iter().map(|&s| tilecodec::mamaps::body::Heightmap::metres(s)).collect(); |
| 374 | let (lo, hi) = (*metres.iter().min().unwrap(), *metres.iter().max().unwrap()); |
| 375 | let mid = hm.sample(hm.dim / 2, hm.dim / 2).map(tilecodec::mamaps::body::Heightmap::metres); |
| 376 | println!("{name:<14} {z}/{x}/{y} dim {} min {lo} m max {hi} m centre {mid:?}", hm.dim); |
| 377 | assert!(hi >= min_peak, "{name}: max {hi} m below {min_peak} m"); |
| 378 | assert!(lo > -500 && hi < 9000, "{name}: implausible range {lo}..{hi}"); |
| 379 | let mesh = geometry::build( |
| 380 | &body, |
| 381 | layers, |
| 382 | z, |
| 383 | x, |
| 384 | y, |
| 385 | archive.header.rings_validated() && geometry::TRUST_RINGS_VALIDATED, |
| 386 | ); |
| 387 | assert!(!mesh.terrain.indices.is_empty(), "{name}: heightmap present but no terrain mesh"); |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | #[test] |
| 392 | fn an_overlay_segment_is_discovered_and_served_patch_first() { |
| 393 | use tilecodec::mamaps::write::{Options, StreamWriter}; |
| 394 | let (path, _planet) = acquire("overlay-base", |p| { |
| 395 | let tiles: Vec<(u8, u32, u32, Body)> = |
| 396 | [(37.7749, -122.4194), (51.5074, -0.1278), (40.7580, -73.9855)] |
| 397 | .iter() |
| 398 | .map(|&(lat, lon)| { |
| 399 | let (x, y) = tile_of(lat, lon, 14); |
| 400 | (14, x, y, fixture::rich_body(120)) |
| 401 | }) |
| 402 | .collect(); |
| 403 | fixture::write_archive(p, &tiles); |
| 404 | }); |
| 405 | let base = open(&path); |
| 406 | let build = base.header.build_id; |
| 407 | let len = base.header.file_len; |
| 408 | |
| 409 | // Patch one SF z14 tile (drop its buildings layer, so the patch is visible) and |
| 410 | // tombstone one London z14 tile; everything else must still come from the base. |
| 411 | let (px, py) = tile_of(37.7749, -122.4194, 14); |
| 412 | let (tx, ty) = tile_of(51.5074, -0.1278, 14); |
| 413 | let (ux, uy) = tile_of(40.7580, -73.9855, 14); |
| 414 | let mut patched = base.tile(14, px, py).unwrap().expect("SF z14"); |
| 415 | let before = patched.layers.len(); |
| 416 | patched.layers.retain(|l| layer_name(l.layer_id) != "buildings"); |
| 417 | patched.buildings.clear(); |
| 418 | assert!(patched.layers.len() < before, "SF z14 had no buildings layer to drop"); |
| 419 | |
| 420 | let dir = std::env::temp_dir().join(format!("synthetic-overlay-{}", std::process::id())); |
| 421 | let _ = std::fs::remove_dir_all(&dir); |
| 422 | std::fs::create_dir_all(dir.join("overlays/0001")).unwrap(); |
| 423 | let base_link = dir.join("basemap.mamaps"); |
| 424 | #[cfg(unix)] |
| 425 | std::os::unix::fs::symlink(&path, &base_link).unwrap(); |
| 426 | #[cfg(not(unix))] |
| 427 | std::fs::copy(&path, &base_link).unwrap(); |
| 428 | let mut writer = StreamWriter::new(Options { |
| 429 | build_id: 0xabcd, |
| 430 | rings_validated: true, |
| 431 | ..Options::default() |
| 432 | }) |
| 433 | .unwrap(); |
| 434 | writer.append(tilecodec::pmtiles::tile_id(14, px as u64, py as u64), &patched).unwrap(); |
| 435 | let seg = writer.finish().unwrap(); |
| 436 | std::fs::write(dir.join("overlays/0001/overlay-0000.mamaps"), &seg).unwrap(); |
| 437 | let manifest = format!( |
| 438 | r#"{{"version":1,"base":{{"url":"https://data.maproj.org/planet4.mamaps","build_id":"{build:#018x}","len":{len}}},"overlay_seq":1,"overlay_build_id":"0xabcd","segments":[{{"url":"https://data.maproj.org/overlays/0001/overlay-0000.mamaps","len":{},"sha256":"x","seq":0}}],"sections":[],"tombstones":[{}],"min_client":1}}"#, |
| 439 | seg.len(), |
| 440 | tilecodec::pmtiles::tile_id(14, tx as u64, ty as u64), |
| 441 | ); |
| 442 | std::fs::write(dir.join("overlays/manifest.json"), manifest).unwrap(); |
| 443 | |
| 444 | let found = discover(&base_link, Arc::new(LeafCache::new())) |
| 445 | .expect("discover refused a valid overlay over the base"); |
| 446 | assert_eq!(found.seq, 1); |
| 447 | let overlay = found.overlay; |
| 448 | assert_eq!(overlay.header().build_id, build, "the overlay keeps the base identity"); |
| 449 | let served = overlay.tile(14, px, py).unwrap().expect("patched tile"); |
| 450 | assert!( |
| 451 | served.layers.iter().all(|l| layer_name(l.layer_id) != "buildings"), |
| 452 | "segment not served first" |
| 453 | ); |
| 454 | assert!(overlay.tile(14, tx, ty).unwrap().is_none(), "tombstoned tile still served"); |
| 455 | let untouched = overlay.tile(14, ux, uy).unwrap().expect("base tile"); |
| 456 | assert_eq!( |
| 457 | untouched, |
| 458 | base.tile(14, ux, uy).unwrap().unwrap(), |
| 459 | "base tile changed under the overlay" |
| 460 | ); |
| 461 | let batch = overlay.tiles(&[(14, px, py), (14, tx, ty), (14, ux, uy)]); |
| 462 | assert!(batch[0].as_ref().unwrap().is_some() && batch[1].as_ref().unwrap().is_none()); |
| 463 | println!( |
| 464 | "overlay: seq 1 segment {} B, patch-first + tombstone + base fall-through OK", |
| 465 | seg.len() |
| 466 | ); |
| 467 | |
| 468 | // A manifest pinned to another base (planet3) must be refused: base alone. |
| 469 | let stale = std::fs::read_to_string(dir.join("overlays/manifest.json")) |
| 470 | .unwrap() |
| 471 | .replace(&format!("{build:#018x}"), "0x0a90e5e4ab91159e"); |
| 472 | std::fs::write(dir.join("overlays/manifest.json"), stale).unwrap(); |
| 473 | assert!( |
| 474 | discover(&base_link, Arc::new(LeafCache::new())).is_none(), |
| 475 | "an overlay for another base was accepted" |
| 476 | ); |
| 477 | let _ = std::fs::remove_dir_all(&dir); |
| 478 | } |
| 479 | |
| 480 | /// A [`RangeFetcher`] over the `curl` binary, standing in for the device's |
| 481 | /// `JniRangeFetcher` (`:library:network`) on the host. Honours `https_proxy`. |
| 482 | struct CurlFetcher; |
| 483 | |
| 484 | impl map_renderer::tile::source::RangeFetcher for CurlFetcher { |
| 485 | fn fetch( |
| 486 | &self, |
| 487 | url: &str, |
| 488 | range: &str, |
| 489 | ) -> tilecodec::proto::Result<map_renderer::tile::source::RangeResponse> { |
| 490 | let bytes = range.strip_prefix("bytes=").unwrap_or(range); |
| 491 | let out = std::env::temp_dir().join(format!("curl-range-{}-{bytes}", std::process::id())); |
| 492 | let status = std::process::Command::new("curl") |
| 493 | .args(["-s", "-m", "60", "-r", bytes, "-o"]) |
| 494 | .arg(&out) |
| 495 | .args(["-w", "%{http_code}", url]) |
| 496 | .output() |
| 497 | .map_err(|e| tilecodec::proto::Error(format!("curl: {e}")))?; |
| 498 | let code: u16 = String::from_utf8_lossy(&status.stdout).trim().parse().unwrap_or(0); |
| 499 | let body = std::fs::read(&out).unwrap_or_default(); |
| 500 | let _ = std::fs::remove_file(&out); |
| 501 | Ok(map_renderer::tile::source::RangeResponse { status: code, body }) |
| 502 | } |
| 503 | } |
| 504 | |
| 505 | /// The LIVE planet4 through the renderer's HTTP path: the 128-byte header range the workers |
| 506 | /// fetch first, the origin marker it keys the disk cache on, then a cold tile read through |
| 507 | /// `CachingRangeReader` + `RangeCache` + the shared decoder — compared byte-for-byte with the |
| 508 | /// local copy when `MAMAPS_REAL_ARCHIVE` is set too. Gated on `MAMAPS_LIVE=1` (network). |
| 509 | /// |
| 510 | /// Planet-only by construction (it pins the published file's build id and |
| 511 | /// length), so it stays ignored; the synthetic tests above cover the same |
| 512 | /// reader paths offline. |
| 513 | #[test] |
| 514 | #[ignore = "needs MAMAPS_LIVE=1 and network to data.maproj.org"] |
| 515 | fn live_planet4_reads_through_the_range_cache() { |
| 516 | use map_renderer::tile::cache::{RangeCache, DEFAULT_MAX_BYTES}; |
| 517 | use map_renderer::tile::source::{ |
| 518 | basemap_origin, CachingRangeReader, RangeFetcher, BASEMAP_ARCHIVE_URL, |
| 519 | }; |
| 520 | if std::env::var("MAMAPS_LIVE").as_deref() != Ok("1") { |
| 521 | eprintln!("MAMAPS_LIVE not set: live test skipped"); |
| 522 | return; |
| 523 | } |
| 524 | assert_eq!(BASEMAP_ARCHIVE_URL, "https://data.maproj.org/planet4.mamaps"); |
| 525 | let head = CurlFetcher.fetch(BASEMAP_ARCHIVE_URL, "bytes=0-127").expect("header fetch"); |
| 526 | assert_eq!(head.status, 206, "the CDN must answer ranges"); |
| 527 | assert_eq!(head.body.len(), tilecodec::mamaps::header::HEADER_LEN); |
| 528 | let header = Header::parse(&head.body).expect("live header parses"); |
| 529 | println!( |
| 530 | "live: build {:#018x} len {} version {} layers {}", |
| 531 | header.build_id, header.file_len, head.body[7], header.layer_count |
| 532 | ); |
| 533 | assert_eq!(header.build_id, 0x2ab5_ba58_33e5_4438); |
| 534 | assert_eq!(header.file_len, 81_331_811_296); |
| 535 | |
| 536 | let dir = std::env::temp_dir().join(format!("live-range-cache-{}", std::process::id())); |
| 537 | let _ = std::fs::remove_dir_all(&dir); |
| 538 | let origin = basemap_origin(BASEMAP_ARCHIVE_URL, header.build_id); |
| 539 | let cache = RangeCache::open(&dir, &origin, DEFAULT_MAX_BYTES); |
| 540 | let reader = CachingRangeReader::new(BASEMAP_ARCHIVE_URL, cache, CurlFetcher); |
| 541 | let live = |
| 542 | MamapsArchive::open_with_cache(reader, Arc::new(LeafCache::new())).expect("live open"); |
| 543 | assert_eq!(live.header, header); |
| 544 | let (x, y) = tile_of(37.7749, -122.4194, 14); |
| 545 | let body = live.tile(14, x, y).expect("live tile").expect("SF z14 present"); |
| 546 | let cached = std::fs::read_dir(&dir) |
| 547 | .unwrap() |
| 548 | .flatten() |
| 549 | .filter(|e| e.path().extension().is_some_and(|x| x == "data")) |
| 550 | .count(); |
| 551 | println!( |
| 552 | "live: SF z14 has {} layers; {cached} ranges cached under {origin}", |
| 553 | body.layers.len() |
| 554 | ); |
| 555 | assert!(cached > 0, "nothing landed in the range cache"); |
| 556 | assert_eq!(std::fs::read_to_string(dir.join(".origin")).unwrap().trim(), origin); |
| 557 | if let Some(path) = fixture::planet_path() { |
| 558 | let local = open(&path); |
| 559 | assert_eq!(local.header, header, "local world.mamaps is not the published planet4"); |
| 560 | assert_eq!(local.tile(14, x, y).unwrap().unwrap(), body, "live and local bodies differ"); |
| 561 | println!("live: header and SF z14 body identical to the local archive"); |
| 562 | } |
| 563 | let _ = std::fs::remove_dir_all(&dir); |
| 564 | } |