use super::Metrics;
use std::sync::{
Arc,
atomic::{AtomicU8, Ordering},
};
use tokio::time::Instant;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub(crate) enum Outcome {
Completed = 1,
Failed = 2,
TimedOut = 3,
Cancelled = 4,
}
impl Outcome {
pub(super) fn index(self) -> usize {
self as usize - 1
}
pub(crate) fn name(self) -> &'static str {
match self {
Self::Completed => "completed",
Self::Failed => "failed",
Self::TimedOut => "timed_out",
Self::Cancelled => "cancelled",
}
}
}
#[derive(Clone)]
pub(crate) struct OutcomeToken(Arc<OutcomeState>);
struct OutcomeState {
terminal: AtomicU8,
failure: AtomicU8,
}
#[derive(Clone, Copy)]
#[repr(u8)]
pub(crate) enum ExchangeFailure {
Body = 1,
Transport = 2,
}
impl OutcomeToken {
pub(crate) fn mark(&self, outcome: Outcome) {
let _ =
self.0
.terminal
.compare_exchange(0, outcome as u8, Ordering::AcqRel, Ordering::Acquire);
}
pub(crate) fn fail(&self, failure: ExchangeFailure) {
let _ =
self.0
.failure
.compare_exchange(0, failure as u8, Ordering::AcqRel, Ordering::Acquire);
self.mark(Outcome::Failed);
}
fn terminal(&self) -> Outcome {
match self.0.terminal.load(Ordering::Acquire) {
1 => Outcome::Completed,
2 => Outcome::Failed,
3 => Outcome::TimedOut,
_ if std::thread::panicking() => Outcome::Failed,
_ => Outcome::Cancelled,
}
}
}
pub(crate) type OutcomeSlot = Arc<std::sync::Mutex<Option<OutcomeToken>>>;
pub(crate) fn mark_current(slot: &OutcomeSlot, outcome: Outcome) {
if let Some(token) = slot.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
token.mark(outcome);
}
}
pub(crate) fn fail_current(slot: &OutcomeSlot, failure: ExchangeFailure) {
if let Some(token) = slot.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
token.fail(failure);
}
}
pub(crate) struct Exchange {
metrics: Arc<Metrics>,
started: Instant,
token: OutcomeToken,
span: tracing::Span,
}
impl Exchange {
pub(super) fn new(metrics: Arc<Metrics>) -> Self {
Self {
metrics,
started: Instant::now(),
token: OutcomeToken(Arc::new(OutcomeState {
terminal: AtomicU8::new(0),
failure: AtomicU8::new(0),
})),
span: tracing::Span::current(),
}
}
pub(crate) fn token(&self) -> OutcomeToken {
self.token.clone()
}
pub(crate) fn mark(&self, outcome: Outcome) {
self.token.mark(outcome);
}
pub(crate) fn fail(&self, failure: ExchangeFailure) {
self.token.fail(failure);
}
}
impl Drop for Exchange {
fn drop(&mut self) {
let outcome = self.token.terminal();
let micros = self.started.elapsed().as_micros().min(u64::MAX as u128) as u64;
self.metrics.finish(micros, outcome);
#[cfg(feature = "otel")]
{
use tracing_opentelemetry::OpenTelemetrySpanExt;
let error = match (outcome, self.token.0.failure.load(Ordering::Acquire)) {
(Outcome::TimedOut, _) => Some("timeout"),
(_, 1) => Some("http.body_error"),
(_, 2) => Some("http.transport_error"),
_ => None,
};
if let Some(error) = error {
self.span.set_attribute("error.type", error);
self.span
.set_status(opentelemetry::trace::Status::error(error));
}
}
self.span.in_scope(|| {
tracing::info!(
outcome = outcome.name(),
elapsed_micros = micros,
"exchange finished"
)
});
}
}