Skip to main content

zincio_quinn/
lib.rs

1//! A compatibility layer for using [`quinn`] with the `zincio` async runtime.
2//!
3//! This crate provides the necessary runtime adapters to run QUIC-based
4//! applications built on `quinn` on top of `zincio`. It implements the
5//! traits required by `quinn`'s runtime abstraction:
6//!
7//! - [`ZincioRuntime`]: A runtime that implements [`quinn::Runtime`] using
8//!   `zincio`'s task spawning, timer, and I/O primitives.
9//!
10//! # Overview
11//!
12//! [`ZincioRuntime`] satisfies all three abstract interfaces that `quinn`
13//! requires from a runtime:
14//!
15//! | `quinn` trait | Implementation |
16//! |---|---|
17//! | [`quinn::Runtime`] | [`ZincioRuntime`] struct |
18//! | [`quinn::AsyncTimer`] | Internal wrapper around `zincio::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 zincio_quinn::ZincioRuntime;
28//!
29//! let runtime = Arc::new(ZincioRuntime);
30//!
31//! let mut endpoint = Endpoint::new(
32//!     EndpointConfig::default(),
33//!     None,
34//!     runtime,
35//! )?;
36//! ```
37//!
38//! # Architecture notes
39//!
40//! `zincio` 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//! `zincio` 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 `zincio` 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 zincio::io::{AsyncReadPoll, AsyncWritePoll};
67use zincio::net::PollUdpSocket;
68
69/// A [`quinn::Runtime`] implementation for the `zincio` async runtime.
70///
71/// This type implements all the traits required by Quinn to operate on top of
72/// the `zincio` runtime: task spawning, timers, and UDP socket I/O.
73///
74/// `zincio` is a single-threaded runtime. [`ZincioRuntime`] 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 `zincio` runtime instance.
77#[derive(Debug, Clone, Copy)]
78pub struct ZincioRuntime;
79
80impl Runtime for ZincioRuntime {
81    #[inline]
82    fn new_timer(&self, i: Instant) -> Pin<Box<dyn AsyncTimer>> {
83        Box::pin(ZincioTimer {
84            inner: Box::pin(zincio::time::sleep_until(i)),
85        })
86    }
87
88    #[inline]
89    fn spawn(&self, future: Pin<Box<dyn Future<Output = ()> + Send>>) {
90        zincio::spawn_detached(future);
91    }
92
93    #[inline]
94    fn wrap_udp_socket(&self, sock: std::net::UdpSocket) -> io::Result<Arc<dyn AsyncUdpSocket>> {
95        let io = sock.try_clone()?;
96        io.set_nonblocking(true)?;
97        let socket = PollUdpSocket::from_std(sock)?;
98        let state = udp::UdpSocketState::new((&io).into())?;
99        Ok(Arc::new(ZincioUdpSocket {
100            io: socket,
101            state,
102            socket: io,
103        }))
104    }
105
106    #[inline]
107    fn now(&self) -> Instant {
108        Instant::now()
109    }
110}
111
112struct ZincioTimer {
113    inner: Pin<Box<zincio::time::Sleep>>,
114}
115
116impl fmt::Debug for ZincioTimer {
117    #[inline]
118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119        f.debug_struct("ZincioTimer").finish_non_exhaustive()
120    }
121}
122
123unsafe impl Send for ZincioTimer {}
124unsafe impl Sync for ZincioTimer {}
125
126impl AsyncTimer for ZincioTimer {
127    #[inline]
128    fn reset(self: Pin<&mut Self>, i: Instant) {
129        self.get_mut().inner.as_mut().get_mut().reset(i);
130    }
131
132    #[inline]
133    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> {
134        self.get_mut().inner.as_mut().poll(cx)
135    }
136}
137
138struct ZincioUdpSocket {
139    io: PollUdpSocket,
140    state: udp::UdpSocketState,
141    socket: std::net::UdpSocket,
142}
143
144impl fmt::Debug for ZincioUdpSocket {
145    #[inline]
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        f.debug_struct("ZincioUdpSocket")
148            .field("local_addr", &self.local_addr())
149            .finish_non_exhaustive()
150    }
151}
152
153unsafe impl Send for ZincioUdpSocket {}
154unsafe impl Sync for ZincioUdpSocket {}
155
156impl AsyncUdpSocket for ZincioUdpSocket {
157    #[inline]
158    fn create_io_poller(self: Arc<Self>) -> Pin<Box<dyn UdpPoller>> {
159        Box::pin(ZincioUdpPoller { socket: self })
160    }
161
162    #[inline]
163    fn try_send(&self, transmit: &Transmit) -> io::Result<()> {
164        self.io
165            .try_io_writable(|| self.state.send((&self.socket).into(), transmit))
166    }
167
168    #[inline]
169    fn poll_recv(
170        &self,
171        cx: &mut Context,
172        bufs: &mut [io::IoSliceMut<'_>],
173        meta: &mut [RecvMeta],
174    ) -> Poll<io::Result<usize>> {
175        loop {
176            ready!(self.io.poll_readable(cx)?);
177            match self
178                .io
179                .try_io_readable(|| self.state.recv((&self.socket).into(), bufs, meta))
180            {
181                Ok(n) => return Poll::Ready(Ok(n)),
182                Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue,
183                Err(e) => return Poll::Ready(Err(e)),
184            }
185        }
186    }
187
188    #[inline]
189    fn local_addr(&self) -> io::Result<SocketAddr> {
190        self.io.local_addr()
191    }
192
193    #[inline]
194    fn max_transmit_segments(&self) -> usize {
195        self.state.max_gso_segments()
196    }
197
198    #[inline]
199    fn max_receive_segments(&self) -> usize {
200        self.state.gro_segments()
201    }
202
203    #[inline]
204    fn may_fragment(&self) -> bool {
205        self.state.may_fragment()
206    }
207}
208
209struct ZincioUdpPoller {
210    socket: Arc<ZincioUdpSocket>,
211}
212
213impl fmt::Debug for ZincioUdpPoller {
214    #[inline]
215    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216        f.debug_struct("ZincioUdpPoller").finish_non_exhaustive()
217    }
218}
219
220unsafe impl Send for ZincioUdpPoller {}
221unsafe impl Sync for ZincioUdpPoller {}
222
223impl UdpPoller for ZincioUdpPoller {
224    #[inline]
225    fn poll_writable(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
226        self.socket.io.poll_writable(cx)
227    }
228}