Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / scripts / maps / mamaps_build / src / main_part2.rs

main_part2.rs293 lines · 12.9 KiBRaw
1fn usage() {
2 eprintln!(
3 "usage: mamaps_build --input IN.osm.pbf --out OUT.mamaps\n\
4 \x20 --coastline LAND.shp|LAND.geojsonseq\n\
5 \x20 --transit-routes ROUTES.geojsonseq\n\
6 \x20 --graph GRAPH_DIR\n\
7 \x20 --dem HEIGHTMAPS.mdem\n\
8 \x20 [--region california|world]\n\
9 \x20 [--build-graph-to DIR] [--build-poi-to DIR]\n\
10 \n\
11 \x20All six flags are required. Every build carries all 9 layers at\n\
12 \x20z0-14 as FORMAT_VERSION 8. --region filters roads/pois/buildings\n\
13 \x20to the region (default world = no filter); everything else is\n\
14 \x20always included."
15 );
16}
17
18/// Whether this build is allowed to proceed given what it was told about a side input.
19///
20/// **Every side input is required, with no way to decline it.** A missing coastline used to be a
21/// warning, which is how an archive ends up with islands and no mainland: the line scrolls past
22/// in a build that takes hours and nobody reads it until the map is on a phone. The same holds
23/// for the other three: the `transit` layer comes from GTFS rather than the `.osm.pbf`, the
24/// `traffic` and `junction` layers from the routing graph, and every tile's heightmap from the
25/// DEM — so a build without one is silently missing a layer, not a build with different options.
26fn check_required(path: &std::path::Path, flag: &str) -> Result<(), String> {
27 if path.as_os_str().is_empty() {
28 return Err(format!("{flag} is required: every build carries all 9 layers"));
29 }
30 Ok(())
31}
32
33/// Validate the routing graph directory BEFORE stage A runs.
34///
35/// This is the failure the world build hit: an empty graph dir (no
36/// `metadata.bin` because `road_graph` never ran or wrote elsewhere), paid
37/// for with 43 minutes of stage A before `traffic` tried to read it. Every
38/// check here fails in seconds with the path in the message.
39///
40/// A region build additionally requires the graph to cover the region: a
41/// world graph beside a california tile build would silently double-cover
42/// traffic, and a california graph beside a world build would silently drop
43/// it outside the state. The graph's own node bbox is compared against the
44/// region's — it must at least touch it.
45fn check_graph_dir(dir: &std::path::Path, region: osm_ingest::region::Region) -> Result<(), String> {
46 let read = |name: &str| -> Result<Vec<u8>, String> {
47 let path = dir.join(name);
48 std::fs::read(&path).map_err(|e| format!("cannot read {}: {e}", path.display()))
49 };
50 // `metadata.bin` first: its absence is THE failure (empty dir), and its
51 // counts size every other check.
52 let meta = read("metadata.bin")?;
53 if meta.len() < 40 {
54 return Err(format!(
55 "metadata.bin is {} bytes, a v6 MARG header is 40 — is {} a graph dir?",
56 meta.len(),
57 dir.display(),
58 ));
59 }
60 let u32_at = |b: &[u8], at: usize| u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]);
61 let u64_at = |b: &[u8], at: usize| {
62 u64::from_le_bytes([
63 b[at], b[at + 1], b[at + 2], b[at + 3], b[at + 4], b[at + 5], b[at + 6], b[at + 7],
64 ])
65 };
66 if u32_at(&meta, 0) != 0x4752_414D {
67 return Err(format!("{} is not a MARG graph header", dir.join("metadata.bin").display()));
68 }
69 let version = u32_at(&meta, 4);
70 if version != 6 && version != 7 {
71 return Err(format!("the graph is version {version}; this build reads v6..=v7"));
72 }
73 let blocked_v7 = version >= 7;
74 let node_count = u64_at(&meta, 8);
75 let edge_count = u64_at(&meta, 16);
76 if node_count == 0 {
77 return Err(format!("the graph at {} has 0 nodes — road_graph wrote nothing?", dir.display()));
78 }
79 // The remaining files must exist and match the header's counts.
80 // Under v7 the record arrays are ZBLK sections: unpack at the boundary
81 // (this is a preflight check, not the hot path, so whole-section inflate
82 // is fine).
83 fn inflate_all(v: &tilecodec::blocked::Blocked) -> Result<Vec<u8>, String> {
84 let mut cache = tilecodec::blocked::BlockCache::new(0);
85 let mut out = Vec::with_capacity(v.unpacked_len() as usize);
86 for b in 0..v.block_count() {
87 out.extend_from_slice(
88 cache
89 .get(v, b)
90 .map_err(|e| format!("blocked inflate failed: {e}"))?,
91 );
92 }
93 if out.len() as u64 != v.unpacked_len() {
94 return Err("blocked inflate came up short".to_string());
95 }
96 Ok(out)
97 }
98 let want_nodes = (node_count + 1)
99 .checked_mul(12)
100 .ok_or_else(|| "node table size overflows".to_string())?;
101 let nodes_raw = read("nodes.bin")?;
102 let nodes: Vec<u8> = if blocked_v7 {
103 let v = tilecodec::blocked::Blocked::parse(&nodes_raw).map_err(|e| {
104 format!("nodes.bin is not a blocked section: {e}")
105 })?;
106 if v.unpacked_len() != want_nodes || v.record_len() != 12 {
107 return Err(format!(
108 "nodes.bin unpacks to {} byte(s), expected {want_nodes} for {node_count}+1 records",
109 v.unpacked_len(),
110 ));
111 }
112 inflate_all(&v)?
113 } else {
114 if nodes_raw.len() as u64 != want_nodes {
115 return Err(format!(
116 "nodes.bin is {} bytes, expected {want_nodes} for {node_count}+1 records — stale graph dir?",
117 nodes_raw.len(),
118 ));
119 }
120 nodes_raw
121 };
122 let edges = read("edges.bin")?;
123 if blocked_v7 {
124 // v7: the record array is blocked (data-dependent length), so only
125 // the tail minimum applies. The real validation (blocked parse +
126 // unpacked lengths + escape/name checks) lives in `traffic::Graph::load`,
127 // which reads this same dir next.
128 let v = tilecodec::blocked::Blocked::parse(&edges).map_err(|e| {
129 format!("edges.bin is not a blocked section: {e}")
130 })?;
131 if v.unpacked_len() != edge_count * 7 || v.record_len() != 7 {
132 return Err(format!(
133 "edges.bin unpacks to {} byte(s), expected {edge_count} 7-byte records",
134 v.unpacked_len(),
135 ));
136 }
137 } else {
138 let want_edges_min = ((edge_count * 7 + 7) & !7) as usize;
139 if edges.len() < want_edges_min {
140 return Err(format!(
141 "edges.bin is {} bytes, too short for {edge_count} edges — stale graph dir?",
142 edges.len(),
143 ));
144 }
145 }
146 let inter = read("intermediate.bin")?;
147 if inter.len() < 8 {
148 return Err(format!(
149 "intermediate.bin is {} bytes — stale graph dir?",
150 inter.len(),
151 ));
152 }
153 println!("graph ok: {node_count} node(s), {edge_count} edge(s) at {}", dir.display());
154
155 // Region coverage: the graph's live extent must touch the region's. A
156 // region graph covers only the region (world nodes outside it are dropped
157 // at collapse), so the extent is the proof the graph and the region agree.
158 //
159 // Sampled by STRIDE, not by prefix: `nodes.bin` is Morton-ordered, so the
160 // first 1M records are one corner of the spatial curve, not the world.
161 // Stepping across the whole file touches every part of the curve for the
162 // cost of ~1M random 12-byte reads.
163 if let Some(b) = region.bbox() {
164 let (mut min_lon, mut min_lat) = (i32::MAX, i32::MAX);
165 let (mut max_lon, mut max_lat) = (i32::MIN, i32::MIN);
166 let stride = (node_count / 1_000_000).max(1);
167 let mut sampled = 0u64;
168 let mut n = 0u64;
169 while n < node_count {
170 let base = (n as usize) * 12;
171 let (lat, lon) = (
172 i32::from_le_bytes(nodes[base..base + 4].try_into().unwrap()),
173 i32::from_le_bytes(nodes[base + 4..base + 8].try_into().unwrap()),
174 );
175 // The trailing sentinel record is (0, 0); skip it and any node the
176 // build left at the origin.
177 if lat != 0 || lon != 0 {
178 min_lon = min_lon.min(lon);
179 min_lat = min_lat.min(lat);
180 max_lon = max_lon.max(lon);
181 max_lat = max_lat.max(lat);
182 sampled += 1;
183 }
184 n += stride;
185 }
186 if sampled == 0 {
187 return Err(format!(
188 "the graph at {} has no located nodes — road_graph wrote nothing?",
189 dir.display(),
190 ));
191 }
192 let touches = !(max_lon < (b.min_lon * 1e7).round() as i32
193 || min_lon > (b.max_lon * 1e7).round() as i32
194 || max_lat < (b.min_lat * 1e7).round() as i32
195 || min_lat > (b.max_lat * 1e7).round() as i32);
196 if !touches {
197 return Err(format!(
198 "the graph at {} covers lon {:.1}..{:.1}, lat {:.1}..{:.1}, which does not touch the {} region — wrong --graph for --region {}?",
199 dir.display(),
200 min_lon as f64 * 1e-7,
201 max_lon as f64 * 1e-7,
202 min_lat as f64 * 1e-7,
203 max_lat as f64 * 1e-7,
204 region.name(),
205 region.name(),
206 ));
207 }
208 }
209 Ok(())
210}
211
212#[cfg(test)]
213mod tests {
214 use super::*;
215
216 /// Every side input is **required**, and there is no flag that says otherwise.
217 ///
218 /// A missing input used to print a line and carry on, which is how an archive ships with
219 /// islands and no mainland: the warning scrolls past in a build that takes hours and nobody
220 /// sees it until the map is on a phone.
221 #[test]
222 fn a_build_cannot_proceed_without_its_side_inputs() {
223 let shp = std::path::Path::new("land_polygons.shp");
224 assert!(check_required(shp, "--coastline").is_ok(), "the normal build");
225 assert!(
226 check_required(std::path::Path::new(""), "--coastline").is_err(),
227 "an empty path is a missing input",
228 );
229 }
230
231 /// The schema's own floor for buildings and the style's have to agree, or the archive either
232 /// carries what nothing draws or is asked for what it does not carry.
233 #[test]
234 fn the_schema_floor_matches_the_styles() {
235 // The style's floor lives in `library/map`'s flat style, which this crate does not link. So
236 // this pins the number and names where the other copy is: a change here without a change
237 // there shows up as a tile the renderer asks for and does not get.
238 assert_eq!(
239 schema::buildings::MIN_ZOOM,
240 14,
241 "buildings' floor is 14 in library/map/src/main/rust/style/basemap.flat.json too",
242 );
243 }
244
245 /// The id has to change when the data would, and not otherwise. A rebuild from an unchanged file
246 /// keeps its id, which is what makes a byte-identical rebuild byte-identical.
247 #[test]
248 fn a_build_id_follows_the_inputs_that_decide_the_output() {
249 let path = std::path::Path::new("nonexistent.osm.pbf");
250 let all = schema::Layers::all();
251 let base = derive_build_id(path, all, 0, 14, 1.0, 100, "world");
252 assert_eq!(base, derive_build_id(path, all, 0, 14, 1.0, 100, "world"), "stable");
253 for other in [
254 derive_build_id(path, all, 0, 14, 2.0, 100, "world"),
255 derive_build_id(path, all, 0, 14, 1.0, 101, "world"),
256 derive_build_id(path, all, 0, 14, 1.0, 100, "california"),
257 derive_build_id(
258 std::path::Path::new("other.osm.pbf"),
259 all,
260 0,
261 14,
262 1.0,
263 100,
264 "world",
265 ),
266 ] {
267 assert_ne!(base, other, "a changed input should change the id");
268 }
269 }
270
271 /// A missing or stale graph dir fails HERE, in seconds — not 43 minutes
272 /// into stage A when `traffic` first reads it. That is the world-build
273 /// failure this exists for: an empty graph dir with no `metadata.bin`.
274 #[test]
275 fn a_missing_graph_fails_before_stage_a() {
276 use osm_ingest::region::Region;
277 let missing = std::path::Path::new("no_such_graph_dir_xyz");
278 let err = check_graph_dir(missing, Region::World).expect_err("missing dir must fail");
279 assert!(err.contains("cannot read"), "{err}");
280 // An empty dir: no metadata.bin is the reported failure.
281 let dir = std::env::temp_dir()
282 .join(format!("mamaps_graphcheck_{}", std::process::id()));
283 let _ = std::fs::remove_dir_all(&dir);
284 std::fs::create_dir_all(&dir).unwrap();
285 let err = check_graph_dir(&dir, Region::World).expect_err("empty dir must fail");
286 assert!(err.contains("metadata.bin"), "{err}");
287 // A bad magic: not a graph dir at all.
288 std::fs::write(dir.join("metadata.bin"), vec![0u8; 40]).unwrap();
289 let err = check_graph_dir(&dir, Region::World).expect_err("bad magic must fail");
290 assert!(err.contains("MARG"), "{err}");
291 let _ = std::fs::remove_dir_all(&dir);
292 }
293}