gitoxide icon indicating copy to clipboard operation
gitoxide copied to clipboard

`reqwest` as blocking http client for `git-transport`

Open Byron opened this issue 4 years ago • 1 comments

The first alternative implementation, which may be easier to hack on while possibly one day being the first async implementation.

Tasks

  • [x] feature toggle
  • [x] get the first http-test to work
  • [x] get all tests to work (kinda)
  • [ ] figure out why 3 tests are hanging

Byron avatar Sep 28 '22 01:09 Byron

This seems to be stuck, as in quite literally hanging, unfortunately. Here is what I could gather from the generous logging that I applied:

❯ cargo test --package git-transport --features=http-client-reqwest,maybe-async/is_sync client::blocking_io::http::handshake_and_lsrefs_and_fetch_v2 -- --exact  --nocapture
   Compiling reqwest v0.11.12 (/Users/byron/dev/github.com/seanmonstar/reqwest)
   Compiling git-transport v0.20.0 (/Users/byron/dev/github.com/Byron/gitoxide/git-transport)
    Finished test [unoptimized + debuginfo] target(s) in 2.39s
     Running unittests src/lib.rs (target/debug/deps/git_transport-12aeb9f37c92b10c)

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 7 filtered out; finished in 0.00s

     Running tests/blocking-transport.rs (target/debug/deps/blocking_transport-a636f8583c84cc39)

running 1 test
[git-transport/tests/client/blocking_io/http/mock.rs:46] "srv: accept" = "srv: accept"
[git-transport/src/client/blocking_io/http/reqwest.rs:144] "client: sent remote request" = "client: sent remote request"
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/wait.rs:29] "loop poll" = "loop poll"
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/wait.rs:39] "pending" = "pending"
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/wait.rs:51] "park" = "park"
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/wait.rs:55] "woke up" = "woke up"
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/wait.rs:29] "loop poll" = "loop poll"
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/wait.rs:32] "OK val" = "OK val"
[git-transport/src/client/blocking_io/http/reqwest.rs:52] "reqw: send request" = "reqw: send request"
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/wait.rs:29] "loop poll" = "loop poll"
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/wait.rs:39] "pending" = "pending"
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/wait.rs:47] "park timeout" = "park timeout"
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/wait.rs:47] deadline - now = 999.972708ms
[git-transport/tests/client/blocking_io/http/mock.rs:55] "srv: read to end" = "srv: read to end"
[git-transport/tests/client/blocking_io/http/mock.rs:58] "srv: write response" = "srv: write response"
[git-transport/tests/client/blocking_io/http/mock.rs:58] response.len() = 482
[git-transport/tests/client/blocking_io/http/mock.rs:60] response.as_bstr() = "HTTP/1.1 200 OK\r\nServer: GitHub Babel 2.0\r\nContent-Type: application/x-git-upload-pack-advertisement\r\nContent-Length: 1000\r\nExpires: Fri, 01 Jan 1980 00:00:00 GMT\r\nPragma: no-cache\r\nCache-Control: no-cache, max-age=0, must-revalidate\r\nVary: Accept-Encoding\r\nX-Frame-Options: DENY\r\nX-GitHub-Request-Id: 737D:544E:C932CB:113F404:5F3F3EE5\r\n\r\n001e# service=git-upload-pack\n0000000eversion 2\n0023agent=git/github-gdf51a71f0236\n000cls-refs\n0019fetch=shallow filter\n0012server-option\n0000\n"
[git-transport/tests/client/blocking_io/http/mock.rs:62] "srv: flush" = "srv: flush"
[git-transport/tests/client/blocking_io/http/mock.rs:64] "srv: done - send read bytes" = "srv: done - send read bytes"
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/wait.rs:55] "woke up" = "woke up"
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/wait.rs:29] "loop poll" = "loop poll"
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/wait.rs:32] "OK val" = "OK val"
[git-transport/src/client/blocking_io/http/reqwest.rs:90] "reqw: send headers" = "reqw: send headers"
[git-transport/src/client/blocking_io/http/reqwest.rs:95] "reqw: sending body" = "reqw: sending body"
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/response.rs:407] buf.len() = 8192
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/wait.rs:29] "loop poll" = "loop poll"
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/wait.rs:32] "OK val" = "OK val"
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/response.rs:412] bytes = 143
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/response.rs:412] String::from_utf8_lossy(&buf[..bytes]) = "001e# service=git-upload-pack\n0000000eversion 2\n0023agent=git/github-gdf51a71f0236\n000cls-refs\n0019fetch=shallow filter\n0012server-option\n0000\n"
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/response.rs:407] buf.len() = 8192
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/wait.rs:29] "loop poll" = "loop poll"
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/wait.rs:39] "pending" = "pending"
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/wait.rs:47] "park timeout" = "park timeout"
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/wait.rs:47] deadline - now = 999.853625ms
[git-transport/tests/client/blocking_io/http/mod.rs:392] "invoke" = "invoke"
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/wait.rs:55] "woke up" = "woke up"
[/Users/byron/dev/github.com/seanmonstar/reqwest/src/blocking/wait.rs:29] "loop poll" = "loop poll"
[git-transport/tests/client/blocking_io/http/mock.rs:46] "srv: accept" = "srv: accept"
test client::blocking_io::http::handshake_and_lsrefs_and_fetch_v2 has been running for over 60 seconds

Everything works as it should, but when reading the server response with reqwest it hangs indefinitely. What happens under the hood is that it actually manages to read the remaining 143 bytes of the body in the first poll round, but then goes again because std::io::copy will only stop once it sees 0 bytes read. The second poll returns with 'pending', which results in the thread being parked (the timeout is lowered to 1s here), but it wakes up immediately as the socket probably indicated that it's ready - probably it disconnected because the server finished sending and flushing the socket a long time ago. Now it polls again, but that poll actually does block and does so forver. That shouldn't be possible and is in violation of what async is supposed to do.

Maybe it's a bug in reqwest, or elsewhere, maybe it's even something strange in my test-setup which spins up a mock http server, but it makes no sense to me. The server listens on something like this by the way: "http://127.0.0.1:15411/path/not/important/due/to/mock/info/refs?service=git-upload-pack", which doesn't seem suspicious.

Then I hardcoded "https://github.com/Byron/gitoxide.git/info/refs?service=git-upload-pack" for a moment and… with that it doesn't hang. So it appears to have something to do with being a local server, or with being http, or maybe something else that is entirely beyond me.

There is a glimpse of hope, and maybe this already works in the wild, but I didn't hook it up yet so couldn't test it with gix.

It's notable that when shutting the mock server stream down explicitly via stream.shutdown(Shutdown::Both).ok(); reqwest tends to hang right away on the second poll without parking, which might mean that it can't handle polling on a closed local socket? It's hard to find out what's actually making the request, and what's called when polling so I have to give up here. It's likely that in the real world, this actually works as it manages to see when servers are done without blocking.

curl works fine so I don't think the issue is with the test setup per-se, and I don't know what I could try there.

Debug code in git-transport.

diff --git a/Cargo.lock b/Cargo.lock
index b4f9672ee..7cd6bcd31 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2872,8 +2872,6 @@ dependencies = [
 [[package]]
 name = "reqwest"
 version = "0.11.12"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "431949c384f4e2ae07605ccaa56d1d9d2ecdb5cadd4f9577ccfab29f2e5149fc"
 dependencies = [
  "base64",
  "bytes",
diff --git a/git-transport/src/client/blocking_io/http/reqwest.rs b/git-transport/src/client/blocking_io/http/reqwest.rs
index 2e617536c..521a5e0fa 100644
--- a/git-transport/src/client/blocking_io/http/reqwest.rs
+++ b/git-transport/src/client/blocking_io/http/reqwest.rs
@@ -25,11 +25,16 @@ mod remote {
                     // received and the sender of the request might restart us.
                     let client = reqwest::blocking::ClientBuilder::new()
                         .connect_timeout(std::time::Duration::from_secs(20))
+                        .timeout(std::time::Duration::from_secs(1))
                         .build()?;
+                    dbg!(&url);
                     let mut req = if upload { client.post(url) } else { client.get(url) }.headers(headers);
                     let (post_body_tx, post_body_rx) = pipe::unidirectional(0);
                     if upload {
+                        dbg!("reqw: is upload");
                         req = req.body(reqwest::blocking::Body::new(post_body_rx));
+                    } else {
+                        drop(post_body_rx);
                     }
                     let (mut response_body_tx, response_body_rx) = pipe::unidirectional(0);
                     let (mut headers_tx, headers_rx) = pipe::unidirectional(0);
@@ -45,6 +50,7 @@ mod remote {
                         // Shut down as something is off.
                         break;
                     }
+                    dbg!("reqw: send request");
                     let mut res = match req.send().and_then(|res| res.error_for_status()) {
                         Ok(res) => res,
                         Err(err) => {
@@ -82,13 +88,16 @@ mod remote {
 
                     // We don't have to care if anybody is receiving the header, as a matter of fact we cannot fail sending them.
                     // Thus an error means the receiver failed somehow, but might also have decided not to read headers at all. Fine with us.
+                    dbg!("reqw: send headers");
                     send_headers().ok();
 
                     // reading the response body is streaming and may fail for many reasons. If so, we send the error over the response
                     // body channel and that's all we can do.
+                    dbg!("reqw: sending body");
                     if let Err(err) = std::io::copy(&mut res, &mut response_body_tx) {
                         response_body_tx.channel.send(Err(err)).ok();
                     }
+                    dbg!("reqw: done sending body");
                 }
                 Ok(())
             });
@@ -133,6 +142,7 @@ mod remote {
                     upload,
                 })
                 .expect("the remote cannot be down at this point");
+            dbg!("client: sent remote request");
 
             let Response {
                 headers,
@@ -141,6 +151,7 @@ mod remote {
             } = match self.response.recv() {
                 Ok(res) => res,
                 Err(_) => {
+                    dbg!("client: error receiving response");
                     let err = self
                         .handle
                         .take()
diff --git a/git-transport/tests/client/blocking_io/http/mock.rs b/git-transport/tests/client/blocking_io/http/mock.rs
index 49c74ee5e..b2f133d3a 100644
--- a/git-transport/tests/client/blocking_io/http/mock.rs
+++ b/git-transport/tests/client/blocking_io/http/mock.rs
@@ -1,3 +1,4 @@
+use std::net::Shutdown;
 use std::{
     io::{Read, Write},
     net::SocketAddr,
@@ -43,17 +44,26 @@ impl Server {
             for command in recv_commands {
                 match command {
                     Command::ReadAndRespond(response) => {
+                        dbg!("srv: accept");
                         let (mut stream, _) = listener.accept().expect("accept to always work");
+                        stream.set_nodelay(true).ok();
                         stream
                             .set_read_timeout(Some(Duration::from_millis(50)))
                             .expect("timeout to always work");
                         stream
                             .set_write_timeout(Some(Duration::from_millis(50)))
                             .expect("timeout to always work");
+                        dbg!("srv: read to end");
                         let mut out = Vec::new();
                         stream.read_to_end(&mut out).ok();
+                        dbg!("srv: write response", response.len());
+                        use bstr::ByteSlice;
+                        dbg!(response.as_bstr());
                         stream.write_all(&response).expect("write to always work");
+                        dbg!("srv: flush");
                         stream.flush().expect("flush to work");
+                        stream.shutdown(Shutdown::Both).ok();
+                        dbg!("srv: done - send read bytes");
                         if send_result.send(CommandResult::ReadAndRespond(out)).is_err() {
                             break;
                         }
diff --git a/git-transport/tests/client/blocking_io/http/mod.rs b/git-transport/tests/client/blocking_io/http/mod.rs
index 3517bf909..5cc5c5129 100644
--- a/git-transport/tests/client/blocking_io/http/mod.rs
+++ b/git-transport/tests/client/blocking_io/http/mod.rs
@@ -321,7 +321,6 @@ Accept: application/x-git-upload-pack-result
 }
 
 #[test]
-#[cfg_attr(feature = "http-client-reqwest", ignore)] // hangs
 fn handshake_and_lsrefs_and_fetch_v2() -> crate::Result {
     let (server, mut c) = mock::serve_and_connect(
         "v2/http-handshake.response",
@@ -390,11 +389,13 @@ Git-Protocol: version=2:value-only:key=value
 
     server.next_read_and_respond_with(fixture_bytes("v2/http-lsrefs.response"));
     drop(refs);
+    dbg!("invoke");
     let res = c.invoke(
         "ls-refs",
         [("without-value", None), ("with-value", Some("value"))].iter().cloned(),
         Some(vec!["arg1".as_bytes().as_bstr().to_owned()].into_iter()),
     )?;
+    dbg!("have res");
     assert_eq!(
         res.lines().collect::<Result<Vec<_>, _>>()?,
         vec![

Debug code in reqwest

diff --git a/src/blocking/response.rs b/src/blocking/response.rs
index 830c489..35de05e 100644
--- a/src/blocking/response.rs
+++ b/src/blocking/response.rs
@@ -32,11 +32,7 @@ impl fmt::Debug for Response {
 }
 
 impl Response {
-    pub(crate) fn new(
-        res: async_impl::Response,
-        timeout: Option<Duration>,
-        thread: KeepCoreThreadAlive,
-    ) -> Response {
+    pub(crate) fn new(res: async_impl::Response, timeout: Option<Duration>, thread: KeepCoreThreadAlive) -> Response {
         Response {
             inner: res,
             body: None,
@@ -304,11 +300,9 @@ impl Response {
     /// # }
     /// ```
     pub fn text_with_charset(self, default_encoding: &str) -> crate::Result<String> {
-        wait::timeout(self.inner.text_with_charset(default_encoding), self.timeout).map_err(|e| {
-            match e {
-                wait::Waited::TimedOut(e) => crate::error::decode(e),
-                wait::Waited::Inner(e) => e,
-            }
+        wait::timeout(self.inner.text_with_charset(default_encoding), self.timeout).map_err(|e| match e {
+            wait::Waited::TimedOut(e) => crate::error::decode(e),
+            wait::Waited::Inner(e) => e,
         })
     }
 
@@ -410,10 +404,13 @@ impl Read for Response {
         use futures_util::io::AsyncReadExt;
 
         let timeout = self.timeout;
-        wait::timeout(self.body_mut().read(buf), timeout).map_err(|e| match e {
+        dbg!(buf.len());
+        let bytes = wait::timeout(self.body_mut().read(buf), timeout).map_err(|e| match e {
             wait::Waited::TimedOut(e) => crate::error::decode(e).into_io(),
             wait::Waited::Inner(e) => e,
-        })
+        })?;
+        dbg!(bytes, String::from_utf8_lossy(&buf[..bytes]));
+        Ok(bytes)
     }
 }
 
diff --git a/src/blocking/wait.rs b/src/blocking/wait.rs
index 3c903f8..374df0a 100644
--- a/src/blocking/wait.rs
+++ b/src/blocking/wait.rs
@@ -26,12 +26,17 @@ where
     futures_util::pin_mut!(fut);
 
     loop {
+        dbg!("loop poll");
         match fut.as_mut().poll(&mut cx) {
-            Poll::Ready(Ok(val)) => return Ok(val),
+            Poll::Ready(Ok(val)) => {
+                dbg!("OK val");
+                return Ok(val);
+            }
             Poll::Ready(Err(err)) => return Err(Waited::Inner(err)),
             Poll::Pending => (), // fallthrough
         }
 
+        dbg!("pending");
         if let Some(deadline) = deadline {
             let now = Instant::now();
             if now >= deadline {
@@ -39,16 +44,15 @@ where
                 return Err(Waited::TimedOut(crate::error::TimedOut));
             }
 
-            log::trace!(
-                "({:?}) park timeout {:?}",
-                thread::current().id(),
-                deadline - now
-            );
+            dbg!("park timeout", deadline - now);
+            log::trace!("({:?}) park timeout {:?}", thread::current().id(), deadline - now);
             thread::park_timeout(deadline - now);
         } else {
+            dbg!("park");
             log::trace!("({:?}) park without timeout", thread::current().id());
             thread::park();
         }
+        dbg!("woke up");
     }
 }

Byron avatar Sep 28 '22 08:09 Byron

In desperation I tried to run the hanging tests on other platforms, but it would consistently hang on Debian linux and on Windows 11 as well :/.

Windows yielded some new errors: An established connection was aborted by the software in your host machine., which might hint at what's going on here. Maybe the server should somehow wait for the client to be ready and done reading? How can that be done?

If the above yields no new answers, it looks like there is no way around debugging this deep into the belly of the beast.

Edit: also tried to not drop the server stream after sending the response body (which is what reqwest sees in full but hangs afterwards) via std::mem::forget(), but that also doesn't change anything. Tried to adjust reqwest tcp settings (keepalive, nodelay, http settings) but it didn't change anything either :/.

Byron avatar Oct 08 '22 03:10 Byron

All tests work now, as it turned out reqwest is easily tricked into blocking forever if the server provides content-lengths which are longer than the actual content. It blocks even though the underlying stream is long closed and no timeout seems to occour to awake it from the dead, at least in blocking mode.

Correcting the content length header fields in all relevant fixtures removed the hangs. It's still puzzling to me how these reads can hang beyond EOF.

Byron avatar Oct 08 '22 06:10 Byron