use std::fs::{self, OpenOptions};
use std::io::{self, Write as _};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use legit_streams::{GroupBacklog, Streams};
use serde::Serialize;
use super::metrics::{self, Metrics, Name};
use crate::service::{Service, Totals};
pub const STATS_FORMAT: u32 = 1;
pub const BACKLOG_TIMEOUT: Duration = Duration::from_secs(2);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Times {
pub median_us: u64,
pub p95_us: u64,
pub p99_us: u64,
pub count: u64,
}
impl Times {
#[must_use]
pub const fn new(median_us: u64, p95_us: u64, p99_us: u64, count: u64) -> Self {
Self {
median_us,
p95_us,
p99_us,
count,
}
}
fn from_counts(counts: &[u64]) -> Option<Self> {
let count: u64 = counts.iter().sum();
if count == 0 {
return None;
}
let at = |quantile: f64| {
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
clippy::cast_precision_loss,
reason = "a rank within `count`"
)]
let rank = ((quantile * count as f64).ceil() as u64).clamp(1, count);
let mut seen = 0;
let bucket = counts
.iter()
.position(|n| {
seen += n;
seen >= rank
})
.unwrap_or(counts.len() - 1);
middle(bucket)
};
Some(Self {
median_us: at(0.5),
p95_us: at(0.95),
p99_us: at(0.99),
count,
})
}
}
fn middle(bucket: usize) -> u64 {
let (lower, upper) = (metrics::lower(bucket), metrics::upper(bucket));
lower + (upper - lower).div_ceil(2)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct LaneSample {
pub answered: u64,
pub failed: u64,
pub times: Option<Times>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
#[non_exhaustive]
pub struct TaskSample {
pub answered: u64,
pub failed: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct SearchSample {
pub values: u64,
pub matches: u64,
pub incomplete: u64,
}
#[derive(Debug, Clone)]
pub struct Meter {
pub(crate) metrics: Arc<Metrics>,
pub(crate) service: Arc<Service>,
pub(crate) started: Instant,
pub(crate) started_at: u64,
pub(crate) fast_lane: bool,
}
impl Meter {
#[must_use]
pub fn sample(&self) -> Sample {
let metrics = &self.metrics;
let file = &metrics.file;
let load = |counter: &AtomicU64| counter.load(Ordering::Relaxed);
let bulk_counts = file.bulk_times.take_counts();
let fast_counts = file.fast_times.take_counts();
let answered = metrics.answered();
let task = |name: Name| {
let index = Name::ALL.iter().position(|known| *known == name).unwrap_or(0);
TaskSample {
answered: answered[index],
failed: load(&file.failed[index]),
}
};
Sample {
at: unix_seconds(SystemTime::now()),
started_at: self.started_at,
uptime: self.started.elapsed(),
in_flight: load(&metrics.in_flight) + load(&metrics.fast_in_flight),
fast_lane: self.fast_lane,
bulk: LaneSample {
answered: load(&file.bulk_answered),
failed: load(&file.bulk_failed),
times: Times::from_counts(&bulk_counts),
},
fast: LaneSample {
answered: load(&file.fast_answered),
failed: load(&file.fast_failed),
times: Times::from_counts(&fast_counts),
},
search: task(Name::Search),
stats: task(Name::Stats),
append: task(Name::Append),
replace: task(Name::Replace),
remove: task(Name::Remove),
searched: SearchSample {
values: metrics.queries(),
matches: load(&file.matches),
incomplete: load(&file.incomplete),
},
totals: self.service.catalog().totals(),
bulk_counts,
fast_counts,
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Sample {
pub at: u64,
pub started_at: u64,
pub uptime: Duration,
pub in_flight: u64,
pub fast_lane: bool,
pub bulk: LaneSample,
pub fast: LaneSample,
pub search: TaskSample,
pub stats: TaskSample,
pub append: TaskSample,
pub replace: TaskSample,
pub remove: TaskSample,
pub searched: SearchSample,
pub totals: Totals,
bulk_counts: Vec<u64>,
fast_counts: Vec<u64>,
}
impl Sample {
fn absorb(&mut self, earlier: &Self) {
for (mine, theirs) in [
(&mut self.bulk_counts, &earlier.bulk_counts),
(&mut self.fast_counts, &earlier.fast_counts),
] {
if mine.len() < theirs.len() {
mine.resize(theirs.len(), 0);
}
for (count, earlier) in mine.iter_mut().zip(theirs) {
*count += earlier;
}
}
self.bulk.times = Times::from_counts(&self.bulk_counts);
self.fast.times = Times::from_counts(&self.fast_counts);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum StatsState {
Running,
Stopped,
}
#[must_use]
pub fn stats_document(
sample: &Sample,
previous: Option<&Sample>,
state: StatsState,
backlog: Option<GroupBacklog>,
) -> String {
let interval = previous.map(|previous| sample.uptime.saturating_sub(previous.uptime).as_secs_f64());
let lane = |now: &LaneSample, before: Option<&LaneSample>| Lane {
answered: now.answered,
failed: now.failed,
#[expect(clippy::cast_precision_loss, reason = "a rate for a person or a collector to read")]
rate_per_s: interval
.zip(before)
.filter(|(interval, _)| *interval > 0.0)
.map(|(interval, before)| round(now.answered.saturating_sub(before.answered) as f64 / interval, 2)),
median_us: now.times.filter(|_| previous.is_some()).map(|times| times.median_us),
p95_us: now.times.filter(|_| previous.is_some()).map(|times| times.p95_us),
p99_us: now.times.filter(|_| previous.is_some()).map(|times| times.p99_us),
};
let tally = |task: TaskSample| Tally {
answered: task.answered,
failed: task.failed,
};
let document = Document {
format: STATS_FORMAT,
program: "legit-hamming",
version: env!("CARGO_PKG_VERSION"),
state,
started_at: sample.started_at,
at: sample.at,
uptime_s: sample.uptime.as_secs(),
interval_s: interval.map(|interval| round(interval, 3)),
in_flight: sample.in_flight,
bulk: lane(&sample.bulk, previous.map(|previous| &previous.bulk)),
fast: sample
.fast_lane
.then(|| lane(&sample.fast, previous.map(|previous| &previous.fast))),
tasks: Tasks {
search: SearchTally {
answered: sample.search.answered,
failed: sample.search.failed,
values: sample.searched.values,
matches: sample.searched.matches,
incomplete: sample.searched.incomplete,
},
stats: tally(sample.stats),
append: tally(sample.append),
replace: tally(sample.replace),
remove: tally(sample.remove),
},
totals: TotalsObject {
sets: sample.totals.sets,
records: sample.totals.records,
changes_held: sample.totals.changes_held,
ready: sample.totals.ready,
not_ready: sample.totals.not_ready,
},
backlog: backlog.map(|backlog| Backlog {
waiting: backlog.lag,
pending: backlog.pending,
}),
};
serde_json::to_string(&document).unwrap_or_default()
}
#[derive(Serialize)]
struct Document {
format: u32,
program: &'static str,
version: &'static str,
state: StatsState,
started_at: u64,
at: u64,
uptime_s: u64,
interval_s: Option<f64>,
in_flight: u64,
bulk: Lane,
fast: Option<Lane>,
tasks: Tasks,
totals: TotalsObject,
backlog: Option<Backlog>,
}
#[derive(Serialize)]
struct Lane {
answered: u64,
failed: u64,
rate_per_s: Option<f64>,
median_us: Option<u64>,
p95_us: Option<u64>,
p99_us: Option<u64>,
}
#[derive(Serialize)]
struct Tasks {
search: SearchTally,
stats: Tally,
append: Tally,
replace: Tally,
remove: Tally,
}
#[derive(Serialize)]
struct SearchTally {
answered: u64,
failed: u64,
values: u64,
matches: u64,
incomplete: u64,
}
#[derive(Serialize)]
struct Tally {
answered: u64,
failed: u64,
}
#[derive(Serialize)]
struct TotalsObject {
sets: u64,
records: u64,
changes_held: u64,
ready: u64,
not_ready: u64,
}
#[derive(Serialize)]
struct Backlog {
waiting: Option<u64>,
pending: u64,
}
fn round(value: f64, places: i32) -> f64 {
let scale = 10f64.powi(places);
(value * scale).round() / scale
}
pub(crate) fn unix_seconds(time: SystemTime) -> u64 {
time.duration_since(UNIX_EPOCH).map_or(0, |since| since.as_secs())
}
#[derive(Debug)]
pub struct StatsFile {
path: PathBuf,
temporary: PathBuf,
previous: Option<Sample>,
unwritten: Option<Sample>,
backlog: Option<BacklogReader>,
failure: Option<io::ErrorKind>,
}
impl StatsFile {
pub fn new(path: impl AsRef<Path>) -> io::Result<Self> {
let (path, temporary) = beside(path.as_ref())?;
Ok(Self {
path,
temporary,
previous: None,
unwritten: None,
backlog: None,
failure: None,
})
}
#[must_use]
pub fn with_backlog(
mut self,
streams: Arc<dyn Streams>,
stream: impl Into<String>,
group: impl Into<String>,
) -> Self {
self.backlog = Some(BacklogReader {
streams,
stream: stream.into(),
group: group.into(),
running: None,
failure: None,
});
self
}
#[must_use]
pub fn path(&self) -> &Path {
&self.path
}
pub fn write(&mut self, mut sample: Sample, state: StatsState) -> io::Result<()> {
if let Some(earlier) = self.unwritten.take() {
sample.absorb(&earlier);
}
let backlog = self.backlog.as_mut().and_then(BacklogReader::read);
let mut document = stats_document(&sample, self.previous.as_ref(), state, backlog);
document.push('\n');
let written = replace(&self.temporary, &self.path, document.as_bytes());
match &written {
Ok(()) => {
self.previous = Some(sample);
self.failure = None;
}
Err(error) => {
self.unwritten = Some(sample);
if self.failure != Some(error.kind()) {
tracing::warn!(path = %self.path.display(), error = %error, "Couldn't write the stats file; the worker carries on");
}
self.failure = Some(error.kind());
}
}
written
}
}
fn beside(path: &Path) -> io::Result<(PathBuf, PathBuf)> {
let Some(name) = path.file_name() else {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "the path names no file"));
};
let directory = match path.parent() {
Some(parent) if !parent.as_os_str().is_empty() => parent,
_ => Path::new("."),
};
if !directory.is_dir() {
return Err(io::Error::new(
io::ErrorKind::NotFound,
"the directory it would be in doesn't exist",
));
}
if path.is_dir() {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "the path is a directory"));
}
let mut temporary = name.to_os_string();
temporary.push(".tmp");
Ok((path.to_path_buf(), directory.join(temporary)))
}
fn replace(temporary: &Path, path: &Path, bytes: &[u8]) -> io::Result<()> {
let written = (|| {
let mut options = OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o644);
let mut file = options.open(temporary)?;
#[cfg(unix)]
file.set_permissions(std::os::unix::fs::PermissionsExt::from_mode(0o644))?;
file.write_all(bytes)?;
drop(file);
fs::rename(temporary, path)
})();
if written.is_err() {
let _ = fs::remove_file(temporary);
}
written
}
type BacklogAnswer = legit_streams::Result<Option<GroupBacklog>>;
struct BacklogReader {
streams: Arc<dyn Streams>,
stream: String,
group: String,
running: Option<Receiver<BacklogAnswer>>,
failure: Option<&'static str>,
}
impl std::fmt::Debug for BacklogReader {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BacklogReader")
.field("stream", &self.stream)
.field("group", &self.group)
.field("running", &self.running.is_some())
.finish_non_exhaustive()
}
}
impl BacklogReader {
fn read(&mut self) -> Option<GroupBacklog> {
let receiver = match self.running.take() {
Some(receiver) => receiver,
None => match self.start() {
Ok(receiver) => receiver,
Err(error) => {
self.failed("thread", &error);
return None;
}
},
};
match receiver.recv_timeout(BACKLOG_TIMEOUT) {
Ok(Ok(backlog)) => {
self.failure = None;
backlog
}
Ok(Err(error)) => {
self.failed(error_kind(&error), &error);
None
}
Err(RecvTimeoutError::Timeout) => {
self.running = Some(receiver);
self.failed(
"timeout",
&format_args!("no answer within {} s", BACKLOG_TIMEOUT.as_secs()),
);
None
}
Err(RecvTimeoutError::Disconnected) => {
self.failed("thread", &"the reading thread ended without an answer");
None
}
}
}
fn start(&self) -> io::Result<Receiver<BacklogAnswer>> {
let (send, receive) = mpsc::channel();
let streams = Arc::clone(&self.streams);
let (stream, group) = (self.stream.clone(), self.group.clone());
std::thread::Builder::new()
.name("hamming-backlog".to_owned())
.spawn(move || {
let _ = send.send(streams.group_backlog(&stream, &group));
})?;
Ok(receive)
}
fn failed(&mut self, kind: &'static str, error: &dyn std::fmt::Display) {
if self.failure != Some(kind) {
tracing::warn!(error = %error, "Couldn't read the bulk group's backlog for the stats file; it's written without");
}
self.failure = Some(kind);
}
}
const fn error_kind(error: &legit_streams::Error) -> &'static str {
match error {
legit_streams::Error::NoGroup { .. } => "no_group",
legit_streams::Error::Redis(_) => "redis",
legit_streams::Error::UnexpectedReply(_) => "unexpected_reply",
_ => "other",
}
}
#[cfg(test)]
mod tests {
use super::super::metrics::{lower, upper};
use super::{Times, middle};
fn bucket_of(micros: u64) -> usize {
(0..512)
.find(|&index| lower(index) <= micros && micros <= upper(index))
.expect("a bucket")
}
#[test]
fn a_bucket_stands_for_a_time_within_a_sixteenth_of_every_time_it_holds() {
for micros in (0..5_000).chain([65_535, 65_536, 1_000_000, 123_456_789, 600_000_000]) {
let stands_for = middle(bucket_of(micros));
assert!(
stands_for.abs_diff(micros) * 16 <= micros.max(1),
"{micros} µs stands as {stands_for}"
);
}
}
fn exact(values: &mut [u64], quantile: f64) -> u64 {
values.sort_unstable();
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
clippy::cast_precision_loss,
reason = "a small rank"
)]
let rank = ((quantile * values.len() as f64).ceil() as usize).max(1);
values[rank - 1]
}
#[test]
fn the_percentiles_are_within_a_sixteenth_of_the_exact_ones() {
let mut state = 0x2545_f491_4f6c_dd1d_u64;
for size in [1, 2, 3, 19, 20, 100, 1_000, 10_000] {
let mut counts = vec![0_u64; 512];
let mut values = Vec::new();
for _ in 0..size {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
#[expect(clippy::cast_precision_loss, reason = "53 random bits")]
let unit = (state >> 11) as f64 / (1_u64 << 53) as f64;
#[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "under 2^34")]
let micros = 1e7_f64.powf(unit) as u64;
counts[bucket_of(micros)] += 1;
values.push(micros);
}
let times = Times::from_counts(&counts).expect("times");
assert_eq!(times.count, size);
for (got, quantile) in [(times.median_us, 0.5), (times.p95_us, 0.95), (times.p99_us, 0.99)] {
let want = exact(&mut values, quantile);
assert!(got.abs_diff(want) * 16 <= want.max(1), "{size}: {got} for {want}");
}
}
assert_eq!(Times::from_counts(&[0; 512]), None);
}
}