ignitia 0.2.4

A blazing fast, lightweight web framework for Rust that ignites your development journey
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! # Request ID Middleware
//!
//! This module provides HTTP request ID middleware for the Ignitia web framework.
//! It generates unique identifiers for each request to enable distributed tracing,
//! request correlation, and improved debugging capabilities.
//!
//! ## Features
//!
//! - **Unique ID Generation**: Creates UUIDs or custom IDs for each request
//! - **Header Propagation**: Uses standard X-Request-ID header
//! - **Client ID Support**: Respects existing request IDs from clients
//! - **Validation**: Ensures request ID format and length constraints
//! - **Context Integration**: Makes request ID available throughout request lifecycle
//! - **Logging Integration**: Structured logging with request correlation
//!
//! ## Quick Start
//!
//! ```
//! use ignitia::{Router, RequestIdMiddleware};
//!
//! let app = Router::new()
//!     .middleware(RequestIdMiddleware::new())
//!     .get("/api/users", || async {
//!         // Request ID automatically available in logs and context
//!         ignitia::Response::json(&users)
//!     });
//! ```

use std::str::FromStr;

use crate::middleware::Middleware;
use crate::{Request, Response};
use http::header::HeaderValue;
use http::HeaderName;
use tracing::{debug, info};
use uuid::Uuid;

use super::Next;

/// Request ID header name (standard convention)
pub const REQUEST_ID_HEADER: &str = "x-request-id";

/// Maximum allowed length for request IDs (security constraint)
const MAX_REQUEST_ID_LENGTH: usize = 200;

/// Minimum allowed length for request IDs
const MIN_REQUEST_ID_LENGTH: usize = 8;

/// Request ID generation strategy
#[derive(Debug, Clone)]
pub enum IdGenerator {
    /// UUID v4 (default) - cryptographically random
    Uuid,
    /// Nanoid - URL-safe, shorter than UUID
    NanoId {
        /// Length of the generated ID
        length: usize,
    },
    /// Custom function for ID generation
    Custom(fn() -> String),
}

impl Default for IdGenerator {
    fn default() -> Self {
        Self::Uuid
    }
}

impl IdGenerator {
    /// Generate a new request ID using the configured strategy
    pub fn generate(&self) -> String {
        match self {
            IdGenerator::Uuid => Uuid::new_v4().to_string(),
            IdGenerator::NanoId { length } => generate_nanoid(*length),
            IdGenerator::Custom(func) => func(),
        }
    }
}

/// 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);
/// ```
#[derive(Debug, Clone)]
pub struct RequestIdMiddleware {
    /// ID generation strategy
    generator: IdGenerator,
    /// Header name for request ID (default: "x-request-id")
    header_name: String,
    /// Whether to validate incoming request IDs
    validate_incoming: bool,
    /// Whether to include request ID in structured logging
    enable_logging: bool,
}

impl Default for RequestIdMiddleware {
    /// 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();
    /// ```
    fn default() -> Self {
        Self {
            generator: IdGenerator::default(),
            header_name: REQUEST_ID_HEADER.to_string(),
            validate_incoming: true,
            enable_logging: true,
        }
    }
}

impl RequestIdMiddleware {
    /// Creates a new `RequestIdMiddleware` with default settings.
    ///
    /// This is equivalent to calling `RequestIdMiddleware::default()`.
    pub fn new() -> Self {
        Self::default()
    }

    /// 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())
    ///     }));
    /// ```
    pub fn with_generator(mut self, generator: IdGenerator) -> Self {
        self.generator = generator;
        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");
    /// ```
    pub fn with_header_name(mut self, header_name: &str) -> Self {
        self.header_name = header_name.to_lowercase();
        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);
    /// ```
    pub fn with_validation(mut self, validate: bool) -> Self {
        self.validate_incoming = validate;
        self
    }

    /// Enables or disables structured logging integration.
    ///
    /// When enabled, request IDs are automatically included in log spans.
    ///
    /// # Parameters
    ///
    /// * `enable` - Whether to enable logging integration
    pub fn with_logging(mut self, enable: bool) -> Self {
        self.enable_logging = enable;
        self
    }

    /// Validates a request ID string.
    ///
    /// Checks format, length, and character constraints for security.
    ///
    /// # Parameters
    ///
    /// * `request_id` - The request ID to validate
    ///
    /// # Returns
    ///
    /// `true` if the request ID is valid, `false` otherwise.
    fn is_valid_request_id(&self, request_id: &str) -> bool {
        if request_id.len() < MIN_REQUEST_ID_LENGTH || request_id.len() > MAX_REQUEST_ID_LENGTH {
            return false;
        }

        // Allow ASCII letters, digits, hyphens, and underscores
        request_id
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
    }

    /// Extracts or generates a request ID for the given request.
    ///
    /// # Parameters
    ///
    /// * `req` - The HTTP request to process
    ///
    /// # Returns
    ///
    /// A valid request ID string.
    fn get_or_generate_request_id(&self, req: &Request) -> String {
        // Try to get existing request ID from headers
        if let Some(existing_id) = req.header(&self.header_name) {
            if !self.validate_incoming || self.is_valid_request_id(existing_id) {
                debug!("Using client-provided request ID: {}", existing_id);
                return existing_id.to_string();
            } else {
                debug!(
                    "Invalid client request ID, generating new one: {}",
                    existing_id
                );
            }
        }

        // Generate new request ID
        let new_id = self.generator.generate();
        debug!("Generated new request ID: {}", new_id);
        new_id
    }
}

#[async_trait::async_trait]
impl Middleware for RequestIdMiddleware {
    async fn handle(&self, mut req: Request, next: Next) -> Response {
        // Generate or get request ID
        let request_id = self.get_or_generate_request_id(&req);

        // Parse header name
        let header_name = match HeaderName::from_str(&self.header_name) {
            Ok(name) => name,
            Err(e) => {
                debug!("Invalid header name: {}", e);
                return next.run(req).await;
            }
        };

        // Store request ID in request headers
        if let Ok(header_value) = HeaderValue::from_str(&request_id) {
            req.headers.insert(header_name.clone(), header_value);
        }

        // Log with request ID if logging is enabled
        if self.enable_logging {
            info!(
                request_id = %request_id,
                method = %req.method,
                uri = %req.uri,
                "Processing request"
            );
        }

        // Process request through the chain
        let mut response = next.run(req).await;

        // Add request ID to response headers
        if let Ok(header_value) = HeaderValue::from_str(&request_id) {
            response.headers.insert(header_name, header_value);
        }

        // Log completion if logging is enabled
        if self.enable_logging {
            info!(
                request_id = %request_id,
                status = response.status.as_u16(),
                "Request completed"
            );
        }

        response
    }
}

// Preset configurations for common use cases
impl RequestIdMiddleware {
    /// 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);
    /// ```
    pub fn for_microservices() -> Self {
        Self::new()
            .with_generator(IdGenerator::NanoId { length: 16 })
            .with_validation(true)
            .with_logging(true)
    }

    /// 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);
    /// ```
    pub fn for_development() -> Self {
        Self::new()
            .with_generator(IdGenerator::Uuid)
            .with_header_name("x-trace-id")
            .with_validation(false)
            .with_logging(true)
    }

    /// 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);
    /// ```
    pub fn for_performance() -> Self {
        Self::new()
            .with_generator(IdGenerator::NanoId { length: 12 })
            .with_validation(false)
            .with_logging(false)
    }
}

/// Helper function to generate NanoID
fn generate_nanoid(length: usize) -> String {
    use rand::Rng;

    const ALPHABET: &[u8] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    let mut rng = rand::thread_rng();

    (0..length)
        .map(|_| {
            let idx = rng.gen_range(0..ALPHABET.len());
            ALPHABET[idx] as char
        })
        .collect()
}