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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// 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();
    }
}

/// Difference vs GaugeGuard: Stores the gauge by value to avoid borrowing issues.
pub struct InflightGuard(IntGauge);

impl InflightGuard {
    pub fn acquire(g: IntGauge) -> Self {
        g.inc();
        Self(g)
    }
}

impl Drop for InflightGuard {
    fn drop(&mut self) {
        self.0.dec();
    }
}

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

impl<F: Future> InflightGuardFutureExt for F {
    fn count_in_flight(self, g: IntGauge) -> InflightGuardFuture<Self> {
        InflightGuardFuture {
            f: Box::pin(self),
            _guard: InflightGuard::acquire(g),
        }
    }
}

pub struct InflightGuardFuture<F: Sized> {
    f: Pin<Box<F>>,
    _guard: InflightGuard,
}

impl<F: Future> Future for InflightGuardFuture<F> {
    type Output = F::Output;

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