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