HTTP/2 client sends HEADERS and an immediately ready Full body in separate socket writes
I maintainer di solito rispondono entro 1 giorno
Nessuno ha ancora preso questa issue.
Valutazione
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Idoneità per principianti
- 52/100
- Tipo di issue
- Funzionalità
- Chiarezza
- Abbastanza chiara
- Stato di attività
- Attiva
- Stack tecnologico
- rust
- Ambito
- backend, networking, performance
Direzione di ricerca
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.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Descrizione
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.
- Lingua principale
- Rust
- Stelle
- 16.4k
- Fork
- 1.8k
- Merge medio
- 1g 13h
- PR unite (30g)
- 12
Preparare l'ambiente
- Nessun Dockerfile né file Docker Compose
- Nessun modello di pull request
- Leggi la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Altre issue di hyperium/hyper
-
C-feature
Difficoltà 1/5 Meno di un'ora Idoneità per principianti 65/100
hyperium/hyper#2652 · 4 reazioni ·
I maintainer di solito rispondono entro 1 giorno
-
C-feature
Difficoltà 5/5 Più di una settimana Idoneità per principianti 35/100
I maintainer di solito rispondono entro 1 giorno
-
False `SendRequest` readiness for HTTP/1 connectionsForse già presa @akasakariko l’ha presa 2 giorni fa. ApertaC-bug
Difficoltà 4/5 1-2 giorni Idoneità per principianti 55/100
hyperium/hyper#4246 · 1 commento ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 4/5 3-5 giorni Idoneità per principianti 48/100
I maintainer di solito rispondono entro 1 giorno
-
can't upgrade request that came in with `Connection: close, Upgrade`Forse già presa @akasakariko l’ha presa 2 giorni fa. ApertaC-bug
Difficoltà 3/5 1-2 giorni Idoneità per principianti 62/100
hyperium/hyper#4244 · 4 commenti ·
I maintainer di solito rispondono entro 1 giorno
Tutte le issue di hyperium/hyper
Issue simili
-
area:cli bug dotnet good first issue priority:medium
Difficoltà 2/5 1-3 ore Idoneità per principianti 76/100
rtk-ai/rtk#4844 · 1 commento ·
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 78/100
delta-io/delta-kernel-rs#3757 ·
I maintainer di solito rispondono entro 3 giorni
-
area: library data-loss type: bug
Difficoltà 2/5 1-3 ore Idoneità per principianti 72/100
alplabai/signex#1740 · 1 commento ·
I maintainer di solito rispondono entro 1 giorno
-
test(fslc): the unreadable mutate catalog test pins the Unix I/O error text and fails on WindowsForse già presa @rizumita l’ha presa oggi. Aperta
Difficoltà 2/5 1-3 ore Idoneità per principianti 82/100
I maintainer di solito rispondono entro 1 giorno
-
Difficoltà 2/5 1-3 ore Idoneità per principianti 69/100
I maintainer di solito rispondono entro 1 giorno