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
128
129
130
131
132
133
134
use crate::{ctxt_with_diag, log_out};
use pin_project::pin_project;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Instant;
use std::{borrow::Cow, fmt, future::Future, mem, pin::Pin, task::Context, task::Poll};
pub fn diagnose<T>(name: impl Into<Cow<'static, str>>, inner: T) -> DiagnoseFuture<T> {
if log_out::is_enabled() {
crate::absolute_time::elapsed_since_abs_time(Instant::now());
}
DiagnoseFuture {
inner,
task_name: name.into(),
task_id: {
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
NEXT_ID.fetch_add(1, Ordering::Relaxed)
},
first_time_poll: true,
}
}
#[pin_project]
#[derive(Clone)]
pub struct DiagnoseFuture<T> {
#[pin]
inner: T,
task_name: Cow<'static, str>,
task_id: u64,
first_time_poll: bool,
}
impl<T> Future for DiagnoseFuture<T>
where
T: Future,
{
type Output = T::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
let this = self.project();
if !log_out::is_enabled() {
return Future::poll(this.inner, cx);
}
let before = Instant::now();
let waker = ctxt_with_diag::waker_with_diag(
cx.waker().clone(),
this.task_name.clone(),
*this.task_id,
);
let mut cx = Context::from_waker(&waker);
let outcome = Future::poll(this.inner, &mut cx);
let after = Instant::now();
log_out::log_poll(
&this.task_name,
*this.task_id,
before,
after,
mem::replace(this.first_time_poll, false),
outcome.is_ready(),
);
outcome
}
}
impl<T> futures01::Future for DiagnoseFuture<T>
where
T: futures01::Future,
{
type Item = T::Item;
type Error = T::Error;
fn poll(&mut self) -> futures01::Poll<Self::Item, Self::Error> {
if !log_out::is_enabled() {
return self.inner.poll();
}
let before = Instant::now();
let outcome = self.inner.poll();
let after = Instant::now();
let last_time = match outcome {
Ok(futures01::Async::Ready(_)) => true,
Ok(futures01::Async::NotReady) => false,
Err(_) => true,
};
log_out::log_poll(
&self.task_name,
self.task_id,
before,
after,
mem::replace(&mut self.first_time_poll, false),
last_time,
);
outcome
}
}
impl<T> fmt::Debug for DiagnoseFuture<T>
where
T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.inner, f)
}
}