domainstack 1.1.1

Write validation once, use everywhere: Rust rules auto-generate JSON Schema + OpenAPI + TypeScript/Zod. WASM browser validation. Axum/Actix/Rocket adapters.
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
use crate::{Rule, RuleContext, ValidationError};
use chrono::{DateTime, Datelike, NaiveDate, Utc};

/// Validates that a datetime is in the past (before now).
///
/// Useful for validating birth dates, historical events, or any datetime
/// that must have already occurred.
///
/// # Examples
///
/// ```
/// use domainstack::prelude::*;
/// use chrono::{DateTime, Utc, Duration};
///
/// let rule = rules::past();
///
/// // Yesterday is valid
/// let yesterday = Utc::now() - Duration::days(1);
/// assert!(rule.apply(&yesterday).is_empty());
///
/// // Tomorrow is invalid
/// let tomorrow = Utc::now() + Duration::days(1);
/// assert!(!rule.apply(&tomorrow).is_empty());
/// ```
///
/// # Error Code
/// - Code: `not_in_past`
/// - Message: `"Must be in the past"`
pub fn past() -> Rule<DateTime<Utc>> {
    Rule::new(|value: &DateTime<Utc>, ctx: &RuleContext| {
        let now = Utc::now();
        if *value < now {
            ValidationError::default()
        } else {
            ValidationError::single(ctx.full_path(), "not_in_past", "Must be in the past")
        }
    })
}

/// Validates that a datetime is in the future (after now).
///
/// Useful for validating event dates, deadlines, or any datetime
/// that must not have occurred yet.
///
/// # Examples
///
/// ```
/// use domainstack::prelude::*;
/// use chrono::{DateTime, Utc, Duration};
///
/// let rule = rules::future();
///
/// // Tomorrow is valid
/// let tomorrow = Utc::now() + Duration::days(1);
/// assert!(rule.apply(&tomorrow).is_empty());
///
/// // Yesterday is invalid
/// let yesterday = Utc::now() - Duration::days(1);
/// assert!(!rule.apply(&yesterday).is_empty());
/// ```
///
/// # Error Code
/// - Code: `not_in_future`
/// - Message: `"Must be in the future"`
pub fn future() -> Rule<DateTime<Utc>> {
    Rule::new(|value: &DateTime<Utc>, ctx: &RuleContext| {
        let now = Utc::now();
        if *value > now {
            ValidationError::default()
        } else {
            ValidationError::single(ctx.full_path(), "not_in_future", "Must be in the future")
        }
    })
}

/// Validates that a datetime is before the specified datetime.
///
/// Useful for validating ranges, ensuring an event occurs before another,
/// or checking temporal constraints.
///
/// # Examples
///
/// ```
/// use domainstack::prelude::*;
/// use chrono::{DateTime, Utc, NaiveDate};
///
/// let deadline = NaiveDate::from_ymd_opt(2025, 12, 31)
///     .unwrap()
///     .and_hms_opt(23, 59, 59)
///     .unwrap()
///     .and_utc();
///
/// let rule = rules::before(deadline);
///
/// let valid = NaiveDate::from_ymd_opt(2025, 6, 15)
///     .unwrap()
///     .and_hms_opt(12, 0, 0)
///     .unwrap()
///     .and_utc();
/// assert!(rule.apply(&valid).is_empty());
///
/// let invalid = NaiveDate::from_ymd_opt(2026, 1, 1)
///     .unwrap()
///     .and_hms_opt(0, 0, 0)
///     .unwrap()
///     .and_utc();
/// assert!(!rule.apply(&invalid).is_empty());
/// ```
///
/// # Error Code
/// - Code: `not_before`
/// - Message: `"Must be before {limit}"`
/// - Meta: `{"limit": "2025-12-31T23:59:59Z"}`
pub fn before(limit: DateTime<Utc>) -> Rule<DateTime<Utc>> {
    Rule::new(move |value: &DateTime<Utc>, ctx: &RuleContext| {
        if *value < limit {
            ValidationError::default()
        } else {
            let mut err = ValidationError::single(
                ctx.full_path(),
                "not_before",
                format!("Must be before {}", limit.to_rfc3339()),
            );
            err.violations[0].meta.insert("limit", limit.to_rfc3339());
            err
        }
    })
}

/// Validates that a datetime is after the specified datetime.
///
/// Useful for validating ranges, ensuring an event occurs after another,
/// or checking temporal constraints.
///
/// # Examples
///
/// ```
/// use domainstack::prelude::*;
/// use chrono::{DateTime, Utc, NaiveDate};
///
/// let start_date = NaiveDate::from_ymd_opt(2025, 1, 1)
///     .unwrap()
///     .and_hms_opt(0, 0, 0)
///     .unwrap()
///     .and_utc();
///
/// let rule = rules::after(start_date);
///
/// let valid = NaiveDate::from_ymd_opt(2025, 6, 15)
///     .unwrap()
///     .and_hms_opt(12, 0, 0)
///     .unwrap()
///     .and_utc();
/// assert!(rule.apply(&valid).is_empty());
///
/// let invalid = NaiveDate::from_ymd_opt(2024, 12, 31)
///     .unwrap()
///     .and_hms_opt(23, 59, 59)
///     .unwrap()
///     .and_utc();
/// assert!(!rule.apply(&invalid).is_empty());
/// ```
///
/// # Error Code
/// - Code: `not_after`
/// - Message: `"Must be after {limit}"`
/// - Meta: `{"limit": "2025-01-01T00:00:00Z"}`
pub fn after(limit: DateTime<Utc>) -> Rule<DateTime<Utc>> {
    Rule::new(move |value: &DateTime<Utc>, ctx: &RuleContext| {
        if *value > limit {
            ValidationError::default()
        } else {
            let mut err = ValidationError::single(
                ctx.full_path(),
                "not_after",
                format!("Must be after {}", limit.to_rfc3339()),
            );
            err.violations[0].meta.insert("limit", limit.to_rfc3339());
            err
        }
    })
}

/// Validates that a birth date corresponds to an age within the specified range.
///
/// Calculates age based on the current date and validates it falls within min-max years.
/// Useful for age verification, eligibility checks, etc.
///
/// # Examples
///
/// ```
/// use domainstack::prelude::*;
/// use chrono::{NaiveDate, Utc, Datelike};
///
/// let rule = rules::age_range(18, 120);
///
/// // Someone born 25 years ago is valid (18-120)
/// let today = Utc::now().date_naive();
/// let birth_date = NaiveDate::from_ymd_opt(
///     today.year() - 25,
///     today.month(),
///     today.day()
/// ).unwrap();
/// assert!(rule.apply(&birth_date).is_empty());
///
/// // Someone born 10 years ago is invalid (under 18)
/// let too_young = NaiveDate::from_ymd_opt(
///     today.year() - 10,
///     today.month(),
///     today.day()
/// ).unwrap();
/// assert!(!rule.apply(&too_young).is_empty());
/// ```
///
/// # Error Code
/// - Code: `age_out_of_range`
/// - Message: `"Age must be between {min} and {max} years"`
/// - Meta: `{"min": "18", "max": "120", "age": "10"}`
pub fn age_range(min: u32, max: u32) -> Rule<NaiveDate> {
    Rule::new(move |birth_date: &NaiveDate, ctx: &RuleContext| {
        let today = Utc::now().date_naive();

        match calculate_age(*birth_date, today) {
            None => {
                // Birth date is in the future - invalid
                let mut err = ValidationError::single(
                    ctx.full_path(),
                    "invalid_birth_date",
                    "Birth date cannot be in the future",
                );
                err.violations[0]
                    .meta
                    .insert("birth_date", birth_date.to_string());
                err
            }
            Some(age) if age >= min && age <= max => ValidationError::default(),
            Some(age) => {
                let mut err = ValidationError::single(
                    ctx.full_path(),
                    "age_out_of_range",
                    format!("Age must be between {} and {} years", min, max),
                );
                err.violations[0].meta.insert("min", min.to_string());
                err.violations[0].meta.insert("max", max.to_string());
                err.violations[0].meta.insert("age", age.to_string());
                err
            }
        }
    })
}

/// Helper function to calculate age from birth date to a given date.
/// Returns None if birth_date is in the future (invalid age).
fn calculate_age(birth_date: NaiveDate, current_date: NaiveDate) -> Option<u32> {
    // Handle future birth dates gracefully
    if birth_date > current_date {
        return None;
    }

    let mut age = current_date.year() - birth_date.year();

    // Adjust if birthday hasn't occurred yet this year
    if current_date.month() < birth_date.month()
        || (current_date.month() == birth_date.month() && current_date.day() < birth_date.day())
    {
        age -= 1;
    }

    // age is guaranteed non-negative here since birth_date <= current_date
    Some(age as u32)
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::Duration;

    #[test]
    fn test_past_valid() {
        let rule = past();

        let yesterday = Utc::now() - Duration::days(1);
        assert!(rule.apply(&yesterday).is_empty());

        let last_year = Utc::now() - Duration::days(365);
        assert!(rule.apply(&last_year).is_empty());
    }

    #[test]
    fn test_past_invalid() {
        let rule = past();

        let tomorrow = Utc::now() + Duration::days(1);
        let result = rule.apply(&tomorrow);
        assert!(!result.is_empty());
        assert_eq!(result.violations[0].code, "not_in_past");
    }

    #[test]
    fn test_future_valid() {
        let rule = future();

        let tomorrow = Utc::now() + Duration::days(1);
        assert!(rule.apply(&tomorrow).is_empty());

        let next_year = Utc::now() + Duration::days(365);
        assert!(rule.apply(&next_year).is_empty());
    }

    #[test]
    fn test_future_invalid() {
        let rule = future();

        let yesterday = Utc::now() - Duration::days(1);
        let result = rule.apply(&yesterday);
        assert!(!result.is_empty());
        assert_eq!(result.violations[0].code, "not_in_future");
    }

    #[test]
    fn test_before_valid() {
        let limit = Utc::now() + Duration::days(30);
        let rule = before(limit);

        let today = Utc::now();
        assert!(rule.apply(&today).is_empty());

        let tomorrow = Utc::now() + Duration::days(1);
        assert!(rule.apply(&tomorrow).is_empty());
    }

    #[test]
    fn test_before_invalid() {
        let limit = Utc::now();
        let rule = before(limit);

        let tomorrow = Utc::now() + Duration::days(1);
        let result = rule.apply(&tomorrow);
        assert!(!result.is_empty());
        assert_eq!(result.violations[0].code, "not_before");
        assert!(result.violations[0].meta.get("limit").is_some());
    }

    #[test]
    fn test_after_valid() {
        let limit = Utc::now() - Duration::days(30);
        let rule = after(limit);

        let today = Utc::now();
        assert!(rule.apply(&today).is_empty());

        let tomorrow = Utc::now() + Duration::days(1);
        assert!(rule.apply(&tomorrow).is_empty());
    }

    #[test]
    fn test_after_invalid() {
        let limit = Utc::now();
        let rule = after(limit);

        let yesterday = Utc::now() - Duration::days(1);
        let result = rule.apply(&yesterday);
        assert!(!result.is_empty());
        assert_eq!(result.violations[0].code, "not_after");
        assert!(result.violations[0].meta.get("limit").is_some());
    }

    #[test]
    fn test_age_range_valid() {
        let rule = age_range(18, 120);

        // Person born 25 years ago
        let birth_date = NaiveDate::from_ymd_opt(Utc::now().year() - 25, 6, 15).unwrap();
        assert!(rule.apply(&birth_date).is_empty());

        // Person born exactly 18 years ago
        let birth_date = NaiveDate::from_ymd_opt(Utc::now().year() - 18, 1, 1).unwrap();
        assert!(rule.apply(&birth_date).is_empty());
    }

    #[test]
    fn test_age_range_too_young() {
        let rule = age_range(18, 120);

        // Person born 10 years ago (January to ensure birthday has passed)
        let birth_date = NaiveDate::from_ymd_opt(Utc::now().year() - 10, 1, 1).unwrap();
        let result = rule.apply(&birth_date);
        assert!(!result.is_empty());
        assert_eq!(result.violations[0].code, "age_out_of_range");
        assert_eq!(result.violations[0].meta.get("min"), Some("18"));
        // Age could be 9 or 10 depending on if birthday passed, so check range
        let age = result.violations[0].meta.get("age").unwrap();
        assert!(
            age == "9" || age == "10",
            "Expected age 9 or 10, got {}",
            age
        );
    }

    #[test]
    fn test_age_range_too_old() {
        let rule = age_range(18, 120);

        // Person born 130 years ago (January to ensure birthday has passed)
        let birth_date = NaiveDate::from_ymd_opt(Utc::now().year() - 130, 1, 1).unwrap();
        let result = rule.apply(&birth_date);
        assert!(!result.is_empty());
        assert_eq!(result.violations[0].code, "age_out_of_range");
        assert_eq!(result.violations[0].meta.get("max"), Some("120"));
        // Age could be 129 or 130 depending on if birthday passed, so check range
        let age = result.violations[0].meta.get("age").unwrap();
        assert!(
            age == "129" || age == "130",
            "Expected age 129 or 130, got {}",
            age
        );
    }

    #[test]
    fn test_age_range_future_birth_date() {
        let rule = age_range(18, 120);

        // Birth date in the future (would have caused integer overflow before fix)
        let birth_date = NaiveDate::from_ymd_opt(Utc::now().year() + 5, 6, 15).unwrap();
        let result = rule.apply(&birth_date);
        assert!(!result.is_empty());
        assert_eq!(result.violations[0].code, "invalid_birth_date");
        assert!(result.violations[0].meta.get("birth_date").is_some());
    }

    #[test]
    fn test_calculate_age() {
        let birth_date = NaiveDate::from_ymd_opt(2000, 6, 15).unwrap();

        // Before birthday
        let current = NaiveDate::from_ymd_opt(2025, 3, 10).unwrap();
        assert_eq!(calculate_age(birth_date, current), Some(24));

        // After birthday
        let current = NaiveDate::from_ymd_opt(2025, 8, 20).unwrap();
        assert_eq!(calculate_age(birth_date, current), Some(25));

        // On birthday
        let current = NaiveDate::from_ymd_opt(2025, 6, 15).unwrap();
        assert_eq!(calculate_age(birth_date, current), Some(25));

        // Future birth date returns None (prevents overflow)
        let future_birth = NaiveDate::from_ymd_opt(2030, 1, 1).unwrap();
        let current = NaiveDate::from_ymd_opt(2025, 1, 1).unwrap();
        assert_eq!(calculate_age(future_birth, current), None);
    }

    #[test]
    fn test_before_after_composition() {
        // Event must be within a specific window
        let start = Utc::now();
        let end = Utc::now() + Duration::days(30);

        let rule = after(start).and(before(end));

        // Within window
        let event = Utc::now() + Duration::days(15);
        assert!(rule.apply(&event).is_empty());

        // Before window
        let event = Utc::now() - Duration::days(1);
        let result = rule.apply(&event);
        assert!(!result.is_empty());

        // After window
        let event = Utc::now() + Duration::days(31);
        let result = rule.apply(&event);
        assert!(!result.is_empty());
    }
}