armature-core 0.8.2

High-performance async HTTP framework core - routing, handlers, middleware
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
//! Route constraints for parameter validation
//!
//! Route constraints allow you to validate path parameters at the routing level,
//! before the handler is called. This provides early validation and better error messages.
//!
//! # Features
//!
//! - **Built-in Constraints**: Int, UInt, Alpha, AlphaNum, UUID, Email, Regex
//! - **Custom Constraints**: Implement `RouteConstraint` trait
//! - **Composable**: Combine multiple constraints
//! - **Type-safe**: Validate parameters match expected types
//!
//! # Examples
//!
//! ```no_run
//! use armature_core::*;
//!
//! // Only match if :id is a valid integer
//! let constraint = RouteConstraints::new()
//!     .add("id", Box::new(IntConstraint));
//!
//! // Only match if :uuid is a valid UUID
//! let constraint = RouteConstraints::new()
//!     .add("uuid", Box::new(UuidConstraint));
//! ```

use crate::Error;
use regex::Regex;
use std::collections::HashMap;
use std::sync::{Arc, LazyLock};

/// Pre-compiled UUID regex (8-4-4-4-12 format), compiled once on first use.
static UUID_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
        .expect("UUID regex is valid")
});

/// Pre-compiled basic email regex, compiled once on first use.
static EMAIL_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$").expect("email regex is valid")
});

/// Trait for validating route parameters
pub trait RouteConstraint: Send + Sync {
    /// Validate a parameter value
    ///
    /// Returns Ok(()) if valid, Err with a descriptive message if invalid
    fn validate(&self, value: &str) -> Result<(), String>;

    /// Get a description of this constraint (for error messages)
    fn description(&self) -> &str;
}

/// Integer constraint - validates that a parameter is a valid integer
#[derive(Debug, Clone)]
pub struct IntConstraint;

impl RouteConstraint for IntConstraint {
    fn validate(&self, value: &str) -> Result<(), String> {
        value
            .parse::<i64>()
            .map(|_| ())
            .map_err(|_| format!("'{}' is not a valid integer", value))
    }

    fn description(&self) -> &str {
        "integer"
    }
}

/// Unsigned integer constraint - validates that a parameter is a valid unsigned integer
#[derive(Debug, Clone)]
pub struct UIntConstraint;

impl RouteConstraint for UIntConstraint {
    fn validate(&self, value: &str) -> Result<(), String> {
        value
            .parse::<u64>()
            .map(|_| ())
            .map_err(|_| format!("'{}' is not a valid unsigned integer", value))
    }

    fn description(&self) -> &str {
        "unsigned integer"
    }
}

/// Float constraint - validates that a parameter is a valid floating point number
#[derive(Debug, Clone)]
pub struct FloatConstraint;

impl RouteConstraint for FloatConstraint {
    fn validate(&self, value: &str) -> Result<(), String> {
        value
            .parse::<f64>()
            .map(|_| ())
            .map_err(|_| format!("'{}' is not a valid float", value))
    }

    fn description(&self) -> &str {
        "float"
    }
}

/// Alphabetic constraint - validates that a parameter contains only letters
#[derive(Debug, Clone)]
pub struct AlphaConstraint;

impl RouteConstraint for AlphaConstraint {
    fn validate(&self, value: &str) -> Result<(), String> {
        if value.chars().all(|c| c.is_alphabetic()) {
            Ok(())
        } else {
            Err(format!("'{}' must contain only letters", value))
        }
    }

    fn description(&self) -> &str {
        "alphabetic"
    }
}

/// Alphanumeric constraint - validates that a parameter contains only letters and numbers
#[derive(Debug, Clone)]
pub struct AlphaNumConstraint;

impl RouteConstraint for AlphaNumConstraint {
    fn validate(&self, value: &str) -> Result<(), String> {
        if value.chars().all(|c| c.is_alphanumeric()) {
            Ok(())
        } else {
            Err(format!("'{}' must contain only letters and numbers", value))
        }
    }

    fn description(&self) -> &str {
        "alphanumeric"
    }
}

/// UUID constraint - validates that a parameter is a valid UUID
#[derive(Debug, Clone)]
pub struct UuidConstraint;

impl RouteConstraint for UuidConstraint {
    fn validate(&self, value: &str) -> Result<(), String> {
        // Simple UUID validation (8-4-4-4-12 format)
        if UUID_REGEX.is_match(value) {
            Ok(())
        } else {
            Err(format!("'{}' is not a valid UUID", value))
        }
    }

    fn description(&self) -> &str {
        "UUID"
    }
}

/// Email constraint - validates that a parameter is a valid email address
#[derive(Debug, Clone)]
pub struct EmailConstraint;

impl RouteConstraint for EmailConstraint {
    fn validate(&self, value: &str) -> Result<(), String> {
        // Basic email validation
        if EMAIL_REGEX.is_match(value) {
            Ok(())
        } else {
            Err(format!("'{}' is not a valid email address", value))
        }
    }

    fn description(&self) -> &str {
        "email address"
    }
}

/// Regex constraint - validates that a parameter matches a regex pattern
pub struct RegexConstraint {
    regex: Regex,
    description: String,
}

impl RegexConstraint {
    /// Create a new regex constraint
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use armature_core::RegexConstraint;
    ///
    /// // Only allow lowercase letters
    /// let constraint = RegexConstraint::new(r"^[a-z]+$", "lowercase letters");
    /// ```
    pub fn new(pattern: &str, description: &str) -> Result<Self, regex::Error> {
        Ok(Self {
            regex: Regex::new(pattern)?,
            description: description.to_string(),
        })
    }
}

impl RouteConstraint for RegexConstraint {
    fn validate(&self, value: &str) -> Result<(), String> {
        if self.regex.is_match(value) {
            Ok(())
        } else {
            Err(format!(
                "'{}' must match pattern: {}",
                value, self.description
            ))
        }
    }

    fn description(&self) -> &str {
        &self.description
    }
}

/// Length constraint - validates that a parameter has a specific length range
#[derive(Debug, Clone)]
pub struct LengthConstraint {
    min: Option<usize>,
    max: Option<usize>,
}

impl LengthConstraint {
    /// Create a new length constraint
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use armature_core::LengthConstraint;
    ///
    /// // Between 3 and 20 characters
    /// let constraint = LengthConstraint::new(Some(3), Some(20));
    ///
    /// // At least 5 characters
    /// let constraint = LengthConstraint::min(5);
    ///
    /// // At most 100 characters
    /// let constraint = LengthConstraint::max(100);
    /// ```
    pub fn new(min: Option<usize>, max: Option<usize>) -> Self {
        Self { min, max }
    }

    /// Create a length constraint with only a minimum
    pub fn min(min: usize) -> Self {
        Self {
            min: Some(min),
            max: None,
        }
    }

    /// Create a length constraint with only a maximum
    pub fn max(max: usize) -> Self {
        Self {
            min: None,
            max: Some(max),
        }
    }

    /// Create a length constraint with an exact length
    pub fn exact(length: usize) -> Self {
        Self {
            min: Some(length),
            max: Some(length),
        }
    }
}

impl RouteConstraint for LengthConstraint {
    fn validate(&self, value: &str) -> Result<(), String> {
        let len = value.len();

        if let Some(min) = self.min
            && len < min
        {
            return Err(format!("'{}' must be at least {} characters", value, min));
        }

        if let Some(max) = self.max
            && len > max
        {
            return Err(format!("'{}' must be at most {} characters", value, max));
        }

        Ok(())
    }

    fn description(&self) -> &str {
        match (self.min, self.max) {
            (Some(min), Some(max)) if min == max => "exact length",
            (Some(_), Some(_)) => "length range",
            (Some(_), None) => "minimum length",
            (None, Some(_)) => "maximum length",
            (None, None) => "any length",
        }
    }
}

/// Range constraint - validates that a number is within a range
#[derive(Debug, Clone)]
pub struct RangeConstraint {
    min: Option<i64>,
    max: Option<i64>,
}

impl RangeConstraint {
    /// Create a new range constraint
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use armature_core::RangeConstraint;
    ///
    /// // Between 1 and 100
    /// let constraint = RangeConstraint::new(Some(1), Some(100));
    ///
    /// // At least 0
    /// let constraint = RangeConstraint::min(0);
    ///
    /// // At most 1000
    /// let constraint = RangeConstraint::max(1000);
    /// ```
    pub fn new(min: Option<i64>, max: Option<i64>) -> Self {
        Self { min, max }
    }

    /// Create a range constraint with only a minimum
    pub fn min(min: i64) -> Self {
        Self {
            min: Some(min),
            max: None,
        }
    }

    /// Create a range constraint with only a maximum
    pub fn max(max: i64) -> Self {
        Self {
            min: None,
            max: Some(max),
        }
    }
}

impl RouteConstraint for RangeConstraint {
    fn validate(&self, value: &str) -> Result<(), String> {
        let num = value
            .parse::<i64>()
            .map_err(|_| format!("'{}' is not a valid number", value))?;

        if let Some(min) = self.min
            && num < min
        {
            return Err(format!("'{}' must be at least {}", value, min));
        }

        if let Some(max) = self.max
            && num > max
        {
            return Err(format!("'{}' must be at most {}", value, max));
        }

        Ok(())
    }

    fn description(&self) -> &str {
        match (self.min, self.max) {
            (Some(_), Some(_)) => "number in range",
            (Some(_), None) => "minimum value",
            (None, Some(_)) => "maximum value",
            (None, None) => "any number",
        }
    }
}

/// Enum constraint - validates that a parameter is one of a set of values
#[derive(Debug, Clone)]
pub struct EnumConstraint {
    values: Vec<String>,
}

impl EnumConstraint {
    /// Create a new enum constraint
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use armature_core::EnumConstraint;
    ///
    /// let constraint = EnumConstraint::new(vec![
    ///     "active".to_string(),
    ///     "inactive".to_string(),
    ///     "pending".to_string(),
    /// ]);
    /// ```
    pub fn new(values: Vec<String>) -> Self {
        Self { values }
    }
}

impl RouteConstraint for EnumConstraint {
    fn validate(&self, value: &str) -> Result<(), String> {
        if self.values.contains(&value.to_string()) {
            Ok(())
        } else {
            Err(format!(
                "'{}' must be one of: {}",
                value,
                self.values.join(", ")
            ))
        }
    }

    fn description(&self) -> &str {
        "enum value"
    }
}

/// Collection of route constraints for a route
///
/// Maps parameter names to their constraints.
#[derive(Default)]
pub struct RouteConstraints {
    constraints: HashMap<String, Arc<dyn RouteConstraint>>,
}

impl RouteConstraints {
    /// Create a new empty constraint collection
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a constraint for a parameter
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use armature_core::*;
    ///
    /// let constraints = RouteConstraints::new()
    ///     .add("id", Box::new(IntConstraint))
    ///     .add("uuid", Box::new(UuidConstraint));
    /// ```
    pub fn add(mut self, param: impl Into<String>, constraint: Box<dyn RouteConstraint>) -> Self {
        self.constraints.insert(param.into(), Arc::from(constraint));
        self
    }

    /// Add a constraint for a parameter (mutable version)
    pub fn add_mut(&mut self, param: impl Into<String>, constraint: Box<dyn RouteConstraint>) {
        self.constraints.insert(param.into(), Arc::from(constraint));
    }

    /// Validate all parameters against their constraints
    ///
    /// Returns Ok(()) if all constraints pass, or an Error if any fail.
    ///
    /// A parameter with no constraint is not checked, but a constrained
    /// parameter that is present and not valid UTF-8 is rejected rather than
    /// skipped: no constraint can pass on bytes it cannot read, so falling
    /// through would silently bypass validation.
    pub fn validate(&self, params: &crate::RouteParams) -> Result<(), Error> {
        for (param_name, constraint) in &self.constraints {
            let Some((_, raw)) = params.iter().find(|(k, _)| *k == param_name) else {
                continue;
            };
            let value = std::str::from_utf8(raw).map_err(|_| {
                Error::BadRequest(format!(
                    "Invalid route parameter '{}': not valid UTF-8",
                    param_name
                ))
            })?;
            constraint.validate(value).map_err(|msg| {
                Error::BadRequest(format!("Invalid route parameter '{}': {}", param_name, msg))
            })?;
        }
        Ok(())
    }

    /// Check if there are any constraints
    pub fn is_empty(&self) -> bool {
        self.constraints.is_empty()
    }

    /// Get the number of constraints
    pub fn len(&self) -> usize {
        self.constraints.len()
    }
}

impl Clone for RouteConstraints {
    fn clone(&self) -> Self {
        Self {
            constraints: self.constraints.clone(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bytes::Bytes;

    #[test]
    fn test_int_constraint() {
        let constraint = IntConstraint;
        assert!(constraint.validate("123").is_ok());
        assert!(constraint.validate("-456").is_ok());
        assert!(constraint.validate("abc").is_err());
        assert!(constraint.validate("12.5").is_err());
    }

    #[test]
    fn test_uint_constraint() {
        let constraint = UIntConstraint;
        assert!(constraint.validate("123").is_ok());
        assert!(constraint.validate("0").is_ok());
        assert!(constraint.validate("-456").is_err());
        assert!(constraint.validate("abc").is_err());
    }

    #[test]
    fn test_alpha_constraint() {
        let constraint = AlphaConstraint;
        assert!(constraint.validate("abc").is_ok());
        assert!(constraint.validate("ABC").is_ok());
        assert!(constraint.validate("abc123").is_err());
        assert!(constraint.validate("abc-def").is_err());
    }

    #[test]
    fn test_alphanum_constraint() {
        let constraint = AlphaNumConstraint;
        assert!(constraint.validate("abc123").is_ok());
        assert!(constraint.validate("ABC").is_ok());
        assert!(constraint.validate("123").is_ok());
        assert!(constraint.validate("abc-def").is_err());
        assert!(constraint.validate("abc 123").is_err());
    }

    #[test]
    fn test_uuid_constraint() {
        let constraint = UuidConstraint;
        assert!(
            constraint
                .validate("550e8400-e29b-41d4-a716-446655440000")
                .is_ok()
        );
        assert!(constraint.validate("not-a-uuid").is_err());
        assert!(constraint.validate("12345").is_err());
    }

    #[test]
    fn test_email_constraint() {
        let constraint = EmailConstraint;
        assert!(constraint.validate("user@example.com").is_ok());
        assert!(constraint.validate("test.user@domain.co.uk").is_ok());
        assert!(constraint.validate("invalid-email").is_err());
        assert!(constraint.validate("@example.com").is_err());
    }

    #[test]
    fn test_length_constraint() {
        let constraint = LengthConstraint::new(Some(3), Some(10));
        assert!(constraint.validate("hello").is_ok());
        assert!(constraint.validate("hi").is_err());
        assert!(constraint.validate("verylongstring").is_err());
    }

    #[test]
    fn test_length_constraint_min() {
        let constraint = LengthConstraint::min(5);
        assert!(constraint.validate("hello").is_ok());
        assert!(constraint.validate("verylongstring").is_ok());
        assert!(constraint.validate("hi").is_err());
    }

    #[test]
    fn test_length_constraint_max() {
        let constraint = LengthConstraint::max(10);
        assert!(constraint.validate("hello").is_ok());
        assert!(constraint.validate("hi").is_ok());
        assert!(constraint.validate("verylongstring").is_err());
    }

    #[test]
    fn test_length_constraint_exact() {
        let constraint = LengthConstraint::exact(5);
        assert!(constraint.validate("hello").is_ok());
        assert!(constraint.validate("hi").is_err());
        assert!(constraint.validate("toolong").is_err());
    }

    #[test]
    fn test_range_constraint() {
        let constraint = RangeConstraint::new(Some(1), Some(100));
        assert!(constraint.validate("50").is_ok());
        assert!(constraint.validate("1").is_ok());
        assert!(constraint.validate("100").is_ok());
        assert!(constraint.validate("0").is_err());
        assert!(constraint.validate("101").is_err());
        assert!(constraint.validate("abc").is_err());
    }

    #[test]
    fn test_enum_constraint() {
        let constraint = EnumConstraint::new(vec![
            "active".to_string(),
            "inactive".to_string(),
            "pending".to_string(),
        ]);
        assert!(constraint.validate("active").is_ok());
        assert!(constraint.validate("pending").is_ok());
        assert!(constraint.validate("unknown").is_err());
    }

    #[test]
    fn test_route_constraints() {
        let constraints = RouteConstraints::new()
            .add("id", Box::new(IntConstraint))
            .add("name", Box::new(AlphaConstraint));

        let mut params = crate::RouteParams::new();
        params.push((
            crate::param_intern::intern("id"),
            Bytes::from_static(b"123"),
        ));
        params.push((
            crate::param_intern::intern("name"),
            Bytes::from_static(b"john"),
        ));

        assert!(constraints.validate(&params).is_ok());

        let mut bad_params = crate::RouteParams::new();
        bad_params.push((
            crate::param_intern::intern("id"),
            Bytes::from_static(b"abc"),
        ));
        bad_params.push((
            crate::param_intern::intern("name"),
            Bytes::from_static(b"john"),
        ));

        assert!(constraints.validate(&bad_params).is_err());
    }

    #[test]
    fn test_non_utf8_param_is_rejected_not_skipped() {
        let constraints = RouteConstraints::new().add("id", Box::new(IntConstraint));

        let mut params = crate::RouteParams::new();
        params.push((
            crate::param_intern::intern("id"),
            Bytes::from_static(&[0xff, 0xfe]),
        ));

        let err = constraints.validate(&params).unwrap_err();
        assert!(
            matches!(&err, Error::BadRequest(msg) if msg.contains("'id'")),
            "{err:?}"
        );

        // An unconstrained parameter is still free to hold arbitrary bytes.
        let mut other = crate::RouteParams::new();
        other.push((
            crate::param_intern::intern("slug"),
            Bytes::from_static(&[0xff, 0xfe]),
        ));
        assert!(constraints.validate(&other).is_ok());
    }
}