Skip to content

handler: PreEncoded body type + Encodable items for streaming handlers - #98

Merged
iainmcgin merged 6 commits into
mainfrom
rpb/pre-encoded-streaming-encodable
May 14, 2026
Merged

iainmcgin merged 6 commits into
mainfrom
rpb/pre-encoded-streaming-encodable

Conversation

@rpb-ant

@rpb-ant rpb-ant commented May 12, 2026 •

Copy link
Copy Markdown
Collaborator

Why

A handler that builds a *View<'a> from local app state (e.g. a resolver snapshot held in Arc) can't satisfy Handler::Body: 'static or ServiceStream<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 a PhantomData<fn() -> M> witness so the type system enforces the bytes belong to the right RPC. PreEncoded::from_view(&view) constrains V: 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.

async fn resolve(&self, _ctx: RequestContext, req: ...)
    -> ServiceResult<PreEncoded<ResolveResponse>>
{
    let snapshot = self.store.load();
    let view = build_view_from_snapshot(&snapshot, &req);
    Response::ok(PreEncoded::from_view(&view))
}

type Item: Encodable<Res> on streaming handlers

StreamingHandler, BidiStreamingHandler, and their View* variants gain type Item: Encodable<Res> + Send + 'static and return ServiceStream<Self::Item> — bringing them to parity with unary Handler::Body (which got the same treatment in 0.4.0). 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>>.

Vestigial Res: Serialize bounds dropped from the streaming wrappers — they only call Encodable::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 declares ServiceStream<impl Encodable<Out> + Send + use<Self>> (RPITIT). Existing handler impls returning ServiceStream<Out> still compile via RPITIT refinement — the same mechanism the unary Body path has used since 0.4.0, with the same allow(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_fn callers compile unchanged. The helpers infer type Item from the closure return type.
  • Only hand-rolled impl StreamingHandler / impl BidiStreamingHandler blocks need an edit — a one-line type Item = Res;. These are the low-level escape-hatch traits behind Router, not the primary handler surface. At the time of this PR there are two such impls across all known consumers.
  • Checked-in protoc-gen-connect-rust output must be regenerated — same regeneration footgun documented in 0.4.0; connectrpc-build users are unaffected.

A non-breaking alternative was considered (a separate Router::route_server_stream_pre_encoded(...) registration path that bypasses StreamingHandler entirely). It works, but permanently doubles the registration API surface and needs a per-method codegen flag, all to avoid a 2-line migration. The type Item shape is the cleaner long-term API and the precedent (unary Body in 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

  • Unit: PreEncoded::proto/from_view round-trip + JSON-unimplemented + typed-witness assertion.
  • Streaming: streaming_handler_item_is_inferred_from_closure (compile-time inference check), encode_body_stream with PreEncoded items.
  • Integration: server_stream_pre_encoded_round_trip in tests/streaming/ — registers a streaming handler with type Item = PreEncoded<EchoResponse>, runs through the full server → axum → client → decode chain.
  • All workspace tests pass; clippy -D warnings clean; nightly fmt clean.

Notes for reviewers

  • Hand-rolled streaming_handler_fn users must turbofish Res (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.

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.
@github-actions

github-actions Bot commented May 12, 2026 •

Copy link
Copy Markdown

All contributors have signed the CLA ✍️ ✅
Posted by the CLA Assistant Lite bot.

rpb-ant and others added 5 commits May 12, 2026 16:29
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).
@iainmcgin

Copy link
Copy Markdown
Collaborator

[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 (b6fc166..d5dc61f) addressing the review findings rather than relitigating in comments. Semantic diff below; happy to discuss or revert any of it.

PreEncoded constructor surface — b6fc166

PreEncoded::proto → PreEncoded::from_bytes_unchecked. The constructor wraps unvalidated bytes; the new name carries that contract at the call site (str::from_utf8_unchecked precedent). Added a debug_assert! that decodes the bytes once in debug builds to surface mismatches early.

Added PreEncoded::from_message(&m) and From<&M>. This was a gap: a stream with type Item = PreEncoded<M> mixing a cache-hit path (owned M) with a cache-miss path (view from a snapshot) had no checked way to produce the owned-message item — from_bytes_unchecked(m.encode_to_bytes()) was the only option, which throws away a guarantee for no reason. The triple now reads as a deliberate spectrum:

PreEncoded::from_message(&m)            // receiver type is the witness
PreEncoded::from_view(&view)            // MessageView::Owned = M is the witness
PreEncoded::from_bytes_unchecked(bytes) // no witness — bytes from a cache/store/sidecar

JSON codec fallback. This is the one design departure from your "Proto-only by design" stance, so flagging it explicitly. The Encodable<M> for PreEncoded<M> impl now decodes the proto bytes back to M and re-serializes for CodecFormat::Json instead of returning unimplemented. Rationale: the codec is selected per-request by the client's Content-Type, so a PreEncoded handler on a JSON-capable router will receive JSON requests, and "works slowly" beats "fails at runtime in a way nothing catches at registration." Two real consequences are documented in the new # Codec behaviour section:

  • Codec-dependent fidelity. The proto path is byte-exact; the JSON path round-trips through M. Unknown fields and non-canonical encodings survive proto and not JSON. Only relevant for from_bytes_unchecked bytes from external sources — from_message/from_view can't carry unknown fields by construction. Pinned with a test.
  • Cost is selected by the client. A client sending application/json shifts that request onto the slow decode-reserialize path (per item for streaming). The doc points services that want to enforce proto-only at the middleware layer (415 Unsupported Media Type before the body is read) rather than relying on the body type to reject it.

The Encodable impl bound tightens to M: Message + Serialize, matching the blanket impl for owned messages — not observably narrower for any buffa-generated message.

If you'd rather keep unimplemented as the default and make the fallback opt-in, that's a small change — say the word.

Coherence note correction. The original comment claimed the impl<M> Encodable<M> for PreEncoded<M> block depends on PreEncoded never implementing Message/Serialize. That's not actually the constraint — the two impls are non-overlapping for structural reasons (T = PreEncoded<T> is infinite) regardless of what PreEncoded implements. We verified this empirically and rewrote the comment with the correct argument. Worth a look since it's load-bearing reasoning for a future reader.

encode_body_stream / encode_response_stream dedup. They were byte-identical after the B-generic generalization; encode_body_stream is now a thin forward.

streaming_handler_fn doc precision. The original doc says a turbofish is required for PreEncoded items. We tested this and it's narrower than that: inference works whenever the closure pins B concretely (from_view, from_message, or PreEncoded::<M>::from_bytes_unchecked(...)). It only fails for PreEncoded::from_bytes_unchecked(bytes) with no ::<M>, and the simpler fix there is to name M at the construction site, not to spell out a 5-element turbofish on the helper. The codegen path is genuinely different (the trait method's item is the opaque RPITIT, which can't unify), and the codegen turbofishes correctly. The streaming_handler_item_is_inferred_from_closure test now demonstrates the no-turbofish PreEncoded case.

Codegen trait docstring — 19f7965

The generated # Implementing handlers section listed Out / view types / MaybeBorrowed body alternatives but not PreEncoded — the type a user needs precisely when they hit a 'static lifetime error trying to return a borrowing view. Added it, plus a paragraph explaining why streaming methods say + use<Self> (vs + use<'a, Self> on unary): stream items must be 'static, PreEncoded is the escape hatch. Regenerated the four checked-in consumers; only the docstring changed.

Bidi integration test — d5dc61f

PreEncodedEchoService::bidi_stream now yields PreEncoded items (same build-view-encode-yield-bytes shape as server_stream), and bidi_stream_pre_encoded_round_trip covers the BidiStreamingViewHandlerWrapper chain end-to-end.

Verification

cargo test --workspace 387 passed, cargo clippy --workspace --all-features --all-targets -- -D warnings clean, nightly cargo fmt --check clean, task generate:all produces no diff in */generated/connect/. The pre-existing EchoServiceImpl impls in tests/streaming/src/lib.rs returning ServiceStream<EchoResponse> compile unchanged — confirms the RPITIT refinement claim from the PR description.

@iainmcgin
iainmcgin marked this pull request as ready for review May 14, 2026 18:22
@iainmcgin
iainmcgin merged commit b4b03ac into main May 14, 2026
12 checks passed
@github-actions github-actions Bot locked and limited conversation to collaborators May 14, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants