Skip to main content

http_type/stream/
impl.rs

1use super::*;
2
3/// Implementation of `From` trait for converting `usize` address into `&Stream`.
4impl From<usize> for &'static Stream {
5    /// Converts a memory address into a reference to `Stream`.
6    ///
7    /// # Arguments
8    ///
9    /// - `usize` - The memory address of the `Stream` instance.
10    ///
11    /// # Returns
12    ///
13    /// - `&'static Stream` - A reference to the `Stream` at the given address.
14    ///
15    /// # Safety
16    ///
17    /// - The address is guaranteed to be a valid `Stream` instance
18    ///   that was previously converted from a reference and is managed by the runtime.
19    #[inline(always)]
20    fn from(address: usize) -> &'static Stream {
21        unsafe { &*(address as *const Stream) }
22    }
23}
24
25/// Implementation of `From` trait for converting `usize` address into `&mut Stream`.
26impl<'a> From<usize> for &'a mut Stream {
27    /// Converts a memory address into a mutable reference to `Stream`.
28    ///
29    /// # Arguments
30    ///
31    /// - `usize` - The memory address of the `Stream` instance.
32    ///
33    /// # Returns
34    ///
35    /// - `&'a mut Stream` - A mutable reference to the `Stream` at the given address.
36    ///
37    /// # Safety
38    ///
39    /// - The address is guaranteed to be a valid `Stream` instance
40    ///   that was previously converted from a reference and is managed by the runtime.
41    #[inline(always)]
42    fn from(address: usize) -> &'a mut Stream {
43        unsafe { &mut *(address as *mut Stream) }
44    }
45}
46
47/// Implementation of `From` trait for converting `&Stream` into `usize` address.
48impl From<&Stream> for usize {
49    /// Converts a reference to `Stream` into its memory address.
50    ///
51    /// # Arguments
52    ///
53    /// - `&Stream` - The reference to the `Stream` instance.
54    ///
55    /// # Returns
56    ///
57    /// - `usize` - The memory address of the `Stream` instance.
58    #[inline(always)]
59    fn from(stream: &Stream) -> Self {
60        stream as *const Stream as usize
61    }
62}
63
64/// Implementation of `From` trait for converting `&mut Stream` into `usize` address.
65impl From<&mut Stream> for usize {
66    /// Converts a mutable reference to `Stream` into its memory address.
67    ///
68    /// # Arguments
69    ///
70    /// - `&mut Stream` - The mutable reference to the `Stream` instance.
71    ///
72    /// # Returns
73    ///
74    /// - `usize` - The memory address of the `Stream` instance.
75    #[inline(always)]
76    fn from(stream: &mut Stream) -> Self {
77        stream as *mut Stream as usize
78    }
79}
80
81/// Implementation of `AsRef` trait for `Stream`.
82impl AsRef<Stream> for Stream {
83    /// Converts `&Stream` to `&Stream` via memory address conversion.
84    ///
85    /// # Returns
86    ///
87    /// - `&Self` - A reference to the `Stream` instance.
88    #[inline(always)]
89    fn as_ref(&self) -> &Self {
90        let address: usize = self.into();
91        address.into()
92    }
93}
94
95/// Implementation of `AsMut` trait for `Stream`.
96impl AsMut<Stream> for Stream {
97    /// Converts `&mut Stream` to `&mut Stream` via memory address conversion.
98    ///
99    /// # Returns
100    ///
101    /// - `&mut Self` - A mutable reference to the `Stream` instance.
102    #[inline(always)]
103    fn as_mut(&mut self) -> &mut Self {
104        let address: usize = self.into();
105        address.into()
106    }
107}
108
109/// Implementation of `Lifetime` trait for `Stream`.
110impl Lifetime for Stream {
111    /// Converts a reference to the stream into a `'static` reference.
112    ///
113    /// # Returns
114    ///
115    /// - `&'static Self` - A reference to the stream with a `'static` lifetime.
116    ///
117    /// # Safety
118    ///
119    /// - The address is guaranteed to be a valid `Self` instance
120    ///   that was previously converted from a reference and is managed by the runtime.
121    #[inline(always)]
122    unsafe fn leak(&self) -> &'static Self {
123        let address: usize = self.into();
124        address.into()
125    }
126
127    /// Converts a reference to the stream into a `'static` mutable reference.
128    ///
129    /// # Returns
130    ///
131    /// - `&'static mut Self` - A mutable reference to the stream with a `'static` lifetime.
132    ///
133    /// # Safety
134    ///
135    /// - The address is guaranteed to be a valid `Self` instance
136    ///   that was previously converted from a reference and is managed by the runtime.
137    #[inline(always)]
138    unsafe fn leak_mut(&self) -> &'static mut Self {
139        let address: usize = self.into();
140        address.into()
141    }
142}
143
144/// Implementation of `Transport` trait for the plain TCP socket.
145///
146/// The socket is the reference transport: it already carries a socket
147/// identity, so its addresses are reported directly.
148impl Transport for TcpStream {
149    /// Reports the address of the remote end of the socket.
150    ///
151    /// # Returns
152    ///
153    /// - `Result<SocketAddr, io::Error>` - The peer address of the socket.
154    fn peer_addr(&self) -> Result<SocketAddr, io::Error> {
155        TcpStream::peer_addr(self)
156    }
157
158    /// Reports the address of the local end of the socket.
159    ///
160    /// # Returns
161    ///
162    /// - `Result<SocketAddr, io::Error>` - The local address of the socket.
163    fn local_addr(&self) -> Result<SocketAddr, io::Error> {
164        TcpStream::local_addr(self)
165    }
166}
167
168/// Implements [`Drop`] for [`PooledReader`].
169impl Drop for PooledReader<'_> {
170    /// Releases the buffer back to the pool for reuse by later requests.
171    fn drop(&mut self) {
172        let buffer: Vec<u8> = mem::take(self.get_mut_buffer());
173        return_read_buffer(buffer);
174    }
175}
176
177/// Implements non-blocking buffered reads for `PooledReader`.
178///
179/// Buffered bytes are served first; once drained, reads are delegated
180/// directly to the underlying stream.
181impl AsyncRead for PooledReader<'_> {
182    /// Polls to read data into the provided buffer.
183    ///
184    /// # Arguments
185    ///
186    /// - `Pin<&mut Self>` - The pinned reader.
187    /// - `&mut Context<'_>` - The task context.
188    /// - `&mut ReadBuf<'_>` - The destination buffer.
189    ///
190    /// # Returns
191    ///
192    /// - `Poll<io::Result<()>>` - Ready when data was read or an error occurred.
193    fn poll_read(
194        self: Pin<&mut Self>,
195        cx: &mut Context<'_>,
196        buf: &mut ReadBuf<'_>,
197    ) -> Poll<io::Result<()>> {
198        let this: &mut Self = self.get_mut();
199        if this.get_start() < this.get_end() {
200            let available: usize = this.get_end() - this.get_start();
201            let amount: usize = available.min(buf.remaining());
202            let end: usize = this.get_start() + amount;
203            buf.put_slice(&this.get_buffer()[this.get_start()..end]);
204            this.set_start(end);
205            return Poll::Ready(Ok(()));
206        }
207        return_read_buffer(mem::take(this.get_mut_buffer()));
208        Pin::new(&mut **this.get_mut_stream()).poll_read(cx, buf)
209    }
210}
211
212/// Implements buffered-read support for `PooledReader`.
213///
214/// The internal buffer is refilled from the stream only when fully
215/// consumed, so a single socket read serves multiple line parses.
216impl AsyncBufRead for PooledReader<'_> {
217    /// Polls to fill the internal buffer and returns the available data.
218    ///
219    /// # Arguments
220    ///
221    /// - `Pin<&mut Self>` - The pinned reader.
222    /// - `&mut Context<'_>` - The task context.
223    ///
224    /// # Returns
225    ///
226    /// - `Poll<io::Result<&[u8]>>` - Ready with the unconsumed bytes, or an error.
227    fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
228        let this: &mut Self = self.get_mut();
229        let PooledReader {
230            stream,
231            buffer,
232            capacity,
233            start,
234            end,
235        } = this;
236        if *start >= *end {
237            *start = 0;
238            *end = 0;
239            if buffer.is_empty() {
240                *buffer = take_read_buffer(*capacity);
241            }
242            let mut read_buf: ReadBuf<'_> = ReadBuf::new(buffer);
243            match Pin::new(&mut **stream).poll_read(cx, &mut read_buf) {
244                Poll::Ready(Ok(())) => {
245                    *end = read_buf.filled().len();
246                }
247                Poll::Ready(Err(error)) => return Poll::Ready(Err(error)),
248                Poll::Pending => {
249                    return_read_buffer(mem::take(buffer));
250                    return Poll::Pending;
251                }
252            }
253        }
254        Poll::Ready(Ok(&buffer[*start..*end]))
255    }
256
257    /// Marks the given number of bytes as consumed.
258    ///
259    /// # Arguments
260    ///
261    /// - `Pin<&mut Self>` - The pinned reader.
262    /// - `usize` - The number of bytes to consume.
263    fn consume(self: Pin<&mut Self>, amount: usize) {
264        let this: &mut Self = self.get_mut();
265        let new_start: usize = (this.get_start() + amount).min(this.get_end());
266        this.set_start(new_start);
267    }
268}
269
270/// Inherent implementation of [`Stream`].
271impl Stream {
272    /// Boxes a transport into a `Stream` for the request pipeline.
273    ///
274    /// This is the single construction path: a plain TCP socket, a TLS session
275    /// and a per-request duplex stream all enter here, so nothing above the
276    /// transport line has to know which one it is serving. The transport is
277    /// type erased immediately, which keeps `Stream` a fixed size regardless of
278    /// the concrete protocol adapter behind it.
279    ///
280    /// # Arguments
281    ///
282    /// - `T` - The transport type to serve the request cycle over.
283    /// - `RequestConfig` - The parsing limits and read timeout for the cycle.
284    /// - `bool` - Whether the connection starts already closed.
285    ///
286    /// # Returns
287    ///
288    /// - `Self` - A stream serving bytes through the boxed transport.
289    pub fn from_transport<T>(transport: T, request_config: RequestConfig, closed: bool) -> Self
290    where
291        T: Transport + 'static,
292    {
293        Self {
294            stream: Box::new(transport),
295            request_config,
296            closed,
297            leftover: Vec::new(),
298            leftover_start: 0,
299            leftover_end: 0,
300            line_buffer: String::new(),
301            header_line_buffer: String::new(),
302            websocket_state: None,
303        }
304    }
305
306    /// Boxes a TCP socket into a `Stream` for the request pipeline.
307    ///
308    /// Kept as the socket-facing constructor so the accept loop keeps its
309    /// existing call shape; it delegates to `from_transport`, so there is one
310    /// construction path rather than two.
311    ///
312    /// # Arguments
313    ///
314    /// - `TcpStream` - The accepted socket to serve the request cycle over.
315    /// - `RequestConfig` - The parsing limits and read timeout for the cycle.
316    /// - `bool` - Whether the connection starts already closed.
317    ///
318    /// # Returns
319    ///
320    /// - `Self` - A stream serving bytes through the boxed socket.
321    pub fn new(stream: TcpStream, request_config: RequestConfig, closed: bool) -> Self {
322        Self::from_transport(stream, request_config, closed)
323    }
324
325    /// Reports the address of the remote end of the transport.
326    ///
327    /// Delegates to the transport itself, so a transport without a socket
328    /// identity answers with an error rather than a fabricated address.
329    ///
330    /// # Returns
331    ///
332    /// - `Result<SocketAddr, io::Error>` - The peer address reported by the transport.
333    #[inline(always)]
334    pub fn get_peer_addr(&self) -> Result<SocketAddr, io::Error> {
335        self.get_stream().peer_addr()
336    }
337
338    /// Reports the address of the local end of the transport.
339    ///
340    /// Delegates to the transport itself, so a transport without a socket
341    /// identity answers with an error rather than a fabricated address.
342    ///
343    /// # Returns
344    ///
345    /// - `Result<SocketAddr, io::Error>` - The local address reported by the transport.
346    #[inline(always)]
347    pub fn get_local_addr(&self) -> Result<SocketAddr, io::Error> {
348        self.get_stream().local_addr()
349    }
350
351    /// Shuts the transport down.
352    ///
353    /// The transport itself is crate-internal, so a caller that needs to
354    /// close the connection reaches it through this method rather than
355    /// through the field.
356    ///
357    /// # Returns
358    ///
359    /// - `Result<(), io::Error>` - Whether the transport shut down.
360    #[inline(always)]
361    pub async fn shutdown(&mut self) -> Result<(), io::Error> {
362        self.get_mut_stream().shutdown().await
363    }
364
365    /// Checks if the connection should be kept alive.
366    ///
367    /// This method evaluates whether the connection should remain open based on
368    /// the closed state and the keep_alive parameter.
369    ///
370    /// # Arguments
371    ///
372    /// - `bool` - Whether keep-alive is enabled for the request.
373    ///
374    /// # Returns
375    ///
376    /// - `bool` - True if the connection should be kept alive, otherwise false.
377    #[inline(always)]
378    pub fn is_keep_alive(&self, keep_alive: bool) -> bool {
379        !self.get_closed() && keep_alive
380    }
381
382    /// Parses the HTTP request content from the stream into the given request.
383    ///
384    /// The request is reset first, then filled in place so its existing
385    /// allocations are reused across keep-alive requests.
386    ///
387    /// # Arguments
388    ///
389    /// - `&mut Request` - The request object to fill.
390    ///
391    /// # Returns
392    ///
393    /// - `Result<(), RequestError>` - Ok on success, or an error if parsing fails.
394    async fn fill_http_from_stream(&mut self, request: &mut Request) -> Result<(), RequestError> {
395        request.reset();
396        let config: RequestConfig = *self.get_request_config();
397        let buffer_size: usize = config.get_buffer_size();
398        let max_path_size: usize = config.get_max_path_size();
399        // Move read-ahead storage and its valid window into the reader instead
400        // of allocating and copying the remaining pipeline for every request.
401        let start: usize = self.get_leftover_start();
402        let end: usize = self.get_leftover_end();
403        let buffer: Vec<u8> = mem::take(self.get_mut_leftover());
404        self.set_leftover_start(0);
405        self.set_leftover_end(0);
406        // Split the borrow of the stream: the reader takes the transport, the
407        // line buffers are separate fields, so both can be held at once.
408        let Stream {
409            stream,
410            line_buffer,
411            header_line_buffer,
412            ..
413        } = self;
414        let mut reader: PooledReader<'_> = PooledReader::new(stream, buffer, buffer_size);
415        reader.set_start(start);
416        reader.set_end(end);
417        line_buffer.clear();
418        let filled_len: usize = future::poll_fn(|cx: &mut Context<'_>| {
419            Pin::new(&mut reader).poll_fill_buf(cx).map_ok(<[u8]>::len)
420        })
421        .await?;
422        let fast_framing: Option<RequestFraming> = if filled_len > 0 {
423            let slice: &[u8] = &reader.get_buffer()[reader.get_start()..reader.get_end()];
424            match request.parse_http_head_from_slice(slice, &config, line_buffer)? {
425                Some((framing, consumed)) => {
426                    Pin::new(&mut reader).consume(consumed);
427                    Some(framing)
428                }
429                None => None,
430            }
431        } else {
432            None
433        };
434        let framing: RequestFraming = match fast_framing {
435            Some(framing) => framing,
436            None => {
437                line_buffer.clear();
438                AsyncBufReadExt::read_line(&mut reader, line_buffer).await?;
439                let (method, path, version): (RequestMethod, &str, RequestVersion) =
440                    Request::get_http_first_line(line_buffer)?;
441                Request::check_http_path_size(path, max_path_size)?;
442                let hash_index: Option<usize> = path.find(HASH);
443                let query_index: Option<usize> = path.find(QUERY);
444                let query: &str = Request::get_http_query(path, query_index, hash_index);
445                Request::fill_http_querys(query, request.get_mut_querys());
446                let path_slice: &str = Request::get_http_path(path, query_index, hash_index);
447                request.get_mut_path().push_str(path_slice);
448                request.set_version(version);
449                let framing: RequestFraming = request
450                    .get_http_headers(&mut reader, &config, header_line_buffer)
451                    .await?;
452                request.set_method(method);
453                framing
454            }
455        };
456        match framing {
457            RequestFraming::Fixed(0) => {}
458            RequestFraming::Fixed(content_size) => {
459                let buffered: usize = reader.get_end() - reader.get_start();
460                if content_size <= buffered {
461                    let body: &mut RequestBody = request.get_mut_body();
462                    body.clear();
463                    let body_start: usize = reader.get_start();
464                    body.extend_from_slice(
465                        &reader.get_buffer()[body_start..body_start + content_size],
466                    );
467                    reader.set_start(body_start + content_size);
468                } else {
469                    if expects_http_continue(request) {
470                        let transport: &mut Box<dyn Transport> = reader.get_mut_stream();
471                        transport.write_all(HTTP_CONTINUE_RESPONSE).await?;
472                        transport.flush().await?;
473                    }
474                    Request::fill_http_body(&mut reader, request.get_mut_body(), content_size)
475                        .await?;
476                }
477            }
478            RequestFraming::Chunked => {
479                Box::pin(fill_chunked_request(&mut reader, request, &config)).await?;
480            }
481        }
482        // Preserve bytes read ahead for the next pipelined request: they have
483        // already left the socket and cannot be read again.
484        let reader_start: usize = reader.get_start();
485        let reader_end: usize = reader.get_end();
486        let pending: Vec<u8> = if reader_start < reader_end {
487            mem::take(reader.get_mut_buffer())
488        } else {
489            Vec::new()
490        };
491        drop(reader);
492        let pending_start: usize = if pending.is_empty() { 0 } else { reader_start };
493        let pending_end: usize = if pending.is_empty() { 0 } else { reader_end };
494        self.set_leftover(pending);
495        self.set_leftover_start(pending_start);
496        self.set_leftover_end(pending_end);
497        Ok(())
498    }
499
500    /// Parses an HTTP request from a TCP stream into the given request.
501    ///
502    /// The request is reset and filled in place, reusing its allocations.
503    /// An HTTP/1.1 continue expectation can write an interim response after
504    /// header validation and before waiting for the body. A chunked body is
505    /// decoded, with trailers discarded and its content length normalized.
506    /// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
507    ///
508    /// # Arguments
509    ///
510    /// - `&mut Request` - The request object to reset and fill.
511    ///
512    /// # Returns
513    ///
514    /// - `Result<(), RequestError>` - Ok on success, or an error if parsing fails.
515    pub async fn try_fill_http_request(
516        &mut self,
517        request: &mut Request,
518    ) -> Result<(), RequestError> {
519        if self.get_closed() {
520            return Err(RequestError::ServerClosedConnection(HttpStatus::BadRequest));
521        }
522        let timeout_ms: u64 = self.get_request_config().get_read_timeout_ms();
523        if timeout_ms == DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS {
524            return self.fill_http_from_stream(request).await;
525        }
526        let duration: Duration = Duration::from_millis(timeout_ms);
527        let mut reading: Pin<&mut _> = pin!(self.fill_http_from_stream(request));
528        // A request whose bytes have already arrived is read on the first
529        // poll, so the ordinary case never arms a timer at all. Arming one
530        // costs a timer registration and a cancellation per request, and that
531        // churn is the most expensive thing a request path can do once the
532        // concurrency is high enough for the timer driver to become a
533        // bottleneck. The timer is armed only when the read really has to
534        // wait, which is exactly when the timeout can still fire.
535        if let Some(result) = poll_once(reading.as_mut()).await {
536            return result;
537        }
538        timeout(duration, reading).await?
539    }
540
541    /// Parses an HTTP request from a TCP stream.
542    ///
543    /// Wraps the stream in a buffered reader and delegates to `http_from_reader`.
544    /// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
545    ///
546    /// # Returns
547    ///
548    /// - `Result<Request, RequestError>` - The parsed request or an error.
549    pub async fn try_get_http_request(&mut self) -> Result<Request, RequestError> {
550        let mut request: Request = Request::default();
551        self.try_fill_http_request(&mut request).await?;
552        Ok(request)
553    }
554
555    /// Parses a WebSocket request from a TCP stream.
556    ///
557    /// Wraps the stream in a buffered reader and delegates to `ws_from_reader`.
558    /// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
559    ///
560    /// # Returns
561    ///
562    /// - `Result<RequestBody, RequestError>` - The parsed WebSocket request or an error.
563    pub async fn try_get_websocket_request(&mut self) -> Result<RequestBody, RequestError> {
564        if self.get_closed() {
565            return self.reset_websocket_state_on_error(Err(RequestError::ServerClosedConnection(
566                HttpStatus::BadRequest,
567            )));
568        }
569        let config: RequestConfig = *self.get_request_config();
570        let read_timeout_ms: u64 = config.get_read_timeout_ms();
571        if self.get_mut_websocket_state().is_none() {
572            let mut buffer: Vec<u8> = mem::take(self.get_mut_leftover());
573            buffer.truncate(self.get_leftover_end());
574            buffer.drain(..self.get_leftover_start());
575            self.set_leftover_start(0);
576            self.set_leftover_end(0);
577            self.set_websocket_state(Some(Box::new(WebSocketReadState {
578                buffer,
579                ..WebSocketReadState::default()
580            })));
581        }
582        let duration_opt: Option<Duration> =
583            if read_timeout_ms == DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS {
584                None
585            } else {
586                let adjusted_timeout_ms: u64 = (read_timeout_ms >> 1) + (read_timeout_ms & 1);
587                Some(Duration::from_millis(adjusted_timeout_ms))
588            };
589        loop {
590            let parsed: Result<Option<RequestBody>, RequestError> =
591                self.try_parse_websocket_request();
592            if let Some(body) = self.reset_websocket_state_on_error(parsed)? {
593                return Ok(body);
594            }
595            let read: Result<Option<usize>, RequestError> =
596                self.get_websocket_from_stream(duration_opt).await;
597            if matches!(self.reset_websocket_state_on_error(read)?, Some(0)) {
598                return self.reset_websocket_state_on_error(Err(
599                    RequestError::IncompleteWebSocketFrame(HttpStatus::BadRequest),
600                ));
601            }
602        }
603    }
604
605    /// Discards cached parsing state only after an operation completes with an error.
606    ///
607    /// # Arguments
608    ///
609    /// - `Result<T, RequestError>` - The completed parsing or reading operation.
610    ///
611    /// # Returns
612    ///
613    /// - `Result<T, RequestError>` - The unchanged result after releasing failed parsing state.
614    #[inline(always)]
615    fn reset_websocket_state_on_error<T>(
616        &mut self,
617        result: Result<T, RequestError>,
618    ) -> Result<T, RequestError> {
619        if result.is_err() {
620            drop(self.get_mut_websocket_state().take());
621        }
622        result
623    }
624
625    /// Parses buffered frames without discarding incomplete or subsequent input.
626    ///
627    /// # Returns
628    ///
629    /// - `Result<Option<RequestBody>, RequestError>` - A complete message, pending input, or a protocol error.
630    fn try_parse_websocket_request(&mut self) -> Result<Option<RequestBody>, RequestError> {
631        let state: &mut WebSocketReadState = self.get_mut_websocket_state().as_deref_mut().ok_or(
632            RequestError::IncompleteWebSocketFrame(HttpStatus::BadRequest),
633        )?;
634        let WebSocketReadState {
635            buffer,
636            full_frame,
637            is_client_response,
638        }: &mut WebSocketReadState = state;
639        while let Some((frame, consumed)) = WebSocketFrame::decode_ws_frame(&buffer[..]) {
640            *is_client_response = true;
641            buffer.drain(..consumed);
642            if buffer.is_empty() {
643                let mut recycled: Vec<u8> = mem::take(buffer);
644                recycled.resize(recycled.capacity().min(MAX_POOLED_READ_BUFFER_SIZE), 0);
645                return_read_buffer(recycled);
646            }
647            match frame.get_opcode() {
648                WebSocketOpcode::Close => {
649                    return Err(RequestError::ClientClosedConnection(HttpStatus::BadRequest));
650                }
651                WebSocketOpcode::Ping | WebSocketOpcode::Pong => continue,
652                WebSocketOpcode::Text | WebSocketOpcode::Binary => {
653                    if frame.get_fin() && full_frame.is_empty() {
654                        let WebSocketFrame { payload_data, .. }: WebSocketFrame = frame;
655                        return Ok(Some(payload_data));
656                    }
657                    if let Some(body) = frame.build_full_frame(full_frame)? {
658                        return Ok(Some(body));
659                    }
660                }
661                _ => {
662                    return Err(RequestError::WebSocketOpcodeUnsupported(
663                        HttpStatus::NotImplemented,
664                    ));
665                }
666            }
667        }
668        Ok(None)
669    }
670
671    /// Polls a WebSocket read using a buffer retained only while data is ready.
672    ///
673    /// # Arguments
674    ///
675    /// - `&mut Context<'_>` - The registered task context.
676    ///
677    /// # Returns
678    ///
679    /// - `Poll<io::Result<usize>>` - The bytes appended to persistent parsing state.
680    fn poll_websocket_read(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<usize>> {
681        let capacity: usize = self.get_request_config().get_buffer_size();
682        let mut temporary: Vec<u8> = take_read_buffer(capacity);
683        let mut read_buffer: ReadBuf<'_> = ReadBuf::new(&mut temporary[..capacity]);
684        match Pin::new(&mut **self.get_mut_stream()).poll_read(cx, &mut read_buffer) {
685            Poll::Ready(Ok(())) => {
686                let len: usize = read_buffer.filled().len();
687                temporary.truncate(len);
688                let state: &mut WebSocketReadState =
689                    match self.get_mut_websocket_state().as_deref_mut() {
690                        Some(state) => state,
691                        None => {
692                            return_read_buffer(temporary);
693                            return Poll::Ready(Err(io::Error::new(
694                                io::ErrorKind::InvalidData,
695                                WEBSOCKET_STATE_ERROR,
696                            )));
697                        }
698                    };
699                if state.get_buffer().is_empty() {
700                    mem::swap(state.get_mut_buffer(), &mut temporary);
701                } else {
702                    state.get_mut_buffer().extend_from_slice(&temporary);
703                }
704                return_read_buffer(temporary);
705                Poll::Ready(Ok(len))
706            }
707            Poll::Ready(Err(error)) => {
708                return_read_buffer(temporary);
709                Poll::Ready(Err(error))
710            }
711            Poll::Pending => {
712                return_read_buffer(temporary);
713                Poll::Pending
714            }
715        }
716    }
717
718    /// Reads data from the stream with optional timeout handling.
719    ///
720    /// # Arguments
721    ///
722    /// - `Option<Duration>` - The timeout interval, or no timeout.
723    ///
724    /// # Returns
725    ///
726    /// - `Result<Option<usize>, RequestError>` - Bytes read, a heartbeat, or an error.
727    pub(crate) async fn get_websocket_from_stream(
728        &mut self,
729        duration_opt: Option<Duration>,
730    ) -> Result<Option<usize>, RequestError> {
731        if let Some(duration) = duration_opt {
732            return match timeout(
733                duration,
734                future::poll_fn(|cx: &mut Context<'_>| self.poll_websocket_read(cx)),
735            )
736            .await
737            {
738                Ok(result) => result.map(Some).map_err(Into::into),
739                Err(error) => {
740                    let state: &mut WebSocketReadState =
741                        self.get_mut_websocket_state().as_deref_mut().ok_or(
742                            RequestError::IncompleteWebSocketFrame(HttpStatus::BadRequest),
743                        )?;
744                    if !state.get_is_client_response() {
745                        return Err(error.into());
746                    }
747                    state.set_is_client_response(false);
748                    self.try_send(&PING_FRAME).await?;
749                    Ok(None)
750                }
751            };
752        }
753        future::poll_fn(|cx: &mut Context<'_>| self.poll_websocket_read(cx))
754            .await
755            .map(Some)
756            .map_err(Into::into)
757    }
758
759    /// Sends data over the stream.
760    ///
761    /// # Arguments
762    ///
763    /// - `D` - The data to send, which must implement `AsRef<[u8]>`.
764    ///
765    /// # Returns
766    ///
767    /// - `Result<(), ResponseError>` - Result indicating success or failure.
768    pub async fn try_send<D>(&mut self, data: D) -> Result<(), ResponseError>
769    where
770        D: AsRef<[u8]>,
771    {
772        if self.get_closed() {
773            return Err(ResponseError::ConnectionClosed);
774        }
775        Ok(self.get_mut_stream().write_all(data.as_ref()).await?)
776    }
777
778    /// Sends data over the stream.
779    ///
780    /// # Arguments
781    ///
782    /// - `D` - The data to send, which must implement `AsRef<[u8]>`.
783    ///
784    /// # Panics
785    ///
786    /// Panics if the write operation fails.
787    pub async fn send<D>(&mut self, data: D)
788    where
789        D: AsRef<[u8]>,
790    {
791        self.try_send(data).await.unwrap();
792    }
793
794    /// Sends multiple data.
795    ///
796    /// # Arguments
797    ///
798    /// - `I` - The data list to send, which must implement `IntoIterator<Item = D>` with
799    ///   `D` requiring the `AsRef<[u8]>` bound.
800    ///
801    /// # Returns
802    ///
803    /// - `Result<(), ResponseError>` - Result indicating success or failure.
804    pub async fn try_send_list<I, D>(&mut self, data_iter: I) -> Result<(), ResponseError>
805    where
806        I: IntoIterator<Item = D>,
807        D: AsRef<[u8]>,
808    {
809        if self.get_closed() {
810            return Err(ResponseError::ConnectionClosed);
811        }
812        let stream: &mut Box<dyn Transport> = self.get_mut_stream();
813        for data in data_iter {
814            stream.write_all(data.as_ref()).await?;
815        }
816        Ok(())
817    }
818
819    /// Sends multiple data.
820    ///
821    /// # Arguments
822    ///
823    /// - `I` - The data list to send, which must implement `IntoIterator<Item = D>` with
824    ///   `D` requiring the `AsRef<[u8]>` bound.
825    ///
826    /// # Panics
827    ///
828    /// Panics if any write operation fails.
829    pub async fn send_list<I, D>(&mut self, data_iter: I)
830    where
831        I: IntoIterator<Item = D>,
832        D: AsRef<[u8]>,
833    {
834        self.try_send_list(data_iter).await.unwrap();
835    }
836
837    /// Flushes all buffered data to the stream.
838    ///
839    /// # Returns
840    ///
841    /// - `Result<(), ResponseError>` - Result indicating success or failure.
842    pub async fn try_flush(&mut self) -> Result<(), ResponseError> {
843        if self.get_closed() {
844            return Err(ResponseError::ConnectionClosed);
845        }
846        Ok(self.get_mut_stream().flush().await?)
847    }
848
849    /// Flushes all buffered data to the stream.
850    ///
851    /// # Panics
852    ///
853    /// Panics if the flush operation fails.
854    pub async fn flush(&mut self) {
855        self.try_flush().await.unwrap();
856    }
857}