diff --git a/.github/workflows/rust-checks.yml b/.github/workflows/rust-checks.yml index 0e08f51..ae7fa02 100644 --- a/.github/workflows/rust-checks.yml +++ b/.github/workflows/rust-checks.yml @@ -37,3 +37,16 @@ jobs: with: command: clippy args: --all --lib -- -D warnings -A deprecated -A unused-variables -A unused-imports + + vendored-tonic-web-wasm-client: + runs-on: ubuntu-24.04 + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Install Rust toolchain + uses: ./.github/actions/install-rust-toolchain + + # The vendored crate is excluded from the workspace, so `--all` does not reach it. + - name: Test the vendored tonic-web-wasm-client + run: cargo test --locked -p tonic-web-wasm-client diff --git a/vendor/tonic-web-wasm-client/VENDORED.md b/vendor/tonic-web-wasm-client/VENDORED.md index eaab074..bf438b2 100644 --- a/vendor/tonic-web-wasm-client/VENDORED.md +++ b/vendor/tonic-web-wasm-client/VENDORED.md @@ -1,10 +1,15 @@ -# Vendored `tonic-web-wasm-client` 0.8.0, with one fix +# Vendored `tonic-web-wasm-client` 0.8.0, with two fixes This is `tonic-web-wasm-client` 0.8.0 from crates.io (MIT/Apache-2.0, see the licence files) with -the change in `trailers-only.patch`, wired in through `[patch.crates-io]` in the workspace -`Cargo.toml`. +the changes in `trailers-only.patch` and then `trailers.patch`, wired in through +`[patch.crates-io]` in the workspace `Cargo.toml`. The unit tests in `src/response_body/` are ours. +`trailers.patch` carries only their two `cfg(test)` hooks (`mod tests;` and +`BodyStream::from_chunks`), not the test files, so on a plain upstream checkout the patched crate +builds but `cargo test` needs `src/response_body/` copied too. -## Why +## Fix 1: trailers-only responses (`trailers-only.patch`) + +### Why A gRPC server may answer a call that returns no messages with a *trailers-only* response: HTTP 200, `grpc-status` in the HTTP headers, and an empty body. lightwalletd v0.5.4 (the Zcash testnet @@ -14,15 +19,63 @@ every new wallet issues during sync. Mainnet (lightwalletd v0.5.3) sends a body Upstream 0.8.0 (and 0.9.2) reads the empty body as a truncated message and fails with `MalformedResponse`, so a wallet could not sync at all on testnet. -## The change +### The change `ResponseBody` records whether the response headers carried `grpc-status`. If the body ends before any frame header *and* the response was trailers-only, it is treated as an empty body. A body that ends early on any other response is still `MalformedResponse`. +## Fix 2: the trailer frame reaches tonic (`trailers.patch`) + +Found, reproduced and first fixed by Crackdevs in their browser OHTTP proof +(https://github.com/Crackdevs/zcash-browser-ohttp-proof). That repository has no licence file, so +none of their code is used here; this fix was written separately. + +### Why + +0.8.0 parses the gRPC-web trailer frame, stores it in a field nothing reads, and ends the body as +soon as it sees the trailer flag. tonic never receives the trailers, and tonic 0.14.3 (the locked +version) treats "HTTP 200, no trailers" as success. So a status sent in the body trailer is lost: +a server-streaming call that fails part-way looks complete, a unary call that returns a message and +then an error status looks successful, and an error with no message at all (for example +`OutOfRange` from `GetBlock` past the tip, which a public mainnet endpoint sends as a body trailer) +becomes an empty successful stream. Errors sent in the HTTP headers are not affected. + +tonic 0.14.6 and later report "HTTP 200, no trailers" as `Unknown: missing grpc-status trailer`, +so without this fix a `cargo update` of tonic would fail every call that has a body. + +### The change + +- After the last data frame the body yields the parsed trailers as one trailers frame, then ends. + This is the `src/response_body.rs` part of upstream commit 0f232d33 + (https://github.com/devashishdxt/tonic-web-wasm-client/pull/90, released in 0.9.1). +- The body counts as finished only once the trailer frame has been read in full. A trailer frame + split across chunks is read; a stream that ends inside it is `MalformedResponse` instead of a + clean end. The split case is upstream issue + https://github.com/devashishdxt/tonic-web-wasm-client/issues/97; the open upstream PR + https://github.com/devashishdxt/tonic-web-wasm-client/pull/112 makes the same predicate change + (unmerged). +- A stream that ends between frames with no trailer frame is unchanged: `MalformedResponse`, except + for the trailers-only case of fix 1. + +Behaviour that changes besides the fix: a trailer block that does not parse now fails with +`HeaderParsingError` whether it arrives in one chunk or split (before, the split case ended +silently); and since body trailers now reach tonic, an invalid `grpc-status-details-bin` there hits +the same tonic handling as one in the HTTP headers. + +Known and not changed: a response with `grpc-status: 0` in the headers and an error in a body +trailer still reports success (tonic does not read the body then); repeated trailer keys keep only +the last value (upstream issue 103); bytes after the trailer frame are ignored; like a data frame, +a trailer frame is buffered until its announced length has arrived. + +### Tests + +`cargo test --locked -p tonic-web-wasm-client` from the workspace root runs them natively against +the workspace lock (CI: the `vendored-tonic-web-wasm-client` job in `rust-checks.yml`). + ## Not bumped to 0.9.2 -0.9.2 has the same behaviour (checked), and requires `js-sys ^0.3.85`, which conflicts with the +0.9.2 has the same trailers-only behaviour (checked), and its `wasm-streams ^0.7` dependency requires `js-sys ^0.3.85`, which conflicts with the workspace's deliberate `wasm-bindgen =0.2.100` / `js-sys =0.3.77` pins (newer versions break the MetaMask Snap sandbox). @@ -34,6 +87,7 @@ reviews). Release 0.9.2 (2026-09-14) does not include it. Do not send our patch ## To remove -Drop this directory, the `[patch.crates-io]` entry and the `exclude` entry once the fix is -released upstream. `trailers-only.patch` is a ready-made upstream change (apply with `patch -p1` -from a `tonic-web-wasm-client` checkout). +Drop this directory, the `[patch.crates-io]` entry, the `exclude` entry and the CI job once both +fixes are in an upstream release the pins allow. `trailers-only.patch` is a ready-made upstream +change (apply with `patch -p1` from a `tonic-web-wasm-client` checkout); `trailers.patch` applies +on top of it. diff --git a/vendor/tonic-web-wasm-client/src/body_stream.rs b/vendor/tonic-web-wasm-client/src/body_stream.rs index 81af90c..55a4811 100644 --- a/vendor/tonic-web-wasm-client/src/body_stream.rs +++ b/vendor/tonic-web-wasm-client/src/body_stream.rs @@ -35,6 +35,15 @@ impl BodyStream { } } + /// A body made of in-memory chunks, for unit tests that run without a browser. + #[cfg(test)] + pub(crate) fn from_chunks(chunks: Vec) -> Self { + Self { + body_stream: Box::pin(futures_util::stream::iter(chunks.into_iter().map(Ok))), + _abort: None, + } + } + pub fn empty() -> Self { let body_stream = empty(); diff --git a/vendor/tonic-web-wasm-client/src/response_body.rs b/vendor/tonic-web-wasm-client/src/response_body.rs index 934c05d..282827c 100644 --- a/vendor/tonic-web-wasm-client/src/response_body.rs +++ b/vendor/tonic-web-wasm-client/src/response_body.rs @@ -97,10 +97,10 @@ pub enum ReadState { } impl ReadState { + /// The body is complete only once the trailer frame has been read in full. Seeing the trailer + /// flag is not enough: the rest of the frame may still be on its way, or never arrive. fn finished_data(&self) -> bool { - matches!(self, ReadState::TrailerLength) - || matches!(self, ReadState::Trailer(_)) - || matches!(self, ReadState::Done) + matches!(self, ReadState::Done) } } @@ -130,8 +130,20 @@ impl ResponseBody { let body_stream = wasm_streams::ReadableStream::from_raw(body_stream.unchecked_into()).into_stream(); + Self::from_body_stream( + BodyStream::new(body_stream, abort), + content_type, + trailers_only, + ) + } + + fn from_body_stream( + body_stream: BodyStream, + content_type: &str, + trailers_only: bool, + ) -> Result { Ok(Self { - body_stream: BodyStream::new(body_stream, abort), + body_stream, buf: EncodedBytes::new(content_type)?, incomplete_data: BytesMut::new(), data: None, @@ -284,9 +296,13 @@ impl Body for ResponseBody { return Poll::Ready(Some(Ok(http_body::Frame::data(data.freeze())))); } - // If reading data is finished return `None` + // Once the body is complete, hand the trailers to the caller (once), then end if self.state.finished_data() { - return Poll::Ready(None); + return Poll::Ready( + self.trailer + .take() + .map(|t| Ok(http_body::Frame::trailers(t))), + ); } loop { @@ -305,8 +321,12 @@ impl Body for ResponseBody { let data = self.data.take().unwrap(); return Poll::Ready(Some(Ok(http_body::Frame::data(data.freeze())))); } else if self.state.finished_data() { - // If we finished reading data continue return `None` - return Poll::Ready(None); + // The body is complete: hand the trailers to the caller (once), then end + return Poll::Ready( + self.trailer + .take() + .map(|t| Ok(http_body::Frame::trailers(t))), + ); } else if self.finished_stream { // A trailers-only response carries its status in the HTTP headers and has an empty // body: the stream legitimately ends before any frame header. @@ -342,3 +362,6 @@ impl Default for ResponseBody { } } } + +#[cfg(test)] +mod tests; diff --git a/vendor/tonic-web-wasm-client/src/response_body/fixtures/body-trailer-error.bin b/vendor/tonic-web-wasm-client/src/response_body/fixtures/body-trailer-error.bin new file mode 100644 index 0000000..8d29a14 Binary files /dev/null and b/vendor/tonic-web-wasm-client/src/response_body/fixtures/body-trailer-error.bin differ diff --git a/vendor/tonic-web-wasm-client/src/response_body/fixtures/data-then-trailer-ok.bin b/vendor/tonic-web-wasm-client/src/response_body/fixtures/data-then-trailer-ok.bin new file mode 100644 index 0000000..b7af0de Binary files /dev/null and b/vendor/tonic-web-wasm-client/src/response_body/fixtures/data-then-trailer-ok.bin differ diff --git a/vendor/tonic-web-wasm-client/src/response_body/tests.rs b/vendor/tonic-web-wasm-client/src/response_body/tests.rs new file mode 100644 index 0000000..3ce9635 --- /dev/null +++ b/vendor/tonic-web-wasm-client/src/response_body/tests.rs @@ -0,0 +1,380 @@ +//! Native unit tests for the gRPC-web response body: the trailer frame must reach tonic. +//! +//! The body is fed from in-memory chunks, so these run with `cargo test` on the host, without a +//! browser. Frames are built by hand: one flag byte (`0x00` data, `0x80` trailer), a 4-byte +//! big-endian length, then the payload. + +use std::{ + future::Future, + pin::pin, + task::{Context, Poll, Waker}, +}; + +use bytes::{Buf, BufMut, Bytes}; +use http::{HeaderMap, StatusCode}; +use http_body::Body; +use tonic::{ + codec::{Codec, DecodeBuf, Decoder, EncodeBuf, Encoder, Streaming}, + Code, Status, +}; + +use super::ResponseBody; +use crate::{body_stream::BodyStream, Error}; + +const CONTENT_TYPE: &str = "application/grpc-web+proto"; +const STATUS_13: &[u8] = b"grpc-status: 13\r\ngrpc-message: boom\r\n"; +const STATUS_5: &[u8] = b"grpc-status: 5\r\ngrpc-message: not found\r\n"; +const STATUS_0: &[u8] = b"grpc-status: 0\r\n"; + +/// A real body captured from a public gRPC-web endpoint (2026-11-15): HTTP 200, no `grpc-status` +/// in the headers, and one trailer frame carrying `grpc-status: 11` for a block past the tip. +const CAPTURED_BODY_TRAILER_ERROR: &[u8] = include_bytes!("fixtures/body-trailer-error.bin"); +/// A real successful unary body (2026-11-15): one data frame, then a trailer frame with status 0. +const CAPTURED_DATA_THEN_TRAILER_OK: &[u8] = include_bytes!("fixtures/data-then-trailer-ok.bin"); + +fn frame(flag: u8, payload: &[u8]) -> Vec { + let mut out = Vec::with_capacity(5 + payload.len()); + out.push(flag); + out.put_u32(payload.len() as u32); + out.extend_from_slice(payload); + out +} + +fn data_frame(payload: &[u8]) -> Vec { + frame(0x00, payload) +} + +fn trailer_frame(payload: &[u8]) -> Vec { + frame(0x80, payload) +} + +fn body(chunks: Vec>, trailers_only: bool) -> ResponseBody { + let chunks = chunks.into_iter().map(Bytes::from).collect(); + ResponseBody::from_body_stream(BodyStream::from_chunks(chunks), CONTENT_TYPE, trailers_only) + .expect("binary content type is accepted") +} + +/// Drives a future that never waits on I/O (every body here is in memory). +fn run(future: F) -> F::Output { + let mut future = pin!(future); + let mut cx = Context::from_waker(Waker::noop()); + match future.as_mut().poll(&mut cx) { + Poll::Ready(output) => output, + Poll::Pending => panic!("an in-memory body never returns Pending"), + } +} + +#[derive(Debug, PartialEq)] +enum Item { + Data(Bytes), + Trailers(HeaderMap), + Malformed, + OtherError(String), +} + +/// Every frame the body yields, up to the end or the first error. +fn frames(mut body: ResponseBody) -> Vec { + let mut items = Vec::new(); + let mut cx = Context::from_waker(Waker::noop()); + loop { + match std::pin::Pin::new(&mut body).poll_frame(&mut cx) { + Poll::Pending => panic!("an in-memory body never returns Pending"), + Poll::Ready(None) => return items, + Poll::Ready(Some(Err(Error::MalformedResponse))) => { + items.push(Item::Malformed); + return items; + } + Poll::Ready(Some(Err(e))) => { + items.push(Item::OtherError(e.to_string())); + return items; + } + Poll::Ready(Some(Ok(frame))) => match frame.into_data() { + Ok(data) => items.push(Item::Data(data)), + Err(frame) => items.push(Item::Trailers( + frame.into_trailers().expect("a frame is data or trailers"), + )), + }, + } + } +} + +fn status_of(item: &Item) -> Option<&str> { + match item { + Item::Trailers(map) => map.get("grpc-status").and_then(|v| v.to_str().ok()), + _ => None, + } +} + +/// Every way to cut `bytes` into two chunks, plus one byte per chunk. +fn splits(bytes: &[u8]) -> Vec>> { + let mut all: Vec>> = (1..bytes.len()) + .map(|at| vec![bytes[..at].to_vec(), bytes[at..].to_vec()]) + .collect(); + all.push(bytes.iter().map(|b| vec![*b]).collect()); + all +} + +/// A codec that passes message bytes through unchanged. +#[derive(Default)] +struct RawCodec; + +impl Codec for RawCodec { + type Encode = Bytes; + type Decode = Bytes; + type Encoder = RawCodec; + type Decoder = RawCodec; + + fn encoder(&mut self) -> Self::Encoder { + RawCodec + } + + fn decoder(&mut self) -> Self::Decoder { + RawCodec + } +} + +impl Encoder for RawCodec { + type Item = Bytes; + type Error = Status; + + fn encode(&mut self, item: Bytes, dst: &mut EncodeBuf<'_>) -> Result<(), Status> { + dst.put(item); + Ok(()) + } +} + +impl Decoder for RawCodec { + type Item = Bytes; + type Error = Status; + + fn decode(&mut self, src: &mut DecodeBuf<'_>) -> Result, Status> { + Ok(Some(src.copy_to_bytes(src.remaining()))) + } +} + +/// What tonic's streaming decoder reports for a body: each message, then the final outcome. +fn through_tonic_stream(body: ResponseBody) -> (Vec, Result<(), Status>) { + let mut stream = Streaming::new_response(RawCodec, body, StatusCode::OK, None, None); + let mut messages = Vec::new(); + loop { + match run(stream.message()) { + Ok(Some(message)) => messages.push(message), + Ok(None) => return (messages, Ok(())), + Err(status) => return (messages, Err(status)), + } + } +} + +/// A gRPC service that answers every call with a fixed gRPC-web body and HTTP 200. +struct FixedResponse(Option); + +impl tower_service::Service> for FixedResponse { + type Response = http::Response; + type Error = Error; + type Future = std::future::Ready>; + + fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn call(&mut self, _: http::Request) -> Self::Future { + let body = self.0.take().expect("one call per test"); + std::future::ready(Ok(http::Response::builder() + .status(StatusCode::OK) + .header(http::header::CONTENT_TYPE, CONTENT_TYPE) + .body(body) + .expect("static response parts are valid"))) + } +} + +fn through_tonic_unary(body: ResponseBody) -> Result { + let mut grpc = tonic::client::Grpc::new(FixedResponse(Some(body))); + let path = http::uri::PathAndQuery::from_static("/test.Service/Unary"); + run(grpc.unary(tonic::Request::new(Bytes::new()), path, RawCodec)).map(|r| r.into_inner()) +} + +// T1 +#[test] +fn trailer_after_data_is_yielded_as_a_trailers_frame() { + let mut bytes = data_frame(b"hello"); + bytes.extend(trailer_frame(STATUS_13)); + + let items = frames(body(vec![bytes], false)); + + assert_eq!(items.len(), 2, "{items:?}"); + assert_eq!(items[0], Item::Data(Bytes::from(data_frame(b"hello")))); + assert_eq!(status_of(&items[1]), Some("13"), "{items:?}"); +} + +// T2 +#[test] +fn trailer_is_yielded_whatever_the_chunk_boundaries() { + let mut bytes = data_frame(b"hello"); + bytes.extend(trailer_frame(STATUS_13)); + + for chunks in splits(&bytes) { + let shape: Vec = chunks.iter().map(Vec::len).collect(); + let items = frames(body(chunks, false)); + let data: Vec = items + .iter() + .filter_map(|i| match i { + Item::Data(d) => Some(d.to_vec()), + _ => None, + }) + .flatten() + .collect(); + assert_eq!(data, data_frame(b"hello"), "chunks {shape:?}: {items:?}"); + assert_eq!( + items.last().and_then(status_of), + Some("13"), + "chunks {shape:?}: {items:?}" + ); + } +} + +// T3 +#[test] +fn trailer_frame_alone_is_yielded() { + let items = frames(body(vec![trailer_frame(STATUS_5)], false)); + + assert_eq!(items.len(), 1, "{items:?}"); + assert_eq!(status_of(&items[0]), Some("5")); +} + +// T4 +#[test] +fn stream_that_ends_inside_the_trailer_frame_is_malformed() { + let mut bytes = data_frame(b"hello"); + let data_len = bytes.len(); + bytes.extend(trailer_frame(STATUS_13)); + + // Cut after the trailer flag, inside and after its length, and inside its payload. + for cut in [ + data_len + 1, + data_len + 3, + data_len + 5, + data_len + 8, + bytes.len() - 1, + ] { + let items = frames(body(vec![bytes[..cut].to_vec()], false)); + assert_eq!( + items.last(), + Some(&Item::Malformed), + "cut at {cut}: {items:?}" + ); + } +} + +// T5 +#[test] +fn tonic_stream_reports_the_status_sent_in_the_body_trailer() { + let mut bytes = data_frame(b"hello"); + bytes.extend(trailer_frame(STATUS_13)); + + for chunks in splits(&bytes) { + let (messages, outcome) = through_tonic_stream(body(chunks, false)); + assert_eq!(messages, vec![Bytes::from_static(b"hello")]); + let status = outcome.expect_err("status 13 must reach the caller"); + assert_eq!(status.code(), Code::Internal); + assert_eq!(status.message(), "boom"); + } +} + +// T5, unary +#[test] +fn tonic_unary_call_reports_the_status_sent_after_its_message() { + let mut bytes = data_frame(b"hello"); + bytes.extend(trailer_frame(STATUS_13)); + + let status = through_tonic_unary(body(vec![bytes], false)) + .expect_err("a message followed by status 13 is a failed call"); + assert_eq!(status.code(), Code::Internal); + assert_eq!(status.message(), "boom"); +} + +// T5, a captured body +#[test] +fn tonic_reports_the_status_of_a_captured_body_trailer() { + for chunks in splits(CAPTURED_BODY_TRAILER_ERROR) { + let (messages, outcome) = through_tonic_stream(body(chunks, false)); + assert!(messages.is_empty()); + let status = outcome.expect_err("status 11 must reach the caller"); + assert_eq!(status.code(), Code::OutOfRange); + assert!(status.message().contains("newer than the latest block")); + } +} + +// T6 +#[test] +fn ok_trailer_is_yielded_and_ends_the_call_cleanly() { + let mut bytes = data_frame(b"hello"); + bytes.extend(trailer_frame(STATUS_0)); + + let items = frames(body(vec![bytes.clone()], false)); + assert_eq!(items.len(), 2, "{items:?}"); + assert_eq!(status_of(&items[1]), Some("0")); + + let (messages, outcome) = through_tonic_stream(body(vec![bytes], false)); + assert_eq!(messages, vec![Bytes::from_static(b"hello")]); + assert!(outcome.is_ok(), "{outcome:?}"); +} + +// T6, a captured body +#[test] +fn captured_successful_unary_body_still_succeeds() { + for chunks in splits(CAPTURED_DATA_THEN_TRAILER_OK) { + let message = through_tonic_unary(body(chunks, false)).expect("status 0 is success"); + assert!(!message.is_empty()); + } +} + +// G1 +#[test] +fn trailers_only_response_with_an_empty_body_ends_cleanly() { + assert_eq!(frames(body(vec![], true)), vec![]); +} + +// G1, the exception is narrow +#[test] +fn trailers_only_response_with_a_truncated_body_is_still_malformed() { + let bytes = data_frame(b"hello"); + for cut in [1, 3, bytes.len() - 1] { + let items = frames(body(vec![bytes[..cut].to_vec()], true)); + assert_eq!(items, vec![Item::Malformed], "cut at {cut}"); + } +} + +// G2 +#[test] +fn data_without_any_trailer_is_malformed() { + let items = frames(body(vec![data_frame(b"hello")], false)); + assert_eq!(items.last(), Some(&Item::Malformed), "{items:?}"); +} + +// G3 +#[test] +fn stream_that_ends_inside_a_data_frame_is_malformed() { + let bytes = data_frame(b"hello"); + let items = frames(body(vec![bytes[..bytes.len() - 2].to_vec()], false)); + assert_eq!(items, vec![Item::Malformed]); +} + +#[test] +fn nothing_is_yielded_after_the_trailers() { + let mut bytes = data_frame(b"hello"); + bytes.extend(trailer_frame(STATUS_0)); + let mut body = body(vec![bytes], false); + let mut cx = Context::from_waker(Waker::noop()); + + let mut seen = 0; + while let Poll::Ready(Some(_)) = std::pin::Pin::new(&mut body).poll_frame(&mut cx) { + seen += 1; + assert!(seen <= 2, "at most one data and one trailers frame"); + } + for _ in 0..3 { + assert!(matches!( + std::pin::Pin::new(&mut body).poll_frame(&mut cx), + Poll::Ready(None) + )); + } +} diff --git a/vendor/tonic-web-wasm-client/trailers.patch b/vendor/tonic-web-wasm-client/trailers.patch new file mode 100644 index 0000000..b8cf4a4 --- /dev/null +++ b/vendor/tonic-web-wasm-client/trailers.patch @@ -0,0 +1,98 @@ +diff --git a/src/body_stream.rs b/src/body_stream.rs +index 81af90c..55a4811 100644 +--- a/src/body_stream.rs ++++ b/src/body_stream.rs +@@ -35,6 +35,15 @@ impl BodyStream { + } + } + ++ /// A body made of in-memory chunks, for unit tests that run without a browser. ++ #[cfg(test)] ++ pub(crate) fn from_chunks(chunks: Vec) -> Self { ++ Self { ++ body_stream: Box::pin(futures_util::stream::iter(chunks.into_iter().map(Ok))), ++ _abort: None, ++ } ++ } ++ + pub fn empty() -> Self { + let body_stream = empty(); + +diff --git a/src/response_body.rs b/src/response_body.rs +index 934c05d..282827c 100644 +--- a/src/response_body.rs ++++ b/src/response_body.rs +@@ -97,10 +97,10 @@ pub enum ReadState { + } + + impl ReadState { ++ /// The body is complete only once the trailer frame has been read in full. Seeing the trailer ++ /// flag is not enough: the rest of the frame may still be on its way, or never arrive. + fn finished_data(&self) -> bool { +- matches!(self, ReadState::TrailerLength) +- || matches!(self, ReadState::Trailer(_)) +- || matches!(self, ReadState::Done) ++ matches!(self, ReadState::Done) + } + } + +@@ -130,8 +130,20 @@ impl ResponseBody { + let body_stream = + wasm_streams::ReadableStream::from_raw(body_stream.unchecked_into()).into_stream(); + ++ Self::from_body_stream( ++ BodyStream::new(body_stream, abort), ++ content_type, ++ trailers_only, ++ ) ++ } ++ ++ fn from_body_stream( ++ body_stream: BodyStream, ++ content_type: &str, ++ trailers_only: bool, ++ ) -> Result { + Ok(Self { +- body_stream: BodyStream::new(body_stream, abort), ++ body_stream, + buf: EncodedBytes::new(content_type)?, + incomplete_data: BytesMut::new(), + data: None, +@@ -284,9 +296,13 @@ impl Body for ResponseBody { + return Poll::Ready(Some(Ok(http_body::Frame::data(data.freeze())))); + } + +- // If reading data is finished return `None` ++ // Once the body is complete, hand the trailers to the caller (once), then end + if self.state.finished_data() { +- return Poll::Ready(None); ++ return Poll::Ready( ++ self.trailer ++ .take() ++ .map(|t| Ok(http_body::Frame::trailers(t))), ++ ); + } + + loop { +@@ -305,8 +321,12 @@ impl Body for ResponseBody { + let data = self.data.take().unwrap(); + return Poll::Ready(Some(Ok(http_body::Frame::data(data.freeze())))); + } else if self.state.finished_data() { +- // If we finished reading data continue return `None` +- return Poll::Ready(None); ++ // The body is complete: hand the trailers to the caller (once), then end ++ return Poll::Ready( ++ self.trailer ++ .take() ++ .map(|t| Ok(http_body::Frame::trailers(t))), ++ ); + } else if self.finished_stream { + // A trailers-only response carries its status in the HTTP headers and has an empty + // body: the stream legitimately ends before any frame header. +@@ -342,3 +362,6 @@ impl Default for ResponseBody { + } + } + } ++ ++#[cfg(test)] ++mod tests;