1use async_std::future;
2use std::time::{Duration, SystemTime};
3use tide::{Middleware, Next, Request, Response};
4
5#[derive(Clone, Debug)]
6pub struct DelayMiddleware {
7 expected_duration: Duration,
8}
9
10impl DelayMiddleware {
11 pub fn new(expected_duration: Duration) -> Self {
12 Self { expected_duration }
13 }
14}
15
16#[tide::utils::async_trait]
17impl<State: Clone + Send + Sync + 'static> Middleware<State> for DelayMiddleware {
18 async fn handle(&self, req: Request<State>, next: Next<'_, State>) -> tide::Result {
19 let time = SystemTime::now();
20
21 let res: Response = next.run(req).await;
22
23 if let Ok(elapsed_duration) = time.elapsed() {
24 if let Some(remaining_duration) = self.expected_duration.checked_sub(elapsed_duration) {
25 let _ = future::timeout(remaining_duration, future::pending::<()>()).await;
26 }
27 }
28
29 Ok(res)
30 }
31}