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

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

spill_part2.rs976 lines · 39.0 KiBRaw
1/// Sequential reader over one bucket.
2///
3/// Errors if a record's `tile_id` falls outside the bucket's range, and at the end if
4/// the record or byte count disagrees with what the writer tallied. The order the
5/// encode pass depends on is asserted directly by its own test;
6/// [`crate::pmtiles::StreamBuilder::add_tile_raw`] refusing a non-ascending id is the
7/// second line of defence, not the first.
8pub struct BucketReader {
9 src: BufReader<File>,
10 path: PathBuf,
11 lo: u64,
12 hi: u64,
13 expect_records: u64,
14 expect_bytes: u64,
15 seen_records: u64,
16 seen_bytes: u64,
17 done: bool,
18 buf: Vec<u8>,
19}
20
21impl BucketReader {
22 #[allow(clippy::should_implement_trait)]
23 pub fn next(&mut self) -> Result<Option<SpillRecord>> {
24 if self.done {
25 return Ok(None);
26 }
27 let mut head = [0u8; REC_HEADER_BYTES];
28 let mut read = 0usize;
29 while read < REC_HEADER_BYTES {
30 let n = self
31 .src
32 .read(&mut head[read..])
33 .map_err(|e| Error(format!("reading {}: {e}", self.path.display())))?;
34 if n == 0 {
35 break;
36 }
37 read += n;
38 }
39 if read == 0 {
40 self.done = true;
41 self.check_totals()?;
42 return Ok(None);
43 }
44 if read < REC_HEADER_BYTES {
45 // A partial header is a truncated file, never a legitimate end.
46 return err(format!(
47 "{} ends {read} byte(s) into a {REC_HEADER_BYTES}-byte record header",
48 self.path.display()
49 ));
50 }
51 let h = RecHeader::parse(&head)?;
52 if h.tile_id < self.lo || h.tile_id >= self.hi {
53 return err(format!(
54 "{} holds tile id {} but covers {}..{}",
55 self.path.display(),
56 h.tile_id,
57 self.lo,
58 self.hi
59 ));
60 }
61 let payload = h.geom_len as usize + h.props_len as usize;
62 self.buf.clear();
63 self.buf.resize(payload, 0);
64 self.src
65 .read_exact(&mut self.buf)
66 .map_err(|e| Error(format!("reading {}'s record payload: {e}", self.path.display())))?;
67 let geom = decode_int_geometry(h.kind, &self.buf[..h.geom_len as usize])?;
68 let props = decode_props(&self.buf[h.geom_len as usize..])?;
69
70 self.seen_records += 1;
71 self.seen_bytes += h.rec_len as u64;
72 Ok(Some(SpillRecord {
73 tile_id: h.tile_id,
74 seq: h.seq,
75 extent: h.extent,
76 geom,
77 props,
78 }))
79 }
80
81 fn check_totals(&self) -> Result<()> {
82 if self.seen_records != self.expect_records || self.seen_bytes != self.expect_bytes {
83 return err(format!(
84 "{} read back {} record(s)/{} byte(s) but the writer tallied {}/{}",
85 self.path.display(),
86 self.seen_records,
87 self.seen_bytes,
88 self.expect_records,
89 self.expect_bytes
90 ));
91 }
92 Ok(())
93 }
94}
95
96// --- the normalized file -----------------------------------------------------
97
98/// What one pass over the geojsonseq learned, beyond the records themselves.
99///
100/// The streaming producer's header comes from here rather than from a second pass:
101/// [`crate::pmtiles::StreamBuilder`]'s bounds fields are serialised last, so they can be
102/// a streaming fold assigned any time before `finish`.
103#[derive(Debug, Clone, Default, PartialEq)]
104pub struct NormalizedSummary {
105 pub count: u64,
106 pub bounds: Option<Rect>,
107 /// The FIRST feature's kind, which is the rule `dominant_geom_type` already applies:
108 /// a layer is styled as one thing, so a mixed layer is a mistake upstream and should
109 /// show as wrong rendering rather than hide as a silently split layer.
110 pub geom_kind: Option<GeomKind>,
111 pub skipped: u64,
112 /// Byte offset of every `NORM_CHUNK_FEATURES`-th record, plus a final sentinel
113 /// holding the file's total length — so chunk `i` spans `chunks[i]..chunks[i + 1]`
114 /// and there are `chunks.len() - 1` of them.
115 ///
116 /// Built by the same single pass that writes the records, because the writer is the
117 /// only place that already knows each record's length. Empty for an empty file.
118 pub chunks: Vec<u64>,
119}
120
121impl NormalizedSummary {
122 /// How many chunks the file has, for [`NormalizedChunks::read_into`].
123 pub fn chunk_count(&self) -> usize {
124 self.chunks.len().saturating_sub(1)
125 }
126}
127
128/// Writes the geojsonseq once into a compact binary every zoom can re-read.
129///
130/// ```text
131/// 0..4 u32 rec_len whole record, this field included
132/// 4..8 u32 geom_len
133/// 8..12 u32 props_len
134/// 12..13 u8 geom_kind
135/// 13..16 reserved, zero
136/// 16.. geometry (lon/lat e7 `i32` pairs), then properties
137/// ```
138///
139/// Eight bytes a vertex rather than sixteen: see [`encode_geometry`] for why that is
140/// lossless for OSM coordinates and what it costs a coastline.
141///
142/// # Compressed frames (planet disk peak)
143///
144/// Records are grouped into frames of [`NORM_CHUNK_FEATURES`] features and each frame is
145/// stored as raw DEFLATE. The file layout is:
146///
147/// ```text
148/// 0..4 magic `NZC1`
149/// 4..5 version 1
150/// 5..8 reserved, zero
151/// 8.. frames, back to back:
152/// u32 compressed_len (this field excluded)
153/// raw DEFLATE stream of one chunk's records
154/// ```
155///
156/// Why this shape: the 259 GB planet feature spill is what fills the disk beside the z14
157/// tile chunks (~101 GB) and the bodies scratch, and coordinates compress ~3x (sorted e7
158/// varints, delta runs). Per-chunk frames keep the [`NormalizedSummary::chunks`] index valid
159/// verbatim -- chunk `i` still spans `chunks[i]..chunks[i+1]`, now over compressed bytes --
160/// so positional reads, the `chunk_mins` zoom filter, the prefetch lanes and the anon backend
161/// all work unchanged, and inflate-then-decode yields byte-identical records. A whole-file
162/// stream would kill positional reads; per-record frames would pay inflate setup 1.9 B x 15
163/// times for worse ratio.
164///
165/// Spill files are build-temp (removed on success, never shipped), so there is no cross-version
166/// compat to keep: a reader that does not know `NZC1` refuses the magic rather than decoding
167/// frames as records.
168///
169/// Backed by a file ([`create`](Self::create)) or by anonymous pagefile memory
170/// ([`create_anon`](Self::create_anon)),
171/// which stages the same bytes with no directory entry. Same records, same
172/// offsets, same output bytes — the -Verify hash check proves it.
173/// Where a [`NormalizedWriter`] stages its bytes: a file, or anonymous memory.
174enum WriterSink {
175 File(BufWriter<File>),
176 Anon(crate::anon::AnonStore),
177}
178
179/// File magic for the compressed normalized spill. A reader that does not know it refuses
180/// the file rather than decoding frames as records.
181const NORM_MAGIC: &[u8; 4] = b"NZC1";
182/// Frame format version. Bumped if the framing ever changes; spill files are build-temp so no
183/// migration path is needed, only a refusal.
184const NORM_VERSION: u8 = 1;
185/// Bytes of file header before the first frame. The chunk index's first offset equals this.
186const NORM_FILE_HEADER_BYTES: usize = 8;
187/// Largest single frame accepted, compressed or not. A 64-feature chunk of plausible records is
188/// kilobytes; a gigabyte frame is corruption, not a dense chunk.
189const MAX_FRAME_BYTES: u64 = 1 << 30;
190
191pub struct NormalizedWriter {
192 out: WriterSink,
193 path: PathBuf,
194 summary: NormalizedSummary,
195 rec: Vec<u8>,
196 /// The current chunk's raw records, accumulating until [`NORM_CHUNK_FEATURES`] are held.
197 /// Buffered rather than written per record because a frame is compressed as a unit: flushing
198 /// per record would be per-record frames (worse ratio, 1.9 B x 15 inflates). One chunk is
199 /// ~9 KB raw, noise next to every other peak in the build.
200 pending: Vec<u8>,
201 /// Records in `pending`. Counted rather than derived because records are variable-length.
202 pending_count: u64,
203 /// Compressed scratch, reused across frames so a chunk seal allocates nothing.
204 sealed: Vec<u8>,
205 /// Bytes written so far, which is the next frame's offset. Tracks *compressed* bytes: the
206 /// chunk index addresses frames, not records.
207 at: u64,
208}
209
210/// DEFLATE level for spill frames. See [`NormalizedWriter::seal_frame`].
211const SPILL_DEFLATE_LEVEL: u8 = 1;
212
213impl NormalizedWriter {
214 pub fn create(path: impl Into<PathBuf>) -> Result<NormalizedWriter> {
215 let path = path.into();
216 if let Some(dir) = path.parent() {
217 if !dir.as_os_str().is_empty() {
218 std::fs::create_dir_all(dir)
219 .map_err(|e| Error(format!("cannot create {}: {e}", dir.display())))?;
220 }
221 }
222 let f = File::create(&path)
223 .map_err(|e| Error(format!("cannot create {}: {e}", path.display())))?;
224 let mut w = NormalizedWriter {
225 out: WriterSink::File(BufWriter::with_capacity(1 << 20, f)),
226 path,
227 summary: NormalizedSummary::default(),
228 rec: Vec::new(),
229 pending: Vec::new(),
230 pending_count: 0,
231 sealed: Vec::new(),
232 // The first frame starts past the file header; the chunk index's first offset
233 // records exactly this, so readers never special-case it.
234 at: NORM_FILE_HEADER_BYTES as u64,
235 };
236 w.write_file_header()?;
237 Ok(w)
238 }
239
240 /// Anonymous twin of [`create`](Self::create): same records and offsets,
241 /// staged in pagefile-backed memory with no file. `path` names nothing on
242 /// disk — it only rides along for error messages. Pair with
243 /// [`NormalizedChunks::open_anon`] on the way back.
244 pub fn create_anon(path: impl Into<PathBuf>) -> Result<NormalizedWriter> {
245 let mut w = NormalizedWriter {
246 out: WriterSink::Anon(crate::anon::AnonStore::new()),
247 path: path.into(),
248 summary: NormalizedSummary::default(),
249 rec: Vec::new(),
250 pending: Vec::new(),
251 pending_count: 0,
252 sealed: Vec::new(),
253 at: NORM_FILE_HEADER_BYTES as u64,
254 };
255 w.write_file_header()?;
256 Ok(w)
257 }
258
259 /// The 8-byte file header: magic, version, reserved zero. Written once, before the first
260 /// frame, on both backends -- so anon and file bytes are identical and every reader parses
261 /// one layout.
262 fn write_file_header(&mut self) -> Result<()> {
263 let mut head = [0u8; NORM_FILE_HEADER_BYTES];
264 head[0..4].copy_from_slice(NORM_MAGIC);
265 head[4] = NORM_VERSION;
266 match &mut self.out {
267 WriterSink::File(f) => f
268 .write_all(&head)
269 .map_err(|e| Error(format!("writing {}: {e}", self.path.display())))?,
270 WriterSink::Anon(a) => {
271 a.push(&head)?;
272 }
273 }
274 Ok(())
275 }
276
277 /// A line the caller could not use. Counted here so the summary is the one place
278 /// the whole pass is described.
279 pub fn skip(&mut self) {
280 self.summary.skipped += 1;
281 }
282
283 pub fn push(&mut self, geometry: &Geometry, props: &[(String, Value)]) -> Result<()> {
284 self.rec.clear();
285 self.rec.resize(NORM_HEADER_BYTES, 0);
286 encode_geometry(geometry, &mut self.rec)?;
287 let geom_len = count(self.rec.len() - NORM_HEADER_BYTES)?;
288 encode_props(props, &mut self.rec)?;
289 let props_len = count(self.rec.len() - NORM_HEADER_BYTES - geom_len as usize)?;
290 let rec_len = count(self.rec.len())?;
291 self.rec[0..4].copy_from_slice(&rec_len.to_le_bytes());
292 self.rec[4..8].copy_from_slice(&geom_len.to_le_bytes());
293 self.rec[8..12].copy_from_slice(&props_len.to_le_bytes());
294 self.rec[12] = GeomKind::of(geometry).tag();
295 // Buffered, not written: a frame is one chunk's records compressed as a unit. The index
296 // entry below still fires on the same 64-feature boundary, so entry `i` still describes
297 // chunk `i` -- only the bytes behind the offset are frames now.
298 self.pending.extend_from_slice(&self.rec);
299 self.pending_count += 1;
300 // Index before sealing, so the offset recorded is this frame's own start.
301 if self.summary.count.is_multiple_of(NORM_CHUNK_FEATURES) {
302 self.summary.chunks.push(self.at);
303 }
304 if self.pending_count >= NORM_CHUNK_FEATURES {
305 self.seal_frame()?;
306 }
307
308 if self.summary.geom_kind.is_none() {
309 self.summary.geom_kind = Some(GeomKind::of(geometry));
310 }
311 self.summary.bounds = crate::pyramid::fold_bounds(self.summary.bounds, geometry);
312 self.summary.count += 1;
313 Ok(())
314 }
315
316 /// [`push`](Self::push) for a geometry encoded off-thread: the same record
317 /// layout with the geometry bytes supplied instead of encoded here.
318 ///
319 /// The materialise drains resolve + encode + region-test each batch on the
320 /// pool and append the records in order here, so the serial thread does no
321 /// vertex walk. Byte-identical to `push`: `geom_bytes` must be what
322 /// [`encode_geometry`](crate::spill::encode_geometry) produced for the same
323 /// geometry, `kind` its [`GeomKind`], `bounds` its
324 /// [`bounds`](crate::geom::bounds) — all pure functions, so computing them
325 /// on the pool changes no byte. Order, chunk index, sealing and the bounds
326 /// fold are untouched: they happen here, serially, exactly as in `push`.
327 pub fn push_preencoded(
328 &mut self,
329 kind: GeomKind,
330 geom_bytes: &[u8],
331 bounds: Option<crate::geom::Rect>,
332 props: &[(String, Value)],
333 ) -> Result<()> {
334 self.rec.clear();
335 self.rec.resize(NORM_HEADER_BYTES, 0);
336 self.rec.extend_from_slice(geom_bytes);
337 let geom_len = count(geom_bytes.len())?;
338 encode_props(props, &mut self.rec)?;
339 let props_len = count(self.rec.len() - NORM_HEADER_BYTES - geom_len as usize)?;
340 let rec_len = count(self.rec.len())?;
341 self.rec[0..4].copy_from_slice(&rec_len.to_le_bytes());
342 self.rec[4..8].copy_from_slice(&geom_len.to_le_bytes());
343 self.rec[8..12].copy_from_slice(&props_len.to_le_bytes());
344 self.rec[12] = kind.tag();
345 self.pending.extend_from_slice(&self.rec);
346 self.pending_count += 1;
347 if self.summary.count.is_multiple_of(NORM_CHUNK_FEATURES) {
348 self.summary.chunks.push(self.at);
349 }
350 if self.pending_count >= NORM_CHUNK_FEATURES {
351 self.seal_frame()?;
352 }
353
354 if self.summary.geom_kind.is_none() {
355 self.summary.geom_kind = Some(kind);
356 }
357 self.summary.bounds = match (self.summary.bounds, bounds) {
358 (None, b) => b,
359 (a, None) => a,
360 (Some(a), Some(b)) => Some(crate::geom::Rect {
361 min_x: a.min_x.min(b.min_x),
362 min_y: a.min_y.min(b.min_y),
363 max_x: a.max_x.max(b.max_x),
364 max_y: a.max_y.max(b.max_y),
365 }),
366 };
367 self.summary.count += 1;
368 Ok(())
369 }
370
371 /// Compress the buffered chunk into one frame and stage it.
372 ///
373 /// Level 1, not 6: the write happens once (stage A, serial sink) while the reads happen
374 /// fifteen times (parallel prefetch lanes), which is what argued for 6 — ratio over deflate
375 /// speed, with level-independent inflate. Measured on California, that argument was wrong:
376 /// level 6 spends ~27 s of a 61 s `materialise-ways` serial drain in DEFLATE while level 1
377 /// spends ~0 s for ~5% more scratch bytes (scratch, deleted on success; the budget gate
378 /// sizes commit with headroom). The drain is serial and order-critical, so its wall is
379 /// Amdahl time; the spill size is not.
380 ///
381 /// The level is a constant, not a knob: the frame header carries no level mark because
382 /// inflate is level-independent, so the choice changes only scratch bytes, never the
383 /// archive — and an operator knob here would trade build minutes for scratch bytes with
384 /// no content effect either way. Re-measure (drain wall + spill GB) before touching it.
385 fn seal_frame(&mut self) -> Result<()> {
386 if self.pending.is_empty() {
387 return Ok(());
388 }
389 self.sealed.clear();
390 self.sealed = miniz_oxide::deflate::compress_to_vec(&self.pending, SPILL_DEFLATE_LEVEL);
391 let frame_len = u32::try_from(self.sealed.len())
392 .map_err(|_| Error("a spill frame is larger than 4 GiB".to_string()))?;
393 let mut staged = Vec::with_capacity(4 + self.sealed.len());
394 staged.extend_from_slice(&frame_len.to_le_bytes());
395 staged.extend_from_slice(&self.sealed);
396 match &mut self.out {
397 WriterSink::File(f) => f
398 .write_all(&staged)
399 .map_err(|e| Error(format!("writing {}: {e}", self.path.display())))?,
400 WriterSink::Anon(a) => {
401 a.push(&staged)?;
402 }
403 }
404 self.at += staged.len() as u64;
405 self.pending.clear();
406 self.pending_count = 0;
407 Ok(())
408 }
409
410 /// Compressed bytes staged so far (frames plus file header). For spill-size
411 /// measurement: the budget calibrator (`SPILL_BYTES_PER_FEATURE`) is tuned
412 /// per deflate level, so level experiments report this alongside the wall.
413 pub fn staged_bytes(&self) -> u64 {
414 self.at
415 }
416
417 /// Flush, and hand back what the pass learned.
418 pub fn finish(mut self) -> Result<NormalizedSummary> {
419 // The last chunk is usually partial and still needs its frame -- without this its
420 // records would be buffered and never staged.
421 self.seal_frame()?;
422 self.flush_out()?;
423 // Close the last chunk. Without this the final partial chunk has no end, and
424 // `chunk_count` would also over-report by one.
425 if !self.summary.chunks.is_empty() {
426 self.summary.chunks.push(self.at);
427 }
428 Ok(self.summary)
429 }
430
431 /// Flush, and hand back what the pass learned plus whatever backend holds the bytes.
432 ///
433 /// Unifies [`finish`](Self::finish) and [`finish_anon`](Self::finish_anon): callers that pick
434 /// the backend by budget ([`osm_ingest::mem::SpillPlan`]) seal without knowing which one they
435 /// chose. A file backend yields no store -- its bytes live at the path it was created with,
436 /// and readers open that path.
437 pub fn finish_either(mut self) -> Result<(NormalizedSummary, Option<crate::anon::AnonStore>)> {
438 self.seal_frame()?;
439 self.flush_out()?;
440 if !self.summary.chunks.is_empty() {
441 self.summary.chunks.push(self.at);
442 }
443 match self.out {
444 WriterSink::Anon(a) => Ok((self.summary, Some(a))),
445 WriterSink::File(_) => Ok((self.summary, None)),
446 }
447 }
448
449 /// Anonymous twin of [`finish`](Self::finish): flush, hand back the summary
450 /// AND the staged store for [`NormalizedChunks::open_anon`]. Errors when
451 /// this writer is file-backed (a programming bug, not a runtime one).
452 pub fn finish_anon(mut self) -> Result<(NormalizedSummary, crate::anon::AnonStore)> {
453 self.seal_frame()?;
454 self.flush_out()?;
455 if !self.summary.chunks.is_empty() {
456 self.summary.chunks.push(self.at);
457 }
458 match self.out {
459 WriterSink::Anon(a) => Ok((self.summary, a)),
460 WriterSink::File(_) => err("finish_anon on a file-backed writer".to_string()),
461 }
462 }
463
464 fn flush_out(&mut self) -> Result<()> {
465 match &mut self.out {
466 WriterSink::File(f) => f
467 .flush()
468 .map_err(|e| Error(format!("flushing {}: {e}", self.path.display())))?,
469 WriterSink::Anon(a) => a.finish(),
470 }
471 Ok(())
472 }
473}
474
475/// One normalized feature.
476#[derive(Debug, Clone, PartialEq)]
477pub struct NormalizedFeature {
478 pub geometry: Geometry,
479 pub props: Vec<(String, Value)>,
480}
481
482/// Validate a normalized record's fixed header, returning its payload shape.
483///
484/// Shared by the sequential reader and the chunked one, so the two cannot diverge on
485/// what they accept: a record one of them rejects must not be one the other decodes.
486fn norm_header(head: &[u8; NORM_HEADER_BYTES]) -> Result<(usize, usize, GeomKind)> {
487 if head[13..NORM_HEADER_BYTES].iter().any(|v| *v != 0) {
488 return err("normalized record has a nonzero reserved tail");
489 }
490 let u32_at = |o: usize| u32::from_le_bytes(head[o..o + 4].try_into().expect("4 bytes"));
491 let rec_len = u32_at(0) as u64;
492 let geom_len = u32_at(4) as usize;
493 let props_len = u32_at(8) as usize;
494 let want = NORM_HEADER_BYTES as u64 + geom_len as u64 + props_len as u64;
495 if rec_len != want {
496 return err(format!(
497 "normalized record claims {rec_len} byte(s) but its header adds up to {want}"
498 ));
499 }
500 if want > MAX_RECORD_BYTES {
501 return err(format!(
502 "normalized record is {want} byte(s), which is corruption"
503 ));
504 }
505 Ok((geom_len, props_len, GeomKind::from_tag(head[12])?))
506}
507
508/// Decode a validated record's payload, `geom_len` bytes of geometry then properties.
509fn norm_payload(kind: GeomKind, geom_len: usize, payload: &[u8]) -> Result<NormalizedFeature> {
510 Ok(NormalizedFeature {
511 geometry: decode_geometry(kind, &payload[..geom_len])?,
512 props: decode_props(&payload[geom_len..])?,
513 })
514}
515
516/// Validate a spill file header, returning nothing: the magic, version and reserved tail are
517/// either exactly what the writer emits or the file is not a spill this reader knows.
518fn norm_file_header(head: &[u8; NORM_FILE_HEADER_BYTES]) -> Result<()> {
519 if &head[0..4] != NORM_MAGIC {
520 return err("not a normalized spill file (bad NZC1 magic)".to_string());
521 }
522 if head[4] != NORM_VERSION {
523 return err(format!(
524 "unsupported normalized spill version {} (this reader speaks v{NORM_VERSION})",
525 head[4],
526 ));
527 }
528 if head[5..NORM_FILE_HEADER_BYTES].iter().any(|v| *v != 0) {
529 return err("a normalized spill file has a nonzero reserved tail".to_string());
530 }
531 Ok(())
532}
533
534/// Inflate one frame: `u32 compressed_len` + raw DEFLATE of one chunk's records.
535///
536/// The length is checked against the chunk span first (a frame longer than its span is
537/// corruption, not a large chunk), then the inflate itself is the check: DEFLATE framing errors
538/// on truncated or bit-rotted input rather than yielding partial records. Record validation
539/// (`norm_header` per record) still runs on the inflated bytes, so a corrupt frame that
540/// happens to inflate is refused as the desync it is.
541fn inflate_frame(chunk: usize, path: &std::path::Path, frame: &[u8]) -> Result<Vec<u8>> {
542 if frame.len() < 4 {
543 return err(format!(
544 "normalized chunk {chunk} of {} ends {} byte(s) into its 4-byte frame header",
545 path.display(),
546 frame.len(),
547 ));
548 }
549 let want = u32::from_le_bytes(frame[0..4].try_into().expect("4 bytes")) as u64;
550 if want > MAX_FRAME_BYTES {
551 return err(format!(
552 "normalized chunk {chunk} of {} claims a {want}-byte frame, which is corruption",
553 path.display(),
554 ));
555 }
556 if want as usize != frame.len() - 4 {
557 return err(format!(
558 "normalized chunk {chunk} of {} holds {} frame byte(s) but claims {want}",
559 path.display(),
560 frame.len() - 4,
561 ));
562 }
563 miniz_oxide::inflate::decompress_to_vec(&frame[4..]).map_err(|e| {
564 Error(format!(
565 "normalized chunk {chunk} of {} does not inflate: {e:?}",
566 path.display(),
567 ))
568 })
569}
570
571/// Decode every record in one inflated chunk into `out`, which is cleared first.
572///
573/// Split from [`NormalizedChunks::read_into`] so the sequential reader shares the exact same
574/// validation: a record one of them rejects must not be one the other decodes.
575fn decode_chunk_records(
576 chunk: usize,
577 path: &std::path::Path,
578 raw: &[u8],
579 out: &mut Vec<NormalizedFeature>,
580) -> Result<()> {
581 out.clear();
582 let mut at = 0usize;
583 while at < raw.len() {
584 if raw.len() - at < NORM_HEADER_BYTES {
585 return err(format!(
586 "normalized chunk {chunk} of {} ends {} byte(s) into a \
587 {NORM_HEADER_BYTES}-byte record header",
588 path.display(),
589 raw.len() - at
590 ));
591 }
592 let head: &[u8; NORM_HEADER_BYTES] = raw[at..at + NORM_HEADER_BYTES]
593 .try_into()
594 .expect("a header's worth of bytes");
595 let (geom_len, props_len, kind) = norm_header(head)?;
596 let body = at + NORM_HEADER_BYTES;
597 let rec_end = body + geom_len + props_len;
598 if rec_end > raw.len() {
599 return err(format!(
600 "normalized chunk {chunk} of {} holds a record running {} byte(s) past its end",
601 path.display(),
602 rec_end - raw.len()
603 ));
604 }
605 out.push(norm_payload(kind, geom_len, &raw[body..rec_end])?);
606 at = rec_end;
607 }
608 Ok(())
609}
610
611/// Sequential reader over the normalized spill, rewindable because every zoom
612/// re-reads it from the front. File-backed ([`open`](Self::open)) or anonymous
613/// ([`open_anon`](Self::open_anon)): the record format is a sequential stream
614/// either way, so the reader is a cursor over bytes — a file cursor or a store
615/// offset.
616pub struct NormalizedReader {
617 src: ReaderIn,
618 path: PathBuf,
619 /// The current frame's inflated records. Refilled from the next frame when exhausted; the
620 /// reader yields records across the refill boundary without the caller seeing frames at all.
621 frame: Vec<u8>,
622 /// Bytes of `frame` already yielded.
623 frame_used: usize,
624 /// Frames exhausted so far, for error messages that name the chunk.
625 frames_seen: usize,
626 /// Scratch for one compressed frame, reused so a refill allocates nothing but the inflate.
627 raw_frame: Vec<u8>,
628}
629
630/// Where a [`NormalizedReader`] reads from.
631///
632/// Both variants are frame-aware now: the file cursor sits at the next unread frame (past the
633/// 8-byte file header), and the anon offset likewise. `rewind` returns both to the first frame.
634enum ReaderIn {
635 File(BufReader<File>),
636 Anon {
637 store: std::sync::Arc<crate::anon::AnonStore>,
638 at: u64,
639 },
640}
641
642impl NormalizedReader {
643 pub fn open(path: impl Into<PathBuf>) -> Result<NormalizedReader> {
644 let path = path.into();
645 let f = File::open(&path)
646 .map_err(|e| Error(format!("cannot read {}: {e}", path.display())))?;
647 let mut reader = NormalizedReader {
648 src: ReaderIn::File(BufReader::with_capacity(1 << 20, f)),
649 path,
650 frame: Vec::new(),
651 frame_used: 0,
652 frames_seen: 0,
653 raw_frame: Vec::new(),
654 };
655 reader.read_file_header()?;
656 Ok(reader)
657 }
658
659 /// Anonymous twin of [`open`](Self::open): reads the sealed store from
660 /// [`NormalizedWriter::finish_anon`], shared by refcount.
661 pub fn open_anon(
662 path: impl Into<PathBuf>,
663 store: std::sync::Arc<crate::anon::AnonStore>,
664 ) -> Result<NormalizedReader> {
665 let mut reader = NormalizedReader {
666 src: ReaderIn::Anon { store, at: NORM_FILE_HEADER_BYTES as u64 },
667 path: path.into(),
668 frame: Vec::new(),
669 frame_used: 0,
670 frames_seen: 0,
671 raw_frame: Vec::new(),
672 };
673 reader.read_file_header()?;
674 Ok(reader)
675 }
676
677 /// Parse and validate the 8-byte file header, positioning the cursor at the first frame.
678 ///
679 /// Read through the cursor itself (not a separate open) so the file and anon paths share
680 /// the framing: on the file path this consumes the header bytes; on anon it validates the
681 /// store's own first 8 bytes while `at` already skips past them.
682 fn read_file_header(&mut self) -> Result<()> {
683 match &mut self.src {
684 ReaderIn::File(f) => {
685 let mut head = [0u8; NORM_FILE_HEADER_BYTES];
686 use std::io::Read;
687 f.read_exact(&mut head).map_err(|e| {
688 Error(format!("reading {}'s spill header: {e}", self.path.display()))
689 })?;
690 norm_file_header(&head)?;
691 }
692 ReaderIn::Anon { store, .. } => {
693 let mut head = [0u8; NORM_FILE_HEADER_BYTES];
694 store.read_at(0, &mut head).map_err(|e| {
695 Error(format!("reading {}'s spill header: {e}", self.path.display()))
696 })?;
697 norm_file_header(&head)?;
698 }
699 }
700 Ok(())
701 }
702
703 pub fn rewind(&mut self) -> Result<()> {
704 match &mut self.src {
705 ReaderIn::File(f) => {
706 use std::io::Seek;
707 // Past the file header: frame 0 starts at byte 8, not byte 0.
708 f.seek(std::io::SeekFrom::Start(NORM_FILE_HEADER_BYTES as u64))
709 .map_err(|e| Error(format!("rewinding {}: {e}", self.path.display())))?;
710 }
711 ReaderIn::Anon { at, .. } => *at = NORM_FILE_HEADER_BYTES as u64,
712 }
713 self.frame.clear();
714 self.frame_used = 0;
715 self.frames_seen = 0;
716 Ok(())
717 }
718
719 /// Fill `buf` with exactly `len` bytes from the cursor, or `Ok(false)` at a
720 /// clean frame boundary (start of read, or exactly past the last frame's bytes).
721 ///
722 /// A short read anywhere else is corruption, and the callers treat it as such: frames state
723 /// their own length, so a file that ends mid-frame is truncated, not finished.
724 fn read_full(&mut self, buf: &mut [u8]) -> Result<bool> {
725 match &mut self.src {
726 ReaderIn::File(f) => {
727 let mut read = 0usize;
728 while read < buf.len() {
729 let n = f
730 .read(&mut buf[read..])
731 .map_err(|e| Error(format!("reading {}: {e}", self.path.display())))?;
732 if n == 0 {
733 break;
734 }
735 read += n;
736 }
737 // `Ok(false)` only at a frame boundary: mid-frame EOF is reported by the frame
738 // length check in `refill`, not here.
739 Ok(read > 0)
740 }
741 ReaderIn::Anon { store, at } => {
742 if *at >= store.len() {
743 return Ok(false);
744 }
745 let remaining = store.len() - *at;
746 let take = (buf.len() as u64).min(remaining) as usize;
747 store.read_at(*at, &mut buf[..take]).map_err(|e| {
748 Error(format!("reading {}: {e}", self.path.display()))
749 })?;
750 *at += take as u64;
751 Ok(true)
752 }
753 }
754 }
755
756 /// The next frame's inflated records, replacing `frame`.
757 ///
758 /// Reads the frame's `u32` length, then exactly that many bytes -- a short read there is a
759 /// truncated file, never a legitimate end -- inflates, and validates the inflate before any
760 /// record is yielded. `Ok(false)` only when the cursor sits exactly at end of input.
761 fn refill(&mut self) -> Result<bool> {
762 let mut len_buf = [0u8; 4];
763 if !self.read_full(&mut len_buf)? {
764 return Ok(false);
765 }
766 let want = u32::from_le_bytes(len_buf) as usize;
767 if want as u64 > MAX_FRAME_BYTES {
768 return err(format!(
769 "normalized frame {} of {} claims {} byte(s), which is corruption",
770 self.frames_seen,
771 self.path.display(),
772 want,
773 ));
774 }
775 self.raw_frame.clear();
776 self.raw_frame.resize(want, 0);
777 // Exact-length by construction (the length was just read), so a short payload is
778 // corruption, not EOF. `read_full` may return short mid-frame on the file path;
779 // loop until the frame is whole or the file ends.
780 let mut read = 0usize;
781 while read < want {
782 let mut chunk = vec![0u8; want - read];
783 if !self.read_full(&mut chunk)? {
784 return err(format!(
785 "{} ends {} byte(s) into frame {}",
786 self.path.display(),
787 read,
788 self.frames_seen,
789 ));
790 }
791 // `read_full` on the file path may return short; on anon it fills exactly.
792 let n = chunk.len();
793 self.raw_frame[read..read + n].copy_from_slice(&chunk);
794 read += n;
795 if n == 0 {
796 break;
797 }
798 }
799 let mut framed = Vec::with_capacity(4 + want);
800 framed.extend_from_slice(&len_buf);
801 framed.extend_from_slice(&self.raw_frame);
802 self.frame = inflate_frame(self.frames_seen, &self.path, &framed)?;
803 self.frame_used = 0;
804 self.frames_seen += 1;
805 Ok(true)
806 }
807
808 #[allow(clippy::should_implement_trait)]
809 pub fn next(&mut self) -> Result<Option<NormalizedFeature>> {
810 loop {
811 if self.frame_used < self.frame.len() {
812 let head: &[u8; NORM_HEADER_BYTES] = self.frame
813 [self.frame_used..self.frame_used + NORM_HEADER_BYTES]
814 .try_into()
815 .map_err(|_| {
816 Error(format!(
817 "{} ends {} byte(s) into a {NORM_HEADER_BYTES}-byte record header",
818 self.path.display(),
819 self.frame.len() - self.frame_used,
820 ))
821 })?;
822 let (geom_len, props_len, kind) = norm_header(head)?;
823 let body = self.frame_used + NORM_HEADER_BYTES;
824 let rec_end = body + geom_len + props_len;
825 if rec_end > self.frame.len() {
826 return err(format!(
827 "{} holds a record running {} byte(s) past its frame",
828 self.path.display(),
829 rec_end - self.frame.len(),
830 ));
831 }
832 let feature = norm_payload(kind, geom_len, &self.frame[body..rec_end])?;
833 self.frame_used = rec_end;
834 return Ok(Some(feature));
835 }
836 if !self.refill()? {
837 return Ok(None);
838 }
839 }
840 }
841}
842
843/// Chunked reader over the normalized file, for reading it across a thread pool.
844///
845/// The sequential [`NormalizedReader`] is one cursor, so the decode of every feature —
846/// which allocates a `Geometry` and a `Vec` of properties, six times over a z11..z16
847/// build — happens on whichever single thread owns it, while the pool waits. This reads
848/// a whole chunk's byte range positionally instead, so the decode happens on the worker
849/// that will bucket those features.
850///
851/// Takes `&self` throughout: see [`crate::pmtiles::read_exact_at`]. One handle serves
852/// every thread.
853///
854/// Anonymous twin: [`open_anon`](Self::open_anon) serves the same chunks from an
855/// [`crate::anon::AnonStore`] instead of a file. Same offsets, same bytes.
856pub struct NormalizedChunks {
857 file: Option<File>,
858 anon: Option<std::sync::Arc<crate::anon::AnonStore>>,
859 path: PathBuf,
860 /// Chunk boundaries, `chunk_count() + 1` of them. See [`NormalizedSummary::chunks`].
861 chunks: Vec<u64>,
862}
863
864impl NormalizedChunks {
865 /// `chunks` is [`NormalizedSummary::chunks`] for this file.
866 pub fn open(path: impl Into<PathBuf>, chunks: Vec<u64>) -> Result<NormalizedChunks> {
867 let path = path.into();
868 let file = File::open(&path)
869 .map_err(|e| Error(format!("cannot read {}: {e}", path.display())))?;
870 Ok(NormalizedChunks { file: Some(file), anon: None, path, chunks })
871 }
872
873 /// Anonymous twin of [`open`](Self::open): `store` is the sealed store from
874 /// [`NormalizedWriter::finish_anon`], shared by refcount — the store
875 /// outlives every reader, so this is a refcount bump, never a copy.
876 /// `path` names nothing — it only rides along for error messages.
877 pub fn open_anon(
878 path: impl Into<PathBuf>,
879 chunks: Vec<u64>,
880 store: std::sync::Arc<crate::anon::AnonStore>,
881 ) -> Result<NormalizedChunks> {
882 Ok(NormalizedChunks {
883 file: None,
884 anon: Some(store),
885 path: path.into(),
886 chunks,
887 })
888 }
889
890 pub fn chunk_count(&self) -> usize {
891 self.chunks.len().saturating_sub(1)
892 }
893
894 /// Whether this reader serves from anonymous memory rather than a file.
895 pub fn is_anon(&self) -> bool {
896 self.anon.is_some()
897 }
898
899 /// Decode chunk `i` into `out`, which is cleared first.
900 ///
901 /// `scratch` is the caller's per-worker byte buffer, reused across chunks so a pass
902 /// allocates once per thread rather than once per chunk.
903 ///
904 /// The first feature of chunk `i` is input feature `i * NORM_CHUNK_FEATURES`, by
905 /// construction of the index — which is what lets the caller reproduce the exact
906 /// `seq` the sequential path assigns.
907 ///
908 /// The chunk span covers one compressed frame: it is read whole, inflated, and decoded
909 /// with the same [`decode_chunk_records`] the sequential reader uses, so the two paths
910 /// cannot diverge on what they accept.
911 pub fn read_into(
912 &self,
913 i: usize,
914 scratch: &mut Vec<u8>,
915 out: &mut Vec<NormalizedFeature>,
916 ) -> Result<()> {
917 out.clear();
918 let (Some(&start), Some(&end)) = (self.chunks.get(i), self.chunks.get(i + 1)) else {
919 return err(format!(
920 "normalized chunk {i} is past the {} in {}",
921 self.chunk_count(),
922 self.path.display()
923 ));
924 };
925 if end < start {
926 return err(format!(
927 "normalized chunk {i} of {} ends before it starts",
928 self.path.display()
929 ));
930 }
931 let len = (end - start) as usize;
932 scratch.clear();
933 scratch.resize(len, 0);
934 match (&self.file, &self.anon) {
935 (Some(f), None) => {
936 crate::pmtiles::read_exact_at(f, scratch, start).map_err(|e| {
937 Error(format!(
938 "reading normalized chunk {i} of {}: {e}",
939 self.path.display()
940 ))
941 })?;
942 }
943 (None, Some(a)) => a.read_at(start, scratch).map_err(|e| {
944 Error(format!(
945 "reading normalized chunk {i} of {}: {e}",
946 self.path.display()
947 ))
948 })?,
949 _ => return err("a normalized chunk reader has no backend".to_string()),
950 }
951 let raw = inflate_frame(i, &self.path, scratch)?;
952 decode_chunk_records(i, &self.path, &raw, out)
953 }
954}
955
956/// The normalized file's lifetime, so a run that dies mid-planet cannot strand it.
957///
958/// A guard rather than `impl Drop` on the reader, because the reader is handed around
959/// and the file has to outlive every one of them.
960pub struct NormalizedFile(PathBuf);
961
962impl NormalizedFile {
963 pub fn new(path: impl Into<PathBuf>) -> NormalizedFile {
964 NormalizedFile(path.into())
965 }
966
967 pub fn path(&self) -> &Path {
968 &self.0
969 }
970}
971
972impl Drop for NormalizedFile {
973 fn drop(&mut self) {
974 let _ = std::fs::remove_file(&self.0);
975 }
976}