Skip to main content

cratefield_runtime_cloudflare/ports/
clock.rs

1//! `Clock` with a real timeout on Workers: races the future against
2//! `worker::Delay` (setTimeout).
3
4use async_trait::async_trait;
5use futures_core::future::BoxFuture;
6use futures_util::future::{Either, select};
7use std::any::Any;
8use std::time::Duration;
9
10pub struct WorkersClock;
11
12#[async_trait]
13impl cratefield_core::Clock for WorkersClock {
14    fn now(&self) -> time::OffsetDateTime {
15        time::OffsetDateTime::now_utc()
16    }
17
18    async fn timeout_any(
19        &self,
20        fut: BoxFuture<'static, Box<dyn Any + Send>>,
21        after: Duration,
22    ) -> Option<Box<dyn Any + Send>> {
23        // worker::Delay holds Rc (single-threaded isolate); SendFuture is
24        // the workers-rs-sanctioned Send wrapper (ADR 0002).
25        let delay = worker::send::SendFuture::new(worker::Delay::from(after));
26        match select(fut, Box::pin(delay)).await {
27            Either::Left((output, _)) => Some(output),
28            Either::Right(((), _)) => None,
29        }
30    }
31}