#[cfg(feature = "metrics")]
use metrics::counter;
pub const RESPONSE_CANCELLATIONS: &str = "wireframe_response_cancellations_total";
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ResponseCancellationReason {
IdleGraceExpired,
Shutdown,
}
impl ResponseCancellationReason {
#[cfg(feature = "metrics")]
pub(crate) const fn as_str(self) -> &'static str {
match self {
Self::IdleGraceExpired => "idle_grace_expired",
Self::Shutdown => "shutdown",
}
}
pub(crate) fn record(self) { inc_response_cancellation(self); }
}
#[cfg(feature = "metrics")]
pub(crate) fn inc_response_cancellation(reason: ResponseCancellationReason) {
counter!(RESPONSE_CANCELLATIONS, "reason" => reason.as_str()).increment(1);
}
#[cfg(not(feature = "metrics"))]
pub(crate) fn inc_response_cancellation(_reason: ResponseCancellationReason) {}
#[cfg(all(test, feature = "metrics", not(loom)))]
mod tests {
use metrics::{SharedString, Unit};
use metrics_util::{
CompositeKey,
debugging::{DebugValue, DebuggingRecorder},
};
use super::{RESPONSE_CANCELLATIONS, ResponseCancellationReason, inc_response_cancellation};
type MetricSample = (CompositeKey, Option<Unit>, Option<SharedString>, DebugValue);
fn sample_matches_reason(sample: &MetricSample, reason: ResponseCancellationReason) -> bool {
let (key, _, _, value) = sample;
if key.key().name() != RESPONSE_CANCELLATIONS || key.key().labels().count() != 1 {
return false;
}
let has_reason = key
.key()
.labels()
.any(|label| label.key() == "reason" && label.value() == reason.as_str());
has_reason && matches!(value, DebugValue::Counter(count) if *count == 1)
}
#[test]
fn response_cancellations_use_a_fixed_reason_label() {
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
let reasons = [
ResponseCancellationReason::IdleGraceExpired,
ResponseCancellationReason::Shutdown,
];
::metrics::with_local_recorder(&recorder, || {
for reason in reasons {
inc_response_cancellation(reason);
}
});
let metric_samples = snapshotter.snapshot().into_vec();
assert_eq!(metric_samples.len(), reasons.len());
for reason in reasons {
assert!(
metric_samples
.iter()
.any(|sample| sample_matches_reason(sample, reason)),
"missing sample for reason {reason:?}"
);
}
}
}