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

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

main_part1.rs373 lines · 16.0 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 check_required(&run.coastline, "--coastline")?;
14 check_required(&run.transit_routes, "--transit-routes")?;
15 check_required(&run.dem, "--dem")?;
16
17 // --- unified pre-stages -------------------------------------------------
18 //
19 // `--build-graph-to` / `--build-poi-to` fold the two sidecar builds into
20 // this process: same thread pool (no oversubscription from two binaries
21 // each claiming the box), one shared blob scan via the graph's sidecar,
22 // and the region filter applied once, consistently, in all three places.
23 // Without them `--graph` must already exist and is validated below.
24 let graph_dir: std::path::PathBuf = if let Some(dir) = run.build_graph_to.as_ref() {
25 println!("building the routing graph in-process -> {}", dir.display());
26 let mut opts = osm_ingest::graph_build::Options::default();
27 opts.within_way_chains = true;
28 opts.bbox = run.region.bbox();
29 osm_ingest::graph_build::build_with(input, dir, opts)
30 .map_err(|e| format!("graph build: {e}"))?;
31 let ov = osm_ingest::overlay::build(dir, &dir.join("overlay.bin"))
32 .map_err(|e| format!("overlay build: {e}"))?;
33 println!("highway overlay: {} nodes, {} edges, {} bytes", ov.nodes, ov.edges, ov.bytes);
34 dir.clone()
35 } else {
36 check_required(&run.graph, "--graph")?;
37 run.graph.clone()
38 };
39 if let Some(dir) = run.build_poi_to.as_ref() {
40 println!("building the POI sidecars in-process -> {}", dir.display());
41 let poi_index = dir.join("poi_index.bin");
42 osm_ingest::poi_build::build_with(
43 input,
44 &dir.join("poi.geojsonseq"),
45 &dir.join("poi_names.bin"),
46 &poi_index,
47 &dir.join("poi_attrs.bin"),
48 &dir.join("poi_spatial.bin"),
49 &dir.join("poi_name_index.bin"),
50 run.region.bbox(),
51 )
52 .map_err(|e| format!("poi build: {e}"))?;
53 }
54
55 // The graph is validated HERE, before stage A — not 43 minutes in when
56 // `traffic` tries to read it. This is the failure the world build hit:
57 // an empty graph dir with no `metadata.bin`, paid for in full.
58 check_graph_dir(&graph_dir, run.region)?;
59
60 // The run's gapless phase clock. Opens in `"other"`, so the setup above (graph/POI builds,
61 // validation) books as overhead; every major stage below switches it, and `finish` emits the
62 // single `TIMING` line before the summary prints.
63 let mut timer = crate::timing::PhaseTimer::start("tiles");
64 let (store, stats, mut region_links, country_populations) = extract::extract(
65 input,
66 layers,
67 &run.coastline,
68 &run.transit_routes,
69 &graph_dir,
70 &spill,
71 run.region.bbox(),
72 &mut timer,
73 )
74 .map_err(|e| format!("{}: {e}", input.display()))?;
75 // The containment fallback: member-less place labels gain links from the whole-polygon
76 // shapes above, never overwriting a member link. Runs here — after the store is sealed
77 // and before the tiler reads the map — because only whole rings answer containment.
78 // It also assigns country label start zooms from footprint × headcount (same pass,
79 // footprints in hand).
80 let mut country_zooms: std::collections::HashMap<u64, u8> = std::collections::HashMap::new();
81 timer.switch("region-fallback");
82 match crate::extract_fallback::extend_region_links_with(
83 &store,
84 &mut region_links,
85 &mut country_zooms,
86 &country_populations,
87 ) {
88 Ok(fallback) => {
89 if fallback.places_total > 0 {
90 println!(
91 " place-label -> boundary links: {} place(s), {} member-linked, {} fallback-linked, {} missed",
92 fallback.places_total,
93 fallback.member_linked,
94 fallback.fallback_linked,
95 fallback.fallback_missed,
96 );
97 for (kind, total, linked) in &fallback.per_kind {
98 let rate = *linked as f64 / (*total).max(1) as f64 * 100.0;
99 println!(" {kind}: {linked}/{total} ({rate:.0}%)");
100 }
101 }
102 if fallback.country_zooms > 0 {
103 println!(
104 " country label zooms: {} countr{} scored by footprint x headcount",
105 fallback.country_zooms,
106 if fallback.country_zooms == 1 { "y" } else { "ies" },
107 );
108 }
109 }
110 Err(e) => return Err(format!("region fallback: {e}")),
111 }
112 println!(
113 "classified {} way(s), {} relation(s) and {} node(s) -> {} feature(s), {} node(s) resolved",
114 stats.ways_classified,
115 stats.relations_classified,
116 stats.nodes_classified,
117 stats.features,
118 stats.nodes_needed,
119 );
120 if stats.geometry_failed > 0 {
121 // Expected at an extract's cut edges, and worth reporting because a large count means
122 // something else.
123 println!(" {} classified element(s) produced no geometry", stats.geometry_failed);
124 }
125 if stats.land_polygons > 0 {
126 println!(" including {} prepared land polygon(s)", stats.land_polygons);
127 }
128 if stats.transit_routes > 0 {
129 println!(" including {} coloured transit route(s) from GTFS", stats.transit_routes);
130 }
131 if stats.traffic_segments > 0 {
132 println!(
133 " including {} drivable component segment(s) for the traffic layer",
134 stats.traffic_segments,
135 );
136 }
137 if stats.junction_connectors > 0 {
138 println!(
139 " including {} lane connector(s) for the junction layer",
140 stats.junction_connectors,
141 );
142 }
143 if stats.corridor_promotions > 0 {
144 println!(
145 " {} road way(s) pulled to their corridor's zoom",
146 stats.corridor_promotions,
147 );
148 }
149 if stats.lanes_inherited > 0 {
150 println!(
151 " {} untagged road way(s) took a lane count from a neighbour",
152 stats.lanes_inherited,
153 );
154 }
155
156 // The build id identifies the *data*: change the input and every reader has to drop its
157 // cache. Derived rather than asked for, so a forgotten input cannot silently republish
158 // under the old one. The region is part of the id: a california and a world
159 // build from the same pbf are different archives.
160 let build_id = derive_build_id(
161 input,
162 layers,
163 min_zoom,
164 max_zoom,
165 simplification,
166 stats.features,
167 run.region.name(),
168 );
169
170 // The DEM heightmap dataset. Loaded here (this is where I/O belongs) and
171 // handed to the tiler, which samples one grid per output tile into the body's heightmap section.
172 timer.switch("dem-load");
173 let dem = dem::Dem::load(&run.dem).map_err(|e| e.to_string())?;
174 println!("loaded the DEM dataset at {}", run.dem.display());
175
176 let settings = tiler::Settings {
177 build_id,
178 // Beside the archive, as the feature spill is. One zoom at a time, removed as each finishes.
179 scratch: scratch_path(out),
180 dem,
181 region_links,
182 country_zooms,
183 // Honour the operator's backend choice: `MAPS_ANON_SPILL=1` (or any truthy value) stages
184 // the tile-chunk spill in pagefile-backed anonymous memory instead of the scratch file
185 // beside the output. Same chunks, same offsets, same bytes -- the merge reads through the
186 // same `ChunkReader` either way, so the archive is identical and `-Verify` still holds.
187 //
188 // This matters because the tiler's own budget gate (`plan_chunk_spill`) answers from the
189 // commit limit, not from this variable: on a box with a generous pagefile it picks anon
190 // for an 11.9 M-feature store even when the operator knows the commit headroom is ~50 GB
191 // and wants files. The variable is the override; the gate stays the default.
192 force_chunk_spill_file: std::env::var("MAPS_ANON_SPILL")
193 .map(|v| {
194 let v = v.trim().to_ascii_lowercase();
195 !(v == "1" || v == "true" || v == "yes")
196 })
197 .unwrap_or(false),
198 };
199 // Streamed straight to `out`: the archive's data section is tens of GB on a planet, and
200 // holding it in a `Vec<u8>` beside the merge's own peak is the OOM after z14 merges.
201 // `build_to_path` runs the identical zoom loop and assembles the identical
202 // header/dictionary/root/leaves/data layout through `finish_to_path`.
203 let per_zoom = tiler::build_to_path(&store, &settings, out, &mut timer).map_err(|e| e.to_string())?;
204 tiler::check_not_empty(&per_zoom).map_err(|e| e.to_string())?;
205 // The spill is scratch. Removed on success; left behind on failure, where it is evidence.
206 let _ = std::fs::remove_file(&spill);
207 // After the last work, before the summary prints: closes the final subphase and emits `TIMING`.
208 timer.finish();
209
210 println!(
211 "\n{:<6}{:>10}{:>12}{:>12}{:>10}{:>12}{:>8}{:>8}{:>8}{:>8}",
212 "zoom", "tiles", "features", "points", "dropped", "bytes", "map_s", "merge_s", "enc_s",
213 "app_s",
214 );
215 for z in &per_zoom {
216 println!(
217 "z{:<5}{:>10}{:>12}{:>12}{:>10}{:>12}{:>8.1}{:>8.1}{:>8.1}{:>8.1}",
218 z.zoom,
219 z.tiles,
220 z.features,
221 z.points,
222 z.dropped,
223 z.bytes,
224 z.map_ms as f64 / 1000.0,
225 z.merge_ms as f64 / 1000.0,
226 z.encode_ms as f64 / 1000.0,
227 z.append_ms as f64 / 1000.0,
228 );
229 // The machine-readable twin of the text row above: integer milliseconds, so the
230 // columns close exactly where the 0.1 s-rounded text does not.
231 crate::timing::emit_zoom_row(
232 z.zoom, z.tiles, z.features, z.points, z.dropped, z.bytes, z.map_ms, z.merge_ms,
233 z.encode_ms, z.append_ms,
234 );
235 }
236 // The four phase columns summed, because which of them dominates is the only thing that says
237 // whether more cores would help: map and encode run on the pool, merge and append do not.
238 let (map, merge, encode, append) = per_zoom.iter().fold((0u64, 0u64, 0u64, 0u64), |a, z| {
239 (a.0 + z.map_ms, a.1 + z.merge_ms, a.2 + z.encode_ms, a.3 + z.append_ms)
240 });
241 let serial = (merge + append) as f64;
242 let total = (map + merge + encode + append).max(1) as f64;
243 // What coalescing removed. The `features` column above is counted in `push`, during the map
244 // phase and therefore BEFORE the merge that coalescing runs after, so it reports what OSM
245 // yielded rather than what was written -- which is the number the map phase's cost tracks. This
246 // line is what was actually encoded.
247 let lines = per_zoom.iter().fold(coalesce::Stats::default(), |mut a, z| {
248 a.add(z.lines);
249 a
250 });
251 if lines.features_before > lines.features_after {
252 println!(
253 " coalesced: {} line feature(s) -> {} ({:.0}x), {} part(s) -> {} ({:.1}x)",
254 lines.features_before,
255 lines.features_after,
256 lines.features_before as f64 / lines.features_after.max(1) as f64,
257 lines.parts_before,
258 lines.parts_after,
259 lines.parts_before as f64 / lines.parts_after.max(1) as f64,
260 );
261 }
262 // How close the archive came to the 65,535-feature cap on one tile-layer. Printed rather than
263 // asserted because the answer is what decides whether the field has to widen, and widening it is
264 // a `FORMAT_VERSION` bump and a matching renderer change.
265 let widest = tiler::widest_layers();
266 if !widest.is_empty() {
267 let dict = tilecodec::mamaps::dict::Dictionary::schema();
268 let worst = widest.iter().map(|(_, n)| *n).max().unwrap_or(0);
269 let named: Vec<String> = widest
270 .iter()
271 .map(|(id, n)| {
272 let name = dict.layer_name(*id).unwrap_or("?");
273 format!("{name} {n}")
274 })
275 .collect();
276 println!(
277 " widest tile-layer: {} (cap {}, {:.0}% used)",
278 named.join(", "),
279 u16::MAX,
280 worst as f64 / u16::MAX as f64 * 100.0,
281 );
282 }
283 println!(
284 "total map {:.1}s merge {:.1}s encode {:.1}s append {:.1}s ({:.0}% of tiling is serial)",
285 map as f64 / 1000.0,
286 merge as f64 / 1000.0,
287 encode as f64 / 1000.0,
288 append as f64 / 1000.0,
289 serial / total * 100.0,
290 );
291 // The archive was streamed straight to `out` (`build_to_path`), so its length is read
292 // back from the file rather than from a buffer that no longer exists.
293 let archive_len = std::fs::metadata(out)
294 .map(|m| m.len())
295 .map_err(|e| format!("cannot stat {}: {e}", out.display()))?;
296 println!(
297 "\nwrote {} ({archive_len} bytes, build_id {build_id:#018x})",
298 out.display(),
299 );
300 Ok(())
301}
302
303/// Where the tiler parks one zoom's chunks while it merges them.
304///
305/// Beside the archive, as `<out>.tilechunks`, matching where the feature spill is placed. Appended
306/// to the whole file name rather than replacing an extension, so `world.mamaps` and `world.tmp`
307/// cannot collide on one path.
308fn scratch_path(out: &std::path::Path) -> PathBuf {
309 let mut p = out.as_os_str().to_owned();
310 p.push(".tilechunks");
311 PathBuf::from(p)
312}
313
314/// Hash the inputs that decide what an archive contains.
315///
316/// The input's **length and modification time** rather than its bytes: digesting 1.3 GB to decide a
317/// cache key would double the build's I/O for a number that only has to change when the data does.
318/// A rebuild from an unchanged file therefore keeps its id, which is what makes a byte-identical
319/// rebuild byte-identical.
320///
321/// The leading generator revision has to be bumped whenever this crate changes what it *puts* in an
322/// archive for the same input, because readers cache byte ranges under `(url, build_id)` and the
323/// URL is deliberately stable across republishes. A device with a warm cache would otherwise keep
324/// serving the old archive's bytes forever. See `library/map/.../tile/source.rs`.
325fn derive_build_id(
326 input: &std::path::Path,
327 layers: schema::Layers,
328 min_zoom: u8,
329 max_zoom: u8,
330 simplification: f64,
331 features: u64,
332 region: &str,
333) -> u64 {
334 let mut h = 0xcbf2_9ce4_8422_2325u64;
335 let mut eat = |bytes: &[u8]| {
336 for &b in bytes {
337 h ^= b as u64;
338 h = h.wrapping_mul(0x100_0000_01b3);
339 }
340 };
341 // Revision 17 fixes the missing lane byte in mixed landtype Road records (#821).
342 // The corrected rebuild must invalidate cached ranges from the malformed archive.
343 eat(b"mamaps_build/17");
344 eat(region.as_bytes());
345 eat(input.to_string_lossy().as_bytes());
346 if let Ok(meta) = std::fs::metadata(input) {
347 eat(&meta.len().to_le_bytes());
348 if let Ok(time) = meta.modified() {
349 if let Ok(since) = time.duration_since(std::time::UNIX_EPOCH) {
350 eat(&since.as_secs().to_le_bytes());
351 }
352 }
353 }
354 eat(&[
355 u8::from(layers.landtype),
356 u8::from(layers.buildings),
357 u8::from(layers.roads),
358 u8::from(layers.boundaries),
359 u8::from(layers.places),
360 u8::from(layers.poi),
361 u8::from(layers.transit),
362 u8::from(layers.traffic),
363 u8::from(layers.junction),
364 min_zoom,
365 max_zoom,
366 ]);
367 eat(&simplification.to_le_bytes());
368 eat(&features.to_le_bytes());
369 // The schema table's own version, so a remapped kind invalidates every cache even when the
370 // input has not moved.
371 eat(&(tilecodec::mamaps::dict::KINDS.len() as u64).to_le_bytes());
372 h
373}