use std::future::{Future, IntoFuture};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant};
use crate::history::{Activity, CustomTab, Measure, Message, Query};
tokio::task_local! {
static CURRENT: Arc<Recorder>;
}
pub struct Recorder {
started: Instant,
active: AtomicBool,
collected: Mutex<Collected>,
}
pub struct PendingMeasure {
pub label: String,
pub started: Instant,
}
#[derive(Default)]
pub struct Collected {
pub queries: Vec<Query>,
pub messages: Vec<Message>,
pub activity: Vec<Activity>,
pub measures: Vec<Measure>,
pub custom: Vec<CustomTab>,
pub pending_measures: Vec<PendingMeasure>,
pub queries_excluded: usize,
pub hard_limited: bool,
pub session: Option<serde_json::Value>,
pub user: Option<serde_json::Value>,
}
impl Recorder {
pub fn with_active(active: bool) -> Self {
Self {
started: Instant::now(),
active: AtomicBool::new(active),
collected: Mutex::default(),
}
}
pub fn is_active(&self) -> bool {
self.active.load(Ordering::Relaxed)
}
pub fn set_active(&self, active: bool) {
self.active.store(active, Ordering::Relaxed);
}
pub fn elapsed(&self) -> Duration {
self.started.elapsed()
}
pub fn since_start(&self, at: Instant) -> f64 {
milliseconds(at.saturating_duration_since(self.started))
}
pub async fn scope<F: Future>(self: Arc<Self>, future: F) -> F::Output {
CURRENT.scope(self, future).await
}
pub fn take(&self) -> Collected {
std::mem::take(&mut *self.collected.lock().unwrap_or_else(PoisonError::into_inner))
}
pub fn collect(&self, add: impl FnOnce(&Self, &mut Collected)) {
add(self, &mut self.collected.lock().unwrap_or_else(PoisonError::into_inner));
}
}
pub fn in_request() -> Option<Arc<Recorder>> {
CURRENT.try_with(Arc::clone).ok()
}
pub fn current() -> Option<Arc<Recorder>> {
in_request().or_else(crate::messages::span_recorder)
}
pub fn record(add: impl FnOnce(&Recorder, &mut Collected)) {
if let Some(recorder) = current() {
recorder.collect(add);
}
}
pub async fn measure<F: IntoFuture>(label: impl Into<String>, future: F) -> F::Output {
measure_with(label, Vec::<(String, String)>::new(), future).await
}
pub async fn measure_with<F, K, V>(
label: impl Into<String>,
params: impl IntoIterator<Item = (K, V)>,
future: F,
) -> F::Output
where
F: IntoFuture,
K: Into<String>,
V: ToString,
{
let started = Instant::now();
let output = future.await;
let duration = started.elapsed();
let params = params
.into_iter()
.map(|(key, value)| (key.into(), value.to_string()))
.collect();
record(|recorder, collected| {
collected.measures.push(Measure {
label: label.into(),
start_ms: recorder.since_start(started),
duration_ms: milliseconds(duration),
params,
});
});
output
}
pub fn milliseconds(duration: Duration) -> f64 {
duration.as_secs_f64() * 1000.0
}