use std::sync::atomic::AtomicU8;
use std::sync::atomic::Ordering;
use std::sync::Arc;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum OnionSessionCondition {
Live,
Stalled,
Failed,
}
impl OnionSessionCondition {
const fn code(self) -> u8 {
match self {
Self::Live => 0,
Self::Stalled => 1,
Self::Failed => 2,
}
}
#[cfg(any(rings_native, test))]
const fn of_code(code: u8) -> Self {
match code {
0 => Self::Live,
1 => Self::Stalled,
_ => Self::Failed,
}
}
}
#[derive(Clone, Debug, Default)]
pub(crate) struct OnionSessionWitness(Arc<AtomicU8>);
impl OnionSessionWitness {
#[cfg(any(rings_native, test))]
pub(crate) fn condition(&self) -> OnionSessionCondition {
OnionSessionCondition::of_code(self.0.load(Ordering::Acquire))
}
pub(crate) fn record_stalled(&self, stalled: bool) {
let condition = if stalled {
OnionSessionCondition::Stalled
} else {
OnionSessionCondition::Live
};
let failed = OnionSessionCondition::Failed.code();
let _ = self
.0
.fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| {
(current != failed).then_some(condition.code())
});
}
pub(crate) fn record_failed(&self) {
self.0
.store(OnionSessionCondition::Failed.code(), Ordering::Release);
}
}