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
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.

use pin_project::pin_project;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use tikv_util::deadline::{Deadline, DeadlineError};

/// Checks the deadline before every poll of the future. If the deadline is exceeded,
/// `DeadlineError` is returned.
pub fn check_deadline<F: Future>(
    fut: F,
    deadline: Deadline,
) -> impl Future<Output = Result<F::Output, DeadlineError>> {
    DeadlineChecker { fut, deadline }
}

#[pin_project]
struct DeadlineChecker<F: Future> {
    #[pin]
    fut: F,
    deadline: Deadline,
}

impl<F> Future for DeadlineChecker<F>
where
    F: Future,
{
    type Output = Result<F::Output, DeadlineError>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        self.deadline.check()?;
        let this = self.project();
        this.fut.poll(cx).map(Ok)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use std::{thread, time::Duration};
    use tokio::task::yield_now;

    #[tokio::test(basic_scheduler)]
    async fn test_deadline_checker() {
        async fn work(iter: i32) {
            for i in 0..iter {
                thread::sleep(Duration::from_millis(50));
                if i < iter - 1 {
                    yield_now().await;
                }
            }
        }

        let res = check_deadline(work(5), Deadline::from_now(Duration::from_millis(500))).await;
        assert!(res.is_ok());

        let res = check_deadline(work(100), Deadline::from_now(Duration::from_millis(500))).await;
        assert!(res.is_err());
    }
}