grippo 0.2.1

Parse, match and scrub data faster and more efficiently.
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
// Project:   grippo
// File:      src/xml/mod.rs
// Purpose:   XML documents to JSON records, streaming, bounded by record
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! XML to JSON records, mechanically: one input always gives the same output,
//! with no per-source branches.
//!
//! - Every attribute is `"@name": "value"`, every child element a key whose
//!   value is an array of that child's values, text `"#text"`. Values stay
//!   strings.
//! - A document splits into records on its own: the children of the first
//!   element down the spine that holds a repeated name. `record` overrides it.
//! - Every record carries `_xml`: its element, path and index.
//! - A `<!DOCTYPE>` is refused, so no entity is ever expanded. Depth, record
//!   size and attribute count are capped.
//!
//! [`Paths`] reads many paths from a raw document in one pass instead, with
//! no tree and no JSON.

mod input;
pub(crate) mod paths;
mod stream;
mod tree;

use std::borrow::Cow;
use std::sync::{Arc, LazyLock, RwLock};

use serde::Deserialize;
use thiserror::Error;

pub use paths::{Kind, Path, PathError, Paths, Raw, Slot, Slots, Values};
pub use stream::XmlRecords;

/// Which elements are records.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum RecordSpec {
    /// The children of the first element down the spine with a repeated child
    /// name, else the whole document.
    #[default]
    Auto,
    /// Every element at this slash path of local names, such as
    /// `/feed/entry`.
    Path(Vec<String>),
}

impl TryFrom<String> for RecordSpec {
    type Error = String;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        if s == "auto" {
            return Ok(Self::Auto);
        }
        let path: Vec<String> = s
            .strip_prefix('/')
            .ok_or_else(|| format!("record: {s:?} is neither `auto` nor a path from `/`"))?
            .split('/')
            .map(str::to_owned)
            .collect();
        if path.iter().any(String::is_empty) {
            return Err(format!("record: {s:?} has an empty step"));
        }
        Ok(Self::Path(path))
    }
}

impl<'de> Deserialize<'de> for RecordSpec {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = String::deserialize(d)?;
        Self::try_from(s).map_err(serde::de::Error::custom)
    }
}

/// When a child element is written as an array.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Arrays {
    /// Always, so a key's JSON type never changes between one child and two.
    #[default]
    Always,
    /// Only when the name repeats. Readable, but a key's JSON type can change.
    Auto,
}

/// How a namespaced name is written.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Namespaces {
    /// The local name, with `xmlns` declarations dropped.
    #[default]
    Strip,
    /// The name as sent, prefix and all.
    Keep,
    /// `{uri}local`.
    Expand,
}

/// An element named by one of its attributes: `<Data Name="user">bob</Data>`
/// under `Event.EventData` is `Event.EventData.user`. The `xml` parser and
/// [`crate::record`]'s `Xml` both take these.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Keyed {
    /// The element's path of local names, root first, joined with `.`, a
    /// name holding `.` quoted: `Event["a.b"]`.
    pub path: String,
    /// The attribute whose value names the element. It isn't written itself.
    pub attribute: String,
}

impl Keyed {
    /// The rule naming each element at `path` by its `attribute`.
    #[must_use]
    pub fn new(path: impl Into<String>, attribute: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            attribute: attribute.into(),
        }
    }

    /// Whether the element at `names`, local names root first, is the one
    /// this rule names.
    #[cfg(feature = "record")]
    pub(crate) fn applies<'n>(&self, names: impl IntoIterator<Item = &'n [u8]>) -> bool {
        let mut names = names.into_iter();
        self.path
            .split('.')
            .all(|part| names.next() == Some(part.as_bytes()))
            && names.next().is_none()
    }
}

/// Caps that bound memory and refuse hostile input.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct XmlLimits {
    /// The most bytes one record may span.
    pub max_record_bytes: usize,
    /// The deepest element nesting.
    pub max_depth: usize,
    /// The bytes read ahead to find the record element.
    pub detect_bytes: usize,
    /// The most attributes on one element.
    pub max_attributes: usize,
}

impl Default for XmlLimits {
    fn default() -> Self {
        Self {
            max_record_bytes: 16 << 20,
            max_depth: 64,
            detect_bytes: 16 << 20,
            max_attributes: 256,
        }
    }
}

/// How a document becomes records. `XmlConfig::default()` needs nothing else.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct XmlConfig {
    /// Which elements are records.
    pub record: RecordSpec,
    /// When a child is an array.
    pub arrays: Arrays,
    /// Paths of local names written as a value, not an array, when the
    /// element occurs once: `/feed/entry`, or `feed.entry` with a name
    /// holding `.` quoted, `feed["a.b"]`.
    pub single: Vec<String>,
    /// How namespaced names are written.
    pub namespaces: Namespaces,
    /// Context copied into each record's `_xml.context`, in this order: an
    /// output key and the path of local names it is read from, as `single`
    /// takes one. An element path gives an array of that element's values,
    /// one ending `/@name`, or `.@name`, an attribute's string. Only what closed before the record
    /// starts is copied, and an entry clears when its parent element re-opens.
    #[serde(deserialize_with = "ordered_map")]
    pub carry: Vec<(String, String)>,
    /// What goes before an attribute name.
    pub attr_prefix: String,
    /// The key for an element's text.
    pub text_key: String,
    /// The key each record's element, path, index, context and SOAP header
    /// go under, `_xml` by default. `None` leaves them out.
    pub meta_key: Option<String>,
    /// The caps.
    pub limits: XmlLimits,
    /// Whether SOAP envelopes are unwrapped.
    pub dialects: DialectMode,
}

impl Default for XmlConfig {
    fn default() -> Self {
        Self {
            record: RecordSpec::Auto,
            arrays: Arrays::Always,
            single: Vec::new(),
            namespaces: Namespaces::Strip,
            attr_prefix: "@".to_owned(),
            text_key: "#text".to_owned(),
            meta_key: Some("_xml".to_owned()),
            carry: Vec::new(),
            limits: XmlLimits::default(),
            dialects: DialectMode::Auto,
        }
    }
}

/// A map read in document order, its paths checked.
fn ordered_map<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Vec<(String, String)>, D::Error> {
    struct Pairs;
    impl<'de> serde::de::Visitor<'de> for Pairs {
        type Value = Vec<(String, String)>;

        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str("a map of output keys to paths")
        }

        fn visit_map<A: serde::de::MapAccess<'de>>(
            self,
            mut map: A,
        ) -> Result<Self::Value, A::Error> {
            let mut pairs = Vec::new();
            while let Some((key, path)) = map.next_entry::<String, String>()? {
                let steps = local_steps(&path);
                let bad = steps.iter().any(|s| s.is_empty() || s.contains('/'))
                    || steps[..steps.len() - 1].iter().any(|s| s.starts_with('@'));
                if bad {
                    return Err(serde::de::Error::custom(format!(
                        "carry {key}: {path:?} is not a path of local names"
                    )));
                }
                pairs.push((key, path));
            }
            Ok(pairs)
        }
    }
    d.deserialize_map(Pairs)
}

/// A path of local names as its steps: a slash path from `/` split at each
/// `/`, any other read as a field name, as [`crate::path`] writes one.
pub(crate) fn local_steps(path: &str) -> Vec<String> {
    path.strip_prefix('/').map_or_else(
        || crate::path::keys(path).map(Cow::into_owned).collect(),
        |rest| rest.split('/').map(str::to_owned).collect(),
    )
}

/// `path` as a slash path of local names.
pub(crate) fn slash_path(path: &str) -> Cow<'_, str> {
    if path.starts_with('/') {
        Cow::Borrowed(path)
    } else {
        Cow::Owned(
            local_steps(path)
                .iter()
                .fold(String::new(), |mut out, step| {
                    out.push('/');
                    out.push_str(step);
                    out
                }),
        )
    }
}

/// Why a document didn't convert.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum XmlError {
    /// Not well-formed XML.
    #[error("xml: malformed at byte {offset}: {reason}")]
    Malformed {
        /// Where, from the start of the document.
        offset: u64,
        /// What.
        reason: String,
    },
    /// Elements nest deeper than the cap.
    #[error("xml: elements nest deeper than {max}")]
    TooDeep {
        /// The cap.
        max: usize,
    },
    /// One record spans more bytes than the cap.
    #[error("xml: a record spans more than {max} bytes")]
    RecordTooLarge {
        /// The cap.
        max: usize,
    },
    /// The document has a `<!DOCTYPE>`, which is refused.
    #[error("xml: a <!DOCTYPE> is refused")]
    Doctype,
    /// The document declares an encoding other than UTF-8.
    #[error("xml: the declared encoding {label:?} isn't UTF-8")]
    Encoding {
        /// The declared label.
        label: String,
    },
    /// The document is a SOAP Fault.
    #[error("xml: a {} fault: {}", .0.version, .0.reason)]
    SoapFault(Box<SoapFault>),
}

impl XmlError {
    /// A stable label for metrics and status mapping: `malformed`,
    /// `too_deep`, `record_too_large`, `doctype`, `encoding` or
    /// `soap_fault`.
    #[must_use]
    pub const fn kind(&self) -> &'static str {
        match self {
            Self::Malformed { .. } => "malformed",
            Self::TooDeep { .. } => "too_deep",
            Self::RecordTooLarge { .. } => "record_too_large",
            Self::Doctype => "doctype",
            Self::Encoding { .. } => "encoding",
            Self::SoapFault(_) => "soap_fault",
        }
    }
}

/// A SOAP Fault, its codes as local names whatever prefix the sender used.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SoapFault {
    /// The envelope version.
    /// The dialect's version label: `1.1` or `1.2` for SOAP.
    pub version: String,
    /// `faultcode`, or 1.2's `Code/Value`.
    pub code: String,
    /// 1.2's `Code/Subcode/Value`.
    pub subcode: Option<String>,
    /// `faultstring`, or 1.2's first `Reason/Text`.
    pub reason: String,
    /// 1.2's `Node`.
    pub node: Option<String>,
    /// `faultactor`, or 1.2's `Role`.
    pub role: Option<String>,
    /// `detail` or `Detail` as a JSON value, by the same rules as a record.
    pub detail: Option<String>,
}

impl SoapFault {
    /// The fault as one JSON object.
    #[must_use]
    pub fn to_json(&self) -> Vec<u8> {
        let mut out = b"{\"version\":".to_vec();
        tree::string(&mut out, &self.version);
        let optional = [
            ("code", Some(&self.code)),
            ("subcode", self.subcode.as_ref()),
            ("reason", Some(&self.reason)),
            ("node", self.node.as_ref()),
            ("role", self.role.as_ref()),
        ];
        for (key, value) in optional {
            if let Some(v) = value {
                out.push(b',');
                tree::string(&mut out, key);
                out.push(b':');
                tree::string(&mut out, v);
            }
        }
        if let Some(detail) = &self.detail {
            out.extend_from_slice(b",\"detail\":");
            out.extend_from_slice(detail.as_bytes());
        }
        out.push(b'}');
        out
    }
}

/// Where a dialect keeps a fault's fields, as slash paths of local names
/// below the fault element.
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct FaultPaths {
    /// The code. Its local name is kept.
    pub code: Option<String>,
    /// The subcode. Its local name is kept.
    pub subcode: Option<String>,
    /// The reason text, the first when there are several.
    pub reason: Option<String>,
    /// The node.
    pub node: Option<String>,
    /// The role or actor.
    pub role: Option<String>,
    /// The detail, written as a JSON value.
    pub detail: Option<String>,
}

/// An envelope family: a root element and namespace, where records start,
/// and where its header and fault sit, each a slash path below the root.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct DialectSpec {
    /// The version label written to `_xml.soap.version`.
    pub version: String,
    /// The root element's namespace URI.
    pub namespace: String,
    /// The root element's local name.
    pub element: String,
    /// The element whose child is where the record split starts, such as `Body`.
    pub content: String,
    /// The header, copied to `_xml.soap.header`.
    #[serde(default)]
    pub header: Option<String>,
    /// The fault, below `content`, returned as [`XmlError::SoapFault`].
    #[serde(default)]
    pub fault: Option<String>,
    /// The fault's fields.
    #[serde(default)]
    pub fault_fields: FaultPaths,
}

/// Why a dialect wasn't registered.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum RegistryError {
    /// A dialect already matches that namespace and element.
    #[error("xml: a dialect for {{{namespace}}}{element} is already registered")]
    Duplicate {
        /// The namespace.
        namespace: String,
        /// The element.
        element: String,
    },
    /// A path in the spec is empty or has an empty step.
    #[error("xml: dialect {0}: a path is empty or has an empty step")]
    BadPath(String),
}

/// Every dialect in force: SOAP 1.1 and 1.2, then the registered ones. A
/// registration swaps in a new list, so a reader keeps the one it was built
/// with and reads a document with no lock.
static DIALECTS: LazyLock<RwLock<Arc<[DialectSpec]>>> =
    LazyLock::new(|| RwLock::new(Arc::from(soap_dialects())));

/// Add a dialect, alongside SOAP 1.1 and 1.2, for every [`XmlRecords`] built
/// after it.
///
/// # Errors
///
/// [`RegistryError`] when a dialect already matches its root, or a path is
/// malformed.
pub fn register_dialect(name: &str, spec: DialectSpec) -> Result<(), RegistryError> {
    let paths = [
        Some(&spec.content),
        spec.header.as_ref(),
        spec.fault.as_ref(),
    ];
    if paths
        .into_iter()
        .flatten()
        .any(|p| p.is_empty() || p.split('/').any(str::is_empty))
    {
        return Err(RegistryError::BadPath(name.to_owned()));
    }
    let mut dialects = DIALECTS
        .write()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    if dialect(&dialects, &spec.namespace, &spec.element).is_none() {
        *dialects = dialects.iter().cloned().chain([spec]).collect();
        return Ok(());
    }
    drop(dialects);
    Err(RegistryError::Duplicate {
        namespace: spec.namespace,
        element: spec.element,
    })
}

/// The dialects in force now, for one reader to keep.
fn dialects() -> Arc<[DialectSpec]> {
    Arc::clone(
        &DIALECTS
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner),
    )
}

/// SOAP 1.1 and 1.2.
fn soap_dialects() -> [DialectSpec; 2] {
    let soap = |version: &str, namespace: &str, fields: FaultPaths| DialectSpec {
        version: version.to_owned(),
        namespace: namespace.to_owned(),
        element: "Envelope".to_owned(),
        content: "Body".to_owned(),
        header: Some("Header".to_owned()),
        fault: Some("Body/Fault".to_owned()),
        fault_fields: fields,
    };
    let path = |s: &str| Some(s.to_owned());
    [
        soap(
            "1.1",
            "http://schemas.xmlsoap.org/soap/envelope/",
            FaultPaths {
                code: path("faultcode"),
                reason: path("faultstring"),
                role: path("faultactor"),
                detail: path("detail"),
                ..FaultPaths::default()
            },
        ),
        soap(
            "1.2",
            "http://www.w3.org/2003/05/soap-envelope",
            FaultPaths {
                code: path("Code/Value"),
                subcode: path("Code/Subcode/Value"),
                reason: path("Reason/Text"),
                node: path("Node"),
                role: path("Role"),
                detail: path("Detail"),
            },
        ),
    ]
}

/// The dialect in `dialects` whose root is `{namespace}element`.
fn dialect<'d>(
    dialects: &'d [DialectSpec],
    namespace: &str,
    element: &str,
) -> Option<&'d DialectSpec> {
    dialects
        .iter()
        .find(|d| d.namespace == namespace && d.element == element)
}

/// Whether a SOAP envelope is unwrapped.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum DialectMode {
    /// SOAP 1.1 and 1.2 envelopes are unwrapped: records come from inside
    /// `Body`, `Header` lands in `_xml.soap.header`, and a `Fault` is
    /// [`XmlError::SoapFault`].
    #[default]
    Auto,
    /// An envelope is a document like any other.
    Off,
}

/// One whole document's records.
///
/// # Errors
///
/// [`XmlError`] when the document isn't well-formed or breaks a cap.
pub fn to_records(doc: &[u8], cfg: &XmlConfig) -> Result<Vec<Vec<u8>>, XmlError> {
    let mut records = XmlRecords::new(Arc::new(cfg.clone()));
    let mut out = Vec::new();
    records.feed(doc, &mut out)?;
    records.finish(&mut out)?;
    Ok(out)
}

/// One element or fragment as one JSON object, never split.
///
/// # Errors
///
/// [`XmlError`] when the fragment isn't one well-formed element or breaks a
/// cap.
pub fn to_json(fragment: &[u8], cfg: &XmlConfig) -> Result<Vec<u8>, XmlError> {
    let mut records = XmlRecords::whole(Arc::new(cfg.clone()));
    let mut out = Vec::new();
    records.feed(fragment, &mut out)?;
    records.finish(&mut out)?;
    out.pop().ok_or_else(|| XmlError::Malformed {
        offset: 0,
        reason: "no element".to_owned(),
    })
}

/// `true` for `application/xml`, `text/xml` and any `+xml` type, parameters
/// ignored.
#[must_use]
pub fn is_xml_media_type(content_type: &str) -> bool {
    let essence = content_type
        .split(';')
        .next()
        .unwrap_or_default()
        .trim()
        .to_ascii_lowercase();
    essence == "application/xml" || essence == "text/xml" || essence.ends_with("+xml")
}

#[cfg(test)]
mod tests;