Skip to main content

aimdb_core/session/
io.rs

1//! Runtime-neutral byte-stream layer: the seam where an adapter owns sockets,
2//! clocks and name resolution, and a connector owns framing and protocol.
3//!
4//! These traits sit one layer **below** [`Connection`](super::Connection): a
5//! [`ByteStream`] is unframed, a [`Connection`](super::Connection) is framed. A
6//! connector generic over them needs no per-runtime module and no `cfg` on its
7//! code path.
8//!
9//! Every async method returns `impl Future<…> + Send`. The bound is on the
10//! return type because generic code must produce `Send` futures at the boxing
11//! boundary and cannot otherwise prove it — return-type notation, which would
12//! say exactly that, is still experimental on the pinned toolchain. An
13//! implementor whose runtime futures are `!Send` wraps them in a force-`Send`
14//! newtype; that `unsafe` belongs to the adapter, and core has none.
15//!
16//! The traits are deliberately not `dyn`-compatible. Connectors are generic
17//! over them; the `dyn` boundary stays at `Box<dyn Connection>` per frame.
18
19use crate::session::events::{report, SessionEvent};
20
21use alloc::boxed::Box;
22use alloc::string::String;
23use alloc::vec::Vec;
24use core::future::Future;
25
26use super::{BoxFut, Connection, Dialer, Listener, PeerInfo, TransportError, TransportResult};
27
28/// Failure of a byte-level I/O operation.
29///
30/// An alias, not a new type: these traits sit directly beneath
31/// [`Connection`](super::Connection), so nothing converts at that boundary.
32pub type IoError = TransportError;
33
34// ===========================================================================
35// Byte streams — the one real fork between runtimes.
36// ===========================================================================
37
38/// The read half of a [`split`](ByteStream::split) stream.
39pub trait ByteRead {
40    /// Read into `buf`, returning the byte count; `Ok(0)` is EOF.
41    fn read<'a>(
42        &'a mut self,
43        buf: &'a mut [u8],
44    ) -> impl Future<Output = TransportResult<usize>> + Send + 'a;
45}
46
47/// The write half of a [`split`](ByteStream::split) stream.
48pub trait ByteWrite {
49    /// Write every byte of `buf`, or fail.
50    fn write_all<'a>(
51        &'a mut self,
52        buf: &'a [u8],
53    ) -> impl Future<Output = TransportResult<()>> + Send + 'a;
54
55    /// Flush any buffered bytes toward the peer.
56    fn flush(&mut self) -> impl Future<Output = TransportResult<()>> + Send + '_;
57}
58
59/// An unframed, bidirectional byte stream — one TCP connection, one UART, one
60/// TLS session. The adapter owns it; the connector never names its type.
61///
62/// `read` returning `Ok(0)` is end of stream, matching both
63/// `embedded_io_async::Read` and `tokio::io::AsyncRead`. The stream is **one
64/// value** — `&mut self` on both directions — so it can wrap a socket that
65/// lends out only borrowed halves; a caller needing both directions at once
66/// borrows them apart with [`split`](ByteStream::split).
67///
68/// # Cancellation
69///
70/// [`read`](ByteStream::read) is cancel-safe on both adapters AimDB ships, but
71/// that is a property of those transports, not a promise of this trait.
72/// [`write_all`](ByteStream::write_all) is **not** cancel-safe anywhere and
73/// must never sit in a `select` arm: a partial write desynchronises the framing
74/// above it with nothing to resync on.
75pub trait ByteStream {
76    /// Read into `buf`, returning the byte count; `Ok(0)` is EOF.
77    fn read<'a>(
78        &'a mut self,
79        buf: &'a mut [u8],
80    ) -> impl Future<Output = TransportResult<usize>> + Send + 'a;
81
82    /// Write every byte of `buf`, or fail.
83    fn write_all<'a>(
84        &'a mut self,
85        buf: &'a [u8],
86    ) -> impl Future<Output = TransportResult<()>> + Send + 'a;
87
88    /// Flush any buffered bytes toward the peer.
89    fn flush(&mut self) -> impl Future<Output = TransportResult<()>> + Send + '_;
90
91    /// Borrow this stream as independent read and write halves, pollable
92    /// concurrently without either waiting on the other.
93    ///
94    /// The halves borrow rather than own, so a caller wanting owned or
95    /// `'static` halves needs a different seam.
96    fn split(&mut self) -> (impl ByteRead + Send + '_, impl ByteWrite + Send + '_);
97}
98
99/// Produces streams: the client side.
100///
101/// `host` is unresolved — name resolution belongs to the adapter, so a
102/// connector carries no resolver.
103pub trait StreamDialer {
104    /// The stream this dialer produces.
105    type Stream: ByteStream + Send;
106
107    /// Open a stream to `host:port`.
108    /// `host` is either a hostname or an unbracketed IP literal.
109    fn connect<'a>(
110        &'a self,
111        host: &'a str,
112        port: u16,
113    ) -> impl Future<Output = TransportResult<Self::Stream>> + Send + 'a;
114}
115
116/// Produces streams: the server side, and the dual of [`StreamDialer`].
117///
118/// One `accept` at a time, matching
119/// [`Listener::accept`](super::Listener::accept) and the `serve` loop that
120/// drives it. The single-shot signature costs no concurrency: an adapter
121/// backing it with a pool of sockets keeps every one of them listening across
122/// calls and consumes only the one that completes.
123pub trait StreamListener {
124    /// The stream this listener produces.
125    type Stream: ByteStream + Send;
126
127    /// Accept the next inbound stream, with whatever peer metadata the
128    /// transport exposes.
129    fn accept(
130        &mut self,
131    ) -> impl Future<Output = TransportResult<(Self::Stream, PeerInfo)>> + Send + '_;
132}
133
134// ===========================================================================
135// Datagrams.
136// ===========================================================================
137
138/// Connectionless I/O.
139pub trait Datagram {
140    /// Send `buf` to `to`.
141    fn send_to<'a>(
142        &'a mut self,
143        buf: &'a [u8],
144        to: core::net::SocketAddr,
145    ) -> impl Future<Output = TransportResult<()>> + Send + 'a;
146
147    /// Receive one datagram into `buf`, with its source address.
148    fn recv_from<'a>(
149        &'a mut self,
150        buf: &'a mut [u8],
151    ) -> impl Future<Output = TransportResult<(usize, core::net::SocketAddr)>> + Send + 'a;
152
153    /// The address this socket is bound to, or `None` on stacks that expose
154    /// none. A protocol that advertises its own endpoint in-band needs the real
155    /// address rather than the NAT-style `0.0.0.0:0`.
156    fn local_addr(&self) -> Option<core::net::SocketAddr>;
157}
158
159/// Binds [`Datagram`] sockets on demand.
160///
161/// A protocol task takes this rather than a socket, because a moved-in socket
162/// cannot be rebound after a reset. A std adapter binds a fresh socket; an
163/// Embassy one closes and re-binds the same socket, whose buffers live as long
164/// as it does.
165pub trait DatagramBinder {
166    /// The socket this binder produces.
167    type Socket: Datagram + Send;
168
169    /// Bind a socket to `port` (`0` for any).
170    fn bind(&self, port: u16) -> impl Future<Output = TransportResult<Self::Socket>> + Send + '_;
171}
172
173// ===========================================================================
174// Time.
175// ===========================================================================
176
177/// A non-allocating sleep.
178///
179/// [`RuntimeOps::sleep`](crate::executor::RuntimeOps::sleep) is `dyn` and must
180/// box; this one is generic and returns the adapter's own timer type with
181/// nothing on the heap. Only sleeping lives here — the clock is the
182/// [`InstanceClock`](crate::InstanceClock), a plain call.
183///
184/// The returned future borrows nothing, so a task holding a `D: Delay` still
185/// produces `'static` futures from it.
186pub trait Delay {
187    /// Complete after at least `d` has elapsed.
188    fn sleep(&self, d: core::time::Duration) -> impl Future<Output = ()> + Send;
189}
190
191// ===========================================================================
192// Framing — a transport crate contributes one of these and inherits the rest.
193// ===========================================================================
194
195/// How badly a framing step failed.
196///
197/// A self-delimiting format resyncs on its next delimiter; a length prefix has
198/// none, so nothing tells payload bytes from the next header. Only the framer
199/// knows which case it is in, so it says, rather than the connection guessing.
200#[derive(Debug, Clone, Copy, PartialEq, Eq)]
201#[cfg_attr(feature = "defmt", derive(defmt::Format))]
202pub enum FrameFault {
203    /// Bad frame, good link: skip it and keep reading.
204    Recoverable,
205    /// The link can no longer be interpreted and must close.
206    Fatal,
207}
208
209/// Frames a byte stream: COBS, length-prefix, NDJSON.
210pub trait Framer {
211    /// Encode one logical frame, appending its wire bytes to `out`.
212    ///
213    /// On `Err` nothing is appended, so a rejected frame never reaches the wire
214    /// half-written.
215    fn encode(&self, frame: &[u8], out: &mut Vec<u8>) -> Result<(), FrameFault>;
216    /// Feed received bytes into the accumulator.
217    fn push_bytes(&mut self, bytes: &[u8]);
218    /// Pull the next complete frame: `Some(Ok(frame))`, `Some(Err(fault))` (see
219    /// [`FrameFault`]), or `None` when more bytes are needed.
220    fn next_frame(&mut self) -> Option<Result<Vec<u8>, FrameFault>>;
221}
222
223/// Builds a fresh [`Framer`] per connection.
224///
225/// A blanket impl covers closures, so a caller writes `|| CobsFramer::new()`.
226pub trait FramerFactory {
227    /// The framer produced.
228    type Framer: Framer + Send;
229    /// Build one, for one connection.
230    fn framer(&self) -> Self::Framer;
231}
232
233impl<F, T> FramerFactory for F
234where
235    F: Fn() -> T,
236    T: Framer + Send,
237{
238    type Framer = T;
239    fn framer(&self) -> T {
240        self()
241    }
242}
243
244// ===========================================================================
245// Framed connections — a [`ByteStream`] plus a [`Framer`] is a [`Connection`].
246// ===========================================================================
247
248/// A framed [`Connection`] over any [`ByteStream`] and [`Framer`].
249///
250/// `RC` caps the per-`read` chunk and `WC` caps a single `write_all`; both are
251/// stack buffers, and some HAL `BufferedUart::write` rejects a write larger
252/// than its TX ring, which is what `WC` exists for.
253pub struct FramedConnection<S, F, const RC: usize = 256, const WC: usize = 256> {
254    stream: S,
255    framer: F,
256    peer: PeerInfo,
257}
258
259impl<S, F, const RC: usize, const WC: usize> FramedConnection<S, F, RC, WC> {
260    /// Frame `stream` with `framer`.
261    pub fn new(stream: S, framer: F) -> Self {
262        Self {
263            stream,
264            framer,
265            peer: PeerInfo::default(),
266        }
267    }
268
269    /// Frame `stream` with `framer`, carrying `peer` metadata from the accept.
270    pub fn with_peer(stream: S, framer: F, peer: PeerInfo) -> Self {
271        Self {
272            stream,
273            framer,
274            peer,
275        }
276    }
277}
278
279impl<S, F, const RC: usize, const WC: usize> Connection for FramedConnection<S, F, RC, WC>
280where
281    S: ByteStream + Send,
282    F: Framer + Send,
283{
284    fn recv(&mut self) -> BoxFut<'_, TransportResult<Option<Vec<u8>>>> {
285        Box::pin(async move {
286            loop {
287                match self.framer.next_frame() {
288                    Some(Ok(frame)) => return Ok(Some(frame)),
289                    // Line noise or a mid-stream join: skip it and resync on
290                    // the next frame.
291                    Some(Err(FrameFault::Recoverable)) => continue,
292                    // No boundary left to resync on: reading on would reinterpret
293                    // payload bytes as headers for the life of the connection.
294                    Some(Err(FrameFault::Fatal)) => {
295                        report(SessionEvent::ReceiveFramingFailed);
296                        return Err(TransportError::Framing);
297                    }
298                    None => {}
299                }
300                let mut chunk = [0u8; RC];
301                match self.stream.read(&mut chunk).await {
302                    Ok(0) => return Ok(None), // EOF — peer closed
303                    Ok(n) => self.framer.push_bytes(&chunk[..n]),
304                    Err(e) => return Err(e),
305                }
306            }
307        })
308    }
309
310    fn send<'a>(&'a mut self, frame: &'a [u8]) -> BoxFut<'a, TransportResult<()>> {
311        Box::pin(async move {
312            let mut out = Vec::new();
313            if let Err(_fault) = self.framer.encode(frame, &mut out) {
314                report(SessionEvent::SendFrameRejected {
315                    bytes: frame.len(),
316                    fault: _fault,
317                });
318                return Err(TransportError::Framing);
319            }
320            for chunk in out.chunks(WC) {
321                self.stream.write_all(chunk).await?;
322            }
323            self.stream.flush().await
324        })
325    }
326
327    fn peer(&self) -> &PeerInfo {
328        &self.peer
329    }
330}
331
332/// Lifts a [`StreamDialer`] and a [`FramerFactory`] into a [`Dialer`], so
333/// `run_client` drives an adapter transport unchanged.
334///
335/// `Clone` because `SessionClientConnector` clones its dialer per build.
336#[derive(Clone)]
337pub struct FramingDialer<D, FF, const RC: usize = 256, const WC: usize = 256> {
338    dialer: D,
339    framers: FF,
340    host: String,
341    port: u16,
342}
343
344impl<D, FF, const RC: usize, const WC: usize> FramingDialer<D, FF, RC, WC> {
345    /// Dial `host:port` through `dialer`, framing each stream with a framer
346    /// from `framers`.
347    pub fn new(dialer: D, framers: FF, host: impl Into<String>, port: u16) -> Self {
348        Self {
349            dialer,
350            framers,
351            host: host.into(),
352            port,
353        }
354    }
355}
356
357impl<D, FF, const RC: usize, const WC: usize> Dialer for FramingDialer<D, FF, RC, WC>
358where
359    D: StreamDialer + Send + Sync,
360    FF: FramerFactory + Send + Sync,
361    D::Stream: 'static,
362    FF::Framer: 'static,
363{
364    fn connect(&self) -> BoxFut<'_, TransportResult<Box<dyn Connection>>> {
365        Box::pin(async move {
366            let stream = self.dialer.connect(&self.host, self.port).await?;
367            let conn: FramedConnection<D::Stream, FF::Framer, RC, WC> =
368                FramedConnection::new(stream, self.framers.framer());
369            Ok(Box::new(conn) as Box<dyn Connection>)
370        })
371    }
372}
373
374/// Lifts a [`StreamListener`] and a [`FramerFactory`] into a [`Listener`], so
375/// `serve` drives an adapter transport unchanged.
376pub struct FramingListener<L, FF, const RC: usize = 256, const WC: usize = 256> {
377    listener: L,
378    framers: FF,
379}
380
381impl<L, FF, const RC: usize, const WC: usize> FramingListener<L, FF, RC, WC> {
382    /// Accept through `listener`, framing each stream with a framer from
383    /// `framers`.
384    pub fn new(listener: L, framers: FF) -> Self {
385        Self { listener, framers }
386    }
387}
388
389impl<L, FF, const RC: usize, const WC: usize> Listener for FramingListener<L, FF, RC, WC>
390where
391    L: StreamListener + Send,
392    FF: FramerFactory + Send,
393    L::Stream: 'static,
394    FF::Framer: 'static,
395{
396    fn accept(&mut self) -> BoxFut<'_, TransportResult<Box<dyn Connection>>> {
397        Box::pin(async move {
398            let (stream, peer) = self.listener.accept().await?;
399            let conn: FramedConnection<L::Stream, FF::Framer, RC, WC> =
400                FramedConnection::with_peer(stream, self.framers.framer(), peer);
401            Ok(Box::new(conn) as Box<dyn Connection>)
402        })
403    }
404}
405
406// ===========================================================================
407// Moved-in resources.
408// ===========================================================================
409
410/// A cell holding a resource until something takes it, once.
411///
412/// `ConnectorBuilder` is `Send + Sync` and its `build` takes `&self`, so a
413/// connector holding a moved-in listener, peripheral or credential set must
414/// take it through interior mutability. `spin::Mutex<Option<T>>` is
415/// `Send + Sync` whenever `T: Send`, with no `unsafe`.
416///
417/// The `T: Send` bound is the contract: a type that is not `Send` cannot be
418/// held here, and that refusal is the signal to fix the type rather than to
419/// reach for `unsafe impl`.
420pub struct OneShot<T> {
421    inner: spin::Mutex<Option<T>>,
422}
423
424impl<T> OneShot<T> {
425    /// Hold `value` for a single [`take`](Self::take).
426    pub fn new(value: T) -> Self {
427        Self {
428            inner: spin::Mutex::new(Some(value)),
429        }
430    }
431
432    /// Take the value, or `None` if it was already taken.
433    pub fn take(&self) -> Option<T> {
434        self.inner.lock().take()
435    }
436}
437
438impl<T> Default for OneShot<T> {
439    /// An already-empty cell, for a resource that may never be supplied.
440    fn default() -> Self {
441        Self {
442            inner: spin::Mutex::new(None),
443        }
444    }
445}
446
447impl<T> From<T> for OneShot<T> {
448    fn from(value: T) -> Self {
449        Self::new(value)
450    }
451}
452
453/// Hands out one pre-built connection, then refuses.
454///
455/// The [`Dialer`] a point-to-point transport wants: a moved-in UART, pipe or
456/// socket has nothing to redial, so the second attempt is
457/// [`TransportError::Closed`] — which [`run_client`](super::run_client) treats
458/// as terminal — rather than a silent reconnect loop.
459pub struct OneShotDialer<C> {
460    conn: OneShot<C>,
461}
462
463impl<C> OneShotDialer<C> {
464    /// Hold `conn` for the first [`connect`](Dialer::connect).
465    pub fn new(conn: C) -> Self {
466        Self {
467            conn: OneShot::new(conn),
468        }
469    }
470}
471
472impl<C: Connection + 'static> Dialer for OneShotDialer<C> {
473    fn connect(&self) -> BoxFut<'_, TransportResult<Box<dyn Connection>>> {
474        Box::pin(async move {
475            self.conn
476                .take()
477                .map(|c| Box::new(c) as Box<dyn Connection>)
478                .ok_or(TransportError::Closed)
479        })
480    }
481}
482
483/// Hands out one pre-built connection, then parks forever.
484///
485/// The [`Listener`] dual of [`OneShotDialer`]: [`serve`](super::serve) loops on
486/// `accept`, and a point-to-point link has no second peer, so parking is the
487/// correct end state rather than an error the loop would spin on.
488pub struct OneShotListener<C> {
489    conn: OneShot<C>,
490}
491
492impl<C> OneShotListener<C> {
493    /// Hold `conn` for the first [`accept`](Listener::accept).
494    pub fn new(conn: C) -> Self {
495        Self {
496            conn: OneShot::new(conn),
497        }
498    }
499}
500
501impl<C: Connection + 'static> Listener for OneShotListener<C> {
502    fn accept(&mut self) -> BoxFut<'_, TransportResult<Box<dyn Connection>>> {
503        Box::pin(async move {
504            match self.conn.take() {
505                Some(c) => Ok(Box::new(c) as Box<dyn Connection>),
506                None => core::future::pending().await,
507            }
508        })
509    }
510}
511
512// ===========================================================================
513// Compile-time assertions.
514// ===========================================================================
515
516/// Generic code over these traits produces `Send` futures, so a connector task
517/// built from them boxes as the runner requires. Drop a `+ Send` from any
518/// return type above and this stops compiling.
519#[allow(dead_code)]
520fn _generic_code_over_the_traits_is_send<D, L, B, T>(
521    dialer: D,
522    mut listener: L,
523    binder: B,
524    delay: T,
525) -> BoxFut<'static, ()>
526where
527    D: StreamDialer + Send + 'static,
528    L: StreamListener + Send + 'static,
529    B: DatagramBinder + Send + 'static,
530    T: Delay + Send + 'static,
531{
532    Box::pin(async move {
533        let mut buf = [0u8; 16];
534
535        if let Ok(mut stream) = dialer.connect("example.test", 1883).await {
536            let _ = stream.read(&mut buf).await;
537            let _ = stream.write_all(&buf).await;
538            let _ = stream.flush().await;
539        }
540        if let Ok((mut stream, _peer)) = listener.accept().await {
541            let _ = stream.read(&mut buf).await;
542        }
543        if let Ok(mut socket) = binder.bind(0).await {
544            let _ = socket.recv_from(&mut buf).await;
545            let _ = socket.local_addr();
546        }
547        delay.sleep(core::time::Duration::from_millis(1)).await;
548    })
549}
550
551/// `OneShot<T>` is `Send + Sync` for any `T: Send`, with no `unsafe`.
552#[allow(dead_code)]
553fn _one_shot_is_send_sync_without_unsafe() {
554    fn assert_send_sync<T: Send + Sync>() {}
555    assert_send_sync::<OneShot<Vec<u8>>>();
556}
557
558#[cfg(test)]
559mod tests {
560    use super::*;
561    use alloc::sync::Arc;
562    use alloc::vec;
563
564    // --- Test doubles -----------------------------------------------------
565
566    /// Length-prefixed framer: one length byte, then that many payload bytes.
567    /// A `0xFF` length marks a corrupt run, so resync has something to skip;
568    /// `0xFE` marks an unrecoverable one. A frame too long for the one-byte
569    /// length is rejected by `encode`.
570    #[derive(Default)]
571    struct LenFramer {
572        buf: Vec<u8>,
573    }
574
575    impl Framer for LenFramer {
576        fn encode(&self, frame: &[u8], out: &mut Vec<u8>) -> Result<(), FrameFault> {
577            if frame.len() >= 0xFE {
578                return Err(FrameFault::Recoverable);
579            }
580            out.push(frame.len() as u8);
581            out.extend_from_slice(frame);
582            Ok(())
583        }
584        fn push_bytes(&mut self, bytes: &[u8]) {
585            self.buf.extend_from_slice(bytes);
586        }
587        fn next_frame(&mut self) -> Option<Result<Vec<u8>, FrameFault>> {
588            let len = *self.buf.first()? as usize;
589            if len == 0xFF {
590                self.buf.remove(0);
591                return Some(Err(FrameFault::Recoverable));
592            }
593            if len == 0xFE {
594                self.buf.clear();
595                return Some(Err(FrameFault::Fatal));
596            }
597            if self.buf.len() < len + 1 {
598                return None;
599            }
600            let frame = self.buf[1..len + 1].to_vec();
601            self.buf.drain(..len + 1);
602            Some(Ok(frame))
603        }
604    }
605
606    /// Shared so a test can inspect what the connection wrote after moving the
607    /// stream into it.
608    #[derive(Default)]
609    struct StreamState {
610        /// Chunks `read` hands out, in order; empty means EOF.
611        reads: Vec<Vec<u8>>,
612        /// Bytes written, concatenated.
613        written: Vec<u8>,
614        /// Size of each individual `write_all` call.
615        write_sizes: Vec<usize>,
616        flushes: usize,
617    }
618
619    #[derive(Clone, Default)]
620    struct MockStream(Arc<spin::Mutex<StreamState>>);
621
622    impl MockStream {
623        fn with_reads(reads: Vec<Vec<u8>>) -> Self {
624            Self(Arc::new(spin::Mutex::new(StreamState {
625                reads,
626                ..Default::default()
627            })))
628        }
629    }
630
631    // Written as plain `async fn`s: an impl on a runtime whose futures are
632    // already `Send` needs nothing more, and the compiler checks the bound the
633    // trait declares.
634    impl ByteStream for MockStream {
635        async fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> TransportResult<usize> {
636            let mut st = self.0.lock();
637            if st.reads.is_empty() {
638                return Ok(0);
639            }
640            let chunk = st.reads.remove(0);
641            let n = chunk.len().min(buf.len());
642            buf[..n].copy_from_slice(&chunk[..n]);
643            Ok(n)
644        }
645
646        async fn write_all<'a>(&'a mut self, buf: &'a [u8]) -> TransportResult<()> {
647            let mut st = self.0.lock();
648            st.written.extend_from_slice(buf);
649            st.write_sizes.push(buf.len());
650            Ok(())
651        }
652
653        async fn flush(&mut self) -> TransportResult<()> {
654            self.0.lock().flushes += 1;
655            Ok(())
656        }
657
658        fn split(&mut self) -> (impl ByteRead + Send + '_, impl ByteWrite + Send + '_) {
659            (MockHalf(self.clone()), MockHalf(self.clone()))
660        }
661    }
662
663    /// Either half of a split [`MockStream`]. The mock is already a shared
664    /// handle, so a half is just a clone of it.
665    struct MockHalf(MockStream);
666
667    impl ByteRead for MockHalf {
668        async fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> TransportResult<usize> {
669            ByteStream::read(&mut self.0, buf).await
670        }
671    }
672
673    impl ByteWrite for MockHalf {
674        async fn write_all<'a>(&'a mut self, buf: &'a [u8]) -> TransportResult<()> {
675            ByteStream::write_all(&mut self.0, buf).await
676        }
677
678        async fn flush(&mut self) -> TransportResult<()> {
679            ByteStream::flush(&mut self.0).await
680        }
681    }
682
683    /// A stream whose first read fails, to check the error is propagated as-is
684    /// rather than flattened.
685    struct FailingStream;
686
687    impl ByteStream for FailingStream {
688        async fn read<'a>(&'a mut self, _buf: &'a mut [u8]) -> TransportResult<usize> {
689            Err(TransportError::Closed)
690        }
691        async fn write_all<'a>(&'a mut self, _buf: &'a [u8]) -> TransportResult<()> {
692            Err(TransportError::Closed)
693        }
694        async fn flush(&mut self) -> TransportResult<()> {
695            Ok(())
696        }
697        fn split(&mut self) -> (impl ByteRead + Send + '_, impl ByteWrite + Send + '_) {
698            (FailingHalf, FailingHalf)
699        }
700    }
701
702    /// Either half of a split [`FailingStream`].
703    struct FailingHalf;
704
705    impl ByteRead for FailingHalf {
706        async fn read<'a>(&'a mut self, _buf: &'a mut [u8]) -> TransportResult<usize> {
707            Err(TransportError::Closed)
708        }
709    }
710
711    impl ByteWrite for FailingHalf {
712        async fn write_all<'a>(&'a mut self, _buf: &'a [u8]) -> TransportResult<()> {
713            Err(TransportError::Closed)
714        }
715
716        async fn flush(&mut self) -> TransportResult<()> {
717            Ok(())
718        }
719    }
720
721    /// A stream whose read cannot finish until its write half has run, so a
722    /// blocked reader that blocked the writer would deadlock the test.
723    #[derive(Clone, Default)]
724    struct DuplexMock {
725        written: Arc<spin::Mutex<Vec<u8>>>,
726        wrote: Arc<tokio::sync::Notify>,
727    }
728
729    impl ByteStream for DuplexMock {
730        async fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> TransportResult<usize> {
731            self.wrote.notified().await;
732            let written = self.written.lock();
733            let n = written.len().min(buf.len());
734            buf[..n].copy_from_slice(&written[..n]);
735            Ok(n)
736        }
737
738        async fn write_all<'a>(&'a mut self, buf: &'a [u8]) -> TransportResult<()> {
739            self.written.lock().extend_from_slice(buf);
740            self.wrote.notify_one();
741            Ok(())
742        }
743
744        async fn flush(&mut self) -> TransportResult<()> {
745            Ok(())
746        }
747
748        fn split(&mut self) -> (impl ByteRead + Send + '_, impl ByteWrite + Send + '_) {
749            (DuplexHalf(self.clone()), DuplexHalf(self.clone()))
750        }
751    }
752
753    /// Either half of a split [`DuplexMock`].
754    struct DuplexHalf(DuplexMock);
755
756    impl ByteRead for DuplexHalf {
757        async fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> TransportResult<usize> {
758            ByteStream::read(&mut self.0, buf).await
759        }
760    }
761
762    impl ByteWrite for DuplexHalf {
763        async fn write_all<'a>(&'a mut self, buf: &'a [u8]) -> TransportResult<()> {
764            ByteStream::write_all(&mut self.0, buf).await
765        }
766
767        async fn flush(&mut self) -> TransportResult<()> {
768            ByteStream::flush(&mut self.0).await
769        }
770    }
771
772    struct MockDialer(MockStream);
773
774    impl StreamDialer for MockDialer {
775        type Stream = MockStream;
776        async fn connect<'a>(&'a self, _host: &'a str, _port: u16) -> TransportResult<MockStream> {
777            Ok(self.0.clone())
778        }
779    }
780
781    struct MockListener(Option<MockStream>);
782
783    impl StreamListener for MockListener {
784        type Stream = MockStream;
785        async fn accept(&mut self) -> TransportResult<(MockStream, PeerInfo)> {
786            let s = self.0.take().ok_or(TransportError::Closed)?;
787            let peer = PeerInfo {
788                peer_addr: Some("10.0.0.1:5555".into()),
789                ..Default::default()
790            };
791            Ok((s, peer))
792        }
793    }
794
795    fn framed(stream: MockStream) -> FramedConnection<MockStream, LenFramer, 256, 256> {
796        FramedConnection::new(stream, LenFramer::default())
797    }
798
799    // --- FramedConnection -------------------------------------------------
800
801    #[tokio::test]
802    async fn recv_yields_each_frame_then_eof() {
803        let mut conn = framed(MockStream::with_reads(vec![vec![
804            2, b'h', b'i', 3, b'y', b'e', b's',
805        ]]));
806        assert_eq!(conn.recv().await.unwrap(), Some(b"hi".to_vec()));
807        assert_eq!(conn.recv().await.unwrap(), Some(b"yes".to_vec()));
808        assert_eq!(conn.recv().await.unwrap(), None, "closed peer is Ok(None)");
809    }
810
811    #[tokio::test]
812    async fn recv_reassembles_a_frame_split_across_reads() {
813        let mut conn = framed(MockStream::with_reads(vec![
814            vec![3, b'a'],
815            vec![b'b'],
816            vec![b'c'],
817        ]));
818        assert_eq!(conn.recv().await.unwrap(), Some(b"abc".to_vec()));
819    }
820
821    #[tokio::test]
822    async fn recv_skips_a_corrupt_run_and_resyncs() {
823        let mut conn = framed(MockStream::with_reads(vec![vec![
824            0xFF, 0xFF, 2, b'o', b'k',
825        ]]));
826        assert_eq!(
827            conn.recv().await.unwrap(),
828            Some(b"ok".to_vec()),
829            "a run that fails to decode is skipped, not fatal"
830        );
831    }
832
833    #[tokio::test]
834    async fn recv_closes_on_an_unrecoverable_framing_error() {
835        // The bytes after the bad header are unreadable, so the connection ends
836        // rather than reinterpreting them as the next header forever.
837        let mut conn = framed(MockStream::with_reads(vec![vec![0xFE, 2, b'o', b'k']]));
838        #[cfg(feature = "std")]
839        let received = Arc::new(core::sync::atomic::AtomicBool::new(false));
840        #[cfg(feature = "std")]
841        let result = crate::session::events::capture::future(
842            {
843                let received = received.clone();
844                Arc::new(move |event| {
845                    assert!(matches!(event, SessionEvent::ReceiveFramingFailed));
846                    received.store(true, core::sync::atomic::Ordering::Relaxed);
847                })
848            },
849            conn.recv(),
850        )
851        .await;
852        #[cfg(not(feature = "std"))]
853        let result = conn.recv().await;
854        #[cfg(feature = "std")]
855        assert!(received.load(core::sync::atomic::Ordering::Relaxed));
856        assert_eq!(
857            result,
858            Err(TransportError::Framing),
859            "a fatal fault ends the connection, it is not skipped"
860        );
861    }
862
863    #[tokio::test]
864    async fn send_reports_a_frame_the_framer_rejects() {
865        let stream = MockStream::default();
866        let mut conn = framed(stream.clone());
867        let oversized = vec![b'x'; 0xFE];
868
869        #[cfg(feature = "std")]
870        let received = Arc::new(core::sync::atomic::AtomicBool::new(false));
871        #[cfg(feature = "std")]
872        let result = crate::session::events::capture::future(
873            {
874                let received = received.clone();
875                Arc::new(move |event| {
876                    assert!(matches!(
877                        event,
878                        SessionEvent::SendFrameRejected {
879                            bytes: 0xFE,
880                            fault: FrameFault::Recoverable
881                        }
882                    ));
883                    received.store(true, core::sync::atomic::Ordering::Relaxed);
884                })
885            },
886            conn.send(&oversized),
887        )
888        .await;
889        #[cfg(not(feature = "std"))]
890        let result = conn.send(&oversized).await;
891        #[cfg(feature = "std")]
892        assert!(received.load(core::sync::atomic::Ordering::Relaxed));
893        assert_eq!(
894            result,
895            Err(TransportError::Framing),
896            "a dropped frame is an error, never a silent Ok"
897        );
898        let st = stream.0.lock();
899        assert!(
900            st.written.is_empty(),
901            "nothing half-encoded reaches the wire"
902        );
903        assert_eq!(st.flushes, 0);
904    }
905
906    #[tokio::test]
907    async fn recv_propagates_the_streams_own_error() {
908        let mut conn = FramedConnection::<_, _, 256, 256>::new(FailingStream, LenFramer::default());
909        assert_eq!(
910            conn.recv().await,
911            Err(TransportError::Closed),
912            "the stream classifies the failure; framing must not flatten it"
913        );
914    }
915
916    #[tokio::test]
917    async fn send_encodes_then_flushes() {
918        let stream = MockStream::default();
919        let mut conn = framed(stream.clone());
920        conn.send(b"hi").await.unwrap();
921
922        let st = stream.0.lock();
923        assert_eq!(st.written, vec![2, b'h', b'i']);
924        assert_eq!(st.flushes, 1);
925    }
926
927    #[tokio::test]
928    async fn send_splits_a_frame_larger_than_the_write_chunk() {
929        let stream = MockStream::default();
930        let mut conn: FramedConnection<MockStream, LenFramer, 256, 4> =
931            FramedConnection::new(stream.clone(), LenFramer::default());
932        conn.send(b"0123456789").await.unwrap();
933
934        let st = stream.0.lock();
935        assert_eq!(st.write_sizes, vec![4, 4, 3], "11 encoded bytes at WC = 4");
936        assert_eq!(st.written.len(), 11);
937    }
938
939    // --- FramingDialer / FramingListener ----------------------------------
940
941    #[tokio::test]
942    async fn framing_dialer_produces_a_working_connection() {
943        let stream = MockStream::with_reads(vec![vec![2, b'h', b'i']]);
944        let dialer: FramingDialer<_, _, 256, 256> =
945            FramingDialer::new(MockDialer(stream), LenFramer::default, "host.test", 1883);
946
947        let mut conn = dialer.connect().await.unwrap();
948        assert_eq!(conn.recv().await.unwrap(), Some(b"hi".to_vec()));
949    }
950
951    #[tokio::test]
952    async fn framing_listener_carries_peer_metadata_through() {
953        let stream = MockStream::with_reads(vec![vec![2, b'h', b'i']]);
954        let mut listener: FramingListener<_, _, 256, 256> =
955            FramingListener::new(MockListener(Some(stream)), LenFramer::default);
956
957        let mut conn = listener.accept().await.unwrap();
958        assert_eq!(conn.peer().peer_addr.as_deref(), Some("10.0.0.1:5555"));
959        assert_eq!(conn.recv().await.unwrap(), Some(b"hi".to_vec()));
960    }
961
962    #[test]
963    fn a_framed_connection_is_boxable_as_dyn_connection() {
964        let conn = framed(MockStream::default());
965        let _boxed: Box<dyn Connection> = Box::new(conn);
966    }
967
968    // --- ByteStream::split ------------------------------------------------
969
970    #[tokio::test]
971    async fn split_halves_run_concurrently() {
972        let mut stream = DuplexMock::default();
973        let (mut rx, mut tx) = stream.split();
974
975        // The read cannot complete until the write has run, so this joining at
976        // all is the assertion: both halves were live at the same time.
977        let mut buf = [0u8; 4];
978        let (read, write) = tokio::join!(rx.read(&mut buf), tx.write_all(b"ping"));
979
980        write.expect("write half");
981        assert_eq!(read.expect("read half"), 4);
982        assert_eq!(&buf, b"ping");
983    }
984
985    #[tokio::test]
986    async fn split_halves_address_the_same_stream() {
987        let stream = MockStream::with_reads(vec![b"hi".to_vec()]);
988        let mut split_me = stream.clone();
989        let (mut rx, mut tx) = split_me.split();
990
991        tx.write_all(b"out").await.expect("write half");
992        let mut buf = [0u8; 8];
993        let n = rx.read(&mut buf).await.expect("read half");
994
995        assert_eq!(&buf[..n], b"hi", "the read half drains the stream's reads");
996        assert_eq!(
997            stream.0.lock().written,
998            b"out",
999            "the write half reaches the stream the halves came from"
1000        );
1001    }
1002
1003    // --- OneShot / FramerFactory ------------------------------------------
1004
1005    #[test]
1006    fn one_shot_yields_its_value_once() {
1007        let cell = OneShot::new(7u32);
1008        assert_eq!(cell.take(), Some(7));
1009        assert_eq!(cell.take(), None, "a second take must not get the resource");
1010    }
1011
1012    #[test]
1013    fn default_one_shot_is_empty() {
1014        assert_eq!(OneShot::<u32>::default().take(), None);
1015    }
1016
1017    #[test]
1018    fn framer_factory_is_implemented_for_closures() {
1019        struct Noop;
1020        impl Framer for Noop {
1021            fn encode(&self, _frame: &[u8], _out: &mut Vec<u8>) -> Result<(), FrameFault> {
1022                Ok(())
1023            }
1024            fn push_bytes(&mut self, _bytes: &[u8]) {}
1025            fn next_frame(&mut self) -> Option<Result<Vec<u8>, FrameFault>> {
1026                None
1027            }
1028        }
1029
1030        fn takes_factory<FF: FramerFactory>(ff: FF) -> FF::Framer {
1031            ff.framer()
1032        }
1033        let _framer = takes_factory(|| Noop);
1034    }
1035}