Skip to main content

khive_db/disk_guard/
lease_hold.rs

1//! How long each volume lease was held, by what it was taken for.
2//!
3//! A held lease excludes every other writer on its volume (ADR-154 section 3),
4//! so its hold time is the time those writers can wait. The record is
5//! process-wide, like the in-process slot: one histogram per class, from grant
6//! to release, recorded when the lease drops. Recording never fails a write.
7
8use 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/// What a volume lease was taken for.
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub(crate) enum LeaseClass {
23    /// One request on a pool's FIFO writer task.
24    WriterTask,
25    /// A checkout of a pool's shared writer connection.
26    Pooled,
27    /// A standalone write connection or statement.
28    Standalone,
29    /// A new database's first write while its pool opens.
30    Bootstrap,
31    /// One schema migration transaction.
32    Migration,
33    /// VACUUM and FTS index maintenance.
34    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
63/// While it lives, every lease this thread takes is recorded as its class, for
64/// operations that reach a general acquisition site (a migration on the pooled
65/// writer, FTS maintenance on a standalone connection).
66///
67/// The scope is thread-local, so it is `!Send`: it cannot be held across an
68/// `.await` that may resume on another thread. Work that crosses a thread
69/// (the writer task, a blocking task, a spawned future) carries a
70/// [`WriteClassContext`] instead.
71pub(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
89/// The class this thread's scope assigns, if any.
90fn scoped_class() -> Option<LeaseClass> {
91    SCOPED_CLASS.with(Cell::get)
92}
93
94/// The class a lease taken here is recorded as: the scope's, else the site's.
95/// A new database's first write while its pool opens stays `Bootstrap` under
96/// any scope, so opening another pool inside migration work is still reported
97/// as the bootstrap it is.
98pub(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/// What the volume leases taken for a unit of work are recorded as, carried
106/// across the threads that work runs on.
107///
108/// The class a lease is recorded as comes from a thread-local scope at the site
109/// that takes it. Work that issues writes from one thread and takes the lease
110/// on another (the pool's writer task, a blocking task, a spawned future)
111/// loses that scope at the hop; this context carries it. It changes only how a
112/// lease is recorded in the lease-hold report, never whether or when a write is
113/// admitted.
114#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
115pub struct WriteClassContext {
116    class: Option<LeaseClass>,
117}
118
119impl WriteClassContext {
120    /// Schema work: every lease taken under this context is recorded as
121    /// migration class.
122    pub fn migration() -> Self {
123        Self {
124            class: Some(LeaseClass::Migration),
125        }
126    }
127
128    /// The calling thread's current context, to hand to work that runs on
129    /// another thread.
130    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    /// Wraps a synchronous closure so it runs under this context, on whatever
141    /// thread calls it.
142    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    /// Wraps a future so each poll runs under this context. The scope is
153    /// installed for the poll and removed before it returns, so it never spans
154    /// a suspension.
155    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
163/// A future polled under a [`WriteClassContext`]; see
164/// [`WriteClassContext::scope_future`].
165pub 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
201/// Records one lease of `class` held for `held`.
202pub(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
212/// Every class's hold histogram since this process started, or why none can
213/// be reported.
214pub(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;