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

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

spill_part6.rs391 lines · 15.4 KiBRaw
1/// One spill record -- header, pre-encoded geometry, properties -- written into `out`
2/// (cleared first). Pure, so the materialise drains build records on the pool and hand them to
3/// [`NormalizedWriter::push_record`] in order; `push_preencoded` is exactly this plus that.
4pub fn encode_normalized_record(
5 kind: GeomKind,
6 geom_bytes: &[u8],
7 props: &[(String, Value)],
8 out: &mut Vec<u8>,
9) -> Result<()> {
10 out.clear();
11 out.resize(NORM_HEADER_BYTES, 0);
12 out.extend_from_slice(geom_bytes);
13 let geom_len = count(geom_bytes.len())?;
14 encode_props(props, out)?;
15 let props_len = count(out.len() - NORM_HEADER_BYTES - geom_len as usize)?;
16 let rec_len = count(out.len())?;
17 out[0..4].copy_from_slice(&rec_len.to_le_bytes());
18 out[4..8].copy_from_slice(&geom_len.to_le_bytes());
19 out[8..12].copy_from_slice(&props_len.to_le_bytes());
20 out[12] = kind.tag();
21 Ok(())
22}
23
24/// One normalized feature.
25#[derive(Debug, Clone, PartialEq)]
26pub struct NormalizedFeature {
27 pub geometry: Geometry,
28 pub props: Vec<(String, Value)>,
29}
30
31/// Validate a normalized record's fixed header, returning its payload shape.
32///
33/// Shared by the sequential reader and the chunked one, so the two cannot diverge on
34/// what they accept: a record one of them rejects must not be one the other decodes.
35fn norm_header(head: &[u8; NORM_HEADER_BYTES]) -> Result<(usize, usize, GeomKind)> {
36 if head[13..NORM_HEADER_BYTES].iter().any(|v| *v != 0) {
37 return err("normalized record has a nonzero reserved tail");
38 }
39 let u32_at = |o: usize| u32::from_le_bytes(head[o..o + 4].try_into().expect("4 bytes"));
40 let rec_len = u32_at(0) as u64;
41 let geom_len = u32_at(4) as usize;
42 let props_len = u32_at(8) as usize;
43 let want = NORM_HEADER_BYTES as u64 + geom_len as u64 + props_len as u64;
44 if rec_len != want {
45 return err(format!(
46 "normalized record claims {rec_len} byte(s) but its header adds up to {want}"
47 ));
48 }
49 if want > MAX_RECORD_BYTES {
50 return err(format!(
51 "normalized record is {want} byte(s), which is corruption"
52 ));
53 }
54 Ok((geom_len, props_len, GeomKind::from_tag(head[12])?))
55}
56
57/// Decode a validated record's payload, `geom_len` bytes of geometry then properties.
58fn norm_payload(kind: GeomKind, geom_len: usize, payload: &[u8]) -> Result<NormalizedFeature> {
59 Ok(NormalizedFeature {
60 geometry: decode_geometry(kind, &payload[..geom_len])?,
61 props: decode_props(&payload[geom_len..])?,
62 })
63}
64
65/// Validate a spill file header, returning nothing: the magic, version and reserved tail are
66/// either exactly what the writer emits or the file is not a spill this reader knows.
67fn norm_file_header(head: &[u8; NORM_FILE_HEADER_BYTES]) -> Result<()> {
68 if &head[0..4] != NORM_MAGIC {
69 return err("not a normalized spill file (bad NZC1 magic)".to_string());
70 }
71 if head[4] != NORM_VERSION {
72 return err(format!(
73 "unsupported normalized spill version {} (this reader speaks v{NORM_VERSION})",
74 head[4],
75 ));
76 }
77 if head[5..NORM_FILE_HEADER_BYTES].iter().any(|v| *v != 0) {
78 return err("a normalized spill file has a nonzero reserved tail".to_string());
79 }
80 Ok(())
81}
82
83/// Inflate one frame: `u32 compressed_len` + raw DEFLATE of one chunk's records.
84///
85/// The length is checked against the chunk span first (a frame longer than its span is
86/// corruption, not a large chunk), then the inflate itself is the check: DEFLATE framing errors
87/// on truncated or bit-rotted input rather than yielding partial records. Record validation
88/// (`norm_header` per record) still runs on the inflated bytes, so a corrupt frame that
89/// happens to inflate is refused as the desync it is.
90fn inflate_frame(chunk: usize, path: &std::path::Path, frame: &[u8]) -> Result<Vec<u8>> {
91 if frame.len() < 4 {
92 return err(format!(
93 "normalized chunk {chunk} of {} ends {} byte(s) into its 4-byte frame header",
94 path.display(),
95 frame.len(),
96 ));
97 }
98 let want = u32::from_le_bytes(frame[0..4].try_into().expect("4 bytes")) as u64;
99 if want > MAX_FRAME_BYTES {
100 return err(format!(
101 "normalized chunk {chunk} of {} claims a {want}-byte frame, which is corruption",
102 path.display(),
103 ));
104 }
105 if want as usize != frame.len() - 4 {
106 return err(format!(
107 "normalized chunk {chunk} of {} holds {} frame byte(s) but claims {want}",
108 path.display(),
109 frame.len() - 4,
110 ));
111 }
112 miniz_oxide::inflate::decompress_to_vec(&frame[4..]).map_err(|e| {
113 Error(format!(
114 "normalized chunk {chunk} of {} does not inflate: {e:?}",
115 path.display(),
116 ))
117 })
118}
119
120/// Decode every record in one inflated chunk into `out`, which is cleared first.
121///
122/// Split from [`NormalizedChunks::read_into`] so the sequential reader shares the exact same
123/// validation: a record one of them rejects must not be one the other decodes.
124fn decode_chunk_records(
125 chunk: usize,
126 path: &std::path::Path,
127 raw: &[u8],
128 out: &mut Vec<NormalizedFeature>,
129) -> Result<()> {
130 out.clear();
131 let mut at = 0usize;
132 while at < raw.len() {
133 if raw.len() - at < NORM_HEADER_BYTES {
134 return err(format!(
135 "normalized chunk {chunk} of {} ends {} byte(s) into a \
136 {NORM_HEADER_BYTES}-byte record header",
137 path.display(),
138 raw.len() - at
139 ));
140 }
141 let head: &[u8; NORM_HEADER_BYTES] = raw[at..at + NORM_HEADER_BYTES]
142 .try_into()
143 .expect("a header's worth of bytes");
144 let (geom_len, props_len, kind) = norm_header(head)?;
145 let body = at + NORM_HEADER_BYTES;
146 let rec_end = body + geom_len + props_len;
147 if rec_end > raw.len() {
148 return err(format!(
149 "normalized chunk {chunk} of {} holds a record running {} byte(s) past its end",
150 path.display(),
151 rec_end - raw.len()
152 ));
153 }
154 out.push(norm_payload(kind, geom_len, &raw[body..rec_end])?);
155 at = rec_end;
156 }
157 Ok(())
158}
159
160/// Sequential reader over the normalized spill, rewindable because every zoom
161/// re-reads it from the front. File-backed ([`open`](Self::open)) or anonymous
162/// ([`open_anon`](Self::open_anon)): the record format is a sequential stream
163/// either way, so the reader is a cursor over bytes — a file cursor or a store
164/// offset.
165pub struct NormalizedReader {
166 src: ReaderIn,
167 path: PathBuf,
168 /// The current frame's inflated records. Refilled from the next frame when exhausted; the
169 /// reader yields records across the refill boundary without the caller seeing frames at all.
170 frame: Vec<u8>,
171 /// Bytes of `frame` already yielded.
172 frame_used: usize,
173 /// Frames exhausted so far, for error messages that name the chunk.
174 frames_seen: usize,
175 /// Scratch for one compressed frame, reused so a refill allocates nothing but the inflate.
176 raw_frame: Vec<u8>,
177}
178
179/// Where a [`NormalizedReader`] reads from.
180///
181/// Both variants are frame-aware now: the file cursor sits at the next unread frame (past the
182/// 8-byte file header), and the anon offset likewise. `rewind` returns both to the first frame.
183enum ReaderIn {
184 File(BufReader<File>),
185 Anon {
186 store: std::sync::Arc<crate::anon::AnonStore>,
187 at: u64,
188 },
189}
190
191impl NormalizedReader {
192 pub fn open(path: impl Into<PathBuf>) -> Result<NormalizedReader> {
193 let path = path.into();
194 let f = File::open(&path)
195 .map_err(|e| Error(format!("cannot read {}: {e}", path.display())))?;
196 let mut reader = NormalizedReader {
197 src: ReaderIn::File(BufReader::with_capacity(1 << 20, f)),
198 path,
199 frame: Vec::new(),
200 frame_used: 0,
201 frames_seen: 0,
202 raw_frame: Vec::new(),
203 };
204 reader.read_file_header()?;
205 Ok(reader)
206 }
207
208 /// Anonymous twin of [`open`](Self::open): reads the sealed store from
209 /// [`NormalizedWriter::finish_anon`], shared by refcount.
210 pub fn open_anon(
211 path: impl Into<PathBuf>,
212 store: std::sync::Arc<crate::anon::AnonStore>,
213 ) -> Result<NormalizedReader> {
214 let mut reader = NormalizedReader {
215 src: ReaderIn::Anon { store, at: NORM_FILE_HEADER_BYTES as u64 },
216 path: path.into(),
217 frame: Vec::new(),
218 frame_used: 0,
219 frames_seen: 0,
220 raw_frame: Vec::new(),
221 };
222 reader.read_file_header()?;
223 Ok(reader)
224 }
225
226 /// Parse and validate the 8-byte file header, positioning the cursor at the first frame.
227 ///
228 /// Read through the cursor itself (not a separate open) so the file and anon paths share
229 /// the framing: on the file path this consumes the header bytes; on anon it validates the
230 /// store's own first 8 bytes while `at` already skips past them.
231 fn read_file_header(&mut self) -> Result<()> {
232 match &mut self.src {
233 ReaderIn::File(f) => {
234 let mut head = [0u8; NORM_FILE_HEADER_BYTES];
235 use std::io::Read;
236 f.read_exact(&mut head).map_err(|e| {
237 Error(format!("reading {}'s spill header: {e}", self.path.display()))
238 })?;
239 norm_file_header(&head)?;
240 }
241 ReaderIn::Anon { store, .. } => {
242 let mut head = [0u8; NORM_FILE_HEADER_BYTES];
243 store.read_at(0, &mut head).map_err(|e| {
244 Error(format!("reading {}'s spill header: {e}", self.path.display()))
245 })?;
246 norm_file_header(&head)?;
247 }
248 }
249 Ok(())
250 }
251
252 pub fn rewind(&mut self) -> Result<()> {
253 match &mut self.src {
254 ReaderIn::File(f) => {
255 use std::io::Seek;
256 // Past the file header: frame 0 starts at byte 8, not byte 0.
257 f.seek(std::io::SeekFrom::Start(NORM_FILE_HEADER_BYTES as u64))
258 .map_err(|e| Error(format!("rewinding {}: {e}", self.path.display())))?;
259 }
260 ReaderIn::Anon { at, .. } => *at = NORM_FILE_HEADER_BYTES as u64,
261 }
262 self.frame.clear();
263 self.frame_used = 0;
264 self.frames_seen = 0;
265 Ok(())
266 }
267
268 /// Fill `buf` with exactly `len` bytes from the cursor, or `Ok(false)` at a
269 /// clean frame boundary (start of read, or exactly past the last frame's bytes).
270 ///
271 /// A short read anywhere else is corruption, and the callers treat it as such: frames state
272 /// their own length, so a file that ends mid-frame is truncated, not finished.
273 fn read_full(&mut self, buf: &mut [u8]) -> Result<bool> {
274 match &mut self.src {
275 ReaderIn::File(f) => {
276 let mut read = 0usize;
277 while read < buf.len() {
278 let n = f
279 .read(&mut buf[read..])
280 .map_err(|e| Error(format!("reading {}: {e}", self.path.display())))?;
281 if n == 0 {
282 break;
283 }
284 read += n;
285 }
286 // `Ok(false)` only at a frame boundary: mid-frame EOF is reported by the frame
287 // length check in `refill`, not here.
288 Ok(read > 0)
289 }
290 ReaderIn::Anon { store, at } => {
291 if *at >= store.len() {
292 return Ok(false);
293 }
294 let remaining = store.len() - *at;
295 let take = (buf.len() as u64).min(remaining) as usize;
296 store.read_at(*at, &mut buf[..take]).map_err(|e| {
297 Error(format!("reading {}: {e}", self.path.display()))
298 })?;
299 *at += take as u64;
300 Ok(true)
301 }
302 }
303 }
304
305 /// The next frame's inflated records, replacing `frame`.
306 ///
307 /// Reads the frame's `u32` length, then exactly that many bytes -- a short read there is a
308 /// truncated file, never a legitimate end -- inflates, and validates the inflate before any
309 /// record is yielded. `Ok(false)` only when the cursor sits exactly at end of input.
310 fn refill(&mut self) -> Result<bool> {
311 let mut len_buf = [0u8; 4];
312 if !self.read_full(&mut len_buf)? {
313 return Ok(false);
314 }
315 let want = u32::from_le_bytes(len_buf) as usize;
316 if want as u64 > MAX_FRAME_BYTES {
317 return err(format!(
318 "normalized frame {} of {} claims {} byte(s), which is corruption",
319 self.frames_seen,
320 self.path.display(),
321 want,
322 ));
323 }
324 self.raw_frame.clear();
325 self.raw_frame.resize(want, 0);
326 // Exact-length by construction (the length was just read), so a short payload is
327 // corruption, not EOF. `read_full` may return short mid-frame on the file path;
328 // loop until the frame is whole or the file ends.
329 let mut read = 0usize;
330 while read < want {
331 let mut chunk = vec![0u8; want - read];
332 if !self.read_full(&mut chunk)? {
333 return err(format!(
334 "{} ends {} byte(s) into frame {}",
335 self.path.display(),
336 read,
337 self.frames_seen,
338 ));
339 }
340 // `read_full` on the file path may return short; on anon it fills exactly.
341 let n = chunk.len();
342 self.raw_frame[read..read + n].copy_from_slice(&chunk);
343 read += n;
344 if n == 0 {
345 break;
346 }
347 }
348 let mut framed = Vec::with_capacity(4 + want);
349 framed.extend_from_slice(&len_buf);
350 framed.extend_from_slice(&self.raw_frame);
351 self.frame = inflate_frame(self.frames_seen, &self.path, &framed)?;
352 self.frame_used = 0;
353 self.frames_seen += 1;
354 Ok(true)
355 }
356
357 #[allow(clippy::should_implement_trait)]
358 pub fn next(&mut self) -> Result<Option<NormalizedFeature>> {
359 loop {
360 if self.frame_used < self.frame.len() {
361 let head: &[u8; NORM_HEADER_BYTES] = self.frame
362 [self.frame_used..self.frame_used + NORM_HEADER_BYTES]
363 .try_into()
364 .map_err(|_| {
365 Error(format!(
366 "{} ends {} byte(s) into a {NORM_HEADER_BYTES}-byte record header",
367 self.path.display(),
368 self.frame.len() - self.frame_used,
369 ))
370 })?;
371 let (geom_len, props_len, kind) = norm_header(head)?;
372 let body = self.frame_used + NORM_HEADER_BYTES;
373 let rec_end = body + geom_len + props_len;
374 if rec_end > self.frame.len() {
375 return err(format!(
376 "{} holds a record running {} byte(s) past its frame",
377 self.path.display(),
378 rec_end - self.frame.len(),
379 ));
380 }
381 let feature = norm_payload(kind, geom_len, &self.frame[body..rec_end])?;
382 self.frame_used = rec_end;
383 return Ok(Some(feature));
384 }
385 if !self.refill()? {
386 return Ok(None);
387 }
388 }
389 }
390}
391