ant_quic/high_level/runtime.rs
1// Copyright 2024 Saorsa Labs Ltd.
2//
3// This Saorsa Network Software is licensed under the General Public License (GPL), version 3.
4// Please see the file LICENSE-GPL, or visit <http://www.gnu.org/licenses/> for the full text.
5//
6// Full details available at https://saorsalabs.com/licenses
7
8use std::{
9 fmt::Debug,
10 future::Future,
11 io::{self, IoSliceMut},
12 net::SocketAddr,
13 pin::Pin,
14 sync::Arc,
15 task::{Context, Poll},
16};
17
18use quinn_udp::{RecvMeta, Transmit};
19use tracing::error;
20
21use crate::Instant;
22
23/// Abstracts I/O and timer operations for runtime independence
24pub trait Runtime: Send + Sync + Debug + 'static {
25 /// Construct a timer that will expire at `i`
26 fn new_timer(&self, i: Instant) -> Pin<Box<dyn AsyncTimer>>;
27 /// Drive `future` to completion in the background
28 fn spawn(&self, future: Pin<Box<dyn Future<Output = ()> + Send>>);
29 /// Convert `t` into the socket type used by this runtime
30 #[cfg(not(wasm_browser))]
31 fn wrap_udp_socket(&self, t: std::net::UdpSocket) -> io::Result<Arc<dyn AsyncUdpSocket>>;
32 /// Look up the current time
33 ///
34 /// Allows simulating the flow of time for testing.
35 fn now(&self) -> Instant {
36 Instant::now()
37 }
38}
39
40/// Abstract implementation of an async timer for runtime independence
41pub trait AsyncTimer: Send + Debug + 'static {
42 /// Update the timer to expire at `i`
43 fn reset(self: Pin<&mut Self>, i: Instant);
44 /// Check whether the timer has expired, and register to be woken if not
45 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<()>;
46}
47
48/// Abstract implementation of a UDP socket for runtime independence
49pub trait AsyncUdpSocket: Send + Sync + Debug + 'static {
50 /// Create a [`UdpSender`] with independent write-readiness notifications.
51 ///
52 /// A `poll_send` method on a single object can usually store only one
53 /// [`Waker`] at a time. This method allows any number of interested tasks
54 /// to construct their own [`UdpSender`] object, each with a separate
55 /// readiness registration.
56 ///
57 /// [`Waker`]: std::task::Waker
58 fn create_sender(&self) -> Pin<Box<dyn UdpSender>>;
59
60 /// Receive UDP datagrams, or register to be woken if receiving may succeed in the future
61 fn poll_recv(
62 &self,
63 cx: &mut Context,
64 bufs: &mut [IoSliceMut<'_>],
65 meta: &mut [RecvMeta],
66 ) -> Poll<io::Result<usize>>;
67
68 /// Look up the local IP address and port used by this socket
69 fn local_addr(&self) -> io::Result<SocketAddr>;
70
71 /// Maximum number of datagrams that might be described by a single [`RecvMeta`]
72 fn max_receive_segments(&self) -> usize {
73 1
74 }
75
76 /// Whether datagrams might get fragmented into multiple parts
77 ///
78 /// Sockets should prevent this for best performance. See e.g. the `IPV6_DONTFRAG` socket
79 /// option.
80 fn may_fragment(&self) -> bool {
81 true
82 }
83}
84
85/// An object for asynchronously writing to an associated [`AsyncUdpSocket`].
86///
87/// Any number of `UdpSender`s may exist for a single socket. Each sender is
88/// responsible for notifying at most one task for send readiness.
89pub trait UdpSender: Send + Sync + Debug + 'static {
90 /// Send a UDP datagram, or register to be woken if sending may succeed in
91 /// the future.
92 ///
93 /// A single `UdpSender` is reused even after returning `Ready`, unlike a
94 /// `Future`, so implementations must tolerate repeated calls.
95 fn poll_send(
96 self: Pin<&mut Self>,
97 transmit: &Transmit,
98 cx: &mut Context<'_>,
99 ) -> Poll<io::Result<()>>;
100
101 /// Maximum number of datagrams that a [`Transmit`] may encode.
102 fn max_transmit_segments(&self) -> usize {
103 1
104 }
105}
106
107/// An object polled to detect when an associated [`AsyncUdpSocket`] is writable
108///
109/// Any number of `UdpPoller`s may exist for a single [`AsyncUdpSocket`]. Each `UdpPoller` is
110/// responsible for notifying at most one task when that socket becomes writable.
111pub(crate) trait UdpPoller: Send + Sync + Debug + 'static {
112 /// Check whether the associated socket is likely to be writable
113 ///
114 /// Must be called after [`AsyncUdpSocket::try_send`] returns [`io::ErrorKind::WouldBlock`] to
115 /// register the task associated with `cx` to be woken when a send should be attempted
116 /// again. Unlike in [`Future::poll`], a [`UdpPoller`] may be reused indefinitely no matter how
117 /// many times `poll_writable` returns [`Poll::Ready`].
118 fn poll_writable(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>>;
119}
120
121pin_project_lite::pin_project! {
122 /// Helper adapting a function `MakeFut` that constructs a single-use future `Fut` into a
123 /// [`UdpPoller`] that may be reused indefinitely
124 struct UdpPollHelper<MakeFut, Fut> {
125 make_fut: MakeFut,
126 #[pin]
127 fut: Option<Fut>,
128 }
129}
130
131impl<MakeFut, Fut> UdpPollHelper<MakeFut, Fut> {
132 /// Construct a [`UdpPoller`] that calls `make_fut` to get the future to poll, storing it until
133 /// it yields [`Poll::Ready`], then creating a new one on the next
134 /// [`poll_writable`](UdpPoller::poll_writable)
135 fn new(make_fut: MakeFut) -> Self {
136 Self {
137 make_fut,
138 fut: None,
139 }
140 }
141}
142
143impl<MakeFut, Fut> UdpPoller for UdpPollHelper<MakeFut, Fut>
144where
145 MakeFut: Fn() -> Fut + Send + Sync + 'static,
146 Fut: Future<Output = io::Result<()>> + Send + Sync + 'static,
147{
148 fn poll_writable(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
149 let mut this = self.project();
150 if this.fut.is_none() {
151 this.fut.set(Some((this.make_fut)()));
152 }
153 // We're forced to use expect here because `Fut` may be `!Unpin`, which means we can't safely
154 // obtain an `&mut Fut` after storing it in `self.fut` when `self` is already behind `Pin`,
155 // and if we didn't store it then we wouldn't be able to keep it alive between
156 // `poll_writable` calls.
157 let result = match this.fut.as_mut().as_pin_mut() {
158 Some(fut) => fut.poll(cx),
159 None => {
160 error!("Future not set when UdpPollHelper is polled");
161 Poll::Ready(Err(std::io::Error::other("Future not set")))
162 }
163 };
164 if result.is_ready() {
165 // Polling an arbitrary `Future` after it becomes ready is a logic error, so arrange for
166 // a new `Future` to be created on the next call.
167 this.fut.set(None);
168 }
169 result
170 }
171}
172
173impl<MakeFut, Fut> Debug for UdpPollHelper<MakeFut, Fut> {
174 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
175 f.debug_struct("UdpPollHelper").finish_non_exhaustive()
176 }
177}
178
179/// Automatically select an appropriate runtime from those enabled at compile time
180///
181/// This function is called from within a Tokio runtime context (tokio is always available),
182/// then `TokioRuntime` is returned. If `runtime-smol` is enabled and not in tokio context,
183/// `SmolRuntime` is returned. Otherwise, `None` is returned.
184/// Returns the default runtime (Tokio) if available.
185pub fn default_runtime() -> Option<Arc<dyn Runtime>> {
186 // Tokio is always available (required dependency)
187 if ::tokio::runtime::Handle::try_current().is_ok() {
188 return Some(Arc::new(TokioRuntime));
189 }
190 None
191}
192
193// Tokio runtime (always available)
194mod tokio;
195pub use self::tokio::TokioRuntime;
196
197// Dual-stack socket (separate IPv4 + IPv6 sockets behind single AsyncUdpSocket)
198pub mod dual_stack;