Repository navigation
handler: PreEncoded body type + Encodable items for streaming handlers - #98
Conversation
Adds PreEncoded<M>, an Encodable<M> body that wraps already-encoded protobuf bytes, and a `type Item: Encodable<Res>` associated type on StreamingHandler/BidiStreamingHandler (and their View* variants) so streaming handlers can yield Encodable items rather than bare Res. Why: a handler that builds a *View<'a> from local app state (e.g. a resolver snapshot held in Arc) can't satisfy `Body: 'static` or `ServiceStream<Res>` — the only ViewEncode-friendly bodies today are request-buffer-backed (OwnedView, MaybeBorrowed). Such handlers need to encode internally and return the bytes. PreEncoded::from_view(&v) does exactly that, with a `MessageView<'a, Owned = M>` bound as a compile-time witness that the bytes decode as M. `type Item` brings the streaming traits to parity with unary Handler::Body. encode_body_stream / encode_response_stream are generalized over `B: Encodable<Res>`; codegen emits the streaming trait method as `ServiceStream<impl Encodable<Out> + Send + use<Self>>` so route-registration closures don't capture &self's lifetime. Vestigial `Res: Serialize` bounds dropped from the streaming wrappers and registrations — they only call `Encodable::encode`, which is codec-agnostic. Breaking: custom `impl StreamingHandler` blocks must add `type Item = Res;`. The `*_handler_fn` helpers infer it.
|
All contributors have signed the CLA ✍️ ✅ |
The streaming type Item change reads as a wide break but the practical surface is two hand-rolled impl StreamingHandler blocks across all known consumers — codegen-generated traits and *_handler_fn callers compile unchanged via RPITIT refinement (same as unary Body in 0.4.0). Added a leading note distinguishing semver-breaking from practically-breaking, and grounded each bullet in who actually has to change something.
Address review findings on PR #98: - Rename PreEncoded::proto -> from_bytes_unchecked. The constructor wraps unvalidated bytes; the new name carries that contract at the call site (str::from_utf8_unchecked precedent). Add a debug_assert! that decodes the bytes once in debug builds to surface mismatches early. - Add PreEncoded::from_message(&m) (and From<&M>) for the case where the handler has an owned M and wants to share the encoding (encode once, clone the Bytes-backed PreEncoded for N readers) or mix owned-message and view-built items under a single `type Item = PreEncoded<M>`. The receiver type is the witness, so this is the checked path; previously the only option for an owned M was the unchecked from_bytes_unchecked(m.encode_to_bytes()). Three constructors total, in decreasing order of compile-time guarantee: from_message, from_view, from_bytes_unchecked. - Implement the JSON codec for PreEncoded by decoding the proto bytes back to M and re-serializing. Slow (proto round-trip per item) but correct: a JSON-capable router with a PreEncoded handler degrades gracefully instead of returning Unimplemented at runtime. The Encodable<M> impl bound tightens to M: Message + Serialize, matching the blanket impl for owned messages. Document the perf cliff prominently and the recommended alternative (return owned). - Correct the coherence note above the PreEncoded Encodable impl. The original claimed it depends on PreEncoded never implementing Message or Serialize; it actually doesn't — the two impls are non-overlapping for structural reasons (no T satisfies T = PreEncoded<T>) regardless. - Reduce encode_body_stream to a thin forward to dispatcher::codegen::encode_response_stream. The two were byte- identical after the B-generic generalization; one canonical impl. - Fix the streaming_handler_fn doc: a turbofish is only needed when the closure leaves the message type open (PreEncoded::from_bytes_unchecked with no ::<M>). Naming M at the construction site is the simpler fix. Update the inference test to demonstrate the no-turbofish case. - Tests: pre_encoded_from_message, pre_encoded_json_decodes_then_serializes, pre_encoded_json_decode_failure_is_internal_error, pre_encoded_from_bytes_unchecked_debug_asserts, encode_body_stream_pre_encoded_json_decodes_per_item.
The trait-level # Implementing handlers section listed owned, view, and MaybeBorrowed body alternatives but omitted PreEncoded — the type a user needs precisely when they hit a 'static lifetime error trying to return a borrowing view. Add it, and add a paragraph explaining the use<Self> precise-capturing clause on streaming methods (why stream items must be 'static, and that PreEncoded is the escape hatch). Regenerate the four checked-in consumers (eliza, multiservice, conformance, benches/rpc) to pick up the new docstring.
Bidi streaming has the same type Item plumbing as server-streaming but lacked end-to-end coverage. Change PreEncodedEchoService::bidi_stream to yield PreEncoded items (build view per request, encode while the borrow is live, yield bytes — same shape as server_stream) and add bidi_stream_pre_encoded_round_trip, modeled on the existing raw-envelope bidi test (the generated client BidiStream stub needs HTTP/2).
|
[claude code] Reviewed in detail with @iainmcgin — the abstraction is sound and the breaking-change blast radius assessment in the description is accurate. We pushed three commits on top (
|
Why
A handler that builds a
*View<'a>from local app state (e.g. a resolver snapshot held inArc) can't satisfyHandler::Body: 'staticorServiceStream<Res>today — the only ViewEncode-friendly bodies are request-buffer-backed (OwnedView,MaybeBorrowed). Such handlers need to encode the view internally while the snapshot is still in scope, then return the bytes.This unblocks the dominant ViewEncode use case for high-throughput servers: 1-source-to-N-readers fanout where each per-reader response borrows from a shared decoded source. Codec-layer benches (
benches/rpc/echo_bloat.rs, fanout sweep at N=64) show ~3.5× over the move-baseline; resolver-shaped workloads (~1k endpoints with string-map metadata per response) measure 2.8–4.2× depending on compression.What
PreEncoded<M>An
Encodable<M>body that wraps already-encoded protobuf bytes, with aPhantomData<fn() -> M>witness so the type system enforces the bytes belong to the right RPC.PreEncoded::from_view(&view)constrainsV: MessageView<'a, Owned = M>for a compile-time match.Proto-only by design. JSON clients receive
unimplemented, same as the existing per-output-type view-body impls. ViewEncode is a high-throughput optimization; JSON is not a high-throughput codec, and supporting both would add a runtime format check on every encode for no realistic consumer.type Item: Encodable<Res>on streaming handlersStreamingHandler,BidiStreamingHandler, and theirView*variants gaintype Item: Encodable<Res> + Send + 'staticand returnServiceStream<Self::Item>— bringing them to parity with unaryHandler::Body(which got the same treatment in 0.4.0).encode_body_stream/encode_response_streamare generalized overB: Encodable<Res>. Codegen emits the streaming trait method asServiceStream<impl Encodable<Out> + Send + use<Self>>.Vestigial
Res: Serializebounds dropped from the streaming wrappers — they only callEncodable::encode, which is codec-agnostic.Breaking — but the practical surface is narrow
This is breaking under semver, but the practical blast radius is much smaller than the trait change suggests:
impl <GeneratedServiceTrait>blocks compile unchanged. The generated trait declaresServiceStream<impl Encodable<Out> + Send + use<Self>>(RPITIT). Existing handler impls returningServiceStream<Out>still compile via RPITIT refinement — the same mechanism the unaryBodypath has used since 0.4.0, with the sameallow(refining_impl_trait)already documented in 0.4.1. Verified:tests/streaming/src/lib.rs's pre-existing handlers were not touched in this diff.*_handler_fncallers compile unchanged. The helpers infertype Itemfrom the closure return type.impl StreamingHandler/impl BidiStreamingHandlerblocks need an edit — a one-linetype Item = Res;. These are the low-level escape-hatch traits behindRouter, not the primary handler surface. At the time of this PR there are two such impls across all known consumers.protoc-gen-connect-rustoutput must be regenerated — same regeneration footgun documented in 0.4.0;connectrpc-buildusers are unaffected.A non-breaking alternative was considered (a separate
Router::route_server_stream_pre_encoded(...)registration path that bypassesStreamingHandlerentirely). It works, but permanently doubles the registration API surface and needs a per-method codegen flag, all to avoid a 2-line migration. Thetype Itemshape is the cleaner long-term API and the precedent (unaryBodyin 0.4.0) was a bigger break and shipped without issue.Size
~700 lines net (excluding generated). Over the usual 250 guideline because the change is coupled: the trait,
encode_body_stream, the dispatcher, the codegen, and the regenerated checked-in code all have to move together — splitting would leave intermediate states uncompilable.Tests
PreEncoded::proto/from_viewround-trip + JSON-unimplemented + typed-witness assertion.streaming_handler_item_is_inferred_from_closure(compile-time inference check),encode_body_streamwithPreEncodeditems.server_stream_pre_encoded_round_tripintests/streaming/— registers a streaming handler withtype Item = PreEncoded<EchoResponse>, runs through the full server → axum → client → decode chain.-D warningsclean; nightly fmt clean.Notes for reviewers
streaming_handler_fnusers must turbofishRes(streaming_handler_fn::<_, _, Req, Res, PreEncoded<Res>>(...)) since the generic body type makes it non-inferable. The codegen-driven path (the common case) hides this. Documented on the helper's doc comment.