Skip to main content

document_svg/document/
xsd.rs

1//! Bounded W3C XML Schema (XSD) previews.
2//!
3//! XSD documents define elements and type components and may import other
4//! schemas. This adapter reports schema structure without fetching imports,
5//! validating instance documents or exposing schema documentation payloads.
6
7use std::path::Path;
8
9use crate::convert::{ConvertOptions, PageConsumer, read_limited_file};
10use crate::document::html::{HtmlBlock, render_blocks_to_pages};
11use crate::error::{Error, Result};
12use crate::geospatial::xml_tree::{XmlElement, XmlLimits, parse_xml_tree};
13use crate::table::{TableAlign, TableData};
14
15const MAX_XSD_BYTES: u64 = 128 * 1024 * 1024;
16const MAX_XSD_EVENTS: usize = 1_000_000;
17const MAX_XSD_NODES: usize = 500_000;
18const MAX_XSD_DEPTH: usize = 128;
19const MAX_XSD_TEXT_BYTES: usize = 32 * 1024 * 1024;
20const MAX_XSD_ROWS: usize = 200_000;
21const MAX_XSD_DISPLAY_BYTES: usize = 512;
22const XSD_NAMESPACE: &str = "http://www.w3.org/2001/XMLSchema";
23
24#[derive(Default)]
25struct Summary {
26    elements: usize,
27    attributes: usize,
28    complex_types: usize,
29    simple_types: usize,
30    groups: usize,
31    attribute_groups: usize,
32    choices: usize,
33    sequences: usize,
34    restrictions: usize,
35    extensions: usize,
36    imports: usize,
37    includes: usize,
38    redefines: usize,
39    overrides: usize,
40    annotations: usize,
41    rows: Vec<Vec<String>>,
42}
43
44struct XsdPageSink<'a> {
45    inner: &'a mut dyn PageConsumer,
46    warnings: &'a [String],
47}
48impl PageConsumer for XsdPageSink<'_> {
49    fn consume(&mut self, mut page: crate::ir::Page) -> Result<()> {
50        page.source_format = "xsd".into();
51        if page.title.is_empty() {
52            page.title = "XML Schema definition".into();
53        }
54        page.description = "W3C XML Schema structure is rendered as bounded inert metadata; imports and validation are not executed".into();
55        for warning in self.warnings {
56            page.warn(warning.clone());
57        }
58        self.inner.consume(page)
59    }
60}
61
62pub(crate) fn looks_like_prefix(prefix: &[u8]) -> bool {
63    crate::geospatial::xml_tree::looks_like_root(prefix, b"schema", None)
64        && String::from_utf8_lossy(prefix)
65            .to_ascii_lowercase()
66            .contains("www.w3.org/2001/xmlschema")
67}
68
69pub(crate) fn convert(
70    path: &Path,
71    options: &ConvertOptions,
72    sink: &mut dyn PageConsumer,
73) -> Result<Vec<String>> {
74    let bytes = read_limited_file(
75        path,
76        options.max_input_bytes.min(MAX_XSD_BYTES),
77        "XSD input",
78    )?;
79    let root = parse_xml_tree(
80        &bytes,
81        &XmlLimits {
82            max_events: options.max_xml_events.min(MAX_XSD_EVENTS),
83            max_nodes: MAX_XSD_NODES,
84            max_depth: MAX_XSD_DEPTH,
85            max_text_bytes: MAX_XSD_TEXT_BYTES,
86        },
87        "XSD",
88    )?;
89    if !root.name.eq_ignore_ascii_case("schema") {
90        return Err(Error::InvalidInput("XSD root must be <schema>".into()));
91    }
92    if root.namespace.as_deref() != Some(XSD_NAMESPACE) {
93        return Err(Error::InvalidInput(
94            "XSD root uses an unsupported namespace".into(),
95        ));
96    }
97    let mut summary = Summary {
98        elements: count_named(&root, "element"),
99        attributes: count_named(&root, "attribute"),
100        complex_types: count_named(&root, "complexType"),
101        simple_types: count_named(&root, "simpleType"),
102        groups: count_named(&root, "group"),
103        attribute_groups: count_named(&root, "attributeGroup"),
104        choices: count_named(&root, "choice"),
105        sequences: count_named(&root, "sequence"),
106        restrictions: count_named(&root, "restriction"),
107        extensions: count_named(&root, "extension"),
108        imports: count_named(&root, "import"),
109        includes: count_named(&root, "include"),
110        redefines: count_named(&root, "redefine"),
111        overrides: count_named(&root, "override"),
112        annotations: count_named(&root, "annotation") + count_named(&root, "documentation"),
113        ..Summary::default()
114    };
115    push_row(
116        &mut summary.rows,
117        "Declarations",
118        &summary.elements.to_string(),
119        &format!(
120            "attributes={} complexTypes={} simpleTypes={}",
121            summary.attributes, summary.complex_types, summary.simple_types
122        ),
123    )?;
124    push_row(
125        &mut summary.rows,
126        "Compositors",
127        &summary.sequences.to_string(),
128        &format!(
129            "choices={} groups={} attributeGroups={}",
130            summary.choices, summary.groups, summary.attribute_groups
131        ),
132    )?;
133    push_row(
134        &mut summary.rows,
135        "Derivation",
136        &summary.restrictions.to_string(),
137        &format!(
138            "extensions={} annotations={}",
139            summary.extensions, summary.annotations
140        ),
141    )?;
142    push_row(
143        &mut summary.rows,
144        "Dependencies",
145        &format!("imports={}", summary.imports),
146        &format!(
147            "includes={} redefines={} overrides={}",
148            summary.includes, summary.redefines, summary.overrides
149        ),
150    )?;
151    let blocks = vec![HtmlBlock::Heading { level: 1, text: "XML Schema definition".into() }, HtmlBlock::Paragraph { text: "W3C XML Schema declarations and type structure are summarized without fetching imports or validating an instance.".into() }, HtmlBlock::Table(TableData { headers: vec!["Kind".into(), "Value".into(), "Detail".into()], rows: summary.rows, alignments: vec![TableAlign::Left; 3], raw_source: String::new() })];
152    let warnings = vec!["XSD names, documentation text, type facets, values, schema locations and instance data are omitted or redacted".into(), "XSD include/import/redefine/override resources, validation, code generation and external URLs are never loaded or executed".into()];
153    let mut page_sink = XsdPageSink {
154        inner: sink,
155        warnings: &warnings,
156    };
157    render_blocks_to_pages(&blocks, &mut page_sink, options)?;
158    Ok(warnings)
159}
160
161fn count_named(element: &XmlElement, name: &str) -> usize {
162    element
163        .children
164        .iter()
165        .map(|child| usize::from(child.name.eq_ignore_ascii_case(name)) + count_named(child, name))
166        .sum()
167}
168fn push_row(rows: &mut Vec<Vec<String>>, kind: &str, value: &str, detail: &str) -> Result<()> {
169    if rows.len() >= MAX_XSD_ROWS {
170        return Err(Error::LimitExceeded(format!(
171            "XSD rows exceed {MAX_XSD_ROWS}"
172        )));
173    }
174    rows.push(vec![truncate(kind), truncate(value), truncate(detail)]);
175    Ok(())
176}
177fn truncate(value: &str) -> String {
178    if value.len() <= MAX_XSD_DISPLAY_BYTES {
179        return value.to_owned();
180    }
181    let mut end = MAX_XSD_DISPLAY_BYTES;
182    while end > 0 && !value.is_char_boundary(end) {
183        end -= 1;
184    }
185    format!("{}…", &value[..end])
186}