Skip to main content

hyprstream_rpc/transport/
uds_session.rs

1//! `UdsSession` — one [`web_transport_trait::Session`] over a Unix-domain socket.
2//!
3//! Epic #131 / moq M1. Same-host processes keep an `ipc` transport after the ZMQ
4//! removal, but re-platformed off ZMQ framing onto the *same* generic plane that
5//! quinn and iroh use: a [`web_transport_trait::Session`]. Because both the RPC
6//! plane ([`super::rpc_session::SessionRpcTransport`] /
7//! [`super::rpc_session::serve_rpc_connection`]) and the streaming plane
8//! (`moq_net::{Client, Server}`) are generic over `Session`, **one** `UdsSession`
9//! impl carries *both* over a single `UnixStream` — exactly as the QUIC/iroh
10//! sessions do.
11//!
12//! # Why a multiplexer
13//!
14//! `web_transport_trait::Session` is a *stream-multiplexed* abstraction
15//! (`open_bi`/`open_uni`/`accept_bi`/`accept_uni`). QUIC and iroh provide that
16//! natively; a `UnixStream` is a single ordered byte-stream. So `UdsSession`
17//! carries a [`yamux`] multiplexer — flow-controlled, head-of-line-correct
18//! concurrent substreams over the one socket. moq-lite needs exactly this: one
19//! bidi SETUP control stream plus one uni stream per Group. It never uses
20//! datagrams, so those trait methods are stubbed (`max_datagram_size() == 0`).
21//!
22//! # Two wire conventions (UDS has neither ALPN nor a uni/bidi distinction)
23//!
24//! 1. **Plane byte** ([`PLANE_RPC`] / [`PLANE_MOQ`]) — written once on the raw
25//!    `UnixStream` *before* yamux wraps it. Replaces ALPN: the listener reads it
26//!    to route the connection to the RPC dispatcher vs `moq_net::Server::accept`.
27//! 2. **Substream tag** ([`TAG_BIDI`] / [`TAG_UNI`]) — yamux substreams are all
28//!    bidirectional, so the opener prefixes each new substream with one tag byte
29//!    and the acceptor reads it to route the substream to `accept_bi` vs
30//!    `accept_uni`. A uni opener simply never reads its half.
31//!
32//! # Driver
33//!
34//! yamux's `Connection` is single-owner and poll-driven (not `Clone`), but
35//! `Session: Clone` and is called concurrently. So one **driver task** owns the
36//! `Connection` and services `open_*`/inbound-stream work over channels; cloned
37//! `UdsSession` handles all talk to it. This mirrors `libp2p-yamux`.
38
39use std::collections::VecDeque;
40use std::path::Path;
41use std::sync::atomic::{AtomicBool, Ordering};
42use std::sync::Arc;
43use std::task::{Context, Poll};
44use std::time::Duration;
45
46use anyhow::Result;
47use bytes::Bytes;
48use futures::io::{AsyncReadExt, AsyncWriteExt, ReadHalf, WriteHalf};
49use tokio::sync::{mpsc, oneshot, Mutex, Notify};
50use tokio_util::compat::TokioAsyncReadCompatExt;
51use web_transport_trait::Session;
52
53/// Connection-plane selector written as the first byte on the raw socket. The
54/// RPC dispatcher and the moq server are distinct planes (as ALPN distinguishes
55/// them on QUIC); one `UnixStream` serves exactly one.
56pub const PLANE_RPC: u8 = 0x01;
57/// See [`PLANE_RPC`]. Routes the connection to `moq_net::Server::accept`.
58pub const PLANE_MOQ: u8 = 0x02;
59
60/// Substream-kind tag: the opener intends a bidirectional stream.
61const TAG_BIDI: u8 = 0x01;
62/// Substream-kind tag: the opener intends a unidirectional stream (writer only).
63const TAG_UNI: u8 = 0x02;
64
65/// Bound on queued accepted substreams and pending opens before backpressure.
66const ACCEPT_CHANNEL_BOUND: usize = 64;
67const CMD_CHANNEL_BOUND: usize = 64;
68
69/// Hard cap on concurrent yamux substreams per connection. Bounds the inbound
70/// classification fan-out (one task + one stream slot each) so a hostile local
71/// peer cannot open an unbounded number of substreams. yamux enforces this at
72/// the protocol layer (excess opens are refused), giving the transport a DoS
73/// bound independent of the downstream rpc_session semaphore.
74const MAX_CONCURRENT_STREAMS: usize = 256;
75
76/// Per-substream deadline for reading the 1-byte UNI/BIDI tag. Without it, a
77/// peer that opens a substream and never sends the tag pins a classification
78/// task and a yamux stream slot forever — a pre-dispatch slowloris that evades
79/// rpc_session's `REQUEST_READ_TIMEOUT` (which only starts after classification).
80const TAG_READ_TIMEOUT: Duration = Duration::from_secs(10);
81
82/// The concrete yamux substream type once wrapped over a compat `UnixStream`.
83type YamuxStream = yamux::Stream;
84
85// ============================================================================
86// Error
87// ============================================================================
88
89/// Error type for [`UdsSession`] and its streams.
90#[derive(Debug, Clone)]
91pub struct UdsError(String);
92
93impl UdsError {
94    fn new(msg: impl Into<String>) -> Self {
95        Self(msg.into())
96    }
97    fn closed() -> Self {
98        Self("uds session closed".to_owned())
99    }
100    fn io(e: std::io::Error) -> Self {
101        Self(format!("uds io: {e}"))
102    }
103    fn conn(e: yamux::ConnectionError) -> Self {
104        Self(format!("uds yamux: {e}"))
105    }
106}
107
108impl std::fmt::Display for UdsError {
109    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110        f.write_str(&self.0)
111    }
112}
113
114impl std::error::Error for UdsError {}
115
116impl web_transport_trait::Error for UdsError {
117    fn session_error(&self) -> Option<(u32, String)> {
118        Some((0, self.0.clone()))
119    }
120}
121
122// ============================================================================
123// Streams
124// ============================================================================
125
126/// Outbound half of a UDS substream. Wraps the yamux write half; `finish`
127/// half-closes (sends FIN) so the peer's read sees EOF.
128pub struct UdsSendStream {
129    // `None` after finish()/reset() so further writes error.
130    inner: Option<WriteHalf<YamuxStream>>,
131}
132
133impl UdsSendStream {
134    fn new(wh: WriteHalf<YamuxStream>) -> Self {
135        Self { inner: Some(wh) }
136    }
137}
138
139impl web_transport_trait::SendStream for UdsSendStream {
140    type Error = UdsError;
141
142    async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
143        let wh = self
144            .inner
145            .as_mut()
146            .ok_or_else(|| UdsError::new("write after finish/reset"))?;
147        wh.write(buf).await.map_err(UdsError::io)
148    }
149
150    async fn write_chunk(&mut self, chunk: Bytes) -> Result<(), Self::Error> {
151        // The trait's default `write_chunk` issues a single `write` and silently
152        // discards any unwritten tail. yamux caps each write at its split-send
153        // size (16 KiB), so a larger chunk — e.g. a signed envelope carrying a
154        // hybrid ML-DSA JWT — would be truncated and then FIN'd by the caller.
155        // Loop until the whole chunk is on the stream.
156        self.write_all(&chunk).await
157    }
158
159    fn set_priority(&mut self, _order: u8) {
160        // yamux has no per-stream priority; no-op.
161    }
162
163    fn finish(&mut self) -> Result<(), Self::Error> {
164        // `finish` is sync but yamux close is async; send the FIN on a detached
165        // task. Subsequent writes error (inner is now None). The driver pumps the
166        // connection so the FIN reaches the peer.
167        if let Some(mut wh) = self.inner.take() {
168            tokio::spawn(async move {
169                if let Err(e) = wh.close().await {
170                    tracing::debug!(error = %e, "uds: send-stream FIN flush failed");
171                }
172            });
173        }
174        Ok(())
175    }
176
177    fn reset(&mut self, _code: u32) {
178        // Drop the write half without a graceful FIN; yamux signals the peer.
179        self.inner = None;
180    }
181
182    async fn closed(&mut self) -> Result<(), Self::Error> {
183        // `closed` must DETECT closure, never CAUSE it. After finish()/reset()
184        // the FIN/RST was already initiated, so report closed. While the stream
185        // is still open we have no portable way to observe a peer STOP_SENDING
186        // through yamux's WriteHalf, so we pend — returning early here would make
187        // moq's `select! { biased; _ = closed() => cancel }` abort a live group
188        // right after its header, dropping every frame.
189        if self.inner.is_some() {
190            std::future::pending::<()>().await;
191        }
192        Ok(())
193    }
194}
195
196/// Inbound half of a UDS substream. Wraps the yamux read half.
197pub struct UdsRecvStream {
198    inner: ReadHalf<YamuxStream>,
199}
200
201impl UdsRecvStream {
202    fn new(rh: ReadHalf<YamuxStream>) -> Self {
203        Self { inner: rh }
204    }
205}
206
207impl web_transport_trait::RecvStream for UdsRecvStream {
208    type Error = UdsError;
209
210    async fn read(&mut self, dst: &mut [u8]) -> Result<Option<usize>, Self::Error> {
211        match self.inner.read(dst).await.map_err(UdsError::io)? {
212            0 => Ok(None), // EOF (FIN)
213            n => Ok(Some(n)),
214        }
215    }
216
217    fn stop(&mut self, _code: u32) {
218        // Best-effort: the read half closes on drop of this `UdsRecvStream`,
219        // which yamux surfaces to the peer. No separate sync close path.
220    }
221
222    async fn closed(&mut self) -> Result<(), Self::Error> {
223        // Must DETECT closure without CONSUMING data — moq selects on
224        // `recv.closed()` concurrently with reads, so draining here would steal
225        // frame bytes. We have no portable yamux peek for a peer FIN/RST on the
226        // ReadHalf, so we pend; the stream closes for real when this
227        // `UdsRecvStream` drops. (A `read()` returning `None` is the actual
228        // EOF signal moq relies on.)
229        std::future::pending::<()>().await;
230        Ok(())
231    }
232}
233
234// ============================================================================
235// Driver
236// ============================================================================
237
238/// Command from a [`UdsSession`] handle to its driver task.
239enum DriverCmd {
240    /// Open a new outbound yamux substream; the tag byte is written by the
241    /// `open_*` method after it receives the stream.
242    OpenOutbound(oneshot::Sender<Result<YamuxStream, yamux::ConnectionError>>),
243    /// Begin a graceful connection close.
244    Close,
245}
246
247/// Read the 1-byte substream tag and route the substream to the matching accept
248/// queue. Runs as its own task so the tag read is driven by the still-pumping
249/// connection driver (it never blocks the driver loop).
250async fn classify_inbound(
251    mut stream: YamuxStream,
252    bi_tx: mpsc::Sender<(UdsSendStream, UdsRecvStream)>,
253    uni_tx: mpsc::Sender<UdsRecvStream>,
254) {
255    let mut tag = [0u8; 1];
256    // Bound the tag read so a peer that opens a substream and never tags it
257    // cannot pin this task + a yamux stream slot indefinitely.
258    match tokio::time::timeout(TAG_READ_TIMEOUT, stream.read_exact(&mut tag)).await {
259        Ok(Ok(())) => {}
260        Ok(Err(e)) => {
261            tracing::debug!(error = %e, "uds: inbound substream closed before tagging");
262            return;
263        }
264        Err(_) => {
265            tracing::warn!(
266                timeout = ?TAG_READ_TIMEOUT,
267                "uds: inbound substream did not send its tag in time, dropping"
268            );
269            return;
270        }
271    }
272    match tag[0] {
273        TAG_BIDI => {
274            let (rh, wh) = stream.split();
275            let _ = bi_tx
276                .send((UdsSendStream::new(wh), UdsRecvStream::new(rh)))
277                .await;
278        }
279        TAG_UNI => {
280            let (rh, _wh) = stream.split();
281            // Uni: peer only writes; we keep the read half, drop the write half.
282            let _ = uni_tx.send(UdsRecvStream::new(rh)).await;
283        }
284        unknown => {
285            tracing::warn!(tag = unknown, "uds: unknown substream tag, dropping");
286        }
287    }
288}
289
290/// The connection driver: owns the yamux `Connection` and pumps it forever,
291/// servicing outbound-open commands and routing inbound substreams, until the
292/// connection ends or all handles drop. A single `poll_fn` keeps exclusive
293/// `&mut conn` per poll, avoiding the borrow dance of `select!`.
294async fn drive_connection<T>(
295    socket: T,
296    mode: yamux::Mode,
297    mut cmd_rx: mpsc::Receiver<DriverCmd>,
298    bi_tx: mpsc::Sender<(UdsSendStream, UdsRecvStream)>,
299    uni_tx: mpsc::Sender<UdsRecvStream>,
300    is_closed: Arc<AtomicBool>,
301    closed_notify: Arc<Notify>,
302) where
303    T: futures::AsyncRead + futures::AsyncWrite + Unpin + Send + 'static,
304{
305    let mut cfg = yamux::Config::default();
306    // Cap concurrent substreams (DoS bound on inbound classification fan-out).
307    cfg.set_max_num_streams(MAX_CONCURRENT_STREAMS);
308    let mut conn = yamux::Connection::new(socket, cfg, mode);
309    let mut pending_opens: VecDeque<oneshot::Sender<Result<YamuxStream, yamux::ConnectionError>>> =
310        VecDeque::new();
311    let mut closing = false;
312
313    std::future::poll_fn(|cx: &mut Context<'_>| {
314        // 1. Ingest outbound-open / close commands (non-blocking drain).
315        if !closing {
316            loop {
317                match cmd_rx.poll_recv(cx) {
318                    Poll::Ready(Some(DriverCmd::OpenOutbound(reply))) => {
319                        pending_opens.push_back(reply);
320                    }
321                    // Explicit close, or all `UdsSession` handles dropped
322                    // (nothing more will be requested) — begin close either way.
323                    Poll::Ready(Some(DriverCmd::Close)) | Poll::Ready(None) => {
324                        closing = true;
325                        break;
326                    }
327                    Poll::Pending => break,
328                }
329            }
330        }
331
332        // 2. Service queued outbound opens (skip while closing).
333        if !closing {
334            while !pending_opens.is_empty() {
335                match conn.poll_new_outbound(cx) {
336                    Poll::Ready(result) => {
337                        let is_err = result.is_err();
338                        if let Some(reply) = pending_opens.pop_front() {
339                            let _ = reply.send(result);
340                        }
341                        if is_err {
342                            closing = true;
343                            break;
344                        }
345                    }
346                    Poll::Pending => break,
347                }
348            }
349        }
350
351        // 3. Closing path: drive the close handshake to completion.
352        if closing {
353            return match conn.poll_close(cx) {
354                Poll::Ready(_) => Poll::Ready(()),
355                Poll::Pending => Poll::Pending,
356            };
357        }
358
359        // 4. Drive inbound: each accepted substream is classified on its own task.
360        loop {
361            match conn.poll_next_inbound(cx) {
362                Poll::Ready(Some(Ok(stream))) => {
363                    tokio::spawn(classify_inbound(stream, bi_tx.clone(), uni_tx.clone()));
364                }
365                Poll::Ready(Some(Err(_))) | Poll::Ready(None) => return Poll::Ready(()),
366                Poll::Pending => return Poll::Pending,
367            }
368        }
369    })
370    .await;
371
372    // Connection ended: wake `closed()` waiters; dropping bi_tx/uni_tx closes the
373    // accept channels so pending `accept_*` calls observe closure.
374    is_closed.store(true, Ordering::Release);
375    closed_notify.notify_waiters();
376}
377
378// ============================================================================
379// Session
380// ============================================================================
381
382struct Inner {
383    cmd_tx: mpsc::Sender<DriverCmd>,
384    accept_bi_rx: Mutex<mpsc::Receiver<(UdsSendStream, UdsRecvStream)>>,
385    accept_uni_rx: Mutex<mpsc::Receiver<UdsRecvStream>>,
386    is_closed: Arc<AtomicBool>,
387    closed_notify: Arc<Notify>,
388}
389
390/// A [`web_transport_trait::Session`] over a Unix-domain socket, multiplexed by
391/// yamux. Clone-cheap (shares one driver via `Arc`). Carries both the RPC and
392/// moq planes — see the module docs.
393#[derive(Clone)]
394pub struct UdsSession {
395    inner: Arc<Inner>,
396}
397
398impl UdsSession {
399    /// Wrap an established, plane-selected socket and spawn its driver task.
400    /// `socket` must already have had the [`PLANE_RPC`]/[`PLANE_MOQ`] byte
401    /// consumed (see [`connect_uds`] / [`accept_uds`]).
402    fn spawn<T>(socket: T, mode: yamux::Mode) -> Self
403    where
404        T: futures::AsyncRead + futures::AsyncWrite + Unpin + Send + 'static,
405    {
406        let (cmd_tx, cmd_rx) = mpsc::channel(CMD_CHANNEL_BOUND);
407        let (bi_tx, bi_rx) = mpsc::channel(ACCEPT_CHANNEL_BOUND);
408        let (uni_tx, uni_rx) = mpsc::channel(ACCEPT_CHANNEL_BOUND);
409        let is_closed = Arc::new(AtomicBool::new(false));
410        let closed_notify = Arc::new(Notify::new());
411
412        tokio::spawn(drive_connection(
413            socket,
414            mode,
415            cmd_rx,
416            bi_tx,
417            uni_tx,
418            Arc::clone(&is_closed),
419            Arc::clone(&closed_notify),
420        ));
421
422        Self {
423            inner: Arc::new(Inner {
424                cmd_tx,
425                accept_bi_rx: Mutex::new(bi_rx),
426                accept_uni_rx: Mutex::new(uni_rx),
427                is_closed,
428                closed_notify,
429            }),
430        }
431    }
432
433    /// Request a fresh outbound yamux substream from the driver.
434    async fn open_outbound(&self) -> Result<YamuxStream, UdsError> {
435        let (tx, rx) = oneshot::channel();
436        self.inner
437            .cmd_tx
438            .send(DriverCmd::OpenOutbound(tx))
439            .await
440            .map_err(|_| UdsError::closed())?;
441        rx.await
442            .map_err(|_| UdsError::closed())?
443            .map_err(UdsError::conn)
444    }
445}
446
447impl Session for UdsSession {
448    type SendStream = UdsSendStream;
449    type RecvStream = UdsRecvStream;
450    type Error = UdsError;
451
452    async fn accept_uni(&self) -> Result<Self::RecvStream, Self::Error> {
453        let mut rx = self.inner.accept_uni_rx.lock().await;
454        rx.recv().await.ok_or_else(UdsError::closed)
455    }
456
457    async fn accept_bi(&self) -> Result<(Self::SendStream, Self::RecvStream), Self::Error> {
458        let mut rx = self.inner.accept_bi_rx.lock().await;
459        rx.recv().await.ok_or_else(UdsError::closed)
460    }
461
462    async fn open_bi(&self) -> Result<(Self::SendStream, Self::RecvStream), Self::Error> {
463        let mut stream = self.open_outbound().await?;
464        // Tag + flush so the acceptor can classify before any plane data.
465        stream.write_all(&[TAG_BIDI]).await.map_err(UdsError::io)?;
466        stream.flush().await.map_err(UdsError::io)?;
467        let (rh, wh) = stream.split();
468        Ok((UdsSendStream::new(wh), UdsRecvStream::new(rh)))
469    }
470
471    async fn open_uni(&self) -> Result<Self::SendStream, Self::Error> {
472        let mut stream = self.open_outbound().await?;
473        stream.write_all(&[TAG_UNI]).await.map_err(UdsError::io)?;
474        stream.flush().await.map_err(UdsError::io)?;
475        let (_rh, wh) = stream.split();
476        Ok(UdsSendStream::new(wh))
477    }
478
479    fn send_datagram(&self, _payload: Bytes) -> Result<(), Self::Error> {
480        Err(UdsError::new("UDS transport does not support datagrams"))
481    }
482
483    async fn recv_datagram(&self) -> Result<Bytes, Self::Error> {
484        // UDS has no datagram channel; moq-lite never calls this. Never resolves.
485        std::future::pending().await
486    }
487
488    fn max_datagram_size(&self) -> usize {
489        0
490    }
491
492    fn protocol(&self) -> Option<&str> {
493        None
494    }
495
496    fn close(&self, _code: u32, _reason: &str) {
497        // Best-effort: signal the driver. If the channel is full/closed the
498        // connection is already going down.
499        let _ = self.inner.cmd_tx.try_send(DriverCmd::Close);
500    }
501
502    async fn closed(&self) -> Self::Error {
503        loop {
504            if self.inner.is_closed.load(Ordering::Acquire) {
505                return UdsError::closed();
506            }
507            let notified = self.inner.closed_notify.notified();
508            // Re-check after arming to avoid missing a wake between the load and
509            // the await.
510            if self.inner.is_closed.load(Ordering::Acquire) {
511                return UdsError::closed();
512            }
513            notified.await;
514        }
515    }
516}
517
518// ============================================================================
519// Connect / accept helpers
520// ============================================================================
521
522/// Connect to a UDS endpoint, select `plane`, and return a multiplexed session.
523///
524/// Writes the [`PLANE_RPC`]/[`PLANE_MOQ`] byte on the raw socket, then wraps it
525/// in a client-mode yamux session.
526pub async fn connect_uds(path: impl AsRef<Path>, plane: u8) -> Result<UdsSession> {
527    let mut stream = tokio::net::UnixStream::connect(path.as_ref()).await?;
528    tokio::io::AsyncWriteExt::write_all(&mut stream, &[plane]).await?;
529    Ok(UdsSession::spawn(stream.compat(), yamux::Mode::Client))
530}
531
532/// Accept side: read the plane byte from a freshly-accepted `UnixStream`, then
533/// wrap it in a server-mode yamux session. The caller routes by `plane`
534/// ([`PLANE_RPC`] → RPC dispatcher, [`PLANE_MOQ`] → `moq_net::Server::accept`).
535pub async fn accept_uds(mut stream: tokio::net::UnixStream) -> Result<(u8, UdsSession)> {
536    let mut plane = [0u8; 1];
537    tokio::io::AsyncReadExt::read_exact(&mut stream, &mut plane).await?;
538    // Fail closed on an unrecognized plane selector rather than handing an
539    // ambiguous connection to a caller that would have to guess how to route it.
540    if !matches!(plane[0], PLANE_RPC | PLANE_MOQ) {
541        anyhow::bail!("uds: unknown plane selector byte 0x{:02x}", plane[0]);
542    }
543    Ok((
544        plane[0],
545        UdsSession::spawn(stream.compat(), yamux::Mode::Server),
546    ))
547}
548
549// Compile-time assertion that our types satisfy the native `MaybeSend` bound
550// (= `Send`) the moq/rpc planes require.
551const _: fn() = || {
552    fn assert_send<T: Send>() {}
553    assert_send::<UdsSession>();
554    assert_send::<UdsSendStream>();
555    assert_send::<UdsRecvStream>();
556};
557
558#[cfg(test)]
559#[allow(clippy::unwrap_used, clippy::expect_used)]
560mod tests {
561    use super::*;
562    use web_transport_trait::{RecvStream as _, SendStream as _};
563
564    /// Spawn a connected client/server `UdsSession` pair over an in-process
565    /// socketpair (no filesystem path needed), with the given plane byte already
566    /// consumed.
567    async fn session_pair() -> (UdsSession, UdsSession) {
568        let (a, b) = tokio::net::UnixStream::pair().unwrap();
569        let client = UdsSession::spawn(a.compat(), yamux::Mode::Client);
570        let server = UdsSession::spawn(b.compat(), yamux::Mode::Server);
571        (client, server)
572    }
573
574    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
575    async fn bidi_round_trip() {
576        let (client, server) = session_pair().await;
577
578        let srv = tokio::spawn(async move {
579            let (mut send, mut recv) = server.accept_bi().await.unwrap();
580            let mut buf = vec![0u8; 5];
581            let n = recv.read(&mut buf).await.unwrap().unwrap();
582            buf.truncate(n);
583            send.write_all(&buf).await.unwrap(); // echo
584            send.finish().unwrap();
585            // keep the session alive until the client has read the echo
586            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
587        });
588
589        let (mut send, mut recv) = client.open_bi().await.unwrap();
590        send.write_all(b"hello").await.unwrap();
591        send.finish().unwrap();
592        let mut got = Vec::new();
593        let mut scratch = [0u8; 64];
594        while let Some(n) = recv.read(&mut scratch).await.unwrap() {
595            got.extend_from_slice(&scratch[..n]);
596        }
597        assert_eq!(&got, b"hello");
598        srv.await.unwrap();
599    }
600
601    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
602    async fn write_chunk_larger_than_yamux_split_size_is_not_truncated() {
603        // yamux caps a single poll_write at its split-send size (16 KiB). A
604        // chunk larger than that must still arrive whole: a partial write that
605        // gets FIN'd truncates the message (e.g. a >16 KiB signed envelope
606        // arriving with its capnp length header claiming more words than the
607        // peer received).
608        let (client, server) = session_pair().await;
609
610        let payload: Vec<u8> = (0..20_000u32).map(|i| (i % 251) as u8).collect();
611        let expected = payload.clone();
612
613        let srv = tokio::spawn(async move {
614            let (_send, mut recv) = server.accept_bi().await.unwrap();
615            recv.read_all().await.unwrap()
616        });
617
618        let (mut send, _recv) = client.open_bi().await.unwrap();
619        send.write_chunk(Bytes::from(payload)).await.unwrap();
620        send.finish().unwrap();
621
622        let got = tokio::time::timeout(Duration::from_secs(5), srv)
623            .await
624            .expect("server read timed out")
625            .unwrap();
626        assert_eq!(got.len(), expected.len(), "chunk was truncated in flight");
627        assert_eq!(&got[..], &expected[..]);
628        drop(client);
629    }
630
631    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
632    async fn many_concurrent_uni_streams() {
633        let (client, server) = session_pair().await;
634        const N: usize = 8;
635
636        let srv = tokio::spawn(async move {
637            let mut totals = Vec::new();
638            for _ in 0..N {
639                let mut recv = server.accept_uni().await.unwrap();
640                let data = recv.read_all().await.unwrap();
641                totals.push(data.to_vec());
642            }
643            totals
644        });
645
646        // Open N uni streams concurrently, each carrying its index byte.
647        let mut handles = Vec::new();
648        for i in 0..N {
649            let c = client.clone();
650            handles.push(tokio::spawn(async move {
651                let mut send = c.open_uni().await.unwrap();
652                send.write_all(&[i as u8; 4]).await.unwrap();
653                send.finish().unwrap();
654                // Hold the stream briefly so FIN flushes.
655                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
656            }));
657        }
658        for h in handles {
659            h.await.unwrap();
660        }
661        let mut got = srv.await.unwrap();
662        got.sort();
663        let mut want: Vec<Vec<u8>> = (0..N).map(|i| vec![i as u8; 4]).collect();
664        want.sort();
665        assert_eq!(got, want);
666    }
667
668    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
669    async fn uni_stream_server_to_client() {
670        // moq publishes group frames as server->client uni streams, so verify
671        // that direction explicitly (the other uni test is client->server).
672        let (client, server) = session_pair().await;
673
674        let cli = tokio::spawn(async move {
675            let mut recv = client.accept_uni().await.unwrap();
676            recv.read_all().await.unwrap()
677        });
678
679        let mut send = server.open_uni().await.unwrap();
680        send.write_all(b"srv->cli").await.unwrap();
681        send.finish().unwrap();
682        tokio::time::sleep(std::time::Duration::from_millis(150)).await;
683
684        let got = cli.await.unwrap();
685        assert_eq!(&got[..], b"srv->cli");
686        // keep server alive until client read
687        drop(server);
688    }
689
690    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
691    async fn datagrams_unsupported() {
692        let (client, _server) = session_pair().await;
693        assert_eq!(client.max_datagram_size(), 0);
694        assert!(client.send_datagram(Bytes::from_static(b"x")).is_err());
695    }
696
697    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
698    async fn closed_fires_when_peer_drops() {
699        let (client, server) = session_pair().await;
700        drop(server);
701        // The driver should observe the broken connection and fire `closed`.
702        let _ = tokio::time::timeout(std::time::Duration::from_secs(5), client.closed())
703            .await
704            .expect("closed() must resolve after peer drop");
705    }
706
707    // ── Integration: the real RPC plane rides UdsSession unchanged ──────────
708    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
709    async fn rpc_plane_round_trip_over_uds() {
710        use crate::transport::rpc_session::{
711            from_fn, serve_rpc_connection, SessionRpcTransport, DEFAULT_STREAM_LIMIT,
712            REQUEST_READ_TIMEOUT,
713        };
714        use crate::transport_traits::Transport;
715        use std::sync::Arc;
716        use tokio::sync::Semaphore;
717        use tokio_util::sync::CancellationToken;
718
719        let (client_session, server_session) = session_pair().await;
720
721        let (sk, _vk) = crate::generate_signing_keypair();
722        let processor = Arc::new(from_fn(|req: Bytes| async move { Ok(req) })); // echo
723        let limit = Arc::new(Semaphore::new(DEFAULT_STREAM_LIMIT));
724        let shutdown = CancellationToken::new();
725
726        let srv = tokio::spawn(serve_rpc_connection(
727            server_session,
728            processor,
729            sk,
730            limit,
731            REQUEST_READ_TIMEOUT,
732            shutdown.clone(),
733            crate::transport::carrier::CarrierContext::trusted_uds(),
734        ));
735
736        // Two sequential calls prove the session multiplexes fresh bidi streams.
737        let client = SessionRpcTransport::new(client_session);
738        let r1 = client.send(b"ping".to_vec(), Some(4_000)).await.unwrap();
739        assert_eq!(r1, b"ping");
740        let r2 = client.send(b"pong".to_vec(), Some(4_000)).await.unwrap();
741        assert_eq!(r2, b"pong");
742
743        shutdown.cancel();
744        let _ = srv.await;
745    }
746
747    // ── Integration: the real moq streaming plane rides UdsSession unchanged ──
748    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
749    async fn moq_plane_publish_subscribe_over_uds() {
750        use moq_net::{Client, Group, Origin, Server, Track};
751        use std::time::Duration;
752
753        let (client_session, server_session) = session_pair().await;
754
755        // Publisher origin: publish a fully-formed broadcast/track/group (one
756        // frame, group closed) before the subscriber connects, so the served
757        // group is complete — matches the known-good iroh_moq round-trip.
758        let producer = Origin::random().produce();
759        let consumer = producer.consume();
760        let mut broadcast = producer.create_broadcast("alice/run-1").unwrap();
761        let mut track = broadcast.create_track(Track::new("tokens")).unwrap();
762        let mut group = track.create_group(Group::from(0u64)).unwrap();
763        group
764            .write_frame(Bytes::from_static(b"hello-uds-moq"))
765            .unwrap();
766        drop(group);
767
768        // The moq handshake is bidirectional (client opens the SETUP stream, the
769        // server accepts it), so server.accept and client.connect must run
770        // concurrently — over iroh/quinn the server side lives in a spawned
771        // accept loop; here we spawn it explicitly.
772        let server = Server::new().with_publish(consumer);
773        let server_task = tokio::spawn(async move { server.accept(server_session).await });
774
775        // Client: run moq Client over the UDS session, subscribe, read the frame.
776        let client_origin = Origin::random().produce();
777        let client_consumer = client_origin.consume();
778        let moq_client = Client::new().with_consume(client_origin);
779        let _moq_session =
780            tokio::time::timeout(Duration::from_secs(8), moq_client.connect(client_session))
781                .await
782                .expect("client.connect hung")
783                .unwrap();
784        let _moq_server = tokio::time::timeout(Duration::from_secs(8), server_task)
785            .await
786            .expect("server.accept hung")
787            .unwrap()
788            .unwrap();
789
790        let bc = tokio::time::timeout(
791            Duration::from_secs(5),
792            client_consumer.announced_broadcast("alice/run-1"),
793        )
794        .await
795        .unwrap()
796        .unwrap();
797        let mut tc = bc.subscribe_track(&Track::new("tokens")).unwrap();
798
799        let mut gc = tokio::time::timeout(Duration::from_secs(5), tc.next_group())
800            .await
801            .unwrap()
802            .unwrap()
803            .unwrap();
804        let frame = tokio::time::timeout(Duration::from_secs(5), gc.read_frame())
805            .await
806            .unwrap()
807            .unwrap()
808            .unwrap();
809        assert_eq!(&frame[..], b"hello-uds-moq");
810
811        // Keep broadcast/track alive until the read completes.
812        drop(track);
813        drop(broadcast);
814    }
815
816    // ── connect_uds / accept_uds plane handshake over a real listener ────────
817    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
818    async fn plane_handshake_over_listener() {
819        let dir = std::env::temp_dir().join(format!("uds-test-{}", std::process::id()));
820        let _ = std::fs::create_dir_all(&dir);
821        let path = dir.join("plane.sock");
822        let _ = std::fs::remove_file(&path);
823        let listener = tokio::net::UnixListener::bind(&path).unwrap();
824
825        let srv = tokio::spawn(async move {
826            let (stream, _) = listener.accept().await.unwrap();
827            let (plane, session) = accept_uds(stream).await.unwrap();
828            assert_eq!(plane, PLANE_RPC);
829            // echo one bidi stream
830            let (mut send, mut recv) = session.accept_bi().await.unwrap();
831            let data = recv.read_all().await.unwrap();
832            send.write_all(&data).await.unwrap();
833            send.finish().unwrap();
834            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
835        });
836
837        let client = connect_uds(&path, PLANE_RPC).await.unwrap();
838        let (mut send, mut recv) = client.open_bi().await.unwrap();
839        send.write_all(b"plane-ok").await.unwrap();
840        send.finish().unwrap();
841        let got = recv.read_all().await.unwrap();
842        assert_eq!(&got[..], b"plane-ok");
843
844        srv.await.unwrap();
845        let _ = std::fs::remove_file(&path);
846        let _ = std::fs::remove_dir(&dir);
847    }
848
849    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
850    async fn accept_uds_rejects_unknown_plane() {
851        let (a, b) = tokio::net::UnixStream::pair().unwrap();
852        // Client writes a bogus plane selector.
853        let cli = tokio::spawn(async move {
854            let mut a = a;
855            tokio::io::AsyncWriteExt::write_all(&mut a, &[0xFF])
856                .await
857                .unwrap();
858            // Hold the socket open so the server's read sees the byte, not EOF.
859            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
860        });
861        let res = accept_uds(b).await;
862        assert!(res.is_err(), "unknown plane selector must be rejected");
863        cli.await.unwrap();
864    }
865}