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

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

chains_part1.rs462 lines · 17.7 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 let hdr = BufWriter::with_capacity(8 << 20, create(&self.hdr)?);
102 let pts = BufWriter::with_capacity(8 << 20, create(&self.pts)?);
103 // The appends run on threads of their own — one per file, since the two
104 // are independent streams — so the chain pass's ordered sink hands
105 // buffers over instead of copying ~45 GB (planet) through write(2)
106 // itself. Bounded, so at most a few chunks are in flight per file.
107 let spawn = |name: &str, mut out: BufWriter<File>| {
108 let (tx, rx) = std::sync::mpsc::sync_channel::<Vec<u8>>(4);
109 std::thread::Builder::new()
110 .name(name.into())
111 .spawn(move || -> std::io::Result<()> {
112 for b in rx {
113 out.write_all(&b)?;
114 }
115 out.flush()
116 })
117 .map(|t| (tx, t))
118 .map_err(|e| Error(format!("cannot start the spill writer: {e}")))
119 };
120 let (hdr_tx, hdr_t) = spawn("chain-hdr-writer", hdr)?;
121 let (pts_tx, pts_t) = spawn("chain-pts-writer", pts)?;
122 let (tx, thread) = ((hdr_tx, pts_tx), (hdr_t, pts_t));
123 Ok(SpillWriter {
124 tx: Some(tx),
125 thread: Some(thread),
126 points: 0,
127 chains: 0,
128 })
129 }
130
131 /// Write `chains` and their points, resolving dense ids to coordinates.
132 ///
133 /// `pts_dense` must be laid out so each chain's range follows the one before
134 /// it, which is how the chain pass builds it; the points then stream out in
135 /// one sequential write and every `pts_start` carries over unchanged.
136 pub fn write(
137 &self,
138 chains: &[Chain],
139 pts_dense: &[u32],
140 coords: &[geom::Pt],
141 ) -> Result<()> {
142 self.make_dirs()?;
143 let mut hdr = BufWriter::new(create(&self.hdr)?);
144 let mut rec = [0u8; CHAIN_REC_BYTES as usize];
145 let mut expect_start = 0u64;
146 for c in chains {
147 let ids = c.pts(pts_dense);
148 debug_assert_eq!(c.pts_start, expect_start, "chain points are not contiguous");
149 expect_start += u64::from(c.pts_len);
150 ChainRec {
151 pts_start: c.pts_start,
152 pts_len: c.pts_len,
153 first: ids[0],
154 last: ids[ids.len() - 1],
155 dist_mm: c.dist_mm,
156 name_offset: c.name_offset,
157 fwd_lane_off: c.fwd_lane_off,
158 bwd_lane_off: c.bwd_lane_off,
159 fwd_lane_count: c.fwd_lane_count,
160 bwd_lane_count: c.bwd_lane_count,
161 type_: c.type_,
162 speed_limit: c.speed_limit,
163 oneway: c.oneway,
164 }
165 .encode(&mut rec);
166 hdr.write_all(&rec).map_err(io_err)?;
167 }
168 hdr.flush().map_err(io_err)?;
169
170 let mut out = BufWriter::new(create(&self.pts)?);
171 for id in pts_dense {
172 let (lat_e7, lon_e7) = coords[*id as usize];
173 out.write_all(&lat_e7.to_le_bytes()).map_err(io_err)?;
174 out.write_all(&lon_e7.to_le_bytes()).map_err(io_err)?;
175 }
176 out.flush().map_err(io_err)?;
177 Ok(())
178 }
179
180 /// How many chains the spill holds, from the header file's size alone.
181 pub fn chain_count(&self) -> Result<u64> {
182 let len = std::fs::metadata(&self.hdr)
183 .map_err(|e| Error(format!("cannot stat {}: {e}", self.hdr.display())))?
184 .len();
185 if len % CHAIN_REC_BYTES != 0 {
186 return Err(Error(format!(
187 "{} is {len} bytes, not a multiple of {CHAIN_REC_BYTES}",
188 self.hdr.display()
189 )));
190 }
191 Ok(len / CHAIN_REC_BYTES)
192 }
193
194 /// Read the whole spill back. The build itself streams; this is for tests,
195 /// which need to see the two files as a unit to check they round-trip.
196 #[cfg(test)]
197 pub fn read_all(&self) -> Result<(Vec<ChainRec>, Vec<geom::Pt>)> {
198 let count = self.chain_count()?;
199 let hdr = self.headers_mapped()?;
200 let mut chains = Vec::with_capacity(count as usize);
201 for i in 0..count {
202 chains.push(hdr.get(i)?);
203 }
204
205 let bytes = self.point_bytes()?;
206 use std::io::Read as _;
207 let mut src = std::io::BufReader::new(open(&self.pts)?);
208 let mut buf = [0u8; CHAIN_PT_BYTES as usize];
209 let mut pts = Vec::with_capacity((bytes / CHAIN_PT_BYTES) as usize);
210 for _ in 0..bytes / CHAIN_PT_BYTES {
211 src.read_exact(&mut buf).map_err(io_err)?;
212 pts.push(decode_pt(&buf));
213 }
214 Ok((chains, pts))
215 }
216
217 /// Random-access reader over `chains.hdr`, for the write rounds.
218 ///
219 /// Records are fixed-stride (`CHAIN_REC_BYTES` each), so chain `i` starts
220 /// at byte `i * CHAIN_REC_BYTES` — no index, no scan. The write used to
221 /// re-stream the whole file once per round (3 rounds on a continent: 3
222 /// full header passes); now one assignment scan records each chain's
223 /// round and every round gathers only its chains through this mapping.
224 /// Page-cached after the assignment scan, so the gather faults almost
225 /// nothing new.
226 pub fn headers_mapped(&self) -> Result<HeaderMap> {
227 Ok(HeaderMap { map: crate::mem::Mapped::open(&self.hdr).map_err(Error)? })
228 }
229
230 /// Random-access reader over `chains.pts`.
231 ///
232 /// The write rounds visit chains in edge order, not chain order, so this is the
233 /// one place the spill is not read sequentially. The file is mapped once and
234 /// read as slices: one seek per edge into a file the page cache has largely
235 /// seen already became zero syscalls per edge.
236 pub fn points(&self) -> Result<PointReader> {
237 Ok(PointReader { map: crate::mem::Mapped::open(&self.pts).map_err(Error)? })
238 }
239
240 #[cfg(test)]
241 fn point_bytes(&self) -> Result<u64> {
242 let bytes = std::fs::metadata(&self.pts)
243 .map_err(|e| Error(format!("cannot stat {}: {e}", self.pts.display())))?
244 .len();
245 if bytes % CHAIN_PT_BYTES != 0 {
246 return Err(Error(format!(
247 "{} is {bytes} bytes, not a multiple of {CHAIN_PT_BYTES}",
248 self.pts.display()
249 )));
250 }
251 Ok(bytes)
252 }
253
254 /// Best-effort cleanup, also run on drop. A leftover spill is tens of
255 /// gigabytes, but failing the build over an undeletable temporary would be
256 /// worse than leaving it.
257 pub fn remove(&self) {
258 let _ = std::fs::remove_file(&self.hdr);
259 let _ = std::fs::remove_file(&self.pts);
260 // Only removes them if empty, so a shared parent survives.
261 let _ = std::fs::remove_dir(&self.hdr_dir);
262 let _ = std::fs::remove_dir(&self.pts_dir);
263 }
264}
265
266impl Drop for Spill {
267 /// The spill is a temporary, so its lifetime is the handle's. Without this, any
268 /// error between writing it and the end of the build would strand it: the one
269 /// path where a leftover is most likely is also the one nobody is watching.
270 fn drop(&mut self) {
271 self.remove();
272 }
273}
274
275fn create(path: &Path) -> Result<File> {
276 File::create(path).map_err(|e| Error(format!("cannot write {}: {e}", path.display())))
277}
278
279#[cfg(test)]
280fn open(path: &Path) -> Result<File> {
281 File::open(path).map_err(|e| Error(format!("cannot read {}: {e}", path.display())))
282}
283
284fn decode_pt(b: &[u8]) -> geom::Pt {
285 (
286 i32::from_le_bytes(b[0..4].try_into().expect("4 bytes")),
287 i32::from_le_bytes(b[4..8].try_into().expect("4 bytes")),
288 )
289}
290
291/// Streams `chains.hdr` and `chains.pts` from the front.
292/// Sender for one spill file's writer thread.
293type SpillSender = std::sync::mpsc::SyncSender<Vec<u8>>;
294/// The two spill writer threads: `(chains.hdr, chains.pts)`.
295type SpillThreads = (
296 std::thread::JoinHandle<std::io::Result<()>>,
297 std::thread::JoinHandle<std::io::Result<()>>,
298);
299
300pub(crate) struct SpillWriter {
301 /// Buffers for the writer thread, in order: `(chains.hdr bytes, chains.pts bytes)`.
302 tx: Option<(SpillSender, SpillSender)>,
303 thread: Option<SpillThreads>,
304 /// Points written so far, which is the next chain's `pts_start`.
305 pub(crate) points: u64,
306 chains: u64,
307}
308
309impl SpillWriter {
310 /// Append one chain and its polyline.
311 ///
312 /// `ids` are the chain's dense node ids in order; their coordinates go to
313 /// `chains.pts` and only the two endpoint *ids* are kept, in the header, since
314 /// coordinates cannot be mapped back to a node.
315 #[cfg(test)]
316 pub fn push(&mut self, c: &Chain, ids: &[u32], coords: &[geom::Pt]) -> Result<()> {
317 debug_assert_eq!(ids.len(), c.pts_len as usize);
318 let mut rec = [0u8; CHAIN_REC_BYTES as usize];
319 ChainRec {
320 pts_start: self.points,
321 pts_len: c.pts_len,
322 first: ids[0],
323 last: ids[ids.len() - 1],
324 dist_mm: c.dist_mm,
325 name_offset: c.name_offset,
326 fwd_lane_off: c.fwd_lane_off,
327 bwd_lane_off: c.bwd_lane_off,
328 fwd_lane_count: c.fwd_lane_count,
329 bwd_lane_count: c.bwd_lane_count,
330 type_: c.type_,
331 speed_limit: c.speed_limit,
332 oneway: c.oneway,
333 }
334 .encode(&mut rec);
335 let mut pts = Vec::with_capacity(ids.len() * CHAIN_PT_BYTES as usize);
336 for id in ids {
337 let (lat_e7, lon_e7) = coords[*id as usize];
338 pts.extend_from_slice(&lat_e7.to_le_bytes());
339 pts.extend_from_slice(&lon_e7.to_le_bytes());
340 }
341 self.push_encoded(rec.to_vec(), pts, u64::from(c.pts_len))
342 }
343
344 /// Append chains already encoded by [`build`]'s workers: `hdr` holds whole
345 /// header records whose `pts_start` the caller has rebased onto
346 /// [`SpillWriter::points`], and `pts` the `points` coordinates they cover.
347 /// Same bytes as a per-chain encode would produce; the write itself happens
348 /// on the writer thread, in the order of these calls.
349 pub fn push_encoded(&mut self, hdr: Vec<u8>, pts: Vec<u8>, points: u64) -> Result<()> {
350 debug_assert_eq!(hdr.len() as u64 % CHAIN_REC_BYTES, 0);
351 debug_assert_eq!(pts.len() as u64, points * CHAIN_PT_BYTES);
352 let chains = hdr.len() as u64 / CHAIN_REC_BYTES;
353 let (htx, ptx) = self.tx.as_ref().expect("the spill writer is open");
354 if htx.send(hdr).is_err() || ptx.send(pts).is_err() {
355 // The writer thread stopped on an I/O error; `finish` reports it.
356 return self.join().and(Err(Error("the chain spill writer stopped".into())));
357 }
358 self.points += points;
359 self.chains += chains;
360 Ok(())
361 }
362
363 fn join(&mut self) -> Result<()> {
364 self.tx = None;
365 let Some((h, p)) = self.thread.take() else {
366 return Ok(());
367 };
368 let one = |t: std::thread::JoinHandle<std::io::Result<()>>| match t.join() {
369 Ok(r) => r.map_err(io_err),
370 Err(_) => Err(Error("the chain spill writer panicked".into())),
371 };
372 let (h, p) = (one(h), one(p));
373 h.and(p)
374 }
375
376 /// Flush both files and report how many chains were written.
377 pub fn finish(mut self) -> Result<u64> {
378 self.join()?;
379 Ok(self.chains)
380 }
381}
382
383impl Drop for SpillWriter {
384 fn drop(&mut self) {
385 let _ = self.join();
386 }
387}
388
389/// Random-access view over `chains.hdr`. See [`Spill::headers_mapped`].
390pub(crate) struct HeaderMap {
391 map: crate::mem::Mapped,
392}
393
394impl HeaderMap {
395 /// How many records the mapping holds, from its length alone — the same
396 /// width check [`Spill::chain_count`] applies to the file.
397 pub fn len(&self) -> Result<u64> {
398 let len = self.map.len() as u64;
399 if len % CHAIN_REC_BYTES != 0 {
400 return Err(Error(format!(
401 "chains.hdr is {len} bytes, not a multiple of {CHAIN_REC_BYTES}"
402 )));
403 }
404 Ok(len / CHAIN_REC_BYTES)
405 }
406
407 /// Decode chain `i`. Bounds-checked: a short mapping fails rather than
408 /// slicing past the end.
409 pub fn get(&self, i: u64) -> Result<ChainRec> {
410 let at = i.checked_mul(CHAIN_REC_BYTES).expect("chain index * stride fits u64");
411 let end = at + CHAIN_REC_BYTES;
412 if end > self.map.len() as u64 {
413 return Err(Error(format!("chains.hdr ends before chain {i}")));
414 }
415 let (at, end) = (at as usize, end as usize);
416 let mut rec = [0u8; CHAIN_REC_BYTES as usize];
417 rec.copy_from_slice(&self.map[at..end]);
418 Ok(ChainRec::decode(&rec))
419 }
420}
421
422/// Reads one chain's polyline out of `chains.pts`.
423pub(crate) struct PointReader {
424 map: crate::mem::Mapped,
425}
426
427/// The shared mapping behind a [`PointReader`]: pool workers read the same
428/// bytes through [`PointReader::read_shared`] with no lock and no cursor.
429pub(crate) fn points_map(reader: &PointReader) -> &crate::mem::Mapped {
430 &reader.map
431}
432
433impl PointReader {
434 /// Read over an explicit mapping: the shared-read form.
435 ///
436 /// `read` takes `&mut self` for the historical reason that the reader
437 /// used to hold a cursor; the mapping itself is never mutated, so pool
438 /// workers share one `&Mapped` and read through this instead. Same
439 /// slices, same errors, no lock.
440 pub fn read_shared(map: &crate::mem::Mapped, start: u64, len: u32, out: &mut Vec<geom::Pt>) -> Result<()> {
441 Self::read_from(map, start, len, out)
442 }
443
444 fn read_from(map: &crate::mem::Mapped, start: u64, len: u32, out: &mut Vec<geom::Pt>) -> Result<()> {
445 out.clear();
446 if len == 0 {
447 return Ok(());
448 }
449 let at = start as u128 * CHAIN_PT_BYTES as u128;
450 let bytes = len as u128 * CHAIN_PT_BYTES as u128;
451 if at + bytes > map.len() as u128 {
452 return Err(Error("chains.pts ended mid-chain".to_string()));
453 }
454 let (at, bytes) = (at as usize, bytes as usize);
455 out.extend(map[at..at + bytes].chunks_exact(CHAIN_PT_BYTES as usize).map(decode_pt));
456 Ok(())
457 }
458}
459
460fn io_err(e: std::io::Error) -> Error {
461 Error(e.to_string())
462}