Skip to main content

vibeio_quinn/
lib.rs

1//! A compatibility layer for using [`quinn`] with the `vibeio` async runtime.
2//!
3//! This crate provides the necessary runtime adapters to run QUIC-based
4//! applications built on `quinn` on top of `vibeio`. It implements the
5//! traits required by `quinn`'s runtime abstraction:
6//!
7//! - [`VibeioRuntime`]: A runtime that implements [`quinn::Runtime`] using
8//!   `vibeio`'s task spawning, timer, and I/O primitives.
9//!
10//! # Overview
11//!
12//! [`VibeioRuntime`] satisfies all three abstract interfaces that `quinn`
13//! requires from a runtime:
14//!
15//! | `quinn` trait | Implementation |
16//! |---|---|
17//! | [`quinn::Runtime`] | [`VibeioRuntime`] struct |
18//! | [`quinn::AsyncTimer`] | Internal wrapper around `vibeio::time::Sleep` |
19//! | [`quinn::AsyncUdpSocket`] | Internal wrapper combining `PollUdpSocket` + `quinn-udp` batching |
20//! | [`quinn::UdpPoller`] | Internal type backed by `AsyncWritePoll` readiness |
21//!
22//! # Usage
23//!
24//! ```rust,ignore
25//! use quinn::{Endpoint, EndpointConfig, ServerConfig};
26//! use std::sync::Arc;
27//! use vibeio_quinn::VibeioRuntime;
28//!
29//! let runtime = Arc::new(VibeioRuntime);
30//!
31//! let mut endpoint = Endpoint::new(
32//!     EndpointConfig::default(),
33//!     None,
34//!     runtime,
35//! )?;
36//! ```
37//!
38//! # Architecture notes
39//!
40//! `vibeio` is a **single-threaded** runtime. All spawned futures and I/O
41//! operations execute on the thread that owns the runtime. The internal I/O
42//! handle types use `Rc<AnyDriver>` internally and are therefore `!Send` and
43//! `!Sync`. To satisfy `quinn`'s `Send + Sync + 'static` bounds on its
44//! runtime traits, the adapters in this crate use `unsafe impl Send + Sync`
45//! under the justification that the runtime's single-threaded architecture
46//! prevents data races.
47//!
48//! Each `quinn` [`Endpoint`](quinn::Endpoint) should be driven from a single
49//! `vibeio` task (e.g. via `endpoint.run_until_stopped()` or manual polling).
50//! The UDP socket, timer, and task spawn implementations all assume they are
51//! used from the thread associated with the current `vibeio` runtime context.
52
53use std::{
54    fmt,
55    future::Future,
56    io,
57    net::SocketAddr,
58    pin::Pin,
59    sync::Arc,
60    task::{ready, Context, Poll},
61    time::Instant,
62};
63
64use quinn::udp::{self, RecvMeta, Transmit};
65use quinn::{AsyncTimer, AsyncUdpSocket, Runtime, UdpPoller};
66use vibeio::io::{AsyncReadPoll, AsyncWritePoll};
67use vibeio::net::PollUdpSocket;
68
69/// A [`quinn::Runtime`] implementation for the `vibeio` async runtime.
70///
71/// This type implements all the traits required by Quinn to operate on top of
72/// the `vibeio` runtime: task spawning, timers, and UDP socket I/O.
73///
74/// `vibeio` is a single-threaded runtime. [`VibeioRuntime`] is safe to
75/// construct and use from any thread, but all spawned tasks and I/O operations
76/// run on the thread associated with the current `vibeio` runtime instance.
77#[derive(Debug, Clone, Copy)]
78pub struct VibeioRuntime;
79
80impl Runtime for VibeioRuntime {
81    #[inline]
82    fn new_timer(&self, i: Instant) -> Pin<Box<dyn AsyncTimer>> {
83        Box::pin(VibeioTimer {
84            inner: Box::pin(vibeio::time::sleep_until(i)),
85        })
86    }
87
88    #[inline]
89    fn spawn(&self, future: Pin<Box<dyn Future<Output = ()> + Send>>) {
90        let future: Pin<Box<dyn Future<Output = ()>>> = unsafe { std::mem::transmute(future) };
91        vibeio::spawn(future);
92    }
93
94    #[inline]
95    fn wrap_udp_socket(&self, sock: std::net::UdpSocket) -> io::Result<Arc<dyn AsyncUdpSocket>> {
96        let io = sock.try_clone()?;
97        io.set_nonblocking(true)?;
98        let socket = PollUdpSocket::from_std(sock)?;
99        let state = udp::UdpSocketState::new((&io).into())?;
100        Ok(Arc::new(VibeioUdpSocket {
101            io: socket,
102            state,
103            socket: io,
104        }))
105    }
106
107    #[inline]
108    fn now(&self) -> Instant {
109        Instant::now()
110    }
111}
112
113struct VibeioTimer {
114    inner: Pin<Box<vibeio::time::Sleep>>,
115}
116
117impl fmt::Debug for VibeioTimer {
118    #[inline]
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        f.debug_struct("VibeioTimer").finish_non_exhaustive()
121    }
122}
123
124unsafe impl Send for VibeioTimer {}
125unsafe impl Sync for VibeioTimer {}
126
127impl AsyncTimer for VibeioTimer {
128    #[inline]
129    fn reset(self: Pin<&mut Self>, i: Instant) {
130        self.get_mut().inner.as_mut().get_mut().reset(i);
131    }
132
133    #[inline]
134    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> {
135        self.get_mut().inner.as_mut().poll(cx)
136    }
137}
138
139struct VibeioUdpSocket {
140    io: PollUdpSocket,
141    state: udp::UdpSocketState,
142    socket: std::net::UdpSocket,
143}
144
145impl fmt::Debug for VibeioUdpSocket {
146    #[inline]
147    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148        f.debug_struct("VibeioUdpSocket")
149            .field("local_addr", &self.local_addr())
150            .finish_non_exhaustive()
151    }
152}
153
154unsafe impl Send for VibeioUdpSocket {}
155unsafe impl Sync for VibeioUdpSocket {}
156
157impl AsyncUdpSocket for VibeioUdpSocket {
158    #[inline]
159    fn create_io_poller(self: Arc<Self>) -> Pin<Box<dyn UdpPoller>> {
160        Box::pin(VibeioUdpPoller { socket: self })
161    }
162
163    #[inline]
164    fn try_send(&self, transmit: &Transmit) -> io::Result<()> {
165        self.io
166            .try_io_writable(|| self.state.send((&self.socket).into(), transmit))
167    }
168
169    #[inline]
170    fn poll_recv(
171        &self,
172        cx: &mut Context,
173        bufs: &mut [io::IoSliceMut<'_>],
174        meta: &mut [RecvMeta],
175    ) -> Poll<io::Result<usize>> {
176        loop {
177            ready!(self.io.poll_readable(cx)?);
178            match self
179                .io
180                .try_io_readable(|| self.state.recv((&self.socket).into(), bufs, meta))
181            {
182                Ok(n) => return Poll::Ready(Ok(n)),
183                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue,
184                Err(e) => return Poll::Ready(Err(e)),
185            }
186        }
187    }
188
189    #[inline]
190    fn local_addr(&self) -> io::Result<SocketAddr> {
191        self.io.local_addr()
192    }
193
194    #[inline]
195    fn max_transmit_segments(&self) -> usize {
196        self.state.max_gso_segments()
197    }
198
199    #[inline]
200    fn max_receive_segments(&self) -> usize {
201        self.state.gro_segments()
202    }
203
204    #[inline]
205    fn may_fragment(&self) -> bool {
206        self.state.may_fragment()
207    }
208}
209
210struct VibeioUdpPoller {
211    socket: Arc<VibeioUdpSocket>,
212}
213
214impl fmt::Debug for VibeioUdpPoller {
215    #[inline]
216    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217        f.debug_struct("VibeioUdpPoller").finish_non_exhaustive()
218    }
219}
220
221unsafe impl Send for VibeioUdpPoller {}
222unsafe impl Sync for VibeioUdpPoller {}
223
224impl UdpPoller for VibeioUdpPoller {
225    #[inline]
226    fn poll_writable(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
227        self.socket.io.poll_writable(cx)
228    }
229}