/// Sequential reader over one bucket. /// /// Errors if a record's `tile_id` falls outside the bucket's range, and at the end if /// the record or byte count disagrees with what the writer tallied. The order the /// encode pass depends on is asserted directly by its own test; /// [`crate::pmtiles::StreamBuilder::add_tile_raw`] refusing a non-ascending id is the /// second line of defence, not the first. pub struct BucketReader { src: BufReader, path: PathBuf, lo: u64, hi: u64, expect_records: u64, expect_bytes: u64, seen_records: u64, seen_bytes: u64, done: bool, buf: Vec, } impl BucketReader { #[allow(clippy::should_implement_trait)] pub fn next(&mut self) -> Result> { if self.done { return Ok(None); } let mut head = [0u8; REC_HEADER_BYTES]; let mut read = 0usize; while read < REC_HEADER_BYTES { let n = self .src .read(&mut head[read..]) .map_err(|e| Error(format!("reading {}: {e}", self.path.display())))?; if n == 0 { break; } read += n; } if read == 0 { self.done = true; self.check_totals()?; return Ok(None); } if read < REC_HEADER_BYTES { // A partial header is a truncated file, never a legitimate end. return err(format!( "{} ends {read} byte(s) into a {REC_HEADER_BYTES}-byte record header", self.path.display() )); } let h = RecHeader::parse(&head)?; if h.tile_id < self.lo || h.tile_id >= self.hi { return err(format!( "{} holds tile id {} but covers {}..{}", self.path.display(), h.tile_id, self.lo, self.hi )); } let payload = h.geom_len as usize + h.props_len as usize; self.buf.clear(); self.buf.resize(payload, 0); self.src .read_exact(&mut self.buf) .map_err(|e| Error(format!("reading {}'s record payload: {e}", self.path.display())))?; let geom = decode_int_geometry(h.kind, &self.buf[..h.geom_len as usize])?; let props = decode_props(&self.buf[h.geom_len as usize..])?; self.seen_records += 1; self.seen_bytes += h.rec_len as u64; Ok(Some(SpillRecord { tile_id: h.tile_id, seq: h.seq, extent: h.extent, geom, props, })) } fn check_totals(&self) -> Result<()> { if self.seen_records != self.expect_records || self.seen_bytes != self.expect_bytes { return err(format!( "{} read back {} record(s)/{} byte(s) but the writer tallied {}/{}", self.path.display(), self.seen_records, self.seen_bytes, self.expect_records, self.expect_bytes )); } Ok(()) } } // --- the normalized file ----------------------------------------------------- /// What one pass over the geojsonseq learned, beyond the records themselves. /// /// The streaming producer's header comes from here rather than from a second pass: /// [`crate::pmtiles::StreamBuilder`]'s bounds fields are serialised last, so they can be /// a streaming fold assigned any time before `finish`. #[derive(Debug, Clone, Default, PartialEq)] pub struct NormalizedSummary { pub count: u64, pub bounds: Option, /// The FIRST feature's kind, which is the rule `dominant_geom_type` already applies: /// a layer is styled as one thing, so a mixed layer is a mistake upstream and should /// show as wrong rendering rather than hide as a silently split layer. pub geom_kind: Option, pub skipped: u64, /// Byte offset of every `NORM_CHUNK_FEATURES`-th record, plus a final sentinel /// holding the file's total length — so chunk `i` spans `chunks[i]..chunks[i + 1]` /// and there are `chunks.len() - 1` of them. /// /// Built by the same single pass that writes the records, because the writer is the /// only place that already knows each record's length. Empty for an empty file. pub chunks: Vec, } impl NormalizedSummary { /// How many chunks the file has, for [`NormalizedChunks::read_into`]. pub fn chunk_count(&self) -> usize { self.chunks.len().saturating_sub(1) } } /// Writes the geojsonseq once into a compact binary every zoom can re-read. /// /// ```text /// 0..4 u32 rec_len whole record, this field included /// 4..8 u32 geom_len /// 8..12 u32 props_len /// 12..13 u8 geom_kind /// 13..16 reserved, zero /// 16.. geometry (lon/lat e7 `i32` pairs), then properties /// ``` /// /// Eight bytes a vertex rather than sixteen: see [`encode_geometry`] for why that is /// lossless for OSM coordinates and what it costs a coastline. /// /// # Compressed frames (planet disk peak) /// /// Records are grouped into frames of [`NORM_CHUNK_FEATURES`] features and each frame is /// stored as raw DEFLATE. The file layout is: /// /// ```text /// 0..4 magic `NZC1` /// 4..5 version 1 /// 5..8 reserved, zero /// 8.. frames, back to back: /// u32 compressed_len (this field excluded) /// raw DEFLATE stream of one chunk's records /// ``` /// /// Why this shape: the 259 GB planet feature spill is what fills the disk beside the z14 /// tile chunks (~101 GB) and the bodies scratch, and coordinates compress ~3x (sorted e7 /// varints, delta runs). Per-chunk frames keep the [`NormalizedSummary::chunks`] index valid /// verbatim -- chunk `i` still spans `chunks[i]..chunks[i+1]`, now over compressed bytes -- /// so positional reads, the `chunk_mins` zoom filter, the prefetch lanes and the anon backend /// all work unchanged, and inflate-then-decode yields byte-identical records. A whole-file /// stream would kill positional reads; per-record frames would pay inflate setup 1.9 B x 15 /// times for worse ratio. /// /// Spill files are build-temp (removed on success, never shipped), so there is no cross-version /// compat to keep: a reader that does not know `NZC1` refuses the magic rather than decoding /// frames as records. /// /// Backed by a file ([`create`](Self::create)) or by anonymous pagefile memory /// ([`create_anon`](Self::create_anon)), /// which stages the same bytes with no directory entry. Same records, same /// offsets, same output bytes — the -Verify hash check proves it. /// Where a [`NormalizedWriter`] stages its bytes: a file, or anonymous memory. enum WriterSink { File(BufWriter), Anon(crate::anon::AnonStore), } /// File magic for the compressed normalized spill. A reader that does not know it refuses /// the file rather than decoding frames as records. const NORM_MAGIC: &[u8; 4] = b"NZC1"; /// Frame format version. Bumped if the framing ever changes; spill files are build-temp so no /// migration path is needed, only a refusal. const NORM_VERSION: u8 = 1; /// Bytes of file header before the first frame. The chunk index's first offset equals this. const NORM_FILE_HEADER_BYTES: usize = 8; /// Largest single frame accepted, compressed or not. A 64-feature chunk of plausible records is /// kilobytes; a gigabyte frame is corruption, not a dense chunk. const MAX_FRAME_BYTES: u64 = 1 << 30; /// A sealed frame's raw records: its own buffer, or a whole-frame slice of a caller's run /// ([`NormalizedWriter::push_run`]) compressed in place without a copy. enum FrameSrc { Owned(Vec), Shared(std::sync::Arc>, std::ops::Range), } impl FrameSrc { fn bytes(&self) -> &[u8] { match self { FrameSrc::Owned(v) => v, FrameSrc::Shared(v, r) => &v[r.clone()], } } } /// A thread staging compressed frames into the sink, in the order they are sent: each frame as /// its `u32` length then its bytes, exactly what the inline path wrote. Bounded, so at most a few /// batches wait. struct BgWriter { tx: Option>>>, handle: Option>>, } impl BgWriter { fn start(mut out: WriterSink, path: PathBuf) -> BgWriter { let (tx, rx) = std::sync::mpsc::sync_channel::>>(4); let handle = std::thread::Builder::new() .name("spill-writer".to_string()) .spawn(move || -> Result { for batch in rx { for frame in batch { let len = (frame.len() as u32).to_le_bytes(); match &mut out { WriterSink::File(f) => f .write_all(&len) .and_then(|()| f.write_all(&frame)) .map_err(|e| Error(format!("writing {}: {e}", path.display())))?, WriterSink::Anon(a) => { a.push(&len)?; a.push(&frame)?; } } } } Ok(out) }) .expect("start the spill writer thread"); BgWriter { tx: Some(tx), handle: Some(handle) } } /// Queue one batch. A writer that already failed reports its error here, at the next send, /// rather than at `finish`. fn send(&self, batch: Vec>) -> Result<()> { if self.tx.as_ref().expect("open until finish").send(batch).is_err() { return err("the spill writer stopped early; its error follows at finish".to_string()); } Ok(()) } fn finish(mut self) -> Result { drop(self.tx.take()); self.handle .take() .expect("joined once") .join() .map_err(|_| Error("the spill writer thread panicked".to_string()))? } } impl Drop for BgWriter { fn drop(&mut self) { drop(self.tx.take()); if let Some(h) = self.handle.take() { let _ = h.join(); } } }