1use std::fmt;
12use std::future::Future;
13use std::pin::Pin;
14use std::time::Duration;
15
16use bytes::Bytes;
17use http::{HeaderMap, Request, Response};
18
19pub type HttpFuture = Pin<Box<dyn Future<Output = Result<Response<Body>, HttpError>>>>;
24
25pub trait HttpClient {
28 fn send(&self, request: Request<Body>, options: SendOptions) -> HttpFuture;
36}
37
38#[derive(Clone, Debug, PartialEq, Eq)]
44pub struct SendOptions {
45 pub redirects: RedirectPolicy,
47 pub connect_timeout: Option<Duration>,
49 pub first_byte_timeout: Option<Duration>,
52 pub between_bytes_timeout: Option<Duration>,
55}
56
57impl SendOptions {
58 pub const fn new() -> SendOptions {
60 SendOptions {
61 redirects: RedirectPolicy::DEFAULT,
62 connect_timeout: None,
63 first_byte_timeout: None,
64 between_bytes_timeout: None,
65 }
66 }
67
68 pub fn redirects(mut self, redirects: RedirectPolicy) -> SendOptions {
70 self.redirects = redirects;
71 self
72 }
73
74 pub fn connect_timeout(mut self, timeout: Duration) -> SendOptions {
76 self.connect_timeout = Some(timeout);
77 self
78 }
79
80 pub fn first_byte_timeout(mut self, timeout: Duration) -> SendOptions {
82 self.first_byte_timeout = Some(timeout);
83 self
84 }
85
86 pub fn between_bytes_timeout(mut self, timeout: Duration) -> SendOptions {
89 self.between_bytes_timeout = Some(timeout);
90 self
91 }
92}
93
94impl Default for SendOptions {
95 fn default() -> SendOptions {
96 SendOptions::new()
97 }
98}
99
100#[derive(Clone, Copy, Debug, PartialEq, Eq)]
103pub enum RedirectPolicy {
104 Follow {
114 max: usize,
116 },
117 Never,
119}
120
121impl RedirectPolicy {
122 pub const DEFAULT: RedirectPolicy = RedirectPolicy::Follow { max: 5 };
124}
125
126impl Default for RedirectPolicy {
127 fn default() -> RedirectPolicy {
128 RedirectPolicy::DEFAULT
129 }
130}
131
132#[derive(Clone, Debug, PartialEq, Eq)]
140#[non_exhaustive]
141pub enum HttpError {
142 DnsTimeout,
144 DnsError(DnsErrorPayload),
147 DestinationNotFound,
149 DestinationUnavailable,
151 DestinationIpProhibited,
153 DestinationIpUnroutable,
155 ConnectionRefused,
157 ConnectionTerminated,
159 ConnectionTimeout,
161 ConnectionReadTimeout,
163 ConnectionWriteTimeout,
165 ConnectionLimitReached,
167 TlsProtocolError,
169 TlsCertificateError,
171 TlsAlertReceived(TlsAlertReceivedPayload),
174 HttpRequestDenied,
176 HttpRequestLengthRequired,
178 HttpRequestBodySize(Option<u64>),
180 HttpRequestMethodInvalid,
182 HttpRequestUriInvalid,
184 HttpRequestUriTooLong,
186 HttpRequestHeaderSectionSize(Option<u32>),
189 HttpRequestHeaderSize(Option<FieldSizePayload>),
192 HttpRequestTrailerSectionSize(Option<u32>),
195 HttpRequestTrailerSize(FieldSizePayload),
197 HttpResponseIncomplete,
199 HttpResponseHeaderSectionSize(Option<u32>),
202 HttpResponseHeaderSize(FieldSizePayload),
204 HttpResponseBodySize(Option<u64>),
206 HttpResponseTrailerSectionSize(Option<u32>),
209 HttpResponseTrailerSize(FieldSizePayload),
211 HttpResponseTransferCoding(Option<String>),
213 HttpResponseContentCoding(Option<String>),
215 HttpResponseTimeout,
219 HttpUpgradeFailed,
221 HttpProtocolError,
223 LoopDetected,
225 ConfigurationError,
227 Internal(Option<String>),
230 TooManyRedirects,
233}
234
235#[derive(Clone, Debug, PartialEq, Eq)]
237pub struct DnsErrorPayload {
238 pub rcode: Option<String>,
240 pub info_code: Option<u16>,
242}
243
244#[derive(Clone, Debug, PartialEq, Eq)]
246pub struct TlsAlertReceivedPayload {
247 pub alert_id: Option<u8>,
249 pub alert_message: Option<String>,
251}
252
253#[derive(Clone, Debug, PartialEq, Eq)]
255pub struct FieldSizePayload {
256 pub field_name: Option<String>,
258 pub field_size: Option<u32>,
260}
261
262impl fmt::Display for HttpError {
263 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
264 match self {
265 HttpError::DnsTimeout => formatter.write_str("the DNS lookup timed out"),
266 HttpError::DnsError(payload) => write!(
267 formatter,
268 "the DNS lookup failed: {}{}",
269 payload.rcode.as_deref().unwrap_or("no response code"),
270 payload
271 .info_code
272 .map(|code| format!(" (info code {code})"))
273 .unwrap_or_default()
274 ),
275 HttpError::DestinationNotFound => formatter.write_str("the destination was not found"),
276 HttpError::DestinationUnavailable => {
277 formatter.write_str("the destination is unavailable")
278 }
279 HttpError::DestinationIpProhibited => {
280 formatter.write_str("the destination's address is prohibited")
281 }
282 HttpError::DestinationIpUnroutable => {
283 formatter.write_str("the destination's address is unroutable")
284 }
285 HttpError::ConnectionRefused => formatter.write_str("the connection was refused"),
286 HttpError::ConnectionTerminated => formatter.write_str("the connection terminated"),
287 HttpError::ConnectionTimeout => formatter.write_str("the connection timed out"),
288 HttpError::ConnectionReadTimeout => {
289 formatter.write_str("reading from the connection timed out")
290 }
291 HttpError::ConnectionWriteTimeout => {
292 formatter.write_str("writing to the connection timed out")
293 }
294 HttpError::ConnectionLimitReached => {
295 formatter.write_str("the connection limit was reached")
296 }
297 HttpError::TlsProtocolError => formatter.write_str("TLS failed"),
298 HttpError::TlsCertificateError => {
299 formatter.write_str("the TLS certificate was refused")
300 }
301 HttpError::TlsAlertReceived(payload) => write!(
302 formatter,
303 "a TLS alert was received: {}",
304 payload.alert_message.as_deref().unwrap_or("no description")
305 ),
306 HttpError::HttpRequestDenied => formatter.write_str("the request was denied"),
307 HttpError::HttpRequestLengthRequired => {
308 formatter.write_str("the request must say its length")
309 }
310 HttpError::HttpRequestBodySize(limit) => write!(
311 formatter,
312 "the request body is too large{}",
313 limit
314 .map(|limit| format!(" (limit {limit})"))
315 .unwrap_or_default()
316 ),
317 HttpError::HttpRequestMethodInvalid => formatter.write_str("the method is not valid"),
318 HttpError::HttpRequestUriInvalid => formatter.write_str("the URI is not valid"),
319 HttpError::HttpRequestUriTooLong => formatter.write_str("the URI is too long"),
320 HttpError::HttpRequestHeaderSectionSize(limit) => write!(
321 formatter,
322 "the request's header section is too large{}",
323 limit
324 .map(|limit| format!(" (limit {limit})"))
325 .unwrap_or_default()
326 ),
327 HttpError::HttpRequestHeaderSize(field) => write_field_size(
328 formatter,
329 "a request header field is too large",
330 field.as_ref(),
331 ),
332 HttpError::HttpRequestTrailerSectionSize(limit) => write!(
333 formatter,
334 "the request's trailer section is too large{}",
335 limit
336 .map(|limit| format!(" (limit {limit})"))
337 .unwrap_or_default()
338 ),
339 HttpError::HttpRequestTrailerSize(field) => write_field_size(
340 formatter,
341 "a request trailer field is too large",
342 Some(field),
343 ),
344 HttpError::HttpResponseIncomplete => formatter.write_str("the response is incomplete"),
345 HttpError::HttpResponseHeaderSectionSize(limit) => write!(
346 formatter,
347 "the response's header section is too large{}",
348 limit
349 .map(|limit| format!(" (limit {limit})"))
350 .unwrap_or_default()
351 ),
352 HttpError::HttpResponseHeaderSize(field) => write_field_size(
353 formatter,
354 "a response header field is too large",
355 Some(field),
356 ),
357 HttpError::HttpResponseBodySize(limit) => write!(
358 formatter,
359 "the response body is too large{}",
360 limit
361 .map(|limit| format!(" (limit {limit})"))
362 .unwrap_or_default()
363 ),
364 HttpError::HttpResponseTrailerSectionSize(limit) => write!(
365 formatter,
366 "the response's trailer section is too large{}",
367 limit
368 .map(|limit| format!(" (limit {limit})"))
369 .unwrap_or_default()
370 ),
371 HttpError::HttpResponseTrailerSize(field) => write_field_size(
372 formatter,
373 "a response trailer field is too large",
374 Some(field),
375 ),
376 HttpError::HttpResponseTransferCoding(coding) => write!(
377 formatter,
378 "the response's transfer coding is not accepted{}",
379 coding
380 .as_ref()
381 .map(|coding| format!(" ({coding})"))
382 .unwrap_or_default()
383 ),
384 HttpError::HttpResponseContentCoding(coding) => write!(
385 formatter,
386 "the response's content coding is not accepted{}",
387 coding
388 .as_ref()
389 .map(|coding| format!(" ({coding})"))
390 .unwrap_or_default()
391 ),
392 HttpError::HttpResponseTimeout => formatter.write_str("the response timed out"),
393 HttpError::HttpUpgradeFailed => formatter.write_str("the protocol upgrade failed"),
394 HttpError::HttpProtocolError => formatter.write_str("the server spoke invalid HTTP"),
395 HttpError::LoopDetected => formatter.write_str("a proxy detected a loop"),
396 HttpError::ConfigurationError => {
397 formatter.write_str("the HTTP client is not configured for this request")
398 }
399 HttpError::Internal(reason) => match reason {
400 Some(reason) => write!(formatter, "HTTP failed: {reason}"),
401 None => formatter.write_str("HTTP failed"),
402 },
403 HttpError::TooManyRedirects => formatter.write_str("too many redirects"),
404 }
405 }
406}
407
408fn write_field_size(
409 formatter: &mut fmt::Formatter<'_>,
410 what: &str,
411 field: Option<&FieldSizePayload>,
412) -> fmt::Result {
413 match field.and_then(|field| field.field_name.as_deref()) {
414 Some(name) => write!(formatter, "{what}: {name}"),
415 None => formatter.write_str(what),
416 }
417}
418
419impl std::error::Error for HttpError {}
420
421pub trait BodyStream {
426 fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> BodyReadFuture<'a>;
428
429 fn trailers(&mut self) -> BodyTrailersFuture<'_>;
436
437 fn length(&self) -> Option<u64>;
440}
441
442pub type BodyReadFuture<'a> = Pin<Box<dyn Future<Output = Result<usize, HttpError>> + 'a>>;
444
445pub type BodyTrailersFuture<'a> =
447 Pin<Box<dyn Future<Output = Result<Option<HeaderMap>, HttpError>> + 'a>>;
448
449pub type BodyReadAllFuture<'a> = Pin<Box<dyn Future<Output = Result<Vec<u8>, HttpError>> + 'a>>;
451
452pub struct Body(BodyKind);
464
465enum BodyKind {
467 Empty,
469 Bytes { bytes: Bytes, read: usize },
471 Trailered {
474 inner: Box<BodyKind>,
475 trailers: HeaderMap,
476 },
477 Stream(Box<dyn BodyStream>),
479}
480
481impl BodyStream for BodyKind {
482 fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> BodyReadFuture<'a> {
483 match self {
484 BodyKind::Empty => Box::pin(std::future::ready(Ok(0))),
485 BodyKind::Bytes { bytes, read } => {
486 let start = *read;
487 let end = (start + buf.len()).min(bytes.len());
488 buf[..end - start].copy_from_slice(&bytes[start..end]);
489 *read = end;
490 Box::pin(std::future::ready(Ok(end - start)))
491 }
492 BodyKind::Trailered { inner, .. } => inner.read(buf),
493 BodyKind::Stream(stream) => stream.read(buf),
494 }
495 }
496
497 fn trailers(&mut self) -> BodyTrailersFuture<'_> {
498 match self {
499 BodyKind::Empty | BodyKind::Bytes { .. } => Box::pin(std::future::ready(Ok(None))),
500 BodyKind::Trailered { trailers, .. } => {
501 let trailers = trailers.clone();
502 Box::pin(std::future::ready(Ok(Some(trailers))))
503 }
504 BodyKind::Stream(stream) => stream.trailers(),
505 }
506 }
507
508 fn length(&self) -> Option<u64> {
509 match self {
510 BodyKind::Empty => Some(0),
511 BodyKind::Bytes { bytes, .. } => Some(bytes.len() as u64),
512 BodyKind::Trailered { inner, .. } => inner.length(),
513 BodyKind::Stream(stream) => stream.length(),
514 }
515 }
516}
517
518const READ_CHUNK: usize = 64 * 1024;
520
521impl Body {
522 pub fn empty() -> Body {
524 Body(BodyKind::Empty)
525 }
526
527 pub fn from_stream(stream: impl BodyStream + 'static) -> Body {
529 Body(BodyKind::Stream(Box::new(stream)))
530 }
531
532 pub fn with_trailers(self, trailers: HeaderMap) -> Body {
540 Body(BodyKind::Trailered {
541 inner: Box::new(self.0),
542 trailers,
543 })
544 }
545
546 pub fn try_clone(&self) -> Option<Body> {
551 Some(Body(self.0.clone_for_resend()?))
552 }
553
554 pub fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> BodyReadFuture<'a> {
557 self.0.read(buf)
558 }
559
560 pub fn read_all(&mut self) -> BodyReadAllFuture<'_> {
562 match &mut self.0 {
563 BodyKind::Empty => Box::pin(std::future::ready(Ok(Vec::new()))),
564 BodyKind::Bytes { bytes, read } => {
565 let start = *read;
566 *read = bytes.len();
567 Box::pin(std::future::ready(Ok(bytes.slice(start..).to_vec())))
568 }
569 body => Box::pin(read_all(body)),
570 }
571 }
572
573 pub fn trailers(&mut self) -> BodyTrailersFuture<'_> {
581 Box::pin(async move {
582 skip_to_end(&mut self.0).await?;
583 self.0.trailers().await
584 })
585 }
586
587 pub fn length(&self) -> Option<u64> {
590 self.0.length()
591 }
592}
593
594impl From<Vec<u8>> for Body {
595 fn from(bytes: Vec<u8>) -> Body {
596 Body(BodyKind::Bytes {
597 bytes: Bytes::from(bytes),
598 read: 0,
599 })
600 }
601}
602
603impl From<&'static [u8]> for Body {
604 fn from(bytes: &'static [u8]) -> Body {
605 Body(BodyKind::Bytes {
606 bytes: Bytes::from_static(bytes),
607 read: 0,
608 })
609 }
610}
611
612impl Default for Body {
613 fn default() -> Body {
614 Body::empty()
615 }
616}
617
618impl fmt::Debug for Body {
619 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
620 match &self.0 {
621 BodyKind::Empty => formatter.write_str("Body(empty)"),
622 kind => formatter
623 .debug_struct("Body")
624 .field("length", &kind.length())
625 .finish(),
626 }
627 }
628}
629
630impl BodyKind {
631 fn clone_for_resend(&self) -> Option<BodyKind> {
634 match self {
635 BodyKind::Empty => Some(BodyKind::Empty),
636 BodyKind::Bytes { bytes, .. } => Some(BodyKind::Bytes {
637 bytes: bytes.clone(),
638 read: 0,
639 }),
640 BodyKind::Trailered { inner, trailers } => Some(BodyKind::Trailered {
641 inner: Box::new(inner.clone_for_resend()?),
642 trailers: trailers.clone(),
643 }),
644 BodyKind::Stream(_) => None,
645 }
646 }
647}
648
649async fn read_all(stream: &mut dyn BodyStream) -> Result<Vec<u8>, HttpError> {
650 let mut bytes = Vec::with_capacity(usize::try_from(stream.length().unwrap_or(0)).unwrap_or(0));
651 let mut chunk = vec![0; READ_CHUNK];
652 loop {
653 let read = stream.read(&mut chunk).await?;
654 if read == 0 {
655 return Ok(bytes);
656 }
657 bytes.extend_from_slice(&chunk[..read]);
658 }
659}
660
661async fn skip_to_end(stream: &mut dyn BodyStream) -> Result<(), HttpError> {
664 let mut discarded = [0u8; 8192];
665 while stream.read(&mut discarded).await? != 0 {}
666 Ok(())
667}
668
669#[cfg(test)]
670mod tests {
671 use super::*;
672
673 fn now<T>(future: impl Future<Output = T>) -> T {
674 let mut future = std::pin::pin!(future);
675 let mut context = std::task::Context::from_waker(std::task::Waker::noop());
676 loop {
677 if let std::task::Poll::Ready(output) = future.as_mut().poll(&mut context) {
678 return output;
679 }
680 }
681 }
682
683 #[test]
684 fn an_empty_body_reads_nothing() {
685 let mut body = Body::empty();
686 assert_eq!(now(body.read_all()).unwrap(), Vec::<u8>::new());
687 }
688
689 #[test]
690 fn a_body_of_bytes_reads_whole_and_says_its_length() {
691 let mut body = Body::from(b"hello, body".to_vec());
692 assert_eq!(body.length(), Some(11));
693 assert_eq!(now(body.read_all()).unwrap(), b"hello, body");
694 assert_eq!(now(body.trailers()).unwrap(), None, "no trailers came");
695 }
696
697 #[test]
698 fn an_empty_body_carries_no_bytes_where_a_stream_of_unknown_length_carries_some_unknown() {
699 assert_eq!(
700 Body::empty().length(),
701 Some(0),
702 "an empty body is zero bytes"
703 );
704 struct Unknown;
705 impl BodyStream for Unknown {
706 fn read<'a>(&'a mut self, _buf: &'a mut [u8]) -> BodyReadFuture<'a> {
707 Box::pin(std::future::ready(Ok(0)))
708 }
709 fn trailers(&mut self) -> BodyTrailersFuture<'_> {
710 Box::pin(std::future::ready(Ok(None)))
711 }
712 fn length(&self) -> Option<u64> {
713 None
714 }
715 }
716 assert_eq!(Body::from_stream(Unknown).length(), None);
717 }
718
719 struct Pieces(Vec<u8>, usize);
721
722 impl BodyStream for Pieces {
723 fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> BodyReadFuture<'a> {
724 let read = (self.0.len() - self.1).min(buf.len()).min(3);
725 buf[..read].copy_from_slice(&self.0[self.1..self.1 + read]);
726 self.1 += read;
727 Box::pin(std::future::ready(Ok(read)))
728 }
729
730 fn trailers(&mut self) -> BodyTrailersFuture<'_> {
731 let mut trailers = HeaderMap::new();
732 trailers.insert("x-checksum", 7u32.into());
733 Box::pin(std::future::ready(Ok(Some(trailers))))
734 }
735
736 fn length(&self) -> Option<u64> {
737 Some(self.0.len() as u64)
738 }
739 }
740
741 #[test]
742 fn a_streamed_body_is_read_a_piece_at_a_time() {
743 let mut body = Body::from_stream(Pieces(b"streamed body".to_vec(), 0));
744 assert_eq!(now(body.read_all()).unwrap(), b"streamed body");
745 assert_eq!(
746 now(body.trailers()).unwrap().unwrap()["x-checksum"],
747 "7",
748 "the trailers came after the body"
749 );
750 }
751
752 #[test]
753 fn asking_for_the_trailers_again_answers_the_same() {
754 let mut body = Body::from_stream(Pieces(b"streamed body".to_vec(), 0));
755 let first = now(body.trailers()).unwrap().expect("trailers came");
756 let second = now(body.trailers()).unwrap().expect("trailers came again");
757 assert_eq!(first, second, "a second asking answers the same fields");
758 }
759
760 #[test]
761 fn asking_for_the_trailers_reads_the_rest_of_the_body_first() {
762 let mut body = Body::from_stream(Pieces(b"streamed body".to_vec(), 0));
763 let trailers = now(body.trailers())
764 .expect("the body ended")
765 .expect("trailers came");
766 assert_eq!(trailers["x-checksum"], "7");
767 let mut chunk = [0u8; 8];
768 assert_eq!(
769 now(body.read(&mut chunk)).unwrap(),
770 0,
771 "the body was drained to its end before the trailers answered"
772 );
773 }
774
775 #[test]
776 fn a_body_with_trailers_to_send_answers_them_once_its_bytes_are_read() {
777 let mut trailers = HeaderMap::new();
778 trailers.insert("x-checksum", 7u32.into());
779 let mut body = Body::from(b"a body".to_vec()).with_trailers(trailers.clone());
780 assert_eq!(now(body.read_all()).unwrap(), b"a body");
781 assert_eq!(now(body.trailers()).unwrap(), Some(trailers.clone()));
782 assert_eq!(
783 now(body.trailers()).unwrap(),
784 Some(trailers),
785 "asking again answers the same fields"
786 );
787 }
788
789 #[test]
790 fn a_streams_own_trailers_may_be_made_from_its_bytes() {
791 struct Counted {
794 bytes: Vec<u8>,
795 read: usize,
796 }
797 impl BodyStream for Counted {
798 fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> BodyReadFuture<'a> {
799 let read = (self.bytes.len() - self.read).min(buf.len());
800 buf[..read].copy_from_slice(&self.bytes[self.read..self.read + read]);
801 self.read += read;
802 Box::pin(std::future::ready(Ok(read)))
803 }
804 fn trailers(&mut self) -> BodyTrailersFuture<'_> {
805 let mut trailers = HeaderMap::new();
806 trailers.insert("x-length", self.read.into());
807 Box::pin(std::future::ready(Ok(Some(trailers))))
808 }
809 fn length(&self) -> Option<u64> {
810 Some(self.bytes.len() as u64)
811 }
812 }
813 let mut body = Body::from_stream(Counted {
814 bytes: b"count these".to_vec(),
815 read: 0,
816 });
817 let trailers = now(body.trailers()).unwrap().unwrap();
818 assert_eq!(
819 trailers["x-length"], "11",
820 "the trailers answered after the bytes were read, so they can be made from them"
821 );
822 }
823
824 #[test]
825 fn a_body_made_from_bytes_is_sent_again_and_a_stream_is_not() {
826 let body = Body::from(b"resend me".to_vec());
827 let mut again = body.try_clone().expect("bytes can be sent again");
828 assert_eq!(again.length(), body.length());
829 assert_eq!(now(again.read_all()).unwrap(), b"resend me");
830 assert_eq!(
831 now(again.trailers()).unwrap(),
832 None,
833 "a body without trailers clones without them"
834 );
835
836 let streamed = Body::from_stream(Pieces(b"streamed".to_vec(), 0));
837 assert!(
838 streamed.try_clone().is_none(),
839 "a stream's bytes are gone once they are read"
840 );
841
842 let mut trailers = HeaderMap::new();
843 trailers.insert("x-checksum", 7u32.into());
844 let wrapped = Body::from(b"a body".to_vec()).with_trailers(trailers.clone());
845 assert!(
846 wrapped.try_clone().is_some(),
847 "bytes and the fixed trailers they send go again together"
848 );
849 }
850
851 #[test]
852 fn a_body_with_fixed_trailers_is_sent_again_with_them() {
853 let mut trailers = HeaderMap::new();
854 trailers.insert("x-checksum", 7u32.into());
855 let body = Body::from(b"a body".to_vec()).with_trailers(trailers.clone());
856 let mut again = body
857 .try_clone()
858 .expect("a body of bytes and fixed trailers is sent again");
859 assert_eq!(now(again.read_all()).unwrap(), b"a body");
860 assert_eq!(now(again.trailers()).unwrap(), Some(trailers.clone()));
861 let mut third = body.try_clone().unwrap();
862 assert_eq!(
863 now(third.trailers()).unwrap(),
864 Some(trailers),
865 "each clone answers the same fields"
866 );
867 }
868
869 #[test]
870 fn trailers_given_to_a_stream_replace_its_own() {
871 let mut trailers = HeaderMap::new();
872 trailers.insert("x-other", 1u32.into());
873 let mut body =
874 Body::from_stream(Pieces(b"streamed body".to_vec(), 0)).with_trailers(trailers.clone());
875 assert_eq!(
876 now(body.trailers()).unwrap(),
877 Some(trailers),
878 "the given fields are the ones sent"
879 );
880 assert!(
881 body.try_clone().is_none(),
882 "a stream's bytes are gone once they are read"
883 );
884 }
885
886 #[test]
887 fn an_empty_body_is_sent_again_with_nothing() {
888 let empty = Body::empty();
889 let mut again = empty.try_clone().expect("nothing to lose");
890 assert_eq!(
891 again.length(),
892 Some(0),
893 "an empty body carries no bytes, where a stream of unknown length says nothing"
894 );
895 assert_eq!(now(again.read_all()).unwrap(), Vec::<u8>::new());
896 }
897
898 #[test]
899 fn send_options_default_to_five_redirects_and_no_timeouts() {
900 let options = SendOptions::default();
901 assert_eq!(options.redirects, RedirectPolicy::Follow { max: 5 });
902 assert_eq!(options.connect_timeout, None);
903 assert_eq!(options.first_byte_timeout, None);
904 assert_eq!(options.between_bytes_timeout, None);
905 assert_eq!(RedirectPolicy::default(), options.redirects);
906 let options = SendOptions::new()
907 .redirects(RedirectPolicy::Never)
908 .connect_timeout(Duration::from_secs(1))
909 .first_byte_timeout(Duration::from_secs(2))
910 .between_bytes_timeout(Duration::from_secs(3));
911 assert_eq!(options.redirects, RedirectPolicy::Never);
912 assert_eq!(options.connect_timeout, Some(Duration::from_secs(1)));
913 assert_eq!(options.first_byte_timeout, Some(Duration::from_secs(2)));
914 assert_eq!(options.between_bytes_timeout, Some(Duration::from_secs(3)));
915 }
916
917 #[test]
918 fn every_error_says_what_went_wrong() {
919 assert_eq!(
920 HttpError::TooManyRedirects.to_string(),
921 "too many redirects"
922 );
923 assert_eq!(
924 HttpError::ConnectionTimeout.to_string(),
925 "the connection timed out"
926 );
927 assert_eq!(
928 HttpError::DnsError(DnsErrorPayload {
929 rcode: Some("NXDOMAIN".to_owned()),
930 info_code: None,
931 })
932 .to_string(),
933 "the DNS lookup failed: NXDOMAIN"
934 );
935 assert_eq!(
936 HttpError::Internal(Some("CORS".to_owned())).to_string(),
937 "HTTP failed: CORS"
938 );
939 }
940}