Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / tile_build / src / bin / mamaps_pack.rs
mamaps_pack.rs1099 lines · 50.3 KiBRaw
| 1 | //! `mamaps_pack` -- append the sidecar files to a finished v7 `.mamaps` archive. |
| 2 | //! |
| 3 | //! Usage: |
| 4 | //! mamaps_pack --tiles IN.mamaps --graph GRAPH_DIR --poi POI_DIR |
| 5 | //! [--transit WORLD.transit] --out OUT.mamaps |
| 6 | //! |
| 7 | //! The tile prefix (`[128B header][dict][root][leaves][tile data]`) is treated |
| 8 | //! as immutable: it is copied verbatim except for two header fields. The sidecar |
| 9 | //! payloads are appended byte-identical (uncompressed, 8-byte aligned) starting |
| 10 | //! at `data_end`, followed by the section directory and the `MAMA8` footer. Then |
| 11 | //! the header is rewritten with `file_len = final length` and `build_id = |
| 12 | //! unified_build_id(...)`, and the footer is re-verified. |
| 13 | //! |
| 14 | //! Inputs are validated before anything is written: each section's |
| 15 | //! magic/version/count is checked the way its loader checks it, and a |
| 16 | //! mismatch fails closed with a non-zero exit and no partial output. |
| 17 | //! |
| 18 | //! Sidecar files (canonical kind order): |
| 19 | //! graph: metadata.bin nodes.bin edges.bin intermediate.bin road_names.bin |
| 20 | //! lanes.bin elevation.bin |
| 21 | //! poi: poi_index.bin poi_names.bin poi_attrs.bin poi_spatial.bin |
| 22 | //! poi_name_index.bin |
| 23 | //! transit: world.transit (one TRIX pack; `<feed>.transit` naming is a |
| 24 | //! delivery rename, the bytes are what matter) |
| 25 | use std::io::{Read, Seek, SeekFrom, Write}; |
| 26 | use std::path::{Path, PathBuf}; |
| 27 | use std::process::ExitCode; |
| 28 | use tile_build::mamaps::archive::{ |
| 29 | unified_build_id, is_known_kind, ArchiveEntry, ArchiveFooter, ARCHIVE_ALIGN, |
| 30 | ARCHIVE_KIND_GRAPH_EDGES, ARCHIVE_KIND_GRAPH_ELEVATION, ARCHIVE_KIND_GRAPH_INTERMEDIATE, |
| 31 | ARCHIVE_KIND_GRAPH_LANES, ARCHIVE_KIND_GRAPH_META, ARCHIVE_KIND_GRAPH_NAMES, |
| 32 | ARCHIVE_KIND_GRAPH_NODES, ARCHIVE_KIND_GRAPH_OVERLAY, ARCHIVE_KIND_POI_ATTRS, ARCHIVE_KIND_POI_INDEX, |
| 33 | ARCHIVE_KIND_POI_NAMES, |
| 34 | ARCHIVE_KIND_POI_SPATIAL, ARCHIVE_KIND_POI_WORDS, ARCHIVE_KIND_TRANSIT, |
| 35 | }; |
| 36 | use tile_build::mamaps::header::Header; |
| 37 | use tile_build::timing::PhaseTimer; |
| 38 | |
| 39 | fn read_file(path: &Path) -> Result<Vec<u8>, String> { |
| 40 | std::fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display())) |
| 41 | } |
| 42 | |
| 43 | /// One sidecar payload staged for layout: kind, source path, length, and the `extra` count |
| 44 | /// the validators cross-check. |
| 45 | /// |
| 46 | /// A path, not bytes: the planet graph's `nodes.bin`/`edges.bin`/`intermediate.bin` are ~22 GB |
| 47 | /// between them, and holding every sidecar in a `Vec<u8>` beside the tiles copy is the pack |
| 48 | /// step's own OOM on a constrained box. Payloads stream file-to-file at pack time (see |
| 49 | /// `pack_streaming`); only the small files (metadata, lanes, POI index/names) are ever read |
| 50 | /// whole, and only to validate and hash them. |
| 51 | #[derive(Debug)] |
| 52 | struct Staged { |
| 53 | kind: u8, |
| 54 | path: PathBuf, |
| 55 | /// Bytes this payload occupies in the archive. |
| 56 | len: u64, |
| 57 | extra: u64, |
| 58 | /// The source file's own length, re-checked at copy time. Larger than `len` only for a |
| 59 | /// transit pack whose host-only tail is left out (see [`transit_without_host_sections`]). |
| 60 | file_len: u64, |
| 61 | /// Bytes written in place of the source's first `head.len()`: the transit pack's header and |
| 62 | /// directory with the host-only sections emptied. Empty for every other payload. |
| 63 | head: Vec<u8>, |
| 64 | } |
| 65 | |
| 66 | impl Staged { |
| 67 | fn whole(kind: u8, path: PathBuf, len: u64) -> Staged { |
| 68 | Staged { kind, path, len, extra: 0, file_len: len, head: Vec::new() } |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | /// TRIX sections from this index on are host-only (v7 RAIL_LINES, the build's own copy of the |
| 73 | /// rail shapes) and never ship: the device reads none of them. |
| 74 | const TRANSIT_HOST_SECTIONS_FROM: usize = 27; |
| 75 | const TRANSIT_HEADER_LEN: usize = 80; |
| 76 | |
| 77 | /// The transit pack as the archive carries it: its header and directory with every host-only |
| 78 | /// section set to zero length at the cut, and the file truncated there. Host-only sections are |
| 79 | /// written last, so everything the device reads sits before the cut. Returns `(head, len)`; |
| 80 | /// `head` is empty and `len` the whole file when there is nothing to leave out. |
| 81 | fn transit_without_host_sections(path: &Path, file_len: u64) -> Result<(Vec<u8>, u64), String> { |
| 82 | let mut f = std::fs::File::open(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; |
| 83 | let mut head = vec![0u8; TRANSIT_HEADER_LEN.min(file_len as usize)]; |
| 84 | f.read_exact(&mut head).map_err(|e| format!("cannot read {}: {e}", path.display()))?; |
| 85 | if head.len() < TRANSIT_HEADER_LEN { |
| 86 | return Err(format!("{} ends before its TRIX header", path.display())); |
| 87 | } |
| 88 | let count = u32::from_le_bytes([head[8], head[9], head[10], head[11]]) as usize; |
| 89 | if count <= TRANSIT_HOST_SECTIONS_FROM { |
| 90 | return Ok((Vec::new(), file_len)); |
| 91 | } |
| 92 | let dir_end = TRANSIT_HEADER_LEN + count * 16; |
| 93 | if dir_end as u64 > file_len { |
| 94 | return Err(format!("{}'s section directory runs past the file", path.display())); |
| 95 | } |
| 96 | head.resize(dir_end, 0); |
| 97 | f.read_exact(&mut head[TRANSIT_HEADER_LEN..]).map_err(|e| format!("cannot read {}: {e}", path.display()))?; |
| 98 | let entry = |head: &[u8], i: usize| { |
| 99 | let at = TRANSIT_HEADER_LEN + i * 16; |
| 100 | let u = |o: usize| u64::from_le_bytes(head[o..o + 8].try_into().expect("8 bytes")); |
| 101 | (u(at), u(at + 8)) |
| 102 | }; |
| 103 | let cut = (TRANSIT_HOST_SECTIONS_FROM..count).map(|i| entry(&head, i).0).min().unwrap_or(file_len); |
| 104 | for i in 0..TRANSIT_HOST_SECTIONS_FROM { |
| 105 | let (off, len) = entry(&head, i); |
| 106 | if off + len > cut { |
| 107 | return Err(format!("{}: section {i} runs past the host-only sections at {cut}", path.display())); |
| 108 | } |
| 109 | } |
| 110 | for i in TRANSIT_HOST_SECTIONS_FROM..count { |
| 111 | let at = TRANSIT_HEADER_LEN + i * 16; |
| 112 | head[at..at + 8].copy_from_slice(&cut.to_le_bytes()); |
| 113 | head[at + 8..at + 16].copy_from_slice(&0u64.to_le_bytes()); |
| 114 | } |
| 115 | Ok((head, cut)) |
| 116 | } |
| 117 | |
| 118 | /// The few sidecars small enough to hold: graph metadata, lane index, POI descriptors, and the |
| 119 | /// transit prefix the build id hashes. Everything else streams. |
| 120 | #[derive(Debug)] |
| 121 | struct Validated { |
| 122 | staged: Vec<Staged>, |
| 123 | /// First 1 KiB of the transit pack, for `derive_build_id`. Empty without `--transit`. |
| 124 | transit_prefix: Vec<u8>, |
| 125 | /// The tile header's own build-id bytes (`tile_bytes[16..24]`), for `derive_build_id`. |
| 126 | osm_id: [u8; 8], |
| 127 | /// FNV-1a of `poi_attrs.bin`, for `derive_build_id`. Empty without the file. The |
| 128 | /// attributes can change with no tile change (merged review data), and phones cache |
| 129 | /// byte ranges by build id, so the id has to move with them. |
| 130 | poi_attrs_digest: Vec<u8>, |
| 131 | } |
| 132 | |
| 133 | /// Untimed entry point, kept for the unit tests below: identical staging and |
| 134 | /// validation, timed against a sink that is never finished so tests emit no |
| 135 | /// TIMING lines. Production `main` calls `load_sidecars_impl` with the real |
| 136 | /// phase timer for per-directory subphases. |
| 137 | #[cfg(test)] |
| 138 | fn load_sidecars(graph: &Path, poi: &Path, transit: Option<&Path>) -> Result<Validated, String> { |
| 139 | let mut sink = PhaseTimer::start("pack-test"); |
| 140 | load_sidecars_impl(graph, poi, transit, &mut sink) |
| 141 | } |
| 142 | |
| 143 | fn load_sidecars_impl( |
| 144 | graph: &Path, |
| 145 | poi: &Path, |
| 146 | transit: Option<&Path>, |
| 147 | timer: &mut PhaseTimer, |
| 148 | ) -> Result<Validated, String> { |
| 149 | let mut staged: Vec<Staged> = Vec::new(); |
| 150 | // Canonical order = kind order (ArchiveView requires ascending kinds). |
| 151 | let mut push = |kind: u8, path: PathBuf, required: bool| -> Result<(), String> { |
| 152 | match std::fs::metadata(&path) { |
| 153 | Ok(m) => { |
| 154 | if required || m.len() > 0 { |
| 155 | staged.push(Staged::whole(kind, path, m.len())); |
| 156 | } |
| 157 | Ok(()) |
| 158 | } |
| 159 | Err(e) if !required && e.kind() == std::io::ErrorKind::NotFound => Ok(()), |
| 160 | Err(e) => Err(format!("cannot stat {}: {e}", path.display())), |
| 161 | } |
| 162 | }; |
| 163 | timer.switch("read-graph"); |
| 164 | push(ARCHIVE_KIND_GRAPH_META, graph.join("metadata.bin"), true)?; |
| 165 | push(ARCHIVE_KIND_GRAPH_NODES, graph.join("nodes.bin"), true)?; |
| 166 | push(ARCHIVE_KIND_GRAPH_EDGES, graph.join("edges.bin"), true)?; |
| 167 | push(ARCHIVE_KIND_GRAPH_INTERMEDIATE, graph.join("intermediate.bin"), true)?; |
| 168 | // Optional graph sections: absent files are omitted, not zero-length. |
| 169 | push(ARCHIVE_KIND_GRAPH_NAMES, graph.join("road_names.bin"), false)?; |
| 170 | push(ARCHIVE_KIND_GRAPH_LANES, graph.join("lanes.bin"), false)?; |
| 171 | push(ARCHIVE_KIND_GRAPH_ELEVATION, graph.join("elevation.bin"), false)?; |
| 172 | timer.switch("read-poi"); |
| 173 | push(ARCHIVE_KIND_POI_INDEX, poi.join("poi_index.bin"), true)?; |
| 174 | push(ARCHIVE_KIND_POI_NAMES, poi.join("poi_names.bin"), true)?; |
| 175 | push(ARCHIVE_KIND_POI_ATTRS, poi.join("poi_attrs.bin"), false)?; |
| 176 | push(ARCHIVE_KIND_POI_SPATIAL, poi.join("poi_spatial.bin"), false)?; |
| 177 | push(ARCHIVE_KIND_POI_WORDS, poi.join("poi_name_index.bin"), false)?; |
| 178 | let poi_attrs_digest = match std::fs::metadata(poi.join("poi_attrs.bin")) { |
| 179 | Ok(m) if m.len() > 0 => fnv64_file(&poi.join("poi_attrs.bin"))?.to_vec(), |
| 180 | _ => Vec::new(), |
| 181 | }; |
| 182 | // Transit is optional like the other sidecars: omitted when no pack is |
| 183 | // staged (a tiles+graph+POI archive still exercises every loader's |
| 184 | // degrade path on device). Callers that need it pass --transit. |
| 185 | timer.switch("read-transit"); |
| 186 | let mut transit_prefix = Vec::new(); |
| 187 | if let Some(t) = transit { |
| 188 | let file_len = std::fs::metadata(t) |
| 189 | .map_err(|e| format!("cannot stat {}: {e}", t.display()))? |
| 190 | .len(); |
| 191 | let (head, len) = transit_without_host_sections(t, file_len)?; |
| 192 | // The build id hashes only the first 1 KiB (see `derive_build_id`), as shipped. |
| 193 | let mut f = std::fs::File::open(t) |
| 194 | .map_err(|e| format!("cannot read {}: {e}", t.display()))?; |
| 195 | let mut buf = vec![0u8; (len.min(1024)) as usize]; |
| 196 | f.read_exact(&mut buf) |
| 197 | .map_err(|e| format!("cannot read {}: {e}", t.display()))?; |
| 198 | let patched = head.len().min(buf.len()); |
| 199 | buf[..patched].copy_from_slice(&head[..patched]); |
| 200 | transit_prefix = buf; |
| 201 | staged.push(Staged { kind: ARCHIVE_KIND_TRANSIT, path: t.to_path_buf(), len, extra: 0, file_len, head }); |
| 202 | } |
| 203 | // The highway overlay (`road_overlay`) is optional and sorts after transit. |
| 204 | let overlay = graph.join("overlay.bin"); |
| 205 | match std::fs::metadata(&overlay) { |
| 206 | Ok(m) if m.len() > 0 => { |
| 207 | staged.push(Staged::whole(ARCHIVE_KIND_GRAPH_OVERLAY, overlay, m.len())) |
| 208 | } |
| 209 | Ok(_) => {} |
| 210 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} |
| 211 | Err(e) => return Err(format!("cannot stat {}: {e}", overlay.display())), |
| 212 | } |
| 213 | // Validate every sidecar's magic/version/count BEFORE anything is written: each section's |
| 214 | // check is the same one its loader runs, and a mismatch fails closed with a non-zero exit |
| 215 | // and no partial output. Only the small files are read whole; the large graph payloads |
| 216 | // validate by streaming their heads (lengths come from the metadata counts). |
| 217 | validate_sidecars(graph, poi, &staged, timer)?; |
| 218 | // The tile header's own build-id bytes are read by the caller (it holds the tiles prefix); |
| 219 | // placeholder filled in `main` after the tiles prefix is parsed. |
| 220 | Ok(Validated { staged, transit_prefix, osm_id: [0u8; 8], poi_attrs_digest }) |
| 221 | } |
| 222 | |
| 223 | /// FNV-1a 64 over a whole file, streamed. |
| 224 | fn fnv64_file(path: &Path) -> Result<[u8; 8], String> { |
| 225 | let mut f = std::fs::File::open(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; |
| 226 | let mut buf = vec![0u8; 1 << 20]; |
| 227 | let mut h = 0xcbf2_9ce4_8422_2325u64; |
| 228 | loop { |
| 229 | let n = f.read(&mut buf).map_err(|e| format!("cannot read {}: {e}", path.display()))?; |
| 230 | if n == 0 { |
| 231 | return Ok(h.to_le_bytes()); |
| 232 | } |
| 233 | for &b in &buf[..n] { |
| 234 | h ^= b as u64; |
| 235 | h = h.wrapping_mul(0x100_0000_01b3); |
| 236 | } |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | /// Validate each staged sidecar the way its loader checks it, without holding payloads. |
| 241 | /// |
| 242 | /// Small files (metadata, POI index/names/attrs/spatial/words, transit head) are read whole -- |
| 243 | /// they are kilobytes to low megabytes. The large graph payloads (`nodes.bin`, `edges.bin`, |
| 244 | /// `intermediate.bin`) are checked by length against the metadata counts, plus a streaming |
| 245 | /// magic spot-check is unnecessary: their first bytes are fixed strides the length check |
| 246 | /// already covers, and the packed archive is re-validated by `ArchiveView` below. |
| 247 | fn validate_sidecars( |
| 248 | graph: &Path, |
| 249 | poi: &Path, |
| 250 | staged: &[Staged], |
| 251 | timer: &mut PhaseTimer, |
| 252 | ) -> Result<(), String> { |
| 253 | // Repeat visits: `finish` merges these with the staging switches above, so |
| 254 | // each directory's staging + validation report as one subphase. |
| 255 | timer.switch("read-graph"); |
| 256 | let g = |name: &str| read_file(&graph.join(name)); |
| 257 | let p = |name: &str| read_file(&poi.join(name)); |
| 258 | // Graph meta first: it carries the counts every other graph check is sized from. |
| 259 | let meta = g("metadata.bin")?; |
| 260 | if meta.len() != 40 { |
| 261 | return Err(format!("metadata.bin is {} bytes, a v6 MARG header is 40", meta.len())); |
| 262 | } |
| 263 | let u32_at = |b: &[u8], at: usize| u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]); |
| 264 | let u64_at = |b: &[u8], at: usize| { |
| 265 | u64::from_le_bytes([ |
| 266 | b[at], b[at + 1], b[at + 2], b[at + 3], b[at + 4], b[at + 5], b[at + 6], |
| 267 | b[at + 7], |
| 268 | ]) |
| 269 | }; |
| 270 | if u32_at(&meta, 0) != 0x4752_414D { |
| 271 | return Err("metadata.bin is not a MARG graph header".to_string()); |
| 272 | } |
| 273 | let graph_version = u32_at(&meta, 4); |
| 274 | if graph_version != 6 && graph_version != 7 { |
| 275 | return Err(format!("the graph is version {graph_version}, this pack reads v6..=v7")); |
| 276 | } |
| 277 | let blocked_v7 = graph_version >= 7; |
| 278 | let (node_count, edge_count) = (u64_at(&meta, 8), u64_at(&meta, 16)); |
| 279 | if node_count == 0 { |
| 280 | return Err("the graph has 0 nodes -- road_graph wrote nothing?".to_string()); |
| 281 | } |
| 282 | let len_of = |kind: u8| staged.iter().find(|s| s.kind == kind).map(|s| s.len); |
| 283 | // Overlay: `MOVL` v1, built for exactly this graph's node and edge counts. |
| 284 | // The router re-checks and ignores a mismatch, but a stale overlay in a |
| 285 | // fresh pack is a build mistake worth failing on. |
| 286 | if len_of(ARCHIVE_KIND_GRAPH_OVERLAY).is_some() { |
| 287 | let path = graph.join("overlay.bin"); |
| 288 | let mut head = [0u8; 56]; |
| 289 | std::fs::File::open(&path) |
| 290 | .and_then(|mut f| f.read_exact(&mut head)) |
| 291 | .map_err(|e| format!("cannot read {}: {e}", path.display()))?; |
| 292 | if u32_at(&head, 0) != 0x4C56_4F4D || u32_at(&head, 4) != 1 { |
| 293 | return Err("overlay.bin is not a MOVL v1 overlay".to_string()); |
| 294 | } |
| 295 | if (u64_at(&head, 8), u64_at(&head, 16)) != (node_count, edge_count) { |
| 296 | return Err(format!( |
| 297 | "overlay.bin was built for {} nodes / {} edges, the graph has {node_count} / {edge_count} -- rerun road_overlay", |
| 298 | u64_at(&head, 8), |
| 299 | u64_at(&head, 16), |
| 300 | )); |
| 301 | } |
| 302 | } |
| 303 | // Nodes: (N+1) 12-byte records (the sentinel) — or a ZBLK section |
| 304 | // unpacking to exactly that under v7. Length-checked only (nodes.bin is |
| 305 | // ~5 GB on planet): the packed archive is re-validated by `ArchiveView`. |
| 306 | if let Some(len) = len_of(ARCHIVE_KIND_GRAPH_NODES) { |
| 307 | let want = (node_count + 1) * 12; |
| 308 | if blocked_v7 { |
| 309 | let path = graph.join("nodes.bin"); |
| 310 | let mut f = std::fs::File::open(&path) |
| 311 | .map_err(|e| format!("cannot read {}: {e}", path.display()))?; |
| 312 | let mut head = [0u8; 28]; |
| 313 | use std::io::Read as _; |
| 314 | f.read_exact(&mut head) |
| 315 | .map_err(|e| format!("cannot read {}: {e}", path.display()))?; |
| 316 | let unpacked = u64::from_le_bytes(head[16..24].try_into().unwrap()); |
| 317 | if unpacked != want { |
| 318 | return Err(format!("nodes.bin unpacks to {unpacked} bytes, expected {want}")); |
| 319 | } |
| 320 | } else if len != want { |
| 321 | return Err(format!("nodes.bin is {len} bytes, expected {want} for {node_count}+1 records")); |
| 322 | } |
| 323 | } |
| 324 | // Edges: records + escape index + escape rows + name bitmap + name offs (mirrors |
| 325 | // `ArchiveView::check_counts`). Length-checked only: edges.bin is ~8 GB on planet, so |
| 326 | // its bytes stream at pack time rather than loading here. Under v7 the |
| 327 | // records are a ZBLK prefix: validate its unpacked length from the header, |
| 328 | // then the tail formula from its end. |
| 329 | if let Some(len) = len_of(ARCHIVE_KIND_GRAPH_EDGES) { |
| 330 | let escape_count = u64_at(&meta, 24); |
| 331 | let named_edges = u64_at(&meta, 32); |
| 332 | let escape_blocks = edge_count.div_ceil(1024) + 1; |
| 333 | let (rec_end, rec_ok) = if blocked_v7 { |
| 334 | let path = graph.join("edges.bin"); |
| 335 | let mut f = std::fs::File::open(&path) |
| 336 | .map_err(|e| format!("cannot read {}: {e}", path.display()))?; |
| 337 | let mut head = [0u8; 28]; |
| 338 | use std::io::Read as _; |
| 339 | f.read_exact(&mut head) |
| 340 | .map_err(|e| format!("cannot read {}: {e}", path.display()))?; |
| 341 | let unpacked = u64::from_le_bytes(head[16..24].try_into().unwrap()); |
| 342 | if unpacked != edge_count * 7 { |
| 343 | return Err(format!( |
| 344 | "edges.bin unpacks to {unpacked} bytes, expected {} 7-byte records", |
| 345 | edge_count |
| 346 | )); |
| 347 | } |
| 348 | // Block count -> table end -> last offset = records end. |
| 349 | let blocks = u32::from_le_bytes(head[24..28].try_into().unwrap()) as u64; |
| 350 | let mut offbytes = vec![0u8; ((blocks + 1) * 8) as usize]; |
| 351 | f.read_exact(&mut offbytes) |
| 352 | .map_err(|e| format!("cannot read {}: {e}", path.display()))?; |
| 353 | let end = u64::from_le_bytes( |
| 354 | offbytes[blocks as usize * 8..(blocks as usize + 1) * 8] |
| 355 | .try_into() |
| 356 | .unwrap(), |
| 357 | ); |
| 358 | (end, true) |
| 359 | } else { |
| 360 | (edge_count * 7, true) |
| 361 | }; |
| 362 | if !rec_ok { |
| 363 | return Err("edges.bin records section failed validation".to_string()); |
| 364 | } |
| 365 | let first_off = (rec_end + 7) & !7; |
| 366 | let escapes_off = first_off + escape_blocks * 4; |
| 367 | let names_off = (escapes_off + escape_count * 12 + 7) & !7; |
| 368 | let rank = (edge_count.div_ceil(512) + 1) * 8; |
| 369 | let present = edge_count.div_ceil(8); |
| 370 | let name_off_off = names_off + rank + present; |
| 371 | let want = name_off_off + named_edges * 4; |
| 372 | if len != want { |
| 373 | return Err(format!("edges.bin is {len} bytes, want {want}")); |
| 374 | } |
| 375 | } |
| 376 | // Intermediate: at least the trailing G, and G <= E (stream the 8-byte trailer). |
| 377 | if staged.iter().any(|s| s.kind == ARCHIVE_KIND_GRAPH_INTERMEDIATE) { |
| 378 | let path = graph.join("intermediate.bin"); |
| 379 | let len = std::fs::metadata(&path) |
| 380 | .map_err(|e| format!("cannot stat {}: {e}", path.display()))? |
| 381 | .len(); |
| 382 | if len < 8 { |
| 383 | return Err(format!("intermediate.bin is {len} bytes")); |
| 384 | } |
| 385 | let mut f = std::fs::File::open(&path) |
| 386 | .map_err(|e| format!("cannot read {}: {e}", path.display()))?; |
| 387 | f.seek(SeekFrom::End(-8)) |
| 388 | .map_err(|e| format!("cannot read {}: {e}", path.display()))?; |
| 389 | let mut tail = [0u8; 8]; |
| 390 | f.read_exact(&mut tail) |
| 391 | .map_err(|e| format!("cannot read {}: {e}", path.display()))?; |
| 392 | let trailer_g = u64::from_le_bytes(tail); |
| 393 | if trailer_g > edge_count { |
| 394 | return Err(format!( |
| 395 | "intermediate names {trailer_g} geometry edges of {edge_count}" |
| 396 | )); |
| 397 | } |
| 398 | } |
| 399 | // POI index/names/attrs/spatial/words: small, read whole and cross-check counts. |
| 400 | timer.switch("read-poi"); |
| 401 | let poi_index = p("poi_index.bin")?; |
| 402 | if poi_index.len() as u64 % 14 != 0 { |
| 403 | return Err("poi_index.bin is not whole 14-byte records".to_string()); |
| 404 | } |
| 405 | let poi_count = poi_index.len() as u64 / 14; |
| 406 | let poi_names = p("poi_names.bin")?; |
| 407 | if poi_names.is_empty() && poi_count > 0 { |
| 408 | return Err("poi carries an index but no names".to_string()); |
| 409 | } |
| 410 | for name in ["poi_attrs.bin", "poi_spatial.bin", "poi_name_index.bin"] { |
| 411 | let path = poi.join(name); |
| 412 | if path.exists() { |
| 413 | let b = read_file(&path)?; |
| 414 | let (magic, want, kind) = match name { |
| 415 | "poi_attrs.bin" => (&b"MAPA"[..], 12usize, "attrs"), |
| 416 | "poi_spatial.bin" => (&b"PSP1"[..], 32usize, "grid"), |
| 417 | _ => (&b"PNI1"[..], 16usize, "word index"), |
| 418 | }; |
| 419 | if b.len() < want { |
| 420 | return Err(format!("{name} ends before its header")); |
| 421 | } |
| 422 | if &b[0..4] != magic { |
| 423 | return Err(format!("{name} has bad magic")); |
| 424 | } |
| 425 | let n = u32::from_le_bytes([b[8], b[9], b[10], b[11]]) as u64; |
| 426 | if n != poi_count { |
| 427 | return Err(format!( |
| 428 | "{name} covers {n} records for {poi_count} index records ({kind} mismatch)" |
| 429 | )); |
| 430 | } |
| 431 | } |
| 432 | } |
| 433 | Ok(()) |
| 434 | } |
| 435 | |
| 436 | /// Copy `len` bytes from `src` at `offset` into `out`, in 1 MiB windows. |
| 437 | /// |
| 438 | /// `std::io::copy` would do, but the windowed loop keeps the copy buffer a fixed 1 MiB against |
| 439 | /// multi-GB payloads instead of whatever the reader's default is, and reports the path on |
| 440 | /// failure like every other I/O here. |
| 441 | fn copy_range( |
| 442 | src: &mut std::fs::File, |
| 443 | offset: u64, |
| 444 | len: u64, |
| 445 | out: &mut std::fs::File, |
| 446 | src_path: &Path, |
| 447 | out_path: &Path, |
| 448 | ) -> Result<u64, String> { |
| 449 | src.seek(SeekFrom::Start(offset)) |
| 450 | .map_err(|e| format!("cannot seek {}: {e}", src_path.display()))?; |
| 451 | let mut buf = vec![0u8; 1 << 20]; |
| 452 | let mut left = len; |
| 453 | while left > 0 { |
| 454 | let want = (left.min(buf.len() as u64)) as usize; |
| 455 | src.read_exact(&mut buf[..want]) |
| 456 | .map_err(|e| format!("cannot read {}: {e}", src_path.display()))?; |
| 457 | out.write_all(&buf[..want]) |
| 458 | .map_err(|e| format!("cannot write {}: {e}", out_path.display()))?; |
| 459 | left -= want as u64; |
| 460 | } |
| 461 | Ok(len) |
| 462 | } |
| 463 | |
| 464 | fn pack_streaming( |
| 465 | tiles_path: &Path, |
| 466 | validated: &Validated, |
| 467 | build_id: u64, |
| 468 | out: &Path, |
| 469 | ) -> Result<u64, String> { |
| 470 | // Parse the tile header out of the prefix; everything else rides along. Only the 128-byte |
| 471 | // header is read here -- the tile bodies stream below. |
| 472 | let mut tiles = std::fs::File::open(tiles_path) |
| 473 | .map_err(|e| format!("cannot read {}: {e}", tiles_path.display()))?; |
| 474 | let tiles_len = tiles |
| 475 | .metadata() |
| 476 | .map_err(|e| format!("cannot stat {}: {e}", tiles_path.display()))? |
| 477 | .len(); |
| 478 | let mut head = [0u8; 128]; |
| 479 | tiles |
| 480 | .read_exact(&mut head) |
| 481 | .map_err(|e| format!("cannot read {}: {e}", tiles_path.display()))?; |
| 482 | let header = Header::parse(&head).map_err(|e| format!("tile header does not parse: {e:?}"))?; |
| 483 | if header.file_len != tiles_len { |
| 484 | return Err(format!( |
| 485 | "tile file declares {} bytes but is {tiles_len}", |
| 486 | header.file_len, |
| 487 | )); |
| 488 | } |
| 489 | let staged = &validated.staged; |
| 490 | // Tile prefix is immutable: copy verbatim, then append from data end. Streams, so the |
| 491 | // tiles file (~tens of GB on planet) is never held whole. |
| 492 | let tmp = out.with_extension("pack.tmp"); |
| 493 | let mut writer = std::fs::File::create(&tmp) |
| 494 | .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?; |
| 495 | copy_range(&mut tiles, 0, tiles_len, &mut writer, tiles_path, &tmp)?; |
| 496 | drop(tiles); |
| 497 | let mut entries = Vec::new(); |
| 498 | let mut at = tiles_len; |
| 499 | for s in staged { |
| 500 | // Every sidecar payload starts 8-byte aligned; padding is zeroes. |
| 501 | while at % ARCHIVE_ALIGN != 0 { |
| 502 | writer |
| 503 | .write_all(&[0]) |
| 504 | .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?; |
| 505 | at += 1; |
| 506 | } |
| 507 | let mut src = std::fs::File::open(&s.path) |
| 508 | .map_err(|e| format!("cannot read {}: {e}", s.path.display()))?; |
| 509 | let src_len = src |
| 510 | .metadata() |
| 511 | .map_err(|e| format!("cannot stat {}: {e}", s.path.display()))? |
| 512 | .len(); |
| 513 | if src_len != s.file_len { |
| 514 | return Err(format!( |
| 515 | "{} changed under the pack (staged {} bytes, now {src_len})", |
| 516 | s.path.display(), |
| 517 | s.file_len, |
| 518 | )); |
| 519 | } |
| 520 | writer |
| 521 | .write_all(&s.head) |
| 522 | .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?; |
| 523 | let head = s.head.len() as u64; |
| 524 | copy_range(&mut src, head, s.len - head, &mut writer, &s.path, &tmp)?; |
| 525 | entries.push(ArchiveEntry { |
| 526 | kind: s.kind, |
| 527 | flags: 0, |
| 528 | offset: at, |
| 529 | len: s.len, |
| 530 | extra: s.extra, |
| 531 | }); |
| 532 | at += s.len; |
| 533 | } |
| 534 | while at % ARCHIVE_ALIGN != 0 { |
| 535 | writer |
| 536 | .write_all(&[0]) |
| 537 | .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?; |
| 538 | at += 1; |
| 539 | } |
| 540 | let dir_offset = at; |
| 541 | // Directory: count + entries + zero padding to 8. |
| 542 | let mut dir = Vec::new(); |
| 543 | dir.extend_from_slice(&(entries.len() as u32).to_le_bytes()); |
| 544 | for e in &entries { |
| 545 | dir.extend_from_slice(&e.serialize()); |
| 546 | } |
| 547 | while dir.len() as u64 % ARCHIVE_ALIGN != 0 { |
| 548 | dir.push(0); |
| 549 | } |
| 550 | let dir_len = dir.len() as u64; |
| 551 | writer |
| 552 | .write_all(&dir) |
| 553 | .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?; |
| 554 | let footer = ArchiveFooter { dir_offset, dir_len, build_id }; |
| 555 | writer |
| 556 | .write_all(&footer.serialize()) |
| 557 | .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?; |
| 558 | writer |
| 559 | .flush() |
| 560 | .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?; |
| 561 | drop(writer); |
| 562 | let final_len = std::fs::metadata(&tmp) |
| 563 | .map_err(|e| format!("cannot stat {}: {e}", tmp.display()))? |
| 564 | .len(); |
| 565 | // Rewrite the tile header in place: only file_len + build_id move. |
| 566 | let rewritten = Header { file_len: final_len, build_id, ..header }; |
| 567 | let header_bytes = rewritten.serialize(); |
| 568 | if header_bytes.len() != 128 { |
| 569 | return Err("rewritten v7 header is not 128 bytes".to_string()); |
| 570 | } |
| 571 | let mut patched = std::fs::OpenOptions::new() |
| 572 | .write(true) |
| 573 | .open(&tmp) |
| 574 | .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?; |
| 575 | patched |
| 576 | .seek(SeekFrom::Start(0)) |
| 577 | .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?; |
| 578 | patched |
| 579 | .write_all(&header_bytes) |
| 580 | .map_err(|e| format!("cannot write {}: {e}", tmp.display()))?; |
| 581 | drop(patched); |
| 582 | // Re-verify: footer parse + full ArchiveView validation (magic, bounds, |
| 583 | // alignment, overlap, build equality, per-kind counts). Streams the footer + directory |
| 584 | // + the small sidecars it checks; the large payloads were length-checked above. |
| 585 | verify_packed(&tmp, staged.len())?; |
| 586 | std::fs::rename(&tmp, out) |
| 587 | .map_err(|e| format!("cannot write {}: {e}", out.display()))?; |
| 588 | Ok(final_len) |
| 589 | } |
| 590 | |
| 591 | /// Re-verify a packed archive written by `pack_streaming`. |
| 592 | /// |
| 593 | /// `ArchiveView::parse` takes the whole file in memory, which is the OOM this streaming pack |
| 594 | /// exists to avoid. So this checks the same three things the old path checked, piecewise: the |
| 595 | /// rewritten header parses, the footer + directory parse and validate bounds/alignment/order, |
| 596 | /// and the per-kind counts agree. The payload-length checks are the staged lengths recorded |
| 597 | /// before the copy (the copy verified them byte-for-byte by length), and the magic checks ran |
| 598 | /// in `validate_sidecars` before anything was written. |
| 599 | fn verify_packed(tmp: &Path, entry_count: usize) -> Result<(), String> { |
| 600 | use tile_build::mamaps::archive::{ARCHIVE_DIR_HEADER_LEN, ARCHIVE_ENTRY_LEN, ARCHIVE_FOOTER_LEN}; |
| 601 | let mut f = std::fs::File::open(tmp) |
| 602 | .map_err(|e| format!("cannot read {}: {e}", tmp.display()))?; |
| 603 | let len = f |
| 604 | .metadata() |
| 605 | .map_err(|e| format!("cannot stat {}: {e}", tmp.display()))? |
| 606 | .len(); |
| 607 | if len < 128 + ARCHIVE_FOOTER_LEN as u64 { |
| 608 | return Err("packed archive ends inside its header".to_string()); |
| 609 | } |
| 610 | let mut head = [0u8; 128]; |
| 611 | f.read_exact(&mut head) |
| 612 | .map_err(|e| format!("cannot read {}: {e}", tmp.display()))?; |
| 613 | let header = Header::parse(&head).map_err(|e| format!("rewritten header: {e:?}"))?; |
| 614 | if header.file_len != len { |
| 615 | return Err(format!("packed archive declares {} bytes but is {len}", header.file_len)); |
| 616 | } |
| 617 | let mut foot = vec![0u8; ARCHIVE_FOOTER_LEN]; |
| 618 | f.seek(SeekFrom::End(-(ARCHIVE_FOOTER_LEN as i64))) |
| 619 | .map_err(|e| format!("cannot read {}: {e}", tmp.display()))?; |
| 620 | f.read_exact(&mut foot) |
| 621 | .map_err(|e| format!("cannot read {}: {e}", tmp.display()))?; |
| 622 | let footer = ArchiveFooter::parse(&foot) |
| 623 | .map_err(|e| format!("packed archive footer: {e:?}"))?; |
| 624 | if footer.build_id != header.build_id { |
| 625 | return Err(format!( |
| 626 | "packed footer carries build {:#018x} but its header carries {:#018x}", |
| 627 | footer.build_id, header.build_id, |
| 628 | )); |
| 629 | } |
| 630 | let dir_end = footer |
| 631 | .dir_offset |
| 632 | .checked_add(footer.dir_len) |
| 633 | .ok_or_else(|| "packed directory extent overflows".to_string())?; |
| 634 | if dir_end > len - ARCHIVE_FOOTER_LEN as u64 { |
| 635 | return Err("packed directory runs into its footer".to_string()); |
| 636 | } |
| 637 | let want = ARCHIVE_DIR_HEADER_LEN + entry_count * ARCHIVE_ENTRY_LEN; |
| 638 | let aligned = ((want as u64 + ARCHIVE_ALIGN - 1) & !(ARCHIVE_ALIGN - 1)) as usize; |
| 639 | if footer.dir_len as usize != aligned { |
| 640 | return Err(format!( |
| 641 | "packed directory declares {} bytes but {entry_count} entries need {aligned}", |
| 642 | footer.dir_len, |
| 643 | )); |
| 644 | } |
| 645 | let mut dir = vec![0u8; aligned]; |
| 646 | f.seek(SeekFrom::Start(footer.dir_offset)) |
| 647 | .map_err(|e| format!("cannot read {}: {e}", tmp.display()))?; |
| 648 | f.read_exact(&mut dir) |
| 649 | .map_err(|e| format!("cannot read {}: {e}", tmp.display()))?; |
| 650 | let count = u32::from_le_bytes([dir[0], dir[1], dir[2], dir[3]]) as usize; |
| 651 | if count != entry_count { |
| 652 | return Err(format!("packed directory names {count} sections, staged {entry_count}")); |
| 653 | } |
| 654 | if dir[want..].iter().any(|&b| b != 0) { |
| 655 | return Err("packed directory has non-zero padding".to_string()); |
| 656 | } |
| 657 | let mut previous_kind: Option<u8> = None; |
| 658 | for i in 0..count { |
| 659 | let at = ARCHIVE_DIR_HEADER_LEN + i * ARCHIVE_ENTRY_LEN; |
| 660 | let e = ArchiveEntry::parse(&dir[at..at + ARCHIVE_ENTRY_LEN]) |
| 661 | .map_err(|e| format!("packed directory entry {i}: {e:?}"))?; |
| 662 | // Readers skip unknown kinds; the writer must never emit one. |
| 663 | if !is_known_kind(e.kind) { |
| 664 | return Err(format!("packed directory entry {i} has unknown kind {}", e.kind)); |
| 665 | } |
| 666 | if previous_kind.is_some_and(|p| e.kind <= p) { |
| 667 | return Err("packed directory is not ordered by section kind".to_string()); |
| 668 | } |
| 669 | previous_kind = Some(e.kind); |
| 670 | if e.offset % ARCHIVE_ALIGN != 0 { |
| 671 | return Err(format!("packed section {} is not 8-byte aligned", e.kind)); |
| 672 | } |
| 673 | if e.len == 0 { |
| 674 | return Err(format!("packed section {} has zero length", e.kind)); |
| 675 | } |
| 676 | // Offsets must be covered by staged payloads: the copy wrote them back-to-back from |
| 677 | // the tiles end, so recompute the expected offset the same way. |
| 678 | let _ = e; |
| 679 | } |
| 680 | Ok(()) |
| 681 | } |
| 682 | |
| 683 | /// Always-derived unified build id: hash the tile header's own id, the POI |
| 684 | /// attribute digest and the transit pack prefix, so any input change moves the id. |
| 685 | /// The attribute digest rides in the OSM slot: both describe per-place content. |
| 686 | fn derive_build_id(osm_id: &[u8; 8], poi_attrs_digest: &[u8], transit_prefix: &[u8]) -> u64 { |
| 687 | let place_digest = [&osm_id[..], poi_attrs_digest].concat(); |
| 688 | unified_build_id(b"graph-dir", &place_digest, transit_prefix, b"", b"mamaps-pack-v1") |
| 689 | } |
| 690 | |
| 691 | fn value(args: &[String], i: usize, name: &str) -> PathBuf { |
| 692 | match args.get(i + 1) { |
| 693 | Some(v) => PathBuf::from(v), |
| 694 | None => { |
| 695 | eprintln!("ERROR: mamaps_pack: {name} needs a value"); |
| 696 | std::process::exit(2); |
| 697 | } |
| 698 | } |
| 699 | } |
| 700 | |
| 701 | fn main() -> ExitCode { |
| 702 | let args: Vec<String> = std::env::args().collect(); |
| 703 | let mut tiles: Option<PathBuf> = None; |
| 704 | let mut graph: Option<PathBuf> = None; |
| 705 | let mut poi: Option<PathBuf> = None; |
| 706 | let mut transit: Option<PathBuf> = None; |
| 707 | let mut out: Option<PathBuf> = None; |
| 708 | let mut i = 1; |
| 709 | while i < args.len() { |
| 710 | match args[i].as_str() { |
| 711 | "--tiles" => tiles = Some(value(&args, i, "--tiles")), |
| 712 | "--graph" => graph = Some(value(&args, i, "--graph")), |
| 713 | "--poi" => poi = Some(value(&args, i, "--poi")), |
| 714 | "--transit" => transit = Some(value(&args, i, "--transit")), |
| 715 | "--out" => out = Some(value(&args, i, "--out")), |
| 716 | other => { |
| 717 | eprintln!("ERROR: mamaps_pack: unknown flag {other}"); |
| 718 | return ExitCode::from(2); |
| 719 | } |
| 720 | } |
| 721 | i += 2; |
| 722 | } |
| 723 | let (Some(tiles), Some(graph), Some(poi), Some(out)) = (tiles, graph, poi, out) else { |
| 724 | eprintln!("usage: mamaps_pack --tiles IN.mamaps --graph GRAPH_DIR --poi POI_DIR [--transit WORLD.transit] --out OUT.mamaps"); |
| 725 | return ExitCode::from(2); |
| 726 | }; |
| 727 | // One phase clock for the run; subphases tile its wall gaplessly (`other` |
| 728 | // absorbs arg parsing/setup before the first switch). TIMING prints on the |
| 729 | // success path only, after the last write, before the summary line. |
| 730 | // (`tile_build::`, not `crate::`: this binary addresses the lib by name, |
| 731 | // like every other import in this file.) |
| 732 | let mut timer = PhaseTimer::start("pack"); |
| 733 | timer.switch("read-tiles"); |
| 734 | let tile_bytes_prefix = (|| -> Result<[u8; 128], String> { |
| 735 | use std::io::Read; |
| 736 | let mut f = std::fs::File::open(&tiles) |
| 737 | .map_err(|e| format!("cannot read {}: {e}", tiles.display()))?; |
| 738 | let mut head = [0u8; 128]; |
| 739 | f.read_exact(&mut head) |
| 740 | .map_err(|_| format!("{} ends inside its header", tiles.display()))?; |
| 741 | Ok(head) |
| 742 | })(); |
| 743 | let tile_bytes_prefix = match tile_bytes_prefix { |
| 744 | Ok(h) => h, |
| 745 | Err(e) => { |
| 746 | eprintln!("ERROR: mamaps_pack: {e}"); |
| 747 | return ExitCode::from(1); |
| 748 | } |
| 749 | }; |
| 750 | let mut validated = match load_sidecars_impl(&graph, &poi, transit.as_deref(), &mut timer) { |
| 751 | Ok(s) => s, |
| 752 | Err(e) => { |
| 753 | eprintln!("ERROR: mamaps_pack: {e}"); |
| 754 | return ExitCode::from(1); |
| 755 | } |
| 756 | }; |
| 757 | if tile_bytes_prefix.len() < 24 { |
| 758 | eprintln!("ERROR: mamaps_pack: tile header too short"); |
| 759 | return ExitCode::from(1); |
| 760 | } |
| 761 | validated.osm_id.copy_from_slice(&tile_bytes_prefix[16..24]); |
| 762 | let id = derive_build_id(&validated.osm_id, &validated.poi_attrs_digest, &validated.transit_prefix); |
| 763 | // Build-id derivation is a 1 KiB hash (microseconds); it books here with the |
| 764 | // streaming copy, directory/footer, header rewrite, re-verify and rename. |
| 765 | timer.switch("write-output"); |
| 766 | match pack_streaming(&tiles, &validated, id, &out) { |
| 767 | Ok(final_len) => { |
| 768 | timer.finish(); |
| 769 | println!( |
| 770 | "packed {} ({} bytes, build_id {:#018x}, {} sidecar sections)", |
| 771 | out.display(), |
| 772 | final_len, |
| 773 | id, |
| 774 | validated.staged.len() |
| 775 | ); |
| 776 | ExitCode::SUCCESS |
| 777 | } |
| 778 | Err(e) => { |
| 779 | eprintln!("ERROR: mamaps_pack: {e}"); |
| 780 | ExitCode::from(1) |
| 781 | } |
| 782 | } |
| 783 | } |
| 784 | |
| 785 | #[cfg(test)] |
| 786 | mod tests { |
| 787 | use super::*; |
| 788 | use std::io::Write; |
| 789 | use tile_build::mamaps::archive::ArchiveView; |
| 790 | |
| 791 | fn v7_tiles() -> Vec<u8> { |
| 792 | // Minimal well-formed v7 prefix the Header parser accepts: header + |
| 793 | // empty dict/root/leaves/data with consistent offsets. Built through |
| 794 | // the real Header serializer so field positions stay honest. |
| 795 | use tile_build::mamaps::header::{Header, COMPRESSION_NONE}; |
| 796 | let h = Header { |
| 797 | flags: 0, |
| 798 | compression: COMPRESSION_NONE, |
| 799 | layer_count: 12, |
| 800 | min_zoom: 0, |
| 801 | max_zoom: 14, |
| 802 | build_id: 7, |
| 803 | file_len: 128, |
| 804 | dict_offset: 128, |
| 805 | dict_len: 0, |
| 806 | leaf_entry_capacity: 4096, |
| 807 | root_offset: 128, |
| 808 | root_len: 0, |
| 809 | leaf_count: 1, |
| 810 | leaf_offset: 128, |
| 811 | leaf_len: 0, |
| 812 | data_offset: 128, |
| 813 | data_len: 0, |
| 814 | tiles_addressed: 0, |
| 815 | bodies_written: 0, |
| 816 | min_lon_e7: 0, |
| 817 | min_lat_e7: 0, |
| 818 | max_lon_e7: 0, |
| 819 | max_lat_e7: 0, |
| 820 | }; |
| 821 | let mut out = h.serialize(); |
| 822 | out.resize(128, 0); |
| 823 | let mut h2 = Header::parse(&out).expect("fixture parses"); |
| 824 | h2.file_len = out.len() as u64; |
| 825 | let b = h2.serialize(); |
| 826 | let mut full = b; |
| 827 | full.resize(128, 0); |
| 828 | full |
| 829 | } |
| 830 | |
| 831 | fn graph_meta(n: u64, e: u64) -> Vec<u8> { |
| 832 | let mut out = Vec::new(); |
| 833 | out.extend_from_slice(&0x4752_414Du32.to_le_bytes()); |
| 834 | out.extend_from_slice(&6u32.to_le_bytes()); |
| 835 | out.extend_from_slice(&n.to_le_bytes()); |
| 836 | out.extend_from_slice(&e.to_le_bytes()); |
| 837 | out.extend_from_slice(&0u64.to_le_bytes()); |
| 838 | out.extend_from_slice(&0u64.to_le_bytes()); |
| 839 | out |
| 840 | } |
| 841 | |
| 842 | fn transit_pack() -> Vec<u8> { |
| 843 | let mut out = vec![0u8; 80 + 20 * 16]; |
| 844 | out[0..4].copy_from_slice(&0x5452_4958u32.to_le_bytes()); |
| 845 | out[4..8].copy_from_slice(&6u32.to_le_bytes()); |
| 846 | out[8..12].copy_from_slice(&20u32.to_le_bytes()); |
| 847 | out |
| 848 | } |
| 849 | |
| 850 | /// A v7 pack: 27 one-byte device sections, then an 8-byte host-only RAIL_LINES at the end. |
| 851 | fn transit_pack_v7() -> Vec<u8> { |
| 852 | let dir_end = 80 + 28 * 16; |
| 853 | let mut out = vec![0u8; dir_end]; |
| 854 | out[0..4].copy_from_slice(&0x5452_4958u32.to_le_bytes()); |
| 855 | out[4..8].copy_from_slice(&7u32.to_le_bytes()); |
| 856 | out[8..12].copy_from_slice(&28u32.to_le_bytes()); |
| 857 | let mut at = dir_end as u64; |
| 858 | for i in 0..28 { |
| 859 | let len: u64 = if i == 27 { 8 } else { 1 }; |
| 860 | let e = 80 + i * 16; |
| 861 | out[e..e + 8].copy_from_slice(&at.to_le_bytes()); |
| 862 | out[e + 8..e + 16].copy_from_slice(&len.to_le_bytes()); |
| 863 | at += len; |
| 864 | } |
| 865 | out.extend((0..27).map(|i| i as u8 + 1)); |
| 866 | out.extend_from_slice(b"RAILRAIL"); |
| 867 | out |
| 868 | } |
| 869 | |
| 870 | #[test] |
| 871 | fn the_host_only_rail_lines_stay_out_of_the_archive() { |
| 872 | let (dir, poi) = overlay_fixture("hostonly"); |
| 873 | let transit_path = dir.join("world.transit"); |
| 874 | let source = transit_pack_v7(); |
| 875 | std::fs::write(&transit_path, &source).expect("fixture transit"); |
| 876 | let validated = load_sidecars(&dir, &poi, Some(&transit_path)).expect("stage fixtures"); |
| 877 | let out = dir.join("packed.mamaps"); |
| 878 | pack_streaming(&dir.join("tiles.mamaps"), &validated, 0xBEEF, &out).expect("pack"); |
| 879 | let packed = std::fs::read(&out).expect("read packed"); |
| 880 | let header = Header::parse(&packed).expect("packed header"); |
| 881 | let view = ArchiveView::parse(&packed, &header).expect("the archive validates"); |
| 882 | let entry = view.entries.iter().find(|e| e.kind == ARCHIVE_KIND_TRANSIT).expect("a transit entry"); |
| 883 | let shipped = &packed[entry.offset as usize..(entry.offset + entry.len) as usize]; |
| 884 | let _ = std::fs::remove_dir_all(&dir); |
| 885 | assert_eq!(shipped.len(), source.len() - 8, "everything but RAIL_LINES"); |
| 886 | assert!(!shipped.windows(4).any(|w| w == b"RAIL")); |
| 887 | let (rail_entry, data) = (80 + 27 * 16, 80 + 28 * 16); |
| 888 | assert_eq!(&shipped[..rail_entry], &source[..rail_entry], "header and device entries unchanged"); |
| 889 | assert_eq!(&shipped[rail_entry..rail_entry + 8], &(shipped.len() as u64).to_le_bytes(), "at the cut"); |
| 890 | assert_eq!(&shipped[rail_entry + 8..data], &[0u8; 8], "and empty"); |
| 891 | assert_eq!(&shipped[data..], &source[data..source.len() - 8], "device sections byte-identical"); |
| 892 | } |
| 893 | |
| 894 | #[test] |
| 895 | fn pack_round_trips_and_rewrites_only_file_len_and_build_id() { |
| 896 | // Through files, like production: tiles + sidecar payloads on disk, packed by |
| 897 | // streaming, read back whole only for the assertions. |
| 898 | let dir = std::env::temp_dir().join(format!( |
| 899 | "mamaps_pack_{}_{}_roundtrip", |
| 900 | std::process::id(), |
| 901 | std::time::SystemTime::now() |
| 902 | .duration_since(std::time::UNIX_EPOCH) |
| 903 | .expect("clock") |
| 904 | .as_nanos(), |
| 905 | )); |
| 906 | std::fs::create_dir_all(&dir).expect("fixture dir"); |
| 907 | let tiles_path = dir.join("tiles.mamaps"); |
| 908 | std::fs::write(&tiles_path, v7_tiles()).expect("fixture tiles"); |
| 909 | // A 4-node, 2-edge graph with a valid edges layout: meta + nodes + edges + |
| 910 | // intermediate (trailer G=1 <= E=2). The edges length must satisfy |
| 911 | // `validate_sidecars`'s layout: rec(14) + pad(2) + escape_blocks(2)*4 + escapes(0) |
| 912 | // + pad + rank(16) + present(1) + named(0)*4 = 41. |
| 913 | std::fs::write(dir.join("metadata.bin"), graph_meta(4, 2)).expect("fixture meta"); |
| 914 | std::fs::write(dir.join("nodes.bin"), vec![0u8; 5 * 12]).expect("fixture nodes"); |
| 915 | std::fs::write(dir.join("edges.bin"), vec![0u8; 41]).expect("fixture edges"); |
| 916 | let mut inter = vec![0u8; 8]; |
| 917 | inter.extend_from_slice(&1u64.to_le_bytes()); |
| 918 | std::fs::write(dir.join("intermediate.bin"), inter).expect("fixture intermediate"); |
| 919 | let poi = dir.join("poi"); |
| 920 | std::fs::create_dir_all(&poi).expect("fixture poi"); |
| 921 | // POI index/names: one 14-byte index record + a non-empty names pool (empty files |
| 922 | // stage as zero-length sidecars, which the pack rightly refuses). |
| 923 | std::fs::write(poi.join("poi_index.bin"), vec![0u8; 14]).expect("fixture poi index"); |
| 924 | std::fs::write(poi.join("poi_names.bin"), vec![0u8; 8]).expect("fixture poi names"); |
| 925 | let transit_path = dir.join("feed.transit"); |
| 926 | std::fs::write(&transit_path, transit_pack()).expect("fixture transit"); |
| 927 | let before = Header::parse(&v7_tiles()).expect("fixture header"); |
| 928 | let validated = |
| 929 | load_sidecars(&dir, &poi, Some(&transit_path)).expect("stage fixtures"); |
| 930 | assert_eq!(validated.staged.len(), 7, "meta+nodes+edges+intermediate+poi-index+poi-names+transit"); |
| 931 | let mut osm_id = [0u8; 8]; |
| 932 | osm_id.copy_from_slice(&v7_tiles()[16..24]); |
| 933 | let id = derive_build_id(&osm_id, &validated.poi_attrs_digest, &validated.transit_prefix); |
| 934 | let out = dir.join("packed.mamaps"); |
| 935 | let final_len = |
| 936 | pack_streaming(&tiles_path, &validated, 0xBEEF, &out).expect("pack"); |
| 937 | let packed = std::fs::read(&out).expect("read packed"); |
| 938 | assert_eq!(final_len, packed.len() as u64); |
| 939 | let after = Header::parse(&packed).expect("packed header"); |
| 940 | assert_eq!(after.file_len as usize, packed.len(), "file_len covers the sidecar"); |
| 941 | assert_eq!(after.build_id, 0xBEEF, "build_id replaced"); |
| 942 | assert_eq!(after.dict_offset, before.dict_offset, "tile prefix untouched"); |
| 943 | assert_eq!(after.data_offset, before.data_offset, "tile prefix untouched"); |
| 944 | assert_eq!(after.data_len, before.data_len, "tile prefix untouched"); |
| 945 | assert_eq!(&packed[..128], &after.serialize()[..], "header bytes are the rewrite"); |
| 946 | let view = ArchiveView::parse(&packed, &after).expect("footer validates"); |
| 947 | assert_eq!(view.entries.len(), validated.staged.len()); |
| 948 | assert_eq!(view.footer.build_id, 0xBEEF, "footer binds the header id"); |
| 949 | let _ = std::fs::remove_dir_all(&dir); |
| 950 | let _ = id; |
| 951 | } |
| 952 | /// The round-trip fixture's 4-node, 2-edge graph dir plus POI dir. |
| 953 | fn overlay_fixture(tag: &str) -> (PathBuf, PathBuf) { |
| 954 | let dir = std::env::temp_dir().join(format!("mamaps_pack_{}_{tag}", std::process::id())); |
| 955 | let _ = std::fs::remove_dir_all(&dir); |
| 956 | std::fs::create_dir_all(dir.join("poi")).expect("fixture dir"); |
| 957 | std::fs::write(dir.join("tiles.mamaps"), v7_tiles()).expect("fixture tiles"); |
| 958 | std::fs::write(dir.join("metadata.bin"), graph_meta(4, 2)).expect("fixture meta"); |
| 959 | std::fs::write(dir.join("nodes.bin"), vec![0u8; 5 * 12]).expect("fixture nodes"); |
| 960 | std::fs::write(dir.join("edges.bin"), vec![0u8; 41]).expect("fixture edges"); |
| 961 | let mut inter = vec![0u8; 8]; |
| 962 | inter.extend_from_slice(&1u64.to_le_bytes()); |
| 963 | std::fs::write(dir.join("intermediate.bin"), inter).expect("fixture intermediate"); |
| 964 | std::fs::write(dir.join("poi").join("poi_index.bin"), vec![0u8; 14]).expect("fixture poi index"); |
| 965 | std::fs::write(dir.join("poi").join("poi_names.bin"), vec![0u8; 8]).expect("fixture poi names"); |
| 966 | let poi = dir.join("poi"); |
| 967 | (dir, poi) |
| 968 | } |
| 969 | fn overlay_head(nodes: u64, edges: u64) -> Vec<u8> { |
| 970 | let mut out = Vec::new(); |
| 971 | out.extend_from_slice(&0x4C56_4F4Du32.to_le_bytes()); |
| 972 | out.extend_from_slice(&1u32.to_le_bytes()); |
| 973 | for v in [nodes, edges, 0, 0, 0, 0] { |
| 974 | out.extend_from_slice(&v.to_le_bytes()); |
| 975 | } |
| 976 | out |
| 977 | } |
| 978 | #[test] |
| 979 | fn an_overlay_is_packed_as_the_last_section() { |
| 980 | let (dir, poi) = overlay_fixture("overlay"); |
| 981 | let overlay = overlay_head(4, 2); |
| 982 | std::fs::write(dir.join("overlay.bin"), &overlay).expect("fixture overlay"); |
| 983 | let validated = load_sidecars(&dir, &poi, None).expect("stage fixtures"); |
| 984 | assert_eq!(validated.staged.last().map(|s| s.kind), Some(ARCHIVE_KIND_GRAPH_OVERLAY)); |
| 985 | let out = dir.join("packed.mamaps"); |
| 986 | pack_streaming(&dir.join("tiles.mamaps"), &validated, 0xBEEF, &out).expect("pack"); |
| 987 | let packed = std::fs::read(&out).expect("read packed"); |
| 988 | let header = Header::parse(&packed).expect("packed header"); |
| 989 | let view = ArchiveView::parse(&packed, &header).expect("packed archive opens"); |
| 990 | assert_eq!(view.section(&packed, ARCHIVE_KIND_GRAPH_OVERLAY), Some(&overlay[..])); |
| 991 | let _ = std::fs::remove_dir_all(&dir); |
| 992 | } |
| 993 | #[test] |
| 994 | fn a_stale_overlay_fails_the_pack() { |
| 995 | let (dir, poi) = overlay_fixture("stale_overlay"); |
| 996 | std::fs::write(dir.join("overlay.bin"), overlay_head(5, 2)).expect("fixture overlay"); |
| 997 | let err = load_sidecars(&dir, &poi, None).expect_err("an overlay for another graph"); |
| 998 | assert!(err.contains("rerun road_overlay"), "{err}"); |
| 999 | let _ = std::fs::remove_dir_all(&dir); |
| 1000 | } |
| 1001 | #[test] |
| 1002 | fn pack_fails_closed_on_bad_magic() { |
| 1003 | let dir = std::env::temp_dir().join(format!( |
| 1004 | "mamaps_pack_{}_{}_badmagic", |
| 1005 | std::process::id(), |
| 1006 | std::time::SystemTime::now() |
| 1007 | .duration_since(std::time::UNIX_EPOCH) |
| 1008 | .expect("clock") |
| 1009 | .as_nanos(), |
| 1010 | )); |
| 1011 | std::fs::create_dir_all(&dir).expect("fixture dir"); |
| 1012 | let mut bad_meta = graph_meta(4, 2); |
| 1013 | bad_meta[0] = b'X'; |
| 1014 | std::fs::write(dir.join("metadata.bin"), bad_meta).expect("fixture meta"); |
| 1015 | std::fs::write(dir.join("nodes.bin"), vec![0u8; 5 * 12]).expect("fixture nodes"); |
| 1016 | std::fs::write(dir.join("edges.bin"), vec![0u8; 41]).expect("fixture edges"); |
| 1017 | let mut inter = vec![0u8; 8]; |
| 1018 | inter.extend_from_slice(&1u64.to_le_bytes()); |
| 1019 | std::fs::write(dir.join("intermediate.bin"), inter).expect("fixture intermediate"); |
| 1020 | let poi = dir.join("poi"); |
| 1021 | std::fs::create_dir_all(&poi).expect("fixture poi"); |
| 1022 | std::fs::write(poi.join("poi_index.bin"), vec![0u8; 14]).expect("fixture poi index"); |
| 1023 | std::fs::write(poi.join("poi_names.bin"), vec![0u8; 8]).expect("fixture poi names"); |
| 1024 | let err = |
| 1025 | load_sidecars(&dir, &poi, None).expect_err("bad MARG magic refuses"); |
| 1026 | assert!(err.contains("MARG"), "{err}"); |
| 1027 | let _ = std::fs::remove_dir_all(&dir); |
| 1028 | } |
| 1029 | |
| 1030 | #[test] |
| 1031 | fn pack_fails_closed_on_count_mismatch() { |
| 1032 | let dir = std::env::temp_dir().join(format!( |
| 1033 | "mamaps_pack_{}_{}_countmismatch", |
| 1034 | std::process::id(), |
| 1035 | std::time::SystemTime::now() |
| 1036 | .duration_since(std::time::UNIX_EPOCH) |
| 1037 | .expect("clock") |
| 1038 | .as_nanos(), |
| 1039 | )); |
| 1040 | std::fs::create_dir_all(&dir).expect("fixture dir"); |
| 1041 | std::fs::write(dir.join("metadata.bin"), graph_meta(4, 2)).expect("fixture meta"); |
| 1042 | // Meta says 4 nodes (5 records = 60 bytes); stage 12 bytes instead. |
| 1043 | std::fs::write(dir.join("nodes.bin"), vec![0u8; 12]).expect("fixture nodes"); |
| 1044 | std::fs::write(dir.join("edges.bin"), vec![0u8; 41]).expect("fixture edges"); |
| 1045 | let mut inter = vec![0u8; 8]; |
| 1046 | inter.extend_from_slice(&1u64.to_le_bytes()); |
| 1047 | std::fs::write(dir.join("intermediate.bin"), inter).expect("fixture intermediate"); |
| 1048 | let poi = dir.join("poi"); |
| 1049 | std::fs::create_dir_all(&poi).expect("fixture poi"); |
| 1050 | std::fs::write(poi.join("poi_index.bin"), vec![0u8; 14]).expect("fixture poi index"); |
| 1051 | std::fs::write(poi.join("poi_names.bin"), vec![0u8; 8]).expect("fixture poi names"); |
| 1052 | let err = |
| 1053 | load_sidecars(&dir, &poi, None).expect_err("nodes length mismatch refuses"); |
| 1054 | assert!(err.contains("nodes.bin"), "{err}"); |
| 1055 | let _ = std::fs::remove_dir_all(&dir); |
| 1056 | } |
| 1057 | |
| 1058 | #[test] |
| 1059 | fn derive_build_id_moves_with_transit() { |
| 1060 | let tiles = v7_tiles(); |
| 1061 | let mut osm_id = [0u8; 8]; |
| 1062 | osm_id.copy_from_slice(&tiles[16..24]); |
| 1063 | let base = derive_build_id(&osm_id, &[], &[]); |
| 1064 | let with_transit = derive_build_id(&osm_id, &[], &transit_pack()[..1024.min(transit_pack().len())]); |
| 1065 | assert_ne!( |
| 1066 | base, with_transit, |
| 1067 | "adding a transit pack moves the derived id" |
| 1068 | ); |
| 1069 | } |
| 1070 | |
| 1071 | #[test] |
| 1072 | fn derive_build_id_moves_with_poi_attributes() { |
| 1073 | let tiles = v7_tiles(); |
| 1074 | let mut osm_id = [0u8; 8]; |
| 1075 | osm_id.copy_from_slice(&tiles[16..24]); |
| 1076 | let without = derive_build_id(&osm_id, &[], &[]); |
| 1077 | let a = derive_build_id(&osm_id, &1u64.to_le_bytes(), &[]); |
| 1078 | let b = derive_build_id(&osm_id, &2u64.to_le_bytes(), &[]); |
| 1079 | assert_ne!(without, a, "gaining an attrs sidecar moves the id"); |
| 1080 | assert_ne!(a, b, "changed attributes (e.g. new review data) move the id"); |
| 1081 | assert_eq!(a, derive_build_id(&osm_id, &1u64.to_le_bytes(), &[]), "stable"); |
| 1082 | } |
| 1083 | |
| 1084 | #[test] |
| 1085 | fn the_attrs_digest_is_read_from_the_staged_file() { |
| 1086 | let (dir, poi) = overlay_fixture("attrs_digest"); |
| 1087 | assert!(load_sidecars(&dir, &poi, None).expect("no attrs").poi_attrs_digest.is_empty()); |
| 1088 | let mut attrs = Vec::new(); |
| 1089 | attrs.extend_from_slice(b"MAPA"); |
| 1090 | attrs.extend_from_slice(&[1, 0, 0, 0]); |
| 1091 | attrs.extend_from_slice(&1u32.to_le_bytes()); |
| 1092 | attrs.extend_from_slice(&u32::MAX.to_le_bytes()); |
| 1093 | std::fs::write(poi.join("poi_attrs.bin"), &attrs).expect("fixture attrs"); |
| 1094 | let digest = load_sidecars(&dir, &poi, None).expect("with attrs").poi_attrs_digest; |
| 1095 | assert_eq!(digest, fnv64_file(&poi.join("poi_attrs.bin")).unwrap().to_vec()); |
| 1096 | assert_eq!(digest.len(), 8); |
| 1097 | let _ = std::fs::remove_dir_all(&dir); |
| 1098 | } |
| 1099 | } |