use std::time::Duration;
use parking_lot::Mutex;
use crate::histogram::Histogram;
use crate::metric::Kind;
use crate::recorder::Sample;
use crate::tag::{Name, Tags};
use crate::value::{Encoding, NumberValue, StateValue};
pub trait Sink: Send + Sync {
fn push(&self, batch: Batch);
}
impl<F: Fn(Batch) + Send + Sync> Sink for F {
fn push(&self, batch: Batch) {
self(batch)
}
}
#[derive(Default)]
pub struct VecSink {
batches: Mutex<Vec<Batch>>,
}
impl VecSink {
pub fn new() -> Self {
VecSink::default()
}
pub fn take(&self) -> Vec<Batch> {
std::mem::take(&mut *self.batches.lock())
}
pub fn len(&self) -> usize {
self.batches.lock().len()
}
pub fn is_empty(&self) -> bool {
self.batches.lock().is_empty()
}
}
impl Sink for VecSink {
fn push(&self, batch: Batch) {
self.batches.lock().push(batch);
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Batch {
pub common_tags: Tags,
pub series: Vec<SeriesBatch>,
pub dropped: Vec<Dropped>,
}
impl Batch {
pub fn is_empty(&self) -> bool {
self.series.is_empty() && self.dropped.is_empty()
}
pub fn series(&self, name: &str, tags: &Tags) -> Option<&SeriesBatch> {
self.series.iter().find(|s| {
s.name == name && s.tags.len() == tags.len() && tags.iter().all(|t| s.tags.contains(t))
})
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct SeriesBatch {
pub name: Name,
pub kind: Kind,
pub encoding: Encoding,
pub tags: Tags,
pub resolution: Duration,
pub points: Points,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Points {
Counts(Vec<(u64, u64)>),
Numbers(Vec<(u64, NumberValue)>),
States(Vec<(u64, StateValue)>),
Histograms(Vec<(u64, Histogram)>),
Samples(Vec<(u64, Sample)>),
}
impl Points {
pub fn len(&self) -> usize {
match self {
Points::Counts(v) => v.len(),
Points::Numbers(v) => v.len(),
Points::States(v) => v.len(),
Points::Histograms(v) => v.len(),
Points::Samples(v) => v.len(),
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn counts(&self) -> Option<&[(u64, u64)]> {
match self {
Points::Counts(v) => Some(v),
_ => None,
}
}
pub fn numbers(&self) -> Option<&[(u64, NumberValue)]> {
match self {
Points::Numbers(v) => Some(v),
_ => None,
}
}
pub fn states(&self) -> Option<&[(u64, StateValue)]> {
match self {
Points::States(v) => Some(v),
_ => None,
}
}
pub fn histograms(&self) -> Option<&[(u64, Histogram)]> {
match self {
Points::Histograms(v) => Some(v),
_ => None,
}
}
pub fn samples(&self) -> Option<&[(u64, Sample)]> {
match self {
Points::Samples(v) => Some(v),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dropped {
pub name: Name,
pub tags: Tags,
pub count: u64,
pub from_ns: u64,
pub to_ns: u64,
}