Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / osm_ingest / src / pbf.rs
pbf.rs305 lines · 13.7 KiBRaw
| 1 | //! `.osm.pbf` container: blob framing, inflate, `PrimitiveBlock` decode, and the |
| 2 | //! parallel pass driver. |
| 3 | //! |
| 4 | //! A `.osm.pbf` is a flat sequence of |
| 5 | //! `[u32 big-endian header_len][BlobHeader][Blob]`. Because the framing is |
| 6 | //! self-describing we can cheaply *scan* the file once, recording each blob's |
| 7 | //! `(offset, len)`, and afterwards let N threads each seek to and inflate their |
| 8 | //! own blobs from their own `File` handle. That replaces the old C++ |
| 9 | //! `ThreadPool`/`MoveTask`/throttling-condvar machinery — and the data race its |
| 10 | //! comments described — with a plain `std::thread::scope`. |
| 11 | //! |
| 12 | //! Work is split into fixed contiguous *chunks* of blobs (not dynamically per |
| 13 | //! blob) so results can be merged in chunk order. That is what makes the whole |
| 14 | //! tool deterministic: name-pool offsets and record order no longer depend on |
| 15 | //! thread scheduling, which the C++ generator's did. |
| 16 | |
| 17 | use std::fs::File; |
| 18 | use std::io::{BufReader, Read, Seek, SeekFrom, Write}; |
| 19 | use std::path::Path; |
| 20 | use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering}; |
| 21 | use std::sync::Mutex; |
| 22 | |
| 23 | use crate::pbf_extra::decode_blob_header; |
| 24 | use crate::proto::{self, Error, Reader, Result, WIRE_BYTES}; |
| 25 | |
| 26 | pub use crate::pbf_extra::probe_compression; |
| 27 | pub use crate::pbf_extra::{load_blob_kinds, write_blob_kinds, BLOB_KINDS_FILE}; |
| 28 | |
| 29 | /// Kind bits: which entity types a pass wants, and which a blob contains. |
| 30 | pub const KIND_NODES: u8 = 1; |
| 31 | pub const KIND_WAYS: u8 = 2; |
| 32 | pub const KIND_RELATIONS: u8 = 4; |
| 33 | |
| 34 | /// A blob is capped at 32 MiB uncompressed by the format spec; allow some slack |
| 35 | /// but refuse absurd sizes so a corrupt length can't trigger a huge allocation. |
| 36 | const MAX_BLOB_BYTES: usize = 128 * 1024 * 1024; |
| 37 | |
| 38 | /// Blobs per work chunk. Fixed (rather than derived from the core count) so the |
| 39 | /// merge order — and therefore every output byte — is identical on any machine. |
| 40 | /// |
| 41 | /// **It also sets peak memory**, because it is the multiplier on the reorder buffer. |
| 42 | /// [`run_pass_sink`] lets `2 * threads` chunk accumulators sit in [`Drain::slots`] at |
| 43 | /// once, and a pass 1 accumulator holds every classified way in its chunk *with that |
| 44 | /// way's node refs*. So the bytes in flight are `2 * threads * CHUNK_BLOBS` blobs' worth |
| 45 | /// of ways, and only this constant is not a property of the machine. |
| 46 | /// |
| 47 | /// **Lowered from 64.** On a 64-core box the window is 128 chunks, which at 64 blobs a |
| 48 | /// chunk is 8192 blobs — more than a California extract has, so the "bound" bound nothing |
| 49 | /// and the reorder buffer was the whole build's peak: 2.19 GB, a few seconds into pass 1. |
| 50 | /// At 8 blobs a chunk the same window is 1024 blobs and the peak of stage A falls to |
| 51 | /// 1.58 GB, which is the node-location table underneath it. It costs eight times as many |
| 52 | /// `deposit` calls — one mutex acquisition each, against a chunk of work measured in |
| 53 | /// milliseconds — and it was inside the noise on a California build. |
| 54 | /// |
| 55 | /// Byte-neutral, which is what makes it safe to tune: chunks are contiguous blob ranges |
| 56 | /// drained in ascending order, so regrouping them cannot reorder the ways inside them. |
| 57 | pub(crate) const CHUNK_BLOBS: usize = 8; |
| 58 | |
| 59 | /// Where one `OSMData` blob lives in the file. |
| 60 | #[derive(Clone, Copy)] |
| 61 | pub struct BlobLoc { |
| 62 | pub offset: u64, |
| 63 | pub datasize: u32, |
| 64 | } |
| 65 | |
| 66 | /// Scan the framing once, returning every `OSMData` blob's location. Only blob |
| 67 | /// *headers* are read, so this is I/O-cheap even on a 1.3 GB extract. |
| 68 | pub fn scan_blobs(path: &Path) -> Result<Vec<BlobLoc>> { |
| 69 | let file = |
| 70 | File::open(path).map_err(|e| Error(format!("cannot open {}: {e}", path.display())))?; |
| 71 | let total = |
| 72 | file.metadata().map_err(|e| Error(format!("cannot stat {}: {e}", path.display())))?.len(); |
| 73 | let mut r = BufReader::with_capacity(1 << 20, file); |
| 74 | let mut out = Vec::new(); |
| 75 | let mut pos: u64 = 0; |
| 76 | let mut header = Vec::new(); |
| 77 | |
| 78 | while pos < total { |
| 79 | let mut len_buf = [0u8; 4]; |
| 80 | if let Err(e) = r.read_exact(&mut len_buf) { |
| 81 | return Err(Error(format!("truncated blob header length at {pos}: {e}"))); |
| 82 | } |
| 83 | let header_len = u32::from_be_bytes(len_buf) as usize; |
| 84 | if header_len == 0 || header_len > 64 * 1024 { |
| 85 | return proto::err(format!("implausible BlobHeader length {header_len} at {pos}")); |
| 86 | } |
| 87 | header.clear(); |
| 88 | header.resize(header_len, 0); |
| 89 | r.read_exact(&mut header) |
| 90 | .map_err(|e| Error(format!("truncated BlobHeader at {pos}: {e}")))?; |
| 91 | |
| 92 | let (kind, datasize) = decode_blob_header(&header)?; |
| 93 | let blob_offset = pos + 4 + header_len as u64; |
| 94 | if datasize as usize > MAX_BLOB_BYTES { |
| 95 | return proto::err(format!("blob at {blob_offset} claims {datasize} bytes")); |
| 96 | } |
| 97 | if kind == b"OSMData" { |
| 98 | out.push(BlobLoc { offset: blob_offset, datasize }); |
| 99 | } |
| 100 | pos = blob_offset + datasize as u64; |
| 101 | // seek_relative keeps the read buffer when the target is already inside it. |
| 102 | // Blobs average tens of KB, so one 1 MiB fill covers many headers; a plain |
| 103 | // `seek` would discard the buffer and refill it for every single blob. |
| 104 | r.seek_relative(datasize as i64) |
| 105 | .map_err(|e| Error(format!("seek to {pos} failed: {e}")))?; |
| 106 | } |
| 107 | Ok(out) |
| 108 | } |
| 109 | |
| 110 | /// Inflate one blob's payload into `out`. |
| 111 | /// |
| 112 | /// `Blob { bytes raw = 1; int32 raw_size = 2; bytes zlib_data = 3; ... }`. |
| 113 | /// The compressions we cannot decode without a C library (lzma/bzip2/lz4/zstd) |
| 114 | /// are reported as a clear error rather than silently skipped — a skipped blob |
| 115 | /// would produce a quietly incomplete graph. |
| 116 | /// |
| 117 | /// # `out` is the caller's buffer, and it is genuinely reused |
| 118 | /// |
| 119 | /// [`run_pass_sink`]'s workers hoist one of these out of the blob loop each, so a pass |
| 120 | /// allocates one inflate buffer per thread rather than one per blob. That only holds if |
| 121 | /// this function inflates *into* the buffer: the obvious |
| 122 | /// `*out = decompress_to_vec_zlib_with_limit(..)?` throws the caller's allocation away on |
| 123 | /// every blob, and worse, the new buffer is allocated and zero-filled before the old one |
| 124 | /// is dropped, so each worker is briefly holding two. |
| 125 | /// |
| 126 | /// It measured 1.5 GB of a 2.19 GB California peak. The peak of that whole build was one |
| 127 | /// second in, during the node region of pass 1 — before a single way had been classified |
| 128 | /// and long before any tile existed — and it scaled with the core count at ~24 MB a |
| 129 | /// thread, which is one and a bit blob buffers apiece. |
| 130 | /// |
| 131 | /// `raw_size` is what makes inflating in place possible: the blob states its own |
| 132 | /// uncompressed length, so the buffer can be sized exactly before decompressing rather |
| 133 | /// than grown by doubling. |
| 134 | pub fn inflate_blob(blob: &[u8], out: &mut Vec<u8>) -> Result<()> { |
| 135 | let mut r = Reader::new(blob); |
| 136 | let mut raw: Option<&[u8]> = None; |
| 137 | let mut raw_size: Option<usize> = None; |
| 138 | let mut zlib: Option<&[u8]> = None; |
| 139 | while let Some((field, wire)) = r.next_field()? { |
| 140 | match (field, wire) { |
| 141 | (1, WIRE_BYTES) => raw = Some(r.bytes()?), |
| 142 | (2, proto::WIRE_VARINT) => raw_size = Some(r.uvarint()? as usize), |
| 143 | (3, WIRE_BYTES) => zlib = Some(r.bytes()?), |
| 144 | (4, WIRE_BYTES) => return proto::err("blob uses lzma compression (unsupported)"), |
| 145 | (5, WIRE_BYTES) => return proto::err("blob uses bzip2 compression (unsupported)"), |
| 146 | (6, WIRE_BYTES) => return proto::err("blob uses lz4 compression (unsupported)"), |
| 147 | (7, WIRE_BYTES) => return proto::err("blob uses zstd compression (unsupported)"), |
| 148 | _ => r.skip(wire)?, |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | out.clear(); |
| 153 | if let Some(z) = zlib { |
| 154 | match raw_size.filter(|want| *want <= MAX_BLOB_BYTES) { |
| 155 | Some(want) => { |
| 156 | // Reuses the caller's capacity: `clear` kept it and `resize` fills it. |
| 157 | out.resize(want, 0); |
| 158 | // `zlib_header` true and `ignore_adler32` false, so this still parses the |
| 159 | // zlib header and verifies the Adler-32 trailer — a mis-framed or corrupt |
| 160 | // blob fails just as loudly as it did through the allocating path. |
| 161 | let got = miniz_oxide::inflate::decompress_slice_iter_to_slice( |
| 162 | out, |
| 163 | std::iter::once(z), |
| 164 | true, |
| 165 | false, |
| 166 | ) |
| 167 | .map_err(|e| Error(format!("inflate failed: {e:?}")))?; |
| 168 | // `out` is `want` long whatever happened, so a short inflate would slip |
| 169 | // past the raw_size check below. This is the one that catches it. |
| 170 | if got != want { |
| 171 | return proto::err(format!( |
| 172 | "blob inflated {got} byte(s) but raw_size says {want}" |
| 173 | )); |
| 174 | } |
| 175 | } |
| 176 | // No `raw_size`, so there is no length to size the buffer from and the growing |
| 177 | // allocator path is all that is left. Every conforming writer emits it, so this |
| 178 | // is the odd file rather than the hot path. |
| 179 | None => { |
| 180 | let limit = raw_size.unwrap_or(MAX_BLOB_BYTES).min(MAX_BLOB_BYTES); |
| 181 | let data = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(z, limit) |
| 182 | .map_err(|e| Error(format!("inflate failed: {e:?}")))?; |
| 183 | *out = data; |
| 184 | } |
| 185 | } |
| 186 | } else if let Some(bytes) = raw { |
| 187 | out.extend_from_slice(bytes); |
| 188 | } else { |
| 189 | return proto::err("blob has neither raw nor zlib_data"); |
| 190 | } |
| 191 | |
| 192 | if let Some(want) = raw_size { |
| 193 | if out.len() != want { |
| 194 | return proto::err(format!( |
| 195 | "blob inflated to {} bytes but raw_size says {want}", |
| 196 | out.len() |
| 197 | )); |
| 198 | } |
| 199 | } |
| 200 | Ok(()) |
| 201 | } |
| 202 | |
| 203 | /// One decoded `PrimitiveBlock`. Strings and group bodies are borrowed from the |
| 204 | /// inflated buffer, so decoding a block allocates only the two index vectors. |
| 205 | pub struct PrimitiveBlock<'a> { |
| 206 | pub strings: Vec<&'a [u8]>, |
| 207 | pub granularity: i64, |
| 208 | pub lat_offset: i64, |
| 209 | pub lon_offset: i64, |
| 210 | pub groups: Vec<&'a [u8]>, |
| 211 | } |
| 212 | |
| 213 | impl<'a> PrimitiveBlock<'a> { |
| 214 | pub fn decode(buf: &'a [u8]) -> Result<PrimitiveBlock<'a>> { |
| 215 | let mut block = PrimitiveBlock { |
| 216 | strings: Vec::new(), |
| 217 | granularity: 100, |
| 218 | lat_offset: 0, |
| 219 | lon_offset: 0, |
| 220 | groups: Vec::new(), |
| 221 | }; |
| 222 | let mut r = Reader::new(buf); |
| 223 | while let Some((field, wire)) = r.next_field()? { |
| 224 | match (field, wire) { |
| 225 | (1, WIRE_BYTES) => { |
| 226 | // StringTable { repeated bytes s = 1; } |
| 227 | let mut st = Reader::new(r.bytes()?); |
| 228 | while let Some((f, w)) = st.next_field()? { |
| 229 | if (f, w) == (1, WIRE_BYTES) { |
| 230 | block.strings.push(st.bytes()?); |
| 231 | } else { |
| 232 | st.skip(w)?; |
| 233 | } |
| 234 | } |
| 235 | } |
| 236 | (2, WIRE_BYTES) => block.groups.push(r.bytes()?), |
| 237 | (17, proto::WIRE_VARINT) => block.granularity = r.ivarint()?, |
| 238 | (19, proto::WIRE_VARINT) => block.lat_offset = r.ivarint()?, |
| 239 | (20, proto::WIRE_VARINT) => block.lon_offset = r.ivarint()?, |
| 240 | _ => r.skip(wire)?, |
| 241 | } |
| 242 | } |
| 243 | if block.granularity <= 0 { |
| 244 | return proto::err(format!("block granularity {}", block.granularity)); |
| 245 | } |
| 246 | Ok(block) |
| 247 | } |
| 248 | |
| 249 | #[inline] |
| 250 | pub fn string(&self, idx: u32) -> &'a [u8] { |
| 251 | self.strings.get(idx as usize).copied().unwrap_or(b"") |
| 252 | } |
| 253 | |
| 254 | /// Raw coordinate delta -> hundredths of a nanodegree -> 1e-7 degrees, the |
| 255 | /// integer libosmium's `Location` stores. Truncating division matches |
| 256 | /// libosmium's `convert_pbf_lat`, so coordinates are bit-identical to what |
| 257 | /// the old C++ tools saw. |
| 258 | #[inline] |
| 259 | pub fn lat_e7(&self, delta: i64) -> i32 { |
| 260 | ((self.lat_offset + self.granularity * delta) / 100) as i32 |
| 261 | } |
| 262 | |
| 263 | #[inline] |
| 264 | pub fn lon_e7(&self, delta: i64) -> i32 { |
| 265 | ((self.lon_offset + self.granularity * delta) / 100) as i32 |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | /// Run one pass over the file in parallel, folding each chunk's accumulator as |
| 270 | /// soon as it is complete. |
| 271 | /// |
| 272 | /// `make` builds a fresh accumulator per chunk, `body` is called once per blob |
| 273 | /// with that chunk's accumulator and must return the kind bits the blob held, and |
| 274 | /// `sink` receives finished accumulators **in chunk order** so merging stays |
| 275 | /// deterministic. |
| 276 | /// |
| 277 | /// Prefer this to [`run_pass`] for anything whose accumulators are large. A |
| 278 | /// planet-scale pass cannot afford `run_pass`'s contract of handing back every |
| 279 | /// chunk at once: on California the pass-2 node accumulators are about a |
| 280 | /// gigabyte, and the caller then folds them into a second copy, so the two peak |
| 281 | /// together. Here a chunk is folded and freed while its neighbours are still |
| 282 | /// being decoded, which also overlaps the merge with the I/O. |
| 283 | /// |
| 284 | /// `sink` runs on the calling thread, one chunk at a time and strictly in chunk |
| 285 | /// order, outside any lock the workers take — so it overlaps with decoding but |
| 286 | /// is still the same single-threaded, ordered merge [`run_pass`]'s callers do. |
| 287 | /// |
| 288 | /// `blob_kinds` (from a previous full pass) lets later passes skip blobs that |
| 289 | /// hold nothing they want — a real win because a PBF stores all nodes first, |
| 290 | /// then ways, then relations. A skipped blob's incoming kinds are carried into |
| 291 | /// the returned mask, so a filtered pass's mask is still a complete description |
| 292 | /// of the file and can be fed to the pass after it. |
| 293 | /// Which blobs a pass wants, and how it is labelled in progress output. |
| 294 | #[derive(Clone, Copy)] |
| 295 | pub struct PassSpec<'a> { |
| 296 | /// Kind mask from a previous full pass, letting this pass skip blobs that |
| 297 | /// hold nothing it wants. `None` scans every blob. |
| 298 | pub blob_kinds: Option<&'a [u8]>, |
| 299 | /// Bitmask of blob kinds this pass wants. |
| 300 | pub want: u8, |
| 301 | /// Progress label. |
| 302 | pub label: &'a str, |
| 303 | } |
| 304 | |
| 305 | include!("pbf_s1.rs"); |