http_type/request/impl.rs
1use crate::*;
2
3/// Implements the `std::error::Error` trait for `RequestError`.
4impl std::error::Error for RequestError {}
5
6/// Provides a default value for `RequestError`.
7impl Default for RequestError {
8 /// Provides a default value for `RequestError`.
9 ///
10 /// Returns a `RequestError::Unknown` with `HttpStatus::InternalServerError`.
11 fn default() -> Self {
12 RequestError::Unknown(HttpStatus::InternalServerError)
13 }
14}
15
16impl RequestError {
17 /// Gets the HTTP status associated with this error.
18 ///
19 /// Returns the HttpStatus enum variant that corresponds to this error.
20 ///
21 /// # Arguments
22 ///
23 /// - `&self` - The RequestError instance.
24 ///
25 /// # Returns
26 ///
27 /// - `HttpStatus` - The HTTP status associated with this error.
28 #[inline(always)]
29 pub fn get_http_status(&self) -> HttpStatus {
30 match self {
31 Self::HttpRead(status) => *status,
32 Self::GetTcpStream(status) => *status,
33 Self::GetTlsStream(status) => *status,
34 Self::ReadConnection(status) => *status,
35 Self::RequestAborted(status) => *status,
36 Self::TlsStreamConnect(status) => *status,
37 Self::NeedOpenRedirect(status) => *status,
38 Self::MaxRedirectTimes(status) => *status,
39 Self::MethodsNotSupport(status) => *status,
40 Self::RedirectInvalidUrl(status) => *status,
41 Self::ClientDisconnected(status) => *status,
42 Self::RedirectUrlDeadLoop(status) => *status,
43 Self::ClientClosedConnection(status) => *status,
44 Self::IncompleteWebSocketFrame(status) => *status,
45 Self::RequestTooLong(status) => *status,
46 Self::PathTooLong(status) => *status,
47 Self::QueryTooLong(status) => *status,
48 Self::HeaderLineTooLong(status) => *status,
49 Self::TooManyHeaders(status) => *status,
50 Self::HeaderKeyTooLong(status) => *status,
51 Self::HeaderValueTooLong(status) => *status,
52 Self::ContentLengthTooLarge(status) => *status,
53 Self::InvalidContentLength(status) => *status,
54 Self::InvalidUrlScheme(status) => *status,
55 Self::InvalidUrlHost(status) => *status,
56 Self::InvalidUrlPort(status) => *status,
57 Self::InvalidUrlPath(status) => *status,
58 Self::InvalidUrlQuery(status) => *status,
59 Self::InvalidUrlFragment(status) => *status,
60 Self::ReadTimeout(status) => *status,
61 Self::WriteTimeout(status) => *status,
62 Self::TcpConnectionFailed(status) => *status,
63 Self::TlsHandshakeFailed(status) => *status,
64 Self::TlsCertificateInvalid(status) => *status,
65 Self::WebSocketFrameTooLarge(status) => *status,
66 Self::WebSocketOpcodeUnsupported(status) => *status,
67 Self::WebSocketMaskMissing(status) => *status,
68 Self::WebSocketPayloadCorrupted(status) => *status,
69 Self::WebSocketInvalidUtf8(status) => *status,
70 Self::WebSocketInvalidCloseCode(status) => *status,
71 Self::WebSocketInvalidExtension(status) => *status,
72 Self::HttpRequestPartsInsufficient(status) => *status,
73 Self::TcpStreamConnect(status) => *status,
74 Self::TlsConnectorBuild(status) => *status,
75 Self::InvalidUrl(status) => *status,
76 Self::ConfigReadError(status) => *status,
77 Self::TcpStreamConnectString(status) => *status,
78 Self::TlsConnectorBuildString(status) => *status,
79 Self::Request(_) => HttpStatus::BadRequest,
80 Self::Unknown(status) => *status,
81 }
82 }
83
84 /// Gets the numeric HTTP status code associated with this error.
85 ///
86 /// Returns the numeric status code (e.g., 400, 404, 500) that corresponds to this error.
87 ///
88 /// # Arguments
89 ///
90 /// - `&self` - The RequestError instance.
91 ///
92 /// # Returns
93 ///
94 /// - `ResponseStatusCode` - The numeric HTTP status code.
95 pub fn get_http_status_code(&self) -> ResponseStatusCode {
96 self.get_http_status().code()
97 }
98}
99
100impl Default for RequestConfigData {
101 /// Creates a `RequestConfig` with secure default values.
102 ///
103 /// # Returns
104 ///
105 /// - `RequestConfigData ` - A new config instance with secure defaults.
106 #[inline(always)]
107 fn default() -> Self {
108 Self {
109 buffer_size: DEFAULT_BUFFER_SIZE,
110 max_request_line_length: DEFAULT_MAX_REQUEST_LINE_LENGTH,
111 max_path_length: DEFAULT_MAX_PATH_LENGTH,
112 max_query_length: DEFAULT_MAX_QUERY_LENGTH,
113 max_header_line_length: DEFAULT_MAX_HEADER_LINE_LENGTH,
114 max_header_count: DEFAULT_MAX_HEADER_COUNT,
115 max_header_key_length: DEFAULT_MAX_HEADER_KEY_LENGTH,
116 max_header_value_length: DEFAULT_MAX_HEADER_VALUE_LENGTH,
117 max_body_size: DEFAULT_MAX_BODY_SIZE,
118 max_ws_frame_size: DEFAULT_MAX_WS_FRAME_SIZE,
119 max_ws_frames: DEFAULT_MAX_WS_FRAMES,
120 http_read_timeout_ms: DEFAULT_HTTP_READ_TIMEOUT_MS,
121 ws_read_timeout_ms: DEFAULT_WS_READ_TIMEOUT_MS,
122 }
123 }
124}
125
126impl RequestConfigData {
127 /// Creates a config optimized for high-security environments.
128 ///
129 /// This configuration uses more restrictive limits to provide
130 /// maximum protection against various attacks.
131 ///
132 /// # Returns
133 ///
134 /// - `RequestConfigData ` - A new config with high-security settings.
135 #[inline(always)]
136 pub(super) fn high_security() -> Self {
137 Self {
138 buffer_size: DEFAULT_HIGH_SECURITY_BUFFER_SIZE,
139 max_request_line_length: DEFAULT_HIGH_SECURITY_MAX_REQUEST_LINE_LENGTH,
140 max_path_length: DEFAULT_HIGH_SECURITY_MAX_PATH_LENGTH,
141 max_query_length: DEFAULT_HIGH_SECURITY_MAX_QUERY_LENGTH,
142 max_header_line_length: DEFAULT_HIGH_SECURITY_MAX_HEADER_LINE_LENGTH,
143 max_header_count: DEFAULT_HIGH_SECURITY_MAX_HEADER_COUNT,
144 max_header_key_length: DEFAULT_HIGH_SECURITY_MAX_HEADER_KEY_LENGTH,
145 max_header_value_length: DEFAULT_HIGH_SECURITY_MAX_HEADER_VALUE_LENGTH,
146 max_body_size: DEFAULT_HIGH_SECURITY_MAX_BODY_SIZE,
147 max_ws_frame_size: DEFAULT_HIGH_SECURITY_MAX_WS_FRAME_SIZE,
148 max_ws_frames: DEFAULT_HIGH_SECURITY_MAX_WS_FRAMES,
149 http_read_timeout_ms: DEFAULT_HIGH_SECURITY_HTTP_READ_TIMEOUT_MS,
150 ws_read_timeout_ms: DEFAULT_HIGH_SECURITY_WS_READ_TIMEOUT_MS,
151 }
152 }
153}
154
155/// Implementation of `From` trait for `RequestConfig`.
156impl From<RequestConfigData> for RequestConfig {
157 /// Converts a `RequestConfigData` into a `RequestConfig`.
158 ///
159 /// # Arguments
160 ///
161 /// - `RequestConfigData` - The wrapped context data.
162 ///
163 /// # Returns
164 ///
165 /// - `RequestConfig` - The newly created context instance.
166 #[inline(always)]
167 fn from(ctx: RequestConfigData) -> Self {
168 Self(arc_rwlock(ctx))
169 }
170}
171
172impl RequestConfig {
173 /// Creates a new `RequestConfig` with default secure settings.
174 ///
175 /// This constructor initializes the configuration with standard security limits
176 /// suitable for most HTTP request parsing scenarios.
177 ///
178 /// # Returns
179 ///
180 /// - `Self` - A new `RequestConfig` instance with default settings.
181 pub async fn new() -> Self {
182 Self(arc_rwlock(RequestConfigData::default()))
183 }
184
185 /// Creates a new `RequestConfig` with high-security settings.
186 ///
187 /// This constructor initializes the configuration with more restrictive limits
188 /// to provide maximum protection against various attacks in high-risk environments.
189 ///
190 /// # Returns
191 ///
192 /// - `Self` - A new `RequestConfig` instance with high-security settings.
193 pub async fn high_security() -> Self {
194 Self(arc_rwlock(RequestConfigData::high_security()))
195 }
196
197 /// Acquires a read lock on the inner configuration.
198 ///
199 /// This method returns a `RwLockReadGuard` that allows reading the
200 /// `RequestConfigData ` values. Multiple threads can read concurrently.
201 ///
202 /// # Returns
203 ///
204 /// - `RwLockReadGuard<'_, RequestConfigData >` - A read guard providing access to the inner configuration.
205 async fn read(&'_ self) -> RwLockReadGuard<'_, RequestConfigData> {
206 self.get_0().read().await
207 }
208
209 /// Acquires a write lock on the inner configuration.
210 ///
211 /// This method returns a `RwLockWriteGuard` that allows mutating the
212 /// `RequestConfigData ` values. Write access is exclusive.
213 ///
214 /// # Returns
215 ///
216 /// - `RwLockWriteGuard<'_, RequestConfigData >` - A write guard providing exclusive access to the inner configuration.
217 async fn write(&'_ self) -> RwLockWriteGuard<'_, RequestConfigData> {
218 self.get_0().write().await
219 }
220
221 /// Sets the configuration data.
222 ///
223 /// # Arguments
224 ///
225 /// - `RequestConfigData` - The configuration data.
226 ///
227 /// # Returns
228 ///
229 /// - `&Self` - The RequestConfig instance for chaining.
230 pub async fn data(&self, data: RequestConfigData) -> &Self {
231 *self.write().await = data;
232 self
233 }
234
235 /// Gets the configuration data.
236 ///
237 /// # Returns
238 ///
239 /// - `RequestConfigData ` - The inner configuration.
240 pub async fn get_data(&self) -> RequestConfigData {
241 *self.read().await
242 }
243
244 /// Sets the buffer size for reading operations.
245 ///
246 /// # Arguments
247 ///
248 /// - `usize` - The buffer size in bytes.
249 ///
250 /// # Returns
251 ///
252 /// - `&Self` - The RequestConfig instance for chaining.
253 pub async fn buffer_size(&self, buffer_size: usize) -> &Self {
254 self.write().await.set_buffer_size(buffer_size);
255 self
256 }
257
258 /// Sets the maximum length for HTTP request line in bytes.
259 ///
260 /// # Arguments
261 ///
262 /// - `usize` - The maximum request line length.
263 ///
264 /// # Returns
265 ///
266 /// - `&Self` - The RequestConfig instance for chaining.
267 pub async fn max_request_line_length(&self, max_request_line_length: usize) -> &Self {
268 self.write()
269 .await
270 .set_max_request_line_length(max_request_line_length);
271 self
272 }
273
274 /// Sets the maximum length for URL path in bytes.
275 ///
276 /// # Arguments
277 ///
278 /// - `usize` - The maximum path length.
279 ///
280 /// # Returns
281 ///
282 /// - `&Self` - The RequestConfig instance for chaining.
283 pub async fn max_path_length(&self, max_path_length: usize) -> &Self {
284 self.write().await.set_max_path_length(max_path_length);
285 self
286 }
287
288 /// Sets the maximum length for query string in bytes.
289 ///
290 /// # Arguments
291 ///
292 /// - `usize` - The maximum query string length.
293 ///
294 /// # Returns
295 ///
296 /// - `&Self` - The RequestConfig instance for chaining.
297 pub async fn max_query_length(&self, max_query_length: usize) -> &Self {
298 self.write().await.set_max_query_length(max_query_length);
299 self
300 }
301
302 /// Sets the maximum length for a single header line in bytes.
303 ///
304 /// # Arguments
305 ///
306 /// - `usize` - The maximum header line length.
307 ///
308 /// # Returns
309 ///
310 /// - `&Self` - The RequestConfig instance for chaining.
311 pub async fn max_header_line_length(&self, max_header_line_length: usize) -> &Self {
312 self.write()
313 .await
314 .set_max_header_line_length(max_header_line_length);
315 self
316 }
317
318 /// Sets the maximum number of headers allowed in a request.
319 ///
320 /// # Arguments
321 ///
322 /// - `usize` - The maximum header count.
323 ///
324 /// # Returns
325 ///
326 /// - `&Self` - The RequestConfig instance for chaining.
327 pub async fn max_header_count(&self, max_header_count: usize) -> &Self {
328 self.write().await.set_max_header_count(max_header_count);
329 self
330 }
331
332 /// Sets the maximum length for a header key in bytes.
333 ///
334 /// # Arguments
335 ///
336 /// - `usize` - The maximum header key length.
337 ///
338 /// # Returns
339 ///
340 /// - `&Self` - The RequestConfig instance for chaining.
341 pub async fn max_header_key_length(&self, max_header_key_length: usize) -> &Self {
342 self.write()
343 .await
344 .set_max_header_key_length(max_header_key_length);
345 self
346 }
347
348 /// Sets the maximum length for a header value in bytes.
349 ///
350 /// # Arguments
351 ///
352 /// - `usize` - The maximum header value length.
353 ///
354 /// # Returns
355 ///
356 /// - `&Self` - The RequestConfig instance for chaining.
357 pub async fn max_header_value_length(&self, max_header_value_length: usize) -> &Self {
358 self.write()
359 .await
360 .set_max_header_value_length(max_header_value_length);
361 self
362 }
363
364 /// Sets the maximum size for request body in bytes.
365 ///
366 /// # Arguments
367 ///
368 /// - `usize` - The maximum body size.
369 ///
370 /// # Returns
371 ///
372 /// - `&Self` - The RequestConfig instance for chaining.
373 pub async fn max_body_size(&self, max_body_size: usize) -> &Self {
374 self.write().await.set_max_body_size(max_body_size);
375 self
376 }
377
378 /// Sets the maximum size for WebSocket frame in bytes.
379 ///
380 /// # Arguments
381 ///
382 /// - `usize` - The maximum WebSocket frame size.
383 ///
384 /// # Returns
385 ///
386 /// - `&Self` - The RequestConfig instance for chaining.
387 pub async fn max_ws_frame_size(&self, max_ws_frame_size: usize) -> &Self {
388 self.write().await.set_max_ws_frame_size(max_ws_frame_size);
389 self
390 }
391
392 /// Sets the maximum number of WebSocket frames to process in a single request.
393 ///
394 /// # Arguments
395 ///
396 /// - `usize` - The maximum WebSocket frames count.
397 ///
398 /// # Returns
399 ///
400 /// - `&Self` - The RequestConfig instance for chaining.
401 pub async fn max_ws_frames(&self, max_ws_frames: usize) -> &Self {
402 self.write().await.set_max_ws_frames(max_ws_frames);
403 self
404 }
405
406 /// Sets the timeout for reading HTTP request in milliseconds.
407 ///
408 /// # Arguments
409 ///
410 /// - `u64` - The HTTP read timeout in milliseconds.
411 ///
412 /// # Returns
413 ///
414 /// - `&Self` - The RequestConfig instance for chaining.
415 pub async fn http_read_timeout_ms(&self, http_read_timeout_ms: u64) -> &Self {
416 self.write()
417 .await
418 .set_http_read_timeout_ms(http_read_timeout_ms);
419 self
420 }
421
422 /// Sets the timeout for reading WebSocket frames in milliseconds.
423 ///
424 /// # Arguments
425 ///
426 /// - `u64` - The WebSocket read timeout in milliseconds.
427 ///
428 /// # Returns
429 ///
430 /// - `&Self` - The RequestConfig instance for chaining.
431 pub async fn ws_read_timeout_ms(&self, ws_read_timeout_ms: u64) -> &Self {
432 self.write()
433 .await
434 .set_ws_read_timeout_ms(ws_read_timeout_ms);
435 self
436 }
437}
438
439/// Provides a default value for `Request`.
440///
441/// Returns a new `Request` instance with all fields initialized to their default values.
442impl Default for Request {
443 #[inline(always)]
444 fn default() -> Self {
445 Self {
446 method: Method::default(),
447 host: String::new(),
448 version: HttpVersion::default(),
449 path: String::new(),
450 querys: hash_map_xx_hash3_64(),
451 headers: hash_map_xx_hash3_64(),
452 body: Vec::new(),
453 }
454 }
455}
456
457impl Request {
458 /// Parses a query string as_ref key-value pairs.
459 ///
460 /// Expects format "key1=value1&key2=value2". Empty values are allowed.
461 ///
462 /// # Arguments
463 ///
464 /// - `&str` - The query string to parse.
465 ///
466 /// # Returns
467 ///
468 /// - `HashMap<String, String>` - The parsed query parameters.
469 fn parse_querys<Q>(query: Q) -> RequestQuerys
470 where
471 Q: AsRef<str>,
472 {
473 let mut query_map: RequestQuerys = hash_map_xx_hash3_64();
474 for pair in query.as_ref().split(AND) {
475 if let Some((key, value)) = pair.split_once(EQUAL) {
476 if !key.is_empty() {
477 query_map.insert(key.to_string(), value.to_string());
478 }
479 } else if !pair.is_empty() {
480 query_map.insert(pair.to_string(), String::new());
481 }
482 }
483 query_map
484 }
485
486 /// Parses HTTP headers from a buffered reader.
487 ///
488 /// This method reads header lines from the provided buffered reader until an empty line
489 /// is encountered, which indicates the end of headers. It validates header count, length,
490 /// and content according to the provided configuration.
491 ///
492 /// # Arguments
493 ///
494 /// - `&mut R` - A mutable reference to a buffered reader implementing `AsyncBufReadExt`.
495 /// - `&RequestConfig` - Configuration for security limits and buffer settings.
496 ///
497 /// # Returns
498 ///
499 /// - `Result<(RequestHeaders, RequestHost, usize), RequestError>` - A tuple containing:
500 /// - The parsed headers as a hash map
501 /// - The host value extracted from the Host header
502 /// - The content length extracted from the Content-Length header
503 /// - Or an error if parsing fails
504 async fn parse_headers<R>(
505 reader: &mut R,
506 config: &RequestConfig,
507 ) -> Result<(RequestHeaders, RequestHost, usize), RequestError>
508 where
509 R: AsyncBufReadExt + Unpin,
510 {
511 let config_inner: RequestConfigData = config.get_data().await;
512 let buffer_size: usize = config_inner.get_buffer_size();
513 let max_header_line_length: usize = config_inner.get_max_header_line_length();
514 let max_header_count: usize = config_inner.get_max_header_count();
515 let max_header_key_length: usize = config_inner.get_max_header_key_length();
516 let max_header_value_length: usize = config_inner.get_max_header_value_length();
517 let max_body_size: usize = config_inner.get_max_body_size();
518 let mut headers: RequestHeaders = hash_map_xx_hash3_64();
519 let mut host: RequestHost = String::new();
520 let mut content_length: usize = 0;
521 let mut header_count: usize = 0;
522 loop {
523 let header_line: &mut String = &mut String::with_capacity(buffer_size);
524 let bytes_read: usize = AsyncBufReadExt::read_line(reader, header_line)
525 .await
526 .map_err(|_| RequestError::HttpRead(HttpStatus::BadRequest))?;
527 if bytes_read > max_header_line_length {
528 return Err(RequestError::HeaderLineTooLong(
529 HttpStatus::RequestHeaderFieldsTooLarge,
530 ));
531 }
532 let header_line: &str = header_line.trim();
533 if header_line.is_empty() {
534 break;
535 }
536 header_count += 1;
537 if header_count > max_header_count {
538 return Err(RequestError::TooManyHeaders(
539 HttpStatus::RequestHeaderFieldsTooLarge,
540 ));
541 }
542 if let Some((key_part, value_part)) = header_line.split_once(COLON) {
543 let key: String = key_part.trim().to_ascii_lowercase();
544 if key.is_empty() {
545 continue;
546 }
547 if key.len() > max_header_key_length {
548 return Err(RequestError::HeaderKeyTooLong(
549 HttpStatus::RequestHeaderFieldsTooLarge,
550 ));
551 }
552 let value: String = value_part.trim().to_string();
553 if value.len() > max_header_value_length {
554 return Err(RequestError::HeaderValueTooLong(
555 HttpStatus::RequestHeaderFieldsTooLarge,
556 ));
557 }
558 if key == HOST {
559 host = value.clone();
560 } else if key == CONTENT_LENGTH {
561 match value.parse::<usize>() {
562 Ok(length) => {
563 if length > max_body_size {
564 return Err(RequestError::ContentLengthTooLarge(
565 HttpStatus::PayloadTooLarge,
566 ));
567 }
568 content_length = length;
569 }
570 Err(_) => {
571 return Err(RequestError::InvalidContentLength(HttpStatus::BadRequest));
572 }
573 }
574 }
575 headers.entry(key).or_default().push_back(value);
576 }
577 }
578 Ok((headers, host, content_length))
579 }
580
581 /// Parses an HTTP request from a TCP stream.
582 ///
583 /// Wraps the stream in a buffered reader and delegates to `http_from_reader`.
584 ///
585 /// # Arguments
586 ///
587 /// - `&ArcRwLock<TcpStream>` - The TCP stream to read from.
588 /// - `&RequestConfig` - Configuration for security limits and buffer settings.
589 ///
590 /// # Returns
591 ///
592 /// - `Result<Request, RequestError>` - The parsed request or an error.
593 pub async fn http_from_stream(
594 stream: &ArcRwLockStream,
595 config: &RequestConfig,
596 ) -> Result<Request, RequestError> {
597 let config_inner: RequestConfigData = config.get_data().await;
598 let buffer_size: usize = config_inner.get_buffer_size();
599 let max_request_line_length: usize = config_inner.get_max_request_line_length();
600 let max_path_length: usize = config_inner.get_max_path_length();
601 let max_query_length: usize = config_inner.get_max_query_length();
602 let http_read_timeout_ms: u64 = config_inner.get_http_read_timeout_ms();
603 timeout(Duration::from_millis(http_read_timeout_ms), async move {
604 let mut buf_stream: RwLockWriteGuard<'_, TcpStream> = stream.write().await;
605 let reader: &mut BufReader<&mut TcpStream> =
606 &mut BufReader::with_capacity(buffer_size, &mut buf_stream);
607 let mut request_line: String = String::with_capacity(buffer_size);
608 let bytes_read: usize = AsyncBufReadExt::read_line(reader, &mut request_line)
609 .await
610 .map_err(|_| RequestError::HttpRead(HttpStatus::BadRequest))?;
611 if bytes_read > max_request_line_length {
612 return Err(RequestError::RequestTooLong(HttpStatus::BadRequest));
613 }
614 let parts: Vec<&str> = request_line.split_whitespace().collect();
615 let parts_len: usize = parts.len();
616 if parts_len < 3 {
617 return Err(RequestError::HttpRequestPartsInsufficient(
618 HttpStatus::BadRequest,
619 ));
620 }
621 let method: RequestMethod = parts[0]
622 .parse::<RequestMethod>()
623 .unwrap_or(Method::Unknown(parts[0].to_string()));
624 let full_path: &str = parts[1];
625 if full_path.len() > max_path_length {
626 return Err(RequestError::PathTooLong(HttpStatus::URITooLong));
627 }
628 let full_path: RequestPath = full_path.to_string();
629 let version: RequestVersion = parts[2]
630 .parse::<RequestVersion>()
631 .unwrap_or(RequestVersion::Unknown(parts[2].to_string()));
632 let hash_index: Option<usize> = full_path.find(HASH);
633 let query_index: Option<usize> = full_path.find(QUERY);
634 let query_string: String = query_index.map_or_else(String::new, |i| {
635 let temp: &str = &full_path[i + 1..];
636 if hash_index.is_none() || hash_index.unwrap() <= i {
637 return temp.to_owned();
638 }
639 temp.split(HASH).next().unwrap_or_default().to_owned()
640 });
641 if query_string.len() > max_query_length {
642 return Err(RequestError::QueryTooLong(HttpStatus::URITooLong));
643 }
644 let querys: RequestQuerys = Self::parse_querys(&query_string);
645 let path: RequestPath = if let Some(i) = query_index.or(hash_index) {
646 full_path[..i].to_owned()
647 } else {
648 full_path.to_owned()
649 };
650 let (headers, host, content_length): (RequestHeaders, RequestHost, usize) =
651 Self::parse_headers(reader, config).await?;
652 let mut body: RequestBody = Vec::with_capacity(content_length);
653 if content_length > 0 {
654 body.resize(content_length, 0);
655 AsyncReadExt::read_exact(reader, &mut body)
656 .await
657 .map_err(|_| RequestError::ReadConnection(HttpStatus::BadRequest))?;
658 }
659 Ok(Request {
660 method,
661 host,
662 version,
663 path,
664 querys,
665 headers,
666 body,
667 })
668 })
669 .await
670 .map_err(|_| RequestError::ReadTimeout(HttpStatus::RequestTimeout))?
671 }
672
673 /// Parses a WebSocket request from a TCP stream.
674 ///
675 /// Wraps the stream in a buffered reader and delegates to `ws_from_reader`.
676 ///
677 /// # Arguments
678 ///
679 /// - `&ArcRwLock<TcpStream>` - The TCP stream to read from.
680 /// - `&RequestConfig` - Configuration for security limits and buffer settings.
681 ///
682 /// # Returns
683 ///
684 /// - `Result<Request, RequestError>` - The parsed WebSocket request or an error.
685 pub async fn ws_from_stream(
686 &self,
687 stream: &ArcRwLockStream,
688 config: &RequestConfig,
689 ) -> Result<Request, RequestError> {
690 let config_inner: RequestConfigData = config.get_data().await;
691 let buffer_size: usize = config_inner.get_buffer_size();
692 let max_ws_frame_size: usize = config_inner.get_max_ws_frame_size();
693 let ws_read_timeout_ms: u64 = config_inner.get_ws_read_timeout_ms();
694 let max_ws_frames: usize = config_inner.get_max_ws_frames();
695 let mut dynamic_buffer: Vec<u8> = Vec::with_capacity(buffer_size);
696 let mut temp_buffer: Vec<u8> = vec![0; buffer_size];
697 let mut full_frame: Vec<u8> = Vec::with_capacity(max_ws_frame_size);
698 let mut frame_count: usize = 0;
699 let mut is_client_response: bool = false;
700 let ws_read_timeout_ms: u64 = (ws_read_timeout_ms >> 1) + (ws_read_timeout_ms & 1);
701 let timeout_duration: Duration = Duration::from_millis(ws_read_timeout_ms);
702 loop {
703 let len: usize = match timeout(
704 timeout_duration,
705 stream.write().await.read(&mut temp_buffer),
706 )
707 .await
708 {
709 Ok(result) => match result {
710 Ok(len) => len,
711 Err(error) => {
712 if error.kind() == ErrorKind::ConnectionReset
713 || error.kind() == ErrorKind::ConnectionAborted
714 {
715 return Err(RequestError::ClientDisconnected(HttpStatus::BadRequest));
716 }
717 return Err(RequestError::Unknown(HttpStatus::InternalServerError));
718 }
719 },
720 Err(_) => {
721 if !is_client_response {
722 return Err(RequestError::ReadTimeout(HttpStatus::RequestTimeout));
723 }
724 is_client_response = false;
725 stream
726 .try_send_body(&PING_FRAME)
727 .await
728 .map_err(|_| RequestError::WriteTimeout(HttpStatus::InternalServerError))?;
729 let _ = stream.try_flush().await;
730 continue;
731 }
732 };
733 if len == 0 {
734 return Err(RequestError::IncompleteWebSocketFrame(
735 HttpStatus::BadRequest,
736 ));
737 }
738 dynamic_buffer.extend_from_slice(&temp_buffer[..len]);
739 while let Some((frame, consumed)) = WebSocketFrame::decode_ws_frame(&dynamic_buffer) {
740 is_client_response = true;
741 dynamic_buffer.drain(0..consumed);
742 frame_count += 1;
743 if frame_count > max_ws_frames {
744 return Err(RequestError::TooManyHeaders(
745 HttpStatus::RequestHeaderFieldsTooLarge,
746 ));
747 }
748 match frame.get_opcode() {
749 WebSocketOpcode::Close => {
750 return Err(RequestError::ClientClosedConnection(HttpStatus::BadRequest));
751 }
752 WebSocketOpcode::Ping | WebSocketOpcode::Pong => {
753 continue;
754 }
755 WebSocketOpcode::Text | WebSocketOpcode::Binary => {
756 let payload_data: &[u8] = frame.get_payload_data();
757 if payload_data.len() > max_ws_frame_size {
758 return Err(RequestError::WebSocketFrameTooLarge(
759 HttpStatus::PayloadTooLarge,
760 ));
761 }
762 if full_frame.len() + payload_data.len() > max_ws_frame_size {
763 return Err(RequestError::WebSocketFrameTooLarge(
764 HttpStatus::PayloadTooLarge,
765 ));
766 }
767 full_frame.extend_from_slice(payload_data);
768 if *frame.get_fin() {
769 let mut request: Request = self.clone();
770 request.body = full_frame;
771 return Ok(request);
772 }
773 }
774 _ => {
775 return Err(RequestError::WebSocketOpcodeUnsupported(
776 HttpStatus::NotImplemented,
777 ));
778 }
779 }
780 }
781 }
782 }
783
784 /// Tries to get a query parameter value by key.
785 ///
786 /// The key type must implement AsRef<str> conversion.
787 ///
788 /// # Arguments
789 ///
790 /// - `AsRef<str>` - The query parameter key (implements AsRef<str>).
791 ///
792 /// # Returns
793 ///
794 /// - `Option<RequestQuerysValue>` - The parameter value if exists.
795 #[inline(always)]
796 pub fn try_get_query<K>(&self, key: K) -> Option<RequestQuerysValue>
797 where
798 K: AsRef<str>,
799 {
800 self.querys.get(key.as_ref()).cloned()
801 }
802
803 /// Gets a query parameter value by key.
804 ///
805 /// The key type must implement AsRef<str> conversion.
806 ///
807 /// # Arguments
808 ///
809 /// - `AsRef<str>` - The query parameter key (implements AsRef<str>).
810 ///
811 /// # Returns
812 ///
813 /// - `RequestQuerysValue` - The parameter value if exists.
814 ///
815 /// # Panics
816 ///
817 /// This function will panic if the query parameter key is not found.
818 #[inline(always)]
819 pub fn get_query<K>(&self, key: K) -> RequestQuerysValue
820 where
821 K: AsRef<str>,
822 {
823 self.try_get_query(key).unwrap()
824 }
825
826 /// Tries to retrieve the value of a request header by its key.
827 ///
828 /// # Arguments
829 ///
830 /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
831 ///
832 /// # Returns
833 ///
834 /// - `Option<RequestHeadersValue>` - The optional header values.
835 #[inline(always)]
836 pub fn try_get_header<K>(&self, key: K) -> Option<RequestHeadersValue>
837 where
838 K: AsRef<str>,
839 {
840 self.headers.get(key.as_ref()).cloned()
841 }
842
843 /// Retrieves the value of a request header by its key.
844 ///
845 /// # Arguments
846 ///
847 /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
848 ///
849 /// # Returns
850 ///
851 /// - `RequestHeadersValue` - The optional header values.
852 ///
853 /// # Panics
854 ///
855 /// This function will panic if the header key is not found.
856 #[inline(always)]
857 pub fn get_header<K>(&self, key: K) -> RequestHeadersValue
858 where
859 K: AsRef<str>,
860 {
861 self.try_get_header(key).unwrap()
862 }
863
864 /// Tries to retrieve the first value of a request header by its key.
865 ///
866 /// # Arguments
867 ///
868 /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
869 ///
870 /// # Returns
871 ///
872 /// - `Option<RequestHeadersValueItem>` - The first header value if exists.
873 #[inline(always)]
874 pub fn try_get_header_front<K>(&self, key: K) -> Option<RequestHeadersValueItem>
875 where
876 K: AsRef<str>,
877 {
878 self.headers
879 .get(key.as_ref())
880 .and_then(|values| values.front().cloned())
881 }
882
883 /// Retrieves the first value of a request header by its key.
884 ///
885 /// # Arguments
886 ///
887 /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
888 ///
889 /// # Returns
890 ///
891 /// - `RequestHeadersValueItem` - The first header value if exists.
892 ///
893 /// # Panics
894 ///
895 /// This function will panic if the header key is not found.
896 #[inline(always)]
897 pub fn get_header_front<K>(&self, key: K) -> RequestHeadersValueItem
898 where
899 K: AsRef<str>,
900 {
901 self.try_get_header_front(key).unwrap()
902 }
903
904 /// Tries to retrieve the last value of a request header by its key.
905 ///
906 /// # Arguments
907 ///
908 /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
909 ///
910 /// # Returns
911 ///
912 /// - `Option<RequestHeadersValueItem>` - The last header value if exists.
913 #[inline(always)]
914 pub fn try_get_header_back<K>(&self, key: K) -> Option<RequestHeadersValueItem>
915 where
916 K: AsRef<str>,
917 {
918 self.headers
919 .get(key.as_ref())
920 .and_then(|values| values.back().cloned())
921 }
922
923 /// Retrieves the last value of a request header by its key.
924 ///
925 /// # Arguments
926 ///
927 /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
928 ///
929 /// # Returns
930 ///
931 /// - `RequestHeadersValueItem` - The last header value if exists.
932 ///
933 /// # Panics
934 ///
935 /// This function will panic if the header key is not found.
936 #[inline(always)]
937 pub fn get_header_back<K>(&self, key: K) -> RequestHeadersValueItem
938 where
939 K: AsRef<str>,
940 {
941 self.try_get_header_back(key).unwrap()
942 }
943
944 /// Tries to retrieve the number of values for a specific header.
945 ///
946 /// # Arguments
947 ///
948 /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
949 ///
950 /// # Returns
951 ///
952 /// - `Option<usize>` - The count of values for the header if exists.
953 #[inline(always)]
954 pub fn try_get_header_length<K>(&self, key: K) -> Option<usize>
955 where
956 K: AsRef<str>,
957 {
958 self.headers.get(key.as_ref()).map(|values| values.len())
959 }
960
961 /// Retrieves the number of values for a specific header.
962 ///
963 /// # Arguments
964 ///
965 /// - `AsRef<str>` - The header's key (must implement AsRef<str>).
966 ///
967 /// # Returns
968 ///
969 /// - `usize` - The count of values for the header.
970 ///
971 /// # Panics
972 ///
973 /// This function will panic if the header key is not found.
974 #[inline(always)]
975 pub fn get_header_length<K>(&self, key: K) -> usize
976 where
977 K: AsRef<str>,
978 {
979 self.try_get_header_length(key).unwrap()
980 }
981
982 /// Retrieves the total number of header values across all headers.
983 ///
984 /// # Returns
985 ///
986 /// - `usize` - The total count of all header values.
987 #[inline(always)]
988 pub fn get_headers_values_length(&self) -> usize {
989 self.headers.values().map(|values| values.len()).sum()
990 }
991
992 /// Retrieves the number of unique headers.
993 ///
994 /// # Returns
995 ///
996 /// - `usize` - The count of unique header keys.
997 #[inline(always)]
998 pub fn get_headers_length(&self) -> usize {
999 self.headers.len()
1000 }
1001
1002 /// Checks if a specific header exists.
1003 ///
1004 /// # Arguments
1005 ///
1006 /// - `AsRef<str>` - The header key to check (must implement AsRef<str>).
1007 ///
1008 /// # Returns
1009 ///
1010 /// - `bool` - Whether the header exists.
1011 #[inline(always)]
1012 pub fn has_header<K>(&self, key: K) -> bool
1013 where
1014 K: AsRef<str>,
1015 {
1016 self.headers.contains_key(key.as_ref())
1017 }
1018
1019 /// Checks if a header contains a specific value.
1020 ///
1021 /// # Arguments
1022 ///
1023 /// - `AsRef<str>` - The header key to check (must implement AsRef<str>).
1024 /// - `AsRef<str>` - The value to search for (must implement AsRef<str>).
1025 ///
1026 /// # Returns
1027 ///
1028 /// - `bool` - Whether the header contains the value.
1029 #[inline(always)]
1030 pub fn has_header_value<K, V>(&self, key: K, value: V) -> bool
1031 where
1032 K: AsRef<str>,
1033 V: AsRef<str>,
1034 {
1035 if let Some(values) = self.headers.get(key.as_ref()) {
1036 values.contains(&value.as_ref().to_owned())
1037 } else {
1038 false
1039 }
1040 }
1041
1042 /// Retrieves the body content of the request as a UTF-8 encoded string.
1043 ///
1044 /// This method uses `String::from_utf8_lossy` to convert the byte slice returned by `self.get_body()` as_ref a string.
1045 /// If the byte slice contains invalid UTF-8 sequences, they will be replaced with the Unicode replacement character ().
1046 ///
1047 /// # Returns
1048 ///
1049 /// - `String` - The body content as a string.
1050 #[inline(always)]
1051 pub fn get_body_string(&self) -> String {
1052 String::from_utf8_lossy(self.get_body()).into_owned()
1053 }
1054
1055 /// Deserializes the body content of the request as_ref a specified type `T`.
1056 ///
1057 /// This method first retrieves the body content as a byte slice using `self.get_body()`.
1058 /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
1059 ///
1060 /// # Arguments
1061 ///
1062 /// - `DeserializeOwned` - The target type to deserialize as_ref (must implement DeserializeOwned).
1063 ///
1064 /// # Returns
1065 ///
1066 /// - `Result<T, serde_json::Error>` - The deserialization result.
1067 pub fn try_get_body_json<T>(&self) -> Result<T, serde_json::Error>
1068 where
1069 T: DeserializeOwned,
1070 {
1071 serde_json::from_slice(self.get_body())
1072 }
1073
1074 /// Deserializes the body content of the request as_ref a specified type `T`.
1075 ///
1076 /// This method first retrieves the body content as a byte slice using `self.get_body()`.
1077 /// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
1078 ///
1079 /// # Arguments
1080 ///
1081 /// - `DeserializeOwned` - The target type to deserialize as_ref (must implement DeserializeOwned).
1082 ///
1083 /// # Returns
1084 ///
1085 /// - `T` - The deserialized body content.
1086 ///
1087 /// # Panics
1088 ///
1089 /// This function will panic if the deserialization fails.
1090 pub fn get_body_json<T>(&self) -> T
1091 where
1092 T: DeserializeOwned,
1093 {
1094 self.try_get_body_json().unwrap()
1095 }
1096
1097 /// Converts the request to a formatted string representation.
1098 ///
1099 /// This method provides a human-readable summary of the request, including its method,
1100 /// host, version, path, query parameters, headers, and body information.
1101 ///
1102 /// # Returns
1103 ///
1104 /// - `String` - The formatted request details.
1105 #[inline(always)]
1106 pub fn get_string(&self) -> String {
1107 let body: &Vec<u8> = self.get_body();
1108 let body_type: &'static str = if std::str::from_utf8(body).is_ok() {
1109 PLAIN
1110 } else {
1111 BINARY
1112 };
1113 format!(
1114 "[Request] => [method]: {}; [host]: {}; [version]: {}; [path]: {}; [querys]: {:?}; [headers]: {:?}; [body]: {} bytes {};",
1115 self.get_method(),
1116 self.get_host(),
1117 self.get_version(),
1118 self.get_path(),
1119 self.get_querys(),
1120 self.get_headers(),
1121 body.len(),
1122 body_type
1123 )
1124 }
1125
1126 /// Retrieves the upgrade type from the request headers.
1127 ///
1128 /// This method looks for the `UPGRADE` header and attempts to parse its value
1129 /// as_ref an `UpgradeType`. If the header is missing or the value is invalid,
1130 /// it returns the default `UpgradeType`.
1131 ///
1132 /// # Returns
1133 ///
1134 /// - `UpgradeType` - The parsed upgrade type.
1135 #[inline(always)]
1136 pub fn get_upgrade_type(&self) -> UpgradeType {
1137 let upgrade_type: UpgradeType = self
1138 .try_get_header_back(UPGRADE)
1139 .and_then(|data| data.parse::<UpgradeType>().ok())
1140 .unwrap_or_default();
1141 upgrade_type
1142 }
1143
1144 /// Checks whether the WebSocket upgrade is enabled for this request.
1145 ///
1146 /// This method determines if the `UPGRADE` header indicates a WebSocket connection.
1147 ///
1148 /// # Returns
1149 ///
1150 /// - `bool` - Whether WebSocket upgrade is enabled.
1151 #[inline(always)]
1152 pub fn is_ws(&self) -> bool {
1153 self.get_upgrade_type().is_ws()
1154 }
1155
1156 /// Checks if the current upgrade type is HTTP/2 cleartext (h2c).
1157 ///
1158 /// # Returns
1159 ///
1160 /// - `bool` - Whether the upgrade type is h2c.
1161 #[inline(always)]
1162 pub fn is_h2c(&self) -> bool {
1163 self.get_upgrade_type().is_h2c()
1164 }
1165
1166 /// Checks if the current upgrade type is TLS (any version).
1167 ///
1168 /// # Returns
1169 ///
1170 /// - `bool` - Whether the upgrade type is TLS.
1171 #[inline(always)]
1172 pub fn is_tls(&self) -> bool {
1173 self.get_upgrade_type().is_tls()
1174 }
1175
1176 /// Checks whether the upgrade type is unknown.
1177 ///
1178 /// # Returns
1179 ///
1180 /// - `bool` - Whether the upgrade type is unknown.
1181 #[inline(always)]
1182 pub fn is_unknown_upgrade(&self) -> bool {
1183 self.get_upgrade_type().is_unknown()
1184 }
1185
1186 /// Checks if the HTTP version is HTTP/1.1 or higher.
1187 ///
1188 /// # Returns
1189 ///
1190 /// - `bool` - Whether the version is HTTP/1.1 or higher.
1191 #[inline(always)]
1192 pub fn is_http1_1_or_higher(&self) -> bool {
1193 self.get_version().is_http1_1_or_higher()
1194 }
1195
1196 /// Checks whether the HTTP version is HTTP/0.9.
1197 ///
1198 /// # Returns
1199 ///
1200 /// - `bool` - Whether the version is HTTP/0.9.
1201 #[inline(always)]
1202 pub fn is_http0_9(&self) -> bool {
1203 self.get_version().is_http0_9()
1204 }
1205
1206 /// Checks whether the HTTP version is HTTP/1.0.
1207 ///
1208 /// # Returns
1209 ///
1210 /// - `bool` - Whether the version is HTTP/1.0.
1211 #[inline(always)]
1212 pub fn is_http1_0(&self) -> bool {
1213 self.get_version().is_http1_0()
1214 }
1215
1216 /// Checks whether the HTTP version is HTTP/1.1.
1217 ///
1218 /// # Returns
1219 ///
1220 /// - `bool` - Whether the version is HTTP/1.1.
1221 #[inline(always)]
1222 pub fn is_http1_1(&self) -> bool {
1223 self.get_version().is_http1_1()
1224 }
1225
1226 /// Checks whether the HTTP version is HTTP/2.
1227 ///
1228 /// # Returns
1229 ///
1230 /// - `bool` - Whether the version is HTTP/2.
1231 #[inline(always)]
1232 pub fn is_http2(&self) -> bool {
1233 self.get_version().is_http2()
1234 }
1235
1236 /// Checks whether the HTTP version is HTTP/3.
1237 ///
1238 /// # Returns
1239 ///
1240 /// - `bool` - Whether the version is HTTP/3.
1241 #[inline(always)]
1242 pub fn is_http3(&self) -> bool {
1243 self.get_version().is_http3()
1244 }
1245
1246 /// Checks whether the HTTP version is unknown.
1247 ///
1248 /// # Returns
1249 ///
1250 /// - `bool` - Whether the version is unknown.
1251 #[inline(always)]
1252 pub fn is_unknown_version(&self) -> bool {
1253 self.get_version().is_unknown()
1254 }
1255
1256 /// Checks whether the version belongs to the HTTP family.
1257 ///
1258 /// # Returns
1259 ///
1260 /// - `bool` - Whether the version is HTTP.
1261 #[inline(always)]
1262 pub fn is_http(&self) -> bool {
1263 self.get_version().is_http()
1264 }
1265
1266 /// Checks whether the request method is GET.
1267 ///
1268 /// # Returns
1269 ///
1270 /// - `bool` - Whether the method is GET.
1271 #[inline(always)]
1272 pub fn is_get(&self) -> bool {
1273 self.get_method().is_get()
1274 }
1275
1276 /// Checks whether the request method is POST.
1277 ///
1278 /// # Returns
1279 ///
1280 /// - `bool` - Whether the method is POST.
1281 #[inline(always)]
1282 pub fn is_post(&self) -> bool {
1283 self.get_method().is_post()
1284 }
1285
1286 /// Checks whether the request method is PUT.
1287 ///
1288 /// # Returns
1289 ///
1290 /// - `bool` - Whether the method is PUT.
1291 #[inline(always)]
1292 pub fn is_put(&self) -> bool {
1293 self.get_method().is_put()
1294 }
1295
1296 /// Checks whether the request method is DELETE.
1297 ///
1298 /// # Returns
1299 ///
1300 /// - `bool` - Whether the method is DELETE.
1301 #[inline(always)]
1302 pub fn is_delete(&self) -> bool {
1303 self.get_method().is_delete()
1304 }
1305
1306 /// Checks whether the request method is PATCH.
1307 ///
1308 /// # Returns
1309 ///
1310 /// - `bool` - Whether the method is PATCH.
1311 #[inline(always)]
1312 pub fn is_patch(&self) -> bool {
1313 self.get_method().is_patch()
1314 }
1315
1316 /// Checks whether the request method is HEAD.
1317 ///
1318 /// # Returns
1319 ///
1320 /// - `bool` - Whether the method is HEAD.
1321 #[inline(always)]
1322 pub fn is_head(&self) -> bool {
1323 self.get_method().is_head()
1324 }
1325
1326 /// Checks whether the request method is OPTIONS.
1327 ///
1328 /// # Returns
1329 ///
1330 /// - `bool` - Whether the method is OPTIONS.
1331 #[inline(always)]
1332 pub fn is_options(&self) -> bool {
1333 self.get_method().is_options()
1334 }
1335
1336 /// Checks whether the request method is CONNECT.
1337 ///
1338 /// # Returns
1339 ///
1340 /// - `bool` - Whether the method is CONNECT.
1341 #[inline(always)]
1342 pub fn is_connect(&self) -> bool {
1343 self.get_method().is_connect()
1344 }
1345
1346 /// Checks whether the request method is TRACE.
1347 ///
1348 /// # Returns
1349 ///
1350 /// - `bool` - Whether the method is TRACE.
1351 #[inline(always)]
1352 pub fn is_trace(&self) -> bool {
1353 self.get_method().is_trace()
1354 }
1355
1356 /// Checks whether the request method is UNKNOWN.
1357 ///
1358 /// # Returns
1359 ///
1360 /// - `bool` - Whether the method is UNKNOWN.
1361 #[inline(always)]
1362 pub fn is_unknown_method(&self) -> bool {
1363 self.get_method().is_unknown()
1364 }
1365
1366 /// Determines if a keep-alive connection should be enabled for this request.
1367 ///
1368 /// This function checks the `Connection` header and the HTTP version to determine
1369 /// if keep-alive should be enabled. The logic is as follows:
1370 ///
1371 /// 1. If the `Connection` header exists:
1372 /// - Returns `true` if the header value is "keep-alive" (case-insensitive).
1373 /// - Returns `false` if the header value is "close" (case-insensitive).
1374 /// 2. If no `Connection` header is present:
1375 /// - Returns `true` if the HTTP version is 1.1 or higher.
1376 /// - Returns `false` otherwise.
1377 ///
1378 /// # Returns
1379 ///
1380 /// - `bool` - Whether keep-alive should be enabled.
1381 #[inline(always)]
1382 pub fn is_enable_keep_alive(&self) -> bool {
1383 if let Some(connection_value) = self.try_get_header_back(CONNECTION) {
1384 if connection_value.eq_ignore_ascii_case(KEEP_ALIVE) {
1385 return true;
1386 } else if connection_value.eq_ignore_ascii_case(CLOSE) {
1387 return self.is_ws();
1388 }
1389 }
1390 self.is_http1_1_or_higher() || self.is_ws()
1391 }
1392
1393 /// Determines if keep-alive should be disabled for this request.
1394 ///
1395 /// # Returns
1396 ///
1397 /// - `bool` - Whether keep-alive should be disabled.
1398 #[inline(always)]
1399 pub fn is_disable_keep_alive(&self) -> bool {
1400 !self.is_enable_keep_alive()
1401 }
1402}