Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / tile_build / src / pyramid_part4.rs
pyramid_part4.rs329 lines · 12.2 KiBRaw
| 1 | /// `tile_lines` and `tile_polygons` are the same program with a different |
| 2 | /// [`Accept`], so they share one implementation and differ only in the name they |
| 3 | /// print. |
| 4 | pub fn cli_main(name: &str, accept: Accept, argv: &[String]) -> std::process::ExitCode { |
| 5 | use std::io::BufRead; |
| 6 | use std::process::ExitCode; |
| 7 | |
| 8 | let usage = || { |
| 9 | eprintln!("usage: {name} --geojson IN.geojsonseq --out OUT.pmtiles --layer NAME"); |
| 10 | eprintln!(" [--minzoom N] [--maxzoom N] [--simplification F]"); |
| 11 | eprintln!(" [--max-tile-bytes N] [--extent N] [--threads N] [--timing]"); |
| 12 | eprintln!(" [--stream [--spill-dir DIR] [--buckets N]"); |
| 13 | eprintln!(" [--bucket-budget-bytes N] [--max-repartition-depth N]]"); |
| 14 | eprintln!(); |
| 15 | eprintln!(" --stream keep peak memory proportional to the TILE COUNT rather than the"); |
| 16 | eprintln!(" input bytes, by spilling to --spill-dir. Required for a"); |
| 17 | eprintln!(" planet-scale layer; unnecessary for a metro extract. Output is"); |
| 18 | eprintln!(" byte-identical either way."); |
| 19 | }; |
| 20 | |
| 21 | let mut geojson = None; |
| 22 | let mut out = None; |
| 23 | let mut layer = None; |
| 24 | let mut min_zoom = 11u8; |
| 25 | let mut max_zoom = 14u8; |
| 26 | let mut simplification = 1.0f64; |
| 27 | let mut max_tile_bytes = DEFAULT_MAX_TILE_BYTES; |
| 28 | let mut extent = DEFAULT_EXTENT; |
| 29 | let mut stream = false; |
| 30 | let mut timing = false; |
| 31 | let mut spill_dir: Option<String> = None; |
| 32 | let mut limits = StreamLimits::default(); |
| 33 | |
| 34 | let mut i = 0; |
| 35 | while i < argv.len() { |
| 36 | let value = || argv.get(i + 1).cloned(); |
| 37 | match argv[i].as_str() { |
| 38 | "--geojson" => { |
| 39 | geojson = value(); |
| 40 | i += 2; |
| 41 | } |
| 42 | "--out" => { |
| 43 | out = value(); |
| 44 | i += 2; |
| 45 | } |
| 46 | "--layer" => { |
| 47 | layer = value(); |
| 48 | i += 2; |
| 49 | } |
| 50 | "--stream" => { |
| 51 | stream = true; |
| 52 | i += 1; |
| 53 | } |
| 54 | "--spill-dir" => { |
| 55 | spill_dir = value(); |
| 56 | i += 2; |
| 57 | } |
| 58 | // A bad numeric value is fatal rather than falling back to the default: |
| 59 | // silently tiling z11-14 when the caller asked for z0-8 produces an |
| 60 | // archive that looks fine and is wrong. |
| 61 | flag @ ("--minzoom" | "--maxzoom" | "--simplification" | "--max-tile-bytes" |
| 62 | | "--extent" | "--buckets" | "--bucket-budget-bytes" |
| 63 | | "--max-repartition-depth") => { |
| 64 | let Some(raw) = value() else { |
| 65 | eprintln!("{name}: {flag} needs a value"); |
| 66 | return ExitCode::from(2); |
| 67 | }; |
| 68 | let ok = match flag { |
| 69 | "--minzoom" => raw.parse().map(|v| min_zoom = v).is_ok(), |
| 70 | "--maxzoom" => raw.parse().map(|v| max_zoom = v).is_ok(), |
| 71 | "--simplification" => raw.parse().map(|v| simplification = v).is_ok(), |
| 72 | "--max-tile-bytes" => raw.parse().map(|v| max_tile_bytes = v).is_ok(), |
| 73 | "--extent" => raw.parse().map(|v| extent = v).is_ok(), |
| 74 | "--buckets" => raw.parse().map(|v| limits.buckets = v).is_ok(), |
| 75 | "--bucket-budget-bytes" => { |
| 76 | raw.parse().map(|v| limits.bucket_budget_bytes = v).is_ok() |
| 77 | } |
| 78 | _ => raw.parse().map(|v| limits.max_repartition_depth = v).is_ok(), |
| 79 | }; |
| 80 | if !ok { |
| 81 | eprintln!("{name}: {flag} wants a number, got '{raw}'"); |
| 82 | return ExitCode::from(2); |
| 83 | } |
| 84 | i += 2; |
| 85 | } |
| 86 | "--timing" => { |
| 87 | timing = true; |
| 88 | i += 1; |
| 89 | } |
| 90 | "--threads" => { |
| 91 | let Some(raw) = value() else { |
| 92 | eprintln!("{name}: --threads needs a value"); |
| 93 | return ExitCode::from(2); |
| 94 | }; |
| 95 | match par::parse_threads(&raw) { |
| 96 | Ok(n) => par::set_threads(n), |
| 97 | Err(e) => { |
| 98 | eprintln!("{name}: {e}"); |
| 99 | return ExitCode::from(2); |
| 100 | } |
| 101 | } |
| 102 | i += 2; |
| 103 | } |
| 104 | "-h" | "--help" => { |
| 105 | usage(); |
| 106 | return ExitCode::SUCCESS; |
| 107 | } |
| 108 | other => { |
| 109 | eprintln!("{name}: unexpected argument '{other}'"); |
| 110 | usage(); |
| 111 | return ExitCode::from(2); |
| 112 | } |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | let (Some(geojson), Some(out), Some(layer)) = (geojson, out, layer) else { |
| 117 | eprintln!("{name}: --geojson, --out and --layer are all required"); |
| 118 | usage(); |
| 119 | return ExitCode::from(2); |
| 120 | }; |
| 121 | if min_zoom > max_zoom { |
| 122 | eprintln!("{name}: --minzoom {min_zoom} is above --maxzoom {max_zoom}"); |
| 123 | return ExitCode::from(2); |
| 124 | } |
| 125 | // Checked before the parse pass rather than after it: a bad bucket count would |
| 126 | // otherwise fail an hour into a planet run, having already written the whole |
| 127 | // normalized file. |
| 128 | if stream && (!limits.buckets.is_power_of_two() || limits.buckets.trailing_zeros() % 2 != 0) { |
| 129 | eprintln!( |
| 130 | "{name}: --buckets must be a power of four so a bucket is one quadtree cell, \ |
| 131 | got {}", |
| 132 | limits.buckets |
| 133 | ); |
| 134 | return ExitCode::from(2); |
| 135 | } |
| 136 | |
| 137 | let opts = Options { |
| 138 | layer: layer.clone(), |
| 139 | min_zoom, |
| 140 | max_zoom, |
| 141 | extent, |
| 142 | simplification, |
| 143 | max_tile_bytes, |
| 144 | // A planet layer spends minutes to hours per zoom, so the operator gets a bar. |
| 145 | progress: true, |
| 146 | timing, |
| 147 | }; |
| 148 | |
| 149 | // Read a line at a time rather than slurping the file: a planet geojsonseq is tens |
| 150 | // of gigabytes and `read_to_string` keeps all of it resident alongside whatever the |
| 151 | // parse produces, so the two peaks land together for no reason. |
| 152 | let file = match std::fs::File::open(&geojson) { |
| 153 | Ok(f) => f, |
| 154 | Err(e) => { |
| 155 | eprintln!("{name}: cannot read {geojson}: {e}"); |
| 156 | return ExitCode::FAILURE; |
| 157 | } |
| 158 | }; |
| 159 | let mut lines = std::io::BufReader::with_capacity(1 << 20, file).lines(); |
| 160 | |
| 161 | if stream { |
| 162 | let spill_dir = spill_dir.unwrap_or_else(|| format!("{out}.spill")); |
| 163 | // Both temporaries clean themselves up, so a run that dies mid-planet cannot |
| 164 | // strand tens of gigabytes in a directory nobody is watching. |
| 165 | let normalized = crate::spill::NormalizedFile::new( |
| 166 | std::path::Path::new(&spill_dir).join("features.bin"), |
| 167 | ); |
| 168 | let mut writer = match crate::spill::NormalizedWriter::create(normalized.path()) { |
| 169 | Ok(w) => w, |
| 170 | Err(e) => { |
| 171 | eprintln!("{name}: {e}"); |
| 172 | return ExitCode::FAILURE; |
| 173 | } |
| 174 | }; |
| 175 | let mut skipped = 0usize; |
| 176 | let mut n = 0usize; |
| 177 | for line in lines.by_ref() { |
| 178 | let line = match line { |
| 179 | Ok(l) => l, |
| 180 | Err(e) => { |
| 181 | eprintln!("{name}: cannot read {geojson}: {e}"); |
| 182 | return ExitCode::FAILURE; |
| 183 | } |
| 184 | }; |
| 185 | n += 1; |
| 186 | let line = line.trim(); |
| 187 | if line.is_empty() { |
| 188 | continue; |
| 189 | } |
| 190 | match crate::geojson::parse_feature(line) { |
| 191 | Some(f) if accept.matches(&f.geometry) => { |
| 192 | if let Err(e) = writer.push(&f.geometry, &f.props) { |
| 193 | eprintln!("{name}: {e}"); |
| 194 | return ExitCode::FAILURE; |
| 195 | } |
| 196 | } |
| 197 | _ => { |
| 198 | skipped += 1; |
| 199 | writer.skip(); |
| 200 | if skipped <= 5 { |
| 201 | eprintln!("{name}: skipping line {n} (not a {})", accept.describe()); |
| 202 | } |
| 203 | } |
| 204 | } |
| 205 | } |
| 206 | if skipped > 5 { |
| 207 | eprintln!("{name}: ... and {} more skipped line(s)", skipped - 5); |
| 208 | } |
| 209 | let summary = match writer.finish() { |
| 210 | Ok(s) => s, |
| 211 | Err(e) => { |
| 212 | eprintln!("{name}: {e}"); |
| 213 | return ExitCode::FAILURE; |
| 214 | } |
| 215 | }; |
| 216 | if summary.count == 0 { |
| 217 | eprintln!("{name}: no {} features in {geojson}", accept.describe()); |
| 218 | return ExitCode::FAILURE; |
| 219 | } |
| 220 | eprintln!( |
| 221 | "{name}: normalized {} feature(s) into {}", |
| 222 | summary.count, |
| 223 | normalized.path().display() |
| 224 | ); |
| 225 | |
| 226 | let count = summary.count; |
| 227 | let mut src = match NormalizedSource::open(normalized.path(), summary) { |
| 228 | Ok(s) => s, |
| 229 | Err(e) => { |
| 230 | eprintln!("{name}: {e}"); |
| 231 | return ExitCode::FAILURE; |
| 232 | } |
| 233 | }; |
| 234 | let report = match build_archive_to(&out, &spill_dir, &opts, &mut src, &limits) { |
| 235 | Ok(r) => r, |
| 236 | Err(e) => { |
| 237 | eprintln!("{name}: {e}"); |
| 238 | return ExitCode::FAILURE; |
| 239 | } |
| 240 | }; |
| 241 | // Only if empty: every bucket set and the normalized file remove themselves, so |
| 242 | // anything left here is a leftover worth seeing rather than deleting. |
| 243 | drop(src); |
| 244 | drop(normalized); |
| 245 | let _ = std::fs::remove_dir(&spill_dir); |
| 246 | |
| 247 | let size = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0); |
| 248 | eprintln!( |
| 249 | "{name}: wrote {out} ({:.1} MiB): {count} feature(s), layer '{layer}', \ |
| 250 | z{min_zoom}-{max_zoom}", |
| 251 | size as f64 / (1024.0 * 1024.0), |
| 252 | ); |
| 253 | report_and_exit(name, &report, max_tile_bytes) |
| 254 | } else { |
| 255 | let mut features = Vec::new(); |
| 256 | let mut skipped = 0usize; |
| 257 | let mut n = 0usize; |
| 258 | for line in lines.by_ref() { |
| 259 | let line = match line { |
| 260 | Ok(l) => l, |
| 261 | Err(e) => { |
| 262 | eprintln!("{name}: cannot read {geojson}: {e}"); |
| 263 | return ExitCode::FAILURE; |
| 264 | } |
| 265 | }; |
| 266 | n += 1; |
| 267 | let line = line.trim(); |
| 268 | if line.is_empty() { |
| 269 | continue; |
| 270 | } |
| 271 | match crate::geojson::parse_feature(line) { |
| 272 | Some(f) if accept.matches(&f.geometry) => features.push(Feature { |
| 273 | geometry: f.geometry, |
| 274 | props: f.props, |
| 275 | }), |
| 276 | _ => { |
| 277 | skipped += 1; |
| 278 | if skipped <= 5 { |
| 279 | eprintln!("{name}: skipping line {n} (not a {})", accept.describe()); |
| 280 | } |
| 281 | } |
| 282 | } |
| 283 | } |
| 284 | if skipped > 5 { |
| 285 | eprintln!("{name}: ... and {} more skipped line(s)", skipped - 5); |
| 286 | } |
| 287 | if features.is_empty() { |
| 288 | eprintln!("{name}: no {} features in {geojson}", accept.describe()); |
| 289 | return ExitCode::FAILURE; |
| 290 | } |
| 291 | |
| 292 | let (bytes, report) = match build_archive(&features, &opts) { |
| 293 | Ok(v) => v, |
| 294 | Err(e) => { |
| 295 | eprintln!("{name}: {e}"); |
| 296 | return ExitCode::FAILURE; |
| 297 | } |
| 298 | }; |
| 299 | if let Err(e) = std::fs::write(&out, &bytes) { |
| 300 | eprintln!("{name}: cannot write {out}: {e}"); |
| 301 | return ExitCode::FAILURE; |
| 302 | } |
| 303 | eprintln!( |
| 304 | "{name}: wrote {out} ({:.1} MiB): {} feature(s), layer '{layer}', \ |
| 305 | z{min_zoom}-{max_zoom}", |
| 306 | bytes.len() as f64 / (1024.0 * 1024.0), |
| 307 | features.len(), |
| 308 | ); |
| 309 | report_and_exit(name, &report, max_tile_bytes) |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | /// The per-zoom report and the drop summary, shared by both paths so a `--stream` build |
| 314 | /// tells the operator exactly what a non-streamed one does. |
| 315 | fn report_and_exit( |
| 316 | name: &str, |
| 317 | report: &[ZoomStats], |
| 318 | max_tile_bytes: usize, |
| 319 | ) -> std::process::ExitCode { |
| 320 | let _ = print_report(report, &mut std::io::stderr()); |
| 321 | let dropped: usize = report.iter().map(|s| s.dropped).sum(); |
| 322 | if dropped > 0 { |
| 323 | eprintln!( |
| 324 | "{name}: {dropped} feature placement(s) dropped by the {max_tile_bytes}-byte \ |
| 325 | per-tile budget" |
| 326 | ); |
| 327 | } |
| 328 | std::process::ExitCode::SUCCESS |
| 329 | } |