// 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 .
//! Metered variant of bounded mpsc channels to be able to extract metrics.
use super::*;
/// Create a wrapped `mpsc::channel` pair of `MeteredSender` and `MeteredReceiver`.
pub fn channel(capacity: usize, name: &'static str) -> (MeteredSender, MeteredReceiver) {
let (tx, rx) = mpsc::channel(capacity);
let mut shared_meter = Meter::default();
shared_meter.name = name;
let tx = MeteredSender { meter: shared_meter.clone(), inner: tx };
let rx = MeteredReceiver { meter: shared_meter, inner: rx };
(tx, rx)
}
/// A receiver tracking the messages consumed by itself.
#[derive(Debug)]
pub struct MeteredReceiver {
// count currently contained messages
meter: Meter,
inner: mpsc::Receiver,
}
impl std::ops::Deref for MeteredReceiver {
type Target = mpsc::Receiver;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl std::ops::DerefMut for MeteredReceiver {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
impl Stream for MeteredReceiver {
type Item = T;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll