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 s
90}
91
92#[derive(Clone, Debug, Eq, PartialEq)]
126pub struct Duration {
127 pub(crate) inner: TimeDuration,
128 raw: String,
129}
130
131impl FromStr for Duration {
132 type Err = Error;
133
134 fn from_str(s: &str) -> Result<Self, Self::Err> {
135 let mut total_milliseconds: i64 = 0;
136
137 let mut raw_num = String::new();
140
141 let mut duration_iter = s.chars().peekable();
144
145 let is_neg = duration_iter.next_if_eq(&'-').is_some();
149
150 while let Some(item) = duration_iter.next() {
151 if ('0'..='9').contains(&item) {
152 raw_num.push(item);
153 continue;
154 }
155
156 let num = raw_num.parse::<i64>().map_err(Error::ParseInt)?;
157
158 let factor = match item {
159 'y' => 1000 * 60 * 60 * 24 * 365,
160 'w' => 1000 * 60 * 60 * 24 * 7,
161 'd' => 1000 * 60 * 60 * 24,
162 'h' => 1000 * 60 * 60,
163 'm' => {
164 if duration_iter.next_if_eq(&'s').is_some() {
165 1
166 } else {
167 1000 * 60
168 }
169 }
170 's' => 1000,
171 _ => return Err(Error::Parse(format!("invalid time duration: {}", s))),
172 };
173
174 if is_neg {
175 total_milliseconds -= num * factor;
176 } else {
177 total_milliseconds += num * factor;
178 }
179
180 raw_num.clear();
181 }
182
183 Ok(Self {
184 inner: TimeDuration::milliseconds(total_milliseconds),
185 raw: s.to_string(),
186 })
187 }
188}
189
190impl fmt::Display for Duration {
191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192 f.write_str(&self.raw)
193 }
194}
195
196impl TryFrom<String> for Duration {
197 type Error = Error;
198
199 fn try_from(s: String) -> Result<Self, Self::Error> {
200 Self::from_str(&s)
201 }
202}
203
204impl From<f64> for Duration {
228 fn from(f: f64) -> Self {
229 let inner = TimeDuration::saturating_seconds_f64(f);
230
231 let raw = time_duration_to_string(inner);
232
233 Self { raw, inner }
234 }
235}
236
237impl Into<f64> for Duration {
238 fn into(self) -> f64 {
239 self.inner.as_seconds_f64()
240 }
241}
242
243impl From<i64> for Duration {
267 fn from(s: i64) -> Self {
268 let inner = TimeDuration::seconds(s);
269
270 let raw = time_duration_to_string(inner);
271
272 Self { raw, inner }
273 }
274}
275
276impl Into<i64> for Duration {
277 fn into(self) -> i64 {
278 self.inner.whole_seconds()
279 }
280}
281
282#[derive(Clone, Copy, Debug)]
284pub enum TargetState {
285 Active,
286 Dropped,
287 Any,
288}
289
290impl fmt::Display for TargetState {
291 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
292 match self {
293 Self::Active => f.write_str("active"),
294 Self::Dropped => f.write_str("dropped"),
295 Self::Any => f.write_str("any"),
296 }
297 }
298}
299
300impl FromStr for TargetState {
301 type Err = Error;
302
303 fn from_str(s: &str) -> Result<Self, Self::Err> {
304 match s {
305 "active" => Ok(Self::Active),
306 "dropped" => Ok(Self::Dropped),
307 "any" => Ok(Self::Any),
308 _ => Err(Error::Parse(format!(
309 "failed to parse target state from '{}', must be one of 'active', 'dropped', 'any'",
310 s
311 ))),
312 }
313 }
314}
315
316#[derive(Debug, Copy, Clone, Deserialize, Eq, PartialEq)]
318pub enum TargetHealth {
319 #[serde(alias = "up")]
320 Up,
321 #[serde(alias = "down")]
322 Down,
323 #[serde(alias = "unknown")]
324 Unknown,
325}
326
327impl TargetHealth {
328 pub fn is_up(&self) -> bool {
329 *self == Self::Up
330 }
331
332 pub fn is_down(&self) -> bool {
333 *self == Self::Down
334 }
335
336 pub fn is_unknown(&self) -> bool {
337 *self == Self::Unknown
338 }
339}
340
341impl fmt::Display for TargetHealth {
342 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
343 match self {
344 Self::Up => f.write_str("up"),
345 Self::Down => f.write_str("down"),
346 Self::Unknown => f.write_str("unknown"),
347 }
348 }
349}
350
351#[derive(Debug, Copy, Clone, Deserialize, Eq, PartialEq)]
353pub enum RuleHealth {
354 #[serde(alias = "ok")]
355 Good,
356 #[serde(alias = "err")]
357 Bad,
358 #[serde(alias = "unknown")]
359 Unknown,
360}
361
362impl RuleHealth {
363 pub fn is_good(&self) -> bool {
364 *self == Self::Good
365 }
366
367 pub fn is_bad(&self) -> bool {
368 *self == Self::Bad
369 }
370
371 pub fn is_unknown(&self) -> bool {
372 *self == Self::Unknown
373 }
374}
375
376impl fmt::Display for RuleHealth {
377 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
378 match self {
379 Self::Good => f.write_str("ok"),
380 Self::Bad => f.write_str("err"),
381 Self::Unknown => f.write_str("unknown"),
382 }
383 }
384}
385
386#[derive(Debug, Copy, Clone, Deserialize, Eq, PartialEq)]
388pub enum AlertState {
389 #[serde(alias = "inactive")]
390 Inactive,
391 #[serde(alias = "pending")]
392 Pending,
393 #[serde(alias = "firing")]
394 Firing,
395}
396
397impl AlertState {
398 pub fn is_inactive(&self) -> bool {
399 *self == Self::Inactive
400 }
401
402 pub fn is_pending(&self) -> bool {
403 *self == Self::Pending
404 }
405
406 pub fn is_firing(&self) -> bool {
407 *self == Self::Firing
408 }
409}
410
411impl fmt::Display for AlertState {
412 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
413 match self {
414 Self::Inactive => f.write_str("inactive"),
415 Self::Pending => f.write_str("pending"),
416 Self::Firing => f.write_str("firing"),
417 }
418 }
419}
420
421#[derive(Copy, Clone, Debug)]
423pub enum RuleKind {
424 Alerting,
425 Recording,
426}
427
428impl RuleKind {
429 pub(crate) fn to_query_param(&self) -> String {
430 match self {
431 Self::Alerting => String::from("alert"),
432 Self::Recording => String::from("record"),
433 }
434 }
435}
436
437impl fmt::Display for RuleKind {
438 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
439 match self {
440 Self::Alerting => f.write_str("alerting"),
441 Self::Recording => f.write_str("recording"),
442 }
443 }
444}
445
446impl FromStr for RuleKind {
447 type Err = Error;
448
449 fn from_str(s: &str) -> Result<Self, Self::Err> {
450 match s {
451 "alert"| "alerting" => Ok(Self::Alerting),
452 "record"| "recording" => Ok(Self::Recording),
453 _ => Err(Error::Parse(format!("failed to parse rule type from '{}', must be one of 'alert', 'alerting', 'record', 'recording'", s)))
454 }
455 }
456}
457
458#[allow(clippy::enum_variant_names)]
459#[derive(Debug, Clone, PartialEq)]
460pub(crate) enum Label<'a> {
461 Equal((&'a str, &'a str)),
462 NotEqual((&'a str, &'a str)),
463 RegexEqual((&'a str, &'a str)),
464 RegexNotEqual((&'a str, &'a str)),
465}
466
467impl<'a> fmt::Display for Label<'a> {
468 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
469 match self {
470 Self::Equal((k, v)) => write!(f, "{}=\"{}\"", k, v),
471 Self::NotEqual((k, v)) => write!(f, "{}!=\"{}\"", k, v),
472 Self::RegexEqual((k, v)) => write!(f, "{}=~\"{}\"", k, v),
473 Self::RegexNotEqual((k, v)) => write!(f, "{}!~\"{}\"", k, v),
474 }
475 }
476}
477
478pub(crate) trait ToBaseUrl {
483 fn to_base_url(self) -> Result<Url, Error>;
484}
485
486impl ToBaseUrl for &str {
487 fn to_base_url(self) -> Result<Url, Error> {
488 Url::parse(self).map_err(|source| {
489 Error::ParseUrl(ParseUrlError {
490 message: "failed to build Prometheus server base URL",
491 source,
492 })
493 })
494 }
495}
496
497impl ToBaseUrl for String {
498 fn to_base_url(self) -> Result<Url, Error> {
499 Url::parse(&self).map_err(|source| {
500 Error::ParseUrl(ParseUrlError {
501 message: "failed to build Prometheus server base URL",
502 source,
503 })
504 })
505 }
506}
507
508pub(crate) fn build_final_url(mut url: Url, path: &str) -> Url {
509 let base_path = url.path();
510 match base_path {
511 "/" => return url.join(path).unwrap(),
512 _ => {
513 let p = format!("{}/{}", base_path, path);
514 url.set_path(&p);
515 }
516 }
517 url
518}
519
520pub(crate) fn is_json(v: Option<&HeaderValue>) -> bool {
521 match v
522 .and_then(|h| h.to_str().ok())
523 .and_then(|h| h.parse::<Mime>().ok())
524 {
525 Some(mime) => match (mime.type_(), mime.subtype()) {
526 (mime::APPLICATION, mime::JSON) => true,
527 _ => false,
528 },
529 None => false,
530 }
531}
532
533#[cfg(test)]
534mod tests {
535 use super::{build_final_url, is_json, Duration, ToBaseUrl};
536 use std::str::FromStr;
537 use time::Duration as TimeDuration;
538
539 #[test]
540 fn test_simple_str_to_url() {
541 let s = "http://127.0.0.1:9090";
542 let url = s.to_base_url().unwrap();
543 assert_eq!("http://127.0.0.1:9090/", url.as_str());
544 }
545
546 #[test]
547 fn test_proxied_str_to_url() {
548 let s = "http://proxy.example.com/prometheus";
549 let url = s.to_base_url().unwrap();
550 assert_eq!("http://proxy.example.com/prometheus", url.as_str());
551 }
552
553 #[test]
554 fn test_simple_string_to_url() {
555 let s = String::from("http://127.0.0.1:9090");
556 let url = s.to_base_url().unwrap();
557 assert_eq!("http://127.0.0.1:9090/", url.as_str());
558 }
559
560 #[test]
561 fn test_proxied_string_to_url() {
562 let s = String::from("http://proxy.example.com/prometheus");
563 let url = s.to_base_url().unwrap();
564 assert_eq!("http://proxy.example.com/prometheus", url.as_str());
565 }
566
567 #[test]
568 fn test_simple_url_finalization() {
569 let s = String::from("http://127.0.0.1:9090");
570 let url = s.to_base_url().unwrap();
571 let final_url = build_final_url(url, "api/v1/targets");
572 assert_eq!("http://127.0.0.1:9090/api/v1/targets", final_url.as_str());
573 }
574
575 #[test]
576 fn test_proxied_url_finalization() {
577 let s = String::from("http://proxy.example.com/prometheus");
578 let url = s.to_base_url().unwrap();
579 let final_url = build_final_url(url, "api/v1/targets");
580 assert_eq!(
581 "http://proxy.example.com/prometheus/api/v1/targets",
582 final_url.as_str()
583 );
584 }
585
586 #[test]
587 fn test_is_json() {
588 let header = reqwest::header::HeaderValue::from_static("application/json");
589 assert!(is_json(Some(&header)));
590 }
591
592 #[test]
593 fn test_is_json_with_charset() {
594 let header = reqwest::header::HeaderValue::from_static("application/json; charset=utf-8");
595 assert!(is_json(Some(&header)));
596 }
597
598 #[test]
599 fn test_duration_from_str() -> Result<(), anyhow::Error> {
600 {
601 let s = "1s";
602 let expected = Duration {
603 inner: TimeDuration::seconds(1),
604 raw: "1s".to_string(),
605 };
606 assert_eq!(Duration::from_str(s)?, expected);
607 assert_eq!(Into::<f64>::into(expected.clone()), 1.0);
608 assert_eq!(Into::<i64>::into(expected), 1);
609 }
610
611 {
612 let s = "-1s";
613 let expected = Duration {
614 inner: TimeDuration::seconds(-1),
615 raw: "-1s".to_string(),
616 };
617 assert_eq!(Duration::from_str(s)?, expected);
618 assert_eq!(Into::<f64>::into(expected.clone()), -1.0);
619 assert_eq!(Into::<i64>::into(expected), -1);
620 }
621
622 {
623 let s = "2m";
624 let expected = Duration {
625 inner: TimeDuration::seconds(120),
626 raw: "2m".to_string(),
627 };
628 assert_eq!(Duration::from_str(s)?, expected);
629 assert_eq!(Into::<f64>::into(expected.clone()), 120.0);
630 assert_eq!(Into::<i64>::into(expected), 120);
631 }
632
633 {
634 let s = "-2m";
635 let expected = Duration {
636 inner: TimeDuration::seconds(-120),
637 raw: "-2m".to_string(),
638 };
639 assert_eq!(Duration::from_str(s)?, expected);
640 assert_eq!(Into::<f64>::into(expected.clone()), -120.0);
641 assert_eq!(Into::<i64>::into(expected), -120);
642 }
643
644 {
645 let s = "1ms";
646 let expected = Duration {
647 inner: TimeDuration::milliseconds(1),
648 raw: "1ms".to_string(),
649 };
650 assert_eq!(Duration::from_str(s)?, expected);
651 assert_eq!(Into::<f64>::into(expected.clone()), 0.001);
652 assert_eq!(Into::<i64>::into(expected), 0);
653 }
654
655 {
656 let s = "-1ms";
657 let expected = Duration {
658 inner: TimeDuration::milliseconds(-1),
659 raw: "-1ms".to_string(),
660 };
661 assert_eq!(Duration::from_str(s)?, expected);
662 assert_eq!(Into::<f64>::into(expected.clone()), -0.001);
663 assert_eq!(Into::<i64>::into(expected), 0);
664 }
665
666 {
667 let s = "-2h";
668 let expected = Duration {
669 inner: TimeDuration::seconds(-7200),
670 raw: "-2h".to_string(),
671 };
672 assert_eq!(Duration::from_str(s)?, expected);
673 assert_eq!(Into::<f64>::into(expected.clone()), -7200.0);
674 assert_eq!(Into::<i64>::into(expected), -7200);
675 }
676
677 {
678 let s = "1h30m";
679 let expected = Duration {
680 inner: TimeDuration::seconds(5400),
681 raw: "1h30m".to_string(),
682 };
683 assert_eq!(Duration::from_str(s)?, expected);
684 assert_eq!(Into::<f64>::into(expected.clone()), 5400.0);
685 assert_eq!(Into::<i64>::into(expected), 5400);
686 }
687
688 {
689 let s = "12h34m56s";
690 let expected = Duration {
691 inner: TimeDuration::seconds(45296),
692 raw: "12h34m56s".to_string(),
693 };
694 assert_eq!(Duration::from_str(s)?, expected);
695 assert_eq!(Into::<f64>::into(expected.clone()), 45296.0);
696 assert_eq!(Into::<i64>::into(expected), 45296);
697 }
698
699 {
700 let s = "54s321ms";
701 let expected = Duration {
702 inner: TimeDuration::saturating_seconds_f64(54.321),
703 raw: "54s321ms".to_string(),
704 };
705 assert_eq!(Duration::from_str(s)?, expected);
706 assert_eq!(Into::<f64>::into(expected.clone()), 54.321);
707 assert_eq!(Into::<i64>::into(expected), 54);
708 }
709
710 Ok(())
711 }
712
713 #[test]
714 fn test_duration_from_f64() -> Result<(), anyhow::Error> {
715 {
716 let f = 50.312;
717 let expected = Duration {
718 inner: TimeDuration::saturating_seconds_f64(50.312),
719 raw: "50s312ms".to_string(),
720 };
721 assert_eq!(Duration::from(f), expected);
722 assert_eq!(Into::<f64>::into(expected.clone()), 50.312);
723 assert_eq!(Into::<i64>::into(expected), 50);
724 }
725
726 {
727 let f = 1000.0;
728 let expected = Duration {
729 inner: TimeDuration::saturating_seconds_f64(1000.0),
730 raw: "16m40s".to_string(),
731 };
732 assert_eq!(Duration::from(f), expected);
733 assert_eq!(Into::<f64>::into(expected.clone()), 1000.0);
734 assert_eq!(Into::<i64>::into(expected), 1000);
735 }
736
737 {
738 let f = 2650034.1;
739 let expected = Duration {
740 inner: TimeDuration::saturating_seconds_f64(2650034.1),
741 raw: "4w2d16h7m14s100ms".to_string(),
742 };
743 assert_eq!(Duration::from(f), expected);
744 assert_eq!(Into::<f64>::into(expected.clone()), 2650034.1);
745 assert_eq!(Into::<i64>::into(expected), 2650034);
746 }
747
748 Ok(())
749 }
750}