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
9#[derive(Clone, Debug, Eq)]
31pub struct Duration {
32 pub(crate) inner: TimeDuration,
33 raw: String,
34}
35
36impl FromStr for Duration {
37 type Err = Error;
38
39 fn from_str(s: &str) -> Result<Self, Self::Err> {
40 let mut total_milliseconds: i64 = 0;
41
42 let mut raw_num = String::new();
45
46 let mut duration_iter = s.chars().peekable();
49
50 let is_neg = duration_iter.next_if_eq(&'-').is_some();
54
55 while let Some(item) = duration_iter.next() {
56 if ('0'..='9').contains(&item) {
57 raw_num.push(item);
58 continue;
59 }
60
61 let num = raw_num.parse::<i64>().map_err(Error::ParseInt)?;
62
63 let factor = match item {
64 'y' => 1000 * 60 * 60 * 24 * 365,
65 'w' => 1000 * 60 * 60 * 24 * 7,
66 'd' => 1000 * 60 * 60 * 24,
67 'h' => 1000 * 60 * 60,
68 'm' => {
69 if duration_iter.next_if_eq(&'s').is_some() {
70 1
71 } else {
72 1000 * 60
73 }
74 }
75 's' => 1000,
76 _ => return Err(Error::Parse(format!("invalid time duration: {}", s))),
77 };
78
79 if is_neg {
80 total_milliseconds -= num * factor;
81 } else {
82 total_milliseconds += num * factor;
83 }
84
85 raw_num.clear();
86 }
87
88 Ok(Self {
89 inner: TimeDuration::milliseconds(total_milliseconds),
90 raw: s.to_string(),
91 })
92 }
93}
94
95impl fmt::Display for Duration {
96 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 f.write_str(&self.raw)
98 }
99}
100
101impl TryFrom<String> for Duration {
102 type Error = Error;
103
104 fn try_from(s: String) -> Result<Self, Self::Error> {
105 Self::from_str(&s)
106 }
107}
108
109impl PartialEq for Duration {
110 fn eq(&self, other: &Self) -> bool {
111 self.inner == other.inner
112 }
113}
114
115impl From<f64> for Duration {
139 fn from(f: f64) -> Self {
140 let inner = TimeDuration::saturating_seconds_f64(f);
141 Self {
142 raw: format!("{}ms", inner.whole_milliseconds()),
143 inner,
144 }
145 }
146}
147
148impl Into<f64> for Duration {
149 fn into(self) -> f64 {
150 self.inner.as_seconds_f64()
151 }
152}
153
154impl From<i64> for Duration {
178 fn from(s: i64) -> Self {
179 let inner = TimeDuration::seconds(s);
180
181 Self {
182 raw: format!("{}s", inner.whole_seconds()),
183 inner,
184 }
185 }
186}
187
188impl Into<i64> for Duration {
189 fn into(self) -> i64 {
190 self.inner.whole_seconds()
191 }
192}
193
194#[derive(Clone, Copy, Debug)]
196pub enum TargetState {
197 Active,
198 Dropped,
199 Any,
200}
201
202impl fmt::Display for TargetState {
203 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204 match self {
205 Self::Active => f.write_str("active"),
206 Self::Dropped => f.write_str("dropped"),
207 Self::Any => f.write_str("any"),
208 }
209 }
210}
211
212impl FromStr for TargetState {
213 type Err = Error;
214
215 fn from_str(s: &str) -> Result<Self, Self::Err> {
216 match s {
217 "active" => Ok(Self::Active),
218 "dropped" => Ok(Self::Dropped),
219 "any" => Ok(Self::Any),
220 _ => Err(Error::Parse(format!(
221 "failed to parse target state from '{}', must be one of 'active', 'dropped', 'any'",
222 s
223 ))),
224 }
225 }
226}
227
228#[derive(Debug, Copy, Clone, Deserialize, Eq, PartialEq)]
230pub enum TargetHealth {
231 #[serde(alias = "up")]
232 Up,
233 #[serde(alias = "down")]
234 Down,
235 #[serde(alias = "unknown")]
236 Unknown,
237}
238
239impl TargetHealth {
240 pub fn is_up(&self) -> bool {
241 *self == Self::Up
242 }
243
244 pub fn is_down(&self) -> bool {
245 *self == Self::Down
246 }
247
248 pub fn is_unknown(&self) -> bool {
249 *self == Self::Unknown
250 }
251}
252
253impl fmt::Display for TargetHealth {
254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255 match self {
256 Self::Up => f.write_str("up"),
257 Self::Down => f.write_str("down"),
258 Self::Unknown => f.write_str("unknown"),
259 }
260 }
261}
262
263#[derive(Debug, Copy, Clone, Deserialize, Eq, PartialEq)]
265pub enum RuleHealth {
266 #[serde(alias = "ok")]
267 Good,
268 #[serde(alias = "err")]
269 Bad,
270 #[serde(alias = "unknown")]
271 Unknown,
272}
273
274impl RuleHealth {
275 pub fn is_good(&self) -> bool {
276 *self == Self::Good
277 }
278
279 pub fn is_bad(&self) -> bool {
280 *self == Self::Bad
281 }
282
283 pub fn is_unknown(&self) -> bool {
284 *self == Self::Unknown
285 }
286}
287
288impl fmt::Display for RuleHealth {
289 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
290 match self {
291 Self::Good => f.write_str("ok"),
292 Self::Bad => f.write_str("err"),
293 Self::Unknown => f.write_str("unknown"),
294 }
295 }
296}
297
298#[derive(Debug, Copy, Clone, Deserialize, Eq, PartialEq)]
300pub enum AlertState {
301 #[serde(alias = "inactive")]
302 Inactive,
303 #[serde(alias = "pending")]
304 Pending,
305 #[serde(alias = "firing")]
306 Firing,
307}
308
309impl AlertState {
310 pub fn is_inactive(&self) -> bool {
311 *self == Self::Inactive
312 }
313
314 pub fn is_pending(&self) -> bool {
315 *self == Self::Pending
316 }
317
318 pub fn is_firing(&self) -> bool {
319 *self == Self::Firing
320 }
321}
322
323impl fmt::Display for AlertState {
324 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
325 match self {
326 Self::Inactive => f.write_str("inactive"),
327 Self::Pending => f.write_str("pending"),
328 Self::Firing => f.write_str("firing"),
329 }
330 }
331}
332
333#[derive(Copy, Clone, Debug)]
335pub enum RuleKind {
336 Alerting,
337 Recording,
338}
339
340impl RuleKind {
341 pub(crate) fn to_query_param(&self) -> String {
342 match self {
343 Self::Alerting => String::from("alert"),
344 Self::Recording => String::from("record"),
345 }
346 }
347}
348
349impl fmt::Display for RuleKind {
350 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
351 match self {
352 Self::Alerting => f.write_str("alerting"),
353 Self::Recording => f.write_str("recording"),
354 }
355 }
356}
357
358impl FromStr for RuleKind {
359 type Err = Error;
360
361 fn from_str(s: &str) -> Result<Self, Self::Err> {
362 match s {
363 "alert"| "alerting" => Ok(Self::Alerting),
364 "record"| "recording" => Ok(Self::Recording),
365 _ => Err(Error::Parse(format!("failed to parse rule type from '{}', must be one of 'alert', 'alerting', 'record', 'recording'", s)))
366 }
367 }
368}
369
370#[allow(clippy::enum_variant_names)]
371#[derive(Debug, Clone, PartialEq)]
372pub(crate) enum Label<'a> {
373 Equal((&'a str, &'a str)),
374 NotEqual((&'a str, &'a str)),
375 RegexEqual((&'a str, &'a str)),
376 RegexNotEqual((&'a str, &'a str)),
377}
378
379impl<'a> fmt::Display for Label<'a> {
380 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
381 match self {
382 Self::Equal((k, v)) => write!(f, "{}=\"{}\"", k, v),
383 Self::NotEqual((k, v)) => write!(f, "{}!=\"{}\"", k, v),
384 Self::RegexEqual((k, v)) => write!(f, "{}=~\"{}\"", k, v),
385 Self::RegexNotEqual((k, v)) => write!(f, "{}!~\"{}\"", k, v),
386 }
387 }
388}
389
390pub(crate) trait ToBaseUrl {
395 fn to_base_url(self) -> Result<Url, Error>;
396}
397
398impl ToBaseUrl for &str {
399 fn to_base_url(self) -> Result<Url, Error> {
400 Url::parse(self).map_err(|source| {
401 Error::ParseUrl(ParseUrlError {
402 message: "failed to build Prometheus server base URL",
403 source,
404 })
405 })
406 }
407}
408
409impl ToBaseUrl for String {
410 fn to_base_url(self) -> Result<Url, Error> {
411 Url::parse(&self).map_err(|source| {
412 Error::ParseUrl(ParseUrlError {
413 message: "failed to build Prometheus server base URL",
414 source,
415 })
416 })
417 }
418}
419
420pub(crate) fn build_final_url(mut url: Url, path: &str) -> Url {
421 let base_path = url.path();
422 match base_path {
423 "/" => return url.join(path).unwrap(),
424 _ => {
425 let p = format!("{}/{}", base_path, path);
426 url.set_path(&p);
427 }
428 }
429 url
430}
431
432pub(crate) fn is_json(v: Option<&HeaderValue>) -> bool {
433 match v
434 .and_then(|h| h.to_str().ok())
435 .and_then(|h| h.parse::<Mime>().ok())
436 {
437 Some(mime) => match (mime.type_(), mime.subtype()) {
438 (mime::APPLICATION, mime::JSON) => true,
439 _ => false,
440 },
441 None => false,
442 }
443}
444
445#[cfg(test)]
446mod tests {
447 use super::{build_final_url, is_json, Duration, ToBaseUrl};
448 use std::str::FromStr;
449 use time::Duration as TimeDuration;
450
451 #[test]
452 fn test_simple_str_to_url() {
453 let s = "http://127.0.0.1:9090";
454 let url = s.to_base_url().unwrap();
455 assert_eq!("http://127.0.0.1:9090/", url.as_str());
456 }
457
458 #[test]
459 fn test_proxied_str_to_url() {
460 let s = "http://proxy.example.com/prometheus";
461 let url = s.to_base_url().unwrap();
462 assert_eq!("http://proxy.example.com/prometheus", url.as_str());
463 }
464
465 #[test]
466 fn test_simple_string_to_url() {
467 let s = String::from("http://127.0.0.1:9090");
468 let url = s.to_base_url().unwrap();
469 assert_eq!("http://127.0.0.1:9090/", url.as_str());
470 }
471
472 #[test]
473 fn test_proxied_string_to_url() {
474 let s = String::from("http://proxy.example.com/prometheus");
475 let url = s.to_base_url().unwrap();
476 assert_eq!("http://proxy.example.com/prometheus", url.as_str());
477 }
478
479 #[test]
480 fn test_simple_url_finalization() {
481 let s = String::from("http://127.0.0.1:9090");
482 let url = s.to_base_url().unwrap();
483 let final_url = build_final_url(url, "api/v1/targets");
484 assert_eq!("http://127.0.0.1:9090/api/v1/targets", final_url.as_str());
485 }
486
487 #[test]
488 fn test_proxied_url_finalization() {
489 let s = String::from("http://proxy.example.com/prometheus");
490 let url = s.to_base_url().unwrap();
491 let final_url = build_final_url(url, "api/v1/targets");
492 assert_eq!(
493 "http://proxy.example.com/prometheus/api/v1/targets",
494 final_url.as_str()
495 );
496 }
497
498 #[test]
499 fn test_is_json() {
500 let header = reqwest::header::HeaderValue::from_static("application/json");
501 assert!(is_json(Some(&header)));
502 }
503
504 #[test]
505 fn test_is_json_with_charset() {
506 let header = reqwest::header::HeaderValue::from_static("application/json; charset=utf-8");
507 assert!(is_json(Some(&header)));
508 }
509
510 #[test]
511 fn test_duration() -> Result<(), anyhow::Error> {
512 {
513 let s = "1s";
514 let expected = Duration {
515 inner: TimeDuration::seconds(1),
516 raw: "1s".to_string(),
517 };
518 assert_eq!(Duration::from_str(s)?, expected);
519 assert_eq!(Into::<f64>::into(expected.clone()), 1.0);
520 assert_eq!(Into::<i64>::into(expected), 1);
521 }
522
523 {
524 let s = "-1s";
525 let expected = Duration {
526 inner: TimeDuration::seconds(-1),
527 raw: "-1s".to_string(),
528 };
529 assert_eq!(Duration::from_str(s)?, expected);
530 assert_eq!(Into::<f64>::into(expected.clone()), -1.0);
531 assert_eq!(Into::<i64>::into(expected), -1);
532 }
533
534 {
535 let s = "2m";
536 let expected = Duration {
537 inner: TimeDuration::seconds(120),
538 raw: "2m".to_string(),
539 };
540 assert_eq!(Duration::from_str(s)?, expected);
541 assert_eq!(Into::<f64>::into(expected.clone()), 120.0);
542 assert_eq!(Into::<i64>::into(expected), 120);
543 }
544
545 {
546 let s = "-2m";
547 let expected = Duration {
548 inner: TimeDuration::seconds(-120),
549 raw: "-2m".to_string(),
550 };
551 assert_eq!(Duration::from_str(s)?, expected);
552 assert_eq!(Into::<f64>::into(expected.clone()), -120.0);
553 assert_eq!(Into::<i64>::into(expected), -120);
554 }
555
556 {
557 let s = "1ms";
558 let expected = Duration {
559 inner: TimeDuration::milliseconds(1),
560 raw: "1ms".to_string(),
561 };
562 assert_eq!(Duration::from_str(s)?, expected);
563 assert_eq!(Into::<f64>::into(expected.clone()), 0.001);
564 assert_eq!(Into::<i64>::into(expected), 0);
565 }
566
567 {
568 let s = "-1ms";
569 let expected = Duration {
570 inner: TimeDuration::milliseconds(-1),
571 raw: "-1ms".to_string(),
572 };
573 assert_eq!(Duration::from_str(s)?, expected);
574 assert_eq!(Into::<f64>::into(expected.clone()), -0.001);
575 assert_eq!(Into::<i64>::into(expected), 0);
576 }
577
578 {
579 let s = "-2h";
580 let expected = Duration {
581 inner: TimeDuration::seconds(-7200),
582 raw: "-2h".to_string(),
583 };
584 assert_eq!(Duration::from_str(s)?, expected);
585 assert_eq!(Into::<f64>::into(expected.clone()), -7200.0);
586 assert_eq!(Into::<i64>::into(expected), -7200);
587 }
588
589 {
590 let s = "1h30m";
591 let expected = Duration {
592 inner: TimeDuration::seconds(5400),
593 raw: "1h30m".to_string(),
594 };
595 assert_eq!(Duration::from_str(s)?, expected);
596 assert_eq!(Into::<f64>::into(expected.clone()), 5400.0);
597 assert_eq!(Into::<i64>::into(expected), 5400);
598 }
599
600 {
601 let s = "12h34m56s";
602 let expected = Duration {
603 inner: TimeDuration::seconds(45296),
604 raw: "12h34m56s".to_string(),
605 };
606 assert_eq!(Duration::from_str(s)?, expected);
607 assert_eq!(Into::<f64>::into(expected.clone()), 45296.0);
608 assert_eq!(Into::<i64>::into(expected), 45296);
609 }
610
611 {
612 let s = "54s321ms";
613 let expected = Duration {
614 inner: TimeDuration::saturating_seconds_f64(54.321),
615 raw: "54s321ms".to_string(),
616 };
617 assert_eq!(Duration::from_str(s)?, expected);
618 assert_eq!(Into::<f64>::into(expected.clone()), 54.321);
619 assert_eq!(Into::<i64>::into(expected), 54);
620 }
621
622 {
623 let expected = Duration {
624 inner: TimeDuration::saturating_seconds_f64(54.321),
625 raw: "54321ms".to_string(),
626 };
627 assert_eq!(Duration::from(54.321), expected);
628 assert_eq!(Into::<f64>::into(expected.clone()), 54.321);
629 assert_eq!(Into::<i64>::into(expected), 54);
630 }
631
632 {
633 let expected = Duration {
634 inner: TimeDuration::seconds(54),
635 raw: "54s".to_string(),
636 };
637 assert_eq!(Duration::from(54), expected);
638 assert_eq!(Into::<f64>::into(expected.clone()), 54.0);
639 assert_eq!(Into::<i64>::into(expected), 54);
640 }
641
642 Ok(())
643 }
644}