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/// Default construction for [`WebSocketReadState`].
271impl Default for WebSocketReadState {
272    /// Initializes WebSocket parsing state with an active heartbeat window.
273    ///
274    /// # Returns
275    ///
276    /// - `Self` - The initial WebSocket read state.
277    #[inline(always)]
278    fn default() -> Self {
279        Self {
280            buffer: Vec::new(),
281            cursor: 0,
282            full_frame: Vec::new(),
283            fragment_opcode: None,
284            is_client_response: true,
285        }
286    }
287}
288
289/// Inherent implementation of [`Stream`].
290impl Stream {
291    /// Boxes a transport into a `Stream` for the request pipeline.
292    ///
293    /// This is the single construction path: a plain TCP socket, a TLS session
294    /// and a per-request duplex stream all enter here, so nothing above the
295    /// transport line has to know which one it is serving. The transport is
296    /// type erased immediately, which keeps `Stream` a fixed size regardless of
297    /// the concrete protocol adapter behind it.
298    ///
299    /// # Arguments
300    ///
301    /// - `T` - The transport type to serve the request cycle over.
302    /// - `RequestConfig` - The parsing limits and read timeout for the cycle.
303    /// - `bool` - Whether the connection starts already closed.
304    ///
305    /// # Returns
306    ///
307    /// - `Self` - A stream serving bytes through the boxed transport.
308    pub fn from_transport<T>(transport: T, request_config: RequestConfig, closed: bool) -> Self
309    where
310        T: Transport + 'static,
311    {
312        Self {
313            stream: Box::new(transport),
314            request_config,
315            closed,
316            leftover: Vec::new(),
317            leftover_start: 0,
318            leftover_end: 0,
319            line_buffer: String::new(),
320            header_line_buffer: String::new(),
321            websocket_state: None,
322            read_timer: None,
323        }
324    }
325
326    /// Boxes a TCP socket into a `Stream` for the request pipeline.
327    ///
328    /// Kept as the socket-facing constructor so the accept loop keeps its
329    /// existing call shape; it delegates to `from_transport`, so there is one
330    /// construction path rather than two.
331    ///
332    /// # Arguments
333    ///
334    /// - `TcpStream` - The accepted socket to serve the request cycle over.
335    /// - `RequestConfig` - The parsing limits and read timeout for the cycle.
336    /// - `bool` - Whether the connection starts already closed.
337    ///
338    /// # Returns
339    ///
340    /// - `Self` - A stream serving bytes through the boxed socket.
341    pub fn new(stream: TcpStream, request_config: RequestConfig, closed: bool) -> Self {
342        Self::from_transport(stream, request_config, closed)
343    }
344
345    /// Reports the address of the remote end of the transport.
346    ///
347    /// Delegates to the transport itself, so a transport without a socket
348    /// identity answers with an error rather than a fabricated address.
349    ///
350    /// # Returns
351    ///
352    /// - `Result<SocketAddr, io::Error>` - The peer address reported by the transport.
353    #[inline(always)]
354    pub fn get_peer_addr(&self) -> Result<SocketAddr, io::Error> {
355        self.get_stream().peer_addr()
356    }
357
358    /// Reports the address of the local end of the transport.
359    ///
360    /// Delegates to the transport itself, so a transport without a socket
361    /// identity answers with an error rather than a fabricated address.
362    ///
363    /// # Returns
364    ///
365    /// - `Result<SocketAddr, io::Error>` - The local address reported by the transport.
366    #[inline(always)]
367    pub fn get_local_addr(&self) -> Result<SocketAddr, io::Error> {
368        self.get_stream().local_addr()
369    }
370
371    /// Shuts the transport down.
372    ///
373    /// The transport itself is crate-internal, so a caller that needs to
374    /// close the connection reaches it through this method rather than
375    /// through the field.
376    ///
377    /// # Returns
378    ///
379    /// - `Result<(), io::Error>` - Whether the transport shut down.
380    #[inline(always)]
381    pub async fn shutdown(&mut self) -> Result<(), io::Error> {
382        self.get_mut_stream().shutdown().await
383    }
384
385    /// Checks if the connection should be kept alive.
386    ///
387    /// This method evaluates whether the connection should remain open based on
388    /// the closed state and the keep_alive parameter.
389    ///
390    /// # Arguments
391    ///
392    /// - `bool` - Whether keep-alive is enabled for the request.
393    ///
394    /// # Returns
395    ///
396    /// - `bool` - True if the connection should be kept alive, otherwise false.
397    #[inline(always)]
398    pub fn is_keep_alive(&self, keep_alive: bool) -> bool {
399        !self.get_closed() && keep_alive
400    }
401
402    /// Parses the HTTP request content from the stream into the given request.
403    ///
404    /// The request is reset first, then filled in place so its existing
405    /// allocations are reused across keep-alive requests.
406    ///
407    /// # Arguments
408    ///
409    /// - `&mut Request` - The request object to fill.
410    ///
411    /// # Returns
412    ///
413    /// - `Result<(), RequestError>` - Ok on success, or an error if parsing fails.
414    async fn fill_http_from_stream(&mut self, request: &mut Request) -> Result<(), RequestError> {
415        request.reset();
416        let config: RequestConfig = *self.get_request_config();
417        let buffer_size: usize = config.get_buffer_size();
418        let max_path_size: usize = config.get_max_path_size();
419        // Move read-ahead storage and its valid window into the reader instead
420        // of allocating and copying the remaining pipeline for every request.
421        let start: usize = self.get_leftover_start();
422        let end: usize = self.get_leftover_end();
423        let buffer: Vec<u8> = mem::take(self.get_mut_leftover());
424        self.set_leftover_start(0);
425        self.set_leftover_end(0);
426        // Split the borrow of the stream: the reader takes the transport, the
427        // line buffers are separate fields, so both can be held at once.
428        let Stream {
429            stream,
430            line_buffer,
431            header_line_buffer,
432            ..
433        } = self;
434        let mut reader: PooledReader<'_> = PooledReader::new(stream, buffer, buffer_size);
435        reader.set_start(start);
436        reader.set_end(end);
437        line_buffer.clear();
438        let filled_len: usize = future::poll_fn(|cx: &mut Context<'_>| {
439            Pin::new(&mut reader).poll_fill_buf(cx).map_ok(<[u8]>::len)
440        })
441        .await?;
442        if filled_len == 0 {
443            return Err(RequestError::ClientClosedConnection(HttpStatus::BadRequest));
444        }
445        let fast_framing: Option<RequestFraming> = {
446            let slice: &[u8] = &reader.get_buffer()[reader.get_start()..reader.get_end()];
447            match request.parse_http_head_from_slice(slice, &config, line_buffer)? {
448                Some((framing, consumed)) => {
449                    Pin::new(&mut reader).consume(consumed);
450                    Some(framing)
451                }
452                None => None,
453            }
454        };
455        let framing: RequestFraming = match fast_framing {
456            Some(framing) => framing,
457            None => {
458                let max_request_line: usize = if max_path_size == DEFAULT_LOW_SECURITY_MAX_PATH_SIZE
459                {
460                    usize::MAX
461                } else {
462                    max_path_size.saturating_add(HTTP_REQUEST_LINE_OVERHEAD)
463                };
464                let line_len: usize = read_http_line_bounded(
465                    &mut reader,
466                    line_buffer,
467                    max_request_line,
468                    RequestError::RequestTooLong(HttpStatus::URITooLong),
469                )
470                .await?;
471                if line_len == 0 {
472                    return Err(RequestError::ClientClosedConnection(HttpStatus::BadRequest));
473                }
474                let (method, path, version): (RequestMethod, &str, RequestVersion) =
475                    Request::get_http_first_line(line_buffer)?;
476                Request::check_http_path_size(path, max_path_size)?;
477                let (query_index, hash_index): (Option<usize>, Option<usize>) =
478                    Request::find_path_separators(path);
479                let query: &str = Request::get_http_query(path, query_index, hash_index);
480                let max_query_count: usize = if max_path_size == DEFAULT_LOW_SECURITY_MAX_PATH_SIZE
481                {
482                    usize::MAX
483                } else {
484                    HTTP_MAX_QUERY_PARAM_COUNT
485                };
486                Request::fill_http_querys(query, request.get_mut_querys(), max_query_count)?;
487                let path_slice: &str = Request::get_http_path(path, query_index, hash_index);
488                request.get_mut_path().push_str(path_slice);
489                request.set_version(version);
490                let framing: RequestFraming = request
491                    .get_http_headers(&mut reader, &config, header_line_buffer)
492                    .await?;
493                request.set_method(method);
494                framing
495            }
496        };
497        match framing {
498            RequestFraming::Fixed(0) => {}
499            RequestFraming::Fixed(content_size) => {
500                let buffered: usize = reader.get_end() - reader.get_start();
501                if content_size <= buffered {
502                    let body: &mut RequestBody = request.get_mut_body();
503                    body.clear();
504                    let body_start: usize = reader.get_start();
505                    body.extend_from_slice(
506                        &reader.get_buffer()[body_start..body_start + content_size],
507                    );
508                    reader.set_start(body_start + content_size);
509                } else {
510                    if expects_http_continue(request) {
511                        let transport: &mut Box<dyn Transport> = reader.get_mut_stream();
512                        transport.write_all(HTTP_CONTINUE_RESPONSE).await?;
513                        transport.flush().await?;
514                    }
515                    Request::fill_http_body(&mut reader, request.get_mut_body(), content_size)
516                        .await?;
517                }
518            }
519            RequestFraming::Chunked => {
520                Box::pin(fill_chunked_request(&mut reader, request, &config)).await?;
521            }
522        }
523        // Preserve bytes read ahead for the next pipelined request: they have
524        // already left the socket and cannot be read again.
525        let reader_start: usize = reader.get_start();
526        let reader_end: usize = reader.get_end();
527        let pending: Vec<u8> = if reader_start < reader_end {
528            mem::take(reader.get_mut_buffer())
529        } else {
530            Vec::new()
531        };
532        drop(reader);
533        let pending_start: usize = if pending.is_empty() { 0 } else { reader_start };
534        let pending_end: usize = if pending.is_empty() { 0 } else { reader_end };
535        self.set_leftover(pending);
536        self.set_leftover_start(pending_start);
537        self.set_leftover_end(pending_end);
538        Ok(())
539    }
540
541    /// Parses an HTTP request from a TCP stream into the given request.
542    ///
543    /// The request is reset and filled in place, reusing its allocations.
544    /// An HTTP/1.1 continue expectation can write an interim response after
545    /// header validation and before waiting for the body. A chunked body is
546    /// decoded, with trailers discarded and its content length normalized.
547    /// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
548    ///
549    /// # Arguments
550    ///
551    /// - `&mut Request` - The request object to reset and fill.
552    ///
553    /// # Returns
554    ///
555    /// - `Result<(), RequestError>` - Ok on success, or an error if parsing fails.
556    pub async fn try_fill_http_request(
557        &mut self,
558        request: &mut Request,
559    ) -> Result<(), RequestError> {
560        if self.get_closed() {
561            return Err(RequestError::ServerClosedConnection(HttpStatus::BadRequest));
562        }
563        let timeout_ms: u64 = self.get_request_config().get_read_timeout_ms();
564        if timeout_ms == DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS {
565            return self.fill_http_from_stream(request).await;
566        }
567        let duration: Duration = Duration::from_millis(timeout_ms);
568        let mut timer_slot: Option<Pin<Box<Sleep>>> = {
569            let Stream { read_timer, .. } = self;
570            read_timer.take()
571        };
572        let outcome: Option<Result<(), RequestError>> = {
573            let mut reading: Pin<&mut _> = pin!(self.fill_http_from_stream(request));
574            poll_with_timeout(reading.as_mut(), &mut timer_slot, duration).await
575        };
576        let Stream { read_timer, .. } = self;
577        *read_timer = timer_slot;
578        match outcome {
579            Some(result) => result,
580            None => Err(RequestError::ReadTimeout(HttpStatus::RequestTimeout)),
581        }
582    }
583
584    /// Parses an HTTP request from a TCP stream.
585    ///
586    /// Wraps the stream in a buffered reader and delegates to `http_from_reader`.
587    /// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
588    ///
589    /// # Returns
590    ///
591    /// - `Result<Request, RequestError>` - The parsed request or an error.
592    pub async fn try_get_http_request(&mut self) -> Result<Request, RequestError> {
593        let mut request: Request = Request::default();
594        self.try_fill_http_request(&mut request).await?;
595        Ok(request)
596    }
597
598    /// Parses a WebSocket request from a TCP stream.
599    ///
600    /// Wraps the stream in a buffered reader and delegates to `ws_from_reader`.
601    /// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
602    ///
603    /// # Returns
604    ///
605    /// - `Result<RequestBody, RequestError>` - The parsed WebSocket request or an error.
606    pub async fn try_get_websocket_request(&mut self) -> Result<RequestBody, RequestError> {
607        if self.get_closed() {
608            return self.reset_websocket_state_on_error(Err(RequestError::ServerClosedConnection(
609                HttpStatus::BadRequest,
610            )));
611        }
612        let config: RequestConfig = *self.get_request_config();
613        let read_timeout_ms: u64 = config.get_read_timeout_ms();
614        if self.get_mut_websocket_state().is_none() {
615            let mut buffer: Vec<u8> = mem::take(self.get_mut_leftover());
616            buffer.truncate(self.get_leftover_end());
617            buffer.drain(..self.get_leftover_start());
618            self.set_leftover_start(0);
619            self.set_leftover_end(0);
620            self.set_websocket_state(Some(Box::new(WebSocketReadState {
621                buffer,
622                ..WebSocketReadState::default()
623            })));
624        }
625        let duration_opt: Option<Duration> =
626            if read_timeout_ms == DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS {
627                None
628            } else {
629                let adjusted_timeout_ms: u64 = (read_timeout_ms >> 1) + (read_timeout_ms & 1);
630                Some(Duration::from_millis(adjusted_timeout_ms))
631            };
632        loop {
633            let parsed: Result<WebSocketParseStep, RequestError> =
634                self.try_parse_websocket_request();
635            match self.reset_websocket_state_on_error(parsed)? {
636                WebSocketParseStep::Message(body) => return Ok(body),
637                WebSocketParseStep::Ping(payload) => {
638                    let mut pong: Vec<u8> = Vec::with_capacity(2 + payload.len());
639                    pong.push(0x8A);
640                    pong.push(payload.len() as u8);
641                    pong.extend_from_slice(&payload);
642                    let send_result: Result<(), RequestError> =
643                        self.try_send(&pong).await.map_err(Into::into);
644                    self.reset_websocket_state_on_error(send_result)?;
645                    let flush_result: Result<(), RequestError> =
646                        self.try_flush().await.map_err(Into::into);
647                    self.reset_websocket_state_on_error(flush_result)?;
648                    continue;
649                }
650                WebSocketParseStep::NeedMore => {}
651            }
652            let read: Result<Option<usize>, RequestError> =
653                self.get_websocket_from_stream(duration_opt).await;
654            if matches!(self.reset_websocket_state_on_error(read)?, Some(0)) {
655                return self.reset_websocket_state_on_error(Err(
656                    RequestError::IncompleteWebSocketFrame(HttpStatus::BadRequest),
657                ));
658            }
659        }
660    }
661
662    /// Discards cached parsing state only after an operation completes with an error.
663    ///
664    /// # Arguments
665    ///
666    /// - `Result<T, RequestError>` - The completed parsing or reading operation.
667    ///
668    /// # Returns
669    ///
670    /// - `Result<T, RequestError>` - The unchanged result after releasing failed parsing state.
671    #[inline(always)]
672    fn reset_websocket_state_on_error<T>(
673        &mut self,
674        result: Result<T, RequestError>,
675    ) -> Result<T, RequestError> {
676        if result.is_err() {
677            drop(self.get_mut_websocket_state().take());
678        }
679        result
680    }
681
682    /// Parses buffered frames without discarding incomplete or subsequent input.
683    ///
684    /// Enforces RFC 6455 control frame constraints, continuation sequencing, UTF-8 validity
685    /// for text messages, close-code validity, and the configured `max_body_size` cap.
686    ///
687    /// # Returns
688    ///
689    /// - `Result<WebSocketParseStep, RequestError>` - A complete message, a ping requiring pong, pending input, or a protocol error.
690    fn try_parse_websocket_request(&mut self) -> Result<WebSocketParseStep, RequestError> {
691        let max_body_size: usize = self.get_request_config().get_max_body_size();
692        let state: &mut WebSocketReadState = self.get_mut_websocket_state().as_deref_mut().ok_or(
693            RequestError::IncompleteWebSocketFrame(HttpStatus::BadRequest),
694        )?;
695        let WebSocketReadState {
696            buffer,
697            cursor,
698            full_frame,
699            fragment_opcode,
700            is_client_response,
701        }: &mut WebSocketReadState = state;
702        while let Some((frame, consumed)) =
703            WebSocketFrame::decode_ws_frame_checked(&buffer[*cursor..], max_body_size)?
704        {
705            *is_client_response = true;
706            *cursor += consumed;
707            if *cursor >= buffer.len() {
708                *cursor = 0;
709                let mut recycled: Vec<u8> = mem::take(buffer);
710                recycled.resize(recycled.capacity().min(MAX_POOLED_READ_BUFFER_SIZE), 0);
711                return_read_buffer(recycled);
712            } else if *cursor >= MAX_POOLED_READ_BUFFER_SIZE {
713                buffer.drain(..*cursor);
714                *cursor = 0;
715            }
716            match frame.get_opcode() {
717                WebSocketOpcode::Close => {
718                    let payload: &[u8] = frame.get_payload_data();
719                    if payload.len() == 1 {
720                        return Err(RequestError::WebSocketInvalidCloseCode(
721                            HttpStatus::BadRequest,
722                        ));
723                    }
724                    if payload.len() >= 2 {
725                        let code: u16 = u16::from_be_bytes([payload[0], payload[1]]);
726                        let is_std_close: bool =
727                            (1000..=1003).contains(&code) || (1007..=1011).contains(&code);
728                        let valid_code: bool = is_std_close || (3000..=4999).contains(&code);
729                        if !valid_code {
730                            return Err(RequestError::WebSocketInvalidCloseCode(
731                                HttpStatus::BadRequest,
732                            ));
733                        }
734                        if from_utf8(&payload[2..]).is_err() {
735                            return Err(RequestError::WebSocketInvalidUtf8(HttpStatus::BadRequest));
736                        }
737                    }
738                    return Err(RequestError::ClientClosedConnection(HttpStatus::BadRequest));
739                }
740                WebSocketOpcode::Ping => {
741                    let WebSocketFrame { payload_data, .. }: WebSocketFrame = frame;
742                    return Ok(WebSocketParseStep::Ping(payload_data));
743                }
744                WebSocketOpcode::Pong => continue,
745                WebSocketOpcode::Text | WebSocketOpcode::Binary => {
746                    if fragment_opcode.is_some() {
747                        return Err(RequestError::WebSocketPayloadCorrupted(
748                            HttpStatus::BadRequest,
749                        ));
750                    }
751                    let is_text: bool = frame.is_text_opcode();
752                    if frame.get_fin() {
753                        let WebSocketFrame { payload_data, .. }: WebSocketFrame = frame;
754                        if is_text && from_utf8(&payload_data).is_err() {
755                            return Err(RequestError::WebSocketInvalidUtf8(HttpStatus::BadRequest));
756                        }
757                        return Ok(WebSocketParseStep::Message(payload_data));
758                    }
759                    let opcode: WebSocketOpcode = *frame.get_opcode();
760                    let payload: &[u8] = frame.get_payload_data();
761                    if max_body_size != DEFAULT_LOW_SECURITY_MAX_BODY_SIZE
762                        && payload.len() > max_body_size
763                    {
764                        return Err(RequestError::WebSocketFrameTooLarge(
765                            HttpStatus::PayloadTooLarge,
766                        ));
767                    }
768                    full_frame.clear();
769                    full_frame.extend_from_slice(payload);
770                    *fragment_opcode = Some(opcode);
771                }
772                WebSocketOpcode::Continuation => {
773                    let Some(active_opcode) = fragment_opcode.as_ref() else {
774                        return Err(RequestError::WebSocketPayloadCorrupted(
775                            HttpStatus::BadRequest,
776                        ));
777                    };
778                    let is_text: bool = active_opcode.is_text();
779                    let payload: &[u8] = frame.get_payload_data();
780                    if max_body_size != DEFAULT_LOW_SECURITY_MAX_BODY_SIZE
781                        && payload.len() > max_body_size.saturating_sub(full_frame.len())
782                    {
783                        return Err(RequestError::WebSocketFrameTooLarge(
784                            HttpStatus::PayloadTooLarge,
785                        ));
786                    }
787                    full_frame.extend_from_slice(payload);
788                    if frame.get_fin() {
789                        *fragment_opcode = None;
790                        let body: RequestBody = mem::take(full_frame);
791                        if is_text && from_utf8(&body).is_err() {
792                            return Err(RequestError::WebSocketInvalidUtf8(HttpStatus::BadRequest));
793                        }
794                        return Ok(WebSocketParseStep::Message(body));
795                    }
796                }
797                WebSocketOpcode::Reserved(_) => {
798                    return Err(RequestError::WebSocketOpcodeUnsupported(
799                        HttpStatus::NotImplemented,
800                    ));
801                }
802            }
803        }
804        Ok(WebSocketParseStep::NeedMore)
805    }
806
807    /// Polls a WebSocket read using a buffer retained only while data is ready.
808    ///
809    /// # Arguments
810    ///
811    /// - `&mut Context<'_>` - The registered task context.
812    ///
813    /// # Returns
814    ///
815    /// - `Poll<io::Result<usize>>` - The bytes appended to persistent parsing state.
816    fn poll_websocket_read(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<usize>> {
817        let capacity: usize = self.get_request_config().get_buffer_size();
818        let max_body_size: usize = self.get_request_config().get_max_body_size();
819        if let Some(state) = self.try_get_websocket_state().as_deref() {
820            let unread: usize = state.get_buffer().len().saturating_sub(state.get_cursor());
821            if max_body_size != DEFAULT_LOW_SECURITY_MAX_BODY_SIZE
822                && unread > max_body_size.saturating_add(14)
823            {
824                return Poll::Ready(Err(io::Error::new(
825                    io::ErrorKind::InvalidData,
826                    WEBSOCKET_FRAME_TOO_LARGE_ERROR,
827                )));
828            }
829        }
830        let mut temporary: Vec<u8> = take_read_buffer(capacity);
831        let mut read_buffer: ReadBuf<'_> = ReadBuf::new(&mut temporary[..capacity]);
832        match Pin::new(&mut **self.get_mut_stream()).poll_read(cx, &mut read_buffer) {
833            Poll::Ready(Ok(())) => {
834                let len: usize = read_buffer.filled().len();
835                temporary.truncate(len);
836                let state: &mut WebSocketReadState =
837                    match self.get_mut_websocket_state().as_deref_mut() {
838                        Some(state) => state,
839                        None => {
840                            return_read_buffer(temporary);
841                            return Poll::Ready(Err(io::Error::new(
842                                io::ErrorKind::InvalidData,
843                                WEBSOCKET_STATE_ERROR,
844                            )));
845                        }
846                    };
847                let cursor: usize = state.get_cursor();
848                if cursor >= state.get_buffer().len() {
849                    state.set_cursor(0);
850                    state.get_mut_buffer().clear();
851                } else if cursor > 0 {
852                    state.get_mut_buffer().drain(..cursor);
853                    state.set_cursor(0);
854                }
855                if state.get_buffer().is_empty() {
856                    mem::swap(state.get_mut_buffer(), &mut temporary);
857                } else {
858                    state.get_mut_buffer().extend_from_slice(&temporary);
859                }
860                return_read_buffer(temporary);
861                Poll::Ready(Ok(len))
862            }
863            Poll::Ready(Err(error)) => {
864                return_read_buffer(temporary);
865                Poll::Ready(Err(error))
866            }
867            Poll::Pending => {
868                return_read_buffer(temporary);
869                Poll::Pending
870            }
871        }
872    }
873
874    /// Reads data from the stream with optional timeout handling.
875    ///
876    /// # Arguments
877    ///
878    /// - `Option<Duration>` - The timeout interval, or no timeout.
879    ///
880    /// # Returns
881    ///
882    /// - `Result<Option<usize>, RequestError>` - Bytes read, a heartbeat, or an error.
883    pub(crate) async fn get_websocket_from_stream(
884        &mut self,
885        duration_opt: Option<Duration>,
886    ) -> Result<Option<usize>, RequestError> {
887        if let Some(duration) = duration_opt {
888            return match timeout(
889                duration,
890                future::poll_fn(|cx: &mut Context<'_>| self.poll_websocket_read(cx)),
891            )
892            .await
893            {
894                Ok(result) => result.map(Some).map_err(Into::into),
895                Err(error) => {
896                    let state: &mut WebSocketReadState =
897                        self.get_mut_websocket_state().as_deref_mut().ok_or(
898                            RequestError::IncompleteWebSocketFrame(HttpStatus::BadRequest),
899                        )?;
900                    if !state.get_is_client_response() {
901                        return Err(error.into());
902                    }
903                    state.set_is_client_response(false);
904                    self.try_send(&PING_FRAME).await?;
905                    Ok(None)
906                }
907            };
908        }
909        future::poll_fn(|cx: &mut Context<'_>| self.poll_websocket_read(cx))
910            .await
911            .map(Some)
912            .map_err(Into::into)
913    }
914
915    /// Sends data over the stream.
916    ///
917    /// # Arguments
918    ///
919    /// - `D` - The data to send, which must implement `AsRef<[u8]>`.
920    ///
921    /// # Returns
922    ///
923    /// - `Result<(), ResponseError>` - Result indicating success or failure.
924    pub async fn try_send<D>(&mut self, data: D) -> Result<(), ResponseError>
925    where
926        D: AsRef<[u8]>,
927    {
928        if self.get_closed() {
929            return Err(ResponseError::ConnectionClosed);
930        }
931        Ok(self.get_mut_stream().write_all(data.as_ref()).await?)
932    }
933
934    /// Sends data over the stream.
935    ///
936    /// # Arguments
937    ///
938    /// - `D` - The data to send, which must implement `AsRef<[u8]>`.
939    ///
940    /// # Panics
941    ///
942    /// Panics if the write operation fails.
943    pub async fn send<D>(&mut self, data: D)
944    where
945        D: AsRef<[u8]>,
946    {
947        self.try_send(data).await.unwrap();
948    }
949
950    /// Sends multiple data.
951    ///
952    /// # Arguments
953    ///
954    /// - `I` - The data list to send, which must implement `IntoIterator<Item = D>` with
955    ///   `D` requiring the `AsRef<[u8]>` bound.
956    ///
957    /// # Returns
958    ///
959    /// - `Result<(), ResponseError>` - Result indicating success or failure.
960    pub async fn try_send_list<I, D>(&mut self, data_iter: I) -> Result<(), ResponseError>
961    where
962        I: IntoIterator<Item = D>,
963        D: AsRef<[u8]>,
964    {
965        if self.get_closed() {
966            return Err(ResponseError::ConnectionClosed);
967        }
968        let stream: &mut Box<dyn Transport> = self.get_mut_stream();
969        for data in data_iter {
970            stream.write_all(data.as_ref()).await?;
971        }
972        Ok(())
973    }
974
975    /// Sends multiple data.
976    ///
977    /// # Arguments
978    ///
979    /// - `I` - The data list to send, which must implement `IntoIterator<Item = D>` with
980    ///   `D` requiring the `AsRef<[u8]>` bound.
981    ///
982    /// # Panics
983    ///
984    /// Panics if any write operation fails.
985    pub async fn send_list<I, D>(&mut self, data_iter: I)
986    where
987        I: IntoIterator<Item = D>,
988        D: AsRef<[u8]>,
989    {
990        self.try_send_list(data_iter).await.unwrap();
991    }
992
993    /// Flushes all buffered data to the stream.
994    ///
995    /// # Returns
996    ///
997    /// - `Result<(), ResponseError>` - Result indicating success or failure.
998    pub async fn try_flush(&mut self) -> Result<(), ResponseError> {
999        if self.get_closed() {
1000            return Err(ResponseError::ConnectionClosed);
1001        }
1002        Ok(self.get_mut_stream().flush().await?)
1003    }
1004
1005    /// Flushes all buffered data to the stream.
1006    ///
1007    /// # Panics
1008    ///
1009    /// Panics if the flush operation fails.
1010    pub async fn flush(&mut self) {
1011        self.try_flush().await.unwrap();
1012    }
1013}