use std::cell::Cell;
use std::sync::OnceLock;
use std::time::Duration;
use parking_lot::Mutex;
use crate::writer_admission_metrics::{Histogram, HistogramSnapshot, Unavailable};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum LeaseClass {
WriterTask,
Pooled,
Standalone,
Bootstrap,
Migration,
Maintenance,
}
impl LeaseClass {
pub(crate) const ALL: [LeaseClass; 6] = [
LeaseClass::WriterTask,
LeaseClass::Pooled,
LeaseClass::Standalone,
LeaseClass::Bootstrap,
LeaseClass::Migration,
LeaseClass::Maintenance,
];
pub(crate) fn as_str(self) -> &'static str {
match self {
LeaseClass::WriterTask => "writer_task",
LeaseClass::Pooled => "pooled",
LeaseClass::Standalone => "standalone",
LeaseClass::Bootstrap => "bootstrap",
LeaseClass::Migration => "migration",
LeaseClass::Maintenance => "maintenance",
}
}
}
thread_local! {
static SCOPED_CLASS: Cell<Option<LeaseClass>> = const { Cell::new(None) };
}
pub(crate) struct LeaseClassScope {
previous: Option<LeaseClass>,
}
pub(crate) fn lease_class_scope(class: LeaseClass) -> LeaseClassScope {
LeaseClassScope {
previous: SCOPED_CLASS.with(|scoped| scoped.replace(Some(class))),
}
}
impl Drop for LeaseClassScope {
fn drop(&mut self) {
SCOPED_CLASS.with(|scoped| scoped.set(self.previous));
}
}
pub(crate) fn effective_class(site: LeaseClass) -> LeaseClass {
SCOPED_CLASS.with(Cell::get).unwrap_or(site)
}
struct Holds {
unavailable: Option<Unavailable>,
by_class: [Histogram; 6],
}
fn holds() -> &'static Mutex<Holds> {
static HOLDS: OnceLock<Mutex<Holds>> = OnceLock::new();
HOLDS.get_or_init(|| {
Mutex::new(Holds {
unavailable: None,
by_class: Default::default(),
})
})
}
fn index(class: LeaseClass) -> usize {
LeaseClass::ALL
.iter()
.position(|candidate| *candidate == class)
.unwrap_or(0)
}
pub(super) fn record(class: LeaseClass, held: Duration) {
let mut holds = holds().lock();
if holds.unavailable.is_some() {
return;
}
if let Err(reason) = holds.by_class[index(class)].record(held) {
holds.unavailable = Some(reason);
}
}
pub(crate) fn lease_hold_snapshot() -> Result<Vec<(LeaseClass, HistogramSnapshot)>, Unavailable> {
let holds = holds().lock();
if let Some(reason) = holds.unavailable {
return Err(reason);
}
LeaseClass::ALL
.iter()
.map(|class| Ok((*class, holds.by_class[index(*class)].snapshot()?)))
.collect()
}