1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
// Copyright 2017-2021 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.

// Polkadot is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Polkadot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Polkadot.  If not, see <http://www.gnu.org/licenses/>.

//! Metered variant of mpsc channels to be able to extract metrics.

use std::sync::{
	atomic::{AtomicUsize, Ordering},
	Arc,
};

use derive_more::{Add, Display};

mod bounded;
pub mod oneshot;
mod unbounded;

pub use self::{bounded::*, unbounded::*};

/// A peek into the inner state of a meter.
#[derive(Debug, Clone, Default)]
pub struct Meter {
	// Number of sends on this channel.
	sent: Arc<AtomicUsize>,
	// Number of receives on this channel.
	received: Arc<AtomicUsize>,
}

/// A readout of sizes from the meter. Note that it is possible, due to asynchrony, for received
/// to be slightly higher than sent.
#[derive(Debug, Add, Display, Clone, Default, PartialEq)]
#[display(fmt = "(sent={} received={})", sent, received)]
pub struct Readout {
	/// The amount of messages sent on the channel, in aggregate.
	pub sent: usize,
	/// The amount of messages received on the channel, in aggregate.
	pub received: usize,
}

impl Meter {
	/// Count the number of items queued up inside the channel.
	pub fn read(&self) -> Readout {
		// when obtaining we don't care much about off by one
		// accuracy
		Readout {
			sent: self.sent.load(Ordering::Relaxed),
			received: self.received.load(Ordering::Relaxed),
		}
	}

	fn note_sent(&self) {
		self.sent.fetch_add(1, Ordering::Relaxed);
	}

	fn retract_sent(&self) {
		self.sent.fetch_sub(1, Ordering::Relaxed);
	}

	fn note_received(&self) {
		self.received.fetch_add(1, Ordering::Relaxed);
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use futures::{executor::block_on, StreamExt};

	#[derive(Clone, Copy, Debug, Default)]
	struct Msg {
		val: u8,
	}

	#[test]
	fn try_send_try_next() {
		block_on(async move {
			let (mut tx, mut rx) = channel::<Msg>(5);
			let msg = Msg::default();
			assert_eq!(rx.meter().read(), Readout { sent: 0, received: 0 });
			tx.try_send(msg).unwrap();
			assert_eq!(tx.meter().read(), Readout { sent: 1, received: 0 });
			tx.try_send(msg).unwrap();
			tx.try_send(msg).unwrap();
			tx.try_send(msg).unwrap();
			assert_eq!(tx.meter().read(), Readout { sent: 4, received: 0 });
			rx.try_next().unwrap();
			assert_eq!(rx.meter().read(), Readout { sent: 4, received: 1 });
			rx.try_next().unwrap();
			rx.try_next().unwrap();
			assert_eq!(tx.meter().read(), Readout { sent: 4, received: 3 });
			rx.try_next().unwrap();
			assert_eq!(rx.meter().read(), Readout { sent: 4, received: 4 });
			assert!(rx.try_next().is_err());
		});
	}

	#[test]
	fn with_tasks() {
		let (ready, go) = futures::channel::oneshot::channel();

		let (mut tx, mut rx) = channel::<Msg>(5);
		block_on(async move {
			futures::join!(
				async move {
					let msg = Msg::default();
					assert_eq!(tx.meter().read(), Readout { sent: 0, received: 0 });
					tx.try_send(msg).unwrap();
					assert_eq!(tx.meter().read(), Readout { sent: 1, received: 0 });
					tx.try_send(msg).unwrap();
					tx.try_send(msg).unwrap();
					tx.try_send(msg).unwrap();
					ready.send(()).expect("Helper oneshot channel must work. qed");
				},
				async move {
					go.await.expect("Helper oneshot channel must work. qed");
					assert_eq!(rx.meter().read(), Readout { sent: 4, received: 0 });
					rx.try_next().unwrap();
					assert_eq!(rx.meter().read(), Readout { sent: 4, received: 1 });
					rx.try_next().unwrap();
					rx.try_next().unwrap();
					assert_eq!(rx.meter().read(), Readout { sent: 4, received: 3 });
					rx.try_next().unwrap();
					assert_eq!(dbg!(rx.meter().read()), Readout { sent: 4, received: 4 });
				}
			)
		});
	}

	use futures_timer::Delay;
	use std::time::Duration;

	#[test]
	fn stream_and_sink() {
		let (mut tx, mut rx) = channel::<Msg>(5);

		block_on(async move {
			futures::join!(
				async move {
					for i in 0..15 {
						println!("Sent #{} with a backlog of {} items", i + 1, tx.meter().read());
						let msg = Msg { val: i as u8 + 1u8 };
						tx.send(msg).await.unwrap();
						assert!(tx.meter().read().sent > 0usize);
						Delay::new(Duration::from_millis(20)).await;
					}
					()
				},
				async move {
					while let Some(msg) = rx.next().await {
						println!("rx'd one {} with {} backlogged", msg.val, rx.meter().read());
						Delay::new(Duration::from_millis(29)).await;
					}
				}
			)
		});
	}

	#[test]
	fn failed_send_does_not_inc_sent() {
		let (mut bounded, _) = channel::<Msg>(5);
		let (unbounded, _) = unbounded::<Msg>();

		block_on(async move {
			assert!(bounded.send(Msg::default()).await.is_err());
			assert!(bounded.try_send(Msg::default()).is_err());
			assert_eq!(bounded.meter().read(), Readout { sent: 0, received: 0 });

			assert!(unbounded.unbounded_send(Msg::default()).is_err());
			assert_eq!(unbounded.meter().read(), Readout { sent: 0, received: 0 });
		});
	}
}