wreq-rb 0.6.2 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. checksums.yaml +4 -4
  2. data/Cargo.lock +47 -21
  3. data/README.md +36 -0
  4. data/ext/wreq_rb/Cargo.toml +4 -4
  5. data/ext/wreq_rb/extconf.rb +10 -3
  6. data/ext/wreq_rb/src/client.rs +41 -0
  7. data/lib/wreq-rb/version.rb +1 -1
  8. data/patches/0002-add-preconnect.patch +266 -0
  9. data/vendor/wreq/Cargo.toml +11 -7
  10. data/vendor/wreq/bench/support/server.rs +2 -0
  11. data/vendor/wreq/src/client/layer/redirect/future.rs +1 -1
  12. data/vendor/wreq/src/client/layer/timeout/body.rs +16 -18
  13. data/vendor/wreq/src/client/layer/timeout/future.rs +2 -2
  14. data/vendor/wreq/src/client/request.rs +27 -15
  15. data/vendor/wreq/src/client/ws.rs +4 -3
  16. data/vendor/wreq/src/client.rs +4 -24
  17. data/vendor/wreq/src/conn/net/tcp.rs +16 -66
  18. data/vendor/wreq/src/conn/proxy/socks.rs +11 -1
  19. data/vendor/wreq/src/conn/proxy/tunnel.rs +14 -11
  20. data/vendor/wreq/src/conn/timeout.rs +1 -1
  21. data/vendor/wreq/src/cookie/jar.rs +170 -36
  22. data/vendor/wreq/src/cookie/store.rs +66 -4
  23. data/vendor/wreq/src/cookie.rs +48 -17
  24. data/vendor/wreq/src/dns.rs +2 -4
  25. data/vendor/wreq/src/error.rs +100 -0
  26. data/vendor/wreq/src/ext.rs +0 -49
  27. data/vendor/wreq/src/lib.rs +2 -0
  28. data/vendor/wreq/src/rt.rs +1 -14
  29. data/vendor/wreq/src/tls/trust/store.rs +35 -2
  30. data/vendor/wreq/tests/badssl.rs +3 -239
  31. data/vendor/wreq/tests/cert_store.rs +168 -0
  32. data/vendor/wreq/tests/client.rs +89 -0
  33. data/vendor/wreq/tests/proxy.rs +149 -3
  34. data/vendor/wreq/tests/redirect.rs +35 -0
  35. data/vendor/wreq/tests/support/tls_cert.rs +56 -0
  36. data/vendor/wreq/tests/timeouts.rs +25 -0
  37. data/vendor/wreq/tests/unix_socket.rs +109 -81
  38. data/vendor/wreq/tests/websocket.rs +40 -0
  39. metadata +9 -6
  40. data/vendor/wreq/examples/rt.rs +0 -23
@@ -140,7 +140,7 @@ where
140
140
  let Some(location) = res
141
141
  .headers()
142
142
  .get(LOCATION)
143
- .and_then(|loc| loc.to_str().ok())
143
+ .and_then(|loc| std::str::from_utf8(loc.as_bytes()).ok())
144
144
  .and_then(|loc| resolve_uri(loc, request.uri()))
145
145
  else {
146
146
  return Poll::Ready(Ok(res));
@@ -54,13 +54,14 @@ pin_project! {
54
54
  pin_project! {
55
55
  /// A body wrapper that enforces a timeout for each read operation.
56
56
  ///
57
- /// The timeout resets after every successful read. If a single read
58
- /// takes longer than the specified duration, an error is returned.
57
+ /// The deadline starts when a frame poll begins and is disarmed once it completes,
58
+ /// so time spent between reads is not counted.
59
59
  pub struct ReadTimeoutBody<B> {
60
60
  #[pin]
61
61
  body: B,
62
62
  #[pin]
63
63
  sleep: Option<Pin<Box<dyn Sleep>>>,
64
+ armed: bool,
64
65
  timeout: Duration,
65
66
  timer: Timer,
66
67
  }
@@ -83,6 +84,7 @@ impl<B> TimeoutBody<B> {
83
84
  body: ReadTimeoutBody {
84
85
  body,
85
86
  sleep: None,
87
+ armed: false,
86
88
  timeout: read_timeout,
87
89
  timer,
88
90
  },
@@ -95,6 +97,7 @@ impl<B> TimeoutBody<B> {
95
97
  body: ReadTimeoutBody {
96
98
  timeout,
97
99
  sleep: None,
100
+ armed: false,
98
101
  body,
99
102
  timer,
100
103
  },
@@ -208,10 +211,14 @@ where
208
211
  ) -> Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> {
209
212
  let mut this = self.project();
210
213
 
211
- // Start the timeout on the first poll.
212
- if this.sleep.is_none() {
214
+ // Arm the deadline when a new frame poll begins, reusing the sleep after the first read.
215
+ if !*this.armed {
213
216
  let deadline = this.timer.now() + *this.timeout;
214
- this.sleep.set(Some(this.timer.sleep_until(deadline)));
217
+ match this.sleep.as_mut().as_pin_mut() {
218
+ Some(sleep) => this.timer.reset(sleep.get_mut(), deadline),
219
+ None => this.sleep.set(Some(this.timer.sleep_until(deadline))),
220
+ }
221
+ *this.armed = true;
215
222
  }
216
223
 
217
224
  // Error if the timeout has expired.
@@ -221,19 +228,10 @@ where
221
228
  return Poll::Ready(Some(Err(Error::body(TimedOut).into())));
222
229
  }
223
230
 
224
- // Poll the actual body
225
- match ready!(this.body.poll_frame(cx)) {
226
- Some(Ok(frame)) => {
227
- // Reuse the sleep to avoid allocating and registering a new timer for every frame.
228
- if let Some(sleep) = this.sleep.as_mut().as_pin_mut() {
229
- let deadline = this.timer.now() + *this.timeout;
230
- this.timer.reset(sleep.get_mut(), deadline);
231
- }
232
- Poll::Ready(Some(Ok(frame)))
233
- }
234
- Some(Err(err)) => Poll::Ready(Some(Err(err.into()))),
235
- None => Poll::Ready(None),
236
- }
231
+ // A completed frame poll disarms the deadline until the next read starts.
232
+ let frame = ready!(this.body.poll_frame(cx));
233
+ *this.armed = false;
234
+ Poll::Ready(frame.map(|res| res.map_err(Into::into)))
237
235
  }
238
236
 
239
237
  #[inline(always)]
@@ -45,8 +45,8 @@ where
45
45
  return Poll::Ready(Err(Error::request(TimedOut).into()));
46
46
  }
47
47
 
48
- // Before headers arrive, the read timer limits that wait. The body starts
49
- // and resets its own read timer after each successful frame.
48
+ // Before headers arrive, the read timer limits that wait. The body rearms
49
+ // the timer when each frame read begins.
50
50
  if let Some(timeout) = this.read_timeout_fut.as_mut()
51
51
  && timeout.as_mut().poll(cx).is_ready()
52
52
  {
@@ -374,9 +374,9 @@ impl RequestBuilder {
374
374
 
375
375
  /// Enables a read timeout.
376
376
  ///
377
- /// The read timeout is applied from when the response body starts being read
378
- /// until the response body has finished. It affects only this request and
379
- /// overrides the read timeout configured using `ClientBuilder::read_timeout()`.
377
+ /// The timeout applies while waiting for response headers and reading each body frame. Time
378
+ /// spent by the caller between body reads is not counted. It affects only this request and
379
+ /// overrides `ClientBuilder::read_timeout()`.
380
380
  pub fn read_timeout(mut self, timeout: Duration) -> RequestBuilder {
381
381
  if let Ok(ref mut req) = self.request {
382
382
  req.config_mut::<TimeoutOptions>()
@@ -394,6 +394,7 @@ impl RequestBuilder {
394
394
  /// overwritten if the same key is used. The key will simply show up
395
395
  /// twice in the query string.
396
396
  /// Calling `.query(&[("foo", "a"), ("foo", "b")])` gives `"foo=a&foo=b"`.
397
+ /// Existing URI components and query encoding are preserved.
397
398
  ///
398
399
  /// # Note
399
400
  /// This method does not support serializing a single key-value
@@ -402,22 +403,33 @@ impl RequestBuilder {
402
403
  /// and maps into a key-value pair.
403
404
  ///
404
405
  /// # Errors
405
- /// This method will fail if the object you provide cannot be serialized
406
- /// into a query string.
406
+ /// This method fails if the parameters cannot be serialized or the
407
+ /// resulting URI is invalid.
407
408
  #[cfg(feature = "query")]
408
409
  #[cfg_attr(docsrs, doc(cfg(feature = "query")))]
409
410
  pub fn query<T: Serialize + ?Sized>(mut self, query: &T) -> RequestBuilder {
410
- let mut error = None;
411
- if let Ok(ref mut req) = self.request {
412
- match serde_html_form::to_string(query) {
413
- Ok(serializer) => {
411
+ if let Ok(ref mut req) = self.request
412
+ && let Err(err) = serde_html_form::to_string(query)
413
+ .map_err(Error::builder)
414
+ .and_then(|query| {
415
+ if query.is_empty() {
416
+ return Ok(());
417
+ }
418
+
414
419
  let uri = req.uri_mut();
415
- uri.set_query(serializer);
416
- }
417
- Err(err) => error = Some(Error::builder(err)),
418
- }
419
- }
420
- if let Some(err) = error {
420
+ let path = uri.path();
421
+ let path_and_query = match uri.query().filter(|query| !query.is_empty()) {
422
+ Some(existing) => format!("{path}?{existing}&{query}"),
423
+ None => format!("{path}?{query}"),
424
+ };
425
+ let path_and_query = http::uri::PathAndQuery::try_from(path_and_query)
426
+ .map_err(Error::builder)?;
427
+ let mut parts = uri.clone().into_parts();
428
+ parts.path_and_query = Some(path_and_query);
429
+ *uri = Uri::from_parts(parts).map_err(Error::builder)?;
430
+ Ok(())
431
+ })
432
+ {
421
433
  self.request = Err(err);
422
434
  }
423
435
  self
@@ -275,6 +275,7 @@ impl WebSocketRequestBuilder {
275
275
  /// overwritten if the same key is used. The key will simply show up
276
276
  /// twice in the query string.
277
277
  /// Calling `.query(&[("foo", "a"), ("foo", "b")])` gives `"foo=a&foo=b"`.
278
+ /// Existing URI components and query encoding are preserved.
278
279
  ///
279
280
  /// # Note
280
281
  /// This method does not support serializing a single key-value
@@ -283,8 +284,8 @@ impl WebSocketRequestBuilder {
283
284
  /// and maps into a key-value pair.
284
285
  ///
285
286
  /// # Errors
286
- /// This method will fail if the object you provide cannot be serialized
287
- /// into a query string.
287
+ /// This method fails if the parameters cannot be serialized or the
288
+ /// resulting URI is invalid.
288
289
  #[inline]
289
290
  #[cfg(feature = "query")]
290
291
  #[cfg_attr(docsrs, doc(cfg(feature = "query")))]
@@ -754,7 +755,7 @@ impl Stream for WebSocket {
754
755
  return Poll::Ready(Some(Ok(msg)));
755
756
  }
756
757
  }
757
- Some(Err(err)) => return Poll::Ready(Some(Err(Error::body(err)))),
758
+ Some(Err(err)) => return Poll::Ready(Some(Err(Error::websocket(err)))),
758
759
  None => return Poll::Ready(None),
759
760
  }
760
761
  }
@@ -73,7 +73,7 @@ use crate::{
73
73
  proxy::Matcher as ProxyMatcher,
74
74
  redirect::{self, FollowRedirectPolicy},
75
75
  retry,
76
- rt::{BoxSendFuture, Executor, Timer},
76
+ rt::{Executor, Timer},
77
77
  tls::{
78
78
  AlpnProtocol, TlsOptions, TlsVersion,
79
79
  keylog::KeyLog,
@@ -641,28 +641,6 @@ impl ClientBuilder {
641
641
  Ok(Client(Arc::new(client)))
642
642
  }
643
643
 
644
- // Runtime options
645
-
646
- /// Provide a timer to be used for timeouts and intervals in client.
647
- #[inline]
648
- pub fn timer<M>(mut self, timer: M) -> Self
649
- where
650
- M: wreq_proto::rt::Timer + Send + Sync + 'static,
651
- {
652
- self.config.timer = Timer::new(timer);
653
- self
654
- }
655
-
656
- /// Provide an executor to run background tasks in the client.
657
- #[inline]
658
- pub fn executor<E>(mut self, executor: E) -> Self
659
- where
660
- E: wreq_proto::rt::Executor<BoxSendFuture> + Send + Sync + 'static,
661
- {
662
- self.config.executor = Executor::new(executor);
663
- self
664
- }
665
-
666
644
  // Higher-level options
667
645
 
668
646
  /// Sets the `User-Agent` header to be used by this client.
@@ -1034,7 +1012,9 @@ impl ClientBuilder {
1034
1012
  self
1035
1013
  }
1036
1014
 
1037
- /// Set a timeout for only the read phase of a `Client`.
1015
+ /// Sets a timeout for waiting for response headers and reading each body frame.
1016
+ ///
1017
+ /// Time spent by the caller between body reads is not counted.
1038
1018
  ///
1039
1019
  /// Default is `None`.
1040
1020
  #[inline]
@@ -716,59 +716,26 @@ pub(crate) struct TcpOptions {
716
716
  #[derive(Default, Debug, Clone, Copy)]
717
717
  pub(crate) struct TcpKeepaliveOptions {
718
718
  pub time: Option<Duration>,
719
- #[cfg(any(
720
- target_os = "android",
721
- target_os = "dragonfly",
722
- target_os = "freebsd",
723
- target_os = "fuchsia",
724
- target_os = "illumos",
725
- target_os = "ios",
726
- target_os = "visionos",
727
- target_os = "linux",
728
- target_os = "macos",
729
- target_os = "netbsd",
730
- target_os = "tvos",
731
- target_os = "watchos",
732
- target_os = "windows",
733
- target_os = "cygwin",
734
- ))]
735
719
  pub interval: Option<Duration>,
736
- #[cfg(any(
737
- target_os = "android",
738
- target_os = "dragonfly",
739
- target_os = "freebsd",
740
- target_os = "fuchsia",
741
- target_os = "illumos",
742
- target_os = "ios",
743
- target_os = "visionos",
744
- target_os = "linux",
745
- target_os = "macos",
746
- target_os = "netbsd",
747
- target_os = "tvos",
748
- target_os = "watchos",
749
- target_os = "cygwin",
750
- target_os = "windows",
751
- ))]
752
720
  pub retries: Option<u32>,
753
721
  }
754
722
 
755
723
  impl TcpKeepaliveOptions {
756
724
  /// Converts into a `socket2::TcpKeealive` if there is any keep alive configuration.
757
725
  pub(crate) fn into_tcpkeepalive(self) -> Option<TcpKeepalive> {
726
+ let Self {
727
+ time,
728
+ interval: _interval,
729
+ retries: _retries,
730
+ } = self;
731
+
758
732
  let mut dirty = false;
759
733
  let mut ka = TcpKeepalive::new();
760
- if let Some(time) = self.time {
734
+ if let Some(time) = time {
761
735
  ka = ka.with_time(time);
762
736
  dirty = true
763
737
  }
764
738
 
765
- // Set the value of the `TCP_KEEPINTVL` option. On Windows, this sets the
766
- // value of the `tcp_keepalive` struct's `keepaliveinterval` field.
767
- //
768
- // Sets the time interval between TCP keepalive probes.
769
- //
770
- // Some platforms specify this value in seconds, so sub-second
771
- // specifications may be omitted.
772
739
  #[cfg(any(
773
740
  target_os = "android",
774
741
  target_os = "dragonfly",
@@ -786,36 +753,19 @@ impl TcpKeepaliveOptions {
786
753
  target_os = "cygwin",
787
754
  ))]
788
755
  {
789
- if let Some(interval) = self.interval {
756
+ // Set the time between TCP keepalive probes. Some platforms specify
757
+ // this value in seconds, so sub-second values may be omitted.
758
+ if let Some(interval) = _interval {
790
759
  dirty = true;
791
760
  ka = ka.with_interval(interval)
792
761
  };
793
- }
794
762
 
795
- // Set the value of the `TCP_KEEPCNT` option.
796
- //
797
- // Set the maximum number of TCP keepalive probes that will be sent before
798
- // dropping a connection, if TCP keepalive is enabled on this socket.
799
- #[cfg(any(
800
- target_os = "android",
801
- target_os = "dragonfly",
802
- target_os = "freebsd",
803
- target_os = "fuchsia",
804
- target_os = "illumos",
805
- target_os = "ios",
806
- target_os = "visionos",
807
- target_os = "linux",
808
- target_os = "macos",
809
- target_os = "netbsd",
810
- target_os = "tvos",
811
- target_os = "watchos",
812
- target_os = "cygwin",
813
- target_os = "windows",
814
- ))]
815
- if let Some(retries) = self.retries {
816
- dirty = true;
817
- ka = ka.with_retries(retries)
818
- };
763
+ // Set how many unanswered probes are sent before dropping the connection.
764
+ if let Some(retries) = _retries {
765
+ dirty = true;
766
+ ka = ka.with_retries(retries)
767
+ };
768
+ }
819
769
 
820
770
  if dirty { Some(ka) } else { None }
821
771
  }
@@ -52,7 +52,17 @@ impl std::fmt::Display for SocksError {
52
52
  }
53
53
  }
54
54
 
55
- impl std::error::Error for SocksError {}
55
+ impl std::error::Error for SocksError {
56
+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
57
+ match self {
58
+ Self::ConnectFailed(e) | Self::DnsResolveFailure(e) => Some(&**e),
59
+ Self::Socks(e) => Some(e),
60
+ Self::Io(e) => Some(e),
61
+ Self::Utf8(e) => Some(e),
62
+ Self::DnsFailure | Self::MissingHost => None,
63
+ }
64
+ }
65
+ }
56
66
 
57
67
  impl From<std::io::Error> for SocksError {
58
68
  fn from(err: std::io::Error) -> Self {
@@ -38,7 +38,7 @@ pub enum TunnelError {
38
38
  MissingHost,
39
39
  ProxyAuthRequired,
40
40
  TunnelUnexpectedEof,
41
- TunnelUnsuccessful,
41
+ TunnelUnsuccessful(Option<u16>),
42
42
  }
43
43
 
44
44
  impl<C> TunnelConnector<C> {
@@ -191,7 +191,7 @@ where
191
191
  httparse::Status::Complete(_) => match res.code {
192
192
  Some(200) => return Ok(conn),
193
193
  Some(407) => return Err(TunnelError::ProxyAuthRequired),
194
- Some(_) | None => return Err(TunnelError::TunnelUnsuccessful),
194
+ status => return Err(TunnelError::TunnelUnsuccessful(status)),
195
195
  },
196
196
  }
197
197
  }
@@ -201,15 +201,18 @@ impl std::fmt::Display for TunnelError {
201
201
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202
202
  f.write_str("tunnel error: ")?;
203
203
 
204
- f.write_str(match self {
205
- TunnelError::MissingHost => "missing destination host",
206
- TunnelError::ProxyAuthRequired => "proxy authorization required",
207
- TunnelError::Parse(_) => "invalid proxy response",
208
- TunnelError::TunnelUnexpectedEof => "unexpected end of file",
209
- TunnelError::TunnelUnsuccessful => "unsuccessful",
210
- TunnelError::ConnectFailed(_) => "failed to create underlying connection",
211
- TunnelError::Io(_) => "io error establishing tunnel",
212
- })
204
+ match self {
205
+ TunnelError::MissingHost => f.write_str("missing destination host"),
206
+ TunnelError::ProxyAuthRequired => f.write_str("proxy authorization required"),
207
+ TunnelError::Parse(_) => f.write_str("invalid proxy response"),
208
+ TunnelError::TunnelUnexpectedEof => f.write_str("unexpected end of file"),
209
+ TunnelError::TunnelUnsuccessful(Some(status)) => {
210
+ write!(f, "unsuccessful (status {status})")
211
+ }
212
+ TunnelError::TunnelUnsuccessful(None) => f.write_str("unsuccessful"),
213
+ TunnelError::ConnectFailed(_) => f.write_str("failed to create underlying connection"),
214
+ TunnelError::Io(_) => f.write_str("io error establishing tunnel"),
215
+ }
213
216
  }
214
217
  }
215
218
 
@@ -155,7 +155,7 @@ mod tests {
155
155
  TimeoutLayer::new(Timer::new(ReadyTimer), Some(Duration::from_millis(50)))
156
156
  .layer(tower::service_fn(|()| pending::<Result<(), BoxError>>()));
157
157
 
158
- let mut future = Box::pin(service.call(()));
158
+ let mut future = std::pin::pin!(service.call(()));
159
159
  let mut cx = Context::from_waker(Waker::noop());
160
160
  let Poll::Ready(Err(error)) = future.as_mut().poll(&mut cx) else {
161
161
  panic!("connect timeout did not complete");