use std::cell::RefCell;
use std::fs::{File, OpenOptions};
use std::io::{BufWriter, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering as AtomicOrdering};
use xxhash_rust::xxh3::xxh3_64;
use crate::sort::block::{BlockDecoder, BlockEncoder};
use crate::sort::entry::SortEntry;
use crate::sort::error::SortRunError;
use crate::sort::reclaim;
use crate::tiles_error::{Result, TilesError};
const DEFAULT_CHUNK_BYTES: usize = 256 * 1024 * 1024;
const WRITE_BUF_SIZE: usize = 8 * 1024 * 1024;
pub const RUN_EXTENSION: &str = "run";
const MAGIC: [u8; 4] = *b"GLRN";
const LAYOUT: u8 = 1;
const HEADER_LEN: usize = 8;
const KIND_BLOCK: u8 = 1;
const KIND_END: u8 = 0xFF;
const BLOCK_HEADER_LEN: usize = 20;
const END_LEN: usize = 24;
const MAX_RAW_BLOCK: usize = 256 * 1024 * 1024;
const BLOCK_RAW_TARGET: usize = 512 * 1024;
const ZSTD_LEVEL: i32 = 3;
thread_local! {
static DECOMPRESSOR: RefCell<Option<zstd::bulk::Decompressor<'static>>> =
const { RefCell::new(None) };
static PACKED: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
}
fn io_error(op: &'static str, path: &Path) -> impl FnOnce(std::io::Error) -> TilesError {
let path = path.to_path_buf();
move |source| SortRunError::Io { op, path, source }.into()
}
pub struct ChunkSink {
dir: PathBuf,
chunk_paths: Vec<PathBuf>,
counter: Arc<AtomicU32>,
}
impl ChunkSink {
pub fn new(dir: PathBuf) -> Result<Self> {
std::fs::create_dir_all(&dir).map_err(|source| TilesError::CreateChunkDir {
path: dir.clone(),
source,
})?;
Ok(Self {
dir,
chunk_paths: Vec::new(),
counter: Arc::new(AtomicU32::new(0)),
})
}
pub const fn with_counter(dir: PathBuf, counter: Arc<AtomicU32>) -> Self {
Self {
dir,
chunk_paths: Vec::new(),
counter,
}
}
pub fn write_chunk(&mut self, entries: &[SortEntry]) -> Result<PathBuf> {
let id = self.counter.fetch_add(1, AtomicOrdering::Relaxed);
let path = self.dir.join(format!("chunk_{id:06}.{RUN_EXTENSION}"));
write_run(&path, entries)?;
self.chunk_paths.push(path.clone());
Ok(path)
}
#[must_use]
pub fn chunk_paths(&self) -> &[PathBuf] {
&self.chunk_paths
}
#[must_use]
pub const fn chunk_count(&self) -> usize {
self.chunk_paths.len()
}
#[must_use]
pub fn into_chunk_paths(self) -> Vec<PathBuf> {
self.chunk_paths
}
pub fn cleanup(&self) -> Result<()> {
for path in &self.chunk_paths {
if path.exists() {
std::fs::remove_file(path).map_err(io_error("remove", path))?;
}
}
Ok(())
}
}
pub(crate) trait RunFile: Write {
fn make_durable(&mut self) -> std::io::Result<()>;
}
impl RunFile for BufWriter<File> {
fn make_durable(&mut self) -> std::io::Result<()> {
self.flush()?;
self.get_ref().sync_all()
}
}
fn write_run(path: &Path, entries: &[SortEntry]) -> Result<()> {
let file = File::create(path).map_err(io_error("create", path))?;
let mut out = BufWriter::with_capacity(WRITE_BUF_SIZE, file);
let result = write_run_to(&mut out, path, entries);
if result.is_err() {
drop(out);
let _ = std::fs::remove_file(path);
return result;
}
geolith::output::sync_parent_dir(path).map_err(io_error("sync the folder of", path))
}
pub(crate) fn write_run_to<W: RunFile>(
out: &mut W,
path: &Path,
entries: &[SortEntry],
) -> Result<()> {
let write = |out: &mut W, bytes: &[u8]| out.write_all(bytes).map_err(io_error("write", path));
let mut header = [0u8; HEADER_LEN];
header[..4].copy_from_slice(&MAGIC);
header[4] = LAYOUT;
write(out, &header)?;
let mut compressor =
zstd::bulk::Compressor::new(ZSTD_LEVEL).map_err(io_error("compress", path))?;
let mut encoder = BlockEncoder::new();
let mut raw = Vec::new();
let mut packed = Vec::new();
let (mut blocks, mut total) = (0u64, 0u64);
let mut close_block = |encoder: &mut BlockEncoder,
out: &mut W,
blocks: &mut u64,
total: &mut u64|
-> Result<()> {
raw.clear();
let count = encoder.finish_into(&mut raw);
if raw.len() > MAX_RAW_BLOCK {
return Err(SortRunError::BadHeader {
path: path.to_path_buf(),
at: *blocks,
what: "an entry is too large for a block",
}
.into());
}
packed.clear();
packed.reserve(zstd::zstd_safe::compress_bound(raw.len()));
compressor
.compress_to_buffer(&raw, &mut packed)
.map_err(io_error("compress", path))?;
let mut head = [0u8; 1 + BLOCK_HEADER_LEN];
head[0] = KIND_BLOCK;
head[1..5].copy_from_slice(&(raw.len() as u32).to_le_bytes());
head[5..9].copy_from_slice(&(packed.len() as u32).to_le_bytes());
head[9..13].copy_from_slice(&count.to_le_bytes());
head[13..21].copy_from_slice(&xxh3_64(&packed).to_le_bytes());
write(out, &head)?;
write(out, &packed)?;
*blocks += 1;
*total += u64::from(count);
Ok(())
};
for entry in entries {
encoder
.push(entry)
.map_err(|source| SortRunError::BadBlock {
path: path.to_path_buf(),
block: blocks,
source,
})?;
if encoder.raw_len() >= BLOCK_RAW_TARGET {
close_block(&mut encoder, out, &mut blocks, &mut total)?;
}
}
if !encoder.is_empty() {
close_block(&mut encoder, out, &mut blocks, &mut total)?;
}
let mut end = [0u8; 1 + END_LEN];
end[0] = KIND_END;
end[1..9].copy_from_slice(&total.to_le_bytes());
end[9..17].copy_from_slice(&blocks.to_le_bytes());
let checksum = xxh3_64(&end[..17]);
end[17..25].copy_from_slice(&checksum.to_le_bytes());
write(out, &end)?;
out.make_durable().map_err(io_error("sync", path))?;
Ok(())
}
pub struct SortBuffer {
entries: Vec<SortEntry>,
approx_bytes: usize,
max_bytes: usize,
}
impl SortBuffer {
#[must_use]
pub fn new() -> Self {
Self::with_max_bytes(DEFAULT_CHUNK_BYTES)
}
#[must_use]
pub fn with_max_bytes(max_bytes: usize) -> Self {
Self {
entries: Vec::with_capacity(1024),
approx_bytes: 0,
max_bytes,
}
}
#[inline]
pub fn push(&mut self, entry: SortEntry) -> bool {
self.approx_bytes +=
58 + entry.feature.properties.len() * 24 + entry.feature.geometry.len() * 4;
self.entries.push(entry);
self.approx_bytes >= self.max_bytes
}
pub fn flush(&mut self, sink: &mut ChunkSink) -> Result<()> {
if self.entries.is_empty() {
return Ok(());
}
self.entries.sort_unstable();
sink.write_chunk(&self.entries)?;
self.entries.clear();
self.approx_bytes = 0;
Ok(())
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.entries.is_empty()
}
#[must_use]
pub const fn len(&self) -> usize {
self.entries.len()
}
}
impl Default for SortBuffer {
fn default() -> Self {
Self::new()
}
}
pub fn read_chunk(path: &Path) -> Result<Vec<SortEntry>> {
let mut reader = ChunkReader::open(path)?;
let mut entries = Vec::new();
while let Some(entry) = reader.take()? {
entries.push(entry);
}
Ok(entries)
}
pub struct ChunkReader {
path: PathBuf,
file: File,
decoder: BlockDecoder,
peeked: Option<SortEntry>,
exhausted: bool,
position: u64,
blocks: u64,
entries: u64,
reclaim: bool,
reclaimed: u64,
}
impl ChunkReader {
pub fn open(path: &Path) -> Result<Self> {
Self::open_with(path, false)
}
pub fn open_reclaiming(path: &Path) -> Result<Self> {
Self::open_with(path, true)
}
fn open_with(path: &Path, reclaim: bool) -> Result<Self> {
let file = OpenOptions::new()
.read(true)
.write(reclaim)
.open(path)
.map_err(io_error("open", path))?;
let mut reader = Self {
path: path.to_path_buf(),
file,
decoder: BlockDecoder::empty(),
peeked: None,
exhausted: false,
position: 0,
blocks: 0,
entries: 0,
reclaim,
reclaimed: 0,
};
reader.read_header()?;
reader.advance()?;
Ok(reader)
}
#[inline]
#[must_use]
pub const fn peek(&self) -> Option<&SortEntry> {
self.peeked.as_ref()
}
pub fn take(&mut self) -> Result<Option<SortEntry>> {
let entry = self.peeked.take();
if entry.is_some() {
self.advance()?;
}
Ok(entry)
}
#[inline]
#[must_use]
pub const fn is_exhausted(&self) -> bool {
self.exhausted
}
fn fill(&mut self, buf: &mut [u8]) -> Result<bool> {
let mut done = 0;
while done < buf.len() {
match self.file.read(&mut buf[done..]) {
Ok(0) => break,
Ok(n) => done += n,
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
Err(source) => return Err(io_error("read", &self.path)(source)),
}
}
self.position += done as u64;
if done == buf.len() {
Ok(true)
} else if done == 0 {
Ok(false)
} else {
Err(self.truncated())
}
}
fn truncated(&self) -> TilesError {
SortRunError::Truncated {
path: self.path.clone(),
at: self.position,
}
.into()
}
fn read_header(&mut self) -> Result<()> {
let mut header = [0u8; HEADER_LEN];
if !self.fill(&mut header)? {
return Err(SortRunError::NotARun {
path: self.path.clone(),
}
.into());
}
if header[..4] != MAGIC {
return Err(SortRunError::NotARun {
path: self.path.clone(),
}
.into());
}
if header[4] != LAYOUT {
return Err(SortRunError::UnsupportedLayout {
path: self.path.clone(),
found: header[4],
expected: LAYOUT,
}
.into());
}
Ok(())
}
fn advance(&mut self) -> Result<()> {
if self.exhausted {
return Ok(());
}
if self.decoder.remaining() == 0 && !self.load_block()? {
return Ok(());
}
let entry = self
.decoder
.next_entry()
.map_err(|source| SortRunError::BadBlock {
path: self.path.clone(),
block: self.blocks.saturating_sub(1),
source,
})?;
if self.decoder.remaining() == 0 {
self.decoder
.check_complete()
.map_err(|source| SortRunError::BadBlock {
path: self.path.clone(),
block: self.blocks.saturating_sub(1),
source,
})?;
}
self.peeked = Some(entry);
Ok(())
}
fn load_block(&mut self) -> Result<bool> {
loop {
let at = self.position;
let mut kind = [0u8; 1];
if !self.fill(&mut kind)? {
return Err(self.truncated());
}
match kind[0] {
KIND_END => {
self.read_end(at)?;
return Ok(false);
}
KIND_BLOCK => {}
_ => {
return Err(SortRunError::BadHeader {
path: self.path.clone(),
at,
what: "unknown record kind",
}
.into());
}
}
let mut head = [0u8; BLOCK_HEADER_LEN];
if !self.fill(&mut head)? {
return Err(self.truncated());
}
let raw_len = u32::from_le_bytes([head[0], head[1], head[2], head[3]]) as usize;
let packed_len = u32::from_le_bytes([head[4], head[5], head[6], head[7]]) as usize;
let count = u32::from_le_bytes([head[8], head[9], head[10], head[11]]);
let checksum = u64::from_le_bytes([
head[12], head[13], head[14], head[15], head[16], head[17], head[18], head[19],
]);
if raw_len > MAX_RAW_BLOCK || packed_len > zstd::zstd_safe::compress_bound(raw_len) {
return Err(SortRunError::BadHeader {
path: self.path.clone(),
at,
what: "block size out of range",
}
.into());
}
let path = self.path.clone();
let block = self.blocks;
let produced = PACKED.with(|packed_cell| -> Result<usize> {
let mut packed = packed_cell.borrow_mut();
packed.resize(packed_len, 0);
if !self.fill(&mut packed)? && packed_len != 0 {
return Err(self.truncated());
}
if xxh3_64(&packed) != checksum {
return Err(SortRunError::BadChecksum {
path: path.clone(),
block,
at,
}
.into());
}
let buffer = self.decoder.buffer();
buffer.clear();
buffer.reserve(raw_len);
DECOMPRESSOR
.with(|cell| -> std::io::Result<usize> {
let mut slot = cell.borrow_mut();
if slot.is_none() {
*slot = Some(zstd::bulk::Decompressor::new()?);
}
let decompressor = slot
.as_mut()
.ok_or_else(|| std::io::Error::other("no decompressor"))?;
decompressor.decompress_to_buffer(&packed[..], buffer)
})
.map_err(|source| SortRunError::Io {
op: "decompress",
path: path.clone(),
source,
})
.map_err(TilesError::from)
})?;
if produced != raw_len {
return Err(SortRunError::BadHeader {
path: self.path.clone(),
at,
what: "block decompresses to another size",
}
.into());
}
self.decoder
.load(count)
.map_err(|source| SortRunError::BadBlock {
path: self.path.clone(),
block,
source,
})?;
self.blocks += 1;
self.entries += u64::from(count);
self.release_read_bytes();
if count == 0 {
continue;
}
return Ok(true);
}
}
fn release_read_bytes(&mut self) {
if !self.reclaim {
return;
}
if let Some(upto) = reclaim::punch_whole_blocks(&self.file, self.reclaimed, self.position) {
self.reclaimed = upto;
}
}
fn read_end(&mut self, at: u64) -> Result<()> {
let mut end = [0u8; END_LEN];
if !self.fill(&mut end)? {
return Err(self.truncated());
}
let mut signed = [0u8; 17];
signed[0] = KIND_END;
signed[1..].copy_from_slice(&end[..16]);
let checksum = u64::from_le_bytes([
end[16], end[17], end[18], end[19], end[20], end[21], end[22], end[23],
]);
if xxh3_64(&signed) != checksum {
return Err(SortRunError::BadHeader {
path: self.path.clone(),
at,
what: "end marker fails its checksum",
}
.into());
}
let entries = u64::from_le_bytes([
end[0], end[1], end[2], end[3], end[4], end[5], end[6], end[7],
]);
let blocks = u64::from_le_bytes([
end[8], end[9], end[10], end[11], end[12], end[13], end[14], end[15],
]);
if entries != self.entries || blocks != self.blocks {
return Err(SortRunError::CountMismatch {
path: self.path.clone(),
expected: entries,
found: self.entries,
}
.into());
}
let mut extra = [0u8; 1];
if self.fill(&mut extra)? {
return Err(SortRunError::TrailingBytes {
path: self.path.clone(),
}
.into());
}
self.exhausted = true;
if self.reclaim
&& let Err(e) = std::fs::remove_file(&self.path)
{
tracing::warn!(
"could not delete the consumed run {}: {e}",
self.path.display()
);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use geolith::layer::Layer;
use geolith::tile::feature::{GeomType, TileFeature};
fn make_entry(key: u64) -> SortEntry {
SortEntry::new(
key,
TileFeature {
layer: Layer::Buildings,
id: key,
geom_type: GeomType::Polygon,
geometry: vec![9, 0, 0],
properties: Arc::new(vec![]),
sort_key: 0,
},
)
}
#[test]
fn roundtrip_chunk_write_read() {
let dir = tempfile::tempdir().expect("tmpdir");
let mut sink = ChunkSink::new(dir.path().to_path_buf()).expect("sink");
let mut entries: Vec<SortEntry> = (0..100).rev().map(make_entry).collect();
entries.sort_unstable();
sink.write_chunk(&entries).expect("write");
let read_back = read_chunk(&sink.chunk_paths()[0]).expect("read");
assert_eq!(read_back.len(), 100);
for window in read_back.windows(2) {
assert!(window[0].key <= window[1].key);
}
}
#[test]
fn sort_buffer_flush_threshold() {
let mut buf = SortBuffer::with_max_bytes(100);
let mut full = false;
for i in 0..1000 {
if buf.push(make_entry(i)) {
full = true;
break;
}
}
assert!(full, "buffer should fill up");
assert!(!buf.is_empty());
}
#[test]
fn chunk_reader_streaming() {
let dir = tempfile::tempdir().expect("tmpdir");
let mut sink = ChunkSink::new(dir.path().to_path_buf()).expect("sink");
let entries: Vec<SortEntry> = (0..50).map(make_entry).collect();
sink.write_chunk(&entries).expect("write");
let mut reader = ChunkReader::open(&sink.chunk_paths()[0]).expect("open");
let mut count = 0;
while !reader.is_exhausted() {
let entry = reader.take().expect("take");
if entry.is_some() {
count += 1;
}
}
assert_eq!(count, 50);
}
struct FailAfter {
limit: usize,
taken: usize,
sync_fails: bool,
}
impl Write for FailAfter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let room = self.limit - self.taken;
if room == 0 && !buf.is_empty() {
return Err(std::io::Error::from_raw_os_error(28));
}
let n = room.min(buf.len());
self.taken += n;
Ok(n)
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl RunFile for FailAfter {
fn make_durable(&mut self) -> std::io::Result<()> {
if self.sync_fails {
Err(std::io::Error::from_raw_os_error(5))
} else {
Ok(())
}
}
}
fn noisy_entries(count: u64) -> Vec<SortEntry> {
(0..count)
.map(|i| {
let mut x = i.wrapping_mul(0x9E37_79B9_7F4A_7C15);
x ^= x >> 29;
make_entry_with(
i,
(0..16).map(|j| (x.rotate_left(j) & 0xFFF) as u32).collect(),
)
})
.collect()
}
fn make_entry_with(key: u64, geometry: Vec<u32>) -> SortEntry {
SortEntry::new(
key,
TileFeature {
layer: Layer::Buildings,
id: key.wrapping_mul(0xBF58_476D_1CE4_E5B9),
geom_type: GeomType::Polygon,
geometry,
properties: Arc::new(vec![]),
sort_key: 0,
},
)
}
#[test]
fn a_run_whose_write_fails_at_any_byte_is_an_error_that_names_the_file() {
let entries = noisy_entries(30_000);
let path = Path::new("/sort/chunk_000007.run");
let mut whole = FailAfter {
limit: usize::MAX,
taken: 0,
sync_fails: false,
};
write_run_to(&mut whole, path, &entries).expect("room enough");
let size = whole.taken;
assert!(
size > BLOCK_RAW_TARGET,
"the run has several blocks: {size}"
);
let mut limits: Vec<usize> = vec![0, 1, 7, 8, 9, 28, 29, size / 3, size / 2, size - 26];
limits.extend((1..=24).map(|k| size - k));
limits.extend((1..60).map(|k| k * size / 61));
for limit in limits {
let mut sink = FailAfter {
limit,
taken: 0,
sync_fails: false,
};
let err = write_run_to(&mut sink, path, &entries).expect_err(&format!(
"a disk full after {limit} of {size} bytes must fail"
));
let text = geolith::error::report(&err);
assert!(text.contains("chunk_000007.run"), "{text}");
assert!(text.contains("os error 28"), "{text}");
assert!(
matches!(
err,
TilesError::SortRun(SortRunError::Io { op: "write", .. })
),
"{text}"
);
}
let mut exact = FailAfter {
limit: size,
taken: 0,
sync_fails: false,
};
write_run_to(&mut exact, path, &entries).expect("exactly enough room");
}
#[test]
fn a_failed_sync_fails_the_run() {
let entries = noisy_entries(100);
let path = Path::new("/sort/chunk_000001.run");
let mut sink = FailAfter {
limit: usize::MAX,
taken: 0,
sync_fails: true,
};
let err = write_run_to(&mut sink, path, &entries).expect_err("sync fails");
let text = geolith::error::report(&err);
assert!(text.contains("sync /sort/chunk_000001.run"), "{text}");
assert!(text.contains("os error 5"), "{text}");
}
#[test]
fn a_run_that_fails_on_disk_leaves_no_file_behind() {
let dir = tempfile::tempdir().expect("tmpdir");
let entries = vec![make_entry_with(9, vec![1]), make_entry_with(3, vec![1])];
let mut sink = ChunkSink::new(dir.path().to_path_buf()).expect("sink");
assert!(sink.write_chunk(&entries).is_err());
let left: Vec<_> = std::fs::read_dir(dir.path())
.expect("read")
.map(|e| e.expect("entry").path())
.collect();
assert!(left.is_empty(), "a failed run was left behind: {left:?}");
assert_eq!(sink.chunk_count(), 0, "a failed run is not listed");
}
}