Skip to main content

hyperlane/context/
impl.rs

1use crate::*;
2
3/// Implementation of `From` trait for `Context`.
4impl From<ContextData> for Context {
5    /// Converts a `ContextData` into a `Context`.
6    ///
7    /// # Arguments
8    ///
9    /// - `ContextData` - The wrapped context data.
10    ///
11    /// # Returns
12    ///
13    /// - `Context` - The newly created context instance.
14    #[inline(always)]
15    fn from(ctx: ContextData) -> Self {
16        Self(arc_rwlock(ctx))
17    }
18}
19
20/// Implementation of `From` trait for converting `&ArcRwLockStream` into `Context`.
21impl From<&ArcRwLockStream> for Context {
22    /// Converts a reference to a network stream into a `Context` with default request.
23    ///
24    /// # Arguments
25    ///
26    /// - `&ArcRwLockStream` - The network stream reference to convert.
27    ///
28    /// # Returns
29    ///
30    /// - `Context` - The newly created context instance.
31    #[inline(always)]
32    fn from(stream: &ArcRwLockStream) -> Self {
33        let request: Request = Request::default();
34        let mut internal_ctx: ContextData = ContextData::default();
35        internal_ctx
36            .set_stream(Some(stream.clone()))
37            .set_request(request.clone())
38            .get_mut_response()
39            .set_version(request.get_version().clone());
40        internal_ctx.into()
41    }
42}
43
44/// Implementation of `From` trait for converting `ArcRwLockStream` into `Context`.
45impl From<ArcRwLockStream> for Context {
46    /// Converts a network stream into a `Context` with default request.
47    ///
48    /// # Arguments
49    ///
50    /// - `ArcRwLockStream` - The network stream to convert.
51    ///
52    /// # Returns
53    ///
54    /// - `Context` - The newly created context instance.
55    #[inline(always)]
56    fn from(stream: ArcRwLockStream) -> Self {
57        (&stream).into()
58    }
59}
60
61/// Implementation of `PartialEq` trait for `ContextData`.
62impl PartialEq for ContextData {
63    /// Compares two `ContextData` instances for equality.
64    ///
65    /// # Arguments
66    ///
67    /// - `&Self` - The first `ContextData` instance.
68    /// - `&Self` - The second `ContextData` instance.
69    ///
70    /// # Returns
71    ///
72    /// - `bool` - True if the instances are equal, otherwise false.
73    #[inline(always)]
74    fn eq(&self, other: &Self) -> bool {
75        self.get_aborted() == other.get_aborted()
76            && self.get_closed() == other.get_closed()
77            && self.get_request() == other.get_request()
78            && self.get_response() == other.get_response()
79            && self.get_route_params() == other.get_route_params()
80            && self.get_attributes().len() == other.get_attributes().len()
81            && self.try_get_stream().is_some() == other.try_get_stream().is_some()
82    }
83}
84
85/// Implementation of `Eq` trait for `ContextData`.
86impl Eq for ContextData {}
87
88/// Implementation of `PartialEq` trait for `Context`.
89impl PartialEq for Context {
90    /// Compares two `Context` instances for equality.
91    ///
92    /// # Arguments
93    ///
94    /// - `&Self` - The first `Context` instance.
95    /// - `&Self` - The second `Context` instance.
96    ///
97    /// # Returns
98    ///
99    /// - `bool` - True if the instances are equal, otherwise false.
100    #[inline(always)]
101    fn eq(&self, other: &Self) -> bool {
102        if Arc::ptr_eq(self.get_0(), other.get_0()) {
103            return true;
104        }
105        if let (Ok(s), Ok(o)) = (self.get_0().try_read(), other.get_0().try_read()) {
106            *s == *o
107        } else {
108            false
109        }
110    }
111}
112
113/// Implementation of methods for `Context` structure.
114impl Context {
115    /// Creates a new `Context` with the provided network stream and HTTP request.
116    ///
117    /// # Arguments
118    ///
119    /// - `&ArcRwLockStream` - The network stream.
120    /// - `&Request` - The HTTP request.
121    ///
122    /// # Returns
123    ///
124    /// - `Context` - The newly created context.
125    #[inline(always)]
126    pub(crate) fn new(stream: &ArcRwLockStream, request: &Request) -> Context {
127        let mut internal_ctx: ContextData = ContextData::default();
128        internal_ctx
129            .set_stream(Some(stream.clone()))
130            .set_request(request.clone())
131            .get_mut_response()
132            .set_version(request.get_version().clone());
133        internal_ctx.into()
134    }
135
136    /// Acquires a read lock on the inner context data.
137    ///
138    /// # Returns
139    ///
140    /// - `ContextReadGuard` - The read guard for the inner context.
141    async fn read(&self) -> ContextReadGuard<'_> {
142        self.get_0().read().await
143    }
144
145    /// Acquires a write lock on the inner context data.
146    ///
147    /// # Returns
148    ///
149    /// - `ContextWriteGuard` - The write guard for the inner context.
150    async fn write(&self) -> ContextWriteGuard<'_> {
151        self.get_0().write().await
152    }
153
154    /// Reads an HTTP request from the underlying stream.
155    ///
156    /// # Arguments
157    ///
158    /// - `&RequestConfigData` - The request config.
159    ///
160    /// # Returns
161    ///
162    /// - `Result<Request, RequestError>` - The parsed request or error.
163    pub async fn http_from_stream(
164        &self,
165        config: &RequestConfigData,
166    ) -> Result<Request, RequestError> {
167        if self.get_aborted().await {
168            return Err(RequestError::RequestAborted(HttpStatus::BadRequest));
169        }
170        if let Some(stream) = self.try_get_stream().await.as_ref() {
171            let request_res: Result<Request, RequestError> =
172                Request::http_from_stream(stream, config).await;
173            if let Ok(request) = request_res.as_ref() {
174                self.set_request(request).await;
175            }
176            return request_res;
177        };
178        Err(RequestError::GetTcpStream(HttpStatus::BadRequest))
179    }
180
181    /// Reads a WebSocket frame from the underlying stream.
182    ///
183    /// # Arguments
184    ///
185    /// - `&RequestConfigData` - The request config.
186    ///
187    /// # Returns
188    ///
189    /// - `Result<Request, RequestError>` - The parsed frame or error.
190    pub async fn ws_from_stream(
191        &self,
192        config: &RequestConfigData,
193    ) -> Result<Request, RequestError> {
194        if self.get_aborted().await {
195            return Err(RequestError::RequestAborted(HttpStatus::BadRequest));
196        }
197        if let Some(stream) = self.try_get_stream().await.as_ref() {
198            let last_request: Request = self.get_request().await;
199            let request_res: Result<Request, RequestError> =
200                last_request.ws_from_stream(stream, config).await;
201            match request_res.as_ref() {
202                Ok(request) => {
203                    self.set_request(request).await;
204                }
205                Err(_) => {
206                    self.set_request(&last_request).await;
207                }
208            }
209            return request_res;
210        };
211        Err(RequestError::GetTcpStream(HttpStatus::BadRequest))
212    }
213
214    /// Checks if the context has been marked as aborted.
215    ///
216    /// # Returns
217    ///
218    /// - `bool` - True if the context is aborted, otherwise false.
219    pub async fn get_aborted(&self) -> bool {
220        *self.read().await.get_aborted()
221    }
222
223    /// Sets the aborted flag for the context.
224    ///
225    /// # Arguments
226    ///
227    /// - `bool` - The aborted state to set.
228    ///
229    /// # Returns
230    ///
231    /// - `&Self` - Reference to self for method chaining.
232    pub async fn set_aborted(&self, aborted: bool) -> &Self {
233        self.write().await.set_aborted(aborted);
234        self
235    }
236
237    /// Marks the context as aborted.
238    ///
239    /// # Returns
240    ///
241    /// - `&Self` - Reference to the modified context.
242    pub async fn aborted(&self) -> &Self {
243        self.set_aborted(true).await;
244        self
245    }
246
247    /// Cancels the aborted state of the context.
248    ///
249    /// # Returns
250    ///
251    /// - `&Self` - Reference to the modified context.
252    pub async fn cancel_aborted(&self) -> &Self {
253        self.set_aborted(false).await;
254        self
255    }
256
257    /// Checks if the connection is marked as closed.
258    ///
259    /// # Returns
260    ///
261    /// - `bool` - True if the connection is closed, otherwise false.
262    pub async fn get_closed(&self) -> bool {
263        *self.read().await.get_closed()
264    }
265
266    /// Sets the closed flag for the connection.
267    ///
268    /// # Arguments
269    ///
270    /// - `bool` - The new value for the closed flag.
271    ///
272    /// # Returns
273    ///
274    /// - `&Self` - Reference to the modified context.
275    pub async fn set_closed(&self, closed: bool) -> &Self {
276        self.write().await.set_closed(closed);
277        self
278    }
279
280    /// Marks the connection as closed.
281    ///
282    /// # Returns
283    ///
284    /// - `&Self` - Reference to the modified context.
285    pub async fn closed(&self) -> &Self {
286        self.set_closed(true).await;
287        self
288    }
289
290    /// Cancels the closed state of the connection.
291    ///
292    /// # Returns
293    ///
294    /// - `&Self` - Reference to the modified context.
295    pub async fn cancel_closed(&self) -> &Self {
296        self.set_closed(false).await;
297        self
298    }
299
300    /// Checks if the connection has been terminated (aborted or closed).
301    ///
302    /// # Returns
303    ///
304    /// - `bool` - True if the connection is either aborted or closed, otherwise false.
305    pub async fn is_terminated(&self) -> bool {
306        self.get_aborted().await || self.get_closed().await
307    }
308
309    /// Checks if the connection should be kept alive.
310    ///
311    /// This method evaluates whether the connection should remain open based on
312    /// the closed state and the keep_alive parameter.
313    ///
314    /// # Arguments
315    ///
316    /// - `bool` - Whether keep-alive is enabled for the request.
317    ///
318    /// # Returns
319    ///
320    /// - `bool` - True if the connection should be kept alive, otherwise false.
321    pub async fn is_keep_alive(&self, keep_alive: bool) -> bool {
322        !self.get_closed().await && keep_alive
323    }
324
325    /// Retrieves the underlying network stream, if available.
326    ///
327    /// # Returns
328    ///
329    /// - `Option<ArcRwLockStream>` - The thread-safe, shareable network stream if it exists.
330    pub async fn try_get_stream(&self) -> Option<ArcRwLockStream> {
331        self.read().await.try_get_stream().clone()
332    }
333
334    /// Retrieves the underlying network stream.
335    ///
336    /// # Returns
337    ///
338    /// - `ArcRwLockStream` - The thread-safe, shareable network stream.
339    ///
340    /// # Panics
341    ///
342    /// - If the network stream is not found.
343    pub async fn get_stream(&self) -> ArcRwLockStream {
344        self.try_get_stream().await.unwrap()
345    }
346
347    /// Retrieves the remote socket address of the connection.
348    ///
349    /// # Returns
350    ///
351    /// - `Option<SocketAddr>` - The socket address of the remote peer if available.
352    pub async fn try_get_socket_addr(&self) -> Option<SocketAddr> {
353        self.try_get_stream()
354            .await
355            .as_ref()?
356            .read()
357            .await
358            .peer_addr()
359            .ok()
360    }
361
362    /// Retrieves the remote socket address.
363    ///
364    /// # Returns
365    ///
366    /// - `SocketAddr` - The socket address of the remote peer.
367    ///
368    /// # Panics
369    ///
370    /// - If the socket address is not found.
371    pub async fn get_socket_addr(&self) -> SocketAddr {
372        self.try_get_socket_addr().await.unwrap()
373    }
374
375    /// Retrieves the remote socket address as a string.
376    ///
377    /// # Returns
378    ///
379    /// - `Option<String>` - The string representation of the socket address if available.
380    pub async fn try_get_socket_addr_string(&self) -> Option<String> {
381        self.try_get_socket_addr()
382            .await
383            .map(|data| data.to_string())
384    }
385
386    /// Retrieves the remote socket address as a string.
387    ///
388    /// # Returns
389    ///
390    /// - `String` - The string representation of the socket address.
391    ///
392    /// # Panics
393    ///
394    /// - If the socket address is not found.
395    pub async fn get_socket_addr_string(&self) -> String {
396        self.get_socket_addr().await.to_string()
397    }
398
399    /// Retrieves the IP address part of the remote socket address.
400    ///
401    /// # Returns
402    ///
403    /// - `Option<SocketHost>` - The IP address of the remote peer.
404    pub async fn try_get_socket_host(&self) -> Option<SocketHost> {
405        self.try_get_socket_addr()
406            .await
407            .map(|socket_addr: SocketAddr| socket_addr.ip())
408    }
409
410    /// Retrieves the IP address part of the remote socket address.
411    ///
412    /// # Returns
413    ///
414    /// - `SocketHost` - The IP address of the remote peer.
415    ///
416    /// # Panics
417    ///
418    /// - If the socket address is not found.
419    pub async fn get_socket_host(&self) -> SocketHost {
420        self.try_get_socket_host().await.unwrap()
421    }
422
423    /// Retrieves the port number part of the remote socket address.
424    ///
425    /// # Returns
426    ///
427    /// - `Option<SocketPort>` - The port number of the remote peer if available.
428    pub async fn try_get_socket_port(&self) -> Option<SocketPort> {
429        self.try_get_socket_addr()
430            .await
431            .map(|socket_addr: SocketAddr| socket_addr.port())
432    }
433
434    /// Retrieves the port number part of the remote socket address.
435    ///
436    /// # Returns
437    ///
438    /// - `SocketPort` - The port number of the remote peer.
439    ///
440    /// # Panics
441    ///
442    /// - If the socket address is not found.
443    pub async fn get_socket_port(&self) -> SocketPort {
444        self.try_get_socket_port().await.unwrap()
445    }
446
447    /// Retrieves the current HTTP request.
448    ///
449    /// # Returns
450    ///
451    /// - `Request` - A clone of the current request.
452    pub async fn get_request(&self) -> Request {
453        self.read().await.get_request().clone()
454    }
455
456    /// Sets the current HTTP request for the context.
457    ///
458    /// # Arguments
459    ///
460    /// - `&Request` - The request to set in the context.
461    ///
462    /// # Returns
463    ///
464    /// - `&Self` - Reference to the modified context.
465    pub(crate) async fn set_request(&self, request_data: &Request) -> &Self {
466        self.write().await.set_request(request_data.clone());
467        self
468    }
469
470    /// Executes an asynchronous closure with the current request.
471    ///
472    /// This method provides temporary access to the request data without needing to clone it.
473    ///
474    /// # Arguments
475    ///
476    /// - `Fn(Request) -> Fut, FutureSendStatic<R>` - A closure that takes the `Request` and returns a future.
477    ///
478    /// # Returns
479    ///
480    /// - `R` - The result of the provided closure's future.
481    pub async fn with_request<F, Fut, R>(&self, func: F) -> R
482    where
483        F: Fn(Request) -> Fut,
484        Fut: FutureSendStatic<R>,
485    {
486        func(self.read().await.get_request().clone()).await
487    }
488
489    /// Serializes the request to a JSON byte vector.
490    ///
491    /// This method attempts to serialize the entire request structure into a JSON
492    /// formatted byte vector representation.
493    ///
494    /// # Returns
495    ///
496    /// - `Result<Vec<u8>, serde_json::Error>` - The serialized JSON bytes on success,
497    ///   or a serialization error on failure.
498    pub async fn try_get_request_json_vec(&self) -> Result<Vec<u8>, serde_json::Error> {
499        self.read().await.get_request().try_json_vec()
500    }
501
502    /// Serializes the request to a JSON string.
503    ///
504    /// This method attempts to serialize the entire request structure into a JSON
505    /// formatted string representation.
506    ///
507    /// # Returns
508    ///
509    /// - `Result<String, serde_json::Error>` - The serialized JSON string on success,
510    ///   or a serialization error on failure.
511    pub async fn get_request_json_vec(&self) -> Vec<u8> {
512        self.read().await.get_request().json_vec()
513    }
514
515    /// Serializes the request to a JSON string.
516    ///
517    /// This method attempts to serialize the entire request structure into a JSON
518    /// formatted string representation.
519    ///
520    /// # Returns
521    ///
522    /// - `Result<String, serde_json::Error>` - The serialized JSON string on success,
523    ///   or a serialization error on failure.
524    pub async fn try_get_request_json_string(&self) -> Result<String, serde_json::Error> {
525        self.read().await.get_request().try_json_string()
526    }
527
528    /// Serializes the request to a JSON string.
529    ///
530    /// This method serializes the entire request structure into a JSON formatted
531    /// string representation.
532    ///
533    /// # Returns
534    ///
535    /// - `String` - The serialized JSON string.
536    ///
537    /// # Panics
538    ///
539    /// This function will panic if the serialization fails.
540    pub async fn get_request_json_string(&self) -> String {
541        self.read().await.get_request().json_string()
542    }
543
544    /// Retrieves the HTTP version of the request.
545    ///
546    /// # Returns
547    ///
548    /// - `RequestVersion` - The HTTP version of the request.
549    pub async fn get_request_version(&self) -> RequestVersion {
550        self.read().await.get_request().get_version().clone()
551    }
552
553    /// Retrieves the HTTP method of the request.
554    ///
555    /// # Returns
556    ///
557    /// - `RequestMethod` - The HTTP method of the request.
558    pub async fn get_request_method(&self) -> RequestMethod {
559        self.read().await.get_request().get_method().clone()
560    }
561
562    /// Retrieves the host from the request headers.
563    ///
564    /// # Returns
565    ///
566    /// - `RequestHost` - The host part of the request's URI.
567    pub async fn get_request_host(&self) -> RequestHost {
568        self.read().await.get_request().get_host().clone()
569    }
570
571    /// Retrieves the path of the request.
572    ///
573    /// # Returns
574    ///
575    /// - `RequestPath` - The path part of the request's URI.
576    pub async fn get_request_path(&self) -> RequestPath {
577        self.read().await.get_request().get_path().clone()
578    }
579
580    /// Retrieves the query parameters of the request.
581    ///
582    /// # Returns
583    ///
584    /// - `RequestQuerys` - A map containing the query parameters.
585    pub async fn get_request_querys(&self) -> RequestQuerys {
586        self.read().await.get_request().get_querys().clone()
587    }
588
589    /// Attempts to retrieve a specific query parameter by its key.
590    ///
591    /// # Arguments
592    ///
593    /// - `AsRef<str>` - The query parameter key.
594    ///
595    /// # Returns
596    ///
597    /// - `Option<RequestQuerysValue>` - The query parameter value if exists.
598    pub async fn try_get_request_query<K>(&self, key: K) -> Option<RequestQuerysValue>
599    where
600        K: AsRef<str>,
601    {
602        self.read().await.get_request().try_get_query(key)
603    }
604
605    /// Retrieves a specific query parameter by its key, panicking if not found.
606    ///
607    /// # Arguments
608    ///
609    /// - `AsRef<str>` - The query parameter key.
610    ///
611    /// # Returns
612    ///
613    /// - `RequestQuerysValue` - The query parameter value if exists.
614    ///
615    /// # Panics
616    ///
617    /// - If the query parameter is not found.
618    pub async fn get_request_query<K>(&self, key: K) -> RequestQuerysValue
619    where
620        K: AsRef<str>,
621    {
622        self.read().await.get_request().get_query(key)
623    }
624
625    /// Retrieves the body of the request.
626    ///
627    /// # Returns
628    ///
629    /// - `RequestBody` - A clone of the request's body.
630    pub async fn get_request_body(&self) -> RequestBody {
631        self.read().await.get_request().get_body().clone()
632    }
633
634    /// Retrieves the request body as a string.
635    ///
636    /// # Returns
637    ///
638    /// - `String` - The request body converted to a string.
639    pub async fn get_request_body_string(&self) -> String {
640        self.read().await.get_request().get_body_string()
641    }
642
643    /// Deserializes the request body from JSON into a specified type.
644    ///
645    /// # Returns
646    ///
647    /// - `Result<J, serde_json::Error>` - The deserialized type `J` or a JSON error.
648    pub async fn try_get_request_body_json<J>(&self) -> Result<J, serde_json::Error>
649    where
650        J: DeserializeOwned,
651    {
652        self.read().await.get_request().try_get_body_json()
653    }
654
655    /// Deserializes the request body from JSON into a specified type, panicking if not found.
656    ///
657    /// # Returns
658    ///
659    /// - `J` - The deserialized type `J`.
660    ///
661    /// # Panics
662    ///
663    /// - If deserialization fails.
664    pub async fn get_request_body_json<J>(&self) -> J
665    where
666        J: DeserializeOwned,
667    {
668        self.read().await.get_request().get_body_json()
669    }
670
671    /// Retrieves all request headers.
672    ///
673    /// # Returns
674    ///
675    /// - `RequestHeaders` - A clone of the request's header map.
676    pub async fn get_request_headers(&self) -> RequestHeaders {
677        self.read().await.get_request().get_headers().clone()
678    }
679
680    /// Retrieves the total number of request headers.
681    ///
682    /// # Returns
683    ///
684    /// - `usize` - The total number of headers in the request.
685    pub async fn get_request_headers_size(&self) -> usize {
686        self.read().await.get_request().get_headers_size()
687    }
688
689    /// Attempts to retrieve a specific request header by its key.
690    ///
691    /// # Arguments
692    ///
693    /// - `AsRef<str>` - The header key.
694    ///
695    /// # Returns
696    ///
697    /// - `Option<RequestHeadersValue>` - The header values if exists.
698    pub async fn try_get_request_header<K>(&self, key: K) -> Option<RequestHeadersValue>
699    where
700        K: AsRef<str>,
701    {
702        self.read().await.get_request().try_get_header(key)
703    }
704
705    /// Retrieves a specific request header by its key, panicking if not found.
706    ///
707    /// # Arguments
708    ///
709    /// - `AsRef<str>` - The key of the header to retrieve.
710    ///
711    /// # Returns
712    ///
713    /// - `RequestHeadersValue` - The header values if exists.
714    ///
715    /// # Panics
716    ///
717    /// - If the header is not found.
718    pub async fn get_request_header<K>(&self, key: K) -> RequestHeadersValue
719    where
720        K: AsRef<str>,
721    {
722        self.read().await.get_request().get_header(key)
723    }
724
725    /// Attempts to retrieve the first value of a specific request header.
726    ///
727    /// # Arguments
728    ///
729    /// - `AsRef<str>` - The key of the header.
730    ///
731    /// # Returns
732    ///
733    /// - `Option<RequestHeadersValueItem>` - The first value of the header if it exists.
734    pub async fn try_get_request_header_front<K>(&self, key: K) -> Option<RequestHeadersValueItem>
735    where
736        K: AsRef<str>,
737    {
738        self.read().await.get_request().try_get_header_front(key)
739    }
740
741    /// Retrieves the first value of a specific request header, panicking if not found.
742    ///
743    /// # Arguments
744    ///
745    /// - `AsRef<str>` - The key of the header.
746    ///
747    /// # Returns
748    ///
749    /// - `RequestHeadersValueItem` - The first value of the header if it exists.
750    ///
751    /// # Panics
752    ///
753    /// - If the header is not found.
754    pub async fn get_request_header_front<K>(&self, key: K) -> RequestHeadersValueItem
755    where
756        K: AsRef<str>,
757    {
758        self.read().await.get_request().get_header_front(key)
759    }
760
761    /// Attempts to retrieve the last value of a specific request header.
762    ///
763    /// # Arguments
764    ///
765    /// - `AsRef<str>` - The key of the header.
766    ///
767    /// # Returns
768    ///
769    /// - `Option<RequestHeadersValueItem>` - The last value of the header if it exists.
770    pub async fn try_get_request_header_back<K>(&self, key: K) -> Option<RequestHeadersValueItem>
771    where
772        K: AsRef<str>,
773    {
774        self.read().await.get_request().try_get_header_back(key)
775    }
776
777    /// Retrieves the last value of a specific request header, panicking if not found.
778    ///
779    /// # Arguments
780    ///
781    /// - `AsRef<str>` - The key of the header.
782    ///
783    /// # Returns
784    ///
785    /// - `RequestHeadersValueItem` - The last value of the header if it exists.
786    ///
787    /// # Panics
788    ///
789    /// - If the header is not found.
790    pub async fn get_request_header_back<K>(&self, key: K) -> RequestHeadersValueItem
791    where
792        K: AsRef<str>,
793    {
794        self.read().await.get_request().get_header_back(key)
795    }
796
797    /// Attempts to retrieve the number of values for a specific request header.
798    ///
799    /// # Arguments
800    ///
801    /// - `AsRef<str>` - The key of the header.
802    ///
803    /// # Returns
804    ///
805    /// - `Option<usize>` - The number of values for the specified header if it exists.
806    pub async fn try_get_request_header_len<K>(&self, key: K) -> Option<usize>
807    where
808        K: AsRef<str>,
809    {
810        self.read().await.get_request().try_get_header_size(key)
811    }
812
813    /// Retrieves the number of values for a specific request header.
814    ///
815    /// # Arguments
816    ///
817    /// - `AsRef<str>` - The key of the header.
818    ///
819    /// # Returns
820    ///
821    /// - `usize` - The number of values for the specified header.
822    ///
823    /// # Panics
824    ///
825    /// - If the header is not found.
826    pub async fn get_request_header_len<K>(&self, key: K) -> usize
827    where
828        K: AsRef<str>,
829    {
830        self.read().await.get_request().get_header_size(key)
831    }
832
833    /// Retrieves the total number of values across all request headers.
834    ///
835    /// # Returns
836    ///
837    /// - `usize` - The total count of all values in all headers.
838    pub async fn get_request_headers_values_size(&self) -> usize {
839        self.read().await.get_request().get_headers_values_size()
840    }
841
842    /// Checks if a specific request header exists.
843    ///
844    /// # Arguments
845    ///
846    /// - `AsRef<str>` - The key of the header to check.
847    ///
848    /// # Returns
849    ///
850    /// - `bool` - True if the header exists, otherwise false.
851    pub async fn get_request_has_header<K>(&self, key: K) -> bool
852    where
853        K: AsRef<str>,
854    {
855        self.read().await.get_request().has_header(key)
856    }
857
858    /// Checks if a request header has a specific value.
859    ///
860    /// # Arguments
861    ///
862    /// - `AsRef<str>` - The header key.
863    /// - `AsRef<str>` - The value to check.
864    ///
865    /// # Returns
866    ///
867    /// - `bool` - True if header contains the value.
868    pub async fn get_request_has_header_value<K, V>(&self, key: K, value: V) -> bool
869    where
870        K: AsRef<str>,
871        V: AsRef<str>,
872    {
873        self.read().await.get_request().has_header_value(key, value)
874    }
875
876    /// Parses and retrieves all cookies from the request headers.
877    ///
878    /// # Returns
879    ///
880    /// - `Cookies` - A map of cookies parsed from the request's Cookie header.
881    pub async fn get_request_cookies(&self) -> Cookies {
882        self.try_get_request_header_back(COOKIE)
883            .await
884            .map(|data| Cookie::parse(&data))
885            .unwrap_or_default()
886    }
887
888    /// Attempts to retrieve a specific cookie by its name from the request.
889    ///
890    /// # Arguments
891    ///
892    /// - `AsRef<str>` - The cookie name.
893    ///
894    /// # Returns
895    ///
896    /// - `Option<CookieValue>` - The cookie value if exists.
897    pub async fn try_get_request_cookie<K>(&self, key: K) -> Option<CookieValue>
898    where
899        K: AsRef<str>,
900    {
901        self.get_request_cookies().await.get(key.as_ref()).cloned()
902    }
903
904    /// Retrieves a specific cookie by its name from the request, panicking if not found.
905    ///
906    /// # Arguments
907    ///
908    /// - `AsRef<str>` - The cookie name.
909    ///
910    /// # Returns
911    ///
912    /// - `CookieValue` - The cookie value if exists.
913    ///
914    /// # Panics
915    ///
916    /// - If the cookie is not found.
917    pub async fn get_request_cookie<K>(&self, key: K) -> CookieValue
918    where
919        K: AsRef<str>,
920    {
921        self.try_get_request_cookie(key).await.unwrap()
922    }
923
924    /// Retrieves the upgrade type of the request.
925    ///
926    /// # Returns
927    ///
928    /// - `UpgradeType` - The upgrade type of the request.
929    pub async fn get_request_upgrade_type(&self) -> UpgradeType {
930        self.read().await.get_request().get_upgrade_type()
931    }
932
933    /// Checks if the request method is GET.
934    ///
935    /// # Returns
936    ///
937    /// - `bool` - True if the method is GET.
938    pub async fn get_request_is_get_method(&self) -> bool {
939        self.read().await.get_request().is_get_method()
940    }
941
942    /// Checks if the request method is POST.
943    ///
944    /// # Returns
945    ///
946    /// - `bool` - True if the method is POST.
947    pub async fn get_request_is_post_method(&self) -> bool {
948        self.read().await.get_request().is_post_method()
949    }
950
951    /// Checks if the request method is PUT.
952    ///
953    /// # Returns
954    ///
955    /// - `bool` - True if the method is PUT.
956    pub async fn get_request_is_put_method(&self) -> bool {
957        self.read().await.get_request().is_put_method()
958    }
959
960    /// Checks if the request method is DELETE.
961    ///
962    /// # Returns
963    ///
964    /// - `bool` - True if the method is DELETE.
965    pub async fn get_request_is_delete_method(&self) -> bool {
966        self.read().await.get_request().is_delete_method()
967    }
968
969    /// Checks if the request method is PATCH.
970    ///
971    /// # Returns
972    ///
973    /// - `bool` - True if the method is PATCH.
974    pub async fn get_request_is_patch_method(&self) -> bool {
975        self.read().await.get_request().is_patch_method()
976    }
977
978    /// Checks if the request method is HEAD.
979    ///
980    /// # Returns
981    ///
982    /// - `bool` - True if the method is HEAD.
983    pub async fn get_request_is_head_method(&self) -> bool {
984        self.read().await.get_request().is_head_method()
985    }
986
987    /// Checks if the request method is OPTIONS.
988    ///
989    /// # Returns
990    ///
991    /// - `bool` - True if the method is OPTIONS.
992    pub async fn get_request_is_options_method(&self) -> bool {
993        self.read().await.get_request().is_options_method()
994    }
995
996    /// Checks if the request method is CONNECT.
997    ///
998    /// # Returns
999    ///
1000    /// - `bool` - True if the method is CONNECT.
1001    pub async fn get_request_is_connect_method(&self) -> bool {
1002        self.read().await.get_request().is_connect_method()
1003    }
1004
1005    /// Checks if the request method is TRACE.
1006    ///
1007    /// # Returns
1008    ///
1009    /// - `bool` - True if the method is TRACE.
1010    pub async fn get_request_is_trace_method(&self) -> bool {
1011        self.read().await.get_request().is_trace_method()
1012    }
1013
1014    /// Checks if the request method is unknown.
1015    ///
1016    /// # Returns
1017    ///
1018    /// - `bool` - True if the method is unknown.
1019    pub async fn get_request_is_unknown_method(&self) -> bool {
1020        self.read().await.get_request().is_unknown_method()
1021    }
1022
1023    /// Checks if the request HTTP version is HTTP/0.9.
1024    ///
1025    /// # Returns
1026    ///
1027    /// - `bool` - True if the version is HTTP/0.9.
1028    pub async fn get_request_is_http0_9_version(&self) -> bool {
1029        self.read().await.get_request().is_http0_9_version()
1030    }
1031
1032    /// Checks if the request HTTP version is HTTP/1.0.
1033    ///
1034    /// # Returns
1035    ///
1036    /// - `bool` - True if the version is HTTP/1.0.
1037    pub async fn get_request_is_http1_0_version(&self) -> bool {
1038        self.read().await.get_request().is_http1_0_version()
1039    }
1040
1041    /// Checks if the request HTTP version is HTTP/1.1.
1042    ///
1043    /// # Returns
1044    ///
1045    /// - `bool` - True if the version is HTTP/1.1.
1046    pub async fn get_request_is_http1_1_version(&self) -> bool {
1047        self.read().await.get_request().is_http1_1_version()
1048    }
1049
1050    /// Checks if the request HTTP version is HTTP/2.
1051    ///
1052    /// # Returns
1053    ///
1054    /// - `bool` - True if the version is HTTP/2.
1055    pub async fn get_request_is_http2_version(&self) -> bool {
1056        self.read().await.get_request().is_http2_version()
1057    }
1058
1059    /// Checks if the request HTTP version is HTTP/3.
1060    ///
1061    /// # Returns
1062    ///
1063    /// - `bool` - True if the version is HTTP/3.
1064    pub async fn get_request_is_http3_version(&self) -> bool {
1065        self.read().await.get_request().is_http3_version()
1066    }
1067
1068    /// Checks if the request HTTP version is HTTP/1.1 or higher.
1069    ///
1070    /// # Returns
1071    ///
1072    /// - `bool` - True if the version is HTTP/1.1 or higher.
1073    pub async fn get_request_is_http1_1_or_higher_version(&self) -> bool {
1074        self.read()
1075            .await
1076            .get_request()
1077            .is_http1_1_or_higher_version()
1078    }
1079
1080    /// Checks if the request uses HTTP protocol.
1081    ///
1082    /// # Returns
1083    ///
1084    /// - `bool` - True if the version belongs to HTTP family.
1085    pub async fn get_request_is_http_version(&self) -> bool {
1086        self.read().await.get_request().is_http_version()
1087    }
1088
1089    /// Checks if the request has an unknown HTTP version.
1090    ///
1091    /// # Returns
1092    ///
1093    /// - `bool` - True if the version is unknown.
1094    pub async fn get_request_is_unknown_version(&self) -> bool {
1095        self.read().await.get_request().is_unknown_version()
1096    }
1097
1098    /// Checks if the request is a WebSocket upgrade request.
1099    ///
1100    /// # Returns
1101    ///
1102    /// - `bool` - True if this is a WebSocket upgrade request.
1103    pub async fn get_request_is_ws_upgrade_type(&self) -> bool {
1104        self.read().await.get_request().is_ws_upgrade_type()
1105    }
1106
1107    /// Checks if the request is an HTTP/2 cleartext (h2c) upgrade.
1108    ///
1109    /// # Returns
1110    ///
1111    /// - `bool` - True if this is an h2c upgrade request.
1112    pub async fn get_request_is_h2c_upgrade_type(&self) -> bool {
1113        self.read().await.get_request().is_h2c_upgrade_type()
1114    }
1115
1116    /// Checks if the request is a TLS upgrade.
1117    ///
1118    /// # Returns
1119    ///
1120    /// - `bool` - True if this is a TLS upgrade request.
1121    pub async fn get_request_is_tls_upgrade_type(&self) -> bool {
1122        self.read().await.get_request().is_tls_upgrade_type()
1123    }
1124
1125    /// Checks if the request has an unknown upgrade type.
1126    ///
1127    /// # Returns
1128    ///
1129    /// - `bool` - True if the upgrade type is unknown.
1130    pub async fn get_request_is_unknown_upgrade_type(&self) -> bool {
1131        self.read().await.get_request().is_unknown_upgrade_type()
1132    }
1133
1134    /// Checks if the connection should be kept alive based on request headers.
1135    ///
1136    /// # Returns
1137    ///
1138    /// - `bool` - True if the Connection header suggests keeping the connection alive, otherwise false.
1139    pub async fn get_request_is_enable_keep_alive(&self) -> bool {
1140        self.read().await.get_request().is_enable_keep_alive()
1141    }
1142
1143    /// Checks if keep-alive should be disabled for the request.
1144    ///
1145    /// # Returns
1146    ///
1147    /// - `bool` - True if keep-alive should be disabled.
1148    pub async fn get_request_is_disable_keep_alive(&self) -> bool {
1149        self.read().await.get_request().is_disable_keep_alive()
1150    }
1151
1152    /// Retrieves the current HTTP response.
1153    ///
1154    /// # Returns
1155    ///
1156    /// - `Response` - A clone of the current response.
1157    pub async fn get_response(&self) -> Response {
1158        self.read().await.get_response().clone()
1159    }
1160
1161    /// Sets the HTTP response for the context.
1162    ///
1163    /// # Arguments
1164    ///
1165    /// - `Borrow<Response>` - The response to set in the context.
1166    ///
1167    /// # Returns
1168    ///
1169    /// - `&Self` - Reference to the modified context.
1170    pub async fn set_response<T>(&self, response: T) -> &Self
1171    where
1172        T: Borrow<Response>,
1173    {
1174        self.write().await.set_response(response.borrow().clone());
1175        self
1176    }
1177
1178    /// Executes an asynchronous closure with the current response.
1179    ///
1180    /// # Arguments
1181    ///
1182    /// - `F: Fn(Response) -> Fut, Fut: FutureSendStatic<R>,` - A closure that takes the `Response` and returns a future.
1183    ///
1184    /// # Returns
1185    ///
1186    /// - `R` - The result of the provided closure's future.
1187    pub async fn with_response<F, Fut, R>(&self, func: F) -> R
1188    where
1189        F: Fn(Response) -> Fut,
1190        Fut: FutureSendStatic<R>,
1191    {
1192        func(self.read().await.get_response().clone()).await
1193    }
1194
1195    /// Serializes the response to a JSON byte vector.
1196    ///
1197    /// This method attempts to serialize the entire response structure into a JSON
1198    /// formatted byte vector representation.
1199    ///
1200    /// # Returns
1201    ///
1202    /// - `Result<Vec<u8>, serde_json::Error>` - The serialized JSON bytes on success,
1203    ///   or a serialization error on failure.
1204    pub async fn try_get_response_json_vec(&self) -> Result<Vec<u8>, serde_json::Error> {
1205        self.read().await.get_response().try_json_vec()
1206    }
1207
1208    /// Serializes the response to a JSON byte vector.
1209    ///
1210    /// This method serializes the entire response structure into a JSON formatted
1211    /// byte vector representation.
1212    ///
1213    /// # Returns
1214    ///
1215    /// - `Vec<u8>` - The serialized JSON bytes.
1216    ///
1217    /// # Panics
1218    ///
1219    /// This function will panic if the serialization fails.
1220    pub async fn get_response_json_vec(&self) -> Vec<u8> {
1221        self.read().await.get_response().json_vec()
1222    }
1223
1224    /// Serializes the response to a JSON byte vector with filtered fields.
1225    ///
1226    /// This method attempts to serialize the response structure into a JSON formatted
1227    /// byte vector representation, keeping only the fields that satisfy the predicate.
1228    ///
1229    /// # Arguments
1230    ///
1231    /// - `F: FnMut(&(&String, &mut Value)) -> bool` - A function that takes a reference to a map entry (&(key, value)),
1232    ///   returns `true` to keep the field, `false` to remove it.
1233    ///
1234    /// # Returns
1235    ///
1236    /// - `Result<Vec<u8>, serde_json::Error>` - The serialized JSON bytes on success,
1237    ///   or a serialization error on failure.
1238    pub async fn try_get_response_json_vec_filter<F>(
1239        &self,
1240        predicate: F,
1241    ) -> Result<Vec<u8>, serde_json::Error>
1242    where
1243        F: FnMut(&(&String, &mut Value)) -> bool,
1244    {
1245        self.read()
1246            .await
1247            .get_response()
1248            .try_json_vec_filter(predicate)
1249    }
1250
1251    /// Serializes the response to a JSON byte vector with filtered fields.
1252    ///
1253    /// This method serializes the response structure into a JSON formatted byte vector
1254    /// representation, keeping only the fields that satisfy the predicate.
1255    ///
1256    /// # Arguments
1257    ///
1258    /// - `FnMut(&(&String, &mut Value)) -> bool` - A function that takes a reference to a map entry (&(key, value)),
1259    ///   returns `true` to keep the field, `false` to remove it.
1260    ///
1261    /// # Returns
1262    ///
1263    /// - `Vec<u8>` - The serialized JSON bytes.
1264    ///
1265    /// # Panics
1266    ///
1267    /// This function will panic if the serialization fails.
1268    pub async fn get_response_json_vec_filter<F>(&self, predicate: F) -> Vec<u8>
1269    where
1270        F: FnMut(&(&String, &mut Value)) -> bool,
1271    {
1272        self.read().await.get_response().json_vec_filter(predicate)
1273    }
1274
1275    /// Serializes the response to a JSON string.
1276    ///
1277    /// This method attempts to serialize the entire response structure into a JSON
1278    /// formatted string representation.
1279    ///
1280    /// # Returns
1281    ///
1282    /// - `Result<String, serde_json::Error>` - The serialized JSON string on success,
1283    ///   or a serialization error on failure.
1284    pub async fn try_get_response_json_string(&self) -> Result<String, serde_json::Error> {
1285        self.read().await.get_response().try_json_string()
1286    }
1287
1288    /// Serializes the response to a JSON string.
1289    ///
1290    /// This method serializes the entire response structure into a JSON formatted
1291    /// string representation.
1292    ///
1293    /// # Returns
1294    ///
1295    /// - `String` - The serialized JSON string.
1296    ///
1297    /// # Panics
1298    ///
1299    /// This function will panic if the serialization fails.
1300    pub async fn get_response_json_string(&self) -> String {
1301        self.read().await.get_response().json_string()
1302    }
1303
1304    /// Serializes the response to a JSON string with filtered fields.
1305    ///
1306    /// This method attempts to serialize the response structure into a JSON formatted
1307    /// string representation, keeping only the fields that satisfy the predicate.
1308    ///
1309    /// # Arguments
1310    ///
1311    /// - `FnMut(&(&String, &mut Value)) -> bool` - A function that takes a reference to a map entry (&(key, value)),
1312    ///   returns `true` to keep the field, `false` to remove it.
1313    ///
1314    /// # Returns
1315    ///
1316    /// - `Result<String, serde_json::Error>` - The serialized JSON string on success,
1317    ///   or a serialization error on failure.
1318    pub async fn try_get_response_json_string_filter<F>(
1319        &self,
1320        predicate: F,
1321    ) -> Result<String, serde_json::Error>
1322    where
1323        F: FnMut(&(&String, &mut Value)) -> bool,
1324    {
1325        self.read()
1326            .await
1327            .get_response()
1328            .try_json_string_filter(predicate)
1329    }
1330
1331    /// Serializes the response to a JSON string with filtered fields.
1332    ///
1333    /// This method serializes the response structure into a JSON formatted string
1334    /// representation, keeping only the fields that satisfy the predicate.
1335    ///
1336    /// # Arguments
1337    ///
1338    /// - `FnMut(&(&String, &mut Value)) -> bool` - A function that takes a reference to a map entry (&(key, value)),
1339    ///   returns `true` to keep the field, `false` to remove it.
1340    ///
1341    /// # Returns
1342    ///
1343    /// - `String` - The serialized JSON string.
1344    ///
1345    /// # Panics
1346    ///
1347    /// This function will panic if the serialization fails.
1348    pub async fn get_response_json_string_filter<F>(&self, predicate: F) -> String
1349    where
1350        F: FnMut(&(&String, &mut Value)) -> bool,
1351    {
1352        self.read()
1353            .await
1354            .get_response()
1355            .json_string_filter(predicate)
1356    }
1357
1358    /// Retrieves the HTTP version of the response.
1359    ///
1360    /// # Returns
1361    ///
1362    /// - `ResponseVersion` - The HTTP version of the response.
1363    pub async fn get_response_version(&self) -> ResponseVersion {
1364        self.read().await.get_response().get_version().clone()
1365    }
1366
1367    /// Sets the HTTP version for the response.
1368    ///
1369    /// # Arguments
1370    ///
1371    /// - `ResponseVersion` - The HTTP version to set for the response.
1372    ///
1373    /// # Returns
1374    ///
1375    /// - `&Self` - Reference to the modified context.
1376    pub async fn set_response_version(&self, version: ResponseVersion) -> &Self {
1377        self.write().await.get_mut_response().set_version(version);
1378        self
1379    }
1380
1381    /// Retrieves all response headers.
1382    ///
1383    /// # Returns
1384    ///
1385    /// - `ResponseHeaders` - A clone of the response's header map.
1386    pub async fn get_response_headers(&self) -> ResponseHeaders {
1387        self.read().await.get_response().get_headers().clone()
1388    }
1389
1390    /// Attempts to retrieve a specific response header by its key.
1391    ///
1392    /// # Arguments
1393    ///
1394    /// - `AsRef<str>` - The key of the header to retrieve.
1395    ///
1396    /// # Returns
1397    ///
1398    /// - `Option<ResponseHeadersValue>` - The header values if the header exists.
1399    pub async fn try_get_response_header<K>(&self, key: K) -> Option<ResponseHeadersValue>
1400    where
1401        K: AsRef<str>,
1402    {
1403        self.read().await.get_response().try_get_header(key)
1404    }
1405
1406    /// Retrieves a specific response header by its key, panicking if not found.
1407    ///
1408    /// # Arguments
1409    ///
1410    /// - `AsRef<str>` - The key of the header to retrieve.
1411    ///
1412    /// # Returns
1413    ///
1414    /// - `ResponseHeadersValue` - The header values if the header exists.
1415    ///
1416    /// # Panics
1417    ///
1418    /// - If the header is not found.
1419    pub async fn get_response_header<K>(&self, key: K) -> ResponseHeadersValue
1420    where
1421        K: AsRef<str>,
1422    {
1423        self.read().await.get_response().get_header(key)
1424    }
1425
1426    /// Sets a response header with a new value, removing any existing values.
1427    ///
1428    /// # Arguments
1429    ///
1430    /// - `AsRef<str>` - The key of the header to set.
1431    /// - `AsRef<str>` - The new value for the header.
1432    ///
1433    /// # Returns
1434    ///
1435    /// - `&Self` - Reference to the modified context.
1436    pub async fn set_response_header<K, V>(&self, key: K, value: V) -> &Self
1437    where
1438        K: AsRef<str>,
1439        V: AsRef<str>,
1440    {
1441        self.write().await.get_mut_response().set_header(key, value);
1442        self
1443    }
1444
1445    /// Attempts to retrieve the first value of a specific response header.
1446    ///
1447    /// # Arguments
1448    ///
1449    /// - `AsRef<str>` - The key of the header.
1450    ///
1451    /// # Returns
1452    ///
1453    /// - `Option<ResponseHeadersValueItem>` - The first value of the header if it exists.
1454    pub async fn try_get_response_header_front<K>(&self, key: K) -> Option<ResponseHeadersValueItem>
1455    where
1456        K: AsRef<str>,
1457    {
1458        self.read().await.get_response().try_get_header_front(key)
1459    }
1460
1461    /// Retrieves the first value of a specific response header, panicking if not found.
1462    ///
1463    /// # Arguments
1464    ///
1465    /// - `AsRef<str>` - The key of the header.
1466    ///
1467    /// # Returns
1468    ///
1469    /// - `ResponseHeadersValueItem` - The first value of the header if it exists.
1470    ///
1471    /// # Panics
1472    ///
1473    /// - If the header is not found.
1474    pub async fn get_response_header_front<K>(&self, key: K) -> ResponseHeadersValueItem
1475    where
1476        K: AsRef<str>,
1477    {
1478        self.read().await.get_response().get_header_front(key)
1479    }
1480
1481    /// Attempts to retrieve the last value of a specific response header.
1482    ///
1483    /// # Arguments
1484    ///
1485    /// - `AsRef<str>` - The key of the header.
1486    ///
1487    /// # Returns
1488    ///
1489    /// - `Option<ResponseHeadersValueItem>` - The last value of the header if it exists.
1490    pub async fn try_get_response_header_back<K>(&self, key: K) -> Option<ResponseHeadersValueItem>
1491    where
1492        K: AsRef<str>,
1493    {
1494        self.read().await.get_response().try_get_header_back(key)
1495    }
1496
1497    /// Retrieves the last value of a specific response header, panicking if not found.
1498    ///
1499    /// # Arguments
1500    ///
1501    /// - `AsRef<str>` - The key of the header.
1502    ///
1503    /// # Returns
1504    ///
1505    /// - `ResponseHeadersValueItem` - The last value of the header if it exists.
1506    ///
1507    /// # Panics
1508    ///
1509    /// - If the header is not found.
1510    pub async fn get_response_header_back<K>(&self, key: K) -> ResponseHeadersValueItem
1511    where
1512        K: AsRef<str>,
1513    {
1514        self.read().await.get_response().get_header_back(key)
1515    }
1516
1517    /// Checks if a specific response header exists.
1518    ///
1519    /// # Arguments
1520    ///
1521    /// - `AsRef<str>` - The key of the header to check.
1522    ///
1523    /// # Returns
1524    ///
1525    /// - `bool` - True if the header exists, otherwise false.
1526    pub async fn get_response_has_header<K>(&self, key: K) -> bool
1527    where
1528        K: AsRef<str>,
1529    {
1530        self.read().await.get_response().has_header(key)
1531    }
1532
1533    /// Checks if a response header has a specific value.
1534    ///
1535    /// # Arguments
1536    ///
1537    /// - `AsRef<str>` - The key of the header.
1538    /// - `AsRef<str>` - The value to check for.
1539    ///
1540    /// # Returns
1541    ///
1542    /// - `bool` - True if the header contains the specified value, otherwise false.
1543    pub async fn get_response_header_value<K, V>(&self, key: K, value: V) -> bool
1544    where
1545        K: AsRef<str>,
1546        V: AsRef<str>,
1547    {
1548        self.read()
1549            .await
1550            .get_response()
1551            .has_header_value(key, value)
1552    }
1553
1554    /// Retrieves the total number of response headers.
1555    ///
1556    /// # Returns
1557    ///
1558    /// - `usize` - The total number of headers in the response.
1559    pub async fn get_response_headers_size(&self) -> usize {
1560        self.read().await.get_response().get_headers_size()
1561    }
1562
1563    /// Attempts to retrieve the number of values for a specific response header.
1564    ///
1565    /// # Arguments
1566    ///
1567    /// - `AsRef<str>` - The key of the header.
1568    ///
1569    /// # Returns
1570    ///
1571    /// - `Option<usize>` - The number of values for the specified header if it exists.
1572    pub async fn try_get_response_header_size<K>(&self, key: K) -> Option<usize>
1573    where
1574        K: AsRef<str>,
1575    {
1576        self.read().await.get_response().try_get_header_size(key)
1577    }
1578
1579    /// Retrieves the number of values for a specific response header.
1580    ///
1581    /// # Arguments
1582    ///
1583    /// - `AsRef<str>` - The key of the header.
1584    ///
1585    /// # Returns
1586    ///
1587    /// - `usize` - The number of values for the specified header.
1588    ///
1589    /// # Panics
1590    ///
1591    /// - If the header is not found.
1592    pub async fn get_response_header_size<K>(&self, key: K) -> usize
1593    where
1594        K: AsRef<str>,
1595    {
1596        self.read().await.get_response().get_header_size(key)
1597    }
1598
1599    /// Retrieves the total number of values across all response headers.
1600    ///
1601    /// # Returns
1602    ///
1603    /// - `usize` - The total count of all values in all headers.
1604    pub async fn get_response_headers_values_size(&self) -> usize {
1605        self.read().await.get_response().get_headers_values_size()
1606    }
1607
1608    /// Adds a response header, adding it if it doesn't exist or appending to it if it does.
1609    ///
1610    /// # Arguments
1611    ///
1612    /// - `AsRef<str>` - The header key.
1613    /// - `AsRef<str>` - The header value.
1614    ///
1615    /// # Returns
1616    ///
1617    /// - `&Self` - Reference to self for method chaining.
1618    pub async fn add_response_header<K, V>(&self, key: K, value: V) -> &Self
1619    where
1620        K: AsRef<str>,
1621        V: AsRef<str>,
1622    {
1623        self.write().await.get_mut_response().add_header(key, value);
1624        self
1625    }
1626
1627    /// Removes a response header and all its values.
1628    ///
1629    /// # Arguments
1630    ///
1631    /// - `AsRef<str>` - The key of the header to remove.
1632    ///
1633    /// # Returns
1634    ///
1635    /// - `&Self` - Reference to the modified context.
1636    pub async fn remove_response_header<K>(&self, key: K) -> &Self
1637    where
1638        K: AsRef<str>,
1639    {
1640        self.write().await.get_mut_response().remove_header(key);
1641        self
1642    }
1643
1644    /// Removes a specific value from a response header.
1645    ///
1646    /// # Arguments
1647    ///
1648    /// - `AsRef<str>` - The header key.
1649    /// - `AsRef<str>` - The value to remove.
1650    ///
1651    /// # Returns
1652    ///
1653    /// - `&Self` - Reference to self for method chaining.
1654    pub async fn remove_response_header_value<K, V>(&self, key: K, value: V) -> &Self
1655    where
1656        K: AsRef<str>,
1657        V: AsRef<str>,
1658    {
1659        self.write()
1660            .await
1661            .get_mut_response()
1662            .remove_header_value(key, value);
1663        self
1664    }
1665
1666    /// Clears all headers from the response.
1667    ///
1668    /// # Returns
1669    ///
1670    /// - `&Self` - Reference to the modified context.
1671    pub async fn clear_response_headers(&self) -> &Self {
1672        self.write().await.get_mut_response().clear_headers();
1673        self
1674    }
1675
1676    /// Parses and retrieves all cookies from the response headers.
1677    ///
1678    /// # Returns
1679    ///
1680    /// - `Cookies` - A map of cookies parsed from the response's Cookie header.
1681    pub async fn get_response_cookies(&self) -> Cookies {
1682        self.try_get_response_header_back(COOKIE)
1683            .await
1684            .map(|data| Cookie::parse(&data))
1685            .unwrap_or_default()
1686    }
1687
1688    /// Attempts to retrieve a specific cookie by its name from the response.
1689    ///
1690    /// # Arguments
1691    ///
1692    /// - `AsRef<str>` - The name of the cookie to retrieve.
1693    ///
1694    /// # Returns
1695    ///
1696    /// - `Option<CookieValue>` - The cookie's value if it exists.
1697    pub async fn try_get_response_cookie<K>(&self, key: K) -> Option<CookieValue>
1698    where
1699        K: AsRef<str>,
1700    {
1701        self.get_response_cookies().await.get(key.as_ref()).cloned()
1702    }
1703
1704    /// Retrieves a specific cookie by its name from the response, panicking if not found.
1705    ///
1706    /// # Arguments
1707    ///
1708    /// - `AsRef<str>` - The name of the cookie to retrieve.
1709    ///
1710    /// # Returns
1711    ///
1712    /// - `CookieValue` - The cookie's value if it exists.
1713    ///
1714    /// # Panics
1715    ///
1716    /// - If the cookie is not found.
1717    pub async fn get_response_cookie<K>(&self, key: K) -> CookieValue
1718    where
1719        K: AsRef<str>,
1720    {
1721        self.try_get_response_cookie(key).await.unwrap()
1722    }
1723
1724    /// Retrieves the body of the response.
1725    ///
1726    /// # Returns
1727    ///
1728    /// - `ResponseBody` - The response body.
1729    pub async fn get_response_body(&self) -> ResponseBody {
1730        self.read().await.get_response().get_body().clone()
1731    }
1732
1733    /// Sets the body of the response.
1734    ///
1735    /// # Arguments
1736    ///
1737    /// - `B` - The body data to set for the response.
1738    ///
1739    /// # Returns
1740    ///
1741    /// - `&Self` - Reference to the modified context.
1742    pub async fn set_response_body<B>(&self, body: B) -> &Self
1743    where
1744        B: AsRef<[u8]>,
1745    {
1746        self.write().await.get_mut_response().set_body(body);
1747        self
1748    }
1749
1750    /// Retrieves the response body as a string.
1751    ///
1752    /// # Returns
1753    ///
1754    /// - `String` - The response body converted to a string.
1755    pub async fn get_response_body_string(&self) -> String {
1756        self.read().await.get_response().get_body_string()
1757    }
1758
1759    /// Deserializes the response body from JSON into a specified type.
1760    ///
1761    /// # Returns
1762    ///
1763    /// - `Result<J, serde_json::Error>` - The deserialized type `J` or a JSON error.
1764    pub async fn try_get_response_body_json<J>(&self) -> Result<J, serde_json::Error>
1765    where
1766        J: DeserializeOwned,
1767    {
1768        self.read().await.get_response().try_get_body_json()
1769    }
1770
1771    /// Deserializes the response body from JSON into a specified type, panicking if not found.
1772    ///
1773    /// # Returns
1774    ///
1775    /// - `J` - The deserialized type `J`.
1776    ///
1777    /// # Panics
1778    ///
1779    /// - If deserialization fails.
1780    pub async fn get_response_body_json<J>(&self) -> J
1781    where
1782        J: DeserializeOwned,
1783    {
1784        self.read().await.get_response().get_body_json()
1785    }
1786
1787    /// Retrieves the reason phrase of the response status code.
1788    ///
1789    /// # Returns
1790    ///
1791    /// - `ResponseReasonPhrase` - The reason phrase associated with the response status code.
1792    pub async fn get_response_reason_phrase(&self) -> ResponseReasonPhrase {
1793        self.read().await.get_response().get_reason_phrase().clone()
1794    }
1795
1796    /// Sets the reason phrase for the response status code.
1797    ///
1798    /// # Arguments
1799    ///
1800    /// - `AsRef<str>` - The reason phrase to set.
1801    ///
1802    /// # Returns
1803    ///
1804    /// - `&Self` - Reference to the modified context.
1805    pub async fn set_response_reason_phrase<P>(&self, reason_phrase: P) -> &Self
1806    where
1807        P: AsRef<str>,
1808    {
1809        self.write()
1810            .await
1811            .get_mut_response()
1812            .set_reason_phrase(reason_phrase);
1813        self
1814    }
1815
1816    /// Retrieves the status code of the response.
1817    ///
1818    /// # Returns
1819    ///
1820    /// - `ResponseStatusCode` - The status code of the response.
1821    pub async fn get_response_status_code(&self) -> ResponseStatusCode {
1822        self.read().await.get_response().get_status_code()
1823    }
1824
1825    /// Sets the status code for the response.
1826    ///
1827    /// # Arguments
1828    ///
1829    /// - `ResponseStatusCode` - The status code to set for the response.
1830    ///
1831    /// # Returns
1832    ///
1833    /// - `&Self` - A reference to the modified context.
1834    pub async fn set_response_status_code(&self, status_code: ResponseStatusCode) -> &Self {
1835        self.write()
1836            .await
1837            .get_mut_response()
1838            .set_status_code(status_code);
1839        self
1840    }
1841
1842    /// Retrieves the parameters extracted from the route path.
1843    ///
1844    /// # Returns
1845    ///
1846    /// - `RouteParams` - A map containing the route parameters.
1847    pub async fn get_route_params(&self) -> RouteParams {
1848        self.read().await.get_route_params().clone()
1849    }
1850
1851    /// Sets the route parameters for the context.
1852    ///
1853    /// # Arguments
1854    ///
1855    /// - `RouteParams` - The route parameters to set.
1856    ///
1857    /// # Returns
1858    ///
1859    /// - `&Self` - A reference to the modified `Context`.
1860    pub(crate) async fn set_route_params(&self, params: RouteParams) -> &Self {
1861        self.write().await.set_route_params(params);
1862        self
1863    }
1864
1865    /// Attempts to retrieve a specific route parameter by its name.
1866    ///
1867    /// # Arguments
1868    ///
1869    /// - `AsRef<str>` - The name of the route parameter to retrieve.
1870    ///
1871    /// # Returns
1872    ///
1873    /// - `Option<String>` - The value of the route parameter if it exists.
1874    pub async fn try_get_route_param<T>(&self, name: T) -> Option<String>
1875    where
1876        T: AsRef<str>,
1877    {
1878        self.read()
1879            .await
1880            .get_route_params()
1881            .get(name.as_ref())
1882            .cloned()
1883    }
1884
1885    /// Retrieves a specific route parameter by its name, panicking if not found.
1886    ///
1887    /// # Arguments
1888    ///
1889    /// - `AsRef<str>` - The name of the route parameter to retrieve.
1890    ///
1891    /// # Returns
1892    ///
1893    /// - `String` - The value of the route parameter if it exists.
1894    ///
1895    /// # Panics
1896    ///
1897    /// - If the route parameter is not found.
1898    pub async fn get_route_param<T>(&self, name: T) -> String
1899    where
1900        T: AsRef<str>,
1901    {
1902        self.try_get_route_param(name).await.unwrap()
1903    }
1904
1905    /// Retrieves all attributes stored in the context.
1906    ///
1907    /// # Returns
1908    ///
1909    /// - `ThreadSafeAttributeStore` - A map containing all attributes.
1910    pub async fn get_attributes(&self) -> ThreadSafeAttributeStore {
1911        self.read().await.get_attributes().clone()
1912    }
1913
1914    /// Attempts to retrieve a specific attribute by its key, casting it to the specified type.
1915    ///
1916    /// # Arguments
1917    ///
1918    /// - `AsRef<str>` - The key of the attribute to retrieve.
1919    ///
1920    /// # Returns
1921    ///
1922    /// - `Option<V>` - The attribute value if it exists and can be cast to the specified type.
1923    pub async fn try_get_attribute<V>(&self, key: impl AsRef<str>) -> Option<V>
1924    where
1925        V: AnySendSyncClone,
1926    {
1927        self.read()
1928            .await
1929            .get_attributes()
1930            .get(&Attribute::External(key.as_ref().to_owned()).to_string())
1931            .and_then(|arc| arc.downcast_ref::<V>())
1932            .cloned()
1933    }
1934
1935    /// Retrieves a specific attribute by its key, casting it to the specified type, panicking if not found.
1936    ///
1937    /// # Arguments
1938    ///
1939    /// - `AsRef<str>` - The key of the attribute to retrieve.
1940    ///
1941    /// # Returns
1942    ///
1943    /// - `AnySendSyncClone` - The attribute value if it exists and can be cast to the specified type.
1944    ///
1945    /// # Panics
1946    ///
1947    /// - If the attribute is not found.
1948    pub async fn get_attribute<V>(&self, key: impl AsRef<str>) -> V
1949    where
1950        V: AnySendSyncClone,
1951    {
1952        self.try_get_attribute(key).await.unwrap()
1953    }
1954
1955    /// Sets an attribute in the context.
1956    ///
1957    /// # Arguments
1958    ///
1959    /// - `AsRef<str>` - The key of the attribute to set.
1960    /// - `AnySendSyncClone` - The value of the attribute.
1961    ///
1962    /// # Returns
1963    ///
1964    /// - `&Self` - A reference to the modified context.
1965    pub async fn set_attribute<K, V>(&self, key: K, value: V) -> &Self
1966    where
1967        K: AsRef<str>,
1968        V: AnySendSyncClone,
1969    {
1970        self.write().await.get_mut_attributes().insert(
1971            Attribute::External(key.as_ref().to_owned()).to_string(),
1972            Arc::new(value),
1973        );
1974        self
1975    }
1976
1977    /// Removes an attribute from the context.
1978    ///
1979    /// # Arguments
1980    ///
1981    /// - `AsRef<str>` - The key of the attribute to remove.
1982    ///
1983    /// # Returns
1984    ///
1985    /// - `&Self` - A reference to the modified context.
1986    pub async fn remove_attribute<K>(&self, key: K) -> &Self
1987    where
1988        K: AsRef<str>,
1989    {
1990        self.write()
1991            .await
1992            .get_mut_attributes()
1993            .remove(&Attribute::External(key.as_ref().to_owned()).to_string());
1994        self
1995    }
1996
1997    /// Clears all attributes from the context.
1998    ///
1999    /// # Returns
2000    ///
2001    /// - `&Self` - A reference to the modified context.
2002    pub async fn clear_attribute(&self) -> &Self {
2003        self.write().await.get_mut_attributes().clear();
2004        self
2005    }
2006
2007    /// Retrieves an internal framework attribute.
2008    ///
2009    /// # Arguments
2010    ///
2011    /// - `InternalAttribute` - The internal attribute key to retrieve.
2012    ///
2013    /// # Returns
2014    ///
2015    /// - `Option<V>` - The attribute value if it exists and can be cast to the specified type.
2016    async fn try_get_internal_attribute<V>(&self, key: InternalAttribute) -> Option<V>
2017    where
2018        V: AnySendSyncClone,
2019    {
2020        self.read()
2021            .await
2022            .get_attributes()
2023            .get(&Attribute::Internal(key).to_string())
2024            .and_then(|arc| arc.downcast_ref::<V>())
2025            .cloned()
2026    }
2027
2028    /// Retrieves an internal framework attribute.
2029    ///
2030    /// # Arguments
2031    ///
2032    /// - `InternalAttribute` - The internal attribute key to retrieve.
2033    ///
2034    /// # Returns
2035    ///
2036    /// - `AnySendSyncClone` - The attribute value if it exists and can be cast to the specified type.
2037    ///
2038    /// # Panics
2039    ///
2040    /// - If the attribute is not found.
2041    async fn get_internal_attribute<V>(&self, key: InternalAttribute) -> V
2042    where
2043        V: AnySendSyncClone,
2044    {
2045        self.try_get_internal_attribute(key).await.unwrap()
2046    }
2047
2048    /// Sets an internal framework attribute.
2049    ///
2050    /// # Arguments
2051    ///
2052    /// - `InternalAttribute` - The internal attribute key to set.
2053    /// - `AnySendSyncClone` - The value of the attribute.
2054    ///
2055    /// # Returns
2056    ///
2057    /// - `&Self` - A reference to the modified context.
2058    async fn set_internal_attribute<V>(&self, key: InternalAttribute, value: V) -> &Self
2059    where
2060        V: AnySendSyncClone,
2061    {
2062        self.write()
2063            .await
2064            .get_mut_attributes()
2065            .insert(Attribute::Internal(key).to_string(), Arc::new(value));
2066        self
2067    }
2068
2069    /// Stores panic data for the current task context.
2070    ///
2071    /// # Arguments
2072    ///
2073    /// - `PanicData` - The panic data specific to the current task.
2074    ///
2075    /// # Returns
2076    ///
2077    /// - `&Self` - Reference to the modified context for method chaining.
2078    pub(crate) async fn set_task_panic(&self, panic_data: PanicData) -> &Self {
2079        self.set_internal_attribute(InternalAttribute::TaskPanicData, panic_data)
2080            .await
2081    }
2082
2083    /// Retrieves panic data associated with the current task.
2084    ///
2085    /// # Returns
2086    ///
2087    /// - `Option<PanicData>` - Task panic data if a panic was caught during execution.
2088    pub async fn try_get_task_panic_data(&self) -> Option<PanicData> {
2089        self.try_get_internal_attribute(InternalAttribute::TaskPanicData)
2090            .await
2091    }
2092
2093    /// Retrieves panic data associated with the current task.
2094    ///
2095    /// # Returns
2096    ///
2097    /// - `PanicData` - Task panic data if available.
2098    ///
2099    /// # Panics
2100    ///
2101    /// - If no task panic data is found.
2102    pub async fn get_task_panic_data(&self) -> PanicData {
2103        self.get_internal_attribute(InternalAttribute::TaskPanicData)
2104            .await
2105    }
2106
2107    /// Sets the request error information for the context.
2108    ///
2109    /// # Arguments
2110    ///
2111    /// - `RequestError` - The request error information to store.
2112    ///
2113    /// # Returns
2114    ///
2115    /// - `&Self` - A reference to the modified context.
2116    pub(crate) async fn set_request_error_data(&self, request_error: RequestError) -> &Self {
2117        self.set_internal_attribute(InternalAttribute::RequestErrorData, request_error)
2118            .await
2119    }
2120
2121    /// Retrieves request error information if an error occurred during handling.
2122    ///
2123    /// # Returns
2124    ///
2125    /// - `Option<RequestError>` - The request error information if an error was caught.
2126    pub async fn try_get_request_error_data(&self) -> Option<RequestError> {
2127        self.try_get_internal_attribute(InternalAttribute::RequestErrorData)
2128            .await
2129    }
2130
2131    /// Retrieves request error information if an error occurred during handling.
2132    ///
2133    /// # Returns
2134    ///
2135    /// - `RequestError` - The request error information if an error was caught.
2136    ///
2137    /// # Panics
2138    ///
2139    /// - If the request error information is not found.
2140    pub async fn get_request_error_data(&self) -> RequestError {
2141        self.get_internal_attribute(InternalAttribute::RequestErrorData)
2142            .await
2143    }
2144
2145    /// Sets a hook function for the context with a custom key.
2146    ///
2147    /// # Arguments
2148    ///
2149    /// - `AsRef<str>` - The key to identify this hook.
2150    /// - `FnContextSendSyncStatic<Fut, ()>, Fut: FutureSendStatic<()>` - The hook function to store.
2151    ///
2152    /// # Returns
2153    ///
2154    /// - `&Self` - A reference to the modified context.
2155    pub async fn set_hook<K, F, Fut>(&self, key: K, hook: F) -> &Self
2156    where
2157        K: AsRef<str>,
2158        F: FnContextSendSyncStatic<Fut, ()>,
2159        Fut: FutureSendStatic<()>,
2160    {
2161        let hook_fn: HookHandler<()> =
2162            Arc::new(move |ctx: Context| -> SendableAsyncTask<()> { Box::pin(hook(ctx)) });
2163        self.set_internal_attribute(InternalAttribute::Hook(key.as_ref().to_owned()), hook_fn)
2164            .await
2165    }
2166
2167    /// Attempts to retrieve a hook function if it has been set.
2168    ///
2169    /// # Arguments
2170    ///
2171    /// - `AsRef<str>` - The key to identify the hook.
2172    ///
2173    /// # Returns
2174    ///
2175    /// - `Option<HookHandler<()>>` - The hook function if it has been set.
2176    pub async fn try_get_hook<K>(&self, key: K) -> Option<HookHandler<()>>
2177    where
2178        K: AsRef<str>,
2179    {
2180        self.try_get_internal_attribute(InternalAttribute::Hook(key.as_ref().to_owned()))
2181            .await
2182    }
2183
2184    /// Retrieves a hook function if it has been set, panicking if not found.
2185    ///
2186    /// # Arguments
2187    ///
2188    /// - `AsRef<str>` - The key to identify the hook.
2189    ///
2190    /// # Returns
2191    ///
2192    /// - `HookHandler<()>` - The hook function if it has been set.
2193    ///
2194    /// # Panics
2195    ///
2196    /// - If the hook function is not found.
2197    pub async fn get_hook<K>(&self, key: K) -> HookHandler<()>
2198    where
2199        K: AsRef<str>,
2200    {
2201        self.get_internal_attribute(InternalAttribute::Hook(key.as_ref().to_owned()))
2202            .await
2203    }
2204
2205    /// Sends HTTP response data over the stream.
2206    ///
2207    /// # Returns
2208    ///
2209    /// - `Result<(), ResponseError>` - Result indicating success or failure.
2210    pub async fn try_send(&self) -> Result<(), ResponseError> {
2211        if self.is_terminated().await {
2212            return Err(ResponseError::Terminated);
2213        }
2214        let response_data: ResponseData = self.write().await.get_mut_response().build();
2215        if let Some(stream) = self.try_get_stream().await {
2216            return stream.try_send(response_data).await;
2217        }
2218        Err(ResponseError::NotFoundStream)
2219    }
2220
2221    /// Sends HTTP response data over the stream.
2222    ///
2223    /// # Panics
2224    ///
2225    /// Panics if the write operation fails.
2226    pub async fn send(&self) {
2227        self.try_send().await.unwrap();
2228    }
2229
2230    /// Sends HTTP response body.
2231    ///
2232    /// # Returns
2233    ///
2234    /// - `Result<(), ResponseError>` - Result indicating success or failure.
2235    pub async fn try_send_body(&self) -> Result<(), ResponseError> {
2236        if self.is_terminated().await {
2237            return Err(ResponseError::Terminated);
2238        }
2239        let response_body: ResponseBody = self.get_response_body().await;
2240        self.try_send_body_with_data(response_body).await
2241    }
2242
2243    /// Sends HTTP response body.
2244    ///
2245    /// # Panics
2246    ///
2247    /// Panics if the write operation fails.
2248    pub async fn send_body(&self) {
2249        self.try_send_body().await.unwrap();
2250    }
2251
2252    /// Sends only the response body to the client with additional data.
2253    ///
2254    /// This method is useful for streaming data or for responses where headers have already been sent.
2255    ///
2256    /// # Arguments
2257    ///
2258    /// - `AsRef<[u8]>` - The additional data to send as the body.
2259    ///
2260    /// # Returns
2261    ///
2262    /// - `Result<(), ResponseError>` - The result of the send operation.
2263    pub async fn try_send_body_with_data<D>(&self, data: D) -> Result<(), ResponseError>
2264    where
2265        D: AsRef<[u8]>,
2266    {
2267        if self.is_terminated().await {
2268            return Err(ResponseError::Terminated);
2269        }
2270        if let Some(stream) = self.try_get_stream().await {
2271            return stream.try_send_body(data).await;
2272        }
2273        Err(ResponseError::NotFoundStream)
2274    }
2275
2276    /// Sends HTTP response body.
2277    ///
2278    /// # Arguments
2279    ///
2280    /// - `AsRef<[u8]>` - The response body data (must implement AsRef<[u8]>).
2281    ///
2282    /// # Panics
2283    ///
2284    /// Panics if the write operation fails.
2285    pub async fn send_body_with_data<D>(&self, data: D)
2286    where
2287        D: AsRef<[u8]>,
2288    {
2289        self.try_send_body_with_data(data).await.unwrap();
2290    }
2291
2292    /// Sends multiple HTTP response bodies sequentially.
2293    ///
2294    /// # Arguments
2295    ///
2296    /// - `I: IntoIterator<Item = D>, D: AsRef<[u8]>` - The response body data list to send.
2297    ///
2298    /// # Returns
2299    ///
2300    /// - `Result<(), ResponseError>` - Result indicating success or failure.
2301    pub async fn try_send_body_list<I, D>(&self, data_iter: I) -> Result<(), ResponseError>
2302    where
2303        I: IntoIterator<Item = D>,
2304        D: AsRef<[u8]>,
2305    {
2306        if self.is_terminated().await {
2307            return Err(ResponseError::Terminated);
2308        }
2309        if let Some(stream) = self.try_get_stream().await {
2310            return stream.try_send_body_list(data_iter).await;
2311        }
2312        Err(ResponseError::NotFoundStream)
2313    }
2314
2315    /// Sends multiple HTTP response bodies sequentially.
2316    ///
2317    /// # Arguments
2318    ///
2319    /// - `I: IntoIterator<Item = D>, D: AsRef<[u8]>` - The response body data list to send.
2320    ///
2321    /// # Panics
2322    ///
2323    /// Panics if any write operation fails.
2324    pub async fn send_body_list<I, D>(&self, data_iter: I)
2325    where
2326        I: IntoIterator<Item = D>,
2327        D: AsRef<[u8]>,
2328    {
2329        self.try_send_body_list(data_iter).await.unwrap();
2330    }
2331
2332    /// Sends a list of response bodies to the client with additional data.
2333    ///
2334    /// This is useful for streaming multiple data chunks or for responses where headers have already been sent.
2335    ///
2336    /// # Arguments
2337    ///
2338    /// - `I: IntoIterator<Item = D>, D: AsRef<[u8]>` - The additional data to send as a list of bodies.
2339    ///
2340    /// # Returns
2341    ///
2342    /// - `Result<(), ResponseError>` - The result of the send operation.
2343    pub async fn try_send_body_list_with_data<I, D>(
2344        &self,
2345        data_iter: I,
2346    ) -> Result<(), ResponseError>
2347    where
2348        I: IntoIterator<Item = D>,
2349        D: AsRef<[u8]>,
2350    {
2351        if self.is_terminated().await {
2352            return Err(ResponseError::Terminated);
2353        }
2354        if let Some(stream) = self.try_get_stream().await {
2355            return stream.try_send_body_list(data_iter).await;
2356        }
2357        Err(ResponseError::NotFoundStream)
2358    }
2359
2360    /// Sends a list of response bodies to the client with additional data.
2361    ///
2362    /// # Arguments
2363    ///
2364    /// - `I: IntoIterator<Item = D>, D: AsRef<[u8]>` - The additional data to send as a list of bodies.
2365    ///
2366    /// # Panics
2367    ///
2368    /// Panics if any write operation fails.
2369    pub async fn send_body_list_with_data<I, D>(&self, data_iter: I)
2370    where
2371        I: IntoIterator<Item = D>,
2372        D: AsRef<[u8]>,
2373    {
2374        self.try_send_body_list_with_data(data_iter).await.unwrap()
2375    }
2376
2377    /// Flushes the underlying network stream, ensuring all buffered data is sent.
2378    ///
2379    /// # Returns
2380    ///
2381    /// - `Result<(), ResponseError>` - The result of the flush operation.
2382    pub async fn try_flush(&self) -> Result<(), ResponseError> {
2383        if self.is_terminated().await {
2384            return Err(ResponseError::Terminated);
2385        }
2386        if let Some(stream) = self.try_get_stream().await {
2387            return stream.try_flush().await;
2388        }
2389        Err(ResponseError::NotFoundStream)
2390    }
2391
2392    /// Flushes all buffered data to the stream.
2393    ///
2394    /// # Panics
2395    ///
2396    /// Panics if the flush operation fails.
2397    pub async fn flush(&self) {
2398        self.try_flush().await.unwrap();
2399    }
2400}