lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

commit 2ce4ce5107b5ac27938bc271723c8dd52fd4d3ef
parent 24fc6509b1a1217b8acd619d37fc6bdd9677705e
Author: triesap <tyson@radroots.org>
Date:   Tue, 20 Oct 2026 01:06:42 +0000

transport_nostr: preserve shared deadlines across native and browser hosts

- Centralize session clocks without changing native timer semantics
- Preserve absolute browser deadlines through delayed owner startup
- Bound browser waits and retain cancellation cleanup in a local owner
- Exercise pages and workers against the locked production timing closure

Diffstat:
MCargo.lock | 3+++
MCargo.toml | 2++
Mcrates/transport_nostr/Cargo.toml | 6++++++
Mcrates/transport_nostr/README.md | 11+++++++++++
Acrates/transport_nostr/src/host_time.rs | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/transport_nostr/src/host_time_browser.rs | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/transport_nostr/src/lib.rs | 1+
Mcrates/transport_nostr/src/sink.rs | 15++++-----------
Mcrates/transport_nostr/src/source.rs | 88++++++++++++++++++++++++++++++++++++-------------------------------------------
Mcrates/transport_nostr/src/subscription.rs | 41++++++++++++++++-------------------------
Acrates/transport_nostr/tests/browser_time/Cargo.lock | 501+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/transport_nostr/tests/browser_time/Cargo.toml | 22++++++++++++++++++++++
Acrates/transport_nostr/tests/browser_time/run.mjs | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/transport_nostr/tests/browser_time/src/lib.rs | 184+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/transport_nostr/tests/package_boundary.rs | 3+++
15 files changed, 1035 insertions(+), 84 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock @@ -3767,6 +3767,7 @@ dependencies = [ name = "radroots_transport_nostr" version = "0.1.0-alpha" dependencies = [ + "async-utility", "async-wsocket", "futures", "nostr-sdk", @@ -3781,6 +3782,8 @@ dependencies = [ "tokio-rustls", "tokio-tungstenite", "url", + "wasm-bindgen-futures", + "web-time", "webpki-roots 0.26.11", ] diff --git a/Cargo.toml b/Cargo.toml @@ -172,6 +172,8 @@ aes-gcm = { version = "0.10.3", default-features = false, features = [ "aes", "alloc", ] } +async-utility = { git = "https://github.com/yukibtc/async-utility", rev = "b323ae0c1c1424b78bf8bb8832b95e86771f1dee", version = "=0.3.2" } +web-time = { version = "=1.1.0" } async-wsocket = { version = "0.17" } base64 = { version = "0.22", default-features = false, features = ["alloc"] } bincode = { version = "1.3.3" } diff --git a/crates/transport_nostr/Cargo.toml b/crates/transport_nostr/Cargo.toml @@ -54,11 +54,17 @@ tokio-tungstenite = { workspace = true } url = { workspace = true } webpki-roots = { workspace = true } +[target.'cfg(target_arch = "wasm32")'.dependencies] +async-utility = { workspace = true } +wasm-bindgen-futures = { workspace = true } +web-time = { workspace = true } + [dev-dependencies] tokio = { workspace = true, features = [ "macros", "net", "rt-multi-thread", + "test-util", "time", ] } diff --git a/crates/transport_nostr/README.md b/crates/transport_nostr/README.md @@ -18,6 +18,17 @@ The authoritative package charter is the The reviewed Rust surface is recorded in the [public API baseline](../../contracts/api_baselines/radroots_transport_nostr.txt). +Shared fetch, delivery and subscription timing uses a private host boundary. +Native execution retains Tokio's monotonic deadlines and system observation +clock. The browser implementation uses browser monotonic and wall clocks and +the pinned upstream sleep with a separate local cancellation owner. The owner +measures the original deadline when it starts, without renewing its budget. +Fractional waits round up, long waits use bounded signed-delay chunks, and +each wake rechecks the deadline before reporting expiry. +Its isolated +page/worker fixture lives in `tests/browser_time`; this does not qualify the +complete transport, which still requires native socket I/O at this checkpoint. + ## Configure without connecting Configuration is explicit, validated, and inert. Constructing diff --git a/crates/transport_nostr/src/host_time.rs b/crates/transport_nostr/src/host_time.rs @@ -0,0 +1,105 @@ +//! Host clocks and deadlines shared by the Nostr session adapters. + +use core::time::Duration; + +#[cfg(not(target_arch = "wasm32"))] +pub(crate) use tokio::time::{Instant, timeout, timeout_at}; +#[cfg(target_arch = "wasm32")] +#[path = "host_time_browser.rs"] +mod browser; +#[cfg(target_arch = "wasm32")] +pub(crate) use browser::{Instant, timeout, timeout_at}; + +#[cfg_attr(coverage_nightly, coverage(off))] +pub(crate) fn unix_time_ms() -> u64 { + #[cfg(not(target_arch = "wasm32"))] + use std::time::{SystemTime, UNIX_EPOCH}; + #[cfg(target_arch = "wasm32")] + use web_time::{SystemTime, UNIX_EPOCH}; + + wall_millis(SystemTime::now().duration_since(UNIX_EPOCH).ok()) +} + +fn wall_millis(since_epoch: Option<Duration>) -> u64 { + since_epoch + .map(|duration| u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)) + .unwrap_or_default() +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + use core::{cell::Cell, future::pending}; + use futures::FutureExt; + use std::rc::Rc; + + struct OnDrop(Rc<Cell<bool>>); + + impl Drop for OnDrop { + fn drop(&mut self) { + self.0.set(true); + } + } + + #[test] + fn wall_clock_conversion_preserves_unavailable_and_saturated_values() { + assert_eq!(wall_millis(None), 0); + assert_eq!(wall_millis(Some(Duration::ZERO)), 0); + assert_eq!(wall_millis(Some(Duration::from_micros(1999))), 1); + assert_eq!(wall_millis(Some(Duration::MAX)), u64::MAX); + } + + #[tokio::test(start_paused = true)] + async fn ready_local_future_wins_even_at_an_expired_deadline() { + let local = Rc::new(Cell::new(7)); + let deadline = Instant::now() - Duration::from_secs(1); + assert_eq!( + timeout_at(deadline, async { local.get() }).await.unwrap(), + 7 + ); + } + + #[tokio::test(start_paused = true)] + async fn expiry_drops_pending_local_work() { + let dropped = Rc::new(Cell::new(false)); + let guard = OnDrop(Rc::clone(&dropped)); + assert!( + timeout(Duration::from_millis(10), async move { + let _guard = guard; + pending::<()>().await; + }) + .await + .is_err() + ); + assert!(dropped.get()); + } + + #[tokio::test(start_paused = true)] + async fn cancellation_drops_work_and_a_fresh_timeout_still_runs() { + let dropped = Rc::new(Cell::new(false)); + let guard = OnDrop(Rc::clone(&dropped)); + assert!( + timeout(Duration::from_secs(1), async move { + let _guard = guard; + pending::<()>().await; + }) + .now_or_never() + .is_none() + ); + assert!(dropped.get()); + assert_eq!( + timeout(Duration::from_secs(1), async { 9 }).await.unwrap(), + 9 + ); + } + + #[tokio::test(start_paused = true)] + async fn queued_work_consumes_one_original_deadline() { + let started = Instant::now(); + let deadline = started + Duration::from_millis(20); + tokio::time::sleep(Duration::from_millis(15)).await; + assert!(timeout_at(deadline, pending::<()>()).await.is_err()); + assert_eq!(Instant::now() - started, Duration::from_millis(20)); + assert!(timeout_at(deadline, pending::<()>()).await.is_err()); + } +} diff --git a/crates/transport_nostr/src/host_time_browser.rs b/crates/transport_nostr/src/host_time_browser.rs @@ -0,0 +1,59 @@ +//! Absolute deadlines with timer disposal confined to its local owner. + +use core::{future::Future, pin::pin, time::Duration}; +use futures::{ + channel::oneshot, + future::{Either, select}, +}; +pub(crate) use web_time::Instant; + +#[derive(Debug)] +pub(crate) struct Elapsed; + +pub(crate) async fn timeout<F: Future>( + duration: Duration, + future: F, +) -> Result<F::Output, Elapsed> { + timeout_at(Instant::now() + duration, future).await +} + +pub(crate) async fn timeout_at<F: Future>( + deadline: Instant, + future: F, +) -> Result<F::Output, Elapsed> { + let (elapsed, receiver) = oneshot::channel(); + let (cancel_on_drop, cancellation) = oneshot::channel::<()>(); + wasm_bindgen_futures::spawn_local(async move { + // Measure here: this owner may begin after the original caller yields. + // Dropping a losing timer here also avoids browser executor reentry in + // the task that polls the network future. + let timer = pin!(sleep_until(deadline)); + if matches!(select(timer, pin!(cancellation)).await, Either::Left(_)) { + let _ = elapsed.send(()); + } + }); + let result = match select(pin!(future), pin!(receiver)).await { + Either::Left((value, _)) => Ok(value), + Either::Right(_) => Err(Elapsed), + }; + // This sender also drops if the observer cancels while select is pending. + drop(cancel_on_drop); + result +} + +async fn sleep_until(deadline: Instant) { + loop { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return; + } + // Gloo truncates to whole milliseconds, then casts to the browser's + // signed timer argument. Round up and split long waits; recheck after + // every wake so neither truncation nor an early callback proves expiry. + let millis = remaining + .as_nanos() + .div_ceil(1_000_000) + .min(i32::MAX as u128) as u64; + async_utility::time::sleep(Duration::from_millis(millis)).await; + } +} diff --git a/crates/transport_nostr/src/lib.rs b/crates/transport_nostr/src/lib.rs @@ -8,6 +8,7 @@ mod connections; mod cursor; mod error; mod exact_delivery; +mod host_time; mod profile; mod relay; mod sink; diff --git a/crates/transport_nostr/src/sink.rs b/crates/transport_nostr/src/sink.rs @@ -1,6 +1,7 @@ //! Nostr implementation of the transport event sink. use crate::exact_delivery::ExactEvent; +use crate::host_time::unix_time_ms; use crate::{NostrTransport, RelayUrl, status}; use core::{fmt, time::Duration}; use futures::{StreamExt, stream}; @@ -104,14 +105,14 @@ impl RelayClient for LiveRelayClient { operation_timeout: Duration, ) -> BoxFuture<'a, Vec<RelayPublishResult>> { Box::pin(async move { - let deadline = tokio::time::Instant::now() + operation_timeout; + let deadline = crate::host_time::Instant::now() + operation_timeout; stream::iter(relays.into_iter().map(|relay| { let event = event.clone(); async move { let url = relay.as_str().to_owned(); let mut attempted = false; let attempt = async { - if tokio::time::Instant::now() >= deadline { + if crate::host_time::Instant::now() >= deadline { return Err("timeout".to_owned()); } attempted = true; @@ -130,7 +131,7 @@ impl RelayClient for LiveRelayClient { .map_err(|error| error.to_string())?; event.publish(&self.client, &self.writers, &url).await }; - let outcome = match tokio::time::timeout_at(deadline, attempt).await { + let outcome = match crate::host_time::timeout_at(deadline, attempt).await { Err(_) => status::delivery_failure("timeout"), Ok(Err(error)) => status::delivery_failure(&error), Ok(Ok(outcome)) => outcome, @@ -366,14 +367,6 @@ impl EventSink for NostrTransport { } } -#[cfg_attr(coverage_nightly, coverage(off))] -fn unix_time_ms() -> u64 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|duration| u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)) - .unwrap_or_default() -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/transport_nostr/src/source.rs b/crates/transport_nostr/src/source.rs @@ -1,5 +1,6 @@ //! Nostr implementation of the transport event source. +use crate::host_time::unix_time_ms; use crate::{NostrTransport, RelayCursor, RelayUrl, status}; use core::cmp::Ordering; use core::time::Duration; @@ -16,7 +17,6 @@ use radroots_transport::{ use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; -use std::time::{SystemTime, UNIX_EPOCH}; #[path = "source_budget.rs"] pub(crate) mod budget; @@ -39,7 +39,7 @@ pub(crate) struct SourceQuery { selector: radroots_transport::source::FetchSelector, until_unix_seconds: Option<u64>, connect_timeout: Duration, - deadline: tokio::time::Instant, + deadline: crate::host_time::Instant, max_connections: usize, } @@ -161,7 +161,7 @@ impl RelaySourceClient for LiveRelaySourceClient { if budget.exhausted() { return Ok(RelayFetchResult::ResourceLimit(Vec::new())); } - if tokio::time::Instant::now() >= deadline { + if crate::host_time::Instant::now() >= deadline { return Ok(RelayFetchResult::Timeout(Vec::new())); } let kinds = selector @@ -194,17 +194,17 @@ impl RelaySourceClient for LiveRelaySourceClient { if let Some(until) = until_unix_seconds { filter = filter.until(Timestamp::from_secs(until)); } - let connected = tokio::time::timeout_at(deadline, async { + let connected = crate::host_time::timeout_at(deadline, async { crate::client::connect_tracked( - &self.client, - &self.connections, - url.as_str(), - connect_timeout.min( - deadline.saturating_duration_since(tokio::time::Instant::now()), - ), - ) - .await - .map_err(|error| error.to_string()) + &self.client, + &self.connections, + url.as_str(), + connect_timeout.min(deadline.saturating_duration_since( + crate::host_time::Instant::now(), + )), + ) + .await + .map_err(|error| error.to_string()) }) .await; let relay = match connected { @@ -217,14 +217,14 @@ impl RelaySourceClient for LiveRelaySourceClient { .map(|item| item.map_err(|_| ())); let subscription_id = SubscriptionId::generate(); let remaining = - deadline.saturating_duration_since(tokio::time::Instant::now()); + deadline.saturating_duration_since(crate::host_time::Instant::now()); if remaining.is_zero() { return Ok(RelayFetchResult::Timeout(Vec::new())); } let options = SubscribeAutoCloseOptions::default() .exit_policy(ReqExitPolicy::ExitOnEOSE) .timeout(Some(remaining)); - match tokio::time::timeout_at( + match crate::host_time::timeout_at( deadline, relay .subscribe(filter) @@ -276,12 +276,12 @@ impl RelaySourceClient for LiveRelaySourceClient { async fn admit_fetch_connections( client: &nostr_sdk::client::Client, relays: &[RelayUrl], - deadline: tokio::time::Instant, + deadline: crate::host_time::Instant, ) -> Result<FetchConnections, RelayFetchResult> { let connections = FetchConnections::default(); - let admitted = tokio::time::timeout_at(deadline, async { + let admitted = crate::host_time::timeout_at(deadline, async { for relay in relays { - if tokio::time::Instant::now() >= deadline { + if crate::host_time::Instant::now() >= deadline { return Err(RelayFetchResult::Timeout(Vec::new())); } // Adding a relay is inert SDK metadata admission, not connection @@ -305,7 +305,7 @@ async fn admit_fetch_connections( ) .map_err(RelayFetchResult::Failed)?; } - if tokio::time::Instant::now() >= deadline { + if crate::host_time::Instant::now() >= deadline { Err(RelayFetchResult::Timeout(Vec::new())) } else { Ok(()) @@ -378,7 +378,7 @@ impl Drop for FetchConnections { async fn collect_until_eose( notifications: &mut (impl Stream<Item = Result<RelayNotification, ()>> + Unpin), subscription_id: &SubscriptionId, - deadline: tokio::time::Instant, + deadline: crate::host_time::Instant, budget: &FetchBudget, ) -> RelayFetchResult { let mut events = Vec::new(); @@ -386,13 +386,13 @@ async fn collect_until_eose( if budget.exhausted() { return RelayFetchResult::ResourceLimit(events); } - if tokio::time::Instant::now() >= deadline { + if crate::host_time::Instant::now() >= deadline { return RelayFetchResult::Timeout(events); } let received = tokio::select! { biased; _ = budget.wait_exhausted() => return RelayFetchResult::ResourceLimit(events), - received = tokio::time::timeout_at(deadline, notifications.next()) => received, + received = crate::host_time::timeout_at(deadline, notifications.next()) => received, }; let notification = match received { Ok(Some(Ok(notification))) => notification, @@ -427,7 +427,7 @@ async fn collect_until_eose( { return if budget.exhausted() { RelayFetchResult::ResourceLimit(events) - } else if tokio::time::Instant::now() < deadline { + } else if crate::host_time::Instant::now() < deadline { RelayFetchResult::Complete(events) } else { RelayFetchResult::Timeout(events) @@ -494,7 +494,7 @@ impl EventSource for NostrTransport { let now_ms = unix_time_ms(); let remaining_ms = request.bounds().deadline_unix_ms().saturating_sub(now_ms); let timeout_ms = remaining_ms.min(self.config().request_timeout_ms()); - let deadline = tokio::time::Instant::now() + Duration::from_millis(timeout_ms); + let deadline = crate::host_time::Instant::now() + Duration::from_millis(timeout_ms); let mut targets = BTreeMap::new(); let mut outcomes = Vec::new(); @@ -828,14 +828,6 @@ fn hex_encode(bytes: &[u8]) -> String { encoded } -#[cfg_attr(coverage_nightly, coverage(off))] -fn unix_time_ms() -> u64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|duration| u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)) - .unwrap_or_default() -} - #[cfg(test)] mod tests { use super::*; @@ -1144,7 +1136,7 @@ mod tests { collect_until_eose( &mut test_notifications(&mut receiver), &subscription_id, - tokio::time::Instant::now() + Duration::from_secs(1), + crate::host_time::Instant::now() + Duration::from_secs(1), &FetchBudget::default(), ) .await, @@ -1156,7 +1148,7 @@ mod tests { collect_until_eose( &mut test_notifications(&mut receiver), &subscription_id, - tokio::time::Instant::now(), + crate::host_time::Instant::now(), &FetchBudget::default() ) .await, @@ -1181,7 +1173,7 @@ mod tests { collect_until_eose( &mut test_notifications(&mut receiver), &subscription_id, - tokio::time::Instant::now() + Duration::from_secs(1), + crate::host_time::Instant::now() + Duration::from_secs(1), &budget ) .await, @@ -1207,7 +1199,7 @@ mod tests { collect_until_eose( &mut test_notifications(&mut receiver), &id, - tokio::time::Instant::now() + Duration::from_secs(1), + crate::host_time::Instant::now() + Duration::from_secs(1), &FetchBudget::default(), ) .await, @@ -1247,7 +1239,7 @@ mod tests { result: collect_until_eose( &mut test_notifications(&mut receiver), &id, - tokio::time::Instant::now() + Duration::from_secs(1), + crate::host_time::Instant::now() + Duration::from_secs(1), &budget, ) .await, @@ -1349,7 +1341,7 @@ mod tests { let connections = admit_fetch_connections( &client, &relays, - tokio::time::Instant::now() + Duration::from_secs(1), + crate::host_time::Instant::now() + Duration::from_secs(1), ) .await .unwrap(); @@ -1386,7 +1378,7 @@ mod tests { let relay = RelayUrl::parse("wss://one.example", RelayUrlPolicy::Public).unwrap(); for relays in [vec![relay], Vec::new()] { assert!(matches!( - admit_fetch_connections(&client, &relays, tokio::time::Instant::now()).await, + admit_fetch_connections(&client, &relays, crate::host_time::Instant::now()).await, Err(RelayFetchResult::Timeout(_)) )); assert!(client.relays().await.is_empty()); @@ -1404,7 +1396,7 @@ mod tests { admit_fetch_connections( &client, &relays, - tokio::time::Instant::now() + Duration::from_secs(1) + crate::host_time::Instant::now() + Duration::from_secs(1) ) .await, Err(RelayFetchResult::Failed(_)) @@ -1540,7 +1532,7 @@ mod tests { selector: radroots_transport::source::FetchSelector::all(), until_unix_seconds: None, connect_timeout: Duration::from_secs(1), - deadline: tokio::time::Instant::now() + deadline: crate::host_time::Instant::now() + if matches!(mode, QueuedCleanup::Deadline) { Duration::from_millis(500) } else { @@ -1549,7 +1541,7 @@ mod tests { max_connections: 1, }; let mut fetch = source.fetch(query); - let started = tokio::time::timeout(Duration::from_secs(10), async { + let started = crate::host_time::timeout(Duration::from_secs(10), async { tokio::select! { biased; result = observed => result.is_ok(), @@ -1560,11 +1552,11 @@ mod tests { let batches = if matches!(mode, QueuedCleanup::Cancel) { None } else { - Some(tokio::time::timeout(Duration::from_secs(10), &mut fetch).await) + Some(crate::host_time::timeout(Duration::from_secs(10), &mut fetch).await) }; drop(fetch); let status = queued.status(); - let closed = tokio::time::timeout(Duration::from_secs(2), closure).await; + let closed = crate::host_time::timeout(Duration::from_secs(2), closure).await; for server in [first_server, second_server] { server.abort(); let result = server.await; @@ -1761,7 +1753,7 @@ mod tests { selector, until_unix_seconds: None, connect_timeout: Duration::from_millis(1), - deadline: tokio::time::Instant::now() + Duration::from_millis(1), + deadline: crate::host_time::Instant::now() + Duration::from_millis(1), max_connections: 1, })); assert_eq!(batches.len(), 1); @@ -1784,7 +1776,7 @@ mod tests { collect_until_eose( &mut test_notifications(&mut receiver), &id, - tokio::time::Instant::now() + Duration::from_secs(10), + crate::host_time::Instant::now() + Duration::from_secs(10), &FetchBudget::default() ) .await, @@ -1810,7 +1802,7 @@ mod tests { let result = collect_until_eose( &mut test_notifications(&mut receiver), &id, - tokio::time::Instant::now() + Duration::from_secs(10), + crate::host_time::Instant::now() + Duration::from_secs(10), &FetchBudget::default(), ) .await; @@ -1887,7 +1879,7 @@ mod tests { let result = collect_until_eose( &mut test_notifications(&mut receiver), &id, - tokio::time::Instant::now() + Duration::from_secs(10), + crate::host_time::Instant::now() + Duration::from_secs(10), &shared, ) .await; diff --git a/crates/transport_nostr/src/subscription.rs b/crates/transport_nostr/src/subscription.rs @@ -1,5 +1,6 @@ //! Bounded Nostr live-subscription adapter. +use crate::host_time::unix_time_ms; use crate::{NostrTransport, RelayCursor, RelayUrl}; use futures::StreamExt; use nostr_sdk::prelude::{ @@ -18,7 +19,7 @@ use std::{ Arc, atomic::{AtomicBool, Ordering}, }, - time::{Duration, SystemTime, UNIX_EPOCH}, + time::Duration, }; const CURSOR_PREFIX: &str = "nostr-live-v1"; @@ -306,7 +307,7 @@ impl RelayEventSubscription { .session .as_mut() .ok_or(radroots_transport::Error::SubscriptionUnavailable)?; - tokio::time::timeout(remaining, session.next()).await + crate::host_time::timeout(remaining, session.next()).await }; let item = match item { Ok(Ok(item)) => item, @@ -428,7 +429,7 @@ impl RelayEventSubscription { if remaining.is_zero() { reason = SubscriptionEndReason::Deadline; } else if let Some(session) = self.session.as_mut() { - match tokio::time::timeout(remaining, session.cancel()).await { + match crate::host_time::timeout(remaining, session.cancel()).await { Ok(Ok(())) => {} Ok(Err(())) => { return Err(radroots_transport::Error::SubscriptionUnavailable); @@ -559,21 +560,19 @@ impl EventSubscriber for NostrTransport { .min(Duration::from_millis(self.config().connect_timeout_ms())), timeout: remaining, }; - let session = match tokio::time::timeout( - timeout, - self.subscription_client.subscribe(query), - ) - .await - { - Ok(Ok(session)) => session, - Ok(Err(())) | Err(_) => { - let observed_at = unix_time_ms().max(1); - for relay in &active_relays { - self.status.record_read(relay, false, true, observed_at); + let session = + match crate::host_time::timeout(timeout, self.subscription_client.subscribe(query)) + .await + { + Ok(Ok(session)) => session, + Ok(Err(())) | Err(_) => { + let observed_at = unix_time_ms().max(1); + for relay in &active_relays { + self.status.record_read(relay, false, true, observed_at); + } + return Err(radroots_transport::Error::SubscriptionUnavailable); } - return Err(radroots_transport::Error::SubscriptionUnavailable); - } - }; + }; let resume_cursors = cursors.clone(); Ok(Box::new(RelayEventSubscription { @@ -753,14 +752,6 @@ fn hex_encode(bytes: &[u8]) -> String { encoded } -#[cfg_attr(coverage_nightly, coverage(off))] -fn unix_time_ms() -> u64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|duration| u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)) - .unwrap_or_default() -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/transport_nostr/tests/browser_time/Cargo.lock b/crates/transport_nostr/tests/browser_time/Cargo.lock @@ -0,0 +1,501 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "addr2line" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "async-utility" +version = "0.3.2" +source = "git+https://github.com/yukibtc/async-utility?rev=b323ae0c1c1424b78bf8bb8832b95e86771f1dee#b323ae0c1c1424b78bf8bb8832b95e86771f1dee" +dependencies = [ + "futures-util", + "gloo-timers", + "tokio", + "wasm-bindgen-futures", +] + +[[package]] +name = "backtrace" +version = "0.3.76" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6" +dependencies = [ + "addr2line", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", + "windows-link", +] + +[[package]] +name = "bitflags" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" + +[[package]] +name = "bumpalo" +version = "3.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "futures" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-executor" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" + +[[package]] +name = "futures-macro" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "gimli" +version = "0.32.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" + +[[package]] +name = "gloo-timers" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994" +dependencies = [ + "futures-channel", + "futures-core", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "io-uring" +version = "0.7.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9080b15e63775b9a2ac7dca720f7050a8b955e092ea0f6020a4a80f69998cdc0" +dependencies = [ + "bitflags", + "cfg-if", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.91" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b49715b7073f385ba4bc528e5747d02e66cb39c6146efb66b781f131f0fb399c" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.183" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d" + +[[package]] +name = "memchr" +version = "2.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", +] + +[[package]] +name = "mio" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + +[[package]] +name = "object" +version = "0.37.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "radroots_nostr_time_browser_fixture" +version = "0.0.0" +dependencies = [ + "async-utility", + "futures", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-time", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tokio" +version = "1.47.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89e49afdadebb872d3145a5638b59eb0691ea23e46ca484037cfab3b76b95038" +dependencies = [ + "backtrace", + "io-uring", + "libc", + "mio", + "pin-project-lite", + "slab", + "tokio-macros", +] + +[[package]] +name = "tokio-macros" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6532f9a5c1ece3798cb1c2cfdba640b9b3ba884f5db45973a6f442510a87d38e" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9c5522b3a28661442748e09d40924dfb9ca614b21c00d3fd135720e48b67db8" +dependencies = [ + "cfg-if", + "futures-util", + "js-sys", + "once_cell", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18a2d50fcf105fb33bb15f00e7a77b772945a2ee45dcf454961fd843e74c18e6" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03ce4caeaac547cdf713d280eda22a730824dd11e6b8c3ca9e42247b25c631e3" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.114" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75a326b8c223ee17883a4251907455a2431acc2791c98c26279376490c378c16" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.91" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "854ba17bb104abfb26ba36da9729addc7ce7f06f5c0f90f3c391f8461cca21f9" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[patch.unused]] +name = "radroots_blossom" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_core" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_event" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_event_codec" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_geonames" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_identity" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_nostr" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_nostr_connect" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_protocol" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_secrets" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_signing" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_storage" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_storage_sqlite" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_sync" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_trade" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_transport" +version = "0.1.0-alpha" + +[[patch.unused]] +name = "radroots_transport_nostr" +version = "0.1.0-alpha" diff --git a/crates/transport_nostr/tests/browser_time/Cargo.toml b/crates/transport_nostr/tests/browser_time/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "radroots_nostr_time_browser_fixture" +version = "0.0.0" +publish = false +edition = "2024" +rust-version = "1.99.0" + +[workspace] + +[lib] +crate-type = ["cdylib"] + +[dependencies] +async-utility = { git = "https://github.com/yukibtc/async-utility", rev = "b323ae0c1c1424b78bf8bb8832b95e86771f1dee", version = "=0.3.2" } +futures = "=0.3.32" +js-sys = "=0.3.91" +wasm-bindgen = "=0.2.114" +wasm-bindgen-futures = "=0.4.64" +web-time = "=1.1.0" + +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ["cfg(coverage_nightly)"] } diff --git a/crates/transport_nostr/tests/browser_time/run.mjs b/crates/transport_nostr/tests/browser_time/run.mjs @@ -0,0 +1,78 @@ +import assert from 'node:assert/strict'; +import {createRequire} from 'node:module'; +import {createServer} from 'node:http'; +import {readFile} from 'node:fs/promises'; +import {resolve} from 'node:path'; + +const [moduleRoot, packageDir, engine = 'chromium'] = process.argv.slice(2); +assert(moduleRoot && packageDir, 'usage: node run.mjs PLAYWRIGHT_PACKAGE WASM_DIRECTORY ENGINE'); +assert(['chromium', 'firefox', 'webkit'].includes(engine)); +const playwright = createRequire(resolve(moduleRoot, 'package.json'))('playwright'); +// Observe the actual host timer request, without a tight elapsed-time assertion. +const delayedCheck = `async function delayedCheck(verify) { + const original=globalThis.setTimeout,delays=[]; + globalThis.setTimeout=function(callback,delay,...args){delays.push(delay);return original.call(globalThis,callback,delay,...args);}; + try {await verify();} finally {globalThis.setTimeout=original;} + if(delays.length>1 || delays.some(delay=>delay!==0))throw Error('delayed owner renewed timer budget: '+JSON.stringify(delays)); +}`; +const longCheck = `async function longCheck(verify) { + const original=globalThis.setTimeout,clear=globalThis.clearTimeout,delays=[],active=new Set(); + globalThis.setTimeout=function(callback,delay,...args){ + delays.push(delay);let id;id=original.call(globalThis,(...values)=>{active.delete(id);callback(...values);},delay,...args);active.add(id);return id; + }; + globalThis.clearTimeout=function(id){active.delete(id);return clear.call(globalThis,id);}; + try {await verify();} finally {globalThis.setTimeout=original;globalThis.clearTimeout=clear;} + if(delays.some(value=>value<0 || value>2147483647) || !delays.includes(2147483647))throw Error('invalid long timer delay: '+JSON.stringify(delays)); + if(active.size!==0)throw Error('long timer leaked after cancellation'); +}`; +const worker = `import init,{verify_host_time,verify_delayed_timer_owner,verify_long_timer_owner,verify_extreme_timer_owner,verify_fractional_deadlines} from './fixture.js'; +${delayedCheck} +${longCheck} +self.onmessage=async()=>{try{await init();await delayedCheck(verify_delayed_timer_owner);await longCheck(verify_long_timer_owner);await longCheck(verify_extreme_timer_owner);await verify_fractional_deadlines();self.postMessage({passed:['delayed timer owner','long timer cancellation','extreme timer cancellation','fractional deadline',...Array.from(await verify_host_time())]});} +catch(error){self.postMessage({error:String(error)});}};`; +const server = createServer(async (req, res) => { + try { + if (req.url === '/') {res.setHeader('content-type', 'text/html');res.end('<!doctype html><title>Host time fixture</title>');return;} + if (req.url === '/worker.js') {res.setHeader('content-type', 'text/javascript');res.end(worker);return;} + const name = new Map([['/fixture.js', 'fixture.js'], ['/fixture_bg.wasm', 'fixture_bg.wasm']]).get(req.url); + if (!name) {res.statusCode = 404;res.end();return;} + res.setHeader('content-type', name.endsWith('.wasm') ? 'application/wasm' : 'text/javascript'); + res.end(await readFile(resolve(packageDir, name))); + } catch {res.statusCode = 500;res.end();} +}); +await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); +let browser; +const deadline = setTimeout(() => {void browser?.close();}, 60000); +deadline.unref(); +try { + browser = await playwright[engine].launch({headless: true}); + const page = await browser.newPage(); + const errors = []; + page.on('pageerror', error => errors.push(error.message)); + await page.goto(`http://127.0.0.1:${server.address().port}/`); + await page.addScriptTag({content: delayedCheck}); + await page.addScriptTag({content: longCheck}); + const main = await page.evaluate(async () => { + const {default: init, verify_host_time, verify_delayed_timer_owner,verify_long_timer_owner,verify_extreme_timer_owner,verify_fractional_deadlines} = await import('./fixture.js'); + await init();await delayedCheck(verify_delayed_timer_owner); + await longCheck(verify_long_timer_owner);await longCheck(verify_extreme_timer_owner); + await verify_fractional_deadlines(); + return ['delayed timer owner','long timer cancellation','extreme timer cancellation','fractional deadline',...Array.from(await verify_host_time())]; + }); + const dedicated = await page.evaluate(() => new Promise((resolve, reject) => { + const worker = new Worker('./worker.js', {type: 'module'}); + worker.onerror = event => {worker.terminate();reject(Error(event.message));}; + worker.onmessage = event => { + worker.terminate();event.data.error ? reject(Error(event.data.error)) : resolve(event.data.passed); + }; + worker.postMessage('run'); + })); + assert.equal(main.length, 12); + assert.deepEqual(dedicated, main); + assert.deepEqual(errors, []); + console.log(JSON.stringify({engine, version: browser.version(), main, dedicated, pageErrors: errors})); +} finally { + clearTimeout(deadline); + await browser?.close(); + await new Promise(resolve => server.close(resolve)); +} diff --git a/crates/transport_nostr/tests/browser_time/src/lib.rs b/crates/transport_nostr/tests/browser_time/src/lib.rs @@ -0,0 +1,184 @@ +#![forbid(unsafe_code)] + +// Execute the production module, without substituting a native runtime or +// claiming that this isolated host check qualifies the full Nostr transport. +#[path = "../../../src/host_time.rs"] +mod host_time; + +use core::{cell::Cell, future::pending, time::Duration}; +use futures::FutureExt; +use std::rc::Rc; +use wasm_bindgen::prelude::*; + +struct OnDrop(Rc<Cell<bool>>); + +impl Drop for OnDrop { + fn drop(&mut self) { + self.0.set(true); + } +} + +fn require(value: bool, name: &str) -> Result<(), JsValue> { + if value { + Ok(()) + } else { + Err(JsValue::from_str(name)) + } +} + +#[wasm_bindgen] +pub async fn verify_delayed_timer_owner() -> Result<(), JsValue> { + use host_time::{Instant, timeout_at}; + let deadline = Instant::now() + Duration::from_millis(5); + require( + timeout_at(deadline, async { + // Deliberately occupy this poll until the original deadline is past. + // The separate timer owner must schedule zero remaining time, rather + // than granting another relative budget when it eventually runs. + while Instant::now() < deadline + Duration::from_millis(15) {} + pending::<()>().await; + }) + .await + .is_err(), + "delayed timer owner expiry", + ) +} + +#[wasm_bindgen] +pub async fn verify_long_timer_owner() -> Result<(), JsValue> { + long_timer(u64::from(i32::MAX as u32) + 100).await +} + +#[wasm_bindgen] +pub async fn verify_extreme_timer_owner() -> Result<(), JsValue> { + long_timer(u64::MAX).await +} + +async fn long_timer(millis: u64) -> Result<(), JsValue> { + let dropped = Rc::new(Cell::new(false)); + let guard = OnDrop(Rc::clone(&dropped)); + let mut operation = Box::pin(host_time::timeout( + Duration::from_millis(millis), + async move { + let _guard = guard; + pending::<()>().await; + }, + )); + require( + operation.as_mut().now_or_never().is_none(), + "long timer starts pending", + )?; + async_utility::time::sleep(Duration::ZERO).await; + require( + operation.as_mut().now_or_never().is_none(), + "long timer cannot expire immediately", + )?; + drop(operation); + require(dropped.get(), "long observer cancellation drops work")?; + async_utility::time::sleep(Duration::ZERO).await; + Ok(()) +} + +#[wasm_bindgen] +pub async fn verify_fractional_deadlines() -> Result<(), JsValue> { + for _ in 0..8 { + let deadline = host_time::Instant::now() + Duration::from_micros(1_500); + require( + host_time::timeout_at(deadline, pending::<()>()) + .await + .is_err(), + "fractional expiry", + )?; + require( + host_time::Instant::now() >= deadline, + "timer cannot expire early", + )?; + } + Ok(()) +} + +#[wasm_bindgen] +pub async fn verify_host_time() -> Result<js_sys::Array, JsValue> { + use host_time::{Instant, timeout, timeout_at, unix_time_ms}; + let passed = js_sys::Array::new(); + let start = Instant::now(); + let now = unix_time_ms(); + require( + now.abs_diff(js_sys::Date::now() as u64) < 1_000, + "browser wall clock", + )?; + passed.push(&"browser wall clock".into()); + + let local = Rc::new(Cell::new(7)); + let expired = Instant::now(); + require( + timeout_at(expired, async { local.get() }).await.ok() == Some(7), + "expired ready local future", + )?; + passed.push(&"expired ready local future".into()); + require( + timeout_at(expired, pending::<()>()).await.is_err(), + "expired pending future", + )?; + passed.push(&"expired pending future".into()); + + let dropped = Rc::new(Cell::new(false)); + let guard = OnDrop(Rc::clone(&dropped)); + require( + timeout(Duration::from_millis(10), async move { + let _guard = guard; + pending::<()>().await; + }) + .await + .is_err() + && dropped.get(), + "expiry drops local work", + )?; + passed.push(&"expiry drops local work".into()); + + let deadline = Instant::now() + Duration::from_millis(10); + async_utility::time::sleep(Duration::from_millis(20)).await; + // A ready custom future checks its original absolute deadline during its + // first poll. This does not rely on tight wall-time scheduling thresholds. + require( + timeout_at(deadline, async { Instant::now() >= deadline }) + .await + .ok() + == Some(true), + "one absolute deadline", + )?; + require( + timeout_at(deadline, pending::<()>()).await.is_err(), + "elapsed queued work", + )?; + passed.push(&"one absolute deadline".into()); + + for _ in 0..16 { + let dropped = Rc::new(Cell::new(false)); + let guard = OnDrop(Rc::clone(&dropped)); + require( + timeout(Duration::from_secs(1), async move { + let _guard = guard; + pending::<()>().await; + }) + .now_or_never() + .is_none() + && dropped.get(), + "observer cancellation drops work", + )?; + // Give the separate timer owner an executor turn to dispose its timer. + async_utility::time::sleep(Duration::ZERO).await; + } + passed.push(&"repeated observer cancellation".into()); + require( + timeout(Duration::from_secs(1), async { 9 }).await.ok() == Some(9), + "ready after timer cancellation", + )?; + passed.push(&"ready after timer cancellation".into()); + require( + Instant::now() >= start && unix_time_ms() >= now, + "host clocks advance", + )?; + passed.push(&"host clocks advance".into()); + Ok(passed) +} diff --git a/crates/transport_nostr/tests/package_boundary.rs b/crates/transport_nostr/tests/package_boundary.rs @@ -45,6 +45,7 @@ fn manifest_and_root_match_the_governed_transport_boundary() { "cursor", "error", "exact_delivery", + "host_time", "profile", "relay", "sink", @@ -322,6 +323,8 @@ fn adapter_owns_no_storage_outbox_or_orchestration_surface() { "cursor.rs".to_owned(), "error.rs".to_owned(), "exact_delivery.rs".to_owned(), + "host_time.rs".to_owned(), + "host_time_browser.rs".to_owned(), "lib.rs".to_owned(), "native_backend_tests.rs".to_owned(), "profile.rs".to_owned(),