Skip to main content

co_actor/
time.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2026 1io BRANDGUARDIAN GmbH
3
4use std::time::Duration;
5#[cfg(not(feature = "js"))]
6pub use std::time::Instant;
7#[cfg(feature = "js")]
8pub use web_time::Instant;
9
10/// Platform-agnostic sleep for a duration. Send-safe on all platforms.
11#[cfg(not(feature = "js"))]
12pub async fn sleep(duration: Duration) {
13	tokio::time::sleep(duration).await;
14}
15
16/// Platform-agnostic sleep for a duration. Send-safe on all platforms.
17#[cfg(feature = "js")]
18pub async fn sleep(duration: Duration) {
19	futures_timer::Delay::new(duration).await;
20}
21
22/// Platform-agnostic sleep until a deadline
23#[cfg(not(feature = "js"))]
24pub async fn sleep_until(deadline: Instant) {
25	tokio::time::sleep_until(deadline.into()).await;
26}
27
28/// Platform-agnostic sleep until a deadline (tokio_with_wasm Sleep is !Send)
29#[cfg(feature = "js")]
30pub async fn sleep_until(deadline: Instant) {
31	let now = Instant::now();
32	if let Some(duration) = deadline.checked_duration_since(now) {
33		futures_timer::Delay::new(duration).await;
34	}
35}
36
37/// Platform-agnostic timeout. Send-safe on all platforms.
38#[cfg(not(feature = "js"))]
39pub async fn timeout<F: std::future::Future>(
40	duration: Duration,
41	future: F,
42) -> Result<F::Output, tokio::time::error::Elapsed> {
43	tokio::time::timeout(duration, future).await
44}
45
46/// Platform-agnostic timeout. Send-safe on all platforms.
47#[cfg(feature = "js")]
48pub async fn timeout<F: std::future::Future>(duration: Duration, future: F) -> Result<F::Output, Elapsed> {
49	use futures::future::Either;
50	use std::pin::pin;
51
52	let delay = pin!(futures_timer::Delay::new(duration));
53	let future = pin!(future);
54
55	match futures::future::select(future, delay).await {
56		Either::Left((output, _)) => Ok(output),
57		Either::Right((_, _)) => Err(Elapsed),
58	}
59}
60
61/// Error returned when a timeout expires.
62#[cfg(feature = "js")]
63#[derive(Debug)]
64pub struct Elapsed;
65
66#[cfg(feature = "js")]
67impl std::fmt::Display for Elapsed {
68	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69		write!(f, "deadline has elapsed")
70	}
71}
72
73#[cfg(feature = "js")]
74impl std::error::Error for Elapsed {}