Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / tile_build / src / spill_part2.rs
spill_part2.rs269 lines · 10.1 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. |
| 8 | pub 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 | |
| 21 | impl 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)] |
| 104 | pub 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 | |
| 121 | impl 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. |
| 174 | enum 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. |
| 181 | const 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. |
| 184 | const NORM_VERSION: u8 = 1; |
| 185 | /// Bytes of file header before the first frame. The chunk index's first offset equals this. |
| 186 | const 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. |
| 189 | const MAX_FRAME_BYTES: u64 = 1 << 30; |
| 190 | |
| 191 | /// A sealed frame's raw records: its own buffer, or a whole-frame slice of a caller's run |
| 192 | /// ([`NormalizedWriter::push_run`]) compressed in place without a copy. |
| 193 | enum FrameSrc { |
| 194 | Owned(Vec<u8>), |
| 195 | Shared(std::sync::Arc<Vec<u8>>, std::ops::Range<usize>), |
| 196 | } |
| 197 | |
| 198 | impl FrameSrc { |
| 199 | fn bytes(&self) -> &[u8] { |
| 200 | match self { |
| 201 | FrameSrc::Owned(v) => v, |
| 202 | FrameSrc::Shared(v, r) => &v[r.clone()], |
| 203 | } |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | /// A thread staging compressed frames into the sink, in the order they are sent: each frame as |
| 208 | /// its `u32` length then its bytes, exactly what the inline path wrote. Bounded, so at most a few |
| 209 | /// batches wait. |
| 210 | struct BgWriter { |
| 211 | tx: Option<std::sync::mpsc::SyncSender<Vec<Vec<u8>>>>, |
| 212 | handle: Option<std::thread::JoinHandle<Result<WriterSink>>>, |
| 213 | } |
| 214 | |
| 215 | impl BgWriter { |
| 216 | fn start(mut out: WriterSink, path: PathBuf) -> BgWriter { |
| 217 | let (tx, rx) = std::sync::mpsc::sync_channel::<Vec<Vec<u8>>>(4); |
| 218 | let handle = std::thread::Builder::new() |
| 219 | .name("spill-writer".to_string()) |
| 220 | .spawn(move || -> Result<WriterSink> { |
| 221 | for batch in rx { |
| 222 | for frame in batch { |
| 223 | let len = (frame.len() as u32).to_le_bytes(); |
| 224 | match &mut out { |
| 225 | WriterSink::File(f) => f |
| 226 | .write_all(&len) |
| 227 | .and_then(|()| f.write_all(&frame)) |
| 228 | .map_err(|e| Error(format!("writing {}: {e}", path.display())))?, |
| 229 | WriterSink::Anon(a) => { |
| 230 | a.push(&len)?; |
| 231 | a.push(&frame)?; |
| 232 | } |
| 233 | } |
| 234 | } |
| 235 | } |
| 236 | Ok(out) |
| 237 | }) |
| 238 | .expect("start the spill writer thread"); |
| 239 | BgWriter { tx: Some(tx), handle: Some(handle) } |
| 240 | } |
| 241 | |
| 242 | /// Queue one batch. A writer that already failed reports its error here, at the next send, |
| 243 | /// rather than at `finish`. |
| 244 | fn send(&self, batch: Vec<Vec<u8>>) -> Result<()> { |
| 245 | if self.tx.as_ref().expect("open until finish").send(batch).is_err() { |
| 246 | return err("the spill writer stopped early; its error follows at finish".to_string()); |
| 247 | } |
| 248 | Ok(()) |
| 249 | } |
| 250 | |
| 251 | fn finish(mut self) -> Result<WriterSink> { |
| 252 | drop(self.tx.take()); |
| 253 | self.handle |
| 254 | .take() |
| 255 | .expect("joined once") |
| 256 | .join() |
| 257 | .map_err(|_| Error("the spill writer thread panicked".to_string()))? |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | impl Drop for BgWriter { |
| 262 | fn drop(&mut self) { |
| 263 | drop(self.tx.take()); |
| 264 | if let Some(h) = self.handle.take() { |
| 265 | let _ = h.join(); |
| 266 | } |
| 267 | } |
| 268 | } |
| 269 |