Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / scripts / maps / osm_ingest / src / pbf_extra.rs

pbf_extra.rs498 lines · 20.8 KiBRaw
1use std::fs::File;
2use std::path::Path;
3
4use crate::pbf::{BlobLoc, PrimitiveBlock, inflate_blob, read_exact_at};
5use crate::proto::{self, Error, Reader, Result, WIRE_BYTES};
6
7/// `BlobHeader { required string type = 1; required int32 datasize = 3; }`
8pub(crate) fn decode_blob_header(buf: &[u8]) -> Result<(&[u8], u32)> {
9 let mut r = Reader::new(buf);
10 let mut kind: &[u8] = b"";
11 let mut datasize: Option<u32> = None;
12 while let Some((field, wire)) = r.next_field()? {
13 match (field, wire) {
14 (1, WIRE_BYTES) => kind = r.bytes()?,
15 (3, proto::WIRE_VARINT) => datasize = Some(r.uvarint()? as u32),
16 _ => r.skip(wire)?,
17 }
18 }
19 match datasize {
20 Some(d) => Ok((kind, d)),
21 None => proto::err("BlobHeader without datasize"),
22 }
23}
24
25/// Inflate and decode the first data blob, so a file we cannot read fails in
26/// seconds instead of at the end of a multi-hour pass.
27///
28/// Worth its own step because the compression is a property of the whole file:
29/// a planet mirror published with zstd blobs is unreadable here, and finding
30/// that out after an 80 GB download and one full pass is the expensive way to
31/// learn it.
32pub fn probe_compression(path: &Path, blobs: &[BlobLoc]) -> Result<()> {
33 let Some(first) = blobs.first() else {
34 return Ok(());
35 };
36 let mut file =
37 File::open(path).map_err(|e| Error(format!("cannot open {}: {e}", path.display())))?;
38 let mut compressed = Vec::new();
39 let mut inflated = Vec::new();
40 read_exact_at(&mut file, first, &mut compressed)?;
41 inflate_blob(&compressed, &mut inflated)?;
42 PrimitiveBlock::decode(&inflated)?;
43 Ok(())
44}
45
46/// The file name a full pass's blob-kinds mask is cached under, beside a tool's output.
47pub const BLOB_KINDS_FILE: &str = "blob_kinds.bin";
48
49/// Magic + version for the blob-kinds sidecar. Bumped if the header or payload layout changes, so an
50/// old sidecar is rejected rather than misread.
51const BLOB_KINDS_MAGIC: &[u8; 4] = b"MBK1";
52
53/// Header bytes before the per-blob kind payload: magic, blob count, source length, mtime.
54const BLOB_KINDS_HEAD: usize = 4 + 8 + 8 + 8 + 4;
55
56/// Persist a complete per-blob kind mask beside a tool's output, guarded against the source `.pbf`
57/// it describes.
58///
59/// A full pass already learns which blobs hold nodes, ways or relations; two tools run back to back
60/// over the same file (`road_graph` then `mamaps_build`) both want that mask, and the second would
61/// otherwise pay a full scan to recompute it. Writing it here lets the second load it instead. The
62/// guard -- blob count, file length and mtime -- is what makes a stale sidecar a fall-back rather
63/// than a wrong answer; see [`load_blob_kinds`].
64pub fn write_blob_kinds(dir: &Path, input: &Path, kinds: &[u8]) -> Result<()> {
65 let meta = std::fs::metadata(input)
66 .map_err(|e| Error(format!("cannot stat {}: {e}", input.display())))?;
67 let (secs, nanos) = mtime_parts(&meta);
68 let mut out = Vec::with_capacity(BLOB_KINDS_HEAD + kinds.len());
69 out.extend_from_slice(BLOB_KINDS_MAGIC);
70 out.extend_from_slice(&(kinds.len() as u64).to_le_bytes());
71 out.extend_from_slice(&meta.len().to_le_bytes());
72 out.extend_from_slice(&secs.to_le_bytes());
73 out.extend_from_slice(&nanos.to_le_bytes());
74 out.extend_from_slice(kinds);
75 let path = dir.join(BLOB_KINDS_FILE);
76 std::fs::write(&path, &out)
77 .map_err(|e| Error(format!("cannot write {}: {e}", path.display())))
78}
79
80/// Load a blob-kinds mask written by [`write_blob_kinds`], but only if it still describes `input`.
81///
82/// `None` on any mismatch or error -- a missing file, wrong magic, a different blob count, a changed
83/// length or mtime, a short read -- so the caller falls back to a full scan. `blobs` supplies the
84/// count the mask must match; nothing here trusts the file's own count past that check. The returned
85/// mask is byte-for-byte what a full pass over `input` would produce, so feeding it to a later pass
86/// changes no output.
87pub fn load_blob_kinds(dir: &Path, input: &Path, blobs: &[BlobLoc]) -> Option<Vec<u8>> {
88 let raw = std::fs::read(dir.join(BLOB_KINDS_FILE)).ok()?;
89 if raw.len() < BLOB_KINDS_HEAD || &raw[0..4] != BLOB_KINDS_MAGIC {
90 return None;
91 }
92 let count = u64::from_le_bytes(raw[4..12].try_into().ok()?);
93 let file_len = u64::from_le_bytes(raw[12..20].try_into().ok()?);
94 let secs = u64::from_le_bytes(raw[20..28].try_into().ok()?);
95 let nanos = u32::from_le_bytes(raw[28..32].try_into().ok()?);
96 // The count must match the file being read now, and the payload must be exactly that many bytes:
97 // a truncated or padded sidecar is as untrustworthy as a stale one.
98 if count as usize != blobs.len() || raw.len() != BLOB_KINDS_HEAD + blobs.len() {
99 return None;
100 }
101 let meta = std::fs::metadata(input).ok()?;
102 if meta.len() != file_len || mtime_parts(&meta) != (secs, nanos) {
103 return None;
104 }
105 Some(raw[BLOB_KINDS_HEAD..].to_vec())
106}
107
108/// A file's modification time as `(seconds, nanoseconds)` since the Unix epoch, or `(0, 0)` when the
109/// platform cannot report one. Split rather than a single `u128` so the sidecar header is fixed-width
110/// integers that any reader can parse without a wide type.
111fn mtime_parts(meta: &std::fs::Metadata) -> (u64, u32) {
112 match meta.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) {
113 Some(d) => (d.as_secs(), d.subsec_nanos()),
114 None => (0, 0),
115 }
116}
117
118#[cfg(test)]
119mod tests {
120 use super::*;
121 use crate::pbf::{CHUNK_BLOBS, KIND_NODES, KIND_RELATIONS, KIND_WAYS, run_pass, run_pass_sink, scan_blobs};
122 use crate::testpbf;
123 use std::sync::atomic::{AtomicUsize, Ordering};
124
125 /// A file with enough `OSMData` blobs to span several chunks, so the reorder
126 /// buffer and its window are actually reached.
127 fn multi_chunk_pbf(chunks: usize) -> (std::path::PathBuf, std::path::PathBuf) {
128 let block = testpbf::primitive_block();
129 let blobs = chunks * CHUNK_BLOBS;
130 let refs: Vec<&[u8]> = (0..blobs).map(|_| block.as_slice()).collect();
131 let bytes = testpbf::pbf_from_blocks(refs);
132 let dir = std::env::temp_dir().join(format!(
133 "osm_ingest_window_{}_{chunks}_{:?}",
134 std::process::id(),
135 std::thread::current().id()
136 ));
137 let _ = std::fs::remove_dir_all(&dir);
138 std::fs::create_dir_all(&dir).unwrap();
139 let path = dir.join("many.osm.pbf");
140 std::fs::write(&path, &bytes).unwrap();
141 (path, dir)
142 }
143
144 /// The reorder buffer must not grow with the file.
145 ///
146 /// A worker deposits a finished chunk and immediately claims another, so without a
147 /// window one slow chunk 0 parks every later chunk's accumulator at once — and on a
148 /// planet pass those accumulators are the largest things in the build. Chunk 0 is
149 /// made slow here on purpose; the counter is what proves the bound, because the
150 /// pass would produce correct output either way.
151 #[test]
152 fn the_reorder_buffer_stays_bounded_when_the_first_chunk_lags() {
153 let (path, _dir) = multi_chunk_pbf(40);
154 crate::par::set_threads(4);
155 let blobs = scan_blobs(&path).unwrap();
156 let n_chunks = blobs.len().div_ceil(CHUNK_BLOBS);
157 assert!(n_chunks >= 40, "{n_chunks} chunk(s) is not enough to bound anything");
158
159 // Accumulators alive right now, and the worst it ever got.
160 let live = std::sync::Arc::new(AtomicUsize::new(0));
161 let peak = std::sync::Arc::new(AtomicUsize::new(0));
162
163 struct Acc {
164 live: std::sync::Arc<AtomicUsize>,
165 }
166 impl Drop for Acc {
167 fn drop(&mut self) {
168 self.live.fetch_sub(1, Ordering::SeqCst);
169 }
170 }
171
172 let first_seen = AtomicUsize::new(0);
173 let (mk_live, mk_peak) = (live.clone(), peak.clone());
174 let drained = std::sync::Mutex::new(Vec::new());
175 run_pass_sink(
176 &path,
177 &blobs,
178 None,
179 KIND_NODES,
180 "window",
181 || {
182 let n = mk_live.fetch_add(1, Ordering::SeqCst) + 1;
183 mk_peak.fetch_max(n, Ordering::SeqCst);
184 Acc { live: mk_live.clone() }
185 },
186 |_acc, _block| {
187 // Only the very first chunk to start is slowed, which is enough to make
188 // every other worker run ahead of the sink.
189 if first_seen.fetch_add(1, Ordering::SeqCst) == 0 {
190 std::thread::sleep(std::time::Duration::from_millis(300));
191 }
192 Ok(KIND_NODES)
193 },
194 |acc: Acc| {
195 drained.lock().unwrap().push(());
196 drop(acc);
197 Ok(())
198 },
199 )
200 .unwrap();
201
202 assert_eq!(drained.into_inner().unwrap().len(), n_chunks, "every chunk drains");
203 assert_eq!(live.load(Ordering::SeqCst), 0, "an accumulator leaked");
204 // 4 threads => a window of 8, plus the one each worker is filling. Well under
205 // the ~40 that would pile up if the workers were free to run to the end of the
206 // file, which is what makes this assertion mean something.
207 let bound = 8 + 4;
208 let got = peak.load(Ordering::SeqCst);
209 assert!(
210 got <= bound,
211 "{got} accumulators were live at once over {n_chunks} chunks; \
212 the window should have held it to {bound}"
213 );
214 crate::par::clear_threads();
215 }
216
217 #[test]
218 fn round_trips_a_synthetic_file() {
219 let (path, _dir) = testpbf::write_sample("pbf_pass");
220
221 let blobs = scan_blobs(&path).unwrap();
222 assert_eq!(blobs.len(), 1, "the OSMHeader blob is not returned");
223
224 let (states, kinds) = run_pass(
225 &path,
226 &blobs,
227 None,
228 KIND_NODES | KIND_WAYS | KIND_RELATIONS,
229 "test",
230 || (0usize, 0usize, 0usize),
231 |s: &mut (usize, usize, usize), block| {
232 let mut mask = 0;
233 crate::osm::visit_block(
234 block,
235 KIND_NODES | KIND_WAYS | KIND_RELATIONS,
236 &mut mask,
237 &mut |el: crate::osm::Element| {
238 match el {
239 crate::osm::Element::Node(_) => s.0 += 1,
240 crate::osm::Element::Way(_) => s.1 += 1,
241 crate::osm::Element::Relation(_) => s.2 += 1,
242 }
243 Ok(())
244 },
245 )?;
246 Ok(mask)
247 },
248 )
249 .unwrap();
250 let totals = states
251 .iter()
252 .fold((0, 0, 0), |a, b| (a.0 + b.0, a.1 + b.1, a.2 + b.2));
253 assert_eq!(totals, (testpbf::NODE_COUNT, 3, 1));
254 assert_eq!(kinds[0], KIND_NODES | KIND_WAYS | KIND_RELATIONS);
255 }
256
257 #[test]
258 fn blob_kind_filter_skips_whole_blobs() {
259 let (path, _dir) = testpbf::write_sample("pbf_filter");
260 let blobs = scan_blobs(&path).unwrap();
261 // Pretend the only blob holds nothing but nodes; a ways pass must then
262 // never even read it.
263 let (states, _) = run_pass(
264 &path,
265 &blobs,
266 Some(&[KIND_NODES]),
267 KIND_WAYS,
268 "test",
269 || 0usize,
270 |s: &mut usize, _block| {
271 *s += 1;
272 Ok(0)
273 },
274 )
275 .unwrap();
276 assert_eq!(states.iter().sum::<usize>(), 0);
277 }
278
279 #[test]
280 fn a_skipped_blob_keeps_its_kinds_in_the_returned_mask() {
281 let (path, _dir) = testpbf::write_sample("pbf_carry");
282 let blobs = scan_blobs(&path).unwrap();
283 let all = KIND_NODES | KIND_WAYS | KIND_RELATIONS;
284 // A relations-only pass skips this nodes-and-ways-and-relations blob only
285 // if we lie about its contents; do that, and check the lie comes back
286 // rather than a zero. A pass that dropped the kinds would make its own
287 // returned mask useless to the pass after it.
288 let (_, kinds) = run_pass(
289 &path,
290 &blobs,
291 Some(&[KIND_NODES]),
292 KIND_WAYS,
293 "test",
294 || (),
295 |_: &mut (), _| Ok(all),
296 )
297 .unwrap();
298 assert_eq!(kinds, vec![KIND_NODES]);
299
300 // A blob the pass does read reports what it actually saw.
301 let (_, kinds) = run_pass(
302 &path,
303 &blobs,
304 Some(&[KIND_WAYS]),
305 KIND_WAYS,
306 "test",
307 || (),
308 |_: &mut (), _| Ok(all),
309 )
310 .unwrap();
311 assert_eq!(kinds, vec![all]);
312 }
313
314 #[test]
315 fn the_compression_probe_accepts_zlib_and_rejects_zstd() {
316 let (path, dir) = testpbf::write_sample("pbf_probe");
317 let blobs = scan_blobs(&path).unwrap();
318 probe_compression(&path, &blobs).unwrap();
319
320 // One OSMData blob whose only field is `zstd_data`.
321 let blob = [7 << 3 | WIRE_BYTES, 1, 0];
322 let mut header = vec![1 << 3 | WIRE_BYTES, 7];
323 header.extend_from_slice(b"OSMData");
324 header.extend_from_slice(&[3 << 3 | proto::WIRE_VARINT, blob.len() as u8]);
325 let mut file = Vec::new();
326 file.extend_from_slice(&(header.len() as u32).to_be_bytes());
327 file.extend_from_slice(&header);
328 file.extend_from_slice(&blob);
329 let zstd_path = dir.join("zstd.osm.pbf");
330 std::fs::write(&zstd_path, &file).unwrap();
331
332 let blobs = scan_blobs(&zstd_path).unwrap();
333 assert_eq!(blobs.len(), 1);
334 let err = probe_compression(&zstd_path, &blobs).unwrap_err();
335 assert!(err.0.contains("zstd"), "{}", err.0);
336 }
337
338 /// Unsigned varint, for the two length-delimited fields the helpers below write. The
339 /// crate's `proto` has the decoder but no encoder — nothing in `osm_ingest` writes
340 /// protobuf outside tests.
341 fn put_uvarint(out: &mut Vec<u8>, mut value: u64) {
342 loop {
343 let byte = (value & 0x7f) as u8;
344 value >>= 7;
345 if value == 0 {
346 out.push(byte);
347 return;
348 }
349 out.push(byte | 0x80);
350 }
351 }
352
353 /// A zlib stream wrapping `data` in a single STORED deflate block.
354 ///
355 /// Hand-rolled rather than compressed, because `osm_ingest` takes miniz_oxide for its
356 /// inflate side only and a test should not pull in a compressor to make three bytes.
357 /// A stored block still exercises the whole path this cares about: the zlib header is
358 /// parsed and the Adler-32 trailer is verified exactly as it is for a real blob.
359 fn zlib_stored(data: &[u8]) -> Vec<u8> {
360 let mut out = vec![0x78, 0x01];
361 let len = data.len() as u16;
362 out.push(0x01); // BFINAL = 1, BTYPE = 00 (stored)
363 out.extend_from_slice(&len.to_le_bytes());
364 out.extend_from_slice(&(!len).to_le_bytes());
365 out.extend_from_slice(data);
366 let (mut a, mut b) = (1u32, 0u32);
367 for &byte in data {
368 a = (a + byte as u32) % 65521;
369 b = (b + a) % 65521;
370 }
371 out.extend_from_slice(&((b << 16) | a).to_be_bytes());
372 out
373 }
374
375 /// A `Blob` message carrying `zlib_data` and a `raw_size`.
376 fn zlib_blob(data: &[u8], raw_size: usize) -> Vec<u8> {
377 let stream = zlib_stored(data);
378 let mut blob = Vec::new();
379 blob.push(2 << 3 | proto::WIRE_VARINT);
380 put_uvarint(&mut blob, raw_size as u64);
381 blob.push(3 << 3 | WIRE_BYTES);
382 put_uvarint(&mut blob, stream.len() as u64);
383 blob.extend_from_slice(&stream);
384 blob
385 }
386
387 /// **The allocation bound on a parallel pass.** `run_pass_sink` gives each worker one
388 /// inflate buffer for the whole file, so `inflate_blob` must decompress *into* it.
389 ///
390 /// Assigning a fresh `Vec` over `out` instead measured 1.5 GB of a 2.19 GB California
391 /// peak — 64 workers each holding a blob buffer, briefly two, none of them reused —
392 /// and that peak was the whole build's, one second in. Nothing about the output bytes
393 /// changes either way, so only a capacity assertion can catch a regression.
394 #[test]
395 fn inflating_reuses_the_callers_buffer_rather_than_replacing_it() {
396 let big = vec![7u8; 40_000];
397 let small = b"tiny".to_vec();
398 let mut out = Vec::new();
399
400 inflate_blob(&zlib_blob(&big, big.len()), &mut out).expect("big");
401 assert_eq!(out, big, "the big blob must round trip");
402 let capacity = out.capacity();
403 assert!(capacity >= big.len(), "buffer must hold what it inflated");
404
405 inflate_blob(&zlib_blob(&small, small.len()), &mut out).expect("small");
406 assert_eq!(out, small, "the small blob must round trip");
407 assert_eq!(
408 out.capacity(),
409 capacity,
410 "a second, smaller blob must reuse the buffer rather than allocate a new one",
411 );
412 }
413
414 /// The allocating path verified the Adler-32 trailer, and the in-place one has to as
415 /// well. A corrupt blob that inflated silently would be a quietly incomplete graph.
416 #[test]
417 fn a_corrupt_adler_trailer_is_still_rejected() {
418 let data = b"the quick brown fox".to_vec();
419 let mut blob = zlib_blob(&data, data.len());
420 let last = blob.len() - 1;
421 blob[last] ^= 0xff;
422 let mut out = Vec::new();
423 let err = inflate_blob(&blob, &mut out).expect_err("a bad checksum must be refused");
424 assert!(err.0.contains("inflate failed"), "{}", err.0);
425 }
426
427 /// A `raw_size` smaller than the payload must error rather than hand back a truncated
428 /// block. The buffer is sized from `raw_size`, so `out.len()` matches it whatever
429 /// happened and the length check at the end of `inflate_blob` cannot see this.
430 #[test]
431 fn a_zlib_blob_whose_raw_size_is_too_small_is_rejected() {
432 let data = b"0123456789".to_vec();
433 let mut out = Vec::new();
434 let err = inflate_blob(&zlib_blob(&data, 4), &mut out)
435 .expect_err("a short raw_size must be refused");
436 assert!(err.0.contains("inflate"), "{}", err.0);
437 }
438
439 #[test]
440 fn raw_size_mismatch_is_rejected() {
441 // Blob claiming a raw_size that disagrees with the payload.
442 let mut blob = Vec::new();
443 blob.push(1 << 3 | WIRE_BYTES);
444 blob.push(3);
445 blob.extend_from_slice(b"abc");
446 blob.push(2 << 3 | proto::WIRE_VARINT);
447 blob.push(9);
448 let mut out = Vec::new();
449 assert!(inflate_blob(&blob, &mut out).is_err());
450 }
451
452 #[test]
453 fn unsupported_compression_is_reported() {
454 let mut blob = vec![7 << 3 | WIRE_BYTES, 1, 0];
455 let mut out = Vec::new();
456 let err = inflate_blob(&blob, &mut out).unwrap_err();
457 assert!(err.0.contains("zstd"), "{}", err.0);
458 blob[0] = 4 << 3 | WIRE_BYTES;
459 let err = inflate_blob(&blob, &mut out).unwrap_err();
460 assert!(err.0.contains("lzma"), "{}", err.0);
461 }
462
463 /// The blob-kinds sidecar round trips, and every guard rejects a file that no longer matches: a
464 /// stale sidecar must load as `None` (a full-scan fallback), never as a wrong mask.
465 #[test]
466 fn a_blob_kinds_sidecar_round_trips_and_the_guards_reject_a_changed_file() {
467 let dir = std::env::temp_dir().join(format!(
468 "osm_ingest_bk_{}_{:?}",
469 std::process::id(),
470 std::thread::current().id()
471 ));
472 let _ = std::fs::remove_dir_all(&dir);
473 std::fs::create_dir_all(&dir).unwrap();
474 let input = dir.join("in.osm.pbf");
475 std::fs::write(&input, b"a fake pbf, only its length and mtime matter here").unwrap();
476
477 let blobs: Vec<BlobLoc> = (0..5).map(|_| BlobLoc { offset: 0, datasize: 0 }).collect();
478 let kinds = vec![KIND_NODES, KIND_NODES | KIND_WAYS, KIND_WAYS, KIND_RELATIONS, 0];
479 write_blob_kinds(&dir, &input, &kinds).unwrap();
480
481 // Happy path: same file, same blob count.
482 assert_eq!(load_blob_kinds(&dir, &input, &blobs).as_deref(), Some(kinds.as_slice()));
483 // A different blob count is a different file to pass 1, whatever the sidecar claims.
484 let fewer: Vec<BlobLoc> = blobs[..4].to_vec();
485 assert!(load_blob_kinds(&dir, &input, &fewer).is_none(), "blob-count guard did not fire");
486 // A changed source length must invalidate it.
487 std::fs::write(&input, b"a different length entirely").unwrap();
488 assert!(load_blob_kinds(&dir, &input, &blobs).is_none(), "length guard did not fire");
489 // Wrong magic: a foreign or corrupt file at the path is rejected, not misread.
490 std::fs::write(dir.join(BLOB_KINDS_FILE), b"not a real sidecar").unwrap();
491 assert!(load_blob_kinds(&dir, &input, &blobs).is_none(), "magic guard did not fire");
492 // A missing sidecar is simply a full-scan fallback.
493 std::fs::remove_file(dir.join(BLOB_KINDS_FILE)).unwrap();
494 assert!(load_blob_kinds(&dir, &input, &blobs).is_none(), "a missing sidecar must be None");
495
496 let _ = std::fs::remove_dir_all(&dir);
497 }
498}