diff --git a/Cargo.lock b/Cargo.lock index bac659af4..e74a023af 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4569,11 +4569,9 @@ dependencies = [ "http-body-util", "hyper", "hyper-util", - "pin-project-lite", "test-log", "tokio", "tokio-util", - "tracing", "wrpc-test", "wrpc-transport", ] @@ -4593,6 +4591,7 @@ dependencies = [ "bytes", "futures", "http", + "http-body-util", "hyper", "hyper-util", "quinn", diff --git a/Cargo.toml b/Cargo.toml index b6e6d7bec..644d8d7fd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -131,7 +131,7 @@ wrpc-test = { workspace = true, features = [ "quic", "webtransport", ] } -wrpc-http = { workspace = true, features = ["client", "http2", "server"] } +wrpc-http = { workspace = true, features = ["server"] } wrpc-transport = { workspace = true, features = ["net"] } [workspace.dependencies] diff --git a/SPEC.md b/SPEC.md index 4f2e3c681..c30f83445 100644 --- a/SPEC.md +++ b/SPEC.md @@ -139,9 +139,9 @@ A single WebTransport session MAY carry multiple concurrent invocations. ### HTTP -HTTP relies on [Framed stream specification](#framed-stream-specification) to map an HTTP request-response exchange to wRPC invocations, one after another. +HTTP relies on [Framed stream specification](#framed-stream-specification) to map each HTTP request-response exchange to exactly one wRPC invocation. -The client MUST send a `POST` request, which carries one or more invocations (see [Framed stream specification](#framed-stream-specification)), and MAY send a new one per invocation, with the request body carrying the data sent by the client and the response body carrying the data sent by the server. The end of the request or response body communicates the end of transmit. +The client MUST send one `POST` request per invocation, with the request body carrying the data sent by the client and the response body carrying the data sent by the server. The end of the request or response body communicates the end of transmit. A receiver MUST treat data following the invocation in a body as an error. To close the exchange in both directions (see [Framed stream specification](#framed-stream-specification)), a peer SHOULD reset its stream with an error code other than `NO_ERROR`, for example, `RST_STREAM` with `INTERNAL_ERROR` in HTTP/2. Where the exchange has no stream of its own, as in HTTP/1.1, a peer MUST close the connection instead. diff --git a/benches/bench.rs b/benches/bench.rs index 9bac2a21a..db4ac9898 100644 --- a/benches/bench.rs +++ b/benches/bench.rs @@ -1,5 +1,4 @@ -use core::convert::Infallible; -use core::future; +use core::pin::Pin; use std::fs; use std::path::PathBuf; @@ -7,10 +6,17 @@ use std::process::Command; use std::sync::{Arc, Mutex, PoisonError}; use std::time::Instant; -use anyhow::{Context as _, bail, ensure}; +use anyhow::{Context as _, anyhow, ensure}; +use bytes::Bytes; use criterion::measurement::WallTime; use criterion::{BenchmarkGroup, Criterion}; -use hyper::service; +use http::request::Parts; +use http_body_util::BodyExt; +use http_body_util::combinators::UnsyncBoxBody; +use hyper::body::Incoming; +use hyper::client::conn::http2::SendRequest; +use hyper_util::client::legacy::ResponseFuture; +use hyper_util::client::legacy::connect::HttpConnector; use hyper_util::rt::TokioExecutor; use hyper_util::rt::tokio::WithHyperIo; use tokio::io::{AsyncRead, AsyncWrite}; @@ -18,9 +24,11 @@ use tokio::net::{TcpStream, UnixListener}; use tokio::runtime::{Handle, Runtime}; use tokio::task::JoinHandle; use tokio::try_join; +use tokio_util::codec::{Decoder, Encoder}; use wasmtime::component::{Component, Linker, ResourceTable}; use wasmtime_wasi::{WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView}; -use wrpc_transport::{Framed, Header, Listener}; +use wrpc_http::{Body, Client}; +use wrpc_transport::{Codec, Encode, Framed, Header, Invoke, Listener, Receive, Serve, Transmit}; mod ping_bindings_wrpc { wit_bindgen_wrpc::generate!({ @@ -81,19 +89,18 @@ enum Func { } impl Func { - async fn call( - self, - clt: &mut Framed, - ) -> anyhow::Result<()> { + async fn call(self, clt: C) -> anyhow::Result<()> + where + C: Invoke<<() as Encode>::Encoder> + Invoke<<(&'static str,) as Encode>::Encoder>, + { match self { - Self::Ping => ping_bindings_wrpc::wrpc_bench::bench::ping::ping(&mut *clt) + Self::Ping => ping_bindings_wrpc::wrpc_bench::bench::ping::ping(clt) .await .context("failed to call `ping`"), Self::Greet => { - let greeting = - greet_bindings_wrpc::wrpc_bench::bench::greet::greet(&mut *clt, "test") - .await - .context("failed to call `greet`")?; + let greeting = greet_bindings_wrpc::wrpc_bench::bench::greet::greet(clt, "test") + .await + .context("failed to call `greet`")?; ensure!( greeting == "Hello, test", "unexpected greeting `{greeting}`" @@ -103,6 +110,25 @@ impl Func { } } + fn handle<'a, S: Serve + Send + 'a>( + self, + handler: &impl Handler, + instance: &str, + name: &str, + srv: S, + ) -> Pin> + Send + 'a>> { + let res = match self { + Self::Ping => ping_bindings_wrpc::handle(handler, instance, name, srv) + .map(|fut| Box::pin(fut) as Pin + Send>>), + Self::Greet => greet_bindings_wrpc::handle(handler, instance, name, srv) + .map(|fut| Box::pin(fut) as Pin + Send>>), + }; + res.unwrap_or_else(|_| { + let err = anyhow!("`{instance}#{name}` is not exported"); + Box::pin(async { Err(err) }) + }) + } + async fn call_direct(self, handler: &WasmHandler) { match self { Self::Ping => handler.ping().await.expect("failed to call handler"), @@ -297,22 +323,7 @@ impl Tasks { self.spawn(async move { let mut lis = Listener::new(tx, rx); while let Some((Header { instance, name }, srv)) = lis.accept().await? { - match func { - Func::Ping => { - let Ok(fut) = ping_bindings_wrpc::handle(&handler, &instance, &name, srv) - else { - bail!("`{instance}#{name}` is not exported"); - }; - fut.await?; - } - Func::Greet => { - let Ok(fut) = greet_bindings_wrpc::handle(&handler, &instance, &name, srv) - else { - bail!("`{instance}#{name}` is not exported"); - }; - fut.await?; - } - } + func.handle(&handler, &instance, &name, srv).await?; } Ok(()) }); @@ -327,6 +338,74 @@ impl Tasks { } } +/// Client invoking functions with HTTP/1 requests sent by a pooling client +struct Http1<'a> { + clt: + &'a hyper_util::client::legacy::Client>, + parts: Parts, +} + +impl<'a, E: Transmit + Send + 'static> Invoke for Http1<'a> { + type Invocation = wrpc_http::Invocation; + + fn invoke( + self, + codec: Codec, + instance: &str, + func: &str, + params: T, + ) -> impl Future)>> + use<'a, E, D, T> + where + E: Encoder, + D: Decoder + Receive, + { + let Self { clt, parts } = self; + Client { + parts, + send: |req: http::Request>| clt.request(req.map(BodyExt::boxed_unsync)), + } + .invoke(codec, instance, func, params) + } +} + +/// Client invoking functions with HTTP/2 requests sent on a connection +struct Http2<'a> { + sender: &'a mut SendRequest>, + parts: Parts, +} + +impl<'a, E: Transmit + Send + 'static> Invoke for Http2<'a> { + type Invocation = wrpc_http::Invocation< + Pin>> + Send + 'a>>, + Incoming, + D, + >; + + fn invoke( + self, + codec: Codec, + instance: &str, + func: &str, + params: T, + ) -> impl Future)>> + use<'a, E, D, T> + where + E: Encoder, + D: Decoder + Receive, + { + let Self { sender, parts } = self; + Client { + parts, + send: |req: http::Request>| { + Box::pin(async move { + sender.ready().await?; + sender.send_request(req.map(BodyExt::boxed_unsync)).await + }) as Pin + Send>> + }, + } + .invoke(codec, instance, func, params) + } +} + fn bench_invoke( g: &mut BenchmarkGroup, rt: &Runtime, @@ -342,12 +421,22 @@ fn bench_invoke( ) -> anyhow::Result<()> { let (tx, rx) = rt.block_on(connect)?; let mut clt = Framed::new(tx, rx); + bench_calls(g, rt, tasks, transport, async || func.call(&mut clt).await) +} + +fn bench_calls( + g: &mut BenchmarkGroup, + rt: &Runtime, + tasks: &Tasks, + transport: &str, + mut call: impl AsyncFnMut() -> anyhow::Result<()>, +) -> anyhow::Result<()> { g.bench_function(transport, |b| { b.iter_custom(|n| { rt.block_on(async { let start = Instant::now(); for _ in 0..n { - if let Err(err) = func.call(&mut clt).await { + if let Err(err) = call().await { panic!("{:?}", tasks.check().err().unwrap_or(err)); } } @@ -503,25 +592,22 @@ fn bench_http1( stream .set_nodelay(true) .context("failed to set TCP_NODELAY")?; - let svc = service::service_fn({ - let tasks = tasks.clone(); - let handler = handler.clone(); - move |req| { - let (res, tx, rx) = wrpc_http::accept(req.into_body()); - tasks.serve(func, tx, rx, handler.clone()); - future::ready(Ok::<_, Infallible>(res)) - } - }); - let conn = hyper::server::conn::http1::Builder::new() - .serve_connection(WithHyperIo::new(stream), svc); - tasks.spawn(async move { conn.await.context("failed to serve HTTP/1 connection") }); + let handler = handler.clone(); + tasks.spawn(wrpc_test::serve_http1( + stream, + move |_, Header { instance, name }, srv| { + func.handle(&handler, &instance, &name, srv) + }, + )); } } }); - bench_invoke(g, &rt, &tasks, "http1", func, async { - let (req, tx) = wrpc_http::request(parts.clone()); - let rx = wrpc_http::response(clt.request(req)); - Ok((tx, rx)) + bench_calls(g, &rt, &tasks, "http1", async || { + func.call(Http1 { + clt: &clt, + parts: parts.clone(), + }) + .await }) } @@ -535,7 +621,7 @@ fn bench_http2( let addr = lis .local_addr() .context("failed to query listener address")?; - let ((sender, conn), (stream, _)) = rt + let ((mut sender, conn), (stream, ..)) = rt .block_on(async { try_join!( async { @@ -557,20 +643,21 @@ fn bench_http2( conn.await .context("failed to drive HTTP/2 client connection") }); - tasks.spawn({ - let tasks = tasks.clone(); - async move { - wrpc_http::serve(WithHyperIo::new(stream), |_, _, tx, rx| { - tasks.serve(func, tx, rx, handler.clone()); - }) - .await - .context("failed to serve HTTP/2 connection") - } + tasks.spawn(async move { + wrpc_http::serve( + WithHyperIo::new(stream), + move |_, Header { instance, name }, srv| func.handle(&handler, &instance, &name, srv), + ) + .await + .context("failed to serve HTTP/2 connection") }); let (parts, ()) = http::Request::new(()).into_parts(); - bench_invoke(g, &rt, &tasks, "http2", func, async { - let (tx, rx) = wrpc_test::http_open(sender.clone(), parts.clone()).await?; - Ok((tx, rx)) + bench_calls(g, &rt, &tasks, "http2", async || { + func.call(Http2 { + sender: &mut sender, + parts: parts.clone(), + }) + .await }) } diff --git a/crates/http/Cargo.toml b/crates/http/Cargo.toml index 307ab987c..c13e6d8ee 100644 --- a/crates/http/Cargo.toml +++ b/crates/http/Cargo.toml @@ -10,9 +10,7 @@ license.workspace = true repository.workspace = true [features] -default = ["client", "http2", "server"] -client = ["dep:hyper", "hyper/client"] -http2 = ["hyper?/http2"] +default = ["server"] server = [ "dep:hyper", "dep:hyper-util", @@ -29,10 +27,9 @@ http-body = { workspace = true } http-body-util = { workspace = true } hyper = { workspace = true, optional = true } hyper-util = { workspace = true, optional = true } -pin-project-lite = { workspace = true } -tokio = { workspace = true, features = ["io-util"] } -tokio-util = { workspace = true, features = ["io"] } -tracing = { workspace = true, features = ["attributes"] } +tokio = { workspace = true } +tokio-util = { workspace = true, features = ["codec", "io"] } +wrpc-transport = { workspace = true } [dev-dependencies] anyhow = { workspace = true } @@ -46,4 +43,3 @@ hyper-util = { workspace = true, features = [ test-log = { workspace = true, features = ["color", "log", "trace"] } tokio = { workspace = true, features = ["macros", "net", "rt-multi-thread", "sync"] } wrpc-test = { workspace = true, features = ["http"] } -wrpc-transport = { workspace = true } diff --git a/crates/http/src/lib.rs b/crates/http/src/lib.rs index 1a7af27a0..b1ae1fc6c 100644 --- a/crates/http/src/lib.rs +++ b/crates/http/src/lib.rs @@ -1,201 +1,525 @@ +#![allow(clippy::type_complexity)] + //! wRPC HTTP transport -use core::pin::Pin; +use core::future::poll_fn; +use core::pin::{Pin, pin}; use core::task::{Context, Poll, ready}; use bytes::{Bytes, BytesMut}; -use futures::stream::BoxStream; -use futures::{StreamExt as _, TryStreamExt as _, stream}; +use futures::channel::oneshot; +use futures::{Stream, StreamExt as _, TryStreamExt as _}; use http::HeaderValue; use http::header::CONTENT_TYPE; -use http_body::Frame; -use http_body_util::combinators::MapErr; -use http_body_util::{BodyDataStream, BodyExt as _}; -use pin_project_lite::pin_project; -use tokio::io::{DuplexStream, duplex}; -use tokio_util::io::{StreamReader, poll_read_buf}; - -/// Body buffer size -pub const DEFAULT_BODY_BUFFER_SIZE: usize = 8192; +use http_body::{Frame, SizeHint}; +use http_body_util::combinators::{MapErr, UnsyncBoxBody}; +use http_body_util::{BodyDataStream, BodyExt}; +use tokio::io::{AsyncRead, ReadBuf}; +use tokio_util::codec::{Decoder, Encoder, FramedRead}; +use tokio_util::io::StreamReader; +use wrpc_transport::{ + Codec, FrameDecoder, FrameEncoder, FrameRef, Header, HeaderDecoder, HeaderEncoder, HeaderRef, + Invoke, Receipt, Receive, Serve, Transmit, error_data_after_end, receive, +}; /// Media type of wRPC request and response bodies pub const MEDIA_TYPE: &str = "application/vnd.bytecodealliance.wrpc"; -/// Reader of the data of a request body, see [accept] -pub type RequestBodyReader = StreamReader< +/// Size of the buffered data, at which a [Body] stops transmitting until the data is taken +const MAX_BUFFERED: usize = 1 << 16; + +/// Reader of the data of a request or response body +pub type BodyReader = StreamReader< BodyDataStream::Error) -> std::io::Error>>, ::Data, >; -/// Reader of the data of a response body, see [response] -pub type ResponseBodyReader<'a> = StreamReader>, Bytes>; - -pin_project! { - /// Body streaming the data written to the [DuplexStream] returned by [`OutgoingBody::new`] - #[project = OutgoingBodyProj] - #[derive(Debug)] - pub struct OutgoingBody { - buffer: BytesMut, - #[pin] - stream: DuplexStream, - } +/// Body transmitting a value, the parameters of a [Client] request or the results of a [Server] +/// response, and the asynchronous values nested in it, using `E` +pub struct Body { + enc: E, + path: Vec, + buf: BytesMut, + sent: SentSignal, } -impl OutgoingBody { - /// Returns the body and the writer of its data - #[must_use] - pub fn new() -> (Self, DuplexStream) { - let (rx, tx) = duplex(DEFAULT_BODY_BUFFER_SIZE); - ( - Self { - buffer: BytesMut::default(), - stream: rx, +impl Unpin for Body {} + +impl Body { + fn new(mut enc: E, header: Option>, value: T) -> std::io::Result + where + E: Encoder, + { + let mut buf = BytesMut::default(); + if let Some(header) = header { + HeaderEncoder.encode(header, &mut buf)?; + } + let mut data = BytesMut::default(); + enc.encode(value, &mut data)?; + for data in data.chunks(usize::try_from(u32::MAX).unwrap_or(usize::MAX)) { + FrameEncoder.encode(FrameRef { path: &[], data }, &mut buf)?; + } + FrameEncoder.encode( + FrameRef { + path: &[], + data: &[], }, - tx, - ) + &mut buf, + )?; + Ok(Self { + enc, + path: Vec::default(), + buf, + sent: SentSignal::default(), + }) } } -impl http_body::Body for OutgoingBody { +impl http_body::Body for Body { type Data = Bytes; type Error = std::io::Error; fn poll_frame( - mut self: Pin<&mut Self>, + self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll, Self::Error>>> { - let this = self.as_mut().project(); - this.buffer.reserve(DEFAULT_BODY_BUFFER_SIZE); - ready!(poll_read_buf(this.stream, cx, this.buffer))?; - let buf = self.buffer.split().freeze(); - if buf.is_empty() { + let Self { + enc, + path, + buf, + sent, + } = self.get_mut(); + if !sent.done + && let Some(tx) = &mut sent.tx + && tx.poll_canceled(cx).is_ready() + { + return Poll::Ready(Some(Err(std::io::Error::new( + std::io::ErrorKind::BrokenPipe, + "invocation dropped", + )))); + } + let mut closed = enc.is_closed(); + while !closed && buf.len() < MAX_BUFFERED { + let n = buf.len(); + match enc.poll_transmit(cx, path, buf) { + Poll::Ready(Ok(())) => closed = true, + Poll::Ready(Err(err)) => return Poll::Ready(Some(Err(err))), + Poll::Pending if buf.len() == n => break, + Poll::Pending => {} + } + } + sent.done = closed; + if !buf.is_empty() { + Poll::Ready(Some(Ok(Frame::data(buf.split().freeze())))) + } else if closed { Poll::Ready(None) } else { - Poll::Ready(Some(Ok(Frame::data(buf)))) + Poll::Pending + } + } + + fn is_end_stream(&self) -> bool { + self.buf.is_empty() && self.enc.is_closed() + } + + fn size_hint(&self) -> SizeHint { + let n = u64::try_from(self.buf.len()).unwrap_or(u64::MAX); + if self.enc.is_closed() { + SizeHint::with_exact(n) + } else { + let mut hint = SizeHint::default(); + hint.set_lower(n); + hint } } } -/// Accepts a wRPC request with `body`, returning the response to send without waiting for the -/// request body, with content type [`MEDIA_TYPE`], the response body writer and the request body -/// reader +/// Signal of a request body, which was handed out in full +#[derive(Default)] +struct SentSignal { + tx: Option>, + done: bool, +} + +impl Drop for SentSignal { + fn drop(&mut self) { + if let Some(tx) = self.tx.take() + && self.done + { + _ = tx.send(()); + } + } +} + +/// Receives the invocation header of a request with `body`, returning it along with the [Server] +/// of the invocation /// -/// Read the request body to its end before dropping its reader: dropping it earlier may cancel -/// the response before the peer received it. -pub fn accept( - body: T, -) -> ( - http::Response, - DuplexStream, - RequestBodyReader, -) +/// Receive the parameters from its frames to their end before dropping them: dropping them +/// earlier may cancel the response before the peer received it. +pub async fn accept(body: T) -> std::io::Result<(Header, Server)> where - T: http_body::Body, - T::Error: Into>, + T: http_body::Body>> + Unpin, { - let rx = StreamReader::new(body.map_err(io_error as fn(_) -> _).into_data_stream()); - let (body, tx) = OutgoingBody::new(); - let mut res = http::Response::new(body); - res.headers_mut() - .insert(CONTENT_TYPE, HeaderValue::from_static(MEDIA_TYPE)); - (res, tx, rx) + let rx = StreamReader::new(body.map_err(into_io_error as fn(_) -> _).into_data_stream()); + let mut rx = FramedRead::new(rx, HeaderDecoder::default()); + let Some(header) = rx.try_next().await? else { + return Err(std::io::ErrorKind::UnexpectedEof.into()); + }; + let rx = rx.map_decoder(|_| FrameDecoder::default()); + Ok((header, Server { rx })) +} + +/// Reader of the data of the body of the response a future resolves to, which it awaits on first +/// read +struct ResponseReader { + res: Option>>, + body: Option>>>, } -/// Returns a `POST` wRPC request with `parts`, with content type [`MEDIA_TYPE`] unless `parts` set -/// one, and its body writer +impl AsyncRead for ResponseReader +where + F: Future, Err>>, + B: http_body::Body>>, + Err: Into>, +{ + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + let Self { res, body } = self.get_mut(); + if let Some(fut) = res { + let ret = ready!(fut.as_mut().poll(cx)); + *res = None; + let ret = ret.map_err(into_io_error)?; + *body = Some(Box::pin(StreamReader::new( + ret.into_body() + .map_err(into_io_error as fn(_) -> _) + .into_data_stream(), + ))); + } + match body { + Some(body) => body.as_mut().poll_read(cx, buf), + None => Poll::Ready(Ok(())), + } + } +} + +/// Client invoking a function with a `POST` request with `parts`, with content type +/// [`MEDIA_TYPE`] unless `parts` set one, sent by `send`, such as a closure calling +/// `send_request` of a hyper HTTP/1 or HTTP/2 connection +/// +/// The parameters are encoded before [`Invoke::invoke`] returns. +/// +/// The response status and headers are not checked: to act on them, map the response `send` +/// resolves to, failing it with an error. +pub struct Client { + /// Parts of the request + pub parts: http::request::Parts, + /// Function sending the request and returning a future resolving to its response + pub send: F, +} + +impl Invoke for Client +where + E: Transmit, + F: FnOnce(http::Request>) -> Fut, + Fut: Future, Err>>, + B: http_body::Body>>, + Err: Into>, +{ + type Invocation = Invocation; + + fn invoke( + self, + codec: Codec, + instance: &str, + func: &str, + params: T, + ) -> impl Future)>> + + use + where + E: Encoder, + D: Decoder + Receive, + { + let Self { mut parts, send } = self; + let Codec { enc, dec } = codec; + let body = Body::new( + enc, + Some(HeaderRef { + instance, + name: func, + }), + params, + ); + parts.method = http::Method::POST; + parts + .headers + .entry(CONTENT_TYPE) + .or_insert(HeaderValue::from_static(MEDIA_TYPE)); + async move { + let mut body = body?; + let (tx, sent) = oneshot::channel(); + body.sent.tx = Some(tx); + let res = send(http::Request::from_parts(parts, body)); + let rx = ResponseReader { + res: Some(Box::pin(res)), + body: None, + }; + let rx = FramedRead::new(rx, FrameDecoder::default()); + let (results, rx) = receive(dec, rx).await?; + Ok(( + results, + Invocation { + sent: Some(sent), + rx: Some(rx), + rest: None, + }, + )) + } + } +} + +/// Future receiving the asynchronous results and the end of the response body of a [Client] +/// invocation +/// +/// It also completes once the request body was sent, dropping it before fails the request body. #[must_use] -pub fn request(mut parts: http::request::Parts) -> (http::Request, DuplexStream) { - let (body, tx) = OutgoingBody::new(); - parts.method = http::Method::POST; - parts - .headers - .entry(CONTENT_TYPE) - .or_insert(HeaderValue::from_static(MEDIA_TYPE)); - (http::Request::from_parts(parts, body), tx) +pub struct Invocation { + sent: Option>, + rx: Option, FrameDecoder>, ResponseReader, D>>, + rest: Option, FrameDecoder>>, } -/// Returns a reader of the body of the response `res` resolves to +impl Future for Invocation +where + F: Future, Err>>, + B: http_body::Body>>, + Err: Into>, + D: Receive, +{ + type Output = std::io::Result<()>; + + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + let Self { sent, rx, rest } = self.get_mut(); + if let Some(fut) = rx + && let Poll::Ready(res) = Pin::new(fut).poll(cx) + { + res?; + *rest = rx.take().map(Receipt::into_inner); + } + if let Poll::Ready(Err(err)) = poll_eof(cx, rest) { + return Poll::Ready(Err(err)); + } + if let Some(fut) = sent + && let Poll::Ready(res) = Pin::new(fut).poll(cx) + { + res.map_err(|_| { + std::io::Error::new(std::io::ErrorKind::BrokenPipe, "request body was not sent") + })?; + *sent = None; + } + if sent.is_some() || rx.is_some() || rest.is_some() { + return Poll::Pending; + } + Poll::Ready(Ok(())) + } +} + +/// Server serving the invocation, which a request body carries, see [accept], with the response +/// transmitting the results /// -/// The response is awaited on first read, so that the request body can be sent first. Its status -/// and headers are not checked: to act on them, map `res`, failing reads with its error. -pub fn response<'a>( - res: impl Future< - Output = Result< - http::Response< - impl http_body::Body< - Data = Bytes, - Error: Into>, - > + Send - + 'a, - >, - impl Into>, - >, - > + Send - + 'a, -) -> ResponseBodyReader<'a> { - let body = stream::once(Box::pin(async move { - let res = res.await.map_err(io_error)?; - Ok::<_, std::io::Error>(res.into_body().map_err(io_error).into_data_stream()) - })) - .try_flatten(); - StreamReader::new(body.boxed()) -} - -/// Serves wRPC requests on HTTP/2 connection `io`, calling `f` with the parts of each, the parts -/// of its response (as [accept] returns them) and the byte streams [accept] returns for its body +/// The rest of the request body is received while the response body is polled, which fails on +/// an ingress error or on data following the invocation. +pub struct Server { + /// Frames of the invocation following its header + pub rx: FramedRead, FrameDecoder>, +} + +impl Server +where + T: http_body::Body>> + Unpin, +{ + /// Serves the invocation using `codec` by calling `f` with its parameters, see + /// [`Codec::serve`], returning the response transmitting the results + /// + /// Unlike [`Serve`], this does not require [`Send`] values and futures. + pub async fn serve( + self, + codec: Codec, + f: impl AsyncFnOnce(D::Item) -> Result, + ) -> Result>>, Err> + where + E: Transmit + Encoder, + D: Decoder + Receive, + Err: From, + { + let Self { rx } = self; + let Codec { enc, dec } = codec; + let (params, rx) = receive(dec, rx).await?; + let mut rx = Some(rx); + let mut rest = None; + let results = { + let mut results = pin!(f(params)); + poll_fn(|cx| { + if let Some(fut) = &mut rx + && let Poll::Ready(res) = Pin::new(fut).poll(cx) + { + res?; + rest = rx.take().map(Receipt::into_inner); + } + results.as_mut().poll(cx) + }) + .await? + }; + let body = Body::new(ResultsEncoder { enc, rx, rest }, None, results)?; + let mut res = http::Response::new(body); + res.headers_mut() + .insert(CONTENT_TYPE, HeaderValue::from_static(MEDIA_TYPE)); + Ok(res) + } +} + +impl Serve for Server +where + T: http_body::Body>> + + Unpin + + Send + + 'static, +{ + type Output = http::Response>; + + fn serve( + self, + codec: Codec, + f: impl FnOnce(D::Item) -> Fut + Send, + ) -> impl Future> + Send + where + E: Transmit + Encoder + Send + 'static, + D: Decoder + Receive + Send + 'static, + D::Item: Send, + Fut: Future> + Send, + Err: From, + { + let res = Server::serve(self, codec, async move |params| f(params).await); + async move { + let res = res.await?; + Ok(res.map(BodyExt::boxed_unsync)) + } + } +} + +/// Encoder of the results [`Server::serve`] responds with, which receives the asynchronous +/// parameters and the end of the request body while transmitting +pub struct ResultsEncoder { + enc: E, + rx: Option, FrameDecoder>, BodyReader, D>>, + rest: Option, FrameDecoder>>, +} + +impl Encoder for ResultsEncoder +where + E: Encoder, + T: http_body::Body, +{ + type Error = std::io::Error; + + fn encode(&mut self, item: R, dst: &mut BytesMut) -> std::io::Result<()> { + self.enc.encode(item, dst) + } +} + +impl Transmit for ResultsEncoder +where + E: Transmit, + T: http_body::Body>> + Unpin, + D: Receive, +{ + fn poll_transmit( + &mut self, + cx: &mut Context<'_>, + path: &mut Vec, + dst: &mut BytesMut, + ) -> Poll> { + if let Some(rx) = &mut self.rx + && let Poll::Ready(res) = Pin::new(rx).poll(cx) + { + res?; + self.rest = self.rx.take().map(Receipt::into_inner); + } + if let Poll::Ready(Err(err)) = poll_eof(cx, &mut self.rest) { + return Poll::Ready(Err(err)); + } + if !self.enc.is_closed() { + ready!(self.enc.poll_transmit(cx, path, dst))?; + } + if self.rx.is_some() || self.rest.is_some() { + return Poll::Pending; + } + Poll::Ready(Ok(())) + } + + fn is_closed(&self) -> bool { + self.rx.is_none() && self.rest.is_none() && self.enc.is_closed() + } +} + +/// Serves wRPC requests on HTTP/2 connection `io`, calling `f` with the parts of each and the +/// invocation header and [Server] [accept] returns for its body, and sending the response `f` +/// resolves to /// -/// The response is sent once `f` returns. As with [accept], read each request body to its end -/// before dropping its reader. +/// The stream of a request is reset if [accept] or `f` fails. #[cfg(feature = "server")] -pub async fn serve( +pub fn serve( io: impl hyper::rt::Read + hyper::rt::Write + Unpin, - f: impl Fn( - http::request::Parts, - &mut http::response::Parts, - DuplexStream, - RequestBodyReader, - ), -) -> Result<(), hyper::Error> { + f: impl Fn(http::request::Parts, Header, Server) -> Fut + + Clone + + Send + + 'static, +) -> impl Future> +where + B: http_body::Body>> + + Send + + 'static, + Fut: Future, Err>> + Send + 'static, + Err: Into>, +{ hyper::server::conn::http2::Builder::new(hyper_util::rt::TokioExecutor::default()) .serve_connection( io, hyper::service::service_fn(move |req| { - let (parts, body) = req.into_parts(); - let (res, tx, rx) = accept(body); - let (mut res, body) = res.into_parts(); - f(parts, &mut res, tx, rx); - let res = http::Response::from_parts(res, body); - core::future::ready(Ok::<_, core::convert::Infallible>(res)) + let f = f.clone(); + async move { + let (parts, body) = req.into_parts(); + let (header, srv) = accept(body).await?; + let res = f(parts, header, srv).await.map_err(Into::into)?; + Ok::<_, Box>(res) + } }), ) - .await -} - -/// Sends the wRPC [request] with `parts` on `sender`, returning the request body writer and the -/// response future to pass to [response] -#[cfg(all(feature = "client", feature = "http2"))] -#[tracing::instrument(level = "trace", skip_all)] -pub async fn open( - mut sender: hyper::client::conn::http2::SendRequest, - parts: http::request::Parts, -) -> Result< - ( - DuplexStream, - impl Future, hyper::Error>> + Send, - ), - hyper::Error, -> { - sender.ready().await?; - let (req, tx) = request(parts); - Ok((tx, sender.send_request(req))) -} - -fn io_error(err: impl Into>) -> std::io::Error { +} + +/// Polls `rx` for its end, failing on data +fn poll_eof( + cx: &mut Context<'_>, + rx: &mut Option> + Unpin>, +) -> Poll> { + if let Some(frames) = rx { + let frame = ready!(frames.poll_next_unpin(cx)).transpose()?; + if frame.is_some() { + return Poll::Ready(Err(error_data_after_end())); + } + *rx = None; + } + Poll::Ready(Ok(())) +} + +fn into_io_error(err: impl Into>) -> std::io::Error { let err = match err.into().downcast::() { Ok(err) => return *err, Err(err) => err, }; - #[cfg(any(feature = "client", feature = "server"))] + #[cfg(feature = "server")] if err .downcast_ref::() .is_some_and(hyper::Error::is_timeout) diff --git a/crates/http/tests/loopback.rs b/crates/http/tests/loopback.rs index dc80c3690..3d4f25a9b 100644 --- a/crates/http/tests/loopback.rs +++ b/crates/http/tests/loopback.rs @@ -1,43 +1,124 @@ +use core::time::Duration; + +use std::rc::Rc; + use anyhow::{Context as _, ensure}; -use bytes::Bytes; +use bytes::{Bytes, BytesMut}; +use futures::StreamExt as _; +use futures::future::LocalBoxFuture; +use futures::stream::{self, BoxStream}; use http::header::CONTENT_TYPE; use http::{HeaderValue, StatusCode}; -use http_body_util::{BodyExt as _, Full}; +use http_body::Body as _; +use http_body_util::{BodyExt, Full}; use hyper_util::rt::TokioIo; -use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; -use tokio::sync::mpsc; +use tokio::time::sleep; use tokio::{spawn, try_join}; -use wrpc_http::OutgoingBody; -use wrpc_transport::{Framed, Listener}; +use tokio_util::codec::Encoder as _; +use wrpc_http::{Body, Client}; +use wrpc_transport::{ + Codec, Decode, Encode, FrameEncoder, FrameRef, Header, HeaderEncoder, HeaderRef, invoke, + invoke_blocking, serve, +}; #[test_log::test(tokio::test(flavor = "multi_thread"))] async fn http2() -> anyhow::Result<()> { - wrpc_test::serve_http2(async |parts, sender, srv| { - let open = || wrpc_test::http_open(sender.clone(), parts.clone()); - let (tx, rx) = open().await?; - wrpc_test::assert_single_invocation(tx, rx, wrpc_test::http_accept(&mut *srv)).await?; - wrpc_test::assert_invalid_data_resets(open, async || { - wrpc_test::http_accept(&mut *srv).await - }) - .await - }) + wrpc_test::with_http2( + async |stream| { + wrpc_http::serve(TokioIo::new(stream), |_, header, srv| async move { + if header.name == "baz" { + return serve::<(), (), _, _, _>(srv, async |()| anyhow::Ok(())).await; + } + wrpc_test::serve_http_invocation(header, srv).await + }) + .await + .context("failed to serve HTTP/2 connection") + }, + |parts, mut sender| async move { + sender.ready().await?; + wrpc_test::assert_http_invocation(parts.clone(), |req| sender.send_request(req)) + .await?; + + let mut baz = BytesMut::default(); + HeaderEncoder.encode( + HeaderRef { + instance: "foo", + name: "baz", + }, + &mut baz, + )?; + for path in [&[1][..], &[]] { + let mut buf = baz.clone(); + FrameEncoder.encode(FrameRef { path, data: b"" }, &mut buf)?; + buf.extend_from_slice(&baz); + let body = Full::new(buf.freeze()).map_err(|err| match err {}); + let req = http::Request::from_parts(parts.clone(), body.boxed_unsync()); + sender.ready().await?; + let res = async { + let res = sender.send_request(req).await?; + res.into_body().collect().await + } + .await; + res.expect_err("invalid data must fail the response"); + } + Ok(()) + }, + ) + .await +} + +#[test_log::test(tokio::test(flavor = "multi_thread"))] +async fn unread_params() -> anyhow::Result<()> { + wrpc_test::with_http2( + async |stream| { + wrpc_http::serve(TokioIo::new(stream), |_, _, srv| { + serve::<(BoxStream<'static, Bytes>,), (), _, _, _>(srv, async |(s,)| { + drop(s); + anyhow::Ok(()) + }) + }) + .await + .context("failed to serve HTTP/2 connection") + }, + |parts, mut sender| async move { + let s: BoxStream<'static, Bytes> = Box::pin( + stream::repeat(Bytes::from_static(b"foo")).then(async |buf| { + sleep(Duration::from_millis(10)).await; + buf + }), + ); + sender.ready().await?; + let clt = Client { + parts, + send: |req: http::Request>| { + sender.send_request(req.map(BodyExt::boxed_unsync)) + }, + }; + let res = async { + let ((), io) = invoke::<_, (), _>(clt, "foo", "bar", (s,)).await?; + io.await + }; + res.await + .expect_err("unread parameters must fail the invocation"); + Ok(()) + }, + ) .await } #[test_log::test(tokio::test(flavor = "multi_thread"))] async fn pooling() -> anyhow::Result<()> { wrpc_test::with_http_pooling(|parts, clt, lis| async move { - let (tx, mut rx) = mpsc::channel(16); let accept = async { let (conn, addr) = lis.accept().await.context("failed to accept connection")?; assert!(addr.ip().is_loopback()); - anyhow::Ok(spawn(wrpc_test::serve_http1(conn, tx))) + anyhow::Ok(spawn(wrpc_test::serve_http1(conn, |_, header, srv| { + wrpc_test::serve_http_invocation(header, srv) + }))) }; - let (req, req_tx) = wrpc_http::request(parts); - let req_rx = wrpc_http::response(clt.request(req)); - let (conn, _) = try_join!( + let (conn, ()) = try_join!( accept, - wrpc_test::assert_single_invocation(req_tx, req_rx, wrpc_test::http_accept(&mut rx)) + wrpc_test::assert_http_invocation(parts, |req| clt.request(req)) )?; drop(clt); conn.await.context("connection task panicked")? @@ -48,106 +129,105 @@ async fn pooling() -> anyhow::Result<()> { #[test_log::test(tokio::test(flavor = "multi_thread"))] async fn response_parts() -> anyhow::Result<()> { let serve = async |stream| { - wrpc_http::serve(TokioIo::new(stream), |req, res, mut tx, mut rx| { - res.status = StatusCode::IM_A_TEAPOT; - res.headers.insert("foo", HeaderValue::from_static("bar")); - res.headers - .insert("req-content-type", req.headers[CONTENT_TYPE].clone()); - spawn(async move { - rx.read_to_end(&mut Vec::default()).await?; - tx.write_all(b"baz").await - }); + wrpc_http::serve(TokioIo::new(stream), |req, _, srv| async move { + let mut res = + serve::<(), _, _, _, _>(srv, async |()| anyhow::Ok((Bytes::from_static(b"baz"),))) + .await?; + *res.status_mut() = StatusCode::IM_A_TEAPOT; + let headers = res.headers_mut(); + headers.insert("foo", HeaderValue::from_static("bar")); + headers.insert("req-content-type", req.headers[CONTENT_TYPE].clone()); + anyhow::Ok(res) }) .await - .context("failed to serve connection") + .context("failed to serve HTTP/2 connection") }; - wrpc_test::with_http2(serve, |parts, sender| async move { - let (tx, res) = wrpc_http::open(sender.clone(), parts.clone()).await?; - drop(tx); - let mut buf = Vec::default(); - wrpc_http::response(res).read_to_end(&mut buf).await?; - assert_eq!(buf, b"baz"); + wrpc_test::with_http2(serve, |parts, mut sender| async move { + sender.ready().await?; + let clt = Client { + parts: parts.clone(), + send: |req: http::Request>| sender.send_request(req), + }; + let (buf,) = invoke_blocking::<(), (Bytes,), _>(clt, "foo", "bar", ()).await?; + assert_eq!(buf, "baz"); - let (tx, res) = wrpc_http::open(sender, parts).await?; - drop(tx); - let err = wrpc_http::response(async { - let res = res.await?; - let headers = res.headers(); - assert_eq!(headers[CONTENT_TYPE], wrpc_http::MEDIA_TYPE); - assert_eq!(headers["req-content-type"], wrpc_http::MEDIA_TYPE); - assert_eq!(headers["foo"], "bar"); - ensure!(res.status().is_success(), "status `{}`", res.status()); - Ok(res) - }) - .read_to_end(&mut Vec::default()) - .await - .expect_err("reading results should fail"); + sender.ready().await?; + let clt = Client { + parts, + send: |req: http::Request>| { + let res = sender.send_request(req); + async { + let res = res.await?; + let headers = res.headers(); + assert_eq!(headers[CONTENT_TYPE], wrpc_http::MEDIA_TYPE); + assert_eq!(headers["req-content-type"], wrpc_http::MEDIA_TYPE); + assert_eq!(headers["foo"], "bar"); + ensure!(res.status().is_success(), "status `{}`", res.status()); + Ok(res) + } + }, + }; + let res = invoke_blocking::<(), (Bytes,), _>(clt, "foo", "bar", ()).await; + let err = res.err().context("receiving results should fail")?; assert_eq!(err.to_string(), "status `418 I'm a teapot`"); Ok(()) }) .await } -#[test_log::test(tokio::test(flavor = "multi_thread"))] -async fn body_writer_dropped() -> anyhow::Result<()> { - let (body, mut tx) = OutgoingBody::new(); - tx.write_all(b"foo").await.context("failed to write body")?; - drop(tx); - let res = body.collect().await.context("failed to read body")?; - assert_eq!(res.to_bytes(), "foo"); - Ok(()) -} - #[test_log::test(tokio::test(flavor = "multi_thread"))] async fn buffered() -> anyhow::Result<()> { - struct Transport; - - impl Transport { - async fn request( - &self, - req: http::Request>, - ) -> anyhow::Result<(http::response::Parts, Bytes)> { - let (res, tx, rx) = wrpc_http::accept(req.into_body()); - let (parts, body) = res.into_parts(); - let ((), body) = try_join!( - async { - let mut lis = Listener::new(tx, rx); - let srv = wrpc_test::next_invocation(&mut lis, "foo", "bar").await?; - wrpc_transport::serve::(srv, async |params| { - anyhow::Ok(params) - }) - .await?; - let next = lis.accept().await?; - ensure!(next.is_none(), "unexpected invocation"); - Ok(()) - }, - async { - let body = body.collect().await?; - anyhow::Ok(body) - }, - )?; - Ok((parts, body.to_bytes())) - } - } - - let transport = Transport; let params = Bytes::from(vec![0x42; 65536]); let (parts, ()) = http::Request::new(()).into_parts(); - let (req, tx) = wrpc_http::request(parts); - let rx = wrpc_http::response(async { - let (parts, body) = req.into_parts(); - let body = body.collect().await?; - let req = http::Request::from_parts(parts, Full::new(body.to_bytes())); - let (parts, body) = transport.request(req).await?; - Ok::<_, anyhow::Error>(http::Response::from_parts(parts, Full::new(body))) - }); - let results = wrpc_transport::invoke_blocking::<_, Bytes, _>( - Framed::new(tx, rx), - "foo", - "bar", - params.clone(), - ) - .await?; + let clt = Client { + parts, + send: |req: http::Request>| async { + let size = req.body().size_hint().exact(); + let (parts, body) = req.into_parts(); + let body = body.collect().await?; + let body = body.to_bytes(); + ensure!(size == u64::try_from(body.len()).ok()); + let (Header { instance, name }, srv) = wrpc_http::accept(Full::new(body)).await?; + ensure!(instance == "foo" && name == "bar"); + let res = serve::(srv, async |params| anyhow::Ok(params)).await?; + let (res, body) = res.into_parts(); + let body = body.collect().await?; + ensure!(parts.headers[CONTENT_TYPE] == res.headers[CONTENT_TYPE]); + Ok(http::Response::from_parts(res, Full::new(body.to_bytes()))) + }, + }; + let results = invoke_blocking::(clt, "foo", "bar", params.clone()).await?; assert_eq!(results, params); Ok(()) } + +#[test_log::test(tokio::test)] +async fn local() -> anyhow::Result<()> { + let name = Rc::new(String::from("world")); + let (parts, ()) = http::Request::new(()).into_parts(); + let clt = Client { + parts, + send: |req: http::Request>| async move { + let ( + Header { + instance, + name: func, + }, + srv, + ) = wrpc_http::accept(req.into_body()).await?; + ensure!(instance == "foo" && func == "bar"); + srv.serve( + Codec::< + <(String,) as Encode>::Encoder, + <(LocalBoxFuture<'static, String>,) as Decode>::Decoder, + >::default(), + async |(greeting,)| anyhow::Ok((format!("{}, {name}", greeting.await),)), + ) + .await + }, + }; + let greeting: LocalBoxFuture<'static, String> = Box::pin(async { "Hello".into() }); + let (greeting,) = invoke_blocking::<_, (String,), _>(clt, "foo", "bar", (greeting,)).await?; + assert_eq!(greeting, "Hello, world"); + Ok(()) +} diff --git a/crates/test/Cargo.toml b/crates/test/Cargo.toml index 6179c1ab1..1c440a610 100644 --- a/crates/test/Cargo.toml +++ b/crates/test/Cargo.toml @@ -11,7 +11,13 @@ repository.workspace = true [features] default = ["http", "quic", "webtransport"] -http = ["dep:http", "dep:hyper", "dep:hyper-util", "dep:wrpc-http"] +http = [ + "dep:http", + "dep:http-body-util", + "dep:hyper", + "dep:hyper-util", + "dep:wrpc-http", +] net = ["dep:tempfile", "wrpc-transport/net"] quic = ["dep:quinn"] webtransport = ["dep:quinn", "dep:url", "dep:web-transport-quinn"] @@ -21,6 +27,7 @@ anyhow = { workspace = true } bytes = { workspace = true } futures = { workspace = true } http = { workspace = true, optional = true } +http-body-util = { workspace = true, optional = true } hyper = { workspace = true, features = [ "client", "http1", @@ -43,5 +50,5 @@ tokio-util = { workspace = true, features = ["codec"] } tracing = { workspace = true } url = { workspace = true, optional = true } web-transport-quinn = { workspace = true, optional = true } -wrpc-http = { workspace = true, features = ["client", "http2", "server"], optional = true } +wrpc-http = { workspace = true, features = ["server"], optional = true } wrpc-transport = { workspace = true } diff --git a/crates/test/src/lib.rs b/crates/test/src/lib.rs index 23fff64fb..5b4562b6c 100644 --- a/crates/test/src/lib.rs +++ b/crates/test/src/lib.rs @@ -23,6 +23,10 @@ use wrpc_transport::{ HeaderRef, Listener, invoke, receive, serve, }; +/// Parameters and results of the invocation of [`assert_single_invocation`] and +/// [`assert_http_invocation`] +type FooBar = (Bytes, BoxStream<'static, Bytes>); + /// Maximum number of connections [`serve_until`] serves concurrently const MAX_CONNECTIONS: usize = 64; @@ -203,19 +207,17 @@ pub async fn assert_single_invocation( Box::pin(stream::iter([Bytes::from_static(b"client->server")])); let tx = FramedWrite::new(tx, FrameEncoder); let mut rx = FramedRead::new(rx, FrameDecoder::default()); - let ((results, s), io) = Codec::< - <(Bytes, BoxStream<'static, Bytes>) as Encode>::Encoder, - <(Bytes, BoxStream<'static, Bytes>) as Decode>::Decoder, - >::default() - .invoke( - tx, - &mut rx, - "foo", - "bar", - (Bytes::from_static(b"testbar"), s), - ) - .await - .context("failed to invoke `foo.bar`")?; + let ((results, s), io) = + Codec::<::Encoder, ::Decoder>::default() + .invoke( + tx, + &mut rx, + "foo", + "bar", + (Bytes::from_static(b"testbar"), s), + ) + .await + .context("failed to invoke `foo.bar`")?; assert_eq!(results, b"foo".as_slice()); let (buf, ()) = try_join!( async { anyhow::Ok(s.collect::>().await.concat()) }, @@ -561,59 +563,30 @@ where f(parts, clt, lis).await.context("closure failed") } -/// Opens a wRPC request with `parts` on `sender`, returning its body writer and the response body -/// reader -#[cfg(feature = "http")] -pub async fn http_open( - sender: hyper::client::conn::http2::SendRequest, - parts: http::request::Parts, -) -> Result< - ( - tokio::io::DuplexStream, - wrpc_http::ResponseBodyReader<'static>, - ), - hyper::Error, -> { - let (tx, res) = wrpc_http::open(sender, parts).await?; - Ok((tx, wrpc_http::response(res))) -} - -/// Receives the byte streams of a request from `rx` -#[cfg(feature = "http")] -pub async fn http_accept( - rx: &mut tokio::sync::mpsc::Receiver<( - tokio::io::DuplexStream, - wrpc_http::RequestBodyReader, - )>, -) -> std::io::Result<( - tokio::io::DuplexStream, - wrpc_http::RequestBodyReader, -)> { - rx.recv() - .await - .ok_or_else(|| std::io::ErrorKind::UnexpectedEof.into()) -} - -/// Serves HTTP/1 connection `stream`, sending the byte streams of each request to `tx` +/// Serves HTTP/1 connection `stream` like [`wrpc_http::serve`] serves HTTP/2 connections #[cfg(feature = "http")] -pub async fn serve_http1( +pub async fn serve_http1( stream: TcpStream, - tx: tokio::sync::mpsc::Sender<( - tokio::io::DuplexStream, - wrpc_http::RequestBodyReader, - )>, -) -> anyhow::Result<()> { + f: impl Fn(http::request::Parts, Header, wrpc_http::Server) -> Fut + + Clone + + Send + + 'static, +) -> anyhow::Result<()> +where + B: hyper::body::Body>> + + Send + + 'static, + Fut: Future>> + Send + 'static, +{ hyper::server::conn::http1::Builder::new() .serve_connection( hyper_util::rt::TokioIo::new(stream), hyper::service::service_fn(move |req| { - let (res, body_tx, body_rx) = wrpc_http::accept(req.into_body()); - let tx = tx.clone(); + let f = f.clone(); async move { - tx.send((body_tx, body_rx)) - .await - .map_err(|_| std::io::Error::from(std::io::ErrorKind::BrokenPipe))?; - Ok::<_, std::io::Error>(res) + let (parts, body) = req.into_parts(); + let (header, srv) = wrpc_http::accept(body).await?; + f(parts, header, srv).await } }), ) @@ -621,31 +594,62 @@ pub async fn serve_http1( .context("failed to serve HTTP/1 connection") } +/// A common single-invocation test of HTTP clients, like [`assert_single_invocation`] +/// +/// The invocation request with `parts` is sent using `send` and served by +/// [`serve_http_invocation`]. #[cfg(feature = "http")] -pub async fn serve_http2( - f: impl AsyncFnOnce( - http::request::Parts, - hyper::client::conn::http2::SendRequest, - &mut tokio::sync::mpsc::Receiver<( - tokio::io::DuplexStream, - wrpc_http::RequestBodyReader, - )>, - ) -> anyhow::Result, -) -> anyhow::Result { - let (tx, mut rx) = tokio::sync::mpsc::channel(16); - with_http2( - async |stream| { - wrpc_http::serve( - hyper_util::rt::TokioIo::new(stream), - move |_, _, body_tx, body_rx| { - tx.try_send((body_tx, body_rx)) - .expect("failed to send request byte streams"); - }, - ) - .await - .context("failed to serve HTTP/2 connection") +pub async fn assert_http_invocation( + parts: http::request::Parts, + send: impl FnOnce( + http::Request>, + ) -> Fut, +) -> anyhow::Result<()> +where + B: hyper::body::Body>> + + Send + + 'static, + E: Into>, + Fut: Future, E>> + Send + 'static, +{ + let s: BoxStream<'static, Bytes> = + Box::pin(stream::iter([Bytes::from_static(b"client->server")])); + let clt = wrpc_http::Client { + parts, + send: |req: http::Request>| { + send(req.map(http_body_util::BodyExt::boxed_unsync)) }, - |parts, sender| async move { f(parts, sender, &mut rx).await }, - ) + }; + let ((results, s), io) = + invoke::(clt, "foo", "bar", (Bytes::from_static(b"testbar"), s)) + .await + .context("failed to invoke `foo.bar`")?; + assert_eq!(results, b"foo".as_slice()); + let (buf, ()) = try_join!(async { anyhow::Ok(s.collect::>().await) }, async { + io.await.context("`foo.bar` invocation failed") + },)?; + assert_eq!(buf.concat(), b"server->client"); + Ok(()) +} + +/// Serves the invocation of [`assert_http_invocation`] +#[cfg(feature = "http")] +pub async fn serve_http_invocation( + Header { instance, name }: Header, + srv: wrpc_http::Server, +) -> anyhow::Result>> +{ + ensure!( + instance == "foo" && name == "bar", + "unexpected invocation of `{instance}.{name}`", + ); + serve::(srv, async |(testbar, s)| { + assert_eq!(testbar, b"testbar".as_slice()); + let buf = s.collect::>().await; + assert_eq!(buf.concat(), b"client->server"); + let results: BoxStream<'static, Bytes> = + Box::pin(stream::iter([Bytes::from_static(b"server->client")])); + Ok((Bytes::from_static(b"foo"), results)) + }) .await } diff --git a/crates/transport/src/lib.rs b/crates/transport/src/lib.rs index 1901e4936..019f88024 100644 --- a/crates/transport/src/lib.rs +++ b/crates/transport/src/lib.rs @@ -109,7 +109,7 @@ pub fn error_unknown_path(path: &[usize]) -> std::io::Error { } /// Returns the error for data received after the end of a value -fn error_data_after_end() -> std::io::Error { +pub fn error_data_after_end() -> std::io::Error { std::io::Error::new( std::io::ErrorKind::InvalidData, "received data after value end", diff --git a/crates/transport/src/mux.rs b/crates/transport/src/mux.rs index b85558b44..c6ca5ed12 100644 --- a/crates/transport/src/mux.rs +++ b/crates/transport/src/mux.rs @@ -98,6 +98,13 @@ pub struct Receipt { impl Unpin for Receipt {} +impl Receipt { + /// Returns the frame reader, past the frame closing the last open path once this resolved + pub fn into_inner(self) -> F { + self.rx + } +} + impl Future for Receipt where F: BorrowMut>, diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 098bc81f2..a989cb9b5 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -3,14 +3,73 @@ use core::time::Duration; use anyhow::{Context as _, bail, ensure}; use bytes::Bytes; +use futures::future::BoxFuture; use futures::{StreamExt as _, future, stream}; +use http::request::Parts; +use http::{Request, Response}; +use http_body_util::BodyExt; +use http_body_util::combinators::UnsyncBoxBody; +use hyper::body::Incoming; +use hyper::client::conn::http2::SendRequest; use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt as _}; use tokio::sync::oneshot; use tokio::task::yield_now; use tokio::time::timeout; use tokio::{join, try_join}; use tracing::info; -use wrpc_transport::Framed; +use wrpc_http::{Body, Client}; +use wrpc_transport::{Framed, Invoke, Transmit}; + +/// Connection, which invocations are made on one after another +pub trait Connection { + type Client<'a, E: Transmit + Send + 'static>: Invoke + where + Self: 'a; + + /// Returns the client of the next invocation + fn client(&mut self) -> Self::Client<'_, E>; +} + +impl Connection for Framed +where + I: AsyncRead + Unpin, + O: AsyncWrite + Unpin, +{ + type Client<'a, E: Transmit + Send + 'static> + = &'a mut Framed + where + Self: 'a; + + fn client(&mut self) -> Self::Client<'_, E> { + self + } +} + +impl Connection for (SendRequest>, Parts) { + type Client<'a, E: Transmit + Send + 'static> + = Client< + Box< + dyn FnOnce(Request>) -> BoxFuture<'a, hyper::Result>> + + Send + + 'a, + >, + > + where + Self: 'a; + + fn client(&mut self) -> Self::Client<'_, E> { + let (sender, parts) = self; + Client { + parts: parts.clone(), + send: Box::new(|req| { + Box::pin(async move { + sender.ready().await?; + sender.send_request(req.map(BodyExt::boxed_unsync)).await + }) + }), + } + } +} /// Shut down `tx` and check that `rx` ends without data. pub async fn assert_eof( @@ -24,9 +83,7 @@ pub async fn assert_eof( wrpc_test::read_eof(&mut rx).await } -pub async fn assert_async( - clt: &mut Framed, -) -> anyhow::Result<()> { +pub async fn assert_async(clt: &mut impl Connection) -> anyhow::Result<()> { wit_bindgen_wrpc::generate!({ world: "async-client", path: "tests/wit", @@ -40,7 +97,7 @@ pub async fn assert_async( } info!("calling `wrpc-test:integration/async.with-streams`"); - let ((a, b), io) = wrpc_test::integration::async_::with_streams(&mut *clt) + let ((a, b), io) = wrpc_test::integration::async_::with_streams(clt.client()) .await .context("failed to call `wrpc-test:integration/async.with-streams`")?; join!( @@ -63,7 +120,7 @@ pub async fn assert_async( info!("calling `wrpc-test:integration/async.with-future`"); let (fut, io) = wrpc_test::integration::async_::with_future( - &mut *clt, + clt.client(), &wrpc_test::integration::async_::Something { foo: "bar".to_string(), }, @@ -85,7 +142,7 @@ pub async fn assert_async( info!("calling `wrpc-test:integration/async.identity-future`"); let (fut_tx, fut_rx) = oneshot::channel(); let (mut fut, io) = wrpc_test::integration::async_::identity_future( - &mut *clt, + clt.client(), Box::pin(async { fut_rx.await.expect("sender dropped") }), ) .await @@ -113,7 +170,7 @@ pub async fn assert_async( let (r_tx, r_rx) = oneshot::channel(); let (v_tx, v_rx) = oneshot::channel(); let ((o, r, v), io) = wrpc_test::integration::async_::identity_cases( - &mut *clt, + clt.client(), Some(Box::pin(async { o_rx.await.expect("sender dropped") })), Err(Box::pin(async { r_rx.await.expect("sender dropped") })), wrpc_test::integration::async_::AsyncCase::Fut(Box::pin(async { @@ -163,7 +220,7 @@ pub async fn assert_async( ] { info!(?v, "calling `wrpc-test:integration/async.identity-cases`"); let ((o, r, v), io) = wrpc_test::integration::async_::identity_cases( - &mut *clt, + clt.client(), None, Err(Box::pin(async { 42 })), v, @@ -210,9 +267,7 @@ pub async fn assert_async( /// Call every function of the `sync-client` world in `tests/wit` and check the /// results the `sync-server` world is expected to return. -pub async fn assert_sync( - clt: &mut Framed, -) -> anyhow::Result<()> { +pub async fn assert_sync(clt: &mut impl Connection) -> anyhow::Result<()> { mod bindings { wit_bindgen_wrpc::generate!({ world: "sync-client", @@ -227,30 +282,30 @@ pub async fn assert_sync( use bindings::{foo, strange}; info!("calling `wrpc-test:integration/sync-client.foo.f`"); - let v = foo::f(&mut *clt, "f") + let v = foo::f(clt.client(), "f") .await .context("failed to call `wrpc-test:integration/sync-client.foo.f`")?; ensure!(v == 42); info!("calling `wrpc-test:integration/sync-client.foo.foo`"); - foo::foo(&mut *clt, "foo") + foo::foo(clt.client(), "foo") .await .context("failed to call `wrpc-test:integration/sync-client.foo.foo`")?; info!("calling `wrpc-test:integration/sync.fallible`"); - let res = sync::fallible(&mut *clt, true) + let res = sync::fallible(clt.client(), true) .await .context("failed to call `wrpc-test:integration/sync.fallible`")?; ensure!(res == Ok(true)); info!("calling `wrpc-test:integration/sync.fallible`"); - let res = sync::fallible(&mut *clt, false) + let res = sync::fallible(clt.client(), false) .await .context("failed to call `wrpc-test:integration/sync.fallible`")?; ensure!(res == Err("test".to_string())); info!("calling `wrpc-test:integration/sync.numbers`"); - let (a, b, c, d, e, f, g, h, i, j) = sync::numbers(&mut *clt) + let (a, b, c, d, e, f, g, h, i, j) = sync::numbers(clt.client()) .await .context("failed to call `wrpc-test:integration/sync.numbers`")?; ensure!(a == 1); @@ -265,19 +320,19 @@ pub async fn assert_sync( ensure!(j == 10.); info!("calling `wrpc-test:integration/sync.with-flags`"); - let v = sync::with_flags(&mut *clt, true, false, true) + let v = sync::with_flags(clt.client(), true, false, true) .await .context("failed to call `wrpc-test:integration/sync.with-flags`")?; ensure!(v == Abc::A | Abc::C, "{v:?}"); info!("calling `wrpc-test:integration/sync.with-variant-option`"); - let v = sync::with_variant_option(&mut *clt, false) + let v = sync::with_variant_option(clt.client(), false) .await .context("failed to call `wrpc-test:integration/sync.with-variant-option`")?; ensure!(v.is_none(), "{v:?}"); info!("calling `wrpc-test:integration/sync.with-variant-option`"); - let v = sync::with_variant_option(&mut *clt, true) + let v = sync::with_variant_option(clt.client(), true) .await .context("failed to call `wrpc-test:integration/sync.with-variant-option`")?; ensure!( @@ -290,7 +345,7 @@ pub async fn assert_sync( ); info!("calling `wrpc-test:integration/sync.with-variant-list`"); - let v = sync::with_variant_list(&mut *clt) + let v = sync::with_variant_list(clt.client()) .await .context("failed to call `wrpc-test:integration/sync.with-variant-list`")?; ensure!( @@ -314,7 +369,7 @@ pub async fn assert_sync( ); info!("calling `wrpc-test:integration/sync.with-record`"); - let v = sync::with_record(&mut *clt) + let v = sync::with_record(clt.client()) .await .context("failed to call `wrpc-test:integration/sync.with-record`")?; ensure!( @@ -327,13 +382,13 @@ pub async fn assert_sync( ); info!("calling `wrpc-test:integration/sync.with-record-list`"); - let v = sync::with_record_list(&mut *clt, 0) + let v = sync::with_record_list(clt.client(), 0) .await .context("failed to call `wrpc-test:integration/sync.with-record-list`")?; ensure!(v.is_empty(), "{v:?}"); info!("calling `wrpc-test:integration/sync.with-record-list`"); - let v = sync::with_record_list(&mut *clt, 3) + let v = sync::with_record_list(clt.client(), 3) .await .context("failed to call `wrpc-test:integration/sync.with-record-list`")?; ensure!( @@ -358,7 +413,7 @@ pub async fn assert_sync( ); info!("calling `wrpc-test:integration/sync.with-record-tuple`"); - let v = sync::with_record_tuple(&mut *clt) + let v = sync::with_record_tuple(clt.client()) .await .context("failed to call `wrpc-test:integration/sync.with-record-tuple`")?; ensure!( @@ -378,14 +433,14 @@ pub async fn assert_sync( ); info!("calling `wrpc-test:integration/sync.with-enum`"); - let v = sync::with_enum(&mut *clt) + let v = sync::with_enum(clt.client()) .await .context("failed to call `wrpc-test:integration/sync.with-enum`")?; ensure!(v == Foobar::Bar, "{v:?}"); for c in ['a', 'é', '🚩'] { info!("calling `wrpc-test:integration/sync.identity-char`"); - let v = sync::identity_char(&mut *clt, c) + let v = sync::identity_char(clt.client(), c) .await .context("failed to call `wrpc-test:integration/sync.identity-char`")?; ensure!(v == c, "{v:?}"); @@ -400,77 +455,77 @@ pub async fn assert_sync( .as_ref() .map(|b| b.iter().map(String::as_str).collect::>()); info!("calling `wrpc-test:integration/sync.identity-option-lists`"); - let v = sync::identity_option_lists(&mut *clt, a.as_ref(), b_ref.as_deref()) + let v = sync::identity_option_lists(clt.client(), a.as_ref(), b_ref.as_deref()) .await .context("failed to call `wrpc-test:integration/sync.identity-option-lists`")?; ensure!(v == (a, b), "{v:?}"); } info!("calling `wrpc-test:integration/sync-client.ping`"); - let v = bindings::ping(&mut *clt) + let v = bindings::ping(clt.client()) .await .context("failed to call `wrpc-test:integration/sync-client.ping`")?; ensure!(v == "pong", "{v:?}"); info!("calling `wrpc-test:integration/resources.[constructor]foo`"); - let res = Foo::new(&mut *clt) + let res = Foo::new(clt.client()) .await .context("failed to call `wrpc-test:integration/resources.[constructor]foo`")?; info!("calling `wrpc-test:integration/resources.[method]foo.bar`"); - let v = Foo::bar(&mut *clt, &res.as_borrow()) + let v = Foo::bar(clt.client(), &res.as_borrow()) .await .context("failed to call `wrpc-test:integration/resources.[method]foo.bar`")?; ensure!(v == "bar", "{v:?}"); info!("calling `wrpc-test:integration/resources.bar`"); - let v = resources::bar(&mut *clt, &res.as_borrow()) + let v = resources::bar(clt.client(), &res.as_borrow()) .await .context("failed to call `wrpc-test:integration/resources.bar`")?; ensure!(v == "bar", "{v:?}"); info!("calling `wrpc-test:integration/sync-client.strange.bar`"); - let v = strange::bar(&mut *clt, &res.as_borrow()) + let v = strange::bar(clt.client(), &res.as_borrow()) .await .context("failed to call `wrpc-test:integration/sync-client.strange.bar`")?; ensure!(v == 42, "{v:?}"); info!("calling `wrpc-test:integration/resources.[static]foo.foo`"); - let v = Foo::foo(&mut *clt, &res) + let v = Foo::foo(clt.client(), &res) .await .context("failed to call `wrpc-test:integration/resources.[static]foo.foo`")?; ensure!(v == "foo", "{v:?}"); info!("calling `wrpc-test:integration/resources.[constructor]counter`"); - let a = Counter::new(&mut *clt, 1) + let a = Counter::new(clt.client(), 1) .await .context("failed to call `wrpc-test:integration/resources.[constructor]counter`")?; info!("calling `wrpc-test:integration/resources.[method]counter.increment-by`"); - Counter::increment_by(&mut *clt, &a.as_borrow(), 2) + Counter::increment_by(clt.client(), &a.as_borrow(), 2) .await .context("failed to call `wrpc-test:integration/resources.[method]counter.increment-by`")?; info!("calling `wrpc-test:integration/resources.[method]counter.get-count`"); - let v = Counter::get_count(&mut *clt, &a.as_borrow()) + let v = Counter::get_count(clt.client(), &a.as_borrow()) .await .context("failed to call `wrpc-test:integration/resources.[method]counter.get-count`")?; ensure!(v == 3, "{v:?}"); info!("calling `wrpc-test:integration/resources.[method]counter.clone-counter`"); - let b = Counter::clone_counter(&mut *clt, &a.as_borrow()) + let b = Counter::clone_counter(clt.client(), &a.as_borrow()) .await .context( "failed to call `wrpc-test:integration/resources.[method]counter.clone-counter`", )?; info!("calling `wrpc-test:integration/resources.[method]counter.increment-by`"); - Counter::increment_by(&mut *clt, &b.as_borrow(), 1) + Counter::increment_by(clt.client(), &b.as_borrow(), 1) .await .context("failed to call `wrpc-test:integration/resources.[method]counter.increment-by`")?; info!("calling `wrpc-test:integration/resources.[static]counter.sum`"); - let v = Counter::sum(&mut *clt, &a.as_borrow(), &b.as_borrow()) + let v = Counter::sum(clt.client(), &a.as_borrow(), &b.as_borrow()) .await .context("failed to call `wrpc-test:integration/resources.[static]counter.sum`")?; ensure!(v == 7, "{v:?}"); diff --git a/tests/go.rs b/tests/go.rs index da97c9658..11f6e589a 100644 --- a/tests/go.rs +++ b/tests/go.rs @@ -75,7 +75,7 @@ async fn go_bindgen() -> anyhow::Result<()> { let (tx, rx) = wrpc_test::tcp_streams(&addr).await?; let mut clt = Framed::new(tx, rx); common::assert_sync(&mut clt).await?; - let res = invoke_blocking::<(&str,), (u32,), _>(&mut clt, "foo", "f", ("panic",)).await; + let res = invoke_blocking::<(&str,), (u32,), _>(clt, "foo", "f", ("panic",)).await; let Err(err) = res else { bail!("a panicking handler must fail the invocation"); }; diff --git a/tests/js.rs b/tests/js.rs index 906e076aa..d4ec845f4 100644 --- a/tests/js.rs +++ b/tests/js.rs @@ -10,12 +10,9 @@ use bytes::BytesMut; use hyper::client::conn::http2; use hyper_util::rt::{TokioExecutor, TokioIo}; use tempfile::{TempDir, tempdir}; -use tokio::io::{ - AsyncBufReadExt as _, AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _, BufReader, -}; +use tokio::io::{AsyncBufReadExt as _, AsyncReadExt as _, AsyncWriteExt as _, BufReader}; use tokio::net::TcpListener; use tokio::process::{Child, Command}; -use tokio::sync::mpsc; use tokio::time::timeout; use tokio::{select, spawn}; use tokio_util::codec::Encoder as _; @@ -67,17 +64,7 @@ async fn start_server(addr: &str, bindings: &Path) -> anyhow::Result { Ok(server) } -/// Serve the `echo-server` world of `tests/js/wit` on the connections accepted using `accept` -/// until `tests/js/client.js`, run against `addr`, exits. -async fn serve_echo( - mut accept: impl AsyncFnMut() -> Result<(O, I), E>, - addr: &str, -) -> anyhow::Result<()> -where - I: AsyncRead + Send + Unpin + 'static, - O: AsyncWrite + Send + Unpin + 'static, - E: core::error::Error + Send + Sync + 'static, -{ +mod echo { mod bindings { wit_bindgen_wrpc::generate!({ world: "echo-server", @@ -85,10 +72,12 @@ where }); } + pub use bindings::handle; + use bindings::exports::wrpc_test::js::echo::{Asyncs, Handler, Values}; #[derive(Clone, Copy)] - struct Echo; + pub struct Echo; impl Handler for Echo { async fn echo(&self, v: Values) -> anyhow::Result { @@ -99,7 +88,19 @@ where Ok(v) } } +} +/// Serve the `echo-server` world of `tests/js/wit` on the connections accepted using `accept` +/// with `serve` until `tests/js/client.js`, run against `addr`, exits. +async fn serve_echo( + mut accept: impl AsyncFnMut() -> Result, + serve: impl Fn(T) -> Fut, + addr: &str, +) -> anyhow::Result<()> +where + E: core::error::Error + Send + Sync + 'static, + Fut: Future> + Send + 'static, +{ let bindings = bindgen("tests/js/wit", &["echo-client"]).await?; info!("running `tests/js/client.js`"); let mut client = pin!( @@ -117,20 +118,8 @@ where return Ok(()); } res = accept() => { - let (tx, rx) = res.expect("failed to accept connection"); - spawn(async move { - let mut lis = Listener::new(tx, rx); - while let Some((Header { instance, name }, srv)) = lis - .accept() - .await - .expect("failed to read invocation header") - { - let Ok(fut) = bindings::handle(&Echo, &instance, &name, srv) else { - panic!("`{instance}#{name}` is not exported"); - }; - fut.await.expect("failed to serve invocation"); - } - }); + let fut = serve(res.expect("failed to accept connection")); + spawn(async move { fut.await.expect("failed to serve connection") }); } } } @@ -203,11 +192,9 @@ async fn js_http_server() -> anyhow::Result<()> { parts.uri = format!("http://{addr}/") .parse() .context("failed to parse request URI")?; - let (tx, rx) = wrpc_test::http_open(sender, parts).await?; - let mut clt = Framed::new(tx, rx); + let mut clt = (sender, parts); common::assert_sync(&mut clt).await?; common::assert_async(&mut clt).await?; - common::assert_eof(clt).await?; server.start_kill().context("failed to kill `node`")?; server.wait().await.context("failed to wait for `node`")?; @@ -223,6 +210,16 @@ async fn js_client() -> anyhow::Result<()> { let addr = lis.local_addr().context("failed to get server address")?; serve_echo( async || wrpc_test::tcp_accept(&lis).await, + |(tx, rx)| async move { + let mut lis = Listener::new(tx, rx); + while let Some((Header { instance, name }, srv)) = lis.accept().await? { + let Ok(fut) = echo::handle(&echo::Echo, &instance, &name, srv) else { + bail!("`{instance}#{name}` is not exported"); + }; + fut.await?; + } + Ok(()) + }, &addr.to_string(), ) .await @@ -235,23 +232,20 @@ async fn js_http_client() -> anyhow::Result<()> { .await .context("failed to start TCP listener")?; let addr = lis.local_addr().context("failed to get server address")?; - let (tx, mut rx) = mpsc::channel(16); - let conns = spawn(async move { - loop { - let (stream, ..) = lis.accept().await.expect("failed to accept connection"); - let tx = tx.clone(); - spawn(async move { - wrpc_test::serve_http1(stream, tx) - .await - .expect("failed to serve HTTP connection"); - }); - } - }); - let res = serve_echo( - async || wrpc_test::http_accept(&mut rx).await, + serve_echo( + async || { + let (stream, ..) = lis.accept().await?; + std::io::Result::Ok(stream) + }, + |stream| { + wrpc_test::serve_http1(stream, |_, Header { instance, name }, srv| async move { + let Ok(fut) = echo::handle(&echo::Echo, &instance, &name, srv) else { + bail!("`{instance}#{name}` is not exported"); + }; + fut.await + }) + }, &format!("http://{addr}"), ) - .await; - conns.abort(); - res + .await } diff --git a/tests/rust.rs b/tests/rust.rs index 811155aa6..2c8cfb831 100644 --- a/tests/rust.rs +++ b/tests/rust.rs @@ -7,7 +7,7 @@ use core::iter; use core::pin::Pin; use core::time::Duration; -use std::sync::{Arc, Mutex}; +use std::sync::Arc; use anyhow::{Context as _, bail, ensure}; use bytes::{Bytes, BytesMut}; @@ -28,32 +28,26 @@ use tracing::instrument; use wrpc_test::next_invocation; use wrpc_transport::{ Decode, Encode, FrameDecoder, FrameEncoder, FrameRef, Framed, Header, HeaderDecoder, - HeaderEncoder, HeaderRef, Listener, ResourceBorrow, ResourceOwn, invoke, invoke_blocking, - receive, serve, transmit, + HeaderEncoder, HeaderRef, Listener, invoke, invoke_blocking, receive, serve, transmit, }; -#[instrument(skip_all, ret)] -async fn assert_bindgen_sync( - connect: impl Fn() -> Fut + Clone + Send + Sync + 'static, - mut accept: impl AsyncFnMut() -> Result<(O, I), E>, -) -> anyhow::Result<()> -where - Fut: Future> + Send, - CI: AsyncRead + Send + Unpin, - CO: AsyncWrite + Send + Unpin, - CE: core::error::Error + Send + Sync + 'static, - I: AsyncRead + Send + Unpin + 'static, - O: AsyncWrite + Send + Unpin + 'static, - E: core::error::Error + Send + Sync + 'static, -{ - mod sync_client { +mod sync_bindgen { + use std::sync::{Arc, Mutex}; + + use anyhow::{Context as _, ensure}; + use bytes::Bytes; + use wrpc_transport::{ResourceBorrow, ResourceOwn}; + + use crate::common::Connection; + + pub mod sync_client { wit_bindgen_wrpc::generate!({ world: "sync-client", path: "tests/wit", }); } - mod sync_server { + pub mod sync_server { wit_bindgen_wrpc::generate!({ world: "sync-server", path: "tests/wit", @@ -77,9 +71,9 @@ where } #[derive(Clone)] - struct Handler { - counts: Arc>>, - connect: F, + pub struct Handler { + pub counts: Arc>>, + pub count: F, } impl Handler { @@ -171,27 +165,27 @@ where } } - impl sync_server::Handler for Handler + impl sync_server::Handler for Handler where F: Fn() -> Fut + Send + Sync + 'static, - Fut: Future> + Send, - I: AsyncRead + Send + Unpin, - O: AsyncWrite + Send + Unpin, - E: core::error::Error + Send + Sync + 'static, + Fut: Future> + Send, { async fn ping(&self) -> anyhow::Result { - use sync_client::wrpc_test::integration::resources::Counter; - - let (tx, rx) = (self.connect)().await?; - let mut clt = Framed::new(tx, rx); - let counter = Counter::new(&mut clt, 42).await?; - let n = Counter::get_count(&mut clt, &counter.as_borrow()).await?; + let n = (self.count)().await?; ensure!(n == 42); - assert_eof(clt).await?; Ok("pong".into()) } } + /// Creates a counter on `clt` and returns its count + pub async fn count(clt: &mut impl Connection) -> anyhow::Result { + use sync_client::wrpc_test::integration::resources::Counter; + + let counter = Counter::new(clt.client(), 42).await?; + let n = Counter::get_count(clt.client(), &counter.as_borrow()).await?; + Ok(n) + } + impl sync::Handler for Handler { async fn fallible(&self, ok: bool) -> anyhow::Result> { Ok(if ok { Ok(true) } else { Err("test".into()) }) @@ -266,15 +260,42 @@ where Ok(()) } } +} - let handler = Handler { +#[instrument(skip_all, ret)] +async fn assert_bindgen_sync( + connect: impl Fn() -> Fut + Clone + Send + Sync + 'static, + mut accept: impl AsyncFnMut() -> Result<(O, I), E>, +) -> anyhow::Result<()> +where + Fut: Future> + Send, + CI: AsyncRead + Send + Unpin + 'static, + CO: AsyncWrite + Send + Unpin + 'static, + CE: core::error::Error + Send + Sync + 'static, + I: AsyncRead + Send + Unpin + 'static, + O: AsyncWrite + Send + Unpin + 'static, + E: core::error::Error + Send + Sync + 'static, +{ + let handler = sync_bindgen::Handler { counts: Arc::default(), - connect: connect.clone(), + count: { + let connect = connect.clone(); + move || { + let connect = connect.clone(); + async move { + let (tx, rx) = connect().await?; + let mut clt = Framed::new(tx, rx); + let n = sync_bindgen::count(&mut clt).await?; + assert_eof(clt).await?; + Ok(n) + } + } + }, }; let serve = async |tx, rx| { let mut lis = Listener::new(tx, rx); while let Some((Header { instance, name }, srv)) = lis.accept().await? { - let Ok(fut) = sync_server::handle(&handler, &instance, &name, srv) else { + let Ok(fut) = sync_bindgen::sync_server::handle(&handler, &instance, &name, srv) else { bail!("`{instance}#{name}` is not exported"); }; fut.await?; @@ -299,21 +320,12 @@ where Ok(()) } -#[instrument(skip_all, ret)] -async fn assert_bindgen_async( - tx: impl AsyncWrite + Send + Unpin, - rx: impl AsyncRead + Send + Unpin, - accept: impl Future< - Output = Result< - ( - impl AsyncWrite + Send + Unpin + 'static, - impl AsyncRead + Send + Unpin + 'static, - ), - impl core::error::Error + Send + Sync + 'static, - >, - >, -) -> anyhow::Result<()> { - mod bindings { +mod async_bindgen { + use bytes::Bytes; + use futures::future::BoxFuture; + use futures::stream::{self, BoxStream}; + + pub mod bindings { wit_bindgen_wrpc::generate!({ world: "async-server", path: "tests/wit", @@ -323,7 +335,7 @@ async fn assert_bindgen_async( use bindings::exports::wrpc_test::integration::async_::{self, AsyncCase, Something}; #[derive(Clone)] - struct Handler; + pub struct Handler; impl async_::Handler for Handler { async fn with_streams( @@ -385,14 +397,34 @@ async fn assert_bindgen_async( Ok((o, r, v)) } } +} +#[instrument(skip_all, ret)] +async fn assert_bindgen_async( + tx: impl AsyncWrite + Send + Unpin, + rx: impl AsyncRead + Send + Unpin, + accept: impl Future< + Output = Result< + ( + impl AsyncWrite + Send + Unpin + 'static, + impl AsyncRead + Send + Unpin + 'static, + ), + impl core::error::Error + Send + Sync + 'static, + >, + >, +) -> anyhow::Result<()> { try_join!( async { let (srv_tx, srv_rx) = accept.await.context("failed to accept")?; spawn(async move { let mut lis = Listener::new(srv_tx, srv_rx); while let Some((Header { instance, name }, srv)) = lis.accept().await? { - let Ok(fut) = bindings::handle(&Handler, &instance, &name, srv) else { + let Ok(fut) = async_bindgen::bindings::handle( + &async_bindgen::Handler, + &instance, + &name, + srv, + ) else { bail!("`{instance}#{name}` is not exported"); }; fut.await?; @@ -410,6 +442,111 @@ async fn assert_bindgen_async( Ok(()) } +type SyncValues = ( + (bool, u8, u16, u32, u64, i8, i16, i32, i64, f32, f64, char), + String, + Vec>>, + Vec, ()>>>>, +); + +type AsyncValues = ( + BoxStream<'static, Vec>, + BoxStream<'static, Vec>, + Pin>, + BoxFuture<'static, Vec>, + BoxStream<'static, Bytes>, + Vec>, +); + +fn sync_values() -> SyncValues { + ( + ( + true, + 0xfe, + 0xfeff, + 0xfeff_ffff, + 0xfeff_ffff_ffff_ffff, + 0x7e, + 0x7eff, + 0x7eff_ffff, + 0x7eff_ffff_ffff_ffff, + 0.42, + 0.4242, + 'a', + ), + "test".into(), + vec![vec![b"foo".to_vec()]], + vec![Some(vec![Ok(Some("bar".into()))])], + ) +} + +fn pending( + items: impl IntoIterator, +) -> BoxStream<'static, T> { + Box::pin(stream::iter(items).then(|v| async move { + yield_now().await; + v + })) +} + +fn pending_string(s: &'static str) -> BoxFuture<'static, String> { + Box::pin(async move { + yield_now().await; + s.into() + }) +} + +fn async_values() -> AsyncValues { + ( + pending([vec![0xc0, 0xff], vec![], vec![0xee]]), + pending([vec!["foo".into()], vec![], vec!["bar".into()]]), + Box::pin(StreamReader::new(pending([Ok::<_, std::io::Error>( + Bytes::from("test"), + )]))), + Box::pin(async { + yield_now().await; + vec![1, 2, 3] + }), + pending( + iter::once(Bytes::default()) + .chain(iter::repeat_n(Bytes::from("abcd".repeat(1 << 13)), 1 << 3)), + ), + vec![pending_string("foo"), pending_string("bar")], + ) +} + +async fn assert_async_values( + (a, b, mut c, d, e, f): AsyncValues, + io: impl Future>, +) -> anyhow::Result<()> { + try_join!( + async { + let (a, b, c, d, e, f) = join!( + a.concat(), + b.concat(), + async { + let mut s = String::default(); + let res = c.read_to_string(&mut s).await; + res.map(|_| s) + }, + d, + e.collect::>(), + future::join_all(f), + ); + assert_eq!(a, [0xc0, 0xff, 0xee]); + assert_eq!(b, ["foo", "bar"]); + let c = c?; + assert_eq!(c, "test"); + assert_eq!(d, [1, 2, 3]); + assert_eq!(e.concat(), b"abcd".repeat(1 << 16)); + assert_eq!(f, ["foo", "bar"]); + anyhow::Ok(()) + }, + async { io.await.context("failed to complete I/O") }, + )?; + Ok(()) +} + #[instrument(skip_all, ret)] async fn assert_dynamic( connect: impl AsyncFn() -> Result<(CO, CI), CE>, @@ -423,111 +560,6 @@ where O: AsyncWrite + Send + Unpin + 'static, E: core::error::Error + Send + Sync + 'static, { - type SyncValues = ( - (bool, u8, u16, u32, u64, i8, i16, i32, i64, f32, f64, char), - String, - Vec>>, - Vec, ()>>>>, - ); - - type AsyncValues = ( - BoxStream<'static, Vec>, - BoxStream<'static, Vec>, - Pin>, - BoxFuture<'static, Vec>, - BoxStream<'static, Bytes>, - Vec>, - ); - - fn sync_values() -> SyncValues { - ( - ( - true, - 0xfe, - 0xfeff, - 0xfeff_ffff, - 0xfeff_ffff_ffff_ffff, - 0x7e, - 0x7eff, - 0x7eff_ffff, - 0x7eff_ffff_ffff_ffff, - 0.42, - 0.4242, - 'a', - ), - "test".into(), - vec![vec![b"foo".to_vec()]], - vec![Some(vec![Ok(Some("bar".into()))])], - ) - } - - fn pending( - items: impl IntoIterator, - ) -> BoxStream<'static, T> { - Box::pin(stream::iter(items).then(|v| async move { - yield_now().await; - v - })) - } - - fn pending_string(s: &'static str) -> BoxFuture<'static, String> { - Box::pin(async move { - yield_now().await; - s.into() - }) - } - - fn async_values() -> AsyncValues { - ( - pending([vec![0xc0, 0xff], vec![], vec![0xee]]), - pending([vec!["foo".into()], vec![], vec!["bar".into()]]), - Box::pin(StreamReader::new(pending([Ok::<_, std::io::Error>( - Bytes::from("test"), - )]))), - Box::pin(async { - yield_now().await; - vec![1, 2, 3] - }), - pending( - iter::once(Bytes::default()) - .chain(iter::repeat_n(Bytes::from("abcd".repeat(1 << 13)), 1 << 3)), - ), - vec![pending_string("foo"), pending_string("bar")], - ) - } - - async fn assert_async_values( - (a, b, mut c, d, e, f): AsyncValues, - io: impl Future>, - ) -> anyhow::Result<()> { - try_join!( - async { - let (a, b, c, d, e, f) = join!( - a.concat(), - b.concat(), - async { - let mut s = String::default(); - let res = c.read_to_string(&mut s).await; - res.map(|_| s) - }, - d, - e.collect::>(), - future::join_all(f), - ); - assert_eq!(a, [0xc0, 0xff, 0xee]); - assert_eq!(b, ["foo", "bar"]); - let c = c?; - assert_eq!(c, "test"); - assert_eq!(d, [1, 2, 3]); - assert_eq!(e.concat(), b"abcd".repeat(1 << 16)); - assert_eq!(f, ["foo", "bar"]); - anyhow::Ok(()) - }, - async { io.await.context("failed to complete I/O") }, - )?; - Ok(()) - } - try_join!( async { for spawned in [false, true] { @@ -833,36 +865,165 @@ async fn rust_webtransport_stopped_mid_params() -> anyhow::Result<()> { #[cfg(feature = "http")] #[test_log::test(tokio::test(flavor = "multi_thread"))] async fn rust_http_bindgen_sync() -> anyhow::Result<()> { - wrpc_test::serve_http2(async |parts, sender, srv| { - assert_bindgen_sync( - move || wrpc_test::http_open(sender.clone(), parts.clone()), - async || wrpc_test::http_accept(srv).await, - ) - .await - }) + use std::sync::OnceLock; + + use http::request::Parts; + use http_body_util::combinators::UnsyncBoxBody; + use hyper::client::conn::http2::SendRequest; + use hyper_util::rt::TokioIo; + + let conn: Arc>, Parts)>> = + Arc::default(); + let handler = sync_bindgen::Handler { + counts: Arc::default(), + count: { + let conn = Arc::clone(&conn); + move || { + let clt = conn.get().cloned(); + async move { + let mut clt = clt.context("connection missing")?; + sync_bindgen::count(&mut clt).await + } + } + }, + }; + wrpc_test::with_http2( + async |stream| { + wrpc_http::serve( + TokioIo::new(stream), + move |_, Header { instance, name }, srv| { + let handler = handler.clone(); + async move { + let Ok(fut) = + sync_bindgen::sync_server::handle(&handler, &instance, &name, srv) + else { + bail!("`{instance}#{name}` is not exported"); + }; + fut.await + } + }, + ) + .await + .context("failed to serve HTTP/2 connection") + }, + |parts, sender| async move { + let mut clt = (sender, parts); + _ = conn.set(clt.clone()); + assert_sync(&mut clt).await + }, + ) .await } #[cfg(feature = "http")] #[test_log::test(tokio::test(flavor = "multi_thread"))] async fn rust_http_bindgen_async() -> anyhow::Result<()> { - wrpc_test::serve_http2(async |parts, sender, srv| { - let (tx, rx) = wrpc_test::http_open(sender, parts).await?; - assert_bindgen_async(tx, rx, wrpc_test::http_accept(srv)).await - }) + use hyper_util::rt::TokioIo; + + wrpc_test::with_http2( + async |stream| { + wrpc_http::serve( + TokioIo::new(stream), + |_, Header { instance, name }, srv| async move { + let Ok(fut) = async_bindgen::bindings::handle( + &async_bindgen::Handler, + &instance, + &name, + srv, + ) else { + bail!("`{instance}#{name}` is not exported"); + }; + fut.await + }, + ) + .await + .context("failed to serve HTTP/2 connection") + }, + |parts, sender| async move { assert_async(&mut (sender, parts)).await }, + ) .await } #[cfg(feature = "http")] #[test_log::test(tokio::test(flavor = "multi_thread"))] async fn rust_http_dynamic() -> anyhow::Result<()> { - wrpc_test::serve_http2(async |parts, sender, srv| { - assert_dynamic( - || wrpc_test::http_open(sender.clone(), parts.clone()), - async || wrpc_test::http_accept(srv).await, - ) - .await - }) + use http_body_util::BodyExt; + use hyper_util::rt::TokioIo; + use wrpc_http::{Body, Client}; + + wrpc_test::with_http2( + async |stream| { + wrpc_http::serve( + TokioIo::new(stream), + |_, Header { instance, name }, srv| async move { + ensure!(instance == "test", "unexpected instance `{instance}`"); + match name.as_str() { + "sync" => { + serve::(srv, async |params| { + assert_eq!(params, sync_values()); + anyhow::Ok(sync_values()) + }) + .await + } + "async" => { + serve::(srv, |params| async move { + assert_async_values(params, future::ready(Ok(()))).await?; + anyhow::Ok(async_values()) + }) + .await + } + _ => bail!("`{instance}.{name}` is not exported"), + } + }, + ) + .await + .context("failed to serve HTTP/2 connection") + }, + |parts, mut sender| async move { + sender.ready().await?; + let res = invoke_blocking::<(String,), (String,), _>( + Client { + parts: parts.clone(), + send: |req: http::Request>| { + sender.send_request(req.map(BodyExt::boxed_unsync)) + }, + }, + "test", + "reset", + ("arg".into(),), + ) + .await; + ensure!(res.is_err(), "`test.reset` should have failed"); + + let res = invoke_blocking::( + Client { + parts: parts.clone(), + send: |req: http::Request>| { + sender.send_request(req.map(BodyExt::boxed_unsync)) + }, + }, + "test", + "sync", + sync_values(), + ) + .await?; + assert_eq!(res, sync_values()); + + let (res, io) = invoke::( + Client { + parts, + send: |req: http::Request>| { + sender.send_request(req.map(BodyExt::boxed_unsync)) + }, + }, + "test", + "async", + async_values(), + ) + .await?; + assert_async_values(res, io).await + }, + ) .await }