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    #[cfg(wasm_browser)]
73    fn new_timer(&self, deadline: n0_future::time::Instant) -> Pin<Box<dyn noq::AsyncTimer>> {
74        Box::pin(web::Timer(n0_future::time::sleep_until(deadline)))
75    }
76
77    #[cfg(not(wasm_browser))]
78    fn spawn(&self, future: Pin<Box<dyn Future<Output = ()> + Send>>) {
79        // Do not allow spawning more tasks if the runtime should be closed.
80        if self.tasks.is_closed() {
81            tracing::debug!(me = %self.id.fmt_short(), "runtime closed, dropping spawned task");
82            return;
83        }
84
85        use tracing::{Instrument, trace_span};
86
87        let task_id = self.task_counter.fetch_add(1, Ordering::Relaxed);
88        let cancel = self.cancel.clone();
89        let span = trace_span!("runtime", me = %self.id.fmt_short(), task_id);
90        self.tasks.spawn(async move {
91            // wrapping the future in a cancellation token is what allows
92            // us to "abort" tasks in the event the runtime is meant to
93            // close quickly and ungracefully
94            cancel.run_until_cancelled(future.instrument(span)).await;
95        });
96    }
97
98    #[cfg(wasm_browser)]
99    fn spawn(&self, future: Pin<Box<dyn Future<Output = ()> + Send>>) {
100        wasm_bindgen_futures::spawn_local(future);
101    }
102
103    // We're not actually using this function in iroh
104    #[cfg(not(wasm_browser))]
105    fn wrap_udp_socket(
106        &self,
107        t: std::net::UdpSocket,
108    ) -> std::io::Result<Box<dyn noq::AsyncUdpSocket>> {
109        noq::TokioRuntime.wrap_udp_socket(t)
110    }
111}
112
113#[cfg(wasm_browser)]
114mod web {
115    use std::{
116        future::Future,
117        pin::Pin,
118        task::{Context, Poll},
119    };
120
121    use n0_future::time;
122
123    #[derive(Debug)]
124    pub(crate) struct Timer(pub(crate) time::Sleep);
125
126    impl noq::AsyncTimer for Timer {
127        fn reset(mut self: Pin<&mut Self>, deadline: time::Instant) {
128            Pin::new(&mut self.0).reset(deadline)
129        }
130
131        fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
132            Pin::new(&mut self.0).poll(cx)
133        }
134    }
135}