Skip to main content

prometheus_http_query/
util.rs

1use crate::error::{Error, ParseUrlError};
2use mime::Mime;
3use reqwest::header::HeaderValue;
4use serde::Deserialize;
5use std::{fmt, str::FromStr};
6use time::Duration as TimeDuration;
7use url::Url;
8
9fn time_duration_to_string(mut duration: TimeDuration) -> String {
10    let mut s = String::new();
11
12    if duration.is_negative() {
13        s.push('-');
14    }
15
16    {
17        let d = TimeDuration::weeks(duration.whole_weeks());
18
19        let years = (d / TimeDuration::weeks(12)).floor() as i64;
20
21        if years >= 1 {
22            let d = TimeDuration::weeks(12 * years);
23            s.push_str(&d.to_string());
24            s.push('y');
25            duration -= d;
26        }
27    }
28
29    {
30        let d = TimeDuration::weeks(duration.whole_weeks());
31
32        if !d.is_zero() {
33            s.push_str(&d.whole_weeks().to_string());
34            s.push('w');
35            duration -= d;
36        }
37    }
38
39    {
40        let d = TimeDuration::days(duration.whole_days());
41
42        if !d.is_zero() {
43            s.push_str(&d.whole_days().to_string());
44            s.push('d');
45            duration -= d;
46        }
47    }
48
49    {
50        let d = TimeDuration::hours(duration.whole_hours());
51
52        if !d.is_zero() {
53            s.push_str(&d.whole_hours().to_string());
54            s.push('h');
55            duration -= d;
56        }
57    }
58
59    {
60        let d = TimeDuration::minutes(duration.whole_minutes());
61
62        if !d.is_zero() {
63            s.push_str(&d.whole_minutes().to_string());
64            s.push('m');
65            duration -= d;
66        }
67    }
68
69    {
70        let d = TimeDuration::seconds(duration.whole_seconds());
71
72        if !d.is_zero() {
73            s.push_str(&d.whole_seconds().to_string());
74            s.push('s');
75            duration -= d;
76        }
77    }
78
79    {
80        let d = TimeDuration::milliseconds(duration.whole_milliseconds() as i64);
81
82        if !d.is_zero() {
83            s.push_str(&d.whole_milliseconds().to_string());
84            s.push_str("ms");
85            duration -= d;
86        }
87    }
88
89    // Sub-millisecond durations cannot be expressed. Thus when the
90    // string is still empty we return a hardcoded value to account
91    // for the missing precision.
92    if s.is_empty() {
93        String::from("0ms")
94    } else {
95        s
96    }
97}
98
99/// A wrapper around [`time::Duration`] that is used to deserialize
100/// responses or verify time durations before sending them to Prometheus.
101///
102/// ```rust
103/// use prometheus_http_query::{Duration, Client};
104/// use std::str::FromStr;
105///
106/// #[tokio::main(flavor = "current_thread")]
107/// async fn main() -> Result<(), anyhow::Error> {
108///     let client = Client::default();
109///
110///     let q = "prometheus_http_requests_total";
111///     let d = Duration::from_str("1m")?;
112///
113///     // Use parsed duration by converting to `f64`.
114///     let response = client.query_range(q, 1648373100, 1648373300, d.into()).get().await?;
115///
116///     assert!(response.data().as_matrix().is_some());
117///
118///     // Durations converted from numeric types can also be printed back to
119///     // a Prometheus duration string.
120///     let d = Duration::from(50.312);
121///     assert_eq!(&d.to_string(), "50s312ms");
122///
123///     // However durations that were parsed from a string retain their original
124///     // string representation, even when they could be expressed more succinctly.
125///     // For example this could also be "2m".
126///     let d = Duration::from_str("120s")?;
127///     assert_eq!(&d.to_string(), "120s");
128///
129///     Ok(())
130/// }
131/// ```
132#[derive(Clone, Debug, Eq, PartialEq)]
133pub struct Duration {
134    pub(crate) inner: TimeDuration,
135    raw: String,
136}
137
138impl FromStr for Duration {
139    type Err = Error;
140
141    fn from_str(s: &str) -> Result<Self, Self::Err> {
142        let mut total_milliseconds: i64 = 0;
143
144        // Add each number character to a string until a unit character is encountered.
145        // This string is then cleared to process the next number + unit.
146        let mut raw_num = String::new();
147
148        // Iterate the duration string, convert each unit to nanoseconds and add
149        // it to the total.
150        let mut duration_iter = s.chars().peekable();
151
152        // Check for minus sign. It can be safely ignored at this point and the first
153        // number parsed as a positive integer because any of the following
154        // multiplications will switch the sign automatically.
155        let is_neg = duration_iter.next_if_eq(&'-').is_some();
156
157        while let Some(item) = duration_iter.next() {
158            if ('0'..='9').contains(&item) {
159                raw_num.push(item);
160                continue;
161            }
162
163            let num = raw_num.parse::<i64>().map_err(Error::ParseInt)?;
164
165            let factor = match item {
166                'y' => 1000 * 60 * 60 * 24 * 365,
167                'w' => 1000 * 60 * 60 * 24 * 7,
168                'd' => 1000 * 60 * 60 * 24,
169                'h' => 1000 * 60 * 60,
170                'm' => {
171                    if duration_iter.next_if_eq(&'s').is_some() {
172                        1
173                    } else {
174                        1000 * 60
175                    }
176                }
177                's' => 1000,
178                _ => return Err(Error::Parse(format!("invalid time duration: {}", s))),
179            };
180
181            if is_neg {
182                total_milliseconds -= num * factor;
183            } else {
184                total_milliseconds += num * factor;
185            }
186
187            raw_num.clear();
188        }
189
190        Ok(Self {
191            inner: TimeDuration::milliseconds(total_milliseconds),
192            raw: s.to_string(),
193        })
194    }
195}
196
197impl fmt::Display for Duration {
198    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199        f.write_str(&self.raw)
200    }
201}
202
203impl TryFrom<String> for Duration {
204    type Error = Error;
205
206    fn try_from(s: String) -> Result<Self, Self::Error> {
207        Self::from_str(&s)
208    }
209}
210
211/// Convert fractional seconds to `Duration`.
212///
213/// ```rust
214/// use prometheus_http_query::Duration;
215/// use std::str::FromStr;
216///
217/// #[tokio::main(flavor = "current_thread")]
218/// async fn main() -> Result<(), anyhow::Error> {
219///     {
220///         let a = Duration::from_str("1s")?;
221///         let b = Duration::from(1.0);
222///         assert_eq!(a, b);
223///     }
224///
225///     {
226///         let a = Duration::from_str("312ms")?;
227///         let b = Duration::from(0.312);
228///         assert_eq!(a, b);
229///     }
230///
231///     Ok(())
232/// }
233/// ```
234impl From<f64> for Duration {
235    fn from(f: f64) -> Self {
236        let inner = TimeDuration::saturating_seconds_f64(f);
237
238        let raw = time_duration_to_string(inner);
239
240        Self { raw, inner }
241    }
242}
243
244impl Into<f64> for Duration {
245    fn into(self) -> f64 {
246        self.inner.as_seconds_f64()
247    }
248}
249
250/// Convert seconds to `Duration`.
251///
252/// ```rust
253/// use prometheus_http_query::Duration;
254/// use std::str::FromStr;
255///
256/// #[tokio::main(flavor = "current_thread")]
257/// async fn main() -> Result<(), anyhow::Error> {
258///     {
259///         let a = Duration::from_str("2m")?;
260///         let b = Duration::from(120);
261///         assert_eq!(a, b);
262///     }
263///
264///     {
265///         let a = Duration::from_str("1h")?;
266///         let b = Duration::from(3600);
267///         assert_eq!(a, b);
268///     }
269///
270///     Ok(())
271/// }
272/// ```
273impl From<i64> for Duration {
274    fn from(s: i64) -> Self {
275        let inner = TimeDuration::seconds(s);
276
277        let raw = time_duration_to_string(inner);
278
279        Self { raw, inner }
280    }
281}
282
283impl Into<i64> for Duration {
284    fn into(self) -> i64 {
285        self.inner.whole_seconds()
286    }
287}
288
289/// A helper enum to filter targets by state.
290#[derive(Clone, Copy, Debug)]
291pub enum TargetState {
292    Active,
293    Dropped,
294    Any,
295}
296
297impl fmt::Display for TargetState {
298    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
299        match self {
300            Self::Active => f.write_str("active"),
301            Self::Dropped => f.write_str("dropped"),
302            Self::Any => f.write_str("any"),
303        }
304    }
305}
306
307impl FromStr for TargetState {
308    type Err = Error;
309
310    fn from_str(s: &str) -> Result<Self, Self::Err> {
311        match s {
312            "active" => Ok(Self::Active),
313            "dropped" => Ok(Self::Dropped),
314            "any" => Ok(Self::Any),
315            _ => Err(Error::Parse(format!(
316                "failed to parse target state from '{}', must be one of 'active', 'dropped', 'any'",
317                s
318            ))),
319        }
320    }
321}
322
323/// A helper enum to represent possible target health states.
324#[derive(Debug, Copy, Clone, Deserialize, Eq, PartialEq)]
325pub enum TargetHealth {
326    #[serde(alias = "up")]
327    Up,
328    #[serde(alias = "down")]
329    Down,
330    #[serde(alias = "unknown")]
331    Unknown,
332}
333
334impl TargetHealth {
335    pub fn is_up(&self) -> bool {
336        *self == Self::Up
337    }
338
339    pub fn is_down(&self) -> bool {
340        *self == Self::Down
341    }
342
343    pub fn is_unknown(&self) -> bool {
344        *self == Self::Unknown
345    }
346}
347
348impl fmt::Display for TargetHealth {
349    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350        match self {
351            Self::Up => f.write_str("up"),
352            Self::Down => f.write_str("down"),
353            Self::Unknown => f.write_str("unknown"),
354        }
355    }
356}
357
358/// A helper enum to represent possible rule health states.
359#[derive(Debug, Copy, Clone, Deserialize, Eq, PartialEq)]
360pub enum RuleHealth {
361    #[serde(alias = "ok")]
362    Good,
363    #[serde(alias = "err")]
364    Bad,
365    #[serde(alias = "unknown")]
366    Unknown,
367}
368
369impl RuleHealth {
370    pub fn is_good(&self) -> bool {
371        *self == Self::Good
372    }
373
374    pub fn is_bad(&self) -> bool {
375        *self == Self::Bad
376    }
377
378    pub fn is_unknown(&self) -> bool {
379        *self == Self::Unknown
380    }
381}
382
383impl fmt::Display for RuleHealth {
384    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
385        match self {
386            Self::Good => f.write_str("ok"),
387            Self::Bad => f.write_str("err"),
388            Self::Unknown => f.write_str("unknown"),
389        }
390    }
391}
392
393/// A helper type to represent possible rule health states.
394#[derive(Debug, Copy, Clone, Deserialize, Eq, PartialEq)]
395pub enum AlertState {
396    #[serde(alias = "inactive")]
397    Inactive,
398    #[serde(alias = "pending")]
399    Pending,
400    #[serde(alias = "firing")]
401    Firing,
402}
403
404impl AlertState {
405    pub fn is_inactive(&self) -> bool {
406        *self == Self::Inactive
407    }
408
409    pub fn is_pending(&self) -> bool {
410        *self == Self::Pending
411    }
412
413    pub fn is_firing(&self) -> bool {
414        *self == Self::Firing
415    }
416}
417
418impl fmt::Display for AlertState {
419    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
420        match self {
421            Self::Inactive => f.write_str("inactive"),
422            Self::Pending => f.write_str("pending"),
423            Self::Firing => f.write_str("firing"),
424        }
425    }
426}
427
428/// A helper enum to filter rules by type.
429#[derive(Copy, Clone, Debug)]
430pub enum RuleKind {
431    Alerting,
432    Recording,
433}
434
435impl RuleKind {
436    pub(crate) fn to_query_param(&self) -> String {
437        match self {
438            Self::Alerting => String::from("alert"),
439            Self::Recording => String::from("record"),
440        }
441    }
442}
443
444impl fmt::Display for RuleKind {
445    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
446        match self {
447            Self::Alerting => f.write_str("alerting"),
448            Self::Recording => f.write_str("recording"),
449        }
450    }
451}
452
453impl FromStr for RuleKind {
454    type Err = Error;
455
456    fn from_str(s: &str) -> Result<Self, Self::Err> {
457        match s {
458            "alert"| "alerting" => Ok(Self::Alerting),
459            "record"| "recording" => Ok(Self::Recording),
460            _ => Err(Error::Parse(format!("failed to parse rule type from '{}', must be one of 'alert', 'alerting', 'record', 'recording'", s)))
461        }
462    }
463}
464
465#[allow(clippy::enum_variant_names)]
466#[derive(Debug, Clone, PartialEq)]
467pub(crate) enum Label<'a> {
468    Equal((&'a str, &'a str)),
469    NotEqual((&'a str, &'a str)),
470    RegexEqual((&'a str, &'a str)),
471    RegexNotEqual((&'a str, &'a str)),
472}
473
474impl<'a> fmt::Display for Label<'a> {
475    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
476        match self {
477            Self::Equal((k, v)) => write!(f, "{}=\"{}\"", k, v),
478            Self::NotEqual((k, v)) => write!(f, "{}!=\"{}\"", k, v),
479            Self::RegexEqual((k, v)) => write!(f, "{}=~\"{}\"", k, v),
480            Self::RegexNotEqual((k, v)) => write!(f, "{}!~\"{}\"", k, v),
481        }
482    }
483}
484
485/// Create a base URL that is common to all queries from a string literal.
486/// The implementations are probably a little more complicated than they need
487/// to be as we need to allocate a new string during the URL construction
488/// to preserve a possibly existing path component in the source string.
489pub(crate) trait ToBaseUrl {
490    fn to_base_url(self) -> Result<Url, Error>;
491}
492
493impl ToBaseUrl for &str {
494    fn to_base_url(self) -> Result<Url, Error> {
495        Url::parse(self).map_err(|source| {
496            Error::ParseUrl(ParseUrlError {
497                message: "failed to build Prometheus server base URL",
498                source,
499            })
500        })
501    }
502}
503
504impl ToBaseUrl for String {
505    fn to_base_url(self) -> Result<Url, Error> {
506        Url::parse(&self).map_err(|source| {
507            Error::ParseUrl(ParseUrlError {
508                message: "failed to build Prometheus server base URL",
509                source,
510            })
511        })
512    }
513}
514
515pub(crate) fn build_final_url(mut url: Url, path: &str) -> Url {
516    let base_path = url.path();
517    match base_path {
518        "/" => return url.join(path).unwrap(),
519        _ => {
520            let p = format!("{}/{}", base_path, path);
521            url.set_path(&p);
522        }
523    }
524    url
525}
526
527pub(crate) fn is_json(v: Option<&HeaderValue>) -> bool {
528    match v
529        .and_then(|h| h.to_str().ok())
530        .and_then(|h| h.parse::<Mime>().ok())
531    {
532        Some(mime) => match (mime.type_(), mime.subtype()) {
533            (mime::APPLICATION, mime::JSON) => true,
534            _ => false,
535        },
536        None => false,
537    }
538}
539
540#[cfg(test)]
541mod tests {
542    use super::{build_final_url, is_json, Duration, ToBaseUrl};
543    use std::str::FromStr;
544    use time::Duration as TimeDuration;
545
546    #[test]
547    fn test_simple_str_to_url() {
548        let s = "http://127.0.0.1:9090";
549        let url = s.to_base_url().unwrap();
550        assert_eq!("http://127.0.0.1:9090/", url.as_str());
551    }
552
553    #[test]
554    fn test_proxied_str_to_url() {
555        let s = "http://proxy.example.com/prometheus";
556        let url = s.to_base_url().unwrap();
557        assert_eq!("http://proxy.example.com/prometheus", url.as_str());
558    }
559
560    #[test]
561    fn test_simple_string_to_url() {
562        let s = String::from("http://127.0.0.1:9090");
563        let url = s.to_base_url().unwrap();
564        assert_eq!("http://127.0.0.1:9090/", url.as_str());
565    }
566
567    #[test]
568    fn test_proxied_string_to_url() {
569        let s = String::from("http://proxy.example.com/prometheus");
570        let url = s.to_base_url().unwrap();
571        assert_eq!("http://proxy.example.com/prometheus", url.as_str());
572    }
573
574    #[test]
575    fn test_simple_url_finalization() {
576        let s = String::from("http://127.0.0.1:9090");
577        let url = s.to_base_url().unwrap();
578        let final_url = build_final_url(url, "api/v1/targets");
579        assert_eq!("http://127.0.0.1:9090/api/v1/targets", final_url.as_str());
580    }
581
582    #[test]
583    fn test_proxied_url_finalization() {
584        let s = String::from("http://proxy.example.com/prometheus");
585        let url = s.to_base_url().unwrap();
586        let final_url = build_final_url(url, "api/v1/targets");
587        assert_eq!(
588            "http://proxy.example.com/prometheus/api/v1/targets",
589            final_url.as_str()
590        );
591    }
592
593    #[test]
594    fn test_is_json() {
595        let header = reqwest::header::HeaderValue::from_static("application/json");
596        assert!(is_json(Some(&header)));
597    }
598
599    #[test]
600    fn test_is_json_with_charset() {
601        let header = reqwest::header::HeaderValue::from_static("application/json; charset=utf-8");
602        assert!(is_json(Some(&header)));
603    }
604
605    #[test]
606    fn test_duration_from_str() -> Result<(), anyhow::Error> {
607        {
608            let s = "1s";
609            let expected = Duration {
610                inner: TimeDuration::seconds(1),
611                raw: "1s".to_string(),
612            };
613            assert_eq!(Duration::from_str(s)?, expected);
614            assert_eq!(Into::<f64>::into(expected.clone()), 1.0);
615            assert_eq!(Into::<i64>::into(expected), 1);
616        }
617
618        {
619            let s = "-1s";
620            let expected = Duration {
621                inner: TimeDuration::seconds(-1),
622                raw: "-1s".to_string(),
623            };
624            assert_eq!(Duration::from_str(s)?, expected);
625            assert_eq!(Into::<f64>::into(expected.clone()), -1.0);
626            assert_eq!(Into::<i64>::into(expected), -1);
627        }
628
629        {
630            let s = "2m";
631            let expected = Duration {
632                inner: TimeDuration::seconds(120),
633                raw: "2m".to_string(),
634            };
635            assert_eq!(Duration::from_str(s)?, expected);
636            assert_eq!(Into::<f64>::into(expected.clone()), 120.0);
637            assert_eq!(Into::<i64>::into(expected), 120);
638        }
639
640        {
641            let s = "-2m";
642            let expected = Duration {
643                inner: TimeDuration::seconds(-120),
644                raw: "-2m".to_string(),
645            };
646            assert_eq!(Duration::from_str(s)?, expected);
647            assert_eq!(Into::<f64>::into(expected.clone()), -120.0);
648            assert_eq!(Into::<i64>::into(expected), -120);
649        }
650
651        {
652            let s = "1ms";
653            let expected = Duration {
654                inner: TimeDuration::milliseconds(1),
655                raw: "1ms".to_string(),
656            };
657            assert_eq!(Duration::from_str(s)?, expected);
658            assert_eq!(Into::<f64>::into(expected.clone()), 0.001);
659            assert_eq!(Into::<i64>::into(expected), 0);
660        }
661
662        {
663            let s = "-1ms";
664            let expected = Duration {
665                inner: TimeDuration::milliseconds(-1),
666                raw: "-1ms".to_string(),
667            };
668            assert_eq!(Duration::from_str(s)?, expected);
669            assert_eq!(Into::<f64>::into(expected.clone()), -0.001);
670            assert_eq!(Into::<i64>::into(expected), 0);
671        }
672
673        {
674            let s = "-2h";
675            let expected = Duration {
676                inner: TimeDuration::seconds(-7200),
677                raw: "-2h".to_string(),
678            };
679            assert_eq!(Duration::from_str(s)?, expected);
680            assert_eq!(Into::<f64>::into(expected.clone()), -7200.0);
681            assert_eq!(Into::<i64>::into(expected), -7200);
682        }
683
684        {
685            let s = "1h30m";
686            let expected = Duration {
687                inner: TimeDuration::seconds(5400),
688                raw: "1h30m".to_string(),
689            };
690            assert_eq!(Duration::from_str(s)?, expected);
691            assert_eq!(Into::<f64>::into(expected.clone()), 5400.0);
692            assert_eq!(Into::<i64>::into(expected), 5400);
693        }
694
695        {
696            let s = "12h34m56s";
697            let expected = Duration {
698                inner: TimeDuration::seconds(45296),
699                raw: "12h34m56s".to_string(),
700            };
701            assert_eq!(Duration::from_str(s)?, expected);
702            assert_eq!(Into::<f64>::into(expected.clone()), 45296.0);
703            assert_eq!(Into::<i64>::into(expected), 45296);
704        }
705
706        {
707            let s = "54s321ms";
708            let expected = Duration {
709                inner: TimeDuration::saturating_seconds_f64(54.321),
710                raw: "54s321ms".to_string(),
711            };
712            assert_eq!(Duration::from_str(s)?, expected);
713            assert_eq!(Into::<f64>::into(expected.clone()), 54.321);
714            assert_eq!(Into::<i64>::into(expected), 54);
715        }
716
717        Ok(())
718    }
719
720    #[test]
721    fn test_duration_from_f64() -> Result<(), anyhow::Error> {
722        {
723            let f = 50.312;
724            let expected = Duration {
725                inner: TimeDuration::saturating_seconds_f64(50.312),
726                raw: "50s312ms".to_string(),
727            };
728            assert_eq!(Duration::from(f), expected);
729            assert_eq!(Into::<f64>::into(expected.clone()), 50.312);
730            assert_eq!(Into::<i64>::into(expected), 50);
731        }
732
733        {
734            let f = 1000.0;
735            let expected = Duration {
736                inner: TimeDuration::saturating_seconds_f64(1000.0),
737                raw: "16m40s".to_string(),
738            };
739            assert_eq!(Duration::from(f), expected);
740            assert_eq!(Into::<f64>::into(expected.clone()), 1000.0);
741            assert_eq!(Into::<i64>::into(expected), 1000);
742        }
743
744        {
745            let f = 2650034.1;
746            let expected = Duration {
747                inner: TimeDuration::saturating_seconds_f64(2650034.1),
748                raw: "4w2d16h7m14s100ms".to_string(),
749            };
750            assert_eq!(Duration::from(f), expected);
751            assert_eq!(Into::<f64>::into(expected.clone()), 2650034.1);
752            assert_eq!(Into::<i64>::into(expected), 2650034);
753        }
754
755        {
756            let f = 0.000001;
757            let expected = Duration {
758                inner: TimeDuration::saturating_seconds_f64(0.000001),
759                raw: "0ms".to_string(),
760            };
761            assert_eq!(Duration::from(f), expected);
762            assert_eq!(Into::<f64>::into(expected.clone()), 0.000001);
763            assert_eq!(Into::<i64>::into(expected), 0);
764        }
765
766        Ok(())
767    }
768}