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
use futures::Future;
use std::{
pin::Pin,
task::{Context, Poll},
};
use tokio::{
sync::mpsc,
time::{sleep_until, Duration, Instant, Sleep},
};
#[derive(Debug)]
pub struct Elapsed;
#[derive(Debug)]
pub struct Closed;
pin_project_lite::pin_project! {
#[derive(Debug)]
pub struct AdjustableTimeout<T> {
#[pin]
future: T,
#[pin]
delay: Sleep,
tx: mpsc::UnboundedSender<Command>,
rx: mpsc::UnboundedReceiver<Command>,
}
}
enum Command {
Increment(Duration),
Decrement(Duration),
Update(Instant),
}
pub struct Handle {
tx: mpsc::UnboundedSender<Command>,
}
impl Handle {
pub(crate) fn new(tx: mpsc::UnboundedSender<Command>) -> Self {
Self { tx }
}
pub fn increment(&self, value: Duration) -> Result<(), Closed> {
self.tx.send(Command::Increment(value)).map_err(|_| Closed)
}
pub fn decrement(&self, value: Duration) -> Result<(), Closed> {
self.tx.send(Command::Decrement(value)).map_err(|_| Closed)
}
pub fn update(&self, deadline: Instant) -> Result<(), Closed> {
self.tx.send(Command::Update(deadline)).map_err(|_| Closed)
}
}
impl<T> AdjustableTimeout<T> {
pub fn handle(&self) -> Handle {
Handle::new(self.tx.clone())
}
}
pub fn adjustable_timeout<T>(duration: Duration, future: T) -> AdjustableTimeout<T>
where
T: Future,
{
let (tx, rx) = mpsc::unbounded_channel();
let deadline = Instant::now() + duration;
let delay = sleep_until(deadline);
AdjustableTimeout {
future,
delay,
tx,
rx,
}
}
impl<T> Future for AdjustableTimeout<T>
where
T: Future,
{
type Output = Result<T::Output, Elapsed>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut this = self.project();
if let Poll::Ready(v) = this.future.poll(cx) {
return Poll::Ready(Ok(v));
}
if let Poll::Ready(cmd) = this.rx.poll_recv(cx) {
let deadline = match cmd.expect("shouldn't happen") {
Command::Increment(value) => this.delay.deadline() + value,
Command::Decrement(value) => this.delay.deadline() - value,
Command::Update(deadline) => deadline,
};
this.delay.as_mut().reset(deadline);
}
if let Poll::Ready(()) = this.delay.poll(cx) {
return Poll::Ready(Err(Elapsed));
}
Poll::Pending
}
}