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
mod future_ext;
#[cfg(feature = "prometheus")]
pub mod prometheus;
pub use future_ext::{ObservedFuture, ObservedFutureExt};
/// Represents an observer, which reacts to different events happening to the
/// future.
///
/// If any of the functions is used incorrectly, implementation's behaviour
/// could be undefined but must always be safe.
#[allow(unused_variables)]
pub trait Observer<Out: ?Sized> {
/// Called once before the first future's poll.
fn on_first_poll(&mut self) {}
/// Called each time before the future is polled, but *after* `on_first_poll`.
fn on_poll(&mut self) {}
/// Called once after the future returns `Poll::Ready`.
fn on_poll_ready(&mut self, output: &Out) {}
/// Called once after `on_poll_ready` or before `on_drop`, depending on
/// whether future was cancelled or not. It isn't called if there was no
/// call to `on_first_poll`.
fn on_finish(&mut self, output: Option<&Out>) {}
/// Called once before the future is dropped, therefore is never called twice
/// and forbids calls to other trait's functions.
fn on_drop(&mut self) {}
}
/// Represents the object that can be seen as a status in metrics system.
pub trait AsStatusLabel {
/// Get status label of this object.
fn as_status_label(&self) -> String;
}
impl<T, E: AsStatusLabel> AsStatusLabel for Result<T, E> {
fn as_status_label(&self) -> String {
match self {
Ok(_) => "ok".to_owned(),
Err(err) => err.as_status_label(),
}
}
}
impl AsStatusLabel for str {
fn as_status_label(&self) -> String {
self.to_string()
}
}
#[allow(non_snake_case)]
mod macro_impl {
use super::Observer;
macro_rules! impl_observer_tuple {
($($t:tt)+) => {
impl<Out: ?Sized, $($t),+> Observer<Out> for ($($t),+,)
where
$($t: Observer<Out>),+
{
fn on_first_poll(&mut self) {
let ($($t),+,) = self;
$($t.on_first_poll();)+
}
fn on_poll(&mut self) {
let ($($t),+,) = self;
$($t.on_poll();)+
}
fn on_poll_ready(&mut self, output: &Out) {
let ($($t),+,) = self;
$($t.on_poll_ready(output);)+
}
fn on_finish(&mut self, output: Option<&Out>) {
let ($($t),+,) = self;
$($t.on_finish(output);)+
}
fn on_drop(&mut self) {
let ($($t),+,) = self;
$($t.on_drop();)+
}
}
}
}
impl_observer_tuple! { O1 }
impl_observer_tuple! { O1 O2 }
impl_observer_tuple! { O1 O2 O3 }
impl_observer_tuple! { O1 O2 O3 O4 }
impl_observer_tuple! { O1 O2 O3 O4 O5 }
impl_observer_tuple! { O1 O2 O3 O4 O5 O6 }
impl_observer_tuple! { O1 O2 O3 O4 O5 O6 O7 }
impl_observer_tuple! { O1 O2 O3 O4 O5 O6 O7 O8 }
}