Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ tokio = { version = "1", features = ["macros", "test-util", "signal", "net", "io
tokio-test = "0.4"
tower-test = "0.4"
pretty_env_logger = "0.5"
tracing = "0.1.36"
tracing-subscriber = { version = "0.3", default-features = false, features = ["registry", "std"] }

[target.'cfg(any(target_os = "linux", target_os = "macos"))'.dev-dependencies]
pnet_datalink = "0.35.0"
Expand Down
4 changes: 3 additions & 1 deletion src/common/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ impl Exec {
{
match *self {
Exec::Executor(ref e) => {
e.execute(Box::pin(fut));
tracing::dispatcher::with_default(&tracing::Dispatch::none(), || {

@dswij dswij Aug 16, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems that the problem is with TokioExecutor instead of Exec.

Also, this makes tracing a dependency when running Exec without tokio.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems that the problem is with TokioExecutor instead of Exec.

TokioExecutor (or any Executor someone passes in) is shared by both the client and the h2 server implementation, whereas Exec is client only. So fixing Exec seems more logical to me, because changing the behaviour of TokioExecutor would have an impact on the h2 server span propagation (which I believe works correctly at the moment). Not too sure what a good API would look like here... open to suggestions.

Also, this makes tracing a dependency when running Exec without tokio.

I believe that's already the case today, see:

$ cargo tree --invert tracing --no-default-features --features client-legacy --edges no-dev

tracing v0.1.44
└── hyper-util v0.1.20

client enables dep:tracing so the legacy client already pulls it in.
And the client-legacy feature enables hyper-util's tokio feature:

$ cargo tree --invert tokio --no-default-features --features client-legacy --edges features,no-dev

tokio v1.53.1
└── hyper-util v0.1.20
    ├── hyper-util feature "client"
    │   └── hyper-util feature "client-legacy" (command-line)
    ├── hyper-util feature "client-legacy" (command-line)
    └── hyper-util feature "tokio"
        └── hyper-util feature "client-legacy" (command-line)

That being said, I agree with you that the question becomes whether Exec should know about tracing at all, and it probably should not. Perhaps something like this would be more semantically accurate (i.e. gating on the tracing feature):

            Exec::Executor(ref e) => {
                #[cfg(feature = "tracing")]
                tracing::dispatcher::with_default(&tracing::Dispatch::none(), || {
                    e.execute(Box::pin(fut));
                });
                #[cfg(not(feature = "tracing"))]
                e.execute(Box::pin(fut));
            }

What do you think?

e.execute(Box::pin(fut));
});
}
}
}
Expand Down
1 change: 1 addition & 0 deletions src/common/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#![allow(missing_docs)]

#[cfg(feature = "client-legacy")]
pub(crate) mod exec;
#[cfg(feature = "client-legacy")]
mod lazy;
Expand Down
141 changes: 141 additions & 0 deletions tests/legacy_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ use std::io::{Read, Write};
use std::net::{SocketAddr, TcpListener};
use std::pin::{Pin, pin};
use std::sync::Arc;
#[cfg(not(miri))]
use std::sync::Mutex;
use std::sync::atomic::Ordering;
use std::task::Poll;
use std::thread;
Expand All @@ -18,6 +20,12 @@ use futures_util::{self, Stream};
use http_body_util::BodyExt;
use http_body_util::{Empty, Full, StreamBody};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
#[cfg(not(miri))]
use tracing::Instrument;
#[cfg(not(miri))]
use tracing_subscriber::layer::{Context, Layer, SubscriberExt};
#[cfg(not(miri))]
use tracing_subscriber::registry::LookupSpan;

use hyper::Request;
use hyper::body::Bytes;
Expand Down Expand Up @@ -152,6 +160,139 @@ async fn drop_client_closes_idle_connections() {
t1.await.unwrap();
}

#[cfg(not(miri))]
#[derive(Clone, Default)]
struct ClosedSpans(Arc<Mutex<Vec<String>>>);

#[cfg(not(miri))]
impl ClosedSpans {
// records the name of every span that closes until the guard is dropped
fn record() -> (ClosedSpans, tracing::subscriber::DefaultGuard) {
let spans = ClosedSpans::default();
let guard =
tracing::subscriber::set_default(tracing_subscriber::registry().with(spans.clone()));
(spans, guard)
}

fn contains(&self, name: &str) -> bool {
self.0.lock().unwrap().iter().any(|span| span == name)
}
}

#[cfg(not(miri))]
impl<S> Layer<S> for ClosedSpans
where
S: tracing::Subscriber + for<'a> LookupSpan<'a>,
{
fn on_close(&self, id: tracing::Id, ctx: Context<'_, S>) {
let name = ctx.span(&id).unwrap().name();
self.0.lock().unwrap().push(name.to_owned());
}
}

#[cfg(not(miri))]
#[cfg(feature = "http1")]
#[tokio::test]
async fn request_span_closes_while_conn_idle() {
let _ = pretty_env_logger::try_init();

let (closed_spans, _guard) = ClosedSpans::record();

let server = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = server.local_addr().unwrap();
let (tx1, rx1) = oneshot::channel();

let t1 = tokio::spawn(async move {
let mut sock = server.accept().await.unwrap().0;
let mut buf = [0; 4096];
sock.read(&mut buf).await.unwrap();
sock.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")
.await
.unwrap();
let _ = tx1.send(());

// prevent this thread from closing until end of test, so the connection
// stays open and idle until Client is dropped
if let Ok(n) = sock.read(&mut buf).await {
assert_eq!(n, 0);
}
});

let client = Client::builder(TokioExecutor::new()).build_http::<Empty<Bytes>>();
let req = Request::builder()
.uri(&*format!("http://{addr}/a"))
.body(Empty::<Bytes>::new())
.unwrap();

async {
let res = client.request(req).await.unwrap();
assert_eq!(res.status(), hyper::StatusCode::OK);
res.into_body().collect().await.unwrap();
}
.instrument(tracing::info_span!("test.request"))
.await;

rx1.await.unwrap();

// the idle connection must not hold the request's span open
assert!(closed_spans.contains("test.request"));

drop(client);
t1.await.unwrap();
}

#[cfg(not(miri))]
#[cfg(feature = "http2")]
#[tokio::test]
async fn request_span_closes_while_h2_conn_idle() {
use http::Response;
use hyper::service::service_fn;

let _ = pretty_env_logger::try_init();

let (closed_spans, _guard) = ClosedSpans::record();

let server = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = server.local_addr().unwrap();

let t1 = tokio::spawn(async move {
let stream = TokioIo::new(server.accept().await.unwrap().0);
// serves until the Client is dropped at the end of the test
let _ = hyper::server::conn::http2::Builder::new(TokioExecutor::new())
.serve_connection(
stream,
service_fn(|_| async {
Ok::<_, hyper::Error>(Response::new(Empty::<Bytes>::new()))
}),
)
.await;
});

// prior knowledge, so the handshake happens on the first request
let client = Client::builder(TokioExecutor::new())
.http2_only(true)
.build_http::<Empty<Bytes>>();
let req = Request::builder()
.uri(&*format!("http://{addr}/a"))
.body(Empty::<Bytes>::new())
.unwrap();

async {
let res = client.request(req).await.unwrap();
assert_eq!(res.status(), hyper::StatusCode::OK);
res.into_body().collect().await.unwrap();
}
.instrument(tracing::info_span!("test.request"))
.await;

// neither our dispatcher nor the one hyper spawns during the handshake may
// hold the request's span open
assert!(closed_spans.contains("test.request"));

drop(client);
t1.await.unwrap();
}

#[cfg(not(miri))]
#[cfg(feature = "http1")]
#[tokio::test]
Expand Down