fedimint_core/task/
waiter.rs

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
//! Wait for a task to finish.

use tokio::sync::Semaphore;

/// Helper to wait for actions to be [`Self::done`]
#[derive(Debug)]
pub struct Waiter {
    done_semaphore: Semaphore,
}

impl Default for Waiter {
    fn default() -> Self {
        Self::new()
    }
}

impl Waiter {
    pub fn new() -> Self {
        Self {
            // semaphore never has permits.
            done_semaphore: Semaphore::new(0),
        }
    }

    /// Mark this waiter as done.
    ///
    /// NOTE: Calling this twice is ignored.
    pub fn done(&self) {
        // close the semaphore and notify all waiters.
        self.done_semaphore.close();
    }

    /// Wait for [`Self::done`] call.
    pub async fn wait(&self) {
        // wait for semaphore to be closed.
        self.done_semaphore
            .acquire()
            .await
            .expect_err("done semaphore is only closed, never has permits");
    }

    /// Check if Waiter was marked as done.
    pub fn is_done(&self) -> bool {
        self.done_semaphore.is_closed()
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::*;

    #[tokio::test]
    async fn test_simple() {
        let waiter = Waiter::new();
        assert!(!waiter.is_done());
        waiter.done();
        assert!(waiter.is_done());
    }

    #[tokio::test]
    async fn test_async() {
        let waiter = Waiter::new();
        assert!(!waiter.is_done());
        tokio::join!(
            async {
                waiter.done();
            },
            async {
                waiter.wait().await;
            }
        );
        assert!(waiter.is_done());
        waiter.wait().await;
        assert!(waiter.is_done());
    }
    #[tokio::test]
    async fn test_async_multi() {
        let waiter = Waiter::new();
        assert!(!waiter.is_done());
        tokio::join!(
            async {
                waiter.done();
            },
            async {
                waiter.done();
            },
            async {
                waiter.done();
            },
        );
        assert!(waiter.is_done());
        waiter.wait().await;
        assert!(waiter.is_done());
    }
    #[tokio::test]
    async fn test_async_sleep() {
        let waiter = Waiter::new();
        assert!(!waiter.is_done());
        tokio::join!(
            async {
                fedimint_core::runtime::sleep(Duration::from_millis(10)).await;
                waiter.done();
            },
            waiter.wait(),
        );
        assert!(waiter.is_done());
        waiter.wait().await;
        assert!(waiter.is_done());
    }
}