use core::ops::Bound;
use rand::rng as thread_rng;
use crate::flatdir::hca::ThreadRngSource;
use crate::flatdir::layout::{ROOT_PATH_SEGMENT, data_region};
use crate::flatdir::ops;
use crate::key::validate_dir;
use crate::rawkv::{AsyncRawKv, RawKv};
use crate::stream::KvPair;
pub use crate::flatdir::error::FlatError;
pub struct FlatEngine<R: RawKv> {
raw: R,
}
impl<R: RawKv> FlatEngine<R> {
pub fn new(raw: R) -> Self {
Self { raw }
}
pub fn raw(&self) -> &R {
&self.raw
}
pub fn raw_mut(&mut self) -> &mut R {
&mut self.raw
}
fn layer_path<'a>(dir: &[&'a [u8]]) -> Vec<&'a [u8]> {
let mut v: Vec<&'a [u8]> = Vec::with_capacity(dir.len() + 1);
v.push(ROOT_PATH_SEGMENT.as_bytes());
v.extend_from_slice(dir);
v
}
pub fn prefix_of(&self, dir: &[&[u8]]) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
validate_dir(dir).map_err(FlatError::Key)?;
ops::check_version_read(&self.raw)?;
ops::find(&self.raw, &Self::layer_path(dir))
}
pub fn allocate_dir(&mut self, dir: &[&[u8]]) -> Result<Vec<u8>, FlatError<R::Error>> {
validate_dir(dir).map_err(FlatError::Key)?;
let mut rng = thread_rng();
ops::create_or_open(&mut self.raw, &Self::layer_path(dir), true, &mut rng)
.map(|p| p.expect("create_or_open with creation returns Some"))
}
pub fn get(&self, dir: &[&[u8]], key: &[u8]) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
let Some(prefix) = self.prefix_of(dir)? else {
return Ok(None);
};
let mut raw_key = prefix;
raw_key.extend_from_slice(key);
Ok(self.raw.get(&raw_key)?)
}
pub fn scan(
&self,
dir: &[&[u8]],
start: Bound<&[u8]>,
end: Bound<&[u8]>,
forward: bool,
) -> Result<Vec<KvPair>, FlatError<R::Error>> {
let Some(prefix) = self.prefix_of(dir)? else {
return Ok(Vec::new());
};
let owned = map_bounds(&prefix, start, end);
if raw_range_empty(&owned.0, &owned.1) {
return Ok(Vec::new());
}
let (rs, re) = bounds_ref(&owned);
let rows = self.raw.scan(rs, re, forward)?;
let plen = prefix.len();
Ok(rows
.into_iter()
.map(|pair| KvPair {
key: pair.key[plen..].to_vec(),
value: pair.value,
})
.collect())
}
pub fn data_bounds(
&self,
dir: &[&[u8]],
start: Bound<&[u8]>,
end: Bound<&[u8]>,
) -> Result<Option<DataBounds>, FlatError<R::Error>> {
let Some(prefix) = self.prefix_of(dir)? else {
return Ok(None);
};
Ok(map_data_bounds(&prefix, start, end))
}
pub fn set(
&mut self,
dir: &[&[u8]],
key: &[u8],
value: &[u8],
) -> Result<(), FlatError<R::Error>> {
let prefix = self.allocate_dir(dir)?;
let mut raw_key = prefix;
raw_key.extend_from_slice(key);
self.raw.insert(&raw_key, value)?;
Ok(())
}
pub fn delete(&mut self, dir: &[&[u8]], key: &[u8]) -> Result<(), FlatError<R::Error>> {
let Some(prefix) = self.prefix_of(dir)? else {
return Ok(());
};
let mut raw_key = prefix;
raw_key.extend_from_slice(key);
self.raw.delete(&raw_key)?;
Ok(())
}
pub fn clear_range(
&mut self,
dir: &[&[u8]],
start: Bound<&[u8]>,
end: Bound<&[u8]>,
) -> Result<(), FlatError<R::Error>> {
let Some(prefix) = self.prefix_of(dir)? else {
return Ok(());
};
let owned = map_bounds(&prefix, start, end);
if raw_range_empty(&owned.0, &owned.1) {
return Ok(());
}
let (rs, re) = bounds_ref(&owned);
self.raw.clear_range(rs, re)?;
Ok(())
}
pub fn list_dirs(&self, dir: &[&[u8]]) -> Result<Vec<Vec<u8>>, FlatError<R::Error>> {
validate_dir(dir).map_err(FlatError::Key)?;
ops::check_version_read(&self.raw)?;
let Some(prefix) = ops::find(&self.raw, &Self::layer_path(dir))? else {
return Ok(Vec::new());
};
let names = ops::list_children(&self.raw, &prefix)?;
Ok(names.into_iter().map(|s| s.into_bytes()).collect())
}
pub fn dir_exists(&self, dir: &[&[u8]]) -> Result<bool, FlatError<R::Error>> {
validate_dir(dir).map_err(FlatError::Key)?;
ops::check_version_read(&self.raw)?;
Ok(ops::find(&self.raw, &Self::layer_path(dir))?.is_some())
}
pub fn remove_dir(&mut self, dir: &[&[u8]]) -> Result<bool, FlatError<R::Error>> {
validate_dir(dir).map_err(FlatError::Key)?;
if dir.is_empty() {
return Err(FlatError::Key(crate::key::KeyError::RootNotRemovable));
}
ops::check_version_read(&self.raw)?;
ops::remove_dir(&mut self.raw, &Self::layer_path(dir))
}
}
pub struct AsyncFlatEngine<R: AsyncRawKv> {
raw: R,
}
impl<R: AsyncRawKv> AsyncFlatEngine<R> {
pub fn new(raw: R) -> Self {
Self { raw }
}
pub fn raw(&self) -> &R {
&self.raw
}
pub fn raw_mut(&mut self) -> &mut R {
&mut self.raw
}
pub fn into_raw(self) -> R {
self.raw
}
fn layer_path<'a>(dir: &[&'a [u8]]) -> Vec<&'a [u8]> {
let mut v: Vec<&'a [u8]> = Vec::with_capacity(dir.len() + 1);
v.push(ROOT_PATH_SEGMENT.as_bytes());
v.extend_from_slice(dir);
v
}
pub async fn prefix_of(&self, dir: &[&[u8]]) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
validate_dir(dir).map_err(FlatError::Key)?;
ops::check_version_read_async(&self.raw).await?;
let path = Self::layer_path(dir);
ops::find_async(&self.raw, &path).await
}
pub async fn allocate_dir(&mut self, dir: &[&[u8]]) -> Result<Vec<u8>, FlatError<R::Error>> {
validate_dir(dir).map_err(FlatError::Key)?;
let path = Self::layer_path(dir);
let mut rng = ThreadRngSource;
ops::create_or_open_async(&mut self.raw, &path, true, &mut rng)
.await
.map(|p| p.expect("create_or_open_async with creation returns Some"))
}
pub async fn get(
&self,
dir: &[&[u8]],
key: &[u8],
) -> Result<Option<Vec<u8>>, FlatError<R::Error>> {
let Some(prefix) = self.prefix_of(dir).await? else {
return Ok(None);
};
let mut raw_key = prefix;
raw_key.extend_from_slice(key);
Ok(self.raw.get(&raw_key).await?)
}
pub async fn exists(&self, dir: &[&[u8]], key: &[u8]) -> Result<bool, FlatError<R::Error>> {
let Some(prefix) = self.prefix_of(dir).await? else {
return Ok(false);
};
let mut raw_key = prefix;
raw_key.extend_from_slice(key);
Ok(self.raw.exists(&raw_key).await?)
}
pub async fn scan(
&self,
dir: &[&[u8]],
start: Bound<&[u8]>,
end: Bound<&[u8]>,
forward: bool,
) -> Result<Vec<KvPair>, FlatError<R::Error>> {
let Some(bounds) = self.data_bounds(dir, start, end).await? else {
return Ok(Vec::new());
};
let owned = (bounds.start, bounds.end);
let (rs, re) = bounds_ref(&owned);
let rows = self.raw.scan(rs, re, forward, None).await?;
let plen = bounds.prefix.len();
Ok(rows
.into_iter()
.map(|pair| KvPair {
key: pair.key[plen..].to_vec(),
value: pair.value,
})
.collect())
}
pub async fn data_bounds(
&self,
dir: &[&[u8]],
start: Bound<&[u8]>,
end: Bound<&[u8]>,
) -> Result<Option<DataBounds>, FlatError<R::Error>> {
let Some(prefix) = self.prefix_of(dir).await? else {
return Ok(None);
};
Ok(map_data_bounds(&prefix, start, end))
}
pub async fn set(
&mut self,
dir: &[&[u8]],
key: &[u8],
value: &[u8],
) -> Result<(), FlatError<R::Error>> {
let prefix = self.allocate_dir(dir).await?;
let mut raw_key = prefix;
raw_key.extend_from_slice(key);
self.raw.insert(&raw_key, value).await?;
Ok(())
}
pub async fn delete(&mut self, dir: &[&[u8]], key: &[u8]) -> Result<(), FlatError<R::Error>> {
let Some(prefix) = self.prefix_of(dir).await? else {
return Ok(());
};
let mut raw_key = prefix;
raw_key.extend_from_slice(key);
self.raw.delete(&raw_key).await?;
Ok(())
}
pub async fn clear_range(
&mut self,
dir: &[&[u8]],
start: Bound<&[u8]>,
end: Bound<&[u8]>,
) -> Result<(), FlatError<R::Error>> {
let Some(bounds) = self.data_bounds(dir, start, end).await? else {
return Ok(());
};
let owned = (bounds.start, bounds.end);
let (rs, re) = bounds_ref(&owned);
self.raw.clear_range(rs, re).await?;
Ok(())
}
pub async fn list_dirs(&self, dir: &[&[u8]]) -> Result<Vec<Vec<u8>>, FlatError<R::Error>> {
validate_dir(dir).map_err(FlatError::Key)?;
ops::check_version_read_async(&self.raw).await?;
let path = Self::layer_path(dir);
let Some(prefix) = ops::find_async(&self.raw, &path).await? else {
return Ok(Vec::new());
};
let names = ops::list_children_async(&self.raw, &prefix).await?;
Ok(names.into_iter().map(|s| s.into_bytes()).collect())
}
pub async fn dir_exists(&self, dir: &[&[u8]]) -> Result<bool, FlatError<R::Error>> {
validate_dir(dir).map_err(FlatError::Key)?;
ops::check_version_read_async(&self.raw).await?;
let path = Self::layer_path(dir);
Ok(ops::find_async(&self.raw, &path).await?.is_some())
}
pub async fn remove_dir(&mut self, dir: &[&[u8]]) -> Result<bool, FlatError<R::Error>> {
validate_dir(dir).map_err(FlatError::Key)?;
if dir.is_empty() {
return Err(FlatError::Key(crate::key::KeyError::RootNotRemovable));
}
ops::check_version_read_async(&self.raw).await?;
let path = Self::layer_path(dir);
ops::remove_dir_async(&mut self.raw, &path).await
}
}
pub fn map_data_bounds(
prefix: &[u8],
start: Bound<&[u8]>,
end: Bound<&[u8]>,
) -> Option<DataBounds> {
let (rs, re) = map_bounds(prefix, start, end);
if raw_range_empty(&rs, &re) {
return None;
}
Some(DataBounds {
prefix: prefix.to_vec(),
start: rs,
end: re,
})
}
pub struct DataBounds {
pub prefix: Vec<u8>,
pub start: Bound<Vec<u8>>,
pub end: Bound<Vec<u8>>,
}
impl core::fmt::Debug for DataBounds {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("DataBounds")
.field("prefix_len", &self.prefix.len())
.field("start", &bound_len(&self.start))
.field("end", &bound_len(&self.end))
.finish()
}
}
fn bound_len(b: &Bound<Vec<u8>>) -> String {
match b {
Bound::Unbounded => "unbounded".to_owned(),
Bound::Included(v) => format!("incl({} bytes)", v.len()),
Bound::Excluded(v) => format!("excl({} bytes)", v.len()),
}
}
fn bounds_ref(b: &(Bound<Vec<u8>>, Bound<Vec<u8>>)) -> (Bound<&[u8]>, Bound<&[u8]>) {
(bound_ref(&b.0), bound_ref(&b.1))
}
fn bound_ref(b: &Bound<Vec<u8>>) -> Bound<&[u8]> {
match b {
Bound::Unbounded => Bound::Unbounded,
Bound::Included(v) => Bound::Included(v.as_slice()),
Bound::Excluded(v) => Bound::Excluded(v.as_slice()),
}
}
fn data_end_exclusive(prefix: &[u8]) -> Vec<u8> {
match data_region(prefix).1 {
Bound::Excluded(b) => b,
_ => unreachable!("data_region end is always Excluded"),
}
}
fn map_bounds(
prefix: &[u8],
start: Bound<&[u8]>,
end: Bound<&[u8]>,
) -> (Bound<Vec<u8>>, Bound<Vec<u8>>) {
let mk = |k: &[u8]| {
let mut raw = prefix.to_vec();
raw.extend_from_slice(k);
raw
};
let rs = match start {
Bound::Unbounded => Bound::Included(prefix.to_vec()),
Bound::Included(k) => Bound::Included(mk(k)),
Bound::Excluded(k) => Bound::Excluded(mk(k)),
};
let re = match end {
Bound::Unbounded => Bound::Excluded(data_end_exclusive(prefix)),
Bound::Excluded(k) => Bound::Excluded(mk(k)),
Bound::Included(k) => {
let mut raw = mk(k);
raw.push(0x00);
Bound::Excluded(raw)
}
};
(rs, re)
}
fn raw_range_empty(start: &Bound<Vec<u8>>, end: &Bound<Vec<u8>>) -> bool {
match (start, end) {
(Bound::Included(a), Bound::Excluded(b)) => a >= b,
(Bound::Excluded(a), Bound::Excluded(b)) => a >= b,
(Bound::Unbounded, _) => false,
(_, Bound::Unbounded) => false,
_ => unreachable!("end bounds are always Excluded"),
}
}
#[cfg(test)]
pub(crate) struct Mem {
map: core::cell::RefCell<std::collections::BTreeMap<Vec<u8>, Vec<u8>>>,
}
#[cfg(test)]
impl Default for Mem {
fn default() -> Self {
Self {
map: core::cell::RefCell::new(std::collections::BTreeMap::new()),
}
}
}
#[cfg(test)]
impl RawKv for Mem {
type Error = std::convert::Infallible;
fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
Ok(self.map.borrow().get(key).cloned())
}
fn scan(
&self,
start: Bound<&[u8]>,
end: Bound<&[u8]>,
forward: bool,
) -> Result<Vec<KvPair>, Self::Error> {
let map = self.map.borrow();
let rows: Vec<KvPair> = map
.iter()
.filter(|(k, _)| {
let k = &k[..];
let above = match start {
Bound::Unbounded => true,
Bound::Included(s) => k >= s,
Bound::Excluded(s) => k > s,
};
let below = match end {
Bound::Unbounded => true,
Bound::Excluded(e) => k < e,
Bound::Included(e) => k <= e,
};
above && below
})
.map(|(k, v)| KvPair {
key: k.clone(),
value: v.clone(),
})
.collect();
if forward {
Ok(rows)
} else {
Ok(rows.into_iter().rev().collect())
}
}
fn insert(&mut self, key: &[u8], value: &[u8]) -> Result<(), Self::Error> {
self.map.borrow_mut().insert(key.to_vec(), value.to_vec());
Ok(())
}
fn delete(&mut self, key: &[u8]) -> Result<(), Self::Error> {
self.map.borrow_mut().remove(key);
Ok(())
}
fn clear_range(&mut self, start: Bound<&[u8]>, end: Bound<&[u8]>) -> Result<(), Self::Error> {
let mut map = self.map.borrow_mut();
let keys: Vec<Vec<u8>> = map
.keys()
.filter(|k| {
let k = &k[..];
let above = match start {
Bound::Unbounded => true,
Bound::Included(s) => k >= s,
Bound::Excluded(s) => k > s,
};
let below = match end {
Bound::Unbounded => true,
Bound::Excluded(e) => k < e,
Bound::Included(e) => k <= e,
};
above && below
})
.cloned()
.collect();
for k in keys {
map.remove(&k);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::key::KeyError;
fn engine() -> FlatEngine<Mem> {
FlatEngine::new(Mem::default())
}
fn ok<T>(r: Result<T, FlatError<std::convert::Infallible>>) -> T {
r.unwrap()
}
#[test]
fn fresh_reads_return_empty_and_first_write_initialises() {
let mut e = engine();
assert_eq!(ok(e.prefix_of(&[])), None);
assert_eq!(ok(e.get(&[], b"k")), None);
assert!(ok(e.scan(&[], Bound::Unbounded, Bound::Unbounded, true)).is_empty());
assert!(ok(e.list_dirs(&[])).is_empty());
assert!(!ok(e.dir_exists(&[])));
assert!(!ok(e.remove_dir(&[b"a"])));
ok(e.set(&[], b"k", b"v"));
assert!(ok(e.dir_exists(&[])));
assert_eq!(ok(e.get(&[], b"k")), Some(b"v".to_vec()));
let version = e
.raw()
.map
.borrow()
.get(crate::flatdir::layout::VERSION_KEY)
.cloned();
assert_eq!(
version,
Some(crate::flatdir::layout::LAYOUT_VERSION.to_vec())
);
}
#[test]
fn a_first_set_produces_exactly_nine_raw_rows() {
let mut e = engine();
ok(e.set(&[b"a"], b"k", b"v"));
let map = e.raw().map.borrow();
assert_eq!(map.len(), 9, "unexpected raw rows: {map:?}");
}
#[test]
fn reads_on_a_foreign_store_fail_closed() {
let mut e = engine();
let mut v = [0u8; 12];
v[0..4].copy_from_slice(&2u32.to_le_bytes());
e.raw_mut()
.insert(crate::flatdir::layout::VERSION_KEY, &v)
.unwrap();
assert_eq!(e.prefix_of(&[]), Err(FlatError::Foreign));
assert_eq!(e.get(&[], b"k"), Err(FlatError::Foreign));
assert_eq!(
e.scan(&[], Bound::Unbounded, Bound::Unbounded, true),
Err(FlatError::Foreign)
);
assert!(matches!(
e.data_bounds(&[], Bound::Unbounded, Bound::Unbounded),
Err(FlatError::Foreign)
));
assert_eq!(e.dir_exists(&[]), Err(FlatError::Foreign));
assert_eq!(e.list_dirs(&[]), Err(FlatError::Foreign));
assert_eq!(e.set(&[], b"k", b"v"), Err(FlatError::Foreign));
assert_eq!(e.remove_dir(&[b"a"]), Err(FlatError::Foreign));
}
#[test]
fn a_malformed_version_row_fails_closed() {
let mut e = engine();
e.raw_mut()
.insert(crate::flatdir::layout::VERSION_KEY, &[1, 0])
.unwrap();
assert_eq!(e.dir_exists(&[]), Err(FlatError::Foreign));
}
#[test]
fn a_corrupt_node_value_is_corrupt_not_a_panic() {
let mut e = engine();
e.set(&[b"dir"], b"k", b"v").unwrap();
let child_tag = crate::flatdir::layout::ROOT_NODE
.iter()
.copied()
.chain(std::iter::once(0x14))
.collect::<Vec<u8>>();
let row_key = e
.raw()
.map
.borrow()
.iter()
.find(|(k, _)| k.starts_with(&child_tag))
.expect("the anchor child row")
.0
.clone();
e.raw_mut()
.map
.borrow_mut()
.insert(row_key, vec![0x99, 0x00]);
assert_eq!(e.get(&[b"dir"], b"k"), Err(FlatError::Corrupt));
assert_eq!(
e.scan(&[b"dir"], Bound::Unbounded, Bound::Unbounded, true),
Err(FlatError::Corrupt)
);
assert_eq!(e.remove_dir(&[b"dir"]), Err(FlatError::Corrupt));
}
#[test]
fn allocation_is_recursive_and_stable() {
let mut e = engine();
let p = ok(e.allocate_dir(&[b"a", b"b"]));
assert_eq!(ok(e.prefix_of(&[b"a", b"b"])), Some(p.clone()));
let q = ok(e.allocate_dir(&[b"a", b"c"]));
assert_ne!(p, q);
assert!(ok(e.prefix_of(&[b"a"])).is_some());
let dirs: [[&[u8]; 2]; 2] = [[b"a" as &[u8], b"b"], [b"a" as &[u8], b"c"]];
for dir in dirs {
let p = ok(e.prefix_of(&dir)).unwrap();
assert!((0x0c..=0x1c).contains(&p[0]), "prefix {p:?}");
}
}
#[test]
fn many_allocations_stay_in_the_data_region() {
let mut e = engine();
for i in 0..300u32 {
let d = format!("d{i:03}").into_bytes();
let d = [d.as_slice()];
let p = ok(e.allocate_dir(&d));
assert!((0x0c..=0x1c).contains(&p[0]), "prefix {p:?} at {i}");
}
}
#[test]
fn resolve_missing_dir_is_none() {
let mut e = engine();
ok(e.set(&[], b"k", b"v"));
assert_eq!(ok(e.prefix_of(&[b"nope"])), None);
assert_eq!(ok(e.prefix_of(&[b"nope", b"deeper"])), None);
}
#[test]
fn set_get_delete_round_trips_per_dir() {
let mut e = engine();
ok(e.set(&[b"asset", b"btc"], b"k", b"v"));
assert_eq!(ok(e.get(&[b"asset", b"btc"], b"k")), Some(b"v".to_vec()));
assert_eq!(ok(e.get(&[b"asset"], b"k")), None);
assert_eq!(ok(e.get(&[b"btc"], b"k")), None);
ok(e.delete(&[b"asset", b"btc"], b"k"));
assert_eq!(ok(e.get(&[b"asset", b"btc"], b"k")), None);
}
#[test]
fn scan_orders_within_dir_only() {
let mut e = engine();
for k in [b"b", b"a", b"c"] {
ok(e.set(&[b"d"], k, k));
ok(e.set(&[b"other"], k, k));
}
let rows = ok(e.scan(&[b"d"], Bound::Unbounded, Bound::Unbounded, true));
let keys: Vec<Vec<u8>> = rows.iter().map(|p| p.key.clone()).collect();
assert_eq!(keys, vec![b"a".to_vec(), b"b".to_vec(), b"c".to_vec()]);
let rows = ok(e.scan(&[b"d"], Bound::Unbounded, Bound::Unbounded, false));
assert_eq!(rows.first().unwrap().key, b"c".to_vec());
}
#[test]
fn scan_bound_matrix() {
let mut e = engine();
for k in [b"a", b"b", b"c", b"\xff"] {
ok(e.set(&[b"d"], k, b"v"));
}
let get = |s: core::ops::Bound<&[u8]>,
en: core::ops::Bound<&[u8]>,
e: &FlatEngine<Mem>|
-> Vec<Vec<u8>> {
ok(e.scan(&[b"d"], s, en, true))
.into_iter()
.map(|pair| pair.key)
.collect()
};
assert_eq!(
get(Bound::Included(b"b"), Bound::Excluded(b"c"), &e),
vec![b"b".to_vec()]
);
assert_eq!(
get(Bound::Excluded(b"b"), Bound::Included(b"c"), &e),
vec![b"c".to_vec()]
);
assert_eq!(
get(Bound::Excluded(&[0xFFu8]), Bound::Unbounded, &e),
Vec::<Vec<u8>>::new()
);
assert_eq!(
get(Bound::Unbounded, Bound::Included(&[0xFFu8]), &e),
vec![b"a".to_vec(), b"b".to_vec(), b"c".to_vec(), vec![0xFF]]
);
assert_eq!(
get(Bound::Included(&[0xFFu8]), Bound::Unbounded, &e),
vec![vec![0xFF]]
);
assert_eq!(
get(Bound::Excluded(&[0xFFu8]), Bound::Excluded(&[0xFFu8]), &e),
Vec::<Vec<u8>>::new()
);
}
#[test]
fn clear_range_clears_within_dir_only() {
let mut e = engine();
for k in [b"a", b"b", b"c"] {
ok(e.set(&[b"d"], k, b"v"));
ok(e.set(&[b"e"], k, b"v"));
}
ok(e.clear_range(&[b"d"], Bound::Included(b"b"), Bound::Excluded(b"c")));
assert_eq!(ok(e.get(&[b"d"], b"a")), Some(b"v".to_vec()));
assert_eq!(ok(e.get(&[b"d"], b"b")), None);
assert_eq!(ok(e.get(&[b"d"], b"c")), Some(b"v".to_vec()));
assert_eq!(ok(e.get(&[b"e"], b"b")), Some(b"v".to_vec()));
ok(e.clear_range(&[b"d"], Bound::Unbounded, Bound::Unbounded));
assert!(ok(e.scan(&[b"d"], Bound::Unbounded, Bound::Unbounded, true)).is_empty());
assert!(ok(e.dir_exists(&[b"d"])));
}
#[test]
fn nav_list_exists_remove() {
let mut e = engine();
ok(e.set(&[b"a", b"1"], b"k", b"v"));
ok(e.set(&[b"a", b"2"], b"k", b"v"));
ok(e.set(&[b"b"], b"k", b"v"));
assert_eq!(ok(e.list_dirs(&[])), vec![b"a".to_vec(), b"b".to_vec()]);
assert_eq!(ok(e.list_dirs(&[b"a"])), vec![b"1".to_vec(), b"2".to_vec()]);
assert!(ok(e.dir_exists(&[b"a"])));
assert!(ok(e.dir_exists(&[b"a", b"1"])));
assert!(!ok(e.dir_exists(&[b"a", b"3"])));
ok(e.allocate_dir(&[b"empty"]));
assert!(ok(e.dir_exists(&[b"empty"])));
assert!(ok(e.list_dirs(&[b"empty"])).is_empty());
assert!(ok(e.list_dirs(&[b"nope"])).is_empty());
assert!(!ok(e.dir_exists(&[b"nope"])));
}
#[test]
fn nav_remove_is_recursive() {
let mut e = engine();
ok(e.set(&[b"a", b"b", b"c"], b"k1", b"v1"));
ok(e.set(&[b"a", b"b"], b"k2", b"v2"));
ok(e.set(&[b"a", b"d"], b"k3", b"v3"));
ok(e.set(&[b"z"], b"k4", b"v4"));
assert!(ok(e.remove_dir(&[b"a", b"b"])));
assert_eq!(ok(e.get(&[b"a", b"b", b"c"], b"k1")), None);
assert_eq!(ok(e.get(&[b"a", b"b"], b"k2")), None);
assert_eq!(ok(e.get(&[b"a", b"d"], b"k3")), Some(b"v3".to_vec()));
assert!(ok(e.dir_exists(&[b"a"])));
assert!(!ok(e.dir_exists(&[b"a", b"b"])));
assert!(ok(e.remove_dir(&[b"a", b"d"])));
assert_eq!(ok(e.get(&[b"a", b"d"], b"k3")), None);
assert!(!ok(e.remove_dir(&[b"a", b"b"])));
assert_eq!(ok(e.get(&[b"z"], b"k4")), Some(b"v4".to_vec()));
}
#[test]
fn nav_root_is_not_removable() {
let mut e = engine();
ok(e.set(&[], b"k", b"v"));
assert_eq!(
e.remove_dir(&[]),
Err(FlatError::Key(KeyError::RootNotRemovable))
);
assert!(ok(e.dir_exists(&[])));
}
#[test]
fn nav_rejects_non_utf8() {
let mut e = engine();
let seg: &[u8] = b"\xFF\xFE";
let bad = [seg];
assert_eq!(
e.list_dirs(&bad),
Err(FlatError::Key(KeyError::DirSegmentNotUtf8 { segment: 0 }))
);
assert_eq!(
e.remove_dir(&bad),
Err(FlatError::Key(KeyError::DirSegmentNotUtf8 { segment: 0 }))
);
}
#[test]
fn remove_and_recreate_work() {
let mut e = engine();
ok(e.set(&[b"x"], b"k", b"v1"));
let p1 = ok(e.prefix_of(&[b"x"])).unwrap();
assert!(ok(e.remove_dir(&[b"x"])));
assert!(!ok(e.dir_exists(&[b"x"])));
assert_eq!(ok(e.get(&[b"x"], b"k")), None);
ok(e.set(&[b"x"], b"k", b"v2"));
let p2 = ok(e.prefix_of(&[b"x"])).unwrap();
assert_eq!(ok(e.get(&[b"x"], b"k")), Some(b"v2".to_vec()));
if p1 == p2 {
assert_eq!(
ok(e.scan(&[b"x"], Bound::Unbounded, Bound::Unbounded, true)).len(),
1
);
}
assert!(ops::validate(e.raw()).is_ok());
}
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
mod async_tests {
use std::collections::BTreeMap;
use std::sync::Mutex;
use super::*;
#[derive(Default)]
struct AsyncMem {
map: Mutex<BTreeMap<Vec<u8>, Vec<u8>>>,
}
impl AsyncRawKv for AsyncMem {
type Error = std::convert::Infallible;
async fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
Ok(self.map.lock().unwrap().get(key).cloned())
}
async fn exists(&self, key: &[u8]) -> Result<bool, Self::Error> {
Ok(self.map.lock().unwrap().contains_key(key))
}
async fn scan(
&self,
start: Bound<&[u8]>,
end: Bound<&[u8]>,
forward: bool,
limit: Option<usize>,
) -> Result<Vec<KvPair>, Self::Error> {
if limit == Some(0) {
return Ok(Vec::new());
}
let map = self.map.lock().unwrap();
let mut rows: Vec<KvPair> = map
.iter()
.filter(|(k, _)| {
let k = k.as_slice();
let above = match start {
Bound::Unbounded => true,
Bound::Included(s) => k >= s,
Bound::Excluded(s) => k > s,
};
let below = match end {
Bound::Unbounded => true,
Bound::Excluded(e) => k < e,
Bound::Included(e) => k <= e,
};
above && below
})
.map(|(k, v)| KvPair {
key: k.clone(),
value: v.clone(),
})
.collect();
if !forward {
rows.reverse();
}
if let Some(limit) = limit {
rows.truncate(limit);
}
Ok(rows)
}
async fn insert(&mut self, key: &[u8], value: &[u8]) -> Result<(), Self::Error> {
self.map
.lock()
.unwrap()
.insert(key.to_vec(), value.to_vec());
Ok(())
}
async fn delete(&mut self, key: &[u8]) -> Result<(), Self::Error> {
self.map.lock().unwrap().remove(key);
Ok(())
}
async fn clear_range(
&mut self,
start: Bound<&[u8]>,
end: Bound<&[u8]>,
) -> Result<(), Self::Error> {
let mut map = self.map.lock().unwrap();
let keys: Vec<Vec<u8>> = map
.keys()
.filter(|k| {
let k = k.as_slice();
let above = match start {
Bound::Unbounded => true,
Bound::Included(s) => k >= s,
Bound::Excluded(s) => k > s,
};
let below = match end {
Bound::Unbounded => true,
Bound::Excluded(e) => k < e,
Bound::Included(e) => k <= e,
};
above && below
})
.cloned()
.collect();
for k in keys {
map.remove(&k);
}
Ok(())
}
}
fn assert_send<T: Send>(_: &T) {}
#[tokio::test]
async fn async_engine_futures_are_send_and_round_trip() {
let mut e = AsyncFlatEngine::new(AsyncMem::default());
{
let fut = e.set(&[b"a", b"b"], b"k1", b"v1");
assert_send(&fut);
fut.await.unwrap();
}
{
let fut = e.get(&[b"a", b"b"], b"k1");
assert_send(&fut);
assert_eq!(fut.await.unwrap(), Some(b"v1".to_vec()));
}
assert!(e.exists(&[b"a", b"b"], b"k1").await.unwrap());
assert!(!e.exists(&[b"a", b"b"], b"missing").await.unwrap());
assert!(!e.exists(&[b"missing"], b"k1").await.unwrap());
assert_eq!(e.list_dirs(&[]).await.unwrap(), vec![b"a".to_vec()]);
assert_eq!(e.list_dirs(&[b"a"]).await.unwrap(), vec![b"b".to_vec()]);
assert!(e.remove_dir(&[b"a"]).await.unwrap());
assert!(!e.dir_exists(&[b"a"]).await.unwrap());
assert!(!e.dir_exists(&[b"a", b"b"]).await.unwrap());
assert_eq!(e.get(&[b"a", b"b"], b"k1").await.unwrap(), None);
assert!(ops::validate_async(e.raw()).await.is_ok());
}
#[tokio::test]
async fn async_engine_handles_many_allocations_foreign_and_clear_range() {
let mut e = AsyncFlatEngine::new(AsyncMem::default());
for i in 0..130u32 {
let d = format!("d{i:03}").into_bytes();
let p = e.allocate_dir(&[d.as_slice()]).await.unwrap();
assert!((0x0c..=0x1c).contains(&p[0]));
}
e.set(&[b"d000"], b"a", b"1").await.unwrap();
e.set(&[b"d000"], b"b", b"2").await.unwrap();
e.set(&[b"d000"], b"c", b"3").await.unwrap();
e.clear_range(&[b"d000"], Bound::Included(b"b"), Bound::Excluded(b"c"))
.await
.unwrap();
let rows = e
.scan(&[b"d000"], Bound::Unbounded, Bound::Unbounded, false)
.await
.unwrap();
let keys: Vec<Vec<u8>> = rows.into_iter().map(|p| p.key).collect();
assert_eq!(keys, vec![b"c".to_vec(), b"a".to_vec()]);
assert!(ops::validate_async(e.raw()).await.is_ok());
let mut foreign = AsyncFlatEngine::new(AsyncMem::default());
let mut v = [0u8; 12];
v[0..4].copy_from_slice(&2u32.to_le_bytes());
foreign
.raw_mut()
.insert(crate::flatdir::layout::VERSION_KEY, &v)
.await
.unwrap();
assert_eq!(foreign.get(&[], b"k").await, Err(FlatError::Foreign));
assert_eq!(foreign.set(&[], b"k", b"v").await, Err(FlatError::Foreign));
assert_eq!(
foreign.remove_dir(&[]).await,
Err(FlatError::Key(KeyError::RootNotRemovable))
);
}
#[tokio::test]
async fn sync_and_async_flatdir_ops_produce_byte_identical_raw_maps() {
use crate::flatdir::hca::Lcg;
let mut sync_raw = Mem::default();
let mut async_raw = AsyncMem::default();
let mut sync_rng = Lcg::new(42);
let mut async_rng = Lcg::new(42);
let mut paths: Vec<Vec<Vec<u8>>> = vec![
vec![b"alpha".to_vec(), b"beta".to_vec(), b"gamma".to_vec()],
vec![b"alpha".to_vec(), b"delta".to_vec()],
vec![b"nested".to_vec(), b"one".to_vec(), b"two".to_vec()],
];
for i in 0..40u32 {
paths.push(vec![format!("dir-{i:02}").into_bytes()]);
}
let to_layer_path = |segs: &[Vec<u8>]| -> Vec<Vec<u8>> {
let mut full = Vec::with_capacity(segs.len() + 1);
full.push(ROOT_PATH_SEGMENT.as_bytes().to_vec());
full.extend_from_slice(segs);
full
};
for segs in &paths {
let full = to_layer_path(segs);
let refs: Vec<&[u8]> = full.iter().map(Vec::as_slice).collect();
let sync_prefix = ops::create_or_open(&mut sync_raw, &refs, true, &mut sync_rng)
.unwrap()
.unwrap();
let async_prefix =
ops::create_or_open_async(&mut async_raw, &refs, true, &mut async_rng)
.await
.unwrap()
.unwrap();
assert_eq!(sync_prefix, async_prefix);
let mut data_key = sync_prefix;
data_key.extend_from_slice(b"payload");
sync_raw.insert(&data_key, b"value").unwrap();
async_raw.insert(&data_key, b"value").await.unwrap();
}
assert_eq!(
*sync_raw.map.borrow(),
*async_raw.map.lock().unwrap(),
"raw maps must match byte-for-byte after nested creates and HCA window advance"
);
for target in [
vec![b"alpha".to_vec()],
vec![b"nested".to_vec(), b"one".to_vec()],
vec![b"dir-15".to_vec()],
vec![b"missing".to_vec()],
] {
let full = to_layer_path(&target);
let refs: Vec<&[u8]> = full.iter().map(Vec::as_slice).collect();
let sync_removed = ops::remove_dir(&mut sync_raw, &refs).unwrap();
let async_removed = ops::remove_dir_async(&mut async_raw, &refs).await.unwrap();
assert_eq!(sync_removed, async_removed);
}
assert_eq!(
*sync_raw.map.borrow(),
*async_raw.map.lock().unwrap(),
"raw maps must match byte-for-byte after recursive removals"
);
let recreate = to_layer_path(&[b"alpha".to_vec(), b"beta".to_vec()]);
let refs: Vec<&[u8]> = recreate.iter().map(Vec::as_slice).collect();
let sp = ops::create_or_open(&mut sync_raw, &refs, true, &mut sync_rng).unwrap();
let ap = ops::create_or_open_async(&mut async_raw, &refs, true, &mut async_rng)
.await
.unwrap();
assert_eq!(sp, ap);
assert_eq!(*sync_raw.map.borrow(), *async_raw.map.lock().unwrap());
assert_eq!(
ops::validate(&sync_raw).unwrap(),
ops::validate_async(&async_raw).await.unwrap()
);
}
}
}