Skip to main content

moirai_core/channel/
stats.rs

1//! Statistics types for channels.
2
3use std::sync::atomic::{AtomicUsize, Ordering};
4
5/// Performance statistics for adaptive channel behavior
6#[derive(Debug)]
7pub(crate) struct ChannelStats {
8    /// Total messages sent
9    pub(crate) messages_sent: AtomicUsize,
10    /// Total messages received
11    pub(crate) messages_received: AtomicUsize,
12    /// Number of times overflow pool was used
13    pub(crate) overflow_events: AtomicUsize,
14    /// Contention counter for adaptive behavior
15    pub(crate) contention_count: AtomicUsize,
16}
17
18impl ChannelStats {
19    pub(crate) fn new() -> Self {
20        Self {
21            messages_sent: AtomicUsize::new(0),
22            messages_received: AtomicUsize::new(0),
23            overflow_events: AtomicUsize::new(0),
24            contention_count: AtomicUsize::new(0),
25        }
26    }
27
28    /// Record a successful send operation
29    pub(crate) fn record_send(&self) {
30        self.messages_sent.fetch_add(1, Ordering::Relaxed);
31    }
32
33    /// Record a successful receive operation
34    pub(crate) fn record_receive(&self) {
35        self.messages_received.fetch_add(1, Ordering::Relaxed);
36    }
37
38    /// Record an overflow event
39    pub(crate) fn record_overflow(&self) {
40        self.overflow_events.fetch_add(1, Ordering::Relaxed);
41    }
42
43    /// Record contention
44    pub(crate) fn record_contention(&self) {
45        self.contention_count.fetch_add(1, Ordering::Relaxed);
46    }
47
48    /// Get send/receive ratio for adaptive behavior
49    // justification: message counts converted to f64 for a ratio; precision loss
50    // only occurs past 2^52 messages, unreachable for these counters in practice.
51    #[allow(clippy::cast_precision_loss)]
52    pub(crate) fn get_throughput_ratio(&self) -> f64 {
53        let sent = self.messages_sent.load(Ordering::Relaxed);
54        let received = self.messages_received.load(Ordering::Relaxed);
55
56        if received == 0 {
57            return f64::INFINITY;
58        }
59
60        sent as f64 / received as f64
61    }
62}
63
64/// Statistics snapshot for monitoring channel performance
65#[derive(Debug, Clone)]
66pub struct ChannelStatistics {
67    /// Total number of messages successfully sent through the channel
68    pub messages_sent: usize,
69    /// Total number of messages successfully received from the channel
70    pub messages_received: usize,
71    /// Number of times the channel had to use overflow handling
72    pub overflow_events: usize,
73    /// Number of contention events detected during operations
74    pub contention_count: usize,
75    /// Current number of messages in the channel
76    pub current_length: usize,
77    /// Maximum capacity of the channel
78    pub capacity: usize,
79    /// Ratio of successful operations to total attempts
80    pub throughput_ratio: f64,
81}