Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / store_part2.rs
store_part2.rs294 lines · 12.3 KiBRaw
| 1 | impl Store { |
| 2 | /// How many features are in the file. |
| 3 | #[cfg_attr(not(test), allow(dead_code))] |
| 4 | pub fn len(&self) -> u64 { |
| 5 | self.count |
| 6 | } |
| 7 | |
| 8 | /// The bounding box of every feature, in degrees times 1e7, for the archive header. |
| 9 | pub fn bbox(&self) -> (i32, i32, i32, i32) { |
| 10 | self.bbox |
| 11 | } |
| 12 | |
| 13 | /// Read every feature a zoom could want, in the order they were written. |
| 14 | /// |
| 15 | /// A chunk whose shallowest `min_zoom` is deeper than `z` holds nothing this zoom draws, so it is |
| 16 | /// skipped outright — not read, not parsed. Order is unchanged, because the chunks that survive |
| 17 | /// are still visited in file order, and that is what keeps the archive byte-identical. |
| 18 | #[cfg_attr(not(test), allow(dead_code))] |
| 19 | pub fn reader_for_zoom(&self, z: u8) -> Result<ZoomReader> { |
| 20 | let wanted: Vec<usize> = self |
| 21 | .chunk_mins |
| 22 | .iter() |
| 23 | .enumerate() |
| 24 | .filter(|(_, min)| **min <= z) |
| 25 | .map(|(i, _)| i) |
| 26 | .collect(); |
| 27 | self.reader_for_wanted(wanted, z) |
| 28 | } |
| 29 | |
| 30 | pub fn wanted_chunks_for_zoom(&self, z: u8) -> Vec<usize> { |
| 31 | self.chunk_mins |
| 32 | .iter() |
| 33 | .enumerate() |
| 34 | .filter(|(_, min)| **min <= z) |
| 35 | .map(|(i, _)| i) |
| 36 | .collect() |
| 37 | } |
| 38 | |
| 39 | /// Open the staged bytes for chunked reading, anonymous or file according to the plan the |
| 40 | /// sink was created with. One helper so the three reader constructors agree. |
| 41 | fn open_chunks(&self) -> Result<NormalizedChunks> { |
| 42 | match &self.anon { |
| 43 | Some(store) => NormalizedChunks::open_anon( |
| 44 | self.path.clone(), |
| 45 | self.chunks.clone(), |
| 46 | std::sync::Arc::clone(store), |
| 47 | ) |
| 48 | .map_err(|e| osm_ingest::proto::Error(e.to_string())), |
| 49 | None => NormalizedChunks::open(self.path.clone(), self.chunks.clone()) |
| 50 | .map_err(|e| osm_ingest::proto::Error(e.to_string())), |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | /// Open the staged bytes for sequential reading. See [`open_chunks`](Self::open_chunks). |
| 55 | fn open_sequential(&self) -> Result<NormalizedReader> { |
| 56 | match &self.anon { |
| 57 | Some(store) => NormalizedReader::open_anon( |
| 58 | self.path.clone(), |
| 59 | std::sync::Arc::clone(store), |
| 60 | ) |
| 61 | .map_err(|e| osm_ingest::proto::Error(e.to_string())), |
| 62 | None => NormalizedReader::open(self.path.clone()) |
| 63 | .map_err(|e| osm_ingest::proto::Error(e.to_string())), |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | /// Take the marking-convention grid stage A resolved from the country relations. |
| 68 | pub fn with_conventions( |
| 69 | mut self, |
| 70 | conventions: crate::schema::boundaries::Conventions, |
| 71 | ) -> Self { |
| 72 | self.conventions = conventions; |
| 73 | self |
| 74 | } |
| 75 | |
| 76 | /// Which marking convention applies where, for the tiler to stamp onto each tile. |
| 77 | pub fn conventions(&self) -> &crate::schema::boundaries::Conventions { |
| 78 | &self.conventions |
| 79 | } |
| 80 | |
| 81 | pub fn reader_for_wanted(&self, wanted: Vec<usize>, z: u8) -> Result<ZoomReader> { |
| 82 | let chunks = self.open_chunks()?; |
| 83 | ZoomReader::spawn(chunks, wanted, z) |
| 84 | } |
| 85 | |
| 86 | /// Read every feature, in the order they were written. |
| 87 | /// |
| 88 | /// Kept as the reference [`Self::reader_for_zoom`] is checked against: a test that reads a store |
| 89 | /// both ways and compares is the cheapest possible guard on the chunk index being right. |
| 90 | #[cfg_attr(not(test), allow(dead_code))] |
| 91 | pub fn reader(&self) -> Result<Reader> { |
| 92 | Ok(Reader { inner: self.open_sequential()? }) |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | impl Store { |
| 97 | /// Spill features from memory into a temporary store. |
| 98 | /// |
| 99 | /// For tests only. The generator never has a `Vec<Feature>` to hand -- that is the entire point |
| 100 | /// of this module -- but a test that had to write a file to state its case would be a worse test. |
| 101 | #[cfg(test)] |
| 102 | pub fn of(features: &[Feature]) -> Result<Store> { |
| 103 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 104 | static NEXT: AtomicU64 = AtomicU64::new(0); |
| 105 | let path = std::env::temp_dir().join(format!( |
| 106 | "mamaps_test_{}_{}.features", |
| 107 | std::process::id(), |
| 108 | NEXT.fetch_add(1, Ordering::Relaxed), |
| 109 | )); |
| 110 | let mut sink = Sink::create(&path)?; |
| 111 | for feature in features { |
| 112 | // Test-only path: encode inline (the pool-built path is exercised |
| 113 | // by the materialise drains, not here). |
| 114 | let encoded = EncodedGeom::live(&feature.geometry)?; |
| 115 | if feature.transit_color != 0 { |
| 116 | sink.push_transit( |
| 117 | &feature.class, |
| 118 | &encoded, |
| 119 | feature.transit_color, |
| 120 | feature.transit_ordinal, |
| 121 | feature.transit_lanes, |
| 122 | feature.transit_taper, |
| 123 | )?; |
| 124 | } else if let Some(attrs) = feature.building { |
| 125 | sink.push_building( |
| 126 | &feature.class, |
| 127 | &encoded, |
| 128 | feature.name.as_deref(), |
| 129 | attrs, |
| 130 | )?; |
| 131 | } else if feature.lane_count != 0 |
| 132 | || !feature.turn_fwd.is_empty() |
| 133 | || !feature.turn_bwd.is_empty() |
| 134 | || !feature.carriageway.is_empty() |
| 135 | { |
| 136 | sink.push_road( |
| 137 | &feature.class, |
| 138 | &encoded, |
| 139 | RoadAttrs { |
| 140 | name: feature.name.as_deref(), |
| 141 | lane_count: feature.lane_count, |
| 142 | turn_fwd: &feature.turn_fwd, |
| 143 | turn_bwd: &feature.turn_bwd, |
| 144 | carriageway: feature.carriageway, |
| 145 | }, |
| 146 | )?; |
| 147 | } else { |
| 148 | sink.push_named(&feature.class, &encoded, feature.name.as_deref(), feature.id)?; |
| 149 | } |
| 150 | } |
| 151 | sink.finish(&path) |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | /// A spilled record as a [`Feature`]. |
| 156 | /// |
| 157 | /// A record whose class property is missing or is not an integer is a corrupt file rather than a |
| 158 | /// feature to skip: everything in here was written by [`Sink::push`] one run ago, so anything else |
| 159 | /// means the file is not the one we wrote. A `n` string property rides along as the display |
| 160 | /// name, a `t` integer as the transit colour, an `s` integer as its packed lane inputs and an `i` |
| 161 | /// integer as the tagged OSM id; anything else in there is corruption for the same reason. |
| 162 | fn feature_of(record: tile_build::spill::NormalizedFeature) -> Result<Feature> { |
| 163 | let bits = match record.props.iter().find(|(key, _)| key == CLASS_KEY) { |
| 164 | Some((_, Value::Uint(bits))) => *bits, |
| 165 | _ => return err("a spilled feature carries no packed class".to_string()), |
| 166 | }; |
| 167 | let mut name: Option<String> = None; |
| 168 | let mut id: u64 = tilecodec::mamaps::body::ID_NONE; |
| 169 | let mut transit_color: u32 = 0; |
| 170 | let mut transit_ordinal: u8 = 0; |
| 171 | let mut transit_lanes: u8 = 0; |
| 172 | let mut transit_taper: u8 = 0; |
| 173 | let mut lane_count: u8 = 0; |
| 174 | let mut turn_fwd: Vec<u16> = Vec::new(); |
| 175 | let mut turn_bwd: Vec<u16> = Vec::new(); |
| 176 | let mut carriageway = Carriageway::default(); |
| 177 | let mut bld_a: Option<u64> = None; |
| 178 | let mut bld_b: Option<u64> = None; |
| 179 | let mut bld_c: Option<u64> = None; |
| 180 | for (key, value) in &record.props { |
| 181 | if key == CLASS_KEY { |
| 182 | continue; |
| 183 | } |
| 184 | match (key.as_str(), value) { |
| 185 | (NAME_KEY, Value::String(text)) if !text.is_empty() => { |
| 186 | if name.replace(text.clone()).is_some() { |
| 187 | return err("a spilled feature carries two names".to_string()); |
| 188 | } |
| 189 | } |
| 190 | (COLOR_KEY, Value::Uint(color)) => { |
| 191 | transit_color = u32::try_from(*color) |
| 192 | .map_err(|_| Error("a spilled transit colour does not fit u32".to_string()))?; |
| 193 | } |
| 194 | (LANE_KEY, Value::Uint(lane_bits)) => { |
| 195 | if *lane_bits > 0xff_ff_ff { |
| 196 | return err("a spilled transit lane triple does not fit three bytes".to_string()); |
| 197 | } |
| 198 | transit_ordinal = (lane_bits >> 16) as u8; |
| 199 | transit_lanes = (lane_bits >> 8) as u8; |
| 200 | transit_taper = *lane_bits as u8; |
| 201 | } |
| 202 | (LANE_COUNT_KEY, Value::Uint(count)) => { |
| 203 | lane_count = u8::try_from(*count) |
| 204 | .map_err(|_| Error("a spilled road lane count does not fit a byte".to_string()))?; |
| 205 | } |
| 206 | (TURN_FWD_KEY, Value::String(packed)) => { |
| 207 | turn_fwd = unpack_lanes(packed)?; |
| 208 | } |
| 209 | (TURN_BWD_KEY, Value::String(packed)) => { |
| 210 | turn_bwd = unpack_lanes(packed)?; |
| 211 | } |
| 212 | (CARRIAGEWAY_KEY, Value::Uint(bits)) => { |
| 213 | carriageway = unpack_carriageway(*bits); |
| 214 | } |
| 215 | (BLD_A_KEY, Value::Uint(v)) => bld_a = Some(*v), |
| 216 | (BLD_B_KEY, Value::Uint(v)) => bld_b = Some(*v), |
| 217 | (BLD_C_KEY, Value::Uint(v)) => bld_c = Some(*v), |
| 218 | (ID_KEY, Value::Uint(tagged)) => { |
| 219 | if id != tilecodec::mamaps::body::ID_NONE { |
| 220 | return err("a spilled feature carries two ids".to_string()); |
| 221 | } |
| 222 | id = *tagged; |
| 223 | } |
| 224 | _ => { |
| 225 | return err(format!("a spilled feature carries an unknown property `{key}`")); |
| 226 | } |
| 227 | } |
| 228 | } |
| 229 | Ok(Feature { |
| 230 | class: unpack(bits), |
| 231 | geometry: record.geometry, |
| 232 | name, |
| 233 | id, |
| 234 | transit_color, |
| 235 | transit_ordinal, |
| 236 | transit_lanes, |
| 237 | transit_taper, |
| 238 | lane_count, |
| 239 | turn_fwd, |
| 240 | turn_bwd, |
| 241 | carriageway, |
| 242 | building: match (bld_a, bld_b, bld_c) { |
| 243 | (Some(a), Some(b), Some(c)) => Some(unpack_building(a, b, c)), |
| 244 | (None, None, None) => None, |
| 245 | _ => return err("a spilled building is missing part of its attributes".to_string()), |
| 246 | }, |
| 247 | }) |
| 248 | } |
| 249 | |
| 250 | /// Chunks of features as the lanes hand them over, or the error that stopped one. |
| 251 | /// |
| 252 | /// [`Feature`] rather than the decoder's own record, because turning one into the other is where |
| 253 | /// the reader thread's remaining time went. It looks like a field lookup and a move, and the field |
| 254 | /// lookup and the move are free; what is not is dropping the `props` the decoder built — a `Vec` and |
| 255 | /// an owned key `String` per feature, freed one at a time on the one thread the whole map phase |
| 256 | /// waits on. Converting in the lane puts that on the lane. |
| 257 | #[cfg_attr(not(test), allow(dead_code))] |
| 258 | type Decoded = Result<Vec<Feature>>; |
| 259 | |
| 260 | /// Threads decoding spill chunks ahead of the tiler. |
| 261 | /// |
| 262 | /// Not the pool: see [`ZoomReader::spawn`]. **Four is the safe default, not the right answer**, and |
| 263 | /// there is no right answer available as a constant. The two extracts want opposite things: |
| 264 | /// |
| 265 | /// | lanes / tiling workers | us-west | north-america | |
| 266 | /// |---|---|---| |
| 267 | /// | 4 / 64 | **91.9 s** | 945.7 s | |
| 268 | /// | 16 / 64 | 151.9 s | **766.9 s** | |
| 269 | /// | 16 / 48 | 94.4 s | 900.4 s | |
| 270 | /// |
| 271 | /// Sixteen lanes is a 65% regression on us-west and a 19% improvement on north-america, and the |
| 272 | /// mechanism is the same in both: a lane competes for a CPU only when it is running. On |
| 273 | /// north-america the reader cannot fill the channel fast enough, so the clipping workers are blocked |
| 274 | /// and the lanes are free; on us-west the workers saturate the machine and the lanes take CPU from |
| 275 | /// the single reader thread they exist to feed. Which regime a build lands in depends on the spill |
| 276 | /// against the page cache, not on anything this constant can see — the middle row of that table is |
| 277 | /// the attempt to correct for it by taking the lanes out of the worker budget, and it makes each |
| 278 | /// case worse than that case's own best. |
| 279 | /// |
| 280 | /// So it is a knob, defaulting to the value that cannot hurt. `MAPS_PREFETCH_LANES=16` is what a |
| 281 | /// continent wants. Removing the need for the knob means removing the re-decode it is compensating |
| 282 | /// for: the spill is read once per zoom, which is ~1.06 billion feature decodes to deliver |
| 283 | /// 199.7 M distinct features on north-america, and no lane count makes redundant work cheap. |
| 284 | #[cfg_attr(not(test), allow(dead_code))] |
| 285 | pub fn prefetch_lanes() -> usize { |
| 286 | static LANES: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| 287 | *LANES.get_or_init(|| { |
| 288 | std::env::var("MAPS_PREFETCH_LANES") |
| 289 | .ok() |
| 290 | .and_then(|raw| raw.trim().parse::<usize>().ok()) |
| 291 | .filter(|n| *n > 0) |
| 292 | .unwrap_or(4) |
| 293 | }) |
| 294 | } |