-
-
Notifications
You must be signed in to change notification settings - Fork 211
feat(client): Add Expect: 100-continue body wrapper #321
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
bountis
wants to merge
1
commit into
hyperium:master
Choose a base branch
from
bountis:feat/client-expect-continue
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| //! This example demonstrates request -> response flow of the `Expect: 100-continue` header | ||
|
|
||
| use std::{convert::Infallible, error::Error}; | ||
|
|
||
| use bytes::Bytes; | ||
| use http::{Method, Request, Response}; | ||
| use http_body_util::{BodyExt, Full}; | ||
| use hyper::{client::conn::http1::handshake, server::conn::http1::Builder, service::service_fn}; | ||
| use hyper_util::{client::expect_continue::wrap, rt::TokioIo}; | ||
| use tokio::net::{TcpListener, TcpStream}; | ||
|
|
||
| async fn echo(req: Request<hyper::body::Incoming>) -> Result<Response<Full<Bytes>>, Infallible> { | ||
| let body = req.into_body().collect().await.unwrap().to_bytes(); | ||
|
|
||
| println!( | ||
| "server read {} body bytes {:?}", | ||
| body.len(), | ||
| String::from_utf8_lossy(&body) | ||
| ); | ||
|
|
||
| Ok(Response::new(Full::new(body))) | ||
| } | ||
|
|
||
| #[tokio::main(flavor = "current_thread")] | ||
| async fn main() -> Result<(), Box<dyn Error + Send + Sync + 'static>> { | ||
| let addr = "127.0.0.1:3000"; | ||
|
|
||
| let listener = TcpListener::bind(addr).await?; | ||
| tokio::spawn(async move { | ||
| let (tcp, _) = listener.accept().await.unwrap(); | ||
| let io = TokioIo::new(tcp); | ||
|
|
||
| if let Err(e) = Builder::new().serve_connection(io, service_fn(echo)).await { | ||
| eprintln!("server error {e:?}"); | ||
| } | ||
| }); | ||
|
|
||
| let stream = TcpStream::connect(addr).await?; | ||
| let io = TokioIo::new(stream); | ||
| let (mut sender, conn) = handshake(io).await?; | ||
| tokio::spawn(async move { | ||
| if let Err(e) = conn.await { | ||
| eprintln!("client connection error: {e:?}"); | ||
| } | ||
| }); | ||
|
|
||
| let req = Request::builder() | ||
| .method(Method::POST) | ||
| .uri("/") | ||
| .header(hyper::header::HOST, addr) | ||
| .body(Full::new(Bytes::from("hi")))?; | ||
|
|
||
| let resp = sender.send_request(wrap(req, None)).await?; | ||
|
|
||
| println!("{:?} {:?}", resp.version(), resp.status()); | ||
| println!("{:#?}", resp.headers()); | ||
|
|
||
| Ok(()) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,189 @@ | ||
| //! Client side `Expect: 100-Continue` support | ||
| //! | ||
| //! This module contains the `ExpectContinueBody` request body wrapper | ||
| //! and the `wrap` convenience helper for building it. | ||
|
|
||
| use std::{ | ||
| pin::Pin, | ||
| task::{Context, Poll}, | ||
| }; | ||
|
|
||
| use futures_channel::oneshot; | ||
| use http::{HeaderValue, Request, StatusCode, header}; | ||
| use http_body::{Body, Frame}; | ||
| use hyper::rt::Sleep; | ||
| use pin_project_lite::pin_project; | ||
|
|
||
| pin_project! { | ||
| /// ExpectContinueBody is a request body wrapper that withholds | ||
| /// its data until the client is cleared to send. | ||
| /// | ||
| /// The body is cleared to send when a `100-continue` is received | ||
| /// (delivered via hyper's `on_informational` hook) or the optional timeout elapses. | ||
| /// | ||
| /// HTTP/1.1 only. Use the `wrap` helper for building this conveniently. | ||
| pub struct ExpectContinueBody<B> { | ||
| #[pin] | ||
| inner: B, | ||
| signal: Option<oneshot::Receiver<()>>, | ||
| sleep: Option<Pin<Box<dyn Sleep>>>, | ||
| released: bool, | ||
| } | ||
| } | ||
|
|
||
| impl<B> ExpectContinueBody<B> { | ||
| pub(crate) fn new( | ||
| inner: B, | ||
| signal: oneshot::Receiver<()>, | ||
| sleep: Option<Pin<Box<dyn Sleep>>>, | ||
| ) -> Self { | ||
| Self { | ||
| inner, | ||
| signal: Some(signal), | ||
| sleep, | ||
| released: false, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl<B: Body> Body for ExpectContinueBody<B> { | ||
| type Data = B::Data; | ||
| type Error = B::Error; | ||
|
|
||
| fn poll_frame( | ||
| self: Pin<&mut Self>, | ||
| cx: &mut Context<'_>, | ||
| ) -> Poll<Option<Result<Frame<B::Data>, B::Error>>> { | ||
| let this = self.project(); | ||
| if !*this.released { | ||
| if let Some(rx) = this.signal.as_mut() { | ||
| if Pin::new(rx).poll(cx).is_ready() { | ||
| *this.released = true; | ||
| } | ||
| } | ||
|
|
||
| if !*this.released { | ||
| if let Some(sleep) = this.sleep.as_mut() { | ||
| if sleep.as_mut().poll(cx).is_ready() { | ||
| *this.released = true; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| if !*this.released { | ||
| return Poll::Pending; | ||
| } | ||
| } | ||
|
|
||
| this.inner.poll_frame(cx) | ||
| } | ||
|
|
||
| fn is_end_stream(&self) -> bool { | ||
| self.inner.is_end_stream() | ||
| } | ||
|
|
||
| fn size_hint(&self) -> http_body::SizeHint { | ||
| self.inner.size_hint() | ||
| } | ||
| } | ||
|
|
||
| /// wrap returns a request whose body is withheld until 100/timeout | ||
| /// | ||
| /// It adds `Expect: 100-continue` header to the request if absent. | ||
| /// Wraps the body in `ExpectContinueBody`. | ||
| /// Registers an `on_informational` hook that releases the body on a 100. | ||
| pub fn wrap<B>( | ||
| req: Request<B>, | ||
| sleep: Option<Pin<Box<dyn Sleep>>>, | ||
| ) -> Request<ExpectContinueBody<B>> { | ||
| let (tx, rx) = oneshot::channel(); | ||
|
|
||
| let (mut parts, body) = req.into_parts(); | ||
| parts | ||
| .headers | ||
| .entry(header::EXPECT) | ||
| .or_insert(HeaderValue::from_static("100-continue")); | ||
|
|
||
| let mut req = Request::from_parts(parts, ExpectContinueBody::new(body, rx, sleep)); | ||
|
|
||
| let tx = std::sync::Mutex::new(Some(tx)); | ||
| hyper::ext::on_informational(&mut req, move |res| { | ||
| if res.status() == StatusCode::CONTINUE { | ||
| if let Some(tx) = tx.lock().unwrap().take() { | ||
| let _ = tx.send(()); | ||
| } | ||
| } | ||
| }); | ||
|
|
||
| req | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use std::time::Duration; | ||
|
|
||
| use bytes::Bytes; | ||
| use futures_util::future::poll_fn; | ||
| use http_body_util::{BodyExt, Full}; | ||
|
|
||
| use super::*; | ||
|
|
||
| use crate::rt::TokioTimer; | ||
| use hyper::rt::Timer; | ||
|
|
||
| #[tokio::test] | ||
| async fn withholds_body_until_signalled() { | ||
| let (tx, rx) = oneshot::channel::<()>(); | ||
| let mut body = std::pin::pin!(ExpectContinueBody::new( | ||
| Full::new(Bytes::from("hi")), | ||
| rx, | ||
| None, | ||
| )); | ||
|
|
||
| let first = poll_fn(|cx| Poll::Ready(body.as_mut().poll_frame(cx))).await; | ||
| assert!(first.is_pending()); | ||
|
|
||
| tx.send(()).unwrap(); | ||
|
|
||
| let frame = body.frame().await.unwrap().unwrap(); | ||
| assert_eq!(frame.into_data().unwrap(), Bytes::from("hi")); | ||
| } | ||
|
|
||
| #[tokio::test(start_paused = true)] | ||
| async fn release_body_with_timeout() { | ||
| let (_tx, rx) = oneshot::channel::<()>(); | ||
|
|
||
| let sleep = TokioTimer.sleep(Duration::from_millis(100)); | ||
| let mut body = std::pin::pin!(ExpectContinueBody::new( | ||
| Full::new(Bytes::from("hi")), | ||
| rx, | ||
| Some(sleep), | ||
| )); | ||
|
|
||
| let first = poll_fn(|cx| Poll::Ready(body.as_mut().poll_frame(cx))).await; | ||
| assert!(first.is_pending()); | ||
|
|
||
| tokio::time::advance(Duration::from_millis(100)).await; | ||
|
|
||
| let frame = body.frame().await.unwrap().unwrap(); | ||
| assert_eq!(frame.into_data().unwrap(), Bytes::from("hi")); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn release_on_signal_cancel() { | ||
| let (tx, rx) = oneshot::channel::<()>(); | ||
| let mut body = std::pin::pin!(ExpectContinueBody::new( | ||
| Full::new(Bytes::from("hi")), | ||
| rx, | ||
| None, | ||
| )); | ||
|
|
||
| let first = poll_fn(|cx| Poll::Ready(body.as_mut().poll_frame(cx))).await; | ||
| assert!(first.is_pending()); | ||
|
|
||
| drop(tx); | ||
|
|
||
| let frame = body.frame().await.unwrap().unwrap(); | ||
| assert_eq!(frame.into_data().unwrap(), Bytes::from("hi")); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why accept an
Option? Should we not nudge people harder to supply a timeout?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm, yes, this should probably be stricter and require a timeout as the RFC also states that
client SHOULD NOT wait for an indefinite period before sending the content.I can modify
wrapthen to accept a timer + a duration.ExpectContinueBody::newcan probably continue to accept the option since it's private to the crate and the signal/cancel tests useNone, or do you want me to change that too?