use std::cell::Cell;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, OnceLock, PoisonError, Weak};
use std::time::{Duration, Instant};
use crate::sqlite::Readers;
#[allow(dead_code, reason = "each engine reports what it measures: a library built without it leaves its calls unused")]
pub(crate) trait Listen: Send + Sync {
fn committed(&self, file: &str, writes: usize, took: Duration, waits: &[Duration]);
fn failed(&self, task: &str);
fn count(&self, name: &'static str, labels: Labels<'_>, by: f64);
fn time(&self, name: &'static str, labels: Labels<'_>, took: Duration);
fn set(&self, name: &'static str, labels: Labels<'_>, value: f64);
fn shift(&self, name: &'static str, labels: Labels<'_>, delta: f64);
}
pub(crate) type Labels<'a> = &'a [(&'static str, &'a str)];
#[allow(dead_code, reason = "each engine reports what it measures: a library built without it leaves its calls unused")]
pub(crate) trait Sample: Send + Sync {
fn sample(&self, probe: &Probe);
}
#[derive(Default)]
pub(crate) struct Probe {
listener: OnceLock<Arc<dyn Listen>>,
#[cfg(feature = "metrics")]
files: Mutex<Vec<Opened>>,
#[allow(
dead_code,
reason = "each engine reports what it measures: a library built without it leaves its calls unused"
)]
samplers: Mutex<Vec<Weak<dyn Sample>>>,
}
#[cfg(feature = "metrics")]
struct Opened {
file: String,
path: PathBuf,
readers: Weak<Readers>,
}
#[cfg(feature = "metrics")]
pub(crate) struct OpenFile {
pub(crate) file: String,
pub(crate) path: PathBuf,
pub(crate) readers: usize,
}
#[allow(dead_code, reason = "each engine reports what it measures: a library built without it leaves its calls unused")]
impl Probe {
#[cfg(feature = "metrics")]
pub(crate) fn listen(&self, listener: Arc<dyn Listen>) {
let _ = self.listener.set(listener);
}
pub(crate) fn listening(&self) -> bool {
self.listener.get().is_some()
}
pub(crate) fn for_file(self: &Arc<Self>, file: String) -> FileProbe {
FileProbe { probe: Arc::clone(self), file }
}
pub(crate) fn failed(&self, task: &str) {
if let Some(listener) = self.listener.get() {
listener.failed(task);
}
}
pub(crate) fn count(&self, name: &'static str, labels: Labels<'_>, by: f64) {
if let Some(listener) = self.listener.get() {
listener.count(name, labels, by);
}
}
pub(crate) fn time(&self, name: &'static str, labels: Labels<'_>, took: Duration) {
if let Some(listener) = self.listener.get() {
listener.time(name, labels, took);
}
}
pub(crate) fn start(&self) -> Option<Instant> {
self.listening().then(Instant::now)
}
pub(crate) fn set(&self, name: &'static str, labels: Labels<'_>, value: f64) {
if let Some(listener) = self.listener.get() {
listener.set(name, labels, value);
}
}
pub(crate) fn shift(&self, name: &'static str, labels: Labels<'_>, delta: f64) {
if let Some(listener) = self.listener.get() {
listener.shift(name, labels, delta);
}
}
pub(crate) fn sampled(&self, sampler: Weak<dyn Sample>) {
self.samplers.lock().unwrap_or_else(PoisonError::into_inner).push(sampler);
}
#[cfg(feature = "metrics")]
pub(crate) fn sample(&self) {
let samplers: Vec<Arc<dyn Sample>> = {
let mut samplers = self.samplers.lock().unwrap_or_else(PoisonError::into_inner);
samplers.retain(|sampler| sampler.strong_count() > 0);
samplers.iter().filter_map(Weak::upgrade).collect()
};
for sampler in samplers {
sampler.sample(self);
}
}
#[cfg(feature = "metrics")]
pub(crate) fn files(&self) -> Vec<OpenFile> {
let mut files = self.files.lock().unwrap_or_else(PoisonError::into_inner);
files.retain(|opened| opened.readers.strong_count() > 0);
let open = |opened: &Opened| {
let readers = opened.readers.upgrade()?.open();
Some(OpenFile { file: opened.file.clone(), path: opened.path.clone(), readers })
};
files.iter().filter_map(open).collect()
}
}
#[derive(Clone)]
pub(crate) struct FileProbe {
probe: Arc<Probe>,
file: String,
}
impl std::fmt::Debug for FileProbe {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "FileProbe({})", self.file)
}
}
impl FileProbe {
pub(crate) fn queued(&self) -> Option<Instant> {
(self.probe.listening() && !UNMEASURED.get()).then(Instant::now)
}
pub(crate) fn committed(&self, took: Duration, waits: &[Duration]) {
if let (Some(listener), false) = (self.probe.listener.get(), waits.is_empty()) {
listener.committed(&self.file, waits.len(), took, waits);
}
}
#[cfg_attr(not(feature = "metrics"), expect(unused_variables, reason = "nothing reads a file's sizes"))]
pub(crate) fn opened(&self, path: PathBuf, readers: Weak<Readers>) {
#[cfg(feature = "metrics")]
let mut files = self.probe.files.lock().unwrap_or_else(PoisonError::into_inner);
#[cfg(feature = "metrics")]
files.push(Opened { file: self.file.clone(), path, readers });
}
}
thread_local! {
static UNMEASURED: Cell<bool> = const { Cell::new(false) };
}
#[cfg(feature = "metrics")]
pub(crate) fn unmeasured<T>(work: impl FnOnce() -> T) -> T {
struct Restore(bool);
impl Drop for Restore {
fn drop(&mut self) {
UNMEASURED.set(self.0);
}
}
let _restore = Restore(UNMEASURED.replace(true));
work()
}
pub(crate) fn label(name: &str) -> String {
name.strip_suffix(".db").unwrap_or(name).replace('\\', "/")
}
#[cfg(all(
test,
feature = "metrics",
any(
feature = "kv",
feature = "jobs",
feature = "records",
feature = "channels",
feature = "locks",
feature = "search",
feature = "blobs",
feature = "wire"
)
))]
#[path = "probe_tests.rs"]
mod probe_tests;