RequestIdMiddleware

Struct RequestIdMiddleware 

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

HTTP Request ID middleware for distributed tracing and request correlation.

This middleware automatically assigns unique identifiers to HTTP requests, enabling better debugging, logging, and distributed tracing capabilities.

§Behavior

  1. Request Processing:

    • Checks for existing X-Request-ID header from client
    • Validates existing ID format and length
    • Generates new ID if missing or invalid
    • Sets ID in request context for downstream use
  2. Response Processing:

    • Always includes X-Request-ID header in response
    • Enables client-side request correlation
    • Supports debugging and audit trails

§Security Considerations

  • Request IDs are limited to 200 characters maximum
  • Only ASCII alphanumeric and safe characters allowed
  • Invalid IDs are replaced with server-generated ones

§Examples

§Basic Usage

use ignitia::{Router, RequestIdMiddleware};

let app = Router::new()
    .middleware(RequestIdMiddleware::new())
    .get("/health", || async {
        // Request ID available in tracing spans automatically
        ignitia::Response::text("OK")
    });

§Custom Configuration

use ignitia::{RequestIdMiddleware, IdGenerator};

let request_id_mw = RequestIdMiddleware::new()
    .with_generator(IdGenerator::NanoId { length: 16 })
    .with_header_name("x-trace-id")
    .with_validation(true);

§With Logging Integration

use ignitia::{RequestIdMiddleware, LoggerMiddleware};

let app = Router::new()
    .middleware(RequestIdMiddleware::new())  // Must come first
    .middleware(LoggerMiddleware::new())     // Will include request ID
    .get("/api/data", handler);

Implementations§

Source§

impl RequestIdMiddleware

Source

pub fn new() -> Self

Creates a new RequestIdMiddleware with default settings.

This is equivalent to calling RequestIdMiddleware::default().

Source

pub fn with_generator(self, generator: IdGenerator) -> Self

Sets the ID generation strategy.

§Parameters
  • generator - The ID generation strategy to use
§Examples
use ignitia::{RequestIdMiddleware, IdGenerator};

// Use shorter NanoIDs
let middleware = RequestIdMiddleware::new()
    .with_generator(IdGenerator::NanoId { length: 12 });

// Use custom generator
let middleware = RequestIdMiddleware::new()
    .with_generator(IdGenerator::Custom(|| {
        format!("req_{}", chrono::Utc::now().timestamp_millis())
    }));
Source

pub fn with_header_name(self, header_name: &str) -> Self

Sets the header name for the request ID.

§Parameters
  • header_name - The HTTP header name to use
§Examples
use ignitia::RequestIdMiddleware;

// Use custom header name
let middleware = RequestIdMiddleware::new()
    .with_header_name("x-trace-id");

// Use correlation ID header
let middleware = RequestIdMiddleware::new()
    .with_header_name("x-correlation-id");
Source

pub fn with_validation(self, validate: bool) -> Self

Enables or disables validation of incoming request IDs.

When enabled, incoming request IDs are validated for format and length. Invalid IDs are replaced with server-generated ones.

§Parameters
  • validate - Whether to validate incoming request IDs
§Examples
use ignitia::RequestIdMiddleware;

// Trust all client-provided request IDs
let middleware = RequestIdMiddleware::new()
    .with_validation(false);
Source

pub fn with_logging(self, enable: bool) -> Self

Enables or disables structured logging integration.

When enabled, request IDs are automatically included in log spans.

§Parameters
  • enable - Whether to enable logging integration
Source§

impl RequestIdMiddleware

Source

pub fn for_microservices() -> Self

Creates request ID middleware optimized for microservices.

This configuration is designed for distributed systems:

  • Short NanoID for reduced header size
  • Standard X-Request-ID header
  • Strict validation enabled
  • Logging enabled for observability
§Examples
use ignitia::{Router, RequestIdMiddleware};

let api = Router::new()
    .middleware(RequestIdMiddleware::for_microservices())request_id.rs
    .get("/api/users", get_users_handler);
Source

pub fn for_development() -> Self

Creates request ID middleware for development and debugging.

This configuration prioritizes debugging convenience:

  • UUID for maximum uniqueness
  • Custom trace header
  • Relaxed validation
  • Verbose logging
§Examples
use ignitia::{Router, RequestIdMiddleware};

let dev_app = Router::new()
    .middleware(RequestIdMiddleware::for_development())
    .get("/debug", debug_handler);
Source

pub fn for_performance() -> Self

Creates request ID middleware for high-performance scenarios.

This configuration minimizes overhead:

  • Short NanoID for performance
  • Minimal validation
  • Reduced logging
§Examples
use ignitia::{Router, RequestIdMiddleware};

let fast_api = Router::new()
    .middleware(RequestIdMiddleware::for_performance())
    .get("/api/fast", fast_handler);

Trait Implementations§

Source§

impl Clone for RequestIdMiddleware

Source§

fn clone(&self) -> RequestIdMiddleware

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for RequestIdMiddleware

Source§

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

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

impl Default for RequestIdMiddleware

Source§

fn default() -> Self

Creates a new RequestIdMiddleware with sensible defaults.

§Default Configuration
  • Generator: UUID v4
  • Header: “x-request-id”
  • Validation: Enabled
  • Logging: Enabled
§Examples
use ignitia::RequestIdMiddleware;

let middleware = RequestIdMiddleware::default();
// Equivalent to:
let middleware = RequestIdMiddleware::new();
Source§

impl Middleware for RequestIdMiddleware

Source§

fn handle<'life0, 'async_trait>( &'life0 self, req: Request, next: Next, ) -> Pin<Box<dyn Future<Output = Response> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Process a request and optionally pass it to the next middleware. 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> 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> Same for T

Source§

type Output = T

Should always be Self
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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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
Source§

impl<T> ErasedDestructor for T
where T: 'static,