use std::num::NonZeroUsize;
use super::TelemetryError;
pub struct RingBuffer<T> {
storage: Vec<T>,
capacity: NonZeroUsize,
write_head: usize,
total_pushed: u64,
}
impl<T> RingBuffer<T> {
pub fn new(capacity: usize) -> Result<Self, TelemetryError> {
let capacity = NonZeroUsize::new(capacity).ok_or(TelemetryError::InvalidCapacity(0))?;
Ok(Self::sized(capacity))
}
const fn sized(capacity: NonZeroUsize) -> Self {
Self {
storage: Vec::new(),
capacity,
write_head: 0,
total_pushed: 0,
}
}
pub fn push(&mut self, item: T) {
if self.storage.len() < self.capacity.get() {
self.storage.push(item);
} else {
self.storage[self.write_head] = item;
self.write_head = cycle_next(self.write_head, self.capacity);
}
self.total_pushed = self.total_pushed.wrapping_add(1);
}
#[must_use]
pub fn count(&self) -> usize {
self.storage.len()
}
#[must_use]
pub const fn total_pushed(&self) -> u64 {
self.total_pushed
}
#[must_use]
pub fn snapshot(&self) -> Vec<T>
where
T: Clone,
{
(0..self.storage.len())
.map(|offset| self.storage[cycle_add(self.write_head, offset, self.capacity)].clone())
.collect()
}
}
fn cycle_add(position: usize, offset: usize, capacity: NonZeroUsize) -> usize {
position.saturating_add(offset) % capacity
}
fn cycle_next(position: usize, capacity: NonZeroUsize) -> usize {
cycle_add(position, 1, capacity)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct TelemetryMetrics {
emits_observed: u64,
append_errors: u64,
tap_latency_p99_microseconds: u64,
}
impl TelemetryMetrics {
#[must_use]
pub const fn new(
emits_observed: u64,
append_errors: u64,
tap_latency_p99_microseconds: u64,
) -> Self {
Self {
emits_observed,
append_errors,
tap_latency_p99_microseconds,
}
}
#[must_use]
pub const fn emits_observed(&self) -> u64 {
self.emits_observed
}
#[must_use]
pub const fn append_errors(&self) -> u64 {
self.append_errors
}
#[must_use]
pub const fn tap_latency_p99_microseconds(&self) -> u64 {
self.tap_latency_p99_microseconds
}
}
pub struct LatencyTracker {
samples: RingBuffer<u64>,
}
impl LatencyTracker {
#[must_use]
pub fn new() -> Self {
Self::with_capacity(1_000)
}
#[must_use]
pub fn with_capacity(sample_capacity: usize) -> Self {
let capacity = NonZeroUsize::MIN.saturating_add(sample_capacity.saturating_sub(1));
Self {
samples: RingBuffer::sized(capacity),
}
}
pub fn record(&mut self, nanoseconds: u64) {
self.samples.push(nanoseconds);
}
#[must_use]
pub fn p99_microseconds(&self) -> u64 {
let mut sorted = self.samples.snapshot();
if sorted.is_empty() {
return 0;
}
sorted.sort_unstable();
let last = sorted.len().saturating_sub(1);
let index = last.wrapping_mul(99).wrapping_div(100);
sorted[index].wrapping_div(1_000)
}
}
impl Default for LatencyTracker {
fn default() -> Self {
Self::new()
}
}