Skip to main content

prometheus_http_query/
response.rs

1//! All types that are returned when querying the Prometheus API.
2use crate::util::{AlertState, RuleHealth, TargetHealth};
3use enum_as_inner::EnumAsInner;
4use serde::Deserialize;
5use std::collections::HashMap;
6use std::fmt;
7use time::{Duration, OffsetDateTime, PrimitiveDateTime};
8use url::Url;
9
10mod de {
11    use serde::{
12        de::{Error as SerdeError, Unexpected},
13        Deserialize, Deserializer,
14    };
15    use std::str::FromStr;
16    use time::format_description::FormatItem;
17    use time::macros::format_description;
18    use time::{Duration, PrimitiveDateTime};
19
20    const BUILD_INFO_DATE_FORMAT: &[FormatItem] = format_description!(
21        "[year repr:full][month repr:numerical][day]-[hour repr:24]:[minute]:[second]"
22    );
23
24    pub(super) fn deserialize_f64<'de, D>(deserializer: D) -> Result<f64, D::Error>
25    where
26        D: Deserializer<'de>,
27    {
28        String::deserialize(deserializer).and_then(|s| {
29            f64::from_str(&s).map_err(|_| {
30                SerdeError::invalid_value(
31                    Unexpected::Str(&s),
32                    &"a float value inside a quoted JSON string",
33                )
34            })
35        })
36    }
37
38    // This function is used to deserialize a specific datetime string like "20191102-16:19:59".
39    pub(super) fn deserialize_build_info_date<'de, D>(
40        deserializer: D,
41    ) -> Result<PrimitiveDateTime, D::Error>
42    where
43        D: Deserializer<'de>,
44    {
45        String::deserialize(deserializer).and_then(|s| {
46            PrimitiveDateTime::parse(&s, &BUILD_INFO_DATE_FORMAT).map_err(|_| {
47                SerdeError::invalid_value(
48                    Unexpected::Str(&s),
49                    &"a datetime string in format <yyyymmdd-hh:mm:ss>",
50                )
51            })
52        })
53    }
54
55    // This function is used to deserialize Prometheus duration strings like "1d" or "5m" or
56    // composits like "1d12h10m".
57    // Note that this function assumes that the input string is non-empty and that the total
58    // amount of milliseconds does not exceed i64::MAX. This seems to be a reasonable assumption
59    // since the Prometheus server creates durations from Go's int64 on the server side and the
60    // int64 depicts the total amount of nanoseconds.
61    pub(super) fn deserialize_prometheus_duration<'de, D>(
62        deserializer: D,
63    ) -> Result<Duration, D::Error>
64    where
65        D: Deserializer<'de>,
66    {
67        let raw_str = String::deserialize(deserializer)?;
68
69        let duration = crate::util::Duration::try_from(raw_str).map_err(SerdeError::custom)?;
70
71        Ok(duration.inner)
72    }
73
74    // This function deserializes both a list of alerts as well as `null` to a list.
75    pub(super) fn deserialize_alerts_as_array<'de, D>(
76        deserializer: D,
77    ) -> Result<Vec<super::Alert>, D::Error>
78    where
79        D: Deserializer<'de>,
80    {
81        match Option::<Vec<super::Alert>>::deserialize(deserializer) {
82            Ok(Some(alerts)) => Ok(alerts),
83            Ok(None) => Ok(vec![]),
84            Err(error) => Err(error),
85        }
86    }
87}
88
89#[derive(Debug, Deserialize)]
90#[serde(tag = "status")]
91pub(crate) enum ApiResponse<D> {
92    #[serde(alias = "success")]
93    Success { data: D },
94    #[serde(alias = "error")]
95    Error(crate::error::PrometheusError),
96}
97
98#[derive(Debug, Clone, Deserialize)]
99pub struct Stats {
100    timings: Timings,
101    samples: Samples,
102}
103
104impl Stats {
105    pub fn timings(&self) -> &Timings {
106        &self.timings
107    }
108
109    pub fn samples(&self) -> &Samples {
110        &self.samples
111    }
112}
113
114#[derive(Debug, Copy, Clone, Deserialize)]
115pub struct Timings {
116    #[serde(alias = "evalTotalTime")]
117    eval_total_time: f64,
118    #[serde(alias = "resultSortTime")]
119    result_sort_time: f64,
120    #[serde(alias = "queryPreparationTime")]
121    query_preparation_time: f64,
122    #[serde(alias = "innerEvalTime")]
123    inner_eval_time: f64,
124    #[serde(alias = "execQueueTime")]
125    exec_queue_time: f64,
126    #[serde(alias = "execTotalTime")]
127    exec_total_time: f64,
128}
129
130impl Timings {
131    pub fn eval_total_time(&self) -> f64 {
132        self.eval_total_time
133    }
134
135    pub fn result_sort_time(&self) -> f64 {
136        self.result_sort_time
137    }
138
139    pub fn query_preparation_time(&self) -> f64 {
140        self.query_preparation_time
141    }
142
143    pub fn inner_eval_time(&self) -> f64 {
144        self.inner_eval_time
145    }
146
147    pub fn exec_queue_time(&self) -> f64 {
148        self.exec_queue_time
149    }
150
151    pub fn exec_total_time(&self) -> f64 {
152        self.exec_total_time
153    }
154}
155
156#[derive(Debug, Clone, Deserialize)]
157pub struct Samples {
158    #[serde(alias = "totalQueryableSamplesPerStep")]
159    total_queryable_samples_per_step: Option<Vec<SamplesPerStep>>,
160    #[serde(alias = "totalQueryableSamples")]
161    total_queryable_samples: i64,
162    #[serde(alias = "peakSamples")]
163    peak_samples: i64,
164}
165
166impl Samples {
167    pub fn total_queryable_samples_per_step(&self) -> Option<&Vec<SamplesPerStep>> {
168        self.total_queryable_samples_per_step.as_ref()
169    }
170
171    pub fn total_queryable_samples(&self) -> i64 {
172        self.total_queryable_samples
173    }
174
175    pub fn peak_samples(&self) -> i64 {
176        self.peak_samples
177    }
178}
179
180/// A hint to the total queryable samples in this step.
181#[derive(Clone, Copy, Debug, PartialEq, Deserialize)]
182pub struct SamplesPerStep {
183    pub(crate) timestamp: f64,
184    pub(crate) value: usize,
185}
186
187impl SamplesPerStep {
188    /// Returns the timestamp at the start of this step.
189    pub fn timestamp(&self) -> f64 {
190        self.timestamp
191    }
192
193    /// Returns the number of samples in this step.
194    pub fn value(&self) -> usize {
195        self.value
196    }
197}
198
199#[derive(Debug, Clone, Deserialize)]
200pub struct PromqlResult {
201    #[serde(flatten)]
202    pub(crate) data: Data,
203    pub(crate) stats: Option<Stats>,
204}
205
206impl PromqlResult {
207    /// Return the response [`Data`] from this query.
208    pub fn data(&self) -> &Data {
209        &self.data
210    }
211
212    /// Return the [`Stats`] that the Prometheus server gathered while the query was processed.
213    pub fn stats(&self) -> Option<&Stats> {
214        self.stats.as_ref()
215    }
216
217    /// Returns the inner types when ownership is required
218    pub fn into_inner(self) -> (Data, Option<Stats>) {
219        (self.data, self.stats)
220    }
221}
222
223/// A wrapper for possible result types of expression queries ([`Client::query`](crate::Client::query) and [`Client::query_range`](crate::Client::query_range)).
224#[derive(Clone, Debug, Deserialize, EnumAsInner)]
225#[serde(tag = "resultType", content = "result")]
226pub enum Data {
227    #[serde(alias = "vector")]
228    Vector(Vec<InstantVector>),
229    #[serde(alias = "matrix")]
230    Matrix(Vec<RangeVector>),
231    #[serde(alias = "scalar")]
232    Scalar(Sample),
233}
234
235impl Data {
236    /// This is a shortcut to check if the query returned any data at all regardless of the exact type.
237    pub fn is_empty(&self) -> bool {
238        match self {
239            Data::Vector(v) => v.is_empty(),
240            Data::Matrix(v) => v.is_empty(),
241            Data::Scalar(_) => false,
242        }
243    }
244}
245
246/// A single time series containing a single data point/sample.
247#[derive(Clone, Debug, PartialEq, Deserialize)]
248pub struct InstantVector {
249    pub(crate) metric: HashMap<String, String>,
250    #[serde(alias = "value")]
251    pub(crate) sample: Sample,
252}
253
254impl InstantVector {
255    /// Returns a reference to the set of labels (+ metric name)
256    /// of this time series.
257    pub fn metric(&self) -> &HashMap<String, String> {
258        &self.metric
259    }
260
261    /// Returns a reference to the sample of this time series.
262    pub fn sample(&self) -> &Sample {
263        &self.sample
264    }
265
266    /// Returns the inner types when ownership is required
267    pub fn into_inner(self) -> (HashMap<String, String>, Sample) {
268        (self.metric, self.sample)
269    }
270}
271
272/// A single time series containing a range of data points/samples.
273#[derive(Clone, Debug, PartialEq, Deserialize)]
274pub struct RangeVector {
275    pub(crate) metric: HashMap<String, String>,
276    #[serde(alias = "values")]
277    pub(crate) samples: Vec<Sample>,
278}
279
280impl RangeVector {
281    /// Returns a reference to the set of labels (+ metric name)
282    /// of this time series.
283    pub fn metric(&self) -> &HashMap<String, String> {
284        &self.metric
285    }
286
287    /// Returns a reference to the set of samples of this time series.
288    pub fn samples(&self) -> &[Sample] {
289        &self.samples
290    }
291
292    /// Returns the inner types when ownership is required
293    pub fn into_inner(self) -> (HashMap<String, String>, Vec<Sample>) {
294        (self.metric, self.samples)
295    }
296}
297
298/// A single data point.
299#[derive(Clone, Copy, Debug, PartialEq, Deserialize)]
300pub struct Sample {
301    pub(crate) timestamp: f64,
302    #[serde(deserialize_with = "de::deserialize_f64")]
303    pub(crate) value: f64,
304}
305
306impl Sample {
307    /// Returns the timestamp contained in this sample.
308    pub fn timestamp(&self) -> f64 {
309        self.timestamp
310    }
311
312    /// Returns the value contained in this sample.
313    pub fn value(&self) -> f64 {
314        self.value
315    }
316}
317
318/// Collection of active and dropped targets as returned by the API.
319#[derive(Clone, Debug, Deserialize)]
320pub struct Targets {
321    #[serde(alias = "activeTargets")]
322    pub(crate) active: Vec<ActiveTarget>,
323    #[serde(alias = "droppedTargets")]
324    pub(crate) dropped: Vec<DroppedTarget>,
325}
326
327impl Targets {
328    /// Get a list of currently active targets.
329    pub fn active(&self) -> &[ActiveTarget] {
330        &self.active
331    }
332
333    /// Get a list of dropped targets.
334    pub fn dropped(&self) -> &[DroppedTarget] {
335        &self.dropped
336    }
337}
338
339/// A single active target.
340#[derive(Clone, Debug, Deserialize)]
341pub struct ActiveTarget {
342    #[serde(alias = "discoveredLabels")]
343    pub(crate) discovered_labels: HashMap<String, String>,
344    pub(crate) labels: HashMap<String, String>,
345    #[serde(alias = "scrapePool")]
346    pub(crate) scrape_pool: String,
347    #[serde(alias = "scrapeUrl")]
348    pub(crate) scrape_url: Url,
349    #[serde(alias = "globalUrl")]
350    pub(crate) global_url: Url,
351    #[serde(alias = "lastError")]
352    pub(crate) last_error: String,
353    #[serde(alias = "lastScrape")]
354    #[serde(with = "time::serde::rfc3339")]
355    pub(crate) last_scrape: OffsetDateTime,
356    #[serde(alias = "lastScrapeDuration")]
357    pub(crate) last_scrape_duration: f64,
358    pub(crate) health: TargetHealth,
359    #[serde(
360        alias = "scrapeInterval",
361        deserialize_with = "de::deserialize_prometheus_duration"
362    )]
363    pub(crate) scrape_interval: Duration,
364    #[serde(
365        alias = "scrapeTimeout",
366        deserialize_with = "de::deserialize_prometheus_duration"
367    )]
368    pub(crate) scrape_timeout: Duration,
369}
370
371impl ActiveTarget {
372    /// Get a set of unmodified labels as before relabelling occurred.
373    pub fn discovered_labels(&self) -> &HashMap<String, String> {
374        &self.discovered_labels
375    }
376
377    /// Get a set of labels after relabelling.
378    pub fn labels(&self) -> &HashMap<String, String> {
379        &self.labels
380    }
381
382    /// Get the scrape pool of this target.
383    pub fn scrape_pool(&self) -> &str {
384        &self.scrape_pool
385    }
386
387    /// Get the scrape URL of this target.
388    pub fn scrape_url(&self) -> &Url {
389        &self.scrape_url
390    }
391
392    /// Get the global URL of this target.
393    pub fn global_url(&self) -> &Url {
394        &self.global_url
395    }
396
397    /// Get the last error reported for this target.
398    pub fn last_error(&self) -> &str {
399        &self.last_error
400    }
401
402    /// Get the time when the last scrape occurred.
403    pub fn last_scrape(&self) -> &OffsetDateTime {
404        &self.last_scrape
405    }
406
407    /// Get the duration that the last scrape ran for in seconds.
408    pub fn last_scrape_duration(&self) -> f64 {
409        self.last_scrape_duration
410    }
411
412    /// Get the health status of this target.
413    pub fn health(&self) -> TargetHealth {
414        self.health
415    }
416
417    /// Get the scrape interval of this target.
418    pub fn scrape_interval(&self) -> &Duration {
419        &self.scrape_interval
420    }
421
422    /// Get the scrape timeout of this target.
423    pub fn scrape_timeout(&self) -> &Duration {
424        &self.scrape_timeout
425    }
426}
427
428/// A single dropped target.
429#[derive(Clone, Debug, Deserialize)]
430pub struct DroppedTarget {
431    #[serde(alias = "discoveredLabels")]
432    pub(crate) discovered_labels: HashMap<String, String>,
433}
434
435impl DroppedTarget {
436    /// Get a set of unmodified labels as before relabelling occurred.
437    pub fn discovered_labels(&self) -> &HashMap<String, String> {
438        &self.discovered_labels
439    }
440}
441
442/// This is a wrapper around a collection of [`RuleGroup`]s as it is
443/// returned by the API.
444#[derive(Debug, Deserialize)]
445pub(crate) struct RuleGroups {
446    pub groups: Vec<RuleGroup>,
447}
448
449/// A group of rules.
450#[derive(Clone, Debug, Deserialize)]
451pub struct RuleGroup {
452    pub(crate) rules: Vec<Rule>,
453    pub(crate) file: String,
454    pub(crate) interval: f64,
455    pub(crate) name: String,
456    #[serde(alias = "evaluationTime")]
457    pub(crate) evaluation_time: f64,
458    #[serde(alias = "lastEvaluation", with = "time::serde::rfc3339")]
459    pub(crate) last_evaluation: OffsetDateTime,
460    pub(crate) limit: usize,
461}
462
463impl RuleGroup {
464    /// Get a reference to all rules associated with this group.
465    pub fn rules(&self) -> &[Rule] {
466        &self.rules
467    }
468
469    /// Get the path to the file where this group is defined in.
470    pub fn file(&self) -> &str {
471        &self.file
472    }
473
474    /// Get the interval that defines how often rules are evaluated.
475    pub fn interval(&self) -> f64 {
476        self.interval
477    }
478
479    /// Get the name of this rule group.
480    pub fn name(&self) -> &str {
481        &self.name
482    }
483
484    /// Get the time when the group of rules was last evaluated.
485    pub fn last_evaluation(&self) -> &OffsetDateTime {
486        &self.last_evaluation
487    }
488
489    /// Get duration in seconds that Prometheus took to evaluate this group of
490    /// rules.
491    pub fn evaluation_time(&self) -> f64 {
492        self.evaluation_time
493    }
494
495    /// Return the limit of alerts (alerting rule) or series (recording rule)
496    /// that the rules in this group may produce. Zero means not limit.
497    pub fn limit(&self) -> usize {
498        self.limit
499    }
500}
501
502/// A wrapper for different types of rules that the HTTP API may return.
503#[derive(Clone, Debug, Deserialize)]
504#[serde(tag = "type")]
505pub enum Rule {
506    #[serde(alias = "recording")]
507    Recording(RecordingRule),
508    #[serde(alias = "alerting")]
509    Alerting(AlertingRule),
510}
511
512impl Rule {
513    pub fn as_recording(&self) -> Option<&RecordingRule> {
514        match self {
515            Self::Recording(rule) => Some(&rule),
516            _ => None,
517        }
518    }
519
520    pub fn as_alerting(&self) -> Option<&AlertingRule> {
521        match self {
522            Self::Alerting(rule) => Some(&rule),
523            _ => None,
524        }
525    }
526}
527
528/// An alerting rule.
529#[derive(Clone, Debug, Deserialize)]
530pub struct AlertingRule {
531    #[serde(deserialize_with = "de::deserialize_alerts_as_array")]
532    pub(crate) alerts: Vec<Alert>,
533    pub(crate) annotations: HashMap<String, String>,
534    pub(crate) duration: f64,
535    pub(crate) health: RuleHealth,
536    pub(crate) labels: HashMap<String, String>,
537    pub(crate) name: String,
538    pub(crate) query: String,
539    #[serde(alias = "evaluationTime")]
540    pub(crate) evaluation_time: f64,
541    #[serde(alias = "lastEvaluation", with = "time::serde::rfc3339")]
542    pub(crate) last_evaluation: OffsetDateTime,
543    #[serde(alias = "keepFiringFor")]
544    pub(crate) keep_firing_for: f64,
545}
546
547impl AlertingRule {
548    /// Get a list of active alerts fired due to this alerting rule.
549    pub fn alerts(&self) -> &[Alert] {
550        &self.alerts
551    }
552
553    /// Get a set of annotations set for this rule.
554    pub fn annotations(&self) -> &HashMap<String, String> {
555        &self.annotations
556    }
557
558    /// Get the duration that Prometheus waits for before firing for this rule.
559    pub fn duration(&self) -> f64 {
560        self.duration
561    }
562
563    /// Get the health state of this rule.
564    pub fn health(&self) -> RuleHealth {
565        self.health
566    }
567
568    /// Get a set of labels defined for this rule.
569    pub fn labels(&self) -> &HashMap<String, String> {
570        &self.labels
571    }
572
573    /// Get the name of this rule.
574    pub fn name(&self) -> &str {
575        &self.name
576    }
577
578    /// Get the PromQL expression that is evaluated as part of this rule.
579    pub fn query(&self) -> &str {
580        &self.query
581    }
582
583    /// Get the time when the rule was last evaluated.
584    pub fn last_evaluation(&self) -> &OffsetDateTime {
585        &self.last_evaluation
586    }
587
588    /// Get duration in seconds that Prometheus took to evaluate this rule.
589    pub fn evaluation_time(&self) -> f64 {
590        self.evaluation_time
591    }
592
593    /// Get the duration that Prometheus waits before clearing an alert that
594    /// has previously been firing.
595    pub fn keep_firing_for(&self) -> f64 {
596        self.keep_firing_for
597    }
598}
599
600/// A recording rule.
601#[derive(Clone, Debug, Deserialize)]
602pub struct RecordingRule {
603    pub(crate) health: RuleHealth,
604    pub(crate) name: String,
605    pub(crate) query: String,
606    pub(crate) labels: Option<HashMap<String, String>>,
607    #[serde(alias = "evaluationTime")]
608    pub(crate) evaluation_time: f64,
609    #[serde(alias = "lastEvaluation", with = "time::serde::rfc3339")]
610    pub(crate) last_evaluation: OffsetDateTime,
611}
612
613impl RecordingRule {
614    /// Get the health state of this rule.
615    pub fn health(&self) -> RuleHealth {
616        self.health
617    }
618
619    /// Get the name of this rule.
620    pub fn name(&self) -> &str {
621        &self.name
622    }
623
624    /// Get the PromQL expression that is evaluated as part of this rule.
625    pub fn query(&self) -> &str {
626        &self.query
627    }
628
629    /// Get a set of labels defined for this rule.
630    pub fn labels(&self) -> &Option<HashMap<String, String>> {
631        &self.labels
632    }
633
634    /// Get the time when the rule was last evaluated.
635    pub fn last_evaluation(&self) -> &OffsetDateTime {
636        &self.last_evaluation
637    }
638
639    /// Get duration in seconds that Prometheus took to evaluate this rule.
640    pub fn evaluation_time(&self) -> f64 {
641        self.evaluation_time
642    }
643}
644
645/// A wrapper around a collection of [`Alert`]s as it is returned by
646/// the API.
647#[derive(Debug, Deserialize)]
648pub(crate) struct Alerts {
649    pub alerts: Vec<Alert>,
650}
651
652/// A single alert.
653#[derive(Clone, Debug, Deserialize)]
654pub struct Alert {
655    #[serde(alias = "activeAt", with = "time::serde::rfc3339")]
656    pub(crate) active_at: OffsetDateTime,
657    pub(crate) annotations: HashMap<String, String>,
658    pub(crate) labels: HashMap<String, String>,
659    pub(crate) state: AlertState,
660    #[serde(deserialize_with = "de::deserialize_f64")]
661    pub(crate) value: f64,
662}
663
664impl Alert {
665    /// Get the time when this alert started firing.
666    pub fn active_at(&self) -> &OffsetDateTime {
667        &self.active_at
668    }
669
670    /// Get a set of annotations associated with this alert.
671    pub fn annotations(&self) -> &HashMap<String, String> {
672        &self.annotations
673    }
674
675    /// Get a set of labels associated with this alert.
676    pub fn labels(&self) -> &HashMap<String, String> {
677        &self.labels
678    }
679
680    /// Get the state of this alert.
681    pub fn state(&self) -> AlertState {
682        self.state
683    }
684
685    /// Get the value as evaluated by the PromQL expression that caused the alert to fire.
686    pub fn value(&self) -> f64 {
687        self.value
688    }
689}
690
691/// Collection of active and dropped alertmanagers as returned by the API.
692#[derive(Clone, Debug, Deserialize)]
693pub struct Alertmanagers {
694    #[serde(alias = "activeAlertmanagers")]
695    pub(crate) active: Vec<Alertmanager>,
696    #[serde(alias = "droppedAlertmanagers")]
697    pub(crate) dropped: Vec<Alertmanager>,
698}
699
700impl Alertmanagers {
701    /// Get a list of currently active alertmanagers.
702    pub fn active(&self) -> &[Alertmanager] {
703        &self.active
704    }
705
706    /// Get a list of dropped alertmanagers.
707    pub fn dropped(&self) -> &[Alertmanager] {
708        &self.dropped
709    }
710}
711
712/// A single alertmanager.
713#[derive(Clone, Debug, Deserialize)]
714pub struct Alertmanager {
715    url: Url,
716}
717
718impl Alertmanager {
719    /// Get the URL of this Alertmanager.
720    pub fn url(&self) -> &Url {
721        &self.url
722    }
723}
724
725/// Possible metric types that the HTTP API may return.
726#[derive(Debug, Copy, Clone, Deserialize, Eq, PartialEq)]
727pub enum MetricType {
728    #[serde(alias = "counter")]
729    Counter,
730    #[serde(alias = "gauge")]
731    Gauge,
732    #[serde(alias = "histogram")]
733    Histogram,
734    #[serde(alias = "gaugehistogram")]
735    GaugeHistogram,
736    #[serde(alias = "summary")]
737    Summary,
738    #[serde(alias = "info")]
739    Info,
740    #[serde(alias = "stateset")]
741    Stateset,
742    #[serde(alias = "unknown")]
743    Unknown,
744}
745
746impl MetricType {
747    pub fn is_counter(&self) -> bool {
748        *self == Self::Counter
749    }
750
751    pub fn is_gauge(&self) -> bool {
752        *self == Self::Gauge
753    }
754
755    pub fn is_histogram(&self) -> bool {
756        *self == Self::Histogram
757    }
758
759    pub fn is_gauge_histogram(&self) -> bool {
760        *self == Self::GaugeHistogram
761    }
762
763    pub fn is_summary(&self) -> bool {
764        *self == Self::Summary
765    }
766
767    pub fn is_info(&self) -> bool {
768        *self == Self::Info
769    }
770
771    pub fn is_stateset(&self) -> bool {
772        *self == Self::Stateset
773    }
774
775    pub fn is_unknown(&self) -> bool {
776        *self == Self::Unknown
777    }
778}
779
780impl fmt::Display for MetricType {
781    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
782        match self {
783            MetricType::Counter => write!(f, "counter"),
784            MetricType::Gauge => write!(f, "gauge"),
785            MetricType::Histogram => write!(f, "histogram"),
786            MetricType::GaugeHistogram => write!(f, "gaugehistogram"),
787            MetricType::Summary => write!(f, "summary"),
788            MetricType::Info => write!(f, "info"),
789            MetricType::Stateset => write!(f, "stateset"),
790            MetricType::Unknown => write!(f, "unknown"),
791        }
792    }
793}
794
795/// A target metadata object.
796#[derive(Clone, Debug, Deserialize)]
797pub struct TargetMetadata {
798    pub(crate) target: HashMap<String, String>,
799    #[serde(alias = "type")]
800    pub(crate) metric_type: MetricType,
801    pub(crate) metric: Option<String>,
802    pub(crate) help: String,
803    pub(crate) unit: String,
804}
805
806impl TargetMetadata {
807    /// Get target labels.
808    pub fn target(&self) -> &HashMap<String, String> {
809        &self.target
810    }
811
812    /// Get the metric type.
813    pub fn metric_type(&self) -> MetricType {
814        self.metric_type
815    }
816
817    /// Get the metric name.
818    pub fn metric(&self) -> Option<&str> {
819        self.metric.as_deref()
820    }
821
822    /// Get the metric help.
823    pub fn help(&self) -> &str {
824        &self.help
825    }
826
827    /// Get the metric unit.
828    pub fn unit(&self) -> &str {
829        &self.unit
830    }
831}
832
833/// A metric metadata object.
834#[derive(Clone, Debug, Deserialize)]
835pub struct MetricMetadata {
836    #[serde(alias = "type")]
837    pub(crate) metric_type: MetricType,
838    pub(crate) help: String,
839    pub(crate) unit: String,
840}
841
842impl MetricMetadata {
843    /// Get the metric type.
844    pub fn metric_type(&self) -> MetricType {
845        self.metric_type
846    }
847
848    /// Get the metric help.
849    pub fn help(&self) -> &str {
850        &self.help
851    }
852
853    /// Get the metric unit.
854    pub fn unit(&self) -> &str {
855        &self.unit
856    }
857}
858
859/// An object containing Prometheus server build information.
860#[derive(Clone, Debug, Deserialize)]
861pub struct BuildInformation {
862    pub(crate) version: String,
863    pub(crate) revision: String,
864    pub(crate) branch: String,
865    #[serde(alias = "buildUser")]
866    pub(crate) build_user: String,
867    #[serde(alias = "buildDate")]
868    #[serde(deserialize_with = "de::deserialize_build_info_date")]
869    pub(crate) build_date: PrimitiveDateTime,
870    #[serde(alias = "goVersion")]
871    pub(crate) go_version: String,
872}
873
874impl BuildInformation {
875    /// Get the server version.
876    pub fn version(&self) -> &str {
877        &self.version
878    }
879
880    /// Get the git revision from which the server was built.
881    pub fn revision(&self) -> &str {
882        &self.revision
883    }
884
885    /// Get the git branch from which the server was built.
886    pub fn branch(&self) -> &str {
887        &self.branch
888    }
889
890    /// Get the user who built the server.
891    pub fn build_user(&self) -> &str {
892        &self.build_user
893    }
894
895    /// Get the date at which the server was built.
896    pub fn build_date(&self) -> &PrimitiveDateTime {
897        &self.build_date
898    }
899
900    /// Get the Go version that was used to build the server.
901    pub fn go_version(&self) -> &str {
902        &self.go_version
903    }
904}
905
906/// An object containing Prometheus server build information.
907#[derive(Clone, Debug, Deserialize)]
908pub struct RuntimeInformation {
909    #[serde(alias = "startTime", with = "time::serde::rfc3339")]
910    pub(crate) start_time: OffsetDateTime,
911    #[serde(alias = "CWD")]
912    pub(crate) cwd: String,
913    #[serde(alias = "reloadConfigSuccess")]
914    pub(crate) reload_config_success: bool,
915    #[serde(alias = "lastConfigTime", with = "time::serde::rfc3339")]
916    pub(crate) last_config_time: OffsetDateTime,
917    #[serde(alias = "corruptionCount")]
918    pub(crate) corruption_count: i64,
919    #[serde(alias = "goroutineCount")]
920    pub(crate) goroutine_count: usize,
921    #[serde(alias = "GOMAXPROCS")]
922    pub(crate) go_max_procs: usize,
923    #[serde(alias = "GOGC")]
924    pub(crate) go_gc: String,
925    #[serde(alias = "GODEBUG")]
926    pub(crate) go_debug: String,
927    #[serde(
928        alias = "storageRetention",
929        deserialize_with = "de::deserialize_prometheus_duration"
930    )]
931    pub(crate) storage_retention: Duration,
932}
933
934impl RuntimeInformation {
935    /// Get the server start time.
936    pub fn start_time(&self) -> &OffsetDateTime {
937        &self.start_time
938    }
939
940    /// Get the current working directory.
941    pub fn cwd(&self) -> &str {
942        &self.cwd
943    }
944
945    /// Check if the last configuration reload was successful.
946    pub fn reload_config_success(&self) -> bool {
947        self.reload_config_success
948    }
949
950    /// Get the time of last configuration reload.
951    pub fn last_config_time(&self) -> &OffsetDateTime {
952        &self.last_config_time
953    }
954
955    pub fn corruption_count(&self) -> i64 {
956        self.corruption_count
957    }
958
959    pub fn goroutine_count(&self) -> usize {
960        self.goroutine_count
961    }
962
963    pub fn go_max_procs(&self) -> usize {
964        self.go_max_procs
965    }
966
967    pub fn go_gc(&self) -> &str {
968        &self.go_gc
969    }
970
971    pub fn go_debug(&self) -> &str {
972        &self.go_debug
973    }
974
975    pub fn storage_retention(&self) -> &Duration {
976        &self.storage_retention
977    }
978}
979
980/// Prometheus TSDB statistics.
981#[derive(Clone, Debug, Deserialize)]
982pub struct TsdbStatistics {
983    #[serde(alias = "headStats")]
984    pub(crate) head_stats: HeadStatistics,
985    #[serde(alias = "seriesCountByMetricName")]
986    pub(crate) series_count_by_metric_name: Vec<TsdbItemCount>,
987    #[serde(alias = "labelValueCountByLabelName")]
988    pub(crate) label_value_count_by_label_name: Vec<TsdbItemCount>,
989    #[serde(alias = "memoryInBytesByLabelName")]
990    pub(crate) memory_in_bytes_by_label_name: Vec<TsdbItemCount>,
991    #[serde(alias = "seriesCountByLabelValuePair")]
992    pub(crate) series_count_by_label_value_pair: Vec<TsdbItemCount>,
993}
994
995impl TsdbStatistics {
996    /// Get the head block data.
997    pub fn head_stats(&self) -> HeadStatistics {
998        self.head_stats
999    }
1000
1001    /// Get a list of metric names and their series count.
1002    pub fn series_count_by_metric_name(&self) -> &[TsdbItemCount] {
1003        &self.series_count_by_metric_name
1004    }
1005
1006    /// Get a list of label names and their value count.
1007    pub fn label_value_count_by_label_name(&self) -> &[TsdbItemCount] {
1008        &self.label_value_count_by_label_name
1009    }
1010
1011    /// Get a list of label names and memory used in bytes.
1012    pub fn memory_in_bytes_by_label_name(&self) -> &[TsdbItemCount] {
1013        &self.memory_in_bytes_by_label_name
1014    }
1015
1016    /// Get a list of label name/value pairs and their series count.
1017    pub fn series_count_by_label_value_pair(&self) -> &[TsdbItemCount] {
1018        &self.series_count_by_label_value_pair
1019    }
1020}
1021
1022/// Prometheus TSDB head block data.
1023#[derive(Clone, Copy, Debug, Deserialize)]
1024pub struct HeadStatistics {
1025    #[serde(alias = "numSeries")]
1026    pub(crate) num_series: usize,
1027    #[serde(alias = "chunkCount")]
1028    pub(crate) chunk_count: usize,
1029    #[serde(alias = "minTime")]
1030    pub(crate) min_time: i64,
1031    #[serde(alias = "maxTime")]
1032    pub(crate) max_time: i64,
1033}
1034
1035impl HeadStatistics {
1036    /// Get the number of series.
1037    pub fn num_series(&self) -> usize {
1038        self.num_series
1039    }
1040
1041    /// Get the number of chunks.
1042    pub fn chunk_count(&self) -> usize {
1043        self.chunk_count
1044    }
1045
1046    /// Get the current minimum timestamp in milliseconds.
1047    pub fn min_time(&self) -> i64 {
1048        self.min_time
1049    }
1050
1051    /// Get the current maximum timestamp in milliseconds.
1052    pub fn max_time(&self) -> i64 {
1053        self.max_time
1054    }
1055}
1056
1057/// Prometheus TSDB item counts used in different contexts (e.g. series count, label value count ...).
1058#[derive(Clone, Debug, Deserialize)]
1059pub struct TsdbItemCount {
1060    pub(crate) name: String,
1061    pub(crate) value: usize,
1062}
1063
1064impl TsdbItemCount {
1065    /// Get the name of the item in question, e.g. metric name or label name.
1066    pub fn name(&self) -> &str {
1067        &self.name
1068    }
1069
1070    /// Get the count of the item in question, e.g. the series count of a given metric name.
1071    pub fn value(&self) -> usize {
1072        self.value
1073    }
1074}
1075
1076/// WAL replay state.
1077#[derive(Clone, Copy, Debug, Deserialize)]
1078pub struct WalReplayStatistics {
1079    pub(crate) min: usize,
1080    pub(crate) max: usize,
1081    pub(crate) current: usize,
1082    pub(crate) state: Option<WalReplayState>,
1083}
1084
1085impl WalReplayStatistics {
1086    pub fn min(&self) -> usize {
1087        self.min
1088    }
1089
1090    pub fn max(&self) -> usize {
1091        self.max
1092    }
1093
1094    pub fn current(&self) -> usize {
1095        self.current
1096    }
1097
1098    pub fn state(&self) -> Option<WalReplayState> {
1099        self.state
1100    }
1101}
1102
1103#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
1104pub enum WalReplayState {
1105    #[serde(alias = "waiting")]
1106    Waiting,
1107    #[serde(alias = "in progress")]
1108    InProgress,
1109    #[serde(alias = "done")]
1110    Done,
1111}
1112
1113impl WalReplayState {
1114    pub fn is_waiting(&self) -> bool {
1115        *self == Self::Waiting
1116    }
1117
1118    pub fn is_in_progress(&self) -> bool {
1119        *self == Self::InProgress
1120    }
1121
1122    pub fn is_done(&self) -> bool {
1123        *self == Self::Done
1124    }
1125}
1126
1127#[cfg(test)]
1128mod tests {
1129    // The examples used in these test cases are partly taken from prometheus.io.
1130    // Others are copied from responses of live Prometheus servers.
1131
1132    use super::*;
1133    use std::collections::HashMap;
1134    use time::macros::datetime;
1135
1136    #[test]
1137    fn test_api_error_deserialization() -> Result<(), anyhow::Error> {
1138        let data = r#"
1139{
1140  "status": "error",
1141  "data": null,
1142  "errorType": "bad_data",
1143  "error": "1:14: parse error: unexpected end of input in aggregation",
1144  "warnings": []
1145}
1146"#;
1147
1148        let result = serde_json::from_str::<ApiResponse<PromqlResult>>(data)?;
1149        assert!(
1150            matches!(result, ApiResponse::Error(err) if err.error_type == crate::error::PrometheusErrorType::BadData)
1151        );
1152
1153        Ok(())
1154    }
1155
1156    #[test]
1157    fn test_api_success_deserialization() -> Result<(), anyhow::Error> {
1158        let data = r#"
1159{
1160  "status": "success",
1161  "data": {
1162    "resultType": "scalar",
1163    "result": [ 0, "0.0" ]
1164  },
1165  "warnings": []
1166}
1167"#;
1168
1169        let result = serde_json::from_str::<ApiResponse<PromqlResult>>(data)?;
1170        assert!(matches!(result, ApiResponse::Success { data: _ }));
1171
1172        Ok(())
1173    }
1174
1175    #[test]
1176    fn test_bad_combination_in_deserialization() -> Result<(), anyhow::Error> {
1177        let data = r#"
1178{
1179  "status": "error",
1180  "data": {
1181    "resultType": "scalar",
1182    "result": [ 0, "0.0" ]
1183  },
1184  "warnings": []
1185}
1186"#;
1187
1188        let result = serde_json::from_str::<ApiResponse<()>>(data);
1189        assert!(result.is_err());
1190
1191        Ok(())
1192    }
1193
1194    #[test]
1195    fn test_another_bad_combination_in_deserialization() -> Result<(), anyhow::Error> {
1196        let data = r#"
1197{
1198  "status": "success",
1199  "warnings": []
1200  "errorType": "bad_data",
1201  "error": "1:14: parse error: unexpected end of input in aggregation",
1202}
1203"#;
1204
1205        let result = serde_json::from_str::<ApiResponse<()>>(data);
1206        assert!(result.is_err());
1207
1208        Ok(())
1209    }
1210
1211    #[test]
1212    fn test_query_result_deserialization() -> Result<(), anyhow::Error> {
1213        let data = r#"
1214{
1215  "resultType": "matrix",
1216  "result": [
1217    {
1218      "metric": {
1219        "__name__": "up",
1220        "instance": "localhost:9090",
1221        "job": "prometheus"
1222      },
1223      "values": [
1224        [
1225          1659268100,
1226          "1"
1227        ],
1228        [
1229          1659268160,
1230          "1"
1231        ],
1232        [
1233          1659268220,
1234          "1"
1235        ],
1236        [
1237          1659268280,
1238          "1"
1239        ]
1240      ]
1241    }
1242  ],
1243  "stats": {
1244    "timings": {
1245      "evalTotalTime": 0.000102139,
1246      "resultSortTime": 8.7e-07,
1247      "queryPreparationTime": 5.4169e-05,
1248      "innerEvalTime": 3.787e-05,
1249      "execQueueTime": 4.07e-05,
1250      "execTotalTime": 0.000151989
1251    },
1252    "samples": {
1253      "totalQueryableSamplesPerStep": [
1254        [
1255          1659268100,
1256          1
1257        ],
1258        [
1259          1659268160,
1260          1
1261        ],
1262        [
1263          1659268220,
1264          1
1265        ],
1266        [
1267          1659268280,
1268          1
1269        ]
1270      ],
1271      "totalQueryableSamples": 4,
1272      "peakSamples": 4
1273    }
1274  }
1275}
1276"#;
1277        let result = serde_json::from_str::<PromqlResult>(data)?;
1278        let data = &result.data;
1279        assert!(data.is_matrix());
1280        let matrix = data.as_matrix().unwrap();
1281        assert!(matrix.len() == 1);
1282        let range_vector = &matrix[0];
1283        let metric = &range_vector.metric();
1284        assert!(metric.len() == 3);
1285        assert!(metric.get("__name__").is_some_and(|v| v == "up"));
1286        assert!(metric
1287            .get("instance")
1288            .is_some_and(|v| v == "localhost:9090"));
1289        assert!(metric.get("job").is_some_and(|v| v == "prometheus"));
1290        let samples = range_vector.samples();
1291        assert!(samples.len() == 4);
1292        assert!(samples[0].timestamp() == 1659268100.0);
1293        assert!(samples[0].value() == 1.0);
1294        assert!(samples[1].timestamp() == 1659268160.0);
1295        assert!(samples[1].value() == 1.0);
1296        assert!(samples[2].timestamp() == 1659268220.0);
1297        assert!(samples[2].value() == 1.0);
1298        assert!(samples[3].timestamp() == 1659268280.0);
1299        assert!(samples[3].value() == 1.0);
1300        assert!(result.stats().is_some());
1301        let stats = result.stats().unwrap();
1302        let timings = stats.timings();
1303        assert!(timings.eval_total_time() == 0.000102139);
1304        assert!(timings.result_sort_time() == 8.7e-07_f64);
1305        assert!(timings.query_preparation_time() == 5.4169e-05_f64);
1306        assert!(timings.inner_eval_time() == 3.787e-05_f64);
1307        assert!(timings.exec_queue_time() == 4.07e-05_f64);
1308        assert!(timings.exec_total_time() == 0.000151989);
1309        let samples = stats.samples();
1310        assert!(samples.peak_samples() == 4);
1311        assert!(samples.total_queryable_samples() == 4);
1312        assert!(samples.total_queryable_samples_per_step().is_some());
1313        let per_step = samples.total_queryable_samples_per_step().unwrap();
1314        assert!(per_step.len() == 4);
1315        assert!(per_step[0].timestamp() == 1659268100.0);
1316        assert!(per_step[0].value() == 1);
1317        assert!(per_step[1].timestamp() == 1659268160.0);
1318        assert!(per_step[1].value() == 1);
1319        assert!(per_step[2].timestamp() == 1659268220.0);
1320        assert!(per_step[2].value() == 1);
1321        assert!(per_step[3].timestamp() == 1659268280.0);
1322        assert!(per_step[3].value() == 1);
1323        Ok(())
1324    }
1325
1326    #[test]
1327    fn test_query_result_no_per_step_stats_deserialization() -> Result<(), anyhow::Error> {
1328        let data = r#"
1329{
1330  "resultType": "matrix",
1331  "result": [
1332    {
1333      "metric": {
1334        "__name__": "up",
1335        "instance": "localhost:9090",
1336        "job": "prometheus"
1337      },
1338      "values": [
1339        [
1340          1659268100,
1341          "1"
1342        ],
1343        [
1344          1659268160,
1345          "1"
1346        ],
1347        [
1348          1659268220,
1349          "1"
1350        ],
1351        [
1352          1659268280,
1353          "1"
1354        ]
1355      ]
1356    }
1357  ],
1358  "stats": {
1359    "timings": {
1360      "evalTotalTime": 0.000102139,
1361      "resultSortTime": 8.7e-07,
1362      "queryPreparationTime": 5.4169e-05,
1363      "innerEvalTime": 3.787e-05,
1364      "execQueueTime": 4.07e-05,
1365      "execTotalTime": 0.000151989
1366    },
1367    "samples": {
1368      "totalQueryableSamples": 4,
1369      "peakSamples": 4
1370    }
1371  }
1372}
1373"#;
1374        let result = serde_json::from_str::<PromqlResult>(data)?;
1375        assert!(result.stats().is_some());
1376        let stats = result.stats().unwrap();
1377        assert!(stats.samples().total_queryable_samples_per_step().is_none());
1378
1379        Ok(())
1380    }
1381
1382    #[test]
1383    fn test_query_result_no_stats_deserialization() -> Result<(), anyhow::Error> {
1384        let data = r#"
1385{
1386  "resultType": "matrix",
1387  "result": [
1388    {
1389      "metric": {
1390        "__name__": "up",
1391        "instance": "localhost:9090",
1392        "job": "prometheus"
1393      },
1394      "values": [
1395        [
1396          1659268100,
1397          "1"
1398        ],
1399        [
1400          1659268160,
1401          "1"
1402        ],
1403        [
1404          1659268220,
1405          "1"
1406        ],
1407        [
1408          1659268280,
1409          "1"
1410        ]
1411      ]
1412    }
1413  ]
1414}
1415"#;
1416        let result = serde_json::from_str::<PromqlResult>(data)?;
1417        assert!(result.stats().is_none());
1418
1419        Ok(())
1420    }
1421
1422    #[test]
1423    fn test_instant_vector_deserialization() -> Result<(), anyhow::Error> {
1424        let data = r#"
1425[
1426  {
1427    "metric": {
1428      "__name__": "up",
1429      "job": "prometheus",
1430      "instance": "localhost:9090"
1431    },
1432    "value": [
1433      1435781451.781,
1434      "1"
1435    ]
1436  },
1437  {
1438    "metric": {
1439      "__name__": "up",
1440      "job": "node",
1441      "instance": "localhost:9100"
1442    },
1443    "value": [
1444      1435781451.781,
1445      "0"
1446    ]
1447  }
1448]
1449"#;
1450        serde_json::from_str::<Vec<InstantVector>>(data)?;
1451        Ok(())
1452    }
1453
1454    #[test]
1455    fn test_range_vector_deserialization() -> Result<(), anyhow::Error> {
1456        let data = r#"
1457[
1458  {
1459    "metric": {
1460      "__name__": "up",
1461      "job": "prometheus",
1462      "instance": "localhost:9090"
1463    },
1464    "values": [
1465      [
1466        1435781430.781,
1467        "1"
1468      ],
1469      [
1470        1435781445.781,
1471        "1"
1472      ],
1473      [
1474        1435781460.781,
1475        "1"
1476      ]
1477    ]
1478  },
1479  {
1480    "metric": {
1481      "__name__": "up",
1482      "job": "node",
1483      "instance": "localhost:9091"
1484    },
1485    "values": [
1486      [
1487        1435781430.781,
1488        "0"
1489      ],
1490      [
1491        1435781445.781,
1492        "0"
1493      ],
1494      [
1495        1435781460.781,
1496        "1"
1497      ]
1498    ]
1499  }
1500]
1501"#;
1502        serde_json::from_str::<Vec<RangeVector>>(data)?;
1503        Ok(())
1504    }
1505
1506    #[test]
1507    fn test_target_deserialization() -> Result<(), anyhow::Error> {
1508        let data = r#"
1509{
1510  "activeTargets": [
1511    {
1512      "discoveredLabels": {
1513        "__address__": "127.0.0.1:9090",
1514        "__metrics_path__": "/metrics",
1515        "__scheme__": "http",
1516        "job": "prometheus"
1517      },
1518      "labels": {
1519        "instance": "127.0.0.1:9090",
1520        "job": "prometheus"
1521      },
1522      "scrapePool": "prometheus",
1523      "scrapeUrl": "http://127.0.0.1:9090/metrics",
1524      "globalUrl": "http://example-prometheus:9090/metrics",
1525      "lastError": "",
1526      "lastScrape": "2017-01-17T15:07:44.723715405+01:00",
1527      "lastScrapeDuration": 0.050688943,
1528      "health": "up",
1529      "scrapeInterval": "1m",
1530      "scrapeTimeout": "10s"
1531    }
1532  ],
1533  "droppedTargets": [
1534    {
1535      "discoveredLabels": {
1536        "__address__": "127.0.0.1:9100",
1537        "__metrics_path__": "/metrics",
1538        "__scheme__": "http",
1539        "__scrape_interval__": "1m",
1540        "__scrape_timeout__": "10s",
1541        "job": "node"
1542      }
1543    }
1544  ]
1545}
1546"#;
1547        let targets = serde_json::from_str::<Targets>(data)?;
1548        let active = &targets.active();
1549        assert!(active.len() == 1);
1550        let target = &active[0];
1551        assert!(target
1552            .discovered_labels()
1553            .get("__address__")
1554            .is_some_and(|v| v == "127.0.0.1:9090"));
1555        assert!(target
1556            .discovered_labels()
1557            .get("__metrics_path__")
1558            .is_some_and(|v| v == "/metrics"));
1559        assert!(target
1560            .discovered_labels()
1561            .get("__scheme__")
1562            .is_some_and(|v| v == "http"));
1563        assert!(target
1564            .discovered_labels()
1565            .get("job")
1566            .is_some_and(|v| v == "prometheus"));
1567        assert!(target
1568            .labels()
1569            .get("instance")
1570            .is_some_and(|v| v == "127.0.0.1:9090"));
1571        assert!(target
1572            .labels()
1573            .get("job")
1574            .is_some_and(|v| v == "prometheus"));
1575        assert!(target.scrape_pool() == "prometheus");
1576        assert!(target.scrape_url() == &Url::parse("http://127.0.0.1:9090/metrics")?);
1577        assert!(target.global_url() == &Url::parse("http://example-prometheus:9090/metrics")?);
1578        assert!(target.last_error().is_empty());
1579        assert!(target.last_scrape() == &datetime!(2017-01-17 15:07:44.723715405 +1));
1580        assert!(target.last_scrape_duration() == 0.050688943);
1581        assert!(target.health().is_up());
1582        assert!(target.scrape_interval() == &Duration::seconds(60));
1583        assert!(target.scrape_timeout() == &Duration::seconds(10));
1584        let dropped = &targets.dropped();
1585        assert!(dropped.len() == 1);
1586        let target = &dropped[0];
1587        assert!(target
1588            .discovered_labels()
1589            .get("__address__")
1590            .is_some_and(|v| v == "127.0.0.1:9100"));
1591        assert!(target
1592            .discovered_labels()
1593            .get("__metrics_path__")
1594            .is_some_and(|v| v == "/metrics"));
1595        assert!(target
1596            .discovered_labels()
1597            .get("__scheme__")
1598            .is_some_and(|v| v == "http"));
1599        assert!(target
1600            .discovered_labels()
1601            .get("__scrape_interval__")
1602            .is_some_and(|v| v == "1m"));
1603        assert!(target
1604            .discovered_labels()
1605            .get("__scrape_timeout__")
1606            .is_some_and(|v| v == "10s"));
1607        assert!(target
1608            .discovered_labels()
1609            .get("job")
1610            .is_some_and(|v| v == "node"));
1611        Ok(())
1612    }
1613
1614    #[test]
1615    fn test_rule_group_deserialization() -> Result<(), anyhow::Error> {
1616        let data = r#"
1617{
1618  "groups": [
1619    {
1620      "rules": [
1621        {
1622          "alerts": [
1623            {
1624              "activeAt": "2018-07-04T20:27:12.60602144+02:00",
1625              "annotations": {
1626                "summary": "High request latency"
1627              },
1628              "labels": {
1629                "alertname": "HighRequestLatency",
1630                "severity": "page"
1631              },
1632              "state": "firing",
1633              "value": "1e+00"
1634            }
1635          ],
1636          "annotations": {
1637            "summary": "High request latency"
1638          },
1639          "duration": 600,
1640          "health": "ok",
1641          "labels": {
1642            "severity": "page"
1643          },
1644          "name": "HighRequestLatency",
1645          "query": "job:request_latency_seconds:mean5m{job=\"myjob\"} > 0.5",
1646          "type": "alerting",
1647          "evaluationTime": 0.000312805,
1648          "lastEvaluation": "2023-10-05T19:51:25.462004334+02:00",
1649          "keepFiringFor": 60
1650        },
1651        {
1652          "health": "ok",
1653          "name": "job:http_inprogress_requests:sum",
1654          "query": "sum by (job) (http_inprogress_requests)",
1655          "type": "recording",
1656          "evaluationTime": 0.000256946,
1657          "lastEvaluation": "2023-10-05T19:51:25.052982522+02:00"
1658        }
1659      ],
1660      "file": "/rules.yaml",
1661      "interval": 60,
1662      "limit": 0,
1663      "name": "example",
1664      "evaluationTime": 0.000267716,
1665      "lastEvaluation": "2023-10-05T19:51:25.052974842+02:00"
1666    }
1667  ]
1668}
1669"#;
1670        let groups = serde_json::from_str::<RuleGroups>(data)?.groups;
1671        assert!(groups.len() == 1);
1672        let group = &groups[0];
1673        assert!(group.name() == "example");
1674        assert!(group.file() == "/rules.yaml");
1675        assert!(group.interval() == 60.0);
1676        assert!(group.limit() == 0);
1677        assert!(group.evaluation_time() == 0.000267716);
1678        assert!(group.last_evaluation() == &datetime!(2023-10-05 7:51:25.052974842 pm +2));
1679        assert!(group.rules().len() == 2);
1680        let alerting_rule = &group.rules[0].as_alerting().unwrap();
1681        assert!(alerting_rule.health() == RuleHealth::Good);
1682        assert!(alerting_rule.name() == "HighRequestLatency");
1683        assert!(alerting_rule.query() == "job:request_latency_seconds:mean5m{job=\"myjob\"} > 0.5");
1684        assert!(alerting_rule.evaluation_time() == 0.000312805);
1685        assert!(alerting_rule.last_evaluation() == &datetime!(2023-10-05 7:51:25.462004334 pm +2));
1686        assert!(alerting_rule.duration() == 600.0);
1687        assert!(alerting_rule.keep_firing_for() == 60.0);
1688        assert!(alerting_rule.alerts().len() == 1);
1689        assert!(alerting_rule
1690            .annotations()
1691            .get("summary")
1692            .is_some_and(|v| v == "High request latency"));
1693        let alert = &alerting_rule.alerts()[0];
1694        assert!(alert.value() == 1.0);
1695        assert!(alert.state().is_firing());
1696        assert!(alert.active_at() == &datetime!(2018-07-04 20:27:12.60602144 +2));
1697        let recording_rule = &group.rules[1].as_recording().unwrap();
1698        assert!(recording_rule.health() == RuleHealth::Good);
1699        assert!(recording_rule.name() == "job:http_inprogress_requests:sum");
1700        assert!(recording_rule.query() == "sum by (job) (http_inprogress_requests)");
1701        assert!(recording_rule.evaluation_time() == 0.000256946);
1702        assert!(recording_rule.last_evaluation() == &datetime!(2023-10-05 7:51:25.052982522 pm +2));
1703        Ok(())
1704    }
1705
1706    #[test]
1707    fn test_alert_deserialization() -> Result<(), anyhow::Error> {
1708        let data = r#"
1709{
1710  "alerts": [
1711     {
1712        "activeAt":"2018-07-04T20:27:12.60602144+02:00",
1713        "annotations":{
1714        },
1715        "labels":{
1716           "alertname":"my-alert"
1717        },
1718        "state":"firing",
1719        "value":"1e+00"
1720     }
1721  ]
1722}
1723"#;
1724        serde_json::from_str::<Alerts>(data)?;
1725        Ok(())
1726    }
1727
1728    #[test]
1729    fn test_target_metadata_deserialization_1() -> Result<(), anyhow::Error> {
1730        let data = r#"
1731[
1732  {
1733    "target": {
1734      "instance": "127.0.0.1:9090",
1735      "job": "prometheus"
1736    },
1737    "type": "gauge",
1738    "help": "Number of goroutines that currently exist.",
1739    "unit": ""
1740  },
1741  {
1742    "target": {
1743      "instance": "127.0.0.1:9091",
1744      "job": "prometheus"
1745    },
1746    "type": "gauge",
1747    "help": "Number of goroutines that currently exist.",
1748    "unit": ""
1749  },
1750  {
1751    "target": {
1752      "instance": "localhost:9090",
1753      "job": "prometheus"
1754    },
1755    "metric": "process_virtual_memory_bytes",
1756    "type": "gauge",
1757    "help": "Virtual memory size in bytes.",
1758    "unit": ""
1759  },
1760  {
1761    "target": {
1762      "instance": "localhost:9090",
1763      "job": "prometheus"
1764    },
1765    "metric": "prometheus_http_response_size_bytes",
1766    "type": "histogram",
1767    "help": "Histogram of response size for HTTP requests.",
1768    "unit": ""
1769  },
1770  {
1771    "target": {
1772      "instance": "localhost:9090",
1773      "job": "prometheus"
1774    },
1775    "metric": "prometheus_ready",
1776    "type": "gauge",
1777    "help": "Whether Prometheus startup was fully completed and the server is ready for normal operation.",
1778    "unit": ""
1779  },
1780  {
1781    "target": {
1782      "instance": "localhost:9090",
1783      "job": "prometheus"
1784    },
1785    "metric": "prometheus_rule_group_iterations_missed_total",
1786    "type": "counter",
1787    "help": "The total number of rule group evaluations missed due to slow rule group evaluation.",
1788    "unit": ""
1789  },
1790  {
1791    "target": {
1792      "instance": "localhost:9090",
1793      "job": "prometheus"
1794    },
1795    "metric": "prometheus_target_scrape_pool_reloads_failed_total",
1796    "type": "counter",
1797    "help": "Total number of failed scrape pool reloads.",
1798    "unit": ""
1799  },
1800  {
1801    "target": {
1802      "instance": "localhost:9090",
1803      "job": "prometheus"
1804    },
1805    "metric": "prometheus_target_scrape_pool_reloads_total",
1806    "type": "counter",
1807    "help": "Total number of scrape pool reloads.",
1808    "unit": ""
1809  }
1810]
1811"#;
1812        let metadata = serde_json::from_str::<Vec<TargetMetadata>>(data)?;
1813        assert!(metadata.len() == 8);
1814        let first = &metadata[0];
1815        assert!(first
1816            .target()
1817            .get("instance")
1818            .is_some_and(|v| v == "127.0.0.1:9090"));
1819        assert!(first.target().get("job").is_some_and(|v| v == "prometheus"));
1820        assert!(first.metric_type().is_gauge());
1821        assert!(first.help() == "Number of goroutines that currently exist.");
1822        assert!(first.unit().is_empty());
1823        assert!(first.metric().is_none());
1824        let third = &metadata[2];
1825        assert!(third
1826            .target()
1827            .get("instance")
1828            .is_some_and(|v| v == "localhost:9090"));
1829        assert!(third.target().get("job").is_some_and(|v| v == "prometheus"));
1830        assert!(third.metric_type().is_gauge());
1831        assert!(third.help() == "Virtual memory size in bytes.");
1832        assert!(third.unit().is_empty());
1833        assert!(third
1834            .metric()
1835            .is_some_and(|v| v == "process_virtual_memory_bytes"));
1836        let fourth = &metadata[3];
1837        assert!(fourth
1838            .target()
1839            .get("instance")
1840            .is_some_and(|v| v == "localhost:9090"));
1841        assert!(fourth
1842            .target()
1843            .get("job")
1844            .is_some_and(|v| v == "prometheus"));
1845        assert!(fourth.metric_type().is_histogram());
1846        assert!(fourth.help() == "Histogram of response size for HTTP requests.");
1847        assert!(fourth.unit().is_empty());
1848        assert!(fourth
1849            .metric()
1850            .is_some_and(|v| v == "prometheus_http_response_size_bytes"));
1851        Ok(())
1852    }
1853
1854    #[test]
1855    fn test_target_metadata_deserialization_2() -> Result<(), anyhow::Error> {
1856        let data = r#"
1857[
1858  {
1859    "target": {
1860      "instance": "127.0.0.1:9090",
1861      "job": "prometheus"
1862    },
1863    "metric": "prometheus_treecache_zookeeper_failures_total",
1864    "type": "counter",
1865    "help": "The total number of ZooKeeper failures.",
1866    "unit": ""
1867  },
1868  {
1869    "target": {
1870      "instance": "127.0.0.1:9090",
1871      "job": "prometheus"
1872    },
1873    "metric": "prometheus_tsdb_reloads_total",
1874    "type": "counter",
1875    "help": "Number of times the database reloaded block data from disk.",
1876    "unit": ""
1877  }
1878]
1879"#;
1880        serde_json::from_str::<Vec<TargetMetadata>>(data)?;
1881        Ok(())
1882    }
1883
1884    #[test]
1885    fn test_metric_metadata_deserialization() -> Result<(), anyhow::Error> {
1886        let data = r#"
1887{
1888  "cortex_ring_tokens": [
1889    {
1890      "type": "gauge",
1891      "help": "Number of tokens in the ring",
1892      "unit": ""
1893    }
1894  ],
1895  "http_requests_total": [
1896    {
1897      "type": "counter",
1898      "help": "Number of HTTP requests",
1899      "unit": ""
1900    },
1901    {
1902      "type": "counter",
1903      "help": "Amount of HTTP requests",
1904      "unit": ""
1905    }
1906  ]
1907}
1908"#;
1909        let metadata = serde_json::from_str::<HashMap<String, Vec<MetricMetadata>>>(data)?;
1910        assert!(metadata.len() == 2);
1911        assert!(metadata
1912            .get("cortex_ring_tokens")
1913            .is_some_and(|v| v[0].metric_type().is_gauge()
1914                && v[0].help() == "Number of tokens in the ring"
1915                && v[0].unit().is_empty()));
1916        assert!(metadata.get("http_requests_total").is_some_and(|v| v[0]
1917            .metric_type()
1918            .is_counter()
1919            && v[0].help() == "Number of HTTP requests"
1920            && v[0].unit().is_empty()));
1921        Ok(())
1922    }
1923
1924    #[test]
1925    fn test_alertmanagers_deserialization() -> Result<(), anyhow::Error> {
1926        let data = r#"
1927{
1928  "activeAlertmanagers": [
1929    {
1930      "url": "http://127.0.0.1:9090/api/v1/alerts"
1931    }
1932  ],
1933  "droppedAlertmanagers": [
1934    {
1935      "url": "http://127.0.0.1:9093/api/v1/alerts"
1936    }
1937  ]
1938}
1939"#;
1940        serde_json::from_str::<Alertmanagers>(data)?;
1941        Ok(())
1942    }
1943
1944    #[test]
1945    fn test_buildinformation_deserialization() -> Result<(), anyhow::Error> {
1946        let data = r#"
1947{
1948  "version": "2.13.1",
1949  "revision": "cb7cbad5f9a2823a622aaa668833ca04f50a0ea7",
1950  "branch": "master",
1951  "buildUser": "julius@desktop",
1952  "buildDate": "20191102-16:19:51",
1953  "goVersion": "go1.13.1"
1954}
1955"#;
1956        serde_json::from_str::<BuildInformation>(data)?;
1957        Ok(())
1958    }
1959
1960    #[test]
1961    fn test_runtimeinformation_deserialization() -> Result<(), anyhow::Error> {
1962        let data = r#"
1963{
1964  "startTime": "2019-11-02T17:23:59.301361365+01:00",
1965  "CWD": "/",
1966  "reloadConfigSuccess": true,
1967  "lastConfigTime": "2019-11-02T17:23:59+01:00",
1968  "timeSeriesCount": 873,
1969  "corruptionCount": 0,
1970  "goroutineCount": 48,
1971  "GOMAXPROCS": 4,
1972  "GOGC": "",
1973  "GODEBUG": "",
1974  "storageRetention": "15d"
1975}
1976"#;
1977        serde_json::from_str::<RuntimeInformation>(data)?;
1978        Ok(())
1979    }
1980
1981    #[test]
1982    fn test_tsdb_stats_deserialization() -> Result<(), anyhow::Error> {
1983        let data = r#"
1984{
1985  "headStats": {
1986    "numSeries": 508,
1987    "chunkCount": 937,
1988    "minTime": 1591516800000,
1989    "maxTime": 1598896800143
1990  },
1991  "seriesCountByMetricName": [
1992    {
1993      "name": "net_conntrack_dialer_conn_failed_total",
1994      "value": 20
1995    },
1996    {
1997      "name": "prometheus_http_request_duration_seconds_bucket",
1998      "value": 20
1999    }
2000  ],
2001  "labelValueCountByLabelName": [
2002    {
2003      "name": "__name__",
2004      "value": 211
2005    },
2006    {
2007      "name": "event",
2008      "value": 3
2009    }
2010  ],
2011  "memoryInBytesByLabelName": [
2012    {
2013      "name": "__name__",
2014      "value": 8266
2015    },
2016    {
2017      "name": "instance",
2018      "value": 28
2019    }
2020  ],
2021  "seriesCountByLabelValuePair": [
2022    {
2023      "name": "job=prometheus",
2024      "value": 425
2025    },
2026    {
2027      "name": "instance=localhost:9090",
2028      "value": 425
2029    }
2030  ]
2031}
2032"#;
2033        serde_json::from_str::<TsdbStatistics>(data)?;
2034        Ok(())
2035    }
2036
2037    #[test]
2038    fn test_wal_replay_deserialization() -> Result<(), anyhow::Error> {
2039        let data = r#"
2040{
2041  "min": 2,
2042  "max": 5,
2043  "current": 40,
2044  "state": "waiting"
2045}
2046"#;
2047        let result: Result<WalReplayStatistics, serde_json::Error> = serde_json::from_str(data);
2048        assert!(result.is_ok());
2049
2050        let data = r#"
2051{
2052  "min": 2,
2053  "max": 5,
2054  "current": 40,
2055  "state": "in progress"
2056}
2057"#;
2058        let result: Result<WalReplayStatistics, serde_json::Error> = serde_json::from_str(data);
2059        assert!(result.is_ok());
2060
2061        let data = r#"
2062{
2063  "min": 2,
2064  "max": 5,
2065  "current": 40,
2066  "state": "done"
2067}
2068"#;
2069        let result: Result<WalReplayStatistics, serde_json::Error> = serde_json::from_str(data);
2070        assert!(result.is_ok());
2071
2072        let data = r#"
2073{
2074  "min": 2,
2075  "max": 5,
2076  "current": 40
2077}
2078"#;
2079        serde_json::from_str::<WalReplayStatistics>(data)?;
2080        Ok(())
2081    }
2082}