zenoh_flow_commons/
deserialize.rs

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
//
// Copyright (c) 2021 - 2024 ZettaScale Technology
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
//
// Contributors:
//   ZettaScale Zenoh Team, <zenoh@zettascale.tech>
//

//! This module exposes the functions [deserialize_size] and [deserialize_time] that are used
//! throughout Zenoh-Flow to "parse" values used to express time or size.
//!
//! The external crates [bytesize] and [humantime] are leveraged for these purposes.

use serde::Deserializer;
use std::{str::FromStr, sync::Arc};
use zenoh_keyexpr::OwnedKeyExpr;

/// Deserialise, from a String, an `Arc<str>` that is guaranteed to be a valid Zenoh-Flow [NodeId](crate::NodeId) or
/// [PortId](crate::PortId).
///
/// # Errors
///
/// The deserialisation will fail if:
/// - the String is empty,
/// - the String contains any of the symbols: * # $ ? >
/// - the String is not a valid Zenoh key expression in its canonical form (see [autocanonize]).
///
/// [autocanonize]: zenoh_keyexpr::OwnedKeyExpr::autocanonize
pub fn deserialize_id<'de, D>(deserializer: D) -> std::result::Result<Arc<str>, D::Error>
where
    D: Deserializer<'de>,
{
    let id: String = serde::de::Deserialize::deserialize(deserializer)?;
    if id.contains(['*', '#', '$', '?', '>']) {
        return Err(serde::de::Error::custom(format!(
            r#"
Identifiers (for nodes or ports) in Zenoh-Flow must *not* contain any of the characters: '*', '#', '$', '?', '>'.
The identifier < {} > does not satisfy that condition.

These characters, except for '>', have a special meaning in Zenoh and they could negatively impact Zenoh-Flow's
behaviour.

The character '>' is used as a separator when flattening a composite operator. Allowing it could also negatively impact
Zenoh-Flow's behaviour.
"#,
            id
        )));
    }

    OwnedKeyExpr::autocanonize(id.clone()).map_err(|e| {
        serde::de::Error::custom(format!(
            r#"
Identifiers (for nodes or ports) in Zenoh-Flow *must* be valid key-expressions in their canonical form.
The identifier < {} > does not satisfy that condition.

Caused by:
{:?}
"#,
            id, e
        ))
    })?;

    Ok(id.into())
}

/// Deserialise a bytes size leveraging the [bytesize] crate.
///
/// This allows parsing, for instance, "1Ko" into "1024" bytes. For more example, see the [bytesize] crate.
///
/// # Errors
///
/// See the [bytesize] documentation.
pub fn deserialize_size<'de, D>(deserializer: D) -> std::result::Result<usize, D::Error>
where
    D: Deserializer<'de>,
{
    let size_str: String = serde::de::Deserialize::deserialize(deserializer)?;
    let size_u64 = bytesize::ByteSize::from_str(&size_str)
        .map_err(|e| {
            serde::de::Error::custom(format!(
                "Unable to parse value as bytes {size_str}:\n{:?}",
                e
            ))
        })?
        .as_u64();

    usize::try_from(size_u64).map_err(|e| serde::de::Error::custom(format!(
        "Unable to convert < {} > into a `usize`. Maybe check the architecture of the target device?\n{:?}",
        size_u64, e
    )))
}

/// Deserialise a duration in *microseconds* leveraging the [humantime] crate.
///
/// This allows parsing, for instance, "1ms" as 1000 microseconds.
///
/// # Errors
///
/// See the [humantime] documentation.
pub fn deserialize_time<'de, D>(deserializer: D) -> std::result::Result<u64, D::Error>
where
    D: Deserializer<'de>,
{
    let buf: &str = serde::de::Deserialize::deserialize(deserializer)?;
    let time_u128 = buf
        .parse::<humantime::Duration>()
        .map_err(serde::de::Error::custom)?
        .as_micros();

    u64::try_from(time_u128).map_err(|e| {
        serde::de::Error::custom(format!(
            "Unable to convert < {} > into a `u64`. Maybe lower the value?\n{:?}",
            time_u128, e
        ))
    })
}

#[cfg(test)]
mod tests {
    use serde::Deserialize;

    use crate::NodeId;

    #[derive(Deserialize, Debug)]
    pub struct TestStruct {
        pub id: NodeId,
    }

    #[test]
    fn test_deserialize_id() {
        let json_str = r#"
{
  "id": "my//chunk"
}
"#;
        assert!(serde_json::from_str::<TestStruct>(json_str).is_err());

        let json_str = r#"
{
  "id": "my*chunk"
}
"#;
        assert!(serde_json::from_str::<TestStruct>(json_str).is_err());

        let json_str = r##"
{
  "id": "#chunk"
}
"##;
        assert!(serde_json::from_str::<TestStruct>(json_str).is_err());

        let json_str = r#"
{
  "id": "?chunk"
}
"#;
        assert!(serde_json::from_str::<TestStruct>(json_str).is_err());

        let json_str = r#"
{
  "id": "$chunk"
}
"#;
        assert!(serde_json::from_str::<TestStruct>(json_str).is_err());

        let json_str = r#"
{
  "id": "my>chunk"
}
"#;
        assert!(serde_json::from_str::<TestStruct>(json_str).is_err());

        let json_str = r#"
{
  "id": "my/chunk/is/alright"
}
"#;
        assert!(serde_json::from_str::<TestStruct>(json_str).is_ok());
    }
}