khive_db/disk_guard/
lease_hold.rs1use std::cell::Cell;
9use std::future::Future;
10use std::marker::PhantomData;
11use std::pin::Pin;
12use std::sync::OnceLock;
13use std::task::{Context, Poll};
14use std::time::Duration;
15
16use parking_lot::Mutex;
17
18use crate::writer_admission_metrics::{Histogram, HistogramSnapshot, Unavailable};
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub(crate) enum LeaseClass {
23 WriterTask,
25 Pooled,
27 Standalone,
29 Bootstrap,
31 Migration,
33 Maintenance,
35}
36
37impl LeaseClass {
38 pub(crate) const ALL: [LeaseClass; 6] = [
39 LeaseClass::WriterTask,
40 LeaseClass::Pooled,
41 LeaseClass::Standalone,
42 LeaseClass::Bootstrap,
43 LeaseClass::Migration,
44 LeaseClass::Maintenance,
45 ];
46
47 pub(crate) fn as_str(self) -> &'static str {
48 match self {
49 LeaseClass::WriterTask => "writer_task",
50 LeaseClass::Pooled => "pooled",
51 LeaseClass::Standalone => "standalone",
52 LeaseClass::Bootstrap => "bootstrap",
53 LeaseClass::Migration => "migration",
54 LeaseClass::Maintenance => "maintenance",
55 }
56 }
57}
58
59thread_local! {
60 static SCOPED_CLASS: Cell<Option<LeaseClass>> = const { Cell::new(None) };
61}
62
63pub(crate) struct LeaseClassScope {
72 previous: Option<LeaseClass>,
73 _thread_bound: PhantomData<*const ()>,
74}
75
76pub(crate) fn lease_class_scope(class: LeaseClass) -> LeaseClassScope {
77 LeaseClassScope {
78 previous: SCOPED_CLASS.with(|scoped| scoped.replace(Some(class))),
79 _thread_bound: PhantomData,
80 }
81}
82
83impl Drop for LeaseClassScope {
84 fn drop(&mut self) {
85 SCOPED_CLASS.with(|scoped| scoped.set(self.previous));
86 }
87}
88
89fn scoped_class() -> Option<LeaseClass> {
91 SCOPED_CLASS.with(Cell::get)
92}
93
94pub(crate) fn effective_class(site: LeaseClass) -> LeaseClass {
99 if site == LeaseClass::Bootstrap {
100 return site;
101 }
102 scoped_class().unwrap_or(site)
103}
104
105#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
115pub struct WriteClassContext {
116 class: Option<LeaseClass>,
117}
118
119impl WriteClassContext {
120 pub fn migration() -> Self {
123 Self {
124 class: Some(LeaseClass::Migration),
125 }
126 }
127
128 pub fn capture() -> Self {
131 Self {
132 class: scoped_class(),
133 }
134 }
135
136 pub(crate) fn enter(self) -> Option<LeaseClassScope> {
137 self.class.map(lease_class_scope)
138 }
139
140 pub fn wrap_blocking<F, R>(self, f: F) -> impl FnOnce() -> R + Send
143 where
144 F: FnOnce() -> R + Send,
145 {
146 move || {
147 let _scope = self.enter();
148 f()
149 }
150 }
151
152 pub fn scope_future<F: Future>(self, future: F) -> ScopedFuture<F> {
156 ScopedFuture {
157 context: self,
158 future: Box::pin(future),
159 }
160 }
161}
162
163pub struct ScopedFuture<F> {
166 context: WriteClassContext,
167 future: Pin<Box<F>>,
168}
169
170impl<F: Future> Future for ScopedFuture<F> {
171 type Output = F::Output;
172
173 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
174 let _scope = self.context.enter();
175 self.future.as_mut().poll(cx)
176 }
177}
178
179struct Holds {
180 unavailable: Option<Unavailable>,
181 by_class: [Histogram; 6],
182}
183
184fn holds() -> &'static Mutex<Holds> {
185 static HOLDS: OnceLock<Mutex<Holds>> = OnceLock::new();
186 HOLDS.get_or_init(|| {
187 Mutex::new(Holds {
188 unavailable: None,
189 by_class: Default::default(),
190 })
191 })
192}
193
194fn index(class: LeaseClass) -> usize {
195 LeaseClass::ALL
196 .iter()
197 .position(|candidate| *candidate == class)
198 .unwrap_or(0)
199}
200
201pub(super) fn record(class: LeaseClass, held: Duration) {
203 let mut holds = holds().lock();
204 if holds.unavailable.is_some() {
205 return;
206 }
207 if let Err(reason) = holds.by_class[index(class)].record(held) {
208 holds.unavailable = Some(reason);
209 }
210}
211
212pub(crate) fn lease_hold_snapshot() -> Result<Vec<(LeaseClass, HistogramSnapshot)>, Unavailable> {
215 let holds = holds().lock();
216 if let Some(reason) = holds.unavailable {
217 return Err(reason);
218 }
219 LeaseClass::ALL
220 .iter()
221 .map(|class| Ok((*class, holds.by_class[index(*class)].snapshot()?)))
222 .collect()
223}
224
225#[cfg(test)]
226#[path = "lease_class_tests.rs"]
227mod lease_class_tests;