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

Modern-Apps.git / scripts / maps / tile_build / src / bin / mamaps_pack.rs

mamaps_pack.rs319 lines · 14.9 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//! [--sha256-out OUT.mamaps.sha256]
7//!
8//! The tile prefix (`[128B header][dict][root][leaves][tile data]`) is treated
9//! as immutable: it is copied verbatim except for two header fields. The sidecar
10//! payloads are appended byte-identical (uncompressed, 8-byte aligned) starting
11//! at `data_end`, followed by the section directory and the `MAMA8` footer. Then
12//! the header is rewritten with `file_len = final length` and `build_id =
13//! unified_build_id(...)`, and the footer is re-verified.
14//!
15//! Inputs are validated before anything is written: each section's
16//! magic/version/count is checked the way its loader checks it, and a
17//! mismatch fails closed with a non-zero exit and no partial output.
18//!
19//! Sidecar files (canonical kind order):
20//! graph: metadata.bin nodes.bin edges.bin intermediate.bin road_names.bin
21//! lanes.bin elevation.bin
22//! poi: poi_index.bin poi_names.bin poi_attrs.bin poi_spatial.bin
23//! poi_name_index.bin poi_region.bin poi_admin.bin
24//! transit: world.transit (one TRIX pack; `<feed>.transit` naming is a
25//! delivery rename, the bytes are what matter)
26use std::io::{Read, Seek, SeekFrom, Write};
27use std::path::{Path, PathBuf};
28use std::process::ExitCode;
29use tile_build::mamaps::archive::{
30 is_known_kind, unified_build_id, ArchiveEntry, ArchiveFooter, ARCHIVE_ALIGN,
31 ARCHIVE_KIND_GRAPH_EDGES, ARCHIVE_KIND_GRAPH_ELEVATION, ARCHIVE_KIND_GRAPH_INTERMEDIATE,
32 ARCHIVE_KIND_GRAPH_LANES, ARCHIVE_KIND_GRAPH_META, ARCHIVE_KIND_GRAPH_NAMES,
33 ARCHIVE_KIND_GRAPH_NODES, ARCHIVE_KIND_GRAPH_OVERLAY, ARCHIVE_KIND_POI_ADMIN,
34 ARCHIVE_KIND_POI_ATTRS, ARCHIVE_KIND_POI_INDEX, ARCHIVE_KIND_POI_NAMES,
35 ARCHIVE_KIND_POI_REGION, ARCHIVE_KIND_POI_SPATIAL, ARCHIVE_KIND_POI_WORDS,
36 ARCHIVE_KIND_TRANSIT,
37};
38use tile_build::mamaps::header::Header;
39use tile_build::timing::PhaseTimer;
40
41fn read_file(path: &Path) -> Result<Vec<u8>, String> {
42 std::fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display()))
43}
44
45/// One sidecar payload staged for layout: kind, source path, length, and the `extra` count
46/// the validators cross-check.
47///
48/// A path, not bytes: the planet graph's `nodes.bin`/`edges.bin`/`intermediate.bin` are ~22 GB
49/// between them, and holding every sidecar in a `Vec<u8>` beside the tiles copy is the pack
50/// step's own OOM on a constrained box. Payloads stream file-to-file at pack time (see
51/// `pack_streaming`); only the small files (metadata, lanes, POI index/names) are ever read
52/// whole, and only to validate and hash them.
53#[derive(Debug)]
54struct Staged {
55 kind: u8,
56 path: PathBuf,
57 /// Bytes this payload occupies in the archive.
58 len: u64,
59 extra: u64,
60 /// The source file's own length, re-checked at copy time. Larger than `len` only for a
61 /// transit pack whose host-only tail is left out (see [`transit_without_host_sections`]).
62 file_len: u64,
63 /// Bytes written in place of the source's first `head.len()`: the transit pack's header and
64 /// directory with the host-only sections emptied. Empty for every other payload.
65 head: Vec<u8>,
66}
67
68impl Staged {
69 fn whole(kind: u8, path: PathBuf, len: u64) -> Staged {
70 Staged { kind, path, len, extra: 0, file_len: len, head: Vec::new() }
71 }
72}
73
74/// TRIX sections from this index on are host-only (v7 RAIL_LINES, the build's own copy of the
75/// rail shapes) and never ship: the device reads none of them.
76const TRANSIT_HOST_SECTIONS_FROM: usize = 27;
77const TRANSIT_HEADER_LEN: usize = 80;
78
79/// The transit pack as the archive carries it: its header and directory with every host-only
80/// section set to zero length at the cut, and the file truncated there. Host-only sections are
81/// written last, so everything the device reads sits before the cut. Returns `(head, len)`;
82/// `head` is empty and `len` the whole file when there is nothing to leave out.
83fn transit_without_host_sections(path: &Path, file_len: u64) -> Result<(Vec<u8>, u64), String> {
84 let mut f =
85 std::fs::File::open(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
86 let mut head = vec![0u8; TRANSIT_HEADER_LEN.min(file_len as usize)];
87 f.read_exact(&mut head).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
88 if head.len() < TRANSIT_HEADER_LEN {
89 return Err(format!("{} ends before its TRIX header", path.display()));
90 }
91 let count = u32::from_le_bytes([head[8], head[9], head[10], head[11]]) as usize;
92 if count <= TRANSIT_HOST_SECTIONS_FROM {
93 return Ok((Vec::new(), file_len));
94 }
95 let dir_end = TRANSIT_HEADER_LEN + count * 16;
96 if dir_end as u64 > file_len {
97 return Err(format!("{}'s section directory runs past the file", path.display()));
98 }
99 head.resize(dir_end, 0);
100 f.read_exact(&mut head[TRANSIT_HEADER_LEN..])
101 .map_err(|e| format!("cannot read {}: {e}", path.display()))?;
102 let entry = |head: &[u8], i: usize| {
103 let at = TRANSIT_HEADER_LEN + i * 16;
104 let u = |o: usize| u64::from_le_bytes(head[o..o + 8].try_into().expect("8 bytes"));
105 (u(at), u(at + 8))
106 };
107 let cut =
108 (TRANSIT_HOST_SECTIONS_FROM..count).map(|i| entry(&head, i).0).min().unwrap_or(file_len);
109 for i in 0..TRANSIT_HOST_SECTIONS_FROM {
110 let (off, len) = entry(&head, i);
111 if off + len > cut {
112 return Err(format!(
113 "{}: section {i} runs past the host-only sections at {cut}",
114 path.display()
115 ));
116 }
117 }
118 for i in TRANSIT_HOST_SECTIONS_FROM..count {
119 let at = TRANSIT_HEADER_LEN + i * 16;
120 head[at..at + 8].copy_from_slice(&cut.to_le_bytes());
121 head[at + 8..at + 16].copy_from_slice(&0u64.to_le_bytes());
122 }
123 Ok((head, cut))
124}
125
126/// The few sidecars small enough to hold: graph metadata, lane index, POI descriptors, and the
127/// transit prefix the build id hashes. Everything else streams.
128#[derive(Debug)]
129struct Validated {
130 staged: Vec<Staged>,
131 /// First 1 KiB of the transit pack, for `derive_build_id`. Empty without `--transit`.
132 transit_prefix: Vec<u8>,
133 /// The tile header's own build-id bytes (`tile_bytes[16..24]`), for `derive_build_id`.
134 osm_id: [u8; 8],
135 /// `poi_attrs.bin` when staged non-empty: its FNV-1a feeds `derive_build_id`. The
136 /// attributes can change with no tile change (merged review data), and phones cache
137 /// byte ranges by build id, so the id has to move with them.
138 ///
139 /// A path, hashed by [`Validated::poi_attrs_digest`] on demand, so `main` can run the
140 /// hash (a strictly serial byte loop, ~1.7 GB on a planet) beside the payload copy
141 /// rather than in front of it: the id is only needed for the header and footer,
142 /// which are written last.
143 poi_attrs: Option<PathBuf>,
144 /// `poi_admin.bin` when staged non-empty. Its FNV-1a is appended to the attributes digest
145 /// for the same reason: adding or rebuilding the hierarchy changes the section directory
146 /// with no tile change. Absent, the digest (and so every existing build id) is unchanged.
147 poi_admin: Option<PathBuf>,
148}
149
150impl Validated {
151 /// FNV-1a of `poi_attrs.bin` followed by FNV-1a of `poi_admin.bin`, each only when that
152 /// file is staged; empty with neither.
153 fn poi_attrs_digest(&self) -> Result<Vec<u8>, String> {
154 let mut out = Vec::new();
155 for p in [&self.poi_attrs, &self.poi_admin].into_iter().flatten() {
156 out.extend_from_slice(&fnv64_file(p)?);
157 }
158 Ok(out)
159 }
160}
161
162/// Untimed entry point, kept for the unit tests below: identical staging and
163/// validation, timed against a sink that is never finished so tests emit no
164/// TIMING lines. Production `main` calls `load_sidecars_impl` with the real
165/// phase timer for per-directory subphases.
166#[cfg(test)]
167fn load_sidecars(graph: &Path, poi: &Path, transit: Option<&Path>) -> Result<Validated, String> {
168 let mut sink = PhaseTimer::start("pack-test");
169 load_sidecars_impl(graph, poi, transit, &mut sink)
170}
171
172fn load_sidecars_impl(
173 graph: &Path,
174 poi: &Path,
175 transit: Option<&Path>,
176 timer: &mut PhaseTimer,
177) -> Result<Validated, String> {
178 let mut staged: Vec<Staged> = Vec::new();
179 // Canonical order = kind order (ArchiveView requires ascending kinds).
180 let mut push = |kind: u8, path: PathBuf, required: bool| -> Result<(), String> {
181 match std::fs::metadata(&path) {
182 Ok(m) => {
183 if required || m.len() > 0 {
184 staged.push(Staged::whole(kind, path, m.len()));
185 }
186 Ok(())
187 }
188 Err(e) if !required && e.kind() == std::io::ErrorKind::NotFound => Ok(()),
189 Err(e) => Err(format!("cannot stat {}: {e}", path.display())),
190 }
191 };
192 timer.switch("read-graph");
193 push(ARCHIVE_KIND_GRAPH_META, graph.join("metadata.bin"), true)?;
194 push(ARCHIVE_KIND_GRAPH_NODES, graph.join("nodes.bin"), true)?;
195 push(ARCHIVE_KIND_GRAPH_EDGES, graph.join("edges.bin"), true)?;
196 push(ARCHIVE_KIND_GRAPH_INTERMEDIATE, graph.join("intermediate.bin"), true)?;
197 // Optional graph sections: absent files are omitted, not zero-length.
198 push(ARCHIVE_KIND_GRAPH_NAMES, graph.join("road_names.bin"), false)?;
199 push(ARCHIVE_KIND_GRAPH_LANES, graph.join("lanes.bin"), false)?;
200 push(ARCHIVE_KIND_GRAPH_ELEVATION, graph.join("elevation.bin"), false)?;
201 timer.switch("read-poi");
202 push(ARCHIVE_KIND_POI_INDEX, poi.join("poi_index.bin"), true)?;
203 push(ARCHIVE_KIND_POI_NAMES, poi.join("poi_names.bin"), true)?;
204 push(ARCHIVE_KIND_POI_ATTRS, poi.join("poi_attrs.bin"), false)?;
205 push(ARCHIVE_KIND_POI_SPATIAL, poi.join("poi_spatial.bin"), false)?;
206 push(ARCHIVE_KIND_POI_WORDS, poi.join("poi_name_index.bin"), false)?;
207 let poi_attrs = match std::fs::metadata(poi.join("poi_attrs.bin")) {
208 Ok(m) if m.len() > 0 => Some(poi.join("poi_attrs.bin")),
209 _ => None,
210 };
211 // Transit is optional like the other sidecars: omitted when no pack is
212 // staged (a tiles+graph+POI archive still exercises every loader's
213 // degrade path on device). Callers that need it pass --transit.
214 timer.switch("read-transit");
215 let mut transit_prefix = Vec::new();
216 if let Some(t) = transit {
217 let file_len =
218 std::fs::metadata(t).map_err(|e| format!("cannot stat {}: {e}", t.display()))?.len();
219 let (head, len) = transit_without_host_sections(t, file_len)?;
220 // The build id hashes only the first 1 KiB (see `derive_build_id`), as shipped.
221 let mut f =
222 std::fs::File::open(t).map_err(|e| format!("cannot read {}: {e}", t.display()))?;
223 let mut buf = vec![0u8; (len.min(1024)) as usize];
224 f.read_exact(&mut buf).map_err(|e| format!("cannot read {}: {e}", t.display()))?;
225 let patched = head.len().min(buf.len());
226 buf[..patched].copy_from_slice(&head[..patched]);
227 transit_prefix = buf;
228 staged.push(Staged {
229 kind: ARCHIVE_KIND_TRANSIT,
230 path: t.to_path_buf(),
231 len,
232 extra: 0,
233 file_len,
234 head,
235 });
236 }
237 // The highway overlay (`road_overlay`) is optional and sorts after transit.
238 let overlay = graph.join("overlay.bin");
239 match std::fs::metadata(&overlay) {
240 Ok(m) if m.len() > 0 => {
241 staged.push(Staged::whole(ARCHIVE_KIND_GRAPH_OVERLAY, overlay, m.len()))
242 }
243 Ok(_) => {}
244 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
245 Err(e) => return Err(format!("cannot stat {}: {e}", overlay.display())),
246 }
247 // The POI region sidecar (`poi_region.bin`) is optional and sorts last: kind 15
248 // comes after the overlay's 14, and `ArchiveView::parse` requires ascending kinds.
249 let poi_region = poi.join("poi_region.bin");
250 match std::fs::metadata(&poi_region) {
251 Ok(m) if m.len() > 0 => {
252 staged.push(Staged::whole(ARCHIVE_KIND_POI_REGION, poi_region, m.len()))
253 }
254 Ok(_) => {}
255 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
256 Err(e) => return Err(format!("cannot stat {}: {e}", poi_region.display())),
257 }
258 // The boundary hierarchy (`poi_admin.bin`, kind 16) is optional and sorts after the region
259 // sidecar it describes. Older apps skip the kind; its digest feeds the build id (below).
260 let poi_admin = poi.join("poi_admin.bin");
261 let poi_admin = match std::fs::metadata(&poi_admin) {
262 Ok(m) if m.len() > 0 => {
263 staged.push(Staged::whole(ARCHIVE_KIND_POI_ADMIN, poi_admin.clone(), m.len()));
264 Some(poi_admin)
265 }
266 Ok(_) => None,
267 Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
268 Err(e) => return Err(format!("cannot stat {}: {e}", poi_admin.display())),
269 };
270 // Validate every sidecar's magic/version/count BEFORE anything is written: each section's
271 // check is the same one its loader runs, and a mismatch fails closed with a non-zero exit
272 // and no partial output. Only the small files are read whole; the large graph payloads
273 // validate by streaming their heads (lengths come from the metadata counts).
274 validate_sidecars(graph, poi, &staged, timer)?;
275 // The tile header's own build-id bytes are read by the caller (it holds the tiles prefix);
276 // placeholder filled in `main` after the tiles prefix is parsed.
277 Ok(Validated { staged, transit_prefix, osm_id: [0u8; 8], poi_attrs, poi_admin })
278}
279
280/// A file's length, with the same "cannot read" wording a whole-file read would give.
281fn file_len(path: &Path) -> Result<u64, String> {
282 std::fs::metadata(path)
283 .map(|m| m.len())
284 .map_err(|e| format!("cannot read {}: {e}", path.display()))
285}
286
287/// Up to the first `n` bytes of a file (fewer only if the file is shorter).
288fn read_head(path: &Path, n: usize) -> Result<Vec<u8>, String> {
289 let f =
290 std::fs::File::open(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
291 let mut buf = Vec::with_capacity(n);
292 f.take(n as u64)
293 .read_to_end(&mut buf)
294 .map_err(|e| format!("cannot read {}: {e}", path.display()))?;
295 Ok(buf)
296}
297
298/// FNV-1a 64 over a whole file, streamed.
299fn fnv64_file(path: &Path) -> Result<[u8; 8], String> {
300 let mut f =
301 std::fs::File::open(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
302 let mut buf = vec![0u8; 1 << 20];
303 let mut h = 0xcbf2_9ce4_8422_2325u64;
304 loop {
305 let n = f.read(&mut buf).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
306 if n == 0 {
307 return Ok(h.to_le_bytes());
308 }
309 for &b in &buf[..n] {
310 h ^= b as u64;
311 h = h.wrapping_mul(0x100_0000_01b3);
312 }
313 }
314}
315
316include!("mamaps_pack_parts/mamaps_pack_part1.rs");
317include!("mamaps_pack_parts/mamaps_pack_part2.rs");
318include!("mamaps_pack_parts/mamaps_pack_part3.rs");
319include!("mamaps_pack_parts/mamaps_pack_part4.rs");