xdoc-rs 0.1.1

Declarative XML engine for Rust
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
//! Structural XML contracts and validation.
//!
//! This module implements a small, engine-native contract layer. It is not an
//! XSD implementation; the types are intentionally shaped so an XSD adapter can
//! be added later without making `schema` depend on any XML domain.

use crate::core::{Document, ErrorKind, NodeId, NodeKind, XmlError, XmlResult};
use crate::query::{NamespaceContext, Query, QueryValue};

pub type CustomRule = Box<dyn Fn(&Document) -> XmlResult<Vec<ValidationIssue>>>;

pub struct XmlContract {
    name: String,
    namespaces: NamespaceContext,
    rules: Vec<ContractRule>,
    custom_rules: Vec<CustomRule>,
}

impl XmlContract {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            namespaces: NamespaceContext::new(),
            rules: Vec::new(),
            custom_rules: Vec::new(),
        }
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn with_namespace(
        mut self,
        alias: impl Into<String>,
        uri: impl Into<String>,
    ) -> XmlResult<Self> {
        self.namespaces = self.namespaces.with_alias(alias, uri)?;
        Ok(self)
    }

    pub fn required(mut self, path: impl AsRef<str>) -> XmlResult<Self> {
        self.rules
            .push(ContractRule::Required(CompiledPath::new(path)?));
        Ok(self)
    }

    pub fn cardinality(
        mut self,
        path: impl AsRef<str>,
        min: usize,
        max: Option<usize>,
    ) -> XmlResult<Self> {
        if max.is_some_and(|max| min > max) {
            return Err(schema_error(format!(
                "invalid cardinality for `{}`: min cannot be greater than max",
                path.as_ref()
            )));
        }

        self.rules.push(ContractRule::Cardinality {
            path: CompiledPath::new(path)?,
            min,
            max,
        });
        Ok(self)
    }

    pub fn text_type(mut self, path: impl AsRef<str>, value_type: ValueType) -> XmlResult<Self> {
        self.rules.push(ContractRule::TextType {
            path: CompiledPath::new(path)?,
            value_type,
        });
        Ok(self)
    }

    pub fn enum_value(
        mut self,
        path: impl AsRef<str>,
        values: impl IntoIterator<Item = impl Into<String>>,
    ) -> XmlResult<Self> {
        let values = values.into_iter().map(Into::into).collect::<Vec<_>>();
        if values.is_empty() {
            return Err(schema_error(format!(
                "enum rule for `{}` requires at least one value",
                path.as_ref()
            )));
        }

        self.rules.push(ContractRule::EnumValue {
            path: CompiledPath::new(path)?,
            values,
        });
        Ok(self)
    }

    pub fn rule(
        mut self,
        rule: impl Fn(&Document) -> XmlResult<Vec<ValidationIssue>> + 'static,
    ) -> Self {
        self.custom_rules.push(Box::new(rule));
        self
    }

    pub fn validate(&self, document: &Document) -> XmlResult<ValidationReport> {
        let mut report = ValidationReport::new(self.name.clone());

        for rule in &self.rules {
            rule.validate(document, &self.namespaces, &mut report)?;
        }

        for rule in &self.custom_rules {
            for issue in rule(document)? {
                report.push(issue);
            }
        }

        Ok(report)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValueType {
    String,
    Integer,
    Decimal,
    Boolean,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationReport {
    contract_name: String,
    issues: Vec<ValidationIssue>,
}

impl ValidationReport {
    pub fn new(contract_name: impl Into<String>) -> Self {
        Self {
            contract_name: contract_name.into(),
            issues: Vec::new(),
        }
    }

    pub fn contract_name(&self) -> &str {
        &self.contract_name
    }

    pub fn is_valid(&self) -> bool {
        !self
            .issues
            .iter()
            .any(|issue| issue.severity == ValidationSeverity::Error)
    }

    pub fn issues(&self) -> &[ValidationIssue] {
        &self.issues
    }

    pub fn errors(&self) -> impl Iterator<Item = &ValidationIssue> {
        self.issues
            .iter()
            .filter(|issue| issue.severity == ValidationSeverity::Error)
    }

    pub fn warnings(&self) -> impl Iterator<Item = &ValidationIssue> {
        self.issues
            .iter()
            .filter(|issue| issue.severity == ValidationSeverity::Warning)
    }

    pub fn push(&mut self, issue: ValidationIssue) {
        self.issues.push(issue);
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationIssue {
    severity: ValidationSeverity,
    path: String,
    message: String,
}

impl ValidationIssue {
    pub fn error(path: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            severity: ValidationSeverity::Error,
            path: path.into(),
            message: message.into(),
        }
    }

    pub fn warning(path: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            severity: ValidationSeverity::Warning,
            path: path.into(),
            message: message.into(),
        }
    }

    pub fn severity(&self) -> &ValidationSeverity {
        &self.severity
    }

    pub fn path(&self) -> &str {
        &self.path
    }

    pub fn message(&self) -> &str {
        &self.message
    }
}

pub type ValidationError = ValidationIssue;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationSeverity {
    Error,
    Warning,
}

pub trait XsdContractAdapter {
    fn contract_name(&self) -> &str;
    fn into_contract(self) -> XmlResult<XmlContract>;
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum ContractRule {
    Required(CompiledPath),
    Cardinality {
        path: CompiledPath,
        min: usize,
        max: Option<usize>,
    },
    TextType {
        path: CompiledPath,
        value_type: ValueType,
    },
    EnumValue {
        path: CompiledPath,
        values: Vec<String>,
    },
}

impl ContractRule {
    fn validate(
        &self,
        document: &Document,
        namespaces: &NamespaceContext,
        report: &mut ValidationReport,
    ) -> XmlResult<()> {
        match self {
            Self::Required(path) => {
                let result = path.query.evaluate_with_context(document, namespaces)?;
                if result.is_empty() {
                    report.push(ValidationIssue::error(
                        path.source(),
                        format!("required path `{}` was not found", path.source()),
                    ));
                }
            }
            Self::Cardinality { path, min, max } => {
                let count = path
                    .query
                    .evaluate_with_context(document, namespaces)?
                    .len();
                if count < *min {
                    report.push(ValidationIssue::error(
                        path.source(),
                        format!(
                            "path `{}` expected at least {} match(es), found {}",
                            path.source(),
                            min,
                            count
                        ),
                    ));
                }
                if let Some(max) = max {
                    if count > *max {
                        report.push(ValidationIssue::error(
                            path.source(),
                            format!(
                                "path `{}` expected at most {} match(es), found {}",
                                path.source(),
                                max,
                                count
                            ),
                        ));
                    }
                }
            }
            Self::TextType { path, value_type } => {
                for value in text_values(document, path, namespaces)? {
                    if !value_type.matches(&value) {
                        report.push(ValidationIssue::error(
                            path.source(),
                            format!(
                                "value `{}` at `{}` is not a valid {:?}",
                                value,
                                path.source(),
                                value_type
                            ),
                        ));
                    }
                }
            }
            Self::EnumValue { path, values } => {
                for value in text_values(document, path, namespaces)? {
                    if !values.iter().any(|allowed| allowed == &value) {
                        report.push(ValidationIssue::error(
                            path.source(),
                            format!(
                                "value `{}` at `{}` is not one of [{}]",
                                value,
                                path.source(),
                                values.join(", ")
                            ),
                        ));
                    }
                }
            }
        }

        Ok(())
    }
}

impl ValueType {
    fn matches(&self, value: &str) -> bool {
        let value = value.trim();
        match self {
            Self::String => true,
            Self::Integer => value.parse::<i64>().is_ok(),
            Self::Decimal => value.parse::<f64>().is_ok(),
            Self::Boolean => matches!(value, "true" | "false" | "1" | "0"),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct CompiledPath {
    source: String,
    query: Query,
}

impl CompiledPath {
    fn new(path: impl AsRef<str>) -> XmlResult<Self> {
        let source = path.as_ref().to_owned();
        Ok(Self {
            query: Query::parse(&source)?,
            source,
        })
    }

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

fn text_values(
    document: &Document,
    path: &CompiledPath,
    namespaces: &NamespaceContext,
) -> XmlResult<Vec<String>> {
    let result = path.query.evaluate_with_context(document, namespaces)?;
    let mut values = Vec::new();

    for value in result.values() {
        match value {
            QueryValue::Text(value) | QueryValue::Attribute { value, .. } => {
                values.push(value.clone());
            }
            QueryValue::Node(id) => values.push(direct_text(document, *id)?),
        }
    }

    Ok(values)
}

fn direct_text(document: &Document, node_id: NodeId) -> XmlResult<String> {
    let mut value = String::new();
    let node = document.node(node_id)?;
    match node.kind() {
        NodeKind::Text(text) | NodeKind::CData(text) => value.push_str(text),
        NodeKind::Element(element) => {
            for child in element.children() {
                match document.node(*child)?.kind() {
                    NodeKind::Text(text) | NodeKind::CData(text) => value.push_str(text),
                    _ => {}
                }
            }
        }
        NodeKind::Comment(_) | NodeKind::ProcessingInstruction { .. } => {}
    }
    Ok(value)
}

fn schema_error(message: impl Into<String>) -> XmlError {
    XmlError::new(ErrorKind::Validation, message)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser;
    use crate::query::DocumentQueryExt;

    fn valid_document() -> XmlResult<Document> {
        parser::parse_str(
            r#"<Root>
                <Header>
                    <ID>DOC-1</ID>
                    <Status>draft</Status>
                </Header>
                <Lines>
                    <Line code="A1"><Quantity>2</Quantity><Amount>10.50</Amount></Line>
                    <Line code="B2"><Quantity>4</Quantity><Amount>20.00</Amount></Line>
                </Lines>
                <Approved>true</Approved>
            </Root>"#,
        )
    }

    #[test]
    fn schema_contract_validates_correct_document() -> XmlResult<()> {
        let document = valid_document()?;
        let contract = XmlContract::new("Example")
            .required("/Root/Header/ID")?
            .cardinality("/Root/Lines/Line", 1, Some(3))?
            .text_type("/Root/Lines/Line/Quantity", ValueType::Integer)?
            .text_type("/Root/Lines/Line/Amount", ValueType::Decimal)?
            .text_type("/Root/Approved", ValueType::Boolean)?
            .enum_value("/Root/Header/Status", ["draft", "final"])?;

        let report = contract.validate(&document)?;

        assert!(report.is_valid());
        assert_eq!(report.contract_name(), "Example");
        assert!(report.issues().is_empty());
        Ok(())
    }

    #[test]
    fn schema_required_reports_missing_path() -> XmlResult<()> {
        let document = valid_document()?;
        let contract = XmlContract::new("Example").required("/Root/Header/Missing")?;

        let report = contract.validate(&document)?;

        assert!(!report.is_valid());
        let error = report.errors().next().expect("required error");
        assert_eq!(error.path(), "/Root/Header/Missing");
        assert!(error.message().contains("required path"));
        Ok(())
    }

    #[test]
    fn schema_cardinality_reports_minimum_and_maximum() -> XmlResult<()> {
        let document = valid_document()?;
        let contract = XmlContract::new("Example")
            .cardinality("/Root/Lines/Line", 3, None)?
            .cardinality("/Root/Lines/Line", 0, Some(1))?;

        let report = contract.validate(&document)?;
        let messages = report
            .errors()
            .map(ValidationIssue::message)
            .collect::<Vec<_>>();

        assert_eq!(messages.len(), 2);
        assert!(messages
            .iter()
            .any(|message| message.contains("at least 3")));
        assert!(messages.iter().any(|message| message.contains("at most 1")));
        Ok(())
    }

    #[test]
    fn schema_types_report_invalid_values() -> XmlResult<()> {
        let document = parser::parse_str("<Root><Quantity>abc</Quantity></Root>")?;
        let contract = XmlContract::new("Example")
            .text_type("/Root/Quantity", ValueType::Integer)?
            .text_type("/Root/Quantity", ValueType::String)?;

        let report = contract.validate(&document)?;

        assert!(!report.is_valid());
        assert_eq!(report.errors().count(), 1);
        assert!(report.issues()[0].message().contains("Integer"));
        Ok(())
    }

    #[test]
    fn schema_enum_reports_invalid_values() -> XmlResult<()> {
        let document = parser::parse_str("<Root><Status>archived</Status></Root>")?;
        let contract =
            XmlContract::new("Example").enum_value("/Root/Status", ["draft", "final"])?;

        let report = contract.validate(&document)?;

        assert!(!report.is_valid());
        assert!(report.issues()[0].message().contains("not one of"));
        Ok(())
    }

    #[test]
    fn schema_custom_rule_can_return_error_with_path() -> XmlResult<()> {
        let document = valid_document()?;
        let contract = XmlContract::new("Example").rule(|document| {
            if document.query("/Root/Header/ID")?.is_empty() {
                Ok(vec![ValidationIssue::error(
                    "/Root/Header/ID",
                    "ID must be present",
                )])
            } else {
                Ok(vec![ValidationIssue::warning(
                    "/Root/Header/ID",
                    "custom rule was evaluated",
                )])
            }
        });

        let report = contract.validate(&document)?;

        assert!(report.is_valid());
        let warning = report.warnings().next().expect("custom warning");
        assert_eq!(warning.path(), "/Root/Header/ID");
        assert_eq!(warning.severity(), &ValidationSeverity::Warning);
        Ok(())
    }

    #[test]
    fn schema_namespaces_use_query_context() -> XmlResult<()> {
        let document = parser::parse_str(
            r#"<doc:Root xmlns:doc="urn:doc"><doc:ID>DOC-1</doc:ID></doc:Root>"#,
        )?;
        let contract = XmlContract::new("Namespaced")
            .with_namespace("d", "urn:doc")?
            .required("/d:Root/d:ID")?;

        let report = contract.validate(&document)?;

        assert!(report.is_valid());
        Ok(())
    }

    #[test]
    fn schema_invalid_cardinality_is_validation_error() {
        let error = match XmlContract::new("Example").cardinality("/Root/Line", 2, Some(1)) {
            Ok(_) => panic!("invalid cardinality must fail"),
            Err(error) => error,
        };

        assert_eq!(error.kind(), &ErrorKind::Validation);
        assert!(error.message().contains("min cannot be greater"));
    }
}