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

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

chains_part1.rs438 lines · 16.5 KiBRaw
1impl ChainRec {
2 /// This chain's polyline, from `chains.pts` read into memory.
3 #[cfg(test)]
4 pub fn pts<'a>(&self, all: &'a [geom::Pt]) -> &'a [geom::Pt] {
5 let s = self.pts_start as usize;
6 &all[s..s + self.pts_len as usize]
7 }
8
9 fn encode(&self, out: &mut [u8; CHAIN_REC_BYTES as usize]) {
10 out.fill(0);
11 out[0..8].copy_from_slice(&self.pts_start.to_le_bytes());
12 out[8..12].copy_from_slice(&self.pts_len.to_le_bytes());
13 out[12..16].copy_from_slice(&self.first.to_le_bytes());
14 out[16..20].copy_from_slice(&self.last.to_le_bytes());
15 out[20..24].copy_from_slice(&self.dist_mm.to_le_bytes());
16 out[24..28].copy_from_slice(&self.name_offset.to_le_bytes());
17 out[28..32].copy_from_slice(&self.fwd_lane_off.to_le_bytes());
18 out[32..36].copy_from_slice(&self.bwd_lane_off.to_le_bytes());
19 out[36..38].copy_from_slice(&self.fwd_lane_count.to_le_bytes());
20 out[38..40].copy_from_slice(&self.bwd_lane_count.to_le_bytes());
21 out[40] = self.type_;
22 out[41] = self.speed_limit;
23 out[42] = u8::from(self.oneway);
24 }
25
26 fn decode(b: &[u8]) -> ChainRec {
27 let u32_at = |o: usize| u32::from_le_bytes(b[o..o + 4].try_into().expect("4 bytes"));
28 let u16_at = |o: usize| u16::from_le_bytes(b[o..o + 2].try_into().expect("2 bytes"));
29 ChainRec {
30 pts_start: u64::from_le_bytes(b[0..8].try_into().expect("8 bytes")),
31 pts_len: u32_at(8),
32 first: u32_at(12),
33 last: u32_at(16),
34 dist_mm: u32_at(20),
35 name_offset: u32_at(24),
36 fwd_lane_off: u32_at(28),
37 bwd_lane_off: u32_at(32),
38 fwd_lane_count: u16_at(36),
39 bwd_lane_count: u16_at(38),
40 type_: b[40],
41 speed_limit: b[41],
42 oneway: b[42] != 0,
43 }
44 }
45}
46
47/// The pair of spill files, in a directory of their own so a build cannot
48/// mistake them for pack output.
49///
50/// The two files can live on different filesystems, because they are read very
51/// differently. `chains.hdr` is only ever streamed from the front, once per write
52/// round, so a slow-but-roomy mount costs little. `chains.pts` is read *randomly*,
53/// once per edge that stores a polyline, and that is the access pattern a
54/// translation layer like drvfs punishes by an order of magnitude. At planet scale
55/// the header is also the larger of the two — about 24 GB against 18 GB — so
56/// separating them puts the bulk where there is room and the seeks where they are
57/// cheap.
58pub(crate) struct Spill {
59 hdr_dir: PathBuf,
60 pts_dir: PathBuf,
61 hdr: PathBuf,
62 pts: PathBuf,
63}
64
65impl Spill {
66 /// Both files in one directory.
67 #[cfg(test)]
68 pub fn new(dir: &Path) -> Spill {
69 Spill::split(dir, dir)
70 }
71
72 /// `chains.hdr` under `hdr_dir`, `chains.pts` under `pts_dir`.
73 pub fn split(hdr_dir: &Path, pts_dir: &Path) -> Spill {
74 let hdr_dir = hdr_dir.join("chain_spill");
75 let pts_dir = pts_dir.join("chain_spill");
76 Spill {
77 hdr: hdr_dir.join("chains.hdr"),
78 pts: pts_dir.join("chains.pts"),
79 hdr_dir,
80 pts_dir,
81 }
82 }
83
84 fn make_dirs(&self) -> Result<()> {
85 for dir in [&self.hdr_dir, &self.pts_dir] {
86 std::fs::create_dir_all(dir)
87 .map_err(|e| Error(format!("cannot create {}: {e}", dir.display())))?;
88 }
89 Ok(())
90 }
91
92 /// An incremental writer, for the chain pass to stream into.
93 ///
94 /// The alternative — accumulate every chain and every point, then write them —
95 /// costs 11.7 GB on Europe and about 31 GB on a planet, which is most of the
96 /// budget the spill exists to save. The pass sink is already single-threaded
97 /// and called in chunk order, so writing from it keeps the files
98 /// byte-deterministic.
99 pub fn writer(&self) -> Result<SpillWriter> {
100 self.make_dirs()?;
101 Ok(SpillWriter {
102 hdr: BufWriter::with_capacity(1 << 20, create(&self.hdr)?),
103 pts: BufWriter::with_capacity(1 << 20, create(&self.pts)?),
104 points: 0,
105 chains: 0,
106 })
107 }
108
109 /// Write `chains` and their points, resolving dense ids to coordinates.
110 ///
111 /// `pts_dense` must be laid out so each chain's range follows the one before
112 /// it, which is how the chain pass builds it; the points then stream out in
113 /// one sequential write and every `pts_start` carries over unchanged.
114 pub fn write(
115 &self,
116 chains: &[Chain],
117 pts_dense: &[u32],
118 coords: &[geom::Pt],
119 ) -> Result<()> {
120 self.make_dirs()?;
121 let mut hdr = BufWriter::new(create(&self.hdr)?);
122 let mut rec = [0u8; CHAIN_REC_BYTES as usize];
123 let mut expect_start = 0u64;
124 for c in chains {
125 let ids = c.pts(pts_dense);
126 debug_assert_eq!(c.pts_start, expect_start, "chain points are not contiguous");
127 expect_start += u64::from(c.pts_len);
128 ChainRec {
129 pts_start: c.pts_start,
130 pts_len: c.pts_len,
131 first: ids[0],
132 last: ids[ids.len() - 1],
133 dist_mm: c.dist_mm,
134 name_offset: c.name_offset,
135 fwd_lane_off: c.fwd_lane_off,
136 bwd_lane_off: c.bwd_lane_off,
137 fwd_lane_count: c.fwd_lane_count,
138 bwd_lane_count: c.bwd_lane_count,
139 type_: c.type_,
140 speed_limit: c.speed_limit,
141 oneway: c.oneway,
142 }
143 .encode(&mut rec);
144 hdr.write_all(&rec).map_err(io_err)?;
145 }
146 hdr.flush().map_err(io_err)?;
147
148 let mut out = BufWriter::new(create(&self.pts)?);
149 for id in pts_dense {
150 let (lat_e7, lon_e7) = coords[*id as usize];
151 out.write_all(&lat_e7.to_le_bytes()).map_err(io_err)?;
152 out.write_all(&lon_e7.to_le_bytes()).map_err(io_err)?;
153 }
154 out.flush().map_err(io_err)?;
155 Ok(())
156 }
157
158 /// How many chains the spill holds, from the header file's size alone.
159 pub fn chain_count(&self) -> Result<u64> {
160 let len = std::fs::metadata(&self.hdr)
161 .map_err(|e| Error(format!("cannot stat {}: {e}", self.hdr.display())))?
162 .len();
163 if len % CHAIN_REC_BYTES != 0 {
164 return Err(Error(format!(
165 "{} is {len} bytes, not a multiple of {CHAIN_REC_BYTES}",
166 self.hdr.display()
167 )));
168 }
169 Ok(len / CHAIN_REC_BYTES)
170 }
171
172 /// Read the whole spill back. The build itself streams; this is for tests,
173 /// which need to see the two files as a unit to check they round-trip.
174 #[cfg(test)]
175 pub fn read_all(&self) -> Result<(Vec<ChainRec>, Vec<geom::Pt>)> {
176 let count = self.chain_count()?;
177 let mut hdr = self.headers()?;
178 let mut chains = Vec::with_capacity(count as usize);
179 while let Some(c) = hdr.next()? {
180 chains.push(c);
181 }
182
183 let bytes = self.point_bytes()?;
184 let mut src = BufReader::new(open(&self.pts)?);
185 let mut buf = [0u8; CHAIN_PT_BYTES as usize];
186 let mut pts = Vec::with_capacity((bytes / CHAIN_PT_BYTES) as usize);
187 for _ in 0..bytes / CHAIN_PT_BYTES {
188 src.read_exact(&mut buf).map_err(io_err)?;
189 pts.push(decode_pt(&buf));
190 }
191 Ok((chains, pts))
192 }
193
194 /// Sequential reader over `chains.hdr`. Every stage after the chain pass is one
195 /// of these: the degree count for the CSR, the target scatter, and the single
196 /// round-assignment scan feeding [`Spill::headers_mapped`](Self::headers_mapped).
197 pub fn headers(&self) -> Result<HeaderReader> {
198 Ok(HeaderReader {
199 src: BufReader::with_capacity(1 << 20, open(&self.hdr)?),
200 left: self.chain_count()?,
201 })
202 }
203
204 /// Random-access reader over `chains.hdr`, for the write rounds.
205 ///
206 /// Records are fixed-stride (`CHAIN_REC_BYTES` each), so chain `i` starts
207 /// at byte `i * CHAIN_REC_BYTES` — no index, no scan. The write used to
208 /// re-stream the whole file once per round (3 rounds on a continent: 3
209 /// full header passes); now one assignment scan records each chain's
210 /// round and every round gathers only its chains through this mapping.
211 /// Page-cached after the assignment scan, so the gather faults almost
212 /// nothing new.
213 pub fn headers_mapped(&self) -> Result<HeaderMap> {
214 Ok(HeaderMap { map: crate::mem::Mapped::open(&self.hdr).map_err(Error)? })
215 }
216
217 /// Random-access reader over `chains.pts`.
218 ///
219 /// The write rounds visit chains in edge order, not chain order, so this is the
220 /// one place the spill is not read sequentially. The file is mapped once and
221 /// read as slices: one seek per edge into a file the page cache has largely
222 /// seen already became zero syscalls per edge.
223 pub fn points(&self) -> Result<PointReader> {
224 Ok(PointReader { map: crate::mem::Mapped::open(&self.pts).map_err(Error)? })
225 }
226
227 #[cfg(test)]
228 fn point_bytes(&self) -> Result<u64> {
229 let bytes = std::fs::metadata(&self.pts)
230 .map_err(|e| Error(format!("cannot stat {}: {e}", self.pts.display())))?
231 .len();
232 if bytes % CHAIN_PT_BYTES != 0 {
233 return Err(Error(format!(
234 "{} is {bytes} bytes, not a multiple of {CHAIN_PT_BYTES}",
235 self.pts.display()
236 )));
237 }
238 Ok(bytes)
239 }
240
241 /// Best-effort cleanup, also run on drop. A leftover spill is tens of
242 /// gigabytes, but failing the build over an undeletable temporary would be
243 /// worse than leaving it.
244 pub fn remove(&self) {
245 let _ = std::fs::remove_file(&self.hdr);
246 let _ = std::fs::remove_file(&self.pts);
247 // Only removes them if empty, so a shared parent survives.
248 let _ = std::fs::remove_dir(&self.hdr_dir);
249 let _ = std::fs::remove_dir(&self.pts_dir);
250 }
251}
252
253impl Drop for Spill {
254 /// The spill is a temporary, so its lifetime is the handle's. Without this, any
255 /// error between writing it and the end of the build would strand it: the one
256 /// path where a leftover is most likely is also the one nobody is watching.
257 fn drop(&mut self) {
258 self.remove();
259 }
260}
261
262fn create(path: &Path) -> Result<File> {
263 File::create(path).map_err(|e| Error(format!("cannot write {}: {e}", path.display())))
264}
265
266fn open(path: &Path) -> Result<File> {
267 File::open(path).map_err(|e| Error(format!("cannot read {}: {e}", path.display())))
268}
269
270fn decode_pt(b: &[u8]) -> geom::Pt {
271 (
272 i32::from_le_bytes(b[0..4].try_into().expect("4 bytes")),
273 i32::from_le_bytes(b[4..8].try_into().expect("4 bytes")),
274 )
275}
276
277/// Streams `chains.hdr` and `chains.pts` from the front.
278pub(crate) struct SpillWriter {
279 hdr: BufWriter<File>,
280 pts: BufWriter<File>,
281 /// Points written so far, which is the next chain's `pts_start`.
282 points: u64,
283 chains: u64,
284}
285
286impl SpillWriter {
287 /// Append one chain and its polyline.
288 ///
289 /// `ids` are the chain's dense node ids in order; their coordinates go to
290 /// `chains.pts` and only the two endpoint *ids* are kept, in the header, since
291 /// coordinates cannot be mapped back to a node.
292 pub fn push(&mut self, c: &Chain, ids: &[u32], coords: &[geom::Pt]) -> Result<()> {
293 debug_assert_eq!(ids.len(), c.pts_len as usize);
294 let mut rec = [0u8; CHAIN_REC_BYTES as usize];
295 ChainRec {
296 pts_start: self.points,
297 pts_len: c.pts_len,
298 first: ids[0],
299 last: ids[ids.len() - 1],
300 dist_mm: c.dist_mm,
301 name_offset: c.name_offset,
302 fwd_lane_off: c.fwd_lane_off,
303 bwd_lane_off: c.bwd_lane_off,
304 fwd_lane_count: c.fwd_lane_count,
305 bwd_lane_count: c.bwd_lane_count,
306 type_: c.type_,
307 speed_limit: c.speed_limit,
308 oneway: c.oneway,
309 }
310 .encode(&mut rec);
311 self.hdr.write_all(&rec).map_err(io_err)?;
312 for id in ids {
313 let (lat_e7, lon_e7) = coords[*id as usize];
314 self.pts.write_all(&lat_e7.to_le_bytes()).map_err(io_err)?;
315 self.pts.write_all(&lon_e7.to_le_bytes()).map_err(io_err)?;
316 }
317 self.points += u64::from(c.pts_len);
318 self.chains += 1;
319 Ok(())
320 }
321
322 /// Flush both files and report how many chains were written.
323 pub fn finish(mut self) -> Result<u64> {
324 self.hdr.flush().map_err(io_err)?;
325 self.pts.flush().map_err(io_err)?;
326 Ok(self.chains)
327 }
328}
329
330/// Streams `chains.hdr` from the front.
331pub(crate) struct HeaderReader {
332 src: BufReader<File>,
333 left: u64,
334}
335
336impl HeaderReader {
337 #[allow(clippy::should_implement_trait)]
338 pub fn next(&mut self) -> Result<Option<ChainRec>> {
339 if self.left == 0 {
340 return Ok(None);
341 }
342 let mut rec = [0u8; CHAIN_REC_BYTES as usize];
343 self.src.read_exact(&mut rec).map_err(io_err)?;
344 self.left -= 1;
345 Ok(Some(ChainRec::decode(&rec)))
346 }
347}
348
349/// Random-access view over `chains.hdr`. See [`Spill::headers_mapped`].
350pub(crate) struct HeaderMap {
351 map: crate::mem::Mapped,
352}
353
354impl HeaderMap {
355 /// How many records the mapping holds, from its length alone — the same
356 /// width check [`Spill::chain_count`] applies to the file.
357 pub fn len(&self) -> Result<u64> {
358 let len = self.map.len() as u64;
359 if len % CHAIN_REC_BYTES != 0 {
360 return Err(Error(format!(
361 "chains.hdr is {len} bytes, not a multiple of {CHAIN_REC_BYTES}"
362 )));
363 }
364 Ok(len / CHAIN_REC_BYTES)
365 }
366
367 /// Decode chain `i`. Bounds-checked: a short mapping fails rather than
368 /// slicing past the end.
369 pub fn get(&self, i: u64) -> Result<ChainRec> {
370 let at = i.checked_mul(CHAIN_REC_BYTES).expect("chain index * stride fits u64");
371 let end = at + CHAIN_REC_BYTES;
372 if end > self.map.len() as u64 {
373 return Err(Error(format!("chains.hdr ends before chain {i}")));
374 }
375 let (at, end) = (at as usize, end as usize);
376 let mut rec = [0u8; CHAIN_REC_BYTES as usize];
377 rec.copy_from_slice(&self.map[at..end]);
378 Ok(ChainRec::decode(&rec))
379 }
380}
381
382/// Reads one chain's polyline out of `chains.pts`.
383pub(crate) struct PointReader {
384 map: crate::mem::Mapped,
385}
386
387/// The shared mapping behind a [`PointReader`]: pool workers read the same
388/// bytes through [`PointReader::read_shared`] with no lock and no cursor.
389pub(crate) fn points_map(reader: &PointReader) -> &crate::mem::Mapped {
390 &reader.map
391}
392
393impl PointReader {
394 /// Replace `out` with the `len` points starting at point index `start`.
395 ///
396 /// A slice of one persistent mapping, not a positional read: the write
397 /// rounds visit chains in edge order, not chain order, so a `File` paid
398 /// one syscall per edge (~300 M at planet scale) for a few dozen bytes
399 /// each. The mapping faults the same pages with zero syscalls, no
400 /// per-edge buffer zeroing, and no cursor to keep — which is also what a
401 /// parallel writer would need first.
402 ///
403 /// Short reads fail exactly as the positional path did (`UnexpectedEof`
404 /// naming the file), so a truncated spill surfaces here rather than as a
405 /// wrong polyline downstream.
406 pub fn read(&mut self, start: u64, len: u32, out: &mut Vec<geom::Pt>) -> Result<()> {
407 Self::read_from(&self.map, start, len, out)
408 }
409
410 /// [`read`](Self::read) over an explicit mapping: the shared-read form.
411 ///
412 /// `read` takes `&mut self` for the historical reason that the reader
413 /// used to hold a cursor; the mapping itself is never mutated, so pool
414 /// workers share one `&Mapped` and read through this instead. Same
415 /// slices, same errors, no lock.
416 pub fn read_shared(map: &crate::mem::Mapped, start: u64, len: u32, out: &mut Vec<geom::Pt>) -> Result<()> {
417 Self::read_from(map, start, len, out)
418 }
419
420 fn read_from(map: &crate::mem::Mapped, start: u64, len: u32, out: &mut Vec<geom::Pt>) -> Result<()> {
421 out.clear();
422 if len == 0 {
423 return Ok(());
424 }
425 let at = start as u128 * CHAIN_PT_BYTES as u128;
426 let bytes = len as u128 * CHAIN_PT_BYTES as u128;
427 if at + bytes > map.len() as u128 {
428 return Err(Error(format!("chains.pts ended mid-chain")));
429 }
430 let (at, bytes) = (at as usize, bytes as usize);
431 out.extend(map[at..at + bytes].chunks_exact(CHAIN_PT_BYTES as usize).map(decode_pt));
432 Ok(())
433 }
434}
435
436fn io_err(e: std::io::Error) -> Error {
437 Error(e.to_string())
438}