//! `mamaps_pack` -- append the sidecar files to a finished v7 `.mamaps` archive. //! //! Usage: //! mamaps_pack --tiles IN.mamaps --graph GRAPH_DIR --poi POI_DIR //! [--transit WORLD.transit] --out OUT.mamaps //! [--sha256-out OUT.mamaps.sha256] //! //! The tile prefix (`[128B header][dict][root][leaves][tile data]`) is treated //! as immutable: it is copied verbatim except for two header fields. The sidecar //! payloads are appended byte-identical (uncompressed, 8-byte aligned) starting //! at `data_end`, followed by the section directory and the `MAMA8` footer. Then //! the header is rewritten with `file_len = final length` and `build_id = //! unified_build_id(...)`, and the footer is re-verified. //! //! Inputs are validated before anything is written: each section's //! magic/version/count is checked the way its loader checks it, and a //! mismatch fails closed with a non-zero exit and no partial output. //! //! Sidecar files (canonical kind order): //! graph: metadata.bin nodes.bin edges.bin intermediate.bin road_names.bin //! lanes.bin elevation.bin //! poi: poi_index.bin poi_names.bin poi_attrs.bin poi_spatial.bin //! poi_name_index.bin poi_region.bin poi_admin.bin //! transit: world.transit (one TRIX pack; `.transit` naming is a //! delivery rename, the bytes are what matter) use std::io::{Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; use std::process::ExitCode; use tile_build::mamaps::archive::{ is_known_kind, unified_build_id, ArchiveEntry, ArchiveFooter, ARCHIVE_ALIGN, ARCHIVE_KIND_GRAPH_EDGES, ARCHIVE_KIND_GRAPH_ELEVATION, ARCHIVE_KIND_GRAPH_INTERMEDIATE, ARCHIVE_KIND_GRAPH_LANES, ARCHIVE_KIND_GRAPH_META, ARCHIVE_KIND_GRAPH_NAMES, ARCHIVE_KIND_GRAPH_NODES, ARCHIVE_KIND_GRAPH_OVERLAY, ARCHIVE_KIND_POI_ADMIN, ARCHIVE_KIND_POI_ATTRS, ARCHIVE_KIND_POI_INDEX, ARCHIVE_KIND_POI_NAMES, ARCHIVE_KIND_POI_REGION, ARCHIVE_KIND_POI_SPATIAL, ARCHIVE_KIND_POI_WORDS, ARCHIVE_KIND_TRANSIT, }; use tile_build::mamaps::header::Header; use tile_build::timing::PhaseTimer; fn read_file(path: &Path) -> Result, String> { std::fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display())) } /// One sidecar payload staged for layout: kind, source path, length, and the `extra` count /// the validators cross-check. /// /// A path, not bytes: the planet graph's `nodes.bin`/`edges.bin`/`intermediate.bin` are ~22 GB /// between them, and holding every sidecar in a `Vec` beside the tiles copy is the pack /// step's own OOM on a constrained box. Payloads stream file-to-file at pack time (see /// `pack_streaming`); only the small files (metadata, lanes, POI index/names) are ever read /// whole, and only to validate and hash them. #[derive(Debug)] struct Staged { kind: u8, path: PathBuf, /// Bytes this payload occupies in the archive. len: u64, extra: u64, /// The source file's own length, re-checked at copy time. Larger than `len` only for a /// transit pack whose host-only tail is left out (see [`transit_without_host_sections`]). file_len: u64, /// Bytes written in place of the source's first `head.len()`: the transit pack's header and /// directory with the host-only sections emptied. Empty for every other payload. head: Vec, } impl Staged { fn whole(kind: u8, path: PathBuf, len: u64) -> Staged { Staged { kind, path, len, extra: 0, file_len: len, head: Vec::new() } } } /// TRIX sections from this index on are host-only (v7 RAIL_LINES, the build's own copy of the /// rail shapes) and never ship: the device reads none of them. const TRANSIT_HOST_SECTIONS_FROM: usize = 27; const TRANSIT_HEADER_LEN: usize = 80; /// The transit pack as the archive carries it: its header and directory with every host-only /// section set to zero length at the cut, and the file truncated there. Host-only sections are /// written last, so everything the device reads sits before the cut. Returns `(head, len)`; /// `head` is empty and `len` the whole file when there is nothing to leave out. fn transit_without_host_sections(path: &Path, file_len: u64) -> Result<(Vec, u64), String> { let mut f = std::fs::File::open(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; let mut head = vec![0u8; TRANSIT_HEADER_LEN.min(file_len as usize)]; f.read_exact(&mut head).map_err(|e| format!("cannot read {}: {e}", path.display()))?; if head.len() < TRANSIT_HEADER_LEN { return Err(format!("{} ends before its TRIX header", path.display())); } let count = u32::from_le_bytes([head[8], head[9], head[10], head[11]]) as usize; if count <= TRANSIT_HOST_SECTIONS_FROM { return Ok((Vec::new(), file_len)); } let dir_end = TRANSIT_HEADER_LEN + count * 16; if dir_end as u64 > file_len { return Err(format!("{}'s section directory runs past the file", path.display())); } head.resize(dir_end, 0); f.read_exact(&mut head[TRANSIT_HEADER_LEN..]) .map_err(|e| format!("cannot read {}: {e}", path.display()))?; let entry = |head: &[u8], i: usize| { let at = TRANSIT_HEADER_LEN + i * 16; let u = |o: usize| u64::from_le_bytes(head[o..o + 8].try_into().expect("8 bytes")); (u(at), u(at + 8)) }; let cut = (TRANSIT_HOST_SECTIONS_FROM..count).map(|i| entry(&head, i).0).min().unwrap_or(file_len); for i in 0..TRANSIT_HOST_SECTIONS_FROM { let (off, len) = entry(&head, i); if off + len > cut { return Err(format!( "{}: section {i} runs past the host-only sections at {cut}", path.display() )); } } for i in TRANSIT_HOST_SECTIONS_FROM..count { let at = TRANSIT_HEADER_LEN + i * 16; head[at..at + 8].copy_from_slice(&cut.to_le_bytes()); head[at + 8..at + 16].copy_from_slice(&0u64.to_le_bytes()); } Ok((head, cut)) } /// The few sidecars small enough to hold: graph metadata, lane index, POI descriptors, and the /// transit prefix the build id hashes. Everything else streams. #[derive(Debug)] struct Validated { staged: Vec, /// First 1 KiB of the transit pack, for `derive_build_id`. Empty without `--transit`. transit_prefix: Vec, /// The tile header's own build-id bytes (`tile_bytes[16..24]`), for `derive_build_id`. osm_id: [u8; 8], /// `poi_attrs.bin` when staged non-empty: its FNV-1a feeds `derive_build_id`. The /// attributes can change with no tile change (merged review data), and phones cache /// byte ranges by build id, so the id has to move with them. /// /// A path, hashed by [`Validated::poi_attrs_digest`] on demand, so `main` can run the /// hash (a strictly serial byte loop, ~1.7 GB on a planet) beside the payload copy /// rather than in front of it: the id is only needed for the header and footer, /// which are written last. poi_attrs: Option, /// `poi_admin.bin` when staged non-empty. Its FNV-1a is appended to the attributes digest /// for the same reason: adding or rebuilding the hierarchy changes the section directory /// with no tile change. Absent, the digest (and so every existing build id) is unchanged. poi_admin: Option, } impl Validated { /// FNV-1a of `poi_attrs.bin` followed by FNV-1a of `poi_admin.bin`, each only when that /// file is staged; empty with neither. fn poi_attrs_digest(&self) -> Result, String> { let mut out = Vec::new(); for p in [&self.poi_attrs, &self.poi_admin].into_iter().flatten() { out.extend_from_slice(&fnv64_file(p)?); } Ok(out) } } /// Untimed entry point, kept for the unit tests below: identical staging and /// validation, timed against a sink that is never finished so tests emit no /// TIMING lines. Production `main` calls `load_sidecars_impl` with the real /// phase timer for per-directory subphases. #[cfg(test)] fn load_sidecars(graph: &Path, poi: &Path, transit: Option<&Path>) -> Result { let mut sink = PhaseTimer::start("pack-test"); load_sidecars_impl(graph, poi, transit, &mut sink) } fn load_sidecars_impl( graph: &Path, poi: &Path, transit: Option<&Path>, timer: &mut PhaseTimer, ) -> Result { let mut staged: Vec = Vec::new(); // Canonical order = kind order (ArchiveView requires ascending kinds). let mut push = |kind: u8, path: PathBuf, required: bool| -> Result<(), String> { match std::fs::metadata(&path) { Ok(m) => { if required || m.len() > 0 { staged.push(Staged::whole(kind, path, m.len())); } Ok(()) } Err(e) if !required && e.kind() == std::io::ErrorKind::NotFound => Ok(()), Err(e) => Err(format!("cannot stat {}: {e}", path.display())), } }; timer.switch("read-graph"); push(ARCHIVE_KIND_GRAPH_META, graph.join("metadata.bin"), true)?; push(ARCHIVE_KIND_GRAPH_NODES, graph.join("nodes.bin"), true)?; push(ARCHIVE_KIND_GRAPH_EDGES, graph.join("edges.bin"), true)?; push(ARCHIVE_KIND_GRAPH_INTERMEDIATE, graph.join("intermediate.bin"), true)?; // Optional graph sections: absent files are omitted, not zero-length. push(ARCHIVE_KIND_GRAPH_NAMES, graph.join("road_names.bin"), false)?; push(ARCHIVE_KIND_GRAPH_LANES, graph.join("lanes.bin"), false)?; push(ARCHIVE_KIND_GRAPH_ELEVATION, graph.join("elevation.bin"), false)?; timer.switch("read-poi"); push(ARCHIVE_KIND_POI_INDEX, poi.join("poi_index.bin"), true)?; push(ARCHIVE_KIND_POI_NAMES, poi.join("poi_names.bin"), true)?; push(ARCHIVE_KIND_POI_ATTRS, poi.join("poi_attrs.bin"), false)?; push(ARCHIVE_KIND_POI_SPATIAL, poi.join("poi_spatial.bin"), false)?; push(ARCHIVE_KIND_POI_WORDS, poi.join("poi_name_index.bin"), false)?; let poi_attrs = match std::fs::metadata(poi.join("poi_attrs.bin")) { Ok(m) if m.len() > 0 => Some(poi.join("poi_attrs.bin")), _ => None, }; // Transit is optional like the other sidecars: omitted when no pack is // staged (a tiles+graph+POI archive still exercises every loader's // degrade path on device). Callers that need it pass --transit. timer.switch("read-transit"); let mut transit_prefix = Vec::new(); if let Some(t) = transit { let file_len = std::fs::metadata(t).map_err(|e| format!("cannot stat {}: {e}", t.display()))?.len(); let (head, len) = transit_without_host_sections(t, file_len)?; // The build id hashes only the first 1 KiB (see `derive_build_id`), as shipped. let mut f = std::fs::File::open(t).map_err(|e| format!("cannot read {}: {e}", t.display()))?; let mut buf = vec![0u8; (len.min(1024)) as usize]; f.read_exact(&mut buf).map_err(|e| format!("cannot read {}: {e}", t.display()))?; let patched = head.len().min(buf.len()); buf[..patched].copy_from_slice(&head[..patched]); transit_prefix = buf; staged.push(Staged { kind: ARCHIVE_KIND_TRANSIT, path: t.to_path_buf(), len, extra: 0, file_len, head, }); } // The highway overlay (`road_overlay`) is optional and sorts after transit. let overlay = graph.join("overlay.bin"); match std::fs::metadata(&overlay) { Ok(m) if m.len() > 0 => { staged.push(Staged::whole(ARCHIVE_KIND_GRAPH_OVERLAY, overlay, m.len())) } Ok(_) => {} Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} Err(e) => return Err(format!("cannot stat {}: {e}", overlay.display())), } // The POI region sidecar (`poi_region.bin`) is optional and sorts last: kind 15 // comes after the overlay's 14, and `ArchiveView::parse` requires ascending kinds. let poi_region = poi.join("poi_region.bin"); match std::fs::metadata(&poi_region) { Ok(m) if m.len() > 0 => { staged.push(Staged::whole(ARCHIVE_KIND_POI_REGION, poi_region, m.len())) } Ok(_) => {} Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} Err(e) => return Err(format!("cannot stat {}: {e}", poi_region.display())), } // The boundary hierarchy (`poi_admin.bin`, kind 16) is optional and sorts after the region // sidecar it describes. Older apps skip the kind; its digest feeds the build id (below). let poi_admin = poi.join("poi_admin.bin"); let poi_admin = match std::fs::metadata(&poi_admin) { Ok(m) if m.len() > 0 => { staged.push(Staged::whole(ARCHIVE_KIND_POI_ADMIN, poi_admin.clone(), m.len())); Some(poi_admin) } Ok(_) => None, Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, Err(e) => return Err(format!("cannot stat {}: {e}", poi_admin.display())), }; // Validate every sidecar's magic/version/count BEFORE anything is written: each section's // check is the same one its loader runs, and a mismatch fails closed with a non-zero exit // and no partial output. Only the small files are read whole; the large graph payloads // validate by streaming their heads (lengths come from the metadata counts). validate_sidecars(graph, poi, &staged, timer)?; // The tile header's own build-id bytes are read by the caller (it holds the tiles prefix); // placeholder filled in `main` after the tiles prefix is parsed. Ok(Validated { staged, transit_prefix, osm_id: [0u8; 8], poi_attrs, poi_admin }) } /// A file's length, with the same "cannot read" wording a whole-file read would give. fn file_len(path: &Path) -> Result { std::fs::metadata(path) .map(|m| m.len()) .map_err(|e| format!("cannot read {}: {e}", path.display())) } /// Up to the first `n` bytes of a file (fewer only if the file is shorter). fn read_head(path: &Path, n: usize) -> Result, String> { let f = std::fs::File::open(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; let mut buf = Vec::with_capacity(n); f.take(n as u64) .read_to_end(&mut buf) .map_err(|e| format!("cannot read {}: {e}", path.display()))?; Ok(buf) } /// FNV-1a 64 over a whole file, streamed. fn fnv64_file(path: &Path) -> Result<[u8; 8], String> { let mut f = std::fs::File::open(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; let mut buf = vec![0u8; 1 << 20]; let mut h = 0xcbf2_9ce4_8422_2325u64; loop { let n = f.read(&mut buf).map_err(|e| format!("cannot read {}: {e}", path.display()))?; if n == 0 { return Ok(h.to_le_bytes()); } for &b in &buf[..n] { h ^= b as u64; h = h.wrapping_mul(0x100_0000_01b3); } } } include!("mamaps_pack_parts/mamaps_pack_part1.rs"); include!("mamaps_pack_parts/mamaps_pack_part2.rs"); include!("mamaps_pack_parts/mamaps_pack_part3.rs"); include!("mamaps_pack_parts/mamaps_pack_part4.rs");