Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / store_part6_s1.rs
store_part6_s1.rs345 lines · 14.7 KiBRaw
| 1 | /// Everything in a way record after its id varint (see [`WaySink`]'s table), appended to `out`. |
| 2 | /// Returns the largest ref, or zero for none -- the fold `WaySink` keeps. |
| 3 | #[allow(clippy::too_many_arguments)] |
| 4 | fn encode_way_tail( |
| 5 | out: &mut Vec<u8>, |
| 6 | class: &Class, |
| 7 | refs: &[i64], |
| 8 | name: Option<&str>, |
| 9 | lane_count: u8, |
| 10 | turn_fwd: &[u16], |
| 11 | turn_bwd: &[u16], |
| 12 | carriageway: Carriageway, |
| 13 | building: Option<BuildingAttrs>, |
| 14 | ) -> Result<i64> { |
| 15 | put_uvarint(out, pack(class)?); |
| 16 | put_uvarint(out, refs.len() as u64); |
| 17 | let mut previous: i64 = 0; |
| 18 | let mut max_ref: i64 = 0; |
| 19 | for &node in refs { |
| 20 | put_svarint(out, node.wrapping_sub(previous)); |
| 21 | previous = node; |
| 22 | max_ref = max_ref.max(node); |
| 23 | } |
| 24 | match name.filter(|n| !n.is_empty()) { |
| 25 | Some(name) => { |
| 26 | put_uvarint(out, name.len() as u64); |
| 27 | out.extend_from_slice(name.as_bytes()); |
| 28 | } |
| 29 | None => put_uvarint(out, 0), |
| 30 | } |
| 31 | put_uvarint(out, lane_count as u64); |
| 32 | // The turn masks: a count then each u16, forward then backward. Zero counts for the |
| 33 | // overwhelming majority, which cost one byte each. |
| 34 | for masks in [turn_fwd, turn_bwd] { |
| 35 | put_uvarint(out, masks.len() as u64); |
| 36 | for &m in masks { |
| 37 | put_uvarint(out, m as u64); |
| 38 | } |
| 39 | } |
| 40 | // The directional split, as one packed varint. Zero -- one byte -- when never surveyed. |
| 41 | put_uvarint(out, pack_carriageway(carriageway)); |
| 42 | // The building attributes: a presence byte, then the three packed words when present. A |
| 43 | // non-building writes one zero byte; a building -- even one with no S3DB tags -- writes its |
| 44 | // (usually all-zero) words so the tiler's side table stays dense-parallel to the layer. |
| 45 | match building { |
| 46 | Some(attrs) => { |
| 47 | put_uvarint(out, 1); |
| 48 | let (a, b, c) = pack_building(&attrs); |
| 49 | put_uvarint(out, a); |
| 50 | put_uvarint(out, b); |
| 51 | put_uvarint(out, c); |
| 52 | } |
| 53 | None => put_uvarint(out, 0), |
| 54 | } |
| 55 | Ok(max_ref) |
| 56 | } |
| 57 | |
| 58 | /// The sealed ways spill as independently decodable blocks. Shared read-only across the pool: |
| 59 | /// every [`reader`](Self::reader) call is a positional read of one block. |
| 60 | pub struct WayBlocks { |
| 61 | file: Option<File>, |
| 62 | anon: Option<std::sync::Arc<tile_build::anon::AnonStore>>, |
| 63 | locs: Vec<WayBlockLoc>, |
| 64 | } |
| 65 | |
| 66 | impl WayBlocks { |
| 67 | /// Open whichever backend the sink sealed -- the shared anon store when present, else the |
| 68 | /// file at `path` -- with the index [`WaySink`] returned in its [`WayCounts`]. |
| 69 | pub fn open( |
| 70 | path: &Path, |
| 71 | anon: &Option<std::sync::Arc<tile_build::anon::AnonStore>>, |
| 72 | locs: Vec<WayBlockLoc>, |
| 73 | ) -> Result<WayBlocks> { |
| 74 | let file = match anon { |
| 75 | Some(_) => None, |
| 76 | None => Some( |
| 77 | File::open(path).map_err(|e| Error(format!("cannot open {}: {e}", path.display())))?, |
| 78 | ), |
| 79 | }; |
| 80 | Ok(WayBlocks { file, anon: anon.clone(), locs }) |
| 81 | } |
| 82 | |
| 83 | pub fn locs(&self) -> &[WayBlockLoc] { |
| 84 | &self.locs |
| 85 | } |
| 86 | |
| 87 | /// A cursor over block `i` alone, positioned on its first record with the id its first delta |
| 88 | /// is taken from. Yields exactly the records [`WayReader::open`] yields over that byte range. |
| 89 | pub fn reader(&self, i: usize) -> Result<WayReader> { |
| 90 | let loc = self.locs[i]; |
| 91 | let len = usize::try_from(loc.len) |
| 92 | .map_err(|_| Error("a ways spill block does not fit in memory".to_string()))?; |
| 93 | let mut buf = vec![0u8; len]; |
| 94 | match (&self.anon, &self.file) { |
| 95 | (Some(anon), _) => anon |
| 96 | .read_at(loc.offset, &mut buf) |
| 97 | .map_err(|e| Error(format!("cannot read the anon ways spill: {e}")))?, |
| 98 | (None, Some(file)) => read_exact_at(file, &mut buf, loc.offset) |
| 99 | .map_err(|e| Error(format!("cannot read the ways spill: {e}")))?, |
| 100 | (None, None) => return err("a ways spill with no backend".to_string()), |
| 101 | } |
| 102 | Ok(WayReader { |
| 103 | inner: WayIn::Slice { buf, used: 0 }, |
| 104 | last_id: loc.start_last_id, |
| 105 | seen: 0, |
| 106 | }) |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | /// Positional read of exactly `buf.len()` bytes, safe to call from many threads on one `File`. |
| 111 | fn read_exact_at(file: &File, mut buf: &mut [u8], mut offset: u64) -> std::io::Result<()> { |
| 112 | while !buf.is_empty() { |
| 113 | #[cfg(windows)] |
| 114 | let n = std::os::windows::fs::FileExt::seek_read(file, buf, offset)?; |
| 115 | #[cfg(unix)] |
| 116 | let n = std::os::unix::fs::FileExt::read_at(file, buf, offset)?; |
| 117 | if n == 0 { |
| 118 | return Err(std::io::Error::new( |
| 119 | std::io::ErrorKind::UnexpectedEof, |
| 120 | "the ways spill ended inside a block", |
| 121 | )); |
| 122 | } |
| 123 | buf = &mut buf[n..]; |
| 124 | offset += n as u64; |
| 125 | } |
| 126 | Ok(()) |
| 127 | } |
| 128 | |
| 129 | #[cfg(test)] |
| 130 | mod way_block_tests { |
| 131 | use super::*; |
| 132 | |
| 133 | fn class(layer: u8, kind: u16) -> Class { |
| 134 | Class { layer, kind, kind_detail: 0, flags: 0, area: false, min_zoom: 12, min_area_px: 0.0 } |
| 135 | } |
| 136 | |
| 137 | /// Pushing ways one at a time and pushing the same ways as worker-built blocks must write the |
| 138 | /// same bytes, report the same counts, and read back the same records both through the |
| 139 | /// sequential cursor and block by block -- on both backends. |
| 140 | #[test] |
| 141 | fn blocks_write_the_same_stream_and_read_back_block_by_block() { |
| 142 | let dir = std::env::temp_dir().join(format!("mamaps_wayblock_{}", std::process::id())); |
| 143 | let _ = std::fs::remove_dir_all(&dir); |
| 144 | std::fs::create_dir_all(&dir).unwrap(); |
| 145 | type WayRow = (i64, Vec<i64>, Option<String>, u8, Vec<u16>); |
| 146 | let mut ways: Vec<WayRow> = Vec::new(); |
| 147 | let mut id = 7i64; |
| 148 | for i in 0..10_000i64 { |
| 149 | id += 1 + (i % 5) * 1000; |
| 150 | let refs: Vec<i64> = (0..(2 + i % 9)).map(|k| 1_000_000 + i * 3 + k * 17).collect(); |
| 151 | let name = (i % 7 == 0).then(|| format!("Road {i}")); |
| 152 | ways.push((id, refs, name, (i % 4) as u8, if i % 11 == 0 { vec![1, 4] } else { vec![] })); |
| 153 | } |
| 154 | let c = class(tilecodec::mamaps::dict::LAYER_ROADS, 3); |
| 155 | for anon in [false, true] { |
| 156 | let one_path = dir.join(format!("one{anon}.tmp")); |
| 157 | let blk_path = dir.join(format!("blk{anon}.tmp")); |
| 158 | let plan = if anon { osm_ingest::mem::SpillPlan::Anon } else { osm_ingest::mem::SpillPlan::File }; |
| 159 | let mut one = WaySink::create_planned(&one_path, plan).unwrap(); |
| 160 | let mut blk = WaySink::create_planned(&blk_path, plan).unwrap(); |
| 161 | let mut block = WayBlock::new(); |
| 162 | for (n, (id, refs, name, lanes, turns)) in ways.iter().enumerate() { |
| 163 | one.push(*id, &c, refs, name.as_deref(), *lanes, turns, &[], Carriageway::default(), None) |
| 164 | .unwrap(); |
| 165 | block |
| 166 | .push(*id, &c, refs, name.as_deref(), *lanes, turns, &[], Carriageway::default(), None) |
| 167 | .unwrap(); |
| 168 | // Uneven block sizes, including one-way blocks, to exercise coalescing. |
| 169 | if n % 1237 == 0 || block.len() >= 3000 { |
| 170 | blk.push_block(&std::mem::take(&mut block)).unwrap(); |
| 171 | } |
| 172 | } |
| 173 | blk.push_block(&block).unwrap(); |
| 174 | let (c1, s1) = one.finish_either().unwrap(); |
| 175 | let (c2, s2) = blk.finish_either().unwrap(); |
| 176 | assert_eq!((c1.ways, c1.refs, c1.max_ref), (c2.ways, c2.refs, c2.max_ref)); |
| 177 | let bytes = |path: &Path, s: Option<&tile_build::anon::AnonStore>| -> Vec<u8> { |
| 178 | match s { |
| 179 | Some(a) => { |
| 180 | let mut v = vec![0u8; a.len() as usize]; |
| 181 | a.read_at(0, &mut v).unwrap(); |
| 182 | v |
| 183 | } |
| 184 | None => std::fs::read(path).unwrap(), |
| 185 | } |
| 186 | }; |
| 187 | let s2 = s2.map(std::sync::Arc::new); |
| 188 | let b1 = bytes(&one_path, s1.as_ref()); |
| 189 | let b2 = bytes(&blk_path, s2.as_deref()); |
| 190 | assert_eq!(b1, b2, "the block path must write the per-way stream byte for byte"); |
| 191 | for counts in [&c1, &c2] { |
| 192 | assert!(counts.blocks.iter().all(|l| l.ways <= WAY_BLOCK_WAYS)); |
| 193 | assert_eq!(counts.blocks.iter().map(|l| l.ways).sum::<u64>(), ways.len() as u64); |
| 194 | } |
| 195 | // Block-by-block decode equals the sequential cursor, record for record. |
| 196 | let blocks = WayBlocks::open(&blk_path, &s2, c2.blocks.clone()).unwrap(); |
| 197 | let mut seq = WayReader::open_either(&blk_path, &s2).unwrap(); |
| 198 | let (mut r1, mut r2) = (Vec::new(), Vec::new()); |
| 199 | for i in 0..blocks.locs().len() { |
| 200 | let mut reader = blocks.reader(i).unwrap(); |
| 201 | let mut n = 0u64; |
| 202 | while let Some(a) = reader.next(&mut r1).unwrap() { |
| 203 | let b = seq.next(&mut r2).unwrap().expect("sequential has as many records"); |
| 204 | assert_eq!(a.0, b.0); |
| 205 | assert_eq!(a.2, b.2); |
| 206 | assert_eq!(a.3, b.3); |
| 207 | assert_eq!(a.4, b.4); |
| 208 | assert_eq!(r1, r2); |
| 209 | n += 1; |
| 210 | } |
| 211 | assert_eq!(n, blocks.locs()[i].ways); |
| 212 | } |
| 213 | assert!(seq.next(&mut r2).unwrap().is_none()); |
| 214 | } |
| 215 | let _ = std::fs::remove_dir_all(&dir); |
| 216 | } |
| 217 | |
| 218 | /// The ordering rule holds across a block boundary, not only inside one. |
| 219 | #[test] |
| 220 | fn a_block_that_does_not_advance_is_refused() { |
| 221 | let path = std::env::temp_dir().join(format!("mamaps_wayblock_order_{}.tmp", std::process::id())); |
| 222 | let c = class(tilecodec::mamaps::dict::LAYER_ROADS, 3); |
| 223 | let mut sink = WaySink::create_planned(&path, osm_ingest::mem::SpillPlan::Anon).unwrap(); |
| 224 | let mut a = WayBlock::new(); |
| 225 | a.push(10, &c, &[1, 2], None, 0, &[], &[], Carriageway::default(), None).unwrap(); |
| 226 | sink.push_block(&a).unwrap(); |
| 227 | let mut b = WayBlock::new(); |
| 228 | b.push(10, &c, &[1, 2], None, 0, &[], &[], Carriageway::default(), None).unwrap(); |
| 229 | assert!(sink.push_block(&b).is_err()); |
| 230 | assert!(a.push(9, &c, &[1, 2], None, 0, &[], &[], Carriageway::default(), None).is_err()); |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | // --- zoom decode for the parallel map reader -------------------------------------------------------- |
| 235 | |
| 236 | /// The staged features opened for positional, many-thread decoding: one handle shared by every |
| 237 | /// decode thread of [`crate::tiler`]'s map reader. |
| 238 | pub struct ZoomChunks { |
| 239 | inner: NormalizedChunks, |
| 240 | } |
| 241 | |
| 242 | impl Store { |
| 243 | /// Open the staged bytes for [`ZoomChunks::decode`]. Same backend choice as every other reader. |
| 244 | pub fn zoom_chunks(&self) -> Result<ZoomChunks> { |
| 245 | Ok(ZoomChunks { inner: self.open_chunks()? }) |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | impl ZoomChunks { |
| 250 | /// Spill chunk `chunk`'s features that zoom `z` draws, in file order, plus each one's vertex |
| 251 | /// count. Exactly what a [`ZoomReader`] lane yields for that chunk -- the same `read_into`, the |
| 252 | /// same `feature_of`, the same zoom window -- so a reader that concatenates these in wanted |
| 253 | /// order sees the stream `reader_for_zoom` delivers. |
| 254 | pub fn decode( |
| 255 | &self, |
| 256 | chunk: usize, |
| 257 | z: u8, |
| 258 | scratch: &mut Vec<u8>, |
| 259 | records: &mut Vec<tile_build::spill::NormalizedFeature>, |
| 260 | ) -> Result<(Vec<Feature>, Vec<usize>)> { |
| 261 | self.inner |
| 262 | .read_into(chunk, scratch, records) |
| 263 | .map_err(|e| osm_ingest::proto::Error(e.to_string()))?; |
| 264 | let mut features = Vec::with_capacity(records.len()); |
| 265 | let mut counts = Vec::with_capacity(records.len()); |
| 266 | for record in records.drain(..) { |
| 267 | let feature = feature_of(record)?; |
| 268 | // The zoom window: floor is the feature's own `min_zoom`, ceiling the layer cap |
| 269 | // (`MAX_ZOOM_PER_LAYER`). The same test `ZoomReader`'s lanes apply. |
| 270 | if z >= feature.class.min_zoom |
| 271 | && z <= crate::schema::max_zoom_for_layer(feature.class.layer) |
| 272 | { |
| 273 | counts.push(geometry_vertices(&feature.geometry)); |
| 274 | features.push(feature); |
| 275 | } |
| 276 | } |
| 277 | Ok((features, counts)) |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | /// Every vertex in a geometry, all parts and rings: the measure the map reader cuts chunks by. |
| 282 | pub fn geometry_vertices(geometry: &Geometry) -> usize { |
| 283 | match geometry { |
| 284 | Geometry::Points(points) => points.len(), |
| 285 | Geometry::Lines(lines) => lines.iter().map(Vec::len).sum(), |
| 286 | Geometry::Polygons(polygons) => polygons.iter().flatten().map(Vec::len).sum(), |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | impl Store { |
| 291 | /// Parallel scan with a cheap pre-filter on each record's packed class and |
| 292 | /// whether it carries a feature id: records it rejects are never turned into features (their |
| 293 | /// geometry is never decoded), so it must accept every record `keep` could keep. |
| 294 | pub fn par_scan_where<T, P, F>(&self, pre: P, keep: F) -> Result<Vec<T>> |
| 295 | where |
| 296 | T: Send, |
| 297 | P: Fn(&Class, bool) -> bool + Sync + 'static, |
| 298 | F: Fn(Feature) -> Option<T> + Sync, |
| 299 | { |
| 300 | let pre = move |props: &[(String, Value)]| -> bool { |
| 301 | let class = props.iter().find_map(|(k, v)| match (k.as_str(), v) { |
| 302 | (CLASS_KEY, Value::Uint(bits)) => Some(unpack(*bits)), |
| 303 | _ => None, |
| 304 | }); |
| 305 | // A record with no class is corrupt: let it through so `feature_of` reports it. |
| 306 | let Some(class) = class else { return true }; |
| 307 | pre(&class, props.iter().any(|(k, _)| k == ID_KEY)) |
| 308 | }; |
| 309 | use rayon::prelude::*; |
| 310 | let chunks = self.open_chunks()?; |
| 311 | let n = chunks.chunk_count(); |
| 312 | // Groups bound what is in flight (one `Vec` header per chunk) on a 21 M-chunk planet. |
| 313 | const GROUP: usize = 1 << 16; |
| 314 | let mut out = Vec::new(); |
| 315 | let mut start = 0usize; |
| 316 | while start < n { |
| 317 | let end = (start + GROUP).min(n); |
| 318 | let results: Vec<Result<Vec<T>>> = tile_build::par::install(|| { |
| 319 | (start..end) |
| 320 | .into_par_iter() |
| 321 | .map_init( |
| 322 | || (Vec::new(), Vec::new()), |
| 323 | |(scratch, records), i| -> Result<Vec<T>> { |
| 324 | chunks |
| 325 | .read_into_where(i, scratch, records, &pre) |
| 326 | .map_err(|e| osm_ingest::proto::Error(e.to_string()))?; |
| 327 | let mut kept = Vec::new(); |
| 328 | for record in records.drain(..) { |
| 329 | if let Some(v) = keep(feature_of(record)?) { |
| 330 | kept.push(v); |
| 331 | } |
| 332 | } |
| 333 | Ok(kept) |
| 334 | }, |
| 335 | ) |
| 336 | .collect() |
| 337 | }); |
| 338 | for r in results { |
| 339 | out.extend(r?); |
| 340 | } |
| 341 | start = end; |
| 342 | } |
| 343 | Ok(out) |
| 344 | } |
| 345 | } |