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
//! File system metadata.

use anyhow::{bail, Result};
use chrono::{DateTime, TimeZone, Utc};
use libipld::Ipld;
use serde::{
    de::{DeserializeOwned, Error as DeError},
    Deserialize, Deserializer, Serialize, Serializer,
};
use std::{collections::BTreeMap, convert::TryInto};

//--------------------------------------------------------------------------------------------------
// Type Definitions
//--------------------------------------------------------------------------------------------------

/// The type of file system node.
#[derive(Debug, Clone, PartialEq, Eq, Copy)]
pub enum NodeType {
    PublicFile,
    PublicDirectory,
    PrivateFile,
    PrivateDirectory,
    TemporalSharePointer,
    SnapshotSharePointer,
}

impl ToString for NodeType {
    fn to_string(&self) -> String {
        match self {
            NodeType::PublicFile => "wnfs/pub/file",
            NodeType::PublicDirectory => "wnfs/pub/dir",
            NodeType::PrivateFile => "wnfs/priv/file",
            NodeType::PrivateDirectory => "wnfs/priv/dir",
            NodeType::TemporalSharePointer => "wnfs/share/temporal",
            NodeType::SnapshotSharePointer => "wnfs/share/snapshot",
        }
        .to_string()
    }
}

/// The metadata of a node in the WNFS file system.
///
/// # Examples
///
/// ```
/// use wnfs_common::Metadata;
/// use chrono::Utc;
///
/// let metadata = Metadata::new(Utc::now());
///
/// println!("{:?}", metadata);
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Metadata(pub BTreeMap<String, Ipld>);

//--------------------------------------------------------------------------------------------------
// Implementations
//--------------------------------------------------------------------------------------------------

impl Metadata {
    /// Creates a new metadata.
    ///
    /// # Examples
    ///
    /// ```
    /// use wnfs_common::Metadata;
    /// use chrono::Utc;
    ///
    /// let metadata = Metadata::new(Utc::now());
    ///
    /// println!("{:?}", metadata);
    /// ```
    pub fn new(time: DateTime<Utc>) -> Self {
        let time = time.timestamp();
        Self(BTreeMap::from([
            ("created".into(), time.into()),
            ("modified".into(), time.into()),
        ]))
    }

    /// Updates modified time.
    ///
    /// # Examples
    ///
    /// ```
    /// use wnfs_common::Metadata;
    /// use chrono::{Utc, TimeZone, Duration};
    ///
    /// let mut metadata = Metadata::new(Utc::now());
    /// let time = Utc::now() + Duration::days(1);
    ///
    /// metadata.upsert_mtime(time);
    ///
    /// let imprecise_time = Utc.timestamp_opt(time.timestamp(), 0).single();
    /// assert_eq!(metadata.get_modified(), imprecise_time);
    /// ```
    pub fn upsert_mtime(&mut self, time: DateTime<Utc>) {
        self.0.insert("modified".into(), time.timestamp().into());
    }

    /// Returns the created time.
    ///
    /// # Examples
    ///
    /// ```
    /// use wnfs_common::Metadata;
    /// use chrono::{Utc, TimeZone};
    ///
    /// let time = Utc::now();
    /// let metadata = Metadata::new(time);
    ///
    /// let imprecise_time = Utc.timestamp_opt(time.timestamp(), 0).single();
    /// assert_eq!(metadata.get_created(), imprecise_time);
    /// ```
    ///
    /// Will return `None` if there's no created metadata on the
    /// node or if it's not a second-based POSIX timestamp integer.
    pub fn get_created(&self) -> Option<DateTime<Utc>> {
        self.0.get("created").and_then(|ipld| match ipld {
            Ipld::Integer(i) => Utc.timestamp_opt(i64::try_from(*i).ok()?, 0).single(),
            _ => None,
        })
    }

    /// Returns the modified time.
    ///
    /// # Examples
    ///
    /// ```
    /// use wnfs_common::Metadata;
    /// use chrono::{Utc, TimeZone};
    ///
    /// let time = Utc::now();
    /// let metadata = Metadata::new(time);
    ///
    /// let imprecise_time = Utc.timestamp_opt(time.timestamp(), 0).single();
    /// assert_eq!(metadata.get_modified(), imprecise_time);
    /// ```
    ///
    /// Will return `None` if there's no created metadata on the
    /// node or if it's not a second-based POSIX timestamp integer.
    pub fn get_modified(&self) -> Option<DateTime<Utc>> {
        self.0.get("modified").and_then(|ipld| match ipld {
            Ipld::Integer(i) => Utc.timestamp_opt(i64::try_from(*i).ok()?, 0).single(),
            _ => None,
        })
    }

    /// Inserts a key-value pair into the metadata.
    /// If the key already existed, the value is updated, and the old value is returned.
    ///
    /// # Examples
    /// ```
    /// use wnfs_common::Metadata;
    /// use chrono::Utc;
    /// use libipld::Ipld;
    ///
    /// let mut metadata = Metadata::new(Utc::now());
    /// metadata.put("foo", Ipld::String("bar".into()));
    /// assert_eq!(metadata.0.get("foo"), Some(&Ipld::String("bar".into())));
    /// metadata.put("foo", Ipld::String("baz".into()));
    /// assert_eq!(metadata.0.get("foo"), Some(&Ipld::String("baz".into())));
    /// ```
    ///
    /// Returns (self, old_value), where old_value is `None` if the key did not exist prior to this call.
    pub fn put(&mut self, key: &str, value: Ipld) -> Option<Ipld> {
        self.0.insert(key.into(), value)
    }

    /// Returns metadata value behind given key.
    pub fn get(&self, key: &str) -> Option<&Ipld> {
        self.0.get(key)
    }

    /// Serializes and inserts given value at given key in metadata.
    pub fn put_serializable(&mut self, key: &str, value: impl Serialize) -> Result<Option<Ipld>> {
        let serialized = libipld::serde::to_ipld(value)?;
        Ok(self.put(key, serialized))
    }

    /// Returns deserialized metadata value behind given key.
    pub fn get_deserializable<D: DeserializeOwned>(&self, key: &str) -> Option<Result<D>> {
        self.get(key)
            .map(|ipld| Ok(libipld::serde::from_ipld(ipld.clone())?))
    }

    /// Deletes a key from the metadata.
    ///
    /// # Examples
    /// ```
    /// use wnfs_common::Metadata;
    /// use chrono::Utc;
    /// use libipld::Ipld;
    ///
    /// let mut metadata = Metadata::new(Utc::now());
    /// metadata.put("foo", Ipld::String("bar".into()));
    /// assert_eq!(metadata.0.get("foo"), Some(&Ipld::String("bar".into())));
    /// metadata.delete("foo");
    /// assert_eq!(metadata.0.get("foo"), None);
    /// ```
    ///
    /// Returns `Some<Ipld>` if the key existed prior to this call, otherwise None.
    pub fn delete(&mut self, key: &str) -> Option<Ipld> {
        self.0.remove(key)
    }

    /// Updates this metadata with the contents of another metadata. merge strategy is to take theirs.
    ///
    /// # Examples
    /// ```
    /// use wnfs_common::Metadata;
    /// use chrono::Utc;
    /// use libipld::Ipld;
    ///
    /// let mut metadata1 = Metadata::new(Utc::now());
    /// metadata1.put("foo", Ipld::String("bar".into()));
    /// let mut metadata2 = Metadata::new(Utc::now());
    /// metadata2.put("foo", Ipld::String("baz".into()));
    /// metadata1.update(&metadata2);
    /// assert_eq!(metadata1.0.get("foo"), Some(&Ipld::String("baz".into())));
    /// ```
    pub fn update(&mut self, other: &Self) {
        for (key, value) in other.0.iter() {
            self.0.insert(key.clone(), value.clone());
        }
    }
}

impl TryFrom<&Ipld> for NodeType {
    type Error = anyhow::Error;

    fn try_from(ipld: &Ipld) -> Result<Self> {
        match ipld {
            Ipld::String(s) => NodeType::try_from(s.as_str()),
            other => bail!("Expected `Ipld::String` got {:#?}", other),
        }
    }
}

impl TryFrom<&str> for NodeType {
    type Error = anyhow::Error;

    fn try_from(name: &str) -> Result<Self> {
        Ok(match name.to_lowercase().as_str() {
            "wnfs/priv/dir" => NodeType::PrivateDirectory,
            "wnfs/priv/file" => NodeType::PrivateFile,
            "wnfs/pub/dir" => NodeType::PublicDirectory,
            "wnfs/pub/file" => NodeType::PublicFile,
            "wnfs/share/temporal" => NodeType::TemporalSharePointer,
            "wnfs/share/snapshot" => NodeType::SnapshotSharePointer,
            _ => bail!("Unknown UnixFsNodeKind: {}", name),
        })
    }
}

impl From<&NodeType> for String {
    fn from(r#type: &NodeType) -> Self {
        match r#type {
            NodeType::PrivateDirectory => "wnfs/priv/dir".into(),
            NodeType::PrivateFile => "wnfs/priv/file".into(),
            NodeType::PublicDirectory => "wnfs/pub/dir".into(),
            NodeType::PublicFile => "wnfs/pub/file".into(),
            NodeType::TemporalSharePointer => "wnfs/share/temporal".into(),
            NodeType::SnapshotSharePointer => "wnfs/share/snapshot".into(),
        }
    }
}

impl Serialize for NodeType {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        String::from(self).serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for NodeType {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let r#type = String::deserialize(deserializer)?;
        r#type.as_str().try_into().map_err(DeError::custom)
    }
}
//--------------------------------------------------------------------------------------------------
// Tests
//--------------------------------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use crate::{decode, encode, Metadata};
    use chrono::Utc;
    use libipld::cbor::DagCborCodec;

    #[async_std::test]
    async fn metadata_can_encode_decode_as_cbor() {
        let metadata = Metadata::new(Utc::now());

        let encoded_metadata = encode(&metadata, DagCborCodec).unwrap();
        let decoded_metadata: Metadata = decode(encoded_metadata.as_ref(), DagCborCodec).unwrap();

        assert_eq!(metadata, decoded_metadata);
    }
}