use std::fs::File; use std::path::Path; use crate::pbf::{inflate_blob, read_exact_at, BlobLoc, PrimitiveBlock}; use crate::proto::{self, Error, Reader, Result, WIRE_BYTES}; /// `BlobHeader { required string type = 1; required int32 datasize = 3; }` pub(crate) fn decode_blob_header(buf: &[u8]) -> Result<(&[u8], u32)> { let mut r = Reader::new(buf); let mut kind: &[u8] = b""; let mut datasize: Option = None; while let Some((field, wire)) = r.next_field()? { match (field, wire) { (1, WIRE_BYTES) => kind = r.bytes()?, (3, proto::WIRE_VARINT) => datasize = Some(r.uvarint()? as u32), _ => r.skip(wire)?, } } match datasize { Some(d) => Ok((kind, d)), None => proto::err("BlobHeader without datasize"), } } /// Inflate and decode the first data blob, so a file we cannot read fails in /// seconds instead of at the end of a multi-hour pass. /// /// Worth its own step because the compression is a property of the whole file: /// a planet mirror published with zstd blobs is unreadable here, and finding /// that out after an 80 GB download and one full pass is the expensive way to /// learn it. pub fn probe_compression(path: &Path, blobs: &[BlobLoc]) -> Result<()> { let Some(first) = blobs.first() else { return Ok(()); }; let mut file = File::open(path).map_err(|e| Error(format!("cannot open {}: {e}", path.display())))?; let mut compressed = Vec::new(); let mut inflated = Vec::new(); read_exact_at(&mut file, first, &mut compressed)?; inflate_blob(&compressed, &mut inflated)?; PrimitiveBlock::decode(&inflated)?; Ok(()) } /// The file name a full pass's blob-kinds mask is cached under, beside a tool's output. pub const BLOB_KINDS_FILE: &str = "blob_kinds.bin"; /// Magic + version for the blob-kinds sidecar. Bumped if the header or payload layout changes, so an /// old sidecar is rejected rather than misread. `MBK2` replaced `MBK1`'s source mtime with a content /// fingerprint, so the graph directory is byte-identical wherever and whenever the `.pbf` lives. const BLOB_KINDS_MAGIC: &[u8; 4] = b"MBK2"; /// Header bytes before the per-blob kind payload: magic, blob count, source length, fingerprint. const BLOB_KINDS_HEAD: usize = 4 + 8 + 8 + 8; /// What guards a blob-kinds sidecar against a different `.pbf`: the file's content fingerprint /// (length, first and last 4 MiB -- [`crate::fingerprint::file_fingerprint`]) mixed with the blob /// index pass 1 already holds (every blob's offset and size), so an edit anywhere that resizes a /// blob changes it. Never a path or a timestamp: a copy of the same file elsewhere, or touched, /// still matches, and the sidecar's bytes depend only on the input's bytes. fn blob_kinds_guard(input: &Path, blobs: &[BlobLoc]) -> Result { let mut h = crate::fingerprint::Fnv::default(); h.eat(b"blob-kinds/2"); h.eat_u64( crate::fingerprint::file_fingerprint(input) .map_err(|e| Error(format!("cannot read {}: {e}", input.display())))?, ); h.eat_u64(blobs.len() as u64); for b in blobs { h.eat_u64(b.offset); h.eat_u64(b.datasize as u64); } Ok(h.finish()) } /// Persist a complete per-blob kind mask beside a tool's output, guarded against the source `.pbf` /// it describes. /// /// A full pass already learns which blobs hold nodes, ways or relations; two tools run back to back /// over the same file (`road_graph` then `mamaps_build`) both want that mask, and the second would /// otherwise pay a full scan to recompute it. Writing it here lets the second load it instead. The /// guard -- blob count, file length and a content fingerprint ([`blob_kinds_guard`]) -- is what /// makes a stale sidecar a fall-back rather than a wrong answer; see [`load_blob_kinds`]. pub fn write_blob_kinds(dir: &Path, input: &Path, blobs: &[BlobLoc], kinds: &[u8]) -> Result<()> { let len = std::fs::metadata(input) .map_err(|e| Error(format!("cannot stat {}: {e}", input.display())))? .len(); let guard = blob_kinds_guard(input, blobs)?; let mut out = Vec::with_capacity(BLOB_KINDS_HEAD + kinds.len()); out.extend_from_slice(BLOB_KINDS_MAGIC); out.extend_from_slice(&(kinds.len() as u64).to_le_bytes()); out.extend_from_slice(&len.to_le_bytes()); out.extend_from_slice(&guard.to_le_bytes()); out.extend_from_slice(kinds); let path = dir.join(BLOB_KINDS_FILE); std::fs::write(&path, &out).map_err(|e| Error(format!("cannot write {}: {e}", path.display()))) } /// Load a blob-kinds mask written by [`write_blob_kinds`], but only if it still describes `input`. /// /// `None` on any mismatch or error -- a missing file, wrong magic (an `MBK1` sidecar included), a /// different blob count, a changed length or fingerprint, a short read -- so the caller falls back /// to a full scan. `blobs` supplies the count the mask must match; nothing here trusts the file's /// own count past that check. The returned mask is byte-for-byte what a full pass over `input` /// would produce, so feeding it to a later pass changes no output. pub fn load_blob_kinds(dir: &Path, input: &Path, blobs: &[BlobLoc]) -> Option> { let raw = std::fs::read(dir.join(BLOB_KINDS_FILE)).ok()?; if raw.len() < BLOB_KINDS_HEAD || &raw[0..4] != BLOB_KINDS_MAGIC { return None; } let count = u64::from_le_bytes(raw[4..12].try_into().ok()?); let file_len = u64::from_le_bytes(raw[12..20].try_into().ok()?); let guard = u64::from_le_bytes(raw[20..28].try_into().ok()?); // The count must match the file being read now, and the payload must be exactly that many bytes: // a truncated or padded sidecar is as untrustworthy as a stale one. if count as usize != blobs.len() || raw.len() != BLOB_KINDS_HEAD + blobs.len() { return None; } if std::fs::metadata(input).ok()?.len() != file_len || blob_kinds_guard(input, blobs).ok()? != guard { return None; } Some(raw[BLOB_KINDS_HEAD..].to_vec()) } include!("pbf_extra_s1.rs");