#[cfg(all(feature = "pool", not(loom)))]
use std::sync::atomic::AtomicBool;
#[cfg(all(feature = "metrics", feature = "pool", not(loom)))]
use std::sync::atomic::Ordering;
#[cfg(all(feature = "metrics", feature = "pool", not(loom)))]
use std::time::Instant;
#[cfg(all(feature = "metrics", feature = "pool", not(loom)))]
use metrics::{counter, histogram};
pub const POOL_CONNECTION_DISCARDS: &str = "wireframe_pool_connection_discards_total";
#[cfg(all(feature = "metrics", feature = "pool", not(loom)))]
pub(crate) fn inc_pool_incomplete_operation_discard() {
counter!(POOL_CONNECTION_DISCARDS, "reason" => "operation_incomplete").increment(1);
}
#[cfg(all(not(feature = "metrics"), feature = "pool", not(loom)))]
pub(crate) fn inc_pool_incomplete_operation_discard() {}
#[cfg(all(feature = "metrics", feature = "pool", not(loom)))]
pub(crate) fn inc_pool_pending_response_discard() {
counter!(POOL_CONNECTION_DISCARDS, "reason" => "response_pending").increment(1);
}
#[cfg(all(not(feature = "metrics"), feature = "pool", not(loom)))]
pub(crate) fn inc_pool_pending_response_discard() {}
pub const POOL_ACQUISITIONS: &str = "wireframe_pool_acquisitions_total";
pub const POOL_PERMIT_RACES_STARTED: &str = "wireframe_pool_permit_races_started_total";
pub const POOL_PERMIT_RACES: &str = "wireframe_pool_permit_races_total";
pub const POOL_PERMIT_RACE_DURATION: &str = "wireframe_pool_permit_race_duration_seconds";
#[cfg(all(feature = "metrics", feature = "pool", not(loom)))]
static POOL_PERMIT_RACE_CLOCK: fn() -> Instant = Instant::now;
#[cfg(all(feature = "pool", not(loom)))]
pub(crate) struct PoolPermitRaceGuard<'a> {
shutdown: &'a AtomicBool,
#[cfg(feature = "metrics")]
started: Instant,
#[cfg(feature = "metrics")]
clock: &'a (dyn Fn() -> Instant + Send + Sync),
#[cfg(feature = "metrics")]
finished: bool,
}
#[cfg(all(feature = "pool", not(loom)))]
impl<'a> PoolPermitRaceGuard<'a> {
pub(crate) fn start(shutdown: &'a AtomicBool) -> Self {
#[cfg(feature = "metrics")]
{
Self::start_with_clock(shutdown, &POOL_PERMIT_RACE_CLOCK)
}
#[cfg(not(feature = "metrics"))]
{
Self { shutdown }
}
}
#[cfg(feature = "metrics")]
fn start_with_clock(
shutdown: &'a AtomicBool,
clock: &'a (dyn Fn() -> Instant + Send + Sync),
) -> Self {
counter!(POOL_PERMIT_RACES_STARTED).increment(1);
Self {
shutdown,
started: clock(),
clock,
finished: false,
}
}
#[cfg(feature = "metrics")]
pub(crate) fn finish(mut self, outcome: PoolAcquisitionOutcome) {
self.record(outcome.as_str());
self.finished = true;
}
#[cfg(not(feature = "metrics"))]
pub(crate) fn finish(self, _outcome: PoolAcquisitionOutcome) {}
#[cfg(feature = "metrics")]
fn record(&self, outcome: &'static str) {
counter!(POOL_PERMIT_RACES, "outcome" => outcome).increment(1);
histogram!(POOL_PERMIT_RACE_DURATION, "outcome" => outcome).record(
(self.clock)()
.saturating_duration_since(self.started)
.as_secs_f64(),
);
}
}
#[cfg(all(feature = "pool", not(loom)))]
impl Drop for PoolPermitRaceGuard<'_> {
fn drop(&mut self) {
#[cfg(feature = "metrics")]
if !self.finished {
let outcome = if self.shutdown.load(Ordering::Acquire) {
"shutdown"
} else {
"cancelled"
};
self.record(outcome);
}
#[cfg(not(feature = "metrics"))]
let _ = self.shutdown;
}
}
#[cfg(all(feature = "pool", not(loom)))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum PoolAcquisitionMode {
Immediate,
PermitRace,
}
#[cfg(all(feature = "metrics", feature = "pool", not(loom)))]
impl PoolAcquisitionMode {
pub(crate) const fn as_str(self) -> &'static str {
match self {
Self::Immediate => "immediate",
Self::PermitRace => "permit_race",
}
}
}
#[cfg(all(feature = "pool", not(loom)))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum PoolAcquisitionOutcome {
Granted,
Exhausted,
Shutdown,
Error,
}
#[cfg(all(feature = "metrics", feature = "pool", not(loom)))]
impl PoolAcquisitionOutcome {
pub(crate) const fn as_str(self) -> &'static str {
match self {
Self::Granted => "granted",
Self::Exhausted => "exhausted",
Self::Shutdown => "shutdown",
Self::Error => "error",
}
}
}
#[cfg(all(feature = "metrics", feature = "pool", not(loom)))]
pub(crate) fn inc_pool_acquisition(mode: PoolAcquisitionMode, outcome: PoolAcquisitionOutcome) {
counter!(
POOL_ACQUISITIONS,
"mode" => mode.as_str(),
"outcome" => outcome.as_str()
)
.increment(1);
}
#[cfg(all(not(feature = "metrics"), feature = "pool", not(loom)))]
pub(crate) fn inc_pool_acquisition(_mode: PoolAcquisitionMode, _outcome: PoolAcquisitionOutcome) {}
#[cfg(all(test, feature = "metrics", feature = "pool", not(loom)))]
mod tests {
use std::{
sync::atomic::{AtomicBool, AtomicU64, Ordering},
time::{Duration, Instant},
};
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
use rstest::rstest;
use super::{
POOL_ACQUISITIONS,
POOL_CONNECTION_DISCARDS,
POOL_PERMIT_RACE_DURATION,
PoolAcquisitionMode,
PoolAcquisitionOutcome,
PoolPermitRaceGuard,
inc_pool_acquisition,
inc_pool_incomplete_operation_discard,
inc_pool_pending_response_discard,
};
#[rstest]
#[case::incomplete_operation(
"operation_incomplete",
inc_pool_incomplete_operation_discard as fn(),
"incomplete-operation discard metric was not recorded"
)]
#[case::pending_response(
"response_pending",
inc_pool_pending_response_discard as fn(),
"pending-response discard metric was not recorded"
)]
fn discard_metric_uses_a_bounded_reason(
#[case] reason: &str,
#[case] increment: fn(),
#[case] message: &str,
) {
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
::metrics::with_local_recorder(&recorder, increment);
let found = snapshotter
.snapshot()
.into_vec()
.iter()
.any(|(key, _, _, value)| {
key.key().name() == POOL_CONNECTION_DISCARDS
&& key
.key()
.labels()
.any(|label| label.key() == "reason" && label.value() == reason)
&& matches!(value, DebugValue::Counter(count) if *count == 1)
});
assert!(found, "{message}");
}
#[rstest]
#[case::immediate_granted(PoolAcquisitionMode::Immediate, PoolAcquisitionOutcome::Granted)]
#[case::immediate_shutdown(PoolAcquisitionMode::Immediate, PoolAcquisitionOutcome::Shutdown)]
#[case::race_exhausted(PoolAcquisitionMode::PermitRace, PoolAcquisitionOutcome::Exhausted)]
#[case::race_error(PoolAcquisitionMode::PermitRace, PoolAcquisitionOutcome::Error)]
fn acquisition_metric_uses_bounded_mode_and_outcome(
#[case] mode: PoolAcquisitionMode,
#[case] outcome: PoolAcquisitionOutcome,
) {
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
::metrics::with_local_recorder(&recorder, || inc_pool_acquisition(mode, outcome));
let found = snapshotter
.snapshot()
.into_vec()
.iter()
.any(|(key, _, _, value)| {
key.key().name() == POOL_ACQUISITIONS
&& key
.key()
.labels()
.any(|label| label.key() == "mode" && label.value() == mode.as_str())
&& key
.key()
.labels()
.any(|label| label.key() == "outcome" && label.value() == outcome.as_str())
&& matches!(value, DebugValue::Counter(count) if *count == 1)
});
assert!(
found,
"acquisition metric for {mode:?}/{outcome:?} was not recorded"
);
}
#[rstest]
#[case::granted(Some(PoolAcquisitionOutcome::Granted), "granted")]
#[case::cancelled(None, "cancelled")]
fn blocked_race_records_duration_from_injected_clock(
#[case] outcome: Option<PoolAcquisitionOutcome>,
#[case] expected_label: &str,
) {
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
let shutdown = AtomicBool::new(false);
let elapsed = AtomicU64::new(0);
let origin = Instant::now();
let clock = || origin + Duration::from_secs(elapsed.load(Ordering::Relaxed));
::metrics::with_local_recorder(&recorder, || {
let guard = PoolPermitRaceGuard::start_with_clock(&shutdown, &clock);
elapsed.store(7, Ordering::Relaxed);
if let Some(finish_outcome) = outcome {
guard.finish(finish_outcome);
} else {
drop(guard);
}
});
let found = snapshotter.snapshot().into_vec().iter().any(|(key, _, _, value)| {
key.key().name() == POOL_PERMIT_RACE_DURATION
&& key.key().labels().any(|label| {
label.key() == "outcome" && label.value() == expected_label
})
&& matches!(value, DebugValue::Histogram(samples)
if samples.len() == 1
&& samples.first().is_some_and(|sample| sample.0.to_bits() == 7.0_f64.to_bits()))
});
assert!(
found,
"the histogram must record the injected seven-second duration"
);
}
}