#[cfg(not(all(feature = "wasm", target_family = "wasm")))]
use chrono::Utc;
#[cfg(not(all(feature = "wasm", target_family = "wasm")))]
pub(crate) use tokio::time::Instant;
#[cfg(all(feature = "wasm", target_family = "wasm"))]
pub(crate) use web_time::Instant;
#[cfg(all(feature = "wasm", target_family = "wasm"))]
use super::js_utils;
#[cfg(not(all(feature = "wasm", target_family = "wasm")))]
pub fn get_epoch_ms() -> u128 {
#[cfg(all(test, feature = "dummy", not(target_family = "wasm")))]
if let Some(now_ms) = crate::simulation::epoch_ms_override() {
return now_ms;
}
Utc::now().timestamp_millis() as u128
}
#[cfg(all(feature = "wasm", target_family = "wasm"))]
pub fn get_epoch_ms() -> u128 {
let now = js_sys::Date::now();
if now.is_finite() && now > 0.0 {
now as u128
} else {
0
}
}
pub(crate) fn get_epoch_ms_i64() -> i64 {
i64::try_from(get_epoch_ms()).unwrap_or(i64::MAX)
}
#[cfg(not(all(feature = "wasm", target_family = "wasm")))]
pub(crate) async fn sleep(duration: std::time::Duration) {
#[cfg(all(test, feature = "dummy", not(target_family = "wasm")))]
if crate::simulation::epoch_ms_override().is_some() {
tokio::time::sleep(duration).await;
return;
}
futures_timer::Delay::new(duration).await;
}
#[cfg(not(all(feature = "wasm", target_family = "wasm")))]
pub(crate) async fn try_sleep(duration: std::time::Duration) -> bool {
#[cfg(all(test, feature = "dummy", not(target_family = "wasm")))]
if crate::simulation::epoch_ms_override().is_some() {
tokio::time::sleep(duration).await;
return true;
}
futures_timer::Delay::new(duration).await;
true
}
#[cfg(all(feature = "wasm", target_family = "wasm"))]
pub(crate) async fn sleep(duration: std::time::Duration) {
let _ = try_sleep(duration).await;
}
#[cfg(all(feature = "wasm", target_family = "wasm"))]
pub(crate) async fn try_sleep(duration: std::time::Duration) -> bool {
let millis = i32::try_from(duration.as_millis()).unwrap_or(i32::MAX);
match js_utils::window_sleep(millis).await {
Ok(_) => true,
Err(error) => {
tracing::error!("failed to wait for timeout: {:?}", error);
false
}
}
}