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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
// Copyright 2019 Dmitry Tantsur <divius.inside@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Common JSON structures and protocol bits.

use std::cmp::Ordering;
use std::fmt;
use std::iter::{DoubleEndedIterator, FusedIterator};
use std::str::FromStr;
use std::vec::IntoIter;

use serde::de::{DeserializeOwned, Error as DeserError};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;
use url::Url;

/// A link to a resource.
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
pub struct Link {
    pub href: Url,
    pub rel: String,
}

#[derive(Clone, Debug, Deserialize)]
pub struct Ref {
    pub id: String,
    pub links: Vec<Link>,
}

/// A reference to an ID and name.
#[derive(Clone, Debug, Deserialize)]
pub struct IdAndName {
    pub id: String,
    pub name: String,
}

/// A pair `X.Y` where `X` and `Y` can be converted to/from a string and `Y` is optional.
#[derive(Copy, Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct XdotY<T>(pub T, pub T);

/// A single API version as returned by a version discovery endpoint.
#[derive(Clone, Debug, Deserialize)]
pub struct Version {
    pub id: XdotY<u16>,
    #[serde(default)]
    pub links: Vec<Link>,
    #[serde(deserialize_with = "empty_as_default", default)]
    pub status: Option<String>,
    #[serde(deserialize_with = "empty_as_default", default)]
    pub version: Option<XdotY<u16>>,
    #[serde(deserialize_with = "empty_as_default", default)]
    pub min_version: Option<XdotY<u16>>,
}

impl Version {
    /// Whether a version is considered stable according to its status.
    #[inline]
    pub fn is_stable(&self) -> bool {
        if let Some(ref status) = self.status {
            let upper = status.to_uppercase();
            upper == "STABLE" || upper == "CURRENT" || upper == "SUPPORTED"
        } else {
            true
        }
    }
}

impl PartialEq for Version {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl Eq for Version {}

impl PartialOrd for Version {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(&other))
    }
}

impl Ord for Version {
    fn cmp(&self, other: &Self) -> Ordering {
        self.id.cmp(&other.id)
    }
}

/// A result of a version discovery endpoint.
#[derive(Clone, Debug, Deserialize)]
#[serde(untagged)]
pub enum Root {
    /// Multiple major versions.
    MultipleVersions { versions: Vec<Version> },
    /// Single major version.
    OneVersion { version: Version },
}

#[derive(Debug, Clone)]
enum IntoStableIterInner {
    Many(IntoIter<Version>),
    One(Option<Version>),
}

/// An iterator over stable versions.
#[derive(Debug)]
pub struct IntoStableIter(IntoStableIterInner);

impl Iterator for IntoStableIter {
    type Item = Version;

    fn next(&mut self) -> Option<Self::Item> {
        match self.0 {
            IntoStableIterInner::Many(ref mut inner) => {
                for next in inner {
                    if next.is_stable() {
                        return Some(next);
                    }
                }

                None
            }
            IntoStableIterInner::One(ref mut opt) => opt.take(),
        }
    }
}

impl DoubleEndedIterator for IntoStableIter {
    fn next_back(&mut self) -> Option<Self::Item> {
        match self.0 {
            IntoStableIterInner::Many(ref mut inner) => {
                while let Some(next) = inner.next_back() {
                    if next.is_stable() {
                        return Some(next);
                    }
                }

                None
            }
            IntoStableIterInner::One(ref mut opt) => opt.take(),
        }
    }
}

impl FusedIterator for IntoStableIter {}

impl Root {
    /// Sort versions from lowest to highest (using unstable sorting).
    #[inline]
    pub fn sort(&mut self) {
        if let Root::MultipleVersions {
            versions: ref mut vers,
        } = self
        {
            vers.sort_unstable();
        }
    }

    /// Create a `Root` sorted with `sort`.
    #[inline]
    pub fn into_sorted(mut self) -> Self {
        self.sort();
        self
    }

    /// Create an iterator over stable versions.
    pub fn into_stable_iter(self) -> IntoStableIter {
        match self {
            Root::MultipleVersions { versions: vers } => {
                IntoStableIter(IntoStableIterInner::Many(vers.into_iter()))
            }
            Root::OneVersion { version: ver } => {
                let stable = if ver.is_stable() { Some(ver) } else { None };
                IntoStableIter(IntoStableIterInner::One(stable))
            }
        }
    }
}

impl<T> fmt::Display for XdotY<T>
where
    T: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}.{}", self.0, self.1)
    }
}

impl<T> fmt::Debug for XdotY<T>
where
    T: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("").field(&self.0).field(&self.1).finish()
    }
}

impl<T> Serialize for XdotY<T>
where
    T: fmt::Display,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

impl<T> FromStr for XdotY<T>
where
    T: FromStr + Default,
    T::Err: fmt::Display,
{
    type Err = String;

    fn from_str(s: &str) -> Result<XdotY<T>, String> {
        let mut parts = s.split('.');

        if let Some(x_part) = parts.next() {
            let x = x_part
                .parse()
                .map_err(|err| format!("cannot parse the first component: {}", err))?;

            let y = if let Some(y_part) = parts.next() {
                y_part
                    .parse()
                    .map_err(|err| format!("cannot parse the second component: {}", err))?
            } else {
                T::default()
            };

            if parts.next().is_some() {
                Err(format!("expected X.Y, got {}", s))
            } else {
                Ok(XdotY(x, y))
            }
        } else {
            Err(format!("expected X.Y, got {}", s))
        }
    }
}

impl<'de, T> Deserialize<'de> for XdotY<T>
where
    T: FromStr + Default,
    T::Err: fmt::Display,
{
    fn deserialize<D>(deserializer: D) -> Result<XdotY<T>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value: String = Deserialize::deserialize(deserializer)?;
        let version_part = if value.starts_with('v') {
            &value[1..]
        } else {
            &value
        };
        XdotY::from_str(&version_part).map_err(D::Error::custom)
    }
}

impl<T> From<(T, T)> for XdotY<T> {
    fn from(value: (T, T)) -> XdotY<T> {
        XdotY(value.0, value.1)
    }
}

/// Deserialize a value where empty string is replaced by `Default` value.
pub fn empty_as_default<'de, D, T>(des: D) -> Result<T, D::Error>
where
    D: Deserializer<'de>,
    T: DeserializeOwned + Default,
{
    let value = Value::deserialize(des)?;
    match value {
        Value::String(ref s) if s.is_empty() => Ok(T::default()),
        _ => serde_json::from_value(value).map_err(D::Error::custom),
    }
}

#[cfg(test)]
pub mod test {
    use std::str::FromStr;

    use serde::{Deserialize, Serialize};
    use serde_json;

    use super::{empty_as_default, Root, Version, XdotY};

    pub fn compare<T: Serialize>(sample: &str, value: T) {
        let converted: serde_json::Value = serde_json::from_str(sample).unwrap();
        let result = serde_json::to_value(value).unwrap();
        assert_eq!(result, converted);
    }

    #[derive(Debug, Deserialize)]
    struct Custom(bool);

    #[derive(Debug, Deserialize)]
    struct EmptyAsDefault {
        #[serde(deserialize_with = "empty_as_default")]
        number: u8,
        #[serde(deserialize_with = "empty_as_default")]
        vec: Vec<String>,
        #[serde(deserialize_with = "empty_as_default")]
        opt: Option<Custom>,
        #[serde(deserialize_with = "empty_as_default")]
        string: Option<String>,
    }

    #[test]
    fn test_empty_as_default_with_values() {
        let s = "{\"number\": 42, \"vec\": [\"value\"], \"opt\": true, \"string\": \"value\"}";
        let r: EmptyAsDefault = serde_json::from_str(s).unwrap();
        assert_eq!(r.number, 42);
        assert_eq!(r.vec, vec!["value".to_string()]);
        assert!(r.opt.unwrap().0);
        assert_eq!(r.string.unwrap(), "value");
    }

    #[test]
    fn test_empty_as_default_with_empty_string() {
        let s = "{\"number\": \"\", \"vec\": \"\", \"opt\": \"\", \"string\": \"\"}";
        let r: EmptyAsDefault = serde_json::from_str(s).unwrap();
        assert_eq!(r.number, 0);
        assert!(r.vec.is_empty());
        assert!(r.opt.is_none());
        assert!(r.string.is_none());
    }

    #[test]
    fn test_xdoty_debug() {
        let xy = XdotY(1, 2);
        let s = format!("{:?}", xy);
        assert_eq!(s, "(1, 2)");
        let s2 = format!("{:?}", (1, 2));
        assert_eq!(s, s2);
    }

    #[test]
    fn test_xdoty_display() {
        let xy = XdotY(1, 2);
        let s = format!("{}", xy);
        assert_eq!(s, "1.2");
    }

    #[test]
    fn test_xdoty_from_str() {
        let xy: XdotY<u8> = XdotY::from_str("1.2").unwrap();
        assert_eq!(xy.0, 1);
        assert_eq!(xy.1, 2);
    }

    #[test]
    fn test_xdoty_from_str_no_y() {
        let xy: XdotY<u8> = XdotY::from_str("1").unwrap();
        assert_eq!(xy.0, 1);
        assert_eq!(xy.1, 0);
    }

    #[test]
    fn test_xdoty_from_str_failure() {
        for s in &["foo", "1.foo", "foo.2", "1.2.3"] {
            let res: Result<XdotY<u8>, _> = XdotY::from_str(s);
            assert!(res.is_err());
        }
    }

    #[test]
    fn test_xdoty_serde_serialize() {
        let xy = XdotY(2u8, 27);
        let ser = serde_json::to_string(&xy).unwrap();
        assert_eq!(&ser, "\"2.27\"");
    }

    #[derive(Debug, Deserialize)]
    struct Struct {
        pub req: XdotY<u16>,
        pub opt: Option<XdotY<u16>>,
    }

    #[test]
    fn test_xdoty_serde_deserialize() {
        let xy: XdotY<u8> = serde_json::from_str("\"2.27\"").unwrap();
        assert_eq!(xy, XdotY(2, 27));
        let xy2: XdotY<u16> =
            serde_json::from_value(serde_json::Value::String("2.27".to_string())).unwrap();
        assert_eq!(xy2, XdotY(2, 27));
        let st: Struct = serde_json::from_str("{\"req\": \"2.27\", \"opt\": \"2.42\"}").unwrap();
        assert_eq!(st.req, XdotY(2, 27));
        assert_eq!(st.opt.unwrap(), XdotY(2, 42));
    }

    #[test]
    fn test_xdoty_serde_deserialize_with_v() {
        let xy: XdotY<u8> = serde_json::from_str("\"v2.27\"").unwrap();
        assert_eq!(xy, XdotY(2, 27));
        let xy2: XdotY<u16> =
            serde_json::from_value(serde_json::Value::String("v2.27".to_string())).unwrap();
        assert_eq!(xy2, XdotY(2, 27));
        let st: Struct = serde_json::from_str("{\"req\": \"v2.27\", \"opt\": \"v2.42\"}").unwrap();
        assert_eq!(st.req, XdotY(2, 27));
        assert_eq!(st.opt.unwrap(), XdotY(2, 42));
    }

    #[test]
    fn test_version_current_is_stable() {
        let stable = Version {
            id: XdotY(2, 0),
            links: Vec::new(),
            status: Some("CURRENT".to_string()),
            version: None,
            min_version: None,
        };
        assert!(stable.is_stable());
    }

    #[test]
    fn test_version_stable_is_stable() {
        let stable = Version {
            id: XdotY(2, 0),
            links: Vec::new(),
            status: Some("Stable".to_string()),
            version: None,
            min_version: None,
        };
        assert!(stable.is_stable());
    }

    #[test]
    fn test_version_supported_is_stable() {
        let stable = Version {
            id: XdotY(2, 0),
            links: Vec::new(),
            status: Some("supported".to_string()),
            version: None,
            min_version: None,
        };
        assert!(stable.is_stable());
    }

    #[test]
    fn test_version_no_status_is_stable() {
        let stable = Version {
            id: XdotY(2, 0),
            links: Vec::new(),
            status: None,
            version: None,
            min_version: None,
        };
        assert!(stable.is_stable());
    }

    #[test]
    fn test_version_deprecated_is_not_stable() {
        let unstable = Version {
            id: XdotY(2, 0),
            links: Vec::new(),
            status: Some("DEPRECATED".to_string()),
            version: None,
            min_version: None,
        };
        assert!(!unstable.is_stable());
    }

    #[test]
    fn test_root_sort() {
        let vers: Vec<_> = [3, 1, 2]
            .iter()
            .map(|idx| Version {
                id: XdotY(*idx, 0),
                links: Vec::new(),
                status: None,
                version: None,
                min_version: None,
            })
            .collect();
        let mut root = Root::MultipleVersions { versions: vers };
        root.sort();
        if let Root::MultipleVersions { versions: res } = root {
            let idx = res.into_iter().map(|v| v.id.0).collect::<Vec<_>>();
            assert_eq!(idx, vec![1, 2, 3]);
        } else {
            unreachable!();
        }
    }

    #[test]
    fn test_root_sort_one() {
        let ver = Version {
            id: XdotY(2, 0),
            links: Vec::new(),
            status: Some("supported".to_string()),
            version: None,
            min_version: None,
        };
        let mut root = Root::OneVersion { version: ver };
        root.sort();
        if let Root::OneVersion { version: res } = root {
            assert_eq!(res.id.0, 2);
        } else {
            unreachable!();
        }
    }

    #[test]
    fn test_root_into_sorted() {
        let vers: Vec<_> = [3, 1, 2]
            .iter()
            .map(|idx| Version {
                id: XdotY(*idx, 0),
                links: Vec::new(),
                status: None,
                version: None,
                min_version: None,
            })
            .collect();
        let mut root = Root::MultipleVersions { versions: vers };
        root = root.into_sorted();
        if let Root::MultipleVersions { versions: res } = root {
            let idx = res.into_iter().map(|v| v.id.0).collect::<Vec<_>>();
            assert_eq!(idx, vec![1, 2, 3]);
        } else {
            unreachable!();
        }
    }

    #[test]
    fn test_root_into_stable_iter() {
        let vers: Vec<_> = [3, 1, 2]
            .iter()
            .map(|idx| Version {
                id: XdotY(*idx, 0),
                links: Vec::new(),
                status: Some(if *idx > 1 { "CURRENT" } else { "DEPRECATED" }.to_string()),
                version: None,
                min_version: None,
            })
            .collect();
        let root = Root::MultipleVersions { versions: vers };
        let idx = root
            .into_stable_iter()
            .map(|ver| ver.id.0)
            .collect::<Vec<_>>();
        assert_eq!(idx, vec![3, 2]);
    }

    #[test]
    fn test_root_into_stable_iter_reverse() {
        let vers: Vec<_> = [3, 1, 2]
            .iter()
            .map(|idx| Version {
                id: XdotY(*idx, 0),
                links: Vec::new(),
                status: Some(if *idx > 1 { "CURRENT" } else { "DEPRECATED" }.to_string()),
                version: None,
                min_version: None,
            })
            .collect();
        let root = Root::MultipleVersions { versions: vers };
        let mut idx = root.into_stable_iter().map(|ver| ver.id.0);
        assert_eq!(idx.next_back(), Some(2));
        assert_eq!(idx.next_back(), Some(3));
        assert!(idx.next_back().is_none());
        assert!(idx.next().is_none());
    }

    #[test]
    fn test_root_into_stable_iter_one() {
        let ver = Version {
            id: XdotY(2, 0),
            links: Vec::new(),
            status: Some("supported".to_string()),
            version: None,
            min_version: None,
        };
        let root = Root::OneVersion { version: ver };
        let idx = root
            .into_stable_iter()
            .map(|ver| ver.id.0)
            .collect::<Vec<_>>();
        assert_eq!(idx, vec![2]);
    }

    #[test]
    fn test_root_into_stable_iter_one_unstable() {
        let ver = Version {
            id: XdotY(2, 0),
            links: Vec::new(),
            status: Some("deprecated".to_string()),
            version: None,
            min_version: None,
        };
        let root = Root::OneVersion { version: ver };
        let mut idx = root.into_stable_iter().map(|ver| ver.id.0);
        assert!(idx.next().is_none());
    }

    #[test]
    fn test_root_into_stable_iter_one_reverse() {
        let ver = Version {
            id: XdotY(2, 0),
            links: Vec::new(),
            status: Some("supported".to_string()),
            version: None,
            min_version: None,
        };
        let root = Root::OneVersion { version: ver };
        let mut idx = root.into_stable_iter().map(|ver| ver.id.0);
        assert_eq!(idx.next_back(), Some(2));
        assert!(idx.next_back().is_none());
    }

    const COMPUTE_ONE: &str = r#"{
  "version": {
    "status": "CURRENT",
    "updated": "2013-07-23T11:33:21Z",
    "links": [
      {
        "href": "https://example.org:13774/v2.1/",
        "rel": "self"
      },
      {
        "href": "http://docs.openstack.org/",
        "type": "text/html",
        "rel": "describedby"
      }
    ],
    "min_version": "2.1",
    "version": "2.42",
    "media-types": [
      {
        "base": "application/json",
        "type": "application/vnd.openstack.compute+json;version=2.1"
      }
    ],
    "id": "v2.1"
  }
}"#;

    #[test]
    fn test_parse_root_one_version() {
        let root: Root = serde_json::from_str(COMPUTE_ONE).unwrap();
        match root {
            Root::OneVersion { version } => {
                assert_eq!(version.id, XdotY(2, 1));
            }
            Root::MultipleVersions { .. } => panic!("Unexpected multiple versions"),
        }
    }
}