Skip to main content

netconf_async/
message.rs

1//! NETCONF messages: `<hello>`, `<rpc>`, `<rpc-reply>`, and operation bodies.
2
3use crate::{NETCONF_URN, error};
4use core::fmt;
5use core::fmt::Display;
6use core::str::FromStr;
7use quick_xml::se::Serializer;
8use serde::de::DeserializeOwned;
9use serde::{Deserialize, Deserializer, Serialize};
10use time::OffsetDateTime;
11use time::format_description::well_known::Rfc3339;
12use uuid::Uuid;
13
14/// Deserialize `xml`, retrying without namespace prefixes if the first pass fails.
15///
16/// Devices that answer with `<nc:hello>` / `<nc:rpc-reply>` are common enough
17/// that a strict, prefix-sensitive parse would refuse to talk to them. The
18/// retry only runs on failure, so conforming devices pay nothing.
19pub(crate) fn from_xml<T: DeserializeOwned>(xml: &str) -> error::NetconfClientResult<T> {
20    match quick_xml::de::from_str(xml) {
21        Ok(parsed) => Ok(parsed),
22        Err(err) => match strip_namespace_prefixes(xml) {
23            Some(stripped) => quick_xml::de::from_str(&stripped).map_err(|_| err.into()),
24            None => Err(err.into()),
25        },
26    }
27}
28
29/// Rewrite every element name to its local part, dropping the namespace prefix.
30///
31/// Returns `None` when the document cannot be re-serialized, in which case the
32/// caller keeps the original parse error.
33fn strip_namespace_prefixes(xml: &str) -> Option<String> {
34    use quick_xml::events::{BytesEnd, BytesStart, Event};
35    use quick_xml::{Reader, Writer};
36
37    let mut reader = Reader::from_str(xml);
38    let mut writer = Writer::new(Vec::new());
39    let mut changed = false;
40    loop {
41        match reader.read_event().ok()? {
42            Event::Eof => break,
43            Event::Start(event) => {
44                let (name, renamed) = local_name(&event);
45                changed |= renamed;
46                let mut start = BytesStart::new(name);
47                start.extend_attributes(event.attributes().filter_map(Result::ok));
48                writer.write_event(Event::Start(start)).ok()?;
49            }
50            Event::Empty(event) => {
51                let (name, renamed) = local_name(&event);
52                changed |= renamed;
53                let mut start = BytesStart::new(name);
54                start.extend_attributes(event.attributes().filter_map(Result::ok));
55                writer.write_event(Event::Empty(start)).ok()?;
56            }
57            Event::End(event) => {
58                let name = String::from_utf8_lossy(event.local_name().as_ref()).into_owned();
59                changed |= name.len() != event.name().as_ref().len();
60                writer.write_event(Event::End(BytesEnd::new(name))).ok()?;
61            }
62            event => writer.write_event(event).ok()?,
63        }
64    }
65    if !changed {
66        return None;
67    }
68    String::from_utf8(writer.into_inner()).ok()
69}
70
71fn local_name(event: &quick_xml::events::BytesStart<'_>) -> (String, bool) {
72    let local = String::from_utf8_lossy(event.local_name().as_ref()).into_owned();
73    let renamed = local.len() != event.name().as_ref().len();
74    (local, renamed)
75}
76
77/// Capability URN without its `?query` parameters.
78pub(crate) fn capability_id(capability: &str) -> &str {
79    capability
80        .split_once('?')
81        .map(|(base, _)| base)
82        .unwrap_or(capability)
83}
84
85/// Caller-supplied XML that must reach the device verbatim.
86///
87/// The serializer escapes every string it writes, which would corrupt a config
88/// or filter payload. Serializing a placeholder and substituting the original
89/// afterwards keeps the payload intact without disturbing the escaping of
90/// neighbouring elements such as `<url>`.
91#[derive(Debug)]
92struct RawXml {
93    xml: String,
94    placeholder: String,
95}
96
97impl RawXml {
98    fn new(xml: &str) -> Self {
99        RawXml {
100            xml: xml.trim().to_string(),
101            placeholder: format!("netconf-raw-{}", Uuid::new_v4().simple()),
102        }
103    }
104}
105
106impl Serialize for RawXml {
107    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
108        // The placeholder is `[a-z0-9-]` only, so the serializer writes it as-is.
109        serializer.serialize_str(&self.placeholder)
110    }
111}
112
113/// `<hello>` advertisement ([RFC6241 8.1](https://www.rfc-editor.org/rfc/rfc6241.html#section-8.1)).
114///
115/// [`Hello::new`] advertises `:base:1.0` and `:base:1.1`.
116#[derive(Debug, Default, Deserialize, Serialize)]
117#[serde(rename(serialize = "hello"))]
118pub struct Hello {
119    #[serde(rename = "@xmlns", default, skip_serializing_if = "Option::is_none")]
120    xmlns: Option<String>,
121    capabilities: Capabilities,
122    #[serde(
123        rename = "session-id",
124        default,
125        skip_serializing_if = "Option::is_none"
126    )]
127    session_id: Option<u64>,
128}
129
130impl Hello {
131    /// Client hello advertising `:base:1.0` and `:base:1.1`.
132    pub fn new() -> Hello {
133        Hello {
134            xmlns: Some(NETCONF_URN.to_string()),
135            session_id: None,
136            capabilities: Capabilities {
137                capability: vec![
138                    crate::NETCONF_BASE_10_CAP.to_string(),
139                    crate::NETCONF_BASE_11_CAP.to_string(),
140                ],
141            },
142        }
143    }
144
145    /// Capability URNs advertised in this hello.
146    pub fn capabilities(&self) -> Vec<String> {
147        self.capabilities.capability.clone()
148    }
149
150    /// True if `capability` was advertised, ignoring any `?query` parameters.
151    pub fn has_capability(&self, capability: &str) -> bool {
152        self.capabilities
153            .capability
154            .iter()
155            .any(|cap| capability_id(cap) == capability)
156    }
157
158    /// Server-assigned session-id, present only on the server hello.
159    pub fn session_id(&self) -> Option<u64> {
160        self.session_id
161    }
162}
163
164impl Display for Hello {
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        let mut buffer = String::with_capacity(256);
167        buffer.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
168        self.serialize(Serializer::new(&mut buffer))
169            .map_err(|_| fmt::Error)?;
170        buffer.push('\n');
171        f.write_str(&buffer)
172    }
173}
174
175/// `<capabilities>` list inside `<hello>`.
176#[derive(Debug, Default, Deserialize, Serialize)]
177pub struct Capabilities {
178    capability: Vec<String>,
179}
180
181/// `<rpc>` envelope with a `message-id` ([RFC6241 4.1](https://www.rfc-editor.org/rfc/rfc6241.html#section-4.1)).
182///
183/// [`Connection`](crate::connection::Connection) assigns a per-session
184/// monotonically increasing integer. Standalone construction defaults to `"1"`.
185#[derive(Debug, Serialize)]
186pub struct Rpc {
187    #[serde(rename = "@message-id")]
188    message_id: String,
189    #[serde(rename = "@xmlns")]
190    xmlns: String,
191    #[serde(rename = "$value")]
192    operation: RpcOperation,
193}
194
195impl Rpc {
196    /// Wrap `operation` with `message-id` `"1"`.
197    ///
198    /// [`Connection`](crate::connection::Connection) overwrites this with the
199    /// next session counter before sending.
200    pub fn new_with_operation(operation: RpcOperation) -> Rpc {
201        Self::with_message_id(operation, "1")
202    }
203
204    /// Wrap `operation` with an explicit `message-id`.
205    pub fn with_message_id(operation: RpcOperation, message_id: impl Into<String>) -> Rpc {
206        Rpc {
207            xmlns: NETCONF_URN.to_string(),
208            message_id: message_id.into(),
209            operation,
210        }
211    }
212
213    pub(crate) fn set_message_id(&mut self, message_id: impl Into<String>) {
214        self.message_id = message_id.into();
215    }
216
217    /// `message-id` carried by this request.
218    pub fn message_id(&self) -> &str {
219        &self.message_id
220    }
221
222    /// True when this is a `<commit>` (including confirmed / persist confirm).
223    pub(crate) fn is_commit(&self) -> bool {
224        matches!(self.operation, RpcOperation::Commit(_))
225    }
226
227    /// RFC local-name of the wrapped operation (`get-config`, `lock`, …).
228    pub(crate) fn operation_name(&self) -> &'static str {
229        self.operation.name()
230    }
231}
232
233impl Display for Rpc {
234    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
235        let mut buffer = String::with_capacity(256);
236        let mut ser = Serializer::with_root(&mut buffer, Some("rpc")).map_err(|_| fmt::Error)?;
237        ser.indent(' ', 2);
238        self.serialize(ser).map_err(|_| fmt::Error)?;
239        for raw in self.operation.raw_payloads() {
240            buffer = buffer.replace(&raw.placeholder, &raw.xml);
241        }
242        f.write_str(&buffer)
243    }
244}
245
246/// Body of an `<rpc>` ([RFC6241 7](https://www.rfc-editor.org/rfc/rfc6241.html#section-7)).
247#[derive(Debug, Serialize)]
248#[serde(rename_all = "kebab-case")]
249#[non_exhaustive]
250pub enum RpcOperation {
251    /// `<close-session>`.
252    CloseSession,
253    /// `<kill-session>`.
254    KillSession {
255        /// Session to terminate.
256        #[serde(rename = "session-id")]
257        session_id: u64,
258    },
259    /// `<validate>`.
260    Validate {
261        /// Datastore to validate.
262        source: Source,
263    },
264    /// `<get-config>`.
265    GetConfig(GetConfig),
266    /// `<get>`.
267    Get(Get),
268    /// `<edit-config>`.
269    EditConfig(EditConfig),
270    /// `<copy-config>`.
271    CopyConfig(CopyConfig),
272    /// `<delete-config>`.
273    DeleteConfig {
274        /// Datastore to delete.
275        target: Target,
276    },
277    /// `<lock>`.
278    Lock {
279        /// Datastore to lock.
280        target: Target,
281    },
282    /// `<unlock>`.
283    Unlock {
284        /// Datastore to unlock.
285        target: Target,
286    },
287    /// `<discard-changes>`.
288    DiscardChanges,
289    /// `<cancel-commit>`.
290    CancelCommit(CancelCommit),
291    /// `<commit>`.
292    Commit(Commit),
293    /// `<create-subscription>`.
294    CreateSubscription(CreateSubscription),
295}
296
297impl RpcOperation {
298    /// RFC local-name (`get-config`, `close-session`, …).
299    pub(crate) fn name(&self) -> &'static str {
300        match self {
301            Self::CloseSession => "close-session",
302            Self::KillSession { .. } => "kill-session",
303            Self::Validate { .. } => "validate",
304            Self::GetConfig(_) => "get-config",
305            Self::Get(_) => "get",
306            Self::EditConfig(_) => "edit-config",
307            Self::CopyConfig(_) => "copy-config",
308            Self::DeleteConfig { .. } => "delete-config",
309            Self::Lock { .. } => "lock",
310            Self::Unlock { .. } => "unlock",
311            Self::DiscardChanges => "discard-changes",
312            Self::CancelCommit(_) => "cancel-commit",
313            Self::Commit(_) => "commit",
314            Self::CreateSubscription(_) => "create-subscription",
315        }
316    }
317
318    /// `<get-config>` ([RFC6241 7.1](https://www.rfc-editor.org/rfc/rfc6241.html#section-7.1)).
319    pub fn new_get_config(
320        datastore: Datastore,
321        filter: Option<Filter>,
322        defaults: Option<WithDefaultsValue>,
323    ) -> RpcOperation {
324        RpcOperation::GetConfig(GetConfig {
325            source: Source { datastore },
326            filter,
327            with_defaults: defaults.map(WithDefaults::new),
328        })
329    }
330
331    /// `<get>` ([RFC6241 7.7](https://www.rfc-editor.org/rfc/rfc6241.html#section-7.7)).
332    pub fn new_get(filter: Option<Filter>, defaults: Option<WithDefaultsValue>) -> RpcOperation {
333        RpcOperation::Get(Get {
334            filter,
335            with_defaults: defaults.map(WithDefaults::new),
336        })
337    }
338
339    /// `<commit>`, optionally confirmed ([RFC6241 8.3](https://www.rfc-editor.org/rfc/rfc6241.html#section-8.3), [8.4](https://www.rfc-editor.org/rfc/rfc6241.html#section-8.4)).
340    pub fn new_commit(
341        confirmed: Option<()>,
342        confirm_timeout: Option<i32>,
343        persist: Option<String>,
344        persist_id: Option<String>,
345    ) -> RpcOperation {
346        RpcOperation::Commit(Commit {
347            confirmed,
348            confirm_timeout,
349            persist,
350            persist_id,
351        })
352    }
353
354    /// `<create-subscription>` ([RFC5277 2.1.1](https://www.rfc-editor.org/rfc/rfc5277.html#section-2.1.1)).
355    ///
356    /// `start_time` / `stop_time` are RFC 3339. `stop_time` requires
357    /// `start_time`. `stop_time` earlier than `start_time` is rejected.
358    pub fn new_create_subscription(
359        stream: Option<&str>,
360        filter: Option<Filter>,
361        start_time: Option<&str>,
362        stop_time: Option<&str>,
363    ) -> error::NetconfClientResult<RpcOperation> {
364        let start_time = start_time.map(parse_date_time).transpose()?;
365        let stop_time = stop_time.map(parse_date_time).transpose()?;
366        if let Some(stop) = stop_time {
367            let Some(start) = start_time else {
368                return Err(error::NetconfClientError::new(
369                    "stopTime requires startTime (RFC5277 2.1.1)",
370                ));
371            };
372            if stop < start {
373                return Err(error::NetconfClientError::new(
374                    "stopTime is earlier than startTime (RFC5277 2.1.1)",
375                ));
376            }
377        }
378        Ok(RpcOperation::CreateSubscription(CreateSubscription {
379            xmlns: "urn:ietf:params:xml:ns:netconf:notification:1.0".to_string(),
380            stream: stream.map(str::to_string),
381            filter,
382            start_time,
383            stop_time,
384        }))
385    }
386
387    /// `<edit-config>` ([RFC6241 7.2](https://www.rfc-editor.org/rfc/rfc6241.html#section-7.2)).
388    pub fn new_edit_config(
389        target: Datastore,
390        content: EditContent,
391        default_operation: Option<DefaultOperation>,
392        test_option: Option<TestOption>,
393        error_option: Option<ErrorOption>,
394    ) -> RpcOperation {
395        let (config, url) = match content {
396            EditContent::Config(xml) => (Some(InlineConfig::new(&xml)), None),
397            EditContent::Url(url) => (None, Some(url)),
398        };
399        RpcOperation::EditConfig(EditConfig {
400            target: Target { datastore: target },
401            default_operation,
402            test_option,
403            error_option,
404            config,
405            url,
406        })
407    }
408
409    /// `<copy-config>` ([RFC6241 7.3](https://www.rfc-editor.org/rfc/rfc6241.html#section-7.3)).
410    pub fn new_copy_config(source: CopySource, target: Datastore) -> RpcOperation {
411        RpcOperation::CopyConfig(CopyConfig {
412            target: Target { datastore: target },
413            source: CopySourceXml {
414                value: CopySourceKind::from(source),
415            },
416        })
417    }
418
419    /// `<delete-config>` ([RFC6241 7.4](https://www.rfc-editor.org/rfc/rfc6241.html#section-7.4)).
420    pub fn new_delete_config(target: Datastore) -> RpcOperation {
421        RpcOperation::DeleteConfig {
422            target: Target { datastore: target },
423        }
424    }
425
426    /// `<lock>` ([RFC6241 7.5](https://www.rfc-editor.org/rfc/rfc6241.html#section-7.5)).
427    pub fn new_lock(target: Datastore) -> RpcOperation {
428        RpcOperation::Lock {
429            target: Target { datastore: target },
430        }
431    }
432
433    /// `<unlock>` ([RFC6241 7.6](https://www.rfc-editor.org/rfc/rfc6241.html#section-7.6)).
434    pub fn new_unlock(target: Datastore) -> RpcOperation {
435        RpcOperation::Unlock {
436            target: Target { datastore: target },
437        }
438    }
439
440    /// `<discard-changes>` ([RFC6241 8.3.4.2](https://www.rfc-editor.org/rfc/rfc6241.html#section-8.3.4.2)).
441    pub fn new_discard_changes() -> RpcOperation {
442        RpcOperation::DiscardChanges
443    }
444
445    /// `<cancel-commit>` ([RFC6241 8.4.4.1](https://www.rfc-editor.org/rfc/rfc6241.html#section-8.4.4.1)).
446    pub fn new_cancel_commit(persist_id: Option<String>) -> RpcOperation {
447        RpcOperation::CancelCommit(CancelCommit { persist_id })
448    }
449
450    /// Verbatim payloads to splice back in after serialization.
451    fn raw_payloads(&self) -> Vec<&RawXml> {
452        match self {
453            RpcOperation::Get(get) => get.filter.iter().map(|f| &f.filter).collect(),
454            RpcOperation::GetConfig(get) => get.filter.iter().map(|f| &f.filter).collect(),
455            RpcOperation::EditConfig(edit) => edit.config.iter().map(|c| &c.xml).collect(),
456            RpcOperation::CopyConfig(copy) => match &copy.source.value {
457                CopySourceKind::Config(raw) => vec![raw],
458                _ => Vec::new(),
459            },
460            RpcOperation::CreateSubscription(sub) => sub.filter.iter().map(|f| &f.filter).collect(),
461            _ => Vec::new(),
462        }
463    }
464}
465
466/// `<commit>` body ([RFC6241 8.3](https://www.rfc-editor.org/rfc/rfc6241.html#section-8.3), [8.4](https://www.rfc-editor.org/rfc/rfc6241.html#section-8.4)).
467#[derive(Debug, Serialize)]
468#[serde(rename_all = "kebab-case")]
469pub struct Commit {
470    #[serde(skip_serializing_if = "Option::is_none")]
471    confirmed: Option<()>,
472    #[serde(rename = "confirm-timeout", skip_serializing_if = "Option::is_none")]
473    confirm_timeout: Option<i32>,
474    #[serde(skip_serializing_if = "Option::is_none")]
475    persist: Option<String>,
476    #[serde(rename = "persist-id", skip_serializing_if = "Option::is_none")]
477    persist_id: Option<String>,
478}
479
480/// `<get>` body ([RFC6241 7.7](https://www.rfc-editor.org/rfc/rfc6241.html#section-7.7)).
481#[derive(Debug, Serialize)]
482#[serde(rename_all = "kebab-case")]
483pub struct Get {
484    #[serde(skip_serializing_if = "Option::is_none")]
485    filter: Option<Filter>,
486    #[serde(skip_serializing_if = "Option::is_none")]
487    with_defaults: Option<WithDefaults>,
488}
489
490/// `<get-config>` body ([RFC6241 7.1](https://www.rfc-editor.org/rfc/rfc6241.html#section-7.1)).
491#[derive(Debug, Serialize)]
492#[serde(rename_all = "kebab-case")]
493pub struct GetConfig {
494    source: Source,
495    #[serde(skip_serializing_if = "Option::is_none")]
496    filter: Option<Filter>,
497    #[serde(skip_serializing_if = "Option::is_none")]
498    with_defaults: Option<WithDefaults>,
499}
500
501/// `with-defaults` element ([RFC6243](https://www.rfc-editor.org/rfc/rfc6243.html)).
502#[derive(Debug, Serialize)]
503#[serde(rename_all = "kebab-case")]
504pub struct WithDefaults {
505    #[serde(rename = "@xmlns")]
506    xmlns: String,
507    #[serde(rename = "$text")]
508    value: WithDefaultsValue,
509}
510
511impl WithDefaults {
512    fn new(value: WithDefaultsValue) -> Self {
513        WithDefaults {
514            xmlns: "urn:ietf:params:xml:ns:yang:ietf-netconf-with-defaults".to_string(),
515            value,
516        }
517    }
518}
519
520/// `with-defaults` mode ([RFC6243](https://www.rfc-editor.org/rfc/rfc6243.html)).
521#[derive(Debug, Clone, Copy, Serialize)]
522#[serde(rename_all = "kebab-case")]
523pub enum WithDefaultsValue {
524    /// Report every default.
525    ReportAll,
526    /// Report every default, tagged.
527    ReportAllTagged,
528    /// Omit values equal to their default.
529    Trim,
530    /// Report only explicitly set values.
531    Explicit,
532}
533
534impl FromStr for WithDefaultsValue {
535    type Err = error::NetconfClientError;
536
537    fn from_str(s: &str) -> Result<Self, Self::Err> {
538        match s.trim().to_lowercase().as_str() {
539            "report-all" => Ok(WithDefaultsValue::ReportAll),
540            "report-all-tagged" => Ok(WithDefaultsValue::ReportAllTagged),
541            "trim" => Ok(WithDefaultsValue::Trim),
542            "explicit" => Ok(WithDefaultsValue::Explicit),
543            _ => Err(error::NetconfClientError::new(format!(
544                "unknown with-defaults value: {s}"
545            ))),
546        }
547    }
548}
549
550/// Source datastore of `<get-config>` / `<validate>` / `<copy-config>`.
551#[derive(Debug, Serialize)]
552pub struct Source {
553    /// Datastore being read.
554    #[serde(rename = "$value")]
555    pub datastore: Datastore,
556}
557
558/// Destination datastore of `<edit-config>` / `<copy-config>` ([RFC6241 7.2](https://www.rfc-editor.org/rfc/rfc6241.html#section-7.2)).
559#[derive(Debug, Serialize)]
560pub struct Target {
561    /// Datastore being written.
562    #[serde(rename = "$value")]
563    pub datastore: Datastore,
564}
565
566/// Configuration datastore ([RFC6241 5.1](https://www.rfc-editor.org/rfc/rfc6241.html#section-5.1)).
567#[derive(Debug, Clone, Serialize)]
568#[serde(rename_all = "lowercase")]
569pub enum Datastore {
570    /// `<candidate/>`.
571    Candidate,
572    /// `<running/>`.
573    Running,
574    /// `<startup/>`.
575    Startup,
576    /// `<url>`, requires the `:url` capability.
577    Url(String),
578}
579
580/// URL schemes accepted for the `:url` capability ([RFC6241 8.8](https://www.rfc-editor.org/rfc/rfc6241.html#section-8.8)).
581const URL_SCHEMES: [&str; 6] = ["http", "https", "ftp", "ftps", "file", "sftp"];
582
583impl FromStr for Datastore {
584    type Err = error::NetconfClientError;
585
586    /// Parse a datastore name. URLs keep their original case.
587    fn from_str(s: &str) -> Result<Self, Self::Err> {
588        let trimmed = s.trim();
589        match trimmed.to_lowercase().as_str() {
590            "running" => Ok(Datastore::Running),
591            "candidate" => Ok(Datastore::Candidate),
592            "startup" => Ok(Datastore::Startup),
593            _ => {
594                let scheme = trimmed
595                    .split_once("://")
596                    .filter(|(_, rest)| !rest.is_empty())
597                    .map(|(scheme, _)| scheme.to_lowercase());
598                match scheme {
599                    Some(scheme) if URL_SCHEMES.contains(&scheme.as_str()) => {
600                        Ok(Datastore::Url(trimmed.to_string()))
601                    }
602                    _ => Err(error::NetconfClientError::UnknownDatastore {
603                        expected: vec![
604                            "running".to_string(),
605                            "candidate".to_string(),
606                            "startup".to_string(),
607                            URL_SCHEMES.join("|"),
608                        ],
609                        unknown: trimmed.to_string(),
610                    }),
611                }
612            }
613        }
614    }
615}
616
617/// Payload of `<edit-config>`: inline config XML or a URL ([RFC6241 7.2](https://www.rfc-editor.org/rfc/rfc6241.html#section-7.2)).
618#[derive(Debug)]
619pub enum EditContent {
620    /// Config XML, with or without a `<config>` wrapper.
621    Config(String),
622    /// URL to fetch the config from.
623    Url(String),
624}
625
626/// `default-operation` of `<edit-config>` ([RFC6241 7.2](https://www.rfc-editor.org/rfc/rfc6241.html#section-7.2)).
627#[derive(Debug, Clone, Copy)]
628pub enum DefaultOperation {
629    /// Merge into the target.
630    Merge,
631    /// Replace the target.
632    Replace,
633    /// Only apply explicit `operation` attributes.
634    None,
635}
636
637impl DefaultOperation {
638    fn as_str(self) -> &'static str {
639        match self {
640            Self::Merge => "merge",
641            Self::Replace => "replace",
642            Self::None => "none",
643        }
644    }
645}
646
647impl Serialize for DefaultOperation {
648    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
649        serializer.serialize_str(self.as_str())
650    }
651}
652
653impl FromStr for DefaultOperation {
654    type Err = error::NetconfClientError;
655
656    fn from_str(s: &str) -> Result<Self, Self::Err> {
657        match s.trim().to_lowercase().as_str() {
658            "merge" => Ok(Self::Merge),
659            "replace" => Ok(Self::Replace),
660            "none" => Ok(Self::None),
661            _ => Err(error::NetconfClientError::new(format!(
662                "unknown default-operation: {s}"
663            ))),
664        }
665    }
666}
667
668/// `test-option` of `<edit-config>` ([RFC6241 7.2](https://www.rfc-editor.org/rfc/rfc6241.html#section-7.2)).
669#[derive(Debug, Clone, Copy)]
670pub enum TestOption {
671    /// Validate, then apply.
672    TestThenSet,
673    /// Apply without validating.
674    Set,
675    /// Validate only.
676    TestOnly,
677}
678
679impl TestOption {
680    fn as_str(self) -> &'static str {
681        match self {
682            Self::TestThenSet => "test-then-set",
683            Self::Set => "set",
684            Self::TestOnly => "test-only",
685        }
686    }
687}
688
689impl Serialize for TestOption {
690    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
691        serializer.serialize_str(self.as_str())
692    }
693}
694
695impl FromStr for TestOption {
696    type Err = error::NetconfClientError;
697
698    fn from_str(s: &str) -> Result<Self, Self::Err> {
699        match s.trim().to_lowercase().as_str() {
700            "test-then-set" => Ok(Self::TestThenSet),
701            "set" => Ok(Self::Set),
702            "test-only" => Ok(Self::TestOnly),
703            _ => Err(error::NetconfClientError::new(format!(
704                "unknown test-option: {s}"
705            ))),
706        }
707    }
708}
709
710/// `error-option` of `<edit-config>` ([RFC6241 7.2](https://www.rfc-editor.org/rfc/rfc6241.html#section-7.2)).
711#[derive(Debug, Clone, Copy)]
712pub enum ErrorOption {
713    /// Stop at the first error.
714    StopOnError,
715    /// Keep going past errors.
716    ContinueOnError,
717    /// Roll the whole edit back on error.
718    RollbackOnError,
719}
720
721impl ErrorOption {
722    fn as_str(self) -> &'static str {
723        match self {
724            Self::StopOnError => "stop-on-error",
725            Self::ContinueOnError => "continue-on-error",
726            Self::RollbackOnError => "rollback-on-error",
727        }
728    }
729}
730
731impl Serialize for ErrorOption {
732    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
733        serializer.serialize_str(self.as_str())
734    }
735}
736
737impl FromStr for ErrorOption {
738    type Err = error::NetconfClientError;
739
740    fn from_str(s: &str) -> Result<Self, Self::Err> {
741        match s.trim().to_lowercase().as_str() {
742            "stop-on-error" => Ok(Self::StopOnError),
743            "continue-on-error" => Ok(Self::ContinueOnError),
744            "rollback-on-error" => Ok(Self::RollbackOnError),
745            _ => Err(error::NetconfClientError::new(format!(
746                "unknown error-option: {s}"
747            ))),
748        }
749    }
750}
751
752#[derive(Debug, Serialize)]
753struct InlineConfig {
754    #[serde(rename = "$value")]
755    xml: RawXml,
756}
757
758impl InlineConfig {
759    fn new(xml: &str) -> Self {
760        Self {
761            xml: RawXml::new(strip_config_wrapper(xml)),
762        }
763    }
764}
765
766fn strip_config_wrapper(xml: &str) -> &str {
767    let xml = xml.trim();
768    let Some(after) = xml.strip_prefix("<config") else {
769        return xml;
770    };
771    let first = after.chars().next();
772    if !matches!(first, Some('>' | ' ' | '\t' | '\n' | '\r' | '/')) {
773        return xml;
774    }
775    if !xml.ends_with("</config>") {
776        return xml;
777    }
778    let Some(start) = xml.find('>') else {
779        return xml;
780    };
781    let end = xml.len() - "</config>".len();
782    if start + 1 >= end {
783        return xml;
784    }
785    xml[start + 1..end].trim()
786}
787
788/// `<edit-config>` body ([RFC6241 7.2](https://www.rfc-editor.org/rfc/rfc6241.html#section-7.2)).
789#[derive(Debug, Serialize)]
790#[serde(rename_all = "kebab-case")]
791pub struct EditConfig {
792    target: Target,
793    #[serde(skip_serializing_if = "Option::is_none")]
794    default_operation: Option<DefaultOperation>,
795    #[serde(skip_serializing_if = "Option::is_none")]
796    test_option: Option<TestOption>,
797    #[serde(skip_serializing_if = "Option::is_none")]
798    error_option: Option<ErrorOption>,
799    #[serde(skip_serializing_if = "Option::is_none")]
800    config: Option<InlineConfig>,
801    #[serde(skip_serializing_if = "Option::is_none")]
802    url: Option<String>,
803}
804
805/// Source of `<copy-config>` ([RFC6241 7.3](https://www.rfc-editor.org/rfc/rfc6241.html#section-7.3)).
806#[derive(Debug)]
807pub enum CopySource {
808    /// `<candidate/>`.
809    Candidate,
810    /// `<running/>`.
811    Running,
812    /// `<startup/>`.
813    Startup,
814    /// `<url>`.
815    Url(String),
816    /// Inline `<config>`, with or without the wrapper.
817    Config(String),
818}
819
820impl From<Datastore> for CopySource {
821    fn from(datastore: Datastore) -> Self {
822        match datastore {
823            Datastore::Candidate => Self::Candidate,
824            Datastore::Running => Self::Running,
825            Datastore::Startup => Self::Startup,
826            Datastore::Url(url) => Self::Url(url),
827        }
828    }
829}
830
831#[derive(Debug, Serialize)]
832#[serde(rename_all = "lowercase")]
833enum CopySourceKind {
834    Candidate,
835    Running,
836    Startup,
837    Url(String),
838    Config(RawXml),
839}
840
841impl From<CopySource> for CopySourceKind {
842    fn from(source: CopySource) -> Self {
843        match source {
844            CopySource::Candidate => Self::Candidate,
845            CopySource::Running => Self::Running,
846            CopySource::Startup => Self::Startup,
847            CopySource::Url(url) => Self::Url(url),
848            CopySource::Config(xml) => Self::Config(RawXml::new(strip_config_wrapper(&xml))),
849        }
850    }
851}
852
853#[derive(Debug, Serialize)]
854struct CopySourceXml {
855    #[serde(rename = "$value")]
856    value: CopySourceKind,
857}
858
859/// `<copy-config>` body ([RFC6241 7.3](https://www.rfc-editor.org/rfc/rfc6241.html#section-7.3)).
860#[derive(Debug, Serialize)]
861#[serde(rename_all = "kebab-case")]
862pub struct CopyConfig {
863    target: Target,
864    source: CopySourceXml,
865}
866
867/// `<cancel-commit>` body ([RFC6241 8.4.4.1](https://www.rfc-editor.org/rfc/rfc6241.html#section-8.4.4.1)).
868#[derive(Debug, Serialize)]
869#[serde(rename_all = "kebab-case")]
870pub struct CancelCommit {
871    #[serde(rename = "persist-id", skip_serializing_if = "Option::is_none")]
872    persist_id: Option<String>,
873}
874
875/// Subtree filter for `<get>` / `<get-config>` ([RFC6241 6](https://www.rfc-editor.org/rfc/rfc6241.html#section-6)).
876#[derive(Debug, Serialize)]
877pub struct Filter {
878    #[serde(rename = "@type")]
879    filter_type: String,
880    #[serde(rename = "$value")]
881    filter: RawXml,
882}
883
884impl Filter {
885    /// Build a subtree filter from XML, which is sent to the device verbatim.
886    pub fn subtree(filter: &str) -> Filter {
887        Filter {
888            filter_type: "subtree".to_string(),
889            filter: RawXml::new(filter),
890        }
891    }
892}
893
894/// `<rpc-reply>` ([RFC6241 4.2](https://www.rfc-editor.org/rfc/rfc6241.html#section-4.2)).
895#[derive(Debug, Deserialize, Serialize)]
896#[serde(rename_all = "kebab-case", rename(serialize = "rpc-reply"))]
897pub struct RpcReply {
898    #[serde(
899        rename = "@message-id",
900        default,
901        skip_serializing_if = "Option::is_none"
902    )]
903    message_id: Option<String>,
904    #[serde(default, skip_serializing_if = "Option::is_none")]
905    rpc_error: Option<Vec<Error>>,
906    #[serde(default, skip_serializing_if = "Option::is_none")]
907    ok: Option<()>,
908}
909
910impl RpcReply {
911    /// True when the reply has `<ok>` and no error-severity `<rpc-error>`.
912    ///
913    /// Warning-severity errors plus `<ok/>` still count as success.
914    pub fn is_ok(&self) -> bool {
915        self.ok.is_some() && !self.has_errors()
916    }
917
918    /// True when the reply contains at least one error-severity `<rpc-error>`.
919    ///
920    /// Warning-only replies return `false`. Unknown severities count as errors.
921    pub fn has_errors(&self) -> bool {
922        self.errors().iter().any(|err| err.is_error_severity())
923    }
924
925    /// True when the reply contains at least one warning-severity `<rpc-error>`.
926    pub fn has_warnings(&self) -> bool {
927        self.errors()
928            .iter()
929            .any(|err| err.error_severity == ErrorSeverity::Warning)
930    }
931
932    /// Every `<rpc-error>` in the reply, including warnings.
933    pub fn errors(&self) -> &[Error] {
934        self.rpc_error.as_deref().unwrap_or(&[])
935    }
936
937    /// Warning-severity `<rpc-error>` elements.
938    pub fn warnings(&self) -> Vec<&Error> {
939        self.errors()
940            .iter()
941            .filter(|err| err.error_severity == ErrorSeverity::Warning)
942            .collect()
943    }
944
945    /// `message-id` echoed from the request, if the device sent one.
946    pub fn message_id(&self) -> Option<&str> {
947        self.message_id.as_deref()
948    }
949}
950
951impl Display for RpcReply {
952    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
953        let mut buffer = String::with_capacity(512);
954        let mut ser = Serializer::new(&mut buffer);
955        ser.indent(' ', 2);
956        self.serialize(ser).map_err(|_| fmt::Error)?;
957        f.write_str(&buffer)
958    }
959}
960
961impl std::error::Error for RpcReply {}
962
963/// One `<rpc-error>` from a reply ([RFC6241 4.3](https://www.rfc-editor.org/rfc/rfc6241.html#section-4.3)).
964#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
965#[serde(rename = "rpc-error", rename_all = "kebab-case")]
966#[non_exhaustive]
967pub struct Error {
968    /// `<error-severity>`.
969    pub error_severity: ErrorSeverity,
970    /// `<error-type>`, the protocol layer that failed.
971    pub error_type: ErrorType,
972    /// `<error-tag>`, the machine-readable reason.
973    pub error_tag: ErrorTag,
974    /// `<error-app-tag>`, a data-model-specific reason.
975    #[serde(default, skip_serializing_if = "Option::is_none")]
976    pub error_app_tag: Option<String>,
977    /// `<error-path>`, the offending node.
978    #[serde(default, skip_serializing_if = "Option::is_none")]
979    pub error_path: Option<String>,
980    /// `<error-message>`, human-readable text.
981    #[serde(default, skip_serializing_if = "Option::is_none")]
982    pub error_message: Option<String>,
983    /// `<error-info>`, protocol- or data-model-specific detail.
984    #[serde(default, skip_serializing_if = "Option::is_none")]
985    pub error_info: Option<ErrorInfo>,
986}
987
988impl Error {
989    /// True when `<error-severity>` is not `warning`.
990    ///
991    /// Unknown values fail closed and count as errors.
992    pub fn is_error_severity(&self) -> bool {
993        self.error_severity != ErrorSeverity::Warning
994    }
995}
996
997/// Builds an enum that round-trips through XML text and keeps unknown values.
998///
999/// Vendors ship tags outside RFC 6241, and losing the whole reply to an
1000/// unrecognised `<error-tag>` would hide the error the device is reporting.
1001macro_rules! open_enum {
1002    ($(#[$meta:meta])* $name:ident { $($(#[$vmeta:meta])* $variant:ident => $text:literal,)* }) => {
1003        $(#[$meta])*
1004        #[derive(Debug, Clone, PartialEq, Eq)]
1005        #[non_exhaustive]
1006        pub enum $name {
1007            $($(#[$vmeta])* $variant,)*
1008            /// A value this crate does not know.
1009            Other(String),
1010        }
1011
1012        impl $name {
1013            /// The value as it appears on the wire.
1014            pub fn as_str(&self) -> &str {
1015                match self {
1016                    $(Self::$variant => $text,)*
1017                    Self::Other(value) => value,
1018                }
1019            }
1020        }
1021
1022        impl From<&str> for $name {
1023            fn from(value: &str) -> Self {
1024                match value.trim() {
1025                    $($text => Self::$variant,)*
1026                    other => Self::Other(other.to_string()),
1027                }
1028            }
1029        }
1030
1031        impl Display for $name {
1032            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1033                f.write_str(self.as_str())
1034            }
1035        }
1036
1037        impl Serialize for $name {
1038            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1039                serializer.serialize_str(self.as_str())
1040            }
1041        }
1042
1043        impl<'de> Deserialize<'de> for $name {
1044            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1045                Ok(Self::from(String::deserialize(deserializer)?.as_str()))
1046            }
1047        }
1048    };
1049}
1050
1051open_enum!(
1052    /// `<error-type>` ([RFC6241 4.3](https://www.rfc-editor.org/rfc/rfc6241.html#section-4.3)).
1053    ErrorType {
1054        /// Secure transport layer.
1055        Transport => "transport",
1056        /// RPC layer.
1057        Rpc => "rpc",
1058        /// Protocol operation layer.
1059        Protocol => "protocol",
1060        /// Content layer.
1061        Application => "application",
1062    }
1063);
1064
1065open_enum!(
1066    /// `<error-severity>` ([RFC6241 4.3](https://www.rfc-editor.org/rfc/rfc6241.html#section-4.3)).
1067    ErrorSeverity {
1068        /// The operation failed.
1069        Error => "error",
1070        /// Advisory only.
1071        Warning => "warning",
1072    }
1073);
1074
1075open_enum!(
1076    /// `<error-tag>` ([RFC6241 appendix A](https://www.rfc-editor.org/rfc/rfc6241.html#appendix-A)).
1077    ErrorTag {
1078        /// Resource is in use.
1079        InUse => "in-use",
1080        /// Value is out of range or otherwise invalid.
1081        InvalidValue => "invalid-value",
1082        /// Request or reply is too large.
1083        TooBig => "too-big",
1084        /// A required attribute is missing.
1085        MissingAttribute => "missing-attribute",
1086        /// An attribute has an unexpected value.
1087        BadAttribute => "bad-attribute",
1088        /// An attribute is not recognised.
1089        UnknownAttribute => "unknown-attribute",
1090        /// A required element is missing.
1091        MissingElement => "missing-element",
1092        /// An element has an unexpected value.
1093        BadElement => "bad-element",
1094        /// An element is not recognised.
1095        UnknownElement => "unknown-element",
1096        /// A namespace is not recognised.
1097        UnknownNamespace => "unknown-namespace",
1098        /// Access to the resource was denied.
1099        AccessDenied => "access-denied",
1100        /// The lock is already held.
1101        LockDenied => "lock-denied",
1102        /// The device is out of resources.
1103        ResourceDenied => "resource-denied",
1104        /// Rollback was requested but failed.
1105        RollbackFailed => "rollback-failed",
1106        /// The data already exists.
1107        DataExists => "data-exists",
1108        /// The data does not exist.
1109        DataMissing => "data-missing",
1110        /// The operation is not supported.
1111        OperationNotSupported => "operation-not-supported",
1112        /// The operation failed for an unspecified reason.
1113        OperationFailed => "operation-failed",
1114        /// The operation was only partly applied.
1115        PartialOperation => "partial-operation",
1116        /// The message is not well-formed.
1117        MalformedMessage => "malformed-message",
1118    }
1119);
1120
1121/// `<error-info>` detail ([RFC6241 4.3](https://www.rfc-editor.org/rfc/rfc6241.html#section-4.3)).
1122#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize, Serialize)]
1123#[serde(rename_all = "kebab-case")]
1124#[non_exhaustive]
1125pub struct ErrorInfo {
1126    /// Element that caused the error.
1127    #[serde(default, skip_serializing_if = "Option::is_none")]
1128    pub bad_element: Option<String>,
1129    /// Attribute that caused the error.
1130    #[serde(default, skip_serializing_if = "Option::is_none")]
1131    pub bad_attribute: Option<String>,
1132    /// Namespace that caused the error.
1133    #[serde(default, skip_serializing_if = "Option::is_none")]
1134    pub bad_namespace: Option<String>,
1135    /// Element that was applied successfully.
1136    #[serde(default, skip_serializing_if = "Option::is_none")]
1137    pub ok_element: Option<String>,
1138    /// Element that failed.
1139    #[serde(default, skip_serializing_if = "Option::is_none")]
1140    pub err_element: Option<String>,
1141    /// Element that was not attempted.
1142    #[serde(default, skip_serializing_if = "Option::is_none")]
1143    pub noop_element: Option<String>,
1144    /// Session holding the lock, for `lock-denied`.
1145    #[serde(default, skip_serializing_if = "Option::is_none")]
1146    pub session_id: Option<u64>,
1147}
1148
1149/// Parse an RFC 3339 timestamp for `<create-subscription>` replay.
1150pub(crate) fn parse_date_time(value: &str) -> error::NetconfClientResult<OffsetDateTime> {
1151    OffsetDateTime::parse(value, &Rfc3339).map_err(|err| {
1152        error::NetconfClientError::new(format!("invalid date-time '{value}': {err}"))
1153    })
1154}
1155
1156fn format_date_time(value: OffsetDateTime) -> error::NetconfClientResult<String> {
1157    value
1158        .format(&Rfc3339)
1159        .map_err(|err| error::NetconfClientError::new(format!("failed to format date-time: {err}")))
1160}
1161
1162/// RFC 3339 start/stop for a replay window of `duration`.
1163///
1164/// If `start_time` is omitted, start is now (UTC) and stop is now + `duration`.
1165/// Otherwise stop is `start_time` + `duration`.
1166pub fn replay_window(
1167    start_time: Option<&str>,
1168    duration: core::time::Duration,
1169) -> error::NetconfClientResult<(String, String)> {
1170    if duration.is_zero() {
1171        return Err(error::NetconfClientError::new(
1172            "duration must be greater than zero",
1173        ));
1174    }
1175    let start = match start_time {
1176        Some(value) => parse_date_time(value)?,
1177        None => OffsetDateTime::now_utc(),
1178    };
1179    let add = time::Duration::try_from(duration)
1180        .map_err(|err| error::NetconfClientError::new(format!("duration too large: {err}")))?;
1181    let stop = start
1182        .checked_add(add)
1183        .ok_or_else(|| error::NetconfClientError::new("duration overflows stopTime"))?;
1184    Ok((format_date_time(start)?, format_date_time(stop)?))
1185}
1186
1187/// `<create-subscription>` body ([RFC5277 2.1.1](https://www.rfc-editor.org/rfc/rfc5277.html#section-2.1.1)).
1188#[derive(Debug, Serialize)]
1189pub struct CreateSubscription {
1190    #[serde(rename = "@xmlns")]
1191    xmlns: String,
1192    #[serde(skip_serializing_if = "Option::is_none")]
1193    stream: Option<String>,
1194    #[serde(skip_serializing_if = "Option::is_none")]
1195    filter: Option<Filter>,
1196    #[serde(
1197        rename = "startTime",
1198        skip_serializing_if = "Option::is_none",
1199        with = "time::serde::rfc3339::option"
1200    )]
1201    start_time: Option<OffsetDateTime>,
1202    #[serde(
1203        rename = "stopTime",
1204        skip_serializing_if = "Option::is_none",
1205        with = "time::serde::rfc3339::option"
1206    )]
1207    stop_time: Option<OffsetDateTime>,
1208}
1209
1210#[cfg(test)]
1211mod tests {
1212    use super::*;
1213    use pretty_assertions::assert_eq;
1214    use quick_xml::de::from_str;
1215
1216    fn rpc(operation: RpcOperation) -> Rpc {
1217        Rpc {
1218            xmlns: NETCONF_URN.to_string(),
1219            message_id: "c1be0e7f-3cbc-413f-8aa8-18ed663221d4".to_string(),
1220            operation,
1221        }
1222    }
1223
1224    #[test]
1225    fn operation_name_is_the_rfc_local_name() {
1226        assert_eq!(RpcOperation::CloseSession.name(), "close-session");
1227        assert_eq!(RpcOperation::new_get(None, None).name(), "get");
1228        assert_eq!(
1229            RpcOperation::new_get_config(Datastore::Running, None, None).name(),
1230            "get-config"
1231        );
1232        assert_eq!(
1233            rpc(RpcOperation::new_discard_changes()).operation_name(),
1234            "discard-changes"
1235        );
1236    }
1237
1238    #[test]
1239    fn test_deserialize_rpc_reply() {
1240        let reply = r#"
1241<rpc-reply message-id="67d83d6b-1f0b-47fb-8fdf-2cfc3fb2a371" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1242  <rpc-error>
1243    <error-type>protocol</error-type>
1244    <error-tag>bad-element</error-tag>
1245    <error-severity>error</error-severity>
1246    <error-message>Element is not valid in the specified context.</error-message>
1247    <error-info>
1248      <bad-element>startu</bad-element>
1249    </error-info>
1250  </rpc-error>
1251  <rpc-error>
1252    <error-type>application</error-type>
1253    <error-tag>bad-element</error-tag>
1254    <error-severity>error</error-severity>
1255    <error-message>Element is not valid in the specified context.</error-message>
1256    <error-info>
1257      <bad-element>startu</bad-element>
1258    </error-info>
1259  </rpc-error>
1260</rpc-reply>
1261"#;
1262        let reply: RpcReply = from_str(reply).unwrap();
1263        assert_eq!(reply.errors().len(), 2);
1264        assert_eq!(reply.errors()[0].error_type, ErrorType::Protocol);
1265        assert_eq!(reply.errors()[1].error_type, ErrorType::Application);
1266
1267        let reply = r#"
1268<rpc-reply message-id="1" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1269  <rpc-error>
1270    <error-type>application</error-type>
1271    <error-tag>unknown-element</error-tag>
1272    <error-severity>error</error-severity>
1273    <error-message>Unknown element</error-message>
1274    <error-info>
1275      <bad-element>startup</bad-element>
1276    </error-info>
1277  </rpc-error>
1278</rpc-reply>
1279"#;
1280        let reply: RpcReply = from_str(reply).unwrap();
1281        assert!(reply.has_errors());
1282        assert_eq!(reply.errors()[0].error_tag, ErrorTag::UnknownElement);
1283        assert_eq!(
1284            reply.errors()[0].error_info.as_ref().unwrap().bad_element,
1285            Some("startup".to_string())
1286        );
1287
1288        let reply = r#"
1289<rpc-reply message-id="c60e637d-0f79-41ea-ad09-a5ee02f08434">
1290  <data>
1291    <configure xmlns="urn:nokia.com:sros:ns:yang:sr:conf" xmlns:nokia-attr="urn:nokia.com:sros:ns:yang:sr:attributes">
1292      <port>
1293        <port-id>1/1/2</port-id>
1294      </port>
1295      <system>
1296        <time>
1297          <ntp>
1298            <admin-state>enable</admin-state>
1299          </ntp>
1300        </time>
1301      </system>
1302    </configure>
1303  </data>
1304</rpc-reply>
1305        "#;
1306        let reply: RpcReply = from_str(reply).unwrap();
1307        assert!(!reply.has_errors());
1308        assert!(!reply.is_ok());
1309
1310        let reply = r#"
1311<?xml version="1.0" encoding="UTF-8"?>
1312<rpc-reply message-id="938f1c28-e6e3-4641-a4d0-383d9ef1a280" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1313  <ok/>
1314</rpc-reply>
1315"#;
1316        let reply: RpcReply = from_str(reply).unwrap();
1317        assert!(reply.is_ok());
1318    }
1319
1320    #[test]
1321    fn warning_plus_ok_is_success_not_an_error() {
1322        let xml = r#"<rpc-reply message-id="1" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1323  <rpc-error>
1324    <error-type>application</error-type>
1325    <error-tag>operation-failed</error-tag>
1326    <error-severity>warning</error-severity>
1327    <error-message>statement not found</error-message>
1328  </rpc-error>
1329  <ok/>
1330</rpc-reply>"#;
1331        let reply: RpcReply = from_xml(xml).unwrap();
1332        assert!(reply.is_ok());
1333        assert!(!reply.has_errors());
1334        assert!(reply.has_warnings());
1335        assert_eq!(reply.warnings().len(), 1);
1336        assert_eq!(reply.warnings()[0].error_tag, ErrorTag::OperationFailed);
1337        assert_eq!(reply.errors().len(), 1);
1338    }
1339
1340    #[test]
1341    fn warning_and_error_is_still_an_error() {
1342        let xml = r#"<rpc-reply message-id="1">
1343  <rpc-error>
1344    <error-type>application</error-type>
1345    <error-tag>operation-failed</error-tag>
1346    <error-severity>warning</error-severity>
1347  </rpc-error>
1348  <rpc-error>
1349    <error-type>protocol</error-type>
1350    <error-tag>lock-denied</error-tag>
1351    <error-severity>error</error-severity>
1352  </rpc-error>
1353</rpc-reply>"#;
1354        let reply: RpcReply = from_xml(xml).unwrap();
1355        assert!(!reply.is_ok());
1356        assert!(reply.has_errors());
1357        assert!(reply.has_warnings());
1358        assert_eq!(reply.warnings().len(), 1);
1359    }
1360
1361    #[test]
1362    fn reply_without_message_id_parses() {
1363        let reply =
1364            r#"<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><ok/></rpc-reply>"#;
1365        let reply: RpcReply = from_xml(reply).unwrap();
1366        assert!(reply.is_ok());
1367        assert_eq!(reply.message_id(), None);
1368    }
1369
1370    #[test]
1371    fn namespace_prefixed_reply_parses() {
1372        let reply = r#"<nc:rpc-reply xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="4">
1373  <nc:rpc-error>
1374    <nc:error-type>protocol</nc:error-type>
1375    <nc:error-tag>access-denied</nc:error-tag>
1376    <nc:error-severity>error</nc:error-severity>
1377  </nc:rpc-error>
1378</nc:rpc-reply>"#;
1379        let reply: RpcReply = from_xml(reply).unwrap();
1380        assert!(reply.has_errors());
1381        assert_eq!(reply.errors()[0].error_tag, ErrorTag::AccessDenied);
1382    }
1383
1384    #[test]
1385    fn vendor_error_tag_is_preserved() {
1386        let reply = r#"<rpc-reply message-id="1">
1387  <rpc-error>
1388    <error-type>application</error-type>
1389    <error-tag>vendor-specific-failure</error-tag>
1390    <error-severity>error</error-severity>
1391  </rpc-error>
1392</rpc-reply>"#;
1393        let reply: RpcReply = from_xml(reply).unwrap();
1394        assert_eq!(
1395            reply.errors()[0].error_tag,
1396            ErrorTag::Other("vendor-specific-failure".to_string())
1397        );
1398        assert_eq!(
1399            reply.errors()[0].error_tag.as_str(),
1400            "vendor-specific-failure"
1401        );
1402    }
1403
1404    #[test]
1405    fn namespace_prefixed_hello_parses() {
1406        let hello = r#"<nc:hello xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0">
1407  <nc:capabilities>
1408    <nc:capability>urn:ietf:params:netconf:base:1.0</nc:capability>
1409    <nc:capability>urn:ietf:params:netconf:base:1.1</nc:capability>
1410  </nc:capabilities>
1411  <nc:session-id>42</nc:session-id>
1412</nc:hello>"#;
1413        let hello: Hello = from_xml(hello).unwrap();
1414        assert_eq!(hello.session_id(), Some(42));
1415        assert!(hello.has_capability(crate::NETCONF_BASE_11_CAP));
1416    }
1417
1418    #[test]
1419    fn hello_without_xmlns_attribute_parses() {
1420        let hello = r#"<hello><capabilities><capability>urn:ietf:params:netconf:base:1.1</capability></capabilities></hello>"#;
1421        let hello: Hello = from_xml(hello).unwrap();
1422        assert!(hello.has_capability(crate::NETCONF_BASE_11_CAP));
1423        assert_eq!(hello.session_id(), None);
1424    }
1425
1426    #[test]
1427    fn hello_capability_ignores_query_parameters() {
1428        let hello = r#"<hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><capabilities>
1429  <capability>urn:ietf:params:netconf:capability:url:1.0?scheme=http,ftp,file</capability>
1430</capabilities></hello>"#;
1431        let hello: Hello = from_xml(hello).unwrap();
1432        assert!(hello.has_capability(crate::URL_CAP));
1433    }
1434
1435    #[test]
1436    fn datastore_from_str_keeps_url_case() {
1437        assert!(matches!(
1438            Datastore::from_str("RUNNING").unwrap(),
1439            Datastore::Running
1440        ));
1441        let Datastore::Url(url) =
1442            Datastore::from_str("ftp://Server.EXAMPLE.com/Router.CFG").unwrap()
1443        else {
1444            panic!("expected a url datastore");
1445        };
1446        assert_eq!(url, "ftp://Server.EXAMPLE.com/Router.CFG");
1447        assert!(Datastore::from_str("httpfoo").is_err());
1448        assert!(Datastore::from_str("http://").is_err());
1449    }
1450
1451    #[test]
1452    fn url_query_parameters_stay_escaped() {
1453        let xml = rpc(RpcOperation::new_edit_config(
1454            Datastore::Running,
1455            EditContent::Url("ftp://host/router.cfg?a=1&b=2".to_string()),
1456            None,
1457            None,
1458            None,
1459        ))
1460        .to_string();
1461        assert!(
1462            xml.contains("<url>ftp://host/router.cfg?a=1&amp;b=2</url>"),
1463            "ampersand must stay escaped:\n{xml}"
1464        );
1465
1466        let xml = rpc(RpcOperation::new_copy_config(
1467            CopySource::Url("ftp://host/router.cfg?a=1&b=2".to_string()),
1468            Datastore::Running,
1469        ))
1470        .to_string();
1471        assert!(
1472            xml.contains("<url>ftp://host/router.cfg?a=1&amp;b=2</url>"),
1473            "ampersand must stay escaped:\n{xml}"
1474        );
1475    }
1476
1477    #[test]
1478    fn config_payload_reaches_the_device_verbatim() {
1479        let config = r#"<top xmlns="http://example.com/1.2"><name>a &amp; b</name><cdata><![CDATA[<x/>]]></cdata></top>"#;
1480        let xml = rpc(RpcOperation::new_edit_config(
1481            Datastore::Candidate,
1482            EditContent::Config(config.to_string()),
1483            None,
1484            None,
1485            None,
1486        ))
1487        .to_string();
1488        assert!(xml.contains(config), "payload was rewritten:\n{xml}");
1489    }
1490
1491    #[test]
1492    fn filter_payload_reaches_the_device_verbatim() {
1493        let filter = r#"<top><name>a &amp; b</name></top>"#;
1494        let xml = rpc(RpcOperation::new_get(Some(Filter::subtree(filter)), None)).to_string();
1495        assert!(xml.contains(filter), "filter was rewritten:\n{xml}");
1496    }
1497
1498    #[test]
1499    fn filter_with_trailing_backslash_is_not_a_panic() {
1500        let filter = Filter::subtree(r"<top>C:\temp\</top>");
1501        let xml = rpc(RpcOperation::new_get(Some(filter), None)).to_string();
1502        assert!(xml.contains(r"<top>C:\temp\</top>"), "{xml}");
1503    }
1504
1505    #[test]
1506    fn test_serialize_hello() {
1507        let expected = concat!(
1508            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n",
1509            "<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">",
1510            "<capabilities>",
1511            "<capability>urn:ietf:params:netconf:base:1.0</capability>",
1512            "<capability>urn:ietf:params:netconf:base:1.1</capability>",
1513            "</capabilities></hello>\n",
1514        );
1515        assert_eq!(Hello::new().to_string(), expected);
1516    }
1517
1518    #[test]
1519    fn test_serialize_close_session() {
1520        let expected = r#"
1521<rpc message-id="c1be0e7f-3cbc-413f-8aa8-18ed663221d4" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1522  <close-session/>
1523</rpc>
1524"#;
1525        assert_eq!(rpc(RpcOperation::CloseSession).to_string(), expected.trim());
1526    }
1527
1528    #[test]
1529    fn test_serialize_kill_session() {
1530        let expected = r#"
1531<rpc message-id="c1be0e7f-3cbc-413f-8aa8-18ed663221d4" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1532  <kill-session>
1533    <session-id>69</session-id>
1534  </kill-session>
1535</rpc>
1536"#;
1537        assert_eq!(
1538            rpc(RpcOperation::KillSession { session_id: 69 }).to_string(),
1539            expected.trim()
1540        );
1541    }
1542
1543    #[test]
1544    fn test_serialize_get_config() {
1545        let expected = r#"
1546<rpc message-id="c1be0e7f-3cbc-413f-8aa8-18ed663221d4" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1547  <get-config>
1548    <source>
1549      <running/>
1550    </source>
1551    <with-defaults xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-with-defaults">report-all</with-defaults>
1552  </get-config>
1553</rpc>
1554"#;
1555        assert_eq!(
1556            rpc(RpcOperation::new_get_config(
1557                Datastore::Running,
1558                None,
1559                Some(WithDefaultsValue::ReportAll),
1560            ))
1561            .to_string(),
1562            expected.trim()
1563        );
1564    }
1565
1566    #[test]
1567    fn test_serialize_get() {
1568        let expected = r#"
1569<rpc message-id="c1be0e7f-3cbc-413f-8aa8-18ed663221d4" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1570  <get>
1571    <filter type="subtree"><top xmlns="https://example.com/schema/1.2/config"><users><user><name>fred</name></user></users></top></filter>
1572  </get>
1573</rpc>
1574"#;
1575        let filter = r#"<top xmlns="https://example.com/schema/1.2/config"><users><user><name>fred</name></user></users></top>"#;
1576        assert_eq!(
1577            rpc(RpcOperation::new_get(Some(Filter::subtree(filter)), None)).to_string(),
1578            expected.trim()
1579        );
1580    }
1581
1582    #[test]
1583    fn test_serialize_commit() {
1584        let expected = r#"
1585<rpc message-id="c1be0e7f-3cbc-413f-8aa8-18ed663221d4" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1586  <commit/>
1587</rpc>
1588"#;
1589        assert_eq!(
1590            rpc(RpcOperation::new_commit(None, None, None, None)).to_string(),
1591            expected.trim()
1592        );
1593
1594        let expected = r#"
1595<rpc message-id="c1be0e7f-3cbc-413f-8aa8-18ed663221d4" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1596  <commit>
1597    <confirmed/>
1598    <confirm-timeout>120</confirm-timeout>
1599    <persist>persis,qqSADD</persist>
1600  </commit>
1601</rpc>
1602"#;
1603        assert_eq!(
1604            rpc(RpcOperation::new_commit(
1605                Some(()),
1606                Some(120),
1607                Some("persis,qqSADD".to_string()),
1608                None,
1609            ))
1610            .to_string(),
1611            expected.trim()
1612        );
1613
1614        let expected = r#"
1615<rpc message-id="c1be0e7f-3cbc-413f-8aa8-18ed663221d4" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1616  <commit>
1617    <persist-id>myid</persist-id>
1618  </commit>
1619</rpc>
1620"#;
1621        assert_eq!(
1622            rpc(RpcOperation::new_commit(
1623                None,
1624                None,
1625                None,
1626                Some("myid".to_string())
1627            ))
1628            .to_string(),
1629            expected.trim()
1630        );
1631    }
1632
1633    #[test]
1634    fn test_serialize_validate() {
1635        let expected = r#"
1636<rpc message-id="c1be0e7f-3cbc-413f-8aa8-18ed663221d4" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1637  <validate>
1638    <source>
1639      <candidate/>
1640    </source>
1641  </validate>
1642</rpc>
1643"#;
1644        assert_eq!(
1645            rpc(RpcOperation::Validate {
1646                source: Source {
1647                    datastore: Datastore::Candidate,
1648                },
1649            })
1650            .to_string(),
1651            expected.trim()
1652        );
1653    }
1654
1655    #[test]
1656    fn test_serialize_create_subscription() {
1657        let expected = r#"
1658<rpc message-id="c1be0e7f-3cbc-413f-8aa8-18ed663221d4" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1659  <create-subscription xmlns="urn:ietf:params:xml:ns:netconf:notification:1.0">
1660    <stream>NETCONF</stream>
1661    <startTime>2026-01-01T00:00:00Z</startTime>
1662    <stopTime>2026-01-01T00:01:00Z</stopTime>
1663  </create-subscription>
1664</rpc>
1665"#;
1666        let subscription = rpc(RpcOperation::new_create_subscription(
1667            Some("NETCONF"),
1668            None,
1669            Some("2026-01-01T00:00:00Z"),
1670            Some("2026-01-01T00:01:00Z"),
1671        )
1672        .unwrap());
1673        assert_eq!(subscription.to_string(), expected.trim());
1674    }
1675
1676    #[test]
1677    fn create_subscription_start_only_omits_stop() {
1678        let expected = r#"
1679<rpc message-id="c1be0e7f-3cbc-413f-8aa8-18ed663221d4" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1680  <create-subscription xmlns="urn:ietf:params:xml:ns:netconf:notification:1.0">
1681    <startTime>2026-01-01T00:00:00Z</startTime>
1682  </create-subscription>
1683</rpc>
1684"#;
1685        let subscription = rpc(RpcOperation::new_create_subscription(
1686            None,
1687            None,
1688            Some("2026-01-01T00:00:00Z"),
1689            None,
1690        )
1691        .unwrap());
1692        assert_eq!(subscription.to_string(), expected.trim());
1693    }
1694
1695    #[test]
1696    fn create_subscription_stop_requires_start() {
1697        let err =
1698            RpcOperation::new_create_subscription(None, None, None, Some("2026-01-01T00:01:00Z"))
1699                .unwrap_err();
1700        assert!(
1701            err.to_string().contains("stopTime requires startTime"),
1702            "{err}"
1703        );
1704    }
1705
1706    #[test]
1707    fn create_subscription_stop_before_start_is_error() {
1708        let err = RpcOperation::new_create_subscription(
1709            None,
1710            None,
1711            Some("2026-01-01T00:01:00Z"),
1712            Some("2026-01-01T00:00:00Z"),
1713        )
1714        .unwrap_err();
1715        assert!(err.to_string().contains("earlier than startTime"), "{err}");
1716    }
1717
1718    #[test]
1719    fn parse_date_time_rejects_garbage() {
1720        let err = parse_date_time("yesterday").unwrap_err();
1721        assert!(err.to_string().contains("invalid date-time"), "{err}");
1722    }
1723
1724    #[test]
1725    fn create_subscription_rejects_garbage_start() {
1726        let err =
1727            RpcOperation::new_create_subscription(None, None, Some("yesterday"), None).unwrap_err();
1728        assert!(err.to_string().contains("invalid date-time"), "{err}");
1729    }
1730
1731    #[test]
1732    fn from_xml_garbage_is_serializing_failure() {
1733        let err = from_xml::<RpcReply>("<<<").unwrap_err();
1734        assert!(
1735            matches!(err, error::NetconfClientError::SerializingFailure(_)),
1736            "{err:?}"
1737        );
1738    }
1739
1740    #[test]
1741    fn replay_window_from_start_and_duration() {
1742        let (start, stop) = replay_window(
1743            Some("2026-01-01T00:00:00Z"),
1744            core::time::Duration::from_secs(60),
1745        )
1746        .unwrap();
1747        assert_eq!(start, "2026-01-01T00:00:00Z");
1748        assert_eq!(stop, "2026-01-01T00:01:00Z");
1749    }
1750
1751    #[test]
1752    fn replay_window_without_start_uses_now() {
1753        let (start, stop) = replay_window(None, core::time::Duration::from_secs(60)).unwrap();
1754        let start = parse_date_time(&start).unwrap();
1755        let stop = parse_date_time(&stop).unwrap();
1756        assert_eq!(stop - start, time::Duration::seconds(60));
1757    }
1758
1759    #[test]
1760    fn test_serialize_edit_config() {
1761        let expected = r#"
1762<rpc message-id="c1be0e7f-3cbc-413f-8aa8-18ed663221d4" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1763  <edit-config>
1764    <target>
1765      <candidate/>
1766    </target>
1767    <default-operation>replace</default-operation>
1768    <test-option>test-only</test-option>
1769    <error-option>continue-on-error</error-option>
1770    <config><top xmlns="http://example.com/schema/1.2/config"><interface><name>Ethernet0/0</name><mtu>1500</mtu></interface></top></config>
1771  </edit-config>
1772</rpc>
1773"#;
1774        let config = r#"<top xmlns="http://example.com/schema/1.2/config"><interface><name>Ethernet0/0</name><mtu>1500</mtu></interface></top>"#;
1775        assert_eq!(
1776            rpc(RpcOperation::new_edit_config(
1777                Datastore::Candidate,
1778                EditContent::Config(config.to_string()),
1779                Some(DefaultOperation::Replace),
1780                Some(TestOption::TestOnly),
1781                Some(ErrorOption::ContinueOnError),
1782            ))
1783            .to_string(),
1784            expected.trim()
1785        );
1786    }
1787
1788    #[test]
1789    fn test_serialize_edit_config_url_and_wrapped_config() {
1790        let expected = r#"
1791<rpc message-id="c1be0e7f-3cbc-413f-8aa8-18ed663221d4" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1792  <edit-config>
1793    <target>
1794      <running/>
1795    </target>
1796    <url>ftp://myserver.example.com/router.cfg</url>
1797  </edit-config>
1798</rpc>
1799"#;
1800        assert_eq!(
1801            rpc(RpcOperation::new_edit_config(
1802                Datastore::Running,
1803                EditContent::Url("ftp://myserver.example.com/router.cfg".to_string()),
1804                None,
1805                None,
1806                None,
1807            ))
1808            .to_string(),
1809            expected.trim()
1810        );
1811
1812        let expected = r#"
1813<rpc message-id="c1be0e7f-3cbc-413f-8aa8-18ed663221d4" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1814  <edit-config>
1815    <target>
1816      <candidate/>
1817    </target>
1818    <config><system><host-name>darkstar</host-name></system></config>
1819  </edit-config>
1820</rpc>
1821"#;
1822        assert_eq!(
1823            rpc(RpcOperation::new_edit_config(
1824                Datastore::Candidate,
1825                EditContent::Config(
1826                    "<config>\n  <system><host-name>darkstar</host-name></system>\n</config>"
1827                        .to_string(),
1828                ),
1829                None,
1830                None,
1831                None,
1832            ))
1833            .to_string(),
1834            expected.trim()
1835        );
1836    }
1837
1838    #[test]
1839    fn test_serialize_copy_config() {
1840        let expected = r#"
1841<rpc message-id="c1be0e7f-3cbc-413f-8aa8-18ed663221d4" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1842  <copy-config>
1843    <target>
1844      <startup/>
1845    </target>
1846    <source>
1847      <running/>
1848    </source>
1849  </copy-config>
1850</rpc>
1851"#;
1852        assert_eq!(
1853            rpc(RpcOperation::new_copy_config(
1854                Datastore::Running.into(),
1855                Datastore::Startup
1856            ))
1857            .to_string(),
1858            expected.trim()
1859        );
1860    }
1861
1862    #[test]
1863    fn test_serialize_copy_config_url_and_inline() {
1864        let expected = r#"
1865<rpc message-id="c1be0e7f-3cbc-413f-8aa8-18ed663221d4" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1866  <copy-config>
1867    <target>
1868      <url>ftp://myserver.example.com/router.cfg</url>
1869    </target>
1870    <source>
1871      <running/>
1872    </source>
1873  </copy-config>
1874</rpc>
1875"#;
1876        assert_eq!(
1877            rpc(RpcOperation::new_copy_config(
1878                Datastore::Running.into(),
1879                Datastore::Url("ftp://myserver.example.com/router.cfg".to_string()),
1880            ))
1881            .to_string(),
1882            expected.trim()
1883        );
1884
1885        let expected = r#"
1886<rpc message-id="c1be0e7f-3cbc-413f-8aa8-18ed663221d4" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1887  <copy-config>
1888    <target>
1889      <candidate/>
1890    </target>
1891    <source>
1892      <config><top xmlns="http://example.com/schema/1.2/config"/></config>
1893    </source>
1894  </copy-config>
1895</rpc>
1896"#;
1897        assert_eq!(
1898            rpc(RpcOperation::new_copy_config(
1899                CopySource::Config(
1900                    r#"<top xmlns="http://example.com/schema/1.2/config"/>"#.to_string(),
1901                ),
1902                Datastore::Candidate,
1903            ))
1904            .to_string(),
1905            expected.trim()
1906        );
1907    }
1908
1909    #[test]
1910    fn test_serialize_delete_config() {
1911        let expected = r#"
1912<rpc message-id="c1be0e7f-3cbc-413f-8aa8-18ed663221d4" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1913  <delete-config>
1914    <target>
1915      <startup/>
1916    </target>
1917  </delete-config>
1918</rpc>
1919"#;
1920        assert_eq!(
1921            rpc(RpcOperation::new_delete_config(Datastore::Startup)).to_string(),
1922            expected.trim()
1923        );
1924    }
1925
1926    #[test]
1927    fn test_serialize_lock_unlock() {
1928        let expected = r#"
1929<rpc message-id="c1be0e7f-3cbc-413f-8aa8-18ed663221d4" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1930  <lock>
1931    <target>
1932      <candidate/>
1933    </target>
1934  </lock>
1935</rpc>
1936"#;
1937        assert_eq!(
1938            rpc(RpcOperation::new_lock(Datastore::Candidate)).to_string(),
1939            expected.trim()
1940        );
1941
1942        let expected = r#"
1943<rpc message-id="c1be0e7f-3cbc-413f-8aa8-18ed663221d4" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1944  <unlock>
1945    <target>
1946      <candidate/>
1947    </target>
1948  </unlock>
1949</rpc>
1950"#;
1951        assert_eq!(
1952            rpc(RpcOperation::new_unlock(Datastore::Candidate)).to_string(),
1953            expected.trim()
1954        );
1955    }
1956
1957    #[test]
1958    fn test_serialize_discard_changes() {
1959        let expected = r#"
1960<rpc message-id="c1be0e7f-3cbc-413f-8aa8-18ed663221d4" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1961  <discard-changes/>
1962</rpc>
1963"#;
1964        assert_eq!(
1965            rpc(RpcOperation::new_discard_changes()).to_string(),
1966            expected.trim()
1967        );
1968    }
1969
1970    #[test]
1971    fn test_serialize_cancel_commit() {
1972        let expected = r#"
1973<rpc message-id="c1be0e7f-3cbc-413f-8aa8-18ed663221d4" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1974  <cancel-commit/>
1975</rpc>
1976"#;
1977        assert_eq!(
1978            rpc(RpcOperation::new_cancel_commit(None)).to_string(),
1979            expected.trim()
1980        );
1981
1982        let expected = r#"
1983<rpc message-id="c1be0e7f-3cbc-413f-8aa8-18ed663221d4" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
1984  <cancel-commit>
1985    <persist-id>myid</persist-id>
1986  </cancel-commit>
1987</rpc>
1988"#;
1989        assert_eq!(
1990            rpc(RpcOperation::new_cancel_commit(Some("myid".to_string()))).to_string(),
1991            expected.trim()
1992        );
1993    }
1994}