tearup/helper/
time_gate.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
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
#[cfg(feature = "async")]
pub use asyncc::*;
use std::{
    sync::{Arc, Mutex},
    thread::sleep,
    time::Duration,
};
use stopwatch::Stopwatch;

use crate::TimeoutError;

pub type ReadyFn = Box<dyn Fn() + Send + Sync>;

pub struct TimeGate {
    ready_flag: Arc<Mutex<bool>>,
    ready_checks_interval: Duration,
}

impl TimeGate {
    pub fn new(ready_checks_interval: Duration) -> Self {
        TimeGate {
            ready_flag: Arc::new(Mutex::new(false)),
            ready_checks_interval,
        }
    }

    pub fn notifier(&self) -> ReadyFn {
        let ready_flag = self.ready_flag.clone();

        Box::new(move || {
            let mut ready = ready_flag.lock().unwrap();
            *ready = true;
        })
    }

    pub fn wait_signal(self) {
        let ready = || *self.ready_flag.lock().unwrap();

        while !ready() {
            sleep(self.ready_checks_interval);
        }
    }

    pub fn wait_signal_or_timeout(self, timeout: Duration) -> Result<(), TimeoutError> {
        let stopwatch = Stopwatch::start_new();
        let ready = || *self.ready_flag.lock().unwrap();

        while !ready() {
            if stopwatch.elapsed() >= timeout {
                return Err(TimeoutError {
                    duration: timeout,
                    ready_checks_interval: self.ready_checks_interval,
                });
            }
            sleep(self.ready_checks_interval);
        }

        Ok(())
    }
}

impl Default for TimeGate {
    fn default() -> Self {
        Self::new(Duration::from_millis(10))
    }
}

#[cfg(feature = "async")]
mod asyncc {

    use futures::future::BoxFuture;
    pub use futures::future::FutureExt;
    use std::{sync::Arc, time::Duration};
    use stopwatch::Stopwatch;
    use tokio::{sync::Mutex, time::sleep};

    use crate::TimeoutError;

    pub struct AsyncTimeGate {
        ready_flag: Arc<Mutex<bool>>,
        ready_checks_interval: Duration,
    }

    pub type AsyncReadyFn<'a> = Box<dyn Fn() -> BoxFuture<'a, ()> + Send + Sync>;

    impl AsyncTimeGate {
        pub fn new(ready_checks_interval: Duration) -> Self {
            AsyncTimeGate {
                ready_flag: Arc::new(Mutex::new(false)),
                ready_checks_interval,
            }
        }

        pub fn notifier<'a>(&self) -> AsyncReadyFn<'a> {
            let ready_flag = self.ready_flag.clone();

            Box::new(move || {
                let ready_flag = ready_flag.clone();
                Box::pin(async move {
                    let mut ready_flag = ready_flag.lock().await;
                    *ready_flag = true;
                })
            })
        }

        pub async fn wait_signal_or_timeout(self, timeout: Duration) -> Result<(), TimeoutError> {
            let stopwatch = Stopwatch::start_new();

            while !self.is_ready().await {
                if stopwatch.elapsed() >= timeout {
                    return Err(TimeoutError {
                        duration: timeout,
                        ready_checks_interval: self.ready_checks_interval,
                    });
                }
                sleep(self.ready_checks_interval).await;
            }

            Ok(())
        }

        async fn is_ready(&self) -> bool {
            *self.ready_flag.lock().await
        }
    }

    impl Default for AsyncTimeGate {
        fn default() -> Self {
            Self::new(Duration::from_millis(10))
        }
    }

    #[cfg(test)]
    mod test {
        use std::time::Duration;
        use stopwatch::Stopwatch;
        use tokio::{spawn, time::sleep};

        use crate::TimeoutError;

        use super::AsyncTimeGate;

        #[tokio::test]
        async fn it_waits_signal() {
            let stopwatch = Stopwatch::start_new();

            let gate = AsyncTimeGate::default();
            let ready = gate.notifier();

            spawn(async move {
                sleep(Duration::from_millis(100)).await;
                ready().await;
            })
            .await
            .unwrap();

            gate.wait_signal_or_timeout(Duration::from_millis(115))
                .await
                .unwrap();
            assert_around_100ms_(&stopwatch);
        }

        #[tokio::test]
        async fn it_waits_signal_even_with_timeout_option() {
            let stopwatch = Stopwatch::start_new();

            let gate = AsyncTimeGate::default();
            let ready = gate.notifier();

            spawn(async move {
                sleep(Duration::from_millis(100)).await;
                ready().await;
            });

            assert!(gate
                .wait_signal_or_timeout(Duration::from_millis(115))
                .await
                .is_ok(),);
            assert_around_100ms_(&stopwatch);
        }

        #[tokio::test]
        async fn it_timeouts() {
            let stopwatch = Stopwatch::start_new();

            let gate = AsyncTimeGate::default();
            let ready = gate.notifier();

            spawn(async move {
                sleep(Duration::from_millis(100)).await;
                ready().await;
            });

            let timeout = Duration::from_millis(85);
            assert_eq!(
                gate.wait_signal_or_timeout(Duration::from_millis(85)).await,
                Err(TimeoutError {
                    duration: timeout,
                    ready_checks_interval: Duration::from_millis(10),
                })
            );
            assert_around_100ms_(&stopwatch);
        }

        fn assert_around_100ms_(stopwatch: &Stopwatch) {
            let ms = stopwatch.elapsed_ms();
            assert!(115 > ms, "stopwatch has {} elapsed ms > 115", ms);
            assert!(ms > 85, "stopwatch has {} elapsed ms < 85", ms);
        }
    }
}

#[cfg(test)]
mod test {
    use std::{
        thread::{sleep, spawn},
        time::Duration,
    };
    use stopwatch::Stopwatch;

    use super::TimeGate;
    use crate::TimeoutError;

    #[test]
    fn it_waits_signal() {
        let stopwatch = Stopwatch::start_new();

        let gate = TimeGate::default();
        let ready = gate.notifier();

        spawn(move || {
            sleep(Duration::from_millis(100));
            ready();
        });

        gate.wait_signal();
        assert_around_100ms_(&stopwatch);
    }

    #[test]
    fn it_waits_signal_even_with_timeout_option() {
        let stopwatch = Stopwatch::start_new();

        let gate = TimeGate::default();
        let ready = gate.notifier();

        spawn(move || {
            sleep(Duration::from_millis(100));
            ready();
        });

        assert!(gate
            .wait_signal_or_timeout(Duration::from_millis(115))
            .is_ok(),);
        assert_around_100ms_(&stopwatch);
    }

    #[test]
    fn it_timeouts() {
        let stopwatch = Stopwatch::start_new();

        let gate = TimeGate::default();
        let ready = gate.notifier();

        spawn(move || {
            sleep(Duration::from_millis(100));
            ready();
        });

        let timeout = Duration::from_millis(85);
        assert_eq!(
            gate.wait_signal_or_timeout(Duration::from_millis(85)),
            Err(TimeoutError {
                duration: timeout,
                ready_checks_interval: Duration::from_millis(10),
            })
        );
        assert_around_100ms_(&stopwatch);
    }

    fn assert_around_100ms_(stopwatch: &Stopwatch) {
        let ms = stopwatch.elapsed_ms();
        assert!(115 > ms, "stopwatch has {} elapsed ms > 115", ms);
        assert!(ms > 85, "stopwatch has {} elapsed ms < 85", ms);
    }
}