wsdl 0.1.3

Idiomatic Rust wrapper for WSDL
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
use roxmltree::{Document, ExpandedName, Node, NodeId};
use thiserror::Error;

type Result<'a, 'input, T> = std::result::Result<T, WsError>;

#[derive(Error, Debug)]
pub enum WsErrorMalformedType {
    #[error("missing attribute \"{0}\"")]
    MissingAttribute(String),
    #[error("missing element \"{0}\"")]
    MissingElement(String),
}

#[derive(Error, Debug)]
pub enum WsErrorType {
    #[error("The input WSDL document was malformed: {0}")]
    MalformedWsdl(WsErrorMalformedType),
    #[error("Attempt to refer to unknown element {0}")]
    InvalidReference(String),
    #[error("Node unexpectedly did not have a parent node")]
    NoParentNode,
}

#[derive(Error, Debug)]
pub struct WsError(pub NodeId, pub WsErrorType);

impl WsError {
    fn new(node: Node, typ: WsErrorType) -> Self {
        Self(node.id(), typ)
    }
}

impl std::fmt::Display for WsError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("{}", self.1))
    }
}

fn target_namespace<'a, 'input>(node: Node<'a, 'input>) -> Result<'a, 'input, &'a str> {
    // Traverse the parents until we find the targetNamespace attribute.
    let mut nparent = node.parent();
    while let Some(parent) = nparent {
        if let Some(ns) = parent.attribute("targetNamespace") {
            return Ok(ns);
        }

        nparent = parent.parent();
    }

    Err(WsError::new(
        node,
        WsErrorType::MalformedWsdl(WsErrorMalformedType::MissingAttribute(
            "targetNamespace".to_string(),
        )),
    ))
}

fn resolve_qualified<'a, 'input: 'a>(
    node: Node<'a, 'input>,
    qualified_name: &'a str,
) -> std::result::Result<ExpandedName<'a, 'a>, WsErrorType> {
    if qualified_name.contains(":") {
        let mut s = qualified_name.split(":");

        let ns = s
            .next()
            .ok_or(WsErrorType::InvalidReference(qualified_name.to_string()))?;

        let uri = node
            .lookup_namespace_uri(Some(ns))
            .ok_or(WsErrorType::InvalidReference(qualified_name.to_string()))?;

        let name = s
            .next()
            .ok_or(WsErrorType::InvalidReference(qualified_name.to_string()))?;

        Ok((uri, name).into())
    } else {
        Ok(qualified_name.into())
    }
}

fn split_qualified(qualified_name: &str) -> std::result::Result<(Option<&str>, &str), WsErrorType> {
    let (namespace, name) = {
        if qualified_name.contains(":") {
            let mut s = qualified_name.split(":");
            let ns = s
                .next()
                .ok_or(WsErrorType::InvalidReference(qualified_name.to_string()))?;

            let name = s
                .next()
                .ok_or(WsErrorType::InvalidReference(qualified_name.to_string()))?;

            (Some(ns), name)
        } else {
            (None, qualified_name)
        }
    };

    Ok((namespace, name))
}

// Given a qualified name such as `tns:MyAnnoyingXmlType`, look for an XML
// node with both the name and element type.
/*
fn lookup_qualified<'a, 'input>(
    root: Node<'a, 'input>,
    name: &str,
    tag: &str,
) -> Option<Node<'a, 'input>> {
    todo!()
}
*/

/// Describes a WSDL `message`. These can otherwise be described as
/// a list of function parameters.
#[derive(Debug, Clone)]
pub struct WsMessage<'a, 'input>(Node<'a, 'input>);

impl<'a, 'input> WsMessage<'a, 'input> {
    /// Retrieve the name of the message.
    pub fn name(&self) -> Result<&'a str> {
        self.0.attribute("name").ok_or(WsError::new(
            self.0,
            WsErrorType::MalformedWsdl(WsErrorMalformedType::MissingAttribute("name".to_string())),
        ))
    }

    /// Retrieve the parts of this message.
    pub fn parts(&self) -> impl Iterator<Item = WsMessagePart> {
        self.0
            .children()
            .filter(|n| n.has_tag_name(("http://schemas.xmlsoap.org/wsdl/", "part")))
            .map(|n| WsMessagePart(n))
    }

    /// Return the XML node this struct is associated with
    pub fn node(&self) -> Node<'a, 'input> {
        self.0
    }
}

/// Describes a part of a WSDL message. This can otherwise be described
/// as an individual function parameter.
#[derive(Debug, Clone)]
pub struct WsMessagePart<'a, 'input>(Node<'a, 'input>);

impl<'a, 'input: 'a> WsMessagePart<'a, 'input> {
    /// Retrieve the name of the part.
    pub fn name(&self) -> Result<&'a str> {
        self.0.attribute("name").ok_or(WsError::new(
            self.0,
            WsErrorType::MalformedWsdl(WsErrorMalformedType::MissingAttribute("name".to_string())),
        ))
    }

    /// Retrieve the typename of this parameter. This refers to a type defined
    /// under the `wsdl:types` XML node.
    pub fn typename(&self) -> Result<ExpandedName<'a, 'a>> {
        let typename = self
            .0
            .attribute("element")
            .or(self.0.attribute("type"))
            .ok_or(WsError::new(
                self.0,
                WsErrorType::MalformedWsdl(WsErrorMalformedType::MissingAttribute(
                    "type".to_string(),
                )),
            ))?;

        resolve_qualified(self.0, typename).map_err(|e| WsError::new(self.0, e))
    }

    /// Return the XML node this struct is associated with
    pub fn node(&self) -> Node<'a, 'input> {
        self.0
    }
}

/// Describes a WSDL `portType`. These describe groups of operations.
#[derive(Debug, Clone)]
pub struct WsPortType<'a, 'input>(Node<'a, 'input>);

impl<'a, 'input> WsPortType<'a, 'input> {
    /// Retrieve the name of the port type.
    pub fn name(&self) -> Result<&'a str> {
        self.0.attribute("name").ok_or(WsError::new(
            self.0,
            WsErrorType::MalformedWsdl(WsErrorMalformedType::MissingAttribute("name".to_string())),
        ))
    }

    /// Retrieve the port type's target namespace.
    pub fn target_namespace(&self) -> Result<&'a str> {
        target_namespace(self.0)
    }

    /// Retrieve the operations associated with this port.
    pub fn operations(&self) -> Result<impl Iterator<Item = WsPortOperation<'a, 'input>>> {
        Ok(self
            .0
            .children()
            .filter(|n| n.has_tag_name(("http://schemas.xmlsoap.org/wsdl/", "operation")))
            .map(|n| WsPortOperation(n)))
    }

    /// Return the XML node this struct is associated with
    pub fn node(&self) -> Node<'a, 'input> {
        self.0
    }
}

/// Describes an operation associated with a WSDL `portType`.
/// A WSDL operation can otherwise be described as a function.
#[derive(Debug, Clone)]
pub struct WsPortOperation<'a, 'input>(Node<'a, 'input>);

impl<'a, 'input> WsPortOperation<'a, 'input> {
    /// Retrieve the name of an operation.
    pub fn name(&self) -> Result<&'a str> {
        self.0.attribute("name").ok_or(WsError::new(
            self.0,
            WsErrorType::MalformedWsdl(WsErrorMalformedType::MissingAttribute("name".to_string())),
        ))
    }

    /// Retrieve the input message for this port.
    pub fn input(&self) -> Result<Option<WsMessage<'a, 'input>>> {
        let message_typename = match self
            .0
            .children()
            .find(|n| n.has_tag_name(("http://schemas.xmlsoap.org/wsdl/", "input")))
            .map(|n| n.attribute("message"))
            .flatten()
        {
            Some(n) => n,
            None => return Ok(None),
        };

        let (_message_namespace, message_name) =
            split_qualified(message_typename).map_err(|e| WsError::new(self.0, e))?;

        let def = WsDefinitions::find_parent(self.0)?;
        Ok(Some(
            def.messages()?
                .find(|n| n.0.attribute("name") == Some(message_name))
                .ok_or(WsError::new(
                    self.0,
                    WsErrorType::InvalidReference(message_name.to_string()),
                ))?,
        ))
    }

    /// Retrieve the output message for this port.
    pub fn output(&self) -> Result<Option<WsMessage<'a, 'input>>> {
        let message_typename = match self
            .0
            .children()
            .find(|n| n.has_tag_name(("http://schemas.xmlsoap.org/wsdl/", "output")))
            .map(|n| n.attribute("message"))
            .flatten()
        {
            Some(n) => n,
            None => return Ok(None),
        };

        let (_message_namespace, message_name) =
            split_qualified(message_typename).map_err(|e| WsError::new(self.0, e))?;

        let def = WsDefinitions::find_parent(self.0)?;
        Ok(Some(
            def.messages()?
                .find(|n| n.0.attribute("name") == Some(message_name))
                .ok_or(WsError::new(
                    self.0,
                    WsErrorType::InvalidReference(message_name.to_string()),
                ))?,
        ))
    }

    /// Retrieve the fault message for this port.
    pub fn fault(&self) -> Result<Option<WsMessage<'a, 'input>>> {
        let message_typename = match self
            .0
            .children()
            .find(|n| n.has_tag_name(("http://schemas.xmlsoap.org/wsdl/", "fault")))
            .map(|n| n.attribute("message"))
            .flatten()
        {
            Some(n) => n,
            None => return Ok(None),
        };

        let (_message_namespace, message_name) =
            split_qualified(message_typename).map_err(|e| WsError::new(self.0, e))?;

        let def = WsDefinitions::find_parent(self.0)?;
        Ok(Some(
            def.messages()?
                .find(|n| n.0.attribute("name") == Some(message_name))
                .ok_or(WsError::new(
                    self.0,
                    WsErrorType::InvalidReference(message_name.to_string()),
                ))?,
        ))
    }

    /// Return the XML node this struct is associated with
    pub fn node(&self) -> Node<'a, 'input> {
        self.0
    }
}

/// A WSDL binding operation.
#[derive(Debug, Clone)]
pub struct WsBindingOperation<'a, 'input>(Node<'a, 'input>);

impl<'a, 'input> WsBindingOperation<'a, 'input> {
    /// Return the name of the operation described.
    pub fn name(&self) -> Result<&'a str> {
        self.0.attribute("name").ok_or(WsError::new(
            self.0,
            WsErrorType::MalformedWsdl(WsErrorMalformedType::MissingAttribute("name".to_string())),
        ))
    }

    /// Retrieve the port operation that corresponds to this binding operation.
    pub fn port_operation(&self) -> Result<WsPortOperation<'a, 'input>> {
        let name = self.name()?;
        let binding = WsBinding(
            self.0
                .parent()
                .ok_or(WsError::new(self.0, WsErrorType::NoParentNode))?,
        );

        let port_type: WsPortType<'a, 'input> = binding.port_type()?;
        let mut operations = port_type.operations()?;

        operations
            .try_find(|o| Ok(o.name()? == name))?
            .ok_or(WsError::new(
                self.0,
                WsErrorType::MalformedWsdl(WsErrorMalformedType::MissingElement(name.to_string())),
            ))
    }

    /// Return the XML node this struct is associated with
    pub fn node(&self) -> Node<'a, 'input> {
        self.0
    }
}

/// A WSDL binding that describes how the operations in a port type
/// are bound to/from the wire.
#[derive(Debug, Clone)]
pub struct WsBinding<'a, 'input>(Node<'a, 'input>);

impl<'a, 'input> WsBinding<'a, 'input> {
    /// Retrieve the name of a binding.
    pub fn name(&self) -> Result<&'a str> {
        self.0.attribute("name").ok_or(WsError::new(
            self.0,
            WsErrorType::MalformedWsdl(WsErrorMalformedType::MissingAttribute("name".to_string())),
        ))
    }

    pub fn port_type(&self) -> Result<WsPortType<'a, 'input>> {
        let port_typename = self.0.attribute("type").ok_or(WsError::new(
            self.0,
            WsErrorType::MalformedWsdl(WsErrorMalformedType::MissingAttribute("type".to_string())),
        ))?;

        let (_port_namespace, port_name) =
            split_qualified(port_typename).map_err(|e| WsError::new(self.0, e))?;

        let def = WsDefinitions::find_parent(self.0)?;
        def.port_types()?
            .find(|n| n.0.attribute("name") == Some(port_name))
            .ok_or(WsError::new(
                self.0,
                WsErrorType::InvalidReference(port_name.to_string()),
            ))
    }

    pub fn operations(&self) -> Result<impl Iterator<Item = WsBindingOperation>> {
        Ok(self
            .0
            .children()
            .filter(|n| n.has_tag_name(("http://schemas.xmlsoap.org/wsdl/", "operation")))
            .map(|n| WsBindingOperation(n)))
    }

    /// Return the XML node this struct is associated with
    pub fn node(&self) -> Node<'a, 'input> {
        self.0
    }
}

#[derive(Debug, Clone)]
pub struct WsServicePort<'a, 'input>(Node<'a, 'input>);

impl<'a, 'input> WsServicePort<'a, 'input> {
    pub fn name(&self) -> Result<&'a str> {
        self.0.attribute("name").ok_or(WsError::new(
            self.0,
            WsErrorType::MalformedWsdl(WsErrorMalformedType::MissingAttribute("name".to_string())),
        ))
    }

    /// Fetch the binding information associated with this service port.
    pub fn binding(&self) -> Result<WsBinding<'a, 'input>> {
        let binding_typename = self.0.attribute("binding").ok_or(WsError::new(
            self.0,
            WsErrorType::MalformedWsdl(WsErrorMalformedType::MissingAttribute(
                "binding".to_string(),
            )),
        ))?;

        let (_binding_namespace, binding_name) =
            split_qualified(binding_typename).map_err(|e| WsError::new(self.0, e))?;

        let def = WsDefinitions::find_parent(self.0)?;
        def.bindings()?
            .find(|n| n.0.attribute("name") == Some(binding_name))
            .ok_or(WsError::new(
                self.0,
                WsErrorType::InvalidReference(binding_name.to_string()),
            ))
    }

    /// Return the XML node this struct is associated with
    pub fn node(&self) -> Node<'a, 'input> {
        self.0
    }
}

/// A WSDL service, usually describing an HTTP endpoint that serves
/// messages bound with a [WsBinding]
#[derive(Debug, Clone)]
pub struct WsService<'a, 'input>(Node<'a, 'input>);

impl<'a, 'input> WsService<'a, 'input> {
    pub fn name(&self) -> Result<&'a str> {
        self.0.attribute("name").ok_or(WsError::new(
            self.0,
            WsErrorType::MalformedWsdl(WsErrorMalformedType::MissingAttribute("name".to_string())),
        ))
    }

    pub fn ports(&self) -> Result<impl Iterator<Item = WsServicePort>> {
        Ok(self
            .0
            .children()
            .filter(|n| n.has_tag_name(("http://schemas.xmlsoap.org/wsdl/", "port")))
            .map(|n| WsServicePort(n)))
    }

    /// Return the XML node this struct is associated with
    pub fn node(&self) -> Node<'a, 'input> {
        self.0
    }
}

#[derive(Debug, Clone)]
pub struct WsTypes<'a, 'input>(Node<'a, 'input>);

impl<'a, 'input> WsTypes<'a, 'input> {
    /// Return the schemas contained within. These are defined according to the XML schema specification,
    /// and are out of scope for this library to interpret.
    pub fn schemas(&self) -> Result<impl Iterator<Item = Node<'a, 'input>>> {
        Ok(self
            .0
            .children()
            .filter(|n| n.has_tag_name(("http://www.w3.org/2001/XMLSchema", "schema"))))
    }
}

#[derive(Debug, Clone)]
pub struct WsDefinitions<'a, 'input>(Node<'a, 'input>);

impl<'a, 'input> WsDefinitions<'a, 'input> {
    /// Find the definitions block from one of the node's parents
    fn find_parent(mut node: Node<'a, 'input>) -> Result<'a, 'input, Self> {
        loop {
            node = node
                .parent()
                .ok_or(WsError::new(node, WsErrorType::NoParentNode))?;

            if let Ok(definitions) = Self::from_node(node) {
                return Ok(definitions);
            }
        }
    }

    pub fn from_node(node: Node<'a, 'input>) -> Result<'a, 'input, Self> {
        if node.has_tag_name(("http://schemas.xmlsoap.org/wsdl/", "definitions")) {
            Ok(Self(node))
        } else {
            Err(WsError::new(
                node,
                WsErrorType::MalformedWsdl(WsErrorMalformedType::MissingElement(
                    "definitions".to_string(),
                )),
            ))
        }
    }

    pub fn from_document(document: &'a Document<'input>) -> Result<'a, 'input, Self> {
        document
            .root()
            .children()
            .find(|n| n.has_tag_name(("http://schemas.xmlsoap.org/wsdl/", "definitions")))
            .ok_or(WsError::new(
                document.root_element(),
                WsErrorType::MalformedWsdl(WsErrorMalformedType::MissingElement(
                    "definitions".to_string(),
                )),
            ))
            .map(|n| Self(n))
    }

    pub fn port_types(&self) -> Result<impl Iterator<Item = WsPortType<'a, 'input>>> {
        Ok(self
            .0
            .children()
            .filter(|n| n.has_tag_name(("http://schemas.xmlsoap.org/wsdl/", "portType")))
            .map(|n| WsPortType(n))
            .into_iter())
    }

    pub fn messages(&self) -> Result<impl Iterator<Item = WsMessage<'a, 'input>>> {
        Ok(self
            .0
            .children()
            .filter(|n| n.has_tag_name(("http://schemas.xmlsoap.org/wsdl/", "message")))
            .map(|n| WsMessage(n))
            .into_iter())
    }

    pub fn bindings(&self) -> Result<impl Iterator<Item = WsBinding<'a, 'input>>> {
        Ok(self
            .0
            .children()
            .filter(|n| n.has_tag_name(("http://schemas.xmlsoap.org/wsdl/", "binding")))
            .map(|n| WsBinding(n))
            .into_iter())
    }

    pub fn services(&self) -> Result<impl Iterator<Item = WsService<'a, 'input>>> {
        Ok(self
            .0
            .children()
            .filter(|n| n.has_tag_name(("http://schemas.xmlsoap.org/wsdl/", "service")))
            .map(|n| WsService(n))
            .into_iter())
    }

    pub fn types(&self) -> Result<impl Iterator<Item = Node<'a, 'input>>> {
        // FIXME: I'm pretty sure only one of these nodes can exist?
        Ok(self
            .0
            .children()
            .filter(|n| n.has_tag_name(("http://schemas.xmlsoap.org/wsdl/", "types")))
            .into_iter())
    }
}