Skip to content

interceptor: Interceptor trait, Next continuation, server registration - #114

Merged
iainmcgin merged 2 commits into
connectrpc:mainfrom
aknott-ant:aknott/interceptors-pr3-trait
May 19, 2026
Merged

iainmcgin merged 2 commits into
connectrpc:mainfrom
aknott-ant:aknott/interceptors-pr3-trait

Conversation

@aknott-ant

Copy link
Copy Markdown
Collaborator

Stacked on #113 (aknott/interceptors-pr2-payload), which is stacked
on #112.

This PR targets main, so its diff currently also includes the #112 and
#113 commits. Review only the top commit — "interceptor: Interceptor
trait, Next continuation, server registration"
. Once #112 and #113 merge,
this branch will be rebased and the diff will reduce to just that commit.
Kept as a draft until #112 and #113 land.

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 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.

Interceptor series

  1. spec: add Spec, StreamType, IdempotencyLevel; thread through dispatch #112 — Spec / StreamType / IdempotencyLevel
  2. payload: AnyMessage and Payload — type-erased, lazily-decoded message bodies #113 — AnyMessage / Payload
  3. (this PR) — Interceptor trait, Next, server registration

Verification

Run on the rebased branch (buffa 0.6.0):

  • task generate:all — no generated-code drift
  • task lint — pass
  • task test — pass, 0 failed
  • Conformance: 3600/3600 (the suite runs with zero interceptors)

@github-actions

github-actions Bot commented May 18, 2026 •

Copy link
Copy Markdown

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

@aknott-ant
aknott-ant force-pushed the aknott/interceptors-pr3-trait branch from fcaa895 to 3752bb8 Compare May 18, 2026 18:33
@aknott-ant

Copy link
Copy Markdown
Collaborator Author

I have read the CLA Document and I hereby sign the CLA

@aknott-ant
aknott-ant marked this pull request as ready for review May 18, 2026 19:47
@aknott-ant
aknott-ant force-pushed the aknott/interceptors-pr3-trait branch from 3752bb8 to 28c053c Compare May 19, 2026 00:24
iainmcgin added a commit that referenced this pull request May 19, 2026
…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).
@iainmcgin

Copy link
Copy Markdown
Collaborator

[claude code] Reviewed after rebasing onto main (post-#113/#116/#117). Clean rebase; one mechanical fixup folded into your commit (the path_flows_to_handler_context test from #116 needed the new &[] interceptors arg). 327 tests pass.

The design is sound. Next consuming self so it can be called at most once is a real improvement over connect-go's next func(...) (which is callable twice and double-runs the chain). The Arc<[Arc<dyn Interceptor>]> storage and the is_empty() fast path that skips UnaryRequest/Payload construction entirely are exactly right for the no-interceptor common case. The interceptor_wraps_unary_call e2e test exercising the full Tower + axum stack is good.

Two things I'd address before merge, both small.

High

H1 — The trait doc example canonicalizes the pattern path() exists to replace

interceptor.rs:76:

let proc = req.ctx.spec().map(|s| s.procedure).unwrap_or("<dynamic>");

Now that RequestContext::path() (#116) is in main, this is the wrong example to lead with. spec() is None for dynamic Router dispatch, and falling back to "<dynamic>" means an auth interceptor or span builder copying this pattern silently loses the method name for an entire class of routes — the exact gap path() was added to close.

The trait doc is what every interceptor author starts from. It should read:

// `ctx.path()` is the requested procedure path, populated unconditionally
// by the dispatch path. `ctx.spec()` is the *resolved* method's static
// metadata and is `None` for the dynamic `Router`; use it for
// `stream_type`/`idempotency`, not for the method name.
let proc = req.ctx.path().unwrap_or("<unknown>");
tracing::info!(%proc, "rpc start");

(The unwrap_or is for hand-built test contexts; the dispatch path always sets path() before the interceptor runs.)

Medium

M1 — No test pins that a short-circuiting interceptor's ConnectError headers reach the wire

short_circuit_skips_terminal asserts err.code but not response headers. An auth interceptor that returns Err(ConnectError::permission_denied("...").with_headers(diagnostic_headers)) relies on those headers landing in the wire response. The error renderers (error_response, grpc_error_response) do walk response_headers() — but a regression there would land silently because nothing exercises the interceptor → error → wire path end-to-end. Worth one assertion in the existing test, or one new e2e test in tests/streaming/.

M2 — Interceptor coverage is one-protocol-shape

The commit message says interceptors are threaded through "Connect unary, Connect GET, gRPC fast-path, gRPC streaming-frame unary, and the generic fallback." The only test (interceptor_wraps_unary_call) is Connect POST. The other four shapes are wired identically (call_unary_intercepted at each site), so a regression probably hits them all together — but the Connect GET path in particular is the one that matters for an authz interceptor: an idempotent unary RPC that opts into HTTP GET must not bypass the chain. One test that registers an interceptor and makes a GET request, asserting it ran, would close the gap. The gRPC fast-path one is cheaper to add inline alongside empty_chain_is_no_op since the test infra is already there.

Low / not for this PR

  • with_interceptor always wraps in a fresh Arc. There's no way to register an existing Arc<dyn Interceptor> (sharing one stateful interceptor across multiple ConnectRpcServices). The workaround is fine — interceptors carry their shared state internally as Arc<...>, so the interceptor doesn't need to be shared — but a with_interceptor_arc overload is a cheap ergonomic add if anyone asks.
  • DispatchTerminal::call does payload.encoded() (one Bytes clone for the no-replacement case) and the handler's call_unary decodes again. An interceptor that calls payload.message() decodes once; the handler decodes a second time on the same bytes. Fine for the foundation PR, worth a tracking note for a future change that has the dispatcher accept Payload directly.

I'll push the H1 fix and the M1/M2 tests directly per Iain's go-ahead.

iainmcgin added a commit to aknott-ant/connect-rust that referenced this pull request May 19, 2026
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>
@iainmcgin
iainmcgin force-pushed the aknott/interceptors-pr3-trait branch from 28c053c to 4efc205 Compare May 19, 2026 18:31
iainmcgin added a commit to aknott-ant/connect-rust that referenced this pull request May 19, 2026
…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>
@iainmcgin
iainmcgin force-pushed the aknott/interceptors-pr3-trait branch from 4efc205 to dbe28d9 Compare May 19, 2026 19:04
iainmcgin added a commit to aknott-ant/connect-rust that referenced this pull request May 19, 2026
…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>
@iainmcgin
iainmcgin force-pushed the aknott/interceptors-pr3-trait branch from dbe28d9 to f785b4f Compare May 19, 2026 19:42
…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>
@iainmcgin
iainmcgin force-pushed the aknott/interceptors-pr3-trait branch from f785b4f to d52739f Compare May 19, 2026 19:54
@iainmcgin
iainmcgin merged commit b2e93a3 into connectrpc:main May 19, 2026
12 checks passed
@github-actions github-actions Bot locked and limited conversation to collaborators May 19, 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