use std::fmt;
use std::future::Future;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use super::run;
use crate::Result;
use crate::cancel;
use crate::pool::Pool;
pub use crate::metrics::{
Aggregate, Bucket, Buckets, Builder, Condition, Counter, Damage, Description, Exceeds, Gauge, GaugeFunc, Histogram,
Kind, LabelPage, Labels, Latest, NameInfo, NamePage, Not, Op, Plan, Prefix, Reading, Recorder, Sample, Series,
Timer, Timing, Value, ValuePage, Values, exponential_buckets,
};
const INGEST: &str = "metrics: an ingest";
impl super::Store {
pub fn metrics(&self) -> Result<Metrics> {
Ok(Metrics { blocking: self.blocking().metrics()?, pool: Arc::clone(self.pool()) })
}
}
#[derive(Clone)]
pub struct Metrics {
blocking: crate::metrics::Metrics,
pool: Arc<Pool>,
}
impl From<crate::metrics::Metrics> for Metrics {
fn from(blocking: crate::metrics::Metrics) -> Metrics {
let pool = blocking.store().map_or_else(Pool::stopped, |store| Pool::of_or_stopped(&store));
Metrics { blocking, pool }
}
}
impl fmt::Debug for Metrics {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.blocking, f)
}
}
impl Metrics {
pub fn blocking(&self) -> &crate::metrics::Metrics {
&self.blocking
}
pub fn ingest(&self, series: &[Series]) -> impl Future<Output = Result<()>> + Send + 'static {
let (stats, series) = (self.blocking.clone(), series.to_vec());
run::holding(&self.pool, self.blocking.memory(), INGEST.to_owned(), move || {
let checked = stats.check(&series)?;
Ok((checked.holds(), move |held| stats.ingest_checked(checked, held)))
})
}
pub fn query(&self) -> Query {
Query { blocking: self.blocking.query(), pool: Arc::clone(&self.pool) }
}
pub fn prometheus(&self) -> Prometheus {
Prometheus { blocking: self.blocking.prometheus(), stats: self.blocking.clone(), pool: Arc::clone(&self.pool) }
}
pub fn names(&self) -> List<NamePage> {
self.list(self.blocking.names())
}
pub fn label_names(&self, name: impl Into<String>) -> List<LabelPage> {
self.list(self.blocking.label_names(name))
}
pub fn label_values(&self, name: impl Into<String>, label: impl Into<String>) -> List<ValuePage> {
self.list(self.blocking.label_values(name, label))
}
pub fn describe(&self, name: &str, description: Description) -> impl Future<Output = Result<()>> + Send + 'static {
let (stats, name) = (self.blocking.clone(), name.to_owned());
let what = format!("metrics {name}: its description");
run::blocking(&self.pool, None, what, move || stats.describe(&name, description))
}
pub fn description(&self, name: &str) -> impl Future<Output = Result<Description>> + Send + 'static {
let (stats, name) = (self.blocking.clone(), name.to_owned());
run::point(&self.pool, format!("metrics {name}: its description"), move || stats.description(&name))
}
pub fn damaged(&self) -> impl Future<Output = Result<Vec<Damage>>> + Send + 'static {
let stats = self.blocking.clone();
run::read(&self.pool, "metrics: the damaged series".to_owned(), move || stats.damaged())
}
pub fn delete<K: AsRef<str>, V: AsRef<str>>(
&self,
name: &str,
labels: impl IntoIterator<Item = (K, V)>,
) -> impl Future<Output = Result<bool>> + Send + 'static {
let labels: Vec<(String, String)> =
labels.into_iter().map(|(label, value)| (label.as_ref().to_owned(), value.as_ref().to_owned())).collect();
let (stats, name) = (self.blocking.clone(), name.to_owned());
let what = format!("metrics {name}: a delete");
run::blocking(&self.pool, None, what, move || stats.delete(&name, labels))
}
pub fn flush(&self) -> impl Future<Output = Result<()>> + Send + 'static {
let stats = self.blocking.clone();
run::blocking(&self.pool, None, "metrics: a flush".to_owned(), move || stats.flush())
}
pub fn counter(&self, name: impl Into<String>) -> Builder<Counter> {
self.blocking.counter(name)
}
pub fn gauge(&self, name: impl Into<String>) -> Builder<Gauge> {
self.blocking.gauge(name)
}
pub fn gauge_func<R: Reading>(
&self,
name: impl Into<String>,
read: impl Fn() -> R + Send + Sync + 'static,
) -> Builder<GaugeFunc> {
self.blocking.gauge_func(name, read)
}
pub fn timer(&self, name: impl Into<String>) -> Builder<Timer> {
self.blocking.timer(name)
}
pub fn histogram(&self, name: impl Into<String>) -> Builder<Histogram> {
self.blocking.histogram(name)
}
pub fn recorder(&self) -> Recorder {
self.blocking.recorder()
}
fn list<P>(&self, blocking: crate::metrics::List<P>) -> List<P> {
List { blocking, pool: Arc::clone(&self.pool) }
}
}
#[derive(Clone)]
pub struct Query {
blocking: crate::metrics::Query,
pool: Arc<Pool>,
}
impl fmt::Debug for Query {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.blocking, f)
}
}
impl Query {
pub fn name(self, name: impl Into<String>) -> Self {
self.with(|query| query.name(name))
}
pub fn filter(self, label: impl Into<String>, condition: impl Into<Condition>) -> Self {
self.with(|query| query.filter(label, condition))
}
pub fn since(self, span: Duration) -> Self {
self.with(|query| query.since(span))
}
pub fn from(self, at: SystemTime) -> Self {
self.with(|query| query.from(at))
}
pub fn to(self, at: SystemTime) -> Self {
self.with(|query| query.to(at))
}
pub fn every(self, span: Duration) -> Self {
self.with(|query| query.every(span))
}
pub fn calendar(self, unit: crate::Calendar, zone: &str) -> Self {
self.with(|query| query.calendar(unit, zone))
}
pub fn by(self, labels: &[&str]) -> Self {
self.with(|query| query.by(labels))
}
pub fn without(self, labels: &[&str]) -> Self {
self.with(|query| query.without(labels))
}
pub fn estimate(self) -> Self {
self.with(crate::metrics::Query::estimate)
}
pub fn read(&self) -> impl Future<Output = Result<Vec<Series>>> + Send + 'static {
let query = self.blocking.clone();
checked_then_read(&self.pool, "metrics: a read", move || query.checked_read())
}
pub fn aggregate(&self, op: Op) -> impl Future<Output = Result<Vec<Aggregate>>> + Send + 'static {
let query = self.blocking.clone();
checked_then_read(&self.pool, "metrics: an aggregate", move || query.checked_aggregate(op))
}
pub fn latest(&self) -> impl Future<Output = Result<Vec<Latest>>> + Send + 'static {
let query = self.blocking.clone();
checked_then_read(&self.pool, "metrics: the newest samples", move || query.checked_latest())
}
pub fn explain(&self, op: impl Into<Option<Op>>) -> impl Future<Output = Result<Plan>> + Send + 'static {
let (query, op) = (self.blocking.clone(), op.into());
checked_then_read(&self.pool, "metrics: a plan", move || query.checked_explain(op))
}
fn with(self, change: impl FnOnce(crate::metrics::Query) -> crate::metrics::Query) -> Self {
Query { blocking: change(self.blocking), pool: self.pool }
}
}
fn checked_then_read<T, C, R>(
pool: &Arc<Pool>,
what: &str,
check: C,
) -> impl Future<Output = Result<T>> + Send + 'static + use<T, C, R>
where
C: FnOnce() -> Result<R> + Send + 'static,
R: FnOnce() -> Result<T> + Send + 'static,
T: Send + 'static,
{
let (pool, what, tokens) = (Arc::clone(pool), what.to_owned(), cancel::captured());
async move {
let read = check()?;
let reading = tokens.run(None, || run::read(&pool, what, read));
reading.await
}
}
#[derive(Clone)]
#[must_use = "a list reads nothing until its page"]
pub struct List<P> {
blocking: crate::metrics::List<P>,
pool: Arc<Pool>,
}
impl<P> fmt::Debug for List<P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.blocking, f)
}
}
impl<P> List<P> {
pub fn prefix(self, prefix: impl Into<String>) -> Self {
List { blocking: self.blocking.prefix(prefix), pool: self.pool }
}
pub fn after(self, next: impl Into<String>) -> Self {
List { blocking: self.blocking.after(next), pool: self.pool }
}
pub fn limit(self, most: usize) -> Self {
List { blocking: self.blocking.limit(most), pool: self.pool }
}
}
impl List<NamePage> {
pub fn page(self) -> impl Future<Output = Result<NamePage>> + Send + 'static {
let list = self.blocking;
run::read(&self.pool, "metrics: a page of names".to_owned(), move || list.page())
}
}
impl List<LabelPage> {
pub fn page(self) -> impl Future<Output = Result<LabelPage>> + Send + 'static {
let list = self.blocking;
run::read(&self.pool, "metrics: a page of labels".to_owned(), move || list.page())
}
}
impl List<ValuePage> {
pub fn page(self) -> impl Future<Output = Result<ValuePage>> + Send + 'static {
let list = self.blocking;
run::read(&self.pool, "metrics: a page of values".to_owned(), move || list.page())
}
}
#[derive(Clone)]
#[must_use = "a text is written by ingest"]
pub struct Prometheus {
blocking: crate::metrics::Prometheus,
stats: crate::metrics::Metrics,
pool: Arc<Pool>,
}
impl fmt::Debug for Prometheus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.blocking, f)
}
}
impl Prometheus {
pub fn label(self, name: impl Into<String>, value: impl fmt::Display) -> Prometheus {
self.with(|blocking| blocking.label(name, value))
}
pub fn at(self, at: SystemTime) -> Prometheus {
self.with(|blocking| blocking.at(at))
}
pub fn keep(self, keep: Duration) -> Prometheus {
self.with(|blocking| blocking.keep(keep))
}
pub fn ingest(&self, text: impl AsRef<[u8]>) -> impl Future<Output = Result<()>> + Send + 'static {
let (prometheus, text) = (self.blocking.clone(), text.as_ref().to_vec());
let (pool, memory) = (Arc::clone(&self.pool), Arc::clone(self.stats.memory()));
async move {
let prometheus = prometheus.timed();
let ingesting = run::holding(&pool, &memory, INGEST.to_owned(), move || {
Ok((prometheus.holds(&text), move |held| prometheus.ingest_held(&text, held)))
});
ingesting.await
}
}
fn with(self, change: impl FnOnce(crate::metrics::Prometheus) -> crate::metrics::Prometheus) -> Prometheus {
Prometheus { blocking: change(self.blocking), ..self }
}
}
#[cfg(test)]
#[path = "metrics_tests.rs"]
mod tests;