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

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

graph_build_part5.rs194 lines · 7.5 KiBRaw
1/// `lanes.bin`, as a sparse index: `[ u32 n ][ (u32 edge_idx, u32 off) x (n + 1) ]`
2/// then the `u16` mask blob.
3///
4/// `turn:lanes` is rare — 2.9 M of a planet's 1.07 G directed edges carry any — so
5/// a dense `u64` per edge made 99.8% of an 8.60 GB file describe edges with no
6/// lanes. Listing only the edges that have them is ~23 MB of index plus a 13 MB
7/// blob. Entry *i*'s masks run from its offset to entry *i+1*'s, so the trailing
8/// sentinel gives the last edge its length and the blob its total.
9///
10/// The round-partitioned writer cannot know `n` up front, so the blob streams to a
11/// scratch file while the index accumulates in memory (23 MB at planet scale) and
12/// the header plus index are written in front of it at the end.
13struct LaneFile {
14 path: PathBuf,
15 blob_path: PathBuf,
16 blob: BufWriter<File>,
17 index: Vec<(u32, u32)>,
18 blob_len: u64,
19}
20
21impl LaneFile {
22 fn create(dir: &Path, name: &str) -> Result<LaneFile> {
23 let blob_path = dir.join(format!("{name}.blob"));
24 Ok(LaneFile {
25 path: dir.join(name),
26 blob: BufWriter::new(create(&blob_path)?),
27 blob_path,
28 index: Vec::new(),
29 blob_len: 0,
30 })
31 }
32
33 /// Record `bytes` as edge `idx`'s masks. Only called for edges that have any,
34 /// and always with an ascending `idx`, because the rounds ascend and each round
35 /// writes its edges in index order.
36 fn push(&mut self, idx: u64, bytes: &[u8]) -> Result<()> {
37 debug_assert!(!bytes.is_empty(), "an empty lane blob would read back as absent");
38 debug_assert!(
39 self.index.last().is_none_or(|(last, _)| *last < idx as u32),
40 "lane index entries must ascend by edge index"
41 );
42 let off = self.blob_off()?;
43 self.index.push((idx as u32, off));
44 self.blob.write_all(bytes).map_err(io_err)?;
45 self.blob_len += bytes.len() as u64;
46 Ok(())
47 }
48
49 /// The current blob length as the `u32` an index entry stores.
50 fn blob_off(&self) -> Result<u32> {
51 u32::try_from(self.blob_len).map_err(|_| {
52 Error(format!(
53 "the lane blob reached {} bytes, past the {} a u32 offset can address",
54 self.blob_len,
55 u32::MAX
56 ))
57 })
58 }
59
60 /// Write the header and index, then the blob behind it. Returns the finished
61 /// file's size.
62 fn finish(mut self) -> Result<u64> {
63 self.blob.flush().map_err(io_err)?;
64 let n = u32::try_from(self.index.len()).map_err(|_| {
65 Error(format!(
66 "{} lane-bearing edge(s) is past the {} the index header can count",
67 self.index.len(),
68 u32::MAX
69 ))
70 })?;
71 let mut out = BufWriter::new(create(&self.path)?);
72 out.write_all(&n.to_le_bytes()).map_err(io_err)?;
73 for (idx, off) in &self.index {
74 out.write_all(&idx.to_le_bytes()).map_err(io_err)?;
75 out.write_all(&off.to_le_bytes()).map_err(io_err)?;
76 }
77 // The sentinel's edge index is `u32::MAX` rather than a real one: it exists
78 // only to give the last entry a length, and the reader's binary search
79 // covers the first `n` entries, so no valid index may collide with it. Its
80 // offset is the blob length, which is also how the reader length-validates
81 // the blob.
82 let blob_end = self.blob_off()?;
83 out.write_all(&u32::MAX.to_le_bytes()).map_err(io_err)?;
84 out.write_all(&blob_end.to_le_bytes()).map_err(io_err)?;
85
86 let mut src = BufReader::with_capacity(1 << 20, open(&self.blob_path)?);
87 std::io::copy(&mut src, &mut out).map_err(io_err)?;
88 out.flush().map_err(io_err)?;
89 Ok(4 + u64::from(n + 1) * 8 + self.blob_len)
90 }
91}
92
93impl Drop for LaneFile {
94 fn drop(&mut self) {
95 let _ = std::fs::remove_file(&self.blob_path);
96 }
97}
98
99fn create(path: &Path) -> Result<File> {
100 File::create(path).map_err(|e| Error(format!("cannot write {}: {e}", path.display())))
101}
102
103fn open(path: &Path) -> Result<File> {
104 File::open(path).map_err(|e| Error(format!("cannot read {}: {e}", path.display())))
105}
106
107fn io_err(e: std::io::Error) -> Error {
108 Error(e.to_string())
109}
110
111/// Parse the tool's command line:
112/// `road_graph IN.osm.pbf [--out DIR] [--reference-collapse] [--rounds N]
113/// [--spill-dir DIR] [--spill-pts-dir DIR] [--dem DATASET.mdem] [--region california|world] [--stats]`.
114pub fn parse_args(
115 args: &[String],
116) -> std::result::Result<(PathBuf, PathBuf, Options), String> {
117 let mut input: Option<PathBuf> = None;
118 let mut out = PathBuf::from("map_data");
119 // The CLI defaults to the streaming within-way collapse: it is the only path
120 // whose working set fits a planet build on a commodity box. The reference
121 // whole-graph collapse stays reachable for cross-checking via
122 // --reference-collapse. The library default (`Options::default`) is unchanged.
123 let mut opts = Options { within_way_chains: true, ..Default::default() };
124 let mut i = 0;
125 while i < args.len() {
126 match args[i].as_str() {
127 "--out" | "-o" => {
128 i += 1;
129 let dir = args.get(i).ok_or_else(|| "--out needs a directory".to_string())?;
130 out = PathBuf::from(dir);
131 }
132 "--reference-collapse" => opts.within_way_chains = false,
133 "--stats" => opts.stats = true,
134 "--threads" => {
135 i += 1;
136 let n = args
137 .get(i)
138 .ok_or_else(|| "--threads needs a count".to_string())?;
139 opts.threads = Some(crate::par::parse_threads(n)?);
140 }
141 "--spill-dir" => {
142 i += 1;
143 let dir = args
144 .get(i)
145 .ok_or_else(|| "--spill-dir needs a directory".to_string())?;
146 opts.spill_dir = Some(PathBuf::from(dir));
147 }
148 "--spill-pts-dir" => {
149 i += 1;
150 let dir = args
151 .get(i)
152 .ok_or_else(|| "--spill-pts-dir needs a directory".to_string())?;
153 opts.spill_pts_dir = Some(PathBuf::from(dir));
154 }
155 "--rounds" => {
156 i += 1;
157 let n = args.get(i).ok_or_else(|| "--rounds needs a count".to_string())?;
158 opts.rounds = n
159 .parse::<u32>()
160 .ok()
161 .filter(|n| *n > 0)
162 .ok_or_else(|| format!("--rounds wants a positive count, not {n}"))?;
163 }
164 "--dem" => {
165 i += 1;
166 let path = args
167 .get(i)
168 .ok_or_else(|| "--dem needs a .mdem dataset path".to_string())?;
169 opts.dem = Some(PathBuf::from(path));
170 }
171 "--region" => {
172 i += 1;
173 let value = args
174 .get(i)
175 .ok_or_else(|| "--region needs `california`, `na` or `world`".to_string())?;
176 let region = crate::region::Region::parse(value).map_err(|e| e.0)?;
177 opts.bbox = region.bbox();
178 }
179 a if a.starts_with('-') => return Err(format!("unknown option: {a}")),
180 a => {
181 if input.is_some() {
182 return Err(format!("unexpected extra argument: {a}"));
183 }
184 input = Some(PathBuf::from(a));
185 }
186 }
187 i += 1;
188 }
189 Ok((
190 input.ok_or_else(|| "missing IN.osm.pbf".to_string())?,
191 out,
192 opts,
193 ))
194}