Skip to main content

geolith_tiles_builder/sort/
chunk.rs

1//! LZ4-compressed sort chunk files for spilling to disk.
2//!
3//! During Phase 1 (read + process), each rayon thread accumulates
4//! `SortEntry` items in a local buffer. When the buffer exceeds a
5//! size threshold, it is sorted by key and flushed to a chunk file.
6//!
7//! Each chunk file contains a sequence of length-prefixed postcard
8//! frames compressed with LZ4.
9
10use std::fs::File;
11use std::io::{BufReader, BufWriter, Read, Write};
12use std::path::{Path, PathBuf};
13use std::sync::Arc;
14use std::sync::atomic::{AtomicU32, Ordering as AtomicOrdering};
15
16use lz4_flex::frame::{FrameDecoder, FrameEncoder};
17
18use crate::sort::entry::SortEntry;
19use geolith::error::{GeolithError, Result};
20
21/// Maximum uncompressed bytes per chunk before flushing (default 256 MB).
22const DEFAULT_CHUNK_BYTES: usize = 256 * 1024 * 1024;
23
24/// Write buffer size for chunk files (8 MB).
25///
26/// Larger buffers reduce syscall overhead during Phase 1 writes.
27const WRITE_BUF_SIZE: usize = 8 * 1024 * 1024;
28
29/// Read buffer size for chunk files (1 MB).
30///
31/// Sized to balance per-file memory (many files open during merge)
32/// against reducing syscall overhead.
33const READ_BUF_SIZE: usize = 1024 * 1024;
34
35/// Manages writing sorted chunk files to a temporary directory.
36///
37/// Each instance tracks its own chunk paths. Multiple sinks can share
38/// a single atomic counter to produce unique filenames across threads.
39pub struct ChunkSink {
40    /// Directory to store chunk files.
41    dir: PathBuf,
42    /// Paths of all chunk files written so far.
43    chunk_paths: Vec<PathBuf>,
44    /// Shared counter for generating unique chunk file names.
45    counter: Arc<AtomicU32>,
46}
47
48impl ChunkSink {
49    /// Create a new chunk sink writing to the given directory.
50    ///
51    /// Creates the directory if it doesn't exist. Uses a private counter
52    /// starting at 0 for chunk file naming.
53    ///
54    /// # Errors
55    ///
56    /// Returns an error if creating the directory fails.
57    pub fn new(dir: PathBuf) -> Result<Self> {
58        std::fs::create_dir_all(&dir)?;
59        Ok(Self {
60            dir,
61            chunk_paths: Vec::new(),
62            counter: Arc::new(AtomicU32::new(0)),
63        })
64    }
65
66    /// Create a per-thread chunk sink sharing a global chunk ID counter.
67    ///
68    /// The directory must already exist (caller creates it once).
69    /// The shared counter ensures chunk files have unique names across
70    /// all threads, eliminating the need for a global `Mutex`.
71    pub const fn with_counter(dir: PathBuf, counter: Arc<AtomicU32>) -> Self {
72        Self {
73            dir,
74            chunk_paths: Vec::new(),
75            counter,
76        }
77    }
78
79    /// Write a sorted slice of entries to a new chunk file.
80    ///
81    /// The entries MUST already be sorted by key before calling this.
82    ///
83    /// # Errors
84    ///
85    /// Returns an error if file creation, postcard serialization,
86    /// or LZ4 compression fails.
87    pub fn write_chunk(&mut self, entries: &[SortEntry]) -> Result<PathBuf> {
88        let id = self.counter.fetch_add(1, AtomicOrdering::Relaxed);
89        let path = self.dir.join(format!("chunk_{id:06}.lz4"));
90
91        let file = File::create(&path)?;
92        let buf = BufWriter::with_capacity(WRITE_BUF_SIZE, file);
93        let mut encoder = FrameEncoder::new(buf);
94
95        for entry in entries {
96            let bytes = entry.to_bytes()?;
97            let len = length_prefix(bytes.len())?;
98            encoder.write_all(&len.to_le_bytes())?;
99            encoder.write_all(&bytes)?;
100        }
101
102        encoder.finish()?;
103        self.chunk_paths.push(path.clone());
104        Ok(path)
105    }
106
107    /// All chunk file paths written so far, in creation order.
108    #[must_use]
109    pub fn chunk_paths(&self) -> &[PathBuf] {
110        &self.chunk_paths
111    }
112
113    /// Number of chunk files written.
114    #[must_use]
115    pub const fn chunk_count(&self) -> usize {
116        self.chunk_paths.len()
117    }
118
119    /// Consume this sink and return all chunk file paths written.
120    #[must_use]
121    pub fn into_chunk_paths(self) -> Vec<PathBuf> {
122        self.chunk_paths
123    }
124
125    /// Clean up all chunk files.
126    ///
127    /// # Errors
128    ///
129    /// Returns an error if removing any chunk file fails.
130    pub fn cleanup(&self) -> Result<()> {
131        for path in &self.chunk_paths {
132            if path.exists() {
133                std::fs::remove_file(path)?;
134            }
135        }
136        Ok(())
137    }
138}
139
140/// A thread-local buffer that accumulates sort entries and flushes
141/// to a `ChunkSink` when the buffer exceeds the size threshold.
142pub struct SortBuffer {
143    entries: Vec<SortEntry>,
144    /// Approximate total serialized size in bytes.
145    approx_bytes: usize,
146    /// Flush threshold in bytes.
147    max_bytes: usize,
148}
149
150impl SortBuffer {
151    /// Create a new sort buffer with the default size threshold.
152    #[must_use]
153    pub fn new() -> Self {
154        Self::with_max_bytes(DEFAULT_CHUNK_BYTES)
155    }
156
157    /// Create a new sort buffer with a custom size threshold.
158    #[must_use]
159    pub fn with_max_bytes(max_bytes: usize) -> Self {
160        Self {
161            entries: Vec::with_capacity(1024),
162            approx_bytes: 0,
163            max_bytes,
164        }
165    }
166
167    /// Push an entry into the buffer.
168    ///
169    /// Returns `true` if the buffer is now full and should be flushed.
170    #[inline]
171    pub fn push(&mut self, entry: SortEntry) -> bool {
172        // Approximate size: 8 bytes key + ~50 bytes avg feature
173        self.approx_bytes +=
174            58 + entry.feature.properties.len() * 24 + entry.feature.geometry.len() * 4;
175        self.entries.push(entry);
176        self.approx_bytes >= self.max_bytes
177    }
178
179    /// Sort entries by key and flush to a chunk file via the sink.
180    ///
181    /// Clears the buffer after writing.
182    ///
183    /// # Errors
184    ///
185    /// Returns an error if sorting or chunk write fails.
186    pub fn flush(&mut self, sink: &mut ChunkSink) -> Result<()> {
187        if self.entries.is_empty() {
188            return Ok(());
189        }
190        self.entries.sort_unstable();
191        sink.write_chunk(&self.entries)?;
192        self.entries.clear();
193        self.approx_bytes = 0;
194        Ok(())
195    }
196
197    /// Whether the buffer has pending entries.
198    #[must_use]
199    pub const fn is_empty(&self) -> bool {
200        self.entries.is_empty()
201    }
202
203    /// Number of entries in the buffer.
204    #[must_use]
205    pub const fn len(&self) -> usize {
206        self.entries.len()
207    }
208}
209
210impl Default for SortBuffer {
211    fn default() -> Self {
212        Self::new()
213    }
214}
215
216/// Read all sort entries from a chunk file, in order.
217///
218/// This is a convenience for testing; the merge module uses
219/// `ChunkReader` for streaming reads.
220///
221/// # Errors
222///
223/// Returns an error if file open, LZ4 decompression, or postcard
224/// deserialization fails.
225pub fn read_chunk(path: &Path) -> Result<Vec<SortEntry>> {
226    let file = File::open(path)?;
227    let buf = BufReader::with_capacity(READ_BUF_SIZE, file);
228    let mut decoder = FrameDecoder::new(buf);
229    let mut entries = Vec::with_capacity(1024);
230    let mut len_buf = [0u8; 4];
231    let mut data_buf = Vec::with_capacity(256);
232
233    loop {
234        match decoder.read_exact(&mut len_buf) {
235            Ok(()) => {}
236            Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => break,
237            Err(e) => return Err(e.into()),
238        }
239        let len = u32::from_le_bytes(len_buf) as usize;
240        if data_buf.len() < len {
241            data_buf.resize(len, 0);
242        }
243        decoder.read_exact(&mut data_buf[..len])?;
244        let entry = SortEntry::from_bytes(&data_buf[..len])?;
245        entries.push(entry);
246    }
247
248    Ok(entries)
249}
250
251/// Streaming reader for a single chunk file.
252///
253/// Used by the k-way merge to read entries one at a time without
254/// loading the entire chunk into memory.
255pub struct ChunkReader {
256    decoder: FrameDecoder<BufReader<File>>,
257    /// The next entry, pre-read for the merge heap.
258    peeked: Option<SortEntry>,
259    /// Whether we've reached the end of the chunk.
260    exhausted: bool,
261    /// Reusable buffer for reading entry data, avoids per-entry allocation.
262    data_buf: Vec<u8>,
263}
264
265impl ChunkReader {
266    /// Open a chunk file for streaming reads.
267    ///
268    /// # Errors
269    ///
270    /// Returns an error if file open, LZ4 frame read, or initial
271    /// entry deserialization fails.
272    pub fn open(path: &Path) -> Result<Self> {
273        let file = File::open(path)?;
274        let buf = BufReader::with_capacity(READ_BUF_SIZE, file);
275        let decoder = FrameDecoder::new(buf);
276        let mut reader = Self {
277            decoder,
278            peeked: None,
279            exhausted: false,
280            data_buf: Vec::with_capacity(256),
281        };
282        reader.advance()?;
283        Ok(reader)
284    }
285
286    /// The next entry, if any, without consuming it.
287    #[inline]
288    #[must_use]
289    pub const fn peek(&self) -> Option<&SortEntry> {
290        self.peeked.as_ref()
291    }
292
293    /// Take the next entry and advance the reader.
294    ///
295    /// # Errors
296    ///
297    /// Returns an error if reading or deserializing the next entry fails.
298    pub fn take(&mut self) -> Result<Option<SortEntry>> {
299        let entry = self.peeked.take();
300        if entry.is_some() {
301            self.advance()?;
302        }
303        Ok(entry)
304    }
305
306    /// Whether this reader has been fully consumed.
307    #[inline]
308    #[must_use]
309    pub const fn is_exhausted(&self) -> bool {
310        self.exhausted
311    }
312
313    /// Read the next entry from the decoder.
314    fn advance(&mut self) -> Result<()> {
315        if self.exhausted {
316            return Ok(());
317        }
318        let mut len_buf = [0u8; 4];
319        match self.decoder.read_exact(&mut len_buf) {
320            Ok(()) => {}
321            Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
322                self.exhausted = true;
323                return Ok(());
324            }
325            Err(e) => return Err(e.into()),
326        }
327        let len = u32::from_le_bytes(len_buf) as usize;
328        // Grow buffer only when needed — never shrinks, so the allocation
329        // stabilises after the first few entries.
330        if self.data_buf.len() < len {
331            self.data_buf.resize(len, 0);
332        }
333        self.decoder.read_exact(&mut self.data_buf[..len])?;
334        let entry = SortEntry::from_bytes(&self.data_buf[..len])?;
335        self.peeked = Some(entry);
336        Ok(())
337    }
338}
339
340/// The `u32` length prefix written before each encoded entry.
341fn length_prefix(len: usize) -> Result<u32> {
342    u32::try_from(len).map_err(|_| {
343        GeolithError::Io(std::io::Error::new(
344            std::io::ErrorKind::InvalidData,
345            format!("sort entry of {len} bytes exceeds the u32 length prefix"),
346        ))
347    })
348}
349
350#[cfg(test)]
351mod tests {
352    use super::*;
353
354    #[test]
355    fn an_entry_length_must_fit_the_u32_prefix() {
356        assert_eq!(
357            length_prefix(4_294_967_295).expect("u32::MAX fits"),
358            u32::MAX
359        );
360        assert!(length_prefix(4_294_967_296).is_err());
361    }
362    use std::sync::Arc;
363
364    use geolith::layer::Layer;
365    use geolith::tile::feature::{GeomType, TileFeature};
366
367    fn make_entry(key: u64) -> SortEntry {
368        SortEntry::new(
369            key,
370            TileFeature {
371                layer: Layer::Buildings,
372                id: key,
373                geom_type: GeomType::Polygon,
374                geometry: vec![9, 0, 0],
375                properties: Arc::new(vec![]),
376                sort_key: 0,
377            },
378        )
379    }
380
381    #[test]
382    fn roundtrip_chunk_write_read() {
383        let dir = tempfile::tempdir().expect("tmpdir");
384        let mut sink = ChunkSink::new(dir.path().to_path_buf()).expect("sink");
385
386        let mut entries: Vec<SortEntry> = (0..100).rev().map(make_entry).collect();
387        entries.sort_unstable();
388        sink.write_chunk(&entries).expect("write");
389
390        let read_back = read_chunk(&sink.chunk_paths()[0]).expect("read");
391        assert_eq!(read_back.len(), 100);
392        // Verify sorted order
393        for window in read_back.windows(2) {
394            assert!(window[0].key <= window[1].key);
395        }
396    }
397
398    #[test]
399    fn sort_buffer_flush_threshold() {
400        let mut buf = SortBuffer::with_max_bytes(100);
401        let mut full = false;
402        for i in 0..1000 {
403            if buf.push(make_entry(i)) {
404                full = true;
405                break;
406            }
407        }
408        assert!(full, "buffer should fill up");
409        assert!(!buf.is_empty());
410    }
411
412    #[test]
413    fn chunk_reader_streaming() {
414        let dir = tempfile::tempdir().expect("tmpdir");
415        let mut sink = ChunkSink::new(dir.path().to_path_buf()).expect("sink");
416
417        let entries: Vec<SortEntry> = (0..50).map(make_entry).collect();
418        sink.write_chunk(&entries).expect("write");
419
420        let mut reader = ChunkReader::open(&sink.chunk_paths()[0]).expect("open");
421        let mut count = 0;
422        while !reader.is_exhausted() {
423            let entry = reader.take().expect("take");
424            if entry.is_some() {
425                count += 1;
426            }
427        }
428        assert_eq!(count, 50);
429    }
430}