use std::cell::Cell;
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::OnceLock;
use std::task::{Context, Poll};
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>,
_thread_bound: PhantomData<*const ()>,
}
pub(crate) fn lease_class_scope(class: LeaseClass) -> LeaseClassScope {
LeaseClassScope {
previous: SCOPED_CLASS.with(|scoped| scoped.replace(Some(class))),
_thread_bound: PhantomData,
}
}
impl Drop for LeaseClassScope {
fn drop(&mut self) {
SCOPED_CLASS.with(|scoped| scoped.set(self.previous));
}
}
fn scoped_class() -> Option<LeaseClass> {
SCOPED_CLASS.with(Cell::get)
}
pub(crate) fn effective_class(site: LeaseClass) -> LeaseClass {
if site == LeaseClass::Bootstrap {
return site;
}
scoped_class().unwrap_or(site)
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct WriteClassContext {
class: Option<LeaseClass>,
}
impl WriteClassContext {
pub fn migration() -> Self {
Self {
class: Some(LeaseClass::Migration),
}
}
pub fn capture() -> Self {
Self {
class: scoped_class(),
}
}
pub(crate) fn enter(self) -> Option<LeaseClassScope> {
self.class.map(lease_class_scope)
}
pub fn wrap_blocking<F, R>(self, f: F) -> impl FnOnce() -> R + Send
where
F: FnOnce() -> R + Send,
{
move || {
let _scope = self.enter();
f()
}
}
pub fn scope_future<F: Future>(self, future: F) -> ScopedFuture<F> {
ScopedFuture {
context: self,
future: Box::pin(future),
}
}
}
pub struct ScopedFuture<F> {
context: WriteClassContext,
future: Pin<Box<F>>,
}
impl<F: Future> Future for ScopedFuture<F> {
type Output = F::Output;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let _scope = self.context.enter();
self.future.as_mut().poll(cx)
}
}
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()
}
#[cfg(test)]
#[path = "lease_class_tests.rs"]
mod lease_class_tests;