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
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ce3d1d61f00a9a6585dcf3dedf9c32efe8bb25d99ab3ce332deee5de6c84ee4f
4
- data.tar.gz: 97e22c094b0d0f28db1c0e65f94eb82eeca2f55bb1a96fa8e7f706d17a008df3
3
+ metadata.gz: cde4314d5b59d330769e0e2b8032696b5eafc374954e0c1b63de09e69d26ca4a
4
+ data.tar.gz: 6914fd3852c01df30409b0235c8f57768b0643b9649f1f7ed5e60a82c5ad94ef
5
5
  SHA512:
6
- metadata.gz: 7ce21633e4394d4f4d6a3a71ad38708d98e9809f3d0910bf5e0f947adb2bdabbb59481bcd5a4c9096114fc74ffa035c2519e4460733a61c9a810220be3c6b7a3
7
- data.tar.gz: 643d9f5411aaa343c165665a9a1de939102d2abe7396b5c07ff16e18456a0c5fce885ffe0118c57491ce850227117a5d5248ebda5d083c0b5c903020b0458978
6
+ metadata.gz: 27eb9e5818a595babf019c2fb932f32fe6396fcb9c526927e289e51496523b6249a4a558956e745cab11f09230e530a15618f3cb145cd84df19d9204d027d31a
7
+ data.tar.gz: 19fe676356523bcd206da208a6c06ea6599f69a220b77a545dc5266b9e11160f396e4ed4d5dc29ee9a2a1f158f946a68a81726bbfd6701dd70ba360d5d2696bd
data/Cargo.lock CHANGED
@@ -41,12 +41,6 @@ dependencies = [
41
41
  "cc",
42
42
  ]
43
43
 
44
- [[package]]
45
- name = "allocator-api2"
46
- version = "0.2.21"
47
- source = "registry+https://github.com/rust-lang/crates.io-index"
48
- checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
49
-
50
44
  [[package]]
51
45
  name = "anes"
52
46
  version = "0.1.6"
@@ -647,8 +641,8 @@ dependencies = [
647
641
  "compression-core",
648
642
  "flate2",
649
643
  "memchr",
650
- "zstd",
651
- "zstd-safe",
644
+ "zstd 0.13.3",
645
+ "zstd-safe 7.2.4",
652
646
  ]
653
647
 
654
648
  [[package]]
@@ -1302,8 +1296,6 @@ version = "0.17.1"
1302
1296
  source = "registry+https://github.com/rust-lang/crates.io-index"
1303
1297
  checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
1304
1298
  dependencies = [
1305
- "allocator-api2",
1306
- "equivalent",
1307
1299
  "foldhash 0.2.0",
1308
1300
  ]
1309
1301
 
@@ -1859,9 +1851,9 @@ dependencies = [
1859
1851
 
1860
1852
  [[package]]
1861
1853
  name = "lru"
1862
- version = "0.18.0"
1854
+ version = "0.19.2"
1863
1855
  source = "registry+https://github.com/rust-lang/crates.io-index"
1864
- checksum = "8a860605968fce16869fd239cf4237a82f3ac470723415db603b0e8b6c8d4fb9"
1856
+ checksum = "d4e2a1b977b42ee8b53a2a4adbd1183431c493f1d1960b7ccd893e2f0b9407ba"
1865
1857
  dependencies = [
1866
1858
  "hashbrown 0.17.1",
1867
1859
  ]
@@ -2261,6 +2253,21 @@ dependencies = [
2261
2253
  "unicode-ident",
2262
2254
  ]
2263
2255
 
2256
+ [[package]]
2257
+ name = "psl"
2258
+ version = "2.1.264"
2259
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2260
+ checksum = "8782e35cade255f17d5ad527b899ea5b4e6bef29dcdc3502965a7d8d2f3fc3f5"
2261
+ dependencies = [
2262
+ "psl-types",
2263
+ ]
2264
+
2265
+ [[package]]
2266
+ name = "psl-types"
2267
+ version = "2.0.11"
2268
+ source = "registry+https://github.com/rust-lang/crates.io-index"
2269
+ checksum = "33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac"
2270
+
2264
2271
  [[package]]
2265
2272
  name = "quinn"
2266
2273
  version = "0.11.9"
@@ -4103,7 +4110,7 @@ dependencies = [
4103
4110
 
4104
4111
  [[package]]
4105
4112
  name = "wreq"
4106
- version = "0.16.1"
4113
+ version = "0.16.5"
4107
4114
  dependencies = [
4108
4115
  "brotli",
4109
4116
  "btls",
@@ -4134,6 +4141,7 @@ dependencies = [
4134
4141
  "percent-encoding",
4135
4142
  "pin-project-lite",
4136
4143
  "pretty_env_logger",
4144
+ "psl",
4137
4145
  "reqwest",
4138
4146
  "serde",
4139
4147
  "serde_html_form",
@@ -4157,7 +4165,7 @@ dependencies = [
4157
4165
  "windows-registry",
4158
4166
  "wreq-proto",
4159
4167
  "wreq-rt",
4160
- "zstd",
4168
+ "zstd 0.13.3",
4161
4169
  ]
4162
4170
 
4163
4171
  [[package]]
@@ -4197,21 +4205,21 @@ dependencies = [
4197
4205
 
4198
4206
  [[package]]
4199
4207
  name = "wreq-util"
4200
- version = "0.2.0"
4208
+ version = "0.2.1"
4201
4209
  source = "registry+https://github.com/rust-lang/crates.io-index"
4202
- checksum = "833a5528fd9346f1f61a351104878be96024b5905f39774fc66909502da3acd5"
4210
+ checksum = "636ad931b75aa030cc320899507ce8d5e44f1d9b3b44a81d2e1a225b0d4aad3b"
4203
4211
  dependencies = [
4204
4212
  "brotli",
4205
4213
  "flate2",
4206
4214
  "serde",
4207
4215
  "typed-builder",
4208
4216
  "wreq",
4209
- "zstd",
4217
+ "zstd 0.14.5",
4210
4218
  ]
4211
4219
 
4212
4220
  [[package]]
4213
4221
  name = "wreq_rb"
4214
- version = "0.6.2"
4222
+ version = "0.7.1"
4215
4223
  dependencies = [
4216
4224
  "bytes",
4217
4225
  "http",
@@ -4345,7 +4353,16 @@ version = "0.13.3"
4345
4353
  source = "registry+https://github.com/rust-lang/crates.io-index"
4346
4354
  checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a"
4347
4355
  dependencies = [
4348
- "zstd-safe",
4356
+ "zstd-safe 7.2.4",
4357
+ ]
4358
+
4359
+ [[package]]
4360
+ name = "zstd"
4361
+ version = "0.14.5"
4362
+ source = "registry+https://github.com/rust-lang/crates.io-index"
4363
+ checksum = "465cb081cac3a28a84ef547702dba1fe0f4a9f22e4e57a0b675ceee028c2af80"
4364
+ dependencies = [
4365
+ "zstd-safe 8.4.0",
4349
4366
  ]
4350
4367
 
4351
4368
  [[package]]
@@ -4357,11 +4374,20 @@ dependencies = [
4357
4374
  "zstd-sys",
4358
4375
  ]
4359
4376
 
4377
+ [[package]]
4378
+ name = "zstd-safe"
4379
+ version = "8.4.0"
4380
+ source = "registry+https://github.com/rust-lang/crates.io-index"
4381
+ checksum = "9b09bddd92c53b91833f4df03e0ea07e02d8367cfcd15a3b9acda94fc273f793"
4382
+ dependencies = [
4383
+ "zstd-sys",
4384
+ ]
4385
+
4360
4386
  [[package]]
4361
4387
  name = "zstd-sys"
4362
- version = "2.0.16+zstd.1.5.7"
4388
+ version = "2.2.0+zstd.1.6.0"
4363
4389
  source = "registry+https://github.com/rust-lang/crates.io-index"
4364
- checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748"
4390
+ checksum = "c3f4089cda6dda4dc43c43dd9f8964140064fd2f752f3da46c3a483c3c175160"
4365
4391
  dependencies = [
4366
4392
  "cc",
4367
4393
  "pkg-config",
data/README.md CHANGED
@@ -142,6 +142,33 @@ client.request_batch([
142
142
  - `cancel` and Ruby thread interrupts abort the whole batch, raising
143
143
  `Wreq::Error` with `"request interrupted"`.
144
144
 
145
+ ### Preconnecting
146
+
147
+ `Wreq::Client#preconnect` opens a connection to a URL's origin ahead of time —
148
+ DNS, TCP, proxy tunnel and TLS handshake — without sending a request. The
149
+ connection is kept idle in the client's pool, so the next request to the same
150
+ origin skips connection setup.
151
+
152
+ ```ruby
153
+ client = Wreq::Client.new
154
+
155
+ client.preconnect("https://api.example.com") # returns nil, raises Wreq::Error on failure
156
+ # ... later ...
157
+ client.get("https://api.example.com/data") # reuses the warm connection
158
+ ```
159
+
160
+ - Connection-level options must match the later request for the connection to
161
+ be reused. Pass `proxy:` and `emulation:` (plus `emulation_os:` etc.) the same
162
+ way you would to the request. `timeout:` bounds the preconnect. Other request
163
+ options are ignored.
164
+ - If an idle connection to the origin already exists, it's reused and no new
165
+ connection is opened. Preconnect several origins concurrently from separate
166
+ threads, because the GVL is released.
167
+ - The connection is subject to the pool's idle timeout (90 seconds) and may
168
+ also be closed by the server. If it's closed, the request falls back to a
169
+ fresh connection. Preconnecting has no effect with `pool_max_idle_per_host: 0`.
170
+ - `cancel` and Ruby thread interrupts abort a pending preconnect.
171
+
145
172
  ### Cancelling Requests
146
173
 
147
174
  Call `cancel` on a client to interrupt all in-flight requests immediately:
@@ -173,6 +200,7 @@ Pass an options hash as the second argument to any HTTP method:
173
200
  | `proxy` | String | Per-request proxy URL |
174
201
  | `emulation` | String/Boolean | Per-request emulation override |
175
202
  | `emulation_os` | String | OS emulation: `windows`, `macos`, `linux`, `android`, `ios` |
203
+ | `default_headers` | Boolean | `false` skips the client's default headers for this request (default: `true`) |
176
204
 
177
205
  ## Browser Emulation
178
206
 
@@ -198,6 +226,14 @@ client = Wreq::Client.new(emulation: "chrome_148", user_agent: "MyBot/1.0")
198
226
 
199
227
  # Per-request emulation override
200
228
  resp = client.get("https://example.com", emulation: "safari_26.2")
229
+
230
+ # Send only the request's headers: skips the client's emulation headers,
231
+ # user_agent and headers. A per-request emulation still adds its own.
232
+ # The emulation's TLS and HTTP/2 settings stay. The client's header_order
233
+ # setting still takes precedence over the request hash's order.
234
+ resp = client.get("https://example.com/script.js",
235
+ default_headers: false,
236
+ headers: { "User-Agent" => "...", "Accept" => "*/*", "Sec-Fetch-Dest" => "script" })
201
237
  ```
202
238
 
203
239
  ### Supported Browsers
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "wreq_rb"
3
- version = "0.6.2"
3
+ version = "0.7.1"
4
4
  edition = "2021"
5
5
  publish = false
6
6
 
@@ -10,7 +10,7 @@ crate-type = ["cdylib"]
10
10
  [dependencies]
11
11
  magnus = { version = "0.8", features = ["rb-sys"] }
12
12
  rb-sys = "0.9"
13
- wreq = { path = "../../vendor/wreq", version = "=0.16.1", features = [
13
+ wreq = { path = "../../vendor/wreq", version = "=0.16.5", features = [
14
14
  "cookies",
15
15
  "json",
16
16
  "gzip",
@@ -24,7 +24,7 @@ wreq = { path = "../../vendor/wreq", version = "=0.16.1", features = [
24
24
  "query",
25
25
  "form",
26
26
  ] }
27
- wreq-util = { version = "=0.2.0", features = ["emulation", "emulation-serde", "emulation-compression"] }
27
+ wreq-util = { version = "=0.2.1", features = ["emulation", "emulation-serde", "emulation-compression"] }
28
28
  tokio = { version = "1", features = ["full"] }
29
29
  tokio-util = "0.7"
30
30
  serde_json = "1.0"
@@ -35,6 +35,6 @@ http = "1"
35
35
  magnus = { version = "0.8", features = ["embed"] }
36
36
 
37
37
  [target.'cfg(target_os = "linux")'.dependencies]
38
- wreq = { path = "../../vendor/wreq", version = "=0.16.1", features = [
38
+ wreq = { path = "../../vendor/wreq", version = "=0.16.5", features = [
39
39
  "prefix-symbols",
40
40
  ] }
@@ -8,9 +8,16 @@ patch_dir = File.expand_path("../../patches", __dir__)
8
8
  wreq_dir = File.expand_path("../../vendor/wreq", __dir__)
9
9
 
10
10
  if File.directory?(patch_dir)
11
- Dir.glob(File.join(patch_dir, "*.patch")).sort.each do |patch|
12
- check = `cd #{wreq_dir} && git apply --check --reverse #{patch} 2>&1`
13
- if $?.success?
11
+ patches = Dir.glob(File.join(patch_dir, "*.patch")).sort
12
+ # Patches stack in order and may touch the same files, so a patch only reverse-applies
13
+ # cleanly while no later patch is applied. The newest patch that reverse-applies marks
14
+ # itself and every earlier patch as already applied.
15
+ applied_count = (patches.rindex do |patch|
16
+ system("git", "apply", "--check", "--reverse", patch, chdir: wreq_dir, out: File::NULL, err: File::NULL)
17
+ end || -1) + 1
18
+
19
+ patches.each_with_index do |patch, index|
20
+ if index < applied_count
14
21
  puts "Patch already applied: #{File.basename(patch)}"
15
22
  else
16
23
  puts "Applying patch: #{File.basename(patch)}"
@@ -441,6 +441,42 @@ impl Client {
441
441
  self.execute_method("OPTIONS", args)
442
442
  }
443
443
 
444
+ /// client.preconnect(url) or client.preconnect(url, opts)
445
+ ///
446
+ /// Opens a connection (TCP + proxy tunnel + TLS handshake) to the URL's origin
447
+ /// and keeps it idle in the pool without sending a request.
448
+ fn preconnect(&self, args: &[Value]) -> Result<(), magnus::Error> {
449
+ let url: String = match args.first() {
450
+ Some(v) => TryConvert::try_convert(*v)?,
451
+ None => return Err(generic_error("url is required")),
452
+ };
453
+
454
+ let mut req = self.inner.get(&url);
455
+ if let Some(opts) = args.get(1) {
456
+ req = apply_request_options(req, &RHash::try_convert(*opts)?)?;
457
+ }
458
+
459
+ let client_token = self.cancel_token.lock().unwrap_or_else(|e| e.into_inner()).clone();
460
+
461
+ let outcome: Option<Result<(), wreq::Error>> = unsafe {
462
+ without_gvl(|thread_token| {
463
+ runtime().block_on(async {
464
+ tokio::select! {
465
+ biased;
466
+ _ = thread_token.cancelled() => None,
467
+ _ = client_token.cancelled() => None,
468
+ res = req.preconnect() => Some(res),
469
+ }
470
+ })
471
+ })
472
+ }?;
473
+
474
+ match outcome {
475
+ Some(res) => res.map_err(to_magnus_error),
476
+ None => Err(generic_error("request interrupted")),
477
+ }
478
+ }
479
+
444
480
  fn cancel(&self) {
445
481
  // Replace the cancel token first so new requests use a fresh token,
446
482
  // then cancel the old one to unblock all current in-flight select!s.
@@ -642,6 +678,10 @@ fn apply_request_options(
642
678
  req = req.headers(hmap);
643
679
  }
644
680
 
681
+ if let Some(enabled) = hash_get_bool(opts, "default_headers")? {
682
+ req = req.default_headers(enabled);
683
+ }
684
+
645
685
  if let Some(body_str) = hash_get_string(opts, "body")? {
646
686
  req = req.body(body_str);
647
687
  }
@@ -870,6 +910,7 @@ pub fn init(_ruby: &magnus::Ruby, module: &magnus::RModule) -> Result<(), magnus
870
910
  client_class.define_method("head", method!(Client::head, -1))?;
871
911
  client_class.define_method("options", method!(Client::options, -1))?;
872
912
  client_class.define_method("request_batch", method!(Client::request_batch, -1))?;
913
+ client_class.define_method("preconnect", method!(Client::preconnect, -1))?;
873
914
  client_class.define_method("cancel", method!(Client::cancel, 0))?;
874
915
 
875
916
  module.define_module_function("get", function!(wreq_get, -1))?;
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Wreq
4
- VERSION = "0.6.2"
4
+ VERSION = "0.7.1"
5
5
  end
@@ -0,0 +1,266 @@
1
+ diff --git a/src/client.rs b/src/client.rs
2
+ index c5eda4c6..629f1433 100644
3
+ --- a/src/client.rs
4
+ +++ b/src/client.rs
5
+ @@ -48,7 +48,9 @@ use self::{
6
+ config::{ConfigService, ConfigServiceLayer},
7
+ redirect::{FollowRedirect, FollowRedirectLayer},
8
+ retry::RetryPolicy,
9
+ - timeout::{Timeout, TimeoutLayer, TimeoutOptions, body::TimeoutBody},
10
+ + timeout::{
11
+ + Timeout, TimeoutLayer, TimeoutOptions, body::TimeoutBody, fetch_timeout_options,
12
+ + },
13
+ transfer_size::{CountingBody, TransferSizeLayer, TransferSizeService},
14
+ },
15
+ request::{Request, RequestBuilder},
16
+ @@ -60,6 +62,7 @@ use crate::cookie;
17
+ use crate::dns::hickory::HickoryDnsResolver;
18
+ use crate::{
19
+ IntoUri, Method, Proxy,
20
+ + config::RequestConfig,
21
+ conn::{
22
+ BoxedConnectorLayer, BoxedTransportConnector, Conn, Unnameable,
23
+ connector::{Connector, ConnectorBuilder},
24
+ @@ -68,6 +71,7 @@ use crate::{
25
+ },
26
+ dns::{DnsResolverWithOverrides, DynResolver, GaiResolver, IntoResolve, Resolve},
27
+ error::{self, Error},
28
+ + ext::UriExt,
29
+ header::OrigHeaderMap,
30
+ http1::Http1Options,
31
+ http2::Http2Options,
32
+ @@ -154,7 +158,23 @@ type BoxedClientServiceLayer = BoxCloneSyncServiceLayer<
33
+ ///
34
+ /// [`Rc`]: std::rc::Rc
35
+ #[derive(Clone)]
36
+ -pub struct Client(Arc<Either<ClientService, BoxedClientService>>);
37
+ +pub struct Client(Arc<ClientRef>);
38
+ +
39
+ +struct ClientRef {
40
+ + service: Either<ClientService, BoxedClientService>,
41
+ + preconnector: Preconnector,
42
+ +}
43
+ +
44
+ +/// Direct handle to the connection pool used by [`Client::preconnect`].
45
+ +///
46
+ +/// Preconnecting bypasses the request middleware stack, so the checks that
47
+ +/// stack would apply before a connection is opened are replicated here.
48
+ +struct Preconnector {
49
+ + http: HttpClient<Connector, Body>,
50
+ + https_only: bool,
51
+ + timer: Timer,
52
+ + timeout: RequestConfig<TimeoutOptions>,
53
+ +}
54
+
55
+ /// A [`ClientBuilder`] can be used to create a [`Client`] with custom configuration.
56
+ #[must_use]
57
+ @@ -430,7 +450,67 @@ impl Client {
58
+ let req = http::Request::<Body>::from(request);
59
+ Pending::Request {
60
+ uri: Some(req.uri().clone()),
61
+ - fut: Box::pin(Oneshot::new((*self.0).clone(), req)),
62
+ + fut: Box::pin(Oneshot::new(self.0.service.clone(), req)),
63
+ + }
64
+ + }
65
+ +
66
+ + /// Establishes a connection to the given URI ahead of time, without sending a request.
67
+ + ///
68
+ + /// The TCP connection (plus proxy tunnel and TLS handshake, where applicable) is
69
+ + /// completed and the connection is kept idle in the pool, so that a subsequent
70
+ + /// request to the same origin can reuse it and skip connection setup.
71
+ + ///
72
+ + /// If an idle connection to the origin already exists, it is reused and no new
73
+ + /// connection is opened. The connection is subject to the pool's idle timeout and
74
+ + /// has no effect if pooling is disabled.
75
+ + ///
76
+ + /// Use [`RequestBuilder::preconnect`] to preconnect with per-request options such as
77
+ + /// a proxy or emulation, which must match the options of the later request for the
78
+ + /// connection to be reused.
79
+ + ///
80
+ + /// # Errors
81
+ + ///
82
+ + /// This method fails if the URI is invalid or the connection cannot be established.
83
+ + #[inline]
84
+ + pub fn preconnect<U: IntoUri>(&self, uri: U) -> impl Future<Output = crate::Result<()>> {
85
+ + self.get(uri).preconnect()
86
+ + }
87
+ +
88
+ + pub(crate) fn execute_preconnect(
89
+ + &self,
90
+ + request: Request,
91
+ + ) -> impl Future<Output = crate::Result<()>> + Send + 'static + use<> {
92
+ + let req = http::Request::<Body>::from(request);
93
+ + let client = self.0.clone();
94
+ + async move {
95
+ + let preconnector = &client.preconnector;
96
+ + let uri = req.uri().clone();
97
+ +
98
+ + if !(uri.is_http() || uri.is_https()) || (preconnector.https_only && !uri.is_https()) {
99
+ + return Err(Error::uri_bad_scheme(uri));
100
+ + }
101
+ +
102
+ + let (total_timeout, _) = fetch_timeout_options(&preconnector.timeout, req.extensions());
103
+ + let connect = preconnector.http.preconnect(req);
104
+ + let res = match total_timeout {
105
+ + Some(timeout) => {
106
+ + let sleep = wreq_proto::rt::Timer::sleep(&preconnector.timer, timeout);
107
+ + match futures_util::future::select(connect, sleep).await {
108
+ + futures_util::future::Either::Left((res, _)) => res,
109
+ + futures_util::future::Either::Right(_) => {
110
+ + Err(Error::request(error::TimedOut).into())
111
+ + }
112
+ + }
113
+ + }
114
+ + None => connect.await,
115
+ + };
116
+ +
117
+ + res.map_err(|err| {
118
+ + let err = err
119
+ + .downcast::<Error>()
120
+ + .map_or_else(Error::request, |err| *err);
121
+ + if err.uri().is_none() { err.with_uri(uri) } else { err }
122
+ + })
123
+ }
124
+ }
125
+ }
126
+ @@ -588,6 +668,13 @@ impl ClientBuilder {
127
+ .build(connector)
128
+ };
129
+
130
+ + let preconnector = Preconnector {
131
+ + http: service.clone(),
132
+ + https_only: config.https_only,
133
+ + timer: config.timer.clone(),
134
+ + timeout: RequestConfig::new(Some(config.timeout_options)),
135
+ + };
136
+ +
137
+ // Configured client service with layers
138
+ let client = {
139
+ let service = ServiceBuilder::new()
140
+ @@ -645,7 +732,10 @@ impl ClientBuilder {
141
+ }
142
+ };
143
+
144
+ - Ok(Client(Arc::new(client)))
145
+ + Ok(Client(Arc::new(ClientRef {
146
+ + service: client,
147
+ + preconnector,
148
+ + })))
149
+ }
150
+
151
+ // Higher-level options
152
+ diff --git a/src/client/layer/client.rs b/src/client/layer/client.rs
153
+ index 8b000486..8e5177a2 100644
154
+ --- a/src/client/layer/client.rs
155
+ +++ b/src/client/layer/client.rs
156
+ @@ -145,32 +145,50 @@ where
157
+ B::Data: Send,
158
+ B::Error: Into<BoxError>,
159
+ {
160
+ - fn request(
161
+ - &self,
162
+ - mut req: Request<B>,
163
+ - ) -> BoxFuture<'static, Result<Response<Incoming>, BoxError>> {
164
+ + fn request(&self, mut req: Request<B>) -> BoxFuture<'static, Result<Response<Incoming>, BoxError>> {
165
+ + match self.prepare(&mut req) {
166
+ + Ok((this, descriptor)) => {
167
+ + Box::pin(this.send_request(req, descriptor).map_err(Into::into))
168
+ + }
169
+ + Err(err) => Box::pin(future::err(err.into())),
170
+ + }
171
+ + }
172
+ +
173
+ + /// Establishes (or reuses) a pooled connection for the request's destination
174
+ + /// without sending the request, leaving the connection idle in the pool.
175
+ + ///
176
+ + /// The request is only used to derive the connection descriptor, so per-request
177
+ + /// options (proxy, TLS/emulation, HTTP version, ...) produce the same pool key a
178
+ + /// subsequent real request would use.
179
+ + pub(crate) fn preconnect(&self, mut req: Request<B>) -> BoxFuture<'static, Result<(), BoxError>> {
180
+ + match self.prepare(&mut req) {
181
+ + Ok((this, descriptor)) => Box::pin(async move {
182
+ + // Dropping the pooled connection returns it to the pool as idle.
183
+ + this.connection_for(descriptor).await.map(drop).map_err(Into::into)
184
+ + }),
185
+ + Err(err) => Box::pin(future::err(err.into())),
186
+ + }
187
+ + }
188
+ +
189
+ + #[allow(clippy::result_large_err)]
190
+ + fn prepare(&self, req: &mut Request<B>) -> Result<(Self, ConnectionDescriptor), Error> {
191
+ let is_http_connect = req.method() == Method::CONNECT;
192
+ // Validate HTTP version early
193
+ match req.version() {
194
+ Version::HTTP_10 if is_http_connect => {
195
+ warn!("CONNECT is not allowed for HTTP/1.0");
196
+ - return Box::pin(future::err(e!(UserUnsupportedRequestMethod).into()));
197
+ + return Err(e!(UserUnsupportedRequestMethod));
198
+ }
199
+ Version::HTTP_10 | Version::HTTP_11 | Version::HTTP_2 => {}
200
+ // completely unsupported HTTP version (like HTTP/0.9)!
201
+ _unsupported => {
202
+ warn!("Request has unsupported version: {:?}", _unsupported);
203
+ - return Box::pin(future::err(e!(UserUnsupportedVersion).into()));
204
+ + return Err(e!(UserUnsupportedVersion));
205
+ }
206
+ };
207
+
208
+ // Extract and normalize URI
209
+ - let uri = match normalize_uri(&mut req, is_http_connect) {
210
+ - Ok(uri) => uri,
211
+ - Err(err) => {
212
+ - return Box::pin(future::err(e!(UserAbsoluteUriRequired, err).into()));
213
+ - }
214
+ - };
215
+ + let uri = normalize_uri(req, is_http_connect).map_err(|err| e!(UserAbsoluteUriRequired, err))?;
216
+
217
+ let mut this = self.clone();
218
+
219
+ @@ -196,7 +214,7 @@ where
220
+ ConnectionDescriptor::new(uri, group, proxy, version, tls_options, socket_bind_options)
221
+ };
222
+
223
+ - Box::pin(this.send_request(req, descriptor).map_err(Into::into))
224
+ + Ok((this, descriptor))
225
+ }
226
+
227
+ async fn send_request(
228
+ diff --git a/src/client/layer/timeout.rs b/src/client/layer/timeout.rs
229
+ index b978d75b..0d3f340c 100644
230
+ --- a/src/client/layer/timeout.rs
231
+ +++ b/src/client/layer/timeout.rs
232
+ @@ -105,7 +105,7 @@ where
233
+ }
234
+ }
235
+
236
+ -fn fetch_timeout_options(
237
+ +pub(crate) fn fetch_timeout_options(
238
+ opts: &RequestConfig<TimeoutOptions>,
239
+ extensions: &http::Extensions,
240
+ ) -> (Option<Duration>, Option<Duration>) {
241
+ diff --git a/src/client/request.rs b/src/client/request.rs
242
+ index fe02a938..6a76c3a4 100644
243
+ --- a/src/client/request.rs
244
+ +++ b/src/client/request.rs
245
+ @@ -847,6 +847,21 @@ impl RequestBuilder {
246
+ }
247
+ }
248
+
249
+ + /// Establishes a connection for this request ahead of time, without sending it.
250
+ + ///
251
+ + /// Only connection-level options (such as proxy, emulation/TLS options, HTTP
252
+ + /// version and timeout) are taken into account; the method, headers and body are
253
+ + /// ignored. See [`Client::preconnect`] for details.
254
+ + ///
255
+ + /// # Errors
256
+ + ///
257
+ + /// This method fails if the request is invalid or the connection cannot be
258
+ + /// established.
259
+ + pub fn preconnect(self) -> impl Future<Output = crate::Result<()>> + Send + 'static {
260
+ + let fut = self.request.map(|req| self.client.execute_preconnect(req));
261
+ + async move { fut?.await }
262
+ + }
263
+ +
264
+ /// Attempt to clone the RequestBuilder.
265
+ ///
266
+ /// `None` is returned if the RequestBuilder can not be cloned,
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "wreq"
3
- version = "0.16.1"
3
+ version = "0.16.5"
4
4
  description = "An ergonomic, privacy-aware Rust HTTP Client"
5
5
  keywords = ["http", "client", "websocket", "ja3", "ja4"]
6
6
  categories = ["web-programming::http-client"]
@@ -33,6 +33,9 @@ charset = ["dep:encoding_rs", "dep:mime"]
33
33
  # Enable cookies store support.
34
34
  cookies = ["dep:cookie"]
35
35
 
36
+ # Restrict cookie domains using the Public Suffix List.
37
+ cookies-psl = ["cookies", "dep:psl"]
38
+
36
39
  # Enable gzip decompression support.
37
40
  gzip = ["dep:tower-http", "tower-http?/decompression-gzip"]
38
41
 
@@ -98,7 +101,7 @@ pin-project-lite = "0.2.17"
98
101
  futures-util = { version = "0.3.33", default-features = false }
99
102
  socket2 = { version = "0.6.3", features = ["all"] }
100
103
  ipnet = "2.12.0"
101
- lru = "0.18.0"
104
+ lru = "0.19.0"
102
105
  btls = "0.5.6"
103
106
  btls-sys = "0.5.6"
104
107
  tokio-btls = "0.5.6"
@@ -134,6 +137,7 @@ webpki-root-certs = { version = "1.0.7", optional = true }
134
137
 
135
138
  ## cookies
136
139
  cookie = { version = "0.18", optional = true }
140
+ psl = { version = "2.1", optional = true }
137
141
 
138
142
  ## tower http
139
143
  tower-http = { version = "0.6.8", default-features = false, optional = true }
@@ -270,6 +274,11 @@ required-features = ["multipart", "stream"]
270
274
  name = "retry"
271
275
  path = "tests/retry.rs"
272
276
 
277
+ [[test]]
278
+ name = "websocket"
279
+ path = "tests/websocket.rs"
280
+ required-features = ["ws"]
281
+
273
282
  [[example]]
274
283
  name = "json_dynamic"
275
284
  path = "examples/json_dynamic.rs"
@@ -348,8 +357,3 @@ path = "examples/keylog.rs"
348
357
  [[example]]
349
358
  name = "unix_socket"
350
359
  path = "examples/unix_socket.rs"
351
-
352
- [[example]]
353
- name = "rt"
354
- path = "examples/rt.rs"
355
- required-features = ["compio-rt"]
@@ -79,6 +79,8 @@ impl Server {
79
79
  }
80
80
  accept = listener.accept() => {
81
81
  if let Ok((socket, _peer_addr)) = accept {
82
+ // Nagle would hold small response writes until the client's delayed ACK.
83
+ socket.set_nodelay(true)?;
82
84
  let tls_acceptor = self.tls_acceptor.clone();
83
85
  let builder = self.builder.clone();
84
86
  join_set.spawn(async move {