crates/kleene-index/src/store.rs
//! Where a set's indexes live: the directory `<set>.kix` beside it, holding a copy of the
//! set's root hash and, per index, one Arrow IPC file per column (buffers 64-byte aligned,
//! so an index is read in place from its mapping) and a `.done` mark written last. A directory whose hash differs from the set's is
//! removed before anything is read from it. A set without a root hash gets no directory:
//! its indexes are built in memory each time.
use std::path::{Path, PathBuf};
use std::sync::Arc;
use arrow_array::{ArrayRef, RecordBatch, UInt32Array, UInt64Array};
use arrow_buffer::ScalarBuffer;
use graphar::mapped::{MappedChunk, write_ipc};
use crate::error::{Result, bad};
/// The file in a set (and in its index directory) that holds the set's root hash.
const ROOT: &str = "root";
/// A set's index directory, checked against the set's root hash.
#[derive(Clone, Debug)]
pub struct Store {
dir: Option<PathBuf>,
root: Option<Vec<u8>>,
}
impl Store {
/// The directory `<set>.kix` beside `set`.
pub fn beside(set: impl AsRef<Path>) -> Result<Store> {
let set = set.as_ref();
let mut name = set
.file_name()
.ok_or_else(|| bad(format!("{} names no directory", set.display())))?
.to_os_string();
name.push(".kix");
Store::at(set, set.with_file_name(name))
}
/// The index directory `dir` for `set`. A stale directory (another root hash, or none)
/// is removed and made again; nothing is written when the set has no root hash.
pub fn at(set: impl AsRef<Path>, dir: impl Into<PathBuf>) -> Result<Store> {
let root = match std::fs::read(set.as_ref().join(ROOT)) {
Ok(r) if !r.is_empty() => r,
Ok(_) => return Ok(Store::memory()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Store::memory()),
Err(e) => return Err(e.into()),
};
Store::keyed(dir, root)
}
/// The directory `dir` keyed by `key` where [`Store::at`] keys it by a set's root hash
/// (a version of a set that has no root file: an Iceberg table's snapshot id, say): a
/// directory kept under another key is removed and made again. An empty key keeps
/// nothing.
pub fn keyed(dir: impl Into<PathBuf>, key: impl Into<Vec<u8>>) -> Result<Store> {
let dir = dir.into();
let root: Vec<u8> = key.into();
if root.is_empty() {
return Ok(Store::memory());
}
let kept = std::fs::read(dir.join(ROOT)).ok();
if kept.as_deref() != Some(&root[..]) {
match std::fs::remove_dir_all(&dir) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
std::fs::create_dir_all(&dir)?;
let tmp = dir.join(".root.tmp");
std::fs::write(&tmp, &root)?;
std::fs::rename(&tmp, dir.join(ROOT))?;
}
Ok(Store {
dir: Some(dir),
root: Some(root),
})
}
/// No directory: indexes are built in memory and never stored.
pub fn memory() -> Store {
Store {
dir: None,
root: None,
}
}
/// The index directory, if indexes are stored.
pub fn dir(&self) -> Option<&Path> {
self.dir.as_deref()
}
/// The set's root hash the directory is keyed by.
pub fn root(&self) -> Option<&[u8]> {
self.root.as_deref()
}
/// The stored index `name`, if it was stored whole.
pub fn load(&self, name: &str) -> Result<Option<Stored>> {
let Some(dir) = &self.dir else {
return Ok(None);
};
if !dir.join(format!("{name}.done")).exists() {
return Ok(None);
}
Ok(Some(Stored {
dir: dir.clone(),
name: name.to_string(),
}))
}
/// Store index `name` as named columns (any lengths), each its own file, then the mark
/// that makes it whole. Without a directory this does nothing.
pub fn save(&self, name: &str, columns: Vec<(&str, ArrayRef)>) -> Result<()> {
let Some(dir) = &self.dir else {
return Ok(());
};
for (col, array) in columns {
let batch =
RecordBatch::try_from_iter([(col, array)]).map_err(|e| bad(e.to_string()))?;
write_ipc(dir.join(format!("{name}.{col}.arrow")), &batch)?;
}
let tmp = dir.join(format!(".{name}.done.tmp"));
std::fs::write(&tmp, b"")?;
std::fs::rename(&tmp, dir.join(format!("{name}.done")))?;
Ok(())
}
}
/// One stored index: its columns are mapped when asked for.
pub struct Stored {
dir: PathBuf,
name: String,
}
impl Stored {
fn chunk(&self, col: &str) -> Result<MappedChunk> {
Ok(MappedChunk::open(
self.dir.join(format!("{}.{col}.arrow", self.name)),
)?)
}
/// A `u32` column, sharing the mapping.
pub fn u32(&self, col: &str) -> Result<ScalarBuffer<u32>> {
Ok(self.chunk(col)?.shared::<u32>(col)?)
}
/// A `u64` column, sharing the mapping.
pub fn u64(&self, col: &str) -> Result<ScalarBuffer<u64>> {
Ok(self.chunk(col)?.shared::<u64>(col)?)
}
/// Column `col` as it was saved (any Arrow type), its buffers shared with the mapping.
pub fn array(&self, col: &str) -> Result<ArrayRef> {
Ok(self.chunk(col)?.batch().column(0).clone())
}
/// Whether the index has column `col`.
pub fn has(&self, col: &str) -> bool {
self.dir.join(format!("{}.{col}.arrow", self.name)).exists()
}
}
/// A `u32` column for [`Store::save`].
pub(crate) fn col32(v: impl Into<ScalarBuffer<u32>>) -> ArrayRef {
Arc::new(UInt32Array::new(v.into(), None))
}
/// A `u64` column for [`Store::save`].
pub(crate) fn col64(v: impl Into<ScalarBuffer<u64>>) -> ArrayRef {
Arc::new(UInt64Array::new(v.into(), None))
}