energyml-core 0.2.0-alpha.2

Runtime support for generated EnergyML (eml/resqml/witsml/prodml) crates: XML/JSON serialization, reflection, validation and identifiers.
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
//! Energistics identifiers: UUID, content type, qualified type and ETP URI.
//!
//! See `doc/Energistics_Identifier_Specification_v4.0_Doc_v1.2.pdf`. These are
//! parsed with regexes because the same strings appear in `[Content_Types].xml`,
//! in `.rels`, in DORs and in ETP messages, and all of them must agree.

use std::fmt;
use std::sync::OnceLock;

use regex::Regex;

use crate::error::{Error, Result};

const UUID_PATTERN: &str = r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";

fn uuid_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| Regex::new(&format!("^{UUID_PATTERN}$")).expect("valid uuid regex"))
}

fn content_type_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(
            r"(?x)
            ^\s*
            application/
            (?:x-(?<domain>[\w]+)\+xml|(?<mime>[\w.+-]+))
            \s*;\s*version=(?<version>[^;\s]+)
            (?:\s*;\s*type=(?<type>[\w]+))?
            \s*$",
        )
        .expect("valid content type regex")
    })
}

fn qualified_type_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(r"^\s*(?<domain>[a-zA-Z]+)(?<version>[\d]+)\.(?<type>[\w]+)\s*$")
            .expect("valid qualified type regex")
    })
}

/// A quoted value of an ETP URI - a dataspace path, an object version - where
/// a quote is written twice (ETP v1.2 §25.3.10).
const QUOTED_PATTERN: &str = r"[^']*?(?:''[^']*?)*";

fn etp_uri_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(&format!(
            r"(?x)
            ^\s*eml:///
            (?:dataspace\('(?<dataspace>{QUOTED_PATTERN})'\)/?)?
            (?:
                (?<domain>[a-zA-Z]+)(?<version>[\d]+)
                \.(?<type>[\w]+)
                \((?:uuid=)?(?<uuid>{UUID_PATTERN})(?:,version='(?<objversion>{QUOTED_PATTERN})')?\)
                (?:/(?<rest>.*))?
            )?
            \s*$"
        ))
        .expect("valid ETP URI regex")
    })
}

/// The four regular expressions ETP v1.2 gives for a **canonical** URI
/// (§25.3.10; the Identifier Specification v5.0 repeats them): a dataspace, a
/// data object with or without its version, and the two query forms.
///
/// The reader above is lenient - it takes `(uuid=…)`, an alternate form - so
/// whether a URI is canonical is a question of its own, answered here and
/// nowhere else.
fn canonical_etp_uri_res() -> &'static [Regex; 4] {
    static RES: OnceLock<[Regex; 4]> = OnceLock::new();
    RES.get_or_init(|| {
        let dataspace = format!(r"(?:dataspace\('{QUOTED_PATTERN}'\)/)?");
        let object = format!(
            r"(?:witsml|resqml|prodml|eml)[1-9]\d\.\w+\((?:{UUID_PATTERN}|uuid={UUID_PATTERN},version='{QUOTED_PATTERN}')\)"
        );
        let collection = r"(?:witsml|resqml|prodml|eml)[1-9]\d\.\w+(?:\?[^#]+)?";
        [
            format!(r"^eml:///(?:dataspace\('{QUOTED_PATTERN}'\))?$"),
            format!(r"^eml:///{dataspace}{object}$"),
            format!(r"^eml:///{dataspace}{object}/{collection}$"),
            format!(r"^eml:///{dataspace}{collection}$"),
        ]
        .map(|pattern| Regex::new(&pattern).expect("valid canonical ETP URI regex"))
    })
}

/// Whether a string is a well-formed UUID.
pub fn is_uuid(value: &str) -> bool {
    uuid_re().is_match(value.trim())
}

/// Validate and normalize a UUID to lowercase.
pub fn normalize_uuid(value: &str) -> Result<String> {
    let trimmed = value.trim();
    if is_uuid(trimmed) {
        Ok(trimmed.to_ascii_lowercase())
    } else {
        Err(Error::parse(trimmed, "uuid", "not a UUID"))
    }
}

/// A parsed EPC content type, e.g.
/// `application/x-resqml+xml;version=2.2;type=TriangulatedSetRepresentation`.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct ContentType {
    /// Domain short name: `resqml`, `witsml`, `prodml`, `eml`.
    pub domain: String,
    /// Domain version as written, e.g. `2.2`.
    pub version: String,
    /// Object type **verbatim**, `obj_` prefix included where RESQML 2.0.1 and
    /// common 2.0 write one. Absent for non-object parts.
    ///
    /// Stripping the prefix here would corrupt the string on the way back out;
    /// use [`crate::naming::strip_obj_prefix`] when grouping instead.
    pub object_type: Option<String>,
    /// Raw media type when it is not an EnergyML `x-*+xml` type (a PDF or CSV
    /// carried along inside the EPC, for instance).
    pub raw_mime: Option<String>,
}

impl ContentType {
    /// Parse a content type string.
    pub fn parse(value: &str) -> Result<Self> {
        let caps = content_type_re()
            .captures(value)
            .ok_or_else(|| Error::parse(value, "contentType", "does not match the Energistics form"))?;
        Ok(ContentType {
            domain: caps
                .name("domain")
                .map(|m| m.as_str().to_string())
                .unwrap_or_default(),
            version: caps["version"].to_string(),
            object_type: caps.name("type").map(|m| m.as_str().to_string()),
            raw_mime: caps.name("mime").map(|m| m.as_str().to_string()),
        })
    }

    /// Grouping key: the object type without its `obj_` prefix.
    pub fn type_key(&self) -> Option<&str> {
        self.object_type.as_deref().map(crate::naming::strip_obj_prefix)
    }

    /// Build the content type of a top-level object.
    pub fn of_object(domain: &str, version: &str, object_type: &str) -> String {
        format!("application/x-{domain}+xml;version={version};type={object_type}")
    }
}

impl fmt::Display for ContentType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match (&self.raw_mime, &self.object_type) {
            (Some(mime), _) => write!(f, "application/{};version={}", mime, self.version),
            (None, Some(ty)) => {
                write!(
                    f,
                    "application/x-{}+xml;version={};type={}",
                    self.domain, self.version, ty
                )
            }
            (None, None) => write!(f, "application/x-{}+xml;version={}", self.domain, self.version),
        }
    }
}

/// A parsed qualified type, e.g. `resqml22.TriangulatedSetRepresentation`.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct QualifiedType {
    /// Domain short name.
    pub domain: String,
    /// Compact version digits as they appear in the string, e.g. `22`.
    pub version: String,
    /// Object type **verbatim**, `obj_` prefix included where the schema has
    /// one - `resqml20.obj_Activity` keeps it.
    pub object_type: String,
}

impl QualifiedType {
    /// Parse a qualified type string.
    pub fn parse(value: &str) -> Result<Self> {
        let caps = qualified_type_re()
            .captures(value)
            .ok_or_else(|| Error::parse(value, "qualifiedType", "expected `<domain><version>.<Type>`"))?;
        Ok(QualifiedType {
            domain: caps["domain"].to_string(),
            version: caps["version"].to_string(),
            object_type: caps["type"].to_string(),
        })
    }

    /// Grouping key: the object type without its `obj_` prefix.
    pub fn type_key(&self) -> &str {
        crate::naming::strip_obj_prefix(&self.object_type)
    }

    /// Dotted version, e.g. `22` becomes `2.2`.
    ///
    /// Energistics writes versions without separators in qualified types but
    /// with them in content types, and the two have to be matched up.
    pub fn dotted_version(&self) -> String {
        self.version
            .chars()
            .map(|c| c.to_string())
            .collect::<Vec<_>>()
            .join(".")
    }
}

impl fmt::Display for QualifiedType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}{}.{}", self.domain, self.version, self.object_type)
    }
}

/// A parsed ETP 1.2 URI.
///
/// Covers the dataspace and data-object forms, the object's version included:
/// `eml:///dataspace('demo')/resqml22.TriangulatedSetRepresentation(uuid)`,
/// `eml:///resqml22.TriangulatedSetRepresentation(uuid=…,version='2')`.
///
/// An Energistics URI always has three slashes here: the Identifier
/// Specification v4.0 allowed an authority between the second and the third
/// (`eml://witsml14/well(uid)`), and v5.0 and ETP v1.2 no longer do.
#[derive(Clone, PartialEq, Eq, Debug, Default)]
pub struct EtpUri {
    /// Dataspace name, absent for the default dataspace.
    pub dataspace: Option<String>,
    /// Domain short name, absent for a bare dataspace URI.
    pub domain: Option<String>,
    /// Compact version digits.
    pub version: Option<String>,
    /// Object type.
    pub object_type: Option<String>,
    /// Object UUID, normalized to lowercase.
    pub uuid: Option<String>,
    /// The object's version, `version='…'`, when the URI names one - not to be
    /// confused with [`EtpUri::version`], the schema version of its type.
    pub object_version: Option<String>,
    /// Anything trailing the object, such as a sub-path.
    pub rest: Option<String>,
}

impl EtpUri {
    /// Parse an ETP URI.
    pub fn parse(value: &str) -> Result<Self> {
        let caps = etp_uri_re()
            .captures(value)
            .ok_or_else(|| Error::parse(value, "ETP URI", "does not match the ETP 1.2 grammar"))?;
        Ok(EtpUri {
            dataspace: caps.name("dataspace").map(|m| m.as_str().to_string()),
            domain: caps.name("domain").map(|m| m.as_str().to_string()),
            version: caps.name("version").map(|m| m.as_str().to_string()),
            object_type: caps.name("type").map(|m| m.as_str().to_string()),
            uuid: caps.name("uuid").map(|m| m.as_str().to_ascii_lowercase()),
            // A quote is written twice inside a quoted value (ETP v1.2 §25.3.10):
            // the version `O'Neil` travels as `O''Neil`.
            object_version: caps.name("objversion").map(|m| m.as_str().replace("''", "'")),
            rest: caps
                .name("rest")
                .map(|m| m.as_str().to_string())
                .filter(|s| !s.is_empty()),
        })
    }

    /// Whether `value` is a **canonical** ETP URI (ETP v1.2 §25.3.4-25.3.10) -
    /// what every endpoint must understand, and what some messages require
    /// whatever was negotiated (§3.7.4.2). Anything else, however well it
    /// reads, is at best an alternate URI (§25.3.9).
    pub fn is_canonical(value: &str) -> bool {
        canonical_etp_uri_res().iter().any(|re| re.is_match(value))
    }

    /// Whether the URI addresses a dataspace rather than an object.
    pub fn is_dataspace(&self) -> bool {
        self.uuid.is_none()
    }

    /// The qualified type this URI refers to, if it addresses an object.
    pub fn qualified_type(&self) -> Option<QualifiedType> {
        Some(QualifiedType {
            domain: self.domain.clone()?,
            version: self.version.clone()?,
            object_type: self.object_type.clone()?,
        })
    }

    /// Build a data-object URI.
    pub fn object(dataspace: Option<&str>, qualified_type: &str, uuid: &str) -> String {
        Self::object_versioned(dataspace, qualified_type, uuid, None)
    }

    /// Build a data-object URI that names the object's version when it has
    /// one: `eml:///{type}(uuid={uuid},version='{version}')` - Identifier
    /// Specification v5.0 §3.4.2 (p. 14); a quote inside the version is written
    /// twice (ETP v1.2 §25.3.10). Without a version this is the short form,
    /// which §3.4.2.1 (p. 15) reads as *the most recent version*.
    pub fn object_versioned(
        dataspace: Option<&str>,
        qualified_type: &str,
        uuid: &str,
        object_version: Option<&str>,
    ) -> String {
        let name = match object_version {
            Some(version) => {
                format!(
                    "{qualified_type}(uuid={uuid},version='{}')",
                    version.replace('\'', "''")
                )
            }
            None => format!("{qualified_type}({uuid})"),
        };
        match dataspace {
            Some(ds) => format!("eml:///dataspace('{ds}')/{name}"),
            None => format!("eml:///{name}"),
        }
    }
}

impl fmt::Display for EtpUri {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "eml:///")?;
        if let Some(ds) = &self.dataspace {
            write!(f, "dataspace('{ds}')")?;
            if self.uuid.is_some() {
                write!(f, "/")?;
            }
        }
        if let (Some(d), Some(v), Some(t), Some(u)) =
            (&self.domain, &self.version, &self.object_type, &self.uuid)
        {
            match &self.object_version {
                Some(ov) => write!(f, "{d}{v}.{t}(uuid={u},version='{}')", ov.replace('\'', "''"))?,
                None => write!(f, "{d}{v}.{t}({u})")?,
            }
            if let Some(rest) = &self.rest {
                write!(f, "/{rest}")?;
            }
        }
        Ok(())
    }
}

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

    #[test]
    fn uuids() {
        assert!(is_uuid("a1b2c3d4-e5f6-7890-abcd-ef1234567890"));
        assert!(!is_uuid("not-a-uuid"));
        assert_eq!(
            normalize_uuid(" A1B2C3D4-E5F6-7890-ABCD-EF1234567890 ").unwrap(),
            "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
        );
    }

    #[test]
    fn content_types() {
        let ct =
            ContentType::parse("application/x-resqml+xml;version=2.2;type=TriangulatedSetRepresentation")
                .unwrap();
        assert_eq!(ct.domain, "resqml");
        assert_eq!(ct.version, "2.2");
        assert_eq!(ct.object_type.as_deref(), Some("TriangulatedSetRepresentation"));

        // RESQML 2.0.1 spells top-level objects with the obj_ prefix, and it
        // must survive: fesapi writes it, and the EPC part is named after it.
        let raw = "application/x-resqml+xml;version=2.0;type=obj_TriangulatedSetRepresentation";
        let old = ContentType::parse(raw).unwrap();
        assert_eq!(
            old.object_type.as_deref(),
            Some("obj_TriangulatedSetRepresentation")
        );
        assert_eq!(
            old.to_string(),
            raw,
            "a parsed content type must round trip verbatim"
        );
        assert_eq!(old.type_key(), Some("TriangulatedSetRepresentation"));

        // A referenced non-EnergyML part.
        let h5 = ContentType::parse("application/x-hdf5;version=1.0").unwrap();
        assert_eq!(h5.raw_mime.as_deref(), Some("x-hdf5"));
    }

    #[test]
    fn qualified_types() {
        let qt = QualifiedType::parse("resqml22.TriangulatedSetRepresentation").unwrap();
        assert_eq!(qt.domain, "resqml");
        assert_eq!(qt.version, "22");
        assert_eq!(qt.dotted_version(), "2.2");
        assert_eq!(qt.to_string(), "resqml22.TriangulatedSetRepresentation");
    }

    #[test]
    fn etp_uris() {
        let uri = EtpUri::parse(
            "eml:///dataspace('demo/ds')/resqml22.TriangulatedSetRepresentation(a1b2c3d4-e5f6-7890-abcd-ef1234567890)",
        )
        .unwrap();
        assert_eq!(uri.dataspace.as_deref(), Some("demo/ds"));
        assert_eq!(uri.object_type.as_deref(), Some("TriangulatedSetRepresentation"));
        assert!(!uri.is_dataspace());

        let ds = EtpUri::parse("eml:///dataspace('demo')").unwrap();
        assert!(ds.is_dataspace());

        let no_ds = EtpUri::parse("eml:///witsml21.Well(a1b2c3d4-e5f6-7890-abcd-ef1234567890)").unwrap();
        assert_eq!(no_ds.dataspace, None);
        assert_eq!(no_ds.domain.as_deref(), Some("witsml"));

        // Round trip - against the string read, not against itself.
        assert_eq!(
            uri.to_string(),
            "eml:///dataspace('demo/ds')/resqml22.TriangulatedSetRepresentation(a1b2c3d4-e5f6-7890-abcd-ef1234567890)"
        );
    }

    /// The version of an object is part of a canonical URI (ETP v1.2
    /// §25.3.7, §25.3.10): read, kept apart from the schema version, and
    /// written back.
    #[test]
    fn a_versioned_object_uri_reads_and_writes_back() {
        let text = "eml:///dataspace('rdms-db')/resqml20.obj_HorizonInterpretation(uuid=421a7a05-033a-450d-bcef-051352023578,version='2.0')";
        let uri = EtpUri::parse(text).unwrap();
        assert_eq!(uri.uuid.as_deref(), Some("421a7a05-033a-450d-bcef-051352023578"));
        assert_eq!(uri.object_version.as_deref(), Some("2.0"));
        assert_eq!(
            uri.version.as_deref(),
            Some("20"),
            "the schema version is another field"
        );
        assert_eq!(uri.rest, None);
        assert_eq!(uri.to_string(), text);
        assert!(EtpUri::is_canonical(text));
        // `uuid=` without a version reads, and is not canonical (§25.3.9 item 7).
        let alternate =
            "eml:///resqml20.obj_HorizonInterpretation(uuid=421a7a05-033a-450d-bcef-051352023578)";
        assert!(EtpUri::parse(alternate).is_ok());
        assert!(!EtpUri::is_canonical(alternate));
    }
}