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
// Copyright (C) 2019-2021 Aleo Systems Inc.
// This file is part of the snarkOS library.

// The snarkOS library 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.

// The snarkOS library 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 the snarkOS library. If not, see <https://www.gnu.org/licenses/>.

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

use tokio::sync::mpsc::{
    self,
    error::{SendError, TrySendError},
};

/// Wrapper over mpsc::Sender to track metrics
pub struct Sender<T: Send> {
    inner: mpsc::Sender<T>,
    tracker: Arc<AtomicUsize>,
    metrics_tracker: &'static str,
}

impl<T: Send> Clone for Sender<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            tracker: self.tracker.clone(),
            metrics_tracker: self.metrics_tracker,
        }
    }
}

impl<T: Send> fmt::Debug for Sender<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "sender for {}", self.metrics_tracker)
    }
}

impl<T: Send> Sender<T> {
    fn increment(&self) {
        metrics::increment_gauge!(self.metrics_tracker, 1.0);
        self.tracker.fetch_add(1, Ordering::SeqCst);
    }

    pub async fn send(&self, value: T) -> Result<(), SendError<T>> {
        self.increment();
        self.inner.send(value).await
    }

    pub fn try_send(&self, message: T) -> Result<(), TrySendError<T>> {
        self.increment();
        self.inner.try_send(message)
    }

    pub fn blocking_send(&self, value: T) -> Result<(), SendError<T>> {
        self.increment();
        self.inner.blocking_send(value)
    }
}

/// Wrapper over mpsc::Receiver to track metrics
#[derive(Debug)]
pub struct Receiver<T: Send> {
    inner: mpsc::Receiver<T>,
    tracker: Arc<AtomicUsize>,
    metrics_tracker: &'static str,
}

impl<T: Send> Receiver<T> {
    fn maybe_decrement(&self, is_ok: bool) {
        if is_ok {
            metrics::decrement_gauge!(self.metrics_tracker, 1.0);
            self.tracker.fetch_sub(1, Ordering::SeqCst);
        }
    }

    pub async fn recv(&mut self) -> Option<T> {
        let out = self.inner.recv().await;
        self.maybe_decrement(out.is_some());
        out
    }

    pub fn blocking_recv(&mut self) -> Option<T> {
        let out = self.inner.blocking_recv();
        self.maybe_decrement(out.is_some());
        out
    }
}

pub fn channel<T: Send>(metrics_tracker: &'static str, buffer: usize) -> (Sender<T>, Receiver<T>) {
    let (sender, receiver) = mpsc::channel(buffer);
    let tracker = Arc::new(AtomicUsize::new(0));

    (
        Sender {
            inner: sender,
            metrics_tracker,
            tracker: tracker.clone(),
        },
        Receiver {
            inner: receiver,
            metrics_tracker,
            tracker,
        },
    )
}

impl<T: Send> Drop for Receiver<T> {
    fn drop(&mut self) {
        let count = self.tracker.swap(0, Ordering::SeqCst) as f64;
        metrics::decrement_gauge!(self.metrics_tracker, count);
    }
}