Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / tile_build / src / pyramid_part3.rs
pyramid_part3.rs224 lines · 8.3 KiBRaw
| 1 | /// Drain one bucket set in ascending index, recursing into anything over budget. |
| 2 | /// |
| 3 | /// Sub-buckets ascend within a parent and parents ascend, so the ids handed to |
| 4 | /// [`crate::pmtiles::StreamBuilder`] ascend at every depth. |
| 5 | #[allow(clippy::too_many_arguments)] |
| 6 | fn encode_buckets( |
| 7 | set: &spill::BucketSet, |
| 8 | scratch_dir: &Path, |
| 9 | z: u8, |
| 10 | depth: u32, |
| 11 | opts: &Options, |
| 12 | geom_type: GeomType, |
| 13 | limits: &StreamLimits, |
| 14 | builder: &mut pmtiles::StreamBuilder, |
| 15 | stats: &mut ZoomStats, |
| 16 | bar: &mut Progress, |
| 17 | prof: &mut EncodeProfile, |
| 18 | ) -> Result<()> { |
| 19 | for i in 0..set.len() { |
| 20 | let records = set.records_in(i); |
| 21 | if records == 0 { |
| 22 | continue; |
| 23 | } |
| 24 | let bytes = set.bytes_in(i); |
| 25 | let (lo, hi) = set.range_of(i); |
| 26 | |
| 27 | if bytes > limits.bucket_budget_bytes { |
| 28 | // `--buckets 1` would give a child covering exactly this range, so the split |
| 29 | // is a no-op that copies the bucket once per level until the depth cap. A |
| 30 | // split has to actually narrow the range to be worth doing. |
| 31 | let splittable = hi - lo > 1 |
| 32 | && limits.buckets > 1 |
| 33 | && depth < limits.max_repartition_depth; |
| 34 | if !splittable { |
| 35 | // A single tile's candidates cannot be split any further, and capping |
| 36 | // them would change which features survive -- an output change, and out |
| 37 | // of scope. Erroring beats being killed by the OOM reaper halfway |
| 38 | // through a planet run with nothing to show for it. |
| 39 | if hi - lo == 1 { |
| 40 | let (_, x, y) = pmtiles::tile_zxy(lo); |
| 41 | return err(format!( |
| 42 | "z{z}/{x}/{y} alone holds {records} spill record(s) in {bytes} byte(s), \ |
| 43 | over the {}-byte bucket budget; raise --bucket-budget-bytes", |
| 44 | limits.bucket_budget_bytes |
| 45 | )); |
| 46 | } |
| 47 | return err(format!( |
| 48 | "z{z} tile ids {lo}..{hi} hold {records} spill record(s) in {bytes} byte(s), \ |
| 49 | over the {}-byte bucket budget, and the range cannot be split further \ |
| 50 | (--buckets {}, --max-repartition-depth {}, depth {depth})", |
| 51 | limits.bucket_budget_bytes, limits.buckets, limits.max_repartition_depth |
| 52 | )); |
| 53 | } |
| 54 | // `lo` is unique across every sibling at every depth, so the child's files |
| 55 | // cannot collide with anyone else's. |
| 56 | let mut child = spill::BucketSet::new( |
| 57 | scratch_dir, |
| 58 | &format!("z{z}_d{}_{lo}", depth + 1), |
| 59 | lo, |
| 60 | hi, |
| 61 | limits.buckets, |
| 62 | )?; |
| 63 | let mut reader = set |
| 64 | .reader(i)? |
| 65 | .ok_or_else(|| Error(format!("bucket {i} of z{z} vanished mid-pass")))?; |
| 66 | let mut buf = Vec::new(); |
| 67 | while let Some(r) = reader.next()? { |
| 68 | buf.clear(); |
| 69 | r.encode(&mut buf)?; |
| 70 | child.push(r.tile_id, &buf)?; |
| 71 | } |
| 72 | child.seal()?; |
| 73 | encode_buckets( |
| 74 | &child, |
| 75 | scratch_dir, |
| 76 | z, |
| 77 | depth + 1, |
| 78 | opts, |
| 79 | geom_type, |
| 80 | limits, |
| 81 | builder, |
| 82 | stats, |
| 83 | bar, |
| 84 | prof, |
| 85 | )?; |
| 86 | continue; |
| 87 | } |
| 88 | |
| 89 | let mut recs = set.load(i)?; |
| 90 | // The total sort key: tile id first, then the drop policy's own order, so a |
| 91 | // group is already in importance order when `fit_tile` sees it. |
| 92 | recs.sort_by(|a, b| { |
| 93 | a.tile_id |
| 94 | .cmp(&b.tile_id) |
| 95 | .then_with(|| by_importance_keys(a.extent, a.seq, b.extent, b.seq)) |
| 96 | }); |
| 97 | |
| 98 | // Runs of equal `tile_id`. Each run is one candidate tile, and `fit_tile` is |
| 99 | // pure -- all-shared refs, a fresh `Layer`/`Tile` per call, no statics -- so the |
| 100 | // runs are independent and that is the seam. |
| 101 | // |
| 102 | // Parallel WITHIN a bucket rather than across buckets: one bucket is resident at |
| 103 | // a time either way, so peak memory is unchanged and `--bucket-budget-bytes` |
| 104 | // keeps meaning what it says. Going across buckets instead would hold one |
| 105 | // decoded bucket per thread and turn a 690 MiB peak into ~22 GB at 32 threads. |
| 106 | let mut groups: Vec<(usize, usize)> = Vec::new(); |
| 107 | let mut k = 0usize; |
| 108 | while k < recs.len() { |
| 109 | let id = recs[k].tile_id; |
| 110 | let mut j = k; |
| 111 | while j < recs.len() && recs[j].tile_id == id { |
| 112 | j += 1; |
| 113 | } |
| 114 | groups.push((k, j)); |
| 115 | prof.groups += 1; |
| 116 | if j - k > prof.max_group { |
| 117 | prof.max_group = j - k; |
| 118 | prof.max_group_id = id; |
| 119 | } |
| 120 | k = j; |
| 121 | } |
| 122 | |
| 123 | let encode_group = |gz: &mut crate::gz::Compressor, |
| 124 | &(k, j): &(usize, usize)| |
| 125 | -> Result<EncodedTile> { |
| 126 | let candidates: Vec<TileCandidate> = recs[k..j] |
| 127 | .iter() |
| 128 | .map(|r| TileCandidate { |
| 129 | seq: r.seq, |
| 130 | geom: &r.geom, |
| 131 | props: &r.props, |
| 132 | extent: r.extent, |
| 133 | }) |
| 134 | .collect(); |
| 135 | let (body, kept, over) = fit_tile(&candidates, &opts.layer, geom_type, opts, gz)?; |
| 136 | Ok(EncodedTile { |
| 137 | id: recs[k].tile_id, |
| 138 | body, |
| 139 | kept, |
| 140 | over_budget: over, |
| 141 | placed: candidates.len(), |
| 142 | }) |
| 143 | }; |
| 144 | |
| 145 | // A batch at a time, so live memory is a bounded number of encoded bodies |
| 146 | // rather than every body in the bucket. The fold below is sequential and in |
| 147 | // ascending group order, which is what keeps `add_tile_raw` fed ascending ids |
| 148 | // and the `stats` sums and `largest_tile_bytes` max identical to a serial run. |
| 149 | for chunk in groups.chunks(par::batch_len()) { |
| 150 | let done: Vec<EncodedTile> = par::install(|| { |
| 151 | chunk |
| 152 | .par_iter() |
| 153 | .with_min_len(par::min_task_len(chunk.len())) |
| 154 | .map_init(crate::gz::Compressor::new, encode_group) |
| 155 | .collect::<Result<Vec<_>>>() |
| 156 | })?; |
| 157 | for t in done { |
| 158 | for _ in 0..t.placed { |
| 159 | bar.tick(ENCODED); |
| 160 | } |
| 161 | stats.placed += t.placed; |
| 162 | stats.kept += t.kept; |
| 163 | stats.dropped += t.placed - t.kept; |
| 164 | if t.over_budget { |
| 165 | stats.over_budget += 1; |
| 166 | } |
| 167 | stats.largest_tile_bytes = stats.largest_tile_bytes.max(t.body.len()); |
| 168 | stats.tiles += 1; |
| 169 | builder.add_tile_raw(t.id, &t.body)?; |
| 170 | } |
| 171 | } |
| 172 | } |
| 173 | Ok(()) |
| 174 | } |
| 175 | |
| 176 | /// Print the per-zoom report the drop policy owes the operator. |
| 177 | pub fn print_report(report: &[ZoomStats], out: &mut impl std::io::Write) -> std::io::Result<()> { |
| 178 | writeln!(out, " zoom tiles placed kept dropped largest")?; |
| 179 | for s in report { |
| 180 | writeln!( |
| 181 | out, |
| 182 | " z{:<4} {:>6} {:>8} {:>8} {:>8} {:>8}{}", |
| 183 | s.zoom, |
| 184 | s.tiles, |
| 185 | s.placed, |
| 186 | s.kept, |
| 187 | s.dropped, |
| 188 | s.largest_tile_bytes, |
| 189 | if s.over_budget > 0 { |
| 190 | format!(" ({} tile(s) over budget)", s.over_budget) |
| 191 | } else { |
| 192 | String::new() |
| 193 | } |
| 194 | )?; |
| 195 | } |
| 196 | Ok(()) |
| 197 | } |
| 198 | |
| 199 | // --- the shared CLI ------------------------------------------------------- |
| 200 | |
| 201 | /// Which geometry a binary will tile. A layer is styled as one thing, so mixing |
| 202 | /// kinds in one archive is a mistake upstream; each binary accepts exactly one and |
| 203 | /// counts what it turns away. |
| 204 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 205 | pub enum Accept { |
| 206 | Lines, |
| 207 | Polygons, |
| 208 | } |
| 209 | |
| 210 | impl Accept { |
| 211 | fn matches(self, g: &Geometry) -> bool { |
| 212 | matches!( |
| 213 | (self, g), |
| 214 | (Accept::Lines, Geometry::Lines(_)) | (Accept::Polygons, Geometry::Polygons(_)) |
| 215 | ) |
| 216 | } |
| 217 | |
| 218 | fn describe(self) -> &'static str { |
| 219 | match self { |
| 220 | Accept::Lines => "LineString or MultiLineString", |
| 221 | Accept::Polygons => "Polygon or MultiPolygon", |
| 222 | } |
| 223 | } |
| 224 | } |