use std::{
any::Any,
sync::{Arc, Mutex},
};
use jiff::SignedDuration;
use crate::Skip;
use super::{
NodeName,
fate::Terminal,
policy::{Concern, Occupancy, OverflowDecision, ShedKey},
poll::PollUpstream,
};
#[derive(Debug, Clone, derive_more::IsVariant, derive_more::Unwrap, derive_more::TryUnwrap)]
#[unwrap(ref, ref_mut)]
#[try_unwrap(ref, ref_mut)]
pub enum Lifecycle<I> {
Persisted(I),
Processed(I),
Skipped(Skip),
Failed(Failure),
}
impl<I> Lifecycle<I> {
#[inline]
pub const fn station(&self) -> Station {
match self {
Self::Persisted(_) => Station::Persisted,
Self::Processed(_) => Station::Processed,
Self::Skipped(_) => Station::Skipped,
Self::Failed(_) => Station::Failed,
}
}
#[inline]
#[must_use]
pub fn erase(self) -> Observation
where
I: Any + Send + Sync,
{
Observation::Arrived(self.arrive())
}
#[inline]
#[must_use]
pub fn arrive(self) -> Arrival
where
I: Any + Send + Sync,
{
let station = self.station();
let (info, skip, failure) = match self {
Self::Persisted(info) | Self::Processed(info) => (
Some(Box::new(info) as Box<dyn Any + Send + Sync>),
None,
None,
),
Self::Skipped(skip) => (None, Some(Box::new(skip)), None),
Self::Failed(failure) => (None, None, Some(failure)),
};
Arrival {
station,
info,
skip,
failure,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, derive_more::Display, derive_more::IsVariant)]
#[display("{}", self.as_str())]
pub enum Station {
Persisted,
Processed,
Skipped,
Failed,
}
impl Station {
#[inline]
#[must_use]
pub const fn as_str(&self) -> &'static str {
match self {
Self::Persisted => "persisted",
Self::Processed => "processed",
Self::Skipped => "skipped",
Self::Failed => "failed",
}
}
#[inline]
#[must_use]
pub const fn is_settled(&self) -> bool {
match self {
Self::Persisted | Self::Processed | Self::Skipped => true,
Self::Failed => false,
}
}
}
#[derive(Debug, Clone, derive_more::Display)]
#[display("{_0}")]
pub struct Failure(Arc<dyn core::error::Error + Send + Sync>);
impl Failure {
#[inline]
#[must_use]
pub fn new<E>(error: E) -> Self
where
E: core::error::Error + Send + Sync + 'static,
{
Self(Arc::new(error))
}
#[inline]
#[must_use]
pub fn error(&self) -> &(dyn core::error::Error + Send + Sync + 'static) {
&*self.0
}
}
impl core::error::Error for Failure {
#[inline]
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
Some(&*self.0)
}
}
#[derive(Debug)]
pub struct Arrival {
station: Station,
info: Option<Box<dyn Any + Send + Sync>>,
skip: Option<Box<Skip>>,
failure: Option<Failure>,
}
impl Arrival {
#[inline]
pub const fn station(&self) -> Station {
self.station
}
#[inline]
pub fn info<I: Any>(&self) -> Option<&I> {
self.info.as_ref().and_then(|info| info.downcast_ref())
}
#[inline]
pub fn skip(&self) -> Option<&Skip> {
self.skip.as_deref()
}
#[inline]
pub const fn failure(&self) -> Option<&Failure> {
self.failure.as_ref()
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum Observation {
Arrived(Arrival),
Retrying {
attempt: u32,
after: Option<SignedDuration>,
},
Shed {
key: ShedKey,
decision: OverflowDecision,
occupancy: Occupancy,
},
PolicyFailed {
concern: Concern,
error: crate::BoxedError,
},
Expired {
budget: SignedDuration,
},
GivenUp {
attempt: u32,
failure: Option<Failure>,
},
Lapped {
poll: PollUpstream,
},
}
impl Observation {
#[inline]
#[must_use]
pub const fn arrival(&self) -> Option<&Arrival> {
match self {
Self::Arrived(arrival) => Some(arrival),
_ => None,
}
}
#[inline]
#[must_use]
pub const fn station(&self) -> Option<Station> {
match self {
Self::Arrived(arrival) => Some(arrival.station()),
_ => None,
}
}
#[inline]
#[must_use]
pub const fn terminal(&self) -> Option<Terminal> {
match self {
Self::Shed { .. } => Some(Terminal::Shed),
Self::GivenUp { .. } => Some(Terminal::GivenUp),
Self::Expired { .. } => Some(Terminal::Expired),
_ => None,
}
}
#[inline]
pub fn info<I: Any>(&self) -> Option<&I> {
self.arrival().and_then(Arrival::info)
}
#[inline]
pub fn skip(&self) -> Option<&Skip> {
self.arrival().and_then(Arrival::skip)
}
#[inline]
pub fn failure(&self) -> Option<&Failure> {
self.arrival().and_then(Arrival::failure)
}
}
pub trait LifecycleTap: Send + Sync {
fn observe(&self, node: &NodeName, observation: &Observation);
}
#[derive(Clone, Default)]
pub struct Taps {
taps: Vec<Arc<dyn LifecycleTap>>,
}
impl Taps {
#[inline]
#[must_use]
pub const fn new() -> Self {
Self { taps: Vec::new() }
}
#[inline]
#[must_use]
pub fn with(mut self, tap: Arc<dyn LifecycleTap>) -> Self {
self.taps.push(tap);
self
}
#[inline]
#[must_use]
pub fn len(&self) -> usize {
self.taps.len()
}
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.taps.is_empty()
}
}
impl core::fmt::Debug for Taps {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Taps")
.field("len", &self.taps.len())
.finish()
}
}
impl LifecycleTap for Taps {
#[inline]
fn observe(&self, node: &NodeName, observation: &Observation) {
for tap in &self.taps {
tap.observe(node, observation);
}
}
}
#[derive(Debug, Default)]
pub struct RecordingTap {
seen: Mutex<Vec<(String, Station)>>,
}
impl RecordingTap {
#[inline]
#[must_use]
pub const fn new() -> Self {
Self {
seen: Mutex::new(Vec::new()),
}
}
#[inline]
#[must_use]
pub fn seen(&self) -> Vec<(String, Station)> {
self.seen.lock().expect("the recording tap's lock").clone()
}
#[inline]
#[must_use]
pub fn len(&self) -> usize {
self.seen.lock().expect("the recording tap's lock").len()
}
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl LifecycleTap for RecordingTap {
fn observe(&self, node: &NodeName, observation: &Observation) {
let Observation::Arrived(arrival) = observation else {
return;
};
self
.seen
.lock()
.expect("the recording tap's lock")
.push((node.as_str().to_owned(), arrival.station()));
}
}
#[cfg(test)]
mod tests;