1use std::cell::RefCell;
20use std::fs::{File, OpenOptions};
21use std::io::{BufWriter, Read, Write};
22use std::path::{Path, PathBuf};
23use std::sync::Arc;
24use std::sync::atomic::{AtomicU32, Ordering as AtomicOrdering};
25
26use xxhash_rust::xxh3::xxh3_64;
27
28use crate::sort::block::{BlockDecoder, BlockEncoder};
29use crate::sort::entry::SortEntry;
30use crate::sort::error::SortRunError;
31use crate::sort::reclaim;
32use crate::tiles_error::{Result, TilesError};
33
34const DEFAULT_CHUNK_BYTES: usize = 256 * 1024 * 1024;
36
37const WRITE_BUF_SIZE: usize = 8 * 1024 * 1024;
41
42pub const RUN_EXTENSION: &str = "run";
44
45const MAGIC: [u8; 4] = *b"GLRN";
47const LAYOUT: u8 = 1;
49const HEADER_LEN: usize = 8;
51const KIND_BLOCK: u8 = 1;
53const KIND_END: u8 = 0xFF;
55const BLOCK_HEADER_LEN: usize = 20;
58const END_LEN: usize = 24;
60const MAX_RAW_BLOCK: usize = 256 * 1024 * 1024;
62
63const BLOCK_RAW_TARGET: usize = 512 * 1024;
65const ZSTD_LEVEL: i32 = 3;
67
68thread_local! {
69 static DECOMPRESSOR: RefCell<Option<zstd::bulk::Decompressor<'static>>> =
73 const { RefCell::new(None) };
74
75 static PACKED: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
78}
79
80fn io_error(op: &'static str, path: &Path) -> impl FnOnce(std::io::Error) -> TilesError {
81 let path = path.to_path_buf();
82 move |source| SortRunError::Io { op, path, source }.into()
83}
84
85pub struct ChunkSink {
90 dir: PathBuf,
92 chunk_paths: Vec<PathBuf>,
94 counter: Arc<AtomicU32>,
96}
97
98impl ChunkSink {
99 pub fn new(dir: PathBuf) -> Result<Self> {
108 std::fs::create_dir_all(&dir).map_err(|source| TilesError::CreateChunkDir {
109 path: dir.clone(),
110 source,
111 })?;
112 Ok(Self {
113 dir,
114 chunk_paths: Vec::new(),
115 counter: Arc::new(AtomicU32::new(0)),
116 })
117 }
118
119 pub const fn with_counter(dir: PathBuf, counter: Arc<AtomicU32>) -> Self {
125 Self {
126 dir,
127 chunk_paths: Vec::new(),
128 counter,
129 }
130 }
131
132 pub fn write_chunk(&mut self, entries: &[SortEntry]) -> Result<PathBuf> {
142 let id = self.counter.fetch_add(1, AtomicOrdering::Relaxed);
143 let path = self.dir.join(format!("chunk_{id:06}.{RUN_EXTENSION}"));
144 write_run(&path, entries)?;
145 self.chunk_paths.push(path.clone());
146 Ok(path)
147 }
148
149 #[must_use]
151 pub fn chunk_paths(&self) -> &[PathBuf] {
152 &self.chunk_paths
153 }
154
155 #[must_use]
157 pub const fn chunk_count(&self) -> usize {
158 self.chunk_paths.len()
159 }
160
161 #[must_use]
163 pub fn into_chunk_paths(self) -> Vec<PathBuf> {
164 self.chunk_paths
165 }
166
167 pub fn cleanup(&self) -> Result<()> {
173 for path in &self.chunk_paths {
174 if path.exists() {
175 std::fs::remove_file(path).map_err(io_error("remove", path))?;
176 }
177 }
178 Ok(())
179 }
180}
181
182fn write_run(path: &Path, entries: &[SortEntry]) -> Result<()> {
184 let file = File::create(path).map_err(io_error("create", path))?;
185 let mut out = BufWriter::with_capacity(WRITE_BUF_SIZE, file);
186 let write = |out: &mut BufWriter<File>, bytes: &[u8]| {
187 out.write_all(bytes).map_err(io_error("write", path))
188 };
189
190 let mut header = [0u8; HEADER_LEN];
191 header[..4].copy_from_slice(&MAGIC);
192 header[4] = LAYOUT;
193 write(&mut out, &header)?;
194
195 let mut compressor =
196 zstd::bulk::Compressor::new(ZSTD_LEVEL).map_err(io_error("compress", path))?;
197 let mut encoder = BlockEncoder::new();
198 let mut raw = Vec::new();
199 let mut packed = Vec::new();
200 let (mut blocks, mut total) = (0u64, 0u64);
201
202 let mut close_block = |encoder: &mut BlockEncoder,
203 out: &mut BufWriter<File>,
204 blocks: &mut u64,
205 total: &mut u64|
206 -> Result<()> {
207 raw.clear();
208 let count = encoder.finish_into(&mut raw);
209 if raw.len() > MAX_RAW_BLOCK {
210 return Err(SortRunError::BadHeader {
211 path: path.to_path_buf(),
212 at: *blocks,
213 what: "an entry is too large for a block",
214 }
215 .into());
216 }
217 packed.clear();
218 packed.reserve(zstd::zstd_safe::compress_bound(raw.len()));
219 compressor
220 .compress_to_buffer(&raw, &mut packed)
221 .map_err(io_error("compress", path))?;
222 let mut head = [0u8; 1 + BLOCK_HEADER_LEN];
223 head[0] = KIND_BLOCK;
224 head[1..5].copy_from_slice(&(raw.len() as u32).to_le_bytes());
225 head[5..9].copy_from_slice(&(packed.len() as u32).to_le_bytes());
226 head[9..13].copy_from_slice(&count.to_le_bytes());
227 head[13..21].copy_from_slice(&xxh3_64(&packed).to_le_bytes());
228 write(out, &head)?;
229 write(out, &packed)?;
230 *blocks += 1;
231 *total += u64::from(count);
232 Ok(())
233 };
234
235 for entry in entries {
236 encoder
237 .push(entry)
238 .map_err(|source| SortRunError::BadBlock {
239 path: path.to_path_buf(),
240 block: blocks,
241 source,
242 })?;
243 if encoder.raw_len() >= BLOCK_RAW_TARGET {
244 close_block(&mut encoder, &mut out, &mut blocks, &mut total)?;
245 }
246 }
247 if !encoder.is_empty() {
248 close_block(&mut encoder, &mut out, &mut blocks, &mut total)?;
249 }
250
251 let mut end = [0u8; 1 + END_LEN];
252 end[0] = KIND_END;
253 end[1..9].copy_from_slice(&total.to_le_bytes());
254 end[9..17].copy_from_slice(&blocks.to_le_bytes());
255 let checksum = xxh3_64(&end[..17]);
256 end[17..25].copy_from_slice(&checksum.to_le_bytes());
257 write(&mut out, &end)?;
258 out.flush().map_err(io_error("write", path))?;
259 Ok(())
260}
261
262pub struct SortBuffer {
265 entries: Vec<SortEntry>,
266 approx_bytes: usize,
268 max_bytes: usize,
270}
271
272impl SortBuffer {
273 #[must_use]
275 pub fn new() -> Self {
276 Self::with_max_bytes(DEFAULT_CHUNK_BYTES)
277 }
278
279 #[must_use]
281 pub fn with_max_bytes(max_bytes: usize) -> Self {
282 Self {
283 entries: Vec::with_capacity(1024),
284 approx_bytes: 0,
285 max_bytes,
286 }
287 }
288
289 #[inline]
293 pub fn push(&mut self, entry: SortEntry) -> bool {
294 self.approx_bytes +=
296 58 + entry.feature.properties.len() * 24 + entry.feature.geometry.len() * 4;
297 self.entries.push(entry);
298 self.approx_bytes >= self.max_bytes
299 }
300
301 pub fn flush(&mut self, sink: &mut ChunkSink) -> Result<()> {
309 if self.entries.is_empty() {
310 return Ok(());
311 }
312 self.entries.sort_unstable();
313 sink.write_chunk(&self.entries)?;
314 self.entries.clear();
315 self.approx_bytes = 0;
316 Ok(())
317 }
318
319 #[must_use]
321 pub const fn is_empty(&self) -> bool {
322 self.entries.is_empty()
323 }
324
325 #[must_use]
327 pub const fn len(&self) -> usize {
328 self.entries.len()
329 }
330}
331
332impl Default for SortBuffer {
333 fn default() -> Self {
334 Self::new()
335 }
336}
337
338pub fn read_chunk(path: &Path) -> Result<Vec<SortEntry>> {
348 let mut reader = ChunkReader::open(path)?;
349 let mut entries = Vec::new();
350 while let Some(entry) = reader.take()? {
351 entries.push(entry);
352 }
353 Ok(entries)
354}
355
356pub struct ChunkReader {
361 path: PathBuf,
362 file: File,
363 decoder: BlockDecoder,
364 peeked: Option<SortEntry>,
366 exhausted: bool,
368 position: u64,
370 blocks: u64,
371 entries: u64,
372 reclaim: bool,
375 reclaimed: u64,
377}
378
379impl ChunkReader {
380 pub fn open(path: &Path) -> Result<Self> {
387 Self::open_with(path, false)
388 }
389
390 pub fn open_reclaiming(path: &Path) -> Result<Self> {
401 Self::open_with(path, true)
402 }
403
404 fn open_with(path: &Path, reclaim: bool) -> Result<Self> {
405 let file = OpenOptions::new()
406 .read(true)
407 .write(reclaim)
408 .open(path)
409 .map_err(io_error("open", path))?;
410 let mut reader = Self {
411 path: path.to_path_buf(),
412 file,
413 decoder: BlockDecoder::empty(),
414 peeked: None,
415 exhausted: false,
416 position: 0,
417 blocks: 0,
418 entries: 0,
419 reclaim,
420 reclaimed: 0,
421 };
422 reader.read_header()?;
423 reader.advance()?;
424 Ok(reader)
425 }
426
427 #[inline]
429 #[must_use]
430 pub const fn peek(&self) -> Option<&SortEntry> {
431 self.peeked.as_ref()
432 }
433
434 pub fn take(&mut self) -> Result<Option<SortEntry>> {
440 let entry = self.peeked.take();
441 if entry.is_some() {
442 self.advance()?;
443 }
444 Ok(entry)
445 }
446
447 #[inline]
449 #[must_use]
450 pub const fn is_exhausted(&self) -> bool {
451 self.exhausted
452 }
453
454 fn fill(&mut self, buf: &mut [u8]) -> Result<bool> {
455 let mut done = 0;
456 while done < buf.len() {
457 match self.file.read(&mut buf[done..]) {
458 Ok(0) => break,
459 Ok(n) => done += n,
460 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
461 Err(source) => return Err(io_error("read", &self.path)(source)),
462 }
463 }
464 self.position += done as u64;
465 if done == buf.len() {
466 Ok(true)
467 } else if done == 0 {
468 Ok(false)
469 } else {
470 Err(self.truncated())
471 }
472 }
473
474 fn truncated(&self) -> TilesError {
475 SortRunError::Truncated {
476 path: self.path.clone(),
477 at: self.position,
478 }
479 .into()
480 }
481
482 fn read_header(&mut self) -> Result<()> {
483 let mut header = [0u8; HEADER_LEN];
484 if !self.fill(&mut header)? {
485 return Err(SortRunError::NotARun {
486 path: self.path.clone(),
487 }
488 .into());
489 }
490 if header[..4] != MAGIC {
491 return Err(SortRunError::NotARun {
492 path: self.path.clone(),
493 }
494 .into());
495 }
496 if header[4] != LAYOUT {
497 return Err(SortRunError::UnsupportedLayout {
498 path: self.path.clone(),
499 found: header[4],
500 expected: LAYOUT,
501 }
502 .into());
503 }
504 Ok(())
505 }
506
507 fn advance(&mut self) -> Result<()> {
510 if self.exhausted {
511 return Ok(());
512 }
513 if self.decoder.remaining() == 0 && !self.load_block()? {
514 return Ok(());
515 }
516 let entry = self
517 .decoder
518 .next_entry()
519 .map_err(|source| SortRunError::BadBlock {
520 path: self.path.clone(),
521 block: self.blocks.saturating_sub(1),
522 source,
523 })?;
524 if self.decoder.remaining() == 0 {
525 self.decoder
526 .check_complete()
527 .map_err(|source| SortRunError::BadBlock {
528 path: self.path.clone(),
529 block: self.blocks.saturating_sub(1),
530 source,
531 })?;
532 }
533 self.peeked = Some(entry);
534 Ok(())
535 }
536
537 fn load_block(&mut self) -> Result<bool> {
539 loop {
540 let at = self.position;
541 let mut kind = [0u8; 1];
542 if !self.fill(&mut kind)? {
543 return Err(self.truncated());
544 }
545 match kind[0] {
546 KIND_END => {
547 self.read_end(at)?;
548 return Ok(false);
549 }
550 KIND_BLOCK => {}
551 _ => {
552 return Err(SortRunError::BadHeader {
553 path: self.path.clone(),
554 at,
555 what: "unknown record kind",
556 }
557 .into());
558 }
559 }
560 let mut head = [0u8; BLOCK_HEADER_LEN];
561 if !self.fill(&mut head)? {
562 return Err(self.truncated());
563 }
564 let raw_len = u32::from_le_bytes([head[0], head[1], head[2], head[3]]) as usize;
565 let packed_len = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize;
566 let count = u32::from_le_bytes([head[8], head[9], head[10], head[11]]);
567 let checksum = u64::from_le_bytes([
568 head[12], head[13], head[14], head[15], head[16], head[17], head[18], head[19],
569 ]);
570 if raw_len > MAX_RAW_BLOCK || packed_len > zstd::zstd_safe::compress_bound(raw_len) {
571 return Err(SortRunError::BadHeader {
572 path: self.path.clone(),
573 at,
574 what: "block size out of range",
575 }
576 .into());
577 }
578 let path = self.path.clone();
579 let block = self.blocks;
580 let produced = PACKED.with(|packed_cell| -> Result<usize> {
581 let mut packed = packed_cell.borrow_mut();
582 packed.resize(packed_len, 0);
583 if !self.fill(&mut packed)? && packed_len != 0 {
584 return Err(self.truncated());
585 }
586 if xxh3_64(&packed) != checksum {
587 return Err(SortRunError::BadChecksum {
588 path: path.clone(),
589 block,
590 at,
591 }
592 .into());
593 }
594 let buffer = self.decoder.buffer();
595 buffer.clear();
596 buffer.reserve(raw_len);
597 DECOMPRESSOR
598 .with(|cell| -> std::io::Result<usize> {
599 let mut slot = cell.borrow_mut();
600 if slot.is_none() {
601 *slot = Some(zstd::bulk::Decompressor::new()?);
602 }
603 let decompressor = slot
604 .as_mut()
605 .ok_or_else(|| std::io::Error::other("no decompressor"))?;
606 decompressor.decompress_to_buffer(&packed[..], buffer)
607 })
608 .map_err(|source| SortRunError::Io {
609 op: "decompress",
610 path: path.clone(),
611 source,
612 })
613 .map_err(TilesError::from)
614 })?;
615 if produced != raw_len {
616 return Err(SortRunError::BadHeader {
617 path: self.path.clone(),
618 at,
619 what: "block decompresses to another size",
620 }
621 .into());
622 }
623 self.decoder
624 .load(count)
625 .map_err(|source| SortRunError::BadBlock {
626 path: self.path.clone(),
627 block,
628 source,
629 })?;
630 self.blocks += 1;
631 self.entries += u64::from(count);
632 self.release_read_bytes();
633 if count == 0 {
634 continue;
635 }
636 return Ok(true);
637 }
638 }
639
640 fn release_read_bytes(&mut self) {
643 if !self.reclaim {
644 return;
645 }
646 if let Some(upto) = reclaim::punch_whole_blocks(&self.file, self.reclaimed, self.position) {
647 self.reclaimed = upto;
648 }
649 }
650
651 fn read_end(&mut self, at: u64) -> Result<()> {
652 let mut end = [0u8; END_LEN];
653 if !self.fill(&mut end)? {
654 return Err(self.truncated());
655 }
656 let mut signed = [0u8; 17];
657 signed[0] = KIND_END;
658 signed[1..].copy_from_slice(&end[..16]);
659 let checksum = u64::from_le_bytes([
660 end[16], end[17], end[18], end[19], end[20], end[21], end[22], end[23],
661 ]);
662 if xxh3_64(&signed) != checksum {
663 return Err(SortRunError::BadHeader {
664 path: self.path.clone(),
665 at,
666 what: "end marker fails its checksum",
667 }
668 .into());
669 }
670 let entries = u64::from_le_bytes([
671 end[0], end[1], end[2], end[3], end[4], end[5], end[6], end[7],
672 ]);
673 let blocks = u64::from_le_bytes([
674 end[8], end[9], end[10], end[11], end[12], end[13], end[14], end[15],
675 ]);
676 if entries != self.entries || blocks != self.blocks {
677 return Err(SortRunError::CountMismatch {
678 path: self.path.clone(),
679 expected: entries,
680 found: self.entries,
681 }
682 .into());
683 }
684 let mut extra = [0u8; 1];
685 if self.fill(&mut extra)? {
686 return Err(SortRunError::TrailingBytes {
687 path: self.path.clone(),
688 }
689 .into());
690 }
691 self.exhausted = true;
692 if self.reclaim {
693 std::fs::remove_file(&self.path).map_err(io_error("remove", &self.path))?;
694 }
695 Ok(())
696 }
697}
698
699#[cfg(test)]
700mod tests {
701 use super::*;
702
703 use std::sync::Arc;
704
705 use geolith::layer::Layer;
706 use geolith::tile::feature::{GeomType, TileFeature};
707
708 fn make_entry(key: u64) -> SortEntry {
709 SortEntry::new(
710 key,
711 TileFeature {
712 layer: Layer::Buildings,
713 id: key,
714 geom_type: GeomType::Polygon,
715 geometry: vec![9, 0, 0],
716 properties: Arc::new(vec![]),
717 sort_key: 0,
718 },
719 )
720 }
721
722 #[test]
723 fn roundtrip_chunk_write_read() {
724 let dir = tempfile::tempdir().expect("tmpdir");
725 let mut sink = ChunkSink::new(dir.path().to_path_buf()).expect("sink");
726
727 let mut entries: Vec<SortEntry> = (0..100).rev().map(make_entry).collect();
728 entries.sort_unstable();
729 sink.write_chunk(&entries).expect("write");
730
731 let read_back = read_chunk(&sink.chunk_paths()[0]).expect("read");
732 assert_eq!(read_back.len(), 100);
733 for window in read_back.windows(2) {
735 assert!(window[0].key <= window[1].key);
736 }
737 }
738
739 #[test]
740 fn sort_buffer_flush_threshold() {
741 let mut buf = SortBuffer::with_max_bytes(100);
742 let mut full = false;
743 for i in 0..1000 {
744 if buf.push(make_entry(i)) {
745 full = true;
746 break;
747 }
748 }
749 assert!(full, "buffer should fill up");
750 assert!(!buf.is_empty());
751 }
752
753 #[test]
754 fn chunk_reader_streaming() {
755 let dir = tempfile::tempdir().expect("tmpdir");
756 let mut sink = ChunkSink::new(dir.path().to_path_buf()).expect("sink");
757
758 let entries: Vec<SortEntry> = (0..50).map(make_entry).collect();
759 sink.write_chunk(&entries).expect("write");
760
761 let mut reader = ChunkReader::open(&sink.chunk_paths()[0]).expect("open");
762 let mut count = 0;
763 while !reader.is_exhausted() {
764 let entry = reader.take().expect("take");
765 if entry.is_some() {
766 count += 1;
767 }
768 }
769 assert_eq!(count, 50);
770 }
771}