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 [`WsHeartbeatWheel`].
271impl WsHeartbeatWheel {
272 /// Creates a new staggered heartbeat wheel with `bucket_count` watch channels.
273 ///
274 /// # Arguments
275 ///
276 /// - `usize` - Number of phase buckets.
277 ///
278 /// # Returns
279 ///
280 /// - `Self` - Initialized active heartbeat wheel.
281 pub(crate) fn new(bucket_count: usize) -> Self {
282 let mut buckets: Vec<Sender<u64>> = Vec::with_capacity(bucket_count);
283 for _ in 0..bucket_count {
284 let (tx, _): (Sender<u64>, Receiver<u64>) = watch::channel(0u64);
285 buckets.push(tx);
286 }
287 Self {
288 buckets: buckets.into_boxed_slice(),
289 phase: AtomicUsize::new(0),
290 alive: AtomicBool::new(true),
291 }
292 }
293
294 /// Subscribes to the phase bucket farthest from the next tick.
295 ///
296 /// # Returns
297 ///
298 /// - `Receiver<u64>` - Watch receiver positioned on the most recently ticked phase bucket.
299 #[inline]
300 pub(crate) fn subscribe_staggered(&self) -> Receiver<u64> {
301 let Self { buckets, phase, .. } = self;
302 let len: usize = buckets.len();
303 let cur: usize = phase.load(Ordering::Acquire);
304 let bucket_idx: usize = (cur.wrapping_add(len - 1)) % len;
305 let mut rx: Receiver<u64> = buckets[bucket_idx].subscribe();
306 let _: u64 = *rx.borrow_and_update();
307 rx
308 }
309
310 /// Counts active WebSocket heartbeat receivers across all phase buckets.
311 ///
312 /// # Returns
313 ///
314 /// - `usize` - Total live receivers subscribed to this wheel.
315 #[inline]
316 pub(crate) fn total_receivers(&self) -> usize {
317 let Self { buckets, .. } = self;
318 let mut total: usize = 0;
319 for bucket in buckets.iter() {
320 total += bucket.receiver_count();
321 }
322 total
323 }
324}
325
326/// Default construction for [`WebSocketReadState`].
327impl Default for WebSocketReadState {
328 /// Initializes empty WebSocket parsing state.
329 ///
330 /// # Returns
331 ///
332 /// - `Self` - The initial WebSocket read state.
333 #[inline(always)]
334 fn default() -> Self {
335 Self {
336 buffer: Vec::new(),
337 cursor: 0,
338 full_frame: Vec::new(),
339 fragment_opcode: None,
340 }
341 }
342}
343
344/// Inherent implementation of [`Stream`].
345impl Stream {
346 /// Boxes a transport into a `Stream` for the request pipeline.
347 ///
348 /// This is the single construction path: a plain TCP socket, a TLS session
349 /// and a per-request duplex stream all enter here, so nothing above the
350 /// transport line has to know which one it is serving. The transport is
351 /// type erased immediately, which keeps `Stream` a fixed size regardless of
352 /// the concrete protocol adapter behind it.
353 ///
354 /// # Arguments
355 ///
356 /// - `T` - The transport type to serve the request cycle over.
357 /// - `RequestConfig` - The parsing limits and read timeout for the cycle.
358 /// - `bool` - Whether the connection starts already closed.
359 ///
360 /// # Returns
361 ///
362 /// - `Self` - A stream serving bytes through the boxed transport.
363 pub fn from_transport<T>(transport: T, request_config: RequestConfig, closed: bool) -> Self
364 where
365 T: Transport + 'static,
366 {
367 Self {
368 stream: Box::new(transport),
369 request_config,
370 closed,
371 ws_client_response: true,
372 leftover: Vec::new(),
373 leftover_start: 0,
374 leftover_end: 0,
375 line_buffer: String::new(),
376 header_line_buffer: String::new(),
377 websocket_state: None,
378 read_timer: StreamTimer::None,
379 }
380 }
381
382 /// Boxes a TCP socket into a `Stream` for the request pipeline.
383 ///
384 /// Kept as the socket-facing constructor so the accept loop keeps its
385 /// existing call shape; it delegates to `from_transport`, so there is one
386 /// construction path rather than two.
387 ///
388 /// # Arguments
389 ///
390 /// - `TcpStream` - The accepted socket to serve the request cycle over.
391 /// - `RequestConfig` - The parsing limits and read timeout for the cycle.
392 /// - `bool` - Whether the connection starts already closed.
393 ///
394 /// # Returns
395 ///
396 /// - `Self` - A stream serving bytes through the boxed socket.
397 pub fn new(stream: TcpStream, request_config: RequestConfig, closed: bool) -> Self {
398 Self::from_transport(stream, request_config, closed)
399 }
400
401 /// Reports the address of the remote end of the transport.
402 ///
403 /// Delegates to the transport itself, so a transport without a socket
404 /// identity answers with an error rather than a fabricated address.
405 ///
406 /// # Returns
407 ///
408 /// - `Result<SocketAddr, io::Error>` - The peer address reported by the transport.
409 #[inline(always)]
410 pub fn get_peer_addr(&self) -> Result<SocketAddr, io::Error> {
411 self.get_stream().peer_addr()
412 }
413
414 /// Reports the address of the local end of the transport.
415 ///
416 /// Delegates to the transport itself, so a transport without a socket
417 /// identity answers with an error rather than a fabricated address.
418 ///
419 /// # Returns
420 ///
421 /// - `Result<SocketAddr, io::Error>` - The local address reported by the transport.
422 #[inline(always)]
423 pub fn get_local_addr(&self) -> Result<SocketAddr, io::Error> {
424 self.get_stream().local_addr()
425 }
426
427 /// Shuts the transport down.
428 ///
429 /// The transport itself is crate-internal, so a caller that needs to
430 /// close the connection reaches it through this method rather than
431 /// through the field.
432 ///
433 /// # Returns
434 ///
435 /// - `Result<(), io::Error>` - Whether the transport shut down.
436 #[inline(always)]
437 pub async fn shutdown(&mut self) -> Result<(), io::Error> {
438 self.get_mut_stream().shutdown().await
439 }
440
441 /// Checks if the connection should be kept alive.
442 ///
443 /// This method evaluates whether the connection should remain open based on
444 /// the closed state and the keep_alive parameter.
445 ///
446 /// # Arguments
447 ///
448 /// - `bool` - Whether keep-alive is enabled for the request.
449 ///
450 /// # Returns
451 ///
452 /// - `bool` - True if the connection should be kept alive, otherwise false.
453 #[inline(always)]
454 pub fn is_keep_alive(&self, keep_alive: bool) -> bool {
455 !self.get_closed() && keep_alive
456 }
457
458 /// Parses the HTTP request content from the stream into the given request.
459 ///
460 /// The request is reset first, then filled in place so its existing
461 /// allocations are reused across keep-alive requests.
462 ///
463 /// # Arguments
464 ///
465 /// - `&mut Request` - The request object to fill.
466 ///
467 /// # Returns
468 ///
469 /// - `Result<(), RequestError>` - Ok on success, or an error if parsing fails.
470 async fn fill_http_from_stream(&mut self, request: &mut Request) -> Result<(), RequestError> {
471 request.reset();
472 let config: RequestConfig = *self.get_request_config();
473 let buffer_size: usize = config.get_buffer_size();
474 let max_path_size: usize = config.get_max_path_size();
475 // Fast path: when no pipelined leftover bytes exist, read directly into an
476 // uninitialized stack buffer inside `poll_fn` (zero future size overhead,
477 // zero idle connection memory, zero `READ_BUFFER_POOL` TLS churn).
478 let mut start: usize = self.get_leftover_start();
479 let mut end: usize = self.get_leftover_end();
480 let mut buffer: Vec<u8> = mem::take(self.get_mut_leftover());
481 self.set_leftover_start(0);
482 self.set_leftover_end(0);
483 let mut pre_parsed_framing: Option<RequestFraming> = None;
484 if start >= end {
485 if !buffer.is_empty() {
486 return_read_buffer(buffer);
487 }
488 let read_cap: usize = buffer_size.clamp(1, STACK_READ_BUF_SIZE);
489 let fast_outcome: FastHttpRead = {
490 let Stream {
491 stream,
492 line_buffer,
493 ..
494 } = self;
495 line_buffer.clear();
496 future::poll_fn(|cx: &mut Context<'_>| {
497 let mut stack_buf: [MaybeUninit<u8>; STACK_READ_BUF_SIZE] =
498 [const { MaybeUninit::uninit() }; STACK_READ_BUF_SIZE];
499 let mut read_buf: ReadBuf<'_> = ReadBuf::uninit(&mut stack_buf[..read_cap]);
500 match Pin::new(&mut **stream).poll_read(cx, &mut read_buf) {
501 Poll::Pending => Poll::Pending,
502 Poll::Ready(Err(error)) => Poll::Ready(Err(RequestError::from(error))),
503 Poll::Ready(Ok(())) => {
504 let filled: &[u8] = read_buf.filled();
505 let filled_len: usize = filled.len();
506 if filled_len == 0 {
507 return Poll::Ready(Err(RequestError::ClientClosedConnection(
508 HttpStatus::BadRequest,
509 )));
510 }
511 match request.parse_http_head_from_slice(filled, &config, line_buffer) {
512 Err(error) => Poll::Ready(Err(error)),
513 Ok(Some((RequestFraming::Fixed(content_size), consumed))) => {
514 let avail: usize = filled_len - consumed;
515 if content_size <= avail {
516 if content_size > 0 {
517 let body: &mut Vec<u8> = request.get_mut_body();
518 body.clear();
519 body.extend_from_slice(
520 &filled[consumed..consumed + content_size],
521 );
522 }
523 let after_body: usize = consumed + content_size;
524 if after_body < filled_len {
525 let mut pooled: Vec<u8> =
526 take_read_buffer(buffer_size.max(filled_len));
527 pooled[after_body..filled_len]
528 .copy_from_slice(&filled[after_body..filled_len]);
529 Poll::Ready(Ok(FastHttpRead::CompleteWithLeftover(
530 pooled, after_body, filled_len,
531 )))
532 } else {
533 Poll::Ready(Ok(FastHttpRead::Complete))
534 }
535 } else {
536 let pooled: Vec<u8> = if avail > 0 {
537 let mut buf: Vec<u8> =
538 take_read_buffer(buffer_size.max(avail));
539 buf[..avail]
540 .copy_from_slice(&filled[consumed..filled_len]);
541 buf
542 } else {
543 Vec::new()
544 };
545 Poll::Ready(Ok(FastHttpRead::BodyPending(
546 RequestFraming::Fixed(content_size),
547 pooled,
548 avail,
549 )))
550 }
551 }
552 Ok(Some((RequestFraming::Chunked, consumed))) => {
553 let avail: usize = filled_len - consumed;
554 let pooled: Vec<u8> = if avail > 0 {
555 let mut buf: Vec<u8> =
556 take_read_buffer(buffer_size.max(avail));
557 buf[..avail].copy_from_slice(&filled[consumed..filled_len]);
558 buf
559 } else {
560 Vec::new()
561 };
562 Poll::Ready(Ok(FastHttpRead::BodyPending(
563 RequestFraming::Chunked,
564 pooled,
565 avail,
566 )))
567 }
568 Ok(None) => {
569 let mut pooled: Vec<u8> =
570 take_read_buffer(buffer_size.max(filled_len));
571 pooled[..filled_len].copy_from_slice(filled);
572 Poll::Ready(Ok(FastHttpRead::IncompleteHead(
573 pooled, filled_len,
574 )))
575 }
576 }
577 }
578 }
579 })
580 .await?
581 };
582 match fast_outcome {
583 FastHttpRead::Complete => return Ok(()),
584 FastHttpRead::CompleteWithLeftover(pooled, leftover_start, leftover_end) => {
585 self.set_leftover(pooled);
586 self.set_leftover_start(leftover_start);
587 self.set_leftover_end(leftover_end);
588 return Ok(());
589 }
590 FastHttpRead::BodyPending(framing, pooled, avail) => {
591 buffer = pooled;
592 start = 0;
593 end = avail;
594 pre_parsed_framing = Some(framing);
595 }
596 FastHttpRead::IncompleteHead(pooled, filled_len) => {
597 buffer = pooled;
598 start = 0;
599 end = filled_len;
600 }
601 }
602 }
603 // Split the borrow of the stream: the reader takes the transport, the
604 // line buffers are separate fields, so both can be held at once.
605 let Stream {
606 stream,
607 line_buffer,
608 header_line_buffer,
609 ..
610 } = self;
611 let mut reader: PooledReader<'_> = PooledReader::new(stream, buffer, buffer_size);
612 reader.set_start(start);
613 reader.set_end(end);
614 let framing: RequestFraming = match pre_parsed_framing {
615 Some(framing) => framing,
616 None => {
617 line_buffer.clear();
618 let filled_len: usize = future::poll_fn(|cx: &mut Context<'_>| {
619 Pin::new(&mut reader).poll_fill_buf(cx).map_ok(<[u8]>::len)
620 })
621 .await?;
622 if filled_len == 0 {
623 return Err(RequestError::ClientClosedConnection(HttpStatus::BadRequest));
624 }
625 let fast_framing: Option<RequestFraming> = {
626 let slice: &[u8] = &reader.get_buffer()[reader.get_start()..reader.get_end()];
627 match request.parse_http_head_from_slice(slice, &config, line_buffer)? {
628 Some((framing, consumed)) => {
629 Pin::new(&mut reader).consume(consumed);
630 Some(framing)
631 }
632 None => None,
633 }
634 };
635 match fast_framing {
636 Some(framing) => framing,
637 None => {
638 let max_request_line: usize =
639 if max_path_size == DEFAULT_LOW_SECURITY_MAX_PATH_SIZE {
640 usize::MAX
641 } else {
642 max_path_size.saturating_add(HTTP_REQUEST_LINE_OVERHEAD)
643 };
644 let line_len: usize = read_http_line_bounded(
645 &mut reader,
646 line_buffer,
647 max_request_line,
648 RequestError::RequestTooLong(HttpStatus::URITooLong),
649 )
650 .await?;
651 if line_len == 0 {
652 return Err(RequestError::ClientClosedConnection(
653 HttpStatus::BadRequest,
654 ));
655 }
656 let (method, path, version): (Method, &str, HttpVersion) =
657 Request::get_http_first_line(line_buffer)?;
658 Request::check_http_path_size(path, max_path_size)?;
659 let (query_index, hash_index): (Option<usize>, Option<usize>) =
660 Request::find_path_separators(path);
661 let query: &str = Request::get_http_query(path, query_index, hash_index);
662 let max_query_count: usize =
663 if max_path_size == DEFAULT_LOW_SECURITY_MAX_PATH_SIZE {
664 usize::MAX
665 } else {
666 HTTP_MAX_QUERY_PARAM_COUNT
667 };
668 Request::fill_http_querys(
669 query,
670 request.get_mut_querys(),
671 max_query_count,
672 )?;
673 let path_slice: &str =
674 Request::get_http_path(path, query_index, hash_index);
675 request.get_mut_path().push_str(path_slice);
676 request.set_version(version);
677 let framing: RequestFraming = request
678 .get_http_headers(&mut reader, &config, header_line_buffer)
679 .await?;
680 request.set_method(method);
681 framing
682 }
683 }
684 }
685 };
686 match framing {
687 RequestFraming::Fixed(0) => {}
688 RequestFraming::Fixed(content_size) => {
689 let buffered: usize = reader.get_end() - reader.get_start();
690 if content_size <= buffered {
691 let body: &mut Vec<u8> = request.get_mut_body();
692 body.clear();
693 let body_start: usize = reader.get_start();
694 body.extend_from_slice(
695 &reader.get_buffer()[body_start..body_start + content_size],
696 );
697 reader.set_start(body_start + content_size);
698 } else {
699 if expects_http_continue(request) {
700 let transport: &mut Box<dyn Transport> = reader.get_mut_stream();
701 transport.write_all(HTTP_CONTINUE_RESPONSE).await?;
702 transport.flush().await?;
703 }
704 Request::fill_http_body(&mut reader, request.get_mut_body(), content_size)
705 .await?;
706 }
707 }
708 RequestFraming::Chunked => {
709 Box::pin(fill_chunked_request(&mut reader, request, &config)).await?;
710 }
711 }
712 // Preserve bytes read ahead for the next pipelined request: they have
713 // already left the socket and cannot be read again.
714 let reader_start: usize = reader.get_start();
715 let reader_end: usize = reader.get_end();
716 let pending: Vec<u8> = if reader_start < reader_end {
717 mem::take(reader.get_mut_buffer())
718 } else {
719 Vec::new()
720 };
721 drop(reader);
722 let pending_start: usize = if pending.is_empty() { 0 } else { reader_start };
723 let pending_end: usize = if pending.is_empty() { 0 } else { reader_end };
724 self.set_leftover(pending);
725 self.set_leftover_start(pending_start);
726 self.set_leftover_end(pending_end);
727 Ok(())
728 }
729
730 /// Parses an HTTP request from a TCP stream into the given request.
731 ///
732 /// The request is reset and filled in place, reusing its allocations.
733 /// An HTTP/1.1 continue expectation can write an interim response after
734 /// header validation and before waiting for the body. A chunked body is
735 /// decoded, with trailers discarded and its content length normalized.
736 /// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
737 ///
738 /// # Arguments
739 ///
740 /// - `&mut Request` - The request object to reset and fill.
741 ///
742 /// # Returns
743 ///
744 /// - `Result<(), RequestError>` - Ok on success, or an error if parsing fails.
745 pub async fn try_fill_http_request(
746 &mut self,
747 request: &mut Request,
748 ) -> Result<(), RequestError> {
749 if self.get_closed() {
750 return Err(RequestError::ServerClosedConnection(HttpStatus::BadRequest));
751 }
752 let timeout_ms: u64 = self.get_request_config().get_read_timeout_ms();
753 if timeout_ms == DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS {
754 return self.fill_http_from_stream(request).await;
755 }
756 let duration: Duration = Duration::from_millis(timeout_ms);
757 let mut timer_slot: Option<Pin<Box<Sleep>>> = {
758 let Stream { read_timer, .. } = self;
759 match mem::replace(read_timer, StreamTimer::None) {
760 StreamTimer::Sleep(sleep) => Some(sleep),
761 StreamTimer::None | StreamTimer::WsHeartbeat { .. } => None,
762 }
763 };
764 let outcome: Option<Result<(), RequestError>> = {
765 let mut reading: Pin<&mut _> = pin!(self.fill_http_from_stream(request));
766 poll_with_timeout(reading.as_mut(), &mut timer_slot, duration).await
767 };
768 let Stream { read_timer, .. } = self;
769 *read_timer = match timer_slot {
770 Some(sleep) => StreamTimer::Sleep(sleep),
771 None => StreamTimer::None,
772 };
773 match outcome {
774 Some(result) => result,
775 None => Err(RequestError::ReadTimeout(HttpStatus::RequestTimeout)),
776 }
777 }
778
779 /// Parses an HTTP request from a TCP stream.
780 ///
781 /// Wraps the stream in a buffered reader and delegates to `http_from_reader`.
782 /// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
783 ///
784 /// # Returns
785 ///
786 /// - `Result<Request, RequestError>` - The parsed request or an error.
787 pub async fn try_get_http_request(&mut self) -> Result<Request, RequestError> {
788 let mut request: Request = Request::default();
789 self.try_fill_http_request(&mut request).await?;
790 Ok(request)
791 }
792
793 /// Sends an RFC 6455 Pong frame using a zero-allocation stack buffer.
794 ///
795 /// # Arguments
796 ///
797 /// - `&[u8]` - Unmasked Ping payload bytes (`<= 125` bytes per RFC 6455).
798 ///
799 /// # Returns
800 ///
801 /// - `Result<(), RequestError>` - `Ok(())` on write and flush, or transport error.
802 #[cold]
803 async fn send_ws_pong(&mut self, payload: &[u8]) -> Result<(), RequestError> {
804 let len: usize = payload.len();
805 let mut pong: [u8; WS_PONG_STACK_CAP] = [0u8; WS_PONG_STACK_CAP];
806 pong[0] = WS_PONG_FIRST_BYTE;
807 pong[1] = len as u8;
808 pong[2..2 + len].copy_from_slice(payload);
809 self.try_send(&pong[..2 + len]).await?;
810 self.try_flush().await?;
811 Ok(())
812 }
813
814 /// Parses a WebSocket request from a TCP stream.
815 ///
816 /// Uses a zero-idle-buffer pooled read fast path and a runtime-shared staggered heartbeat wheel
817 /// for long-lived idle connections while preserving RFC 6455 framing, ping/pong, and timeouts.
818 ///
819 /// # Returns
820 ///
821 /// - `Result<Vec<u8>, RequestError>` - The parsed WebSocket request or an error.
822 pub async fn try_get_websocket_request(&mut self) -> Result<Vec<u8>, RequestError> {
823 if self.get_closed() {
824 return self.reset_websocket_state_on_error(Err(RequestError::ServerClosedConnection(
825 HttpStatus::BadRequest,
826 )));
827 }
828 if self.get_line_buffer().capacity() > 0 {
829 self.set_line_buffer(String::new());
830 }
831 if self.get_header_line_buffer().capacity() > 0 {
832 self.set_header_line_buffer(String::new());
833 }
834 let leftover_start: usize = self.get_leftover_start();
835 let leftover_end: usize = self.get_leftover_end();
836 if leftover_start < leftover_end {
837 let leftover: Vec<u8> = mem::take(self.get_mut_leftover());
838 self.set_leftover_start(0);
839 self.set_leftover_end(0);
840 let unread: Vec<u8> = leftover[leftover_start..leftover_end].to_vec();
841 return_read_buffer(leftover);
842 self.set_websocket_state(Some(Box::new(WebSocketReadState {
843 buffer: unread,
844 ..WebSocketReadState::default()
845 })));
846 } else if !self.get_leftover().is_empty() {
847 let leftover: Vec<u8> = mem::take(self.get_mut_leftover());
848 self.set_leftover_start(0);
849 self.set_leftover_end(0);
850 return_read_buffer(leftover);
851 }
852 let read_timeout_ms: u64 = self.get_request_config().get_read_timeout_ms();
853 let adjusted_timeout_opt: Option<u64> =
854 if read_timeout_ms == DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS {
855 None
856 } else {
857 Some((read_timeout_ms >> 1) + (read_timeout_ms & 1))
858 };
859 loop {
860 if self.try_get_websocket_state().is_some() {
861 let parsed: Result<WebSocketParseStep, RequestError> =
862 self.try_parse_websocket_request();
863 match self.reset_websocket_state_on_error(parsed)? {
864 WebSocketParseStep::Message(body) => return Ok(body),
865 WebSocketParseStep::Ping(payload) => {
866 let send_res: Result<(), RequestError> =
867 Box::pin(self.send_ws_pong(&payload)).await;
868 self.reset_websocket_state_on_error(send_res)?;
869 continue;
870 }
871 WebSocketParseStep::NeedMore => {}
872 WebSocketParseStep::Eof => {
873 return self.reset_websocket_state_on_error(Err(
874 RequestError::IncompleteWebSocketFrame(HttpStatus::BadRequest),
875 ));
876 }
877 }
878 }
879 let step: Result<WebSocketParseStep, RequestError> =
880 self.read_next_websocket_step(adjusted_timeout_opt).await;
881 match self.reset_websocket_state_on_error(step)? {
882 WebSocketParseStep::Message(body) => return Ok(body),
883 WebSocketParseStep::Ping(payload) => {
884 let send_res: Result<(), RequestError> =
885 Box::pin(self.send_ws_pong(&payload)).await;
886 self.reset_websocket_state_on_error(send_res)?;
887 }
888 WebSocketParseStep::NeedMore => {}
889 WebSocketParseStep::Eof => {
890 return self.reset_websocket_state_on_error(Err(
891 RequestError::IncompleteWebSocketFrame(HttpStatus::BadRequest),
892 ));
893 }
894 }
895 }
896 }
897
898 /// Discards cached parsing state only after an operation completes with an error.
899 ///
900 /// # Arguments
901 ///
902 /// - `Result<T, RequestError>` - The completed parsing or reading operation.
903 ///
904 /// # Returns
905 ///
906 /// - `Result<T, RequestError>` - The unchanged result after releasing failed parsing state.
907 #[inline(always)]
908 fn reset_websocket_state_on_error<T>(
909 &mut self,
910 result: Result<T, RequestError>,
911 ) -> Result<T, RequestError> {
912 if result.is_err() {
913 let Stream {
914 websocket_state,
915 ws_client_response,
916 ..
917 } = self;
918 drop(websocket_state.take());
919 *ws_client_response = true;
920 }
921 result
922 }
923
924 /// Parses buffered frames without discarding incomplete or subsequent input.
925 ///
926 /// Enforces RFC 6455 control frame constraints, continuation sequencing, UTF-8 validity
927 /// for text messages, close-code validity, and the configured `max_body_size` cap.
928 ///
929 /// # Returns
930 ///
931 /// - `Result<WebSocketParseStep, RequestError>` - A complete message, a ping requiring pong, pending input, or a protocol error.
932 fn try_parse_websocket_request(&mut self) -> Result<WebSocketParseStep, RequestError> {
933 let max_body_size: usize = self.get_request_config().get_max_body_size();
934 let Stream {
935 websocket_state,
936 ws_client_response,
937 ..
938 } = self;
939 loop {
940 let next_frame: Option<WebSocketFrame> = {
941 let Some(state) = websocket_state.as_deref_mut() else {
942 return Ok(WebSocketParseStep::NeedMore);
943 };
944 let WebSocketReadState { buffer, cursor, .. }: &mut WebSocketReadState = state;
945 match WebSocketFrame::decode_ws_frame_checked(&buffer[*cursor..], max_body_size)? {
946 Some((frame, consumed)) => {
947 *ws_client_response = true;
948 *cursor += consumed;
949 if *cursor >= buffer.len() {
950 *cursor = 0;
951 *buffer = Vec::new();
952 } else if *cursor >= MAX_POOLED_READ_BUFFER_SIZE {
953 buffer.drain(..*cursor);
954 *cursor = 0;
955 }
956 Some(frame)
957 }
958 None => None,
959 }
960 };
961 let Some(frame) = next_frame else {
962 release_empty_ws_state(websocket_state);
963 return Ok(WebSocketParseStep::NeedMore);
964 };
965 if let Some(step) = process_ws_frame(frame, max_body_size, websocket_state)? {
966 release_empty_ws_state(websocket_state);
967 return Ok(step);
968 }
969 }
970 }
971
972 /// Handles a short sub-second WebSocket read timeout using a connection-scoped `Sleep` timer.
973 ///
974 /// Kept cold and boxed out of the primary future so idle WebSocket tasks do not reserve inline `Sleep` space.
975 ///
976 /// # Arguments
977 ///
978 /// - `Duration` - Adjusted short timeout interval (`< 1000` ms).
979 ///
980 /// # Returns
981 ///
982 /// - `Result<WebSocketParseStep, RequestError>` - Parsed step, heartbeat probe, or timeout error.
983 #[cold]
984 async fn read_ws_step_short_timeout(
985 &mut self,
986 duration: Duration,
987 ) -> Result<WebSocketParseStep, RequestError> {
988 let mut timer_slot: Option<Pin<Box<Sleep>>> = {
989 let Stream { read_timer, .. } = self;
990 match mem::replace(read_timer, StreamTimer::None) {
991 StreamTimer::Sleep(sleep) => Some(sleep),
992 StreamTimer::None | StreamTimer::WsHeartbeat { .. } => None,
993 }
994 };
995 let outcome: Option<Result<WebSocketParseStep, RequestError>> = {
996 let Stream {
997 stream,
998 request_config,
999 websocket_state,
1000 ws_client_response,
1001 ..
1002 } = self;
1003 let mut reading: Pin<&mut _> = pin!(future::poll_fn(|cx: &mut Context<'_>| {
1004 poll_websocket_transport_step(
1005 stream,
1006 request_config,
1007 websocket_state,
1008 ws_client_response,
1009 cx,
1010 )
1011 }));
1012 poll_with_timeout(reading.as_mut(), &mut timer_slot, duration).await
1013 };
1014 let Stream { read_timer, .. } = self;
1015 *read_timer = match timer_slot {
1016 Some(sleep) => StreamTimer::Sleep(sleep),
1017 None => StreamTimer::None,
1018 };
1019 match outcome {
1020 Some(result) => result,
1021 None => self.handle_ws_heartbeat_tick().await,
1022 }
1023 }
1024
1025 /// Sends an RFC 6455 Ping probe on idle timeout, or fails with [`RequestError::ReadTimeout`].
1026 ///
1027 /// Kept cold and boxed out of the primary read future to minimize idle WebSocket future size.
1028 ///
1029 /// # Returns
1030 ///
1031 /// - `Result<WebSocketParseStep, RequestError>` - `NeedMore` after ping, or `ReadTimeout`.
1032 #[cold]
1033 async fn handle_ws_heartbeat_tick(&mut self) -> Result<WebSocketParseStep, RequestError> {
1034 let Stream {
1035 ws_client_response, ..
1036 } = self;
1037 if !*ws_client_response {
1038 return Err(RequestError::ReadTimeout(HttpStatus::RequestTimeout));
1039 }
1040 *ws_client_response = false;
1041 self.try_send(&PING_FRAME).await?;
1042 Ok(WebSocketParseStep::NeedMore)
1043 }
1044
1045 /// Reads the next WebSocket step with optional shared-wheel or short-timeout heartbeat handling.
1046 ///
1047 /// # Arguments
1048 ///
1049 /// - `Option<u64>` - Adjusted ping timeout interval in milliseconds, or `None` when disabled.
1050 ///
1051 /// # Returns
1052 ///
1053 /// - `Result<WebSocketParseStep, RequestError>` - Parsed step, heartbeat probe, EOF, or error.
1054 async fn read_next_websocket_step(
1055 &mut self,
1056 adjusted_timeout_opt: Option<u64>,
1057 ) -> Result<WebSocketParseStep, RequestError> {
1058 if let Some(timeout_ms) = adjusted_timeout_opt
1059 && timeout_ms < WS_HEARTBEAT_MIN_WHEEL_MS
1060 {
1061 return Box::pin(self.read_ws_step_short_timeout(Duration::from_millis(timeout_ms)))
1062 .await;
1063 }
1064 let timed_out: bool = {
1065 let Stream {
1066 stream,
1067 request_config,
1068 websocket_state,
1069 ws_client_response,
1070 read_timer,
1071 ..
1072 } = self;
1073 let hb_rx: Option<&mut Receiver<u64>> = match adjusted_timeout_opt {
1074 None => {
1075 if !matches!(read_timer, StreamTimer::None) {
1076 *read_timer = StreamTimer::None;
1077 }
1078 None
1079 }
1080 Some(timeout_ms) => {
1081 let needs_subscribe: bool = !matches!(
1082 read_timer,
1083 StreamTimer::WsHeartbeat { interval_ms, .. } if *interval_ms == timeout_ms
1084 );
1085 if needs_subscribe {
1086 *read_timer = StreamTimer::WsHeartbeat {
1087 rx: subscribe_ws_heartbeat(timeout_ms),
1088 interval_ms: timeout_ms,
1089 };
1090 }
1091 match read_timer {
1092 StreamTimer::WsHeartbeat { rx, .. } => Some(rx),
1093 StreamTimer::None | StreamTimer::Sleep(_) => None,
1094 }
1095 }
1096 };
1097 let mut reading: Pin<&mut _> = pin!(future::poll_fn(|cx: &mut Context<'_>| {
1098 poll_websocket_transport_step(
1099 stream,
1100 request_config,
1101 websocket_state,
1102 ws_client_response,
1103 cx,
1104 )
1105 }));
1106 match hb_rx {
1107 None => return reading.await,
1108 Some(rx) => {
1109 select! {
1110 biased;
1111 step = reading.as_mut() => return step,
1112 tick = rx.changed() => tick.is_ok(),
1113 }
1114 }
1115 }
1116 };
1117 if timed_out {
1118 return Box::pin(self.handle_ws_heartbeat_tick()).await;
1119 }
1120 Ok(WebSocketParseStep::NeedMore)
1121 }
1122
1123 /// Sends data over the stream.
1124 ///
1125 /// # Arguments
1126 ///
1127 /// - `D` - The data to send, which must implement `AsRef<[u8]>`.
1128 ///
1129 /// # Returns
1130 ///
1131 /// - `Result<(), ResponseError>` - Result indicating success or failure.
1132 pub async fn try_send<D>(&mut self, data: D) -> Result<(), ResponseError>
1133 where
1134 D: AsRef<[u8]>,
1135 {
1136 if self.get_closed() {
1137 return Err(ResponseError::ConnectionClosed);
1138 }
1139 Ok(self.get_mut_stream().write_all(data.as_ref()).await?)
1140 }
1141
1142 /// Sends data over the stream.
1143 ///
1144 /// # Arguments
1145 ///
1146 /// - `D` - The data to send, which must implement `AsRef<[u8]>`.
1147 ///
1148 /// # Panics
1149 ///
1150 /// Panics if the write operation fails.
1151 pub async fn send<D>(&mut self, data: D)
1152 where
1153 D: AsRef<[u8]>,
1154 {
1155 self.try_send(data).await.unwrap();
1156 }
1157
1158 /// Sends multiple data.
1159 ///
1160 /// # Arguments
1161 ///
1162 /// - `I` - The data list to send, which must implement `IntoIterator<Item = D>` with
1163 /// `D` requiring the `AsRef<[u8]>` bound.
1164 ///
1165 /// # Returns
1166 ///
1167 /// - `Result<(), ResponseError>` - Result indicating success or failure.
1168 pub async fn try_send_list<I, D>(&mut self, data_iter: I) -> Result<(), ResponseError>
1169 where
1170 I: IntoIterator<Item = D>,
1171 D: AsRef<[u8]>,
1172 {
1173 if self.get_closed() {
1174 return Err(ResponseError::ConnectionClosed);
1175 }
1176 let stream: &mut Box<dyn Transport> = self.get_mut_stream();
1177 for data in data_iter {
1178 stream.write_all(data.as_ref()).await?;
1179 }
1180 Ok(())
1181 }
1182
1183 /// Sends multiple data.
1184 ///
1185 /// # Arguments
1186 ///
1187 /// - `I` - The data list to send, which must implement `IntoIterator<Item = D>` with
1188 /// `D` requiring the `AsRef<[u8]>` bound.
1189 ///
1190 /// # Panics
1191 ///
1192 /// Panics if any write operation fails.
1193 pub async fn send_list<I, D>(&mut self, data_iter: I)
1194 where
1195 I: IntoIterator<Item = D>,
1196 D: AsRef<[u8]>,
1197 {
1198 self.try_send_list(data_iter).await.unwrap();
1199 }
1200
1201 /// Flushes all buffered data to the stream.
1202 ///
1203 /// # Returns
1204 ///
1205 /// - `Result<(), ResponseError>` - Result indicating success or failure.
1206 pub async fn try_flush(&mut self) -> Result<(), ResponseError> {
1207 if self.get_closed() {
1208 return Err(ResponseError::ConnectionClosed);
1209 }
1210 Ok(self.get_mut_stream().flush().await?)
1211 }
1212
1213 /// Flushes all buffered data to the stream.
1214 ///
1215 /// # Panics
1216 ///
1217 /// Panics if the flush operation fails.
1218 pub async fn flush(&mut self) {
1219 self.try_flush().await.unwrap();
1220 }
1221
1222 /// Returns whether lazy WebSocket frame-parser state is currently allocated.
1223 #[cfg(test)]
1224 pub(crate) fn has_websocket_state(&self) -> bool {
1225 self.websocket_state.is_some()
1226 }
1227}