use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outcome {
Success,
Failure,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RefreshRole {
Leader,
Follower,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum TelemetryEvent {
RequestStart {
operation: &'static str,
method: &'static str,
path_template: &'static str,
attempt: u32,
},
RequestEnd {
operation: &'static str,
method: &'static str,
path_template: &'static str,
attempt: u32,
status: Option<u16>,
duration: Duration,
outcome: Outcome,
},
Retry {
operation: &'static str,
attempt: u32,
delay: Duration,
reason: String,
},
Refresh {
role: RefreshRole,
duration: Duration,
},
ConfigClamped {
setting: &'static str,
requested: String,
effective: String,
contract_reference: &'static str,
},
SsfUnjudged {
operation: &'static str,
count: usize,
category: &'static str,
},
}
pub trait TelemetrySink: Send + Sync + 'static {
fn emit(&self, event: &TelemetryEvent);
}
impl<F> TelemetrySink for F
where
F: Fn(&TelemetryEvent) + Send + Sync + 'static,
{
fn emit(&self, event: &TelemetryEvent) {
self(event)
}
}
#[derive(Clone, Default)]
pub(crate) struct Telemetry {
sink: Option<std::sync::Arc<dyn TelemetrySink>>,
}
impl std::fmt::Debug for Telemetry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Telemetry")
.field("installed", &self.sink.is_some())
.finish()
}
}
impl Telemetry {
pub(crate) fn new(sink: Option<std::sync::Arc<dyn TelemetrySink>>) -> Self {
Self { sink }
}
pub(crate) fn emit(&self, event: TelemetryEvent) {
let Some(sink) = self.sink.as_ref() else {
return;
};
let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| sink.emit(&event)));
}
}