use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
use serde::Serialize;
use crate::service::{Counts, ErrorType, Lane};
const OTHER_CODES: [&str; 1] = ["other"];
const BUCKETS: usize = 512;
#[derive(Debug)]
pub(crate) struct Metrics {
pub(crate) in_flight: AtomicU64,
pub(crate) fast_in_flight: AtomicU64,
search: AtomicU64,
stats: AtomicU64,
append: AtomicU64,
replace: AtomicU64,
remove: AtomicU64,
other: AtomicU64,
errors: [AtomicU64; ErrorType::ALL.len() + OTHER_CODES.len()],
queries: AtomicU64,
candidates: AtomicU64,
cut_limit: AtomicU64,
cut_time: AtomicU64,
cut_size: AtomicU64,
fast: Histogram,
bulk: Histogram,
pub(crate) file: FileCounts,
}
#[derive(Debug, Default)]
pub(crate) struct FileCounts {
pub(crate) bulk_answered: AtomicU64,
pub(crate) bulk_failed: AtomicU64,
pub(crate) fast_answered: AtomicU64,
pub(crate) fast_failed: AtomicU64,
pub(crate) failed: [AtomicU64; Name::ALL.len()],
pub(crate) matches: AtomicU64,
pub(crate) incomplete: AtomicU64,
pub(crate) bulk_times: Histogram,
pub(crate) fast_times: Histogram,
}
impl Default for Metrics {
fn default() -> Self {
Self {
in_flight: AtomicU64::new(0),
fast_in_flight: AtomicU64::new(0),
search: AtomicU64::new(0),
stats: AtomicU64::new(0),
append: AtomicU64::new(0),
replace: AtomicU64::new(0),
remove: AtomicU64::new(0),
other: AtomicU64::new(0),
errors: std::array::from_fn(|_| AtomicU64::new(0)),
queries: AtomicU64::new(0),
candidates: AtomicU64::new(0),
cut_limit: AtomicU64::new(0),
cut_time: AtomicU64::new(0),
cut_size: AtomicU64::new(0),
fast: Histogram::default(),
bulk: Histogram::default(),
file: FileCounts::default(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Name {
Search,
Stats,
Append,
Replace,
Remove,
Other,
}
impl Name {
pub(crate) const ALL: [Self; 6] = [
Self::Search,
Self::Stats,
Self::Append,
Self::Replace,
Self::Remove,
Self::Other,
];
pub(crate) const fn as_str(self) -> &'static str {
match self {
Self::Search => "search",
Self::Stats => "stats",
Self::Append => "append",
Self::Replace => "replace",
Self::Remove => "remove",
Self::Other => "other",
}
}
pub(crate) const fn is_change(self) -> bool {
matches!(self, Self::Append | Self::Replace | Self::Remove)
}
}
impl Metrics {
pub(crate) fn task(&self, name: Name, lane: Lane, micros: u64, error_type: Option<&str>, counts: Counts) {
let add = |counter: &AtomicU64, by: u64| counter.fetch_add(by, Ordering::Relaxed);
add(
match name {
Name::Search => &self.search,
Name::Stats => &self.stats,
Name::Append => &self.append,
Name::Replace => &self.replace,
Name::Remove => &self.remove,
Name::Other => &self.other,
},
1,
);
let file = &self.file;
let (answered, failed, times) = match lane {
Lane::Fast => (&file.fast_answered, &file.fast_failed, &file.fast_times),
Lane::Bulk => (&file.bulk_answered, &file.bulk_failed, &file.bulk_times),
};
add(answered, 1);
times.record(micros);
if error_type.is_some() {
add(failed, 1);
if let Some(index) = Name::ALL.iter().position(|known| *known == name) {
add(&file.failed[index], 1);
}
}
add(&file.matches, counts.matches);
add(&file.incomplete, counts.cut_limit + counts.cut_time + counts.cut_size);
if let Some(code) = error_type {
let index = ErrorType::ALL
.iter()
.map(|error| error.as_str())
.chain(OTHER_CODES)
.position(|known| known == code)
.unwrap_or(self.errors.len() - 1);
add(&self.errors[index], 1);
}
add(&self.queries, counts.queries);
add(&self.candidates, counts.candidates);
add(&self.cut_limit, counts.cut_limit);
add(&self.cut_time, counts.cut_time);
add(&self.cut_size, counts.cut_size);
match lane {
Lane::Fast => self.fast.record(micros),
Lane::Bulk => self.bulk.record(micros),
}
}
pub(crate) fn answered(&self) -> [u64; Name::ALL.len()] {
let load = |counter: &AtomicU64| counter.load(Ordering::Relaxed);
[
load(&self.search),
load(&self.stats),
load(&self.append),
load(&self.replace),
load(&self.remove),
load(&self.other),
]
}
pub(crate) fn queries(&self) -> u64 {
self.queries.load(Ordering::Relaxed)
}
pub(crate) fn heartbeat(&self, uptime_s: u64) -> Heartbeat {
let load = |counter: &AtomicU64| counter.load(Ordering::Relaxed);
let errors = ErrorType::ALL
.iter()
.map(|error| error.as_str())
.chain(OTHER_CODES)
.zip(&self.errors)
.map(|(code, count)| (code, load(count)))
.filter(|&(_, count)| count > 0)
.collect();
Heartbeat {
uptime_s,
in_flight: load(&self.in_flight),
tasks: TaskCounts {
search: load(&self.search),
stats: load(&self.stats),
append: load(&self.append),
replace: load(&self.replace),
remove: load(&self.remove),
other: load(&self.other),
},
errors,
queries: load(&self.queries),
candidates: load(&self.candidates),
cut_limit: load(&self.cut_limit),
cut_time: load(&self.cut_time),
cut_size: load(&self.cut_size),
fast: self.fast.take(),
bulk: self.bulk.take(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
#[non_exhaustive]
pub struct TaskCounts {
pub search: u64,
pub stats: u64,
pub append: u64,
pub replace: u64,
pub remove: u64,
pub other: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize)]
#[non_exhaustive]
pub struct Latency {
pub count: u64,
pub p50_ms: f64,
pub p99_ms: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[non_exhaustive]
pub struct Heartbeat {
pub uptime_s: u64,
pub in_flight: u64,
pub tasks: TaskCounts,
pub errors: BTreeMap<&'static str, u64>,
pub queries: u64,
pub candidates: u64,
pub cut_limit: u64,
pub cut_time: u64,
pub cut_size: u64,
pub fast: Latency,
pub bulk: Latency,
}
#[derive(Debug)]
pub(crate) struct Histogram {
buckets: Box<[AtomicU64; BUCKETS]>,
}
impl Default for Histogram {
fn default() -> Self {
Self {
buckets: Box::new(std::array::from_fn(|_| AtomicU64::new(0))),
}
}
}
impl Histogram {
fn record(&self, micros: u64) {
self.buckets[bucket(micros)].fetch_add(1, Ordering::Relaxed);
}
pub(crate) fn take_counts(&self) -> Vec<u64> {
self.buckets
.iter()
.map(|bucket| bucket.swap(0, Ordering::Relaxed))
.collect()
}
fn take(&self) -> Latency {
let counts: Vec<u64> = self
.buckets
.iter()
.map(|bucket| bucket.swap(0, Ordering::Relaxed))
.collect();
let count: u64 = counts.iter().sum();
let at = |fraction: f64| -> f64 {
#[expect(
clippy::cast_precision_loss,
clippy::cast_possible_truncation,
clippy::cast_sign_loss
)]
let rank = ((count as f64 * fraction).ceil() as u64).max(1);
let mut seen = 0;
for (index, &bucket_count) in counts.iter().enumerate() {
seen += bucket_count;
if seen >= rank {
#[expect(clippy::cast_precision_loss, reason = "a latency for a person to read")]
return upper(index) as f64 / 1000.0;
}
}
0.0
};
if count == 0 {
return Latency::default();
}
Latency {
count,
p50_ms: at(0.5),
p99_ms: at(0.99),
}
}
}
fn bucket(micros: u64) -> usize {
if micros < 8 {
return micros as usize;
}
let power = 63 - micros.leading_zeros() as usize;
let sub = ((micros >> (power - 3)) & 7) as usize;
((power - 2) * 8 + sub).min(BUCKETS - 1)
}
pub(crate) const fn lower(index: usize) -> u64 {
if index < 8 {
return index as u64;
}
let (power, sub) = (index / 8 + 2, (index % 8) as u64);
(8 + sub) << (power - 3)
}
pub(crate) fn upper(index: usize) -> u64 {
if index < 8 {
return index as u64;
}
let (power, sub) = (index / 8 + 2, (index % 8) as u64);
((9 + sub) << (power - 3)).saturating_sub(1)
}
#[cfg(test)]
mod tests {
use super::{bucket, lower, upper};
#[test]
fn each_latency_is_within_its_bucket() {
for micros in [0, 1, 7, 8, 9, 15, 16, 17, 100, 1_000, 2_047, 2_048, 123_456_789] {
let index = bucket(micros);
assert!(upper(index) >= micros, "{micros} is above its bucket's top");
assert!(lower(index) <= micros, "{micros} is below its bucket's bottom");
assert!(
index == 0 || upper(index - 1) < micros,
"{micros} belongs in an earlier bucket"
);
}
}
}