weida 0.1.0-alpha.16

QUIC-native messaging framework: runtime, native QUIC transport, Req/Rep, Push/Pull, Pub/Sub, PAIR, SURVEY and BUS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! Where a runtime's QUIC sockets come from
//! ([decisions/0042](../../../docs/decisions/0042-simulated-network.md)).

use std::io::{self, IoSliceMut};
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr};
use std::pin::Pin;
use std::sync::{Arc, Mutex, RwLock, Weak};
use std::task::{Context, Poll, ready};

use quinn::udp::{RecvMeta, Transmit};
use tokio::io::Interest;

use weida_core::Error;

use crate::runtime::Exec;

/// Where a runtime's QUIC sockets live: the operating system's UDP (the default) or, with the
/// cargo feature `test-util`, a `SimNet` shared by the runtimes of one test. On a `SimNet` a
/// `weida+unix` binding and dial are simulated too (by path, with no socket file);
/// `weida+inproc` and `weida+pipe` are not affected.
#[derive(Clone, Debug, Default)]
pub struct Network {
    kind: Kind,
}

#[derive(Clone, Debug, Default)]
enum Kind {
    #[default]
    Os,
    #[cfg(feature = "test-util")]
    Sim(crate::sim::SimNet),
}

impl Network {
    /// The simulated network `net`: give every runtime of one test the same one.
    #[cfg(feature = "test-util")]
    pub fn sim(net: &crate::SimNet) -> Network {
        Network {
            kind: Kind::Sim(net.clone()),
        }
    }

    /// The simulated network, where this is one: what a `weida+unix` binding and dial use.
    #[cfg(all(unix, feature = "test-util"))]
    pub(crate) fn sim_net(&self) -> Option<&crate::sim::SimNet> {
        match &self.kind {
            Kind::Os => None,
            Kind::Sim(net) => Some(net),
        }
    }

    /// The socket a QUIC binding on `addr` serves on.
    pub(crate) fn bind_server(&self, addr: SocketAddr, exec: &Exec) -> Result<BoundSocket, Error> {
        match &self.kind {
            Kind::Os => BoundSocket::os(std::net::UdpSocket::bind(addr).map_err(Error::Io)?, exec),
            #[cfg(feature = "test-util")]
            Kind::Sim(net) => {
                let socket = net.bind(addr)?;
                let _guard = exec.enter();
                Ok(BoundSocket {
                    inner: Arc::clone(&socket) as Arc<dyn quinn::AsyncUdpSocket>,
                    runtime: quic_runtime()?,
                    lease: AddrLease::Sim(socket),
                })
            }
        }
    }

    /// The runtime's one client endpoint.
    pub(crate) fn bind_client(&self, exec: &Exec) -> Result<quinn::Endpoint, Error> {
        match &self.kind {
            Kind::Os => bind_os_client(exec),
            #[cfg(feature = "test-util")]
            Kind::Sim(net) => {
                let socket = net.bind(SocketAddr::from((Ipv6Addr::UNSPECIFIED, 0)))?;
                let _guard = exec.enter();
                quinn::Endpoint::new_with_abstract_socket(
                    quinn::EndpointConfig::default(),
                    None,
                    socket,
                    quic_runtime()?,
                )
                .map_err(Error::Io)
            }
        }
    }
}

/// `quinn`'s runtime for the reactor the caller entered.
pub(crate) fn quic_runtime() -> Result<Arc<dyn quinn::Runtime>, Error> {
    quinn::default_runtime()
        .ok_or_else(|| Error::Runtime("no async runtime for the QUIC endpoint".into()))
}

/// Binds the shared client socket, preferring dual-stack IPv6.
///
/// Inside the runtime context: `quinn` registers the socket with the reactor
/// as it is constructed, and the caller's thread may have none.
fn bind_os_client(exec: &Exec) -> Result<quinn::Endpoint, Error> {
    let _guard = exec.enter();
    let socket = client_socket().map_err(Error::Io)?;
    quinn::Endpoint::new(
        quinn::EndpointConfig::default(),
        None,
        socket,
        quic_runtime()?,
    )
    .map_err(Error::Io)
}

/// The client socket: dual-stack IPv6 where the host has it, else IPv4.
fn client_socket() -> io::Result<std::net::UdpSocket> {
    dual_stack_socket().or_else(|e| {
        tracing::debug!(error = %e, "IPv6 client socket unavailable; falling back to IPv4");
        std::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0))
    })
}

/// Ports [`dual_stack_socket`] tries before it gives up on dual-stack.
const PORT_ATTEMPTS: usize = 16;

/// A dual-stack socket on `[::]`, on a port no IPv4 socket holds.
///
/// A dual-stack bind of port 0 checks only the IPv6 sockets on macOS: it
/// can return a port an IPv4 socket holds on `127.0.0.1` or `0.0.0.0`, and
/// every IPv4 datagram to that port then goes to the IPv4 socket, so a dial
/// from it never hears the server and ends at the idle timeout (ticket
/// #47). An IPv4 bind of port 0 checks both families, so the port comes
/// from one, closed again before the dual-stack socket binds it by number.
/// A port taken in between, or held by an IPv6-only socket, is refused
/// with `AddrInUse`, and the next probe picks another.
fn dual_stack_socket() -> io::Result<std::net::UdpSocket> {
    let mut attempts = 0;
    loop {
        attempts += 1;
        // A host without IPv4 has no IPv4 socket to share a port with.
        let port = match std::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)) {
            Ok(probe) => probe.local_addr()?.port(),
            Err(_) => 0,
        };
        let socket = socket2::Socket::new(
            socket2::Domain::IPV6,
            socket2::Type::DGRAM,
            Some(socket2::Protocol::UDP),
        )?;
        if let Err(e) = socket.set_only_v6(false) {
            tracing::debug!(error = %e, "unable to make the client socket dual-stack");
        }
        match socket.bind(&SocketAddr::from((Ipv6Addr::UNSPECIFIED, port)).into()) {
            Ok(()) => return Ok(socket.into()),
            Err(e)
                if port != 0
                    && attempts < PORT_ATTEMPTS
                    && e.kind() == io::ErrorKind::AddrInUse => {}
            Err(e) => return Err(e),
        }
    }
}

/// A socket a QUIC binding serves on.
pub(crate) struct BoundSocket {
    pub(crate) inner: Arc<dyn quinn::AsyncUdpSocket>,
    pub(crate) runtime: Arc<dyn quinn::Runtime>,
    pub(crate) lease: AddrLease,
}

impl BoundSocket {
    /// An OS socket wrapped for `quinn`, with the duplicate a handover passes on.
    pub(crate) fn os(socket: std::net::UdpSocket, exec: &Exec) -> Result<BoundSocket, Error> {
        // Inside the runtime context: the socket is registered with the
        // reactor as it is wrapped, and the calling thread may have none.
        let _guard = exec.enter();
        let runtime = quic_runtime()?;
        let socket = OsSocket::new(socket).map_err(Error::Io)?;
        Ok(BoundSocket {
            inner: Arc::clone(&socket) as Arc<dyn quinn::AsyncUdpSocket>,
            runtime,
            lease: AddrLease::Os(socket),
        })
    }

    /// A hidden peer's relay socket ([`crate::Listener::bind_relay`]).
    pub(crate) fn relay(
        socket: Arc<crate::relay::RelaySocket>,
        exec: &Exec,
    ) -> Result<BoundSocket, Error> {
        let _guard = exec.enter();
        Ok(BoundSocket {
            inner: Arc::clone(&socket) as Arc<dyn quinn::AsyncUdpSocket>,
            runtime: quic_runtime()?,
            lease: AddrLease::Relay(socket),
        })
    }
}

/// Frees a binding's address when it closes: closes the OS socket and its
/// handover duplicate, frees the simulated address, or ends a relay
/// registration.
#[derive(Clone, Debug)]
pub(crate) enum AddrLease {
    Os(Arc<OsSocket>),
    #[cfg(feature = "test-util")]
    Sim(Arc<crate::sim::SimSocket>),
    Relay(Arc<crate::relay::RelaySocket>),
}

impl AddrLease {
    pub(crate) fn release(&self) {
        match self {
            AddrLease::Os(socket) => socket.release(),
            #[cfg(feature = "test-util")]
            AddrLease::Sim(socket) => socket.release(),
            AddrLease::Relay(socket) => socket.release(),
        }
    }

    /// The duplicate a handover passes on; `None` on a simulated network, on
    /// a relay, once taken, and once released.
    pub(crate) fn take_handed(&self) -> Option<std::net::UdpSocket> {
        match self {
            AddrLease::Os(socket) => socket.take_handed(),
            #[cfg(feature = "test-util")]
            AddrLease::Sim(_) => None,
            AddrLease::Relay(_) => None,
        }
    }
}

/// A future that resolves once a socket is writable.
type Writable = Pin<Box<dyn Future<Output = io::Result<()>> + Send>>;

/// A binding's OS UDP socket as `quinn` sees it: what `quinn`'s Tokio runtime
/// wraps a socket into, plus [`OsSocket::release`], which closes the socket
/// while `quinn` still holds this wrapper. `quinn` keeps a connection's socket
/// as long as any handle on that connection lives; without the release a
/// closed binding's port stays taken by whatever still holds one.
pub(crate) struct OsSocket {
    /// `None` once released. Shared only with the writability waits of the
    /// pollers, which `release` clears.
    io: RwLock<Option<Arc<tokio::net::UdpSocket>>>,
    state: quinn::udp::UdpSocketState,
    /// Read at bind time, so it is still answered after the release.
    local_addr: SocketAddr,
    /// The duplicate a handover passes on.
    handed: Mutex<Option<std::net::UdpSocket>>,
    /// The wait slot of every poller made for this socket.
    pollers: Mutex<Vec<Weak<Mutex<Option<Writable>>>>>,
}

impl OsSocket {
    /// Wraps `socket`, inside the runtime context: it is registered with the
    /// reactor here.
    pub(crate) fn new(socket: std::net::UdpSocket) -> io::Result<Arc<OsSocket>> {
        let handed = socket.try_clone()?;
        // Also makes the socket non-blocking.
        let state = quinn::udp::UdpSocketState::new((&socket).into())?;
        let local_addr = socket.local_addr()?;
        let io = tokio::net::UdpSocket::from_std(socket)?;
        Ok(Arc::new(OsSocket {
            io: RwLock::new(Some(Arc::new(io))),
            state,
            local_addr,
            handed: Mutex::new(Some(handed)),
            pollers: Mutex::new(Vec::new()),
        }))
    }

    pub(crate) fn take_handed(&self) -> Option<std::net::UdpSocket> {
        self.handed.lock().expect("handed socket poisoned").take()
    }

    /// Closes the socket and its duplicate; from then on sends are dropped
    /// and nothing is received. Idempotent.
    ///
    /// A poll that cloned the socket before the first step stored its wait
    /// under its slot's lock, which the third step takes afterwards and
    /// clears; a poll after the first step finds `None`. So once the last
    /// step drops it, nothing holds the socket.
    pub(crate) fn release(&self) {
        let io = self.io.write().expect("socket poisoned").take();
        drop(self.handed.lock().expect("handed socket poisoned").take());
        let pollers = std::mem::take(&mut *self.pollers.lock().expect("poller list poisoned"));
        for slot in pollers.iter().filter_map(Weak::upgrade) {
            slot.lock().expect("poller slot poisoned").take();
        }
        drop(io);
    }
}

impl std::fmt::Debug for OsSocket {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OsSocket")
            .field("local_addr", &self.local_addr)
            .field(
                "released",
                &self.io.read().expect("socket poisoned").is_none(),
            )
            .finish_non_exhaustive()
    }
}

impl quinn::AsyncUdpSocket for OsSocket {
    fn create_io_poller(self: Arc<Self>) -> Pin<Box<dyn quinn::UdpPoller>> {
        let waiting = Arc::new(Mutex::new(None));
        {
            let mut pollers = self.pollers.lock().expect("poller list poisoned");
            pollers.retain(|w| w.strong_count() > 0);
            pollers.push(Arc::downgrade(&waiting));
        }
        Box::pin(OsPoller {
            socket: self,
            waiting,
        })
    }

    fn try_send(&self, transmit: &Transmit) -> io::Result<()> {
        match &*self.io.read().expect("socket poisoned") {
            Some(io) => io.try_io(Interest::WRITABLE, || {
                self.state.send((&**io).into(), transmit)
            }),
            // A released socket drops what is sent, as a released `SimSocket` does.
            None => Ok(()),
        }
    }

    fn poll_recv(
        &self,
        cx: &mut Context,
        bufs: &mut [IoSliceMut<'_>],
        meta: &mut [RecvMeta],
    ) -> Poll<io::Result<usize>> {
        let guard = self.io.read().expect("socket poisoned");
        // A released socket receives nothing. `Pending` rather than an error,
        // which `quinn` would log on every close; its driver ends once its
        // handles are gone.
        let Some(io) = &*guard else {
            return Poll::Pending;
        };
        loop {
            ready!(io.poll_recv_ready(cx))?;
            if let Ok(n) = io.try_io(Interest::READABLE, || {
                self.state.recv((&**io).into(), bufs, meta)
            }) {
                return Poll::Ready(Ok(n));
            }
        }
    }

    fn local_addr(&self) -> io::Result<SocketAddr> {
        Ok(self.local_addr)
    }

    fn may_fragment(&self) -> bool {
        self.state.may_fragment()
    }

    fn max_transmit_segments(&self) -> usize {
        self.state.max_gso_segments()
    }

    fn max_receive_segments(&self) -> usize {
        self.state.gro_segments()
    }
}

/// One writability wait on an [`OsSocket`]. A future per poller rather than
/// `tokio::net::UdpSocket::poll_send_ready`, which keeps only the last
/// waker: every connection has a poller of its own.
struct OsPoller {
    socket: Arc<OsSocket>,
    waiting: Arc<Mutex<Option<Writable>>>,
}

impl std::fmt::Debug for OsPoller {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OsPoller").finish_non_exhaustive()
    }
}

impl quinn::UdpPoller for OsPoller {
    fn poll_writable(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
        let mut waiting = self.waiting.lock().expect("poller slot poisoned");
        let wait = match &mut *waiting {
            Some(wait) => wait,
            None => {
                let Some(io) = self.socket.io.read().expect("socket poisoned").clone() else {
                    // Released: sends are dropped, so the socket never blocks.
                    return Poll::Ready(Ok(()));
                };
                waiting.insert(Box::pin(async move { io.writable().await }))
            }
        };
        let result = ready!(wait.as_mut().poll(cx));
        *waiting = None;
        Poll::Ready(result)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Tests that touch the filesystem, network, processes or real time: the
    /// integration tier (`.config/nextest.toml`).
    mod io {
        use super::*;

        #[tokio::test]
        async fn the_client_socket_binds() {
            let exec = Exec::current().expect("ambient runtime");
            let endpoint = Network::default().bind_client(&exec).unwrap();
            assert_ne!(endpoint.local_addr().unwrap().port(), 0);
        }

        /// A dual-stack bind of port 0 on macOS may return a port an IPv4 socket
        /// holds, which then receives every IPv4 datagram meant for the client
        /// (ticket #47). Against 200 held ports one such bind in about 80 hits
        /// one, so 2000 binds find one with near certainty.
        #[test]
        fn the_client_socket_never_takes_a_port_an_ipv4_socket_holds() {
            let holders: Vec<std::net::UdpSocket> = (0..200)
                .map(|_| std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).expect("a holder"))
                .collect();
            let held: std::collections::HashSet<u16> = holders
                .iter()
                .map(|s| s.local_addr().expect("a holder's address").port())
                .collect();
            for _ in 0..2000 {
                let port = client_socket()
                    .expect("a client socket")
                    .local_addr()
                    .expect("its address")
                    .port();
                assert!(
                    !held.contains(&port),
                    "the client socket took port {port}, which an IPv4 socket on 127.0.0.1 holds"
                );
            }
        }
    }
}