Repository navigation
interceptor: Interceptor trait, Next continuation, server registration - #114
Conversation
|
All contributors have signed the CLA ✍️ ✅ |
fcaa895 to
3752bb8
Compare
|
I have read the CLA Document and I hereby sign the CLA |
3752bb8 to
28c053c
Compare
…116) ## Why `Spec` (#112) gives interceptors and span builders the resolved method's static metadata, but only when a generated `FooServiceServer<T>` dispatcher matched the route — `Spec.procedure` is `&'static str`, and the dynamic `Router` can't supply one because its keys are owned `String`s. By the time an interceptor (#114) runs, `handle_*_request` has already consumed the `http::Request`, so there is no way back to the request URI. An interceptor that must label or gate *every* request — an auth boundary, a span builder, a rate limiter — therefore has no reliable source for the method name on the dynamic-`Router` path. ## What `RequestContext::path()` carries the requested procedure path (`/package.Service/Method`) unconditionally — populated at every dispatch site from the request URI. It is the *wire truth*; `spec()` remains the source of *resolved* static metadata (stream type, idempotency level). When both are present they're identical strings; `path()` exists for the cases where `spec()` cannot be. Storage is `Option<String>` (matching `spec()`/`protocol()`), `None` only for hand-built contexts. The leading slash matches `Spec::procedure`, connect-go's `Spec.Procedure`, and `http::Uri::path()`. The five `RequestContext::new(...)` call sites already have the stripped lookup-key form (`pkg.Service/Method`) in scope; the leading slash is reconstructed via `format!("/{path}")`. `strip_prefix('/')` removes at most one leading slash, so the round-trip is exact for any HTTP request that reaches the dispatch layer. ## Confidence - `request_context_with_path` (response.rs) — builder round-trips, `None` for hand-built contexts, `Some("")` preserved verbatim. - `path_flows_to_handler_context` (service.rs) — dispatches a request to `/svc/Method` through the dynamic `Router` and asserts the handler sees `path() == Some("/svc/Method")` *and* `spec() == None` — the case `path()` exists for. - `cargo test` (306 pass), `cargo fmt`, `cargo clippy --all-targets -- -D warnings`, `cargo doc` all clean. `cargo check --all-features` clean. - No wire-format change (the new field is consumed only by handler code). ## Possible follow-ups (not blocking) - Each request currently allocates twice on the dispatch path: once for the stripped lookup key (pre-existing) and once for `format!("/{path}")`. They can be collapsed to one by capturing the un-stripped URI path first and slicing it for the lookup key, at the cost of restructuring borrow scopes. ~30-byte alloc per request is noise next to the body buffer and `HeaderMap` clone on the same path; worth it if `benches/rpc/` shows a difference. - Test coverage exercises `handle_unary_request`; the gRPC-fast-path and streaming entry points use the same `format!("/{path}")` recipe but aren't independently covered. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
Add a connect-go-style typed unary interceptor surface. Interceptors
wrap a single RPC after envelope decoding, decompression, and header
parsing, and before the handler — they see the parsed Spec, headers,
deadline, extensions, and a lazily-decoded Payload, and can rewrite the
request and response messages.
- `Interceptor` async trait with a default-passthrough `intercept_unary`.
Annotate impls with the re-exported `#[connectrpc::async_trait]` —
there is no separate `async-trait` dependency for downstream crates.
- `Next<'a>` continuation: holds the rest of the chain and a
`pub(crate)` terminal. `run(self, req)` consumes it; an interceptor
can call it at most once (enforced by the type system), and not
calling it short-circuits the chain.
- `UnaryRequest { ctx, payload }` (`#[non_exhaustive]`) and
`UnaryResponse = Response<Payload>` so `with_header`/`with_trailer`/
`compress`/`map_body` are inherited.
- `unary_interceptor(closure)` for closure-shaped interceptors, and
`interceptor::run_chain(chain, req, terminal_fn)` so interceptor
authors can unit-test without a tower service or TCP listener.
- `ConnectRpcService::with_interceptor` builder; chain stored as
`Arc<[Arc<dyn Interceptor>]>` for one Arc bump per request.
- `call_unary_intercepted` with an `is_empty()` fast path that
delegates straight to `dispatcher.call_unary` — when no interceptors
are registered the dispatch path is byte-identical to before.
Threaded through the five `call_unary` sites in `service.rs` (Connect
unary, Connect GET, gRPC fast-path, gRPC streaming-frame unary, and
the generic fallback). Streaming RPCs bypass the chain in this release.
Conformance: 3600/3600 (the suite runs with zero interceptors).
|
[claude code] Reviewed after rebasing onto The design is sound. Two things I'd address before merge, both small. HighH1 — The trait doc example canonicalizes the pattern
|
Addresses review at connectrpc#114 (comment): - The trait doc example used `spec().map(|s| s.procedure).unwrap_or("<dynamic>")` — the pattern that loses the method name for dynamic Router routes, which is exactly what RequestContext::path() (connectrpc#116) was added to close. Switched to path() so interceptor authors copying the example get the always-present procedure path, with a note on when to read spec() instead. - short_circuit_skips_terminal now also asserts that diagnostic headers attached to the deny error survive the chain — auth interceptors attach operator-facing hints (which policy denied) and rely on them reaching the wire response. - New test pinning that call_unary_intercepted propagates a short-circuit error verbatim (code + headers) without invoking the dispatcher. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
28c053c to
4efc205
Compare
…ET tests Addresses review at connectrpc#114 (comment): - The trait doc example used `spec().map(|s| s.procedure).unwrap_or("<dynamic>")` — the pattern that loses the method name for dynamic Router routes, which is exactly what RequestContext::path() (connectrpc#116) was added to close. Switched to path() so interceptor authors copying the example get the always-present procedure path, with a note on when to read spec() instead. - short_circuit_skips_terminal now also asserts that diagnostic headers attached to the deny error survive the chain — auth interceptors attach operator-facing hints (which policy denied) and rely on them reaching the wire response. - New test pinning that call_unary_intercepted propagates a short-circuit error verbatim (code + headers) without invoking the dispatcher. - New test pinning that interceptors run on the Connect GET path — an idempotent unary RPC accessed via HTTP GET must not bypass an authz interceptor. Connect POST already had e2e coverage; the GET path was wired identically but untested. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
4efc205 to
dbe28d9
Compare
…ET tests Addresses review at connectrpc#114 (comment): - The trait doc example used `spec().map(|s| s.procedure).unwrap_or("<dynamic>")` — the pattern that loses the method name for dynamic Router routes, which is exactly what RequestContext::path() (connectrpc#116) was added to close. Switched to path() so interceptor authors copying the example get the always-present procedure path, with a note on when to read spec() instead. - short_circuit_skips_terminal now also asserts that diagnostic headers attached to the deny error survive the chain — auth interceptors attach operator-facing hints (which policy denied) and rely on them reaching the wire response. - New test pinning that call_unary_intercepted propagates a short-circuit error verbatim (code + headers) without invoking the dispatcher. - New test pinning that interceptors run on the Connect GET path — an idempotent unary RPC accessed via HTTP GET must not bypass an authz interceptor. Connect POST already had e2e coverage; the GET path was wired identically but untested. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
dbe28d9 to
f785b4f
Compare
…ET tests Addresses review at connectrpc#114 (comment): - The trait doc example used `spec().map(|s| s.procedure).unwrap_or("<dynamic>")` — the pattern that loses the method name for dynamic Router routes, which is exactly what RequestContext::path() (connectrpc#116) was added to close. Switched to path() so interceptor authors copying the example get the always-present procedure path, with a note on when to read spec() instead. - short_circuit_skips_terminal now also asserts that diagnostic headers attached to the deny error survive the chain — auth interceptors attach operator-facing hints (which policy denied) and rely on them reaching the wire response. - New test pinning that call_unary_intercepted propagates a short-circuit error verbatim (code + headers) without invoking the dispatcher. - New test pinning that interceptors run on the Connect GET path — an idempotent unary RPC accessed via HTTP GET must not bypass an authz interceptor. Connect POST already had e2e coverage; the GET path was wired identically but untested. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
f785b4f to
d52739f
Compare
Summary
PR 3 of the interceptor series — the user-facing surface. Adds a
connect-go-style typed unary interceptor. Interceptors wrap a single RPC
after envelope decoding, decompression, and header parsing, and before the
handler — they see the parsed
Spec, headers, deadline, extensions, and alazily-decoded
Payload, and can rewrite the request and response messages.Interceptorasync trait with a default-passthroughintercept_unary.Annotate impls with the re-exported
#[connectrpc::async_trait]— there isno separate
async-traitdependency for downstream crates.Next<'a>continuation: holds the rest of the chain and apub(crate)terminal.run(self, req)consumes it; an interceptor cancall it at most once (enforced by the type system), and not calling it
short-circuits the chain.
UnaryRequest { ctx, payload }(#[non_exhaustive]) andUnaryResponse = Response<Payload>sowith_header/with_trailer/compress/map_bodyare inherited.unary_interceptor(closure)for closure-shaped interceptors, andinterceptor::run_chain(chain, req, terminal_fn)so interceptor authorscan unit-test without a tower service or TCP listener.
ConnectRpcService::with_interceptorbuilder; chain stored asArc<[Arc<dyn Interceptor>]>for one Arc bump per request.call_unary_interceptedwith anis_empty()fast path that delegatesstraight to
dispatcher.call_unary— when no interceptors are registeredthe dispatch path is byte-identical to before.
Threaded through the five
call_unarysites inservice.rs(Connect unary,Connect GET, gRPC fast-path, gRPC streaming-frame unary, and the generic
fallback). Streaming RPCs bypass the chain in this release.
Interceptor series
Spec/StreamType/IdempotencyLevelAnyMessage/PayloadInterceptortrait,Next, server registrationVerification
Run on the rebased branch (buffa 0.6.0):
task generate:all— no generated-code drifttask lint— passtask test— pass, 0 failed