iroh/
runtime.rs

1use std::pin::Pin;
2
3use iroh_base::EndpointId;
4use portable_atomic::{AtomicU64, Ordering};
5use tokio_util::sync::CancellationToken;
6#[cfg(not(wasm_browser))]
7use tokio_util::task::TaskTracker;
8
9#[derive(Debug)]
10pub(crate) struct Runtime {
11    id: EndpointId,
12    #[cfg(not(wasm_browser))]
13    tasks: TaskTracker,
14    #[cfg(not(wasm_browser))]
15    cancel: CancellationToken,
16    #[cfg(not(wasm_browser))]
17    task_counter: AtomicU64,
18}
19
20impl Runtime {
21    /// Create a new [`Runtime`] that manages shutting down tasks properly,
22    /// whether gracefully or un-gracefully.
23    pub(crate) fn new(id: EndpointId) -> Self {
24        Self {
25            id,
26            #[cfg(not(wasm_browser))]
27            tasks: TaskTracker::new(),
28            #[cfg(not(wasm_browser))]
29            cancel: CancellationToken::new(),
30            #[cfg(not(wasm_browser))]
31            task_counter: AtomicU64::new(0),
32        }
33    }
34
35    /// Shutdown the runtime gracefully.
36    ///
37    /// Closes the task tracker and waits for all spawned tasks to finish naturally.
38    #[cfg(not(wasm_browser))]
39    pub(crate) async fn shutdown(&self) {
40        self.abort();
41        // Waits for all tasks to stop (and thus drop all of their futures).
42        // If the task tracker had already been closed and tasks have all been cleaned up,
43        // this returns immediately.
44        self.tasks.wait().await;
45    }
46
47    /// Shutdown the runtime ASAP, not waiting for any graceful closing of tasks.
48    #[cfg(not(wasm_browser))]
49    pub(crate) fn abort(&self) {
50        // Signal all spawned tasks to stop immediately.
51        self.cancel.cancel();
52        // Signal that the runtime should be closed.
53        self.tasks.close();
54        // Does not wait for the tasks to return.
55    }
56
57    /// No-op on wasm. There is no task tracker to close or wait on.
58    #[cfg(wasm_browser)]
59    pub(crate) async fn shutdown(&self) {}
60
61    /// No-op on wasm. There is no task tracker or cancellation to perform.
62    #[cfg(wasm_browser)]
63    pub(crate) fn abort(&self) {}
64}
65
66impl noq::Runtime for Runtime {
67    #[cfg(not(wasm_browser))]
68    fn new_timer(&self, i: std::time::Instant) -> Pin<Box<dyn noq::AsyncTimer>> {
69        noq::TokioRuntime.new_timer(i)
70    }
71
72    /// Tokio's clock.
73    ///
74    /// Like the timers: noq's default reads the system clock, which does not follow
75    /// tokio's paused test clock.
76    #[cfg(not(wasm_browser))]
77    fn now(&self) -> std::time::Instant {
78        noq::TokioRuntime.now()
79    }
80
81    #[cfg(wasm_browser)]
82    fn new_timer(&self, deadline: n0_future::time::Instant) -> Pin<Box<dyn noq::AsyncTimer>> {
83        Box::pin(web::Timer(n0_future::time::sleep_until(deadline)))
84    }
85
86    #[cfg(not(wasm_browser))]
87    fn spawn(&self, future: Pin<Box<dyn Future<Output = ()> + Send>>) {
88        // Do not allow spawning more tasks if the runtime should be closed.
89        if self.tasks.is_closed() {
90            tracing::debug!(me = %self.id.fmt_short(), "runtime closed, dropping spawned task");
91            return;
92        }
93
94        use tracing::{Instrument, trace_span};
95
96        let task_id = self.task_counter.fetch_add(1, Ordering::Relaxed);
97        let cancel = self.cancel.clone();
98        let span = trace_span!("runtime", me = %self.id.fmt_short(), task_id);
99        self.tasks.spawn(async move {
100            // wrapping the future in a cancellation token is what allows
101            // us to "abort" tasks in the event the runtime is meant to
102            // close quickly and ungracefully
103            cancel.run_until_cancelled(future.instrument(span)).await;
104        });
105    }
106
107    #[cfg(wasm_browser)]
108    fn spawn(&self, future: Pin<Box<dyn Future<Output = ()> + Send>>) {
109        wasm_bindgen_futures::spawn_local(future);
110    }
111
112    // We're not actually using this function in iroh
113    #[cfg(not(wasm_browser))]
114    fn wrap_udp_socket(
115        &self,
116        t: std::net::UdpSocket,
117    ) -> std::io::Result<Box<dyn noq::AsyncUdpSocket>> {
118        noq::TokioRuntime.wrap_udp_socket(t)
119    }
120}
121
122#[cfg(wasm_browser)]
123mod web {
124    use std::{
125        future::Future,
126        pin::Pin,
127        task::{Context, Poll},
128    };
129
130    use n0_future::time;
131
132    #[derive(Debug)]
133    pub(crate) struct Timer(pub(crate) time::Sleep);
134
135    impl noq::AsyncTimer for Timer {
136        fn reset(mut self: Pin<&mut Self>, deadline: time::Instant) {
137            Pin::new(&mut self.0).reset(deadline)
138        }
139
140        fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
141            Pin::new(&mut self.0).poll(cx)
142        }
143    }
144}
145
146#[cfg(all(test, not(wasm_browser)))]
147mod tests {
148    use std::time::Duration;
149
150    use iroh_base::SecretKey;
151    use noq::Runtime as _;
152
153    use super::Runtime;
154
155    #[tokio::test(start_paused = true)]
156    async fn now_follows_tokio_clock() {
157        let rt = Runtime::new(SecretKey::from_bytes(&[7u8; 32]).public());
158        let before = rt.now();
159        tokio::time::advance(Duration::from_secs(60)).await;
160        assert_eq!(rt.now() - before, Duration::from_secs(60));
161    }
162}