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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
use std::time::Duration;
use tokio::sync::{mpsc, oneshot};
use tokio::time::delay_for;
use os_clock::{self, Clock, ThreadCPUClock};
use futures::executor::block_on;
async fn delay_until_clock<C: Clock>(clock: C, timeout_at: Duration) -> std::io::Result<()> {
loop {
let current = clock.get_time()?;
if current >= timeout_at {
return Ok(());
}
delay_for(timeout_at - current).await;
}
}
pub struct TimeoutListener(Box<dyn (FnOnce()) + Send>);
impl<L: (FnOnce()) + Send> From<L> for TimeoutListener
where
L: 'static,
{
fn from(listener: L) -> TimeoutListener {
TimeoutListener(Box::new(listener))
}
}
struct TimeoutRequest<C: Clock> {
cancel_rx: oneshot::Receiver<()>,
result_tx: oneshot::Sender<TimeoutResult>,
on_timeout: TimeoutListener,
clock: C,
timeout_at: Duration,
}
impl<C: Clock> TimeoutRequest<C> {
async fn run(self) {
let on_timeout = self.on_timeout;
let cancel_rx = self.cancel_rx;
let result = tokio::select! {
Ok(_) = cancel_rx => {
TimeoutResult::Cancelled
},
result = delay_until_clock(self.clock, self.timeout_at) => {
match result {
Ok(_) => {
on_timeout.0();
TimeoutResult::TimedOut
},
Err(err) => TimeoutResult::StatusError(err)
}
}
};
let _ = self.result_tx.send(result);
}
}
pub enum TimeoutResult {
TimedOut,
Cancelled,
StatusError(std::io::Error),
}
pub struct TimeoutHandle {
cancel_tx: oneshot::Sender<()>,
result_rx: oneshot::Receiver<TimeoutResult>,
}
impl TimeoutHandle {
pub fn cancel_ignored(self) {
let _ = self.cancel_tx.send(());
}
pub async fn cancel(self) -> TimeoutResult {
let _ = self.cancel_tx.send(());
self.result_rx.await.unwrap()
}
pub fn cancel_sync(self) -> TimeoutResult {
block_on(self.cancel())
}
}
pub struct Timer<C: Clock>
where
C: 'static,
{
tx: mpsc::UnboundedSender<TimeoutRequest<C>>,
}
impl<C: Clock> Timer<C> {
pub fn set_timeout<T: Into<TimeoutListener>>(
&self,
clock: C,
duration: Duration,
callback: T,
) -> TimeoutHandle {
let timeout_at = clock.get_time().unwrap() + duration;
let (cancel_tx, cancel_rx) = oneshot::channel();
let (result_tx, result_rx) = oneshot::channel();
self.tx
.send(TimeoutRequest {
cancel_rx,
result_tx,
timeout_at,
on_timeout: callback.into(),
clock,
})
.map_err(|_| {})
.unwrap();
return TimeoutHandle {
cancel_tx,
result_rx,
};
}
pub fn spawn() -> Self {
let (timeout_req_tx, mut timeout_req_rx) = mpsc::unbounded_channel::<TimeoutRequest<C>>();
tokio::spawn(async move {
while let Some(timeout) = timeout_req_rx.recv().await {
tokio::spawn(timeout.run());
}
});
return Timer { tx: timeout_req_tx };
}
}
impl Timer<ThreadCPUClock> {
pub fn set_timeout_on_current_thread_cpu_usage<T: Into<TimeoutListener>>(
&self,
duration: Duration,
callback: T,
) -> TimeoutHandle {
let clock = os_clock::cpu_clock_for_current_thread().unwrap();
self.set_timeout(clock, duration, callback)
}
}