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

Modern-Apps.git / scripts / maps / tile_build / src / spill_part7.rs

spill_part7.rs198 lines · 7.8 KiBRaw
1/// Chunked reader over the normalized file, for reading it across a thread pool.
2///
3/// The sequential [`NormalizedReader`] is one cursor, so the decode of every feature —
4/// which allocates a `Geometry` and a `Vec` of properties, six times over a z11..z16
5/// build — happens on whichever single thread owns it, while the pool waits. This reads
6/// a whole chunk's byte range positionally instead, so the decode happens on the worker
7/// that will bucket those features.
8///
9/// Takes `&self` throughout: see [`crate::pmtiles::read_exact_at`]. One handle serves
10/// every thread.
11///
12/// Anonymous twin: [`open_anon`](Self::open_anon) serves the same chunks from an
13/// [`crate::anon::AnonStore`] instead of a file. Same offsets, same bytes.
14pub struct NormalizedChunks {
15 file: Option<File>,
16 anon: Option<std::sync::Arc<crate::anon::AnonStore>>,
17 path: PathBuf,
18 /// Chunk boundaries, `chunk_count() + 1` of them. See [`NormalizedSummary::chunks`].
19 chunks: Vec<u64>,
20}
21
22impl NormalizedChunks {
23 /// `chunks` is [`NormalizedSummary::chunks`] for this file.
24 pub fn open(path: impl Into<PathBuf>, chunks: Vec<u64>) -> Result<NormalizedChunks> {
25 let path = path.into();
26 let file = File::open(&path)
27 .map_err(|e| Error(format!("cannot read {}: {e}", path.display())))?;
28 Ok(NormalizedChunks { file: Some(file), anon: None, path, chunks })
29 }
30
31 /// Anonymous twin of [`open`](Self::open): `store` is the sealed store from
32 /// [`NormalizedWriter::finish_anon`], shared by refcount — the store
33 /// outlives every reader, so this is a refcount bump, never a copy.
34 /// `path` names nothing — it only rides along for error messages.
35 pub fn open_anon(
36 path: impl Into<PathBuf>,
37 chunks: Vec<u64>,
38 store: std::sync::Arc<crate::anon::AnonStore>,
39 ) -> Result<NormalizedChunks> {
40 Ok(NormalizedChunks {
41 file: None,
42 anon: Some(store),
43 path: path.into(),
44 chunks,
45 })
46 }
47
48 pub fn chunk_count(&self) -> usize {
49 self.chunks.len().saturating_sub(1)
50 }
51
52 /// Whether this reader serves from anonymous memory rather than a file.
53 pub fn is_anon(&self) -> bool {
54 self.anon.is_some()
55 }
56
57 /// Decode chunk `i` into `out`, which is cleared first.
58 ///
59 /// `scratch` is the caller's per-worker byte buffer, reused across chunks so a pass
60 /// allocates once per thread rather than once per chunk.
61 ///
62 /// The first feature of chunk `i` is input feature `i * NORM_CHUNK_FEATURES`, by
63 /// construction of the index — which is what lets the caller reproduce the exact
64 /// `seq` the sequential path assigns.
65 ///
66 /// The chunk span covers one compressed frame: it is read whole, inflated, and decoded
67 /// with the same [`decode_chunk_records`] the sequential reader uses, so the two paths
68 /// cannot diverge on what they accept.
69 /// [`read_into`](Self::read_into), keeping only the records whose properties pass `keep` --
70 /// and decoding the geometry of those alone. For whole-spill scans that want a sliver of it
71 /// (the region fallback keeps boundary shapes and place labels out of ~1.35 B planet
72 /// features): the properties sit after the geometry in each record and are a few bytes, the
73 /// geometry is most of the decode. Kept records come back exactly as `read_into` yields them.
74 pub fn read_into_where(
75 &self,
76 i: usize,
77 scratch: &mut Vec<u8>,
78 out: &mut Vec<NormalizedFeature>,
79 keep: &KeepProps,
80 ) -> Result<()> {
81 out.clear();
82 let mut all = Vec::new();
83 // Inflate through `read_into`'s own path, then walk the raw records here.
84 let (Some(&start), Some(&end)) = (self.chunks.get(i), self.chunks.get(i + 1)) else {
85 return self.read_into(i, scratch, &mut all);
86 };
87 if end < start {
88 return self.read_into(i, scratch, &mut all);
89 }
90 scratch.clear();
91 scratch.resize((end - start) as usize, 0);
92 match (&self.file, &self.anon) {
93 (Some(f), None) => crate::pmtiles::read_exact_at(f, scratch, start).map_err(|e| {
94 Error(format!("reading normalized chunk {i} of {}: {e}", self.path.display()))
95 })?,
96 (None, Some(a)) => a.read_at(start, scratch).map_err(|e| {
97 Error(format!("reading normalized chunk {i} of {}: {e}", self.path.display()))
98 })?,
99 _ => return err("a normalized chunk reader has no backend".to_string()),
100 }
101 let raw = inflate_frame(i, &self.path, scratch)?;
102 let mut at = 0usize;
103 while at < raw.len() {
104 if raw.len() - at < NORM_HEADER_BYTES {
105 return err(format!(
106 "normalized chunk {i} of {} ends inside a record header",
107 self.path.display()
108 ));
109 }
110 let head: &[u8; NORM_HEADER_BYTES] =
111 raw[at..at + NORM_HEADER_BYTES].try_into().expect("a header's worth of bytes");
112 let (geom_len, props_len, kind) = norm_header(head)?;
113 let body = at + NORM_HEADER_BYTES;
114 let rec_end = body + geom_len + props_len;
115 if rec_end > raw.len() {
116 return err(format!(
117 "normalized chunk {i} of {} holds a record running past its end",
118 self.path.display()
119 ));
120 }
121 let props = decode_props(&raw[body + geom_len..rec_end])?;
122 if keep(&props) {
123 out.push(NormalizedFeature {
124 geometry: decode_geometry(kind, &raw[body..body + geom_len])?,
125 props,
126 });
127 }
128 at = rec_end;
129 }
130 Ok(())
131 }
132
133 pub fn read_into(
134 &self,
135 i: usize,
136 scratch: &mut Vec<u8>,
137 out: &mut Vec<NormalizedFeature>,
138 ) -> Result<()> {
139 out.clear();
140 let (Some(&start), Some(&end)) = (self.chunks.get(i), self.chunks.get(i + 1)) else {
141 return err(format!(
142 "normalized chunk {i} is past the {} in {}",
143 self.chunk_count(),
144 self.path.display()
145 ));
146 };
147 if end < start {
148 return err(format!(
149 "normalized chunk {i} of {} ends before it starts",
150 self.path.display()
151 ));
152 }
153 let len = (end - start) as usize;
154 scratch.clear();
155 scratch.resize(len, 0);
156 match (&self.file, &self.anon) {
157 (Some(f), None) => {
158 crate::pmtiles::read_exact_at(f, scratch, start).map_err(|e| {
159 Error(format!(
160 "reading normalized chunk {i} of {}: {e}",
161 self.path.display()
162 ))
163 })?;
164 }
165 (None, Some(a)) => a.read_at(start, scratch).map_err(|e| {
166 Error(format!(
167 "reading normalized chunk {i} of {}: {e}",
168 self.path.display()
169 ))
170 })?,
171 _ => return err("a normalized chunk reader has no backend".to_string()),
172 }
173 let raw = inflate_frame(i, &self.path, scratch)?;
174 decode_chunk_records(i, &self.path, &raw, out)
175 }
176}
177
178/// The normalized file's lifetime, so a run that dies mid-planet cannot strand it.
179///
180/// A guard rather than `impl Drop` on the reader, because the reader is handed around
181/// and the file has to outlive every one of them.
182pub struct NormalizedFile(PathBuf);
183
184impl NormalizedFile {
185 pub fn new(path: impl Into<PathBuf>) -> NormalizedFile {
186 NormalizedFile(path.into())
187 }
188
189 pub fn path(&self) -> &Path {
190 &self.0
191 }
192}
193
194impl Drop for NormalizedFile {
195 fn drop(&mut self) {
196 let _ = std::fs::remove_file(&self.0);
197 }
198}