HTTP/2 client sends HEADERS and an immediately ready Full body in separate socket writes
Maintainer antworten meist innerhalb von 1 Tag
Dieses Issue hat noch niemand übernommen.
Bewertung
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Anfängerfreundlichkeit
- 52/100
- Issue-Typ
- Feature
- Klarheit
- Größtenteils klar
- Aktivitätsstatus
- Aktiv
- Tech-Stack
- rust
- Bereich
- backend, networking, performance
Rechercherichtung
Start by tracing how Hyper’s HTTP/2 client polls request bodies and queues frames for the connection driver; the issue does not name source files or tests. Compare the reported Full<Bytes> and pending streaming body behavior with the direct h2 reproduction, then check existing HTTP/2 client tests for a suitable place to cover both cases. Done means an immediately ready body can share the HEADERS socket write while a pending body still allows headers to be sent promptly.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Beschreibung
This issue was generated by AI.
Version
Reproduced with hyper 1.12.0, h2 0.4.20, hyper-util 0.1.21, and tokio 1.53.2.
Also reproduced the hyper behavior with hyper 1.9.0, h2 0.4.14, hyper-util 0.1.20, and tokio 1.52.3.
Platform
macOS arm64, Rust 1.95.0. Plain loopback TCP, TCP_NODELAY enabled, Tokio current-thread runtime.
Summary
For a small HTTP/2 POST with an immediately available http_body_util::Full<Bytes> body, hyper sends HEADERS and DATA in separate socket writes. A direct h2 client queues the same HEADERS and DATA in one socket write.
This is a performance question, not a protocol error. Can hyper poll and queue an immediately ready first body frame before yielding to the connection driver? Streaming bodies should still send headers promptly when the body is pending.
Reproduction
The program runs a local h2 echo server and records successful client poll_write and poll_write_vectored calls. It warms each connection with one completed request, clears the write trace, then records the second request. It parses frame headers from each write. It also includes a tonic unary variant to distinguish an extra empty DATA frame from the separate HEADERS/body writes.
Cargo.toml
[package]
name = "unary-h2-writes"
version = "0.1.0"
edition = "2021"
[dependencies]
bytes = "1"
h2 = "=0.4.20"
http = "1"
http-body-util = "0.1"
hyper = { version = "=1.12.0", features = ["client", "http2"] }
hyper-util = { version = "=0.1.21", features = ["tokio"] }
tokio = { version = "=1.53.2", features = ["macros", "rt", "net", "io-util", "time"] }
tonic = "=0.14.6"
tonic-prost = "=0.14.6"
prost = "0.14"
tower = { version = "0.5", features = ["util"] }
parking_lot = "0.12"
src/main.rs
use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper_util::rt::{TokioExecutor, TokioIo};
use std::io::{self, IoSlice};
use std::pin::Pin;
use std::sync::Arc;
use parking_lot::Mutex;
use std::task::{Context, Poll};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio::net::{TcpListener, TcpStream};
type Trace = Arc<Mutex<Vec<Vec<u8>>>>;
struct Counted {
inner: TcpStream,
trace: Trace,
}
impl AsyncRead for Counted {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.inner).poll_read(cx, buf)
}
}
impl AsyncWrite for Counted {
fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
match Pin::new(&mut self.inner).poll_write(cx, buf) {
Poll::Ready(Ok(n)) => {
self.trace.lock().push(buf[..n].to_vec());
Poll::Ready(Ok(n))
}
result => result,
}
}
fn poll_write_vectored(mut self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>]) -> Poll<io::Result<usize>> {
match Pin::new(&mut self.inner).poll_write_vectored(cx, bufs) {
Poll::Ready(Ok(n)) => {
let mut bytes = Vec::with_capacity(n);
let mut remaining = n;
for buf in bufs {
let used = remaining.min(buf.len());
bytes.extend_from_slice(&buf[..used]);
remaining -= used;
if remaining == 0 { break; }
}
self.trace.lock().push(bytes);
Poll::Ready(Ok(n))
}
result => result,
}
}
fn is_write_vectored(&self) -> bool { true }
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.inner).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.inner).poll_shutdown(cx)
}
}
async fn server() -> std::net::SocketAddr {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
while let Ok((stream, _)) = listener.accept().await {
stream.set_nodelay(true).unwrap();
tokio::spawn(async move {
let mut connection = h2::server::handshake(stream).await.unwrap();
while let Some(Ok((request, mut respond))) = connection.accept().await {
tokio::spawn(async move {
let mut body = request.into_body();
let mut bytes = Vec::new();
while let Some(chunk) = body.data().await {
let chunk = chunk.unwrap();
body.flow_control().release_capacity(chunk.len()).unwrap();
bytes.extend_from_slice(&chunk);
}
let response = http::Response::builder().header("content-type", "application/grpc").body(()).unwrap();
let mut stream = respond.send_response(response, false).unwrap();
stream.send_data(Bytes::from(bytes), false).unwrap();
let mut trailers = http::HeaderMap::new();
trailers.insert("grpc-status", http::HeaderValue::from_static("0"));
stream.send_trailers(trailers).unwrap();
});
}
});
}
});
addr
}
fn print_trace(name: &str, trace: &Trace) {
let writes = trace.lock();
println!("{name}: {} socket writes", writes.len());
for (i, write) in writes.iter().enumerate() {
print!(" write {}:", i + 1);
let mut bytes = write.as_slice();
while bytes.len() >= 9 {
let len = ((bytes[0] as usize) << 16) | ((bytes[1] as usize) << 8) | bytes[2] as usize;
let kind = match bytes[3] { 0 => "DATA", 1 => "HEADERS", 4 => "SETTINGS", 8 => "WINDOW_UPDATE", _ => "OTHER" };
let stream = u32::from_be_bytes(bytes[5..9].try_into().unwrap()) & 0x7fff_ffff;
print!(" {kind}(stream={stream},len={len},END_STREAM={})", bytes[4] & 1 != 0);
if bytes.len() < 9 + len { break; }
bytes = &bytes[9 + len..];
}
println!();
}
}
#[derive(Clone, PartialEq, prost::Message)]
struct Message {
#[prost(string, tag = "1")]
value: String,
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let addr = server().await;
let trace: Trace = Arc::default();
let stream = TcpStream::connect(addr).await?;
stream.set_nodelay(true)?;
let (mut sender, connection) = hyper::client::conn::http2::Builder::new(TokioExecutor::new())
.handshake(TokioIo::new(Counted { inner: stream, trace: trace.clone() })).await?;
tokio::spawn(async move { let _ = connection.await; });
for round in 0..2 {
if round == 1 { trace.lock().clear(); }
let request = http::Request::post(format!("http://{addr}/echo"))
.body(Full::new(Bytes::from_static(b"hello")))?;
let response = sender.send_request(request).await?;
assert_eq!(response.into_body().collect().await?.to_bytes(), "hello");
}
print_trace("hyper Full body", &trace);
let trace: Trace = Arc::default();
let stream = TcpStream::connect(addr).await?;
stream.set_nodelay(true)?;
let (mut sender, connection) = h2::client::handshake(Counted { inner: stream, trace: trace.clone() }).await?;
tokio::spawn(async move { let _ = connection.await; });
for round in 0..2 {
if round == 1 { trace.lock().clear(); }
sender = sender.ready().await?;
let request = http::Request::post(format!("http://{addr}/echo")).body(())?;
let (response, mut send) = sender.send_request(request, false)?;
send.send_data(Bytes::from_static(b"hello"), true)?;
let mut body = response.await?.into_body();
let mut bytes = Vec::new();
while let Some(chunk) = body.data().await {
let chunk = chunk?;
body.flow_control().release_capacity(chunk.len())?;
bytes.extend_from_slice(&chunk);
}
assert_eq!(bytes, b"hello");
}
print_trace("h2 immediate body", &trace);
let trace: Trace = Arc::default();
let captured = trace.clone();
let channel = tonic::transport::Endpoint::from_shared(format!("http://{addr}"))?
.connect_with_connector(tower::service_fn(move |_uri| {
let trace = captured.clone();
async move {
let inner = TcpStream::connect(addr).await?;
inner.set_nodelay(true)?;
Ok::<_, io::Error>(TokioIo::new(Counted { inner, trace }))
}
})).await?;
let mut grpc = tonic::client::Grpc::new(channel);
for round in 0..2 {
if round == 1 { trace.lock().clear(); }
grpc.ready().await?;
let response: tonic::Response<Message> = grpc.unary(
tonic::Request::new(Message { value: "hello".into() }),
http::uri::PathAndQuery::from_static("/echo.Echo/Unary"),
tonic_prost::ProstCodec::default(),
).await?;
assert_eq!(response.into_inner().value, "hello");
}
print_trace("tonic unary", &trace);
Ok(())
}
Run cargo run.
Actual behavior
hyper Full body: 2 socket writes
write 1: HEADERS(stream=3,len=13,END_STREAM=false)
write 2: DATA(stream=3,len=5,END_STREAM=true)
h2 immediate body: 1 socket writes
write 1: HEADERS(stream=3,len=9,END_STREAM=false) DATA(stream=3,len=5,END_STREAM=true)
tonic unary: 2 socket writes
write 1: HEADERS(stream=3,len=20,END_STREAM=false)
write 2: DATA(stream=3,len=12,END_STREAM=false) DATA(stream=3,len=0,END_STREAM=true)
Expected behavior
A ready small body can share the HEADERS socket write, as in the direct h2 variant. No buffering or delay is needed for a body that returns Pending. If separate writes are required by the API design, an explanation or supported coalescing option would help.
Additional context
The tonic empty final DATA frame is a separate encoder optimization. The hyper-only Full-body variant already puts END_STREAM on its payload DATA frame, but still uses two writes. This reproduction makes no TLS or production-performance claims.
- Vorherrschende Sprache
- Rust
- Sterne
- 16.4k
- Forks
- 1.8k
- Ø Merge
- 1 T. 13 Std.
- Gemergte PRs (30 T.)
- 12
Entwicklungsumgebung
- Kein Dockerfile und keine Docker-Compose-Datei
- Keine Pull-Request-Vorlage
- Beitragsleitfaden lesen
Erste Schritte
- Lesen Sie das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreiben Sie ins Issue, dass Sie es übernehmen — das erspart doppelte Arbeit.
- Forken Sie das Repository und arbeiten Sie in einem Branch.
- Öffnen Sie einen Pull Request, der die Issue-Nummer nennt.
Mehr aus hyperium/hyper
-
C-feature
Schwierigkeit 1/5 Unter einer Stunde Anfängerfreundlichkeit 65/100
hyperium/hyper#2652 · 4 Reaktionen ·
Maintainer antworten meist innerhalb von 1 Tag
-
C-feature
Schwierigkeit 5/5 Über eine Woche Anfängerfreundlichkeit 35/100
Maintainer antworten meist innerhalb von 1 Tag
-
False `SendRequest` readiness for HTTP/1 connectionsEvtl. vergeben @akasakariko hat das vor 2 Tagen übernommen. OffenC-bug
Schwierigkeit 4/5 1-2 Tage Anfängerfreundlichkeit 55/100
hyperium/hyper#4246 · 1 Kommentar ·
Maintainer antworten meist innerhalb von 1 Tag
-
Schwierigkeit 4/5 3-5 Tage Anfängerfreundlichkeit 48/100
Maintainer antworten meist innerhalb von 1 Tag
-
can't upgrade request that came in with `Connection: close, Upgrade`Evtl. vergeben @akasakariko hat das vor 2 Tagen übernommen. OffenC-bug
Schwierigkeit 3/5 1-2 Tage Anfängerfreundlichkeit 62/100
hyperium/hyper#4244 · 4 Kommentare ·
Maintainer antworten meist innerhalb von 1 Tag
Ähnliche Issues
-
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 78/100
Maintainer antworten meist innerhalb von 1 Tag
-
memory_patch_page drops the `#` of headings like `## Notes on C#`Evtl. vergeben @viniciusdsandrade hat das heute übernommen. Offen
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 85/100
akitaonrails/ai-memory#1859 ·
Maintainer antworten meist innerhalb von 1 Tag
-
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 78/100
wealthfolio/wealthfolio#2376 ·
Maintainer antworten meist innerhalb von 1 Tag
-
kind/bug kind/security
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 82/100
spiceai/spiceai#15826 · 1 Kommentar ·
Maintainer antworten meist innerhalb von 1 Tag
-
area:cli bug dotnet good first issue priority:medium
Schwierigkeit 2/5 1-3 Stunden Anfängerfreundlichkeit 76/100
rtk-ai/rtk#4844 · 1 Kommentar ·
Maintainer antworten meist innerhalb von 1 Tag