1// Copyright 2022 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
1415use std::{error::Error, fmt, time::Duration};
1617use futures_core::Future;
18#[cfg(target_arch = "wasm32")]
19use futures_util::future::{select, Either};
20#[cfg(target_arch = "wasm32")]
21use gloo_timers::future::TimeoutFuture;
22#[cfg(not(target_arch = "wasm32"))]
23use tokio::time::timeout as tokio_timeout;
2425/// Error type notifying that a timeout has elapsed.
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub struct ElapsedError(());
2829impl fmt::Display for ElapsedError {
30fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31write!(f, "time waiting for future has elapsed!")
32 }
33}
3435impl Error for ElapsedError {}
3637/// Wait for `future` to be completed. `future` needs to return
38/// a `Result`.
39///
40/// If the given timeout has elapsed the method will stop waiting and return
41/// an error.
42pub async fn timeout<F, T>(future: F, duration: Duration) -> Result<T, ElapsedError>
43where
44F: Future<Output = T>,
45{
46#[cfg(not(target_arch = "wasm32"))]
47return tokio_timeout(duration, future).await.map_err(|_| ElapsedError(()));
4849#[cfg(target_arch = "wasm32")]
50{
51let timeout_future =
52 TimeoutFuture::new(u32::try_from(duration.as_millis()).expect("Overlong duration"));
5354match select(std::pin::pin!(future), timeout_future).await {
55 Either::Left((res, _)) => Ok(res),
56 Either::Right((_, _)) => Err(ElapsedError(())),
57 }
58 }
59}
6061#[cfg(test)]
62pub(crate) mod tests {
63use std::{future, time::Duration};
6465use matrix_sdk_test_macros::async_test;
6667use super::timeout;
6869#[cfg(target_arch = "wasm32")]
70wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
7172#[async_test]
73async fn test_without_timeout() {
74 timeout(future::ready(()), Duration::from_millis(100))
75 .await
76.expect("future should have completed without ElapsedError");
77 }
7879#[async_test]
80async fn test_with_timeout() {
81 timeout(future::pending::<()>(), Duration::from_millis(100))
82 .await
83.expect_err("future should return an ElapsedError");
84 }
85}