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(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 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 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 #[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}