hyperlane/context/impl.rs
1use crate::*;
2
3/// Implementation of methods for `Context` structure.
4impl Context {
5 /// Creates a new `Context` from an internal context instance.
6 ///
7 /// # Arguments
8 ///
9 /// - `ContextInner` - The wrapped context data.
10 ///
11 /// # Returns
12 ///
13 /// - `Context` - The newly created context instance.
14 #[inline(always)]
15 pub(crate) fn from_internal_context(ctx: ContextInner) -> Self {
16 Self(arc_rwlock(ctx))
17 }
18
19 /// Creates a new `Context` for a given stream and request.
20 ///
21 /// # Arguments
22 ///
23 /// - `&ArcRwLockStream` - The network stream.
24 /// - `&Request` - The HTTP request.
25 ///
26 /// # Returns
27 ///
28 /// - `Context` - The newly created context.
29 #[inline(always)]
30 pub(crate) fn create_context(stream: &ArcRwLockStream, request: &Request) -> Context {
31 let mut internal_ctx: ContextInner = ContextInner::default();
32 internal_ctx
33 .set_stream(Some(stream.clone()))
34 .set_request(request.clone())
35 .get_mut_response()
36 .set_version(request.get_version().clone());
37 Context::from_internal_context(internal_ctx)
38 }
39
40 /// Acquires a read lock on the inner context data.
41 ///
42 /// # Returns
43 ///
44 /// - `ContextReadGuard` - The read guard for the inner context.
45 async fn read(&self) -> ContextReadGuard<'_> {
46 self.get_0().read().await
47 }
48
49 /// Acquires a write lock on the inner context data.
50 ///
51 /// # Returns
52 ///
53 /// - `ContextWriteGuard` - The write guard for the inner context.
54 async fn write(&self) -> ContextWriteGuard<'_> {
55 self.get_0().write().await
56 }
57
58 /// Checks if the context has been marked as aborted.
59 ///
60 /// # Returns
61 ///
62 /// - `bool` - True if the context is aborted, otherwise false.
63 pub async fn get_aborted(&self) -> bool {
64 *self.read().await.get_aborted()
65 }
66
67 /// Sets the aborted flag for the context.
68 ///
69 /// # Arguments
70 ///
71 /// - `bool` - The aborted state to set.
72 ///
73 /// # Returns
74 ///
75 /// - `&Self` - Reference to self for method chaining.
76 pub async fn set_aborted(&self, aborted: bool) -> &Self {
77 self.write().await.set_aborted(aborted);
78 self
79 }
80
81 /// Marks the context as aborted.
82 ///
83 /// # Returns
84 ///
85 /// - `&Self` - Reference to the modified context.
86 pub async fn aborted(&self) -> &Self {
87 self.set_aborted(true).await;
88 self
89 }
90
91 /// Cancels the aborted state of the context.
92 ///
93 /// # Returns
94 ///
95 /// - `&Self` - Reference to the modified context.
96 pub async fn cancel_aborted(&self) -> &Self {
97 self.set_aborted(false).await;
98 self
99 }
100
101 /// Checks if the connection is marked as closed.
102 ///
103 /// # Returns
104 ///
105 /// - `bool` - True if the connection is closed, otherwise false.
106 pub async fn get_closed(&self) -> bool {
107 *self.read().await.get_closed()
108 }
109
110 /// Sets the closed flag for the connection.
111 ///
112 /// # Arguments
113 ///
114 /// - `bool` - The new value for the closed flag.
115 ///
116 /// # Returns
117 ///
118 /// - `&Self` - Reference to the modified context.
119 pub async fn set_closed(&self, closed: bool) -> &Self {
120 self.write().await.set_closed(closed);
121 self
122 }
123
124 /// Marks the connection as closed.
125 ///
126 /// # Returns
127 ///
128 /// - `&Self` - Reference to the modified context.
129 pub async fn closed(&self) -> &Self {
130 self.set_closed(true).await;
131 self
132 }
133
134 /// Cancels the closed state of the connection.
135 ///
136 /// # Returns
137 ///
138 /// - `&Self` - Reference to the modified context.
139 pub async fn cancel_closed(&self) -> &Self {
140 self.set_closed(false).await;
141 self
142 }
143
144 /// Checks if the connection has been terminated (aborted and closed).
145 ///
146 /// # Returns
147 ///
148 /// - `bool` - True if the connection is both aborted and closed, otherwise false.
149 pub async fn is_terminated(&self) -> bool {
150 self.get_aborted().await || self.get_closed().await
151 }
152
153 /// Retrieves the underlying network stream, if available.
154 ///
155 /// # Returns
156 ///
157 /// - `OptionArcRwLockStream` - The thread-safe, shareable network stream if it exists.
158 pub async fn try_get_stream(&self) -> OptionArcRwLockStream {
159 self.read().await.get_stream().clone()
160 }
161
162 /// Retrieves the remote socket address of the connection.
163 ///
164 /// # Returns
165 ///
166 /// - `OptionSocketAddr` - The socket address of the remote peer if available.
167 pub async fn try_get_socket_addr(&self) -> OptionSocketAddr {
168 self.try_get_stream()
169 .await
170 .as_ref()?
171 .read()
172 .await
173 .peer_addr()
174 .ok()
175 }
176
177 /// Retrieves the remote socket address or a default value if unavailable.
178 ///
179 /// # Returns
180 ///
181 /// - `SocketAddr` - The socket address of the remote peer, or default if unavailable.
182 pub async fn get_socket_addr(&self) -> SocketAddr {
183 let stream_result: OptionArcRwLockStream = self.try_get_stream().await;
184 if stream_result.is_none() {
185 return DEFAULT_SOCKET_ADDR;
186 }
187 stream_result
188 .unwrap()
189 .read()
190 .await
191 .peer_addr()
192 .unwrap_or(DEFAULT_SOCKET_ADDR)
193 }
194
195 /// Retrieves the remote socket address as a string.
196 ///
197 /// # Returns
198 ///
199 /// - `OptionString` - The string representation of the socket address if available.
200 pub async fn try_get_socket_addr_string(&self) -> OptionString {
201 self.try_get_socket_addr()
202 .await
203 .map(|data| data.to_string())
204 }
205
206 /// Retrieves the remote socket address as a string, or a default value if unavailable.
207 ///
208 /// # Returns
209 ///
210 /// - `String` - The string representation of the socket address, or default if unavailable.
211 pub async fn get_socket_addr_string(&self) -> String {
212 self.get_socket_addr().await.to_string()
213 }
214
215 /// Retrieves the IP address part of the remote socket address.
216 ///
217 /// # Returns
218 ///
219 /// - `OptionSocketHost` - The IP address of the remote peer if available.
220 pub async fn try_get_socket_host(&self) -> OptionSocketHost {
221 self.try_get_socket_addr()
222 .await
223 .map(|socket_addr: SocketAddr| socket_addr.ip())
224 }
225
226 /// Retrieves the port number part of the remote socket address.
227 ///
228 /// # Returns
229 ///
230 /// - `OptionSocketPort` - The port number of the remote peer if available.
231 pub async fn try_get_socket_port(&self) -> OptionSocketPort {
232 self.try_get_socket_addr()
233 .await
234 .map(|socket_addr: SocketAddr| socket_addr.port())
235 }
236
237 /// Retrieves the current HTTP request.
238 ///
239 /// # Returns
240 ///
241 /// - `Request` - A clone of the current request.
242 pub async fn get_request(&self) -> Request {
243 self.read().await.get_request().clone()
244 }
245
246 /// Sets the current HTTP request for the context.
247 ///
248 /// # Arguments
249 ///
250 /// - `&Request` - The request to set in the context.
251 ///
252 /// # Returns
253 ///
254 /// - `&Self` - Reference to the modified context.
255 pub(crate) async fn set_request(&self, request_data: &Request) -> &Self {
256 self.write().await.set_request(request_data.clone());
257 self
258 }
259
260 /// Executes an asynchronous closure with the current request.
261 ///
262 /// This method provides temporary access to the request data without needing to clone it.
263 ///
264 /// # Arguments
265 ///
266 /// - `F` - A closure that takes the `Request` and returns a future.
267 ///
268 /// # Returns
269 ///
270 /// - `R` - The result of the provided closure's future.
271 pub async fn with_request<F, Fut, R>(&self, func: F) -> R
272 where
273 F: Fn(Request) -> Fut,
274 Fut: FutureSendStatic<R>,
275 {
276 func(self.read().await.get_request().clone()).await
277 }
278
279 /// Retrieves the string representation of the current request.
280 ///
281 /// # Returns
282 ///
283 /// - `String` - The full request as a string.
284 pub async fn get_request_string(&self) -> String {
285 self.read().await.get_request().get_string()
286 }
287
288 /// Retrieves the HTTP version of the request.
289 ///
290 /// # Returns
291 ///
292 /// - `RequestVersion` - The HTTP version of the request.
293 pub async fn get_request_version(&self) -> RequestVersion {
294 self.read().await.get_request().get_version().clone()
295 }
296
297 /// Retrieves the HTTP method of the request.
298 ///
299 /// # Returns
300 ///
301 /// - `RequestMethod` - The HTTP method of the request.
302 pub async fn get_request_method(&self) -> RequestMethod {
303 self.read().await.get_request().get_method().clone()
304 }
305
306 /// Retrieves the host from the request headers.
307 ///
308 /// # Returns
309 ///
310 /// - `RequestHost` - The host part of the request's URI.
311 pub async fn get_request_host(&self) -> RequestHost {
312 self.read().await.get_request().get_host().clone()
313 }
314
315 /// Retrieves the path of the request.
316 ///
317 /// # Returns
318 ///
319 /// - `RequestPath` - The path part of the request's URI.
320 pub async fn get_request_path(&self) -> RequestPath {
321 self.read().await.get_request().get_path().clone()
322 }
323
324 /// Retrieves the query parameters of the request.
325 ///
326 /// # Returns
327 ///
328 /// - `RequestQuerys` - A map containing the query parameters.
329 pub async fn get_request_querys(&self) -> RequestQuerys {
330 self.read().await.get_request().get_querys().clone()
331 }
332
333 /// Retrieves a specific query parameter by its key.
334 ///
335 /// # Arguments
336 ///
337 /// - `AsRef<str>` - The query parameter key.
338 ///
339 /// # Returns
340 ///
341 /// - `OptionRequestQuerysValue` - The query parameter value if exists.
342 pub async fn try_get_request_query<K>(&self, key: K) -> OptionRequestQuerysValue
343 where
344 K: AsRef<str>,
345 {
346 self.read().await.get_request().try_get_query(key)
347 }
348
349 /// Retrieves the body of the request.
350 ///
351 /// # Returns
352 ///
353 /// - `RequestBody` - A clone of the request's body.
354 pub async fn get_request_body(&self) -> RequestBody {
355 self.read().await.get_request().get_body().clone()
356 }
357
358 /// Retrieves the request body as a string.
359 ///
360 /// # Returns
361 ///
362 /// - `String` - The request body converted to a string.
363 pub async fn get_request_body_string(&self) -> String {
364 self.read().await.get_request().get_body_string()
365 }
366
367 /// Deserializes the request body from JSON into a specified type.
368 ///
369 /// # Returns
370 ///
371 /// - `ResultJsonError<J>` - The deserialized type `J` or a JSON error.
372 pub async fn get_request_body_json<J>(&self) -> ResultJsonError<J>
373 where
374 J: DeserializeOwned,
375 {
376 self.read().await.get_request().get_body_json()
377 }
378
379 /// Retrieves a specific request header by its key.
380 ///
381 /// Gets a request header by key.
382 ///
383 /// # Arguments
384 ///
385 /// - `AsRef<str>` - The header key.
386 ///
387 /// # Returns
388 ///
389 /// - `OptionRequestHeadersValue` - The header values if exists.
390 pub async fn try_get_request_header<K>(&self, key: K) -> OptionRequestHeadersValue
391 where
392 K: AsRef<str>,
393 {
394 self.read().await.get_request().try_get_header(key)
395 }
396
397 /// Retrieves all request headers.
398 ///
399 /// # Returns
400 ///
401 /// - `RequestHeaders` - A clone of the request's header map.
402 pub async fn get_request_headers(&self) -> RequestHeaders {
403 self.read().await.get_request().get_headers().clone()
404 }
405
406 /// Retrieves the first value of a specific request header.
407 ///
408 /// # Arguments
409 ///
410 /// - `AsRef<str>` - The key of the header.
411 ///
412 /// # Returns
413 ///
414 /// - `OptionRequestHeadersValueItem` - The first value of the header if it exists.
415 pub async fn try_get_request_header_front<K>(&self, key: K) -> OptionRequestHeadersValueItem
416 where
417 K: AsRef<str>,
418 {
419 self.read().await.get_request().try_get_header_front(key)
420 }
421
422 /// Retrieves the last value of a specific request header.
423 ///
424 /// # Arguments
425 ///
426 /// - `AsRef<str>` - The key of the header.
427 ///
428 /// # Returns
429 ///
430 /// - `OptionRequestHeadersValueItem` - The last value of the header if it exists.
431 pub async fn try_get_request_header_back<K>(&self, key: K) -> OptionRequestHeadersValueItem
432 where
433 K: AsRef<str>,
434 {
435 self.read().await.get_request().try_get_header_back(key)
436 }
437
438 /// Retrieves the number of values for a specific request header.
439 ///
440 /// # Arguments
441 ///
442 /// - `AsRef<str>` - The key of the header.
443 ///
444 /// # Returns
445 ///
446 /// - `usize` - The number of values for the specified header.
447 pub async fn get_request_header_len<K>(&self, key: K) -> usize
448 where
449 K: AsRef<str>,
450 {
451 self.read().await.get_request().get_header_length(key)
452 }
453
454 /// Retrieves the total number of values across all request headers.
455 ///
456 /// # Returns
457 ///
458 /// - `usize` - The total count of all values in all headers.
459 pub async fn get_request_headers_values_length(&self) -> usize {
460 self.read().await.get_request().get_headers_values_length()
461 }
462
463 /// Retrieves the total number of request headers.
464 ///
465 /// # Returns
466 ///
467 /// - `usize` - The total number of headers in the request.
468 pub async fn get_request_headers_length(&self) -> usize {
469 self.read().await.get_request().get_headers_length()
470 }
471
472 /// Checks if a specific request header exists.
473 ///
474 /// # Arguments
475 ///
476 /// - `AsRef<str>` - The key of the header to check.
477 ///
478 /// # Returns
479 ///
480 /// - `bool` - True if the header exists, otherwise false.
481 pub async fn get_request_has_header<K>(&self, key: K) -> bool
482 where
483 K: AsRef<str>,
484 {
485 self.read().await.get_request().has_header(key)
486 }
487
488 /// Checks if a request header has a specific value.
489 ///
490 /// # Arguments
491 ///
492 /// - `AsRef<str>` - The header key.
493 /// - `AsRef<str>` - The value to check.
494 ///
495 /// # Returns
496 ///
497 /// - `bool` - True if header contains the value.
498 pub async fn get_request_has_header_value<K, V>(&self, key: K, value: V) -> bool
499 where
500 K: AsRef<str>,
501 V: AsRef<str>,
502 {
503 self.read().await.get_request().has_header_value(key, value)
504 }
505
506 /// Parses and retrieves all cookies from the request headers.
507 ///
508 /// # Returns
509 ///
510 /// - `Cookies` - A map of cookies parsed from the request's Cookie header.
511 pub async fn get_request_cookies(&self) -> Cookies {
512 self.try_get_request_header_back(COOKIE)
513 .await
514 .map(|data| Cookie::parse(&data))
515 .unwrap_or_default()
516 }
517
518 /// Retrieves a specific cookie by its name from the request.
519 ///
520 /// # Arguments
521 ///
522 /// - `AsRef<str>` - The cookie name.
523 ///
524 /// # Returns
525 ///
526 /// - `OptionCookiesValue` - The cookie value if exists.
527 pub async fn try_get_request_cookie<K>(&self, key: K) -> OptionCookiesValue
528 where
529 K: AsRef<str>,
530 {
531 self.get_request_cookies().await.get(key.as_ref()).cloned()
532 }
533
534 /// Retrieves the upgrade type of the request.
535 ///
536 /// # Returns
537 ///
538 /// - `UpgradeType` - Indicates if the request is for a WebSocket connection.
539 pub async fn get_request_upgrade_type(&self) -> UpgradeType {
540 self.read().await.get_request().get_upgrade_type()
541 }
542
543 /// Checks if the request is a WebSocket upgrade request.
544 ///
545 /// # Returns
546 ///
547 /// - `bool` - True if this is a WebSocket upgrade request.
548 pub async fn get_request_is_ws(&self) -> bool {
549 self.read().await.get_request().is_ws()
550 }
551
552 /// Checks if the request is an HTTP/2 cleartext (h2c) upgrade.
553 ///
554 /// # Returns
555 ///
556 /// - `bool` - True if this is an h2c upgrade request.
557 pub async fn get_request_is_h2c(&self) -> bool {
558 self.read().await.get_request().is_h2c()
559 }
560
561 /// Checks if the request is a TLS upgrade.
562 ///
563 /// # Returns
564 ///
565 /// - `bool` - True if this is a TLS upgrade request.
566 pub async fn get_request_is_tls(&self) -> bool {
567 self.read().await.get_request().is_tls()
568 }
569
570 /// Checks if the request has an unknown upgrade type.
571 ///
572 /// # Returns
573 ///
574 /// - `bool` - True if the upgrade type is unknown.
575 pub async fn get_request_is_unknown_upgrade(&self) -> bool {
576 self.read().await.get_request().is_unknown_upgrade()
577 }
578
579 /// Checks if the request HTTP version is HTTP/1.1 or higher.
580 ///
581 /// # Returns
582 ///
583 /// - `bool` - True if the version is HTTP/1.1 or higher.
584 pub async fn get_request_is_http1_1_or_higher(&self) -> bool {
585 self.read().await.get_request().is_http1_1_or_higher()
586 }
587
588 /// Checks if the request HTTP version is HTTP/0.9.
589 ///
590 /// # Returns
591 ///
592 /// - `bool` - True if the version is HTTP/0.9.
593 pub async fn get_request_is_http0_9(&self) -> bool {
594 self.read().await.get_request().is_http0_9()
595 }
596
597 /// Checks if the request HTTP version is HTTP/1.0.
598 ///
599 /// # Returns
600 ///
601 /// - `bool` - True if the version is HTTP/1.0.
602 pub async fn get_request_is_http1_0(&self) -> bool {
603 self.read().await.get_request().is_http1_0()
604 }
605
606 /// Checks if the request HTTP version is HTTP/1.1.
607 ///
608 /// # Returns
609 ///
610 /// - `bool` - True if the version is HTTP/1.1.
611 pub async fn get_request_is_http1_1(&self) -> bool {
612 self.read().await.get_request().is_http1_1()
613 }
614
615 /// Checks if the request HTTP version is HTTP/2.
616 ///
617 /// # Returns
618 ///
619 /// - `bool` - True if the version is HTTP/2.
620 pub async fn get_request_is_http2(&self) -> bool {
621 self.read().await.get_request().is_http2()
622 }
623
624 /// Checks if the request HTTP version is HTTP/3.
625 ///
626 /// # Returns
627 ///
628 /// - `bool` - True if the version is HTTP/3.
629 pub async fn get_request_is_http3(&self) -> bool {
630 self.read().await.get_request().is_http3()
631 }
632
633 /// Checks if the request has an unknown HTTP version.
634 ///
635 /// # Returns
636 ///
637 /// - `bool` - True if the version is unknown.
638 pub async fn get_request_is_unknown_version(&self) -> bool {
639 self.read().await.get_request().is_unknown_version()
640 }
641
642 /// Checks if the request uses HTTP protocol.
643 ///
644 /// # Returns
645 ///
646 /// - `bool` - True if the version belongs to HTTP family.
647 pub async fn get_request_is_http(&self) -> bool {
648 self.read().await.get_request().is_http()
649 }
650
651 /// Checks if the request method is GET.
652 ///
653 /// # Returns
654 ///
655 /// - `bool` - True if the method is GET.
656 pub async fn get_request_is_get(&self) -> bool {
657 self.read().await.get_request().is_get()
658 }
659
660 /// Checks if the request method is POST.
661 ///
662 /// # Returns
663 ///
664 /// - `bool` - True if the method is POST.
665 pub async fn get_request_is_post(&self) -> bool {
666 self.read().await.get_request().is_post()
667 }
668
669 /// Checks if the request method is PUT.
670 ///
671 /// # Returns
672 ///
673 /// - `bool` - True if the method is PUT.
674 pub async fn get_request_is_put(&self) -> bool {
675 self.read().await.get_request().is_put()
676 }
677
678 /// Checks if the request method is DELETE.
679 ///
680 /// # Returns
681 ///
682 /// - `bool` - True if the method is DELETE.
683 pub async fn get_request_is_delete(&self) -> bool {
684 self.read().await.get_request().is_delete()
685 }
686
687 /// Checks if the request method is PATCH.
688 ///
689 /// # Returns
690 ///
691 /// - `bool` - True if the method is PATCH.
692 pub async fn get_request_is_patch(&self) -> bool {
693 self.read().await.get_request().is_patch()
694 }
695
696 /// Checks if the request method is HEAD.
697 ///
698 /// # Returns
699 ///
700 /// - `bool` - True if the method is HEAD.
701 pub async fn get_request_is_head(&self) -> bool {
702 self.read().await.get_request().is_head()
703 }
704
705 /// Checks if the request method is OPTIONS.
706 ///
707 /// # Returns
708 ///
709 /// - `bool` - True if the method is OPTIONS.
710 pub async fn get_request_is_options(&self) -> bool {
711 self.read().await.get_request().is_options()
712 }
713
714 /// Checks if the request method is CONNECT.
715 ///
716 /// # Returns
717 ///
718 /// - `bool` - True if the method is CONNECT.
719 pub async fn get_request_is_connect(&self) -> bool {
720 self.read().await.get_request().is_connect()
721 }
722
723 /// Checks if the request method is TRACE.
724 ///
725 /// # Returns
726 ///
727 /// - `bool` - True if the method is TRACE.
728 pub async fn get_request_is_trace(&self) -> bool {
729 self.read().await.get_request().is_trace()
730 }
731
732 /// Checks if the request method is unknown.
733 ///
734 /// # Returns
735 ///
736 /// - `bool` - True if the method is unknown.
737 pub async fn get_request_is_unknown_method(&self) -> bool {
738 self.read().await.get_request().is_unknown_method()
739 }
740
741 /// Checks if the connection should be kept alive based on request headers.
742 ///
743 /// # Returns
744 ///
745 /// - `bool` - True if the Connection header suggests keeping the connection alive, otherwise false.
746 pub async fn get_request_is_enable_keep_alive(&self) -> bool {
747 self.read().await.get_request().is_enable_keep_alive()
748 }
749
750 /// Checks if keep-alive should be disabled for the request.
751 ///
752 /// # Returns
753 ///
754 /// - `bool` - True if keep-alive should be disabled.
755 pub async fn get_request_is_disable_keep_alive(&self) -> bool {
756 self.read().await.get_request().is_disable_keep_alive()
757 }
758
759 /// Retrieves the current HTTP response.
760 ///
761 /// # Returns
762 ///
763 /// - `Response` - A clone of the current response.
764 pub async fn get_response(&self) -> Response {
765 self.read().await.get_response().clone()
766 }
767
768 /// Sets the HTTP response for the context.
769 ///
770 /// # Arguments
771 ///
772 /// - `Borrow<Response>` - The response to set in the context.
773 ///
774 /// # Returns
775 ///
776 /// - `&Self` - Reference to the modified context.
777 pub async fn set_response<T>(&self, response: T) -> &Self
778 where
779 T: Borrow<Response>,
780 {
781 self.write().await.set_response(response.borrow().clone());
782 self
783 }
784
785 /// Executes an asynchronous closure with the current response.
786 ///
787 /// # Arguments
788 ///
789 /// - `F` - A closure that takes the `Response` and returns a future.
790 ///
791 /// # Returns
792 ///
793 /// - `R` - The result of the provided closure's future.
794 pub async fn with_response<F, Fut, R>(&self, func: F) -> R
795 where
796 F: Fn(Response) -> Fut,
797 Fut: FutureSendStatic<R>,
798 {
799 func(self.read().await.get_response().clone()).await
800 }
801
802 /// Retrieves the string representation of the current response.
803 ///
804 /// # Returns
805 ///
806 /// - `String` - The full response as a string.
807 pub async fn get_response_string(&self) -> String {
808 self.read().await.get_response().get_string()
809 }
810
811 /// Retrieves the HTTP version of the response.
812 ///
813 /// # Returns
814 ///
815 /// - `ResponseVersion` - The HTTP version of the response.
816 pub async fn get_response_version(&self) -> ResponseVersion {
817 self.read().await.get_response().get_version().clone()
818 }
819
820 /// Sets the HTTP version for the response.
821 ///
822 /// # Arguments
823 ///
824 /// - `ResponseVersion` - The HTTP version to set for the response.
825 ///
826 /// # Returns
827 ///
828 /// - `&Self` - Reference to the modified context.
829 pub async fn set_response_version(&self, version: ResponseVersion) -> &Self {
830 self.write().await.get_mut_response().set_version(version);
831 self
832 }
833
834 /// Retrieves all response headers.
835 ///
836 /// # Returns
837 ///
838 /// - `ResponseHeaders` - A clone of the response's header map.
839 pub async fn get_response_headers(&self) -> ResponseHeaders {
840 self.read().await.get_response().get_headers().clone()
841 }
842
843 /// Retrieves a specific response header by its key.
844 ///
845 /// # Arguments
846 ///
847 /// - `AsRef<str>` - The key of the header to retrieve.
848 ///
849 /// # Returns
850 ///
851 /// - `OptionResponseHeadersValue` - The header values if the header exists.
852 pub async fn try_get_response_header<K>(&self, key: K) -> OptionResponseHeadersValue
853 where
854 K: AsRef<str>,
855 {
856 self.read().await.get_response().try_get_header(key)
857 }
858
859 /// Sets a response header with a new value, removing any existing values.
860 ///
861 /// # Arguments
862 ///
863 /// - `K` - The key of the header to set.
864 /// - `V` - The new value for the header.
865 ///
866 /// # Returns
867 ///
868 /// - `&Self` - Reference to the modified context.
869 pub async fn set_response_header<K, V>(&self, key: K, value: V) -> &Self
870 where
871 K: AsRef<str>,
872 V: AsRef<str>,
873 {
874 self.write().await.get_mut_response().set_header(key, value);
875 self
876 }
877
878 /// Retrieves the first value of a specific response header.
879 ///
880 /// # Arguments
881 ///
882 /// - `AsRef<str>` - The key of the header.
883 ///
884 /// # Returns
885 ///
886 /// - `OptionResponseHeadersValueItem` - The first value of the header if it exists.
887 pub async fn try_get_response_header_front<K>(&self, key: K) -> OptionResponseHeadersValueItem
888 where
889 K: AsRef<str>,
890 {
891 self.read().await.get_response().try_get_header_front(key)
892 }
893
894 /// Retrieves the last value of a specific response header.
895 ///
896 /// # Arguments
897 ///
898 /// - `AsRef<str>` - The key of the header.
899 ///
900 /// # Returns
901 ///
902 /// - `OptionResponseHeadersValueItem` - The last value of the header if it exists.
903 pub async fn try_get_response_header_back<K>(&self, key: K) -> OptionResponseHeadersValueItem
904 where
905 K: AsRef<str>,
906 {
907 self.read().await.get_response().try_get_header_back(key)
908 }
909
910 /// Checks if a specific response header exists.
911 ///
912 /// # Arguments
913 ///
914 /// - `AsRef<str>` - The key of the header to check.
915 ///
916 /// # Returns
917 ///
918 /// - `bool` - True if the header exists, otherwise false.
919 pub async fn get_response_has_header<K>(&self, key: K) -> bool
920 where
921 K: AsRef<str>,
922 {
923 self.read().await.get_response().has_header(key)
924 }
925
926 /// Checks if a response header has a specific value.
927 ///
928 /// # Arguments
929 ///
930 /// - `AsRef<str>` - The key of the header.
931 /// - `AsRef<str>` - The value to check for.
932 ///
933 /// # Returns
934 ///
935 /// - `bool` - True if the header contains the specified value, otherwise false.
936 pub async fn get_response_header_value<K, V>(&self, key: K, value: V) -> bool
937 where
938 K: AsRef<str>,
939 V: AsRef<str>,
940 {
941 self.read()
942 .await
943 .get_response()
944 .has_header_value(key, value)
945 }
946
947 /// Retrieves the total number of response headers.
948 ///
949 /// # Returns
950 ///
951 /// - `usize` - The total number of headers in the response.
952 pub async fn get_response_headers_length(&self) -> usize {
953 self.read().await.get_response().get_headers_length()
954 }
955
956 /// Retrieves the number of values for a specific response header.
957 ///
958 /// # Arguments
959 ///
960 /// - `AsRef<str>` - The key of the header.
961 ///
962 /// # Returns
963 ///
964 /// - `usize` - The number of values for the specified header.
965 pub async fn get_response_header_length<K>(&self, key: K) -> usize
966 where
967 K: AsRef<str>,
968 {
969 self.read().await.get_response().get_header_length(key)
970 }
971
972 /// Retrieves the total number of values across all response headers.
973 ///
974 /// # Returns
975 ///
976 /// - `usize` - The total count of all values in all headers.
977 pub async fn get_response_headers_values_length(&self) -> usize {
978 self.read().await.get_response().get_headers_values_length()
979 }
980
981 /// Adds a response header, adding it if it doesn't exist or appending to it if it does.
982 ///
983 /// # Arguments
984 ///
985 /// - `AsRef<str>` - The header key.
986 /// - `AsRef<str>` - The header value.
987 ///
988 /// # Returns
989 ///
990 /// - `&Self` - Reference to self for method chaining.
991 pub async fn add_response_header<K, V>(&self, key: K, value: V) -> &Self
992 where
993 K: AsRef<str>,
994 V: AsRef<str>,
995 {
996 self.write().await.get_mut_response().add_header(key, value);
997 self
998 }
999
1000 /// Removes a response header and all its values.
1001 ///
1002 /// # Arguments
1003 ///
1004 /// - `AsRef<str>` - The key of the header to remove.
1005 ///
1006 /// # Returns
1007 ///
1008 /// - `&Self` - Reference to the modified context.
1009 pub async fn remove_response_header<K>(&self, key: K) -> &Self
1010 where
1011 K: AsRef<str>,
1012 {
1013 self.write().await.get_mut_response().remove_header(key);
1014 self
1015 }
1016
1017 /// Removes a specific value from a response header.
1018 ///
1019 /// # Arguments
1020 ///
1021 /// - `AsRef<str>` - The header key.
1022 /// - `AsRef<str>` - The value to remove.
1023 ///
1024 /// # Returns
1025 ///
1026 /// - `&Self` - Reference to self for method chaining.
1027 pub async fn remove_response_header_value<K, V>(&self, key: K, value: V) -> &Self
1028 where
1029 K: AsRef<str>,
1030 V: AsRef<str>,
1031 {
1032 self.write()
1033 .await
1034 .get_mut_response()
1035 .remove_header_value(key, value);
1036 self
1037 }
1038
1039 /// Clears all headers from the response.
1040 ///
1041 /// # Returns
1042 ///
1043 /// - `&Self` - Reference to the modified context.
1044 pub async fn clear_response_headers(&self) -> &Self {
1045 self.write().await.get_mut_response().clear_headers();
1046 self
1047 }
1048
1049 /// Parses and retrieves all cookies from the response headers.
1050 ///
1051 /// # Returns
1052 ///
1053 /// - `Cookies` - A map of cookies parsed from the response's Cookie header.
1054 pub async fn get_response_cookies(&self) -> Cookies {
1055 self.try_get_response_header_back(COOKIE)
1056 .await
1057 .map(|data| Cookie::parse(&data))
1058 .unwrap_or_default()
1059 }
1060
1061 /// Retrieves a specific cookie by its name from the response.
1062 ///
1063 /// # Arguments
1064 ///
1065 /// - `AsRef<str>` - The name of the cookie to retrieve.
1066 ///
1067 /// # Returns
1068 ///
1069 /// - `OptionCookiesValue` - The cookie's value if it exists.
1070 pub async fn try_get_response_cookie<K>(&self, key: K) -> OptionCookiesValue
1071 where
1072 K: AsRef<str>,
1073 {
1074 self.get_response_cookies().await.get(key.as_ref()).cloned()
1075 }
1076
1077 /// Retrieves the body of the response.
1078 ///
1079 /// # Returns
1080 ///
1081 /// - `ResponseBody` - A clone of the response's body.
1082 pub async fn get_response_body(&self) -> ResponseBody {
1083 self.read().await.get_response().get_body().clone()
1084 }
1085
1086 /// Sets the body of the response.
1087 ///
1088 /// # Arguments
1089 ///
1090 /// - `B` - The body to set for the response.
1091 ///
1092 /// # Returns
1093 ///
1094 /// - `&Self` - Reference to the modified context.
1095 pub async fn set_response_body<B>(&self, body: B) -> &Self
1096 where
1097 B: AsRef<[u8]>,
1098 {
1099 self.write().await.get_mut_response().set_body(body);
1100 self
1101 }
1102
1103 /// Retrieves the response body as a string.
1104 ///
1105 /// # Returns
1106 ///
1107 /// - `String` - The response body converted to a string.
1108 pub async fn get_response_body_string(&self) -> String {
1109 self.read().await.get_response().get_body_string()
1110 }
1111
1112 /// Deserializes the response body from JSON into a specified type.
1113 ///
1114 /// # Returns
1115 ///
1116 /// - `ResultJsonError<J>` - The deserialized type `J` or a JSON error.
1117 pub async fn get_response_body_json<J>(&self) -> ResultJsonError<J>
1118 where
1119 J: DeserializeOwned,
1120 {
1121 self.read().await.get_response().get_body_json()
1122 }
1123
1124 /// Retrieves the reason phrase of the response's status code.
1125 ///
1126 /// # Returns
1127 ///
1128 /// - `ResponseReasonPhrase` - The reason phrase associated with the response's status code.
1129 pub async fn get_response_reason_phrase(&self) -> ResponseReasonPhrase {
1130 self.read().await.get_response().get_reason_phrase().clone()
1131 }
1132
1133 /// Sets the reason phrase for the response's status code.
1134 ///
1135 /// # Arguments
1136 ///
1137 /// - `AsRef<str>` - The reason phrase to set.
1138 ///
1139 /// # Returns
1140 ///
1141 /// - `&Self` - Reference to the modified context.
1142 pub async fn set_response_reason_phrase<P>(&self, reason_phrase: P) -> &Self
1143 where
1144 P: AsRef<str>,
1145 {
1146 self.write()
1147 .await
1148 .get_mut_response()
1149 .set_reason_phrase(reason_phrase);
1150 self
1151 }
1152
1153 /// Retrieves the status code of the response.
1154 ///
1155 /// # Returns
1156 ///
1157 /// The status code of the response.
1158 pub async fn get_response_status_code(&self) -> ResponseStatusCode {
1159 *self.read().await.get_response().get_status_code()
1160 }
1161
1162 /// Sets the status code for the response.
1163 ///
1164 /// # Arguments
1165 ///
1166 /// - `ResponseStatusCode` - The status code to set for the response.
1167 ///
1168 /// # Returns
1169 ///
1170 /// - `&Self` - A reference to the modified context.
1171 pub async fn set_response_status_code(&self, status_code: ResponseStatusCode) -> &Self {
1172 self.write()
1173 .await
1174 .get_mut_response()
1175 .set_status_code(status_code);
1176 self
1177 }
1178
1179 /// Retrieves the parameters extracted from the route path.
1180 ///
1181 /// # Returns
1182 ///
1183 /// - `RouteParams` - A map containing the route parameters.
1184 pub async fn get_route_params(&self) -> RouteParams {
1185 self.read().await.get_route_params().clone()
1186 }
1187
1188 /// Sets the route parameters for the context.
1189 ///
1190 /// # Arguments
1191 ///
1192 /// - `RouteParams` - The route parameters to set.
1193 ///
1194 /// # Returns
1195 ///
1196 /// - `&Self` - A reference to the modified `Context`.
1197 pub(crate) async fn set_route_params(&self, params: RouteParams) -> &Self {
1198 self.write().await.set_route_params(params);
1199 self
1200 }
1201
1202 /// Retrieves a specific route parameter by its name.
1203 ///
1204 /// # Arguments
1205 ///
1206 /// - `AsRef<str>` - The name of the route parameter to retrieve.
1207 ///
1208 /// # Returns
1209 ///
1210 /// - `OptionString` - The value of the route parameter if it exists.
1211 pub async fn try_get_route_param<T>(&self, name: T) -> OptionString
1212 where
1213 T: AsRef<str>,
1214 {
1215 self.read()
1216 .await
1217 .get_route_params()
1218 .get(name.as_ref())
1219 .cloned()
1220 }
1221
1222 /// Retrieves all attributes stored in the context.
1223 ///
1224 /// # Returns
1225 ///
1226 /// - `ThreadSafeAttributeStore` - A map containing all attributes.
1227 pub async fn get_attributes(&self) -> ThreadSafeAttributeStore {
1228 self.read().await.get_attributes().clone()
1229 }
1230
1231 /// Retrieves a specific attribute by its key, casting it to the specified type.
1232 ///
1233 /// # Arguments
1234 ///
1235 /// - `AsRef<str>` - The key of the attribute to retrieve.
1236 ///
1237 /// # Returns
1238 ///
1239 /// - `Option<V>` - The attribute's value if it exists and can be cast to the specified type.
1240 pub async fn try_get_attribute<K, V>(&self, key: K) -> Option<V>
1241 where
1242 K: AsRef<str>,
1243 V: AnySendSyncClone,
1244 {
1245 self.read()
1246 .await
1247 .get_attributes()
1248 .get(&Attribute::External(key.as_ref().to_owned()).to_string())
1249 .and_then(|arc| arc.downcast_ref::<V>())
1250 .cloned()
1251 }
1252
1253 /// Sets an attribute in the context.
1254 ///
1255 /// # Arguments
1256 ///
1257 /// - `AsRef<str>` - The key of the attribute to set.
1258 /// - `AnySendSyncClone` - The value of the attribute.
1259 ///
1260 /// # Returns
1261 ///
1262 /// - `&Self` - A reference to the modified context.
1263 pub async fn set_attribute<K, V>(&self, key: K, value: V) -> &Self
1264 where
1265 K: AsRef<str>,
1266 V: AnySendSyncClone,
1267 {
1268 self.write().await.get_mut_attributes().insert(
1269 Attribute::External(key.as_ref().to_owned()).to_string(),
1270 Arc::new(value),
1271 );
1272 self
1273 }
1274
1275 /// Removes an attribute from the context.
1276 ///
1277 /// # Arguments
1278 ///
1279 /// - `AsRef<str>` - The key of the attribute to remove.
1280 ///
1281 /// # Returns
1282 ///
1283 /// - `&Self` - A reference to the modified context.
1284 pub async fn remove_attribute<K>(&self, key: K) -> &Self
1285 where
1286 K: AsRef<str>,
1287 {
1288 self.write()
1289 .await
1290 .get_mut_attributes()
1291 .remove(&Attribute::External(key.as_ref().to_owned()).to_string());
1292 self
1293 }
1294
1295 /// Clears all attributes from the context.
1296 ///
1297 /// # Returns
1298 ///
1299 /// - `&Self` - A reference to the modified context.
1300 pub async fn clear_attribute(&self) -> &Self {
1301 self.write().await.get_mut_attributes().clear();
1302 self
1303 }
1304
1305 /// Retrieves an internal framework attribute.
1306 ///
1307 /// # Arguments
1308 ///
1309 /// - `InternalAttribute` - The internal attribute key to retrieve.
1310 ///
1311 /// # Returns
1312 ///
1313 /// - `Option<V>` - The attribute's value if it exists and can be cast to the specified type.
1314 async fn try_get_internal_attribute<V>(&self, key: InternalAttribute) -> Option<V>
1315 where
1316 V: AnySendSyncClone,
1317 {
1318 self.read()
1319 .await
1320 .get_attributes()
1321 .get(&Attribute::Internal(key).to_string())
1322 .and_then(|arc| arc.downcast_ref::<V>())
1323 .cloned()
1324 }
1325
1326 /// Sets an internal framework attribute.
1327 ///
1328 /// # Arguments
1329 ///
1330 /// - `InternalAttribute` - The internal attribute key to set.
1331 /// - `AnySendSyncClone` - The value of the attribute.
1332 ///
1333 /// # Returns
1334 ///
1335 /// - `&Self` - A reference to the modified context.
1336 async fn set_internal_attribute<V>(&self, key: InternalAttribute, value: V) -> &Self
1337 where
1338 V: AnySendSyncClone,
1339 {
1340 self.write()
1341 .await
1342 .get_mut_attributes()
1343 .insert(Attribute::Internal(key).to_string(), Arc::new(value));
1344 self
1345 }
1346
1347 /// Retrieves panic information if a panic has occurred during handling.
1348 ///
1349 /// # Returns
1350 ///
1351 /// - `OptionalPanicInfo` - The panic information if a panic was caught.
1352 pub async fn try_get_panic(&self) -> OptionalPanicInfo {
1353 self.try_get_internal_attribute(InternalAttribute::Panic)
1354 .await
1355 }
1356
1357 /// Sets the panic information for the context.
1358 ///
1359 /// # Arguments
1360 ///
1361 /// - `Panic` - The panic information to store.
1362 ///
1363 /// # Returns
1364 ///
1365 /// - `&Self` - A reference to the modified context.
1366 pub(crate) async fn set_panic(&self, panic: Panic) -> &Self {
1367 self.set_internal_attribute(InternalAttribute::Panic, panic)
1368 .await
1369 }
1370
1371 /// Sets a hook function for the context with a custom key.
1372 ///
1373 /// # Arguments
1374 ///
1375 /// - `ToString` - The key to identify this hook.
1376 /// - `FnContextSendSyncStatic<Fut, ()>, Fut: FutureSendStatic<()>` - The hook function to store.
1377 ///
1378 /// # Returns
1379 ///
1380 /// - `&Self` - A reference to the modified context.
1381 pub async fn set_hook<K, F, Fut>(&self, key: K, hook: F) -> &Self
1382 where
1383 K: ToString,
1384 F: FnContextSendSyncStatic<Fut, ()>,
1385 Fut: FutureSendStatic<()>,
1386 {
1387 let hook_fn: SharedHookHandler<()> =
1388 Arc::new(move |ctx: Context| -> SendableAsyncTask<()> { Box::pin(hook(ctx)) });
1389 self.set_internal_attribute(InternalAttribute::Hook(key.to_string()), hook_fn)
1390 .await
1391 }
1392
1393 /// Retrieves a hook function if it has been set.
1394 ///
1395 /// # Arguments
1396 ///
1397 /// - `K: ToString` - The key to identify the hook.
1398 ///
1399 /// # Returns
1400 ///
1401 /// - `OptionalHookHandler<()>` - The hook function if it has been set.
1402 pub async fn try_get_hook<K>(&self, key: K) -> OptionalHookHandler<()>
1403 where
1404 K: ToString,
1405 {
1406 self.try_get_internal_attribute(InternalAttribute::Hook(key.to_string()))
1407 .await
1408 }
1409
1410 /// Updates the lifecycle status based on the current context state.
1411 ///
1412 /// # Arguments
1413 ///
1414 /// - `&mut RequestLifecycle` - The request lifecycle to update.
1415 pub(crate) async fn update_lifecycle_status(&self, lifecycle: &mut RequestLifecycle) {
1416 let keep_alive: bool = !self.get_closed().await && lifecycle.is_keep_alive();
1417 let aborted: bool = self.get_aborted().await;
1418 lifecycle.update_status(aborted, keep_alive);
1419 }
1420
1421 /// Sends the response headers and body to the client.
1422 ///
1423 /// # Returns
1424 ///
1425 /// - `ResponseResult` - The outcome of the send operation.
1426 pub async fn send(&self) -> ResponseResult {
1427 if self.is_terminated().await {
1428 return Err(ResponseError::Terminated);
1429 }
1430 let response_data: ResponseData = self.write().await.get_mut_response().build();
1431 if let Some(stream) = self.try_get_stream().await {
1432 return stream.send(response_data).await;
1433 }
1434 Err(ResponseError::NotFoundStream)
1435 }
1436
1437 /// Sends only the response body to the client.
1438 ///
1439 /// This is useful for streaming data or for responses where headers have already been sent.
1440 ///
1441 /// # Returns
1442 ///
1443 /// - `ResponseResult` - The outcome of the send operation.
1444 pub async fn send_body(&self) -> ResponseResult {
1445 let response_body: ResponseBody = self.get_response_body().await;
1446 self.send_body_with_data(response_body).await
1447 }
1448
1449 /// Sends only the response body to the client with additional data.
1450 ///
1451 /// This is useful for streaming data or for responses where headers have already been sent.
1452 ///
1453 /// # Arguments
1454 ///
1455 /// - `AsRef<[u8]>` - The additional data to send as the body.
1456 ///
1457 /// # Returns
1458 ///
1459 /// - `ResponseResult` - The outcome of the send operation.
1460 pub async fn send_body_with_data<D>(&self, data: D) -> ResponseResult
1461 where
1462 D: AsRef<[u8]>,
1463 {
1464 if self.is_terminated().await {
1465 return Err(ResponseError::Terminated);
1466 }
1467 if let Some(stream) = self.try_get_stream().await {
1468 return stream.send_body(data).await;
1469 }
1470 Err(ResponseError::NotFoundStream)
1471 }
1472
1473 /// Sends a list of response bodies to the client with additional data.
1474 ///
1475 /// This is useful for streaming multiple data chunks or for responses where headers have already been sent.
1476 ///
1477 /// # Arguments
1478 ///
1479 /// - `I: IntoIterator<Item = D>, D: AsRef<[u8]>` - The additional data to send as a list of bodies.
1480 ///
1481 /// # Returns
1482 ///
1483 /// - `ResponseResult` - The outcome of the send operation.
1484 pub async fn send_body_list_with_data<I, D>(&self, data_iter: I) -> ResponseResult
1485 where
1486 I: IntoIterator<Item = D>,
1487 D: AsRef<[u8]>,
1488 {
1489 if self.is_terminated().await {
1490 return Err(ResponseError::Terminated);
1491 }
1492 if let Some(stream) = self.try_get_stream().await {
1493 return stream.send_body_list(data_iter).await;
1494 }
1495 Err(ResponseError::NotFoundStream)
1496 }
1497
1498 /// Flushes the underlying network stream, ensuring all buffered data is sent.
1499 ///
1500 /// # Returns
1501 ///
1502 /// - `ResponseResult` - The outcome of the flush operation.
1503 pub async fn flush(&self) -> ResponseResult {
1504 if let Some(stream) = self.try_get_stream().await {
1505 stream.flush().await;
1506 return Ok(());
1507 }
1508 Err(ResponseError::NotFoundStream)
1509 }
1510
1511 /// Reads an HTTP request from the underlying stream.
1512 ///
1513 /// # Arguments
1514 ///
1515 /// - `usize` - The read buffer size.
1516 ///
1517 /// # Returns
1518 ///
1519 /// - `RequestReaderHandleResult` - The parsed request or error.
1520 pub async fn http_from_stream(&self, buffer: usize) -> RequestReaderHandleResult {
1521 if self.get_aborted().await {
1522 return Err(RequestError::RequestAborted);
1523 }
1524 if let Some(stream) = self.try_get_stream().await.as_ref() {
1525 let request_res: RequestReaderHandleResult =
1526 Request::http_from_stream(stream, buffer).await;
1527 if let Ok(request) = request_res.as_ref() {
1528 self.set_request(request).await;
1529 }
1530 return request_res;
1531 };
1532 Err(RequestError::GetTcpStream)
1533 }
1534
1535 /// Reads a WebSocket frame from the underlying stream.
1536 ///
1537 /// # Arguments
1538 ///
1539 /// - `usize` - The read buffer size.
1540 ///
1541 /// # Returns
1542 ///
1543 /// - `RequestReaderHandleResult` - The parsed frame or error.
1544 pub async fn ws_from_stream(&self, buffer: usize) -> RequestReaderHandleResult {
1545 if self.get_aborted().await {
1546 return Err(RequestError::RequestAborted);
1547 }
1548 if let Some(stream) = self.try_get_stream().await.as_ref() {
1549 let mut last_request: Request = self.get_request().await;
1550 let request_res: RequestReaderHandleResult =
1551 Request::ws_from_stream(stream, buffer, &mut last_request).await;
1552 match request_res.as_ref() {
1553 Ok(request) => {
1554 self.set_request(request).await;
1555 }
1556 Err(_) => {
1557 self.set_request(&last_request).await;
1558 }
1559 }
1560 return request_res;
1561 };
1562 Err(RequestError::GetTcpStream)
1563 }
1564}