Skip to main content

RequestContext

Struct RequestContext 

Source
pub struct RequestContext { /* private fields */ }
Expand description

Request/correlation context attached to request extensions.

RequestContext is available to handlers when the router uses crate::middleware::validated_request_id_layer plus crate::middleware::request_context_layer, or when it is wrapped by crate::middleware::ApiDefaults::production. Extracting it without those extensions rejects the request with 500 Internal Server Error.

Fields are inferred from request headers and Axum extensions:

  • request_id: the final validated/generated x-request-id
  • correlation_id: x-correlation-id, falling back to the request ID
  • trace_id: the trace-id segment from traceparent
  • client_kind: x-api-key means API key, otherwise Authorization means authenticated, otherwise anonymous
  • route: Axum’s axum::extract::MatchedPath when it is available at the point the context layer runs
use nidus_http::{Json, context::RequestContext};

async fn handler(context: RequestContext) -> Json<serde_json::Value> {
    Json(serde_json::json!({
        "requestId": context.request_id(),
        "correlationId": context.correlation_id(),
    }))
}

Implementations§

Source§

impl RequestContext

Source

pub fn new( request_id: impl Into<String>, method: Method, path: impl Into<String>, ) -> Self

Creates a context for the current request boundary.

This constructor is useful in tests or custom middleware. It does not inspect headers, so optional correlation, trace, route, and client fields remain empty/default until set explicitly or built via Self::from_parts.

Source

pub fn from_parts(parts: &Parts, request_id: impl Into<String>) -> Self

Creates a context from request parts.

This reads x-correlation-id, traceparent, x-api-key, Authorization, and axum::extract::MatchedPath from the request boundary. The supplied request_id is expected to be the final ID chosen by request ID middleware.

Source

pub fn request_id(&self) -> &str

Returns the final request id.

With crate::middleware::validated_request_id_layer, this is either a valid inbound UUID v4 or a generated ID.

Source

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

Returns the correlation id when available.

Self::from_parts prefers x-correlation-id and falls back to the request ID when no correlation header is present.

Source

pub const fn method(&self) -> &Method

Returns the request method.

Source

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

Returns the stable matched route pattern when available.

This depends on Axum’s axum::extract::MatchedPath extension being present before the context is built. Layer placement can affect whether this is available for a given router shape.

Source

pub fn path(&self) -> &str

Returns the raw request path.

Source

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

Returns the trace id when available.

The value is extracted from the second segment of the W3C traceparent header. Use [crate::otel::extract_trace_context] when the otel feature is enabled and you need full trace/span validation.

Source

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

Returns the span id when available.

Source

pub const fn client_kind(&self) -> ClientKind

Returns the inferred client kind.

x-api-key takes precedence over Authorization; otherwise the request is classified as anonymous.

Source

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

Returns the optional application user id.

Source

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

Returns the optional application tenant id.

Source

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

Returns the optional application session id.

Source

pub fn with_route(self, route: impl Into<String>) -> Self

Sets the stable matched route pattern.

Source

pub fn with_user_id(self, user_id: impl Into<String>) -> Self

Sets an application user id.

Source

pub fn with_tenant_id(self, tenant_id: impl Into<String>) -> Self

Sets an application tenant id.

Source

pub fn with_session_id(self, session_id: impl Into<String>) -> Self

Sets an application session id.

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 Eq for RequestContext

Source§

impl<S> FromRequestParts<S> for RequestContext
where S: Send + Sync,

Source§

type Rejection = StatusCode

If the extractor fails it’ll use this “rejection” type. A rejection is a kind of error that can be converted into a response.
Source§

fn from_request_parts( parts: &mut Parts, _state: &S, ) -> impl Future<Output = Result<Self, Self::Rejection>> + Send

Perform the extraction.
Source§

impl PartialEq for RequestContext

Source§

fn eq(&self, other: &RequestContext) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for RequestContext

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<S, T> FromRequest<S, ViaParts> for T
where S: Send + Sync, T: FromRequestParts<S>,

Source§

type Rejection = <T as FromRequestParts<S>>::Rejection

If the extractor fails it’ll use this “rejection” type. A rejection is a kind of error that can be converted into a response.
Source§

fn from_request( req: Request<Body>, state: &S, ) -> impl Future<Output = Result<T, <T as FromRequest<S, ViaParts>>::Rejection>>

Perform the extraction.
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

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> Provider for T
where T: Send + Sync + 'static,

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