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