use super::*;
use crate::graph_descriptor_page::GraphDescriptorPageLimits;
use std::cell::{Cell, RefCell};
use std::marker::PhantomData;
const SCOPE_SLOTS: usize = 8;
const SCOPE_CAPACITY_DIVISOR: u64 = 8;
#[derive(Clone)]
pub(super) struct RetainedLeaf {
pub(super) reference: Arc<GraphDescriptorPageRef>,
pub(super) page: GraphDescriptorPageView,
}
impl RetainedLeaf {
fn strictly_contains_prefix(&self, prefix: &[u8]) -> bool {
let first = self.reference.lower_bound.as_slice();
let last = self.reference.upper_bound.as_slice();
first < prefix && last > prefix && !last.starts_with(prefix)
}
}
struct ScopeSlot {
root: Arc<GraphDescriptorTreeRoot>,
limits: GraphDescriptorPageLimits,
leaf: RetainedLeaf,
}
impl ScopeSlot {
fn belongs_to(
&self,
root: &Arc<GraphDescriptorTreeRoot>,
limits: GraphDescriptorPageLimits,
) -> bool {
Arc::ptr_eq(&self.root, root) && self.limits == limits
}
}
struct ScopeState {
depth: usize,
slots: Vec<ScopeSlot>,
}
thread_local! {
static SCOPE: RefCell<ScopeState> = const {
RefCell::new(ScopeState {
depth: 0,
slots: Vec::new(),
})
};
static RETAINED_LEAF_HITS: Cell<u64> = const { Cell::new(0) };
}
#[must_use = "descriptor scans reuse leaves only while the scope is open"]
pub struct DescriptorLeafScope {
_thread_bound: PhantomData<*const ()>,
}
impl DescriptorLeafScope {
pub fn enter() -> Self {
let _ = SCOPE.try_with(|scope| {
let mut scope = scope.borrow_mut();
scope.depth = scope.depth.saturating_add(1);
});
Self {
_thread_bound: PhantomData,
}
}
}
impl Drop for DescriptorLeafScope {
fn drop(&mut self) {
let released = SCOPE
.try_with(|scope| {
let mut scope = scope.borrow_mut();
scope.depth = scope.depth.saturating_sub(1);
if scope.depth == 0 {
std::mem::take(&mut scope.slots)
} else {
Vec::new()
}
})
.unwrap_or_default();
drop(released);
}
}
#[doc(hidden)]
pub fn descriptor_retained_leaf_hits_for_test() -> u64 {
RETAINED_LEAF_HITS.with(Cell::get)
}
pub(super) fn retained_leaf(
root: &Arc<GraphDescriptorTreeRoot>,
limits: GraphDescriptorPageLimits,
prefix: &[u8],
) -> Option<RetainedLeaf> {
let leaf = SCOPE
.try_with(|scope| {
let mut scope = scope.borrow_mut();
if scope.depth == 0 {
return None;
}
let index = scope.slots.iter().rposition(|slot| {
slot.belongs_to(root, limits) && slot.leaf.strictly_contains_prefix(prefix)
})?;
let last = scope.slots.len() - 1;
if index != last {
scope.slots[index..].rotate_left(1);
}
Some(scope.slots[last].leaf.clone())
})
.ok()
.flatten();
if leaf.is_some() {
RETAINED_LEAF_HITS.with(|hits| hits.set(hits.get().saturating_add(1)));
}
leaf
}
pub(super) fn is_open() -> bool {
SCOPE
.try_with(|scope| scope.borrow().depth > 0)
.unwrap_or(false)
}
pub(super) fn retain_leaf(
root: &Arc<GraphDescriptorTreeRoot>,
limits: GraphDescriptorPageLimits,
leaf: RetainedLeaf,
cache_capacity_bytes: u64,
) {
if !leaf.page.is_cache_resident() {
return;
}
let budget = cache_capacity_bytes / SCOPE_CAPACITY_DIVISOR;
let bytes = leaf.page.resident_charge();
let evicted = SCOPE
.try_with(|scope| {
let mut scope = scope.borrow_mut();
if scope.depth == 0 || bytes > budget {
return (Vec::new(), Some(leaf));
}
let mut evicted = Vec::new();
if let Some(index) = scope.slots.iter().position(|slot| {
slot.belongs_to(root, limits)
&& slot.leaf.reference.page_id == leaf.reference.page_id
}) {
evicted.push(scope.slots.remove(index));
}
let mut retained = scope
.slots
.iter()
.map(|slot| slot.leaf.page.resident_charge())
.fold(bytes, u64::saturating_add);
while !scope.slots.is_empty() && (scope.slots.len() >= SCOPE_SLOTS || retained > budget)
{
let slot = scope.slots.remove(0);
retained = retained.saturating_sub(slot.leaf.page.resident_charge());
evicted.push(slot);
}
scope.slots.push(ScopeSlot {
root: Arc::clone(root),
limits,
leaf,
});
(evicted, None)
})
.unwrap_or_default();
drop(evicted);
}
#[cfg(test)]
pub(super) fn retained_leaves() -> usize {
SCOPE.with(|scope| scope.borrow().slots.len())
}