Skip to content

RequestContext: #[non_exhaustive] + accessor methods - #101

Merged
iainmcgin merged 1 commit into
mainfrom
iainmcgin/issue-89-request-context-non-exhaustive
May 15, 2026
Merged

iainmcgin merged 1 commit into
mainfrom
iainmcgin/issue-89-request-context-non-exhaustive

Conversation

@iainmcgin

Copy link
Copy Markdown
Collaborator

Fixes #89

RequestContext was a pub-fields struct without #[non_exhaustive], so any new field is a SemVer break. We've already grown it once (mTLS routed connection-scoped data through extensions precisely to avoid a new field), and the post-0.4.0 ergonomics review identified several more candidate fields — service name, method name, RPC kind, negotiated protocol — all wanted by generic middleware and interceptors. This PR locks the contract before any of them land under pressure.

What changed

RequestContext is now #[non_exhaustive] with pub(crate) fields. Fields are read through accessors:

Old New
ctx.headers ctx.headers() (ctx.header(name) for a single lookup is unchanged)
ctx.deadline ctx.deadline()
ctx.extensions ctx.extensions()

Construction (RequestContext::new(headers), .with_deadline(), .with_extensions()) is unchanged, so dispatch code and test setup don't move.

Additive accessors

  • time_remaining() — saturating Duration until the deadline. Lets handlers budget downstream calls without doing the deadline - Instant::now() arithmetic and underflow check themselves. This is the read side of the deadline-enforcement work in Deadline is parsed but not enforced — handler runs to completion after Connect-Timeout-Ms lapses #92.
  • extensions_mut() — for tower middleware or test shims that construct a RequestContext directly and need to insert connection-scoped values before dispatch.
  • peer_addr() (server feature) and peer_certs() (server-tls feature) — typed extension lookups for the well-known peer types. They return None when the transport didn't insert the value, replacing the ctx.extensions.get::<PeerAddr>().unwrap() pattern that compiles, passes in unit tests, and panics in production behind a transport that didn't insert it.

Migration

Mechanical for almost everyone: add parentheses. The mtls-identity example, conformance server, middleware example, and the user guide are updated in this PR as the model migration. The mtls-identity extract_identity signature changes from Option<&PeerCerts> to Option<&[CertificateDer<'static>]> to match what ctx.peer_certs() returns — that's the one non-trivial change.

Verification

task lint, task test, cargo check -p connectrpc --no-default-features, cargo check -p connectrpc --all-features, and cargo doc -p connectrpc --all-features (intra-doc-link check) are all clean. Net change excluding tests: ~180 lines.

@github-actions

github-actions Bot commented May 14, 2026 •

Copy link
Copy Markdown

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

rpb-ant
rpb-ant previously approved these changes May 15, 2026
iainmcgin added a commit that referenced this pull request May 15, 2026
Fixes #92.

Adds `DeadlinePolicy` for server-side moderation of client-asserted RPC
deadlines. A client controls the per-request timeout via
`Connect-Timeout-Ms` / `grpc-timeout`; without a policy the server
trusts that value verbatim — a 1ms request cancels the handler
mid-write, a 24h request holds a worker indefinitely, no header means no
bound, and once a streaming handler returns its stream the items flow
unbounded regardless of the header.

`DeadlinePolicy` clamps the client value to a server-controlled `[min,
max]`, supplies a default when the client asserts nothing (or sends
garbage), and optionally extends enforcement to streaming response
bodies and to the gap between yielded items.

```rust
let policy = DeadlinePolicy::new()
    .with_min(Duration::from_millis(5))
    .with_max(Duration::from_secs(30))
    .with_default(Duration::from_secs(10))
    .with_enforce_on_streams(true);
ConnectRpcService::new(router).with_deadline_policy(policy)
// or: Server::new(router).deadline_policy(policy)
```

`DeadlinePolicy::new()` is a strict no-op — no clamping, no default, no
stream enforcement. **Existing services that don't set a policy see
exactly the previous behavior**, so this is purely additive and safe in
0.5.0. The recommended production starting point is at least
`with_max()` and `with_default()`.

`min` is `Duration` (not `Option`) because zero is a natural identity
for a floor; `max`/`default` are `Option<Duration>` because there's no
clean identity for them. The asymmetry is deliberate.

Stream-body enforcement (when `enforce_on_streams` is set) is a
pin-projected wrapper applied to server- and bidi-streaming response
bodies. Unary and client-streaming responses are already bounded by the
existing `tokio::time::timeout` on the handler future.
`inter_message_timeout` re-arms a per-item timer to detect stalled
streams independent of the absolute deadline.

When a clamp changes the client value, a `tracing::debug!` event fires
on target `connectrpc::deadline` with the path and before/after
durations.

### Notes for reviewers

- `Server::with_deadline_policy()` is a new delegating builder (renamed
from `deadline_policy()` after review to match
`ConnectRpcService::with_deadline_policy` and avoid colliding with the
same-named getter on `ConnectRpcService`). `Server` does not yet proxy
`ConnectRpcService::with_compression()` / `with_compression_policy()` /
`with_limits()` — that's a pre-existing gap; the
`Server::from_service(ConnectRpcService::new(...).with_*(...))` path is
the canonical way to set those today. Worth a follow-up to either add
the missing proxies or document `from_service` as the configuration
path.
- `enforce_on_streams` and `inter_message_timeout` are independent knobs
— either alone wraps the stream. Both default off.
- `RequestContext.deadline` reflects the *moderated* value once a policy
is set; the field doc cross-links `DeadlinePolicy`. PR #101 (issue #89)
replaces the field with a `deadline()` accessor and adds
`time_remaining()` — there will be a small merge conflict in
`response.rs` between this PR and #101, expected and trivial.
- I have not run the conformance suite locally (the runner wasn't
downloaded in the dev environment). Since `DeadlinePolicy::new()` is a
strict identity (`moderate` returns the input unchanged;
`enforce_on_response_stream` returns the stream unchanged), conformance
behavior is provably unaffected without a configured policy. CI runs the
full suite.
- Per-route deadline policy is deferred to a follow-up coupled to the
typed routing surface (#91). A per-path string map now would be a second
stringly-typed route surface that #91 wants to remove.
- Net change in `connectrpc/src/`: ~250 lines excluding tests and doc
comments. The `deadline.rs` file is large because of doc-comment density
on every public knob.
@iainmcgin
iainmcgin enabled auto-merge (squash) May 15, 2026 16:02
@iainmcgin
iainmcgin force-pushed the iainmcgin/issue-89-request-context-non-exhaustive branch from 424e8cc to d9fc62b Compare May 15, 2026 16:02
Mark `RequestContext` `#[non_exhaustive]` and convert its `pub` fields
(`headers`, `deadline`, `extensions`) to `pub(crate)` with read
accessors. New request-scoped metadata (method name, RPC kind,
negotiated protocol — wanted by interceptor and observability work) can
now ship as non-breaking additions instead of one semver bump per field.

Migration: `ctx.headers` -> `ctx.headers()`, `ctx.deadline` ->
`ctx.deadline()`, `ctx.extensions` -> `ctx.extensions()`. Construction
via `RequestContext::new(headers)` and the `with_*` builders is
unchanged.

Additive accessors landed alongside the change:
- `time_remaining()` — saturating Duration until the deadline, for
  budgeting downstream calls (referenced by deadline-enforcement work
  in #92).
- `extensions_mut()` — for tower middleware that builds the context
  directly.
- `peer_addr()` (server feature) and `peer_certs()` (server-tls
  feature) — typed extension lookups for the well-known peer types.
  They return None when the transport didn't insert the value,
  replacing the panic-prone `extensions().get::<PeerAddr>().unwrap()`
  pattern. The mtls-identity example, the conformance server, and the
  in-crate tests are all updated to use them.

Updated: docs/guide.md RequestContext table, examples/middleware,
examples/mtls-identity (extract_identity now takes
&[CertificateDer] instead of &PeerCerts), and CHANGELOG.
@iainmcgin
iainmcgin force-pushed the iainmcgin/issue-89-request-context-non-exhaustive branch from d9fc62b to 8b48a52 Compare May 15, 2026 16:08
@iainmcgin
iainmcgin merged commit bc0d9a7 into main May 15, 2026
12 checks passed
@github-actions github-actions Bot locked and limited conversation to collaborators May 15, 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.

RequestContext field exposure: decide #[non_exhaustive] / accessor policy before adding fields

2 participants