use std::sync::Arc;
use ahash::AHashMap;
use ahash::AHashSet;
use parking_lot::RwLock;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::thread::available_parallelism;
mod access;
mod entry;
mod shard_map;
mod ttl_list;
pub use access::AccessScope;
#[allow(unused_imports)] pub use shard_map::{
EntryRef, EntryView, Leftover, Lookup, Relocated, Removal, ShardMap, StrRef, Taken, ValueRef,
Written,
};
#[inline]
pub fn shard_index(shards: usize, key: &(impl AsRef<[u8]> + ?Sized)) -> usize {
shard_index_of_bytes(shards, key.as_ref())
}
#[inline]
pub fn shard_index_of_bytes(shards: usize, key: &[u8]) -> usize {
let mut hash: u64 = 0xcbf29ce484222325;
for &byte in key {
hash ^= u64::from(byte);
hash = hash.wrapping_mul(0x100000001b3);
}
(hash as usize) & (shards - 1)
}
#[inline(always)]
pub fn get_shard<'a>(db: &'a Db, key: &(impl AsRef<[u8]> + ?Sized)) -> &'a Shard {
&db[shard_index(db.len(), key)]
}
#[inline(always)]
pub fn get_shard_of_bytes<'a>(db: &'a Db, key: &[u8]) -> &'a Shard {
&db[shard_index_of_bytes(db.len(), key)]
}
pub fn num_shards() -> usize {
let cores = available_parallelism().map(|n| n.get()).unwrap_or(8);
let target = cores * 8;
target.next_power_of_two()
}
pub struct ShardLock {
map: RwLock<ShardMap>,
ttls: AtomicUsize,
keys: AtomicBool,
place: std::sync::OnceLock<(usize, usize)>,
}
const SPIN_FOR: std::time::Duration = std::time::Duration::from_micros(50);
pub struct ShardWrite<'a> {
map: std::mem::ManuallyDrop<parking_lot::RwLockWriteGuard<'a, ShardMap>>,
lock: &'a ShardLock,
}
impl std::ops::Deref for ShardWrite<'_> {
type Target = ShardMap;
#[inline(always)]
fn deref(&self) -> &ShardMap {
&self.map
}
}
impl std::ops::DerefMut for ShardWrite<'_> {
#[inline(always)]
fn deref_mut(&mut self) -> &mut ShardMap {
&mut self.map
}
}
impl Drop for ShardWrite<'_> {
#[inline(always)]
fn drop(&mut self) {
self.map.unpin_now();
let ttls = self.map.ttl_len();
if self.lock.ttls.load(Ordering::Relaxed) != ttls {
self.lock.ttls.store(ttls, Ordering::Release);
}
let keys = !self.map.is_empty();
if self.lock.keys.load(Ordering::Relaxed) != keys {
self.lock.keys.store(keys, Ordering::Release);
}
if self.map.wrote_over_expired() {
return self.unlock_and_announce();
}
unsafe { std::mem::ManuallyDrop::drop(&mut self.map) };
}
}
impl ShardWrite<'_> {
#[cold]
#[inline(never)]
fn unlock_and_announce(&mut self) {
let keys = self.map.take_written_over();
unsafe { std::mem::ManuallyDrop::drop(&mut self.map) };
if let Some(&(store, db)) = self.lock.place.get() {
crate::expiry::written_over(store, db, &keys);
}
}
}
impl ShardLock {
pub fn new(map: ShardMap) -> Self {
ShardLock {
ttls: AtomicUsize::new(map.ttl_len()),
keys: AtomicBool::new(!map.is_empty()),
map: RwLock::new(map),
place: std::sync::OnceLock::new(),
}
}
#[inline(always)]
pub fn read(&self) -> parking_lot::RwLockReadGuard<'_, ShardMap> {
self.map.read()
}
#[inline(always)]
pub fn try_write(&self) -> Option<ShardWrite<'_>> {
let mut map = self.map.try_write()?;
map.pin_now();
Some(ShardWrite {
map: std::mem::ManuallyDrop::new(map),
lock: self,
})
}
#[cold]
#[inline(never)]
pub fn write_after_spinning(&self) -> ShardWrite<'_> {
let started = std::time::Instant::now();
loop {
for _ in 0..32 {
std::hint::spin_loop();
}
if !self.map.is_locked()
&& let Some(guard) = self.try_write()
{
return guard;
}
if started.elapsed() >= SPIN_FOR {
return self.write();
}
}
}
#[inline(always)]
pub fn write(&self) -> ShardWrite<'_> {
let mut map = self.map.write();
map.pin_now();
ShardWrite {
map: std::mem::ManuallyDrop::new(map),
lock: self,
}
}
#[inline(always)]
pub fn holds_no_ttl(&self) -> bool {
self.ttls.load(Ordering::Acquire) == 0
}
#[inline(always)]
pub fn holds_no_keys(&self) -> bool {
!self.keys.load(Ordering::Acquire)
}
#[inline]
pub fn ttl_count(&self) -> usize {
self.ttls.load(Ordering::Acquire)
}
pub fn shrink_if_sparse(&self) -> bool {
if !self.read().is_sparse() {
return false;
}
let mut m = self.write();
if !m.is_sparse() {
return false;
}
let keep = m.len() + m.len() / 8;
m.shrink_to(keep);
true
}
}
impl Default for ShardLock {
fn default() -> Self {
Self::new(ShardMap::new())
}
}
pub type Key = crate::key_bytes::KeyBytes;
pub type Shard = Arc<ShardLock>;
pub type Db = Arc<Vec<Shard>>;
pub type Store = Arc<Vec<Db>>;
pub type TsLabelIndex = AHashMap<String, AHashSet<String>>;
pub type SharedTsIndex = Arc<RwLock<TsLabelIndex>>;
pub fn new_ts_index() -> SharedTsIndex {
Arc::new(RwLock::new(AHashMap::new()))
}
pub fn new_store(dbs: usize) -> Store {
let num_shards = num_shards();
let dbs = (0..dbs)
.map(|_| {
let shards = (0..num_shards)
.map(|_| Arc::new(ShardLock::default()))
.collect::<Vec<_>>();
Arc::new(shards)
})
.collect::<Vec<_>>();
let store = Arc::new(dbs);
let id = Arc::as_ptr(&store) as *const () as usize;
for (db, shards) in store.iter().enumerate() {
for shard in shards.iter() {
let _ = shard.place.set((id, db));
}
}
store
}
macro_rules! mem_swap_rwlock_maps {
($a:expr, $b:expr) => {
std::mem::swap(&mut *$a.write(), &mut *$b.write());
};
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Flushed {
pub entries: usize,
pub keys: usize,
pub slots_released: usize,
}
impl std::ops::AddAssign for Flushed {
fn add_assign(&mut self, rhs: Self) {
self.entries += rhs.entries;
self.keys += rhs.keys;
self.slots_released += rhs.slots_released;
}
}
const SHARD_RELEASE_MIN_CAPACITY: usize = 128;
const TRIM_MIN_ENTRIES: usize = 4096;
impl Flushed {
pub fn should_trim(&self) -> bool {
self.slots_released > 0 || self.entries >= TRIM_MIN_ENTRIES
}
}
fn clear_shard_map(map: &mut ShardMap) -> Flushed {
let entries = map.len();
let capacity = map.capacity();
if capacity >= SHARD_RELEASE_MIN_CAPACITY {
*map = ShardMap::default();
Flushed {
entries,
slots_released: capacity,
..Flushed::default()
}
} else {
map.clear();
Flushed {
entries,
..Flushed::default()
}
}
}
pub fn clear_db(db: &Db) -> Flushed {
let mut total = Flushed::default();
for shard in db.iter() {
total += clear_shard_map(&mut shard.write());
}
total.keys = total.entries;
total
}
pub fn take_db(db: &Db) -> (Vec<ShardMap>, Flushed) {
let mut taken = Vec::with_capacity(db.len());
let mut total = Flushed::default();
for shard in db.iter() {
let mut map = shard.write();
let capacity = map.capacity();
total.entries += map.len();
taken.push(if capacity >= SHARD_RELEASE_MIN_CAPACITY {
total.slots_released += capacity;
std::mem::take(&mut *map)
} else {
std::mem::replace(&mut *map, ShardMap::with_capacity(capacity))
});
}
total.keys = total.entries;
(taken, total)
}
pub fn clear_store(store: &Store) -> Flushed {
let mut total = Flushed::default();
for db in store.iter() {
total += clear_db(db);
}
total
}
#[inline]
pub fn clear_ts_label_index(ts: &SharedTsIndex) {
ts.write().clear();
}
pub fn rebuild_ts_label_index(store: &Store, ts: &SharedTsIndex) {
let mut index = TsLabelIndex::new();
for db in store.iter() {
for shard in db.iter() {
for (key, value) in shard.read().iter() {
if let ValueRef::TimeSeries(series) = value {
for (label, label_value) in series.read().labels.iter() {
index
.entry(format!("{label}={label_value}"))
.or_default()
.insert(crate::key_bytes::text_of(key).into_owned());
}
}
}
}
}
*ts.write() = index;
}
pub fn swap_kv_with_staging(live: &Store, staging: &Store) {
assert_eq!(live.len(), staging.len(), "staging store db count mismatch");
for (db_live, db_staging) in live.iter().zip(staging.iter()) {
assert_eq!(
db_live.len(),
db_staging.len(),
"staging shard count mismatch"
);
for (s_live, s_staging) in db_live.iter().zip(db_staging.iter()) {
mem_swap_rwlock_maps!(s_live, s_staging);
}
}
}
#[cfg(test)]
mod flush_tests {
use super::*;
use crate::types::KiviDBValue;
fn val() -> KiviDBValue {
KiviDBValue::String(crate::types::SharedBytes::from(&b"v"[..]))
}
fn fill(store: &Store, db_index: usize, count: usize) {
for i in 0..count {
let key = format!("flush-key-{i:012}");
get_shard(&store[db_index], &key)
.write()
.insert(key.as_str(), val());
}
}
fn total(db: &Db) -> (usize, usize) {
db.iter().fold((0, 0), |(len, cap), s| {
let m = s.read();
(len + m.len(), cap + m.capacity())
})
}
#[test]
fn clear_db_releases_large_shard_tables() {
let store = new_store(1);
fill(&store, 0, SHARD_RELEASE_MIN_CAPACITY * num_shards() * 4);
let (len_before, cap_before) = total(&store[0]);
assert!(len_before > 0);
assert!(cap_before >= SHARD_RELEASE_MIN_CAPACITY);
let flushed = clear_db(&store[0]);
let (len_after, cap_after) = total(&store[0]);
assert_eq!(len_after, 0, "flush must remove every key");
assert_eq!(cap_after, 0, "flush must hand the bucket arrays back");
assert_eq!(flushed.entries, len_before);
assert_eq!(flushed.slots_released, cap_before);
assert!(flushed.should_trim());
}
#[test]
fn clear_db_keeps_small_shard_tables() {
let store = new_store(1);
fill(&store, 0, 8);
let (_, cap_before) = total(&store[0]);
let flushed = clear_db(&store[0]);
let (len_after, cap_after) = total(&store[0]);
assert_eq!(len_after, 0, "flush must remove every key");
assert_eq!(cap_after, cap_before, "small tables keep their capacity");
assert_eq!(flushed.slots_released, 0);
assert!(
!flushed.should_trim(),
"a handful of keys must not trigger a malloc_trim"
);
}
#[test]
fn clear_store_empties_every_db_and_its_times_to_live() {
let store = new_store(4);
for db in 0..4 {
fill(&store, db, 64);
let key = format!("flush-key-{:012}", 7);
assert!(get_shard(&store[db], &key).write().set_expires(&key, 1));
}
let flushed = clear_store(&store);
assert_eq!(flushed.entries, 4 * 64);
for db in 0..4 {
assert_eq!(total(&store[db]).0, 0, "db{db} still has keys");
assert!(
store[db]
.iter()
.all(|s| s.holds_no_ttl() && s.read().ttl_len() == 0),
"db{db} still has times to live"
);
}
}
#[test]
fn clear_db_leaves_other_dbs_alone() {
let store = new_store(2);
fill(&store, 0, 32);
fill(&store, 1, 32);
clear_db(&store[0]);
assert_eq!(total(&store[0]).0, 0);
assert_eq!(total(&store[1]).0, 32, "FLUSHDB must not touch other dbs");
}
#[test]
fn should_trim_tracks_entry_volume() {
assert!(!Flushed::default().should_trim());
assert!(
!Flushed {
entries: TRIM_MIN_ENTRIES - 1,
slots_released: 0,
..Flushed::default()
}
.should_trim()
);
assert!(
Flushed {
entries: TRIM_MIN_ENTRIES,
slots_released: 0,
..Flushed::default()
}
.should_trim()
);
assert!(
Flushed {
entries: 1,
slots_released: 1,
..Flushed::default()
}
.should_trim()
);
}
#[test]
fn store_is_writable_after_flush() {
let store = new_store(1);
fill(&store, 0, SHARD_RELEASE_MIN_CAPACITY * num_shards() * 4);
clear_db(&store[0]);
fill(&store, 0, 100);
assert_eq!(total(&store[0]).0, 100);
let key = "flush-key-000000000042".to_string();
assert!(get_shard(&store[0], &key).read().contains_key(key.as_str()));
}
}
#[cfg(test)]
mod staging_swap_tests {
use super::*;
use crate::types::KiviDBValue;
#[test]
fn swap_kv_with_staging_moves_staging_maps_into_live() {
let live = new_store(1);
let staging = new_store(1);
let k = "swap-key";
let val = KiviDBValue::String(crate::types::SharedBytes::from(&b"from-staging"[..]));
get_shard(&staging[0], k).write().insert(k, val);
assert!(get_shard(&live[0], k).read().get(k).is_none());
swap_kv_with_staging(&live, &staging);
match get_shard(&live[0], k)
.read()
.get(k)
.expect("key on live after swap")
{
ValueRef::String(b) => assert_eq!(&b[..], b"from-staging"),
_ => panic!("expected string value"),
}
}
#[test]
fn a_swap_moves_times_to_live_with_their_keys() {
let live = new_store(1);
let staging = new_store(1);
let k = "exp-key";
let val = KiviDBValue::String(crate::types::SharedBytes::from(&b"v"[..]));
get_shard(&staging[0], k)
.write()
.insert_expiring(k, val, Some(1_234));
assert!(!get_shard(&staging[0], k).holds_no_ttl());
swap_kv_with_staging(&live, &staging);
assert_eq!(get_shard(&live[0], k).read().expires(k), Some(1_234));
assert!(!get_shard(&live[0], k).holds_no_ttl());
assert!(get_shard(&staging[0], k).holds_no_ttl());
}
}
#[cfg(test)]
mod shrink_tests {
use super::*;
use crate::types::KiviDBValue;
fn table(keys: usize) -> ShardLock {
let mut map = ShardMap::new();
for i in 0..keys {
map.insert(
format!("key-{i}"),
KiviDBValue::String(crate::types::SharedBytes::from(i.to_string().as_str())),
);
}
ShardLock::new(map)
}
fn value(map: &ShardLock, key: &str) -> Option<Vec<u8>> {
match map.read().get(key) {
Some(ValueRef::String(b)) => Some(b.to_vec()),
_ => None,
}
}
#[test]
fn a_table_keys_have_mostly_left_shrinks_once() {
let map = table(100_000);
let grown = map.read().capacity();
for i in (0..100_000).filter(|i| i % 10 != 0) {
map.write().remove(&format!("key-{i}"));
}
assert!(map.shrink_if_sparse());
let shrunk = map.read().capacity();
assert!(shrunk * 4 < grown, "{grown} -> {shrunk}");
assert!(shrunk >= 10_000 + 10_000 / 8, "no room left: {shrunk}");
assert_eq!(map.read().len(), 10_000);
assert_eq!(value(&map, "key-990"), Some(b"990".to_vec()));
assert!(!map.shrink_if_sparse());
}
#[test]
fn a_list_of_times_to_live_most_have_left_shrinks() {
let map = table(10_000);
for i in 0..10_000 {
map.write().set_expires(&format!("key-{i}"), u64::MAX / 2);
}
let grown = {
let m = map.read();
assert_eq!(m.ttl_len(), 10_000);
m.ttl_len()
};
for i in (0..10_000).filter(|i| i % 10 != 0) {
assert!(map.write().persist(&format!("key-{i}")));
}
assert!(map.shrink_if_sparse());
assert_eq!(map.read().ttl_len(), 1_000);
assert_eq!(map.read().len(), 10_000);
assert_eq!(map.read().expires("key-990"), Some(u64::MAX / 2));
assert_eq!(map.read().expires("key-991"), None);
assert!(grown > 1_000);
assert!(!map.shrink_if_sparse());
}
#[test]
fn full_small_and_just_grown_tables_are_left_alone() {
let map = table(100_000);
assert!(!map.shrink_if_sparse());
let small = table(100);
small.write().clear();
assert!(!small.shrink_if_sparse());
let map = table(0);
let mut i = 0u64;
loop {
let before = map.read().capacity();
map.write().insert_str(format!("key-{i}"), b"v");
i += 1;
if before >= 4096 && map.read().capacity() > before {
break;
}
}
assert!(!map.shrink_if_sparse());
}
}
#[cfg(test)]
mod shard_lock_tests {
use super::*;
use crate::types::KiviDBValue;
fn s() -> KiviDBValue {
KiviDBValue::String(crate::types::SharedBytes::from(&b"v"[..]))
}
#[test]
fn the_count_follows_what_writers_do() {
let cell = ShardLock::default();
assert!(cell.holds_no_ttl());
assert!(cell.holds_no_keys());
cell.write().insert_str("k", b"v");
assert!(!cell.holds_no_keys());
cell.write().remove("k");
assert!(cell.holds_no_keys());
let t = u64::MAX / 2;
cell.write().insert_expiring("a", s(), Some(t + 5));
assert!(!cell.holds_no_ttl());
cell.write().insert_str("b", b"x");
cell.write().set_expires("b", t + 9);
assert_eq!(cell.ttl_count(), 2);
cell.write().remove("a");
assert!(!cell.holds_no_ttl());
cell.write().insert("b", s());
assert_eq!(cell.read().expires("b"), Some(t + 9));
cell.write().insert_expiring("b", s(), None);
assert!(cell.holds_no_ttl());
cell.write().insert_expiring("c", s(), Some(t + 1));
assert!(cell.write().persist("c"));
assert!(cell.holds_no_ttl());
cell.write().set_expires("c", t + 3);
cell.write().clear();
assert!(cell.holds_no_ttl());
cell.write().insert_expiring("d", s(), Some(1));
assert_eq!(cell.ttl_count(), 1);
cell.write().insert("d", s());
assert!(cell.holds_no_ttl());
assert_eq!(cell.read().expires("d"), None);
cell.write().clear();
let other = ShardLock::default();
other.write().insert_expiring("c", s(), Some(t + 2));
std::mem::swap(&mut *cell.write(), &mut *other.write());
assert!(!cell.holds_no_ttl());
assert!(other.holds_no_ttl());
assert!(!cell.holds_no_keys());
assert!(other.holds_no_keys());
assert_eq!(cell.read().ttl_len(), 1);
}
}