prometheus-http-query 0.10.1

Prometheus HTTP API client
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
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
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
use crate::error::{Error, ParseUrlError};
use mime::Mime;
use reqwest::header::HeaderValue;
use serde::Deserialize;
use std::{fmt, str::FromStr};
use time::Duration as TimeDuration;
use url::Url;

fn time_duration_to_string(mut duration: TimeDuration) -> String {
    let mut s = String::new();

    if duration.is_negative() {
        s.push('-');
    }

    {
        let d = TimeDuration::weeks(duration.whole_weeks());

        let years = (d / TimeDuration::weeks(12)).floor() as i64;

        if years >= 1 {
            let d = TimeDuration::weeks(12 * years);
            s.push_str(&d.to_string());
            s.push('y');
            duration -= d;
        }
    }

    {
        let d = TimeDuration::weeks(duration.whole_weeks());

        if !d.is_zero() {
            s.push_str(&d.whole_weeks().to_string());
            s.push('w');
            duration -= d;
        }
    }

    {
        let d = TimeDuration::days(duration.whole_days());

        if !d.is_zero() {
            s.push_str(&d.whole_days().to_string());
            s.push('d');
            duration -= d;
        }
    }

    {
        let d = TimeDuration::hours(duration.whole_hours());

        if !d.is_zero() {
            s.push_str(&d.whole_hours().to_string());
            s.push('h');
            duration -= d;
        }
    }

    {
        let d = TimeDuration::minutes(duration.whole_minutes());

        if !d.is_zero() {
            s.push_str(&d.whole_minutes().to_string());
            s.push('m');
            duration -= d;
        }
    }

    {
        let d = TimeDuration::seconds(duration.whole_seconds());

        if !d.is_zero() {
            s.push_str(&d.whole_seconds().to_string());
            s.push('s');
            duration -= d;
        }
    }

    {
        let d = TimeDuration::milliseconds(duration.whole_milliseconds() as i64);

        if !d.is_zero() {
            s.push_str(&d.whole_milliseconds().to_string());
            s.push_str("ms");
            duration -= d;
        }
    }

    // Sub-millisecond durations cannot be expressed. Thus when the
    // string is still empty we return a hardcoded value to account
    // for the missing precision.
    if s.is_empty() {
        String::from("0ms")
    } else {
        s
    }
}

/// A wrapper around [`time::Duration`] that is used to deserialize
/// responses or verify time durations before sending them to Prometheus.
///
/// ```rust
/// use prometheus_http_query::{Duration, Client};
/// use std::str::FromStr;
///
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() -> Result<(), anyhow::Error> {
///     let client = Client::default();
///
///     let q = "prometheus_http_requests_total";
///     let d = Duration::from_str("1m")?;
///
///     // Use parsed duration by converting to `f64`.
///     let response = client.query_range(q, 1648373100, 1648373300, d.into()).get().await?;
///
///     assert!(response.data().as_matrix().is_some());
///
///     // Durations converted from numeric types can also be printed back to
///     // a Prometheus duration string.
///     let d = Duration::from(50.312);
///     assert_eq!(&d.to_string(), "50s312ms");
///
///     // However durations that were parsed from a string retain their original
///     // string representation, even when they could be expressed more succinctly.
///     // For example this could also be "2m".
///     let d = Duration::from_str("120s")?;
///     assert_eq!(&d.to_string(), "120s");
///
///     Ok(())
/// }
/// ```
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Duration {
    pub(crate) inner: TimeDuration,
    raw: String,
}

impl FromStr for Duration {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut total_milliseconds: i64 = 0;

        // Add each number character to a string until a unit character is encountered.
        // This string is then cleared to process the next number + unit.
        let mut raw_num = String::new();

        // Iterate the duration string, convert each unit to nanoseconds and add
        // it to the total.
        let mut duration_iter = s.chars().peekable();

        // Check for minus sign. It can be safely ignored at this point and the first
        // number parsed as a positive integer because any of the following
        // multiplications will switch the sign automatically.
        let is_neg = duration_iter.next_if_eq(&'-').is_some();

        while let Some(item) = duration_iter.next() {
            if ('0'..='9').contains(&item) {
                raw_num.push(item);
                continue;
            }

            let num = raw_num.parse::<i64>().map_err(Error::ParseInt)?;

            let factor = match item {
                'y' => 1000 * 60 * 60 * 24 * 365,
                'w' => 1000 * 60 * 60 * 24 * 7,
                'd' => 1000 * 60 * 60 * 24,
                'h' => 1000 * 60 * 60,
                'm' => {
                    if duration_iter.next_if_eq(&'s').is_some() {
                        1
                    } else {
                        1000 * 60
                    }
                }
                's' => 1000,
                _ => return Err(Error::Parse(format!("invalid time duration: {}", s))),
            };

            if is_neg {
                total_milliseconds -= num * factor;
            } else {
                total_milliseconds += num * factor;
            }

            raw_num.clear();
        }

        Ok(Self {
            inner: TimeDuration::milliseconds(total_milliseconds),
            raw: s.to_string(),
        })
    }
}

impl fmt::Display for Duration {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.raw)
    }
}

impl TryFrom<String> for Duration {
    type Error = Error;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        Self::from_str(&s)
    }
}

/// Convert fractional seconds to `Duration`.
///
/// ```rust
/// use prometheus_http_query::Duration;
/// use std::str::FromStr;
///
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() -> Result<(), anyhow::Error> {
///     {
///         let a = Duration::from_str("1s")?;
///         let b = Duration::from(1.0);
///         assert_eq!(a, b);
///     }
///
///     {
///         let a = Duration::from_str("312ms")?;
///         let b = Duration::from(0.312);
///         assert_eq!(a, b);
///     }
///
///     Ok(())
/// }
/// ```
impl From<f64> for Duration {
    fn from(f: f64) -> Self {
        let inner = TimeDuration::saturating_seconds_f64(f);

        let raw = time_duration_to_string(inner);

        Self { raw, inner }
    }
}

impl Into<f64> for Duration {
    fn into(self) -> f64 {
        self.inner.as_seconds_f64()
    }
}

/// Convert seconds to `Duration`.
///
/// ```rust
/// use prometheus_http_query::Duration;
/// use std::str::FromStr;
///
/// #[tokio::main(flavor = "current_thread")]
/// async fn main() -> Result<(), anyhow::Error> {
///     {
///         let a = Duration::from_str("2m")?;
///         let b = Duration::from(120);
///         assert_eq!(a, b);
///     }
///
///     {
///         let a = Duration::from_str("1h")?;
///         let b = Duration::from(3600);
///         assert_eq!(a, b);
///     }
///
///     Ok(())
/// }
/// ```
impl From<i64> for Duration {
    fn from(s: i64) -> Self {
        let inner = TimeDuration::seconds(s);

        let raw = time_duration_to_string(inner);

        Self { raw, inner }
    }
}

impl Into<i64> for Duration {
    fn into(self) -> i64 {
        self.inner.whole_seconds()
    }
}

/// A helper enum to filter targets by state.
#[derive(Clone, Copy, Debug)]
pub enum TargetState {
    Active,
    Dropped,
    Any,
}

impl fmt::Display for TargetState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Active => f.write_str("active"),
            Self::Dropped => f.write_str("dropped"),
            Self::Any => f.write_str("any"),
        }
    }
}

impl FromStr for TargetState {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "active" => Ok(Self::Active),
            "dropped" => Ok(Self::Dropped),
            "any" => Ok(Self::Any),
            _ => Err(Error::Parse(format!(
                "failed to parse target state from '{}', must be one of 'active', 'dropped', 'any'",
                s
            ))),
        }
    }
}

/// A helper enum to represent possible target health states.
#[derive(Debug, Copy, Clone, Deserialize, Eq, PartialEq)]
pub enum TargetHealth {
    #[serde(alias = "up")]
    Up,
    #[serde(alias = "down")]
    Down,
    #[serde(alias = "unknown")]
    Unknown,
}

impl TargetHealth {
    pub fn is_up(&self) -> bool {
        *self == Self::Up
    }

    pub fn is_down(&self) -> bool {
        *self == Self::Down
    }

    pub fn is_unknown(&self) -> bool {
        *self == Self::Unknown
    }
}

impl fmt::Display for TargetHealth {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Up => f.write_str("up"),
            Self::Down => f.write_str("down"),
            Self::Unknown => f.write_str("unknown"),
        }
    }
}

/// A helper enum to represent possible rule health states.
#[derive(Debug, Copy, Clone, Deserialize, Eq, PartialEq)]
pub enum RuleHealth {
    #[serde(alias = "ok")]
    Good,
    #[serde(alias = "err")]
    Bad,
    #[serde(alias = "unknown")]
    Unknown,
}

impl RuleHealth {
    pub fn is_good(&self) -> bool {
        *self == Self::Good
    }

    pub fn is_bad(&self) -> bool {
        *self == Self::Bad
    }

    pub fn is_unknown(&self) -> bool {
        *self == Self::Unknown
    }
}

impl fmt::Display for RuleHealth {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Good => f.write_str("ok"),
            Self::Bad => f.write_str("err"),
            Self::Unknown => f.write_str("unknown"),
        }
    }
}

/// A helper type to represent possible rule health states.
#[derive(Debug, Copy, Clone, Deserialize, Eq, PartialEq)]
pub enum AlertState {
    #[serde(alias = "inactive")]
    Inactive,
    #[serde(alias = "pending")]
    Pending,
    #[serde(alias = "firing")]
    Firing,
}

impl AlertState {
    pub fn is_inactive(&self) -> bool {
        *self == Self::Inactive
    }

    pub fn is_pending(&self) -> bool {
        *self == Self::Pending
    }

    pub fn is_firing(&self) -> bool {
        *self == Self::Firing
    }
}

impl fmt::Display for AlertState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Inactive => f.write_str("inactive"),
            Self::Pending => f.write_str("pending"),
            Self::Firing => f.write_str("firing"),
        }
    }
}

/// A helper enum to filter rules by type.
#[derive(Copy, Clone, Debug)]
pub enum RuleKind {
    Alerting,
    Recording,
}

impl RuleKind {
    pub(crate) fn to_query_param(&self) -> String {
        match self {
            Self::Alerting => String::from("alert"),
            Self::Recording => String::from("record"),
        }
    }
}

impl fmt::Display for RuleKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Alerting => f.write_str("alerting"),
            Self::Recording => f.write_str("recording"),
        }
    }
}

impl FromStr for RuleKind {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "alert"| "alerting" => Ok(Self::Alerting),
            "record"| "recording" => Ok(Self::Recording),
            _ => Err(Error::Parse(format!("failed to parse rule type from '{}', must be one of 'alert', 'alerting', 'record', 'recording'", s)))
        }
    }
}

#[allow(clippy::enum_variant_names)]
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Label<'a> {
    Equal((&'a str, &'a str)),
    NotEqual((&'a str, &'a str)),
    RegexEqual((&'a str, &'a str)),
    RegexNotEqual((&'a str, &'a str)),
}

impl<'a> fmt::Display for Label<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        match self {
            Self::Equal((k, v)) => write!(f, "{}=\"{}\"", k, v),
            Self::NotEqual((k, v)) => write!(f, "{}!=\"{}\"", k, v),
            Self::RegexEqual((k, v)) => write!(f, "{}=~\"{}\"", k, v),
            Self::RegexNotEqual((k, v)) => write!(f, "{}!~\"{}\"", k, v),
        }
    }
}

/// Create a base URL that is common to all queries from a string literal.
/// The implementations are probably a little more complicated than they need
/// to be as we need to allocate a new string during the URL construction
/// to preserve a possibly existing path component in the source string.
pub(crate) trait ToBaseUrl {
    fn to_base_url(self) -> Result<Url, Error>;
}

impl ToBaseUrl for &str {
    fn to_base_url(self) -> Result<Url, Error> {
        Url::parse(self).map_err(|source| {
            Error::ParseUrl(ParseUrlError {
                message: "failed to build Prometheus server base URL",
                source,
            })
        })
    }
}

impl ToBaseUrl for String {
    fn to_base_url(self) -> Result<Url, Error> {
        Url::parse(&self).map_err(|source| {
            Error::ParseUrl(ParseUrlError {
                message: "failed to build Prometheus server base URL",
                source,
            })
        })
    }
}

pub(crate) fn build_final_url(mut url: Url, path: &str) -> Url {
    let base_path = url.path();
    match base_path {
        "/" => return url.join(path).unwrap(),
        _ => {
            let p = format!("{}/{}", base_path, path);
            url.set_path(&p);
        }
    }
    url
}

pub(crate) fn is_json(v: Option<&HeaderValue>) -> bool {
    match v
        .and_then(|h| h.to_str().ok())
        .and_then(|h| h.parse::<Mime>().ok())
    {
        Some(mime) => match (mime.type_(), mime.subtype()) {
            (mime::APPLICATION, mime::JSON) => true,
            _ => false,
        },
        None => false,
    }
}

#[cfg(test)]
mod tests {
    use super::{build_final_url, is_json, Duration, ToBaseUrl};
    use std::str::FromStr;
    use time::Duration as TimeDuration;

    #[test]
    fn test_simple_str_to_url() {
        let s = "http://127.0.0.1:9090";
        let url = s.to_base_url().unwrap();
        assert_eq!("http://127.0.0.1:9090/", url.as_str());
    }

    #[test]
    fn test_proxied_str_to_url() {
        let s = "http://proxy.example.com/prometheus";
        let url = s.to_base_url().unwrap();
        assert_eq!("http://proxy.example.com/prometheus", url.as_str());
    }

    #[test]
    fn test_simple_string_to_url() {
        let s = String::from("http://127.0.0.1:9090");
        let url = s.to_base_url().unwrap();
        assert_eq!("http://127.0.0.1:9090/", url.as_str());
    }

    #[test]
    fn test_proxied_string_to_url() {
        let s = String::from("http://proxy.example.com/prometheus");
        let url = s.to_base_url().unwrap();
        assert_eq!("http://proxy.example.com/prometheus", url.as_str());
    }

    #[test]
    fn test_simple_url_finalization() {
        let s = String::from("http://127.0.0.1:9090");
        let url = s.to_base_url().unwrap();
        let final_url = build_final_url(url, "api/v1/targets");
        assert_eq!("http://127.0.0.1:9090/api/v1/targets", final_url.as_str());
    }

    #[test]
    fn test_proxied_url_finalization() {
        let s = String::from("http://proxy.example.com/prometheus");
        let url = s.to_base_url().unwrap();
        let final_url = build_final_url(url, "api/v1/targets");
        assert_eq!(
            "http://proxy.example.com/prometheus/api/v1/targets",
            final_url.as_str()
        );
    }

    #[test]
    fn test_is_json() {
        let header = reqwest::header::HeaderValue::from_static("application/json");
        assert!(is_json(Some(&header)));
    }

    #[test]
    fn test_is_json_with_charset() {
        let header = reqwest::header::HeaderValue::from_static("application/json; charset=utf-8");
        assert!(is_json(Some(&header)));
    }

    #[test]
    fn test_duration_from_str() -> Result<(), anyhow::Error> {
        {
            let s = "1s";
            let expected = Duration {
                inner: TimeDuration::seconds(1),
                raw: "1s".to_string(),
            };
            assert_eq!(Duration::from_str(s)?, expected);
            assert_eq!(Into::<f64>::into(expected.clone()), 1.0);
            assert_eq!(Into::<i64>::into(expected), 1);
        }

        {
            let s = "-1s";
            let expected = Duration {
                inner: TimeDuration::seconds(-1),
                raw: "-1s".to_string(),
            };
            assert_eq!(Duration::from_str(s)?, expected);
            assert_eq!(Into::<f64>::into(expected.clone()), -1.0);
            assert_eq!(Into::<i64>::into(expected), -1);
        }

        {
            let s = "2m";
            let expected = Duration {
                inner: TimeDuration::seconds(120),
                raw: "2m".to_string(),
            };
            assert_eq!(Duration::from_str(s)?, expected);
            assert_eq!(Into::<f64>::into(expected.clone()), 120.0);
            assert_eq!(Into::<i64>::into(expected), 120);
        }

        {
            let s = "-2m";
            let expected = Duration {
                inner: TimeDuration::seconds(-120),
                raw: "-2m".to_string(),
            };
            assert_eq!(Duration::from_str(s)?, expected);
            assert_eq!(Into::<f64>::into(expected.clone()), -120.0);
            assert_eq!(Into::<i64>::into(expected), -120);
        }

        {
            let s = "1ms";
            let expected = Duration {
                inner: TimeDuration::milliseconds(1),
                raw: "1ms".to_string(),
            };
            assert_eq!(Duration::from_str(s)?, expected);
            assert_eq!(Into::<f64>::into(expected.clone()), 0.001);
            assert_eq!(Into::<i64>::into(expected), 0);
        }

        {
            let s = "-1ms";
            let expected = Duration {
                inner: TimeDuration::milliseconds(-1),
                raw: "-1ms".to_string(),
            };
            assert_eq!(Duration::from_str(s)?, expected);
            assert_eq!(Into::<f64>::into(expected.clone()), -0.001);
            assert_eq!(Into::<i64>::into(expected), 0);
        }

        {
            let s = "-2h";
            let expected = Duration {
                inner: TimeDuration::seconds(-7200),
                raw: "-2h".to_string(),
            };
            assert_eq!(Duration::from_str(s)?, expected);
            assert_eq!(Into::<f64>::into(expected.clone()), -7200.0);
            assert_eq!(Into::<i64>::into(expected), -7200);
        }

        {
            let s = "1h30m";
            let expected = Duration {
                inner: TimeDuration::seconds(5400),
                raw: "1h30m".to_string(),
            };
            assert_eq!(Duration::from_str(s)?, expected);
            assert_eq!(Into::<f64>::into(expected.clone()), 5400.0);
            assert_eq!(Into::<i64>::into(expected), 5400);
        }

        {
            let s = "12h34m56s";
            let expected = Duration {
                inner: TimeDuration::seconds(45296),
                raw: "12h34m56s".to_string(),
            };
            assert_eq!(Duration::from_str(s)?, expected);
            assert_eq!(Into::<f64>::into(expected.clone()), 45296.0);
            assert_eq!(Into::<i64>::into(expected), 45296);
        }

        {
            let s = "54s321ms";
            let expected = Duration {
                inner: TimeDuration::saturating_seconds_f64(54.321),
                raw: "54s321ms".to_string(),
            };
            assert_eq!(Duration::from_str(s)?, expected);
            assert_eq!(Into::<f64>::into(expected.clone()), 54.321);
            assert_eq!(Into::<i64>::into(expected), 54);
        }

        Ok(())
    }

    #[test]
    fn test_duration_from_f64() -> Result<(), anyhow::Error> {
        {
            let f = 50.312;
            let expected = Duration {
                inner: TimeDuration::saturating_seconds_f64(50.312),
                raw: "50s312ms".to_string(),
            };
            assert_eq!(Duration::from(f), expected);
            assert_eq!(Into::<f64>::into(expected.clone()), 50.312);
            assert_eq!(Into::<i64>::into(expected), 50);
        }

        {
            let f = 1000.0;
            let expected = Duration {
                inner: TimeDuration::saturating_seconds_f64(1000.0),
                raw: "16m40s".to_string(),
            };
            assert_eq!(Duration::from(f), expected);
            assert_eq!(Into::<f64>::into(expected.clone()), 1000.0);
            assert_eq!(Into::<i64>::into(expected), 1000);
        }

        {
            let f = 2650034.1;
            let expected = Duration {
                inner: TimeDuration::saturating_seconds_f64(2650034.1),
                raw: "4w2d16h7m14s100ms".to_string(),
            };
            assert_eq!(Duration::from(f), expected);
            assert_eq!(Into::<f64>::into(expected.clone()), 2650034.1);
            assert_eq!(Into::<i64>::into(expected), 2650034);
        }

        {
            let f = 0.000001;
            let expected = Duration {
                inner: TimeDuration::saturating_seconds_f64(0.000001),
                raw: "0ms".to_string(),
            };
            assert_eq!(Duration::from(f), expected);
            assert_eq!(Into::<f64>::into(expected.clone()), 0.000001);
            assert_eq!(Into::<i64>::into(expected), 0);
        }

        Ok(())
    }
}