Skip to main content

RequestContext

Struct RequestContext 

Source
#[non_exhaustive]
pub struct RequestContext { /* private fields */ }
Expand description

Read-only request context passed to RPC handlers.

Carries the request headers, parsed deadline, and any connection-scoped extensions (peer address, TLS certs, auth context) inserted by a tower layer in front of the service. Handlers do not return this; response-side metadata lives on Response.

RequestContext is #[non_exhaustive]: construct it with RequestContext::new and the with_* builders, and read fields through the accessor methods (headers(), deadline(), extensions(), …). New request-scoped metadata can be added in minor releases without breaking downstream code.

Implementations§

Source§

impl RequestContext

Source

pub fn new(headers: HeaderMap) -> Self

Create a new context with the given request headers.

Source

pub fn with_deadline(self, deadline: Option<Instant>) -> Self

Set the request deadline (absolute Instant).

Source

pub fn with_extensions(self, extensions: Extensions) -> Self

Attach request extensions captured from the underlying http::Request.

Source

pub fn with_spec(self, spec: Option<Spec>) -> Self

Attach the static method metadata for the dispatched RPC.

Source

pub fn with_protocol(self, protocol: Option<Protocol>) -> Self

Attach the negotiated wire protocol.

Source

pub fn with_path(self, path: impl Into<String>) -> Self

Attach the procedure path the client requested. The dispatch path always supplies the leading-slash form ("/package.Service/Method"), matching Spec::procedure; custom dispatch shims and test fixtures should do the same so consumers of path() see a consistent shape.

Source

pub fn headers(&self) -> &HeaderMap

Request headers (after protocol-prefix stripping).

For a single header lookup, header is simpler.

Source

pub fn header(&self, key: impl AsHeaderName) -> Option<&HeaderValue>

Get a request header value.

Source

pub fn deadline(&self) -> Option<Instant>

Absolute request deadline parsed from the protocol’s timeout header (Connect-Timeout-Ms or grpc-timeout), if the client asserted one.

Propagate this to downstream calls so the whole call chain shares a single budget. For the remaining budget as a Duration, see time_remaining.

If a DeadlinePolicy is configured on the service, this is the moderated value — clamped to the policy’s [min, max] range, or the policy default when the client asserted nothing — not the raw client header.

Source

pub fn time_remaining(&self) -> Option<Duration>

Time remaining until the request deadline, saturating at zero.

None if the client did not assert a timeout. Use this to budget downstream calls — for example, subtract a margin before passing the remainder as a downstream RPC’s per-call timeout. See also issue #92 for server-side deadline enforcement.

Source

pub fn extensions(&self) -> &Extensions

Request extensions carried from the underlying http::Request.

This is the passthrough for connection-scoped metadata that a tower layer in front of the service can attach — TLS peer certificates, remote socket address, auth context, etc. The dispatch path moves parts.extensions here verbatim; handlers read it with ctx.extensions().get::<T>(). For the well-known peer types, prefer the typed accessors peer_addr() and peer_certs() (gated on the server and server-tls features respectively) — they return None instead of panicking when the transport didn’t insert the extension.

Source

pub fn extensions_mut(&mut self) -> &mut Extensions

Mutable access to the request extensions.

Useful for code that constructs a RequestContext directly — e.g. a custom dispatch shim or test fixture — and needs to insert connection-scoped values before calling a handler.

§Note

Handlers receive RequestContext by value, so calling ctx.extensions_mut().insert(...) inside a handler mutates a local copy that the framework never sees again — it has no effect on the dispatch path or on downstream layers. To pass values into a handler from middleware, mutate http::Request::extensions_mut() in the layer instead; the dispatcher moves request extensions into RequestContext automatically before dispatch.

Source

pub fn spec(&self) -> Option<Spec>

Static metadata for the dispatched RPC method, when known.

Populated by code-generated FooServiceServer<T> dispatchers and by the dynamic Router when registered through the generated register() (which chains Router::with_spec per route). None only for routes registered through the manual route_* builders without a with_spec call. See path for the always-present procedure path.

Source

pub fn protocol(&self) -> Option<Protocol>

The wire protocol negotiated for this request, when known.

None if the runtime constructed the context outside the dispatch path (e.g. unit tests calling handlers directly).

Source

pub fn path(&self) -> Option<&str>

The procedure path the client requested, "/package.Service/Method".

Always present when constructed by the dispatch path: it is taken from the request URI, so it is populated whenever a handler is dispatched — including dispatch through the dynamic Router, which does not supply a Spec. None only for hand-built contexts (unit tests calling handlers directly, custom dispatch shims). Code that must label or gate every request — auth interceptors, span builders, rate limiters — should read path(), not spec(), and treat None as a misconfigured or synthetic context rather than a real RPC.

Compare spec(): that is the registered method’s static metadata, populated only when a generated FooServiceServer<T> dispatcher resolved the route, and Spec::procedure is its &'static str procedure name. When both are present they are identical strings; path() exists for the cases where spec() cannot be.

The leading slash is included to match Spec::procedure, the connect-go Spec.Procedure convention, and http::Uri::path() for any HTTP request that reached the dispatch layer. To compare against Dispatcher::lookup keys (which omit it), use path.strip_prefix('/').unwrap_or(path).

Source

pub fn peer_addr(&self) -> Option<SocketAddr>

Available on crate feature server only.

Remote peer socket address, if the transport recorded one.

Present when the request arrived through Server::serve (plain) or Server::with_tls(...) (TLS), or any integration that inserts PeerAddr into the request extensions (connectrpc::axum::serve_tls does). Returns None otherwise (e.g. an axum app without a layer that captures the connect info), so prefer this over ctx.extensions().get::<PeerAddr>().unwrap() — the latter compiles, passes in unit tests, and panics in production behind a transport that didn’t insert it.

Source

pub fn peer_certs(&self) -> Option<&[CertificateDer<'static>]>

Available on crate feature server-tls only.

TLS client certificate chain presented by the peer (leaf first), if any.

Present only when the request arrived over a TLS listener that requested a client certificate and the client presented one — see Server::with_tls and connectrpc::axum::serve_tls. Returns None for plaintext transports, for TLS without mutual auth, and for integrations that don’t insert PeerCerts into the request extensions. Like peer_addr, prefer this over a raw extensions().get() + unwrap().

Trait Implementations§

Source§

impl Clone for RequestContext

Source§

fn clone(&self) -> RequestContext

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for RequestContext

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for RequestContext

Source§

fn default() -> RequestContext

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more