Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / main_part2.rs
main_part2.rs397 lines · 18.4 KiBRaw
| 1 | /// The routing graph's availability, for `--graph-ready-file`. |
| 2 | /// |
| 3 | /// Exactly three things in `mamaps_build` read `--graph`, and they are the only stages that wait: |
| 4 | /// |
| 5 | /// | stage | what it reads | without the graph yet | |
| 6 | /// |---|---|---| |
| 7 | /// | preflight (`check_graph_dir`) | `metadata.bin`, `nodes.bin`, `edges.bin`, `intermediate.bin` | deferred to the gate | |
| 8 | /// | pass 1 blob-kinds sidecar (`pbf::load_blob_kinds`) | `blob_kinds.bin` (optional, a skip list) | skipped: pass 1 scans every blob, same output | |
| 9 | /// | feature-spill budget (`plan_feature_spill`) | file sizes of the graph | sized as file-staged (the safe backend), same output | |
| 10 | /// | **junction layer** (`schema::junction::stream_junctions`) | the whole graph + `lanes.bin` | **waits here** | |
| 11 | /// |
| 12 | /// Everything before the junction layer -- passes 1-3, corridors, lane inheritance, materialise |
| 13 | /// ways and relations, land polygons, transit routes -- reads only the `.osm.pbf`, the coastline |
| 14 | /// and the transit routes, and runs while `road_graph` is still working. The tiler and |
| 15 | /// everything after it never read the graph. Without the flag the graph is ready by definition |
| 16 | /// and none of this changes behaviour. |
| 17 | pub(crate) struct GraphGate { |
| 18 | dir: PathBuf, |
| 19 | ready_file: Option<PathBuf>, |
| 20 | region: osm_ingest::region::Region, |
| 21 | validated: std::cell::Cell<bool>, |
| 22 | } |
| 23 | |
| 24 | impl GraphGate { |
| 25 | fn new(dir: PathBuf, ready_file: Option<PathBuf>, region: osm_ingest::region::Region) -> GraphGate { |
| 26 | GraphGate { dir, ready_file, region, validated: std::cell::Cell::new(false) } |
| 27 | } |
| 28 | |
| 29 | /// The graph directory. |
| 30 | pub(crate) fn dir(&self) -> &std::path::Path { |
| 31 | &self.dir |
| 32 | } |
| 33 | |
| 34 | /// Whether the graph may be read right now without waiting. |
| 35 | pub(crate) fn ready_now(&self) -> bool { |
| 36 | self.validated.get() || self.ready_file.as_ref().is_none_or(|p| p.exists()) |
| 37 | } |
| 38 | |
| 39 | /// Block until the ready file exists (polling once a second), then validate the graph |
| 40 | /// directory exactly as the preflight does. Idempotent. |
| 41 | pub(crate) fn wait(&self) -> Result<(), String> { |
| 42 | if self.validated.get() { |
| 43 | return Ok(()); |
| 44 | } |
| 45 | if let Some(ready) = &self.ready_file { |
| 46 | if !ready.exists() { |
| 47 | println!("waiting for graph: {}", ready.display()); |
| 48 | let start = std::time::Instant::now(); |
| 49 | let mut said = 0u64; |
| 50 | while !ready.exists() { |
| 51 | std::thread::sleep(std::time::Duration::from_secs(1)); |
| 52 | let waited = start.elapsed().as_secs(); |
| 53 | if waited >= said + 60 { |
| 54 | said = waited; |
| 55 | println!("waiting for graph: {} ({waited}s)", ready.display()); |
| 56 | } |
| 57 | } |
| 58 | println!("graph ready after {:.0}s", start.elapsed().as_secs_f64()); |
| 59 | } |
| 60 | } |
| 61 | check_graph_dir(&self.dir, self.region)?; |
| 62 | self.validated.set(true); |
| 63 | Ok(()) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | fn usage() { |
| 68 | eprintln!( |
| 69 | "usage: mamaps_build --input IN.osm.pbf --out OUT.mamaps\n\ |
| 70 | \x20 --coastline LAND.shp|LAND.geojsonseq\n\ |
| 71 | \x20 --transit-routes ROUTES.geojsonseq\n\ |
| 72 | \x20 --graph GRAPH_DIR\n\ |
| 73 | \x20 --dem HEIGHTMAPS.mdem\n\ |
| 74 | \x20 [--region california|world]\n\ |
| 75 | \x20 [--build-graph-to DIR] [--build-poi-to DIR]\n\ |
| 76 | \x20 [--graph-ready-file PATH] [--v8-bodies]\n\ |
| 77 | \x20 [--body-zstd LEVEL] [--dem-max-error M] [--dem-px K]\n\ |
| 78 | \x20 [--simplify-scale S] [--z14-tolerance T] [--coord-quant] [--keep-z13-wash] [--no-junction-layer]\n\ |
| 79 | \n\ |
| 80 | \x20All six flags are required. Every build carries all 9 layers at\n\ |
| 81 | \x20z0-14 as FORMAT_VERSION 8. --region filters roads/pois/buildings\n\ |
| 82 | \x20to the region (default world = no filter); everything else is\n\ |
| 83 | \x20always included. --graph-ready-file starts before GRAPH_DIR is\n\ |
| 84 | \x20written and waits for PATH before the junction layer reads it." |
| 85 | ); |
| 86 | } |
| 87 | |
| 88 | /// Whether this build is allowed to proceed given what it was told about a side input. |
| 89 | /// |
| 90 | /// **Every side input is required, with no way to decline it.** A missing coastline used to be a |
| 91 | /// warning, which is how an archive ends up with islands and no mainland: the line scrolls past |
| 92 | /// in a build that takes hours and nobody reads it until the map is on a phone. The same holds |
| 93 | /// for the other three: the `transit` layer comes from GTFS rather than the `.osm.pbf`, the |
| 94 | /// `traffic` and `junction` layers from the routing graph, and every tile's heightmap from the |
| 95 | /// DEM — so a build without one is silently missing a layer, not a build with different options. |
| 96 | fn check_required(path: &std::path::Path, flag: &str) -> Result<(), String> { |
| 97 | if path.as_os_str().is_empty() { |
| 98 | return Err(format!("{flag} is required: every build carries all 9 layers")); |
| 99 | } |
| 100 | Ok(()) |
| 101 | } |
| 102 | |
| 103 | /// Validate the routing graph directory BEFORE stage A runs. |
| 104 | /// |
| 105 | /// This is the failure the world build hit: an empty graph dir (no |
| 106 | /// `metadata.bin` because `road_graph` never ran or wrote elsewhere), paid |
| 107 | /// for with 43 minutes of stage A before `traffic` tried to read it. Every |
| 108 | /// check here fails in seconds with the path in the message. |
| 109 | /// |
| 110 | /// A region build additionally requires the graph to cover the region: a |
| 111 | /// world graph beside a california tile build would silently double-cover |
| 112 | /// traffic, and a california graph beside a world build would silently drop |
| 113 | /// it outside the state. The graph's own node bbox is compared against the |
| 114 | /// region's — it must at least touch it. |
| 115 | fn check_graph_dir(dir: &std::path::Path, region: osm_ingest::region::Region) -> Result<(), String> { |
| 116 | let read = |name: &str| -> Result<Vec<u8>, String> { |
| 117 | let path = dir.join(name); |
| 118 | std::fs::read(&path).map_err(|e| format!("cannot read {}: {e}", path.display())) |
| 119 | }; |
| 120 | // `metadata.bin` first: its absence is THE failure (empty dir), and its |
| 121 | // counts size every other check. |
| 122 | let meta = read("metadata.bin")?; |
| 123 | if meta.len() < 40 { |
| 124 | return Err(format!( |
| 125 | "metadata.bin is {} bytes, a v6 MARG header is 40 — is {} a graph dir?", |
| 126 | meta.len(), |
| 127 | dir.display(), |
| 128 | )); |
| 129 | } |
| 130 | let u32_at = |b: &[u8], at: usize| u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]); |
| 131 | let u64_at = |b: &[u8], at: usize| { |
| 132 | u64::from_le_bytes([ |
| 133 | b[at], b[at + 1], b[at + 2], b[at + 3], b[at + 4], b[at + 5], b[at + 6], b[at + 7], |
| 134 | ]) |
| 135 | }; |
| 136 | if u32_at(&meta, 0) != 0x4752_414D { |
| 137 | return Err(format!("{} is not a MARG graph header", dir.join("metadata.bin").display())); |
| 138 | } |
| 139 | let version = u32_at(&meta, 4); |
| 140 | if version != 6 && version != 7 { |
| 141 | return Err(format!("the graph is version {version}; this build reads v6..=v7")); |
| 142 | } |
| 143 | let blocked_v7 = version >= 7; |
| 144 | let node_count = u64_at(&meta, 8); |
| 145 | let edge_count = u64_at(&meta, 16); |
| 146 | if node_count == 0 { |
| 147 | return Err(format!("the graph at {} has 0 nodes — road_graph wrote nothing?", dir.display())); |
| 148 | } |
| 149 | // The remaining files must exist and match the header's counts. |
| 150 | // Under v7 the record arrays are ZBLK sections: unpack at the boundary |
| 151 | // (this is a preflight check, not the hot path, so whole-section inflate |
| 152 | // is fine). |
| 153 | // Block-parallel (see `schema::traffic::inflate_all`): the planet's 5 GB node table used to |
| 154 | // inflate on one thread here, in the preflight, before stage A could start. |
| 155 | fn inflate_all(v: &tilecodec::blocked::Blocked) -> Result<Vec<u8>, String> { |
| 156 | crate::schema::traffic::inflate_all(v).map_err(|e| format!("blocked inflate failed: {}", e.0)) |
| 157 | } |
| 158 | let want_nodes = (node_count + 1) |
| 159 | .checked_mul(12) |
| 160 | .ok_or_else(|| "node table size overflows".to_string())?; |
| 161 | let nodes_raw = read("nodes.bin")?; |
| 162 | let nodes: Vec<u8> = if blocked_v7 { |
| 163 | let v = tilecodec::blocked::Blocked::parse(&nodes_raw).map_err(|e| { |
| 164 | format!("nodes.bin is not a blocked section: {e}") |
| 165 | })?; |
| 166 | if v.unpacked_len() != want_nodes || v.record_len() != 12 { |
| 167 | return Err(format!( |
| 168 | "nodes.bin unpacks to {} byte(s), expected {want_nodes} for {node_count}+1 records", |
| 169 | v.unpacked_len(), |
| 170 | )); |
| 171 | } |
| 172 | inflate_all(&v)? |
| 173 | } else { |
| 174 | if nodes_raw.len() as u64 != want_nodes { |
| 175 | return Err(format!( |
| 176 | "nodes.bin is {} bytes, expected {want_nodes} for {node_count}+1 records — stale graph dir?", |
| 177 | nodes_raw.len(), |
| 178 | )); |
| 179 | } |
| 180 | nodes_raw |
| 181 | }; |
| 182 | let edges = read("edges.bin")?; |
| 183 | if blocked_v7 { |
| 184 | // v7: the record array is blocked (data-dependent length), so only |
| 185 | // the tail minimum applies. The real validation (blocked parse + |
| 186 | // unpacked lengths + escape/name checks) lives in `traffic::Graph::load`, |
| 187 | // which reads this same dir next. |
| 188 | let v = tilecodec::blocked::Blocked::parse(&edges).map_err(|e| { |
| 189 | format!("edges.bin is not a blocked section: {e}") |
| 190 | })?; |
| 191 | if v.unpacked_len() != edge_count * 7 || v.record_len() != 7 { |
| 192 | return Err(format!( |
| 193 | "edges.bin unpacks to {} byte(s), expected {edge_count} 7-byte records", |
| 194 | v.unpacked_len(), |
| 195 | )); |
| 196 | } |
| 197 | } else { |
| 198 | let want_edges_min = ((edge_count * 7 + 7) & !7) as usize; |
| 199 | if edges.len() < want_edges_min { |
| 200 | return Err(format!( |
| 201 | "edges.bin is {} bytes, too short for {edge_count} edges — stale graph dir?", |
| 202 | edges.len(), |
| 203 | )); |
| 204 | } |
| 205 | } |
| 206 | let inter = read("intermediate.bin")?; |
| 207 | if inter.len() < 8 { |
| 208 | return Err(format!( |
| 209 | "intermediate.bin is {} bytes — stale graph dir?", |
| 210 | inter.len(), |
| 211 | )); |
| 212 | } |
| 213 | println!("graph ok: {node_count} node(s), {edge_count} edge(s) at {}", dir.display()); |
| 214 | |
| 215 | // Region coverage: the graph's live extent must touch the region's. A |
| 216 | // region graph covers only the region (world nodes outside it are dropped |
| 217 | // at collapse), so the extent is the proof the graph and the region agree. |
| 218 | // |
| 219 | // Sampled by STRIDE, not by prefix: `nodes.bin` is Morton-ordered, so the |
| 220 | // first 1M records are one corner of the spatial curve, not the world. |
| 221 | // Stepping across the whole file touches every part of the curve for the |
| 222 | // cost of ~1M random 12-byte reads. |
| 223 | if let Some(b) = region.bbox() { |
| 224 | let (mut min_lon, mut min_lat) = (i32::MAX, i32::MAX); |
| 225 | let (mut max_lon, mut max_lat) = (i32::MIN, i32::MIN); |
| 226 | let stride = (node_count / 1_000_000).max(1); |
| 227 | let mut sampled = 0u64; |
| 228 | let mut n = 0u64; |
| 229 | while n < node_count { |
| 230 | let base = (n as usize) * 12; |
| 231 | let (lat, lon) = ( |
| 232 | i32::from_le_bytes(nodes[base..base + 4].try_into().unwrap()), |
| 233 | i32::from_le_bytes(nodes[base + 4..base + 8].try_into().unwrap()), |
| 234 | ); |
| 235 | // The trailing sentinel record is (0, 0); skip it and any node the |
| 236 | // build left at the origin. |
| 237 | if lat != 0 || lon != 0 { |
| 238 | min_lon = min_lon.min(lon); |
| 239 | min_lat = min_lat.min(lat); |
| 240 | max_lon = max_lon.max(lon); |
| 241 | max_lat = max_lat.max(lat); |
| 242 | sampled += 1; |
| 243 | } |
| 244 | n += stride; |
| 245 | } |
| 246 | if sampled == 0 { |
| 247 | return Err(format!( |
| 248 | "the graph at {} has no located nodes — road_graph wrote nothing?", |
| 249 | dir.display(), |
| 250 | )); |
| 251 | } |
| 252 | let touches = !(max_lon < (b.min_lon * 1e7).round() as i32 |
| 253 | || min_lon > (b.max_lon * 1e7).round() as i32 |
| 254 | || max_lat < (b.min_lat * 1e7).round() as i32 |
| 255 | || min_lat > (b.max_lat * 1e7).round() as i32); |
| 256 | if !touches { |
| 257 | return Err(format!( |
| 258 | "the graph at {} covers lon {:.1}..{:.1}, lat {:.1}..{:.1}, which does not touch the {} region — wrong --graph for --region {}?", |
| 259 | dir.display(), |
| 260 | min_lon as f64 * 1e-7, |
| 261 | max_lon as f64 * 1e-7, |
| 262 | min_lat as f64 * 1e-7, |
| 263 | max_lat as f64 * 1e-7, |
| 264 | region.name(), |
| 265 | region.name(), |
| 266 | )); |
| 267 | } |
| 268 | } |
| 269 | Ok(()) |
| 270 | } |
| 271 | |
| 272 | #[cfg(test)] |
| 273 | mod tests { |
| 274 | use super::*; |
| 275 | |
| 276 | /// Every side input is **required**, and there is no flag that says otherwise. |
| 277 | /// |
| 278 | /// A missing input used to print a line and carry on, which is how an archive ships with |
| 279 | /// islands and no mainland: the warning scrolls past in a build that takes hours and nobody |
| 280 | /// sees it until the map is on a phone. |
| 281 | #[test] |
| 282 | fn a_build_cannot_proceed_without_its_side_inputs() { |
| 283 | let shp = std::path::Path::new("land_polygons.shp"); |
| 284 | assert!(check_required(shp, "--coastline").is_ok(), "the normal build"); |
| 285 | assert!( |
| 286 | check_required(std::path::Path::new(""), "--coastline").is_err(), |
| 287 | "an empty path is a missing input", |
| 288 | ); |
| 289 | } |
| 290 | |
| 291 | /// The schema's own floor for buildings and the style's have to agree, or the archive either |
| 292 | /// carries what nothing draws or is asked for what it does not carry. |
| 293 | #[test] |
| 294 | fn the_schema_floor_matches_the_styles() { |
| 295 | // The style's floor lives in `library/map`'s flat style, which this crate does not link. So |
| 296 | // this pins the number and names where the other copy is: a change here without a change |
| 297 | // there shows up as a tile the renderer asks for and does not get. |
| 298 | assert_eq!( |
| 299 | schema::buildings::MIN_ZOOM, |
| 300 | 14, |
| 301 | "buildings' floor is 14 in library/map/src/main/rust/style/basemap.flat.json too", |
| 302 | ); |
| 303 | } |
| 304 | |
| 305 | /// The id has to change when the data would, and not otherwise. A rebuild from unchanged |
| 306 | /// inputs keeps its id -- wherever the inputs live and whenever they were touched -- which is |
| 307 | /// what makes a byte-identical rebuild byte-identical. |
| 308 | #[test] |
| 309 | fn a_build_id_follows_the_inputs_that_decide_the_output() { |
| 310 | let dir = |name: &str| { |
| 311 | let d = std::env::temp_dir().join(format!("mamaps_bid_{}_{name}", std::process::id())); |
| 312 | let _ = std::fs::remove_dir_all(&d); |
| 313 | std::fs::create_dir_all(d.join("graph")).unwrap(); |
| 314 | for (f, bytes) in [ |
| 315 | ("in.osm.pbf", &b"pbf bytes"[..]), |
| 316 | ("coast.shp", b"shp bytes"), |
| 317 | ("routes.geojsonseq", b"routes"), |
| 318 | ("world.mdem", b"dem bytes"), |
| 319 | ("graph/metadata.bin", b"graph meta"), |
| 320 | ("graph/edges.bin", b"edges"), |
| 321 | ] { |
| 322 | std::fs::write(d.join(f), bytes).unwrap(); |
| 323 | } |
| 324 | d |
| 325 | }; |
| 326 | let digests = |d: &std::path::Path| { |
| 327 | input_digests( |
| 328 | &d.join("in.osm.pbf"), |
| 329 | &d.join("coast.shp"), |
| 330 | &d.join("graph"), |
| 331 | &d.join("routes.geojsonseq"), |
| 332 | &d.join("world.mdem"), |
| 333 | ) |
| 334 | .unwrap() |
| 335 | }; |
| 336 | let all = schema::Layers::all(); |
| 337 | let a = dir("a"); |
| 338 | let inputs = digests(&a); |
| 339 | let base = derive_build_id(&inputs, all, 0, 14, 1.0, 100, "world", false); |
| 340 | assert_eq!(base, derive_build_id(&inputs, all, 0, 14, 1.0, 100, "world", false), "stable"); |
| 341 | // The same bytes at another path, written later, with a `.ready` signal in the graph dir: |
| 342 | // the same id. |
| 343 | std::thread::sleep(std::time::Duration::from_millis(20)); |
| 344 | let b = dir("b"); |
| 345 | std::fs::write(b.join("graph/.ready"), b"").unwrap(); |
| 346 | assert_eq!(digests(&b), inputs, "place or time leaked into an input digest"); |
| 347 | // Every input's content and every parameter moves it. |
| 348 | let mut others = vec![ |
| 349 | derive_build_id(&inputs, all, 0, 14, 2.0, 100, "world", false), |
| 350 | derive_build_id(&inputs, all, 0, 14, 1.0, 101, "world", false), |
| 351 | derive_build_id(&inputs, all, 0, 14, 1.0, 100, "california", false), |
| 352 | derive_build_id(&inputs, all, 0, 13, 1.0, 100, "world", false), |
| 353 | derive_build_id(&inputs, all, 0, 14, 1.0, 100, "world", true), |
| 354 | ]; |
| 355 | for f in ["in.osm.pbf", "coast.shp", "routes.geojsonseq", "world.mdem", "graph/edges.bin"] { |
| 356 | let c = dir("c"); |
| 357 | std::fs::write(c.join(f), b"changed content").unwrap(); |
| 358 | others.push(derive_build_id(&digests(&c), all, 0, 14, 1.0, 100, "world", false)); |
| 359 | } |
| 360 | for (i, other) in others.iter().enumerate() { |
| 361 | assert_ne!(base, *other, "change #{i} should change the id"); |
| 362 | } |
| 363 | // The header id folds in the tile digest: same seed, different tiles, different id. |
| 364 | use tilecodec::mamaps::write::content_build_id; |
| 365 | assert_eq!(content_build_id(base, 1), content_build_id(base, 1)); |
| 366 | assert_ne!(content_build_id(base, 1), content_build_id(base, 2)); |
| 367 | assert_ne!(content_build_id(base, 1), content_build_id(base ^ 1, 1)); |
| 368 | for d in ["a", "b", "c"] { |
| 369 | let _ = std::fs::remove_dir_all( |
| 370 | std::env::temp_dir().join(format!("mamaps_bid_{}_{d}", std::process::id())), |
| 371 | ); |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | /// A missing or stale graph dir fails HERE, in seconds — not 43 minutes |
| 376 | /// into stage A when `traffic` first reads it. That is the world-build |
| 377 | /// failure this exists for: an empty graph dir with no `metadata.bin`. |
| 378 | #[test] |
| 379 | fn a_missing_graph_fails_before_stage_a() { |
| 380 | use osm_ingest::region::Region; |
| 381 | let missing = std::path::Path::new("no_such_graph_dir_xyz"); |
| 382 | let err = check_graph_dir(missing, Region::World).expect_err("missing dir must fail"); |
| 383 | assert!(err.contains("cannot read"), "{err}"); |
| 384 | // An empty dir: no metadata.bin is the reported failure. |
| 385 | let dir = std::env::temp_dir() |
| 386 | .join(format!("mamaps_graphcheck_{}", std::process::id())); |
| 387 | let _ = std::fs::remove_dir_all(&dir); |
| 388 | std::fs::create_dir_all(&dir).unwrap(); |
| 389 | let err = check_graph_dir(&dir, Region::World).expect_err("empty dir must fail"); |
| 390 | assert!(err.contains("metadata.bin"), "{err}"); |
| 391 | // A bad magic: not a graph dir at all. |
| 392 | std::fs::write(dir.join("metadata.bin"), vec![0u8; 40]).unwrap(); |
| 393 | let err = check_graph_dir(&dir, Region::World).expect_err("bad magic must fail"); |
| 394 | assert!(err.contains("MARG"), "{err}"); |
| 395 | let _ = std::fs::remove_dir_all(&dir); |
| 396 | } |
| 397 | } |