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

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

pbf_extra.rs128 lines · 6.0 KiBRaw
1use std::fs::File;
2use std::path::Path;
3
4use crate::pbf::{inflate_blob, read_exact_at, BlobLoc, PrimitiveBlock};
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. `MBK2` replaced `MBK1`'s source mtime with a content
51/// fingerprint, so the graph directory is byte-identical wherever and whenever the `.pbf` lives.
52const BLOB_KINDS_MAGIC: &[u8; 4] = b"MBK2";
53
54/// Header bytes before the per-blob kind payload: magic, blob count, source length, fingerprint.
55const BLOB_KINDS_HEAD: usize = 4 + 8 + 8 + 8;
56
57/// What guards a blob-kinds sidecar against a different `.pbf`: the file's content fingerprint
58/// (length, first and last 4 MiB -- [`crate::fingerprint::file_fingerprint`]) mixed with the blob
59/// index pass 1 already holds (every blob's offset and size), so an edit anywhere that resizes a
60/// blob changes it. Never a path or a timestamp: a copy of the same file elsewhere, or touched,
61/// still matches, and the sidecar's bytes depend only on the input's bytes.
62fn blob_kinds_guard(input: &Path, blobs: &[BlobLoc]) -> Result<u64> {
63 let mut h = crate::fingerprint::Fnv::default();
64 h.eat(b"blob-kinds/2");
65 h.eat_u64(
66 crate::fingerprint::file_fingerprint(input)
67 .map_err(|e| Error(format!("cannot read {}: {e}", input.display())))?,
68 );
69 h.eat_u64(blobs.len() as u64);
70 for b in blobs {
71 h.eat_u64(b.offset);
72 h.eat_u64(b.datasize as u64);
73 }
74 Ok(h.finish())
75}
76
77/// Persist a complete per-blob kind mask beside a tool's output, guarded against the source `.pbf`
78/// it describes.
79///
80/// A full pass already learns which blobs hold nodes, ways or relations; two tools run back to back
81/// over the same file (`road_graph` then `mamaps_build`) both want that mask, and the second would
82/// otherwise pay a full scan to recompute it. Writing it here lets the second load it instead. The
83/// guard -- blob count, file length and a content fingerprint ([`blob_kinds_guard`]) -- is what
84/// makes a stale sidecar a fall-back rather than a wrong answer; see [`load_blob_kinds`].
85pub fn write_blob_kinds(dir: &Path, input: &Path, blobs: &[BlobLoc], kinds: &[u8]) -> Result<()> {
86 let len = std::fs::metadata(input)
87 .map_err(|e| Error(format!("cannot stat {}: {e}", input.display())))?
88 .len();
89 let guard = blob_kinds_guard(input, blobs)?;
90 let mut out = Vec::with_capacity(BLOB_KINDS_HEAD + kinds.len());
91 out.extend_from_slice(BLOB_KINDS_MAGIC);
92 out.extend_from_slice(&(kinds.len() as u64).to_le_bytes());
93 out.extend_from_slice(&len.to_le_bytes());
94 out.extend_from_slice(&guard.to_le_bytes());
95 out.extend_from_slice(kinds);
96 let path = dir.join(BLOB_KINDS_FILE);
97 std::fs::write(&path, &out).map_err(|e| Error(format!("cannot write {}: {e}", path.display())))
98}
99
100/// Load a blob-kinds mask written by [`write_blob_kinds`], but only if it still describes `input`.
101///
102/// `None` on any mismatch or error -- a missing file, wrong magic (an `MBK1` sidecar included), a
103/// different blob count, a changed length or fingerprint, a short read -- so the caller falls back
104/// to a full scan. `blobs` supplies the count the mask must match; nothing here trusts the file's
105/// own count past that check. The returned mask is byte-for-byte what a full pass over `input`
106/// would produce, so feeding it to a later pass changes no output.
107pub fn load_blob_kinds(dir: &Path, input: &Path, blobs: &[BlobLoc]) -> Option<Vec<u8>> {
108 let raw = std::fs::read(dir.join(BLOB_KINDS_FILE)).ok()?;
109 if raw.len() < BLOB_KINDS_HEAD || &raw[0..4] != BLOB_KINDS_MAGIC {
110 return None;
111 }
112 let count = u64::from_le_bytes(raw[4..12].try_into().ok()?);
113 let file_len = u64::from_le_bytes(raw[12..20].try_into().ok()?);
114 let guard = u64::from_le_bytes(raw[20..28].try_into().ok()?);
115 // The count must match the file being read now, and the payload must be exactly that many bytes:
116 // a truncated or padded sidecar is as untrustworthy as a stale one.
117 if count as usize != blobs.len() || raw.len() != BLOB_KINDS_HEAD + blobs.len() {
118 return None;
119 }
120 if std::fs::metadata(input).ok()?.len() != file_len
121 || blob_kinds_guard(input, blobs).ok()? != guard
122 {
123 return None;
124 }
125 Some(raw[BLOB_KINDS_HEAD..].to_vec())
126}
127
128include!("pbf_extra_s1.rs");