Skip to main content

dcp/multiplex/
connection.rs

1//! Multiplexed connection implementation.
2//!
3//! Provides concurrent stream processing over a single connection.
4
5use bytes::{Bytes, BytesMut};
6use std::collections::{HashMap, VecDeque};
7use std::sync::atomic::{AtomicU16, AtomicU64, Ordering};
8use std::sync::Arc;
9use thiserror::Error;
10use tokio::sync::{Mutex, RwLock};
11
12use super::header::{StreamFlags, StreamHeader, STREAM_HEADER_SIZE};
13
14/// Maximum concurrent streams per connection
15pub const MAX_STREAMS: u16 = 65535;
16
17/// Default maximum queued outbound frames per connection.
18pub const DEFAULT_MAX_SEND_QUEUE_LEN: usize = 1024;
19
20/// Default window size for flow control
21pub const DEFAULT_WINDOW_SIZE: u32 = 65536;
22
23/// Default maximum unread received bytes per stream.
24pub const DEFAULT_MAX_RECV_BUFFER_BYTES: usize = DEFAULT_WINDOW_SIZE as usize;
25
26/// Multiplexing errors
27#[derive(Debug, Clone, Error, PartialEq, Eq)]
28pub enum MultiplexError {
29    #[error("stream not found: {0}")]
30    StreamNotFound(u16),
31    #[error("stream already exists: {0}")]
32    StreamAlreadyExists(u16),
33    #[error("stream closed: {0}")]
34    StreamClosed(u16),
35    #[error("too many streams")]
36    TooManyStreams,
37    #[error("invalid stream id")]
38    InvalidStreamId,
39    #[error("connection closed")]
40    ConnectionClosed,
41    #[error("send buffer full")]
42    SendBufferFull,
43    #[error("receive buffer full")]
44    ReceiveBufferFull,
45    #[error("stream error: {0}")]
46    StreamError(u16),
47    #[error("protocol error: {0}")]
48    ProtocolError(String),
49}
50
51/// Stream status
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum StreamStatus {
54    /// Stream is open for both sending and receiving
55    Open,
56    /// Local side has sent FIN, waiting for remote FIN
57    HalfClosedLocal,
58    /// Remote side has sent FIN, can still send
59    HalfClosedRemote,
60    /// Stream is fully closed
61    Closed,
62    /// Stream was reset due to error
63    Reset,
64}
65
66impl StreamStatus {
67    /// Check if stream can send data
68    pub fn can_send(&self) -> bool {
69        matches!(self, StreamStatus::Open | StreamStatus::HalfClosedRemote)
70    }
71
72    /// Check if stream can receive data
73    pub fn can_receive(&self) -> bool {
74        matches!(self, StreamStatus::Open | StreamStatus::HalfClosedLocal)
75    }
76
77    /// Check if stream is fully closed
78    pub fn is_closed(&self) -> bool {
79        matches!(self, StreamStatus::Closed | StreamStatus::Reset)
80    }
81}
82
83/// Stream state
84pub struct StreamState {
85    /// Stream ID
86    pub id: u16,
87    /// Current status
88    pub status: StreamStatus,
89    /// Send buffer
90    pub send_buffer: VecDeque<Bytes>,
91    /// Receive buffer
92    pub recv_buffer: VecDeque<Bytes>,
93    /// Number of unread bytes in the receive buffer
94    recv_buffered_bytes: usize,
95    /// Flow control window size
96    pub window_size: u32,
97    /// Bytes sent
98    pub bytes_sent: AtomicU64,
99    /// Bytes received
100    pub bytes_received: AtomicU64,
101    /// Error message if stream was reset
102    pub error: Option<String>,
103}
104
105impl StreamState {
106    /// Create a new stream state
107    pub fn new(id: u16) -> Self {
108        Self {
109            id,
110            status: StreamStatus::Open,
111            send_buffer: VecDeque::new(),
112            recv_buffer: VecDeque::new(),
113            recv_buffered_bytes: 0,
114            window_size: DEFAULT_WINDOW_SIZE,
115            bytes_sent: AtomicU64::new(0),
116            bytes_received: AtomicU64::new(0),
117            error: None,
118        }
119    }
120
121    /// Queue data for sending
122    pub fn queue_send(&mut self, data: Bytes) -> Result<(), MultiplexError> {
123        if !self.status.can_send() {
124            return Err(MultiplexError::StreamClosed(self.id));
125        }
126        self.send_buffer.push_back(data);
127        Ok(())
128    }
129
130    /// Queue received data
131    pub fn queue_recv(
132        &mut self,
133        data: Bytes,
134        max_recv_buffer_bytes: usize,
135    ) -> Result<(), MultiplexError> {
136        if !self.status.can_receive() {
137            return Err(MultiplexError::StreamClosed(self.id));
138        }
139        let next_buffered = self.recv_buffered_bytes.saturating_add(data.len());
140        if next_buffered > max_recv_buffer_bytes {
141            return Err(MultiplexError::ReceiveBufferFull);
142        }
143        self.bytes_received
144            .fetch_add(data.len() as u64, Ordering::Relaxed);
145        self.recv_buffered_bytes = next_buffered;
146        self.recv_buffer.push_back(data);
147        Ok(())
148    }
149
150    /// Take next data from send buffer
151    pub fn take_send(&mut self) -> Option<Bytes> {
152        let data = self.send_buffer.pop_front()?;
153        self.bytes_sent
154            .fetch_add(data.len() as u64, Ordering::Relaxed);
155        Some(data)
156    }
157
158    /// Take next data from receive buffer
159    pub fn take_recv(&mut self) -> Option<Bytes> {
160        let data = self.recv_buffer.pop_front()?;
161        self.recv_buffered_bytes = self.recv_buffered_bytes.saturating_sub(data.len());
162        Some(data)
163    }
164
165    /// Close local side of stream
166    pub fn close_local(&mut self) {
167        self.status = match self.status {
168            StreamStatus::Open => StreamStatus::HalfClosedLocal,
169            StreamStatus::HalfClosedRemote => StreamStatus::Closed,
170            other => other,
171        };
172    }
173
174    /// Close remote side of stream
175    pub fn close_remote(&mut self) {
176        self.status = match self.status {
177            StreamStatus::Open => StreamStatus::HalfClosedRemote,
178            StreamStatus::HalfClosedLocal => StreamStatus::Closed,
179            other => other,
180        };
181    }
182
183    /// Reset stream with error
184    pub fn reset(&mut self, error: Option<String>) {
185        self.status = StreamStatus::Reset;
186        self.error = error;
187        self.send_buffer.clear();
188        // Keep recv_buffer so pending reads can see the error
189    }
190}
191
192/// Multiplexed connection supporting concurrent streams
193pub struct MultiplexedConnection {
194    /// Active streams
195    streams: RwLock<HashMap<u16, Arc<Mutex<StreamState>>>>,
196    /// Stream ID counter (starts at 1, 0 is control)
197    next_stream_id: AtomicU16,
198    /// Connection-level send buffer
199    send_queue: Mutex<VecDeque<(StreamHeader, Bytes)>>,
200    /// Maximum queued outbound frames per connection
201    max_send_queue_len: usize,
202    /// Maximum unread received bytes per stream
203    max_recv_buffer_bytes: usize,
204    /// Whether connection is closed
205    closed: std::sync::atomic::AtomicBool,
206    /// Total bytes sent
207    bytes_sent: AtomicU64,
208    /// Total bytes received
209    bytes_received: AtomicU64,
210    /// Stream count
211    stream_count: AtomicU16,
212}
213
214impl MultiplexedConnection {
215    /// Create a new multiplexed connection
216    pub fn new() -> Self {
217        Self::with_limits(DEFAULT_MAX_SEND_QUEUE_LEN, DEFAULT_MAX_RECV_BUFFER_BYTES)
218    }
219
220    /// Create a new multiplexed connection with a bounded outbound frame queue.
221    pub fn with_max_send_queue_len(max_send_queue_len: usize) -> Self {
222        Self::with_limits(max_send_queue_len, DEFAULT_MAX_RECV_BUFFER_BYTES)
223    }
224
225    /// Create a new multiplexed connection with a bounded receive buffer.
226    pub fn with_max_recv_buffer_bytes(max_recv_buffer_bytes: usize) -> Self {
227        Self::with_limits(DEFAULT_MAX_SEND_QUEUE_LEN, max_recv_buffer_bytes)
228    }
229
230    /// Create a new multiplexed connection with explicit transport limits.
231    pub fn with_limits(max_send_queue_len: usize, max_recv_buffer_bytes: usize) -> Self {
232        Self {
233            streams: RwLock::new(HashMap::new()),
234            next_stream_id: AtomicU16::new(1),
235            send_queue: Mutex::new(VecDeque::new()),
236            max_send_queue_len,
237            max_recv_buffer_bytes,
238            closed: std::sync::atomic::AtomicBool::new(false),
239            bytes_sent: AtomicU64::new(0),
240            bytes_received: AtomicU64::new(0),
241            stream_count: AtomicU16::new(0),
242        }
243    }
244
245    /// Check if connection is closed
246    pub fn is_closed(&self) -> bool {
247        self.closed.load(Ordering::SeqCst)
248    }
249
250    /// Get current stream count
251    pub fn stream_count(&self) -> u16 {
252        self.stream_count.load(Ordering::Relaxed)
253    }
254
255    /// Open a new stream
256    pub async fn open_stream(&self) -> Result<u16, MultiplexError> {
257        if self.is_closed() {
258            return Err(MultiplexError::ConnectionClosed);
259        }
260
261        // Check stream limit
262        if self.stream_count() >= MAX_STREAMS {
263            return Err(MultiplexError::TooManyStreams);
264        }
265
266        // Allocate stream ID
267        let mut stream_id = self.next_stream_id.fetch_add(1, Ordering::SeqCst);
268        if stream_id == 0 {
269            // Wrapped around, skip 0 (control stream)
270            stream_id = self.next_stream_id.fetch_add(1, Ordering::SeqCst);
271            if stream_id == 0 {
272                return Err(MultiplexError::TooManyStreams);
273            }
274        }
275
276        // Create stream state
277        let state = Arc::new(Mutex::new(StreamState::new(stream_id)));
278
279        // Register stream
280        {
281            let mut streams = self.streams.write().await;
282            if streams.contains_key(&stream_id) {
283                return Err(MultiplexError::StreamAlreadyExists(stream_id));
284            }
285            streams.insert(stream_id, state);
286        }
287
288        self.stream_count.fetch_add(1, Ordering::Relaxed);
289
290        // Queue SYN
291        if let Err(error) = self
292            .queue_frame(StreamHeader::syn(stream_id), Bytes::new())
293            .await
294        {
295            self.streams.write().await.remove(&stream_id);
296            self.stream_count.fetch_sub(1, Ordering::Relaxed);
297            return Err(error);
298        }
299
300        Ok(stream_id)
301    }
302
303    /// Accept an incoming stream (called when receiving SYN)
304    pub async fn accept_stream(&self, stream_id: u16) -> Result<(), MultiplexError> {
305        if self.is_closed() {
306            return Err(MultiplexError::ConnectionClosed);
307        }
308
309        if stream_id == StreamHeader::CONTROL_STREAM {
310            return Err(MultiplexError::InvalidStreamId);
311        }
312
313        // Check stream limit
314        if self.stream_count() >= MAX_STREAMS {
315            return Err(MultiplexError::TooManyStreams);
316        }
317
318        // Create stream state
319        let state = Arc::new(Mutex::new(StreamState::new(stream_id)));
320
321        // Register stream
322        {
323            let mut streams = self.streams.write().await;
324            if streams.contains_key(&stream_id) {
325                return Err(MultiplexError::StreamAlreadyExists(stream_id));
326            }
327            streams.insert(stream_id, state);
328        }
329
330        self.stream_count.fetch_add(1, Ordering::Relaxed);
331
332        // Queue ACK
333        if let Err(error) = self
334            .queue_frame(StreamHeader::ack(stream_id), Bytes::new())
335            .await
336        {
337            self.streams.write().await.remove(&stream_id);
338            self.stream_count.fetch_sub(1, Ordering::Relaxed);
339            return Err(error);
340        }
341
342        Ok(())
343    }
344
345    /// Send data on a stream
346    pub async fn send(&self, stream_id: u16, data: Bytes) -> Result<(), MultiplexError> {
347        if self.is_closed() {
348            return Err(MultiplexError::ConnectionClosed);
349        }
350
351        // Get stream
352        let stream = {
353            let streams = self.streams.read().await;
354            streams
355                .get(&stream_id)
356                .cloned()
357                .ok_or(MultiplexError::StreamNotFound(stream_id))?
358        };
359
360        // Queue data in stream
361        {
362            let mut state = stream.lock().await;
363            state.queue_send(data.clone())?;
364        }
365
366        // Queue frame for sending
367        let header = StreamHeader::data(stream_id, data.len() as u32);
368        if let Err(error) = self.queue_frame(header, data).await {
369            let mut state = stream.lock().await;
370            state.send_buffer.pop_back();
371            return Err(error);
372        }
373
374        Ok(())
375    }
376
377    /// Receive data from a stream
378    pub async fn recv(&self, stream_id: u16) -> Result<Option<Bytes>, MultiplexError> {
379        if self.is_closed() {
380            return Err(MultiplexError::ConnectionClosed);
381        }
382
383        // Get stream
384        let stream = {
385            let streams = self.streams.read().await;
386            streams
387                .get(&stream_id)
388                .cloned()
389                .ok_or(MultiplexError::StreamNotFound(stream_id))?
390        };
391
392        // Take data from receive buffer
393        let mut state = stream.lock().await;
394
395        // Check for error
396        if state.status == StreamStatus::Reset {
397            return Err(MultiplexError::StreamError(stream_id));
398        }
399
400        Ok(state.take_recv())
401    }
402
403    /// Close a stream gracefully
404    pub async fn close_stream(&self, stream_id: u16) -> Result<(), MultiplexError> {
405        // Get stream
406        let stream = {
407            let streams = self.streams.read().await;
408            streams
409                .get(&stream_id)
410                .cloned()
411                .ok_or(MultiplexError::StreamNotFound(stream_id))?
412        };
413
414        // Mark local side as closed
415        {
416            let mut state = stream.lock().await;
417            state.close_local();
418        }
419
420        // Queue FIN
421        self.queue_frame(StreamHeader::fin(stream_id), Bytes::new())
422            .await?;
423
424        Ok(())
425    }
426
427    /// Reset a stream with error
428    pub async fn reset_stream(
429        &self,
430        stream_id: u16,
431        error: Option<String>,
432    ) -> Result<(), MultiplexError> {
433        // Get stream
434        let stream = {
435            let streams = self.streams.read().await;
436            streams
437                .get(&stream_id)
438                .cloned()
439                .ok_or(MultiplexError::StreamNotFound(stream_id))?
440        };
441
442        // Reset stream
443        {
444            let mut state = stream.lock().await;
445            state.reset(error);
446        }
447
448        // Queue RST
449        self.queue_frame(StreamHeader::rst(stream_id), Bytes::new())
450            .await?;
451
452        Ok(())
453    }
454
455    /// Process an incoming frame
456    pub async fn process_frame(
457        &self,
458        header: StreamHeader,
459        payload: Bytes,
460    ) -> Result<(), MultiplexError> {
461        if self.is_closed() {
462            return Err(MultiplexError::ConnectionClosed);
463        }
464
465        self.bytes_received.fetch_add(
466            (STREAM_HEADER_SIZE + payload.len()) as u64,
467            Ordering::Relaxed,
468        );
469
470        if header.length as usize != payload.len() {
471            return Err(MultiplexError::ProtocolError(
472                "frame length mismatch".to_string(),
473            ));
474        }
475        Self::validate_frame_shape(&header, payload.len())?;
476
477        // Handle control stream
478        if header.is_control() {
479            return self.process_control_frame(header, payload).await;
480        }
481
482        // Handle SYN (new stream)
483        if header.flags.is_syn() {
484            return self.accept_stream(header.stream_id).await;
485        }
486
487        // Get existing stream
488        let stream = {
489            let streams = self.streams.read().await;
490            streams.get(&header.stream_id).cloned()
491        };
492
493        let stream = match stream {
494            Some(s) => s,
495            None => {
496                // Unknown stream - send RST
497                self.queue_frame(StreamHeader::rst(header.stream_id), Bytes::new())
498                    .await?;
499                return Ok(());
500            }
501        };
502
503        let mut state = stream.lock().await;
504
505        // Handle RST
506        if header.flags.is_rst() {
507            state.reset(Some("Remote reset".to_string()));
508            return Ok(());
509        }
510
511        // Handle FIN
512        if header.flags.is_fin() {
513            state.close_remote();
514
515            // If fully closed, remove stream
516            if state.status.is_closed() {
517                drop(state);
518                self.remove_stream(header.stream_id).await;
519            }
520            return Ok(());
521        }
522
523        // Handle data
524        if !payload.is_empty() {
525            if let Err(error) = state.queue_recv(payload, self.max_recv_buffer_bytes) {
526                if matches!(error, MultiplexError::ReceiveBufferFull) {
527                    state.reset(Some("Receive buffer full".to_string()));
528                }
529                return Err(error);
530            }
531        }
532
533        Ok(())
534    }
535
536    fn validate_frame_shape(
537        header: &StreamHeader,
538        payload_len: usize,
539    ) -> Result<(), MultiplexError> {
540        if header.reserved != 0 {
541            return Err(MultiplexError::ProtocolError(
542                "reserved frame byte must be zero".to_string(),
543            ));
544        }
545        if header.flags.has_unknown_bits() {
546            return Err(MultiplexError::ProtocolError(
547                "unknown frame flag bits set".to_string(),
548            ));
549        }
550        if header.is_control() {
551            if !header.flags.is_empty() {
552                return Err(MultiplexError::ProtocolError(
553                    "control stream flags are unsupported".to_string(),
554                ));
555            }
556            if payload_len != 0 {
557                return Err(MultiplexError::ProtocolError(
558                    "control frame payload not supported".to_string(),
559                ));
560            }
561            return Ok(());
562        }
563
564        if header.flags.is_syn() {
565            if header.flags.as_byte() != StreamFlags::SYN.as_byte() {
566                return Err(MultiplexError::ProtocolError(
567                    "SYN frame must not combine control flags".to_string(),
568                ));
569            }
570            if payload_len != 0 {
571                return Err(MultiplexError::ProtocolError(
572                    "SYN frame payload not supported".to_string(),
573                ));
574            }
575        }
576        if header.flags.is_fin() && header.flags.is_rst() {
577            return Err(MultiplexError::ProtocolError(
578                "FIN and RST flags conflict".to_string(),
579            ));
580        }
581        if payload_len != 0
582            && (header.flags.is_fin() || header.flags.is_rst() || header.flags.is_ack())
583        {
584            return Err(MultiplexError::ProtocolError(
585                "stream control frame payload not supported".to_string(),
586            ));
587        }
588
589        Ok(())
590    }
591
592    /// Process a control frame
593    async fn process_control_frame(
594        &self,
595        _header: StreamHeader,
596        payload: Bytes,
597    ) -> Result<(), MultiplexError> {
598        if !payload.is_empty() {
599            return Err(MultiplexError::ProtocolError(
600                "control frame payload not supported".to_string(),
601            ));
602        }
603
604        // Control frames are for connection-level operations
605        // Currently not implemented - reserved for future use
606        Ok(())
607    }
608
609    /// Remove a stream
610    async fn remove_stream(&self, stream_id: u16) {
611        let mut streams = self.streams.write().await;
612        if streams.remove(&stream_id).is_some() {
613            self.stream_count.fetch_sub(1, Ordering::Relaxed);
614        }
615    }
616
617    /// Remove a locally-opened stream before it is visible on the wire.
618    pub(crate) async fn rollback_stream_open(&self, stream_id: u16) {
619        self.remove_stream(stream_id).await;
620
621        let mut queue = self.send_queue.lock().await;
622        queue.retain(|(header, _)| header.stream_id != stream_id);
623    }
624
625    /// Queue a frame for sending
626    async fn queue_frame(
627        &self,
628        header: StreamHeader,
629        payload: Bytes,
630    ) -> Result<(), MultiplexError> {
631        if self.is_closed() {
632            return Err(MultiplexError::ConnectionClosed);
633        }
634
635        let mut queue = self.send_queue.lock().await;
636        if queue.len() >= self.max_send_queue_len {
637            return Err(MultiplexError::SendBufferFull);
638        }
639        queue.push_back((header, payload));
640        Ok(())
641    }
642
643    /// Take next frame to send
644    pub async fn take_frame(&self) -> Option<(StreamHeader, Bytes)> {
645        let mut queue = self.send_queue.lock().await;
646        let frame = queue.pop_front()?;
647        self.bytes_sent.fetch_add(
648            (STREAM_HEADER_SIZE + frame.1.len()) as u64,
649            Ordering::Relaxed,
650        );
651        Some(frame)
652    }
653
654    /// Encode a frame to bytes
655    pub fn encode_frame(header: &StreamHeader, payload: &Bytes) -> Bytes {
656        let mut buf = BytesMut::with_capacity(STREAM_HEADER_SIZE + payload.len());
657        header.encode(&mut buf);
658        buf.extend_from_slice(payload);
659        buf.freeze()
660    }
661
662    /// Get stream status
663    pub async fn stream_status(&self, stream_id: u16) -> Result<StreamStatus, MultiplexError> {
664        let streams = self.streams.read().await;
665        let stream = streams
666            .get(&stream_id)
667            .ok_or(MultiplexError::StreamNotFound(stream_id))?;
668        let state = stream.lock().await;
669        Ok(state.status)
670    }
671
672    /// Close the connection
673    pub async fn close(&self) {
674        self.closed.store(true, Ordering::SeqCst);
675
676        self.send_queue.lock().await.clear();
677
678        let mut streams = self.streams.write().await;
679        for stream in streams.values() {
680            let mut state = stream.lock().await;
681            state.reset(Some("Connection closed".to_string()));
682        }
683        streams.clear();
684        self.stream_count.store(0, Ordering::Relaxed);
685    }
686
687    /// Get total bytes sent
688    pub fn total_bytes_sent(&self) -> u64 {
689        self.bytes_sent.load(Ordering::Relaxed)
690    }
691
692    /// Get total bytes received
693    pub fn total_bytes_received(&self) -> u64 {
694        self.bytes_received.load(Ordering::Relaxed)
695    }
696
697    /// Check if a stream exists
698    pub async fn has_stream(&self, stream_id: u16) -> bool {
699        let streams = self.streams.read().await;
700        streams.contains_key(&stream_id)
701    }
702
703    /// Get all active stream IDs
704    pub async fn active_streams(&self) -> Vec<u16> {
705        let streams = self.streams.read().await;
706        streams.keys().copied().collect()
707    }
708}
709
710impl Default for MultiplexedConnection {
711    fn default() -> Self {
712        Self::new()
713    }
714}
715
716#[cfg(test)]
717mod tests {
718    use super::*;
719
720    #[tokio::test]
721    async fn test_open_stream() {
722        let conn = MultiplexedConnection::new();
723
724        let stream_id = conn.open_stream().await.unwrap();
725        assert!(stream_id > 0);
726        assert_eq!(conn.stream_count(), 1);
727        assert!(conn.has_stream(stream_id).await);
728    }
729
730    #[tokio::test]
731    async fn test_multiple_streams() {
732        let conn = MultiplexedConnection::new();
733
734        let id1 = conn.open_stream().await.unwrap();
735        let id2 = conn.open_stream().await.unwrap();
736        let id3 = conn.open_stream().await.unwrap();
737
738        assert_ne!(id1, id2);
739        assert_ne!(id2, id3);
740        assert_eq!(conn.stream_count(), 3);
741    }
742
743    #[tokio::test]
744    async fn open_stream_wrap_skips_control_stream() {
745        let conn = MultiplexedConnection::new();
746        conn.next_stream_id.store(0, Ordering::SeqCst);
747
748        let stream_id = conn.open_stream().await.unwrap();
749        let (header, _) = conn.take_frame().await.unwrap();
750
751        assert_eq!(stream_id, 1);
752        assert_eq!(header.stream_id, 1);
753        assert!(!conn.has_stream(StreamHeader::CONTROL_STREAM).await);
754        assert!(conn.has_stream(1).await);
755    }
756
757    #[tokio::test]
758    async fn test_send_recv() {
759        let conn = MultiplexedConnection::new();
760        let stream_id = conn.open_stream().await.unwrap();
761
762        // Simulate receiving data
763        let header = StreamHeader::data(stream_id, 5);
764        let payload = Bytes::from("hello");
765        conn.process_frame(header, payload).await.unwrap();
766
767        // Receive the data
768        let data = conn.recv(stream_id).await.unwrap();
769        assert_eq!(data, Some(Bytes::from("hello")));
770    }
771
772    #[tokio::test]
773    async fn test_close_stream() {
774        let conn = MultiplexedConnection::new();
775        let stream_id = conn.open_stream().await.unwrap();
776
777        conn.close_stream(stream_id).await.unwrap();
778
779        let status = conn.stream_status(stream_id).await.unwrap();
780        assert_eq!(status, StreamStatus::HalfClosedLocal);
781    }
782
783    #[tokio::test]
784    async fn test_reset_stream() {
785        let conn = MultiplexedConnection::new();
786        let stream_id = conn.open_stream().await.unwrap();
787
788        conn.reset_stream(stream_id, Some("test error".to_string()))
789            .await
790            .unwrap();
791
792        let status = conn.stream_status(stream_id).await.unwrap();
793        assert_eq!(status, StreamStatus::Reset);
794    }
795
796    #[tokio::test]
797    async fn test_stream_isolation() {
798        let conn = MultiplexedConnection::new();
799
800        let id1 = conn.open_stream().await.unwrap();
801        let id2 = conn.open_stream().await.unwrap();
802
803        // Send data to stream 1
804        let header1 = StreamHeader::data(id1, 7);
805        conn.process_frame(header1, Bytes::from("stream1"))
806            .await
807            .unwrap();
808
809        // Send data to stream 2
810        let header2 = StreamHeader::data(id2, 7);
811        conn.process_frame(header2, Bytes::from("stream2"))
812            .await
813            .unwrap();
814
815        // Reset stream 1
816        conn.reset_stream(id1, None).await.unwrap();
817
818        // Stream 2 should still work
819        let data2 = conn.recv(id2).await.unwrap();
820        assert_eq!(data2, Some(Bytes::from("stream2")));
821
822        // Stream 1 should error
823        let result = conn.recv(id1).await;
824        assert!(matches!(result, Err(MultiplexError::StreamError(_))));
825    }
826
827    #[tokio::test]
828    async fn test_accept_stream() {
829        let conn = MultiplexedConnection::new();
830
831        // Simulate receiving SYN
832        let header = StreamHeader::syn(100);
833        conn.process_frame(header, Bytes::new()).await.unwrap();
834
835        assert!(conn.has_stream(100).await);
836        assert_eq!(conn.stream_count(), 1);
837    }
838
839    #[tokio::test]
840    async fn test_connection_close() {
841        let conn = MultiplexedConnection::new();
842        let stream_id = conn.open_stream().await.unwrap();
843
844        conn.close().await;
845
846        assert!(conn.is_closed());
847
848        // Operations should fail
849        let result = conn.open_stream().await;
850        assert!(matches!(result, Err(MultiplexError::ConnectionClosed)));
851
852        let result = conn.send(stream_id, Bytes::from("test")).await;
853        assert!(matches!(result, Err(MultiplexError::ConnectionClosed)));
854    }
855
856    #[tokio::test]
857    async fn test_take_frame() {
858        let conn = MultiplexedConnection::new();
859        let stream_id = conn.open_stream().await.unwrap();
860
861        // Opening a stream queues a SYN frame
862        let frame = conn.take_frame().await;
863        assert!(frame.is_some());
864        let (header, _) = frame.unwrap();
865        assert!(header.flags.is_syn());
866        assert_eq!(header.stream_id, stream_id);
867    }
868
869    #[tokio::test]
870    async fn test_stream_status_transitions() {
871        let conn = MultiplexedConnection::new();
872        let stream_id = conn.open_stream().await.unwrap();
873
874        // Initial status is Open
875        let status = conn.stream_status(stream_id).await.unwrap();
876        assert_eq!(status, StreamStatus::Open);
877
878        // Close local side
879        conn.close_stream(stream_id).await.unwrap();
880        let status = conn.stream_status(stream_id).await.unwrap();
881        assert_eq!(status, StreamStatus::HalfClosedLocal);
882
883        // Receive FIN from remote
884        let fin = StreamHeader::fin(stream_id);
885        conn.process_frame(fin, Bytes::new()).await.unwrap();
886
887        // Stream should be removed after full close
888        assert!(!conn.has_stream(stream_id).await);
889    }
890
891    #[tokio::test]
892    async fn test_concurrent_streams_limit() {
893        // This test verifies the MAX_STREAMS constant is respected
894        // We don't actually create 65535 streams, just verify the limit exists
895        assert_eq!(MAX_STREAMS, 65535);
896    }
897
898    #[test]
899    fn test_stream_status_can_send() {
900        assert!(StreamStatus::Open.can_send());
901        assert!(!StreamStatus::HalfClosedLocal.can_send());
902        assert!(StreamStatus::HalfClosedRemote.can_send());
903        assert!(!StreamStatus::Closed.can_send());
904        assert!(!StreamStatus::Reset.can_send());
905    }
906
907    #[test]
908    fn test_stream_status_can_receive() {
909        assert!(StreamStatus::Open.can_receive());
910        assert!(StreamStatus::HalfClosedLocal.can_receive());
911        assert!(!StreamStatus::HalfClosedRemote.can_receive());
912        assert!(!StreamStatus::Closed.can_receive());
913        assert!(!StreamStatus::Reset.can_receive());
914    }
915}