Repository navigation
RequestContext: #[non_exhaustive] + accessor methods - #101
Merged
iainmcgin merged 1 commit intoMay 15, 2026
Merged
Conversation
|
All contributors have signed the CLA ✍️ ✅ |
iainmcgin
force-pushed
the
iainmcgin/issue-89-request-context-non-exhaustive
branch
from
May 14, 2026 22:11
fc4a16e to
2f5ea42
Compare
iainmcgin
marked this pull request as ready for review
May 14, 2026 22:30
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
enabled auto-merge (squash)
May 15, 2026 16:02
iainmcgin
force-pushed
the
iainmcgin/issue-89-request-context-non-exhaustive
branch
from
May 15, 2026 16:02
424e8cc to
d9fc62b
Compare
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
force-pushed
the
iainmcgin/issue-89-request-context-non-exhaustive
branch
from
May 15, 2026 16:08
d9fc62b to
8b48a52
Compare
rpb-ant
approved these changes
May 15, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #89
RequestContextwas apub-fields struct without#[non_exhaustive], so any new field is a SemVer break. We've already grown it once (mTLS routed connection-scoped data throughextensionsprecisely 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
RequestContextis now#[non_exhaustive]withpub(crate)fields. Fields are read through accessors:ctx.headersctx.headers()(ctx.header(name)for a single lookup is unchanged)ctx.deadlinectx.deadline()ctx.extensionsctx.extensions()Construction (
RequestContext::new(headers),.with_deadline(),.with_extensions()) is unchanged, so dispatch code and test setup don't move.Additive accessors
time_remaining()— saturatingDurationuntil the deadline. Lets handlers budget downstream calls without doing thedeadline - 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 aRequestContextdirectly and need to insert connection-scoped values before dispatch.peer_addr()(serverfeature) andpeer_certs()(server-tlsfeature) — typed extension lookups for the well-known peer types. They returnNonewhen the transport didn't insert the value, replacing thectx.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_identitysignature changes fromOption<&PeerCerts>toOption<&[CertificateDer<'static>]>to match whatctx.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, andcargo doc -p connectrpc --all-features(intra-doc-link check) are all clean. Net change excluding tests: ~180 lines.