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

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

main_part1.rs457 lines · 20.2 KiBRaw
1fn run(
2 input: &std::path::Path,
3 out: &std::path::Path,
4 run: &RunSettings,
5) -> Result<(), String> {
6 let (layers, min_zoom, max_zoom, simplification) =
7 (schema::Layers::all(), 0u8, DEFAULT_MAX_ZOOM, tiler::DEFAULT_SIMPLIFICATION);
8 println!("reading {}", input.display());
9 println!("region: {}", run.region.name());
10 // Features are spilled here rather than held: it was 4.9 GB of a measured 10.03 GB California
11 // peak, and nothing reads them until the tiler does.
12 let spill = out.with_extension("features.tmp");
13 // Named scratch (the pass-3 coordinate table: 83 GB on a planet) goes next to the spills,
14 // not in the system temp dir; `MAPS_SCRATCH_DIR` overrides. Such files are unlinked as soon
15 // as they are open, so a killed build leaves none of them behind.
16 osm_ingest::mem::set_scratch_dir(spill.parent().map(|p| {
17 if p.as_os_str().is_empty() { std::path::PathBuf::from(".") } else { p.to_path_buf() }
18 }));
19 check_required(&run.coastline, "--coastline")?;
20 check_required(&run.transit_routes, "--transit-routes")?;
21 check_required(&run.dem, "--dem")?;
22
23 // --- unified pre-stages -------------------------------------------------
24 //
25 // `--build-graph-to` / `--build-poi-to` fold the two sidecar builds into
26 // this process: same thread pool (no oversubscription from two binaries
27 // each claiming the box), one shared blob scan via the graph's sidecar,
28 // and the region filter applied once, consistently, in all three places.
29 // Without them `--graph` must already exist and is validated below.
30 let graph_dir: std::path::PathBuf = if let Some(dir) = run.build_graph_to.as_ref() {
31 println!("building the routing graph in-process -> {}", dir.display());
32 let opts = osm_ingest::graph_build::Options { within_way_chains: true, bbox: run.region.bbox(), ..Default::default() };
33 osm_ingest::graph_build::build_with(input, dir, opts)
34 .map_err(|e| format!("graph build: {e}"))?;
35 let ov = osm_ingest::overlay::build(dir, &dir.join("overlay.bin"))
36 .map_err(|e| format!("overlay build: {e}"))?;
37 println!("highway overlay: {} nodes, {} edges, {} bytes", ov.nodes, ov.edges, ov.bytes);
38 dir.clone()
39 } else {
40 check_required(&run.graph, "--graph")?;
41 run.graph.clone()
42 };
43 if let Some(dir) = run.build_poi_to.as_ref() {
44 println!("building the POI sidecars in-process -> {}", dir.display());
45 let poi_index = dir.join("poi_index.bin");
46 osm_ingest::poi_build::build_with(
47 osm_ingest::poi_build::Paths {
48 input,
49 geojson: &dir.join("poi.geojsonseq"),
50 names: &dir.join("poi_names.bin"),
51 index: &poi_index,
52 attrs: &dir.join("poi_attrs.bin"),
53 spatial: &dir.join("poi_spatial.bin"),
54 name_index: &dir.join("poi_name_index.bin"),
55 region: &dir.join("poi_region.bin"),
56 },
57 run.region.bbox(),
58 )
59 .map_err(|e| format!("poi build: {e}"))?;
60 }
61
62 // The graph is validated HERE, before stage A — not 43 minutes in when
63 // `traffic` tries to read it. This is the failure the world build hit:
64 // an empty graph dir with no `metadata.bin`, paid for in full.
65 //
66 // With `--graph-ready-file` and the graph not yet ready, validation moves to the gate: it
67 // runs the moment the ready file appears, before the first stage that reads the graph.
68 let gate = GraphGate::new(graph_dir.clone(), run.graph_ready_file.clone(), run.region);
69 if gate.ready_now() {
70 gate.wait()?;
71 } else {
72 println!(
73 "graph not ready yet: starting without it, will wait for {} before the junction layer",
74 run.graph_ready_file.as_ref().expect("only without the flag is the graph always ready").display(),
75 );
76 }
77
78 // The run's gapless phase clock. Opens in `"other"`, so the setup above (graph/POI builds,
79 // validation) books as overhead; every major stage below switches it, and `finish` emits the
80 // single `TIMING` line before the summary prints.
81 let mut timer = crate::timing::PhaseTimer::start("tiles");
82 let (store, stats, mut region_links, country_populations) = extract::extract(extract::ExtractArgs {
83 input,
84 layers,
85 coastline: &run.coastline,
86 transit_routes: &run.transit_routes,
87 graph: &gate,
88 spill_path: &spill,
89 region: run.region.bbox(),
90 timer: &mut timer,
91 })
92 .map_err(|e| format!("{}: {e}", input.display()))?;
93 // The containment fallback: member-less place labels gain links from the whole-polygon
94 // shapes above, never overwriting a member link. Runs here — after the store is sealed
95 // and before the tiler reads the map — because only whole rings answer containment.
96 // It also assigns country label start zooms from footprint × headcount (same pass,
97 // footprints in hand).
98 let mut country_zooms: std::collections::HashMap<u64, u8> = std::collections::HashMap::new();
99 timer.switch("region-fallback");
100 match crate::extract_fallback::extend_region_links_with(
101 &store,
102 &mut region_links,
103 &mut country_zooms,
104 &country_populations,
105 ) {
106 Ok(fallback) => {
107 if fallback.places_total > 0 {
108 println!(
109 " place-label -> boundary links: {} place(s), {} member-linked, {} fallback-linked, {} missed",
110 fallback.places_total,
111 fallback.member_linked,
112 fallback.fallback_linked,
113 fallback.fallback_missed,
114 );
115 for (kind, total, linked) in &fallback.per_kind {
116 let rate = *linked as f64 / (*total).max(1) as f64 * 100.0;
117 println!(" {kind}: {linked}/{total} ({rate:.0}%)");
118 }
119 }
120 if fallback.country_zooms > 0 {
121 println!(
122 " country label zooms: {} countr{} scored by footprint x headcount",
123 fallback.country_zooms,
124 if fallback.country_zooms == 1 { "y" } else { "ies" },
125 );
126 }
127 }
128 Err(e) => return Err(format!("region fallback: {e}")),
129 }
130 println!(
131 "classified {} way(s), {} relation(s) and {} node(s) -> {} feature(s), {} node(s) resolved",
132 stats.ways_classified,
133 stats.relations_classified,
134 stats.nodes_classified,
135 stats.features,
136 stats.nodes_needed,
137 );
138 if stats.geometry_failed > 0 {
139 // Expected at an extract's cut edges, and worth reporting because a large count means
140 // something else.
141 println!(" {} classified element(s) produced no geometry", stats.geometry_failed);
142 }
143 if stats.land_polygons > 0 {
144 println!(" including {} prepared land polygon(s)", stats.land_polygons);
145 }
146 if stats.transit_routes > 0 {
147 println!(" including {} coloured transit route(s) from GTFS", stats.transit_routes);
148 }
149 if stats.traffic_segments > 0 {
150 println!(
151 " including {} drivable component segment(s) for the traffic layer",
152 stats.traffic_segments,
153 );
154 }
155 if stats.junction_connectors > 0 {
156 println!(
157 " including {} lane connector(s) for the junction layer",
158 stats.junction_connectors,
159 );
160 }
161 if stats.corridor_promotions > 0 {
162 println!(
163 " {} road way(s) pulled to their corridor's zoom",
164 stats.corridor_promotions,
165 );
166 }
167 if stats.lanes_inherited > 0 {
168 println!(
169 " {} untagged road way(s) took a lane count from a neighbour",
170 stats.lanes_inherited,
171 );
172 }
173
174 // The build id identifies the *data*: change the input and every reader has to drop its
175 // cache. Derived rather than asked for, so a forgotten input cannot silently republish
176 // under the old one. The region is part of the id: a california and a world
177 // build from the same pbf are different archives.
178 tiler::V8_BODIES.store(run.v8_bodies, std::sync::atomic::Ordering::Relaxed);
179 let digests = input_digests(input, &run.coastline, &graph_dir, &run.transit_routes, &run.dem)?;
180 let build_id = derive_build_id(
181 &digests,
182 layers,
183 min_zoom,
184 max_zoom,
185 simplification,
186 stats.features,
187 run.region.name(),
188 run.v8_bodies,
189 );
190
191 // The DEM heightmap dataset. Loaded here (this is where I/O belongs) and
192 // handed to the tiler, which samples one grid per output tile into the body's heightmap section.
193 timer.switch("dem-load");
194 let dem = dem::Dem::load(&run.dem).map_err(|e| e.to_string())?;
195 println!("loaded the DEM dataset at {}", run.dem.display());
196
197 let settings = tiler::Settings {
198 build_id,
199 // Beside the archive, as the feature spill is. One zoom at a time, removed as each finishes.
200 scratch: scratch_path(out),
201 dem,
202 region_links,
203 country_zooms,
204 // Honour the operator's backend choice: `MAPS_ANON_SPILL=1` (or any truthy value) stages
205 // the tile-chunk spill in pagefile-backed anonymous memory instead of the scratch file
206 // beside the output. Same chunks, same offsets, same bytes -- the merge reads through the
207 // same `ChunkReader` either way, so the archive is identical and `-Verify` still holds.
208 //
209 // This matters because the tiler's own budget gate (`plan_chunk_spill`) answers from the
210 // commit limit, not from this variable: on a box with a generous pagefile it picks anon
211 // for an 11.9 M-feature store even when the operator knows the commit headroom is ~50 GB
212 // and wants files. The variable is the override; the gate stays the default.
213 force_chunk_spill_file: std::env::var("MAPS_ANON_SPILL")
214 .map(|v| {
215 let v = v.trim().to_ascii_lowercase();
216 !(v == "1" || v == "true" || v == "yes")
217 })
218 .unwrap_or(false),
219 };
220 // Streamed straight to `out`: the archive's data section is tens of GB on a planet, and
221 // holding it in a `Vec<u8>` beside the merge's own peak is the OOM after z14 merges.
222 // `build_to_path` runs the identical zoom loop and assembles the identical
223 // header/dictionary/root/leaves/data layout through `finish_to_path`.
224 let per_zoom = tiler::build_to_path(&store, &settings, out, &mut timer).map_err(|e| e.to_string())?;
225 tiler::check_not_empty(&per_zoom).map_err(|e| e.to_string())?;
226 // The spill is scratch. Removed on success; left behind on failure, where it is evidence.
227 let _ = std::fs::remove_file(&spill);
228 // After the last work, before the summary prints: closes the final subphase and emits `TIMING`.
229 timer.finish();
230
231 println!(
232 "\n{:<6}{:>10}{:>12}{:>12}{:>10}{:>12}{:>8}{:>8}{:>8}{:>8}",
233 "zoom", "tiles", "features", "points", "dropped", "bytes", "map_s", "merge_s", "enc_s",
234 "app_s",
235 );
236 for z in &per_zoom {
237 println!(
238 "z{:<5}{:>10}{:>12}{:>12}{:>10}{:>12}{:>8.1}{:>8.1}{:>8.1}{:>8.1}",
239 z.zoom,
240 z.tiles,
241 z.features,
242 z.points,
243 z.dropped,
244 z.bytes,
245 z.map_ms as f64 / 1000.0,
246 z.merge_ms as f64 / 1000.0,
247 z.encode_ms as f64 / 1000.0,
248 z.append_ms as f64 / 1000.0,
249 );
250 // The machine-readable twin of the text row above: integer milliseconds, so the
251 // columns close exactly where the 0.1 s-rounded text does not.
252 crate::timing::emit_zoom_row(
253 z.zoom, z.tiles, z.features, z.points, z.dropped, z.bytes, z.map_ms, z.merge_ms,
254 z.encode_ms, z.append_ms,
255 );
256 }
257 // The four phase columns summed, because which of them dominates is the only thing that says
258 // whether more cores would help: map and encode run on the pool, merge and append do not.
259 let (map, merge, encode, append) = per_zoom.iter().fold((0u64, 0u64, 0u64, 0u64), |a, z| {
260 (a.0 + z.map_ms, a.1 + z.merge_ms, a.2 + z.encode_ms, a.3 + z.append_ms)
261 });
262 let serial = (merge + append) as f64;
263 let total = (map + merge + encode + append).max(1) as f64;
264 // What coalescing removed. The `features` column above is counted in `push`, during the map
265 // phase and therefore BEFORE the merge that coalescing runs after, so it reports what OSM
266 // yielded rather than what was written -- which is the number the map phase's cost tracks. This
267 // line is what was actually encoded.
268 let lines = per_zoom.iter().fold(coalesce::Stats::default(), |mut a, z| {
269 a.add(z.lines);
270 a
271 });
272 if lines.features_before > lines.features_after {
273 println!(
274 " coalesced: {} line feature(s) -> {} ({:.0}x), {} part(s) -> {} ({:.1}x)",
275 lines.features_before,
276 lines.features_after,
277 lines.features_before as f64 / lines.features_after.max(1) as f64,
278 lines.parts_before,
279 lines.parts_after,
280 lines.parts_before as f64 / lines.parts_after.max(1) as f64,
281 );
282 }
283 // How close the archive came to the 65,535-feature cap on one tile-layer. Printed rather than
284 // asserted because the answer is what decides whether the field has to widen, and widening it is
285 // a `FORMAT_VERSION` bump and a matching renderer change.
286 let widest = tiler::widest_layers();
287 if !widest.is_empty() {
288 let dict = tilecodec::mamaps::dict::Dictionary::schema();
289 let worst = widest.iter().map(|(_, n)| *n).max().unwrap_or(0);
290 let named: Vec<String> = widest
291 .iter()
292 .map(|(id, n)| {
293 let name = dict.layer_name(*id).unwrap_or("?");
294 format!("{name} {n}")
295 })
296 .collect();
297 println!(
298 " widest tile-layer: {} (cap {}, {:.0}% used)",
299 named.join(", "),
300 u16::MAX,
301 worst as f64 / u16::MAX as f64 * 100.0,
302 );
303 }
304 println!(
305 "total map {:.1}s merge {:.1}s encode {:.1}s append {:.1}s ({:.0}% of tiling is serial)",
306 map as f64 / 1000.0,
307 merge as f64 / 1000.0,
308 encode as f64 / 1000.0,
309 append as f64 / 1000.0,
310 serial / total * 100.0,
311 );
312 // The archive was streamed straight to `out` (`build_to_path`), so its length is read
313 // back from the file rather than from a buffer that no longer exists.
314 let archive_len = std::fs::metadata(out)
315 .map(|m| m.len())
316 .map_err(|e| format!("cannot stat {}: {e}", out.display()))?;
317 // The header's id: the seed above folded with the archive's tile digest by the writer.
318 let header_id = read_header_build_id(out)?;
319 crate::dem::DEM_STATS.report();
320 println!(
321 "\nwrote {} ({archive_len} bytes, build_id {header_id:#018x}, seed {build_id:#018x})",
322 out.display(),
323 );
324 Ok(())
325}
326
327/// Where the tiler parks one zoom's chunks while it merges them.
328///
329/// Beside the archive, as `<out>.tilechunks`, matching where the feature spill is placed. Appended
330/// to the whole file name rather than replacing an extension, so `world.mamaps` and `world.tmp`
331/// cannot collide on one path.
332fn scratch_path(out: &std::path::Path) -> PathBuf {
333 let mut p = out.as_os_str().to_owned();
334 p.push(".tilechunks");
335 PathBuf::from(p)
336}
337
338/// The build id in a finished archive's header.
339fn read_header_build_id(out: &std::path::Path) -> Result<u64, String> {
340 use std::io::Read;
341 let mut head = vec![0u8; tilecodec::mamaps::header::HEADER_LEN];
342 std::fs::File::open(out)
343 .and_then(|mut f| f.read_exact(&mut head))
344 .map_err(|e| format!("cannot read back {}: {e}", out.display()))?;
345 tilecodec::mamaps::header::Header::parse(&head)
346 .map(|h| h.build_id)
347 .map_err(|e| format!("cannot parse {}: {e}", out.display()))
348}
349
350/// Content fingerprints of every file the archive is built from ([`input_digests`]).
351#[derive(Debug, Clone, Copy, PartialEq, Eq)]
352pub(crate) struct InputDigests {
353 pub pbf: u64,
354 pub coastline: u64,
355 pub graph: u64,
356 pub transit_routes: u64,
357 pub dem: u64,
358}
359
360/// Fingerprint every input by content ([`osm_ingest::fingerprint`]): never a path or an mtime.
361///
362/// - `.osm.pbf`: length + first and last 4 MiB. The first blob is the `OSMHeader` block (with the
363/// replication timestamp and sequence number), always well inside the first 4 MiB.
364/// - coastline: the `.shp` (the only part of the shapefile read).
365/// - graph: every regular file in the directory, by relative name (dot-files such as
366/// `planet_build.sh`'s `.ready` signal skipped) -- metadata, nodes, edges, lanes, names, the
367/// overlay outputs and `blob_kinds.bin`.
368/// - transit routes and DEM: length + first and last 4 MiB.
369pub(crate) fn input_digests(
370 pbf: &std::path::Path,
371 coastline: &std::path::Path,
372 graph: &std::path::Path,
373 transit_routes: &std::path::Path,
374 dem: &std::path::Path,
375) -> Result<InputDigests, String> {
376 use osm_ingest::fingerprint::{dir_fingerprint, file_fingerprint};
377 let file = |p: &std::path::Path| {
378 file_fingerprint(p).map_err(|e| format!("cannot fingerprint {}: {e}", p.display()))
379 };
380 Ok(InputDigests {
381 pbf: file(pbf)?,
382 coastline: file(coastline)?,
383 graph: dir_fingerprint(graph)
384 .map_err(|e| format!("cannot fingerprint {}: {e}", graph.display()))?,
385 transit_routes: file(transit_routes)?,
386 dem: file(dem)?,
387 })
388}
389
390/// The generator's build id: the seed the archive writer then mixes with the digest of every tile
391/// it holds (`Options::build_id_from_content`, `tilecodec::mamaps::write::content_build_id`), so
392/// the header's id is
393///
394/// ```text
395/// header build_id = content_build_id(derive_build_id(..), tile digest)
396/// tile digest = fold over every appended tile, in order, of (tile id, stored length,
397/// FNV-1a 64 of the stored body)
398/// ```
399///
400/// The seed is FNV-1a 64 over, in order: the tool revision tag `mamaps_build/18`; the archive
401/// format version; the region name; the five input fingerprints ([`InputDigests`]: pbf,
402/// coastline, graph, transit routes, DEM); the layer flags and zoom range; the simplification
403/// factor; the stage-A feature count; the schema table's kind count; and the body encoding (v10,
404/// or v8 under `--v8-bodies`).
405///
406/// Nothing environmental goes in -- no path, mtime, host, user or clock -- so identical inputs and
407/// identical code give an identical id on any machine; a changed input changes the seed, and any
408/// changed tile changes the digest. Readers key caches on this id, so both halves err on the side
409/// of changing it.
410#[allow(clippy::too_many_arguments)]
411pub(crate) fn derive_build_id(
412 inputs: &InputDigests,
413 layers: schema::Layers,
414 min_zoom: u8,
415 max_zoom: u8,
416 simplification: f64,
417 features: u64,
418 region: &str,
419 v8_bodies: bool,
420) -> u64 {
421 let mut h = osm_ingest::fingerprint::Fnv::default();
422 // Revision 17 fixed the missing lane byte in mixed landtype Road records (#821).
423 // Revision 18: the id is content-derived (input fingerprints + tile digest), no longer the
424 // input's path and mtime.
425 h.eat(b"mamaps_build/18");
426 h.eat(&[tilecodec::mamaps::header::FORMAT_VERSION]);
427 h.eat(region.as_bytes());
428 h.eat(&[0]);
429 for digest in [inputs.pbf, inputs.coastline, inputs.graph, inputs.transit_routes, inputs.dem] {
430 h.eat_u64(digest);
431 }
432 h.eat(&[
433 u8::from(layers.landtype),
434 u8::from(layers.buildings),
435 u8::from(layers.roads),
436 u8::from(layers.boundaries),
437 u8::from(layers.places),
438 u8::from(layers.poi),
439 u8::from(layers.transit),
440 u8::from(layers.traffic),
441 u8::from(layers.junction),
442 min_zoom,
443 max_zoom,
444 ]);
445 h.eat(&simplification.to_le_bytes());
446 h.eat_u64(features);
447 // The schema table's own version, so a remapped kind invalidates every cache even when the
448 // input has not moved.
449 h.eat_u64(tilecodec::mamaps::dict::KINDS.len() as u64);
450 h.eat(if v8_bodies { b"bodies/v8" } else { b"bodies/v10" });
451 // Planet-size knobs: only hashed when set, so a default build keeps its id.
452 let size = tiler::size_opts();
453 if !size.is_default() {
454 h.eat(size.tag().as_bytes());
455 }
456 h.finish()
457}