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 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 #[cfg(not(wasm_browser))]
39 pub(crate) async fn shutdown(&self) {
40 self.abort();
41 self.tasks.wait().await;
45 }
46
47 #[cfg(not(wasm_browser))]
49 pub(crate) fn abort(&self) {
50 self.cancel.cancel();
52 self.tasks.close();
54 }
56
57 #[cfg(wasm_browser)]
59 pub(crate) async fn shutdown(&self) {}
60
61 #[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(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 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 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 #[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}