1use std::net::SocketAddr;
9use std::sync::Arc;
10
11use bytes::Bytes;
12use http::Version;
13
14use crate::body::RequestBody;
15use crate::client::Client;
16use crate::error::Result;
17use crate::headers::Headers;
18use crate::redirect::RedirectPolicy;
19use crate::response::Response;
20#[cfg(feature = "logical-retry")]
21use crate::retry::RetryPolicy;
22use crate::timeout::Timeout;
23
24use crate::auth::AuthScheme;
25#[cfg(feature = "proxy")]
26use crate::proxy::ProxyConfig;
27
28pub use crate::transport_hints::{NativeRequestOptions, ResolvedTarget, TransportHints};
34
35#[derive(Debug, Clone, Default)]
40#[allow(
41 clippy::large_enum_variant,
42 reason = "ProxyConfig is transient and cloning it is cheap; boxing adds unnecessary allocation"
43)]
44pub enum ProxyOverride {
45 #[default]
47 Inherit,
48 Direct,
50 #[cfg(feature = "proxy")]
52 Override(ProxyConfig),
53}
54
55pub(crate) struct RequestParts {
62 pub(crate) method: http::Method,
63 pub(crate) url: url::Url,
64 pub(crate) headers: Headers,
65 pub(crate) body: RequestBody,
66 pub(crate) version: Version,
67 pub(crate) timeout: Option<Timeout>,
68 pub(crate) redirect: Option<RedirectPolicy>,
69 pub(crate) auth: Option<AuthScheme>,
70 pub(crate) auth_disabled: bool,
71 pub(crate) decompress: Option<bool>,
72 pub(crate) max_decoded_body_size: Option<usize>,
73 pub(crate) max_decompression_ratio: Option<f64>,
74 pub(crate) proxy_override: ProxyOverride,
75 #[cfg(feature = "logical-retry")]
76 pub(crate) retry: Option<RetryPolicy>,
77 pub(crate) retry_disabled: bool,
83 pub(crate) transport_hints: TransportHints,
84 pub(crate) proxied_target: Option<ResolvedTarget>,
85 pub(crate) failure_context: Option<Arc<crate::error::RequestFailureContext>>,
86}
87
88impl RequestParts {
89 #[allow(
96 dead_code,
97 reason = "exhaustiveness anchor for RequestParts: guarantees new fields fail to compile even though live code uses retry_request"
98 )]
99 pub(crate) fn into_request(self) -> Request {
100 let RequestParts {
101 method,
102 url,
103 headers,
104 body,
105 version,
106 timeout,
107 redirect,
108 auth,
109 auth_disabled,
110 decompress,
111 max_decoded_body_size,
112 max_decompression_ratio,
113 proxy_override,
114 #[cfg(feature = "logical-retry")]
115 retry,
116 retry_disabled,
117 transport_hints,
118 proxied_target,
119 failure_context,
120 } = self;
121 let mut request = Request::new(method, url);
122 *request.headers_mut() = headers;
123 request.set_body(body);
124 request.set_version(version);
125 request.set_timeout(timeout);
126 request.set_redirect(redirect);
127 request.set_auth(auth);
128 request.set_auth_disabled(auth_disabled);
129 request.set_decompress(decompress);
130 request.set_max_decoded_body_size(max_decoded_body_size);
131 request.set_max_decompression_ratio(max_decompression_ratio);
132 #[cfg(feature = "proxy")]
133 request.set_proxy_override(proxy_override);
134 #[cfg(not(feature = "proxy"))]
135 let _ = proxy_override;
136 #[cfg(feature = "logical-retry")]
137 request.set_retry(retry);
138 #[cfg(not(feature = "logical-retry"))]
139 let _ = ();
140 request.set_retry_disabled(retry_disabled);
141 request.set_transport_hints(transport_hints);
142 request.set_proxied_target(proxied_target);
143 request.set_failure_context(failure_context);
144 request
145 }
146
147 #[cfg(feature = "logical-retry")]
162 pub(crate) fn retry_request(
163 &self,
164 attempt_timeout: Option<Timeout>,
165 ) -> crate::error::Result<Request> {
166 let replayed = self.body.try_clone_for_retry()?;
167 let mut request = Request::new(self.method.clone(), self.url.clone());
168 *request.headers_mut() = self.headers.clone();
169 request.set_body(replayed);
170 request.set_version(self.version);
171 request.set_timeout(attempt_timeout);
172 request.set_redirect(self.redirect.clone());
173 request.set_auth(self.auth.clone());
174 request.set_auth_disabled(self.auth_disabled);
175 request.set_decompress(self.decompress);
176 request.set_max_decoded_body_size(self.max_decoded_body_size);
177 request.set_max_decompression_ratio(self.max_decompression_ratio);
178 #[cfg(feature = "proxy")]
179 request.set_proxy_override(self.proxy_override.clone());
180 request.set_retry(self.retry.clone());
181 request.set_retry_disabled(self.retry_disabled);
182 request.set_transport_hints(self.transport_hints.clone());
183 request.set_proxied_target(self.proxied_target.clone());
184 request.set_failure_context(self.failure_context.clone());
185 Ok(request)
186 }
187
188 #[cfg(feature = "logical-retry")]
202 pub(crate) fn shrink_total_deadline(
203 timeout: &Timeout,
204 elapsed: std::time::Duration,
205 ) -> Timeout {
206 let mut out = *timeout;
207 if let Some(total) = out.total {
208 out.total = Some(total.saturating_sub(elapsed));
209 }
210 out
211 }
212}
213
214pub struct Request {
223 method: http::Method,
224 url: url::Url,
225 headers: Headers,
226 body: RequestBody,
227 version: Version,
228 timeout: Option<Timeout>,
229 redirect: Option<RedirectPolicy>,
230 auth: Option<AuthScheme>,
231 auth_disabled: bool,
232 decompress: Option<bool>,
233 max_decoded_body_size: Option<usize>,
234 max_decompression_ratio: Option<f64>,
235 proxy_override: ProxyOverride,
237 #[cfg(feature = "logical-retry")]
239 retry: Option<RetryPolicy>,
240 retry_disabled: bool,
245 transport_hints: TransportHints,
247 proxied_target: Option<ResolvedTarget>,
249 failure_context: Option<Arc<crate::error::RequestFailureContext>>,
252}
253
254impl std::fmt::Debug for Request {
255 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
256 let mut debug = f.debug_struct("Request");
257 debug
258 .field("method", &self.method)
259 .field("url", &crate::redact::redact_url(&self.url))
260 .field("headers", &self.headers)
261 .field("body", &self.body)
262 .field("version", &self.version)
263 .field("timeout", &self.timeout);
264 debug.field("redirect", &self.redirect);
265 debug
266 .field("auth", &self.auth)
267 .field("auth_disabled", &self.auth_disabled)
268 .field("decompress", &self.decompress)
269 .field("max_decoded_body_size", &self.max_decoded_body_size)
270 .field("max_decompression_ratio", &self.max_decompression_ratio)
271 .field("proxy_override", &self.proxy_override);
272 #[cfg(feature = "logical-retry")]
273 debug.field("retry", &self.retry);
274 debug.field("retry_disabled", &self.retry_disabled);
275 debug
276 .field("transport_hints", &self.transport_hints)
277 .field("proxied_target", &self.proxied_target)
278 .field(
279 "failure_context",
280 &self.failure_context.as_ref().map(|_| "configured"),
281 )
282 .finish()
283 }
284}
285
286impl Request {
287 pub(crate) fn new(method: http::Method, url: url::Url) -> Self {
289 Self {
290 method,
291 url,
292 headers: Headers::new(),
293 body: RequestBody::default(),
294 version: Version::HTTP_11,
295 timeout: None,
296 redirect: None,
297 auth: None,
298 auth_disabled: false,
299 decompress: None,
300 max_decoded_body_size: None,
301 max_decompression_ratio: None,
302 proxy_override: ProxyOverride::Inherit,
303 #[cfg(feature = "logical-retry")]
304 retry: None,
305 retry_disabled: false,
306 transport_hints: TransportHints::default(),
307 proxied_target: None,
308 failure_context: None,
309 }
310 }
311
312 #[must_use]
314 pub fn method(&self) -> &http::Method {
315 &self.method
316 }
317
318 #[must_use]
320 pub fn url(&self) -> &url::Url {
321 &self.url
322 }
323
324 #[must_use]
326 pub fn headers(&self) -> &Headers {
327 &self.headers
328 }
329
330 pub fn headers_mut(&mut self) -> &mut Headers {
332 &mut self.headers
333 }
334
335 #[must_use]
337 pub fn body(&self) -> &RequestBody {
338 &self.body
339 }
340
341 pub fn set_body(&mut self, body: RequestBody) {
343 self.body = body;
344 }
345
346 #[must_use]
348 pub fn version(&self) -> Version {
349 self.version
350 }
351
352 pub fn set_version(&mut self, version: Version) {
354 self.version = version;
355 }
356
357 #[must_use]
359 pub fn timeout(&self) -> Option<&Timeout> {
360 self.timeout.as_ref()
361 }
362
363 pub fn set_timeout(&mut self, timeout: Option<Timeout>) {
365 self.timeout = timeout;
366 }
367
368 #[must_use]
375 pub fn redirect(&self) -> Option<&RedirectPolicy> {
376 self.redirect.as_ref()
377 }
378
379 pub fn set_redirect(&mut self, redirect: Option<RedirectPolicy>) {
385 self.redirect = redirect;
386 }
387
388 #[must_use]
390 pub fn auth(&self) -> Option<&AuthScheme> {
391 self.auth.as_ref()
392 }
393
394 pub fn set_auth(&mut self, auth: Option<AuthScheme>) {
396 self.auth = auth;
397 }
398
399 #[must_use]
401 pub fn is_auth_disabled(&self) -> bool {
402 self.auth_disabled
403 }
404
405 pub fn set_auth_disabled(&mut self, disabled: bool) {
407 self.auth_disabled = disabled;
408 }
409
410 #[must_use]
416 pub fn decompress(&self) -> Option<bool> {
417 self.decompress
418 }
419
420 pub fn set_decompress(&mut self, decompress: Option<bool>) {
422 self.decompress = decompress;
423 }
424
425 #[must_use]
429 pub fn max_decoded_body_size(&self) -> Option<usize> {
430 self.max_decoded_body_size
431 }
432
433 pub fn set_max_decoded_body_size(&mut self, max: Option<usize>) {
435 self.max_decoded_body_size = max;
436 }
437
438 #[must_use]
442 pub fn max_decompression_ratio(&self) -> Option<f64> {
443 self.max_decompression_ratio
444 }
445
446 pub fn set_max_decompression_ratio(&mut self, ratio: Option<f64>) {
448 self.max_decompression_ratio = ratio;
449 }
450
451 #[cfg(feature = "proxy")]
453 #[must_use]
454 pub fn proxy_override(&self) -> &ProxyOverride {
455 &self.proxy_override
456 }
457
458 #[cfg(feature = "proxy")]
460 pub fn set_proxy_override(&mut self, proxy: ProxyOverride) {
461 self.proxy_override = proxy;
462 }
463
464 #[cfg(feature = "logical-retry")]
468 #[must_use]
469 pub fn retry(&self) -> Option<&RetryPolicy> {
470 self.retry.as_ref()
471 }
472
473 #[cfg(feature = "logical-retry")]
477 pub fn set_retry(&mut self, retry: Option<RetryPolicy>) {
478 self.retry = retry;
479 }
480
481 #[must_use]
486 pub fn is_retry_disabled(&self) -> bool {
487 self.retry_disabled
488 }
489
490 pub fn set_retry_disabled(&mut self, retry_disabled: bool) {
496 self.retry_disabled = retry_disabled;
497 }
498
499 #[must_use]
501 pub fn transport_hints(&self) -> &TransportHints {
502 &self.transport_hints
503 }
504
505 pub fn set_transport_hints(&mut self, hints: TransportHints) {
507 self.transport_hints = hints;
508 }
509
510 #[must_use]
513 pub fn proxied_target(&self) -> Option<&ResolvedTarget> {
514 self.proxied_target.as_ref()
515 }
516
517 pub fn set_proxied_target(&mut self, target: Option<ResolvedTarget>) {
519 self.proxied_target = target;
520 }
521
522 pub(crate) fn set_failure_context(
523 &mut self,
524 context: Option<Arc<crate::error::RequestFailureContext>>,
525 ) {
526 self.failure_context = context;
527 }
528
529 pub(crate) fn into_parts(self) -> RequestParts {
533 RequestParts {
534 method: self.method,
535 url: self.url,
536 headers: self.headers,
537 body: self.body,
538 version: self.version,
539 timeout: self.timeout,
540 redirect: self.redirect,
541 auth: self.auth,
542 auth_disabled: self.auth_disabled,
543 decompress: self.decompress,
544 max_decoded_body_size: self.max_decoded_body_size,
545 max_decompression_ratio: self.max_decompression_ratio,
546 proxy_override: self.proxy_override,
547 #[cfg(feature = "logical-retry")]
548 retry: self.retry,
549 retry_disabled: self.retry_disabled,
550 transport_hints: self.transport_hints,
551 proxied_target: self.proxied_target,
552 failure_context: self.failure_context,
553 }
554 }
555}
556
557pub struct RequestBuilder {
559 client: Option<Client>,
560 method: http::Method,
561 url: url::Url,
562 headers: Headers,
563 body: RequestBody,
564 timeout: Option<Timeout>,
565 redirect: Option<RedirectPolicy>,
566 auth: Option<AuthScheme>,
567 auth_disabled: bool,
568 decompress: Option<bool>,
569 max_decoded_body_size: Option<usize>,
570 max_decompression_ratio: Option<f64>,
571 proxy_override: ProxyOverride,
572 #[cfg(feature = "logical-retry")]
573 retry: Option<RetryPolicy>,
574 retry_disabled: bool,
579 transport_hints: TransportHints,
580 proxied_target: Option<ResolvedTarget>,
581 error: Option<crate::Error>,
582}
583
584impl RequestBuilder {
585 pub(crate) fn new(client: Client, method: http::Method, url: url::Url) -> Self {
587 Self {
588 client: Some(client),
589 method,
590 url,
591 headers: Headers::new(),
592 body: RequestBody::default(),
593 timeout: None,
594 redirect: None,
595 auth: None,
596 auth_disabled: false,
597 decompress: None,
598 max_decoded_body_size: None,
599 max_decompression_ratio: None,
600 proxy_override: ProxyOverride::Inherit,
601 #[cfg(feature = "logical-retry")]
602 retry: None,
603 retry_disabled: false,
604 transport_hints: TransportHints::default(),
605 proxied_target: None,
606 error: None,
607 }
608 }
609
610 #[must_use]
612 pub fn header(mut self, name: &str, value: &str) -> Self {
613 if let Err(e) = self.headers.insert(name, value) {
614 if self.error.is_none() {
615 self.error = Some(e);
616 }
617 }
618 self
619 }
620
621 #[must_use]
623 pub fn headers(mut self, headers: Headers) -> Self {
624 self.headers = headers;
625 self
626 }
627
628 #[must_use]
630 pub fn query(mut self, key: &str, value: &str) -> Self {
631 self.url.query_pairs_mut().append_pair(key, value);
632 self
633 }
634
635 #[must_use]
637 pub fn body(mut self, body: impl Into<RequestBody>) -> Self {
638 self.body = body.into();
639 self
640 }
641
642 #[must_use]
644 pub fn bytes(self, data: impl Into<Bytes>) -> Self {
645 self.body(RequestBody::Bytes(data.into()))
646 }
647
648 #[cfg(feature = "json")]
662 pub fn json<T: serde::Serialize>(mut self, value: &T) -> Result<Self> {
663 let bytes = serde_json::to_vec(value)
664 .map_err(|_| crate::Error::JsonSerialize("failed to serialize JSON value".into()))?;
665 self.body = RequestBody::Bytes(Bytes::from(bytes));
666 if !self.headers.contains("content-type") {
667 self.headers.insert("content-type", "application/json")?;
668 }
669 Ok(self)
670 }
671
672 #[must_use]
678 pub fn timeout(mut self, timeout: Timeout) -> Self {
679 self.timeout = Some(timeout);
680 self
681 }
682
683 #[must_use]
692 pub fn redirect_policy(mut self, policy: RedirectPolicy) -> Self {
693 self.redirect = Some(policy);
694 self
695 }
696
697 #[must_use]
701 pub fn auth(mut self, auth: impl Into<AuthScheme>) -> Self {
702 self.auth = Some(auth.into());
703 self.auth_disabled = false;
704 self
705 }
706
707 #[must_use]
712 pub fn without_auth(mut self) -> Self {
713 self.auth_disabled = true;
714 self.auth = None;
715 self
716 }
717
718 #[cfg(feature = "proxy")]
722 #[must_use]
723 pub fn proxy(mut self, proxy: &crate::proxy::Proxy) -> Self {
724 self.proxy_override = ProxyOverride::Override(proxy.config());
725 self
726 }
727
728 #[cfg(feature = "proxy")]
733 #[must_use]
734 pub fn without_proxy(mut self) -> Self {
735 self.proxy_override = ProxyOverride::Direct;
736 self
737 }
738
739 #[must_use]
744 pub fn decompress(mut self, decompress: bool) -> Self {
745 self.decompress = Some(decompress);
746 self
747 }
748
749 #[must_use]
758 pub fn max_decoded_body_size(mut self, max: usize) -> Self {
759 self.max_decoded_body_size = Some(max);
760 self
761 }
762
763 #[must_use]
772 pub fn max_decompression_ratio(mut self, ratio: f64) -> Self {
773 assert!(
774 ratio.is_finite() && ratio > 0.0,
775 "max_decompression_ratio must be finite and positive, got {ratio}"
776 );
777 self.max_decompression_ratio = Some(ratio);
778 self
779 }
780
781 #[cfg(feature = "logical-retry")]
789 #[must_use]
790 pub fn retry(mut self, policy: RetryPolicy) -> Self {
791 self.retry = Some(policy);
792 self.retry_disabled = false;
793 self
794 }
795
796 #[cfg(feature = "logical-retry")]
802 fn disable_retry_policy(&mut self) {
803 self.retry = Some(RetryPolicy::default());
804 }
805
806 #[cfg(not(feature = "logical-retry"))]
812 fn disable_retry_policy(&mut self) {}
813
814 #[must_use]
826 pub fn without_retry(mut self) -> Self {
827 self.retry_disabled = true;
828 self.disable_retry_policy();
829 self
830 }
831
832 #[must_use]
837 pub fn transport_hints(mut self, hints: TransportHints) -> Self {
838 self.transport_hints = hints;
839 self
840 }
841
842 #[cfg(feature = "advanced-routing")]
854 #[must_use]
855 pub fn resolved_addresses<I>(mut self, addresses: I) -> Self
856 where
857 I: IntoIterator<Item = SocketAddr>,
858 {
859 match ResolvedTarget::new(addresses) {
860 Ok(target) => self.transport_hints.resolved_target = Some(target),
861 Err(error) => {
862 if self.error.is_none() {
863 self.error = Some(error);
864 }
865 }
866 }
867 self
868 }
869
870 #[must_use]
879 pub fn proxy_target_addresses<I>(mut self, addresses: I) -> Self
880 where
881 I: IntoIterator<Item = SocketAddr>,
882 {
883 match ResolvedTarget::new(addresses) {
884 Ok(target) => self.proxied_target = Some(target),
885 Err(error) => {
886 if self.error.is_none() {
887 self.error = Some(error);
888 }
889 }
890 }
891 self
892 }
893
894 pub fn build(mut self) -> Result<Request> {
901 if let Some(e) = self.error.take() {
902 return Err(e);
903 }
904 if let Some(target) = &self.transport_hints.resolved_target {
905 crate::http_origin::validate_url_effective_port(
906 crate::http_origin::EffectivePortSubject::ResolvedDestination,
907 &self.url,
908 target.addresses(),
909 )?;
910 }
911 if let Some(target) = &self.proxied_target {
912 crate::http_origin::validate_url_effective_port(
913 crate::http_origin::EffectivePortSubject::ProxiedDestination,
914 &self.url,
915 target.addresses(),
916 )?;
917 }
918 let request_target = self
919 .transport_hints
920 .target
921 .as_deref()
922 .unwrap_or_else(|| self.url.as_str().as_bytes());
923 self.headers
924 .validate_request_size(&self.method, request_target)?;
925 let mut req = Request::new(self.method, self.url);
926 req.headers = self.headers;
927 req.body = self.body;
928 req.timeout = self.timeout;
929 req.set_redirect(self.redirect);
930 req.auth = self.auth;
931 req.auth_disabled = self.auth_disabled;
932 req.decompress = self.decompress;
933 req.max_decoded_body_size = self.max_decoded_body_size;
934 req.max_decompression_ratio = self.max_decompression_ratio;
935 req.proxy_override = self.proxy_override;
936 #[cfg(feature = "logical-retry")]
937 req.set_retry(self.retry);
938 req.set_retry_disabled(self.retry_disabled);
939 req.transport_hints = self.transport_hints;
940 req.proxied_target = self.proxied_target;
941 Ok(req)
942 }
943
944 pub async fn send(self) -> Result<Response> {
950 let client = self.client.clone().ok_or_else(|| {
951 crate::Error::RequestBuild("no client associated with request builder".into())
952 })?;
953 let request = self.build()?;
954 Box::pin(client.send(request)).await
955 }
956
957 pub async fn send_detailed(self) -> std::result::Result<Response, crate::RequestFailure> {
969 let Some(client) = self.client.clone() else {
970 return Err(crate::RequestFailure::from_error(
971 crate::Error::RequestBuild("no client associated with request builder".into()),
972 ));
973 };
974 let request = match self.build() {
975 Ok(request) => request,
976 Err(error) => return Err(crate::RequestFailure::from_error(error)),
977 };
978 client.send_detailed(request).await
979 }
980}
981
982#[cfg(test)]
983mod tests {
984 use proptest::prelude::*;
985
986 use super::{Request, ResolvedTarget};
987 use crate::auth::AuthScheme;
988 #[cfg(feature = "basic-auth")]
989 use crate::auth::BasicAuth;
990 use bytes::Bytes;
991 use std::net::SocketAddr;
992
993 proptest::proptest! {
994 #[test]
995 fn url_parse_round_trip(scheme in "https?", host in "[a-z]{2,10}\\.[a-z]{2,5}", path in "/[a-z]{0,20}") {
996 let url_str = format!("{scheme}://{host}{path}");
997 let parsed = url::Url::parse(&url_str).unwrap();
998 let serialized = parsed.to_string();
999 prop_assert_eq!(url_str, serialized);
1000 }
1001
1002 #[test]
1003 fn query_pairs_round_trip(key in "[a-z]{1,10}", value in "[a-z0-9]{1,20}") {
1004 let mut url = url::Url::parse("http://example.com/").unwrap();
1005 url.query_pairs_mut().append_pair(&key, &value);
1006 let found = url.query_pairs().find(|(k, _)| k == &key).map(|(_, v)| v.into_owned());
1007 prop_assert_eq!(found, Some(value));
1008 }
1009
1010 #[test]
1011 fn url_with_arbitrary_path(path in "/[a-zA-Z0-9._/-]{0,50}") {
1012 let url_str = format!("http://example.com{path}");
1013 let _ = url::Url::parse(&url_str);
1015 }
1016 }
1017
1018 #[test]
1019 fn request_debug_redacts_secrets() {
1020 let url = url::Url::parse("https://example.com/submit?api_key=top-secret-key").unwrap();
1021 let mut req = Request::new(http::Method::POST, url);
1022 req.headers_mut()
1023 .insert("authorization", "Bearer bearer-secret-token")
1024 .unwrap();
1025 req.headers_mut()
1026 .insert("cookie", "session=cookie-secret")
1027 .unwrap();
1028 req.set_body(crate::body::RequestBody::Bytes(Bytes::from(
1029 "password=form-secret",
1030 )));
1031 #[cfg(feature = "basic-auth")]
1032 req.set_auth(Some(AuthScheme::Basic(
1033 BasicAuth::new("user", "auth-secret").unwrap(),
1034 )));
1035 #[cfg(not(feature = "basic-auth"))]
1036 req.set_auth(Some(AuthScheme::bearer("auth-secret").unwrap()));
1037 let debug = format!("{req:?}");
1038 for leaked in [
1039 "top-secret-key",
1040 "bearer-secret-token",
1041 "cookie-secret",
1042 "form-secret",
1043 "auth-secret",
1044 ] {
1045 assert!(
1046 !debug.contains(leaked),
1047 "Request Debug must not leak {leaked:?}: {debug}"
1048 );
1049 }
1050 assert!(debug.contains("example.com"), "keeps the host: {debug}");
1052 assert!(debug.contains("POST"), "keeps the method: {debug}");
1053 }
1054
1055 #[test]
1056 fn resolved_target_rejects_empty_and_hides_addresses_in_debug() {
1057 assert!(ResolvedTarget::new(Vec::<SocketAddr>::new()).is_err());
1058 let target = ResolvedTarget::new(["127.0.0.1:443".parse().unwrap()]).unwrap();
1059 let debug = format!("{target:?}");
1060 assert!(debug.contains("address_count: 1"));
1061 assert!(!debug.contains("127.0.0.1"));
1062 }
1063
1064 #[test]
1065 fn ordinary_request_has_no_failure_context() {
1066 let request = Request::new(
1067 http::Method::GET,
1068 url::Url::parse("http://example.com/").expect("valid URL"),
1069 );
1070 assert!(request.failure_context.is_none());
1071 }
1072
1073 #[cfg(feature = "advanced-routing")]
1074 #[test]
1075 fn request_builder_validates_resolved_target_port() {
1076 let client = crate::client::Client::new();
1077 let request = client
1078 .get("http://example.invalid/")
1079 .unwrap()
1080 .resolved_addresses(["127.0.0.1:80".parse().unwrap()])
1081 .build()
1082 .unwrap();
1083 assert_eq!(
1084 request
1085 .transport_hints()
1086 .resolved_target
1087 .as_ref()
1088 .unwrap()
1089 .addresses()
1090 .len(),
1091 1
1092 );
1093
1094 let error = client
1095 .get("http://example.invalid/")
1096 .unwrap()
1097 .resolved_addresses(["127.0.0.1:443".parse().unwrap()])
1098 .build()
1099 .unwrap_err();
1100 assert_eq!(error.kind(), "invalid_resolved_target");
1101 }
1102
1103 #[cfg(feature = "json")]
1104 #[test]
1105 fn request_json_sets_default_content_type_and_replayable_body() {
1106 let client = crate::client::Client::new();
1107 let request = client
1108 .post("http://example.invalid/")
1109 .unwrap()
1110 .json(&serde_json::json!({"key": "value"}))
1111 .unwrap()
1112 .build()
1113 .unwrap();
1114 assert_eq!(
1115 request.headers().get("content-type").unwrap(),
1116 "application/json"
1117 );
1118 assert!(request.body().is_replayable());
1119
1120 let request = client
1121 .post("http://example.invalid/")
1122 .unwrap()
1123 .header("content-type", "application/vnd.api+json")
1124 .json(&serde_json::json!([1, 2, 3]))
1125 .unwrap()
1126 .build()
1127 .unwrap();
1128 assert_eq!(
1129 request.headers().get("content-type").unwrap(),
1130 "application/vnd.api+json"
1131 );
1132 }
1133}