use std::{
fmt,
sync::{
Arc,
atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
mpsc::{Receiver, RecvTimeoutError, TryRecvError},
},
time::Duration,
};
use super::{EventSequence, EvidenceCapabilities, RuntimeEvent, SCHEMA_VERSION};
pub(super) const NO_DROPPED_SEQUENCE: u64 = u64::MAX;
#[derive(
::core::clone::Clone,
::core::marker::Copy,
::core::fmt::Debug,
::core::cmp::PartialEq,
::core::cmp::Eq,
)]
#[non_exhaustive]
pub enum EvidenceRecvError {
Timeout,
Disconnected,
}
impl fmt::Display for EvidenceRecvError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::Timeout => "runtime evidence receive timed out",
Self::Disconnected => "runtime evidence stream disconnected",
})
}
}
impl std::error::Error for EvidenceRecvError {}
#[derive(
::core::clone::Clone,
::core::marker::Copy,
::core::fmt::Debug,
::core::cmp::PartialEq,
::core::cmp::Eq,
)]
pub struct EvidenceStatus {
capacity: usize,
pending: usize,
recorded: u64,
dropped: u64,
first_dropped: Option<EventSequence>,
runtime_terminal: bool,
}
impl EvidenceStatus {
pub fn capacity(self) -> usize {
self.capacity
}
pub fn pending(self) -> usize {
self.pending
}
pub fn recorded(self) -> u64 {
self.recorded
}
pub fn dropped(self) -> u64 {
self.dropped
}
pub fn first_dropped(self) -> Option<EventSequence> {
self.first_dropped
}
pub fn runtime_terminal(self) -> bool {
self.runtime_terminal
}
pub fn is_complete(self) -> bool {
self.dropped == 0
}
}
pub(super) struct Status {
pub(super) capacity: usize,
pub(super) next_sequence: AtomicU64,
pub(super) pending: AtomicUsize,
pub(super) recorded: AtomicU64,
pub(super) dropped: AtomicU64,
pub(super) first_dropped: AtomicU64,
pub(super) runtime_terminal: AtomicBool,
}
impl Status {
fn snapshot(&self) -> EvidenceStatus {
let first = self.first_dropped.load(Ordering::Acquire);
EvidenceStatus {
capacity: self.capacity,
pending: self.pending.load(Ordering::Acquire),
recorded: self.recorded.load(Ordering::Acquire),
dropped: self.dropped.load(Ordering::Acquire),
first_dropped: (first != NO_DROPPED_SEQUENCE).then(|| EventSequence::new(first)),
runtime_terminal: self.runtime_terminal.load(Ordering::Acquire),
}
}
pub(super) fn record_drop(&self, sequence: u64) {
self.dropped.fetch_add(1, Ordering::Relaxed);
let _ = self.first_dropped.compare_exchange(
NO_DROPPED_SEQUENCE,
sequence,
Ordering::Release,
Ordering::Relaxed,
);
}
}
pub struct EvidenceStream {
pub(super) receiver: Receiver<RuntimeEvent>,
pub(super) status: Arc<Status>,
}
impl EvidenceStream {
pub fn schema_version(&self) -> u16 {
SCHEMA_VERSION
}
pub fn capabilities(&self) -> EvidenceCapabilities {
EvidenceCapabilities::runtime()
}
pub fn drain(&mut self) -> Vec<RuntimeEvent> {
self.collect_batch(None)
}
pub fn recv_batch_timeout(
&mut self,
timeout: Duration,
) -> Result<Vec<RuntimeEvent>, EvidenceRecvError> {
let first = match self.receiver.recv_timeout(timeout) {
Ok(event) => event,
Err(RecvTimeoutError::Timeout) => return Err(EvidenceRecvError::Timeout),
Err(RecvTimeoutError::Disconnected) => return Err(EvidenceRecvError::Disconnected),
};
Ok(self.collect_batch(Some(first)))
}
pub fn status(&self) -> EvidenceStatus {
self.status.snapshot()
}
fn collect_batch(&mut self, first: Option<RuntimeEvent>) -> Vec<RuntimeEvent> {
let mut events = Vec::new();
if let Some(first) = first {
events.push(first);
}
while events.len() < self.status.capacity {
match self.receiver.try_recv() {
Ok(event) => events.push(event),
Err(TryRecvError::Empty | TryRecvError::Disconnected) => break,
}
}
self.status
.pending
.fetch_sub(events.len(), Ordering::AcqRel);
events.sort_unstable_by_key(|event| event.sequence());
events
}
}
#[cfg(test)]
#[path = "stream_test.rs"]
mod stream_test;