mysten_metrics/
guards.rs

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
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use prometheus::IntGauge;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

/// Increments gauge when acquired, decrements when guard drops
pub struct GaugeGuard<'a>(&'a IntGauge);

impl<'a> GaugeGuard<'a> {
    pub fn acquire(g: &'a IntGauge) -> Self {
        g.inc();
        Self(g)
    }
}

impl Drop for GaugeGuard<'_> {
    fn drop(&mut self) {
        self.0.dec();
    }
}

pub trait GaugeGuardFutureExt: Future + Sized {
    /// Count number of in flight futures running
    fn count_in_flight(self, g: &IntGauge) -> GaugeGuardFuture<Self>;
}

impl<F: Future> GaugeGuardFutureExt for F {
    fn count_in_flight(self, g: &IntGauge) -> GaugeGuardFuture<Self> {
        GaugeGuardFuture {
            f: Box::pin(self),
            _guard: GaugeGuard::acquire(g),
        }
    }
}

pub struct GaugeGuardFuture<'a, F: Sized> {
    f: Pin<Box<F>>,
    _guard: GaugeGuard<'a>,
}

impl<F: Future> Future for GaugeGuardFuture<'_, F> {
    type Output = F::Output;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.f.as_mut().poll(cx)
    }
}