dmvs 0.1.1

Async high-level client for selected Czech ČÚZK DMVS SOAP services
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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
use std::fmt;
use std::str::FromStr;
use std::time::Duration;

use uuid::Uuid;

use crate::{Error, Result};

macro_rules! string_id {
    ($name:ident, $doc:literal) => {
        #[doc = $doc]
        #[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
        pub struct $name(String);

        impl $name {
            /// Validates and creates an identifier without interpreting its value.
            pub fn new(value: impl Into<String>) -> Result<Self> {
                let value = value.into();
                if value.is_empty()
                    || value.len() > 256
                    || value.chars().any(char::is_control)
                    || value.trim() != value
                {
                    return Err(Error::invalid_input(
                        "identifier",
                        "expected a non-empty, trimmed string of at most 256 bytes without control characters",
                    ));
                }
                Ok(Self(value))
            }

            /// Returns the identifier exactly as supplied by the server or caller.
            pub fn as_str(&self) -> &str {
                &self.0
            }
        }

        impl fmt::Debug for $name {
            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str(concat!(stringify!($name), "([REDACTED])"))
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str(concat!(stringify!($name), "([REDACTED])"))
            }
        }

        impl FromStr for $name {
            type Err = Error;

            fn from_str(value: &str) -> Result<Self> {
                Self::new(value)
            }
        }

        impl TryFrom<String> for $name {
            type Error = Error;

            fn try_from(value: String) -> Result<Self> {
                Self::new(value)
            }
        }

        impl From<$name> for String {
            fn from(value: $name) -> Self {
                value.0
            }
        }

        #[cfg(feature = "serde")]
        impl serde::Serialize for $name {
            fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
            where
                S: serde::Serializer,
            {
                serializer.serialize_str(self.as_str())
            }
        }

        #[cfg(feature = "serde")]
        impl<'de> serde::Deserialize<'de> for $name {
            fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                let value = String::deserialize(deserializer)?;
                Self::new(value).map_err(serde::de::Error::custom)
            }
        }
    };
}

string_id!(SubjectId, "An opaque IS DMVS subject identifier.");
string_id!(
    RequestId,
    "An opaque server-issued asynchronous request identifier."
);
string_id!(
    InfrastructurePartId,
    "An opaque infrastructure-part identifier."
);
string_id!(RegionCode, "An IS DTMK region code, retained as a string.");

/// A UUID used to correlate one SOAP request and response.
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub struct CorrelationId(Uuid);

impl CorrelationId {
    /// Generates a fresh random UUID.
    pub fn new() -> Self {
        Self(Uuid::new_v4())
    }

    /// Wraps an existing UUID, for example for a reproducible integration test.
    pub fn from_uuid(value: Uuid) -> Self {
        Self(value)
    }

    /// Returns the wrapped UUID.
    pub fn as_uuid(&self) -> Uuid {
        self.0
    }
}

impl Default for CorrelationId {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Debug for CorrelationId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("CorrelationId([REDACTED])")
    }
}

impl fmt::Display for CorrelationId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("CorrelationId([REDACTED])")
    }
}

impl FromStr for CorrelationId {
    type Err = Error;

    fn from_str(value: &str) -> Result<Self> {
        Uuid::parse_str(value)
            .map(Self)
            .map_err(|_| Error::invalid_input("correlation_id", "expected a UUID"))
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for CorrelationId {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.as_uuid().to_string())
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for CorrelationId {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        value.parse().map_err(serde::de::Error::custom)
    }
}

/// Common processing state returned in every DMVS response header.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ProcessingState {
    /// A synchronous operation succeeded (`OK`).
    Ok,
    /// An asynchronous request was accepted (`Prijato`).
    Accepted,
    /// Background processing continues (`ProbihaZpracovani`).
    InProgress,
    /// Background processing completed (`Zpracovano`).
    Completed,
    /// The operation or request failed (`Chyba`).
    Failed,
    /// A state unknown to this crate version, preserved exactly.
    Other(String),
}

impl ProcessingState {
    pub(crate) fn from_raw(raw: impl Into<String>) -> Self {
        let raw = raw.into();
        match raw.as_str() {
            "OK" => Self::Ok,
            "Prijato" => Self::Accepted,
            "ProbihaZpracovani" => Self::InProgress,
            "Zpracovano" => Self::Completed,
            "Chyba" => Self::Failed,
            _ => Self::Other(raw),
        }
    }

    /// Returns the official or untouched unknown state.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Ok => "OK",
            Self::Accepted => "Prijato",
            Self::InProgress => "ProbihaZpracovani",
            Self::Completed => "Zpracovano",
            Self::Failed => "Chyba",
            Self::Other(raw) => raw,
        }
    }

    /// Returns whether the state cannot normally transition to ready.
    pub fn is_terminal(&self) -> bool {
        matches!(self, Self::Ok | Self::Completed | Self::Failed)
    }
}

/// Severity of a DMVS service message.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum MessageLevel {
    /// Informational message (`Informace`).
    Information,
    /// Warning (`Varovani`).
    Warning,
    /// Application error (`Chyba`).
    Error,
    /// An unknown severity, preserved exactly.
    Other(String),
}

impl MessageLevel {
    pub(crate) fn from_raw(raw: impl Into<String>) -> Self {
        let raw = raw.into();
        match raw.as_str() {
            "Informace" => Self::Information,
            "Varovani" => Self::Warning,
            "Chyba" => Self::Error,
            _ => Self::Other(raw),
        }
    }

    /// Returns the official or untouched unknown severity.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Information => "Informace",
            Self::Warning => "Varovani",
            Self::Error => "Chyba",
            Self::Other(raw) => raw,
        }
    }
}

/// A common DMVS message code with raw preservation for future values.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum MessageCode {
    /// Successful action (`1000`).
    Success,
    /// Request accepted (`1010`).
    Accepted,
    /// Processing continues (`1020`).
    Processing,
    /// Processing completed (`1030`).
    Completed,
    /// Certificate expires soon (`2000`).
    CertificateExpiring,
    /// Unexpected subject state (`3100`).
    InvalidSubjectState,
    /// Authentication failure (`3150`).
    Authentication,
    /// Authorization failure (`3200`).
    Forbidden,
    /// Unknown request (`4000`).
    UnknownRequest,
    /// Invalid input (`4100`).
    InvalidInput,
    /// Input-reading failure (`4110`).
    InputRead,
    /// Unknown item (`4400`).
    NotFound,
    /// Unexpected state (`4500`).
    UnexpectedState,
    /// Processing deadline elapsed (`4900`).
    ProcessingTimeout,
    /// Unknown server error (`5000`).
    Internal,
    /// A code unknown to this crate version.
    Other(String),
}

impl MessageCode {
    pub(crate) fn from_raw(raw: impl Into<String>) -> Self {
        let raw = raw.into();
        match raw.as_str() {
            "1000" => Self::Success,
            "1010" => Self::Accepted,
            "1020" => Self::Processing,
            "1030" => Self::Completed,
            "2000" => Self::CertificateExpiring,
            "3100" => Self::InvalidSubjectState,
            "3150" => Self::Authentication,
            "3200" => Self::Forbidden,
            "4000" => Self::UnknownRequest,
            "4100" => Self::InvalidInput,
            "4110" => Self::InputRead,
            "4400" => Self::NotFound,
            "4500" => Self::UnexpectedState,
            "4900" => Self::ProcessingTimeout,
            "5000" => Self::Internal,
            _ => Self::Other(raw),
        }
    }

    /// Returns the official or untouched unknown code.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Success => "1000",
            Self::Accepted => "1010",
            Self::Processing => "1020",
            Self::Completed => "1030",
            Self::CertificateExpiring => "2000",
            Self::InvalidSubjectState => "3100",
            Self::Authentication => "3150",
            Self::Forbidden => "3200",
            Self::UnknownRequest => "4000",
            Self::InvalidInput => "4100",
            Self::InputRead => "4110",
            Self::NotFound => "4400",
            Self::UnexpectedState => "4500",
            Self::ProcessingTimeout => "4900",
            Self::Internal => "5000",
            Self::Other(raw) => raw,
        }
    }
}

impl fmt::Display for MessageCode {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// One informational, warning, error, or unknown DMVS service message.
#[derive(Clone, Eq, PartialEq)]
pub struct ServiceMessage {
    /// Typed known code or untouched lexical value.
    pub code: MessageCode,
    /// Message severity.
    pub level: MessageLevel,
    /// Human-readable server text, available explicitly but redacted from debugging.
    pub text: String,
    /// Optional additional server detail, redacted from debugging.
    pub detail: Option<String>,
}

impl fmt::Debug for ServiceMessage {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ServiceMessage")
            .field("code", &self.code)
            .field("level", &self.level)
            .field("text", &"[REDACTED]")
            .field("detail", &self.detail.as_ref().map(|_| "[REDACTED]"))
            .finish()
    }
}

/// Common response correlation, state, and messages.
#[derive(Clone, Eq, PartialEq)]
pub struct ResponseMetadata {
    /// Server-generated response UUID.
    pub response_id: CorrelationId,
    /// UUID of the correlated request.
    pub request_id: CorrelationId,
    /// Common processing state.
    pub state: ProcessingState,
    /// Every service message in response order.
    pub messages: Vec<ServiceMessage>,
}

impl fmt::Debug for ResponseMetadata {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ResponseMetadata")
            .field("response_id", &"[REDACTED]")
            .field("request_id", &"[REDACTED]")
            .field("state", &self.state)
            .field("messages", &self.messages)
            .finish()
    }
}

/// A successful DMVS value together with common response metadata.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Response<T> {
    /// Operation-specific returned value.
    pub value: T,
    /// Common response metadata.
    pub metadata: ResponseMetadata,
}

/// Exact DMVS offset-page input.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct PageRequest {
    /// Zero-based record offset.
    pub offset: u32,
    /// Maximum records in one page, from 1 through 250.
    pub limit: u32,
    /// Whether the server should return the total record count.
    pub include_total: bool,
}

impl PageRequest {
    /// Creates a page request and includes the total count.
    pub fn new(offset: u32, limit: u32) -> Result<Self> {
        if !(1..=250).contains(&limit) {
            return Err(Error::invalid_input(
                "page.limit",
                "page size must be between 1 and 250",
            ));
        }
        Ok(Self {
            offset,
            limit,
            include_total: true,
        })
    }

    /// Changes whether the total count is requested.
    pub fn with_total(mut self, include_total: bool) -> Self {
        self.include_total = include_total;
        self
    }
}

impl Default for PageRequest {
    fn default() -> Self {
        Self {
            offset: 0,
            limit: 250,
            include_total: true,
        }
    }
}

/// One DMVS offset page without hidden auto-pagination.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct Page<T> {
    /// Requested zero-based offset.
    pub offset: u32,
    /// Number of records in this page.
    pub count: u32,
    /// Optional total count supplied by the server.
    pub total: Option<u32>,
    /// Returned items in server order.
    pub items: Vec<T>,
}

/// An XML calendar date retaining its validated lexical representation.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct XmlDate(String);

impl XmlDate {
    /// Validates an XML `YYYY-MM-DD` value.
    pub fn new(value: impl Into<String>) -> Result<Self> {
        let value = value.into();
        let value = value.trim();
        value
            .parse::<jiff::civil::Date>()
            .map_err(|_| Error::invalid_input("date", "expected a valid YYYY-MM-DD date"))?;
        Ok(Self(value.to_owned()))
    }

    /// Returns the original validated lexical representation.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns the corresponding `jiff` civil date.
    pub fn date(&self) -> jiff::civil::Date {
        self.0.parse().expect("validated XML date")
    }
}

impl fmt::Display for XmlDate {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for XmlDate {
    type Err = Error;

    fn from_str(value: &str) -> Result<Self> {
        Self::new(value)
    }
}

impl From<jiff::civil::Date> for XmlDate {
    fn from(value: jiff::civil::Date) -> Self {
        Self(value.to_string())
    }
}

/// An XML date-time retaining its original lexical representation.
///
/// DMVS examples include both naive and offset-bearing values. Accessors expose
/// `jiff` values when the corresponding representation is available.
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct XmlDateTime(String);

impl XmlDateTime {
    /// Validates and retains an XML date-time.
    pub fn new(value: impl Into<String>) -> Result<Self> {
        let value = value.into();
        let value = value.trim();
        if value.parse::<jiff::Timestamp>().is_ok()
            || value.parse::<jiff::civil::DateTime>().is_ok()
        {
            Ok(Self(value.to_owned()))
        } else {
            Err(Error::invalid_input(
                "date_time",
                "expected a valid naive or offset-bearing XML date-time",
            ))
        }
    }

    /// Returns the original lexical representation.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Parses an offset-bearing value as a timestamp, or returns `None` for a naive value.
    pub fn timestamp(&self) -> Option<jiff::Timestamp> {
        self.0.parse().ok()
    }

    /// Parses a naive value as a civil date-time, or returns `None` for an offset value.
    pub fn civil(&self) -> Option<jiff::civil::DateTime> {
        if self.timestamp().is_some() {
            None
        } else {
            self.0.parse().ok()
        }
    }
}

impl fmt::Debug for XmlDateTime {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_tuple("XmlDateTime")
            .field(&self.as_str())
            .finish()
    }
}

impl fmt::Display for XmlDateTime {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for XmlDateTime {
    type Err = Error;

    fn from_str(value: &str) -> Result<Self> {
        Self::new(value)
    }
}

/// Backoff strategy for bounded asynchronous-result waiting.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum WaitBackoff {
    /// Use the configured interval for every delay.
    Fixed,
    /// Double the delay after each pending response, up to a nonzero maximum.
    Exponential {
        /// Longest permitted delay between requests.
        max_interval: Duration,
    },
}

/// Bounds and pacing for application-asynchronous DMVS result polling.
///
/// Waiting performs no background work and never downloads result content.
/// DMVS documents result polling at most once per minute; workflow helpers reject
/// intervals below 60 seconds.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct WaitOptions {
    /// Delay before the first result request.
    pub initial_delay: Duration,
    /// Base interval between result requests; defaults to 60 seconds.
    pub interval: Duration,
    /// Total waiting deadline, including in-flight requests.
    pub max_elapsed: Duration,
    /// Fixed or bounded exponential backoff.
    pub backoff: WaitBackoff,
}

impl WaitOptions {
    pub(crate) fn validate(self) -> Result<()> {
        if self.interval < Duration::from_secs(60) {
            return Err(Error::invalid_input(
                "wait.interval",
                "DMVS result polling requires an interval of at least 60 seconds",
            ));
        }
        if self.max_elapsed.is_zero() {
            return Err(Error::invalid_input(
                "wait.max_elapsed",
                "wait deadline must be greater than zero",
            ));
        }
        if let WaitBackoff::Exponential { max_interval } = self.backoff
            && (max_interval < self.interval || max_interval.is_zero())
        {
            return Err(Error::invalid_input(
                "wait.backoff.max_interval",
                "maximum backoff interval must be at least the base interval",
            ));
        }
        Ok(())
    }

    pub(crate) fn next_interval(self, current: Duration) -> Duration {
        match self.backoff {
            WaitBackoff::Fixed => self.interval,
            WaitBackoff::Exponential { max_interval } => {
                current.saturating_mul(2).min(max_interval)
            }
        }
    }
}

impl Default for WaitOptions {
    fn default() -> Self {
        Self {
            initial_delay: Duration::ZERO,
            interval: Duration::from_secs(60),
            max_elapsed: Duration::from_secs(15 * 60),
            backoff: WaitBackoff::Fixed,
        }
    }
}

/// Metadata for one documented JVF version.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct JvfVersionInfo {
    /// Version identifier, such as `1.4.3`.
    pub version: String,
    /// Start of validity.
    pub valid_from: XmlDateTime,
    /// Optional end of validity.
    pub valid_to: Option<XmlDateTime>,
    /// Official version description.
    pub description: String,
}

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

    #[test]
    fn identifiers_validate_and_serde_uses_the_same_validation() {
        let id = SubjectId::new("SUBJ-00000000").unwrap();
        assert_eq!(id.as_str(), "SUBJ-00000000");
        assert!(SubjectId::new(" bad ").is_err());
        assert!(SubjectId::new("").is_err());
        assert_eq!(format!("{id:?}"), "SubjectId([REDACTED])");

        #[cfg(feature = "serde")]
        {
            assert_eq!(serde_json::to_string(&id).unwrap(), "\"SUBJ-00000000\"");
            assert!(serde_json::from_str::<SubjectId>("\" bad \"").is_err());
        }
    }

    #[test]
    fn sensitive_identifier_display_is_redacted() {
        let subject = SubjectId::new("synthetic-sensitive-subject").unwrap();
        let request = RequestId::new("synthetic-sensitive-request").unwrap();
        let uuid = Uuid::parse_str("ed8af7af-5b39-4dff-96ab-7561214336f1").unwrap();
        let correlation = CorrelationId::from_uuid(uuid);

        assert_eq!(subject.to_string(), "SubjectId([REDACTED])");
        assert_eq!(request.to_string(), "RequestId([REDACTED])");
        assert_eq!(correlation.to_string(), "CorrelationId([REDACTED])");
        assert_eq!(correlation.as_uuid().to_string(), uuid.to_string());

        #[cfg(feature = "serde")]
        assert_eq!(
            serde_json::to_string(&correlation).unwrap(),
            "\"ed8af7af-5b39-4dff-96ab-7561214336f1\""
        );
    }

    #[test]
    fn xml_date_time_preserves_naive_and_offset_values() {
        let offset = XmlDateTime::new("2022-01-01T00:00:00.000+01:00").unwrap();
        assert!(offset.timestamp().is_some());
        assert!(offset.civil().is_none());
        let naive = XmlDateTime::new("2024-01-17T10:11:26.880").unwrap();
        assert!(naive.timestamp().is_none());
        assert!(naive.civil().is_some());
        assert!(XmlDateTime::new("not-a-date").is_err());
    }

    #[test]
    fn page_limit_is_bounded() {
        assert!(PageRequest::new(0, 0).is_err());
        assert!(PageRequest::new(0, 251).is_err());
        assert_eq!(PageRequest::new(0, 250).unwrap().limit, 250);
    }
}